lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
5293fbaab31353eed3db9fd7e7d8971e99548f98
0
GlassTune/GlassTune
package com.glasstune.activities; import com.glasstune.R; import com.glasstune.tone.Note; import com.glasstune.utils.FrequencySmoother; import com.glasstune.utils.NoteCalculator; import com.google.android.glass.app.Card; import com.google.android.glass.widget.CardScrollAdapter; import com.google.android.glass.widget.CardScrollView; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.RelativeLayout; import android.widget.TextView; import be.hogent.tarsos.dsp.AudioEvent; import be.hogent.tarsos.dsp.MicrophoneAudioDispatcher; import be.hogent.tarsos.dsp.pitch.PitchDetectionHandler; import be.hogent.tarsos.dsp.pitch.PitchDetectionResult; import be.hogent.tarsos.dsp.pitch.PitchProcessor; /** * An {@link Activity} showing a tuggable "Hello World!" card. * <p> * The main content view is composed of a one-card {@link CardScrollView} that provides tugging * feedback to the user when swipe gestures are detected. * If your Glassware intends to intercept swipe gestures, you should set the content view directly * and use a {@link com.google.android.glass.touchpad.GestureDetector}. * @see <a href="https://developers.google.com/glass/develop/gdk/touch">GDK Developer Guide</a> */ public class TuneGuitarActivity extends Activity implements PitchDetectionHandler { private static final String TAG = "GlassTune"; private final double CALLIBRATION = 1.04; private final int SAMPLE_RATE = 22050; private final int BUFFER_SIZE = 1024; private final int OVERLAP = 512; /** {@link CardScrollView} to use as the main content view. */ private CardScrollView mCardScroller; /** "Hello World!" {@link View} generated by {@link #buildView()}. */ private View mView; private Thread _pitchThread; private MicrophoneAudioDispatcher _dispatcher; private FrequencySmoother _smoother; private DisplayUpdater _displayUpdater; @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mView = buildView(); mCardScroller = new CardScrollView(this); mCardScroller.setAdapter(new CardScrollAdapter() { @Override public int getCount() { return 1; } @Override public Object getItem(int position) { return mView; } @Override public View getView(int position, View convertView, ViewGroup parent) { return mView; } @Override public int getPosition(Object item) { if (mView.equals(item)) { return 0; } return AdapterView.INVALID_POSITION; } }); // Handle the TAP event. mCardScroller.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { openOptionsMenu(); } }); setContentView(mCardScroller); _smoother = new FrequencySmoother(); startPitchDetection(SAMPLE_RATE, BUFFER_SIZE, OVERLAP); _displayUpdater = new DisplayUpdater(); _displayUpdater.execute(300); } private void startPitchDetection(int sampleRate, int bufferSize, int overlap) { _dispatcher = new MicrophoneAudioDispatcher(sampleRate,bufferSize,overlap); _dispatcher.addAudioProcessor(new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.FFT_YIN, sampleRate, bufferSize, this)); Log.d(TAG, "Start Thread"); _pitchThread = new Thread(_dispatcher,"Audio dispatching"); _pitchThread.start(); } @Override protected void onResume() { super.onResume(); Log.d(TAG,"resume"); mCardScroller.activate(); } @Override protected void onPause() { Log.d(TAG,"pause"); hideCard(); super.onPause(); } private void hideCard() { _displayUpdater.cancel(false); _dispatcher.stop(); _pitchThread.interrupt(); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mCardScroller.deactivate(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.tuner_menu,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.dismiss_menu_item: hideCard(); finish(); // close the activity return true; default: return super.onOptionsItemSelected(item); } } private class DisplayUpdater extends AsyncTask<Integer, Double, Void> { @Override protected Void doInBackground(Integer... params) { while(!isCancelled()) { final double average = _smoother.getSmoothedAverage(); _smoother.clear(); publishProgress(average); try { Thread.sleep(params[0]); } catch (InterruptedException e) { e.printStackTrace(); } } return null; } protected void onProgressUpdate(double... frequency) { setDisplayForFrequency(frequency[0]); } } public void setDisplayForFrequency(double frequency) { Note mainNote = Note.getNearestNote(frequency); Note sharpNote = Note.getNextNote(mainNote); Note flatNote = Note.getPreviousNote(mainNote); TextView mainNoteText = (TextView)findViewById(R.id.tune_view_main_note); mainNoteText.setText(mainNote.toString()); TextView flatNoteText = (TextView)findViewById(R.id.tune_view_flat_note); flatNoteText.setText(flatNote.toString()); TextView sharpNoteText = (TextView)findViewById(R.id.tune_view_sharp_note); sharpNoteText.setText(sharpNote.toString()); View pitchBar = (View)findViewById(R.id.tune_view_current_pitch); double left = NoteCalculator.getPitchBarPercentage(frequency); double leftDP = left * (double)640; RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(pitchBar.getWidth(),pitchBar.getHeight()); params.setMargins((int)leftDP,0,0,0); pitchBar.setLayoutParams(params); } /** * Builds a Glass styled "Hello World!" view using the {@link Card} class. */ private View buildView() { return getLayoutInflater().inflate(R.layout.tune_view,null); } /** * Callback for the pitch detection thread, called on new pitch detected */ @Override public void handlePitch(PitchDetectionResult pitchDetectionResult,AudioEvent audioEvent) { final float pitch = pitchDetectionResult.getPitch(); if(pitch != -1 && audioEvent.getRMS() > 0.005){ String message = String.format("Pitch detected at %.2fs: %.2fHz ( %.2f probability, RMS: %.5f )\n", audioEvent.getTimeStamp(),pitch,pitchDetectionResult.getProbability(),(audioEvent.getRMS() * 100); Log.d(TAG,message); _smoother.add(pitch * CALLIBRATION); } } }
glass/src/main/java/com/glasstune/activities/TuneGuitarActivity.java
package com.glasstune.activities; import com.glasstune.R; import com.glasstune.tone.Note; import com.glasstune.utils.FrequencySmoother; import com.glasstune.utils.NoteCalculator; import com.google.android.glass.app.Card; import com.google.android.glass.media.Sounds; import com.google.android.glass.widget.CardScrollAdapter; import com.google.android.glass.widget.CardScrollView; import android.app.Activity; import android.content.Context; import android.media.AudioManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AbsoluteLayout; import android.widget.AdapterView; import android.widget.RelativeLayout; import android.widget.TextView; import be.hogent.tarsos.dsp.AudioEvent; import be.hogent.tarsos.dsp.MicrophoneAudioDispatcher; import be.hogent.tarsos.dsp.pitch.PitchDetectionHandler; import be.hogent.tarsos.dsp.pitch.PitchDetectionResult; import be.hogent.tarsos.dsp.pitch.PitchProcessor; /** * An {@link Activity} showing a tuggable "Hello World!" card. * <p> * The main content view is composed of a one-card {@link CardScrollView} that provides tugging * feedback to the user when swipe gestures are detected. * If your Glassware intends to intercept swipe gestures, you should set the content view directly * and use a {@link com.google.android.glass.touchpad.GestureDetector}. * @see <a href="https://developers.google.com/glass/develop/gdk/touch">GDK Developer Guide</a> */ public class TuneGuitarActivity extends Activity implements PitchDetectionHandler { private static final String TAG = "GlassTune"; /** {@link CardScrollView} to use as the main content view. */ private CardScrollView mCardScroller; /** "Hello World!" {@link View} generated by {@link #buildView()}. */ private View mView; private Thread _pitchThread; private MicrophoneAudioDispatcher _dispatcher; private final double CALLIBRATION = 1.04; private FrequencySmoother _smoother; private Thread _displayUpdater; @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mView = buildView(); mCardScroller = new CardScrollView(this); mCardScroller.setAdapter(new CardScrollAdapter() { @Override public int getCount() { return 1; } @Override public Object getItem(int position) { return mView; } @Override public View getView(int position, View convertView, ViewGroup parent) { return mView; } @Override public int getPosition(Object item) { if (mView.equals(item)) { return 0; } return AdapterView.INVALID_POSITION; } }); // Handle the TAP event. mCardScroller.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { openOptionsMenu(); } }); setContentView(mCardScroller); int sampleRate = 22050; int bufferSize = 1024; int overlap = 512; _smoother = new FrequencySmoother(); _dispatcher = new MicrophoneAudioDispatcher(sampleRate,bufferSize,overlap); _dispatcher.addAudioProcessor(new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.FFT_YIN, sampleRate, bufferSize, this)); Log.d(TAG, "Start Thread"); _pitchThread = new Thread(_dispatcher,"Audio dispatching"); _pitchThread.start(); final TuneGuitarActivity self = this; _displayUpdater = new Thread(new Runnable() { public void run() { while(!_displayUpdater.isInterrupted()) { final double average = _smoother.getSmoothedAverage(); _smoother.clear(); if(average > 0) { self.runOnUiThread(new Runnable() { public void run() { setDisplayForFrequency(average); } }); } try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } } }); _displayUpdater.start(); } @Override protected void onResume() { super.onResume(); Log.d(TAG,"resume"); mCardScroller.activate(); } @Override protected void onPause() { Log.d(TAG,"pause"); hideCard(); super.onPause(); } private void hideCard() { _displayUpdater.interrupt(); _dispatcher.stop(); _pitchThread.interrupt(); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mCardScroller.deactivate(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.tuner_menu,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.dismiss_menu_item: hideCard(); finish(); // close the activity return true; default: return super.onOptionsItemSelected(item); } } public void setDisplayForFrequency(double frequency) { Note mainNote = Note.getNearestNote(frequency); Note sharpNote = Note.getNextNote(mainNote); Note flatNote = Note.getPreviousNote(mainNote); TextView mainNoteText = (TextView)findViewById(R.id.tune_view_main_note); mainNoteText.setText(mainNote.toString()); TextView flatNoteText = (TextView)findViewById(R.id.tune_view_flat_note); flatNoteText.setText(flatNote.toString()); TextView sharpNoteText = (TextView)findViewById(R.id.tune_view_sharp_note); sharpNoteText.setText(sharpNote.toString()); View pitchBar = (View)findViewById(R.id.tune_view_current_pitch); double left = NoteCalculator.getPitchBarPercentage(frequency); double leftDP = left * (double)640; RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(pitchBar.getWidth(),pitchBar.getHeight()); params.setMargins((int)leftDP,0,0,0); pitchBar.setLayoutParams(params); } /** * Builds a Glass styled "Hello World!" view using the {@link Card} class. */ private View buildView() { return getLayoutInflater().inflate(R.layout.tune_view,null); } @Override public void handlePitch(PitchDetectionResult pitchDetectionResult,AudioEvent audioEvent) { if(pitchDetectionResult.getPitch() != -1 && (audioEvent.getRMS() * 100) > 0.5){ double timeStamp = audioEvent.getTimeStamp(); final float pitch = pitchDetectionResult.getPitch(); float probability = pitchDetectionResult.getProbability(); double rms = audioEvent.getRMS() * 100; String message = String.format("Pitch detected at %.2fs: %.2fHz ( %.2f probability, RMS: %.5f )\n", timeStamp,pitch,probability,rms); Log.d(TAG,message); _smoother.add(pitch * CALLIBRATION); } } }
updated backgroug thread to use Async task
glass/src/main/java/com/glasstune/activities/TuneGuitarActivity.java
updated backgroug thread to use Async task
<ide><path>lass/src/main/java/com/glasstune/activities/TuneGuitarActivity.java <ide> import com.glasstune.utils.FrequencySmoother; <ide> import com.glasstune.utils.NoteCalculator; <ide> import com.google.android.glass.app.Card; <del>import com.google.android.glass.media.Sounds; <ide> import com.google.android.glass.widget.CardScrollAdapter; <ide> import com.google.android.glass.widget.CardScrollView; <ide> <ide> import android.app.Activity; <del>import android.content.Context; <del>import android.media.AudioManager; <ide> import android.os.AsyncTask; <ide> import android.os.Bundle; <del>import android.os.Handler; <del>import android.os.PowerManager; <ide> import android.util.Log; <del>import android.view.KeyEvent; <ide> import android.view.Menu; <ide> import android.view.MenuInflater; <ide> import android.view.MenuItem; <ide> import android.view.View; <ide> import android.view.ViewGroup; <ide> import android.view.WindowManager; <del>import android.widget.AbsoluteLayout; <ide> import android.widget.AdapterView; <ide> import android.widget.RelativeLayout; <ide> import android.widget.TextView; <ide> public class TuneGuitarActivity extends Activity implements PitchDetectionHandler { <ide> <ide> private static final String TAG = "GlassTune"; <add> <add> private final double CALLIBRATION = 1.04; <add> private final int SAMPLE_RATE = 22050; <add> private final int BUFFER_SIZE = 1024; <add> private final int OVERLAP = 512; <add> <ide> /** {@link CardScrollView} to use as the main content view. */ <ide> private CardScrollView mCardScroller; <ide> <ide> private Thread _pitchThread; <ide> private MicrophoneAudioDispatcher _dispatcher; <ide> <del> private final double CALLIBRATION = 1.04; <ide> private FrequencySmoother _smoother; <del> private Thread _displayUpdater; <del> <add> private DisplayUpdater _displayUpdater; <ide> <ide> @Override <ide> protected void onCreate(Bundle bundle) { <ide> }); <ide> setContentView(mCardScroller); <ide> <del> int sampleRate = 22050; <del> int bufferSize = 1024; <del> int overlap = 512; <del> <ide> _smoother = new FrequencySmoother(); <ide> <add> startPitchDetection(SAMPLE_RATE, BUFFER_SIZE, OVERLAP); <add> <add> _displayUpdater = new DisplayUpdater(); <add> _displayUpdater.execute(300); <add> <add> } <add> <add> private void startPitchDetection(int sampleRate, int bufferSize, int overlap) { <ide> _dispatcher = new MicrophoneAudioDispatcher(sampleRate,bufferSize,overlap); <ide> _dispatcher.addAudioProcessor(new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.FFT_YIN, sampleRate, bufferSize, this)); <ide> Log.d(TAG, "Start Thread"); <ide> _pitchThread = new Thread(_dispatcher,"Audio dispatching"); <ide> _pitchThread.start(); <del> <del> final TuneGuitarActivity self = this; <del> <del> _displayUpdater = new Thread(new Runnable() { <del> public void run() { <del> while(!_displayUpdater.isInterrupted()) { <del> <del> final double average = _smoother.getSmoothedAverage(); <del> _smoother.clear(); <del> <del> if(average > 0) { <del> self.runOnUiThread(new Runnable() { <del> public void run() { <del> setDisplayForFrequency(average); <del> } <del> }); <del> } <del> <del> try { <del> Thread.sleep(300); <del> } catch (InterruptedException e) { <del> e.printStackTrace(); <del> } <del> } <del> } <del> }); <del> <del> _displayUpdater.start(); <del> <ide> } <ide> <ide> @Override <ide> } <ide> <ide> private void hideCard() { <del> _displayUpdater.interrupt(); <add> _displayUpdater.cancel(false); <ide> _dispatcher.stop(); <ide> _pitchThread.interrupt(); <ide> getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); <ide> } <ide> } <ide> <add> private class DisplayUpdater extends AsyncTask<Integer, Double, Void> { <add> <add> @Override <add> protected Void doInBackground(Integer... params) { <add> <add> while(!isCancelled()) { <add> final double average = _smoother.getSmoothedAverage(); <add> _smoother.clear(); <add> publishProgress(average); <add> try { <add> Thread.sleep(params[0]); <add> } catch (InterruptedException e) { <add> e.printStackTrace(); <add> } <add> } <add> return null; <add> } <add> <add> protected void onProgressUpdate(double... frequency) { <add> setDisplayForFrequency(frequency[0]); <add> } <add> } <add> <ide> public void setDisplayForFrequency(double frequency) { <ide> Note mainNote = Note.getNearestNote(frequency); <ide> Note sharpNote = Note.getNextNote(mainNote); <ide> return getLayoutInflater().inflate(R.layout.tune_view,null); <ide> } <ide> <add> /** <add> * Callback for the pitch detection thread, called on new pitch detected <add> */ <ide> @Override <ide> public void handlePitch(PitchDetectionResult pitchDetectionResult,AudioEvent audioEvent) { <del> if(pitchDetectionResult.getPitch() != -1 && (audioEvent.getRMS() * 100) > 0.5){ <del> double timeStamp = audioEvent.getTimeStamp(); <del> final float pitch = pitchDetectionResult.getPitch(); <del> float probability = pitchDetectionResult.getProbability(); <del> double rms = audioEvent.getRMS() * 100; <del> String message = String.format("Pitch detected at %.2fs: %.2fHz ( %.2f probability, RMS: %.5f )\n", timeStamp,pitch,probability,rms); <add> final float pitch = pitchDetectionResult.getPitch(); <add> <add> if(pitch != -1 && audioEvent.getRMS() > 0.005){ <add> String message = String.format("Pitch detected at %.2fs: %.2fHz ( %.2f probability, RMS: %.5f )\n", audioEvent.getTimeStamp(),pitch,pitchDetectionResult.getProbability(),(audioEvent.getRMS() * 100); <ide> Log.d(TAG,message); <ide> <ide> _smoother.add(pitch * CALLIBRATION);
Java
apache-2.0
b264a8a113ce2ee468fc6c7a131ac0db6b0ac3f1
0
karahiyo/hanoi-hadoop-2.0.0-cdh,karahiyo/hanoi-hadoop-2.0.0-cdh,karahiyo/hanoi-hadoop-2.0.0-cdh,karahiyo/hanoi-hadoop-2.0.0-cdh,karahiyo/hanoi-hadoop-2.0.0-cdh,karahiyo/hanoi-hadoop-2.0.0-cdh,karahiyo/hanoi-hadoop-2.0.0-cdh,karahiyo/hanoi-hadoop-2.0.0-cdh,karahiyo/hanoi-hadoop-2.0.0-cdh
package aj.hadoop.monitor.mapreduce; import java.io.*; import java.net.*; import java.util.*; import java.text.*; import java.lang.*; import java.lang.management.*; import java.util.StringTokenizer; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.Mapper.Context; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.Signature; import aj.hadoop.monitor.util.PickerClient; import java.util.logging.Logger; import java.util.logging.Level; import java.util.logging.FileHandler; @Aspect public abstract class MapperMonitor { private String HOST = "localhost"; private int PORT = 9999; /** log file */ public static final String LOGFILE = "Hanoi-MethodTraceMonitor.log"; /** logger */ private Logger logger = null; /** file handler */ private FileHandler fh = null; /** * initialize */ public MapperMonitor() { logger = Logger.getLogger(this.getClass().getName()); try { fh = new FileHandler(this.LOGFILE, true); logger.addHandler(fh); } catch (IOException e) { e.printStackTrace(); } logger.log(Level.INFO, "Start trace..."); } @Pointcut ("call(void org.apache.hadoop.mapreduce.Mapper.Context.write" + "(" + "java.lang.Object, " + "java.lang.Object" + "))" + "&& cflow(execution(public void org.apache.hadoop.examples.WordCount$TokenizerMapper.map(..)))" + "&& args(key, value)") public void pointcut_mapper_out(Object key, Object value){} @Before (value = "pointcut_mapper_out( key, value )") public void logging( JoinPoint thisJoinPoint, Object key, Object value) { //PickerClient client = new PickerClient(); //client.setHost(this.HOST); //client.setPORT(this.PORT); //client.send((String)key); try { String outfile = "/tmp" + "/" + this.LOGFILE; FileOutputStream fos = new FileOutputStream(outfile, true); OutputStreamWriter out = new OutputStreamWriter(fos); out.write((String)key); out.close(); } catch (IOException ioe) { System.out.println(ioe); } catch (Exception e) { System.out.println(e); } System.err.println("** [POINTCUT]" + (String)key); System.out.println("** [POINTCUT]" + (String)key); } }
src/monitor/aj/hadoop/monitor/mapreduce/MapperMonitor.java
package aj.hadoop.monitor.mapreduce; import java.io.*; import java.net.*; import java.util.*; import java.text.*; import java.lang.*; import java.lang.management.*; import java.util.StringTokenizer; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.Mapper.Context; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.Signature; import aj.hadoop.monitor.util.PickerClient; import java.util.logging.Logger; import java.util.logging.Level; import java.util.logging.FileHandler; import org.apache.hadoop.examples.*; @Aspect public abstract class MapperMonitor { private String HOST = "localhost"; private int PORT = 9999; /** log file */ public static final String LOGFILE = "Hanoi-MethodTraceMonitor.log"; /** logger */ private Logger logger = null; /** file handler */ private FileHandler fh = null; /** * initialize */ public MapperMonitor() { logger = Logger.getLogger(this.getClass().getName()); try { fh = new FileHandler(this.LOGFILE, true); logger.addHandler(fh); } catch (IOException e) { e.printStackTrace(); } logger.log(Level.INFO, "Start trace..."); } @Pointcut ("call(void org.apache.hadoop.mapreduce.Mapper.Context.write" + "(" + "java.lang.Object, " + "java.lang.Object" + "))" + "&& cflow(execution(public void org.apache.hadoop.examples.WordCount$TokenizerMapper.map(..)))" + "&& args(key, value)") public void pointcut_mapper_out(Object key, Object value){} @Before (value = "pointcut_mapper_out( key, value )") public void logging( JoinPoint thisJoinPoint, Object key, Object value) { //PickerClient client = new PickerClient(); //client.setHost(this.HOST); //client.setPORT(this.PORT); //client.send((String)key); try { String outfile = "/tmp" + "/" + this.LOGFILE; FileOutputStream fos = new FileOutputStream(outfile, true); OutputStreamWriter out = new OutputStreamWriter(fos); out.write((String)key); out.close(); } catch (IOException ioe) { System.out.println(ioe); } catch (Exception e) { System.out.println(e); } System.err.println("** [POINTCUT]" + (String)key); System.out.println("** [POINTCUT]" + (String)key); } }
remove example jar.
src/monitor/aj/hadoop/monitor/mapreduce/MapperMonitor.java
remove example jar.
<ide><path>rc/monitor/aj/hadoop/monitor/mapreduce/MapperMonitor.java <ide> import java.util.logging.Logger; <ide> import java.util.logging.Level; <ide> import java.util.logging.FileHandler; <del> <del>import org.apache.hadoop.examples.*; <ide> <ide> @Aspect <ide> public abstract class MapperMonitor {
JavaScript
apache-2.0
1da78c0d039ef6be530521cdf7586f97d97dfd0f
0
openwrt/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,hnyman/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,hnyman/luci,openwrt/luci,hnyman/luci,openwrt/luci,hnyman/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,openwrt/luci,openwrt/luci,lbthomsen/openwrt-luci,hnyman/luci,hnyman/luci,openwrt/luci,openwrt/luci,openwrt/luci,hnyman/luci,hnyman/luci
'use strict'; 'require baseclass'; 'require form'; return baseclass.extend({ title: _('RRDTool Plugin Configuration'), description: _('The rrdtool plugin stores the collected data in rrd database files, the foundation of the diagrams.<br /><br /><strong>Warning: Setting the wrong values will result in a very high memory consumption in the temporary directory. This can render the device unusable!</strong>'), addFormOptions: function(s) { var o; o = s.option(form.Flag, 'enable', _('Enable this plugin')); o = s.option(form.Value, 'DataDir', _('Storage directory'), _('Note: as pages are rendered by user \'nobody\', the *.rrd files, the storage directory and all its parent directories need to be world readable.')); o.default = '/tmp/rrd'; o.depends('enable', '1'); o = s.option(form.Value, 'StepSize', _('RRD step interval'), _('Seconds')); o.placeholder = '30'; o.datatype = 'uinteger'; o.depends('enable', '1'); o = s.option(form.Value, 'HeartBeat', _('RRD heart beat interval'), _('Seconds')); o.placeholder = '60'; o.datatype = 'uinteger'; o.depends('enable', '1'); o = s.option(form.Flag, 'RRASingle', _('Only create average RRAs'), _('reduces rrd size')); o.default = '1'; o.rmempty = false; o.depends('enable', '1'); o = s.option(form.Flag, 'RRAMax', _('Show max values instead of averages'), _('Max values for a period can be used instead of averages when not using \'only average RRAs\'')); o.depends('RRASingle', '0'); o = s.option(form.DynamicList, 'RRATimespans', _('Stored timespans'), _('List of time spans to be stored in RRD database. E.g. "1hour 1day 14day". Allowed timespan types: min, h, hour(s), d, day(s), w, week(s), m, month(s), y, year(s)')); o.default = '1hour 1day 1week 1month 1year'; o.depends('enable', '1'); o.validate = function(section_id, value) { if (value == '') return true; if (value.match(/^[0-9]+(?:y|m|w|d|h|min|years?|months?|weeks?|days?|hours?)?$/)) return true; return _('Expecting valid time range'); }; o = s.option(form.Value, 'RRARows', _('Rows per RRA')); o.default = '144'; o.datatype = 'min(1)'; o.depends('enable', '1'); o = s.option(form.Value, 'XFF', _('RRD XFiles Factor')); o.placeholder = '0.1'; o.depends('enable', '1'); o.validate = function(section_id, value) { if (value == '') return true; if (value.match(/^[0-9]+(?:\.[0-9]+)?$/) && +value >= 0 && +value < 1) return true; return _('Expecting decimal value lower than one'); }; o = s.option(form.Value, 'CacheTimeout', _('Cache collected data for'), _('Seconds')); o.depends('enable', '1'); o.datatype = 'uinteger'; o.placeholder = '0'; o.validate = function(section_id, value) { var flushinp = this.map.findElement('id', 'widget.cbid.luci_statistics.collectd_rrdtool.CacheFlush'); if (value != '' && !isNaN(value) && +value > 0) { flushinp.placeholder = 10 * +value; flushinp.disabled = false; } else { flushinp.value = ''; flushinp.placeholder = '0'; flushinp.disabled = true; } return true; }; o = s.option(form.Value, 'CacheFlush', _('Flush cache after'), _('Seconds')); o.depends('enable', '1'); o.datatype = 'uinteger'; }, configSummary: function(section) { if (section.DataDir) return _('Writing *.rrd files to %s').format(section.DataDir); } });
applications/luci-app-statistics/htdocs/luci-static/resources/view/statistics/plugins/rrdtool.js
'use strict'; 'require baseclass'; 'require form'; return baseclass.extend({ title: _('RRDTool Plugin Configuration'), description: _('The rrdtool plugin stores the collected data in rrd database files, the foundation of the diagrams.<br /><br /><strong>Warning: Setting the wrong values will result in a very high memory consumption in the temporary directory. This can render the device unusable!</strong>'), addFormOptions: function(s) { var o; o = s.option(form.Flag, 'enable', _('Enable this plugin')); o = s.option(form.Value, 'DataDir', _('Storage directory'), _('Note: as pages are rendered by user \'nobody\', the *.rrd files, the storage directory and all its parent directories need to be world readable.')); o.default = '/tmp/rrd'; o.depends('enable', '1'); o = s.option(form.Value, 'StepSize', _('RRD step interval'), _('Seconds')); o.placeholder = '30'; o.datatype = 'uinteger'; o.depends('enable', '1'); o = s.option(form.Value, 'HeartBeat', _('RRD heart beat interval'), _('Seconds')); o.placeholder = '60'; o.datatype = 'uinteger'; o.depends('enable', '1'); o = s.option(form.Flag, 'RRASingle', _('Only create average RRAs'), _('reduces rrd size')); o.default = '1'; o.rmempty = false; o.depends('enable', '1'); o = s.option(form.Flag, 'RRAMax', _('Show max values instead of averages'), _('Max values for a period can be used instead of averages when not using \'only average RRAs\'')); o.depends('RRASingle', '0'); o = s.option(form.DynamicList, 'RRATimespans', _('Stored timespans')); o.default = '1hour 1day 1week 1month 1year'; o.depends('enable', '1'); o.validate = function(section_id, value) { if (value == '') return true; if (value.match(/^[0-9]+(?:y|m|w|d|h|min|years?|months?|weeks?|days?|hours?)?$/)) return true; return _('Expecting valid time range'); }; o = s.option(form.Value, 'RRARows', _('Rows per RRA')); o.default = '144'; o.datatype = 'min(1)'; o.depends('enable', '1'); o = s.option(form.Value, 'XFF', _('RRD XFiles Factor')); o.placeholder = '0.1'; o.depends('enable', '1'); o.validate = function(section_id, value) { if (value == '') return true; if (value.match(/^[0-9]+(?:\.[0-9]+)?$/) && +value >= 0 && +value < 1) return true; return _('Expecting decimal value lower than one'); }; o = s.option(form.Value, 'CacheTimeout', _('Cache collected data for'), _('Seconds')); o.depends('enable', '1'); o.datatype = 'uinteger'; o.placeholder = '0'; o.validate = function(section_id, value) { var flushinp = this.map.findElement('id', 'widget.cbid.luci_statistics.collectd_rrdtool.CacheFlush'); if (value != '' && !isNaN(value) && +value > 0) { flushinp.placeholder = 10 * +value; flushinp.disabled = false; } else { flushinp.value = ''; flushinp.placeholder = '0'; flushinp.disabled = true; } return true; }; o = s.option(form.Value, 'CacheFlush', _('Flush cache after'), _('Seconds')); o.depends('enable', '1'); o.datatype = 'uinteger'; }, configSummary: function(section) { if (section.DataDir) return _('Writing *.rrd files to %s').format(section.DataDir); } });
luci-app-statistics: Add help text to RRD time spans Add clarifying help text to the RRD time span definition. Only a few strings are allowed and it is easy to cause uninteded results especially with minutes as only "min" is for minute while ("m" or "month") are for month. Signed-off-by: Hannu Nyman <[email protected]>
applications/luci-app-statistics/htdocs/luci-static/resources/view/statistics/plugins/rrdtool.js
luci-app-statistics: Add help text to RRD time spans
<ide><path>pplications/luci-app-statistics/htdocs/luci-static/resources/view/statistics/plugins/rrdtool.js <ide> _('Max values for a period can be used instead of averages when not using \'only average RRAs\'')); <ide> o.depends('RRASingle', '0'); <ide> <del> o = s.option(form.DynamicList, 'RRATimespans', _('Stored timespans')); <add> o = s.option(form.DynamicList, 'RRATimespans', _('Stored timespans'), <add> _('List of time spans to be stored in RRD database. E.g. "1hour 1day 14day". Allowed timespan types: min, h, hour(s), d, day(s), w, week(s), m, month(s), y, year(s)')); <ide> o.default = '1hour 1day 1week 1month 1year'; <ide> o.depends('enable', '1'); <ide> o.validate = function(section_id, value) {
Java
apache-2.0
cef41a336c514aad7f62244fd9c449a237e8bb29
0
June92/Cardshifter,Cardshifter/Cardshifter,SirPython/Cardshifter,Cardshifter/Cardshifter,Cardshifter/Cardshifter,June92/Cardshifter,June92/Cardshifter,SirPython/Cardshifter,SirPython/Cardshifter
package com.cardshifter.gdx; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.ui.*; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.cardshifter.api.both.ChatMessage; import com.cardshifter.api.both.PlayerConfigMessage; import com.cardshifter.api.config.DeckConfig; import com.cardshifter.api.incoming.LoginMessage; import com.cardshifter.api.incoming.ServerQueryMessage; import com.cardshifter.api.messages.Message; import com.cardshifter.api.outgoing.AvailableModsMessage; import com.cardshifter.api.outgoing.NewGameMessage; import com.cardshifter.api.outgoing.UserStatusMessage; import com.cardshifter.gdx.ui.UsersList; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.Map; /** * Created by Zomis on 2014-11-11. */ public class ClientScreen implements Screen, CardshifterMessageHandler { private final CardshifterClient client; private final Map<Class<? extends Message>, SpecificHandler<?>> handlerMap = new HashMap<Class<? extends Message>, SpecificHandler<?>>(); private final Table table; private final HorizontalGroup mods; private final CardshifterGame game; private final TextArea chatMessages; private final UsersList usersList; private String[] availableMods; public ClientScreen(final CardshifterGame game, String host, int port) { this.game = game; client = new CardshifterClient(host, port, this); table = new Table(game.skin); table.setFillParent(true); mods = new HorizontalGroup(); chatMessages = new TextArea("", game.skin); usersList = new UsersList(game.skin); table.add(new ScrollPane(chatMessages)).top().expand().fill(); table.add(usersList.getTable()).right().expandY().fill(); table.row(); table.add(mods).bottom().expandX().fill(); TextButton inviteButton = new TextButton("Invite", game.skin); inviteButton.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { usersList.inviteSelected(availableMods, game.stage, client); } }); table.add(inviteButton).right().expand().fill(); table.setDebug(true, true); handlerMap.put(AvailableModsMessage.class, new SpecificHandler<AvailableModsMessage>() { @Override public void handle(AvailableModsMessage message) { availableMods = message.getMods(); client.send(new ServerQueryMessage(ServerQueryMessage.Request.USERS)); } }); handlerMap.put(ChatMessage.class, new SpecificHandler<ChatMessage>() { @Override public void handle(ChatMessage message) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String append = "\n" + "[" + format.format(Calendar.getInstance().getTime()) + "] " + message.getFrom() + ": " + message.getMessage(); chatMessages.setText(chatMessages.getText() + append); } }); handlerMap.put(UserStatusMessage.class, new SpecificHandler<UserStatusMessage>() { @Override public void handle(UserStatusMessage message) { usersList.handleUserStatus(message); } }); handlerMap.put(PlayerConfigMessage.class, new SpecificHandler<PlayerConfigMessage>() { @Override public void handle(PlayerConfigMessage message) { DeckConfig deckConfig = (DeckConfig) message.getConfigs().get("Deck"); if (deckConfig != null) { deckConfig.generateRandom(); client.send(message); } } }); Gdx.app.postRunnable(new Runnable() { @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { } client.send(new LoginMessage("Zomis_GDX")); } }); } @Override public void render(float delta) { } @Override public void resize(int width, int height) { } @Override public void show() { game.stage.addActor(table); } @Override public void hide() { table.remove(); } @Override public void pause() { } @Override public void resume() { } @Override public void dispose() { } @Override public void handle(final Message message) { Gdx.app.log("Client", "Received " + message); final SpecificHandler<Message> handler = (SpecificHandler<Message>) handlerMap.get(message.getClass()); if (handler != null) { Gdx.app.postRunnable(new Runnable() { @Override public void run() { handler.handle(message); } }); } else { Gdx.app.log("Client", "WARNING: Unable to handle " + message + " of type " + message.getClass()); } } }
gdx/core/src/com/cardshifter/gdx/ClientScreen.java
package com.cardshifter.gdx; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.ui.*; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.cardshifter.api.both.ChatMessage; import com.cardshifter.api.incoming.LoginMessage; import com.cardshifter.api.incoming.ServerQueryMessage; import com.cardshifter.api.incoming.StartGameRequest; import com.cardshifter.api.messages.Message; import com.cardshifter.api.outgoing.AvailableModsMessage; import com.cardshifter.api.outgoing.UserStatusMessage; import com.cardshifter.gdx.ui.UsersList; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.Map; /** * Created by Zomis on 2014-11-11. */ public class ClientScreen implements Screen, CardshifterMessageHandler { private final CardshifterClient client; private final Map<Class<? extends Message>, SpecificHandler<?>> handlerMap = new HashMap<Class<? extends Message>, SpecificHandler<?>>(); private final Table table; private final HorizontalGroup mods; private final CardshifterGame game; private final TextArea chatMessages; private final UsersList usersList; private String[] availableMods; public ClientScreen(final CardshifterGame game, String host, int port) { this.game = game; client = new CardshifterClient(host, port, this); table = new Table(game.skin); table.setFillParent(true); mods = new HorizontalGroup(); chatMessages = new TextArea("", game.skin); usersList = new UsersList(game.skin); table.add(new ScrollPane(chatMessages)).top().expand().fill(); table.add(usersList.getTable()).right().expandY().fill(); table.row(); table.add(mods).bottom().expandX().fill(); TextButton inviteButton = new TextButton("Invite", game.skin); inviteButton.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { usersList.inviteSelected(availableMods, game.stage, client); } }); table.add(inviteButton).right().expand().fill(); table.setDebug(true, true); handlerMap.put(AvailableModsMessage.class, new SpecificHandler<AvailableModsMessage>() { @Override public void handle(AvailableModsMessage message) { availableMods = message.getMods(); client.send(new ServerQueryMessage(ServerQueryMessage.Request.USERS)); } }); handlerMap.put(ChatMessage.class, new SpecificHandler<ChatMessage>() { @Override public void handle(ChatMessage message) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String append = "\n" + "[" + format.format(Calendar.getInstance().getTime()) + "] " + message.getFrom() + ": " + message.getMessage(); chatMessages.setText(chatMessages.getText() + append); } }); handlerMap.put(UserStatusMessage.class, new SpecificHandler<UserStatusMessage>() { @Override public void handle(UserStatusMessage message) { usersList.handleUserStatus(message); } }); Gdx.app.postRunnable(new Runnable() { @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { } client.send(new LoginMessage("Zomis_GDX")); } }); } @Override public void render(float delta) { } @Override public void resize(int width, int height) { } @Override public void show() { game.stage.addActor(table); } @Override public void hide() { table.remove(); } @Override public void pause() { } @Override public void resume() { } @Override public void dispose() { } @Override public void handle(final Message message) { Gdx.app.log("Client", "Received " + message); final SpecificHandler<Message> handler = (SpecificHandler<Message>) handlerMap.get(message.getClass()); if (handler != null) { Gdx.app.postRunnable(new Runnable() { @Override public void run() { handler.handle(message); } }); } else { Gdx.app.log("Client", "WARNING: Unable to handle " + message + " of type " + message.getClass()); } } }
added random generation of DeckConfig when being asked for deck
gdx/core/src/com/cardshifter/gdx/ClientScreen.java
added random generation of DeckConfig when being asked for deck
<ide><path>dx/core/src/com/cardshifter/gdx/ClientScreen.java <ide> import com.badlogic.gdx.scenes.scene2d.ui.*; <ide> import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; <ide> import com.cardshifter.api.both.ChatMessage; <add>import com.cardshifter.api.both.PlayerConfigMessage; <add>import com.cardshifter.api.config.DeckConfig; <ide> import com.cardshifter.api.incoming.LoginMessage; <ide> import com.cardshifter.api.incoming.ServerQueryMessage; <del>import com.cardshifter.api.incoming.StartGameRequest; <ide> import com.cardshifter.api.messages.Message; <ide> import com.cardshifter.api.outgoing.AvailableModsMessage; <add>import com.cardshifter.api.outgoing.NewGameMessage; <ide> import com.cardshifter.api.outgoing.UserStatusMessage; <ide> import com.cardshifter.gdx.ui.UsersList; <ide> <ide> @Override <ide> public void handle(UserStatusMessage message) { <ide> usersList.handleUserStatus(message); <add> } <add> }); <add> handlerMap.put(PlayerConfigMessage.class, new SpecificHandler<PlayerConfigMessage>() { <add> @Override <add> public void handle(PlayerConfigMessage message) { <add> DeckConfig deckConfig = (DeckConfig) message.getConfigs().get("Deck"); <add> if (deckConfig != null) { <add> deckConfig.generateRandom(); <add> client.send(message); <add> } <ide> } <ide> }); <ide>
Java
apache-2.0
e5d9018c14d9bf732d4eb4607241162402e8ef8a
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection; import com.intellij.openapi.application.ApplicationStarter; import org.jetbrains.annotations.NotNull; import java.util.List; public class InspectionMain implements ApplicationStarter { private InspectionApplication myApplication; @Override public String getCommandName() { return "inspect"; } @Override @SuppressWarnings({"HardCodedStringLiteral"}) public void premain(@NotNull List<String> args) { if (args.size() < 4) { System.err.println("invalid args:" + args); printHelp(); } //System.setProperty("idea.load.plugins.category", "inspection"); myApplication = new InspectionApplication(); myApplication.myHelpProvider = new InspectionToolCmdlineOptionHelpProvider() { @Override public void printHelpAndExit() { printHelp(); } }; myApplication.myProjectPath = args.get(1); myApplication.myStubProfile = args.get(2); myApplication.myOutPath = args.get(3); if (myApplication.myProjectPath == null || myApplication.myOutPath == null || myApplication.myStubProfile == null) { System.err.println(myApplication.myProjectPath + myApplication.myOutPath + myApplication.myStubProfile); printHelp(); } try { for (int i = 4; i < args.size(); i++) { String arg = args.get(i); if ("-profileName".equals(arg)) { myApplication.myProfileName = args.get(++i); } else if ("-profilePath".equals(arg)) { myApplication.myProfilePath = args.get(++i); } else if ("-d".equals(arg)) { myApplication.mySourceDirectory = args.get(++i); } else if ("-format".equals(arg)) { myApplication.myOutputFormat = args.get(++i); } else if ("-v0".equals(arg)) { myApplication.setVerboseLevel(0); } else if ("-v1".equals(arg)) { myApplication.setVerboseLevel(1); } else if ("-v2".equals(arg)) { myApplication.setVerboseLevel(2); } else if ("-v3".equals(arg)) { myApplication.setVerboseLevel(3); } else if ("-e".equals(arg)) { myApplication.myRunWithEditorSettings = true; } else if ("-t".equals(arg)) { myApplication.myErrorCodeRequired = false; } else { System.err.println("unexpected argument: " + arg); printHelp(); } } } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); printHelp(); } myApplication.myRunGlobalToolsOnly = System.getProperty("idea.no.local.inspections") != null; } @Override public void main(@NotNull String[] args) { myApplication.startup(); } public static void printHelp() { System.out.println(InspectionsBundle.message("inspection.command.line.explanation")); System.exit(1); } }
platform/lang-impl/src/com/intellij/codeInspection/InspectionMain.java
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection; import com.intellij.openapi.application.ApplicationStarter; import org.jetbrains.annotations.NotNull; import java.util.List; public class InspectionMain implements ApplicationStarter { private InspectionApplication myApplication; @Override public String getCommandName() { return "inspect"; } @Override @SuppressWarnings({"HardCodedStringLiteral"}) public void premain(@NotNull List<String> args) { if (args.size() < 4) { System.err.println("invalid args:" + args); printHelp(); } //System.setProperty("idea.load.plugins.category", "inspection"); myApplication = new InspectionApplication(); myApplication.myHelpProvider = new InspectionToolCmdlineOptionHelpProvider() { @Override public void printHelpAndExit() { printHelp(); } }; myApplication.myProjectPath = args.get(1); myApplication.myStubProfile = args.get(2); myApplication.myOutPath = args.get(3); if (myApplication.myProjectPath == null || myApplication.myOutPath == null || myApplication.myStubProfile == null) { System.err.println(myApplication.myProjectPath + myApplication.myOutPath + myApplication.myStubProfile); printHelp(); } try { for (int i = 4; i < args.size(); i++) { String arg = args.get(i); if ("-profileName".equals(arg)) { myApplication.myProfileName = args.get(++i); } else if ("-profilePath".equals(arg)) { myApplication.myProfilePath = args.get(++i); } else if ("-d".equals(arg)) { myApplication.mySourceDirectory = args.get(++i); } else if ("-format".equals(arg)) { myApplication.myOutputFormat = args[++i]; } else if ("-v0".equals(arg)) { myApplication.setVerboseLevel(0); } else if ("-v1".equals(arg)) { myApplication.setVerboseLevel(1); } else if ("-v2".equals(arg)) { myApplication.setVerboseLevel(2); } else if ("-v3".equals(arg)) { myApplication.setVerboseLevel(3); } else if ("-e".equals(arg)) { myApplication.myRunWithEditorSettings = true; } else if ("-t".equals(arg)) { myApplication.myErrorCodeRequired = false; } else { System.err.println("unexpected argument: " + arg); printHelp(); } } } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); printHelp(); } myApplication.myRunGlobalToolsOnly = System.getProperty("idea.no.local.inspections") != null; } @Override public void main(@NotNull String[] args) { myApplication.startup(); } public static void printHelp() { System.out.println(InspectionsBundle.message("inspection.command.line.explanation")); System.exit(1); } }
Fix array -> List<String> transition after updates from master GitOrigin-RevId: 91447b6a601da329aec2a4ce548dbda4a285d97a
platform/lang-impl/src/com/intellij/codeInspection/InspectionMain.java
Fix array -> List<String> transition after updates from master
<ide><path>latform/lang-impl/src/com/intellij/codeInspection/InspectionMain.java <ide> myApplication.mySourceDirectory = args.get(++i); <ide> } <ide> else if ("-format".equals(arg)) { <del> myApplication.myOutputFormat = args[++i]; <add> myApplication.myOutputFormat = args.get(++i); <ide> } <ide> else if ("-v0".equals(arg)) { <ide> myApplication.setVerboseLevel(0);
Java
mit
665d6ed336bc126c614f8a8b6374aaa3842e3374
0
DemigodsRPG/Demigods3
package com.censoredsoftware.demigods.listener; import com.censoredsoftware.demigods.Demigods; import com.censoredsoftware.demigods.player.DCharacter; import com.censoredsoftware.demigods.player.DPlayer; import com.censoredsoftware.demigods.util.Messages; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.potion.PotionEffect; import java.util.Set; public class DisabledWorldListener implements Listener { // TODO Special listener to prevent interactions between Demigods worlds and non-Demigods worlds. @EventHandler(priority = EventPriority.HIGHEST) public void onDemigodsChat(DemigodsChatEvent event) { Set<Player> modified = event.getRecipients(); for(Player player : event.getRecipients()) if(Demigods.MiscUtil.isDisabledWorld(player.getLocation())) modified.remove(player); if(modified.size() < 1) event.setCancelled(true); event.setRecipients(modified); } @EventHandler(priority = EventPriority.MONITOR) public void onWorldSwitch(PlayerChangedWorldEvent event) { // Only continue if the player is a character Player player = event.getPlayer(); DPlayer dPlayer = DPlayer.Util.getPlayer(player); final DCharacter character = dPlayer.getCurrent(); if(dPlayer.getCurrent() == null) return; // Leaving a disabled world if(Demigods.MiscUtil.isDisabledWorld(event.getFrom()) && !Demigods.MiscUtil.isDisabledWorld(player.getWorld())) { dPlayer.setDisabledWorldInventory(player); player.setDisplayName(character.getDeity().getColor() + character.getName()); try { player.setPlayerListName(character.getDeity().getColor() + character.getName()); } catch(Exception e) { Messages.warning("Character name too long."); } player.setMaxHealth(character.getMaxHealth()); player.setHealth(character.getHealth() >= character.getMaxHealth() ? character.getMaxHealth() : character.getHealth()); player.setFoodLevel(character.getHunger()); player.setExp(character.getExperience()); player.setLevel(character.getLevel()); for(PotionEffect potion : player.getActivePotionEffects()) player.removePotionEffect(potion.getType()); if(character.getPotionEffects() != null) player.addPotionEffects(character.getPotionEffects()); player.setBedSpawnLocation(character.getBedSpawn()); character.getInventory().setToPlayer(player); player.setDisplayName(character.getDeity().getColor() + character.getName()); player.setPlayerListName(character.getDeity().getColor() + character.getName()); player.sendMessage(ChatColor.YELLOW + "Demigods is enabled in this world."); } else if(!Demigods.MiscUtil.isDisabledWorld(event.getFrom()) && Demigods.MiscUtil.isDisabledWorld(player.getWorld())) { character.setHealth(player.getHealth() >= character.getMaxHealth() ? character.getMaxHealth() : player.getHealth()); character.setHunger(player.getFoodLevel()); character.setLevel(player.getLevel()); character.setExperience(player.getExp()); character.setLocation(player.getLocation()); if(player.getBedSpawnLocation() != null) character.setBedSpawn(player.getBedSpawnLocation()); character.setPotionEffects(player.getActivePotionEffects()); character.saveInventory(); player.setMaxHealth(20.0); player.setHealth(20.0); player.setFoodLevel(20); player.setExp(0); player.setLevel(0); for(PotionEffect potion : player.getActivePotionEffects()) player.removePotionEffect(potion.getType()); dPlayer.applyDisabledWorldInventory(); player.setDisplayName(player.getName()); player.setPlayerListName(player.getName()); player.sendMessage(ChatColor.GRAY + "Demigods is disabled in this world."); } } }
src/main/java/com/censoredsoftware/demigods/listener/DisabledWorldListener.java
package com.censoredsoftware.demigods.listener; import com.censoredsoftware.demigods.Demigods; import com.censoredsoftware.demigods.player.DCharacter; import com.censoredsoftware.demigods.player.DPlayer; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.scheduler.BukkitRunnable; import java.util.Set; public class DisabledWorldListener implements Listener { // TODO Special listener to prevent interactions between Demigods worlds and non-Demigods worlds. @EventHandler(priority = EventPriority.HIGHEST) public void onDemigodsChat(DemigodsChatEvent event) { Set<Player> modified = event.getRecipients(); for(Player player : event.getRecipients()) if(Demigods.MiscUtil.isDisabledWorld(player.getLocation())) modified.remove(player); if(modified.size() < 1) event.setCancelled(true); event.setRecipients(modified); } @EventHandler(priority = EventPriority.MONITOR) public void onWorldSwitch(final PlayerChangedWorldEvent event) { // Only continue if the player is a character Player player = event.getPlayer(); if(!DPlayer.Util.isImmortal(player)) return; // Finalize things for the delay final DCharacter character = DPlayer.Util.getPlayer(player).getCurrent(); final String playerName = player.getName(); Bukkit.getScheduler().scheduleSyncDelayedTask(Demigods.PLUGIN, new BukkitRunnable() { @Override public void run() { if(!Bukkit.getOfflinePlayer(playerName).isOnline()) return; // Oh shit, not sure how to prevent this. // Redefine stuff Player player = Bukkit.getOfflinePlayer(playerName).getPlayer(); DPlayer dPlayer = DPlayer.Util.getPlayer(playerName); // Leaving a disabled world if(Demigods.MiscUtil.isDisabledWorld(event.getFrom()) && !Demigods.MiscUtil.isDisabledWorld(player.getWorld())) { dPlayer.setDisabledWorldInventory(player); character.getInventory().setToPlayer(player); player.setDisplayName(character.getDeity().getColor() + character.getName()); player.setPlayerListName(character.getDeity().getColor() + character.getName()); player.sendMessage(ChatColor.YELLOW + "Demigods is enabled in this world."); } else if(!Demigods.MiscUtil.isDisabledWorld(event.getFrom()) && Demigods.MiscUtil.isDisabledWorld(player.getWorld())) { character.saveInventory(); dPlayer.applyDisabledWorldInventory(); player.setDisplayName(player.getName()); player.setPlayerListName(player.getName()); player.sendMessage(ChatColor.GRAY + "Demigods is disabled in this world."); } } }, 60); // Let's see if it even tries at all. } }
More stuff.
src/main/java/com/censoredsoftware/demigods/listener/DisabledWorldListener.java
More stuff.
<ide><path>rc/main/java/com/censoredsoftware/demigods/listener/DisabledWorldListener.java <ide> import com.censoredsoftware.demigods.Demigods; <ide> import com.censoredsoftware.demigods.player.DCharacter; <ide> import com.censoredsoftware.demigods.player.DPlayer; <del>import org.bukkit.Bukkit; <add>import com.censoredsoftware.demigods.util.Messages; <ide> import org.bukkit.ChatColor; <ide> import org.bukkit.entity.Player; <ide> import org.bukkit.event.EventHandler; <ide> import org.bukkit.event.EventPriority; <ide> import org.bukkit.event.Listener; <ide> import org.bukkit.event.player.PlayerChangedWorldEvent; <del>import org.bukkit.scheduler.BukkitRunnable; <add>import org.bukkit.potion.PotionEffect; <ide> <ide> import java.util.Set; <ide> <ide> } <ide> <ide> @EventHandler(priority = EventPriority.MONITOR) <del> public void onWorldSwitch(final PlayerChangedWorldEvent event) <add> public void onWorldSwitch(PlayerChangedWorldEvent event) <ide> { <ide> // Only continue if the player is a character <ide> Player player = event.getPlayer(); <add> DPlayer dPlayer = DPlayer.Util.getPlayer(player); <add> final DCharacter character = dPlayer.getCurrent(); <ide> <del> if(!DPlayer.Util.isImmortal(player)) return; <add> if(dPlayer.getCurrent() == null) return; <ide> <del> // Finalize things for the delay <del> final DCharacter character = DPlayer.Util.getPlayer(player).getCurrent(); <del> final String playerName = player.getName(); <del> <del> Bukkit.getScheduler().scheduleSyncDelayedTask(Demigods.PLUGIN, new BukkitRunnable() <add> // Leaving a disabled world <add> if(Demigods.MiscUtil.isDisabledWorld(event.getFrom()) && !Demigods.MiscUtil.isDisabledWorld(player.getWorld())) <ide> { <del> @Override <del> public void run() <add> dPlayer.setDisabledWorldInventory(player); <add> player.setDisplayName(character.getDeity().getColor() + character.getName()); <add> try <ide> { <del> if(!Bukkit.getOfflinePlayer(playerName).isOnline()) return; // Oh shit, not sure how to prevent this. <del> <del> // Redefine stuff <del> Player player = Bukkit.getOfflinePlayer(playerName).getPlayer(); <del> DPlayer dPlayer = DPlayer.Util.getPlayer(playerName); <del> <del> // Leaving a disabled world <del> if(Demigods.MiscUtil.isDisabledWorld(event.getFrom()) && !Demigods.MiscUtil.isDisabledWorld(player.getWorld())) <del> { <del> dPlayer.setDisabledWorldInventory(player); <del> character.getInventory().setToPlayer(player); <del> player.setDisplayName(character.getDeity().getColor() + character.getName()); <del> player.setPlayerListName(character.getDeity().getColor() + character.getName()); <del> player.sendMessage(ChatColor.YELLOW + "Demigods is enabled in this world."); <del> } <del> else if(!Demigods.MiscUtil.isDisabledWorld(event.getFrom()) && Demigods.MiscUtil.isDisabledWorld(player.getWorld())) <del> { <del> character.saveInventory(); <del> dPlayer.applyDisabledWorldInventory(); <del> player.setDisplayName(player.getName()); <del> player.setPlayerListName(player.getName()); <del> player.sendMessage(ChatColor.GRAY + "Demigods is disabled in this world."); <del> } <add> player.setPlayerListName(character.getDeity().getColor() + character.getName()); <ide> } <del> }, 60); // Let's see if it even tries at all. <add> catch(Exception e) <add> { <add> Messages.warning("Character name too long."); <add> } <add> player.setMaxHealth(character.getMaxHealth()); <add> player.setHealth(character.getHealth() >= character.getMaxHealth() ? character.getMaxHealth() : character.getHealth()); <add> player.setFoodLevel(character.getHunger()); <add> player.setExp(character.getExperience()); <add> player.setLevel(character.getLevel()); <add> for(PotionEffect potion : player.getActivePotionEffects()) <add> player.removePotionEffect(potion.getType()); <add> if(character.getPotionEffects() != null) player.addPotionEffects(character.getPotionEffects()); <add> player.setBedSpawnLocation(character.getBedSpawn()); <add> character.getInventory().setToPlayer(player); <add> player.setDisplayName(character.getDeity().getColor() + character.getName()); <add> player.setPlayerListName(character.getDeity().getColor() + character.getName()); <add> player.sendMessage(ChatColor.YELLOW + "Demigods is enabled in this world."); <add> } <add> else if(!Demigods.MiscUtil.isDisabledWorld(event.getFrom()) && Demigods.MiscUtil.isDisabledWorld(player.getWorld())) <add> { <add> character.setHealth(player.getHealth() >= character.getMaxHealth() ? character.getMaxHealth() : player.getHealth()); <add> character.setHunger(player.getFoodLevel()); <add> character.setLevel(player.getLevel()); <add> character.setExperience(player.getExp()); <add> character.setLocation(player.getLocation()); <add> if(player.getBedSpawnLocation() != null) character.setBedSpawn(player.getBedSpawnLocation()); <add> character.setPotionEffects(player.getActivePotionEffects()); <add> character.saveInventory(); <add> player.setMaxHealth(20.0); <add> player.setHealth(20.0); <add> player.setFoodLevel(20); <add> player.setExp(0); <add> player.setLevel(0); <add> for(PotionEffect potion : player.getActivePotionEffects()) <add> player.removePotionEffect(potion.getType()); <add> dPlayer.applyDisabledWorldInventory(); <add> player.setDisplayName(player.getName()); <add> player.setPlayerListName(player.getName()); <add> player.sendMessage(ChatColor.GRAY + "Demigods is disabled in this world."); <add> } <ide> } <ide> }
Java
mit
9e94d536471a6c368056d84e5769575b4667ba68
0
smooch/react-native-smooch,smooch/react-native-smooch,smooch/react-native-smooch
package com.smooch.rnsmooch; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ReactNativeSmoochPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new ReactNativeSmooch(reactContext)); return modules; } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return new ArrayList<>(); } }
android/src/main/java/com/smooch/rnsmooch/ReactNativeSmoochPackage.java
package com.smooch.rnsmooch; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ReactNativeSmoochPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new ReactNativeSmooch(reactContext)); return modules; } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return new ArrayList<>(); } }
Remove method that was removed from interface See https://github.com/facebook/react-native/commit/ce6fb337a146e6f261f2afb564aa19363774a7a8#diff-63e621165603dc1a84832d6c400fae31
android/src/main/java/com/smooch/rnsmooch/ReactNativeSmoochPackage.java
Remove method that was removed from interface
<ide><path>ndroid/src/main/java/com/smooch/rnsmooch/ReactNativeSmoochPackage.java <ide> } <ide> <ide> @Override <del> public List<Class<? extends JavaScriptModule>> createJSModules() { <del> return Collections.emptyList(); <del> } <del> <del> @Override <ide> public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { <ide> return new ArrayList<>(); <ide> }
Java
mit
f50834e16d408fa7cb5eae54304b0b0af7688a5a
0
hpe-idol/find,hpautonomy/find,hpe-idol/java-powerpoint-report,hpe-idol/find,hpautonomy/find,hpautonomy/find,hpe-idol/find,hpautonomy/find,hpautonomy/find,hpe-idol/java-powerpoint-report,hpe-idol/find,hpe-idol/find
package com.autonomy.abc.search; import com.autonomy.abc.config.ABCTestBase; import com.autonomy.abc.config.TestConfig; import com.autonomy.abc.selenium.config.ApplicationType; import com.autonomy.abc.selenium.element.DatePicker; import com.autonomy.abc.selenium.language.Language; import com.autonomy.abc.selenium.menu.NavBarTabId; import com.autonomy.abc.selenium.menu.TopNavBar; import com.autonomy.abc.selenium.page.promotions.CreateNewPromotionsPage; import com.autonomy.abc.selenium.page.promotions.PromotionsDetailPage; import com.autonomy.abc.selenium.page.promotions.PromotionsPage; import com.autonomy.abc.selenium.page.search.DocumentViewer; import com.autonomy.abc.selenium.page.search.SearchBase; import com.autonomy.abc.selenium.page.search.SearchPage; import com.autonomy.abc.selenium.promotions.PinToPositionPromotion; import com.autonomy.abc.selenium.promotions.Promotion; import com.autonomy.abc.selenium.promotions.PromotionService; import com.autonomy.abc.selenium.promotions.SpotlightPromotion; import com.autonomy.abc.selenium.search.*; import com.autonomy.abc.selenium.util.ElementUtil; import com.autonomy.abc.selenium.util.Errors; import com.autonomy.abc.selenium.util.Waits; import com.hp.autonomy.frontend.selenium.util.AppElement; import org.apache.commons.collections4.ListUtils; import org.apache.commons.lang.time.DateUtils; import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.openqa.selenium.*; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.MalformedURLException; import java.text.ParseException; import java.util.*; import static com.autonomy.abc.framework.ABCAssert.assertThat; import static com.autonomy.abc.framework.ABCAssert.verifyThat; import static com.autonomy.abc.matchers.CommonMatchers.containsItems; import static com.autonomy.abc.matchers.ElementMatchers.*; import static org.hamcrest.Matchers.*; import static org.junit.Assert.fail; import static org.junit.Assume.assumeThat; import static org.openqa.selenium.lift.Matchers.displayed; public class SearchPageITCase extends ABCTestBase { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private SearchPage searchPage; private TopNavBar topNavBar; private CreateNewPromotionsPage createPromotionsPage; private PromotionsPage promotionsPage; private DatePicker datePicker; private SearchService searchService; public SearchPageITCase(final TestConfig config, final String browser, final ApplicationType appType, final Platform platform) { super(config, browser, appType, platform); } @Before public void setUp() throws MalformedURLException { topNavBar = body.getTopNavBar(); topNavBar.search("example"); searchPage = getElementFactory().getSearchPage(); searchPage.waitForSearchLoadIndicatorToDisappear(); searchService = getApplication().createSearchService(getElementFactory()); } private void search(String searchTerm){ logger.info("Searching for: '" + searchTerm + "'"); topNavBar.search(searchTerm); searchPage.waitForSearchLoadIndicatorToDisappear(); } private void applyFilter(SearchFilter filter) { filter.apply(searchPage); searchPage.waitForSearchLoadIndicatorToDisappear(); } @Test public void testUnmodifiedResultsToggleButton(){ new WebDriverWait(getDriver(),30).until(ExpectedConditions.visibilityOf(getElementFactory().getSearchPage())); assertThat("Page should be showing modified results", searchPage.modifiedResultsShown(), is(true)); assertThat("Url incorrect", getDriver().getCurrentUrl(), containsString("/modified")); searchPage.modifiedResultsCheckBox().click(); assertThat("Page should not be showing modified results", searchPage.modifiedResultsShown(), is(false)); assertThat("Url incorrect", getDriver().getCurrentUrl(), containsString("/unmodified")); searchPage.modifiedResultsCheckBox().click(); assertThat("Page should be showing modified results", searchPage.modifiedResultsShown(), is(true)); assertThat("Url incorrect", getDriver().getCurrentUrl(), containsString("/modified")); } @Test public void testSearchBasic(){ search("dog"); assertThat("Search title text is wrong", searchPage.getHeadingSearchTerm(), is("dog")); search("cat"); assertThat("Search title text is wrong", searchPage.getHeadingSearchTerm(), is("cat")); search("ElEPhanT"); assertThat("Search title text is wrong", searchPage.getHeadingSearchTerm(), is("ElEPhanT")); } @Test public void testPromoteButton(){ searchPage.promoteTheseDocumentsButton().click(); Waits.loadOrFadeWait(); assertThat("Promoted items bucket has not appeared", searchPage.promotionsBucket().isDisplayed()); assertThat("Promote these items button should not be enabled", ElementUtil.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled")); assertThat("Promoted items count should equal 0", searchPage.promotedItemsCount(), is(0)); searchPage.searchResultCheckbox(1).click(); assertThat("Promote these items button should be enabled", !ElementUtil.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled")); assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(1)); searchPage.promotionsBucketClose(); assertThat("Promoted items bucket has not appeared", searchPage.getText(), not(containsString("Select Items to Promote"))); searchPage.promoteTheseDocumentsButton().click(); Waits.loadOrFadeWait(); assertThat("Promoted items bucket has not appeared", searchPage.promotionsBucket().isDisplayed()); assertThat("Promote these items button should not be enabled", ElementUtil.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled")); assertThat("Promoted items count should equal 0", searchPage.promotedItemsCount(), is(0)); } @Test public void testAddFilesToPromoteBucket() { searchPage.promoteTheseDocumentsButton().click(); Waits.loadOrFadeWait(); for (int i = 1; i < 7; i++) { ElementUtil.scrollIntoView(searchPage.searchResultCheckbox(i), getDriver()); searchPage.searchResultCheckbox(i).click(); assertThat("Promoted items count not correct", searchPage.promotedItemsCount(),is(i)); } for (int j = 6; j > 0; j--) { ElementUtil.scrollIntoView(searchPage.searchResultCheckbox(j), getDriver()); searchPage.searchResultCheckbox(j).click(); assertThat("Promoted items count not correct", searchPage.promotedItemsCount(), is(j - 1)); } searchPage.promotionsBucketClose(); } //TODO fix this test so it's not being run on something with an obscene amount of pages @Ignore @Test public void testSearchResultsPagination() { search("dog"); Waits.loadOrFadeWait(); assertThat("Back to first page button is not disabled", searchPage.isBackToFirstPageButtonDisabled()); assertThat("Back a page button is not disabled", ElementUtil.getParent(searchPage.backPageButton()).getAttribute("class"),containsString("disabled")); ElementUtil.javascriptClick(searchPage.forwardPageButton(), getDriver()); searchPage.paginateWait(); assertThat("Back to first page button is not enabled", ElementUtil.getParent(searchPage.backToFirstPageButton()).getAttribute("class"),not(containsString("disabled"))); assertThat("Back a page button is not enabled", ElementUtil.getParent(searchPage.backPageButton()).getAttribute("class"),not(containsString("disabled"))); assertThat("Page 2 is not active", searchPage.isPageActive(2)); ElementUtil.javascriptClick(searchPage.forwardPageButton(), getDriver()); searchPage.paginateWait(); ElementUtil.javascriptClick(searchPage.forwardPageButton(), getDriver()); searchPage.paginateWait(); ElementUtil.javascriptClick(searchPage.backPageButton(), getDriver()); searchPage.paginateWait(); assertThat("Page 3 is not active", searchPage.isPageActive(3)); ElementUtil.javascriptClick(searchPage.backToFirstPageButton(), getDriver()); searchPage.paginateWait(); assertThat("Page 1 is not active", searchPage.isPageActive(1)); ElementUtil.javascriptClick(searchPage.forwardToLastPageButton(), getDriver()); searchPage.paginateWait(); assertThat("Forward to last page button is not disabled", ElementUtil.getParent(searchPage.forwardToLastPageButton()).getAttribute("class"),containsString("disabled")); assertThat("Forward a page button is not disabled", ElementUtil.getParent(searchPage.forwardPageButton()).getAttribute("class"),containsString("disabled")); final int numberOfPages = searchPage.getCurrentPageNumber(); for (int i = numberOfPages - 1; i > 0; i--) { ElementUtil.javascriptClick(searchPage.backPageButton(), getDriver()); searchPage.paginateWait(); assertThat("Page " + String.valueOf(i) + " is not active", searchPage.isPageActive(i)); assertThat("Url incorrect", getDriver().getCurrentUrl(),endsWith(String.valueOf(i))); } for (int j = 2; j < numberOfPages + 1; j++) { ElementUtil.javascriptClick(searchPage.forwardPageButton(), getDriver()); searchPage.paginateWait(); assertThat("Page " + String.valueOf(j) + " is not active", searchPage.isPageActive(j)); assertThat("Url incorrect", getDriver().getCurrentUrl(),endsWith(String.valueOf(j))); } } // This used to fail because the predict=false parameter was not added to our query actions @Test public void testPaginationAndBackButton() { search("safe"); searchPage.forwardToLastPageButton().click(); Waits.loadOrFadeWait(); assertThat("Forward to last page button is not disabled", searchPage.forwardToLastPageButton().getAttribute("class"),containsString("disabled")); assertThat("Forward a page button is not disabled", searchPage.forwardPageButton().getAttribute("class"), containsString("disabled")); final int lastPage = searchPage.getCurrentPageNumber(); getDriver().navigate().back(); assertThat("Back button has not brought the user back to the first page", searchPage.getCurrentPageNumber(), is(1)); getDriver().navigate().forward(); assertThat("Forward button has not brought the user back to the last page", searchPage.getCurrentPageNumber(), is(lastPage)); } @Test public void testAddDocumentToPromotionsBucket() { search("horse"); searchPage.promoteTheseDocumentsButton().click(); searchPage.searchResultCheckbox(1).click(); assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(1)); assertThat("File in bucket description does not match file added", searchPage.getSearchResultTitle(1), equalToIgnoringCase(searchPage.bucketDocumentTitle(1))); } @Test public void testPromoteTheseItemsButtonLink() { search("fox"); searchPage.promoteTheseDocumentsButton().click(); searchPage.searchResultCheckbox(1).click(); searchPage.promoteTheseItemsButton().click(); assertThat("Create new promotions page not open", getDriver().getCurrentUrl(), endsWith("promotions/create")); } @Test public void testMultiDocPromotionDrawerExpandAndPagination() { Promotion promotion = new SpotlightPromotion("boat"); Search search = new Search(getApplication(), getElementFactory(), "freeze"); PromotionService promotionService = getApplication().createPromotionService(getElementFactory()); promotionService.setUpPromotion(promotion, search, 18); try { PromotionsDetailPage promotionsDetailPage = promotionService.goToDetails(promotion); promotionsDetailPage.trigger("boat").click(); searchPage = getElementFactory().getSearchPage(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); assertThat("two promotions visible", searchPage.getPromotionSummarySize(), is(2)); assertThat("can show more", searchPage.showMorePromotionsButton(), displayed()); searchPage.showMorePromotions(); assertThat("showing more", searchPage.getPromotionSummarySize(), is(5)); searchPage.showLessPromotions(); assertThat("showing less", searchPage.getPromotionSummarySize(), is(2)); searchPage.showMorePromotions(); assertThat("showing more again", searchPage.getPromotionSummarySize(), is(5)); searchPage.promotionSummaryForwardButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); logger.info("on page 2"); verifyPromotionPagination(true, true); searchPage.promotionSummaryForwardButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); searchPage.promotionSummaryForwardButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); logger.info("on last page"); verifyPromotionPagination(true, false); searchPage.promotionSummaryBackButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); searchPage.promotionSummaryBackButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); searchPage.promotionSummaryBackButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); logger.info("on first page"); verifyPromotionPagination(false, true); searchPage.promotionSummaryForwardToEndButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); logger.info("on last page"); verifyPromotionPagination(true, false); searchPage.promotionSummaryBackToStartButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); logger.info("on first page"); verifyPromotionPagination(false, true); } finally { promotionService.deleteAll(); } } private void verifyPromotionPagination(boolean previousEnabled, boolean nextEnabled) { verifyButtonEnabled("back to start", searchPage.promotionSummaryBackToStartButton(), previousEnabled); verifyButtonEnabled("back", searchPage.promotionSummaryBackButton(), previousEnabled); verifyButtonEnabled("forward", searchPage.promotionSummaryForwardButton(), nextEnabled); verifyButtonEnabled("forward to end", searchPage.promotionSummaryForwardToEndButton(), nextEnabled); } private void verifyButtonEnabled(String name, WebElement element, boolean enabled) { if (enabled) { verifyThat(name + " button enabled", element, not(hasClass("disabled"))); } else { verifyThat(name + " button disabled", element, hasClass("disabled")); } } @Test public void testDocumentsRemainInBucket() { search("cow"); searchPage.promoteTheseDocumentsButton().click(); searchPage.searchResultCheckbox(1).click(); searchPage.searchResultCheckbox(2).click(); assertThat("Promoted items count should equal 2", searchPage.promotedItemsCount(), is(2)); search("bull"); assertThat("Promoted items count should equal 2", searchPage.promotedItemsCount(), is(2)); searchPage.searchResultCheckbox(1).click(); assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(3)); search("cow"); assertThat("Promoted items count should equal 2", searchPage.promotedItemsCount(), is(3)); search("bull"); assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(3)); searchPage.searchResultCheckbox(1).click(); assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(2)); search("cow"); assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(2)); } @Test public void testWhitespaceSearch() { search(" "); assertThat("Whitespace search should not return a message as if it is a blacklisted term", searchPage.getText(),not(containsString("All search terms are blacklisted"))); } String searchErrorMessage = "An error occurred executing the search action"; String correctErrorMessageNotShown = "Correct error message not shown"; @Test public void testSearchParentheses() { List<String> testSearchTerms = Arrays.asList("(",")","()",") (",")war"); if(getConfig().getType().equals(ApplicationType.HOSTED)){ for(String searchTerm : testSearchTerms){ search(searchTerm); assertThat(searchPage.getText(),containsString(Errors.Search.HOD)); } } else if (getConfig().getType().equals(ApplicationType.ON_PREM)) { int searchTerm = 0; String bracketMismatch = "Bracket Mismatch in the query"; search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(bracketMismatch)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(bracketMismatch)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("No valid query text supplied")); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("Terminating boolean operator")); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(bracketMismatch)); } else { fail("Config type not recognised"); } } //TODO there are some which contain helpful error messages? @Test public void testSearchQuotationMarks() { List<String> testSearchTerms = Arrays.asList("\"","\"\"","\" \"","\" \"","\"word","\" word","\" wo\"rd\""); if(getConfig().getType().equals(ApplicationType.HOSTED)){ for (String searchTerm : testSearchTerms){ search(searchTerm); assertThat(searchPage.getText(),containsString(Errors.Search.HOD)); } } else if (getConfig().getType().equals(ApplicationType.ON_PREM)) { String noValidQueryText = "No valid query text supplied"; String unclosedPhrase = "Unclosed phrase"; int searchTerm = 0; search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(noValidQueryText)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(noValidQueryText)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(noValidQueryText)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("An error occurred executing the search action")); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("An error occurred executing the search action")); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase)); } else { fail("Config type not recognised"); } } @Test public void testDeleteDocsFromWithinBucket() { search("sabre"); searchPage.promoteTheseDocumentsButton().click(); searchPage.searchResultCheckbox(1).click(); searchPage.searchResultCheckbox(2).click(); searchPage.searchResultCheckbox(3).click(); searchPage.searchResultCheckbox(4).click(); final List<String> bucketList = searchPage.promotionsBucketList(); final List<WebElement> bucketListElements = searchPage.promotionsBucketWebElements(); assertThat("There should be four documents in the bucket", bucketList.size(),is(4)); assertThat("promote button not displayed when bucket has documents", searchPage.promoteTheseDocumentsButton().isDisplayed()); // for (final String bucketDocTitle : bucketList) { // final int docIndex = bucketList.indexOf(bucketDocTitle); // assertFalse("The document title appears as blank within the bucket for document titled " + searchPage.getSearchResult(bucketList.indexOf(bucketDocTitle) + 1).getText(), bucketDocTitle.equals("")); // searchPage.deleteDocFromWithinBucket(bucketDocTitle); // assertThat("Checkbox still selected when doc deleted from bucket", !searchPage.searchResultCheckbox(docIndex + 1).isSelected()); // assertThat("Document not removed from bucket", searchPage.promotionsBucketList(),not(hasItem(bucketDocTitle))); // assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(),is(3 - docIndex)); // } for (final WebElement bucketDoc : bucketListElements) { bucketDoc.findElement(By.cssSelector("i:nth-child(2)")).click(); } assertThat("promote button should be disabled when bucket has no documents", ElementUtil.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled")); search("tooth"); assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(), is(0)); searchPage.searchResultCheckbox(5).click(); final List<String> docTitles = new ArrayList<>(); docTitles.add(searchPage.getSearchResultTitle(5)); ElementUtil.javascriptClick(searchPage.forwardPageButton(), getDriver()); Waits.loadOrFadeWait(); searchPage.searchResultCheckbox(3).click(); docTitles.add(searchPage.getSearchResultTitle(3)); final List<String> bucketListNew = searchPage.promotionsBucketList(); assertThat("Wrong number of documents in the bucket", bucketListNew.size(),is(2)); // assertThat("", searchPage.promotionsBucketList().containsAll(docTitles)); assertThat(bucketListNew.size(),is(docTitles.size())); for(String docTitle : docTitles){ assertThat(bucketListNew,hasItem(docTitle.toUpperCase())); } searchPage.deleteDocFromWithinBucket(docTitles.get(1)); assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(),is(1)); assertThat("Document should still be in the bucket", searchPage.promotionsBucketList(),hasItem(docTitles.get(0).toUpperCase())); assertThat("Document should no longer be in the bucket", searchPage.promotionsBucketList(),not(hasItem(docTitles.get(1).toUpperCase()))); assertThat("Checkbox still selected when doc deleted from bucket", !searchPage.searchResultCheckbox(3).isSelected()); ElementUtil.javascriptClick(searchPage.backPageButton(), getDriver()); searchPage.deleteDocFromWithinBucket(docTitles.get(0)); assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(),is(0)); assertThat("Checkbox still selected when doc deleted from bucket", !searchPage.searchResultCheckbox(5).isSelected()); assertThat("promote button should be disabled when bucket has no documents", ElementUtil.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled")); } @Test public void testViewFrame() throws InterruptedException { search("army"); searchPage.waitForSearchLoadIndicatorToDisappear(); for (final boolean clickLogo : Arrays.asList(true, false)) { for (int page = 1; page <= 2; page++) { for (int result = 1; result <= 6; result++) { Waits.loadOrFadeWait(); searchPage.viewFrameClick(clickLogo, result); checkViewResult(); } ElementUtil.javascriptClick(searchPage.forwardPageButton(), getDriver()); Waits.loadOrFadeWait(); } } } private void checkViewResult() { final String handle = getDriver().getWindowHandle(); DocumentViewer docViewer = DocumentViewer.make(getDriver()); getDriver().switchTo().frame(docViewer.frame()); verifyThat(getDriver().findElement(By.xpath(".//*")), not(hasTextThat(isEmptyOrNullString()))); getDriver().switchTo().window(handle); docViewer.close(); } @Test public void testViewFromBucketLabel() throws InterruptedException { search("جيمس"); searchPage.selectLanguage(Language.ARABIC); logger.warn("Using Trimmed Titles"); search("Engineer"); //Testing in Arabic because in some instances not latin urls have been encoded incorrectly searchPage.waitForSearchLoadIndicatorToDisappear(); searchPage.promoteTheseDocumentsButton().click(); for (int j = 1; j <=2; j++) { for (int i = 1; i <= 3; i++) { final String handle = getDriver().getWindowHandle(); searchPage.searchResultCheckbox(i).click(); final String docTitle = searchPage.getSearchResultTitle(i); searchPage.getPromotionBucketElementByTitle(docTitle).click(); Thread.sleep(5000); getDriver().switchTo().frame(getDriver().findElement(By.tagName("iframe"))); //Using trimmedtitle is a really hacky way to get around the latin urls not being encoded (possibly, or another problem) correctly assertThat("View frame does not contain document", getDriver().findElement(By.xpath(".//*")).getText(),containsString(docTitle)); getDriver().switchTo().window(handle); getDriver().findElement(By.xpath("//button[contains(@id, 'cboxClose')]")).click(); Waits.loadOrFadeWait(); } ElementUtil.javascriptClick(searchPage.forwardPageButton(), getDriver()); Waits.loadOrFadeWait(); } } @Test public void testChangeLanguage() { assumeThat("Lanugage not implemented in Hosted", getConfig().getType(), Matchers.not(ApplicationType.HOSTED)); String docTitle = searchPage.getSearchResultTitle(1); search("1"); List<Language> languages = Arrays.asList(Language.ENGLISH, Language.AFRIKAANS, Language.FRENCH, Language.ARABIC, Language.URDU, Language.HINDI, Language.CHINESE, Language.SWAHILI); for (final Language language : languages) { searchPage.selectLanguage(language); assertThat(searchPage.getSelectedLanguage(), is(language.toString())); searchPage.waitForSearchLoadIndicatorToDisappear(); assertThat(searchPage.getSearchResultTitle(1), not(docTitle)); docTitle = searchPage.getSearchResultTitle(1); } } @Test public void testBucketEmptiesWhenLanguageChangedInURL() { search("arc"); searchPage.selectLanguage(Language.FRENCH); searchPage.waitForSearchLoadIndicatorToDisappear(); searchPage.promoteTheseDocumentsButton().click(); for (int i = 1; i <=4; i++) { searchPage.searchResultCheckbox(i).click(); } assertThat(searchPage.promotionsBucketWebElements(), hasSize(4)); final String url = getDriver().getCurrentUrl().replace("french", "arabic"); getDriver().get(url); searchPage = getElementFactory().getSearchPage(); Waits.loadOrFadeWait(); assertThat("Have not navigated back to search page with modified url " + url, searchPage.promoteThisQueryButton().isDisplayed()); assertThat(searchPage.promotionsBucketWebElements(), hasSize(0)); } @Test public void testLanguageDisabledWhenBucketOpened() { assumeThat("Lanugage not implemented in Hosted", getConfig().getType(), Matchers.not(ApplicationType.HOSTED)); //This test currently fails because language dropdown is not disabled when the promotions bucket is open searchPage.selectLanguage(Language.ENGLISH); search("al"); Waits.loadOrFadeWait(); assertThat("Languages should be enabled", !ElementUtil.isAttributePresent(searchPage.languageButton(), "disabled")); searchPage.promoteTheseDocumentsButton().click(); searchPage.searchResultCheckbox(1).click(); assertThat("There should be one document in the bucket", searchPage.promotionsBucketList(), hasSize(1)); searchPage.selectLanguage(Language.FRENCH); assertThat("The promotions bucket should close when the language is changed", searchPage.promotionsBucket(), not(displayed())); searchPage.promoteTheseDocumentsButton().click(); assertThat("There should be no documents in the bucket after changing language", searchPage.promotionsBucketList(), hasSize(0)); searchPage.selectLanguage(Language.ENGLISH); assertThat("The promotions bucket should close when the language is changed", searchPage.promotionsBucket(), not(displayed())); } @Test public void testSearchAlternateScriptToSelectedLanguage() { List<Language> languages = Arrays.asList(Language.FRENCH, Language.ENGLISH, Language.ARABIC, Language.URDU, Language.HINDI, Language.CHINESE); for (final Language language : languages) { searchPage.selectLanguage(language); for (final String script : Arrays.asList("निर्वाण", "العربية", "עברית", "сценарий", "latin", "ελληνικά", "ქართული", "བོད་ཡིག")) { search(script); Waits.loadOrFadeWait(); assertThat("Undesired error message for language: " + language + " with script: " + script, searchPage.findElement(By.cssSelector(".search-results-view")).getText(),not(containsString("error"))); } } } @Test public void testFieldTextFilter() { search("text"); if (config.getType().equals(ApplicationType.HOSTED)) { applyFilter(new IndexFilter("sitesearch")); } final String searchResultTitle = searchPage.getSearchResultTitle(1); final String firstWord = getFirstWord(searchResultTitle); final int comparisonResult = searchResultNotStarting(firstWord); final String comparisonString = searchPage.getSearchResultTitle(comparisonResult); searchPage.expand(SearchBase.Facet.FIELD_TEXT); searchPage.fieldTextAddButton().click(); Waits.loadOrFadeWait(); assertThat("input visible", searchPage.fieldTextInput(), displayed()); assertThat("confirm button visible", searchPage.fieldTextTickConfirm(), displayed()); searchPage.setFieldText("WILD{" + firstWord + "*}:DRETITLE"); assertThat(searchPage, not(containsText(Errors.Search.HOD))); assertThat("edit button visible", searchPage.fieldTextEditButton(), displayed()); assertThat("remove button visible", searchPage.fieldTextRemoveButton(), displayed()); assertThat(searchPage.getSearchResultTitle(1), is(searchResultTitle)); try { assertThat(searchPage.getSearchResultTitle(comparisonResult), not(comparisonString)); } catch (final NoSuchElementException e) { // The comparison document is not present } searchPage.fieldTextRemoveButton().click(); Waits.loadOrFadeWait(); assertThat(searchPage.getSearchResultTitle(comparisonResult), is(comparisonString)); assertThat("Field text add button not visible", searchPage.fieldTextAddButton().isDisplayed()); assertThat(searchPage.getSearchResultTitle(1), is(searchResultTitle)); } private int searchResultNotStarting(String prefix) { for (int result = 1; result <= SearchPage.RESULTS_PER_PAGE; result++) { String comparisonString = searchPage.getSearchResultTitle(result); if (!comparisonString.startsWith(prefix)) { return result; } } throw new IllegalStateException("Cannot test field text filter with this search"); } @Test public void testEditFieldText() { if (getConfig().getType().equals(ApplicationType.ON_PREM)) { searchPage.selectAllIndexesOrDatabases(getConfig().getType().getName()); search("boer"); } else { new Search(getApplication(), getElementFactory(), "*").applyFilter(new IndexFilter("sitesearch")).apply(); } searchPage.selectLanguage(Language.AFRIKAANS); searchPage.clearFieldText(); final String firstSearchResult = searchPage.getSearchResultTitle(1); final String secondSearchResult = searchPage.getSearchResultTitle(2); searchPage.fieldTextAddButton().click(); Waits.loadOrFadeWait(); searchPage.fieldTextInput().clear(); searchPage.fieldTextInput().sendKeys("MATCH{" + firstSearchResult + "}:DRETITLE"); searchPage.fieldTextTickConfirm().click(); Waits.loadOrFadeWait(); searchPage.waitForSearchLoadIndicatorToDisappear(); assertThat("Field Text should not have caused an error", searchPage.getText(), not(containsString(Errors.Search.HOD))); assertThat(searchPage.getText(), not(containsString("No results found"))); assertThat(searchPage.getSearchResultTitle(1), is(firstSearchResult)); searchPage.fieldTextEditButton().click(); searchPage.fieldTextInput().clear(); searchPage.fieldTextInput().sendKeys("MATCH{" + secondSearchResult + "}:DRETITLE"); searchPage.fieldTextTickConfirm().click(); Waits.loadOrFadeWait(); searchPage.waitForSearchLoadIndicatorToDisappear(); assertThat("Field Text should not have caused an error", searchPage.getText(), not(containsString(Errors.Search.HOD))); assertThat(searchPage.getSearchResultTitle(1), is(secondSearchResult)); } @Test public void testFieldTextInputDisappearsOnOutsideClick() { searchPage.expand(SearchBase.Facet.FIELD_TEXT); assertThat("Field text add button not visible", searchPage.fieldTextAddButton().isDisplayed()); searchPage.fieldTextAddButton().click(); assertThat("Field text add button visible", !searchPage.fieldTextAddButton().isDisplayed()); assertThat("Field text input not visible", searchPage.fieldTextInput().isDisplayed()); searchPage.fieldTextInput().click(); assertThat("Field text add button visible", !searchPage.fieldTextAddButton().isDisplayed()); assertThat("Field text input not visible", searchPage.fieldTextInput().isDisplayed()); searchPage.expand(SearchBase.Facet.RELATED_CONCEPTS); assertThat("Field text add button not visible", searchPage.fieldTextAddButton().isDisplayed()); assertThat("Field text input visible", !searchPage.fieldTextInput().isDisplayed()); } @Test public void testIdolSearchTypes() { final int redCount = getResultCount("red"); final int starCount = getResultCount("star"); final int unquotedCount = getResultCount("red star"); final int quotedCount = getResultCount("\"red star\""); final int orCount = getResultCount("red OR star"); final int andCount = getResultCount("red AND star"); final int redNotStarCount = getResultCount("red NOT star"); final int starNotRedCount = getResultCount("star NOT red"); verifyThat(redCount, lessThanOrEqualTo(unquotedCount)); verifyThat(quotedCount, lessThanOrEqualTo(unquotedCount)); verifyThat(redNotStarCount, lessThanOrEqualTo(redCount)); verifyThat(starNotRedCount, lessThanOrEqualTo(starCount)); verifyThat(quotedCount, lessThanOrEqualTo(andCount)); verifyThat(andCount, lessThanOrEqualTo(unquotedCount)); verifyThat(orCount, lessThanOrEqualTo(redCount + starCount)); verifyThat(andCount + redNotStarCount + starNotRedCount, is(orCount)); verifyThat(orCount, is(unquotedCount)); } private int getResultCount(String searchTerm) { search(searchTerm); return searchPage.getHeadingResultsCount(); } //TODO @Test public void testFieldTextRestrictionOnPromotions(){ PromotionService promotionService = getApplication().createPromotionService(getElementFactory()); promotionService.deleteAll(); promotionService.setUpPromotion(new SpotlightPromotion(Promotion.SpotlightType.SPONSORED, "boat"), "darth", 2); searchPage = getElementFactory().getSearchPage(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); Waits.loadOrFadeWait(); assertThat(searchPage.getPromotionSummarySize(), is(2)); assertThat(searchPage.getPromotionSummaryLabels(), hasSize(2)); final List<String> initialPromotionsSummary = searchPage.promotionsSummaryList(false); searchPage.setFieldText("MATCH{" + initialPromotionsSummary.get(0) + "}:DRETITLE"); assertThat(searchPage.getPromotionSummarySize(), is(1)); assertThat(searchPage.getPromotionSummaryLabels(), hasSize(1)); assertThat(searchPage.promotionsSummaryList(false).get(0), is(initialPromotionsSummary.get(0))); searchPage.fieldTextEditButton().click(); searchPage.fieldTextInput().clear(); searchPage.fieldTextInput().sendKeys("MATCH{" + initialPromotionsSummary.get(1) + "}:DRETITLE"); searchPage.fieldTextTickConfirm().click(); Waits.loadOrFadeWait(); assertThat(searchPage.getPromotionSummarySize(), is(1)); assertThat(searchPage.getPromotionSummaryLabels(), hasSize(1)); assertThat(searchPage.promotionsSummaryList(false).get(0), is(initialPromotionsSummary.get(1))); } @Test public void testFieldTextRestrictionOnPinToPositionPromotions(){ body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS); promotionsPage = getElementFactory().getPromotionsPage(); promotionsPage.deleteAllPromotions(); search("horse"); searchPage.selectLanguage(Language.ENGLISH); final List<String> promotedDocs = searchPage.createAMultiDocumentPromotion(2); createPromotionsPage = getElementFactory().getCreateNewPromotionsPage(); createPromotionsPage.navigateToTriggers(); createPromotionsPage.addSearchTrigger("duck"); createPromotionsPage.finishButton().click(); new WebDriverWait(getDriver(),10).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); searchPage.waitForSearchLoadIndicatorToDisappear(); assertThat(promotedDocs.get(0) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(0))); assertThat(promotedDocs.get(1) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(1))); searchPage.setFieldText("WILD{*horse*}:DRETITLE"); searchPage.waitForSearchLoadIndicatorToDisappear(); Waits.loadOrFadeWait(); assertThat(promotedDocs.get(0) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(0))); assertThat(promotedDocs.get(1) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(1))); //TODO Seems like this shouldn't be visible assertThat("Wrong number of results displayed", searchPage.getHeadingResultsCount(), is(2)); assertThat("Wrong number of pin to position labels displayed", searchPage.countPinToPositionLabels(), is(2)); searchPage.fieldTextEditButton().click(); searchPage.fieldTextInput().clear(); searchPage.fieldTextInput().sendKeys("MATCH{" + promotedDocs.get(0) + "}:DRETITLE"); searchPage.fieldTextTickConfirm().click(); Waits.loadOrFadeWait(); assertThat(searchPage.getSearchResultTitle(1), is(promotedDocs.get(0))); assertThat(searchPage.getHeadingResultsCount(), is(1)); assertThat(searchPage.countPinToPositionLabels(), is(1)); searchPage.fieldTextEditButton().click(); searchPage.fieldTextInput().clear(); searchPage.fieldTextInput().sendKeys("MATCH{" + promotedDocs.get(1) + "}:DRETITLE"); searchPage.fieldTextTickConfirm().click(); Waits.loadOrFadeWait(); assertThat(promotedDocs.get(1) + " not visible in the search title", searchPage.getSearchResultTitle(1), is(promotedDocs.get(1))); assertThat("Wrong number of search results", searchPage.getHeadingResultsCount(), is(1)); assertThat("Wrong number of pin to position labels", searchPage.countPinToPositionLabels(), is(1)); } // CSA-1818 @Test public void testSearchResultsCount() { searchPage.selectLanguage(Language.ENGLISH); for (final String query : Arrays.asList("dog", "chips", "dinosaur", "melon", "art")) { search(query); final int firstPageResultsCount = searchPage.getHeadingResultsCount(); searchPage.forwardToLastPageButton().click(); searchPage.waitForSearchLoadIndicatorToDisappear(); verifyThat("number of results in title is consistent", searchPage.getHeadingResultsCount(), is(firstPageResultsCount)); final int completePages = searchPage.getCurrentPageNumber() - 1; final int lastPageDocumentsCount = searchPage.visibleDocumentsCount(); final int expectedCount = completePages * SearchPage.RESULTS_PER_PAGE + lastPageDocumentsCount; verifyThat("number of results is as expected", searchPage.getHeadingResultsCount(), is(expectedCount)); } } @Test public void testInvalidQueryTextNoKeywordsLinksDisplayed() { //TODO: map error messages to application type List<String> boolOperators = Arrays.asList("OR", "WHEN", "SENTENCE", "DNEAR"); List<String> stopWords = Arrays.asList("a", "the", "of", "SOUNDEX"); //According to IDOL team SOUNDEX isn't considered a boolean operator without brackets searchPage.selectLanguage(Language.ENGLISH); if(getConfig().getType().equals(ApplicationType.HOSTED)) { List<String> allTerms = ListUtils.union(boolOperators, stopWords); for (final String searchTerm : allTerms) { search(searchTerm); assertThat("Correct error message not present for searchterm: " + searchTerm, searchPage.getText(), containsString(Errors.Search.HOD)); } } else if (getConfig().getType().equals(ApplicationType.ON_PREM)) { for (final String searchTerm : boolOperators) { search(searchTerm); assertThat("Correct error message not present for searchterm: " + searchTerm + searchPage.getText(), searchPage.getText(), containsString("An error occurred executing the search action")); assertThat("Correct error message not present for searchterm: " + searchTerm, searchPage.getText(), containsString("An error occurred fetching the query analysis.")); assertThat("Correct error message not present for searchterm: " + searchTerm, searchPage.getText(), containsString("Opening boolean operator")); } for (final String searchTerm : stopWords) { search(searchTerm); assertThat("Correct error message not present", searchPage.getText(), containsString("An error occurred executing the search action")); assertThat("Correct error message not present", searchPage.getText(), containsString("An error occurred fetching the query analysis.")); assertThat("Correct error message not present", searchPage.getText(), containsString("No valid query text supplied")); } } else { fail("Application Type not recognised"); } } @Test public void testAllowSearchOfStringsThatContainBooleansWithinThem() { final List<String> hiddenBooleansProximities = Arrays.asList("NOTed", "ANDREW", "ORder", "WHENCE", "SENTENCED", "PARAGRAPHING", "NEARLY", "SENTENCE1D", "PARAGRAPHING", "PARAGRAPH2inG", "SOUNDEXCLUSIVE", "XORING", "EORE", "DNEARLY", "WNEARING", "YNEARD", "AFTERWARDS", "BEFOREHAND", "NOTWHENERED"); for (final String hiddenBooleansProximity : hiddenBooleansProximities) { search(hiddenBooleansProximity); Waits.loadOrFadeWait(); assertThat(searchPage.getText(), not(containsString("Terminating boolean operator"))); } } @Test public void testFromDateFilter() throws ParseException { search("Dog"); // some indexes do not have dates new IndexFilter("wiki_eng").apply(searchPage); searchPage.waitForSearchLoadIndicatorToDisappear(); final String firstResult = searchPage.getSearchResultTitle(1); final Date date = searchPage.getDateFromResult(1); if (date == null) { throw new IllegalStateException("testFromDateFilter requires first search result to have a date"); } searchPage.openFromDatePicker(); datePicker = new DatePicker(searchPage.$el(), getDriver()); datePicker.calendarDateSelect(date); searchPage.closeFromDatePicker(); assertThat("displayed with filter = $time", searchPage.getSearchResultTitle(1), is(firstResult)); searchPage.openFromDatePicker(); datePicker = new DatePicker(searchPage.$el(), getDriver()); datePicker.calendarDateSelect(DateUtils.addMinutes(date, 1)); searchPage.closeFromDatePicker(); assertThat("not displayed with filter = $time + 1min", searchPage.getSearchResultTitle(1), not(firstResult)); searchPage.openFromDatePicker(); datePicker = new DatePicker(searchPage.$el(), getDriver()); datePicker.calendarDateSelect(DateUtils.addMinutes(date, -1)); searchPage.closeFromDatePicker(); assertThat("displayed with filter = $time - 1min", searchPage.getSearchResultTitle(1), is(firstResult)); } @Test public void testUntilDateFilter() throws ParseException { search("Dog"); // not all indexes have times configured new IndexFilter("news_eng").apply(searchPage); Waits.loadOrFadeWait(); searchPage.waitForSearchLoadIndicatorToDisappear(); final String firstResult = searchPage.getSearchResultTitle(1); Date date = searchPage.getDateFromResult(1); logger.info("First Result: " + firstResult + " " + date); // plus 1 minute to be inclusive date = DateUtils.addMinutes(date, 1); searchPage.filterBy(new DatePickerFilter().until(date)); for (final String label : searchPage.filterLabelList()) { assertThat("no 'From' filter applied", label,not(containsString("From: "))); } assertThat("applied 'Until' filter", searchPage.untilDateTextBox().getAttribute("value"), not(isEmptyOrNullString())); logger.info(searchPage.untilDateTextBox().getAttribute("value")); assertThat(searchPage.getHeadingResultsCount(), greaterThan(0)); assertThat("Document should still be displayed", searchPage.getSearchResultTitle(1), is(firstResult)); searchPage.filterBy(new DatePickerFilter().until(DateUtils.addMinutes(date, -1))); logger.info(searchPage.untilDateTextBox().getAttribute("value")); assertThat("Document should not be visible. Date filter not working", searchPage.getSearchResultTitle(1), not(firstResult)); searchPage.filterBy(new DatePickerFilter().until(DateUtils.addMinutes(date, 1))); assertThat(searchPage.getHeadingResultsCount(), greaterThan(0)); assertThat("Document should be visible. Date filter not working", searchPage.getSearchResultTitle(1), is(firstResult)); } @Test public void testFromDateAlwaysBeforeUntilDate() { search("food"); searchPage.expand(SearchBase.Facet.FILTER_BY); searchPage.expand(SearchBase.Facet.DATES); searchPage.fromDateTextBox().sendKeys("04/05/2000 12:00 PM"); searchPage.untilDateTextBox().sendKeys("04/05/2000 12:00 PM"); searchPage.sortBy(SearchBase.Sort.RELEVANCE); assertThat("Dates should be equal", searchPage.fromDateTextBox().getAttribute("value"), is(searchPage.untilDateTextBox().getAttribute("value"))); Waits.loadOrFadeWait(); searchPage.fromDateTextBox().clear(); searchPage.fromDateTextBox().sendKeys("04/05/2000 12:01 PM"); //clicking sort by relevance because an outside click is needed for the changes to take place searchPage.sortBy(SearchBase.Sort.RELEVANCE); // assertNotEquals("From date cannot be after the until date", searchPage.fromDateTextBox().getAttribute("value"), "04/05/2000 12:01 PM"); assertThat("From date should be blank", searchPage.fromDateTextBox().getAttribute("value"), isEmptyOrNullString()); searchPage.fromDateTextBox().clear(); searchPage.fromDateTextBox().sendKeys("04/05/2000 12:00 PM"); searchPage.untilDateTextBox().clear(); searchPage.untilDateTextBox().sendKeys("04/05/2000 11:59 AM"); searchPage.sortBy(SearchBase.Sort.RELEVANCE); // assertEquals("Until date cannot be before the from date", searchPage.untilDateTextBox().getAttribute("value"),is(not("04/05/2000 11:59 AM"))); assertThat("Until date should be blank", searchPage.untilDateTextBox().getAttribute("value"), isEmptyOrNullString()); } @Test public void testFromDateEqualsUntilDate() throws ParseException { search("Search"); searchPage.expand(SearchBase.Facet.FILTER_BY); searchPage.expand(SearchBase.Facet.DATES); // searchPage.openFromDatePicker(); // searchPage.closeFromDatePicker(); // searchPage.openUntilDatePicker(); // searchPage.closeUntilDatePicker(); searchPage.fromDateTextBox().sendKeys("12/12/2012 12:12"); searchPage.untilDateTextBox().sendKeys("12/12/2012 12:12"); assertThat("Datepicker dates are not equal", searchPage.fromDateTextBox().getAttribute("value"), is(searchPage.untilDateTextBox().getAttribute("value"))); final Date date = searchPage.getDateFromFilter(searchPage.untilDateTextBox()); searchPage.sendDateToFilter(DateUtils.addMinutes(date, 1), searchPage.untilDateTextBox()); searchPage.sortBy(SearchBase.Sort.RELEVANCE); assertThat(searchPage.untilDateTextBox().getAttribute("value"), is("12/12/2012 12:13")); searchPage.sendDateToFilter(DateUtils.addMinutes(date, -1), searchPage.untilDateTextBox()); //clicking sort by relevance because an outside click is needed for the changes to take place searchPage.sortBy(SearchBase.Sort.RELEVANCE); assertThat(searchPage.untilDateTextBox().getAttribute("value"), isEmptyOrNullString()); } @Test public void testSortByRelevance() { search("string"); searchPage.sortBy(SearchBase.Sort.RELEVANCE); List<Float> weights = searchPage.getWeightsOnPage(5); logger.info("Weight of 0: " + weights.get(0)); for (int i = 0; i < weights.size() - 1; i++) { logger.info("Weight of " + (i + 1) + ": " + weights.get(i + 1)); assertThat("Weight of search result " + i + " is not greater that weight of search result " + (i + 1), weights.get(i), greaterThanOrEqualTo(weights.get(i + 1))); } searchPage.sortBy(SearchBase.Sort.DATE); searchPage.sortBy(SearchBase.Sort.RELEVANCE); weights = searchPage.getWeightsOnPage(5); for (int i = 0; i < weights.size() - 1; i++) { assertThat("Weight of search result " + i + " is not greater that weight of search result " + (i + 1), weights.get(i), greaterThanOrEqualTo(weights.get(i + 1))); } searchPage.sortBy(SearchBase.Sort.DATE); search("paper packages"); searchPage.sortBy(SearchBase.Sort.RELEVANCE); weights = searchPage.getWeightsOnPage(5); for (int i = 0; i < weights.size() - 1; i++) { assertThat("Weight of search result " + i + " is not greater that weight of search result " + (i + 1), weights.get(i), greaterThanOrEqualTo(weights.get(i + 1))); } } @Test public void testSearchBarTextPersistsOnRefresh() { final String searchText = "Stay"; search(searchText); // Change to promotions page since the search page will persist the query in the URL body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS); getDriver().navigate().refresh(); body = getBody(); final String newSearchText = body.getTopNavBar().getSearchBarText(); assertThat("search bar should be blank on refresh of a page that isn't the search page", newSearchText, is(searchText)); } @Test public void testRelatedConceptsLinks() { String queryText = "elephant"; search(queryText); assertThat(topNavBar.getSearchBarText(), is(queryText)); assertThat(searchPage.youSearchedFor(), hasItem(queryText)); assertThat(searchPage.getHeadingSearchTerm(), containsString(queryText)); for (int i = 0; i < 5; i++) { searchPage.expand(SearchBase.Facet.RELATED_CONCEPTS); searchPage.waitForRelatedConceptsLoadIndicatorToDisappear(); final int conceptsCount = searchPage.countRelatedConcepts(); assertThat(conceptsCount, lessThanOrEqualTo(50)); final int index = new Random().nextInt(conceptsCount); queryText = searchPage.getRelatedConcepts().get(index).getText(); searchPage.relatedConcept(queryText).click(); searchPage.waitForSearchLoadIndicatorToDisappear(); assertThat(topNavBar.getSearchBarText(), is(queryText)); List<String> words = new ArrayList<>(); // HACK: avoid stopwords for (String word : queryText.split("\\s+")) { if (word.length() > 3) { words.add(word); } } assertThat(searchPage.youSearchedFor(), containsItems(words)); assertThat(searchPage.getHeadingSearchTerm(), containsString(queryText)); } } @Test public void testRelatedConceptsDifferentInDifferentLanguages() { assumeThat("Lanugage not implemented in Hosted", getConfig().getType(), Matchers.not(ApplicationType.HOSTED)); search("France"); searchPage.expand(SearchBase.Facet.RELATED_CONCEPTS); searchPage.waitForRelatedConceptsLoadIndicatorToDisappear(); final List<String> englishConcepts = ElementUtil.webElementListToStringList(searchPage.getRelatedConcepts()); searchPage.selectLanguage(Language.FRENCH); searchPage.expand(SearchBase.Facet.RELATED_CONCEPTS); searchPage.waitForRelatedConceptsLoadIndicatorToDisappear(); final List<String> frenchConcepts = ElementUtil.webElementListToStringList(searchPage.getRelatedConcepts()); assertThat("Concepts should be different in different languages", englishConcepts, not(containsInAnyOrder(frenchConcepts.toArray()))); searchPage.selectLanguage(Language.ENGLISH); searchPage.expand(SearchBase.Facet.RELATED_CONCEPTS); searchPage.waitForRelatedConceptsLoadIndicatorToDisappear(); final List<String> secondEnglishConcepts = ElementUtil.webElementListToStringList(searchPage.getRelatedConcepts()); assertThat("Related concepts have changed on second search of same query text", englishConcepts, contains(secondEnglishConcepts.toArray())); } // CSA-1819 @Test public void testNavigateToLastPageOfSearchResultsAndEditUrlToTryAndNavigateFurther() { search("nice"); searchPage.forwardToLastPageButton().click(); searchPage.waitForSearchLoadIndicatorToDisappear(); final int currentPage = searchPage.getCurrentPageNumber(); final String docTitle = searchPage.getSearchResultTitle(1); final String url = getDriver().getCurrentUrl(); assertThat("Url and current page number are out of sync", url, containsString("nice/" + currentPage)); final String illegitimateUrl = url.replace("nice/" + currentPage, "nice/" + (currentPage + 5)); getDriver().navigate().to(illegitimateUrl); searchPage = getElementFactory().getSearchPage(); searchPage.waitForSearchLoadIndicatorToDisappear(); assertThat("Page should still have results", searchPage, not(containsText(Errors.Search.NO_RESULTS))); assertThat("Page should not have thrown an error", searchPage, not(containsText(Errors.Search.HOD))); assertThat("Page number should not have changed", currentPage, is(searchPage.getCurrentPageNumber())); assertThat("Url should have reverted to original url", url, is(getDriver().getCurrentUrl())); assertThat("Error message should not be showing", searchPage.isErrorMessageShowing(), is(false)); assertThat("Search results have changed on last page", docTitle, is(searchPage.getSearchResultTitle(1))); } @Test public void testNoRelatedConceptsIfNoResultsFound() { final String garbageQueryText = "garbagedjlsfjijlsf"; search(garbageQueryText); String errorMessage = "Garbage text returned results. garbageQueryText string needs changed to be more garbage like"; assertThat(errorMessage, searchPage.getText(), containsString("No results found")); assertThat(errorMessage, searchPage.getHeadingResultsCount(), is(0)); searchPage.expand(SearchBase.Facet.RELATED_CONCEPTS); assertThat("If there are no search results there should be no related concepts", searchPage.getText(), containsString("No related concepts found")); } @Test //TODO parametric values aren't working - file ticket public void testParametricValuesLoads() throws InterruptedException { searchPage.expand(SearchBase.Facet.FILTER_BY); searchPage.expand(SearchBase.Facet.PARAMETRIC_VALUES); Thread.sleep(20000); assertThat("Load indicator still visible after 20 seconds", searchPage.parametricValueLoadIndicator().isDisplayed(), is(false)); } @Test public void testContentType(){ search("Alexis"); searchPage.openParametricValuesList(); Waits.loadOrFadeWait(); searchPage.waitForParametricValuesToLoad(); int results = searchPage.filterByContentType("TEXT/PLAIN"); Waits.loadOrFadeWait(); searchPage.waitForSearchLoadIndicatorToDisappear(); assertThat(searchPage.getHeadingResultsCount(), is(results)); searchPage.forwardToLastPageButton().click(); int resultsTotal = (searchPage.getCurrentPageNumber() - 1) * SearchPage.RESULTS_PER_PAGE; resultsTotal += searchPage.visibleDocumentsCount(); assertThat(resultsTotal, is(results)); } @Test public void testSearchTermHighlightedInResults() { String searchTerm = "Tiger"; search(searchTerm); for(int i = 0; i < 3; i++) { for (WebElement searchElement : getDriver().findElements(By.xpath("//div[contains(@class,'search-results-view')]//p//*[contains(text(),'" + searchTerm + "')]"))) { if (searchElement.isDisplayed()) { //They can become hidden if they're too far in the summary verifyThat(searchElement.getText(), CoreMatchers.containsString(searchTerm)); } verifyThat(searchElement.getTagName(), is("a")); verifyThat(searchElement.getAttribute("class"), is("query-text")); WebElement parent = searchElement.findElement(By.xpath(".//..")); verifyThat(parent.getTagName(), is("span")); verifyThat(parent.getAttribute("class"), CoreMatchers.containsString("label")); } searchPage.forwardPageButton().click(); } } @Test //CSA-1708 public void testParametricLabelsNotUndefined(){ new Search(getApplication(),getElementFactory(),"simpsons").applyFilter(new IndexFilter("default_index")).apply(); searchPage.filterByContentType("TEXT/HTML"); for(WebElement filter : searchPage.findElements(By.cssSelector(".filter-display-view span"))){ assertThat(filter.getText().toLowerCase(),not(containsString("undefined"))); } } @Test //CSA-1629 public void testPinToPositionPagination(){ PromotionService promotionService = getApplication().createPromotionService(getElementFactory()); try { promotionService.setUpPromotion(new PinToPositionPromotion(1, "thiswillhavenoresults"), new Search(getApplication(), getElementFactory(), "*"), SearchPage.RESULTS_PER_PAGE + 2); searchPage.waitForSearchLoadIndicatorToDisappear(); verifyThat(searchPage.forwardPageButton(), not(disabled())); searchPage.forwardPageButton().click(); verifyThat(searchPage.visibleDocumentsCount(), is(2)); } finally { promotionService.deleteAll(); } } @Test public void testDeletingDocument(){ searchService.search("bbc"); //Hopefully less important documents will be on the last page WebElement fwrdBtn = searchPage.forwardToLastPageButton(); ElementUtil.scrollIntoView(fwrdBtn, getDriver()); fwrdBtn.click(); int results = searchPage.getHeadingResultsCount(); String deletedDoc = searchPage.getSearchResultTitle(1); // Might wanna check this doesn't come up --- hp-icon hp-trash hp-lg fa-spin fa-circle-o-notch searchService.deleteDocument(deletedDoc); verifyThat(searchPage.getHeadingResultsCount(), is(--results)); verifyThat(searchPage.getSearchResultTitle(1), not(is(deletedDoc))); } private String getFirstWord(String string) { return string.substring(0, string.indexOf(' ')); } }
integration-tests-common/src/test/java/com/autonomy/abc/search/SearchPageITCase.java
package com.autonomy.abc.search; import com.autonomy.abc.config.ABCTestBase; import com.autonomy.abc.config.TestConfig; import com.autonomy.abc.selenium.config.ApplicationType; import com.autonomy.abc.selenium.element.DatePicker; import com.autonomy.abc.selenium.language.Language; import com.autonomy.abc.selenium.menu.NavBarTabId; import com.autonomy.abc.selenium.menu.TopNavBar; import com.autonomy.abc.selenium.page.promotions.CreateNewPromotionsPage; import com.autonomy.abc.selenium.page.promotions.PromotionsDetailPage; import com.autonomy.abc.selenium.page.promotions.PromotionsPage; import com.autonomy.abc.selenium.page.search.DocumentViewer; import com.autonomy.abc.selenium.page.search.SearchBase; import com.autonomy.abc.selenium.page.search.SearchPage; import com.autonomy.abc.selenium.promotions.PinToPositionPromotion; import com.autonomy.abc.selenium.promotions.Promotion; import com.autonomy.abc.selenium.promotions.PromotionService; import com.autonomy.abc.selenium.promotions.SpotlightPromotion; import com.autonomy.abc.selenium.search.*; import com.autonomy.abc.selenium.util.ElementUtil; import com.autonomy.abc.selenium.util.Errors; import com.autonomy.abc.selenium.util.Waits; import com.hp.autonomy.frontend.selenium.util.AppElement; import org.apache.commons.collections4.ListUtils; import org.apache.commons.lang.time.DateUtils; import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.openqa.selenium.*; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.MalformedURLException; import java.text.ParseException; import java.util.*; import static com.autonomy.abc.framework.ABCAssert.assertThat; import static com.autonomy.abc.framework.ABCAssert.verifyThat; import static com.autonomy.abc.matchers.CommonMatchers.containsItems; import static com.autonomy.abc.matchers.ElementMatchers.*; import static org.hamcrest.Matchers.*; import static org.junit.Assert.fail; import static org.junit.Assume.assumeThat; import static org.openqa.selenium.lift.Matchers.displayed; public class SearchPageITCase extends ABCTestBase { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private SearchPage searchPage; private TopNavBar topNavBar; private CreateNewPromotionsPage createPromotionsPage; private PromotionsPage promotionsPage; private DatePicker datePicker; private SearchService searchService; public SearchPageITCase(final TestConfig config, final String browser, final ApplicationType appType, final Platform platform) { super(config, browser, appType, platform); } @Before public void setUp() throws MalformedURLException { topNavBar = body.getTopNavBar(); topNavBar.search("example"); searchPage = getElementFactory().getSearchPage(); searchPage.waitForSearchLoadIndicatorToDisappear(); searchService = getApplication().createSearchService(getElementFactory()); } private void search(String searchTerm){ logger.info("Searching for: '" + searchTerm + "'"); topNavBar.search(searchTerm); searchPage.waitForSearchLoadIndicatorToDisappear(); } private void applyFilter(SearchFilter filter) { filter.apply(searchPage); searchPage.waitForSearchLoadIndicatorToDisappear(); } @Test public void testUnmodifiedResultsToggleButton(){ new WebDriverWait(getDriver(),30).until(ExpectedConditions.visibilityOf(getElementFactory().getSearchPage())); assertThat("Page should be showing modified results", searchPage.modifiedResultsShown(), is(true)); assertThat("Url incorrect", getDriver().getCurrentUrl(), containsString("/modified")); searchPage.modifiedResultsCheckBox().click(); assertThat("Page should not be showing modified results", searchPage.modifiedResultsShown(), is(false)); assertThat("Url incorrect", getDriver().getCurrentUrl(), containsString("/unmodified")); searchPage.modifiedResultsCheckBox().click(); assertThat("Page should be showing modified results", searchPage.modifiedResultsShown(), is(true)); assertThat("Url incorrect", getDriver().getCurrentUrl(), containsString("/modified")); } @Test public void testSearchBasic(){ search("dog"); assertThat("Search title text is wrong", searchPage.getHeadingSearchTerm(), is("dog")); search("cat"); assertThat("Search title text is wrong", searchPage.getHeadingSearchTerm(), is("cat")); search("ElEPhanT"); assertThat("Search title text is wrong", searchPage.getHeadingSearchTerm(), is("ElEPhanT")); } @Test public void testPromoteButton(){ searchPage.promoteTheseDocumentsButton().click(); Waits.loadOrFadeWait(); assertThat("Promoted items bucket has not appeared", searchPage.promotionsBucket().isDisplayed()); assertThat("Promote these items button should not be enabled", ElementUtil.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled")); assertThat("Promoted items count should equal 0", searchPage.promotedItemsCount(), is(0)); searchPage.searchResultCheckbox(1).click(); assertThat("Promote these items button should be enabled", !ElementUtil.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled")); assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(1)); searchPage.promotionsBucketClose(); assertThat("Promoted items bucket has not appeared", searchPage.getText(), not(containsString("Select Items to Promote"))); searchPage.promoteTheseDocumentsButton().click(); Waits.loadOrFadeWait(); assertThat("Promoted items bucket has not appeared", searchPage.promotionsBucket().isDisplayed()); assertThat("Promote these items button should not be enabled", ElementUtil.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled")); assertThat("Promoted items count should equal 0", searchPage.promotedItemsCount(), is(0)); } @Test public void testAddFilesToPromoteBucket() { searchPage.promoteTheseDocumentsButton().click(); Waits.loadOrFadeWait(); for (int i = 1; i < 7; i++) { ElementUtil.scrollIntoView(searchPage.searchResultCheckbox(i), getDriver()); searchPage.searchResultCheckbox(i).click(); assertThat("Promoted items count not correct", searchPage.promotedItemsCount(),is(i)); } for (int j = 6; j > 0; j--) { ElementUtil.scrollIntoView(searchPage.searchResultCheckbox(j), getDriver()); searchPage.searchResultCheckbox(j).click(); assertThat("Promoted items count not correct", searchPage.promotedItemsCount(), is(j - 1)); } searchPage.promotionsBucketClose(); } //TODO fix this test so it's not being run on something with an obscene amount of pages @Ignore @Test public void testSearchResultsPagination() { search("dog"); Waits.loadOrFadeWait(); assertThat("Back to first page button is not disabled", searchPage.isBackToFirstPageButtonDisabled()); assertThat("Back a page button is not disabled", ElementUtil.getParent(searchPage.backPageButton()).getAttribute("class"),containsString("disabled")); ElementUtil.javascriptClick(searchPage.forwardPageButton(), getDriver()); searchPage.paginateWait(); assertThat("Back to first page button is not enabled", ElementUtil.getParent(searchPage.backToFirstPageButton()).getAttribute("class"),not(containsString("disabled"))); assertThat("Back a page button is not enabled", ElementUtil.getParent(searchPage.backPageButton()).getAttribute("class"),not(containsString("disabled"))); assertThat("Page 2 is not active", searchPage.isPageActive(2)); ElementUtil.javascriptClick(searchPage.forwardPageButton(), getDriver()); searchPage.paginateWait(); ElementUtil.javascriptClick(searchPage.forwardPageButton(), getDriver()); searchPage.paginateWait(); ElementUtil.javascriptClick(searchPage.backPageButton(), getDriver()); searchPage.paginateWait(); assertThat("Page 3 is not active", searchPage.isPageActive(3)); ElementUtil.javascriptClick(searchPage.backToFirstPageButton(), getDriver()); searchPage.paginateWait(); assertThat("Page 1 is not active", searchPage.isPageActive(1)); ElementUtil.javascriptClick(searchPage.forwardToLastPageButton(), getDriver()); searchPage.paginateWait(); assertThat("Forward to last page button is not disabled", ElementUtil.getParent(searchPage.forwardToLastPageButton()).getAttribute("class"),containsString("disabled")); assertThat("Forward a page button is not disabled", ElementUtil.getParent(searchPage.forwardPageButton()).getAttribute("class"),containsString("disabled")); final int numberOfPages = searchPage.getCurrentPageNumber(); for (int i = numberOfPages - 1; i > 0; i--) { ElementUtil.javascriptClick(searchPage.backPageButton(), getDriver()); searchPage.paginateWait(); assertThat("Page " + String.valueOf(i) + " is not active", searchPage.isPageActive(i)); assertThat("Url incorrect", getDriver().getCurrentUrl(),endsWith(String.valueOf(i))); } for (int j = 2; j < numberOfPages + 1; j++) { ElementUtil.javascriptClick(searchPage.forwardPageButton(), getDriver()); searchPage.paginateWait(); assertThat("Page " + String.valueOf(j) + " is not active", searchPage.isPageActive(j)); assertThat("Url incorrect", getDriver().getCurrentUrl(),endsWith(String.valueOf(j))); } } // This used to fail because the predict=false parameter was not added to our query actions @Test public void testPaginationAndBackButton() { search("safe"); searchPage.forwardToLastPageButton().click(); Waits.loadOrFadeWait(); assertThat("Forward to last page button is not disabled", searchPage.forwardToLastPageButton().getAttribute("class"),containsString("disabled")); assertThat("Forward a page button is not disabled", searchPage.forwardPageButton().getAttribute("class"), containsString("disabled")); final int lastPage = searchPage.getCurrentPageNumber(); getDriver().navigate().back(); assertThat("Back button has not brought the user back to the first page", searchPage.getCurrentPageNumber(), is(1)); getDriver().navigate().forward(); assertThat("Forward button has not brought the user back to the last page", searchPage.getCurrentPageNumber(), is(lastPage)); } @Test public void testAddDocumentToPromotionsBucket() { search("horse"); searchPage.promoteTheseDocumentsButton().click(); searchPage.searchResultCheckbox(1).click(); assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(1)); assertThat("File in bucket description does not match file added", searchPage.getSearchResultTitle(1), equalToIgnoringCase(searchPage.bucketDocumentTitle(1))); } @Test public void testPromoteTheseItemsButtonLink() { search("fox"); searchPage.promoteTheseDocumentsButton().click(); searchPage.searchResultCheckbox(1).click(); searchPage.promoteTheseItemsButton().click(); assertThat("Create new promotions page not open", getDriver().getCurrentUrl(), endsWith("promotions/create")); } @Test public void testMultiDocPromotionDrawerExpandAndPagination() { Promotion promotion = new SpotlightPromotion("boat"); Search search = new Search(getApplication(), getElementFactory(), "freeze"); PromotionService promotionService = getApplication().createPromotionService(getElementFactory()); promotionService.setUpPromotion(promotion, search, 18); try { PromotionsDetailPage promotionsDetailPage = promotionService.goToDetails(promotion); promotionsDetailPage.trigger("boat").click(); searchPage = getElementFactory().getSearchPage(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); assertThat("two promotions visible", searchPage.getPromotionSummarySize(), is(2)); assertThat("can show more", searchPage.showMorePromotionsButton(), displayed()); searchPage.showMorePromotions(); assertThat("showing more", searchPage.getPromotionSummarySize(), is(5)); searchPage.showLessPromotions(); assertThat("showing less", searchPage.getPromotionSummarySize(), is(2)); searchPage.showMorePromotions(); assertThat("showing more again", searchPage.getPromotionSummarySize(), is(5)); searchPage.promotionSummaryForwardButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); logger.info("on page 2"); verifyPromotionPagination(true, true); searchPage.promotionSummaryForwardButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); searchPage.promotionSummaryForwardButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); logger.info("on last page"); verifyPromotionPagination(true, false); searchPage.promotionSummaryBackButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); searchPage.promotionSummaryBackButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); searchPage.promotionSummaryBackButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); logger.info("on first page"); verifyPromotionPagination(false, true); searchPage.promotionSummaryForwardToEndButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); logger.info("on last page"); verifyPromotionPagination(true, false); searchPage.promotionSummaryBackToStartButton().click(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); logger.info("on first page"); verifyPromotionPagination(false, true); } finally { promotionService.deleteAll(); } } private void verifyPromotionPagination(boolean previousEnabled, boolean nextEnabled) { verifyButtonEnabled("back to start", searchPage.promotionSummaryBackToStartButton(), previousEnabled); verifyButtonEnabled("back", searchPage.promotionSummaryBackButton(), previousEnabled); verifyButtonEnabled("forward", searchPage.promotionSummaryForwardButton(), nextEnabled); verifyButtonEnabled("forward to end", searchPage.promotionSummaryForwardToEndButton(), nextEnabled); } private void verifyButtonEnabled(String name, WebElement element, boolean enabled) { if (enabled) { verifyThat(name + " button enabled", element, not(hasClass("disabled"))); } else { verifyThat(name + " button disabled", element, hasClass("disabled")); } } @Test public void testDocumentsRemainInBucket() { search("cow"); searchPage.promoteTheseDocumentsButton().click(); searchPage.searchResultCheckbox(1).click(); searchPage.searchResultCheckbox(2).click(); assertThat("Promoted items count should equal 2", searchPage.promotedItemsCount(), is(2)); search("bull"); assertThat("Promoted items count should equal 2", searchPage.promotedItemsCount(), is(2)); searchPage.searchResultCheckbox(1).click(); assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(3)); search("cow"); assertThat("Promoted items count should equal 2", searchPage.promotedItemsCount(), is(3)); search("bull"); assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(3)); searchPage.searchResultCheckbox(1).click(); assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(2)); search("cow"); assertThat("Promoted items count should equal 1", searchPage.promotedItemsCount(), is(2)); } @Test public void testWhitespaceSearch() { search(" "); assertThat("Whitespace search should not return a message as if it is a blacklisted term", searchPage.getText(),not(containsString("All search terms are blacklisted"))); } String searchErrorMessage = "An error occurred executing the search action"; String correctErrorMessageNotShown = "Correct error message not shown"; @Test public void testSearchParentheses() { List<String> testSearchTerms = Arrays.asList("(",")","()",") (",")war"); if(getConfig().getType().equals(ApplicationType.HOSTED)){ for(String searchTerm : testSearchTerms){ search(searchTerm); assertThat(searchPage.getText(),containsString(Errors.Search.HOD)); } } else if (getConfig().getType().equals(ApplicationType.ON_PREM)) { int searchTerm = 0; String bracketMismatch = "Bracket Mismatch in the query"; search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(bracketMismatch)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(bracketMismatch)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("No valid query text supplied")); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("Terminating boolean operator")); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(bracketMismatch)); } else { fail("Config type not recognised"); } } //TODO there are some which contain helpful error messages? @Test public void testSearchQuotationMarks() { List<String> testSearchTerms = Arrays.asList("\"","\"\"","\" \"","\" \"","\"word","\" word","\" wo\"rd\""); if(getConfig().getType().equals(ApplicationType.HOSTED)){ for (String searchTerm : testSearchTerms){ search(searchTerm); assertThat(searchPage.getText(),containsString(Errors.Search.HOD)); } } else if (getConfig().getType().equals(ApplicationType.ON_PREM)) { String noValidQueryText = "No valid query text supplied"; String unclosedPhrase = "Unclosed phrase"; int searchTerm = 0; search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(noValidQueryText)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(noValidQueryText)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(noValidQueryText)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(searchErrorMessage)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("An error occurred executing the search action")); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase)); search(testSearchTerms.get(searchTerm++)); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString("An error occurred executing the search action")); assertThat(correctErrorMessageNotShown, searchPage.getText(), containsString(unclosedPhrase)); } else { fail("Config type not recognised"); } } @Test public void testDeleteDocsFromWithinBucket() { search("sabre"); searchPage.promoteTheseDocumentsButton().click(); searchPage.searchResultCheckbox(1).click(); searchPage.searchResultCheckbox(2).click(); searchPage.searchResultCheckbox(3).click(); searchPage.searchResultCheckbox(4).click(); final List<String> bucketList = searchPage.promotionsBucketList(); final List<WebElement> bucketListElements = searchPage.promotionsBucketWebElements(); assertThat("There should be four documents in the bucket", bucketList.size(),is(4)); assertThat("promote button not displayed when bucket has documents", searchPage.promoteTheseDocumentsButton().isDisplayed()); // for (final String bucketDocTitle : bucketList) { // final int docIndex = bucketList.indexOf(bucketDocTitle); // assertFalse("The document title appears as blank within the bucket for document titled " + searchPage.getSearchResult(bucketList.indexOf(bucketDocTitle) + 1).getText(), bucketDocTitle.equals("")); // searchPage.deleteDocFromWithinBucket(bucketDocTitle); // assertThat("Checkbox still selected when doc deleted from bucket", !searchPage.searchResultCheckbox(docIndex + 1).isSelected()); // assertThat("Document not removed from bucket", searchPage.promotionsBucketList(),not(hasItem(bucketDocTitle))); // assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(),is(3 - docIndex)); // } for (final WebElement bucketDoc : bucketListElements) { bucketDoc.findElement(By.cssSelector("i:nth-child(2)")).click(); } assertThat("promote button should be disabled when bucket has no documents", ElementUtil.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled")); search("tooth"); assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(), is(0)); searchPage.searchResultCheckbox(5).click(); final List<String> docTitles = new ArrayList<>(); docTitles.add(searchPage.getSearchResultTitle(5)); ElementUtil.javascriptClick(searchPage.forwardPageButton(), getDriver()); Waits.loadOrFadeWait(); searchPage.searchResultCheckbox(3).click(); docTitles.add(searchPage.getSearchResultTitle(3)); final List<String> bucketListNew = searchPage.promotionsBucketList(); assertThat("Wrong number of documents in the bucket", bucketListNew.size(),is(2)); // assertThat("", searchPage.promotionsBucketList().containsAll(docTitles)); assertThat(bucketListNew.size(),is(docTitles.size())); for(String docTitle : docTitles){ assertThat(bucketListNew,hasItem(docTitle.toUpperCase())); } searchPage.deleteDocFromWithinBucket(docTitles.get(1)); assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(),is(1)); assertThat("Document should still be in the bucket", searchPage.promotionsBucketList(),hasItem(docTitles.get(0).toUpperCase())); assertThat("Document should no longer be in the bucket", searchPage.promotionsBucketList(),not(hasItem(docTitles.get(1).toUpperCase()))); assertThat("Checkbox still selected when doc deleted from bucket", !searchPage.searchResultCheckbox(3).isSelected()); ElementUtil.javascriptClick(searchPage.backPageButton(), getDriver()); searchPage.deleteDocFromWithinBucket(docTitles.get(0)); assertThat("Wrong number of documents in the bucket", searchPage.promotionsBucketList().size(),is(0)); assertThat("Checkbox still selected when doc deleted from bucket", !searchPage.searchResultCheckbox(5).isSelected()); assertThat("promote button should be disabled when bucket has no documents", ElementUtil.isAttributePresent(searchPage.promoteTheseItemsButton(), "disabled")); } @Test public void testViewFrame() throws InterruptedException { search("army"); searchPage.waitForSearchLoadIndicatorToDisappear(); for (final boolean clickLogo : Arrays.asList(true, false)) { for (int page = 1; page <= 2; page++) { for (int result = 1; result <= 6; result++) { Waits.loadOrFadeWait(); searchPage.viewFrameClick(clickLogo, result); checkViewResult(); } ElementUtil.javascriptClick(searchPage.forwardPageButton(), getDriver()); Waits.loadOrFadeWait(); } } } private void checkViewResult() { final String handle = getDriver().getWindowHandle(); DocumentViewer docViewer = DocumentViewer.make(getDriver()); getDriver().switchTo().frame(docViewer.frame()); verifyThat(getDriver().findElement(By.xpath(".//*")), not(hasTextThat(isEmptyOrNullString()))); getDriver().switchTo().window(handle); docViewer.close(); } @Test public void testViewFromBucketLabel() throws InterruptedException { search("جيمس"); searchPage.selectLanguage(Language.ARABIC); logger.warn("Using Trimmed Titles"); search("Engineer"); //Testing in Arabic because in some instances not latin urls have been encoded incorrectly searchPage.waitForSearchLoadIndicatorToDisappear(); searchPage.promoteTheseDocumentsButton().click(); for (int j = 1; j <=2; j++) { for (int i = 1; i <= 3; i++) { final String handle = getDriver().getWindowHandle(); searchPage.searchResultCheckbox(i).click(); final String docTitle = searchPage.getSearchResultTitle(i); searchPage.getPromotionBucketElementByTitle(docTitle).click(); Thread.sleep(5000); getDriver().switchTo().frame(getDriver().findElement(By.tagName("iframe"))); //Using trimmedtitle is a really hacky way to get around the latin urls not being encoded (possibly, or another problem) correctly assertThat("View frame does not contain document", getDriver().findElement(By.xpath(".//*")).getText(),containsString(docTitle)); getDriver().switchTo().window(handle); getDriver().findElement(By.xpath("//button[contains(@id, 'cboxClose')]")).click(); Waits.loadOrFadeWait(); } ElementUtil.javascriptClick(searchPage.forwardPageButton(), getDriver()); Waits.loadOrFadeWait(); } } @Test public void testChangeLanguage() { assumeThat("Lanugage not implemented in Hosted", getConfig().getType(), Matchers.not(ApplicationType.HOSTED)); String docTitle = searchPage.getSearchResultTitle(1); search("1"); List<Language> languages = Arrays.asList(Language.ENGLISH, Language.AFRIKAANS, Language.FRENCH, Language.ARABIC, Language.URDU, Language.HINDI, Language.CHINESE, Language.SWAHILI); for (final Language language : languages) { searchPage.selectLanguage(language); assertThat(searchPage.getSelectedLanguage(), is(language.toString())); searchPage.waitForSearchLoadIndicatorToDisappear(); assertThat(searchPage.getSearchResultTitle(1), not(docTitle)); docTitle = searchPage.getSearchResultTitle(1); } } @Test public void testBucketEmptiesWhenLanguageChangedInURL() { search("arc"); searchPage.selectLanguage(Language.FRENCH); searchPage.waitForSearchLoadIndicatorToDisappear(); searchPage.promoteTheseDocumentsButton().click(); for (int i = 1; i <=4; i++) { searchPage.searchResultCheckbox(i).click(); } assertThat(searchPage.promotionsBucketWebElements(), hasSize(4)); final String url = getDriver().getCurrentUrl().replace("french", "arabic"); getDriver().get(url); searchPage = getElementFactory().getSearchPage(); Waits.loadOrFadeWait(); assertThat("Have not navigated back to search page with modified url " + url, searchPage.promoteThisQueryButton().isDisplayed()); assertThat(searchPage.promotionsBucketWebElements(), hasSize(0)); } @Test public void testLanguageDisabledWhenBucketOpened() { assumeThat("Lanugage not implemented in Hosted", getConfig().getType(), Matchers.not(ApplicationType.HOSTED)); //This test currently fails because language dropdown is not disabled when the promotions bucket is open searchPage.selectLanguage(Language.ENGLISH); search("al"); Waits.loadOrFadeWait(); assertThat("Languages should be enabled", !ElementUtil.isAttributePresent(searchPage.languageButton(), "disabled")); searchPage.promoteTheseDocumentsButton().click(); searchPage.searchResultCheckbox(1).click(); assertThat("There should be one document in the bucket", searchPage.promotionsBucketList(), hasSize(1)); searchPage.selectLanguage(Language.FRENCH); assertThat("The promotions bucket should close when the language is changed", searchPage.promotionsBucket(), not(displayed())); searchPage.promoteTheseDocumentsButton().click(); assertThat("There should be no documents in the bucket after changing language", searchPage.promotionsBucketList(), hasSize(0)); searchPage.selectLanguage(Language.ENGLISH); assertThat("The promotions bucket should close when the language is changed", searchPage.promotionsBucket(), not(displayed())); } @Test public void testSearchAlternateScriptToSelectedLanguage() { List<Language> languages = Arrays.asList(Language.FRENCH, Language.ENGLISH, Language.ARABIC, Language.URDU, Language.HINDI, Language.CHINESE); for (final Language language : languages) { searchPage.selectLanguage(language); for (final String script : Arrays.asList("निर्वाण", "العربية", "עברית", "сценарий", "latin", "ελληνικά", "ქართული", "བོད་ཡིག")) { search(script); Waits.loadOrFadeWait(); assertThat("Undesired error message for language: " + language + " with script: " + script, searchPage.findElement(By.cssSelector(".search-results-view")).getText(),not(containsString("error"))); } } } @Test public void testFieldTextFilter() { search("text"); if (config.getType().equals(ApplicationType.HOSTED)) { applyFilter(new IndexFilter("sitesearch")); } final String searchResultTitle = searchPage.getSearchResultTitle(1); final String firstWord = getFirstWord(searchResultTitle); final int comparisonResult = searchResultNotStarting(firstWord); final String comparisonString = searchPage.getSearchResultTitle(comparisonResult); searchPage.expand(SearchBase.Facet.FIELD_TEXT); searchPage.fieldTextAddButton().click(); Waits.loadOrFadeWait(); assertThat("input visible", searchPage.fieldTextInput(), displayed()); assertThat("confirm button visible", searchPage.fieldTextTickConfirm(), displayed()); searchPage.setFieldText("WILD{" + firstWord + "*}:DRETITLE"); assertThat(searchPage, not(containsText(Errors.Search.HOD))); assertThat("edit button visible", searchPage.fieldTextEditButton(), displayed()); assertThat("remove button visible", searchPage.fieldTextRemoveButton(), displayed()); assertThat(searchPage.getSearchResultTitle(1), is(searchResultTitle)); try { assertThat(searchPage.getSearchResultTitle(comparisonResult), not(comparisonString)); } catch (final NoSuchElementException e) { // The comparison document is not present } searchPage.fieldTextRemoveButton().click(); Waits.loadOrFadeWait(); assertThat(searchPage.getSearchResultTitle(comparisonResult), is(comparisonString)); assertThat("Field text add button not visible", searchPage.fieldTextAddButton().isDisplayed()); assertThat(searchPage.getSearchResultTitle(1), is(searchResultTitle)); } private int searchResultNotStarting(String prefix) { for (int result = 1; result <= SearchPage.RESULTS_PER_PAGE; result++) { String comparisonString = searchPage.getSearchResultTitle(result); if (!comparisonString.startsWith(prefix)) { return result; } } throw new IllegalStateException("Cannot test field text filter with this search"); } @Test public void testEditFieldText() { if (getConfig().getType().equals(ApplicationType.ON_PREM)) { searchPage.selectAllIndexesOrDatabases(getConfig().getType().getName()); search("boer"); } else { new Search(getApplication(), getElementFactory(), "*").applyFilter(new IndexFilter("sitesearch")).apply(); } searchPage.selectLanguage(Language.AFRIKAANS); searchPage.clearFieldText(); final String firstSearchResult = searchPage.getSearchResultTitle(1); final String secondSearchResult = searchPage.getSearchResultTitle(2); searchPage.fieldTextAddButton().click(); Waits.loadOrFadeWait(); searchPage.fieldTextInput().clear(); searchPage.fieldTextInput().sendKeys("MATCH{" + firstSearchResult + "}:DRETITLE"); searchPage.fieldTextTickConfirm().click(); Waits.loadOrFadeWait(); searchPage.waitForSearchLoadIndicatorToDisappear(); assertThat("Field Text should not have caused an error", searchPage.getText(), not(containsString(Errors.Search.HOD))); assertThat(searchPage.getText(), not(containsString("No results found"))); assertThat(searchPage.getSearchResultTitle(1), is(firstSearchResult)); searchPage.fieldTextEditButton().click(); searchPage.fieldTextInput().clear(); searchPage.fieldTextInput().sendKeys("MATCH{" + secondSearchResult + "}:DRETITLE"); searchPage.fieldTextTickConfirm().click(); Waits.loadOrFadeWait(); searchPage.waitForSearchLoadIndicatorToDisappear(); assertThat("Field Text should not have caused an error", searchPage.getText(), not(containsString(Errors.Search.HOD))); assertThat(searchPage.getSearchResultTitle(1), is(secondSearchResult)); } @Test public void testFieldTextInputDisappearsOnOutsideClick() { searchPage.expand(SearchBase.Facet.FIELD_TEXT); assertThat("Field text add button not visible", searchPage.fieldTextAddButton().isDisplayed()); searchPage.fieldTextAddButton().click(); assertThat("Field text add button visible", !searchPage.fieldTextAddButton().isDisplayed()); assertThat("Field text input not visible", searchPage.fieldTextInput().isDisplayed()); searchPage.fieldTextInput().click(); assertThat("Field text add button visible", !searchPage.fieldTextAddButton().isDisplayed()); assertThat("Field text input not visible", searchPage.fieldTextInput().isDisplayed()); searchPage.expand(SearchBase.Facet.RELATED_CONCEPTS); assertThat("Field text add button not visible", searchPage.fieldTextAddButton().isDisplayed()); assertThat("Field text input visible", !searchPage.fieldTextInput().isDisplayed()); } @Test public void testIdolSearchTypes() { final int redCount = getResultCount("red"); final int starCount = getResultCount("star"); final int unquotedCount = getResultCount("red star"); final int quotedCount = getResultCount("\"red star\""); final int orCount = getResultCount("red OR star"); final int andCount = getResultCount("red AND star"); final int redNotStarCount = getResultCount("red NOT star"); final int starNotRedCount = getResultCount("star NOT red"); verifyThat(redCount, lessThanOrEqualTo(unquotedCount)); verifyThat(quotedCount, lessThanOrEqualTo(unquotedCount)); verifyThat(redNotStarCount, lessThanOrEqualTo(redCount)); verifyThat(starNotRedCount, lessThanOrEqualTo(starCount)); verifyThat(quotedCount, lessThanOrEqualTo(andCount)); verifyThat(andCount, lessThanOrEqualTo(unquotedCount)); verifyThat(orCount, lessThanOrEqualTo(redCount + starCount)); verifyThat(andCount + redNotStarCount + starNotRedCount, is(orCount)); verifyThat(orCount, is(unquotedCount)); } private int getResultCount(String searchTerm) { search(searchTerm); return searchPage.getHeadingResultsCount(); } //TODO @Test public void testFieldTextRestrictionOnPromotions(){ PromotionService promotionService = getApplication().createPromotionService(getElementFactory()); promotionService.deleteAll(); promotionService.setUpPromotion(new SpotlightPromotion(Promotion.SpotlightType.SPONSORED, "boat"), "darth", 2); searchPage = getElementFactory().getSearchPage(); searchPage.waitForPromotionsLoadIndicatorToDisappear(); Waits.loadOrFadeWait(); assertThat(searchPage.getPromotionSummarySize(), is(2)); assertThat(searchPage.getPromotionSummaryLabels(), hasSize(2)); final List<String> initialPromotionsSummary = searchPage.promotionsSummaryList(false); searchPage.setFieldText("MATCH{" + initialPromotionsSummary.get(0) + "}:DRETITLE"); assertThat(searchPage.getPromotionSummarySize(), is(1)); assertThat(searchPage.getPromotionSummaryLabels(), hasSize(1)); assertThat(searchPage.promotionsSummaryList(false).get(0), is(initialPromotionsSummary.get(0))); searchPage.fieldTextEditButton().click(); searchPage.fieldTextInput().clear(); searchPage.fieldTextInput().sendKeys("MATCH{" + initialPromotionsSummary.get(1) + "}:DRETITLE"); searchPage.fieldTextTickConfirm().click(); Waits.loadOrFadeWait(); assertThat(searchPage.getPromotionSummarySize(), is(1)); assertThat(searchPage.getPromotionSummaryLabels(), hasSize(1)); assertThat(searchPage.promotionsSummaryList(false).get(0), is(initialPromotionsSummary.get(1))); } @Test public void testFieldTextRestrictionOnPinToPositionPromotions(){ body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS); promotionsPage = getElementFactory().getPromotionsPage(); promotionsPage.deleteAllPromotions(); search("horse"); searchPage.selectLanguage(Language.ENGLISH); final List<String> promotedDocs = searchPage.createAMultiDocumentPromotion(2); createPromotionsPage = getElementFactory().getCreateNewPromotionsPage(); createPromotionsPage.navigateToTriggers(); createPromotionsPage.addSearchTrigger("duck"); createPromotionsPage.finishButton().click(); new WebDriverWait(getDriver(),10).until(ExpectedConditions.visibilityOf(searchPage.promoteTheseDocumentsButton())); searchPage.waitForSearchLoadIndicatorToDisappear(); assertThat(promotedDocs.get(0) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(0))); assertThat(promotedDocs.get(1) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(1))); searchPage.setFieldText("WILD{*horse*}:DRETITLE"); searchPage.waitForSearchLoadIndicatorToDisappear(); Waits.loadOrFadeWait(); assertThat(promotedDocs.get(0) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(0))); assertThat(promotedDocs.get(1) + " should be visible", searchPage.getText(), containsString(promotedDocs.get(1))); //TODO Seems like this shouldn't be visible assertThat("Wrong number of results displayed", searchPage.getHeadingResultsCount(), is(2)); assertThat("Wrong number of pin to position labels displayed", searchPage.countPinToPositionLabels(), is(2)); searchPage.fieldTextEditButton().click(); searchPage.fieldTextInput().clear(); searchPage.fieldTextInput().sendKeys("MATCH{" + promotedDocs.get(0) + "}:DRETITLE"); searchPage.fieldTextTickConfirm().click(); Waits.loadOrFadeWait(); assertThat(searchPage.getSearchResultTitle(1), is(promotedDocs.get(0))); assertThat(searchPage.getHeadingResultsCount(), is(1)); assertThat(searchPage.countPinToPositionLabels(), is(1)); searchPage.fieldTextEditButton().click(); searchPage.fieldTextInput().clear(); searchPage.fieldTextInput().sendKeys("MATCH{" + promotedDocs.get(1) + "}:DRETITLE"); searchPage.fieldTextTickConfirm().click(); Waits.loadOrFadeWait(); assertThat(promotedDocs.get(1) + " not visible in the search title", searchPage.getSearchResultTitle(1), is(promotedDocs.get(1))); assertThat("Wrong number of search results", searchPage.getHeadingResultsCount(), is(1)); assertThat("Wrong number of pin to position labels", searchPage.countPinToPositionLabels(), is(1)); } // CSA-1818 @Test public void testSearchResultsCount() { searchPage.selectLanguage(Language.ENGLISH); for (final String query : Arrays.asList("dog", "chips", "dinosaur", "melon", "art")) { search(query); final int firstPageResultsCount = searchPage.getHeadingResultsCount(); searchPage.forwardToLastPageButton().click(); searchPage.waitForSearchLoadIndicatorToDisappear(); verifyThat("number of results in title is consistent", searchPage.getHeadingResultsCount(), is(firstPageResultsCount)); final int completePages = searchPage.getCurrentPageNumber() - 1; final int lastPageDocumentsCount = searchPage.visibleDocumentsCount(); final int expectedCount = completePages * SearchPage.RESULTS_PER_PAGE + lastPageDocumentsCount; verifyThat("number of results is as expected", searchPage.getHeadingResultsCount(), is(expectedCount)); } } @Test public void testInvalidQueryTextNoKeywordsLinksDisplayed() { //TODO: map error messages to application type List<String> boolOperators = Arrays.asList("OR", "WHEN", "SENTENCE", "DNEAR"); List<String> stopWords = Arrays.asList("a", "the", "of", "SOUNDEX"); //According to IDOL team SOUNDEX isn't considered a boolean operator without brackets searchPage.selectLanguage(Language.ENGLISH); if(getConfig().getType().equals(ApplicationType.HOSTED)) { List<String> allTerms = ListUtils.union(boolOperators, stopWords); for (final String searchTerm : allTerms) { search(searchTerm); assertThat("Correct error message not present for searchterm: " + searchTerm, searchPage.getText(), containsString(Errors.Search.HOD)); } } else if (getConfig().getType().equals(ApplicationType.ON_PREM)) { for (final String searchTerm : boolOperators) { search(searchTerm); assertThat("Correct error message not present for searchterm: " + searchTerm + searchPage.getText(), searchPage.getText(), containsString("An error occurred executing the search action")); assertThat("Correct error message not present for searchterm: " + searchTerm, searchPage.getText(), containsString("An error occurred fetching the query analysis.")); assertThat("Correct error message not present for searchterm: " + searchTerm, searchPage.getText(), containsString("Opening boolean operator")); } for (final String searchTerm : stopWords) { search(searchTerm); assertThat("Correct error message not present", searchPage.getText(), containsString("An error occurred executing the search action")); assertThat("Correct error message not present", searchPage.getText(), containsString("An error occurred fetching the query analysis.")); assertThat("Correct error message not present", searchPage.getText(), containsString("No valid query text supplied")); } } else { fail("Application Type not recognised"); } } @Test public void testAllowSearchOfStringsThatContainBooleansWithinThem() { final List<String> hiddenBooleansProximities = Arrays.asList("NOTed", "ANDREW", "ORder", "WHENCE", "SENTENCED", "PARAGRAPHING", "NEARLY", "SENTENCE1D", "PARAGRAPHING", "PARAGRAPH2inG", "SOUNDEXCLUSIVE", "XORING", "EORE", "DNEARLY", "WNEARING", "YNEARD", "AFTERWARDS", "BEFOREHAND", "NOTWHENERED"); for (final String hiddenBooleansProximity : hiddenBooleansProximities) { search(hiddenBooleansProximity); Waits.loadOrFadeWait(); assertThat(searchPage.getText(), not(containsString("Terminating boolean operator"))); } } @Test public void testFromDateFilter() throws ParseException { search("Dog"); // some indexes do not have dates new IndexFilter("wiki_eng").apply(searchPage); searchPage.waitForSearchLoadIndicatorToDisappear(); final String firstResult = searchPage.getSearchResultTitle(1); final Date date = searchPage.getDateFromResult(1); if (date == null) { throw new IllegalStateException("testFromDateFilter requires first search result to have a date"); } searchPage.openFromDatePicker(); datePicker = new DatePicker(searchPage.$el(), getDriver()); datePicker.calendarDateSelect(date); searchPage.closeFromDatePicker(); assertThat("displayed with filter = $time", searchPage.getSearchResultTitle(1), is(firstResult)); searchPage.openFromDatePicker(); datePicker = new DatePicker(searchPage.$el(), getDriver()); datePicker.calendarDateSelect(DateUtils.addMinutes(date, 1)); searchPage.closeFromDatePicker(); assertThat("not displayed with filter = $time + 1min", searchPage.getSearchResultTitle(1), not(firstResult)); searchPage.openFromDatePicker(); datePicker = new DatePicker(searchPage.$el(), getDriver()); datePicker.calendarDateSelect(DateUtils.addMinutes(date, -1)); searchPage.closeFromDatePicker(); assertThat("displayed with filter = $time - 1min", searchPage.getSearchResultTitle(1), is(firstResult)); } @Test public void testUntilDateFilter() throws ParseException { search("Dog"); // not all indexes have times configured new IndexFilter("news_eng").apply(searchPage); Waits.loadOrFadeWait(); searchPage.waitForSearchLoadIndicatorToDisappear(); final String firstResult = searchPage.getSearchResultTitle(1); final Date date = searchPage.getDateFromResult(1); // plus 1 minute to be inclusive date.setTime(date.getTime() + 60000); logger.info("First Result: " + firstResult + " " + date); searchPage.openUntilDatePicker(); datePicker = new DatePicker(searchPage.$el(), getDriver()); try { datePicker.calendarDateSelect(date); } catch (final ElementNotVisibleException e) { for (final String label : searchPage.filterLabelList()) { assertThat("A 'From' date filter has been applied while only an 'Until' filter was selected by the user", label,not(containsString("From: "))); } assertThat("A 'From' date filter has been applied while only an 'Until' filter was selected by the user", searchPage.fromDateTextBox().getAttribute("value"), not(isEmptyOrNullString())); throw e; } searchPage.closeUntilDatePicker(); logger.info(searchPage.untilDateTextBox().getAttribute("value")); assertThat("Document should still be displayed", searchPage.getSearchResultTitle(1), is(firstResult)); searchPage.openUntilDatePicker(); datePicker = new DatePicker(searchPage.$el(), getDriver()); datePicker.calendarDateSelect(DateUtils.addMinutes(date, -1)); searchPage.closeUntilDatePicker(); logger.info(searchPage.untilDateTextBox().getAttribute("value")); assertThat("Document should not be visible. Date filter not working", searchPage.getSearchResultTitle(1), not(firstResult)); searchPage.openUntilDatePicker(); datePicker = new DatePicker(searchPage.$el(), getDriver()); datePicker.calendarDateSelect(DateUtils.addMinutes(date, 1)); searchPage.closeUntilDatePicker(); assertThat("Document should be visible. Date filter not working", searchPage.getSearchResultTitle(1), is(firstResult)); } @Test public void testFromDateAlwaysBeforeUntilDate() { search("food"); searchPage.expand(SearchBase.Facet.FILTER_BY); searchPage.expand(SearchBase.Facet.DATES); searchPage.fromDateTextBox().sendKeys("04/05/2000 12:00 PM"); searchPage.untilDateTextBox().sendKeys("04/05/2000 12:00 PM"); searchPage.sortBy(SearchBase.Sort.RELEVANCE); assertThat("Dates should be equal", searchPage.fromDateTextBox().getAttribute("value"), is(searchPage.untilDateTextBox().getAttribute("value"))); Waits.loadOrFadeWait(); searchPage.fromDateTextBox().clear(); searchPage.fromDateTextBox().sendKeys("04/05/2000 12:01 PM"); //clicking sort by relevance because an outside click is needed for the changes to take place searchPage.sortBy(SearchBase.Sort.RELEVANCE); // assertNotEquals("From date cannot be after the until date", searchPage.fromDateTextBox().getAttribute("value"), "04/05/2000 12:01 PM"); assertThat("From date should be blank", searchPage.fromDateTextBox().getAttribute("value"), isEmptyOrNullString()); searchPage.fromDateTextBox().clear(); searchPage.fromDateTextBox().sendKeys("04/05/2000 12:00 PM"); searchPage.untilDateTextBox().clear(); searchPage.untilDateTextBox().sendKeys("04/05/2000 11:59 AM"); searchPage.sortBy(SearchBase.Sort.RELEVANCE); // assertEquals("Until date cannot be before the from date", searchPage.untilDateTextBox().getAttribute("value"),is(not("04/05/2000 11:59 AM"))); assertThat("Until date should be blank", searchPage.untilDateTextBox().getAttribute("value"), isEmptyOrNullString()); } @Test public void testFromDateEqualsUntilDate() throws ParseException { search("Search"); searchPage.expand(SearchBase.Facet.FILTER_BY); searchPage.expand(SearchBase.Facet.DATES); // searchPage.openFromDatePicker(); // searchPage.closeFromDatePicker(); // searchPage.openUntilDatePicker(); // searchPage.closeUntilDatePicker(); searchPage.fromDateTextBox().sendKeys("12/12/2012 12:12"); searchPage.untilDateTextBox().sendKeys("12/12/2012 12:12"); assertThat("Datepicker dates are not equal", searchPage.fromDateTextBox().getAttribute("value"), is(searchPage.untilDateTextBox().getAttribute("value"))); final Date date = searchPage.getDateFromFilter(searchPage.untilDateTextBox()); searchPage.sendDateToFilter(DateUtils.addMinutes(date, 1), searchPage.untilDateTextBox()); searchPage.sortBy(SearchBase.Sort.RELEVANCE); assertThat(searchPage.untilDateTextBox().getAttribute("value"), is("12/12/2012 12:13")); searchPage.sendDateToFilter(DateUtils.addMinutes(date, -1), searchPage.untilDateTextBox()); //clicking sort by relevance because an outside click is needed for the changes to take place searchPage.sortBy(SearchBase.Sort.RELEVANCE); assertThat(searchPage.untilDateTextBox().getAttribute("value"), isEmptyOrNullString()); } @Test public void testSortByRelevance() { search("string"); searchPage.sortBy(SearchBase.Sort.RELEVANCE); List<Float> weights = searchPage.getWeightsOnPage(5); logger.info("Weight of 0: " + weights.get(0)); for (int i = 0; i < weights.size() - 1; i++) { logger.info("Weight of " + (i + 1) + ": " + weights.get(i + 1)); assertThat("Weight of search result " + i + " is not greater that weight of search result " + (i + 1), weights.get(i), greaterThanOrEqualTo(weights.get(i + 1))); } searchPage.sortBy(SearchBase.Sort.DATE); searchPage.sortBy(SearchBase.Sort.RELEVANCE); weights = searchPage.getWeightsOnPage(5); for (int i = 0; i < weights.size() - 1; i++) { assertThat("Weight of search result " + i + " is not greater that weight of search result " + (i + 1), weights.get(i), greaterThanOrEqualTo(weights.get(i + 1))); } searchPage.sortBy(SearchBase.Sort.DATE); search("paper packages"); searchPage.sortBy(SearchBase.Sort.RELEVANCE); weights = searchPage.getWeightsOnPage(5); for (int i = 0; i < weights.size() - 1; i++) { assertThat("Weight of search result " + i + " is not greater that weight of search result " + (i + 1), weights.get(i), greaterThanOrEqualTo(weights.get(i + 1))); } } @Test public void testSearchBarTextPersistsOnRefresh() { final String searchText = "Stay"; search(searchText); // Change to promotions page since the search page will persist the query in the URL body.getSideNavBar().switchPage(NavBarTabId.PROMOTIONS); getDriver().navigate().refresh(); body = getBody(); final String newSearchText = body.getTopNavBar().getSearchBarText(); assertThat("search bar should be blank on refresh of a page that isn't the search page", newSearchText, is(searchText)); } @Test public void testRelatedConceptsLinks() { String queryText = "elephant"; search(queryText); assertThat(topNavBar.getSearchBarText(), is(queryText)); assertThat(searchPage.youSearchedFor(), hasItem(queryText)); assertThat(searchPage.getHeadingSearchTerm(), containsString(queryText)); for (int i = 0; i < 5; i++) { searchPage.expand(SearchBase.Facet.RELATED_CONCEPTS); searchPage.waitForRelatedConceptsLoadIndicatorToDisappear(); final int conceptsCount = searchPage.countRelatedConcepts(); assertThat(conceptsCount, lessThanOrEqualTo(50)); final int index = new Random().nextInt(conceptsCount); queryText = searchPage.getRelatedConcepts().get(index).getText(); searchPage.relatedConcept(queryText).click(); searchPage.waitForSearchLoadIndicatorToDisappear(); assertThat(topNavBar.getSearchBarText(), is(queryText)); List<String> words = new ArrayList<>(); // HACK: avoid stopwords for (String word : queryText.split("\\s+")) { if (word.length() > 3) { words.add(word); } } assertThat(searchPage.youSearchedFor(), containsItems(words)); assertThat(searchPage.getHeadingSearchTerm(), containsString(queryText)); } } @Test public void testRelatedConceptsDifferentInDifferentLanguages() { assumeThat("Lanugage not implemented in Hosted", getConfig().getType(), Matchers.not(ApplicationType.HOSTED)); search("France"); searchPage.expand(SearchBase.Facet.RELATED_CONCEPTS); searchPage.waitForRelatedConceptsLoadIndicatorToDisappear(); final List<String> englishConcepts = ElementUtil.webElementListToStringList(searchPage.getRelatedConcepts()); searchPage.selectLanguage(Language.FRENCH); searchPage.expand(SearchBase.Facet.RELATED_CONCEPTS); searchPage.waitForRelatedConceptsLoadIndicatorToDisappear(); final List<String> frenchConcepts = ElementUtil.webElementListToStringList(searchPage.getRelatedConcepts()); assertThat("Concepts should be different in different languages", englishConcepts, not(containsInAnyOrder(frenchConcepts.toArray()))); searchPage.selectLanguage(Language.ENGLISH); searchPage.expand(SearchBase.Facet.RELATED_CONCEPTS); searchPage.waitForRelatedConceptsLoadIndicatorToDisappear(); final List<String> secondEnglishConcepts = ElementUtil.webElementListToStringList(searchPage.getRelatedConcepts()); assertThat("Related concepts have changed on second search of same query text", englishConcepts, contains(secondEnglishConcepts.toArray())); } // CSA-1819 @Test public void testNavigateToLastPageOfSearchResultsAndEditUrlToTryAndNavigateFurther() { search("nice"); searchPage.forwardToLastPageButton().click(); searchPage.waitForSearchLoadIndicatorToDisappear(); final int currentPage = searchPage.getCurrentPageNumber(); final String docTitle = searchPage.getSearchResultTitle(1); final String url = getDriver().getCurrentUrl(); assertThat("Url and current page number are out of sync", url, containsString("nice/" + currentPage)); final String illegitimateUrl = url.replace("nice/" + currentPage, "nice/" + (currentPage + 5)); getDriver().navigate().to(illegitimateUrl); searchPage = getElementFactory().getSearchPage(); searchPage.waitForSearchLoadIndicatorToDisappear(); assertThat("Page should still have results", searchPage, not(containsText(Errors.Search.NO_RESULTS))); assertThat("Page should not have thrown an error", searchPage, not(containsText(Errors.Search.HOD))); assertThat("Page number should not have changed", currentPage, is(searchPage.getCurrentPageNumber())); assertThat("Url should have reverted to original url", url, is(getDriver().getCurrentUrl())); assertThat("Error message should not be showing", searchPage.isErrorMessageShowing(), is(false)); assertThat("Search results have changed on last page", docTitle, is(searchPage.getSearchResultTitle(1))); } @Test public void testNoRelatedConceptsIfNoResultsFound() { final String garbageQueryText = "garbagedjlsfjijlsf"; search(garbageQueryText); String errorMessage = "Garbage text returned results. garbageQueryText string needs changed to be more garbage like"; assertThat(errorMessage, searchPage.getText(), containsString("No results found")); assertThat(errorMessage, searchPage.getHeadingResultsCount(), is(0)); searchPage.expand(SearchBase.Facet.RELATED_CONCEPTS); assertThat("If there are no search results there should be no related concepts", searchPage.getText(), containsString("No related concepts found")); } @Test //TODO parametric values aren't working - file ticket public void testParametricValuesLoads() throws InterruptedException { searchPage.expand(SearchBase.Facet.FILTER_BY); searchPage.expand(SearchBase.Facet.PARAMETRIC_VALUES); Thread.sleep(20000); assertThat("Load indicator still visible after 20 seconds", searchPage.parametricValueLoadIndicator().isDisplayed(), is(false)); } @Test public void testContentType(){ search("Alexis"); searchPage.openParametricValuesList(); Waits.loadOrFadeWait(); searchPage.waitForParametricValuesToLoad(); int results = searchPage.filterByContentType("TEXT/PLAIN"); Waits.loadOrFadeWait(); searchPage.waitForSearchLoadIndicatorToDisappear(); assertThat(searchPage.getHeadingResultsCount(), is(results)); searchPage.forwardToLastPageButton().click(); int resultsTotal = (searchPage.getCurrentPageNumber() - 1) * SearchPage.RESULTS_PER_PAGE; resultsTotal += searchPage.visibleDocumentsCount(); assertThat(resultsTotal, is(results)); } @Test public void testSearchTermHighlightedInResults() { String searchTerm = "Tiger"; search(searchTerm); for(int i = 0; i < 3; i++) { for (WebElement searchElement : getDriver().findElements(By.xpath("//div[contains(@class,'search-results-view')]//p//*[contains(text(),'" + searchTerm + "')]"))) { if (searchElement.isDisplayed()) { //They can become hidden if they're too far in the summary verifyThat(searchElement.getText(), CoreMatchers.containsString(searchTerm)); } verifyThat(searchElement.getTagName(), is("a")); verifyThat(searchElement.getAttribute("class"), is("query-text")); WebElement parent = searchElement.findElement(By.xpath(".//..")); verifyThat(parent.getTagName(), is("span")); verifyThat(parent.getAttribute("class"), CoreMatchers.containsString("label")); } searchPage.forwardPageButton().click(); } } @Test //CSA-1708 public void testParametricLabelsNotUndefined(){ new Search(getApplication(),getElementFactory(),"simpsons").applyFilter(new IndexFilter("default_index")).apply(); searchPage.filterByContentType("TEXT/HTML"); for(WebElement filter : searchPage.findElements(By.cssSelector(".filter-display-view span"))){ assertThat(filter.getText().toLowerCase(),not(containsString("undefined"))); } } @Test //CSA-1629 public void testPinToPositionPagination(){ PromotionService promotionService = getApplication().createPromotionService(getElementFactory()); try { promotionService.setUpPromotion(new PinToPositionPromotion(1, "thiswillhavenoresults"), new Search(getApplication(), getElementFactory(), "*"), SearchPage.RESULTS_PER_PAGE + 2); searchPage.waitForSearchLoadIndicatorToDisappear(); verifyThat(searchPage.forwardPageButton(), not(disabled())); searchPage.forwardPageButton().click(); verifyThat(searchPage.visibleDocumentsCount(), is(2)); } finally { promotionService.deleteAll(); } } @Test public void testDeletingDocument(){ searchService.search("bbc"); //Hopefully less important documents will be on the last page WebElement fwrdBtn = searchPage.forwardToLastPageButton(); ElementUtil.scrollIntoView(fwrdBtn, getDriver()); fwrdBtn.click(); int results = searchPage.getHeadingResultsCount(); String deletedDoc = searchPage.getSearchResultTitle(1); // Might wanna check this doesn't come up --- hp-icon hp-trash hp-lg fa-spin fa-circle-o-notch searchService.deleteDocument(deletedDoc); verifyThat(searchPage.getHeadingResultsCount(), is(--results)); verifyThat(searchPage.getSearchResultTitle(1), not(is(deletedDoc))); } private String getFirstWord(String string) { return string.substring(0, string.indexOf(' ')); } }
testUntilDateFilter should use DatePickerFilter
integration-tests-common/src/test/java/com/autonomy/abc/search/SearchPageITCase.java
testUntilDateFilter should use DatePickerFilter
<ide><path>ntegration-tests-common/src/test/java/com/autonomy/abc/search/SearchPageITCase.java <ide> searchPage.waitForSearchLoadIndicatorToDisappear(); <ide> <ide> final String firstResult = searchPage.getSearchResultTitle(1); <del> final Date date = searchPage.getDateFromResult(1); <add> Date date = searchPage.getDateFromResult(1); <add> <add> logger.info("First Result: " + firstResult + " " + date); <ide> // plus 1 minute to be inclusive <del> date.setTime(date.getTime() + 60000); <del> logger.info("First Result: " + firstResult + " " + date); <del> searchPage.openUntilDatePicker(); <del> datePicker = new DatePicker(searchPage.$el(), getDriver()); <del> try { <del> datePicker.calendarDateSelect(date); <del> } catch (final ElementNotVisibleException e) { <del> for (final String label : searchPage.filterLabelList()) { <del> assertThat("A 'From' date filter has been applied while only an 'Until' filter was selected by the user", label,not(containsString("From: "))); <del> } <del> assertThat("A 'From' date filter has been applied while only an 'Until' filter was selected by the user", searchPage.fromDateTextBox().getAttribute("value"), not(isEmptyOrNullString())); <del> throw e; <del> } <del> searchPage.closeUntilDatePicker(); <del> logger.info(searchPage.untilDateTextBox().getAttribute("value")); <add> date = DateUtils.addMinutes(date, 1); <add> <add> searchPage.filterBy(new DatePickerFilter().until(date)); <add> for (final String label : searchPage.filterLabelList()) { <add> assertThat("no 'From' filter applied", label,not(containsString("From: "))); <add> } <add> assertThat("applied 'Until' filter", searchPage.untilDateTextBox().getAttribute("value"), not(isEmptyOrNullString())); <add> logger.info(searchPage.untilDateTextBox().getAttribute("value")); <add> assertThat(searchPage.getHeadingResultsCount(), greaterThan(0)); <ide> assertThat("Document should still be displayed", searchPage.getSearchResultTitle(1), is(firstResult)); <ide> <del> searchPage.openUntilDatePicker(); <del> datePicker = new DatePicker(searchPage.$el(), getDriver()); <del> datePicker.calendarDateSelect(DateUtils.addMinutes(date, -1)); <del> searchPage.closeUntilDatePicker(); <add> searchPage.filterBy(new DatePickerFilter().until(DateUtils.addMinutes(date, -1))); <ide> logger.info(searchPage.untilDateTextBox().getAttribute("value")); <ide> assertThat("Document should not be visible. Date filter not working", searchPage.getSearchResultTitle(1), not(firstResult)); <ide> <del> searchPage.openUntilDatePicker(); <del> datePicker = new DatePicker(searchPage.$el(), getDriver()); <del> datePicker.calendarDateSelect(DateUtils.addMinutes(date, 1)); <del> searchPage.closeUntilDatePicker(); <add> searchPage.filterBy(new DatePickerFilter().until(DateUtils.addMinutes(date, 1))); <add> assertThat(searchPage.getHeadingResultsCount(), greaterThan(0)); <ide> assertThat("Document should be visible. Date filter not working", searchPage.getSearchResultTitle(1), is(firstResult)); <ide> } <ide>
Java
apache-2.0
4b69fad6b7b2bdaef0b4080b62a933e60746f1b3
0
reid-mcpherson/ExoPlayerDebug,Ood-Tsen/ExoPlayer,pittenga/ExoPlayer,Furystorm/ExoPlayer,seventhmoon/ExoPlayer,jcable/ExoPlayer,eriuzo/ExoPlayer,jeoliva/ExoPlayer,aravinds03/ExoPlayer,YouKim/ExoPlayer,YouKim/ExoPlayer,FinalLevel/ExoPlayer,reid-mcpherson/ExoPlayerDebug,tntcrowd/ExoPlayer,ened/ExoPlayer,bongole/ExoPlayer,martinbonnin/ExoPlayer,FinalLevel/ExoPlayer,Dysonics/ExoPlayer,tntcrowd/ExoPlayer,superbderrick/ExoPlayer,zhouweiguo2017/ExoPlayer,pajatopmr/ExoPlayer,kiall/ExoPlayer,mstarvid/ExoPlayer,amzn/exoplayer-amazon-port,androidx/media,saki4510t/ExoPlayer,castlabs/ExoPlayer,tntcrowd/ExoPlayer,kiall/ExoPlayer,algrid/ExoPlayer,ppamorim/ExoPlayer,fanhattan/ExoPlayer,MaTriXy/ExoPlayer,zhouweiguo2017/ExoPlayer,martinbonnin/ExoPlayer,jeoliva/ExoPlayer,saki4510t/ExoPlayer,YouKim/ExoPlayer,barbarian/ExoPlayer,bongole/ExoPlayer,martinbonnin/ExoPlayer,ferrytanu/ExoPlayer,Ood-Tsen/ExoPlayer,androidx/media,natez0r/ExoPlayer,androidx/media,ferrytanu/ExoPlayer,google/ExoPlayer,amzn/exoplayer-amazon-port,pajatopmr/ExoPlayer,amzn/exoplayer-amazon-port,jcable/ExoPlayer,algrid/ExoPlayer,google/ExoPlayer,ClubCom/AndroidExoPlayer,rubensousa/exoplayer-amazon-port,zhouweiguo2017/ExoPlayer,seventhmoon/ExoPlayer,michalliu/ExoPlayer,ened/ExoPlayer,Furystorm/ExoPlayer,FinalLevel/ExoPlayer,fanhattan/ExoPlayer,castlabs/ExoPlayer,seventhmoon/ExoPlayer,ClubCom/AndroidExoPlayer,TheWeatherCompany/ExoPlayer,barbarian/ExoPlayer,WeiChungChang/ExoPlayer,PavelSynek/ExoPlayer,michalliu/ExoPlayer,luckcoolla/ExoPlayer,mstarvid/ExoPlayer,barbarian/ExoPlayer,YouKim/ExoPlayer,ebr11/ExoPlayer,pittenga/ExoPlayer,yangwuan55/ExoPlayer,WeiChungChang/ExoPlayer,ened/ExoPlayer,danikula/ExoPlayer,reid-mcpherson/ExoPlayerDebug,rodrigodzf/ExoPlayer,aravinds03/ExoPlayer,PavelSynek/ExoPlayer,ebr11/ExoPlayer,danikula/ExoPlayer,superbderrick/ExoPlayer,danikula/ExoPlayer,ebr11/ExoPlayer,jeoliva/ExoPlayer,MaTriXy/ExoPlayer,kiall/ExoPlayer,bongole/ExoPlayer,Furystorm/ExoPlayer,algrid/ExoPlayer,aravinds03/ExoPlayer,saki4510t/ExoPlayer,stari4ek/ExoPlayer,Dysonics/ExoPlayer,stari4ek/ExoPlayer,fanhattan/ExoPlayer,TheWeatherCompany/ExoPlayer,pittenga/ExoPlayer,yangwuan55/ExoPlayer,pajatopmr/ExoPlayer,ppamorim/ExoPlayer,natez0r/ExoPlayer,rodrigodzf/ExoPlayer,mstarvid/ExoPlayer,Ood-Tsen/ExoPlayer,stari4ek/ExoPlayer,eriuzo/ExoPlayer,TheWeatherCompany/ExoPlayer,luckcoolla/ExoPlayer,JasonFengHot/ExoPlayerSource,MaTriXy/ExoPlayer,rodrigodzf/ExoPlayer,michalliu/ExoPlayer,PavelSynek/ExoPlayer,ClubCom/AndroidExoPlayer,rubensousa/exoplayer-amazon-port,ppamorim/ExoPlayer,luckcoolla/ExoPlayer,google/ExoPlayer,Dysonics/ExoPlayer,KiminRyu/ExoPlayer,KiminRyu/ExoPlayer,yangwuan55/ExoPlayer,superbderrick/ExoPlayer,eriuzo/ExoPlayer,rubensousa/exoplayer-amazon-port,ferrytanu/ExoPlayer,WeiChungChang/ExoPlayer,natez0r/ExoPlayer,jcable/ExoPlayer,JasonFengHot/ExoPlayerSource,KiminRyu/ExoPlayer,JasonFengHot/ExoPlayerSource,castlabs/ExoPlayer
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer.text.subrip; import com.google.android.exoplayer.C; import com.google.android.exoplayer.ParserException; import com.google.android.exoplayer.text.Cue; import com.google.android.exoplayer.text.SubtitleParser; import com.google.android.exoplayer.util.LongArray; import com.google.android.exoplayer.util.MimeTypes; import android.text.Html; import android.text.Spanned; import android.text.TextUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A simple SubRip parser. */ public final class SubripParser implements SubtitleParser { private static final Pattern SUBRIP_TIMING_LINE = Pattern.compile("(\\S*)\\s*-->\\s*(\\S*)"); private static final Pattern SUBRIP_TIMESTAMP = Pattern.compile("(?:(\\d+):)?(\\d+):(\\d+),(\\d+)"); private final StringBuilder textBuilder; public SubripParser() { textBuilder = new StringBuilder(); } @Override public SubripSubtitle parse(InputStream inputStream) throws IOException { ArrayList<Cue> cues = new ArrayList<>(); LongArray cueTimesUs = new LongArray(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, C.UTF8_NAME)); boolean haveEndTimecode; String currentLine; while ((currentLine = reader.readLine()) != null) { // Skip blank lines. if (currentLine.length() == 0) continue; // Parse the numeric counter as a sanity check. try { Integer.parseInt(currentLine); } catch (NumberFormatException e) { throw new ParserException("Expected numeric counter: " + currentLine); } // Read and parse the timing line. haveEndTimecode = false; currentLine = reader.readLine(); Matcher matcher = SUBRIP_TIMING_LINE.matcher(currentLine); if (matcher.find()) { cueTimesUs.add(parseTimecode(matcher.group(1))); String endTimecode = matcher.group(2); if (!TextUtils.isEmpty(endTimecode)) { haveEndTimecode = true; cueTimesUs.add(parseTimecode(matcher.group(2))); } } else { throw new ParserException("Expected timing line: " + currentLine); } // Read and parse the text. textBuilder.setLength(0); while (!TextUtils.isEmpty(currentLine = reader.readLine())) { if (textBuilder.length() > 0) { textBuilder.append("<br>"); } textBuilder.append(currentLine.trim()); } Spanned text = Html.fromHtml(textBuilder.toString()); cues.add(new Cue(text)); if (haveEndTimecode) { cues.add(null); } } Cue[] cuesArray = new Cue[cues.size()]; cues.toArray(cuesArray); long[] cueTimesUsArray = cueTimesUs.toArray(); return new SubripSubtitle(cuesArray, cueTimesUsArray); } @Override public boolean canParse(String mimeType) { return MimeTypes.APPLICATION_SUBRIP.equals(mimeType); } private static long parseTimecode(String s) throws NumberFormatException { Matcher matcher = SUBRIP_TIMESTAMP.matcher(s); if (!matcher.matches()) { throw new NumberFormatException("has invalid format"); } long timestampMs = Long.parseLong(matcher.group(1)) * 60 * 60 * 1000; timestampMs += Long.parseLong(matcher.group(2)) * 60 * 1000; timestampMs += Long.parseLong(matcher.group(3)) * 1000; timestampMs += Long.parseLong(matcher.group(4)); return timestampMs * 1000; } }
library/src/main/java/com/google/android/exoplayer/text/subrip/SubripParser.java
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer.text.subrip; import com.google.android.exoplayer.C; import com.google.android.exoplayer.ParserException; import com.google.android.exoplayer.text.Cue; import com.google.android.exoplayer.text.SubtitleParser; import com.google.android.exoplayer.util.LongArray; import com.google.android.exoplayer.util.MimeTypes; import android.text.Html; import android.text.Spanned; import android.text.TextUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A simple SubRip parser. */ public final class SubripParser implements SubtitleParser { private static final Pattern SUBRIP_TIMING_LINE = Pattern.compile("(\\S*)\\s*-->\\s*(\\S*)"); private static final Pattern SUBRIP_TIMESTAMP = Pattern.compile("(?:(\\d+):)?(\\d+):(\\d+),(\\d+)"); private final StringBuilder textBuilder; public SubripParser() { textBuilder = new StringBuilder(); } @Override public SubripSubtitle parse(InputStream inputStream) throws IOException { ArrayList<Cue> cues = new ArrayList<>(); LongArray cueTimesUs = new LongArray(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, C.UTF8_NAME)); boolean haveEndTimecode; String currentLine; while ((currentLine = reader.readLine()) != null) { // Parse the numeric counter as a sanity check. try { Integer.parseInt(currentLine); } catch (NumberFormatException e) { throw new ParserException("Expected numeric counter: " + currentLine); } // Read and parse the timing line. haveEndTimecode = false; currentLine = reader.readLine(); Matcher matcher = SUBRIP_TIMING_LINE.matcher(currentLine); if (matcher.find()) { cueTimesUs.add(parseTimecode(matcher.group(1))); String endTimecode = matcher.group(2); if (!TextUtils.isEmpty(endTimecode)) { haveEndTimecode = true; cueTimesUs.add(parseTimecode(matcher.group(2))); } } else { throw new ParserException("Expected timing line: " + currentLine); } // Read and parse the text. textBuilder.setLength(0); while (!TextUtils.isEmpty(currentLine = reader.readLine())) { if (textBuilder.length() > 0) { textBuilder.append("<br>"); } textBuilder.append(currentLine.trim()); } Spanned text = Html.fromHtml(textBuilder.toString()); cues.add(new Cue(text)); if (haveEndTimecode) { cues.add(null); } } Cue[] cuesArray = new Cue[cues.size()]; cues.toArray(cuesArray); long[] cueTimesUsArray = cueTimesUs.toArray(); return new SubripSubtitle(cuesArray, cueTimesUsArray); } @Override public boolean canParse(String mimeType) { return MimeTypes.APPLICATION_SUBRIP.equals(mimeType); } private static long parseTimecode(String s) throws NumberFormatException { Matcher matcher = SUBRIP_TIMESTAMP.matcher(s); if (!matcher.matches()) { throw new NumberFormatException("has invalid format"); } long timestampMs = Long.parseLong(matcher.group(1)) * 60 * 60 * 1000; timestampMs += Long.parseLong(matcher.group(2)) * 60 * 1000; timestampMs += Long.parseLong(matcher.group(3)) * 1000; timestampMs += Long.parseLong(matcher.group(4)); return timestampMs * 1000; } }
Ignore extra returns in Subrip parsing
library/src/main/java/com/google/android/exoplayer/text/subrip/SubripParser.java
Ignore extra returns in Subrip parsing
<ide><path>ibrary/src/main/java/com/google/android/exoplayer/text/subrip/SubripParser.java <ide> String currentLine; <ide> <ide> while ((currentLine = reader.readLine()) != null) { <add> // Skip blank lines. <add> if (currentLine.length() == 0) <add> continue; <add> <ide> // Parse the numeric counter as a sanity check. <ide> try { <ide> Integer.parseInt(currentLine);
Java
apache-2.0
38c996f9347f95351d8d96f5d98f8bac5ced8644
0
SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java
/* * Copyright 2017, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.spine3.test; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import org.junit.Assert; import org.junit.Test; import java.lang.reflect.Type; import java.security.acl.AclNotFoundException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EmptyStackException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @SuppressWarnings({"ClassWithTooManyMethods", "OverlyComplexClass"}) public class VerifyShould { private static final String EMPTY_STRING = ""; private static final String NON_EMPTY_STRING = "Non-empty string"; private static final String MAP_NAME = "map"; @Test public void extend_Assert_class() { final Type expectedSuperclass = Assert.class; final Type actualSuperclass = Verify.class.getGenericSuperclass(); assertEquals(expectedSuperclass, actualSuperclass); } @Test public void has_private_ctor() { assertTrue(Tests.hasPrivateParameterlessCtor(Verify.class)); } @SuppressWarnings({"ThrowCaughtLocally", "ErrorNotRethrown"}) @Test public void mangle_assertion_error() { final AssertionError sourceError = new AssertionError(); final int framesBefore = sourceError.getStackTrace().length; try { throw Verify.mangledException(sourceError); } catch (AssertionError e) { final int framesAfter = e.getStackTrace().length; assertEquals(framesBefore - 1, framesAfter); } } @SuppressWarnings({"ThrowCaughtLocally", "ErrorNotRethrown"}) @Test public void mangle_assertion_error_for_specified_frame_count() { final AssertionError sourceError = new AssertionError(); final int framesBefore = sourceError.getStackTrace().length; final int framesToPop = 3; try { throw Verify.mangledException(sourceError, framesToPop); } catch (AssertionError e) { final int framesAfter = e.getStackTrace().length; assertEquals(framesBefore - framesToPop + 1, framesAfter); } } @SuppressWarnings("ErrorNotRethrown") @Test public void fail_with_specified_message_and_cause() { final String message = "Test failed"; final Throwable cause = new Error(); try { Verify.fail(message, cause); fail("Error was not thrown"); } catch (AssertionError e) { assertEquals(message, e.getMessage()); assertEquals(cause, e.getCause()); } } @Test(expected = AssertionError.class) public void fail_if_float_values_are_positive_infinity() { final float anyDeltaAcceptable = 0.0f; Verify.assertNotEquals(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, anyDeltaAcceptable); } @Test(expected = AssertionError.class) public void fail_if_float_values_are_negative_infinity() { final float anyDeltaAcceptable = 0.0f; Verify.assertNotEquals(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, anyDeltaAcceptable); } @Test(expected = AssertionError.class) public void fail_if_float_values_are_NaN() { final float anyDeltaAcceptable = 0.0f; Verify.assertNotEquals(Float.NaN, Float.NaN, anyDeltaAcceptable); } @Test(expected = AssertionError.class) public void fail_if_float_values_are_equal() { final float positiveValue = 5.0f; final float negativeValue = -positiveValue; final float equalToValuesDifference = positiveValue - negativeValue; Verify.assertNotEquals(positiveValue, negativeValue, equalToValuesDifference); } @Test public void pass_if_float_values_are_different_types_of_infinity() { final float anyDeltaAcceptable = 0.0f; Verify.assertNotEquals(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, anyDeltaAcceptable); Verify.assertNotEquals(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, anyDeltaAcceptable); } @Test public void pass_if_float_values_are_not_equal() { final float expected = 0.0f; final float actual = 1.0f; final float lessThanValuesDifference = Math.abs(expected - actual) - 0.1f; Verify.assertNotEquals(expected, actual, lessThanValuesDifference); } @Test(expected = AssertionError.class) public void fail_if_bool_values_are_equal() { Verify.assertNotEquals(true, true); } @Test public void pass_if_bool_values_are_not_equal() { Verify.assertNotEquals(true, false); } @Test(expected = AssertionError.class) public void fail_if_byte_values_are_equal() { Verify.assertNotEquals((byte) 0, (byte) 0); } @Test public void pass_if_byte_values_are_not_equal() { Verify.assertNotEquals((byte) 0, (byte) 1); } @Test(expected = AssertionError.class) public void fail_if_char_values_are_equal() { Verify.assertNotEquals('a', 'a'); } @Test public void pass_if_char_values_are_not_equal() { Verify.assertNotEquals('a', 'b'); } @Test(expected = AssertionError.class) public void fail_if_short_values_are_equal() { Verify.assertNotEquals((short) 0, (short) 0); } @Test public void pass_if_short_values_are_not_equal() { Verify.assertNotEquals((short) 0, (short) 1); } @Test(expected = AssertionError.class) public void fail_if_object_is_not_instance_of_specified_type() { Verify.assertInstanceOf(Integer.class, ""); } @Test public void pass_if_object_is_instance_of_specified_type() { final String instance = ""; Verify.assertInstanceOf(instance.getClass(), instance); } @Test(expected = AssertionError.class) public void fail_if_object_is_instance_of_specified_type() { final String instance = ""; Verify.assertNotInstanceOf(instance.getClass(), instance); } @Test public void pass_if_object_is_not_instance_of_specified_type() { Verify.assertNotInstanceOf(Integer.class, ""); } @Test(expected = AssertionError.class) public void fail_if_iterable_is_not_empty() { Verify.assertIterableEmpty(FluentIterable.of(1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_iterable_empty() { Verify.assertIterableEmpty(null); } @Test public void pass_if_iterable_is_empty() { Verify.assertIterableEmpty(FluentIterable.of()); } @Test(expected = AssertionError.class) public void fail_if_map_is_not_empty() { Verify.assertEmpty(Collections.singletonMap(1, 1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_assert_empty() { Verify.assertEmpty((Map) null); } @Test public void pass_if_map_is_empty() { Verify.assertEmpty(Collections.emptyMap()); } @Test(expected = AssertionError.class) public void fail_if_multimap_is_not_empty() { final Multimap<Integer, Integer> multimap = ArrayListMultimap.create(); multimap.put(1, 1); Verify.assertEmpty(multimap); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_multimap_is_null_in_assert_empty() { Verify.assertEmpty((Multimap) null); } @Test public void pass_if_multimap_is_empty() { Verify.assertEmpty(ArrayListMultimap.create()); } @Test(expected = AssertionError.class) public void fail_if_iterable_is_empty() { Verify.assertNotEmpty(FluentIterable.of()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_iterable_not_empty() { Verify.assertIterableNotEmpty(null); } @Test public void pass_if_iterable_is_not_empty() { Verify.assertNotEmpty(FluentIterable.of(1)); } @Test(expected = AssertionError.class) public void fail_if_map_is_empty() { Verify.assertNotEmpty(Collections.emptyMap()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_not_empty() { Verify.assertNotEmpty((Map) null); } @Test public void pass_if_map_is_not_empty() { Verify.assertNotEmpty(Collections.singletonMap(1, 1)); } @Test(expected = AssertionError.class) public void fail_if_multimap_is_empty() { Verify.assertNotEmpty(ArrayListMultimap.create()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_multimap_is_null_in_assert_not_empty() { Verify.assertNotEmpty((Multimap) null); } @Test public void pass_if_multimap_is_not_empty() { final Multimap<Integer, Integer> multimap = ArrayListMultimap.create(); multimap.put(1, 1); Verify.assertNotEmpty(multimap); } @SuppressWarnings("ZeroLengthArrayAllocation") @Test(expected = AssertionError.class) public void fail_if_array_is_empty() { Verify.assertNotEmpty(new Integer[0]); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_assert_not_empty() { Verify.assertNotEmpty((Integer[]) null); } @Test public void pass_if_array_is_not_empty() { final Integer[] array = {1, 2, 3}; Verify.assertNotEmpty(array); } @Test(expected = AssertionError.class) public void fail_if_object_array_size_is_not_equal() { Verify.assertSize(-1, new Object[1]); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_assert_size() { Verify.assertSize(0, (Integer[]) null); } @Test public void pass_if_object_array_size_is_equal() { final int size = 0; Verify.assertSize(size, new Object[size]); } @Test(expected = AssertionError.class) public void fail_if_iterable_size_is_not_equal() { Verify.assertSize(-1, FluentIterable.of(1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_assert_size() { Verify.assertSize(0, (Iterable) null); } @Test public void pass_if_iterable_size_is_equal() { Verify.assertSize(0, FluentIterable.of()); } @Test(expected = AssertionError.class) public void fail_if_map_size_is_not_equal() { Verify.assertSize(-1, Collections.emptyMap()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_assert_size() { Verify.assertSize(0, (Map) null); } @Test public void pass_if_map_size_is_equal() { Verify.assertSize(0, Collections.emptyMap()); } @Test(expected = AssertionError.class) public void fail_if_multimap_size_is_not_equal() { Verify.assertSize(-1, ArrayListMultimap.create()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_multimap_is_null_in_assert_size() { Verify.assertSize(0, (Multimap) null); } @Test public void pass_if_multimap_size_is_equal() { Verify.assertSize(0, ArrayListMultimap.create()); } @Test(expected = AssertionError.class) public void fail_if_collection_size_is_not_equal() { Verify.assertSize(-1, Collections.emptyList()); } @Test public void pass_if_collection_size_is_equal() { Verify.assertSize(0, Collections.emptyList()); } @Test(expected = AssertionError.class) public void fail_if_string_not_contains_char_sequence() { Verify.assertContains(NON_EMPTY_STRING, EMPTY_STRING); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_char_sequence_is_null_in_contains() { Verify.assertContains(null, EMPTY_STRING); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_string_is_null_in_contains() { Verify.assertContains(EMPTY_STRING, (String) null); } @SuppressWarnings({"ConstantConditions", "ErrorNotRethrown"}) @Test(expected = AssertionError.class) public void fail_if_contains_char_sequence_or_string_is_null() { final String nullString = null; try { Verify.assertContains(null, EMPTY_STRING); } catch (AssertionError e) { Verify.assertContains(EMPTY_STRING, nullString); } } @Test public void pass_if_string_contains_char_sequence() { Verify.assertContains(EMPTY_STRING, NON_EMPTY_STRING); } @Test(expected = AssertionError.class) public void fail_is_string_contains_char_sequence() { Verify.assertNotContains(EMPTY_STRING, NON_EMPTY_STRING); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_char_sequence_is_null_in_not_contains() { Verify.assertNotContains(null, EMPTY_STRING); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_string_is_null_in_not_contains() { Verify.assertNotContains(EMPTY_STRING, (String) null); } @Test public void pass_if_string_not_contains_char_sequence() { Verify.assertNotContains(NON_EMPTY_STRING, EMPTY_STRING); } @Test(expected = AssertionError.class) public void fail_if_collection_not_contains_item() { Verify.assertContains(1, Collections.emptyList()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_collections_is_null_in_contains() { Verify.assertContains(1, (Collection) null); } @Test public void pass_if_collection_contains_item() { final Integer item = 1; Verify.assertContains(item, Collections.singletonList(item)); } @Test(expected = AssertionError.class) public void fail_if_immutable_collection_not_contains_item() { Verify.assertContains(1, ImmutableList.of()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_immutable_collections_is_null_in_contains() { Verify.assertContains(1, null); } @Test public void pass_if_immutable_collection_contains_item() { final Integer item = 1; Verify.assertContains(item, ImmutableList.of(item)); } @Test(expected = AssertionError.class) public void fail_if_iterable_not_contains_all() { Verify.assertContainsAll(Collections.emptyList(), 1); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_contains_all() { Verify.assertContainsAll(null); } @Test public void pass_if_iterable_contains_all() { final Integer item = 1; Verify.assertContainsAll(Collections.singletonList(item), item); } @Test(expected = AssertionError.class) public void fail_if_map_are_not_equal() { final Map<Integer, Map<Integer, Integer>> firstOne = Collections.singletonMap(1, Collections.singletonMap(1, 1)); final Map<Integer, Map<Integer, Integer>> secondOne = Collections.singletonMap(1, Collections.singletonMap(1, 2)); Verify.assertMapsEqual(firstOne, secondOne, MAP_NAME); } @SuppressWarnings("ConstantConditions") @Test public void pass_if_maps_are_null() { Verify.assertMapsEqual(null, null, MAP_NAME); } @Test public void pass_if_maps_are_equal() { final Map<Integer, Map<Integer, Integer>> firstOne = Collections.singletonMap(1, Collections.singletonMap(1, 1)); final Map<Integer, Map<Integer, Integer>> secondOne = new HashMap<>(firstOne); Verify.assertMapsEqual(firstOne, secondOne, MAP_NAME); } @Test(expected = AssertionError.class) public void fail_if_sets_are_not_equal_by_size() { final Set<Integer> firstOne = Sets.newHashSet(1, 2, 3, 4); final Set<Integer> secondOne = Sets.newHashSet(1, 2, 4); Verify.assertSetsEqual(firstOne, secondOne); } @Test(expected = AssertionError.class) public void fail_if_sets_are_not_equal_by_content() { final Set<Integer> firstOne = Sets.newHashSet(1, 2, 3); final Set<Integer> secondOne = Sets.newHashSet(1, 2, 777); Verify.assertSetsEqual(firstOne, secondOne); } @Test(expected = AssertionError.class) public void fail_if_sets_are_equal_by_size_but_have_over_than_5_differences() { final Set<Integer> firstOne = Sets.newHashSet(1, 2, 3, 4, 5, 6); final Set<Integer> secondOne = Sets.newHashSet(11, 12, 13, 14, 15, 16); Verify.assertSetsEqual(firstOne, secondOne); } @SuppressWarnings("ConstantConditions") @Test public void pass_if_sets_are_null() { Verify.assertSetsEqual(null, null); } @Test public void pass_if_sets_are_equal() { final Set<Integer> firstOne = Sets.newHashSet(1, 2, 3); final Set<Integer> secondOne = Sets.newHashSet(firstOne); Verify.assertSetsEqual(firstOne, secondOne); } @Test(expected = AssertionError.class) public void fail_if_multimap_not_contains_entry() { Verify.assertContainsEntry(1, 1, ArrayListMultimap.<Integer, Integer>create()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_multimap_is_null_in_contains_entry() { Verify.assertContainsEntry(1, 1, null); } @Test public void pass_if_multimap_contains_entry() { final Integer entryKey = 1; final Integer entryValue = 1; final Multimap<Integer, Integer> multimap = ArrayListMultimap.create(); multimap.put(entryKey, entryValue); Verify.assertContainsEntry(entryKey, entryValue, multimap); } @Test(expected = AssertionError.class) public void fail_if_map_not_contains_key() { Verify.assertContainsKey(1, Collections.emptyMap()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_contains_key() { Verify.assertContainsKey(1, null); } @Test public void pass_if_map_contains_key() { final Integer key = 1; Verify.assertContainsKey(key, Collections.singletonMap(key, 1)); } @Test(expected = AssertionError.class) public void fail_if_map_contains_denied_key() { final Integer key = 1; Verify.denyContainsKey(key, Collections.singletonMap(key, 1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_deny_contains_key() { Verify.denyContainsKey(1, null); } @Test public void pass_if_map_not_contains_denied_key() { Verify.denyContainsKey(1, Collections.emptyMap()); } @Test(expected = AssertionError.class) public void fail_if_map_not_contains_entry() { final Integer key = 0; Verify.assertContainsKeyValue(key, 0, Collections.singletonMap(key, 1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_contains_key_value() { Verify.assertContainsKeyValue(1, 1, null); } @Test public void pass_if_map_contains_entry() { final Integer key = 1; final Integer value = 1; Verify.assertContainsKeyValue(key, value, Collections.singletonMap(key, value)); } @Test(expected = AssertionError.class) public void fail_if_collection_contains_item() { final Integer item = 1; Verify.assertNotContains(item, Collections.singletonList(item)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_collection_is_null_in_not_contains() { Verify.assertNotContains(1, null); } @Test public void pass_if_collection_not_contains_item() { Verify.assertNotContains(1, Collections.emptyList()); } @Test(expected = AssertionError.class) public void fail_if_iterable_contains_item() { final Integer item = 1; Verify.assertNotContains(item, FluentIterable.of(item)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_contains_item() { Verify.assertNotContains(1, (Iterable) null); } @Test public void pass_if_iterable_not_contains_item() { Verify.assertNotContains(1, FluentIterable.of()); } @Test(expected = AssertionError.class) public void fail_if_map_contains_key() { final Integer key = 1; Verify.assertNotContainsKey(key, Collections.singletonMap(key, 1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_not_contains_key() { Verify.assertNotContainsKey(1, null); } @Test public void pass_if_map_not_contains_key() { Verify.assertNotContainsKey(1, Collections.emptyMap()); } @Test(expected = AssertionError.class) public void fail_if_former_later_latter() { final Integer firstItem = 1; final Integer secondItem = 2; final List<Integer> list = Arrays.asList(firstItem, secondItem); Verify.assertBefore(secondItem, firstItem, list); } @Test(expected = AssertionError.class) public void fail_if_former_and_latter_are_equal() { final Integer sameItem = 1; Verify.assertBefore(sameItem, sameItem, Collections.singletonList(sameItem)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_list_is_null_in_assert_befor() { Verify.assertBefore(1, 2, null); } @Test public void pass_if_former_before_latter() { final Integer firstItem = 1; final Integer secondItem = 2; final List<Integer> list = Arrays.asList(firstItem, secondItem); Verify.assertBefore(firstItem, secondItem, list); } @Test(expected = AssertionError.class) public void fail_if_list_item_not_at_index() { final Integer firstItem = 1; final Integer secondItem = 2; final List<Integer> list = Arrays.asList(firstItem, secondItem); Verify.assertItemAtIndex(firstItem, list.indexOf(secondItem), list); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_list_is_null_in_assert_item_at_index() { Verify.assertItemAtIndex(1, 1, (List) null); } @Test public void pass_if_list_item_at_index() { final Integer value = 1; final List<Integer> list = Collections.singletonList(value); Verify.assertItemAtIndex(value, list.indexOf(value), list); } @Test(expected = AssertionError.class) public void fail_if_array_item_not_at_index() { final Integer firstItem = 1; final Integer secondItem = 2; final Object[] array = {firstItem, secondItem}; Verify.assertItemAtIndex(firstItem, 1, array); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_assert_item_at_index() { Verify.assertItemAtIndex(1, 1, (Object[]) null); } @Test public void pass_if_array_item_at_index() { final Integer value = 1; final Object[] array = {value}; Verify.assertItemAtIndex(value, 0, array); } @Test(expected = AssertionError.class) public void fail_if_array_not_starts_with_items() { final Integer[] array = {1, 2, 3}; final Integer notStartsWith = 777; Verify.assertStartsWith(array, notStartsWith); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_starts_with() { Verify.assertStartsWith((Integer[]) null, 1, 2, 3); } @Test(expected = AssertionError.class) public void fail_if_items_is_empty_in_array_starts_with() { Verify.assertStartsWith(new Integer[1]); } @Test public void pass_if_array_starts_with_items() { final Integer[] array = {1, 2}; final Integer firstItem = array[0]; Verify.assertStartsWith(array, firstItem); } @Test(expected = AssertionError.class) public void fail_if_list_not_starts_with_items() { final List<Integer> list = Arrays.asList(1, 2, 3); final Integer notStartsWith = 777; Verify.assertStartsWith(list, notStartsWith); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_list_is_null_in_starts_with() { Verify.assertStartsWith((List) null, 1, 2, 3); } @Test(expected = AssertionError.class) public void fail_if_items_is_empty_in_list_starts_with() { Verify.assertStartsWith(Collections.emptyList()); } @Test public void pass_if_list_starts_with_items() { final List<Integer> list = Arrays.asList(1, 2, 3); final Integer firstItem = list.get(0); Verify.assertStartsWith(list, firstItem); } @Test(expected = AssertionError.class) public void fail_if_list_not_ends_with_items() { final List<Integer> list = Arrays.asList(1, 2, 3); final Integer notEndsWith = 777; Verify.assertEndsWith(list, notEndsWith); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_list_is_null_in_ends_with() { Verify.assertEndsWith((List) null, 1, 2, 3); } @Test(expected = AssertionError.class) public void fail_if_items_is_empty_in_list_ends_with() { Verify.assertEndsWith(Collections.emptyList()); } @Test public void pass_if_list_ends_with_items() { final List<Integer> list = Arrays.asList(1, 2, 3); final Integer lastItem = list.get(list.size() - 1); Verify.assertEndsWith(list, lastItem); } @Test(expected = AssertionError.class) public void fail_if_array_not_ends_with_items() { final Integer[] array = {1, 2, 3}; final Integer notEndsWith = 777; Verify.assertEndsWith(array, notEndsWith); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_ends_with() { Verify.assertEndsWith((Integer[]) null, 1, 2, 3); } @Test(expected = AssertionError.class) public void fail_if_items_is_empty_in_array_ends_with() { Verify.assertEndsWith(new Integer[1]); } @Test public void pass_if_array_ends_with() { final Integer[] array = {1, 2, 3}; final Integer lastItem = array[array.length - 1]; Verify.assertEndsWith(array, lastItem); } @Test(expected = AssertionError.class) public void fail_if_objects_are_not_equal() { Verify.assertEqualsAndHashCode(1, 2); } @Test(expected = AssertionError.class) public void fail_if_objects_are_equal_but_hash_codes_are_not_equal() { final ClassThatViolateHashCodeAndCloneableContract objectA = new ClassThatViolateHashCodeAndCloneableContract(1); final ClassThatViolateHashCodeAndCloneableContract objectB = new ClassThatViolateHashCodeAndCloneableContract(1); Verify.assertEqualsAndHashCode(objectA, objectB); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_objects_are_null() { Verify.assertEqualsAndHashCode(null, null); } @Test public void pass_if_objects_and_their_hash_codes_are_equal() { Verify.assertEqualsAndHashCode(1, 1); } @Test(expected = AssertionError.class) public void fail_if_value_is_not_negative() { Verify.assertNegative(1); } @Test(expected = AssertionError.class) public void fail_if_value_is_zero_in_assert_negative() { Verify.assertNegative(0); } @Test public void pass_if_value_is_negative() { Verify.assertNegative(-1); } @Test(expected = AssertionError.class) public void fail_if_value_is_not_positive() { Verify.assertPositive(-1); } @Test(expected = AssertionError.class) public void fail_if_value_is_zero_in_assert_positive() { Verify.assertPositive(0); } @Test public void pass_if_value_is_positive() { Verify.assertPositive(1); } @Test(expected = AssertionError.class) public void fail_if_value_is_positive() { Verify.assertZero(1); } @Test(expected = AssertionError.class) public void fail_if_value_is_negative() { Verify.assertZero(-1); } @Test public void pass_if_value_is_zero() { Verify.assertZero(0); } @Test(expected = AssertionError.class) public void fail_if_clone_returns_same_object() { Verify.assertShallowClone(new ClassThatViolateHashCodeAndCloneableContract(1)); } @Test(expected = AssertionError.class) public void fail_if_clone_does_not_work_correctly() { Verify.assertShallowClone(new ClassThatImplementCloneableIncorrectly(1)); } @Test public void pass_if_cloneable_equals_and_hash_code_overridden_correctly() { Verify.assertShallowClone(new ClassThatImplementCloneableCorrectly(1)); } @Test(expected = AssertionError.class) public void fail_if_class_instantiable() { Verify.assertClassNonInstantiable(Object.class); } @Test(expected = AssertionError.class) public void fail_if_class_instantiable_through_reflection() { Verify.assertClassNonInstantiable(ClassWithPrivateCtor.class); } @Test public void pass_if_new_instance_throw_instantiable_exception() { Verify.assertClassNonInstantiable(void.class); } @Test public void pass_if_class_non_instantiable_through_reflection() { Verify.assertClassNonInstantiable(ClassThatThrowExceptionInConstructor.class); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_error() { final Runnable notThrowsException = new Runnable() { @Override public void run() { } }; Verify.assertError(AssertionError.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_specified_error() { final Runnable throwsAssertionError = new Runnable() { @Override public void run() { throw new AssertionError(); } }; Verify.assertError(Error.class, throwsAssertionError); } @Test public void pass_if_runnable_throws_specified_error() { final Runnable throwsAssertionError = new Runnable() { @Override public void run() { throw new AssertionError(); } }; Verify.assertError(AssertionError.class, throwsAssertionError); } @Test(expected = AssertionError.class) public void fail_if_callable_not_throws_exception() { final Callable notThrowsException = new Callable() { @Override public Object call() throws Exception { return null; } }; Verify.assertThrows(Exception.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_callable_not_throws_specified_exception() { final Callable throwsEmptyStackException = new Callable() { @Override public Object call() throws Exception { throw new EmptyStackException(); } }; Verify.assertThrows(Exception.class, throwsEmptyStackException); } @Test public void pass_if_callable_throws_specified_exception() { final Callable throwsEmptyStackException = new Callable() { @Override public Object call() throws Exception { throw new EmptyStackException(); } }; Verify.assertThrows(EmptyStackException.class, throwsEmptyStackException); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_exception() { final Runnable notThrowsException = new Runnable() { @Override public void run() { } }; Verify.assertThrows(Exception.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_specified_exception() { final Runnable throwsEmptyStackException = new Runnable() { @Override public void run() { throw new EmptyStackException(); } }; Verify.assertThrows(Exception.class, throwsEmptyStackException); } @Test public void pass_if_runnable_throws_specified_exception() { final Runnable throwsEmptyStackException = new Runnable() { @Override public void run() { throw new EmptyStackException(); } }; Verify.assertThrows(EmptyStackException.class, throwsEmptyStackException); } @Test(expected = AssertionError.class) public void fail_if_callable_not_throws_exception_with_cause() { final Callable notThrowsException = new Callable() { @Override public Object call() throws Exception { return null; } }; Verify.assertThrowsWithCause(Exception.class, Exception.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_callable_throws_exception_with_different_causes() { final Throwable expectedCause = new EmptyStackException(); final Throwable actualCause = new AclNotFoundException(); final RuntimeException runtimeException = new RuntimeException(actualCause); final Callable throwsRuntimeException = new Callable() { @Override public Object call() { throw runtimeException; } }; Verify.assertThrowsWithCause(runtimeException.getClass(), expectedCause.getClass(), throwsRuntimeException); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_callable_expected_cause_is_null() { final Callable throwsRuntimeException = new Callable() { @Override public Object call() { throw new RuntimeException(new EmptyStackException()); } }; Verify.assertThrowsWithCause(EmptyStackException.class, null, throwsRuntimeException); } @Test public void pass_if_callable_throws_specified_exception_with_specified_cause() { final Throwable cause = new EmptyStackException(); final RuntimeException runtimeException = new RuntimeException(cause); final Callable throwsRuntimeException = new Callable() { @Override public Object call() { throw runtimeException; } }; Verify.assertThrowsWithCause(runtimeException.getClass(), cause.getClass(), throwsRuntimeException); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_exception_with_cause() { final Runnable notThrowsException = new Runnable() { @Override public void run() { } }; Verify.assertThrowsWithCause(Exception.class, Exception.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_runnable_throws_exception_with_different_causes() { final Throwable expectedCause = new EmptyStackException(); final Throwable actualCause = new AclNotFoundException(); final RuntimeException runtimeException = new RuntimeException(actualCause); final Runnable throwsRuntimeException = new Runnable() { @Override public void run() { throw runtimeException; } }; Verify.assertThrowsWithCause(runtimeException.getClass(), expectedCause.getClass(), throwsRuntimeException); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_runnable_expected_cause_is_null() { final Runnable throwsRuntimeException = new Runnable() { @Override public void run() { throw new RuntimeException(new EmptyStackException()); } }; Verify.assertThrowsWithCause(EmptyStackException.class, null, throwsRuntimeException); } @Test public void pass_if_runnable_throws_specified_exception_with_specified_cause() { final Throwable cause = new EmptyStackException(); final RuntimeException runtimeException = new RuntimeException(cause); final Runnable throwsRuntimeException = new Runnable() { @Override public void run() { throw runtimeException; } }; Verify.assertThrowsWithCause(runtimeException.getClass(), cause.getClass(), throwsRuntimeException); } @SuppressWarnings("EqualsAndHashcode") private static class ClassThatViolateHashCodeAndCloneableContract implements Cloneable { private final int value; private ClassThatViolateHashCodeAndCloneableContract(int value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClassThatViolateHashCodeAndCloneableContract that = (ClassThatViolateHashCodeAndCloneableContract) o; return value == that.value; } @SuppressWarnings("MethodDoesntCallSuperMethod") @Override protected Object clone() throws CloneNotSupportedException { return this; } } private static class ClassThatImplementCloneableCorrectly implements Cloneable { private final int value; private ClassThatImplementCloneableCorrectly(int value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClassThatImplementCloneableCorrectly that = (ClassThatImplementCloneableCorrectly) o; return value == that.value; } @Override public int hashCode() { return value; } } private static final class ClassThatImplementCloneableIncorrectly implements Cloneable { private final int value; private ClassThatImplementCloneableIncorrectly(int value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClassThatImplementCloneableIncorrectly that = (ClassThatImplementCloneableIncorrectly) o; return value == that.value; } @Override public int hashCode() { return value; } @Override protected Object clone() throws CloneNotSupportedException { return new ClassThatImplementCloneableIncorrectly(value + 1); } } private static class ClassWithPrivateCtor { @SuppressWarnings("RedundantNoArgConstructor") private ClassWithPrivateCtor() { } } private static class ClassThatThrowExceptionInConstructor { private ClassThatThrowExceptionInConstructor() { throw new AssertionError("This is non-instantiable class"); } } }
testutil/src/test/java/org/spine3/test/VerifyShould.java
/* * Copyright 2017, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.spine3.test; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import org.junit.Assert; import org.junit.Test; import java.lang.reflect.Type; import java.security.acl.AclNotFoundException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EmptyStackException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @SuppressWarnings({"ClassWithTooManyMethods", "OverlyComplexClass"}) public class VerifyShould { private static final String emptyString = ""; private static final String notEmptyString = "Not empty string"; private static final String mapName = "map"; @Test public void extend_Assert_class() { final Type expectedSuperclass = Assert.class; final Type actualSuperclass = Verify.class.getGenericSuperclass(); assertEquals(expectedSuperclass, actualSuperclass); } @Test public void has_private_ctor() { assertTrue(Tests.hasPrivateParameterlessCtor(Verify.class)); } @SuppressWarnings({"ThrowCaughtLocally", "ErrorNotRethrown"}) @Test public void mangle_assertion_error() { final AssertionError sourceError = new AssertionError(); final int framesBefore = sourceError.getStackTrace().length; try { throw Verify.mangledException(sourceError); } catch (AssertionError e) { final int framesAfter = e.getStackTrace().length; assertEquals(framesBefore - 1, framesAfter); } } @SuppressWarnings({"ThrowCaughtLocally", "ErrorNotRethrown"}) @Test public void mangle_assertion_error_for_specified_frame_count() { final AssertionError sourceError = new AssertionError(); final int framesBefore = sourceError.getStackTrace().length; final int framesToPop = 3; try { throw Verify.mangledException(sourceError, framesToPop); } catch (AssertionError e) { final int framesAfter = e.getStackTrace().length; assertEquals(framesBefore - framesToPop + 1, framesAfter); } } @SuppressWarnings("ErrorNotRethrown") @Test public void fail_with_specified_message_and_cause() { final String message = "Test failed"; final Throwable cause = new Error(); try { Verify.fail(message, cause); fail("Error was not thrown"); } catch (AssertionError e) { assertEquals(message, e.getMessage()); assertEquals(cause, e.getCause()); } } @Test(expected = AssertionError.class) public void fail_if_float_values_are_positive_infinity() { final float anyDeltaAcceptable = 0.0f; Verify.assertNotEquals(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, anyDeltaAcceptable); } @Test(expected = AssertionError.class) public void fail_if_float_values_are_negative_infinity() { final float anyDeltaAcceptable = 0.0f; Verify.assertNotEquals(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, anyDeltaAcceptable); } @Test(expected = AssertionError.class) public void fail_if_float_values_are_NaN() { final float anyDeltaAcceptable = 0.0f; Verify.assertNotEquals(Float.NaN, Float.NaN, anyDeltaAcceptable); } @Test(expected = AssertionError.class) public void fail_if_float_values_are_equal() { final float positiveValue = 5.0f; final float negativeValue = -positiveValue; final float equalToValuesDifference = positiveValue - negativeValue; Verify.assertNotEquals(positiveValue, negativeValue, equalToValuesDifference); } @Test public void pass_if_float_values_are_different_types_of_infinity() { final float anyDeltaAcceptable = 0.0f; Verify.assertNotEquals(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, anyDeltaAcceptable); Verify.assertNotEquals(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, anyDeltaAcceptable); } @Test public void pass_if_float_values_are_not_equal() { final float expected = 0.0f; final float actual = 1.0f; final float lessThanValuesDifference = Math.abs(expected - actual) - 0.1f; Verify.assertNotEquals(expected, actual, lessThanValuesDifference); } @Test(expected = AssertionError.class) public void fail_if_bool_values_are_equal() { Verify.assertNotEquals(true, true); } @Test public void pass_if_bool_values_are_not_equal() { Verify.assertNotEquals(true, false); } @Test(expected = AssertionError.class) public void fail_if_byte_values_are_equal() { Verify.assertNotEquals((byte) 0, (byte) 0); } @Test public void pass_if_byte_values_are_not_equal() { Verify.assertNotEquals((byte) 0, (byte) 1); } @Test(expected = AssertionError.class) public void fail_if_char_values_are_equal() { Verify.assertNotEquals('a', 'a'); } @Test public void pass_if_char_values_are_not_equal() { Verify.assertNotEquals('a', 'b'); } @Test(expected = AssertionError.class) public void fail_if_short_values_are_equal() { Verify.assertNotEquals((short) 0, (short) 0); } @Test public void pass_if_short_values_are_not_equal() { Verify.assertNotEquals((short) 0, (short) 1); } @Test(expected = AssertionError.class) public void fail_if_object_is_not_instance_of_specified_type() { Verify.assertInstanceOf(Integer.class, ""); } @Test public void pass_if_object_is_instance_of_specified_type() { final String instance = ""; Verify.assertInstanceOf(instance.getClass(), instance); } @Test(expected = AssertionError.class) public void fail_if_object_is_instance_of_specified_type() { final String instance = ""; Verify.assertNotInstanceOf(instance.getClass(), instance); } @Test public void pass_if_object_is_not_instance_of_specified_type() { Verify.assertNotInstanceOf(Integer.class, ""); } @Test(expected = AssertionError.class) public void fail_if_iterable_is_not_empty() { Verify.assertIterableEmpty(FluentIterable.of(1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_iterable_empty() { Verify.assertIterableEmpty(null); } @Test public void pass_if_iterable_is_empty() { Verify.assertIterableEmpty(FluentIterable.of()); } @Test(expected = AssertionError.class) public void fail_if_map_is_not_empty() { Verify.assertEmpty(Collections.singletonMap(1, 1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_assert_empty() { Verify.assertEmpty((Map) null); } @Test public void pass_if_map_is_empty() { Verify.assertEmpty(Collections.emptyMap()); } @Test(expected = AssertionError.class) public void fail_if_multimap_is_not_empty() { final Multimap<Integer, Integer> multimap = ArrayListMultimap.create(); multimap.put(1, 1); Verify.assertEmpty(multimap); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_multimap_is_null_in_assert_empty() { Verify.assertEmpty((Multimap) null); } @Test public void pass_if_multimap_is_empty() { Verify.assertEmpty(ArrayListMultimap.create()); } @Test(expected = AssertionError.class) public void fail_if_iterable_is_empty() { Verify.assertNotEmpty(FluentIterable.of()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_iterable_not_empty() { Verify.assertIterableNotEmpty(null); } @Test public void pass_if_iterable_is_not_empty() { Verify.assertNotEmpty(FluentIterable.of(1)); } @Test(expected = AssertionError.class) public void fail_if_map_is_empty() { Verify.assertNotEmpty(Collections.emptyMap()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_not_empty() { Verify.assertNotEmpty((Map) null); } @Test public void pass_if_map_is_not_empty() { Verify.assertNotEmpty(Collections.singletonMap(1, 1)); } @Test(expected = AssertionError.class) public void fail_if_multimap_is_empty() { Verify.assertNotEmpty(ArrayListMultimap.create()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_multimap_is_null_in_assert_not_empty() { Verify.assertNotEmpty((Multimap) null); } @Test public void pass_if_multimap_is_not_empty() { final Multimap<Integer, Integer> multimap = ArrayListMultimap.create(); multimap.put(1, 1); Verify.assertNotEmpty(multimap); } @SuppressWarnings("ZeroLengthArrayAllocation") @Test(expected = AssertionError.class) public void fail_if_array_is_empty() { Verify.assertNotEmpty(new Integer[0]); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_assert_not_empty() { Verify.assertNotEmpty((Integer[]) null); } @Test public void pass_if_array_is_not_empty() { final Integer[] array = {1, 2, 3}; Verify.assertNotEmpty(array); } @Test(expected = AssertionError.class) public void fail_if_object_array_size_is_not_equal() { Verify.assertSize(-1, new Object[1]); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_assert_size() { Verify.assertSize(0, (Integer[]) null); } @Test public void pass_if_object_array_size_is_equal() { final int size = 0; Verify.assertSize(size, new Object[size]); } @Test(expected = AssertionError.class) public void fail_if_iterable_size_is_not_equal() { Verify.assertSize(-1, FluentIterable.of(1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_assert_size() { Verify.assertSize(0, (Iterable) null); } @Test public void pass_if_iterable_size_is_equal() { Verify.assertSize(0, FluentIterable.of()); } @Test(expected = AssertionError.class) public void fail_if_map_size_is_not_equal() { Verify.assertSize(-1, Collections.emptyMap()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_assert_size() { Verify.assertSize(0, (Map) null); } @Test public void pass_if_map_size_is_equal() { Verify.assertSize(0, Collections.emptyMap()); } @Test(expected = AssertionError.class) public void fail_if_multimap_size_is_not_equal() { Verify.assertSize(-1, ArrayListMultimap.create()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_multimap_is_null_in_assert_size() { Verify.assertSize(0, (Multimap) null); } @Test public void pass_if_multimap_size_is_equal() { Verify.assertSize(0, ArrayListMultimap.create()); } @Test(expected = AssertionError.class) public void fail_if_collection_size_is_not_equal() { Verify.assertSize(-1, Collections.emptyList()); } @Test public void pass_if_collection_size_is_equal() { Verify.assertSize(0, Collections.emptyList()); } @Test(expected = AssertionError.class) public void fail_if_string_not_contains_char_sequence() { Verify.assertContains(notEmptyString, emptyString); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_char_sequence_is_null_in_contains() { Verify.assertContains(null, emptyString); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_string_is_null_in_contains() { Verify.assertContains(emptyString, (String) null); } @SuppressWarnings({"ConstantConditions", "ErrorNotRethrown"}) @Test(expected = AssertionError.class) public void fail_if_contains_char_sequence_or_string_is_null() { final String nullString = null; try { Verify.assertContains(null, emptyString); } catch (AssertionError e) { Verify.assertContains(emptyString, nullString); } } @Test public void pass_if_string_contains_char_sequence() { Verify.assertContains(emptyString, notEmptyString); } @Test(expected = AssertionError.class) public void fail_is_string_contains_char_sequence() { Verify.assertNotContains(emptyString, notEmptyString); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_char_sequence_is_null_in_not_contains() { Verify.assertNotContains(null, emptyString); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_string_is_null_in_not_contains() { Verify.assertNotContains(emptyString, (String) null); } @Test public void pass_if_string_not_contains_char_sequence() { Verify.assertNotContains(notEmptyString, emptyString); } @Test(expected = AssertionError.class) public void fail_if_collection_not_contains_item() { Verify.assertContains(1, Collections.emptyList()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_collections_is_null_in_contains() { Verify.assertContains(1, (Collection) null); } @Test public void pass_if_collection_contains_item() { final Integer item = 1; Verify.assertContains(item, Collections.singletonList(item)); } @Test(expected = AssertionError.class) public void fail_if_immutable_collection_not_contains_item() { Verify.assertContains(1, ImmutableList.of()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_immutable_collections_is_null_in_contains() { Verify.assertContains(1, null); } @Test public void pass_if_immutable_collection_contains_item() { final Integer item = 1; Verify.assertContains(item, ImmutableList.of(item)); } @Test(expected = AssertionError.class) public void fail_if_iterable_not_contains_all() { Verify.assertContainsAll(Collections.emptyList(), 1); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_contains_all() { Verify.assertContainsAll(null); } @Test public void pass_if_iterable_contains_all() { final Integer item = 1; Verify.assertContainsAll(Collections.singletonList(item), item); } @Test(expected = AssertionError.class) public void fail_if_map_are_not_equal() { final Map<Integer, Map<Integer, Integer>> firstOne = Collections.singletonMap(1, Collections.singletonMap(1, 1)); final Map<Integer, Map<Integer, Integer>> secondOne = Collections.singletonMap(1, Collections.singletonMap(1, 2)); Verify.assertMapsEqual(firstOne, secondOne, mapName); } @SuppressWarnings("ConstantConditions") @Test public void pass_if_maps_are_null() { Verify.assertMapsEqual(null, null, mapName); } @Test public void pass_if_maps_are_equal() { final Map<Integer, Map<Integer, Integer>> firstOne = Collections.singletonMap(1, Collections.singletonMap(1, 1)); final Map<Integer, Map<Integer, Integer>> secondOne = new HashMap<>(firstOne); Verify.assertMapsEqual(firstOne, secondOne, mapName); } @Test(expected = AssertionError.class) public void fail_if_sets_are_not_equal_by_size() { final Set<Integer> firstOne = Sets.newHashSet(1, 2, 3, 4); final Set<Integer> secondOne = Sets.newHashSet(1, 2, 4); Verify.assertSetsEqual(firstOne, secondOne); } @Test(expected = AssertionError.class) public void fail_if_sets_are_not_equal_by_content() { final Set<Integer> firstOne = Sets.newHashSet(1, 2, 3); final Set<Integer> secondOne = Sets.newHashSet(1, 2, 777); Verify.assertSetsEqual(firstOne, secondOne); } @Test(expected = AssertionError.class) public void fail_if_sets_are_equal_by_size_but_have_over_than_5_differences() { final Set<Integer> firstOne = Sets.newHashSet(1, 2, 3, 4, 5, 6); final Set<Integer> secondOne = Sets.newHashSet(11, 12, 13, 14, 15, 16); Verify.assertSetsEqual(firstOne, secondOne); } @SuppressWarnings("ConstantConditions") @Test public void pass_if_sets_are_null() { Verify.assertSetsEqual(null, null); } @Test public void pass_if_sets_are_equal() { final Set<Integer> firstOne = Sets.newHashSet(1, 2, 3); final Set<Integer> secondOne = Sets.newHashSet(firstOne); Verify.assertSetsEqual(firstOne, secondOne); } @Test(expected = AssertionError.class) public void fail_if_multimap_not_contains_entry() { Verify.assertContainsEntry(1, 1, ArrayListMultimap.<Integer, Integer>create()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_multimap_is_null_in_contains_entry() { Verify.assertContainsEntry(1, 1, null); } @Test public void pass_if_multimap_contains_entry() { final Integer entryKey = 1; final Integer entryValue = 1; final Multimap<Integer, Integer> multimap = ArrayListMultimap.create(); multimap.put(entryKey, entryValue); Verify.assertContainsEntry(entryKey, entryValue, multimap); } @Test(expected = AssertionError.class) public void fail_if_map_not_contains_key() { Verify.assertContainsKey(1, Collections.emptyMap()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_contains_key() { Verify.assertContainsKey(1, null); } @Test public void pass_if_map_contains_key() { final Integer key = 1; Verify.assertContainsKey(key, Collections.singletonMap(key, 1)); } @Test(expected = AssertionError.class) public void fail_if_map_contains_denied_key() { final Integer key = 1; Verify.denyContainsKey(key, Collections.singletonMap(key, 1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_deny_contains_key() { Verify.denyContainsKey(1, null); } @Test public void pass_if_map_not_contains_denied_key() { Verify.denyContainsKey(1, Collections.emptyMap()); } @Test(expected = AssertionError.class) public void fail_if_map_not_contains_entry() { final Integer key = 0; Verify.assertContainsKeyValue(key, 0, Collections.singletonMap(key, 1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_contains_key_value() { Verify.assertContainsKeyValue(1, 1, null); } @Test public void pass_if_map_contains_entry() { final Integer key = 1; final Integer value = 1; Verify.assertContainsKeyValue(key, value, Collections.singletonMap(key, value)); } @Test(expected = AssertionError.class) public void fail_if_collection_contains_item() { final Integer item = 1; Verify.assertNotContains(item, Collections.singletonList(item)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_collection_is_null_in_not_contains() { Verify.assertNotContains(1, null); } @Test public void pass_if_collection_not_contains_item() { Verify.assertNotContains(1, Collections.emptyList()); } @Test(expected = AssertionError.class) public void fail_if_iterable_contains_item() { final Integer item = 1; Verify.assertNotContains(item, FluentIterable.of(item)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_contains_item() { Verify.assertNotContains(1, (Iterable) null); } @Test public void pass_if_iterable_not_contains_item() { Verify.assertNotContains(1, FluentIterable.of()); } @Test(expected = AssertionError.class) public void fail_if_map_contains_key() { final Integer key = 1; Verify.assertNotContainsKey(key, Collections.singletonMap(key, 1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_not_contains_key() { Verify.assertNotContainsKey(1, null); } @Test public void pass_if_map_not_contains_key() { Verify.assertNotContainsKey(1, Collections.emptyMap()); } @Test(expected = AssertionError.class) public void fail_if_former_later_latter() { final Integer firstItem = 1; final Integer secondItem = 2; final List<Integer> list = Arrays.asList(firstItem, secondItem); Verify.assertBefore(secondItem, firstItem, list); } @Test(expected = AssertionError.class) public void fail_if_former_and_latter_are_equal() { final Integer sameItem = 1; Verify.assertBefore(sameItem, sameItem, Collections.singletonList(sameItem)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_list_is_null_in_assert_befor() { Verify.assertBefore(1, 2, null); } @Test public void pass_if_former_before_latter() { final Integer firstItem = 1; final Integer secondItem = 2; final List<Integer> list = Arrays.asList(firstItem, secondItem); Verify.assertBefore(firstItem, secondItem, list); } @Test(expected = AssertionError.class) public void fail_if_list_item_not_at_index() { final Integer firstItem = 1; final Integer secondItem = 2; final List<Integer> list = Arrays.asList(firstItem, secondItem); Verify.assertItemAtIndex(firstItem, list.indexOf(secondItem), list); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_list_is_null_in_assert_item_at_index() { Verify.assertItemAtIndex(1, 1, (List) null); } @Test public void pass_if_list_item_at_index() { final Integer value = 1; final List<Integer> list = Collections.singletonList(value); Verify.assertItemAtIndex(value, list.indexOf(value), list); } @Test(expected = AssertionError.class) public void fail_if_array_item_not_at_index() { final Integer firstItem = 1; final Integer secondItem = 2; final Object[] array = {firstItem, secondItem}; Verify.assertItemAtIndex(firstItem, 1, array); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_assert_item_at_index() { Verify.assertItemAtIndex(1, 1, (Object[]) null); } @Test public void pass_if_array_item_at_index() { final Integer value = 1; final Object[] array = {value}; Verify.assertItemAtIndex(value, 0, array); } @Test(expected = AssertionError.class) public void fail_if_array_not_starts_with_items() { final Integer[] array = {1, 2, 3}; final Integer notStartsWith = 777; Verify.assertStartsWith(array, notStartsWith); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_starts_with() { Verify.assertStartsWith((Integer[]) null, 1, 2, 3); } @Test(expected = AssertionError.class) public void fail_if_items_is_empty_in_array_starts_with() { Verify.assertStartsWith(new Integer[1]); } @Test public void pass_if_array_starts_with_items() { final Integer[] array = {1, 2}; final Integer firstItem = array[0]; Verify.assertStartsWith(array, firstItem); } @Test(expected = AssertionError.class) public void fail_if_list_not_starts_with_items() { final List<Integer> list = Arrays.asList(1, 2, 3); final Integer notStartsWith = 777; Verify.assertStartsWith(list, notStartsWith); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_list_is_null_in_starts_with() { Verify.assertStartsWith((List) null, 1, 2, 3); } @Test(expected = AssertionError.class) public void fail_if_items_is_empty_in_list_starts_with() { Verify.assertStartsWith(Collections.emptyList()); } @Test public void pass_if_list_starts_with_items() { final List<Integer> list = Arrays.asList(1, 2, 3); final Integer firstItem = list.get(0); Verify.assertStartsWith(list, firstItem); } @Test(expected = AssertionError.class) public void fail_if_list_not_ends_with_items() { final List<Integer> list = Arrays.asList(1, 2, 3); final Integer notEndsWith = 777; Verify.assertEndsWith(list, notEndsWith); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_list_is_null_in_ends_with() { Verify.assertEndsWith((List) null, 1, 2, 3); } @Test(expected = AssertionError.class) public void fail_if_items_is_empty_in_list_ends_with() { Verify.assertEndsWith(Collections.emptyList()); } @Test public void pass_if_list_ends_with_items() { final List<Integer> list = Arrays.asList(1, 2, 3); final Integer lastItem = list.get(list.size() - 1); Verify.assertEndsWith(list, lastItem); } @Test(expected = AssertionError.class) public void fail_if_array_not_ends_with_items() { final Integer[] array = {1, 2, 3}; final Integer notEndsWith = 777; Verify.assertEndsWith(array, notEndsWith); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_ends_with() { Verify.assertEndsWith((Integer[]) null, 1, 2, 3); } @Test(expected = AssertionError.class) public void fail_if_items_is_empty_in_array_ends_with() { Verify.assertEndsWith(new Integer[1]); } @Test public void pass_if_array_ends_with() { final Integer[] array = {1, 2, 3}; final Integer lastItem = array[array.length - 1]; Verify.assertEndsWith(array, lastItem); } @Test(expected = AssertionError.class) public void fail_if_objects_are_not_equal() { Verify.assertEqualsAndHashCode(1, 2); } @Test(expected = AssertionError.class) public void fail_if_objects_are_equal_but_hash_codes_are_not_equal() { final ClassThatViolateHashCodeAndCloneableContract objectA = new ClassThatViolateHashCodeAndCloneableContract(1); final ClassThatViolateHashCodeAndCloneableContract objectB = new ClassThatViolateHashCodeAndCloneableContract(1); Verify.assertEqualsAndHashCode(objectA, objectB); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_objects_are_null() { Verify.assertEqualsAndHashCode(null, null); } @Test public void pass_if_objects_and_their_hash_codes_are_equal() { Verify.assertEqualsAndHashCode(1, 1); } @Test(expected = AssertionError.class) public void fail_if_value_is_not_negative() { Verify.assertNegative(1); } @Test(expected = AssertionError.class) public void fail_if_value_is_zero_in_assert_negative() { Verify.assertNegative(0); } @Test public void pass_if_value_is_negative() { Verify.assertNegative(-1); } @Test(expected = AssertionError.class) public void fail_if_value_is_not_positive() { Verify.assertPositive(-1); } @Test(expected = AssertionError.class) public void fail_if_value_is_zero_in_assert_positive() { Verify.assertPositive(0); } @Test public void pass_if_value_is_positive() { Verify.assertPositive(1); } @Test(expected = AssertionError.class) public void fail_if_value_is_positive() { Verify.assertZero(1); } @Test(expected = AssertionError.class) public void fail_if_value_is_negative() { Verify.assertZero(-1); } @Test public void pass_if_value_is_zero() { Verify.assertZero(0); } @Test(expected = AssertionError.class) public void fail_if_clone_returns_same_object() { Verify.assertShallowClone(new ClassThatViolateHashCodeAndCloneableContract(1)); } @Test(expected = AssertionError.class) public void fail_if_clone_does_not_work_correctly() { Verify.assertShallowClone(new ClassThatImplementCloneableIncorrectly(1)); } @Test public void pass_if_cloneable_equals_and_hash_code_overridden_correctly() { Verify.assertShallowClone(new ClassThatImplementCloneableCorrectly(1)); } @Test(expected = AssertionError.class) public void fail_if_class_instantiable() { Verify.assertClassNonInstantiable(Object.class); } @Test(expected = AssertionError.class) public void fail_if_class_instantiable_through_reflection() { Verify.assertClassNonInstantiable(ClassWithPrivateCtor.class); } @Test public void pass_if_new_instance_throw_instantiable_exception() { Verify.assertClassNonInstantiable(void.class); } @Test public void pass_if_class_non_instantiable_through_reflection() { Verify.assertClassNonInstantiable(ClassThatThrowExceptionInConstructor.class); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_error() { final Runnable notThrowsException = new Runnable() { @Override public void run() { } }; Verify.assertError(AssertionError.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_specified_error() { final Runnable throwsAssertionError = new Runnable() { @Override public void run() { throw new AssertionError(); } }; Verify.assertError(Error.class, throwsAssertionError); } @Test public void pass_if_runnable_throws_specified_error() { final Runnable throwsAssertionError = new Runnable() { @Override public void run() { throw new AssertionError(); } }; Verify.assertError(AssertionError.class, throwsAssertionError); } @Test(expected = AssertionError.class) public void fail_if_callable_not_throws_exception() { final Callable notThrowsException = new Callable() { @Override public Object call() throws Exception { return null; } }; Verify.assertThrows(Exception.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_callable_not_throws_specified_exception() { final Callable throwsEmptyStackException = new Callable() { @Override public Object call() throws Exception { throw new EmptyStackException(); } }; Verify.assertThrows(Exception.class, throwsEmptyStackException); } @Test public void pass_if_callable_throws_specified_exception() { final Callable throwsEmptyStackException = new Callable() { @Override public Object call() throws Exception { throw new EmptyStackException(); } }; Verify.assertThrows(EmptyStackException.class, throwsEmptyStackException); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_exception() { final Runnable notThrowsException = new Runnable() { @Override public void run() { } }; Verify.assertThrows(Exception.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_specified_exception() { final Runnable throwsEmptyStackException = new Runnable() { @Override public void run() { throw new EmptyStackException(); } }; Verify.assertThrows(Exception.class, throwsEmptyStackException); } @Test public void pass_if_runnable_throws_specified_exception() { final Runnable throwsEmptyStackException = new Runnable() { @Override public void run() { throw new EmptyStackException(); } }; Verify.assertThrows(EmptyStackException.class, throwsEmptyStackException); } @Test(expected = AssertionError.class) public void fail_if_callable_not_throws_exception_with_cause() { final Callable notThrowsException = new Callable() { @Override public Object call() throws Exception { return null; } }; Verify.assertThrowsWithCause(Exception.class, Exception.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_callable_throws_exception_with_different_causes() { final Throwable expectedCause = new EmptyStackException(); final Throwable actualCause = new AclNotFoundException(); final RuntimeException runtimeException = new RuntimeException(actualCause); final Callable throwsRuntimeException = new Callable() { @Override public Object call() { throw runtimeException; } }; Verify.assertThrowsWithCause(runtimeException.getClass(), expectedCause.getClass(), throwsRuntimeException); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_callable_expected_cause_is_null() { final Callable throwsRuntimeException = new Callable() { @Override public Object call() { throw new RuntimeException(new EmptyStackException()); } }; Verify.assertThrowsWithCause(EmptyStackException.class, null, throwsRuntimeException); } @Test public void pass_if_callable_throws_specified_exception_with_specified_cause() { final Throwable cause = new EmptyStackException(); final RuntimeException runtimeException = new RuntimeException(cause); final Callable throwsRuntimeException = new Callable() { @Override public Object call() { throw runtimeException; } }; Verify.assertThrowsWithCause(runtimeException.getClass(), cause.getClass(), throwsRuntimeException); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_exception_with_cause() { final Runnable notThrowsException = new Runnable() { @Override public void run() { } }; Verify.assertThrowsWithCause(Exception.class, Exception.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_runnable_throws_exception_with_different_causes() { final Throwable expectedCause = new EmptyStackException(); final Throwable actualCause = new AclNotFoundException(); final RuntimeException runtimeException = new RuntimeException(actualCause); final Runnable throwsRuntimeException = new Runnable() { @Override public void run() { throw runtimeException; } }; Verify.assertThrowsWithCause(runtimeException.getClass(), expectedCause.getClass(), throwsRuntimeException); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_runnable_expected_cause_is_null() { final Runnable throwsRuntimeException = new Runnable() { @Override public void run() { throw new RuntimeException(new EmptyStackException()); } }; Verify.assertThrowsWithCause(EmptyStackException.class, null, throwsRuntimeException); } @Test public void pass_if_runnable_throws_specified_exception_with_specified_cause() { final Throwable cause = new EmptyStackException(); final RuntimeException runtimeException = new RuntimeException(cause); final Runnable throwsRuntimeException = new Runnable() { @Override public void run() { throw runtimeException; } }; Verify.assertThrowsWithCause(runtimeException.getClass(), cause.getClass(), throwsRuntimeException); } @SuppressWarnings("EqualsAndHashcode") private static class ClassThatViolateHashCodeAndCloneableContract implements Cloneable { private final int value; private ClassThatViolateHashCodeAndCloneableContract(int value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClassThatViolateHashCodeAndCloneableContract that = (ClassThatViolateHashCodeAndCloneableContract) o; return value == that.value; } @SuppressWarnings("MethodDoesntCallSuperMethod") @Override protected Object clone() throws CloneNotSupportedException { return this; } } private static class ClassThatImplementCloneableCorrectly implements Cloneable { private final int value; private ClassThatImplementCloneableCorrectly(int value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClassThatImplementCloneableCorrectly that = (ClassThatImplementCloneableCorrectly) o; return value == that.value; } @Override public int hashCode() { return value; } } private static final class ClassThatImplementCloneableIncorrectly implements Cloneable { private final int value; private ClassThatImplementCloneableIncorrectly(int value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClassThatImplementCloneableIncorrectly that = (ClassThatImplementCloneableIncorrectly) o; return value == that.value; } @Override public int hashCode() { return value; } @Override protected Object clone() throws CloneNotSupportedException { return new ClassThatImplementCloneableIncorrectly(value + 1); } } private static class ClassWithPrivateCtor { @SuppressWarnings("RedundantNoArgConstructor") private ClassWithPrivateCtor() { } } private static class ClassThatThrowExceptionInConstructor { private ClassThatThrowExceptionInConstructor() { throw new AssertionError("This is non-instantiable class"); } } }
Rename constants in `VerifyShould` according to naming convention
testutil/src/test/java/org/spine3/test/VerifyShould.java
Rename constants in `VerifyShould` according to naming convention
<ide><path>estutil/src/test/java/org/spine3/test/VerifyShould.java <ide> @SuppressWarnings({"ClassWithTooManyMethods", "OverlyComplexClass"}) <ide> public class VerifyShould { <ide> <del> private static final String emptyString = ""; <del> private static final String notEmptyString = "Not empty string"; <del> private static final String mapName = "map"; <add> private static final String EMPTY_STRING = ""; <add> private static final String NON_EMPTY_STRING = "Non-empty string"; <add> private static final String MAP_NAME = "map"; <ide> <ide> @Test <ide> public void extend_Assert_class() { <ide> <ide> @Test(expected = AssertionError.class) <ide> public void fail_if_string_not_contains_char_sequence() { <del> Verify.assertContains(notEmptyString, emptyString); <add> Verify.assertContains(NON_EMPTY_STRING, EMPTY_STRING); <ide> } <ide> <ide> @SuppressWarnings("ConstantConditions") <ide> @Test(expected = AssertionError.class) <ide> public void fail_if_char_sequence_is_null_in_contains() { <del> Verify.assertContains(null, emptyString); <add> Verify.assertContains(null, EMPTY_STRING); <ide> } <ide> <ide> @SuppressWarnings("ConstantConditions") <ide> @Test(expected = AssertionError.class) <ide> public void fail_if_string_is_null_in_contains() { <del> Verify.assertContains(emptyString, (String) null); <add> Verify.assertContains(EMPTY_STRING, (String) null); <ide> } <ide> <ide> @SuppressWarnings({"ConstantConditions", "ErrorNotRethrown"}) <ide> final String nullString = null; <ide> <ide> try { <del> Verify.assertContains(null, emptyString); <add> Verify.assertContains(null, EMPTY_STRING); <ide> } catch (AssertionError e) { <del> Verify.assertContains(emptyString, nullString); <add> Verify.assertContains(EMPTY_STRING, nullString); <ide> } <ide> } <ide> <ide> @Test <ide> public void pass_if_string_contains_char_sequence() { <del> Verify.assertContains(emptyString, notEmptyString); <add> Verify.assertContains(EMPTY_STRING, NON_EMPTY_STRING); <ide> } <ide> <ide> @Test(expected = AssertionError.class) <ide> public void fail_is_string_contains_char_sequence() { <del> Verify.assertNotContains(emptyString, notEmptyString); <add> Verify.assertNotContains(EMPTY_STRING, NON_EMPTY_STRING); <ide> } <ide> <ide> @SuppressWarnings("ConstantConditions") <ide> @Test(expected = AssertionError.class) <ide> public void fail_if_char_sequence_is_null_in_not_contains() { <del> Verify.assertNotContains(null, emptyString); <add> Verify.assertNotContains(null, EMPTY_STRING); <ide> } <ide> <ide> @SuppressWarnings("ConstantConditions") <ide> @Test(expected = AssertionError.class) <ide> public void fail_if_string_is_null_in_not_contains() { <del> Verify.assertNotContains(emptyString, (String) null); <add> Verify.assertNotContains(EMPTY_STRING, (String) null); <ide> } <ide> <ide> @Test <ide> public void pass_if_string_not_contains_char_sequence() { <del> Verify.assertNotContains(notEmptyString, emptyString); <add> Verify.assertNotContains(NON_EMPTY_STRING, EMPTY_STRING); <ide> } <ide> <ide> @Test(expected = AssertionError.class) <ide> final Map<Integer, Map<Integer, Integer>> firstOne = Collections.singletonMap(1, Collections.singletonMap(1, 1)); <ide> final Map<Integer, Map<Integer, Integer>> secondOne = Collections.singletonMap(1, Collections.singletonMap(1, 2)); <ide> <del> Verify.assertMapsEqual(firstOne, secondOne, mapName); <add> Verify.assertMapsEqual(firstOne, secondOne, MAP_NAME); <ide> } <ide> <ide> @SuppressWarnings("ConstantConditions") <ide> @Test <ide> public void pass_if_maps_are_null() { <del> Verify.assertMapsEqual(null, null, mapName); <add> Verify.assertMapsEqual(null, null, MAP_NAME); <ide> } <ide> <ide> @Test <ide> final Map<Integer, Map<Integer, Integer>> firstOne = Collections.singletonMap(1, Collections.singletonMap(1, 1)); <ide> final Map<Integer, Map<Integer, Integer>> secondOne = new HashMap<>(firstOne); <ide> <del> Verify.assertMapsEqual(firstOne, secondOne, mapName); <add> Verify.assertMapsEqual(firstOne, secondOne, MAP_NAME); <ide> } <ide> <ide> @Test(expected = AssertionError.class)
Java
mit
471b6f117bf92d1161ab03d1c899f6a7ae953311
0
Nanopublication/nanopub-java,Nanopublication/nanopub-java
package org.nanopub.extra.server; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Serializable; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import com.google.gson.Gson; public class ServerInfo implements Serializable { private static final long serialVersionUID = 5893051633759794791L; static { } public static class ServerInfoException extends Exception { private static final long serialVersionUID = 3903673740899289181L; public ServerInfoException(String serverUrl) { super(serverUrl); } } public static ServerInfo load(String serverUrl) throws ServerInfoException { return load(serverUrl, ServerInfo.class); } protected static ServerInfo load(String serverUrl, Class<? extends ServerInfo> serverInfoClass) throws ServerInfoException { HttpGet get = new HttpGet(serverUrl); get.setHeader("Accept", "application/json"); ServerInfo si = null; try { RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000).build(); HttpClient c = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); InputStream in = c.execute(get).getEntity().getContent(); si = new Gson().fromJson(new InputStreamReader(in), serverInfoClass); } catch (Exception ex) { throw new ServerInfoException(serverUrl); } if (!si.getPublicUrl().equals(serverUrl)) { throw new ServerInfoException("Server URL does not match its declared public URL"); } return si; } protected String publicUrl; protected String admin; protected boolean postNanopubsEnabled; protected boolean postPeersEnabled; protected int pageSize = -1; protected long nextNanopubNo = -1; protected long journalId = -1; public ServerInfo() { } public boolean isPostNanopubsEnabled() { return postNanopubsEnabled; } public boolean isPostPeersEnabled() { return postPeersEnabled; } public String getPublicUrl() { return publicUrl; } public String getAdmin() { return admin; } public int getPageSize() { return pageSize; } public long getNextNanopubNo() { return nextNanopubNo; } public long getJournalId() { return journalId; } public String asJson() { return new Gson().toJson(this); } }
src/main/java/org/nanopub/extra/server/ServerInfo.java
package org.nanopub.extra.server; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Serializable; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import com.google.gson.Gson; public class ServerInfo implements Serializable { private static final long serialVersionUID = 5893051633759794791L; public static class ServerInfoException extends Exception { private static final long serialVersionUID = 3903673740899289181L; public ServerInfoException(String serverUrl) { super(serverUrl); } } public static ServerInfo load(String serverUrl) throws ServerInfoException { return load(serverUrl, ServerInfo.class); } protected static ServerInfo load(String serverUrl, Class<? extends ServerInfo> serverInfoClass) throws ServerInfoException { HttpGet get = new HttpGet(serverUrl); get.setHeader("Accept", "application/json"); ServerInfo si = null; try { InputStream in = HttpClientBuilder.create().build().execute(get).getEntity().getContent(); si = new Gson().fromJson(new InputStreamReader(in), serverInfoClass); } catch (Exception ex) { throw new ServerInfoException(serverUrl); } if (!si.getPublicUrl().equals(serverUrl)) { throw new ServerInfoException("Server URL does not match its declared public URL"); } return si; } protected String publicUrl; protected String admin; protected boolean postNanopubsEnabled; protected boolean postPeersEnabled; protected int pageSize = -1; protected long nextNanopubNo = -1; protected long journalId = -1; public ServerInfo() { } public boolean isPostNanopubsEnabled() { return postNanopubsEnabled; } public boolean isPostPeersEnabled() { return postPeersEnabled; } public String getPublicUrl() { return publicUrl; } public String getAdmin() { return admin; } public int getPageSize() { return pageSize; } public long getNextNanopubNo() { return nextNanopubNo; } public long getJournalId() { return journalId; } public String asJson() { return new Gson().toJson(this); } }
Reduce timeout to 5 seconds for getting server info
src/main/java/org/nanopub/extra/server/ServerInfo.java
Reduce timeout to 5 seconds for getting server info
<ide><path>rc/main/java/org/nanopub/extra/server/ServerInfo.java <ide> import java.io.InputStreamReader; <ide> import java.io.Serializable; <ide> <add>import org.apache.http.client.HttpClient; <add>import org.apache.http.client.config.RequestConfig; <ide> import org.apache.http.client.methods.HttpGet; <ide> import org.apache.http.impl.client.HttpClientBuilder; <ide> <ide> public class ServerInfo implements Serializable { <ide> <ide> private static final long serialVersionUID = 5893051633759794791L; <add> <add> static { <add> <add> } <ide> <ide> public static class ServerInfoException extends Exception { <ide> <ide> get.setHeader("Accept", "application/json"); <ide> ServerInfo si = null; <ide> try { <del> InputStream in = HttpClientBuilder.create().build().execute(get).getEntity().getContent(); <add> RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000).build(); <add> HttpClient c = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); <add> InputStream in = c.execute(get).getEntity().getContent(); <ide> si = new Gson().fromJson(new InputStreamReader(in), serverInfoClass); <ide> } catch (Exception ex) { <ide> throw new ServerInfoException(serverUrl);
JavaScript
agpl-3.0
04e8f9cd568f0f69af5f3ca9241e2163613a2809
0
richardsawyer/smart-area,richardsawyer/smart-area
/** * AngularJS Directive to allow autocomplete and dropdown suggestions * on textareas. * * Homepage: https://github.com/aurbano/smart-area * * @author Alejandro U. Alvarez (http://urbanoalvarez.es) * @license AGPLv3 (See LICENSE) */ angular.module('smartArea', []) .directive('smartArea', function($compile) { return { restrict: 'A', scope: { areaConfig: '=smartArea', areaData: '=ngModel', placeholder: '@' }, replace: true, link: function(scope, textArea){ if(textArea[0].tagName.toLowerCase() !== 'textarea'){ console.warn("smartArea can only be used on textareas"); return false; } // Caret tracking inspired by // https://github.com/component/textarea-caret-position // Properties to be copied over from the textarea var properties = [ 'direction', // RTL support 'boxSizing', 'width', // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does 'overflowX', 'overflowY', // copy the scrollbar for IE 'color', 'height', 'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth', 'borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor', 'borderTopStyle', 'borderRightStyle', 'borderBottomStyle', 'borderLeftStyle', 'borderRadius', 'backgroundColor', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', // https://developer.mozilla.org/en-US/docs/Web/CSS/font 'fontStyle', 'fontVariant', 'fontWeight', 'fontStretch', 'fontSize', 'fontSizeAdjust', 'lineHeight', 'fontFamily', 'textAlign', 'textTransform', 'textIndent', 'textDecoration', // might not make a difference, but better be safe 'letterSpacing', 'wordSpacing', 'whiteSpace', 'wordBreak', 'wordWrap' ]; // Build the HTML structure var mainWrap = angular.element('<div class="sa-wrapper"></div>'), isFirefox = !(window.mozInnerScreenX === null); scope.fakeAreaElement = angular.element($compile('<div class="sa-fakeArea" ng-trim="false" ng-bind-html="fakeArea"></div>')(scope)) .appendTo(mainWrap); scope.dropdown.element = angular.element($compile('<div class="sa-dropdown" ng-show="dropdown.content.length > 0"><input type="text" class="form-control" ng-show="dropdown.showFilter"/><ul class="dropdown-menu" role="menu" style="position:static"><li ng-repeat="element in dropdown.content" role="presentation"><a href="" role="menuitem" ng-click="dropdown.selected(element)" ng-class="{active: $index == dropdown.current}" ng-bind-html="element.display"></a></li></ul></div>')(scope)) .appendTo(mainWrap); scope.dropdown.filterElement = scope.dropdown.element.find('input'); scope.dropdown.filterElement.bind('keydown', scope.keyboardEvents); // Default textarea css for the div scope.fakeAreaElement.css('whiteSpace', 'pre-wrap'); scope.fakeAreaElement.css('wordWrap', 'break-word'); // Transfer the element's properties to the div properties.forEach(function (prop) { scope.fakeAreaElement.css(prop, textArea.css(prop)); }); // scope.fakeAreaElement.css('width',(parseInt(textArea.outerWidth()) + 1) + 'px'); scope.$watch(function(){ return textArea.outerWidth(); }, function(width) { scope.fakeAreaElement.css('width',(parseInt(width) + 1) + 'px'); }); // Special considerations for Firefox // if (isFirefox) { // scope.fakeAreaElement.css('width',parseInt(textArea.width()) - 2 + 'px'); // Firefox adds 2 pixels to the padding - https://bugzilla.mozilla.org/show_bug.cgi?id=753662 // // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 // if (textArea.scrollHeight > parseInt(textArea.height)){ // scope.fakeAreaElement.css('overflowY', 'scroll'); // } // } // Insert the HTML elements mainWrap.insertBefore(textArea); textArea.appendTo(mainWrap).addClass('sa-realArea').attr('ng-trim',false); $compile(textArea); // Dirty hack to maintain the height textArea.on('keyup', function(){ scope.fakeAreaElement.height(textArea.height()); }); scope.$watch('areaData', function() { scope.fakeAreaElement.height(textArea.height()); }); return mainWrap; }, controller: ['$scope', '$element', '$timeout', '$sce', function($scope, $element, $timeout, $sce){ /* +----------------------------------------------------+ * + Scope Data + * +----------------------------------------------------+ */ $scope.fakeArea = $scope.areaData || ''; $scope.dropdownContent = 'Dropdown'; $scope.dropdown = { content: [], element: null, current: 0, select: null, customSelect: null, filter: '', match: '', mode: 'append', showFilter: false, filterElement: null }; /* +----------------------------------------------------+ * + Scope Watches + * +----------------------------------------------------+ */ $scope.$watch('areaData', function(){ $scope.trackCaret(); // TODO Track caret on another fake area, so I don't have to recalculate autocomplete triggers every time the cursor moves. // checkTriggers(); }); /* +----------------------------------------------------+ * + Scope Functions + * +----------------------------------------------------+ */ /** * Update the Dropdown position according to the current caret position * on the textarea */ $scope.trackCaret = function(){ var text = $scope.areaData || '', position = getCharacterPosition(); $scope.fakeArea = $sce.trustAsHtml(text.substring(0, position) + '<span class="sa-tracking"></span>' + text.substring(position)); // Tracking span $timeout(function(){ var span = $scope.fakeAreaElement.find('span.sa-tracking'); if(span.length > 0){ var spanOffset = span.position(); // Move the dropdown $scope.dropdown.element.css({ top: (spanOffset.top + parseInt($element.css('fontSize')) + 2)+'px', left: (spanOffset.left)+'px' }); } highlightText(); }, 0); }; /** * Keyboard event reacting. This function is triggered by * keydown events in the dropdown filter and the main textarea * * @param event JavaScript event */ $scope.keyboardEvents = function(event){ if($scope.dropdown.content.length > 0) { var code = event.keyCode || event.which; if (code === 13) { // Enter event.preventDefault(); event.stopPropagation(); // Add the selected word from the Dropdown // to the areaData in the current position $timeout(function(){ $scope.dropdown.selected($scope.dropdown.content[$scope.dropdown.current]); },0); }else if(code === 38){ // Up event.preventDefault(); event.stopPropagation(); $timeout(function(){ $scope.dropdown.current--; if($scope.dropdown.current < 0){ $scope.dropdown.current = $scope.dropdown.content.length - 1; // Wrap around } },0); }else if(code === 40){ // Down event.preventDefault(); event.stopPropagation(); $timeout(function(){ $scope.dropdown.current++; if($scope.dropdown.current >= $scope.dropdown.content.length){ $scope.dropdown.current = 0; // Wrap around } },0); }else if(code === 27){ // Esc event.preventDefault(); event.stopPropagation(); $timeout(function(){ $scope.dropdown.content = []; $element[0].focus(); },0); }else{ $scope.dropdown.filterElement.focus(); } } }; /** * Add an item to the textarea, this is called * when selecting an element from the dropdown. * @param item Selected object */ $scope.dropdown.selected = function(item){ if($scope.dropdown.customSelect !== null){ var append = $scope.dropdown.mode === 'append'; addSelectedDropdownText($scope.dropdown.customSelect(item), append); }else{ addSelectedDropdownText(item.display); } $scope.dropdown.content = []; }; /* +----------------------------------------------------+ * + Internal Functions + * +----------------------------------------------------+ */ /** * Add text to the textarea, this handles positioning the text * at the caret position, and also either replacing the last word * or appending as new content. * * @param selectedWord Word to add to the textarea * @param append Whether it should be appended or replace the last word */ function addSelectedDropdownText(selectedWord, append){ $scope.dropdown.showFilter = false; var text = $scope.areaData || '', position = getCharacterPosition(), lastWord = text.substr(0, position).split(/[\s\b{}]/), remove = lastWord[lastWord.length - 1].length; if(!append && $scope.dropdown.match){ remove = $scope.dropdown.match.length; } if(append || remove < 0){ remove = 0; } // Now remove the last word, and replace with the dropped down one $scope.areaData = text.substr(0, position - remove) + selectedWord + text.substr(position); if(!append && $scope.dropdown.match){ position = position - $scope.dropdown.match.length + selectedWord.toString().length; } // Now reset the caret position if($element[0].selectionStart) { $timeout(function(){ $element[0].focus(); $element[0].setSelectionRange(position - remove + selectedWord.toString().length, position - remove + selectedWord.toString().length); checkTriggers(); }, 100); } } /** * Perform the "syntax" highlighting of autocomplete words that have * a cssClass specified. */ function highlightText(){ var colours = { muted: '#777', primary: '#337ab7', success: '#3c763d', info: '#31708f', warning: '#8a6d3b', danger: '#a94442' }; var text = $scope.areaData || ''; if(typeof($scope.areaConfig.autocomplete) === 'undefined' || $scope.areaConfig.autocomplete.length === 0){ return; } $scope.areaConfig.autocomplete.forEach(function(autoList){ for(var i=0; i<autoList.words.length; i++){ if(typeof(autoList.words[i]) === "string"){ text = text.replace(new RegExp("([^\\w]|\\b)("+autoList.words[i]+")([^\\w]|\\b)", 'g'), '$1<span class="'+autoList.cssClass+'" style="color:'+colours[autoList.style]+';">$2</span>$3'); }else{ text = text.replace(autoList.words[i], function(match){ return '<span class="'+autoList.cssClass+'" style="'+autoList.style+'">'+match+'</span>'; }); } } }); text = text !== '' ? text : '<span class="text-muted">' + $scope.placeholder + '</span>'; // Add to the fakeArea $scope.fakeArea = $sce.trustAsHtml(text); } /** * Check all the triggers */ function checkTriggers(){ triggerDropdownAutocomplete(); triggerDropdownAdvanced(); } /** * Trigger the advanced dropdown system, this will check * all the specified triggers in the configuration object under dropdown, * and if any of them match it will call it's list() function and add the * elements returned from it to the dropdown. */ function triggerDropdownAdvanced(){ $scope.dropdown.showFilter = false; $scope.dropdown.match = false; if(typeof($scope.areaConfig.dropdown) === 'undefined' || $scope.areaConfig.dropdown.length === 0){ return; } $scope.areaConfig.dropdown.forEach(function(element){ // Check if the trigger is under the cursor var text = $scope.areaData || '', position = getCharacterPosition(); if(typeof(element.trigger) === 'string' && element.trigger === text.substr(position - element.trigger.length, element.trigger.length)){ // The cursor is exactly at the end of the trigger element.list(function(data){ $scope.dropdown.content = data.map(function(el){ el.display = $sce.trustAsHtml(el.display); return el; }); $scope.dropdown.customSelect = element.onSelect; $scope.dropdown.mode = element.mode || 'append'; $scope.dropdown.match = ''; $scope.dropdown.showFilter = element.filter || false; $timeout(function(){ $scope.dropdown.filterElement.focus(); }, 10); }); }else if(typeof(element.trigger) === 'object'){ // I need to get the index of the last match var searchable = text.substr(0, position), match, found = false, lastPosition = 0; while ((match = element.trigger.exec(searchable)) !== null){ if(match.index === lastPosition){ break; } lastPosition = match.index; if(match.index + match[0].length === position){ found = true; break; } } if(found){ element.list(match, function(data){ $scope.dropdown.content = data.map(function(el){ el.display = $sce.trustAsHtml(el.display); return el; }); $scope.dropdown.customSelect = element.onSelect; $scope.dropdown.mode = element.mode || 'append'; $scope.dropdown.match = match[1]; $scope.dropdown.showFilter = element.filter || false; }); } } }); } /** * Set the scroll on the fake area */ function resetScroll(){ $timeout(function(){ $scope.fakeAreaElement.scrollTop($element.scrollTop()); }, 5); } /** * Trigger a simple autocomplete, this checks the last word and determines * whether any word on the autocomplete lists matches it */ function triggerDropdownAutocomplete(){ // First check with the autocomplete words (the ones that are not objects var autocomplete = [], suggestions = [], text = $scope.areaData || '', position = getCharacterPosition(), lastWord = text.substr(0, position).split(/[\s\b{}]/); // Get the last typed word lastWord = lastWord[lastWord.length-1]; $scope.areaConfig.autocomplete.forEach(function(autoList){ autoList.words.forEach(function(word){ if(typeof(word) === 'string' && autocomplete.indexOf(word) < 0){ if(lastWord.length > 0 || lastWord.length < 1 && autoList.autocompleteOnSpace){ autocomplete.push(word); } } }); }); if ($scope.areaConfig.dropdown !== undefined){ $scope.areaConfig.dropdown.forEach(function(element){ if(typeof(element.trigger) === 'string' && autocomplete.indexOf(element.trigger) < 0){ autocomplete.push(element.trigger); } }); } // Now with the list, filter and return autocomplete.forEach(function(word){ if(lastWord.length < word.length && word.toLowerCase().substr(0, lastWord.length) === lastWord.toLowerCase()){ suggestions.push({ display: $sce.trustAsHtml(word), data: null }); } }); $scope.dropdown.customSelect = null; $scope.dropdown.current = 0; $scope.dropdown.content = suggestions; } /** * Get Character count on an editable field * http://stackoverflow.com/questions/4767848/get-caret-cursor-position-in-contenteditable-area-containing-html-content */ function getCharacterPosition() { var el = $element[0]; if (typeof(el.selectionEnd) == "number") { return el.selectionEnd; } } /* +----------------------------------------------------+ * + Event Binding + * +----------------------------------------------------+ */ $element.bind('keyup click focus', function () { $timeout(function(){ $scope.trackCaret(); }, 0); }); $element.bind('keyup', function (event) { if ([13, 38, 40, 27].indexOf(event.keyCode) === -1) { $timeout(function(){ checkTriggers(); }, 0); } }); $element.bind('click', function () { $timeout(function(){ $scope.dropdown.content = []; $element[0].focus(); }, 0); }); $element.bind('keydown', function(event){ resetScroll(); $scope.keyboardEvents(event); }); }] }; });
dist/smart-area.js
/** * AngularJS Directive to allow autocomplete and dropdown suggestions * on textareas. * * Homepage: https://github.com/aurbano/smart-area * * @author Alejandro U. Alvarez (http://urbanoalvarez.es) * @license AGPLv3 (See LICENSE) */ angular.module('smartArea', []) .directive('smartArea', function($compile) { return { restrict: 'A', scope: { areaConfig: '=smartArea', areaData: '=ngModel', placeholder: '@' }, replace: true, link: function(scope, textArea){ if(textArea[0].tagName.toLowerCase() !== 'textarea'){ console.warn("smartArea can only be used on textareas"); return false; } // Caret tracking inspired by // https://github.com/component/textarea-caret-position // Properties to be copied over from the textarea var properties = [ 'direction', // RTL support 'boxSizing', 'width', // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does 'overflowX', 'overflowY', // copy the scrollbar for IE 'color', 'height', 'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth', 'borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor', 'borderTopStyle', 'borderRightStyle', 'borderBottomStyle', 'borderLeftStyle', 'borderRadius', 'backgroundColor', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', // https://developer.mozilla.org/en-US/docs/Web/CSS/font 'fontStyle', 'fontVariant', 'fontWeight', 'fontStretch', 'fontSize', 'fontSizeAdjust', 'lineHeight', 'fontFamily', 'textAlign', 'textTransform', 'textIndent', 'textDecoration', // might not make a difference, but better be safe 'letterSpacing', 'wordSpacing', 'whiteSpace', 'wordBreak', 'wordWrap' ]; // Build the HTML structure var mainWrap = angular.element('<div class="sa-wrapper"></div>'), isFirefox = !(window.mozInnerScreenX === null); scope.fakeAreaElement = angular.element($compile('<div class="sa-fakeArea" ng-trim="false" ng-bind-html="fakeArea"></div>')(scope)) .appendTo(mainWrap); scope.dropdown.element = angular.element($compile('<div class="sa-dropdown" ng-show="dropdown.content.length > 0"><input type="text" class="form-control" ng-show="dropdown.showFilter"/><ul class="dropdown-menu" role="menu" style="position:static"><li ng-repeat="element in dropdown.content" role="presentation"><a href="" role="menuitem" ng-click="dropdown.selected(element)" ng-class="{active: $index == dropdown.current}" ng-bind-html="element.display"></a></li></ul></div>')(scope)) .appendTo(mainWrap); scope.dropdown.filterElement = scope.dropdown.element.find('input'); scope.dropdown.filterElement.bind('keydown', scope.keyboardEvents); // Default textarea css for the div scope.fakeAreaElement.css('whiteSpace', 'pre-wrap'); scope.fakeAreaElement.css('wordWrap', 'break-word'); // Transfer the element's properties to the div properties.forEach(function (prop) { scope.fakeAreaElement.css(prop, textArea.css(prop)); }); // scope.fakeAreaElement.css('width',(parseInt(textArea.outerWidth()) + 1) + 'px'); scope.$watch(function(){ return textArea.outerWidth(); }, function(width) { scope.fakeAreaElement.css('width',(parseInt(width) + 1) + 'px'); }); // Special considerations for Firefox // if (isFirefox) { // scope.fakeAreaElement.css('width',parseInt(textArea.width()) - 2 + 'px'); // Firefox adds 2 pixels to the padding - https://bugzilla.mozilla.org/show_bug.cgi?id=753662 // // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 // if (textArea.scrollHeight > parseInt(textArea.height)){ // scope.fakeAreaElement.css('overflowY', 'scroll'); // } // } // Insert the HTML elements mainWrap.insertBefore(textArea); textArea.appendTo(mainWrap).addClass('sa-realArea').attr('ng-trim',false); $compile(textArea); // Dirty hack to maintain the height textArea.on('keyup', function(){ scope.fakeAreaElement.height(textArea.height()); }); scope.$watch('areaData', function() { scope.fakeAreaElement.height(textArea.height()); }); return mainWrap; }, controller: ['$scope', '$element', '$timeout', '$sce', function($scope, $element, $timeout, $sce){ /* +----------------------------------------------------+ * + Scope Data + * +----------------------------------------------------+ */ $scope.fakeArea = $scope.areaData || ''; $scope.dropdownContent = 'Dropdown'; $scope.dropdown = { content: [], element: null, current: 0, select: null, customSelect: null, filter: '', match: '', mode: 'append', showFilter: false, filterElement: null }; /* +----------------------------------------------------+ * + Scope Watches + * +----------------------------------------------------+ */ $scope.$watch('areaData', function(){ $scope.trackCaret(); // TODO Track caret on another fake area, so I don't have to recalculate autocomplete triggers every time the cursor moves. // checkTriggers(); }); /* +----------------------------------------------------+ * + Scope Functions + * +----------------------------------------------------+ */ /** * Update the Dropdown position according to the current caret position * on the textarea */ $scope.trackCaret = function(){ var text = $scope.areaData || '', position = getCharacterPosition(); $scope.fakeArea = $sce.trustAsHtml(text.substring(0, position) + '<span class="sa-tracking"></span>' + text.substring(position)); // Tracking span $timeout(function(){ var span = $scope.fakeAreaElement.find('span.sa-tracking'); if(span.length > 0){ var spanOffset = span.position(); // Move the dropdown $scope.dropdown.element.css({ top: (spanOffset.top + parseInt($element.css('fontSize')) + 2)+'px', left: (spanOffset.left)+'px' }); } highlightText(); }, 0); }; /** * Keyboard event reacting. This function is triggered by * keydown events in the dropdown filter and the main textarea * * @param event JavaScript event */ $scope.keyboardEvents = function(event){ if($scope.dropdown.content.length > 0) { var code = event.keyCode || event.which; if (code === 13) { // Enter event.preventDefault(); event.stopPropagation(); // Add the selected word from the Dropdown // to the areaData in the current position $timeout(function(){ $scope.dropdown.selected($scope.dropdown.content[$scope.dropdown.current]); },0); }else if(code === 38){ // Up event.preventDefault(); event.stopPropagation(); $timeout(function(){ $scope.dropdown.current--; if($scope.dropdown.current < 0){ $scope.dropdown.current = $scope.dropdown.content.length - 1; // Wrap around } },0); }else if(code === 40){ // Down event.preventDefault(); event.stopPropagation(); $timeout(function(){ $scope.dropdown.current++; if($scope.dropdown.current >= $scope.dropdown.content.length){ $scope.dropdown.current = 0; // Wrap around } },0); }else if(code === 27){ // Esc event.preventDefault(); event.stopPropagation(); $timeout(function(){ $scope.dropdown.content = []; $element[0].focus(); },0); }else{ $scope.dropdown.filterElement.focus(); } } }; /** * Add an item to the textarea, this is called * when selecting an element from the dropdown. * @param item Selected object */ $scope.dropdown.selected = function(item){ if($scope.dropdown.customSelect !== null){ var append = $scope.dropdown.mode === 'append'; addSelectedDropdownText($scope.dropdown.customSelect(item), append); }else{ addSelectedDropdownText(item.display); } $scope.dropdown.content = []; }; /* +----------------------------------------------------+ * + Internal Functions + * +----------------------------------------------------+ */ /** * Add text to the textarea, this handles positioning the text * at the caret position, and also either replacing the last word * or appending as new content. * * @param selectedWord Word to add to the textarea * @param append Whether it should be appended or replace the last word */ function addSelectedDropdownText(selectedWord, append){ $scope.dropdown.showFilter = false; var text = $scope.areaData || '', position = getCharacterPosition(), lastWord = text.substr(0, position).split(/[\s\b{}]/), remove = lastWord[lastWord.length - 1].length; if(!append && $scope.dropdown.match){ remove = $scope.dropdown.match.length; } if(append || remove < 0){ remove = 0; } // Now remove the last word, and replace with the dropped down one $scope.areaData = text.substr(0, position - remove) + selectedWord + text.substr(position); if(!append && $scope.dropdown.match){ position = position - $scope.dropdown.match.length + selectedWord.toString().length; } // Now reset the caret position if($element[0].selectionStart) { $timeout(function(){ $element[0].focus(); $element[0].setSelectionRange(position - remove + selectedWord.toString().length, position - remove + selectedWord.toString().length); checkTriggers(); }, 100); } } /** * Perform the "syntax" highlighting of autocomplete words that have * a cssClass specified. */ function highlightText(){ var colours = { muted: '#777', primary: '#337ab7', success: '#3c763d', info: '#31708f', warning: '#8a6d3b', danger: '#a94442' }; var text = $scope.areaData || ''; if(typeof($scope.areaConfig.autocomplete) === 'undefined' || $scope.areaConfig.autocomplete.length === 0){ return; } $scope.areaConfig.autocomplete.forEach(function(autoList){ for(var i=0; i<autoList.words.length; i++){ if(typeof(autoList.words[i]) === "string"){ text = text.replace(new RegExp("([^\\w]|\\b)("+autoList.words[i]+")([^\\w]|\\b)", 'g'), '$1<span class="'+autoList.cssClass+'" style="color:'+colours[autoList.style]+';">$2</span>$3'); }else{ text = text.replace(autoList.words[i], function(match){ return '<span class="'+autoList.cssClass+'" style="'+autoList.style+'">'+match+'</span>'; }); } } }); text = text !== '' ? text : '<span class="text-muted">' + $scope.placeholder + '</span>'; // Add to the fakeArea $scope.fakeArea = $sce.trustAsHtml(text); } /** * Check all the triggers */ function checkTriggers(){ triggerDropdownAutocomplete(); triggerDropdownAdvanced(); } /** * Trigger the advanced dropdown system, this will check * all the specified triggers in the configuration object under dropdown, * and if any of them match it will call it's list() function and add the * elements returned from it to the dropdown. */ function triggerDropdownAdvanced(){ $scope.dropdown.showFilter = false; $scope.dropdown.match = false; if(typeof($scope.areaConfig.dropdown) === 'undefined' || $scope.areaConfig.dropdown.length === 0){ return; } $scope.areaConfig.dropdown.forEach(function(element){ // Check if the trigger is under the cursor var text = $scope.areaData || '', position = getCharacterPosition(); if(typeof(element.trigger) === 'string' && element.trigger === text.substr(position - element.trigger.length, element.trigger.length)){ // The cursor is exactly at the end of the trigger element.list(function(data){ $scope.dropdown.content = data.map(function(el){ el.display = $sce.trustAsHtml(el.display); return el; }); $scope.dropdown.customSelect = element.onSelect; $scope.dropdown.mode = element.mode || 'append'; $scope.dropdown.match = ''; $scope.dropdown.showFilter = element.filter || false; $timeout(function(){ $scope.dropdown.filterElement.focus(); }, 10); }); }else if(typeof(element.trigger) === 'object'){ // I need to get the index of the last match var searchable = text.substr(0, position), match, found = false, lastPosition = 0; while ((match = element.trigger.exec(searchable)) !== null){ if(match.index === lastPosition){ break; } lastPosition = match.index; if(match.index + match[0].length === position){ found = true; break; } } if(found){ element.list(match, function(data){ $scope.dropdown.content = data.map(function(el){ el.display = $sce.trustAsHtml(el.display); return el; }); $scope.dropdown.customSelect = element.onSelect; $scope.dropdown.mode = element.mode || 'append'; $scope.dropdown.match = match[1]; $scope.dropdown.showFilter = element.filter || false; }); } } }); } /** * Set the scroll on the fake area */ function resetScroll(){ $timeout(function(){ $scope.fakeAreaElement.scrollTop($element.scrollTop()); }, 5); } /** * Trigger a simple autocomplete, this checks the last word and determines * whether any word on the autocomplete lists matches it */ function triggerDropdownAutocomplete(){ // First check with the autocomplete words (the ones that are not objects var autocomplete = [], suggestions = [], text = $scope.areaData || '', position = getCharacterPosition(), lastWord = text.substr(0, position).split(/[\s\b{}]/); // Get the last typed word lastWord = lastWord[lastWord.length-1]; $scope.areaConfig.autocomplete.forEach(function(autoList){ autoList.words.forEach(function(word){ if(typeof(word) === 'string' && autocomplete.indexOf(word) < 0){ if(lastWord.length > 0 || lastWord.length < 1 && autoList.autocompleteOnSpace){ autocomplete.push(word); } } }); }); if ($scope.areaConfig.dropdown !== undefined){ $scope.areaConfig.dropdown.forEach(function(element){ if(typeof(element.trigger) === 'string' && autocomplete.indexOf(element.trigger) < 0){ autocomplete.push(element.trigger); } }); } // Now with the list, filter and return autocomplete.forEach(function(word){ if(lastWord.length < word.length && word.toLowerCase().substr(0, lastWord.length) === lastWord.toLowerCase()){ suggestions.push({ display: $sce.trustAsHtml(word), data: null }); } }); $scope.dropdown.customSelect = null; $scope.dropdown.current = 0; $scope.dropdown.content = suggestions; } /** * Get Character count on an editable field * http://stackoverflow.com/questions/4767848/get-caret-cursor-position-in-contenteditable-area-containing-html-content */ function getCharacterPosition() { var el = $element[0]; if (typeof(el.selectionEnd) == "number") { return el.selectionEnd; } } /* +----------------------------------------------------+ * + Event Binding + * +----------------------------------------------------+ */ $element.bind('keyup click focus', function () { $timeout(function(){ $scope.trackCaret(); }, 0); }); $element.bind('keyup', function () { $timeout(function(){ checkTriggers(); }, 0); }); $element.bind('click', function () { $timeout(function(){ $scope.dropdown.content = []; $element[0].focus(); }, 0); }); $element.bind('keydown', function(event){ resetScroll(); $scope.keyboardEvents(event); }); }] }; });
fix menu bug on use keyboard
dist/smart-area.js
fix menu bug on use keyboard
<ide><path>ist/smart-area.js <ide> }, 0); <ide> }); <ide> <del> $element.bind('keyup', function () { <del> $timeout(function(){ <del> checkTriggers(); <del> }, 0); <add> $element.bind('keyup', function (event) { <add> if ([13, 38, 40, 27].indexOf(event.keyCode) === -1) { <add> $timeout(function(){ <add> checkTriggers(); <add> }, 0); <add> } <ide> }); <ide> <ide> $element.bind('click', function () {
Java
apache-2.0
424bbbc45be4a3a71df5a57067f0bac7b1d4e658
0
HanSolo/tilesfx,HanSolo/tilesfx,HanSolo/tilesfx
/* * Copyright (c) 2016 by Gerrit Grunwald * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.hansolo.tilesfx.skins; import eu.hansolo.tilesfx.Section; import eu.hansolo.tilesfx.Tile; import eu.hansolo.tilesfx.Tile.TextSize; import eu.hansolo.tilesfx.events.TileEventListener; import eu.hansolo.tilesfx.tools.Helper; import javafx.beans.InvalidationListener; import javafx.geometry.Insets; import javafx.scene.control.Skin; import javafx.scene.control.SkinBase; import javafx.scene.control.Tooltip; import javafx.scene.effect.BlurType; import javafx.scene.effect.DropShadow; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.Border; import javafx.scene.layout.BorderStroke; import javafx.scene.layout.BorderStrokeStyle; import javafx.scene.layout.BorderWidths; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import java.util.List; import java.util.Locale; /** * Created by hansolo on 19.12.16. */ public class TileSkin extends SkinBase<Tile> implements Skin<Tile> { protected static final double PREFERRED_WIDTH = 250; protected static final double PREFERRED_HEIGHT = 250; protected static final double MINIMUM_WIDTH = 50; protected static final double MINIMUM_HEIGHT = 50; protected static final double MAXIMUM_WIDTH = 1024; protected static final double MAXIMUM_HEIGHT = 1024; protected double width; protected double height; protected double size; protected Pane pane; protected double minValue; protected double maxValue; protected double range; protected double threshold; protected double stepSize; protected double angleRange; protected double angleStep; protected boolean highlightSections; protected String formatString; protected Locale locale; protected List<Section> sections; protected boolean sectionsVisible; protected TextSize textSize; protected DropShadow shadow; protected InvalidationListener sizeListener; protected TileEventListener tileEventListener; protected InvalidationListener currentValueListener; protected InvalidationListener currentTimeListener; protected InvalidationListener timeListener; protected Tile tile; protected Tooltip tooltip; // ******************** Constructors ************************************** public TileSkin(final Tile TILE) { super(TILE); tile = TILE; minValue = TILE.getMinValue(); maxValue = TILE.getMaxValue(); range = TILE.getRange(); threshold = TILE.getThreshold(); stepSize = PREFERRED_WIDTH / range; angleRange = Helper.clamp(90.0, 180.0, tile.getAngleRange()); angleStep = angleRange / range; formatString = new StringBuilder("%.").append(Integer.toString(TILE.getDecimals())).append("f").toString(); locale = TILE.getLocale(); sections = TILE.getSections(); sectionsVisible = TILE.getSectionsVisible(); highlightSections = tile.isHighlightSections(); textSize = tile.getTextSize(); sizeListener = o -> handleEvents("RESIZE"); tileEventListener = e -> handleEvents(e.getEventType().name()); currentValueListener = o -> handleCurrentValue(tile.getCurrentValue()); tooltip = new Tooltip(tile.getTooltipText()); initGraphics(); registerListeners(); } // ******************** Initialization ************************************ protected void initGraphics() { // Set initial size if (Double.compare(tile.getPrefWidth(), 0.0) <= 0 || Double.compare(tile.getPrefHeight(), 0.0) <= 0 || Double.compare(tile.getWidth(), 0.0) <= 0 || Double.compare(tile.getHeight(), 0.0) <= 0) { if (tile.getPrefWidth() > 0 && tile.getPrefHeight() > 0) { tile.setPrefSize(tile.getPrefWidth(), tile.getPrefHeight()); } else { tile.setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT); } } shadow = new DropShadow(BlurType.TWO_PASS_BOX, Color.rgb(0, 0, 0, 0.65), 3, 0, 0, 0); pane = new Pane(); pane.setBorder(new Border(new BorderStroke(tile.getBorderColor(), BorderStrokeStyle.SOLID, new CornerRadii(PREFERRED_WIDTH * 0.025), new BorderWidths(tile.getBorderWidth())))); pane.setBackground(new Background(new BackgroundFill(tile.getBackgroundColor(), new CornerRadii(PREFERRED_WIDTH * 0.025), Insets.EMPTY))); Tooltip.install(pane, tooltip); getChildren().setAll(pane); } protected void registerListeners() { tile.widthProperty().addListener(sizeListener); tile.heightProperty().addListener(sizeListener); tile.setOnTileEvent(tileEventListener); tile.currentValueProperty().addListener(currentValueListener); } // ******************** Methods ******************************************* @Override protected double computeMinWidth(final double HEIGHT, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MINIMUM_WIDTH; } @Override protected double computeMinHeight(final double WIDTH, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MINIMUM_HEIGHT; } @Override protected double computePrefWidth(final double HEIGHT, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return super.computePrefWidth(HEIGHT, TOP, RIGHT, BOTTOM, LEFT); } @Override protected double computePrefHeight(final double WIDTH, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return super.computePrefHeight(WIDTH, TOP, RIGHT, BOTTOM, LEFT); } @Override protected double computeMaxWidth(final double HEIGHT, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MAXIMUM_WIDTH; } @Override protected double computeMaxHeight(final double WIDTH, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MAXIMUM_HEIGHT; } protected Pane getPane() { return pane; } protected void handleEvents(final String EVENT_TYPE) { if ("RESIZE".equals(EVENT_TYPE)) { resize(); redraw(); } else if ("REDRAW".equals(EVENT_TYPE)) { redraw(); } else if ("RECALC".equals(EVENT_TYPE)) { minValue = tile.getMinValue(); maxValue = tile.getMaxValue(); range = tile.getRange(); threshold = tile.getThreshold(); stepSize = size / range; angleRange = Helper.clamp(90.0, 180.0, tile.getAngleRange()); angleStep = angleRange / range; highlightSections = tile.isHighlightSections(); redraw(); handleCurrentValue(tile.getCurrentValue()); } else if ("SECTION".equals(EVENT_TYPE)) { sections = tile.getSections(); } else if ("TOOLTIP_TEXT".equals(EVENT_TYPE)) { tooltip.setText(tile.getTooltipText()); if (tile.getTooltipText().isEmpty()) { Tooltip.uninstall(pane, tooltip); } else { Tooltip.install(pane, tooltip); } } }; protected void handleCurrentValue(final double VALUE) {}; @Override public void dispose() { tile.widthProperty().removeListener(sizeListener); tile.heightProperty().removeListener(sizeListener); tile.removeTileEventListener(tileEventListener); tile.currentValueProperty().removeListener(currentValueListener); tile = null; } // ******************** Resizing ****************************************** protected void resizeDynamicText() {}; protected void resizeStaticText() {}; protected void resize() { width = tile.getWidth() - tile.getInsets().getLeft() - tile.getInsets().getRight(); height = tile.getHeight() - tile.getInsets().getTop() - tile.getInsets().getBottom(); size = width < height ? width : height; stepSize = width / range; shadow.setRadius(size * 0.012); if (width > 0 && height > 0) { //pane.setMaxSize(size, size); //pane.relocate((width - size) * 0.5, (height - size) * 0.5); pane.setMaxSize(width, height); pane.setPrefSize(width, height); resizeStaticText(); resizeDynamicText(); } }; protected void redraw() { pane.setBorder(new Border(new BorderStroke(tile.getBorderColor(), BorderStrokeStyle.SOLID, tile.getRoundedCorners() ? new CornerRadii(size * 0.025) : CornerRadii.EMPTY, new BorderWidths(tile.getBorderWidth() / PREFERRED_WIDTH * size)))); pane.setBackground(new Background(new BackgroundFill(tile.getBackgroundColor(), tile.getRoundedCorners() ? new CornerRadii(size * 0.025) : CornerRadii.EMPTY, Insets.EMPTY))); locale = tile.getLocale(); formatString = new StringBuilder("%.").append(Integer.toString(tile.getDecimals())).append("f").toString(); sectionsVisible = tile.getSectionsVisible(); textSize = tile.getTextSize(); }; }
src/main/java/eu/hansolo/tilesfx/skins/TileSkin.java
/* * Copyright (c) 2016 by Gerrit Grunwald * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.hansolo.tilesfx.skins; import eu.hansolo.tilesfx.Section; import eu.hansolo.tilesfx.Tile; import eu.hansolo.tilesfx.Tile.TextSize; import eu.hansolo.tilesfx.events.TileEventListener; import eu.hansolo.tilesfx.tools.Helper; import javafx.beans.InvalidationListener; import javafx.geometry.Insets; import javafx.scene.control.Skin; import javafx.scene.control.SkinBase; import javafx.scene.control.Tooltip; import javafx.scene.effect.BlurType; import javafx.scene.effect.DropShadow; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.Border; import javafx.scene.layout.BorderStroke; import javafx.scene.layout.BorderStrokeStyle; import javafx.scene.layout.BorderWidths; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import java.util.List; import java.util.Locale; /** * Created by hansolo on 19.12.16. */ public class TileSkin extends SkinBase<Tile> implements Skin<Tile> { protected static final double PREFERRED_WIDTH = 250; protected static final double PREFERRED_HEIGHT = 250; protected static final double MINIMUM_WIDTH = 50; protected static final double MINIMUM_HEIGHT = 50; protected static final double MAXIMUM_WIDTH = 1024; protected static final double MAXIMUM_HEIGHT = 1024; protected double width; protected double height; protected double size; protected Pane pane; protected double minValue; protected double maxValue; protected double range; protected double threshold; protected double stepSize; protected double angleRange; protected double angleStep; protected boolean highlightSections; protected String formatString; protected Locale locale; protected List<Section> sections; protected boolean sectionsVisible; protected TextSize textSize; protected DropShadow shadow; protected InvalidationListener sizeListener; protected TileEventListener tileEventListener; protected InvalidationListener currentValueListener; protected InvalidationListener currentTimeListener; protected InvalidationListener timeListener; protected Tile tile; protected Tooltip tooltip; // ******************** Constructors ************************************** public TileSkin(final Tile TILE) { super(TILE); tile = TILE; minValue = TILE.getMinValue(); maxValue = TILE.getMaxValue(); range = TILE.getRange(); threshold = TILE.getThreshold(); stepSize = PREFERRED_WIDTH / range; angleRange = Helper.clamp(90.0, 180.0, tile.getAngleRange()); angleStep = angleRange / range; formatString = new StringBuilder("%.").append(Integer.toString(TILE.getDecimals())).append("f").toString(); locale = TILE.getLocale(); sections = TILE.getSections(); sectionsVisible = TILE.getSectionsVisible(); highlightSections = tile.isHighlightSections(); textSize = tile.getTextSize(); sizeListener = o -> handleEvents("RESIZE"); tileEventListener = e -> handleEvents(e.getEventType().name()); currentValueListener = o -> handleCurrentValue(tile.getCurrentValue()); tooltip = new Tooltip(tile.getTooltipText()); initGraphics(); registerListeners(); } // ******************** Initialization ************************************ protected void initGraphics() { // Set initial size if (Double.compare(tile.getPrefWidth(), 0.0) <= 0 || Double.compare(tile.getPrefHeight(), 0.0) <= 0 || Double.compare(tile.getWidth(), 0.0) <= 0 || Double.compare(tile.getHeight(), 0.0) <= 0) { if (tile.getPrefWidth() > 0 && tile.getPrefHeight() > 0) { tile.setPrefSize(tile.getPrefWidth(), tile.getPrefHeight()); } else { tile.setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT); } } shadow = new DropShadow(BlurType.TWO_PASS_BOX, Color.rgb(0, 0, 0, 0.65), 3, 0, 0, 0); pane = new Pane(); pane.setBorder(new Border(new BorderStroke(tile.getBorderColor(), BorderStrokeStyle.SOLID, new CornerRadii(PREFERRED_WIDTH * 0.025), new BorderWidths(tile.getBorderWidth())))); pane.setBackground(new Background(new BackgroundFill(tile.getBackgroundColor(), new CornerRadii(PREFERRED_WIDTH * 0.025), Insets.EMPTY))); Tooltip.install(pane, tooltip); getChildren().setAll(pane); } protected void registerListeners() { tile.widthProperty().addListener(sizeListener); tile.heightProperty().addListener(sizeListener); tile.setOnTileEvent(tileEventListener); tile.currentValueProperty().addListener(currentValueListener); } // ******************** Methods ******************************************* @Override protected double computeMinWidth(final double HEIGHT, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MINIMUM_WIDTH; } @Override protected double computeMinHeight(final double WIDTH, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MINIMUM_HEIGHT; } @Override protected double computePrefWidth(final double HEIGHT, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return super.computePrefWidth(HEIGHT, TOP, RIGHT, BOTTOM, LEFT); } @Override protected double computePrefHeight(final double WIDTH, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return super.computePrefHeight(WIDTH, TOP, RIGHT, BOTTOM, LEFT); } @Override protected double computeMaxWidth(final double HEIGHT, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MAXIMUM_WIDTH; } @Override protected double computeMaxHeight(final double WIDTH, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MAXIMUM_HEIGHT; } protected Pane getPane() { return pane; } protected void handleEvents(final String EVENT_TYPE) { if ("RESIZE".equals(EVENT_TYPE)) { resize(); redraw(); } else if ("REDRAW".equals(EVENT_TYPE)) { redraw(); } else if ("RECALC".equals(EVENT_TYPE)) { minValue = tile.getMinValue(); maxValue = tile.getMaxValue(); range = tile.getRange(); threshold = tile.getThreshold(); stepSize = size / range; angleRange = Helper.clamp(90.0, 180.0, tile.getAngleRange()); angleStep = angleRange / range; highlightSections = tile.isHighlightSections(); redraw(); handleCurrentValue(tile.getCurrentValue()); } else if ("SECTION".equals(EVENT_TYPE)) { sections = tile.getSections(); } else if ("TOOLTIP_TEXT".equals(EVENT_TYPE)) { System.out.println(tile.getTooltipText()); tooltip.setText(tile.getTooltipText()); if (tile.getTooltipText().isEmpty()) { Tooltip.uninstall(pane, tooltip); } else { Tooltip.install(pane, tooltip); } } }; protected void handleCurrentValue(final double VALUE) {}; @Override public void dispose() { tile.widthProperty().removeListener(sizeListener); tile.heightProperty().removeListener(sizeListener); tile.removeTileEventListener(tileEventListener); tile.currentValueProperty().removeListener(currentValueListener); tile = null; } // ******************** Resizing ****************************************** protected void resizeDynamicText() {}; protected void resizeStaticText() {}; protected void resize() { width = tile.getWidth() - tile.getInsets().getLeft() - tile.getInsets().getRight(); height = tile.getHeight() - tile.getInsets().getTop() - tile.getInsets().getBottom(); size = width < height ? width : height; stepSize = width / range; shadow.setRadius(size * 0.012); if (width > 0 && height > 0) { //pane.setMaxSize(size, size); //pane.relocate((width - size) * 0.5, (height - size) * 0.5); pane.setMaxSize(width, height); pane.setPrefSize(width, height); resizeStaticText(); resizeDynamicText(); } }; protected void redraw() { pane.setBorder(new Border(new BorderStroke(tile.getBorderColor(), BorderStrokeStyle.SOLID, tile.getRoundedCorners() ? new CornerRadii(size * 0.025) : CornerRadii.EMPTY, new BorderWidths(tile.getBorderWidth() / PREFERRED_WIDTH * size)))); pane.setBackground(new Background(new BackgroundFill(tile.getBackgroundColor(), tile.getRoundedCorners() ? new CornerRadii(size * 0.025) : CornerRadii.EMPTY, Insets.EMPTY))); locale = tile.getLocale(); formatString = new StringBuilder("%.").append(Integer.toString(tile.getDecimals())).append("f").toString(); sectionsVisible = tile.getSectionsVisible(); textSize = tile.getTextSize(); }; }
Removed System.out.println
src/main/java/eu/hansolo/tilesfx/skins/TileSkin.java
Removed System.out.println
<ide><path>rc/main/java/eu/hansolo/tilesfx/skins/TileSkin.java <ide> } else if ("SECTION".equals(EVENT_TYPE)) { <ide> sections = tile.getSections(); <ide> } else if ("TOOLTIP_TEXT".equals(EVENT_TYPE)) { <del> System.out.println(tile.getTooltipText()); <ide> tooltip.setText(tile.getTooltipText()); <ide> if (tile.getTooltipText().isEmpty()) { <ide> Tooltip.uninstall(pane, tooltip);
Java
apache-2.0
8a104ea09182f96768b2238682944e497ea045af
0
jzadeh/Aktaion,jzadeh/Aktaion
package com.aktaion.shell; import com.aktaion.ml.weka.randomforest.ClassLabel; import com.aktaion.ml.weka.randomforest.RandomForestLogic; import com.aktaion.ml.weka.randomforest.WekaUtilities; import scala.Option; import java.util.Scanner; public class UserInteractionLogic { private static void pressAnyKeyToContinue() { System.out.println("Press any key to continue..."); try { System.in.read(); } catch (Exception e) { } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("*************************"); System.out.println("*************************"); System.out.println("** Aktaion Version 0.1 **"); System.out.println("*************************"); System.out.println("*************************"); System.out.println("1: Analyze Bro HTTP Sample"); System.out.println("2: Analyze PCAP Sample (Bro must be installed)"); System.out.println("3: Demo (Unix/OS X System)"); System.out.print("Enter Execution Choice [1-3]: "); int userChoice = scanner.nextInt(); if (userChoice == 1) { System.out.print("Specify Input Path: "); String fileInputPath = scanner.next(); System.out.print("Specify Output Path: "); String fileOutputPath = scanner.next(); } else if (userChoice == 2) { System.out.print("Specify Input PCAP Path: "); String fileInputPath = scanner.next(); } else if (userChoice == 3) { //does not work on windows determines where the path to the Jar is String dataPath = CommandLineUtils.tryToFindPathToDataInSourceCode(4); /** * Step 1: (Only Need to Perform Once) * * Train a model by scoring a whole directory of files * in this case we have extracts from 300+ exploit samples * with a .webgateway extension */ String trainDirectory = dataPath + "proxyData/exploitData/"; String trainDataOutFileName = dataPath + "demoData/demoExploitData.arff"; String saveModelFileName = dataPath + "demoData/model.test"; WekaUtilities.extractDirectoryToWekaFormat(trainDirectory, trainDataOutFileName, ".webgateway", ClassLabel.EXPLOIT(), 5); RandomForestLogic.trainWekaRandomForest(trainDataOutFileName, saveModelFileName, 10, 100); pressAnyKeyToContinue(); /** * Step 2: get a PCAP file to score and convert it to bro logs */ String demoInputFileName = dataPath + "demoData/demoExploitPcap.pcap"; //change to whatever pcap we want to score String extractedFile = CommandLineUtils.extractBroFilesFromPcap(demoInputFileName); pressAnyKeyToContinue(); /** * Step 3a: Score Malicious File Extract the IOCs from the scored file */ Option<RandomForestLogic.IocsExtracted> output = RandomForestLogic.scoreBroHttpFile(extractedFile, saveModelFileName, 5); pressAnyKeyToContinue(); /** * Step 3b: Score Benign Traffic File */ // RandomForestLogic.scoreBroHttpFile(dataPath + "demoData/BENIGNEATOhttp.log", saveModelFileName,5); //todo train the model on benign traffic /** * Step 4: Pass the ioc data to an active defense script for * automated Group Policy Object generation in Active Directory * (see https://technet.microsoft.com/en-us/library/hh147307(v=ws.10).aspx for an intro) */ PythonCommandLineLogic.passIocsToActiveDefenseScript(output, 4); } } }
src/main/java/com/aktaion/shell/UserInteractionLogic.java
package com.aktaion.shell; import com.aktaion.ml.weka.randomforest.ClassLabel; import com.aktaion.ml.weka.randomforest.RandomForestLogic; import com.aktaion.ml.weka.randomforest.WekaUtilities; import scala.Option; import java.util.Scanner; public class UserInteractionLogic { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("*************************"); System.out.println("*************************"); System.out.println("** Aktaion Version 0.1 **"); System.out.println("*************************"); System.out.println("*************************"); System.out.println("1: Analyze Bro HTTP Sample"); System.out.println("2: Analyze PCAP Sample (Bro must be installed)"); System.out.println("3: Demo (Unix/OS X System)"); System.out.print("Enter Execution Choice [1-3]: "); int userChoice = scanner.nextInt(); if (userChoice == 1) { System.out.print("Specify Input Path: "); String fileInputPath = scanner.next(); System.out.print("Specify Output Path: "); String fileOutputPath = scanner.next(); } else if (userChoice == 2) { System.out.print("Specify Input PCAP Path: "); String fileInputPath = scanner.next(); //CommandLineUtils.executeBroSimpleDebugLogic(fileInputPath); } else if (userChoice == 3) { //does not work on windows determines where the path to the Jar is String dataPath = CommandLineUtils.tryToFindPathToDataInSourceCode(4); /** * Step 1: (Only Need to Perform Once) * * Train a model by scoring a whole directory of files * in this case we have extracts from 300+ exploit samples * with a .webgateway extension */ String trainDirectory = dataPath + "proxyData/exploitData/"; String trainDataOutFileName = dataPath + "demoData/demoExploitData.arff"; String saveModelFileName = dataPath + "demoData/model.test"; WekaUtilities.extractDirectoryToWekaFormat(trainDirectory, trainDataOutFileName, ".webgateway", ClassLabel.EXPLOIT(), 5); RandomForestLogic.trainWekaRandomForest(trainDataOutFileName, saveModelFileName, 10, 100); /** * Step 2: get a PCAP file to score and convert it to bro logs */ String demoInputFileName = dataPath + "demoData/demoExploitPcap.pcap"; //change to whatever pcap we want to score String extractedFile = CommandLineUtils.extractBroFilesFromPcap(demoInputFileName); /** * Step 3a: Score Malicious File Extract the IOCs from the scored file */ Option<RandomForestLogic.IocsExtracted> output = RandomForestLogic.scoreBroHttpFile(extractedFile, saveModelFileName, 5); /** * Step 3b: Score Benign Traffic File */ // RandomForestLogic.scoreBroHttpFile(dataPath + "demoData/BENIGNEATOhttp.log", saveModelFileName,5); //todo train the model on benign traffic /** * Step 4: Pass the ioc data to an active defense script for * automated Group Policy Object generation in Active Directory * (see https://technet.microsoft.com/en-us/library/hh147307(v=ws.10).aspx for an intro) */ PythonCommandLineLogic.passIocsToActiveDefenseScript(output,4); } } }
Break up demo into steps.
src/main/java/com/aktaion/shell/UserInteractionLogic.java
Break up demo into steps.
<ide><path>rc/main/java/com/aktaion/shell/UserInteractionLogic.java <ide> import java.util.Scanner; <ide> <ide> public class UserInteractionLogic { <add> <add> private static void pressAnyKeyToContinue() { <add> System.out.println("Press any key to continue..."); <add> try { <add> System.in.read(); <add> } catch (Exception e) { <add> } <add> } <ide> <ide> public static void main(String[] args) { <ide> Scanner scanner = new Scanner(System.in); <ide> } else if (userChoice == 2) { <ide> System.out.print("Specify Input PCAP Path: "); <ide> String fileInputPath = scanner.next(); <del> //CommandLineUtils.executeBroSimpleDebugLogic(fileInputPath); <ide> } else if (userChoice == 3) { <del> <ide> //does not work on windows determines where the path to the Jar is <ide> String dataPath = CommandLineUtils.tryToFindPathToDataInSourceCode(4); <ide> <ide> ".webgateway", <ide> ClassLabel.EXPLOIT(), 5); <ide> RandomForestLogic.trainWekaRandomForest(trainDataOutFileName, saveModelFileName, 10, 100); <del> <add> pressAnyKeyToContinue(); <ide> <ide> /** <ide> * Step 2: get a PCAP file to score and convert it to bro logs <ide> */ <ide> String demoInputFileName = dataPath + "demoData/demoExploitPcap.pcap"; //change to whatever pcap we want to score <ide> String extractedFile = CommandLineUtils.extractBroFilesFromPcap(demoInputFileName); <add> pressAnyKeyToContinue(); <ide> <ide> /** <ide> * Step 3a: Score Malicious File Extract the IOCs from the scored file <ide> */ <ide> Option<RandomForestLogic.IocsExtracted> output = RandomForestLogic.scoreBroHttpFile(extractedFile, saveModelFileName, 5); <add> pressAnyKeyToContinue(); <ide> <ide> /** <ide> * Step 3b: Score Benign Traffic File <ide> */ <del> // RandomForestLogic.scoreBroHttpFile(dataPath + "demoData/BENIGNEATOhttp.log", saveModelFileName,5); <del> //todo train the model on benign traffic <del> <add> // RandomForestLogic.scoreBroHttpFile(dataPath + "demoData/BENIGNEATOhttp.log", saveModelFileName,5); <add> //todo train the model on benign traffic <ide> <ide> /** <ide> * Step 4: Pass the ioc data to an active defense script for <ide> * automated Group Policy Object generation in Active Directory <ide> * (see https://technet.microsoft.com/en-us/library/hh147307(v=ws.10).aspx for an intro) <ide> */ <del> <del> PythonCommandLineLogic.passIocsToActiveDefenseScript(output,4); <add> PythonCommandLineLogic.passIocsToActiveDefenseScript(output, 4); <add> } <add> } <ide> <ide> <del> } <del> } <ide> }
Java
mit
024e13b10c2be4d06795216774cabe9282879e77
0
GloomyFolken/HookLib
package gloomyfolken.hooklib.asm; import cpw.mods.fml.relauncher.FMLRelaunchLog; import net.minecraft.launchwrapper.IClassTransformer; import org.objectweb.asm.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; public class HookClassTransformer implements IClassTransformer { public static HookClassTransformer instance; private HashMap<String, List<AsmHook>> hooksMap = new HashMap<String, List<AsmHook>>(); public HookClassTransformer(){ instance = this; } public void registerHook(AsmHook hook){ if (hooksMap.containsKey(hook.getTargetClassName())){ hooksMap.get(hook.getTargetClassName()).add(hook); } else { List<AsmHook> list = new ArrayList<AsmHook>(2); list.add(hook); hooksMap.put(hook.getTargetClassName(), list); } } @Override public byte[] transform(String name, String newName, byte[] bytecode) { List<AsmHook> hooks = hooksMap.get(newName); if (hooks != null){ try { info("Injecting hooks into class " + newName); int numHooks = hooks.size(); int majorVersion = ((bytecode[6]&0xFF)<<8) | (bytecode[7]&0xFF); int minorVersion = ((bytecode[4]&0xFF)<<8) | (bytecode[5]&0xFF); boolean java7 = majorVersion > 50; if (java7){ warning("Bytecode version of class " + newName + " is " + majorVersion + "." + minorVersion + "."); warning("This is Java 1.7+, whereas Minecraft works on Java 1.6 (bytecode version 50)."); warning("Enabling COMPUTE_FRAMES, but it probably will crash minecraft on the server side."); warning("If you are in an MCP environment, you should better set javac version to 1.6."); warning("If you are not, something is going completly wrong."); } ClassReader cr = new ClassReader(bytecode); ClassWriter cw = new ClassWriter(java7 ? ClassWriter.COMPUTE_FRAMES : 0); HookInjectorClassWriter hooksWriter = new HookInjectorClassWriter(cw, hooks); cr.accept(hooksWriter, java7 ? ClassReader.SKIP_FRAMES : ClassReader.EXPAND_FRAMES); int numInjectedHooks = numHooks - hooksWriter.hooks.size(); info("Successfully injected " + numInjectedHooks + " hook" + (numInjectedHooks == 1 ? "" : "s")); for (AsmHook notInjected : hooksWriter.hooks){ warning("Can not found target method of hook " + notInjected); } hooksMap.remove(newName); return cw.toByteArray(); } catch (Exception e){ severe("A problem has occured during transformation of class " + newName + "."); severe("No hook will be injected into this class."); severe("Attached hooks:"); for (AsmHook hook : hooks) { severe(hook.toString()); } severe("Stack trace:"); e.printStackTrace(); } } return bytecode; } private static final String LOG_PREFIX = "[HOOKLIB] "; private void severe(String msg){ FMLRelaunchLog.severe(LOG_PREFIX + msg); } private void info(String msg){ FMLRelaunchLog.info(LOG_PREFIX + msg); } private void warning(String msg){ FMLRelaunchLog.warning(LOG_PREFIX + msg); } private static class HookInjectorClassWriter extends ClassVisitor { List<AsmHook> hooks; public HookInjectorClassWriter(ClassWriter cv, List<AsmHook> hooks) { super(Opcodes.ASM4, cv); this.hooks = hooks; } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); Iterator<AsmHook> it = hooks.iterator(); while (it.hasNext()) { AsmHook hook = it.next(); if (name.equals(hook.getTargetMethodName(HookLibPlugin.obf)) && desc.equals(hook.getTargetMethodDescription())){ mv = hook.getInjectorFactory().createHookInjector(mv, access, name, desc, hook); it.remove(); } } return mv; } } }
src/minecraft/gloomyfolken/hooklib/asm/HookClassTransformer.java
package gloomyfolken.hooklib.asm; import cpw.mods.fml.relauncher.FMLRelaunchLog; import gloomyfolken.mods.effects.asm.EffectsMod; import net.minecraft.launchwrapper.IClassTransformer; import org.objectweb.asm.*; import org.objectweb.asm.tree.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; public class HookClassTransformer implements IClassTransformer { public static HookClassTransformer instance; private HashMap<String, List<AsmHook>> hooksMap = new HashMap<String, List<AsmHook>>(); public HookClassTransformer(){ instance = this; } public void registerHook(AsmHook hook){ if (hooksMap.containsKey(hook.getTargetClassName())){ hooksMap.get(hook.getTargetClassName()).add(hook); } else { List<AsmHook> list = new ArrayList<AsmHook>(2); list.add(hook); hooksMap.put(hook.getTargetClassName(), list); } } @Override public byte[] transform(String name, String newName, byte[] bytecode) { List<AsmHook> hooks = hooksMap.get(newName); if (hooks != null){ try { info("Injecting hooks into class " + newName); int numHooks = hooks.size(); int majorVersion = ((bytecode[6]&0xFF)<<8) | (bytecode[7]&0xFF); int minorVersion = ((bytecode[4]&0xFF)<<8) | (bytecode[5]&0xFF); boolean java7 = majorVersion > 50; if (java7){ warning("Bytecode version of class " + newName + " is " + majorVersion + "." + minorVersion + "."); warning("This is Java 1.7+, whereas Minecraft works on Java 1.6 (bytecode version 50)."); warning("Enabling COMPUTE_FRAMES, but it probably will crash minecraft on the server side."); warning("If you are in an MCP environment, you should better set javac version to 1.6."); warning("If you are not, something is going completly wrong."); } ClassReader cr = new ClassReader(bytecode); ClassWriter cw = new ClassWriter(java7 ? ClassWriter.COMPUTE_FRAMES : 0); HookInjectorClassWriter hooksWriter = new HookInjectorClassWriter(cw, hooks); cr.accept(hooksWriter, java7 ? ClassReader.SKIP_FRAMES : ClassReader.EXPAND_FRAMES); int numInjectedHooks = numHooks - hooksWriter.hooks.size(); info("Successfully injected " + numInjectedHooks + " hook" + (numInjectedHooks == 1 ? "" : "s")); for (AsmHook notInjected : hooksWriter.hooks){ warning("Can not found target method of hook " + notInjected); } hooksMap.remove(newName); return cw.toByteArray(); } catch (Exception e){ severe("A problem has occured during transformation of class " + newName + "."); severe("No hook will be injected into this class."); severe("Attached hooks:"); for (AsmHook hook : hooks) { severe(hook.toString()); } severe("Stack trace:"); e.printStackTrace(); } } return bytecode; } private void printNode(AbstractInsnNode node) { if (node.getType() == 5) { MethodInsnNode mnode = (MethodInsnNode) node; System.out.println("MethodInsnNode: opcode=" + mnode.getOpcode() + ", owner=" + mnode.owner + ", name=" + mnode.name + ", desc=" + mnode.desc); } else if (node.getType() == 7) { JumpInsnNode jnode = (JumpInsnNode) node; System.out.println("JumpInsnNode: opcode=" + jnode.getOpcode() + ", label=" + jnode.label.getLabel()); } else if (node.getType() == 0) { InsnNode inode = (InsnNode) node; System.out.println("InsnNode: opcode=" + inode.getOpcode()); } else if (node.getType() == 8) { LabelNode lnode = (LabelNode) node; System.out.println("LabelNode: opcode= " + lnode.getOpcode() + ", label=" + lnode.getLabel().toString()); } else if (node.getType() == 15) { System.out.println("LineNumberNode, opcode=" + node.getOpcode()); } else if (node instanceof FrameNode) { FrameNode fnode = (FrameNode) node; String out = "FrameNode: opcode=" + fnode.getOpcode() + ", type=" + fnode.type + ", nLocal=" + (fnode.local == null ? -1 : fnode.local.size()) + ", local="; if (fnode.local != null) { for (Object obj : fnode.local) { out += obj == null ? "null" : obj.toString() + ";"; } } else { out += null; } out += ", nstack=" + (fnode.stack == null ? -1 : fnode.stack.size()) + ", stack="; if (fnode.stack != null) { for (Object obj : fnode.stack) { out += obj == null ? "null" : obj.toString() + ";"; } } else { out += null; } System.out.println(out); } else if (node.getType() == 2) { VarInsnNode vnode = (VarInsnNode) node; System.out.println("VarInsnNode: opcode=" + vnode.getOpcode() + ", var=" + vnode.var); } else if (node.getType() == 9) { LdcInsnNode lnode = (LdcInsnNode) node; System.out.println("LdcInsnNode: opcode=" + lnode.getOpcode() + ", cst=" + lnode.cst); } else if (node.getType() == 4) { FieldInsnNode fnode = (FieldInsnNode) node; System.out.println("FieldInsnNode: opcode=" + fnode.getOpcode() + ", owner=" + fnode.owner + ", name=" + fnode.name + ", desc=" + fnode.desc); } else if (node.getType() == 3) { TypeInsnNode tnode = (TypeInsnNode) node; System.out.println("TypeInsnNode: opcode=" + tnode.getOpcode() + ", desc=" + tnode.desc); } else { printUnexpectedNode(node); } } private void printUnexpectedNode(AbstractInsnNode node) { EffectsMod.log("class=" + node.getClass().getCanonicalName() + ", type=" + node.getType() + ", opcode=" + node.getOpcode()); } private static final String LOG_PREFIX = "[HOOKLIB] "; private void severe(String msg){ FMLRelaunchLog.severe(LOG_PREFIX + msg); } private void info(String msg){ FMLRelaunchLog.info(LOG_PREFIX + msg); } private void warning(String msg){ FMLRelaunchLog.warning(LOG_PREFIX + msg); } private static class HookInjectorClassWriter extends ClassVisitor { List<AsmHook> hooks; public HookInjectorClassWriter(ClassWriter cv, List<AsmHook> hooks) { super(Opcodes.ASM4, cv); this.hooks = hooks; } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); Iterator<AsmHook> it = hooks.iterator(); while (it.hasNext()) { AsmHook hook = it.next(); if (name.equals(hook.getTargetMethodName(HookLibPlugin.obf)) && desc.equals(hook.getTargetMethodDescription())){ mv = hook.getInjectorFactory().createHookInjector(mv, access, name, desc, hook); it.remove(); } } return mv; } } }
И опять я забыл выпилить методы на дебаг-вывод..)
src/minecraft/gloomyfolken/hooklib/asm/HookClassTransformer.java
И опять я забыл выпилить методы на дебаг-вывод..)
<ide><path>rc/minecraft/gloomyfolken/hooklib/asm/HookClassTransformer.java <ide> package gloomyfolken.hooklib.asm; <ide> <ide> import cpw.mods.fml.relauncher.FMLRelaunchLog; <del>import gloomyfolken.mods.effects.asm.EffectsMod; <ide> import net.minecraft.launchwrapper.IClassTransformer; <ide> import org.objectweb.asm.*; <del>import org.objectweb.asm.tree.*; <ide> <ide> import java.util.ArrayList; <ide> import java.util.HashMap; <ide> } <ide> return bytecode; <ide> } <del> private void printNode(AbstractInsnNode node) { <del> if (node.getType() == 5) { <del> MethodInsnNode mnode = (MethodInsnNode) node; <del> System.out.println("MethodInsnNode: opcode=" + mnode.getOpcode() + ", owner=" + mnode.owner + ", name=" + mnode.name + ", desc=" <del> + mnode.desc); <del> } else if (node.getType() == 7) { <del> JumpInsnNode jnode = (JumpInsnNode) node; <del> System.out.println("JumpInsnNode: opcode=" + jnode.getOpcode() + ", label=" + jnode.label.getLabel()); <del> } else if (node.getType() == 0) { <del> InsnNode inode = (InsnNode) node; <del> System.out.println("InsnNode: opcode=" + inode.getOpcode()); <del> } else if (node.getType() == 8) { <del> LabelNode lnode = (LabelNode) node; <del> System.out.println("LabelNode: opcode= " + lnode.getOpcode() + ", label=" + lnode.getLabel().toString()); <del> } else if (node.getType() == 15) { <del> System.out.println("LineNumberNode, opcode=" + node.getOpcode()); <del> } else if (node instanceof FrameNode) { <del> FrameNode fnode = (FrameNode) node; <del> String out = "FrameNode: opcode=" + fnode.getOpcode() + ", type=" + fnode.type + ", nLocal=" <del> + (fnode.local == null ? -1 : fnode.local.size()) + ", local="; <del> if (fnode.local != null) { <del> for (Object obj : fnode.local) { <del> out += obj == null ? "null" : obj.toString() + ";"; <del> } <del> } else { <del> out += null; <del> } <del> out += ", nstack=" + (fnode.stack == null ? -1 : fnode.stack.size()) + ", stack="; <del> if (fnode.stack != null) { <del> for (Object obj : fnode.stack) { <del> out += obj == null ? "null" : obj.toString() + ";"; <del> } <del> } else { <del> out += null; <del> } <del> System.out.println(out); <del> } else if (node.getType() == 2) { <del> VarInsnNode vnode = (VarInsnNode) node; <del> System.out.println("VarInsnNode: opcode=" + vnode.getOpcode() + ", var=" + vnode.var); <del> } else if (node.getType() == 9) { <del> LdcInsnNode lnode = (LdcInsnNode) node; <del> System.out.println("LdcInsnNode: opcode=" + lnode.getOpcode() + ", cst=" + lnode.cst); <del> } else if (node.getType() == 4) { <del> FieldInsnNode fnode = (FieldInsnNode) node; <del> System.out.println("FieldInsnNode: opcode=" + fnode.getOpcode() + ", owner=" + fnode.owner + ", name=" + fnode.name + ", desc=" <del> + fnode.desc); <del> } else if (node.getType() == 3) { <del> TypeInsnNode tnode = (TypeInsnNode) node; <del> System.out.println("TypeInsnNode: opcode=" + tnode.getOpcode() + ", desc=" + tnode.desc); <del> } else { <del> printUnexpectedNode(node); <del> } <del> } <del> <del> private void printUnexpectedNode(AbstractInsnNode node) { <del> EffectsMod.log("class=" + node.getClass().getCanonicalName() + ", type=" + node.getType() + ", opcode=" + node.getOpcode()); <del> } <ide> <ide> private static final String LOG_PREFIX = "[HOOKLIB] "; <ide>
Java
mit
c4e9f3cbff38fba7bbf10c9bd2675d4f1b08f7a1
0
icode/ameba-session
package ameba.http.session; import ameba.util.Times; import org.apache.commons.codec.digest.DigestUtils; import javax.annotation.Priority; import javax.inject.Singleton; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.NewCookie; import javax.ws.rs.ext.Provider; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.UUID; /** * @author icode */ @Provider @Priority(Priorities.AUTHENTICATION - 1) @Singleton public class SessionFilter implements ContainerRequestFilter, ContainerResponseFilter { static String DEFAULT_SESSION_ID_COOKIE_KEY = "SID"; static long SESSION_TIMEOUT = Times.parseDuration("1h") * 1000; static Constructor<AbstractSession> SESSION_IMPL_CONSTRUCTOR; private static final String SET_COOKIE_KEY = SessionFilter.class.getName() + ".__SET_SESSION_COOKIE__"; @Override @SuppressWarnings("unchecked") public void filter(ContainerRequestContext requestContext) { Cookie cookie = requestContext.getCookies().get(DEFAULT_SESSION_ID_COOKIE_KEY); boolean isNew = false; if (cookie == null) { isNew = true; cookie = newCookie(requestContext); } AbstractSession session; if (SESSION_IMPL_CONSTRUCTOR != null) { try { session = SESSION_IMPL_CONSTRUCTOR.newInstance(cookie.getValue(), SESSION_TIMEOUT, isNew); } catch (InvocationTargetException e) { throw new SessionExcption("new session instance error"); } catch (InstantiationException e) { throw new SessionExcption("new session instance error"); } catch (IllegalAccessException e) { throw new SessionExcption("new session instance error"); } } else { session = new CacheSession(cookie.getValue(), SESSION_TIMEOUT, isNew); if (isNew) { session.flush(); } } if (!session.isNew() && session.isInvalid()) { cookie = newCookie(requestContext); session.setId(cookie.getValue()); session.flush(); } Session.sessionThreadLocal.set(session); } private String newSessionId() { return DigestUtils.sha1Hex(UUID.randomUUID().toString() + Math.random() + this.hashCode() + System.nanoTime()); } private NewCookie newCookie(ContainerRequestContext requestContext) { NewCookie cookie = new NewCookie( DEFAULT_SESSION_ID_COOKIE_KEY, newSessionId(), requestContext.getUriInfo().getBaseUri().getPath(), null, Cookie.DEFAULT_VERSION, null, (int) (SESSION_TIMEOUT / 1000), null, false, true); requestContext.setProperty(SET_COOKIE_KEY, cookie); return cookie; } @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { NewCookie cookie = (NewCookie) requestContext.getProperty(SET_COOKIE_KEY); if (cookie != null) responseContext.getHeaders().add("Set-Cookie", cookie.toString()); } }
src/main/java/ameba/http/session/SessionFilter.java
package ameba.http.session; import ameba.util.Times; import org.apache.commons.codec.digest.DigestUtils; import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.NewCookie; import javax.ws.rs.ext.Provider; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.UUID; /** * @author icode */ @Provider @Priority(Priorities.AUTHENTICATION - 1) public class SessionFilter implements ContainerRequestFilter, ContainerResponseFilter { static String DEFAULT_SESSION_ID_COOKIE_KEY = "SID"; static long SESSION_TIMEOUT = Times.parseDuration("1h") * 1000; static Constructor<AbstractSession> SESSION_IMPL_CONSTRUCTOR; private static final String SET_COOKIE_KEY = SessionFilter.class.getName() + ".__SET_SESSION_COOKIE__"; @Override @SuppressWarnings("unchecked") public void filter(ContainerRequestContext requestContext) { Cookie cookie = requestContext.getCookies().get(DEFAULT_SESSION_ID_COOKIE_KEY); boolean isNew = false; if (cookie == null) { isNew = true; cookie = newCookie(requestContext); } AbstractSession session; if (SESSION_IMPL_CONSTRUCTOR != null) { try { session = SESSION_IMPL_CONSTRUCTOR.newInstance(cookie.getValue(), SESSION_TIMEOUT, isNew); } catch (InvocationTargetException e) { throw new SessionExcption("new session instance error"); } catch (InstantiationException e) { throw new SessionExcption("new session instance error"); } catch (IllegalAccessException e) { throw new SessionExcption("new session instance error"); } } else { session = new CacheSession(cookie.getValue(), SESSION_TIMEOUT, isNew); if (isNew) { session.flush(); } } if (!session.isNew() && session.isInvalid()) { cookie = newCookie(requestContext); session.setId(cookie.getValue()); session.flush(); } Session.sessionThreadLocal.set(session); } private String newSessionId() { return DigestUtils.sha1Hex(UUID.randomUUID().toString() + Math.random() + this.hashCode() + System.nanoTime()); } private NewCookie newCookie(ContainerRequestContext requestContext) { NewCookie cookie = new NewCookie( DEFAULT_SESSION_ID_COOKIE_KEY, newSessionId(), requestContext.getUriInfo().getBaseUri().getPath(), null, Cookie.DEFAULT_VERSION, null, (int) (SESSION_TIMEOUT / 1000), null, false, true); requestContext.setProperty(SET_COOKIE_KEY, cookie); return cookie; } @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { NewCookie cookie = (NewCookie) requestContext.getProperty(SET_COOKIE_KEY); if (cookie != null) responseContext.getHeaders().add("Set-Cookie", cookie.toString()); } }
完成缓存实现的session
src/main/java/ameba/http/session/SessionFilter.java
完成缓存实现的session
<ide><path>rc/main/java/ameba/http/session/SessionFilter.java <ide> import org.apache.commons.codec.digest.DigestUtils; <ide> <ide> import javax.annotation.Priority; <add>import javax.inject.Singleton; <ide> import javax.ws.rs.Priorities; <ide> import javax.ws.rs.container.ContainerRequestContext; <ide> import javax.ws.rs.container.ContainerRequestFilter; <ide> */ <ide> @Provider <ide> @Priority(Priorities.AUTHENTICATION - 1) <add>@Singleton <ide> public class SessionFilter implements ContainerRequestFilter, ContainerResponseFilter { <ide> static String DEFAULT_SESSION_ID_COOKIE_KEY = "SID"; <ide> static long SESSION_TIMEOUT = Times.parseDuration("1h") * 1000;
JavaScript
apache-2.0
73427434ea2fc1b759c201676e520025c7a027bf
0
HewlettPackard/grommet,HewlettPackard/grommet,grommet/grommet,grommet/grommet,grommet/grommet,HewlettPackard/grommet
import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; import { ThemeContext as IconThemeContext } from 'grommet-icons/contexts'; import { ThemeContext } from '../../contexts'; import { FocusedContainer } from '../FocusedContainer'; import { backgroundIsDark, findScrollParents, findVisibleParent, parseMetricToNum, } from '../../utils'; import { Keyboard } from '../Keyboard'; import { StyledDrop } from './StyledDrop'; export class DropContainer extends Component { static defaultProps = { align: { top: 'top', left: 'left', }, stretch: 'width', } static getDerivedStateFromProps(nextProps, prevState) { // Since the drop background can be different from the current theme context, // we update the theme to set the dark background context. const { theme: propsTheme } = nextProps; const { theme: stateTheme, priorTheme } = prevState; const dark = backgroundIsDark(propsTheme.global.drop.background, propsTheme); if (dark === propsTheme.dark && stateTheme) { return { theme: undefined, priorTheme: undefined }; } if (dark !== propsTheme.dark && (!stateTheme || dark !== stateTheme.dark || propsTheme !== priorTheme)) { return { theme: { ...propsTheme, dark, icon: dark ? propsTheme.iconThemes.dark : propsTheme.iconThemes.light, }, priorTheme: propsTheme, }; } return null; } state = {} dropRef = React.createRef() componentDidMount() { const { restrictFocus } = this.props; this.addScrollListener(); window.addEventListener('resize', this.onResize); document.addEventListener('mousedown', this.onClickDocument); this.place(); if (restrictFocus) { findDOMNode(this.dropRef.current).focus(); } } componentDidUpdate() { this.place(); } componentWillUnmount() { this.removeScrollListener(); window.removeEventListener('resize', this.onResize); document.removeEventListener('mousedown', this.onClickDocument); } addScrollListener = () => { const { dropTarget } = this.props; this.scrollParents = findScrollParents(findDOMNode(dropTarget)); this.scrollParents.forEach(scrollParent => scrollParent.addEventListener('scroll', this.place)); } removeScrollListener = () => { this.scrollParents.forEach( scrollParent => scrollParent.removeEventListener('scroll', this.place) ); } onClickDocument = (event) => { const { dropTarget, onClickOutside } = this.props; const dropTargetNode = findDOMNode(dropTarget); const dropNode = findDOMNode(this.dropRef.current); if ( onClickOutside && dropNode && // need this for ie11 !dropTargetNode.contains(event.target) && !dropNode.contains(event.target) ) { onClickOutside(); } } onResize = () => { this.removeScrollListener(); this.addScrollListener(); this.place(); } place = () => { const { align, dropTarget, responsive, stretch, theme } = this.props; const windowWidth = window.innerWidth; const windowHeight = window.innerHeight; const target = findDOMNode(dropTarget); const container = findDOMNode(this.dropRef.current); if (container && target) { // clear prior styling container.style.left = ''; container.style.width = ''; container.style.top = ''; container.style.maxHeight = ''; // get bounds const targetRect = findVisibleParent(target).getBoundingClientRect(); const containerRect = container.getBoundingClientRect(); // determine width const width = Math.min( (stretch ? Math.max(targetRect.width, containerRect.width) : containerRect.width ), windowWidth ); // set left position let left; if (align.left) { if (align.left === 'left') { left = targetRect.left; } else if (align.left === 'right') { left = targetRect.left + targetRect.width; } } else if (align.right) { if (align.right === 'left') { left = targetRect.left - width; } else if (align.right === 'right') { left = (targetRect.left + targetRect.width) - width; } } else { left = (targetRect.left + (targetRect.width / 2)) - (width / 2); } if ((left + width) > windowWidth) { left -= ((left + width) - windowWidth); } else if (left < 0) { left = 0; } // set top position let top; let maxHeight; if (align.top) { if (align.top === 'top') { top = targetRect.top; maxHeight = Math.min(windowHeight - targetRect.top, windowHeight); } else { top = targetRect.bottom; maxHeight = Math.min( windowHeight - targetRect.bottom, windowHeight - targetRect.height ); } } else if (align.bottom) { if (align.bottom === 'bottom') { top = targetRect.bottom - containerRect.height; maxHeight = Math.max(targetRect.bottom, 0); } else { top = targetRect.top - containerRect.height; maxHeight = Math.max(targetRect.top, 0); } } else { top = (targetRect.top + (targetRect.height / 2)) - (containerRect.height / 2); } // if we can't fit it all, see if there's more room the other direction if (containerRect.height > maxHeight) { // We need more room than we have. if (align.top && top > (windowHeight / 2)) { // We put it below, but there's more room above, put it above if (align.top === 'bottom') { if (responsive) { top = Math.max(targetRect.top - containerRect.height, 0); } maxHeight = targetRect.top; } else { if (responsive) { top = Math.max(targetRect.bottom - containerRect.height, 0); } maxHeight = targetRect.bottom; } } else if (align.bottom && maxHeight < (windowHeight / 2)) { // We put it above but there's more room below, put it below if (align.bottom === 'bottom') { if (responsive) { top = targetRect.top; } maxHeight = Math.min(windowHeight - top, windowHeight); } else { if (responsive) { top = targetRect.bottom; } maxHeight = Math.min( windowHeight - top, windowHeight - targetRect.height ); } } } container.style.left = `${left}px`; if (stretch) { // offset width by 0.1 to avoid a bug in ie11 that // unnecessarily wraps the text if width is the same container.style.width = `${width + 0.1}px`; } // the (position:absolute + scrollTop) // is presenting issues with desktop scroll flickering container.style.top = `${top}px`; maxHeight = windowHeight - (top || 0); if (theme.drop && theme.drop.maxHeight) { maxHeight = Math.min(maxHeight, parseMetricToNum(theme.drop.maxHeight)); } container.style.maxHeight = `${maxHeight}px`; } } render() { const { children, onClickOutside, onEsc, onKeyDown, theme: propsTheme, ...rest } = this.props; const { theme: stateTheme } = this.state; const theme = stateTheme || propsTheme; let content = ( <StyledDrop tabIndex='-1' ref={this.dropRef} theme={theme} {...rest} > {children} </StyledDrop> ); if (stateTheme) { if (stateTheme.dark !== propsTheme.dark && stateTheme.icon) { content = ( <IconThemeContext.Provider value={stateTheme.icon}> {content} </IconThemeContext.Provider> ); } content = ( <ThemeContext.Provider value={stateTheme}> {content} </ThemeContext.Provider> ); } return ( <FocusedContainer> <Keyboard onEsc={onEsc} onKeyDown={onKeyDown} target='document'> {content} </Keyboard> </FocusedContainer> ); } }
src/js/components/Drop/DropContainer.js
import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; import { ThemeContext as IconThemeContext } from 'grommet-icons/contexts'; import { ThemeContext } from '../../contexts'; import { FocusedContainer } from '../FocusedContainer'; import { backgroundIsDark, findScrollParents, findVisibleParent, parseMetricToNum, } from '../../utils'; import { Keyboard } from '../Keyboard'; import { StyledDrop } from './StyledDrop'; export class DropContainer extends Component { static defaultProps = { align: { top: 'top', left: 'left', }, stretch: 'width', } static getDerivedStateFromProps(nextProps, prevState) { // Since the drop background can be different from the current theme context, // we update the theme to set the dark background context. const { theme: propsTheme } = nextProps; const { theme: stateTheme, priorTheme } = prevState; const dark = backgroundIsDark(propsTheme.global.drop.background, propsTheme); if (dark === propsTheme.dark && stateTheme) { return { theme: undefined, priorTheme: undefined }; } if (dark !== propsTheme.dark && (!stateTheme || dark !== stateTheme.dark || propsTheme !== priorTheme)) { return { theme: { ...propsTheme, dark, icon: dark ? propsTheme.iconThemes.dark : propsTheme.iconThemes.light, }, priorTheme: propsTheme, }; } return null; } state = {} dropRef = React.createRef() componentDidMount() { const { restrictFocus } = this.props; this.addScrollListener(); window.addEventListener('resize', this.onResize); document.addEventListener('mousedown', this.onClickDocument); this.place(); if (restrictFocus) { findDOMNode(this.dropRef.current).focus(); } } componentDidUpdate() { this.place(); } componentWillUnmount() { this.removeScrollListener(); window.removeEventListener('resize', this.onResize); document.removeEventListener('mousedown', this.onClickDocument); } addScrollListener = () => { const { dropTarget } = this.props; this.scrollParents = findScrollParents(findDOMNode(dropTarget)); this.scrollParents.forEach(scrollParent => scrollParent.addEventListener('scroll', this.place)); } removeScrollListener = () => { this.scrollParents.forEach( scrollParent => scrollParent.removeEventListener('scroll', this.place) ); } onClickDocument = (event) => { const { dropTarget, onClickOutside } = this.props; const dropTargetNode = findDOMNode(dropTarget); const dropNode = findDOMNode(this.dropRef.current); if ( onClickOutside && dropNode && // need this for ie11 !dropTargetNode.contains(event.target) && !dropNode.contains(event.target) ) { onClickOutside(); } } onResize = () => { this.removeScrollListener(); this.addScrollListener(); this.place(); } place = () => { const { align, dropTarget, responsive, stretch, theme } = this.props; const windowWidth = window.innerWidth; const windowHeight = window.innerHeight; const target = findDOMNode(dropTarget); const container = findDOMNode(this.dropRef.current); if (container && target) { // clear prior styling container.style.left = ''; container.style.width = ''; container.style.top = ''; container.style.maxHeight = ''; // get bounds const targetRect = findVisibleParent(target).getBoundingClientRect(); const containerRect = container.getBoundingClientRect(); // determine width const width = Math.min( (stretch ? Math.max(targetRect.width, containerRect.width) : containerRect.width ), windowWidth ); // set left position let left; if (align.left) { if (align.left === 'left') { left = targetRect.left; } else if (align.left === 'right') { left = targetRect.left + targetRect.width; } } else if (align.right) { if (align.right === 'left') { left = targetRect.left - width; } else if (align.right === 'right') { left = (targetRect.left + targetRect.width) - width; } } else { left = (targetRect.left + (targetRect.width / 2)) - (width / 2); } if ((left + width) > windowWidth) { left -= ((left + width) - windowWidth); } else if (left < 0) { left = 0; } // set top position let top; let maxHeight; if (align.top) { if (align.top === 'top') { top = targetRect.top; maxHeight = Math.min(windowHeight - targetRect.top, windowHeight); } else { top = targetRect.bottom; maxHeight = Math.min( windowHeight - targetRect.bottom, windowHeight - targetRect.height ); } } else if (align.bottom) { if (align.bottom === 'bottom') { top = targetRect.bottom - containerRect.height; maxHeight = Math.max(targetRect.bottom, 0); } else { top = targetRect.top - containerRect.height; maxHeight = Math.max(targetRect.top, 0); } } else { top = (targetRect.top + (targetRect.height / 2)) - (containerRect.height / 2); } // if we can't fit it all, see if there's more room the other direction if (containerRect.height > maxHeight) { // We need more room than we have. if (align.top && top > (windowHeight / 2)) { // We put it below, but there's more room above, put it above if (align.top === 'bottom') { if (responsive) { top = Math.max(targetRect.top - containerRect.height, 0); } maxHeight = targetRect.top; } else { if (responsive) { top = Math.max(targetRect.bottom - containerRect.height, 0); } maxHeight = targetRect.bottom; } } else if (align.bottom && maxHeight < (windowHeight / 2)) { // We put it above but there's more room below, put it below if (align.bottom === 'bottom') { if (responsive) { top = targetRect.top; } maxHeight = Math.min(windowHeight - top, windowHeight); } else { if (responsive) { top = targetRect.bottom; } maxHeight = Math.min( windowHeight - top, windowHeight - targetRect.height ); } } } container.style.left = `${left}px`; if (stretch) { // offset width by 0.1 to avoid a bug in ie11 that // unnecessarily wraps the text if width is the same container.style.width = `${width + 0.1}px`; } // the (position:absolute + scrollTop) // is presenting issues with desktop scroll flickering container.style.top = `${top}px`; maxHeight = windowHeight - (top || 0); if (theme.drop && theme.drop.maxHeight) { maxHeight = Math.min(maxHeight, parseMetricToNum(theme.drop.maxHeight)); } container.style.maxHeight = `${maxHeight}px`; } } render() { const { children, onClickOutside, onEsc, onKeyDown, theme: propsTheme, ...rest } = this.props; const { theme: stateTheme } = this.state; const theme = stateTheme || propsTheme; let content = ( <StyledDrop tabIndex='-1' ref={this.dropRef} theme={theme} {...rest} > {children} </StyledDrop> ); if (stateTheme) { if (stateTheme.dark !== propsTheme.dark && stateTheme.icon) { content = ( <IconThemeContext.Provider value={stateTheme.icon}> {content} </IconThemeContext.Provider> ); } content = ( <ThemeContext.Provider value={stateTheme}> {content} </ThemeContext.Provider> ); } return ( <FocusedContainer> <Keyboard onEsc={onEsc} onKeyDown={onKeyDown}> {content} </Keyboard> </FocusedContainer> ); } }
Fix to close a drop element without having the focus on the drop (#2343)
src/js/components/Drop/DropContainer.js
Fix to close a drop element without having the focus on the drop (#2343)
<ide><path>rc/js/components/Drop/DropContainer.js <ide> <ide> return ( <ide> <FocusedContainer> <del> <Keyboard onEsc={onEsc} onKeyDown={onKeyDown}> <add> <Keyboard onEsc={onEsc} onKeyDown={onKeyDown} target='document'> <ide> {content} <ide> </Keyboard> <ide> </FocusedContainer>
Java
mit
1fe351b7107b9740f933209e0e967d693db320c4
0
ekholabs/elsie-dee
package nl.ekholabs.nlp.controller; import java.io.IOException; import nl.ekholabs.nlp.model.TextResponse; import nl.ekholabs.nlp.service.SpeechToTextService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; @RestController public class SpeechToTextController { private final SpeechToTextService speechToTextService; @Autowired public SpeechToTextController(final SpeechToTextService speechToTextService) { this.speechToTextService = speechToTextService; } @PostMapping(produces = APPLICATION_JSON_UTF8_VALUE, consumes = MULTIPART_FORM_DATA_VALUE) public TextResponse process(final @RequestParam(value = "input") MultipartFile fileToProcess) throws IOException { final String outputText = speechToTextService.processSpeech(fileToProcess.getBytes()); return new TextResponse(outputText); } }
src/main/java/nl/ekholabs/nlp/controller/SpeechToTextController.java
package nl.ekholabs.nlp.controller; import java.io.IOException; import nl.ekholabs.nlp.model.TextResponse; import nl.ekholabs.nlp.service.SpeechToTextService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; @RestController public class SpeechToTextController { private final SpeechToTextService speechToTextService; @Autowired public SpeechToTextController(final SpeechToTextService speechToTextService) { this.speechToTextService = speechToTextService; } @PostMapping(path = "/", produces = APPLICATION_JSON_UTF8_VALUE, consumes = MULTIPART_FORM_DATA_VALUE) public TextResponse process(final @RequestParam(value = "input") MultipartFile fileToProcess) throws IOException { final String outputText = speechToTextService.processSpeech(fileToProcess.getBytes()); return new TextResponse(outputText); } }
Remove path attribute from PostMapping
src/main/java/nl/ekholabs/nlp/controller/SpeechToTextController.java
Remove path attribute from PostMapping
<ide><path>rc/main/java/nl/ekholabs/nlp/controller/SpeechToTextController.java <ide> this.speechToTextService = speechToTextService; <ide> } <ide> <del> @PostMapping(path = "/", produces = APPLICATION_JSON_UTF8_VALUE, consumes = MULTIPART_FORM_DATA_VALUE) <add> @PostMapping(produces = APPLICATION_JSON_UTF8_VALUE, consumes = MULTIPART_FORM_DATA_VALUE) <ide> public TextResponse process(final @RequestParam(value = "input") MultipartFile fileToProcess) throws IOException { <ide> <ide> final String outputText = speechToTextService.processSpeech(fileToProcess.getBytes());
Java
apache-2.0
e4ee186bcdd5489a759335e334ff727397a041cf
0
e-cuellar/pentaho-kettle,pminutillo/pentaho-kettle,wseyler/pentaho-kettle,matthewtckr/pentaho-kettle,graimundo/pentaho-kettle,bmorrise/pentaho-kettle,skofra0/pentaho-kettle,DFieldFL/pentaho-kettle,ddiroma/pentaho-kettle,graimundo/pentaho-kettle,marcoslarsen/pentaho-kettle,wseyler/pentaho-kettle,mkambol/pentaho-kettle,tkafalas/pentaho-kettle,e-cuellar/pentaho-kettle,DFieldFL/pentaho-kettle,pentaho/pentaho-kettle,skofra0/pentaho-kettle,dkincade/pentaho-kettle,ddiroma/pentaho-kettle,DFieldFL/pentaho-kettle,ccaspanello/pentaho-kettle,pedrofvteixeira/pentaho-kettle,HiromuHota/pentaho-kettle,kurtwalker/pentaho-kettle,flbrino/pentaho-kettle,mbatchelor/pentaho-kettle,pentaho/pentaho-kettle,HiromuHota/pentaho-kettle,mkambol/pentaho-kettle,dkincade/pentaho-kettle,HiromuHota/pentaho-kettle,tmcsantos/pentaho-kettle,marcoslarsen/pentaho-kettle,pentaho/pentaho-kettle,pminutillo/pentaho-kettle,roboguy/pentaho-kettle,lgrill-pentaho/pentaho-kettle,lgrill-pentaho/pentaho-kettle,rmansoor/pentaho-kettle,bmorrise/pentaho-kettle,lgrill-pentaho/pentaho-kettle,emartin-pentaho/pentaho-kettle,ddiroma/pentaho-kettle,wseyler/pentaho-kettle,matthewtckr/pentaho-kettle,DFieldFL/pentaho-kettle,HiromuHota/pentaho-kettle,mdamour1976/pentaho-kettle,kurtwalker/pentaho-kettle,dkincade/pentaho-kettle,mbatchelor/pentaho-kettle,wseyler/pentaho-kettle,tmcsantos/pentaho-kettle,pedrofvteixeira/pentaho-kettle,rmansoor/pentaho-kettle,mdamour1976/pentaho-kettle,roboguy/pentaho-kettle,flbrino/pentaho-kettle,graimundo/pentaho-kettle,tkafalas/pentaho-kettle,matthewtckr/pentaho-kettle,mbatchelor/pentaho-kettle,marcoslarsen/pentaho-kettle,matthewtckr/pentaho-kettle,dkincade/pentaho-kettle,flbrino/pentaho-kettle,pedrofvteixeira/pentaho-kettle,roboguy/pentaho-kettle,skofra0/pentaho-kettle,ccaspanello/pentaho-kettle,ddiroma/pentaho-kettle,e-cuellar/pentaho-kettle,kurtwalker/pentaho-kettle,rmansoor/pentaho-kettle,roboguy/pentaho-kettle,pentaho/pentaho-kettle,mdamour1976/pentaho-kettle,marcoslarsen/pentaho-kettle,tmcsantos/pentaho-kettle,graimundo/pentaho-kettle,ccaspanello/pentaho-kettle,mkambol/pentaho-kettle,mbatchelor/pentaho-kettle,bmorrise/pentaho-kettle,tmcsantos/pentaho-kettle,emartin-pentaho/pentaho-kettle,rmansoor/pentaho-kettle,mdamour1976/pentaho-kettle,tkafalas/pentaho-kettle,flbrino/pentaho-kettle,emartin-pentaho/pentaho-kettle,mkambol/pentaho-kettle,pminutillo/pentaho-kettle,pedrofvteixeira/pentaho-kettle,tkafalas/pentaho-kettle,pminutillo/pentaho-kettle,skofra0/pentaho-kettle,ccaspanello/pentaho-kettle,emartin-pentaho/pentaho-kettle,kurtwalker/pentaho-kettle,bmorrise/pentaho-kettle,e-cuellar/pentaho-kettle,lgrill-pentaho/pentaho-kettle
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.pentaho.di.core.injection.DefaultInjectionTypeConverter; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.row.value.ValueMetaBigNumber; import org.pentaho.di.core.row.value.ValueMetaBinary; import org.pentaho.di.core.row.value.ValueMetaBoolean; import org.pentaho.di.core.row.value.ValueMetaDate; import org.pentaho.di.core.row.value.ValueMetaInteger; import org.pentaho.di.core.row.value.ValueMetaInternetAddress; import org.pentaho.di.core.row.value.ValueMetaNumber; import org.pentaho.di.core.row.value.ValueMetaString; import org.pentaho.di.core.row.value.ValueMetaTimestamp; public class RowMetaAndDataTest { RowMeta rowsMeta; RowMetaAndData row; DefaultInjectionTypeConverter converter = new DefaultInjectionTypeConverter(); enum TestEnum { ONE, Two, three } @Before public void prepare() throws Exception { rowsMeta = new RowMeta(); ValueMetaInterface valueMetaString = new ValueMetaString( "str" ); rowsMeta.addValueMeta( valueMetaString ); ValueMetaInterface valueMetaBoolean = new ValueMetaBoolean( "bool" ); rowsMeta.addValueMeta( valueMetaBoolean ); ValueMetaInterface valueMetaInteger = new ValueMetaInteger( "int" ); rowsMeta.addValueMeta( valueMetaInteger ); } @Test public void testMergeRowAndMetaData() { row = new RowMetaAndData( rowsMeta, "text", true, 1 ); RowMetaAndData addRow = new RowMetaAndData( rowsMeta, "text1", false, 3 ); row.mergeRowMetaAndData( addRow, "originName" ); } @Test public void testStringConversion() throws Exception { row = new RowMetaAndData( rowsMeta, "text", null, null ); assertEquals( "text", row.getAsJavaType( "str", String.class, converter ) ); row = new RowMetaAndData( rowsMeta, "7", null, null ); assertEquals( 7, row.getAsJavaType( "str", int.class, converter ) ); assertEquals( 7, row.getAsJavaType( "str", Integer.class, converter ) ); assertEquals( 7L, row.getAsJavaType( "str", long.class, converter ) ); assertEquals( 7L, row.getAsJavaType( "str", Long.class, converter ) ); row = new RowMetaAndData( rowsMeta, "y", null, null ); assertEquals( true, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( true, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, "yes", null, null ); assertEquals( true, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( true, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, "true", null, null ); assertEquals( true, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( true, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, "no", null, null ); assertEquals( false, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( false, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, "n", null, null ); assertEquals( false, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( false, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, "false", null, null ); assertEquals( false, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( false, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, "f", null, null ); assertEquals( false, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( false, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, "other", null, null ); assertEquals( false, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( false, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, TestEnum.ONE.name(), null, null ); assertEquals( TestEnum.ONE, row.getAsJavaType( "str", TestEnum.class, converter ) ); row = new RowMetaAndData( rowsMeta, TestEnum.Two.name(), null, null ); assertEquals( TestEnum.Two, row.getAsJavaType( "str", TestEnum.class, converter ) ); row = new RowMetaAndData( rowsMeta, TestEnum.three.name(), null, null ); assertEquals( TestEnum.three, row.getAsJavaType( "str", TestEnum.class, converter ) ); row = new RowMetaAndData( rowsMeta, null, null, null ); assertEquals( null, row.getAsJavaType( "str", String.class, converter ) ); assertEquals( null, row.getAsJavaType( "str", Integer.class, converter ) ); assertEquals( null, row.getAsJavaType( "str", Long.class, converter ) ); assertEquals( null, row.getAsJavaType( "str", Boolean.class, converter ) ); } @Test public void testBooleanConversion() throws Exception { row = new RowMetaAndData( rowsMeta, null, true, null ); assertEquals( true, row.getAsJavaType( "bool", boolean.class, converter ) ); assertEquals( true, row.getAsJavaType( "bool", Boolean.class, converter ) ); assertEquals( 1, row.getAsJavaType( "bool", int.class, converter ) ); assertEquals( 1, row.getAsJavaType( "bool", Integer.class, converter ) ); assertEquals( 1L, row.getAsJavaType( "bool", long.class, converter ) ); assertEquals( 1L, row.getAsJavaType( "bool", Long.class, converter ) ); assertEquals( "Y", row.getAsJavaType( "bool", String.class, converter ) ); row = new RowMetaAndData( rowsMeta, null, false, null ); assertEquals( false, row.getAsJavaType( "bool", boolean.class, converter ) ); assertEquals( false, row.getAsJavaType( "bool", Boolean.class, converter ) ); assertEquals( 0, row.getAsJavaType( "bool", int.class, converter ) ); assertEquals( 0, row.getAsJavaType( "bool", Integer.class, converter ) ); assertEquals( 0L, row.getAsJavaType( "bool", long.class, converter ) ); assertEquals( 0L, row.getAsJavaType( "bool", Long.class, converter ) ); assertEquals( "N", row.getAsJavaType( "bool", String.class, converter ) ); row = new RowMetaAndData( rowsMeta, null, null, null ); assertEquals( null, row.getAsJavaType( "bool", String.class, converter ) ); assertEquals( null, row.getAsJavaType( "bool", Integer.class, converter ) ); assertEquals( null, row.getAsJavaType( "bool", Long.class, converter ) ); assertEquals( null, row.getAsJavaType( "bool", Boolean.class, converter ) ); } @Test public void testIntegerConversion() throws Exception { row = new RowMetaAndData( rowsMeta, null, null, 7L ); assertEquals( true, row.getAsJavaType( "int", boolean.class, converter ) ); assertEquals( true, row.getAsJavaType( "int", Boolean.class, converter ) ); assertEquals( 7, row.getAsJavaType( "int", int.class, converter ) ); assertEquals( 7, row.getAsJavaType( "int", Integer.class, converter ) ); assertEquals( 7L, row.getAsJavaType( "int", long.class, converter ) ); assertEquals( 7L, row.getAsJavaType( "int", Long.class, converter ) ); assertEquals( "7", row.getAsJavaType( "int", String.class, converter ) ); row = new RowMetaAndData( rowsMeta, null, null, 0L ); assertEquals( false, row.getAsJavaType( "int", boolean.class, converter ) ); assertEquals( false, row.getAsJavaType( "int", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, null, null, null ); assertEquals( null, row.getAsJavaType( "int", String.class, converter ) ); assertEquals( null, row.getAsJavaType( "int", Integer.class, converter ) ); assertEquals( null, row.getAsJavaType( "int", Long.class, converter ) ); assertEquals( null, row.getAsJavaType( "int", Boolean.class, converter ) ); } @Test public void testEmptyValues() throws Exception { RowMeta rowsMetaEmpty = new RowMeta(); rowsMetaEmpty.addValueMeta( new ValueMetaString( "str" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaBoolean( "bool" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaInteger( "int" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaNumber( "num" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaBigNumber( "bignum" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaBinary( "bin" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaDate( "date" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaTimestamp( "timestamp" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaInternetAddress( "inet" ) ); row = new RowMetaAndData( rowsMetaEmpty, null, null, null, null, null, null, null, null, null ); assertTrue( row.isEmptyValue( "str" ) ); assertTrue( row.isEmptyValue( "bool" ) ); assertTrue( row.isEmptyValue( "int" ) ); assertTrue( row.isEmptyValue( "num" ) ); assertTrue( row.isEmptyValue( "bignum" ) ); assertTrue( row.isEmptyValue( "bin" ) ); assertTrue( row.isEmptyValue( "date" ) ); assertTrue( row.isEmptyValue( "timestamp" ) ); assertTrue( row.isEmptyValue( "inet" ) ); } }
core/src/test/java/org/pentaho/di/core/RowMetaAndDataTest.java
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.pentaho.di.core.injection.DefaultInjectionTypeConverter; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.row.value.ValueMetaBigNumber; import org.pentaho.di.core.row.value.ValueMetaBinary; import org.pentaho.di.core.row.value.ValueMetaBoolean; import org.pentaho.di.core.row.value.ValueMetaDate; import org.pentaho.di.core.row.value.ValueMetaInteger; import org.pentaho.di.core.row.value.ValueMetaInternetAddress; import org.pentaho.di.core.row.value.ValueMetaNumber; import org.pentaho.di.core.row.value.ValueMetaString; import org.pentaho.di.core.row.value.ValueMetaTimestamp; public class RowMetaAndDataTest { RowMeta rowsMeta; RowMetaAndData row; DefaultInjectionTypeConverter converter = new DefaultInjectionTypeConverter(); enum TestEnum { ONE, Two, three } @Before public void prepare() throws Exception { rowsMeta = new RowMeta(); ValueMetaInterface valueMetaString = new ValueMetaString( "str" ); rowsMeta.addValueMeta( valueMetaString ); ValueMetaInterface valueMetaBoolean = new ValueMetaBoolean( "bool" ); rowsMeta.addValueMeta( valueMetaBoolean ); ValueMetaInterface valueMetaInteger = new ValueMetaInteger( "int" ); rowsMeta.addValueMeta( valueMetaInteger ); } @Test public void testStringConversion() throws Exception { row = new RowMetaAndData( rowsMeta, "text", null, null ); assertEquals( "text", row.getAsJavaType( "str", String.class, converter ) ); row = new RowMetaAndData( rowsMeta, "7", null, null ); assertEquals( 7, row.getAsJavaType( "str", int.class, converter ) ); assertEquals( 7, row.getAsJavaType( "str", Integer.class, converter ) ); assertEquals( 7L, row.getAsJavaType( "str", long.class, converter ) ); assertEquals( 7L, row.getAsJavaType( "str", Long.class, converter ) ); row = new RowMetaAndData( rowsMeta, "y", null, null ); assertEquals( true, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( true, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, "yes", null, null ); assertEquals( true, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( true, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, "true", null, null ); assertEquals( true, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( true, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, "no", null, null ); assertEquals( false, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( false, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, "n", null, null ); assertEquals( false, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( false, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, "false", null, null ); assertEquals( false, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( false, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, "f", null, null ); assertEquals( false, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( false, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, "other", null, null ); assertEquals( false, row.getAsJavaType( "str", boolean.class, converter ) ); assertEquals( false, row.getAsJavaType( "str", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, TestEnum.ONE.name(), null, null ); assertEquals( TestEnum.ONE, row.getAsJavaType( "str", TestEnum.class, converter ) ); row = new RowMetaAndData( rowsMeta, TestEnum.Two.name(), null, null ); assertEquals( TestEnum.Two, row.getAsJavaType( "str", TestEnum.class, converter ) ); row = new RowMetaAndData( rowsMeta, TestEnum.three.name(), null, null ); assertEquals( TestEnum.three, row.getAsJavaType( "str", TestEnum.class, converter ) ); row = new RowMetaAndData( rowsMeta, null, null, null ); assertEquals( null, row.getAsJavaType( "str", String.class, converter ) ); assertEquals( null, row.getAsJavaType( "str", Integer.class, converter ) ); assertEquals( null, row.getAsJavaType( "str", Long.class, converter ) ); assertEquals( null, row.getAsJavaType( "str", Boolean.class, converter ) ); } @Test public void testBooleanConversion() throws Exception { row = new RowMetaAndData( rowsMeta, null, true, null ); assertEquals( true, row.getAsJavaType( "bool", boolean.class, converter ) ); assertEquals( true, row.getAsJavaType( "bool", Boolean.class, converter ) ); assertEquals( 1, row.getAsJavaType( "bool", int.class, converter ) ); assertEquals( 1, row.getAsJavaType( "bool", Integer.class, converter ) ); assertEquals( 1L, row.getAsJavaType( "bool", long.class, converter ) ); assertEquals( 1L, row.getAsJavaType( "bool", Long.class, converter ) ); assertEquals( "Y", row.getAsJavaType( "bool", String.class, converter ) ); row = new RowMetaAndData( rowsMeta, null, false, null ); assertEquals( false, row.getAsJavaType( "bool", boolean.class, converter ) ); assertEquals( false, row.getAsJavaType( "bool", Boolean.class, converter ) ); assertEquals( 0, row.getAsJavaType( "bool", int.class, converter ) ); assertEquals( 0, row.getAsJavaType( "bool", Integer.class, converter ) ); assertEquals( 0L, row.getAsJavaType( "bool", long.class, converter ) ); assertEquals( 0L, row.getAsJavaType( "bool", Long.class, converter ) ); assertEquals( "N", row.getAsJavaType( "bool", String.class, converter ) ); row = new RowMetaAndData( rowsMeta, null, null, null ); assertEquals( null, row.getAsJavaType( "bool", String.class, converter ) ); assertEquals( null, row.getAsJavaType( "bool", Integer.class, converter ) ); assertEquals( null, row.getAsJavaType( "bool", Long.class, converter ) ); assertEquals( null, row.getAsJavaType( "bool", Boolean.class, converter ) ); } @Test public void testIntegerConversion() throws Exception { row = new RowMetaAndData( rowsMeta, null, null, 7L ); assertEquals( true, row.getAsJavaType( "int", boolean.class, converter ) ); assertEquals( true, row.getAsJavaType( "int", Boolean.class, converter ) ); assertEquals( 7, row.getAsJavaType( "int", int.class, converter ) ); assertEquals( 7, row.getAsJavaType( "int", Integer.class, converter ) ); assertEquals( 7L, row.getAsJavaType( "int", long.class, converter ) ); assertEquals( 7L, row.getAsJavaType( "int", Long.class, converter ) ); assertEquals( "7", row.getAsJavaType( "int", String.class, converter ) ); row = new RowMetaAndData( rowsMeta, null, null, 0L ); assertEquals( false, row.getAsJavaType( "int", boolean.class, converter ) ); assertEquals( false, row.getAsJavaType( "int", Boolean.class, converter ) ); row = new RowMetaAndData( rowsMeta, null, null, null ); assertEquals( null, row.getAsJavaType( "int", String.class, converter ) ); assertEquals( null, row.getAsJavaType( "int", Integer.class, converter ) ); assertEquals( null, row.getAsJavaType( "int", Long.class, converter ) ); assertEquals( null, row.getAsJavaType( "int", Boolean.class, converter ) ); } @Test public void testEmptyValues() throws Exception { RowMeta rowsMetaEmpty = new RowMeta(); rowsMetaEmpty.addValueMeta( new ValueMetaString( "str" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaBoolean( "bool" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaInteger( "int" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaNumber( "num" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaBigNumber( "bignum" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaBinary( "bin" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaDate( "date" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaTimestamp( "timestamp" ) ); rowsMetaEmpty.addValueMeta( new ValueMetaInternetAddress( "inet" ) ); row = new RowMetaAndData( rowsMetaEmpty, null, null, null, null, null, null, null, null, null ); assertTrue( row.isEmptyValue( "str" ) ); assertTrue( row.isEmptyValue( "bool" ) ); assertTrue( row.isEmptyValue( "int" ) ); assertTrue( row.isEmptyValue( "num" ) ); assertTrue( row.isEmptyValue( "bignum" ) ); assertTrue( row.isEmptyValue( "bin" ) ); assertTrue( row.isEmptyValue( "date" ) ); assertTrue( row.isEmptyValue( "timestamp" ) ); assertTrue( row.isEmptyValue( "inet" ) ); } }
[BACKLOG-21321] Avro Streaming enhancments ( pass fields from prior step, handle multiple rows containing avro content, add seperator bar and fix Mac UI )
core/src/test/java/org/pentaho/di/core/RowMetaAndDataTest.java
[BACKLOG-21321] Avro Streaming enhancments ( pass fields from prior step, handle multiple rows containing avro content, add seperator bar and fix Mac UI )
<ide><path>ore/src/test/java/org/pentaho/di/core/RowMetaAndDataTest.java <ide> * <ide> * Pentaho Data Integration <ide> * <del> * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com <add> * Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com <ide> * <ide> ******************************************************************************* <ide> * <ide> <ide> ValueMetaInterface valueMetaInteger = new ValueMetaInteger( "int" ); <ide> rowsMeta.addValueMeta( valueMetaInteger ); <add> } <add> <add> @Test <add> public void testMergeRowAndMetaData() { <add> row = new RowMetaAndData( rowsMeta, "text", true, 1 ); <add> RowMetaAndData addRow = new RowMetaAndData( rowsMeta, "text1", false, 3 ); <add> row.mergeRowMetaAndData( addRow, "originName" ); <ide> } <ide> <ide> @Test
JavaScript
mit
af25c1bf5a590b17bc0f4aef1f30d9993fc8f497
0
DaemonAlchemist/atp-core,DaemonAlchemist/atp-core,DaemonAlchemist/atp-core
;(function ( $, window, document, undefined ) { var pluginName = "bannerRotate"; var defaults = { bannerDisplayTime: 10000, bannerFadeTime: 800 }; function Plugin( element, options ) { this.element = element; this.options = $.extend( {}, defaults, options ); this._defaults = defaults; this._name = pluginName; this.init(); } Plugin.prototype = { init: function() { var elem = $(this.element); var options = this.options; //Hide banners on first load elem.children().addClass("banner").hide(); elem.children(':first-child').addClass("banner-displayed"); elem.children(':first-child').show(); //Add buttons var bannerCount = elem.children().length; elem.append("<div class=\"banner-buttons\"></div>"); var buttons = elem.find(".banner-buttons"); for(var i=1; i<=bannerCount; i++) { buttons.append("<a href=\"#\" class=\"banner-button\">" + i + "</a>"); } buttons.children(":first-child").addClass("active"); var rotatorFunc = function() { //Disable buttons while transition is happening buttons.find("a").addClass("disabled"); //Get current banner and button var curBanner = elem.find(".banner-displayed"); var curButton = elem.find(".banner-buttons a.active"); //Update banner index curBannerIndex++; //Get next banner if(curBannerIndex > bannerCount) curBannerIndex = 1; var nextBanner = elem.find(".banner:nth-child("+curBannerIndex+")"); var nextButton = elem.find(".banner-buttons a:nth-child("+curBannerIndex+")"); //Fade transition between banners curBanner.removeClass("banner-displayed"); curBanner.fadeOut({ duration: options.bannerFadeTime, complete: function(){ nextBanner.fadeIn({ duration: options.bannerFadeTime, complete: function(){ nextBanner.addClass("banner-displayed"); buttons.find("a").removeClass("disabled"); } }); } }); //Update button styles curButton.removeClass("active"); nextButton.addClass("active"); }; var curBannerIndex = 1; var rotator = null; buttons.find("a").click(function(evt){ //Don't do anything if the link is disabled if($(this).hasClass("disabled")) return false; //Get index of selected banner var index = parseInt($(this).html()); curBannerIndex = index - 1; if(curBannerIndex == 0) curBannerIndex = bannerCount; //Show new banner and reset rotator clearInterval(rotator); rotatorFunc(); rotator = setInterval(rotatorFunc, options.bannerDisplayTime); return false; }); //Rotate banners rotator = setInterval(rotatorFunc, options.bannerDisplayTime); }, }; $.fn[pluginName] = function ( options ) { return this.each(function () { if (!$.data(this, "plugin_" + pluginName)) { $.data(this, "plugin_" + pluginName, new Plugin( this, options )); } }); }; })( jQuery, window, document );
public/atp-core/js/jquery_plugins/banner_rotate.js
;(function ( $, window, document, undefined ) { var pluginName = "bannerRotate"; var defaults = { bannerDisplayTime: 10000, bannerFadeTime: 800 }; function Plugin( element, options ) { this.element = element; this.options = $.extend( {}, defaults, options ); this._defaults = defaults; this._name = pluginName; this.init(); } Plugin.prototype = { init: function() { var elem = $(this.element); var options = this.options; //Hide banners on first load elem.children().hide(); elem.children(':first-child').addClass('banner-displayed'); elem.children(':first-child').show(); //Rotate banners setInterval(function() { var curBanner = elem.children('.banner-displayed'); var nextBanner = curBanner.next(); if(nextBanner.length == 0) nextBanner = elem.children(':first-child'); curBanner.removeClass('banner-displayed'); curBanner.fadeOut({ duration: options.bannerFadeTime, complete: function(){ nextBanner.addClass('banner-displayed'); nextBanner.fadeIn({ duration: options.bannerFadeTime }); } }); }, options.bannerDisplayTime); }, }; $.fn[pluginName] = function ( options ) { return this.each(function () { if (!$.data(this, "plugin_" + pluginName)) { $.data(this, "plugin_" + pluginName, new Plugin( this, options )); } }); }; })( jQuery, window, document );
Add buttons to banner rotator
public/atp-core/js/jquery_plugins/banner_rotate.js
Add buttons to banner rotator
<ide><path>ublic/atp-core/js/jquery_plugins/banner_rotate.js <ide> var options = this.options; <ide> <ide> //Hide banners on first load <del> elem.children().hide(); <del> elem.children(':first-child').addClass('banner-displayed'); <add> elem.children().addClass("banner").hide(); <add> elem.children(':first-child').addClass("banner-displayed"); <ide> elem.children(':first-child').show(); <ide> <del> //Rotate banners <del> setInterval(function() { <del> var curBanner = elem.children('.banner-displayed'); <del> var nextBanner = curBanner.next(); <del> if(nextBanner.length == 0) nextBanner = elem.children(':first-child'); <add> //Add buttons <add> var bannerCount = elem.children().length; <add> elem.append("<div class=\"banner-buttons\"></div>"); <add> var buttons = elem.find(".banner-buttons"); <add> for(var i=1; i<=bannerCount; i++) { <add> buttons.append("<a href=\"#\" class=\"banner-button\">" + i + "</a>"); <add> } <add> buttons.children(":first-child").addClass("active"); <add> <add> var rotatorFunc = function() { <add> //Disable buttons while transition is happening <add> buttons.find("a").addClass("disabled"); <add> <add> //Get current banner and button <add> var curBanner = elem.find(".banner-displayed"); <add> var curButton = elem.find(".banner-buttons a.active"); <ide> <del> curBanner.removeClass('banner-displayed'); <add> //Update banner index <add> curBannerIndex++; <add> <add> //Get next banner <add> if(curBannerIndex > bannerCount) curBannerIndex = 1; <add> var nextBanner = elem.find(".banner:nth-child("+curBannerIndex+")"); <add> var nextButton = elem.find(".banner-buttons a:nth-child("+curBannerIndex+")"); <add> <add> //Fade transition between banners <add> curBanner.removeClass("banner-displayed"); <ide> curBanner.fadeOut({ <ide> duration: options.bannerFadeTime, <ide> complete: function(){ <del> nextBanner.addClass('banner-displayed'); <ide> nextBanner.fadeIn({ <del> duration: options.bannerFadeTime <add> duration: options.bannerFadeTime, <add> complete: function(){ <add> nextBanner.addClass("banner-displayed"); <add> buttons.find("a").removeClass("disabled"); <add> } <ide> }); <ide> } <ide> }); <del> }, options.bannerDisplayTime); <add> <add> //Update button styles <add> curButton.removeClass("active"); <add> nextButton.addClass("active"); <add> }; <add> <add> var curBannerIndex = 1; <add> var rotator = null; <add> buttons.find("a").click(function(evt){ <add> //Don't do anything if the link is disabled <add> if($(this).hasClass("disabled")) return false; <add> <add> //Get index of selected banner <add> var index = parseInt($(this).html()); <add> curBannerIndex = index - 1; <add> if(curBannerIndex == 0) curBannerIndex = bannerCount; <add> <add> //Show new banner and reset rotator <add> clearInterval(rotator); <add> rotatorFunc(); <add> rotator = setInterval(rotatorFunc, options.bannerDisplayTime); <add> return false; <add> }); <add> <add> //Rotate banners <add> rotator = setInterval(rotatorFunc, options.bannerDisplayTime); <ide> }, <ide> }; <ide>
Java
bsd-2-clause
f04a016d6ec62acc3d261bd4fe2c432d9fe0fe5d
0
biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej,TehSAUCE/imagej,biovoxxel/imagej
package imagej; import imagej.SampleInfo.ValueType; import imagej.process.ImageUtils; import imagej.process.Index; import imagej.process.Span; import imagej.process.TypeManager; import imagej.process.operation.GetPlaneOperation; import imagej.process.operation.SetPlaneOperation; import mpicbg.imglib.container.ContainerFactory; import mpicbg.imglib.container.basictypecontainer.PlanarAccess; import mpicbg.imglib.container.basictypecontainer.array.ArrayDataAccess; import mpicbg.imglib.image.Image; import mpicbg.imglib.type.numeric.RealType; import mpicbg.imglib.type.numeric.integer.ByteType; import mpicbg.imglib.type.numeric.integer.IntType; import mpicbg.imglib.type.numeric.integer.LongType; import mpicbg.imglib.type.numeric.integer.ShortType; import mpicbg.imglib.type.numeric.integer.UnsignedByteType; import mpicbg.imglib.type.numeric.integer.UnsignedIntType; import mpicbg.imglib.type.numeric.integer.UnsignedShortType; import mpicbg.imglib.type.numeric.real.DoubleType; import mpicbg.imglib.type.numeric.real.FloatType; /** * PlaneStack is the class where Imglib images are actually stored in ImageJ. Used by ImageStack as the backing * data store to ImagePlus. */ public class PlaneStack<T extends RealType<T>> { //****************** instance variables private Image<T> stack; private int planeWidth; private int planeHeight; private ContainerFactory factory; private RealType<?> type; //****************** private interface /** creates a single plane Imglib image using passed in data. */ private Image<T> createPlane(RealType<T> type, ContainerFactory cFact, Object data, ValueType dType) { int[] dimensions = new int[]{planeWidth, planeHeight, 1}; Image<T> image = ImageUtils.createImage(type, cFact, dimensions); PlanarAccess<ArrayDataAccess<?>> planar = ImageUtils.getPlanarAccess(image); if (planar != null) { int[] planePosition = Index.create(1); ImageUtils.setPlane(image, planePosition, data); } else { SetPlaneOperation<T> planeOp = new SetPlaneOperation<T>(image, Index.create(3), data, dType); planeOp.execute(); } return image; } @SuppressWarnings({"unchecked","rawtypes"}) /** copies a given number of consecutive planes from a source image to a destination image */ private void copyPlanesFromTo(int numPlanes, Image<T> srcImage, int srcPlane, Image<T> dstImage, int dstPlane) { if (numPlanes < 1) return; PlanarAccess srcImagePlanarAccess = ImageUtils.getPlanarAccess(srcImage); PlanarAccess dstImagePlanarAccess = ImageUtils.getPlanarAccess(dstImage); // if both datasets are planar if ((srcImagePlanarAccess != null) && (dstImagePlanarAccess != null)) { // simply copy pixel references for (int i = 0; i < numPlanes; i++) { Object plane = srcImagePlanarAccess.getPlane(srcPlane+i); dstImagePlanarAccess.setPlane(dstPlane+i, plane); } } else // can't just copy pixel references { int[] srcOrigin = Index.create(new int[]{0, 0, srcPlane}); int[] dstOrigin = Index.create(new int[]{0, 0, dstPlane}); int[] span = Span.create(new int[]{this.planeWidth, this.planeHeight, numPlanes}); ImageUtils.copyFromImageToImage(srcImage, srcOrigin, span, dstImage, dstOrigin, span); } } /** * inserts a plane into the PlaneStack. Since Imglib images are immutable it does this by creating a new stack * and copying all the old data appropriately. The new plane's contents are provided. Note that callers of this * method carefully match the desired imglib type and the input data type. * @param atPosition - the stack position for the new plane to occupy * @param data - the plane data as an array of the appropriate type * @param dataLen - the number of elements in the plane * @param desiredType - the imglib type we desire the plane to be of * @param dType - the ValueType of the input data */ private void insertPlane(int atPosition, Object data, int dataLen, RealType<T> desiredType, ValueType dType) { if (dataLen != this.planeWidth*this.planeHeight) throw new IllegalArgumentException("insertPlane(): input data does not match XY dimensions of stack - expected "+ dataLen+" samples but got "+(this.planeWidth*this.planeHeight)+" samples"); long numPlanesNow = getNumPlanes(); if (atPosition < 0) throw new IllegalArgumentException("insertPlane(): negative insertion point requested"); if (atPosition > numPlanesNow+1) throw new IllegalArgumentException("insertPlane(): insertion point too large"); Image<T> newPlane = createPlane(desiredType, this.factory, data, dType); if (this.stack == null) { this.stack = newPlane; this.type = desiredType; } else // we already have some entries in stack { // need to type check against existing planes if ( ! (TypeManager.sameKind(desiredType, this.type)) ) throw new IllegalArgumentException("insertPlane(): type clash - " + this.type + " & " + desiredType); int[] newDims = new int[]{this.planeWidth, this.planeHeight, this.getEndPosition()+1}; Image<T> newStack = ImageUtils.createImage(desiredType, this.factory, newDims); copyPlanesFromTo(atPosition, this.stack, 0, newStack, 0); copyPlanesFromTo(1, newPlane, 0, newStack, atPosition); copyPlanesFromTo(getEndPosition()-atPosition, this.stack, atPosition, newStack, atPosition+1); this.stack = newStack; } } /** a helper method to insert unsigned byte plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertUnsignedPlane(int atPosition, byte[] data) { insertPlane(atPosition, data, data.length, (RealType) new UnsignedByteType(), ValueType.UBYTE); } /** a helper method to insert signed byte plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertSignedPlane(int atPosition, byte[] data) { insertPlane(atPosition, data, data.length, (RealType) new ByteType(), ValueType.BYTE); } /** a helper method to insert unsigned short plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertUnsignedPlane(int atPosition, short[] data) { insertPlane(atPosition, data, data.length, (RealType) new UnsignedShortType(), ValueType.USHORT); } /** a helper method to insert signed short plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertSignedPlane(int atPosition, short[] data) { insertPlane(atPosition, data, data.length, (RealType) new ShortType(), ValueType.SHORT); } /** a helper method to insert unsigned int plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertUnsignedPlane(int atPosition, int[] data) { insertPlane(atPosition, data, data.length, (RealType) new UnsignedIntType(), ValueType.UINT); } /** a helper method to insert signed int plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertSignedPlane(int atPosition, int[] data) { insertPlane(atPosition, data, data.length, (RealType) new IntType(), ValueType.INT); } /** a helper method to insert unsigned long plane data into a PlaneStack */ private void insertUnsignedPlane(int atPosition, long[] data) { throw new IllegalArgumentException("PlaneStack::insertUnsignedPlane(long[]): unsigned long data not supported"); } /** a helper method to insert signed long plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertSignedPlane(int atPosition, long[] data) { insertPlane(atPosition, data, data.length, (RealType) new LongType(), ValueType.LONG); } /** a helper method to insert float plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertPlane(int atPosition, float[] data) { insertPlane(atPosition, data, data.length, (RealType) new FloatType(), ValueType.FLOAT); } /** a helper method to insert double plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertPlane(int atPosition, double[] data) { insertPlane(atPosition, data, data.length, (RealType) new DoubleType(), ValueType.DOUBLE); } //****************** public interface /** constructor - create a PlaneStack directly from an Imglib image */ public PlaneStack(Image<T> stack) { this.stack = stack; this.planeWidth = ImageUtils.getWidth(stack); this.planeHeight = ImageUtils.getHeight(stack); this.factory = stack.getContainerFactory(); this.type = ImageUtils.getType(stack); } /** constructor - create an empty PlaneStack given (x,y) dimensions and a factory for creating an Imglib image. * Note that the backing type is not set until the first slice is added to the PlaneStack. */ public PlaneStack(int width, int height, ContainerFactory factory) { if ((height <= 0) || (width <= 0)) throw new IllegalArgumentException("PlaneStack constructor: width("+width+") and height("+ height+") must both be greater than zero."); this.stack = null; this.planeWidth = width; this.planeHeight = height; this.factory = factory; this.type = null; } /** returns the backing Imglib image */ public Image<T> getStorage() { return this.stack; } /** returns the number of planes in the PlaneStack */ public long getNumPlanes() { if (this.stack == null) return 0; return ImageUtils.getTotalPlanes(getStorage().getDimensions()); } /** returns the end position of the PlaneStack where a new plane can be added */ public int getEndPosition() { long totalPlanes = getNumPlanes(); if (totalPlanes > Integer.MAX_VALUE) throw new IllegalArgumentException("PlaneStack()::getEndPosition() - too many planes"); return (int) totalPlanes; } /** * inserts a plane into the PlaneStack * @param atPosition - the position within the stack where the plane should be inserted. other planes moved to make way * @param unsigned - a boolean specifying whether input data is signed or unsigned * @param data - an array of values representing the plane */ public void insertPlane(int atPosition, boolean unsigned, Object data) { if (data instanceof byte[]) { if (unsigned) insertUnsignedPlane(atPosition,(byte[])data); else insertSignedPlane(atPosition,(byte[])data); } else if (data instanceof short[]) { if (unsigned) insertUnsignedPlane(atPosition,(short[])data); else insertSignedPlane(atPosition,(short[])data); } else if (data instanceof int[]) { if (unsigned) insertUnsignedPlane(atPosition,(int[])data); else insertSignedPlane(atPosition,(int[])data); } else if (data instanceof long[]) { if (unsigned) insertUnsignedPlane(atPosition,(long[])data); else insertSignedPlane(atPosition,(long[])data); } else if (data instanceof float[]) { insertPlane(atPosition,(float[])data); } else if (data instanceof double[]) { insertPlane(atPosition,(double[])data); } else throw new IllegalArgumentException("PlaneStack::insertPlane(Object): unknown data type passed in - "+data.getClass()); } /** * adds a plane to the end of the PlaneStack * @param unsigned - a boolean specifying whether input data is signed or unsigned * @param data - an array of values representing the plane */ public void addPlane(boolean unsigned, Object data) { insertPlane(getEndPosition(), unsigned, data); } /** * deletes a plane from a PlaneStack * @param planeNumber - the index of the plane to delete */ @SuppressWarnings("unchecked") public void deletePlane(int planeNumber) // since multidim an int could be too small but can't avoid { if (this.stack == null) throw new IllegalArgumentException("PlaneStack::deletePlane() - cannot delete from empty stack"); int endPosition = getEndPosition(); if ((planeNumber < 0) || (planeNumber >= endPosition)) throw new IllegalArgumentException("PlaneStack::deletePlane() - planeNumber out of bounds - "+planeNumber+" outside [0,"+endPosition+")"); int[] newDims = new int[]{this.planeWidth, this.planeHeight, this.stack.getDimension(2)-1}; if (newDims[2] == 0) { this.stack = null; return; } // create a new image one plane smaller than existing Image<T> newImage = ImageUtils.createImage((RealType<T>)this.type, this.factory, newDims); copyPlanesFromTo(planeNumber, this.stack, 0, newImage, 0); copyPlanesFromTo(getEndPosition()-planeNumber-1, this.stack, planeNumber+1, newImage, planeNumber); this.stack = newImage; } /** gets a plane from a PlaneStack. returns a reference if possible */ public Object getPlane(int planeNumber) { int planes = this.stack.getDimension(2); if ((planeNumber < 0) || (planeNumber >= planes)) throw new IllegalArgumentException("PlaneStack: index ("+planeNumber+") out of bounds (0-"+planes+")"); PlanarAccess<ArrayDataAccess<?>> planar = ImageUtils.getPlanarAccess(this.stack); if (planar != null) { return planar.getPlane(planeNumber); } else // can't get data directly { int[] planePosition = new int[]{planeNumber}; ValueType asType = SampleManager.getValueType(ImageUtils.getType(this.stack)); return GetPlaneOperation.getPlaneAs(this.stack, planePosition, asType); } } }
imagej/src/main/java/imagej/PlaneStack.java
package imagej; import imagej.SampleInfo.ValueType; import imagej.process.ImageUtils; import imagej.process.Index; import imagej.process.Span; import imagej.process.TypeManager; import imagej.process.operation.GetPlaneOperation; import imagej.process.operation.SetPlaneOperation; import mpicbg.imglib.container.ContainerFactory; import mpicbg.imglib.container.basictypecontainer.PlanarAccess; import mpicbg.imglib.container.basictypecontainer.array.ArrayDataAccess; import mpicbg.imglib.image.Image; import mpicbg.imglib.type.numeric.RealType; import mpicbg.imglib.type.numeric.integer.ByteType; import mpicbg.imglib.type.numeric.integer.IntType; import mpicbg.imglib.type.numeric.integer.LongType; import mpicbg.imglib.type.numeric.integer.ShortType; import mpicbg.imglib.type.numeric.integer.UnsignedByteType; import mpicbg.imglib.type.numeric.integer.UnsignedIntType; import mpicbg.imglib.type.numeric.integer.UnsignedShortType; import mpicbg.imglib.type.numeric.real.DoubleType; import mpicbg.imglib.type.numeric.real.FloatType; /** * PlaneStack is the class where Imglib images are actually stored in ImageJ. Used by ImageStack as the backing * data store to ImagePlus. */ public class PlaneStack<T extends RealType<T>> { //****************** instance variables private Image<T> stack; private int planeWidth; private int planeHeight; private ContainerFactory factory; private RealType<?> type; //****************** private interface /** creates a single plane Imglib image using passed in data. */ private Image<T> createPlane(RealType<T> type, ContainerFactory cFact, Object data, ValueType dType) { int[] dimensions = new int[]{planeWidth, planeHeight, 1}; Image<T> image = ImageUtils.createImage(type, cFact, dimensions); PlanarAccess<ArrayDataAccess<?>> planar = ImageUtils.getPlanarAccess(image); if (planar != null) { int[] planePosition = Index.create(1); ImageUtils.setPlane(image, planePosition, data); } else { SetPlaneOperation<T> planeOp = new SetPlaneOperation<T>(image, Index.create(3), data, dType); planeOp.execute(); } return image; } @SuppressWarnings({"unchecked","rawtypes"}) /** copies a given number of consecutive planes from a source image to a destination image */ private void copyPlanesFromTo(int numPlanes, Image<T> srcImage, int srcPlane, Image<T> dstImage, int dstPlane) { if (numPlanes < 1) return; PlanarAccess srcImagePlanarAccess = ImageUtils.getPlanarAccess(srcImage); PlanarAccess dstImagePlanarAccess = ImageUtils.getPlanarAccess(dstImage); // if both datasets are planar if ((srcImagePlanarAccess != null) && (dstImagePlanarAccess != null)) { // simply copy pixel references for (int i = 0; i < numPlanes; i++) { Object plane = srcImagePlanarAccess.getPlane(srcPlane+i); dstImagePlanarAccess.setPlane(dstPlane+i, plane); } } else // can't just copy pixel references { int[] srcOrigin = Index.create(new int[]{0, 0, srcPlane}); int[] dstOrigin = Index.create(new int[]{0, 0, dstPlane}); int[] span = Span.create(new int[]{this.planeWidth, this.planeHeight, numPlanes}); ImageUtils.copyFromImageToImage(srcImage, srcOrigin, span, dstImage, dstOrigin, span); } } /** * inserts a plane into the PlaneStack. Since Imglib images are immutable it does this by creating a new stack * and copying all the old data appropriately. The new plane's contents are provided. Note that callers of this * method carefully match the desired imglib type and the input data type. * @param atPosition - the stack position for the new plane to occupy * @param data - the plane data as an array of the appropriate type * @param dataLen - the number of elements in the plane * @param desiredType - the imglib type we desire the plane to be of * @param dType - the ValueType of the input data */ private void insertPlane(int atPosition, Object data, int dataLen, RealType<T> desiredType, ValueType dType) { if (dataLen != this.planeWidth*this.planeHeight) throw new IllegalArgumentException("insertPlane(): input data does not match XY dimensions of stack - expected "+ dataLen+" samples but got "+(this.planeWidth*this.planeHeight)+" samples"); long numPlanesNow = getNumPlanes(); if (atPosition < 0) throw new IllegalArgumentException("insertPlane(): negative insertion point requested"); if (atPosition > numPlanesNow+1) throw new IllegalArgumentException("insertPlane(): insertion point too large"); Image<T> newPlane = createPlane(desiredType, this.factory, data, dType); if (this.stack == null) { this.stack = newPlane; this.type = desiredType; } else // we already have some entries in stack { // need to type check against existing planes if ( ! (TypeManager.sameKind(desiredType, this.type)) ) throw new IllegalArgumentException("insertPlane(): type clash - " + this.type + " & " + desiredType); int[] newDims = new int[]{this.planeWidth, this.planeHeight, this.getEndPosition()+1}; Image<T> newStack = ImageUtils.createImage(desiredType, this.factory, newDims); copyPlanesFromTo(atPosition, this.stack, 0, newStack, 0); copyPlanesFromTo(1, newPlane, 0, newStack, atPosition); copyPlanesFromTo(getEndPosition()-atPosition, this.stack, atPosition, newStack, atPosition+1); this.stack = newStack; } } /** a helper method to insert unsigned byte plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertUnsignedPlane(int atPosition, byte[] data) { insertPlane(atPosition, data, data.length, (RealType) new UnsignedByteType(), ValueType.UBYTE); } /** a helper method to insert signed byte plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertSignedPlane(int atPosition, byte[] data) { insertPlane(atPosition, data, data.length, (RealType) new ByteType(), ValueType.BYTE); } /** a helper method to insert unsigned short plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertUnsignedPlane(int atPosition, short[] data) { insertPlane(atPosition, data, data.length, (RealType) new UnsignedShortType(), ValueType.USHORT); } /** a helper method to insert signed short plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertSignedPlane(int atPosition, short[] data) { insertPlane(atPosition, data, data.length, (RealType) new ShortType(), ValueType.SHORT); } /** a helper method to insert unsigned int plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertUnsignedPlane(int atPosition, int[] data) { insertPlane(atPosition, data, data.length, (RealType) new UnsignedIntType(), ValueType.UINT); } /** a helper method to insert signed int plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertSignedPlane(int atPosition, int[] data) { insertPlane(atPosition, data, data.length, (RealType) new IntType(), ValueType.INT); } /** a helper method to insert unsigned long plane data into a PlaneStack */ private void insertUnsignedPlane(int atPosition, long[] data) { throw new IllegalArgumentException("PlaneStack::insertUnsignedPlane(long[]): unsigned long data not supported"); } /** a helper method to insert signed long plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertSignedPlane(int atPosition, long[] data) { insertPlane(atPosition, data, data.length, (RealType) new LongType(), ValueType.LONG); } /** a helper method to insert float plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertPlane(int atPosition, float[] data) { insertPlane(atPosition, data, data.length, (RealType) new FloatType(), ValueType.FLOAT); } /** a helper method to insert double plane data into a PlaneStack */ @SuppressWarnings({"rawtypes","unchecked"}) private void insertPlane(int atPosition, double[] data) { insertPlane(atPosition, data, data.length, (RealType) new DoubleType(), ValueType.DOUBLE); } //****************** public interface /** constructor - create a PlaneStack directly from an Imglib image */ public PlaneStack(Image<T> stack) { this.stack = stack; this.planeWidth = ImageUtils.getWidth(stack); this.planeHeight = ImageUtils.getHeight(stack); this.factory = stack.getContainerFactory(); this.type = ImageUtils.getType(stack); } /** constructor - create an empty PlaneStack given (x,y) dimensions and a factory for creating an Imglib image. * Note that the backing type is not set until the first slice is added to the PlaneStack. */ public PlaneStack(int width, int height, ContainerFactory factory) { if ((height <= 0) || (width <= 0)) throw new IllegalArgumentException("PlaneStack constructor: width("+width+") and height("+ height+") must both be greater than zero."); this.stack = null; this.planeWidth = width; this.planeHeight = height; this.factory = factory; this.type = null; } /** returns the backing Imglib image */ public Image<T> getStorage() { return this.stack; } /** returns the number of planes in the PlaneStack */ public long getNumPlanes() { if (this.stack == null) return 0; return ImageUtils.getTotalPlanes(getStorage().getDimensions()); } /** returns the end position of the PlaneStack where a new plane can be added */ public int getEndPosition() { long totalPlanes = getNumPlanes(); if (totalPlanes > Integer.MAX_VALUE) throw new IllegalArgumentException("PlaneStack()::getEndPosition() - too many planes"); return (int) totalPlanes; } /** * inserts a plane into the PlaneStack * @param atPosition - the position within the stack where the plane should be inserted. other planes moved to make way * @param unsigned - a boolean specifying whether input data is signed or unsigned * @param data - an array of values representing the plane */ public void insertPlane(int atPosition, boolean unsigned, Object data) { if (data instanceof byte[]) { if (unsigned) insertUnsignedPlane(atPosition,(byte[])data); else insertSignedPlane(atPosition,(byte[])data); } else if (data instanceof short[]) { if (unsigned) insertUnsignedPlane(atPosition,(short[])data); else insertSignedPlane(atPosition,(short[])data); } else if (data instanceof int[]) { if (unsigned) insertUnsignedPlane(atPosition,(int[])data); else insertSignedPlane(atPosition,(int[])data); } else if (data instanceof long[]) { if (unsigned) insertUnsignedPlane(atPosition,(long[])data); else insertSignedPlane(atPosition,(long[])data); } else if (data instanceof float[]) { insertPlane(atPosition,(float[])data); } else if (data instanceof double[]) { insertPlane(atPosition,(double[])data); } else throw new IllegalArgumentException("PlaneStack::insertPlane(Object): unknown data type passed in - "+data.getClass()); } /** * adds a plane to the end of the PlaneStack * @param unsigned - a boolean specifying whether input data is signed or unsigned * @param data - an array of values representing the plane */ public void addPlane(boolean unsigned, Object data) { insertPlane(getEndPosition(), unsigned, data); } /** * deletes a plane from a PlaneStack * @param planeNumber - the index of the plane to delete */ @SuppressWarnings("unchecked") public void deletePlane(int planeNumber) // since multidim an int could be too small but can't avoid { if (this.stack == null) throw new IllegalArgumentException("PlaneStack::deletePlane() - cannot delete from empty stack"); int endPosition = getEndPosition(); if ((planeNumber < 0) || (planeNumber >= endPosition)) throw new IllegalArgumentException("PlaneStack::deletePlane() - planeNumber out of bounds - "+planeNumber+" outside [0,"+endPosition+")"); int[] newDims = new int[]{this.planeWidth, this.planeHeight, this.stack.getDimension(2)-1}; if (newDims[2] == 0) { this.stack = null; return; } // create a new image one plane smaller than existing Image<T> newImage = ImageUtils.createImage((RealType<T>)this.type, this.factory, newDims); copyPlanesFromTo(planeNumber, this.stack, 0, newImage, 0); copyPlanesFromTo(getEndPosition()-planeNumber-1, this.stack, planeNumber+1, newImage, planeNumber); this.stack = newImage; } public Object getPlane(int planeNumber) { int planes = this.stack.getDimension(2); if ((planeNumber < 0) || (planeNumber >= planes)) throw new IllegalArgumentException("PlaneStack: index ("+planeNumber+") out of bounds (0-"+planes+")"); PlanarAccess<ArrayDataAccess<?>> planar = ImageUtils.getPlanarAccess(this.stack); if (planar != null) { return planar.getPlane(planeNumber); } else // can't get data directly { int[] planePosition = new int[]{planeNumber}; ValueType asType = SampleManager.getValueType(ImageUtils.getType(this.stack)); return GetPlaneOperation.getPlaneAs(this.stack, planePosition, asType); } } }
added comment This used to be revision r1609.
imagej/src/main/java/imagej/PlaneStack.java
added comment
<ide><path>magej/src/main/java/imagej/PlaneStack.java <ide> <ide> this.stack = newImage; <ide> } <del> <add> <add> /** gets a plane from a PlaneStack. returns a reference if possible */ <ide> public Object getPlane(int planeNumber) <ide> { <ide> int planes = this.stack.getDimension(2);
Java
apache-2.0
9e297df94d578b64e6748bf3d928d55588797269
0
apixandru/intellij-community,vladmm/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,adedayo/intellij-community,jagguli/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,semonte/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,holmes/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,da1z/intellij-community,vvv1559/intellij-community,da1z/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,holmes/intellij-community,allotria/intellij-community,supersven/intellij-community,orekyuu/intellij-community,kool79/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,hurricup/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,holmes/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,ryano144/intellij-community,signed/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,slisson/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,signed/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,izonder/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,samthor/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,apixandru/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,dslomov/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,xfournet/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,asedunov/intellij-community,semonte/intellij-community,supersven/intellij-community,supersven/intellij-community,allotria/intellij-community,allotria/intellij-community,supersven/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,holmes/intellij-community,fitermay/intellij-community,vladmm/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,da1z/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,kool79/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,supersven/intellij-community,samthor/intellij-community,FHannes/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,youdonghai/intellij-community,allotria/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,izonder/intellij-community,diorcety/intellij-community,allotria/intellij-community,izonder/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,adedayo/intellij-community,fnouama/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,apixandru/intellij-community,caot/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,signed/intellij-community,kool79/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,caot/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,fnouama/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,ryano144/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,holmes/intellij-community,clumsy/intellij-community,fnouama/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,Distrotech/intellij-community,signed/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,holmes/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,izonder/intellij-community,adedayo/intellij-community,samthor/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,ibinti/intellij-community,xfournet/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,fnouama/intellij-community,jagguli/intellij-community,samthor/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,kool79/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,slisson/intellij-community,izonder/intellij-community,ibinti/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,hurricup/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,blademainer/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,fitermay/intellij-community,fitermay/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,kool79/intellij-community,orekyuu/intellij-community,allotria/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,kool79/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,retomerz/intellij-community,allotria/intellij-community,amith01994/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,semonte/intellij-community,adedayo/intellij-community,robovm/robovm-studio,fnouama/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,kdwink/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,caot/intellij-community,robovm/robovm-studio,robovm/robovm-studio,tmpgit/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,dslomov/intellij-community,caot/intellij-community,hurricup/intellij-community,fitermay/intellij-community,holmes/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,Lekanich/intellij-community,holmes/intellij-community,FHannes/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,caot/intellij-community,xfournet/intellij-community,FHannes/intellij-community,adedayo/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,kool79/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,ryano144/intellij-community,retomerz/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,da1z/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,jagguli/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,signed/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,samthor/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,signed/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,holmes/intellij-community,slisson/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,FHannes/intellij-community,ibinti/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,izonder/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,izonder/intellij-community,FHannes/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,caot/intellij-community,amith01994/intellij-community,fitermay/intellij-community,supersven/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,robovm/robovm-studio,blademainer/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,slisson/intellij-community,vvv1559/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,diorcety/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,signed/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,da1z/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,slisson/intellij-community,xfournet/intellij-community,amith01994/intellij-community,fnouama/intellij-community,ibinti/intellij-community,robovm/robovm-studio,blademainer/intellij-community,fitermay/intellij-community,robovm/robovm-studio,semonte/intellij-community,kdwink/intellij-community,samthor/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,ryano144/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,caot/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,signed/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,apixandru/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,da1z/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,diorcety/intellij-community,dslomov/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,signed/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,amith01994/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,holmes/intellij-community,vladmm/intellij-community,kdwink/intellij-community,semonte/intellij-community,semonte/intellij-community,hurricup/intellij-community,kdwink/intellij-community,supersven/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,caot/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,signed/intellij-community,kdwink/intellij-community,kdwink/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.ui; import com.intellij.BundleBase; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.ui.*; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.swing.*; import javax.swing.Timer; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.plaf.ComboBoxUI; import javax.swing.plaf.ProgressBarUI; import javax.swing.plaf.basic.BasicComboBoxUI; import javax.swing.plaf.basic.ComboPopup; import javax.swing.text.DefaultEditorKit; import javax.swing.text.JTextComponent; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; import javax.swing.undo.UndoManager; import java.awt.*; import java.awt.event.*; import java.awt.font.FontRenderContext; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ImageObserver; import java.awt.image.PixelGrabber; import java.beans.PropertyChangeListener; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.util.*; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.regex.Pattern; /** * @author max */ @SuppressWarnings("StaticMethodOnlyUsedInOneClass") public class UIUtil { @NonNls public static final String BORDER_LINE = "<hr size=1 noshade>"; private static final StyleSheet DEFAULT_HTML_KIT_CSS; static { // save the default JRE CSS and .. HTMLEditorKit kit = new HTMLEditorKit(); DEFAULT_HTML_KIT_CSS = kit.getStyleSheet(); // .. erase global ref to this CSS so no one can alter it kit.setStyleSheet(null); } public static int getMultiClickInterval() { Object property = Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval"); if (property instanceof Integer) { return (Integer)property; } return 500; } private static final AtomicNotNullLazyValue<Boolean> X_RENDER_ACTIVE = new AtomicNotNullLazyValue<Boolean>() { @NotNull @Override protected Boolean compute() { if (!SystemInfo.isXWindow) { return false; } try { final Class<?> clazz = ClassLoader.getSystemClassLoader().loadClass("sun.awt.X11GraphicsEnvironment"); final Method method = clazz.getMethod("isXRenderAvailable"); return (Boolean)method.invoke(null); } catch (Throwable e) { return false; } } }; private static final String[] STANDARD_FONT_SIZES = {"8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48", "72"}; public static void applyStyle(@NotNull ComponentStyle componentStyle, @NotNull Component comp) { if (!(comp instanceof JComponent)) return; JComponent c = (JComponent)comp; if (isUnderAquaBasedLookAndFeel()) { c.putClientProperty("JComponent.sizeVariant", componentStyle == ComponentStyle.REGULAR ? "regular" : componentStyle == ComponentStyle.SMALL ? "small" : "mini"); } else { c.setFont(getFont( componentStyle == ComponentStyle.REGULAR ? FontSize.NORMAL : componentStyle == ComponentStyle.SMALL ? FontSize.SMALL : FontSize.MINI, c.getFont())); } Container p = c.getParent(); if (p != null) { SwingUtilities.updateComponentTreeUI(p); } } public static Cursor getTextCursor(final Color backgroundColor) { return SystemInfo.isMac && ColorUtil.isDark(backgroundColor) ? MacUIUtil.getInvertedTextCursor() : Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR); } /** * Draws two horizontal lines, the first at {@code topY}, the second at {@code bottomY}. * The purpose of this method (and the ground of the name) is to draw two lines framing a horizontal filled rectangle. * * @param g Graphics context to draw with. * @param startX x-start point. * @param endX x-end point. * @param topY y-coordinate of the first line. * @param bottomY y-coordinate of the second line. * @param color color of the lines. */ public static void drawFramingLines(@NotNull Graphics2D g, int startX, int endX, int topY, int bottomY, @NotNull Color color) { drawLine(g, startX, topY, endX, topY, null, color); drawLine(g, startX, bottomY, endX, bottomY, null, color); } private static final GrayFilter DEFAULT_GRAY_FILTER = new GrayFilter(true, 65); private static final GrayFilter DARCULA_GRAY_FILTER = new GrayFilter(true, 30); public static GrayFilter getGrayFilter() { return isUnderDarcula() ? DARCULA_GRAY_FILTER : DEFAULT_GRAY_FILTER; } public static boolean isAppleRetina() { return isRetina() && SystemInfo.isAppleJvm; } public enum FontSize {NORMAL, SMALL, MINI} public enum ComponentStyle {REGULAR, SMALL, MINI} public enum FontColor {NORMAL, BRIGHTER} public static final char MNEMONIC = BundleBase.MNEMONIC; @NonNls public static final String HTML_MIME = "text/html"; @NonNls public static final String JSLIDER_ISFILLED = "JSlider.isFilled"; @NonNls public static final String ARIAL_FONT_NAME = "Arial"; @NonNls public static final String TABLE_FOCUS_CELL_BACKGROUND_PROPERTY = "Table.focusCellBackground"; @NonNls public static final String CENTER_TOOLTIP_DEFAULT = "ToCenterTooltip"; @NonNls public static final String CENTER_TOOLTIP_STRICT = "ToCenterTooltip.default"; public static final Pattern CLOSE_TAG_PATTERN = Pattern.compile("<\\s*([^<>/ ]+)([^<>]*)/\\s*>", Pattern.CASE_INSENSITIVE); @NonNls public static final String FOCUS_PROXY_KEY = "isFocusProxy"; public static Key<Integer> KEEP_BORDER_SIDES = Key.create("keepBorderSides"); private static final Logger LOG = Logger.getInstance("#com.intellij.util.ui.UIUtil"); private static final Color UNFOCUSED_SELECTION_COLOR = Gray._212; private static final Color ACTIVE_HEADER_COLOR = new Color(160, 186, 213); private static final Color INACTIVE_HEADER_COLOR = Gray._128; private static final Color BORDER_COLOR = Color.LIGHT_GRAY; public static final Color AQUA_SEPARATOR_FOREGROUND_COLOR = Gray._190; public static final Color AQUA_SEPARATOR_BACKGROUND_COLOR = Gray._240; public static final Color TRANSPARENT_COLOR = new Color(0, 0, 0, 0); public static final int DEFAULT_HGAP = 10; public static final int DEFAULT_VGAP = 4; public static final int LARGE_VGAP = 12; public static final Insets PANEL_REGULAR_INSETS = new Insets(8, 12, 8, 12); public static final Insets PANEL_SMALL_INSETS = new Insets(5, 8, 5, 8); public static final Border DEBUG_MARKER_BORDER = new Border() { private final Insets empty = new Insets(0, 0, 0, 0); @Override public Insets getBorderInsets(Component c) { return empty; } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Graphics g2 = g.create(); try { g2.setColor(JBColor.RED); drawDottedRectangle(g2, x, y, x + width - 1, y + height - 1); } finally { g2.dispose(); } } @Override public boolean isBorderOpaque() { return true; } }; // accessed only from EDT private static final HashMap<Color, BufferedImage> ourAppleDotSamples = new HashMap<Color, BufferedImage>(); private static volatile Pair<String, Integer> ourSystemFontData = null; @NonNls private static final String ROOT_PANE = "JRootPane.future"; private static final Ref<Boolean> ourRetina = Ref.create(SystemInfo.isMac ? null : false); private UIUtil() { } public static boolean isRetina() { if (GraphicsEnvironment.isHeadless()) return false; //Temporary workaround for HiDPI on Windows/Linux if ("true".equalsIgnoreCase(System.getProperty("is.hidpi"))) { return true; } synchronized (ourRetina) { if (ourRetina.isNull()) { ourRetina.set(false); // in case HiDPIScaledImage.drawIntoImage is not called for some reason if (SystemInfo.isJavaVersionAtLeast("1.6.0_33") && SystemInfo.isAppleJvm) { if (!"false".equals(System.getProperty("ide.mac.retina"))) { ourRetina.set(IsRetina.isRetina()); return ourRetina.get(); } } else if (SystemInfo.isJavaVersionAtLeast("1.7.0_40") && SystemInfo.isOracleJvm) { try { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); final GraphicsDevice device = env.getDefaultScreenDevice(); Field field = device.getClass().getDeclaredField("scale"); if (field != null) { field.setAccessible(true); Object scale = field.get(device); if (scale instanceof Integer && ((Integer)scale).intValue() == 2) { ourRetina.set(true); return true; } } } catch (AWTError ignore) {} catch (Exception ignore) {} } ourRetina.set(false); } return ourRetina.get(); } } public static boolean hasLeakingAppleListeners() { // in version 1.6.0_29 Apple introduced a memory leak in JViewport class - they add a PropertyChangeListeners to the CToolkit // but never remove them: // JViewport.java: // public JViewport() { // ... // final Toolkit toolkit = Toolkit.getDefaultToolkit(); // if(toolkit instanceof CToolkit) // { // final boolean isRunningInHiDPI = ((CToolkit)toolkit).runningInHiDPI(); // if(isRunningInHiDPI) setScrollMode(0); // toolkit.addPropertyChangeListener("apple.awt.contentScaleFactor", new PropertyChangeListener() { ... }); // } // } return SystemInfo.isMac && System.getProperty("java.runtime.version").startsWith("1.6.0_29"); } public static void removeLeakingAppleListeners() { if (!hasLeakingAppleListeners()) return; Toolkit toolkit = Toolkit.getDefaultToolkit(); String name = "apple.awt.contentScaleFactor"; for (PropertyChangeListener each : toolkit.getPropertyChangeListeners(name)) { toolkit.removePropertyChangeListener(name, each); } } public static String getHtmlBody(String text) { return getHtmlBody(new Html(text)); } public static String getHtmlBody(Html html) { String text = html.getText(); String result; if (!text.startsWith("<html>")) { result = text.replaceAll("\n", "<br>"); } else { final int bodyIdx = text.indexOf("<body>"); final int closedBodyIdx = text.indexOf("</body>"); if (bodyIdx != -1 && closedBodyIdx != -1) { result = text.substring(bodyIdx + "<body>".length(), closedBodyIdx); } else { text = StringUtil.trimStart(text, "<html>").trim(); text = StringUtil.trimEnd(text, "</html>").trim(); text = StringUtil.trimStart(text, "<body>").trim(); text = StringUtil.trimEnd(text, "</body>").trim(); result = text; } } return html.isKeepFont() ? result : result.replaceAll("<font(.*?)>", "").replaceAll("</font>", ""); } public static void drawLinePickedOut(Graphics graphics, int x, int y, int x1, int y1) { if (x == x1) { int minY = Math.min(y, y1); int maxY = Math.max(y, y1); graphics.drawLine(x, minY + 1, x1, maxY - 1); } else if (y == y1) { int minX = Math.min(x, x1); int maxX = Math.max(x, x1); graphics.drawLine(minX + 1, y, maxX - 1, y1); } else { drawLine(graphics, x, y, x1, y1); } } public static boolean isReallyTypedEvent(KeyEvent e) { char c = e.getKeyChar(); if (c < 0x20 || c == 0x7F) return false; if (SystemInfo.isMac) { return !e.isMetaDown() && !e.isControlDown(); } return !e.isAltDown() && !e.isControlDown(); } public static int getStringY(@NotNull final String string, @NotNull final Rectangle bounds, @NotNull final Graphics2D g) { final int centerY = bounds.height / 2; final Font font = g.getFont(); final FontRenderContext frc = g.getFontRenderContext(); final Rectangle stringBounds = font.getStringBounds(string, frc).getBounds(); return (int)(centerY - stringBounds.height / 2.0 - stringBounds.y); } public static void setEnabled(Component component, boolean enabled, boolean recursively) { component.setEnabled(enabled); if (component instanceof JComboBox && isUnderAquaLookAndFeel()) { // On Mac JComboBox instances have children: com.apple.laf.AquaComboBoxButton and javax.swing.CellRendererPane. // Disabling these children results in ugly UI: WEB-10733 return; } if (component instanceof JLabel) { Color color = enabled ? getLabelForeground() : getLabelDisabledForeground(); if (color != null) { component.setForeground(color); } } if (recursively && enabled == component.isEnabled()) { if (component instanceof Container) { final Container container = (Container)component; final int subComponentCount = container.getComponentCount(); for (int i = 0; i < subComponentCount; i++) { setEnabled(container.getComponent(i), enabled, recursively); } } } } public static void drawLine(Graphics g, int x1, int y1, int x2, int y2) { g.drawLine(x1, y1, x2, y2); } public static void drawLine(Graphics2D g, int x1, int y1, int x2, int y2, @Nullable Color bgColor, @Nullable Color fgColor) { Color oldFg = g.getColor(); Color oldBg = g.getBackground(); if (fgColor != null) { g.setColor(fgColor); } if (bgColor != null) { g.setBackground(bgColor); } drawLine(g, x1, y1, x2, y2); if (fgColor != null) { g.setColor(oldFg); } if (bgColor != null) { g.setBackground(oldBg); } } @NotNull public static String[] splitText(String text, FontMetrics fontMetrics, int widthLimit, char separator) { ArrayList<String> lines = new ArrayList<String>(); String currentLine = ""; StringBuilder currentAtom = new StringBuilder(); for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); currentAtom.append(ch); if (ch == separator) { currentLine += currentAtom.toString(); currentAtom.setLength(0); } String s = currentLine + currentAtom.toString(); int width = fontMetrics.stringWidth(s); if (width >= widthLimit - fontMetrics.charWidth('w')) { if (!currentLine.isEmpty()) { lines.add(currentLine); currentLine = ""; } else { lines.add(currentAtom.toString()); currentAtom.setLength(0); } } } String s = currentLine + currentAtom.toString(); if (!s.isEmpty()) { lines.add(s); } return ArrayUtil.toStringArray(lines); } public static void setActionNameAndMnemonic(@NotNull String text, @NotNull Action action) { assignMnemonic(text, action); text = text.replaceAll("&", ""); action.putValue(Action.NAME, text); } public static void assignMnemonic(@NotNull String text, @NotNull Action action) { int mnemoPos = text.indexOf('&'); if (mnemoPos >= 0 && mnemoPos < text.length() - 2) { String mnemoChar = text.substring(mnemoPos + 1, mnemoPos + 2).trim(); if (mnemoChar.length() == 1) { action.putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnemoChar.charAt(0))); } } } public static Font getLabelFont(@NotNull FontSize size) { return getFont(size, null); } @NotNull public static Font getFont(@NotNull FontSize size, @Nullable Font base) { if (base == null) base = getLabelFont(); return base.deriveFont(getFontSize(size)); } public static float getFontSize(FontSize size) { int defSize = getLabelFont().getSize(); switch (size) { case SMALL: return Math.max(defSize - 2f, 11f); case MINI: return Math.max(defSize - 4f, 9f); default: return defSize; } } public static Color getLabelFontColor(FontColor fontColor) { Color defColor = getLabelForeground(); if (fontColor == FontColor.BRIGHTER) { return new JBColor(new Color(Math.min(defColor.getRed() + 50, 255), Math.min(defColor.getGreen() + 50, 255), Math.min( defColor.getBlue() + 50, 255)), defColor.darker()); } return defColor; } public static int getScrollBarWidth() { return UIManager.getInt("ScrollBar.width"); } public static Font getLabelFont() { return UIManager.getFont("Label.font"); } public static Color getLabelBackground() { return UIManager.getColor("Label.background"); } public static Color getLabelForeground() { return UIManager.getColor("Label.foreground"); } public static Color getLabelDisabledForeground() { final Color color = UIManager.getColor("Label.disabledForeground"); if (color != null) return color; return UIManager.getColor("Label.disabledText"); } /** @deprecated to remove in IDEA 14 */ @SuppressWarnings("UnusedDeclaration") public static Icon getOptionPanelWarningIcon() { return getWarningIcon(); } /** @deprecated to remove in IDEA 14 */ @SuppressWarnings("UnusedDeclaration") public static Icon getOptionPanelQuestionIcon() { return getQuestionIcon(); } @NotNull public static String removeMnemonic(@NotNull String s) { if (s.indexOf('&') != -1) { s = StringUtil.replace(s, "&", ""); } if (s.indexOf('_') != -1) { s = StringUtil.replace(s, "_", ""); } if (s.indexOf(MNEMONIC) != -1) { s = StringUtil.replace(s, String.valueOf(MNEMONIC), ""); } return s; } public static int getDisplayMnemonicIndex(@NotNull String s) { int idx = s.indexOf('&'); if (idx >= 0 && idx != s.length() - 1 && idx == s.lastIndexOf('&')) return idx; idx = s.indexOf(MNEMONIC); if (idx >= 0 && idx != s.length() - 1 && idx == s.lastIndexOf(MNEMONIC)) return idx; return -1; } public static String replaceMnemonicAmpersand(final String value) { return BundleBase.replaceMnemonicAmpersand(value); } public static Color getTableHeaderBackground() { return UIManager.getColor("TableHeader.background"); } public static Color getTreeTextForeground() { return UIManager.getColor("Tree.textForeground"); } public static Color getTreeSelectionBackground() { if (isUnderNimbusLookAndFeel()) { Color color = UIManager.getColor("Tree.selectionBackground"); if (color != null) return color; color = UIManager.getColor("nimbusSelectionBackground"); if (color != null) return color; } return UIManager.getColor("Tree.selectionBackground"); } public static Color getTreeTextBackground() { return UIManager.getColor("Tree.textBackground"); } public static Color getListSelectionForeground() { final Color color = UIManager.getColor("List.selectionForeground"); if (color == null) { return UIManager.getColor("List[Selected].textForeground"); // Nimbus } return color; } public static Color getFieldForegroundColor() { return UIManager.getColor("field.foreground"); } public static Color getTableSelectionBackground() { if (isUnderNimbusLookAndFeel()) { Color color = UIManager.getColor("Table[Enabled+Selected].textBackground"); if (color != null) return color; color = UIManager.getColor("nimbusSelectionBackground"); if (color != null) return color; } return UIManager.getColor("Table.selectionBackground"); } public static Color getActiveTextColor() { return UIManager.getColor("textActiveText"); } public static Color getInactiveTextColor() { return UIManager.getColor("textInactiveText"); } public static Color getSlightlyDarkerColor(Color c) { float[] hsl = Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(), new float[3]); return new Color(Color.HSBtoRGB(hsl[0], hsl[1], hsl[2] - .08f > 0 ? hsl[2] - .08f : hsl[2])); } /** * @deprecated use com.intellij.util.ui.UIUtil#getTextFieldBackground() */ public static Color getActiveTextFieldBackgroundColor() { return getTextFieldBackground(); } public static Color getInactiveTextFieldBackgroundColor() { return UIManager.getColor("TextField.inactiveBackground"); } public static Font getTreeFont() { return UIManager.getFont("Tree.font"); } public static Font getListFont() { return UIManager.getFont("List.font"); } public static Color getTreeSelectionForeground() { return UIManager.getColor("Tree.selectionForeground"); } /** * @deprecated use com.intellij.util.ui.UIUtil#getInactiveTextColor() */ public static Color getTextInactiveTextColor() { return getInactiveTextColor(); } public static void installPopupMenuColorAndFonts(final JComponent contentPane) { LookAndFeel.installColorsAndFont(contentPane, "PopupMenu.background", "PopupMenu.foreground", "PopupMenu.font"); } public static void installPopupMenuBorder(final JComponent contentPane) { LookAndFeel.installBorder(contentPane, "PopupMenu.border"); } public static Color getTreeSelectionBorderColor() { return UIManager.getColor("Tree.selectionBorderColor"); } public static int getTreeRightChildIndent() { return UIManager.getInt("Tree.rightChildIndent"); } public static int getTreeLeftChildIndent() { return UIManager.getInt("Tree.leftChildIndent"); } public static Color getToolTipBackground() { return UIManager.getColor("ToolTip.background"); } public static Color getToolTipForeground() { return UIManager.getColor("ToolTip.foreground"); } public static Color getComboBoxDisabledForeground() { return UIManager.getColor("ComboBox.disabledForeground"); } public static Color getComboBoxDisabledBackground() { return UIManager.getColor("ComboBox.disabledBackground"); } public static Color getButtonSelectColor() { return UIManager.getColor("Button.select"); } public static Integer getPropertyMaxGutterIconWidth(final String propertyPrefix) { return (Integer)UIManager.get(propertyPrefix + ".maxGutterIconWidth"); } public static Color getMenuItemDisabledForeground() { return UIManager.getColor("MenuItem.disabledForeground"); } public static Object getMenuItemDisabledForegroundObject() { return UIManager.get("MenuItem.disabledForeground"); } public static Object getTabbedPanePaintContentBorder(final JComponent c) { return c.getClientProperty("TabbedPane.paintContentBorder"); } public static boolean isMenuCrossMenuMnemonics() { return UIManager.getBoolean("Menu.crossMenuMnemonic"); } public static Color getTableBackground() { // Under GTK+ L&F "Table.background" often has main panel color, which looks ugly return isUnderGTKLookAndFeel() ? getTreeTextBackground() : UIManager.getColor("Table.background"); } public static Color getTableBackground(final boolean isSelected) { return isSelected ? getTableSelectionBackground() : getTableBackground(); } public static Color getTableSelectionForeground() { if (isUnderNimbusLookAndFeel()) { return UIManager.getColor("Table[Enabled+Selected].textForeground"); } return UIManager.getColor("Table.selectionForeground"); } public static Color getTableForeground() { return UIManager.getColor("Table.foreground"); } public static Color getTableForeground(final boolean isSelected) { return isSelected ? getTableSelectionForeground() : getTableForeground(); } public static Color getTableGridColor() { return UIManager.getColor("Table.gridColor"); } public static Color getListBackground() { if (isUnderNimbusLookAndFeel()) { final Color color = UIManager.getColor("List.background"); //noinspection UseJBColor return new Color(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); } // Under GTK+ L&F "Table.background" often has main panel color, which looks ugly return isUnderGTKLookAndFeel() ? getTreeTextBackground() : UIManager.getColor("List.background"); } public static Color getListBackground(boolean isSelected) { return isSelected ? getListSelectionBackground() : getListBackground(); } public static Color getListForeground() { return UIManager.getColor("List.foreground"); } public static Color getListForeground(boolean isSelected) { return isSelected ? getListSelectionForeground() : getListForeground(); } public static Color getPanelBackground() { return UIManager.getColor("Panel.background"); } public static Color getTreeBackground() { return UIManager.getColor("Tree.background"); } public static Color getTreeForeground() { return UIManager.getColor("Tree.foreground"); } public static Color getTableFocusCellBackground() { return UIManager.getColor(TABLE_FOCUS_CELL_BACKGROUND_PROPERTY); } public static Color getListSelectionBackground() { if (isUnderNimbusLookAndFeel()) { return UIManager.getColor("List[Selected].textBackground"); // Nimbus } return UIManager.getColor("List.selectionBackground"); } public static Color getListUnfocusedSelectionBackground() { return isUnderDarcula() ? Gray._52 : UNFOCUSED_SELECTION_COLOR; } public static Color getTreeSelectionBackground(boolean focused) { return focused ? getTreeSelectionBackground() : getTreeUnfocusedSelectionBackground(); } public static Color getTreeUnfocusedSelectionBackground() { Color background = getTreeTextBackground(); return ColorUtil.isDark(background) ? new JBColor(Gray._30, new Color(13, 41, 62)) : UNFOCUSED_SELECTION_COLOR; } public static Color getTextFieldForeground() { return UIManager.getColor("TextField.foreground"); } public static Color getTextFieldBackground() { return isUnderGTKLookAndFeel() ? UIManager.getColor("EditorPane.background") : UIManager.getColor("TextField.background"); } public static Font getButtonFont() { return UIManager.getFont("Button.font"); } public static Font getToolTipFont() { return UIManager.getFont("ToolTip.font"); } public static Color getTabbedPaneBackground() { return UIManager.getColor("TabbedPane.background"); } public static void setSliderIsFilled(final JSlider slider, final boolean value) { slider.putClientProperty("JSlider.isFilled", Boolean.valueOf(value)); } public static Color getLabelTextForeground() { return UIManager.getColor("Label.textForeground"); } public static Color getControlColor() { return UIManager.getColor("control"); } public static Font getOptionPaneMessageFont() { return UIManager.getFont("OptionPane.messageFont"); } public static Font getMenuFont() { return UIManager.getFont("Menu.font"); } public static Color getSeparatorForeground() { return UIManager.getColor("Separator.foreground"); } public static Color getSeparatorBackground() { return UIManager.getColor("Separator.background"); } public static Color getSeparatorShadow() { return UIManager.getColor("Separator.shadow"); } public static Color getSeparatorHighlight() { return UIManager.getColor("Separator.highlight"); } public static Color getSeparatorColorUnderNimbus() { return UIManager.getColor("nimbusBlueGrey"); } public static Color getSeparatorColor() { Color separatorColor = getSeparatorForeground(); if (isUnderAlloyLookAndFeel()) { separatorColor = getSeparatorShadow(); } if (isUnderNimbusLookAndFeel()) { separatorColor = getSeparatorColorUnderNimbus(); } //under GTK+ L&F colors set hard if (isUnderGTKLookAndFeel()) { separatorColor = Gray._215; } return separatorColor; } public static Border getTableFocusCellHighlightBorder() { return UIManager.getBorder("Table.focusCellHighlightBorder"); } public static void setLineStyleAngled(final ClientPropertyHolder component) { component.putClientProperty("JTree.lineStyle", "Angled"); } public static void setLineStyleAngled(final JTree component) { component.putClientProperty("JTree.lineStyle", "Angled"); } public static Color getTableFocusCellForeground() { return UIManager.getColor("Table.focusCellForeground"); } /** * @deprecated use com.intellij.util.ui.UIUtil#getPanelBackground() instead */ public static Color getPanelBackgound() { return getPanelBackground(); } public static Border getTextFieldBorder() { return UIManager.getBorder("TextField.border"); } public static Border getButtonBorder() { return UIManager.getBorder("Button.border"); } public static Icon getErrorIcon() { return UIManager.getIcon("OptionPane.errorIcon"); } public static Icon getInformationIcon() { return UIManager.getIcon("OptionPane.informationIcon"); } public static Icon getQuestionIcon() { return UIManager.getIcon("OptionPane.questionIcon"); } public static Icon getWarningIcon() { return UIManager.getIcon("OptionPane.warningIcon"); } public static Icon getBalloonInformationIcon() { return AllIcons.General.BalloonInformation; } public static Icon getBalloonWarningIcon() { return AllIcons.General.BalloonWarning; } public static Icon getBalloonErrorIcon() { return AllIcons.General.BalloonError; } public static Icon getRadioButtonIcon() { return UIManager.getIcon("RadioButton.icon"); } public static Icon getTreeNodeIcon(boolean expanded, boolean selected, boolean focused) { boolean white = (selected && focused) || isUnderDarcula(); Icon selectedIcon = getTreeSelectedExpandedIcon(); Icon notSelectedIcon = getTreeExpandedIcon(); int width = Math.max(selectedIcon.getIconWidth(), notSelectedIcon.getIconWidth()); int height = Math.max(selectedIcon.getIconWidth(), notSelectedIcon.getIconWidth()); return new CenteredIcon(expanded ? (white ? getTreeSelectedExpandedIcon() : getTreeExpandedIcon()) : (white ? getTreeSelectedCollapsedIcon() : getTreeCollapsedIcon()), width, height, false); } public static Icon getTreeCollapsedIcon() { return UIManager.getIcon("Tree.collapsedIcon"); } public static Icon getTreeExpandedIcon() { return UIManager.getIcon("Tree.expandedIcon"); } public static Icon getTreeIcon(boolean expanded) { return expanded ? getTreeExpandedIcon() : getTreeCollapsedIcon(); } public static Icon getTreeSelectedCollapsedIcon() { return isUnderAquaBasedLookAndFeel() || isUnderNimbusLookAndFeel() || isUnderGTKLookAndFeel() || isUnderDarcula() || isUnderIntelliJLaF() ? AllIcons.Mac.Tree_white_right_arrow : getTreeCollapsedIcon(); } public static Icon getTreeSelectedExpandedIcon() { return isUnderAquaBasedLookAndFeel() || isUnderNimbusLookAndFeel() || isUnderGTKLookAndFeel() || isUnderDarcula() || isUnderIntelliJLaF() ? AllIcons.Mac.Tree_white_down_arrow : getTreeExpandedIcon(); } public static Border getTableHeaderCellBorder() { return UIManager.getBorder("TableHeader.cellBorder"); } public static Color getWindowColor() { return UIManager.getColor("window"); } public static Color getTextAreaForeground() { return UIManager.getColor("TextArea.foreground"); } public static Color getOptionPaneBackground() { return UIManager.getColor("OptionPane.background"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderAlloyLookAndFeel() { return UIManager.getLookAndFeel().getName().contains("Alloy"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderAlloyIDEALookAndFeel() { return isUnderAlloyLookAndFeel() && UIManager.getLookAndFeel().getName().contains("IDEA"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderWindowsLookAndFeel() { return UIManager.getLookAndFeel().getName().equals("Windows"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderWindowsClassicLookAndFeel() { return UIManager.getLookAndFeel().getName().equals("Windows Classic"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderNimbusLookAndFeel() { return UIManager.getLookAndFeel().getName().contains("Nimbus"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderAquaLookAndFeel() { return SystemInfo.isMac && UIManager.getLookAndFeel().getName().contains("Mac OS X"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderJGoodiesLookAndFeel() { return UIManager.getLookAndFeel().getName().contains("JGoodies"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderAquaBasedLookAndFeel() { return SystemInfo.isMac && (isUnderAquaLookAndFeel() || isUnderDarcula()); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderDarcula() { return UIManager.getLookAndFeel().getName().contains("Darcula"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderIntelliJLaF() { return UIManager.getLookAndFeel().getName().contains("IntelliJ"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderGTKLookAndFeel() { return UIManager.getLookAndFeel().getName().contains("GTK"); } public static final Color GTK_AMBIANCE_TEXT_COLOR = new Color(223, 219, 210); public static final Color GTK_AMBIANCE_BACKGROUND_COLOR = new Color(67, 66, 63); @SuppressWarnings({"HardCodedStringLiteral"}) @Nullable public static String getGtkThemeName() { final LookAndFeel laf = UIManager.getLookAndFeel(); if (laf != null && "GTKLookAndFeel".equals(laf.getClass().getSimpleName())) { try { final Method method = laf.getClass().getDeclaredMethod("getGtkThemeName"); method.setAccessible(true); final Object theme = method.invoke(laf); if (theme != null) { return theme.toString(); } } catch (Exception ignored) { } } return null; } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isMurrineBasedTheme() { final String gtkTheme = getGtkThemeName(); return "Ambiance".equalsIgnoreCase(gtkTheme) || "Radiance".equalsIgnoreCase(gtkTheme) || "Dust".equalsIgnoreCase(gtkTheme) || "Dust Sand".equalsIgnoreCase(gtkTheme); } public static Color shade(final Color c, final double factor, final double alphaFactor) { assert factor >= 0 : factor; return new Color( Math.min((int)Math.round(c.getRed() * factor), 255), Math.min((int)Math.round(c.getGreen() * factor), 255), Math.min((int)Math.round(c.getBlue() * factor), 255), Math.min((int)Math.round(c.getAlpha() * alphaFactor), 255) ); } public static Color mix(final Color c1, final Color c2, final double factor) { assert 0 <= factor && factor <= 1.0 : factor; final double backFactor = 1.0 - factor; return new Color( Math.min((int)Math.round(c1.getRed() * backFactor + c2.getRed() * factor), 255), Math.min((int)Math.round(c1.getGreen() * backFactor + c2.getGreen() * factor), 255), Math.min((int)Math.round(c1.getBlue() * backFactor + c2.getBlue() * factor), 255) ); } public static boolean isFullRowSelectionLAF() { return isUnderGTKLookAndFeel(); } public static boolean isUnderNativeMacLookAndFeel() { return isUnderAquaLookAndFeel() || isUnderDarcula(); } public static int getListCellHPadding() { return isUnderNativeMacLookAndFeel() ? 7 : 2; } public static int getListCellVPadding() { return 1; } public static Insets getListCellPadding() { return new Insets(getListCellVPadding(), getListCellHPadding(), getListCellVPadding(), getListCellHPadding()); } public static Insets getListViewportPadding() { return isUnderNativeMacLookAndFeel() ? new Insets(1, 0, 1, 0) : new Insets(5, 5, 5, 5); } public static boolean isToUseDottedCellBorder() { return !isUnderNativeMacLookAndFeel(); } public static boolean isControlKeyDown(MouseEvent mouseEvent) { return SystemInfo.isMac ? mouseEvent.isMetaDown() : mouseEvent.isControlDown(); } public static String[] getValidFontNames(final boolean familyName) { Set<String> result = new TreeSet<String>(); // adds fonts that can display symbols at [A, Z] + [a, z] + [0, 9] for (Font font : GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts()) { try { if (isValidFont(font)) { result.add(familyName ? font.getFamily() : font.getName()); } } catch (Exception ignore) { // JRE has problems working with the font. Just skip. } } // add label font (if isn't listed among above) Font labelFont = getLabelFont(); if (labelFont != null && isValidFont(labelFont)) { result.add(familyName ? labelFont.getFamily() : labelFont.getName()); } return ArrayUtil.toStringArray(result); } public static String[] getStandardFontSizes() { return STANDARD_FONT_SIZES; } public static boolean isValidFont(@NotNull Font font) { try { return font.canDisplay('a') && font.canDisplay('z') && font.canDisplay('A') && font.canDisplay('Z') && font.canDisplay('0') && font.canDisplay('1'); } catch (Exception e) { // JRE has problems working with the font. Just skip. return false; } } public static void setupEnclosingDialogBounds(final JComponent component) { component.revalidate(); component.repaint(); final Window window = SwingUtilities.windowForComponent(component); if (window != null && (window.getSize().height < window.getMinimumSize().height || window.getSize().width < window.getMinimumSize().width)) { window.pack(); } } public static String displayPropertiesToCSS(Font font, Color fg) { @NonNls StringBuilder rule = new StringBuilder("body {"); if (font != null) { rule.append(" font-family: "); rule.append(font.getFamily()); rule.append(" ; "); rule.append(" font-size: "); rule.append(font.getSize()); rule.append("pt ;"); if (font.isBold()) { rule.append(" font-weight: 700 ; "); } if (font.isItalic()) { rule.append(" font-style: italic ; "); } } if (fg != null) { rule.append(" color: #"); appendColor(fg, rule); rule.append(" ; "); } rule.append(" }"); return rule.toString(); } public static void appendColor(final Color color, final StringBuilder sb) { if (color.getRed() < 16) sb.append('0'); sb.append(Integer.toHexString(color.getRed())); if (color.getGreen() < 16) sb.append('0'); sb.append(Integer.toHexString(color.getGreen())); if (color.getBlue() < 16) sb.append('0'); sb.append(Integer.toHexString(color.getBlue())); } /** * @param g graphics. * @param x top left X coordinate. * @param y top left Y coordinate. * @param x1 right bottom X coordinate. * @param y1 right bottom Y coordinate. */ public static void drawDottedRectangle(Graphics g, int x, int y, int x1, int y1) { int i1; for (i1 = x; i1 <= x1; i1 += 2) { drawLine(g, i1, y, i1, y); } for (i1 = i1 != x1 + 1 ? y + 2 : y + 1; i1 <= y1; i1 += 2) { drawLine(g, x1, i1, x1, i1); } for (i1 = i1 != y1 + 1 ? x1 - 2 : x1 - 1; i1 >= x; i1 -= 2) { drawLine(g, i1, y1, i1, y1); } for (i1 = i1 != x - 1 ? y1 - 2 : y1 - 1; i1 >= y; i1 -= 2) { drawLine(g, x, i1, x, i1); } } /** * Should be invoked only in EDT. * * @param g Graphics surface * @param startX Line start X coordinate * @param endX Line end X coordinate * @param lineY Line Y coordinate * @param bgColor Background color (optional) * @param fgColor Foreground color (optional) * @param opaque If opaque the image will be dr */ public static void drawBoldDottedLine(final Graphics2D g, final int startX, final int endX, final int lineY, final Color bgColor, final Color fgColor, final boolean opaque) { if ((SystemInfo.isMac && !isRetina()) || SystemInfo.isLinux) { drawAppleDottedLine(g, startX, endX, lineY, bgColor, fgColor, opaque); } else { drawBoringDottedLine(g, startX, endX, lineY, bgColor, fgColor, opaque); } } public static void drawSearchMatch(final Graphics2D g, final int startX, final int endX, final int height) { Color c1 = new Color(255, 234, 162); Color c2 = new Color(255, 208, 66); drawSearchMatch(g, startX, endX, height, c1, c2); } public static void drawSearchMatch(Graphics2D g, int startX, int endX, int height, Color c1, Color c2) { final boolean drawRound = endX - startX > 4; final Composite oldComposite = g.getComposite(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f)); g.setPaint(getGradientPaint(startX, 2, c1, startX, height - 5, c2)); if (isRetina()) { g.fillRoundRect(startX - 1, 2, endX - startX + 1, height - 4, 5, 5); g.setComposite(oldComposite); return; } g.fillRect(startX, 3, endX - startX, height - 5); if (drawRound) { g.drawLine(startX - 1, 4, startX - 1, height - 4); g.drawLine(endX, 4, endX, height - 4); g.setColor(new Color(100, 100, 100, 50)); g.drawLine(startX - 1, 4, startX - 1, height - 4); g.drawLine(endX, 4, endX, height - 4); g.drawLine(startX, 3, endX - 1, 3); g.drawLine(startX, height - 3, endX - 1, height - 3); } g.setComposite(oldComposite); } public static void drawRectPickedOut(Graphics2D g, int x, int y, int w, int h) { g.drawLine(x + 1, y, x + w - 1, y); g.drawLine(x + w, y + 1, x + w, y + h - 1); g.drawLine(x + w - 1, y + h, x + 1, y + h); g.drawLine(x, y + 1, x, y + h - 1); } private static void drawBoringDottedLine(final Graphics2D g, final int startX, final int endX, final int lineY, final Color bgColor, final Color fgColor, final boolean opaque) { final Color oldColor = g.getColor(); // Fill 2 lines with background color if (opaque && bgColor != null) { g.setColor(bgColor); drawLine(g, startX, lineY, endX, lineY); drawLine(g, startX, lineY + 1, endX, lineY + 1); } // Draw dotted line: // // CCC CCC CCC ... // CCC CCC CCC ... // // (where "C" - colored pixel, " " - white pixel) final int step = 4; final int startPosCorrection = startX % step < 3 ? 0 : 1; g.setColor(fgColor != null ? fgColor : oldColor); // Now draw bold line segments for (int dotXi = (startX / step + startPosCorrection) * step; dotXi < endX; dotXi += step) { g.drawLine(dotXi, lineY, dotXi + 1, lineY); g.drawLine(dotXi, lineY + 1, dotXi + 1, lineY + 1); } // restore color g.setColor(oldColor); } public static void drawGradientHToolbarBackground(final Graphics g, final int width, final int height) { final Graphics2D g2d = (Graphics2D)g; g2d.setPaint(getGradientPaint(0, 0, Gray._215, 0, height, Gray._200)); g2d.fillRect(0, 0, width, height); } public static void drawHeader(Graphics g, int x, int width, int height, boolean active, boolean drawTopLine) { drawHeader(g, x, width, height, active, false, drawTopLine, true); } public static void drawHeader(Graphics g, int x, int width, int height, boolean active, boolean toolWindow, boolean drawTopLine, boolean drawBottomLine) { g.setColor(getPanelBackground()); g.fillRect(x, 0, width, height); ((Graphics2D)g).setPaint(getGradientPaint(0, 0, new Color(0, 0, 0, 5), 0, height, new Color(0, 0, 0, 20))); g.fillRect(x, 0, width, height); g.setColor(new Color(0, 0, 0, toolWindow ? 90 : 50)); if (drawTopLine) g.drawLine(x, 0, width, 0); if (drawBottomLine) g.drawLine(x, height - 1, width, height - 1); g.setColor(isUnderDarcula() ? Gray._255.withAlpha(30) : new Color(255, 255, 255, 100)); g.drawLine(x, drawTopLine ? 1 : 0, width, drawTopLine ? 1 : 0); if (active) { g.setColor(new Color(100, 150, 230, toolWindow ? 50 : 30)); g.fillRect(x, 0, width, height); } } public static void drawDoubleSpaceDottedLine(final Graphics2D g, final int start, final int end, final int xOrY, final Color fgColor, boolean horizontal) { g.setColor(fgColor); for (int dot = start; dot < end; dot += 3) { if (horizontal) { g.drawLine(dot, xOrY, dot, xOrY); } else { g.drawLine(xOrY, dot, xOrY, dot); } } } private static void drawAppleDottedLine(final Graphics2D g, final int startX, final int endX, final int lineY, final Color bgColor, final Color fgColor, final boolean opaque) { final Color oldColor = g.getColor(); // Fill 3 lines with background color if (opaque && bgColor != null) { g.setColor(bgColor); drawLine(g, startX, lineY, endX, lineY); drawLine(g, startX, lineY + 1, endX, lineY + 1); drawLine(g, startX, lineY + 2, endX, lineY + 2); } // Draw apple like dotted line: // // CCC CCC CCC ... // CCC CCC CCC ... // CCC CCC CCC ... // // (where "C" - colored pixel, " " - white pixel) final int step = 4; final int startPosCorrection = startX % step < 3 ? 0 : 1; // Optimization - lets draw dotted line using dot sample image. // draw one dot by pixel: // save old settings final Composite oldComposite = g.getComposite(); // draw image "over" on top of background g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); // sample final BufferedImage image = getAppleDotStamp(fgColor, oldColor); // Now copy our dot several times final int dotX0 = (startX / step + startPosCorrection) * step; for (int dotXi = dotX0; dotXi < endX; dotXi += step) { g.drawImage(image, dotXi, lineY, null); } //restore previous settings g.setComposite(oldComposite); } private static BufferedImage getAppleDotStamp(final Color fgColor, final Color oldColor) { final Color color = fgColor != null ? fgColor : oldColor; // let's avoid of generating tons of GC and store samples for different colors BufferedImage sample = ourAppleDotSamples.get(color); if (sample == null) { sample = createAppleDotStamp(color); ourAppleDotSamples.put(color, sample); } return sample; } private static BufferedImage createAppleDotStamp(final Color color) { final BufferedImage image = createImage(3, 3, BufferedImage.TYPE_INT_ARGB); final Graphics2D g = image.createGraphics(); g.setColor(color); // Each dot: // | 20% | 50% | 20% | // | 80% | 80% | 80% | // | 50% | 100% | 50% | g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .2f)); g.drawLine(0, 0, 0, 0); g.drawLine(2, 0, 2, 0); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0.7f)); g.drawLine(0, 1, 2, 1); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f)); g.drawLine(1, 2, 1, 2); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .5f)); g.drawLine(1, 0, 1, 0); g.drawLine(0, 2, 0, 2); g.drawLine(2, 2, 2, 2); // dispose graphics g.dispose(); return image; } public static void applyRenderingHints(final Graphics g) { Toolkit tk = Toolkit.getDefaultToolkit(); //noinspection HardCodedStringLiteral Map map = (Map)tk.getDesktopProperty("awt.font.desktophints"); if (map != null) { ((Graphics2D)g).addRenderingHints(map); } } public static BufferedImage createImage(int width, int height, int type) { if (isRetina()) { return RetinaImage.create(width, height, type); } //noinspection UndesirableClassUsage return new BufferedImage(width, height, type); } public static void drawImage(Graphics g, Image image, int x, int y, ImageObserver observer) { if (image instanceof JBHiDPIScaledImage) { final Graphics2D newG = (Graphics2D)g.create(x, y, image.getWidth(observer), image.getHeight(observer)); newG.scale(0.5, 0.5); Image img = ((JBHiDPIScaledImage)image).getDelegate(); if (img == null) { img = image; } newG.drawImage(img, 0, 0, observer); newG.scale(1, 1); newG.dispose(); } else { g.drawImage(image, x, y, observer); } } public static void drawImage(Graphics g, BufferedImage image, BufferedImageOp op, int x, int y) { if (image instanceof JBHiDPIScaledImage) { final Graphics2D newG = (Graphics2D)g.create(x, y, image.getWidth(null), image.getHeight(null)); newG.scale(0.5, 0.5); Image img = ((JBHiDPIScaledImage)image).getDelegate(); if (img == null) { img = image; } newG.drawImage((BufferedImage)img, op, 0, 0); newG.scale(1, 1); newG.dispose(); } else { ((Graphics2D)g).drawImage(image, op, x, y); } } public static void paintWithXorOnRetina(@NotNull Dimension size, @NotNull Graphics g, Consumer<Graphics2D> paintRoutine) { paintWithXorOnRetina(size, g, true, paintRoutine); } /** * Direct painting into component's graphics with XORMode is broken on retina-mode so we need to paint into an intermediate buffer first. */ public static void paintWithXorOnRetina(@NotNull Dimension size, @NotNull Graphics g, boolean useRetinaCondition, Consumer<Graphics2D> paintRoutine) { if (!useRetinaCondition || !isRetina() || Registry.is("ide.mac.retina.disableDrawingFix", false)) { paintRoutine.consume((Graphics2D)g); } else { Rectangle rect = g.getClipBounds(); if (rect == null) rect = new Rectangle(size); //noinspection UndesirableClassUsage Image image = new BufferedImage(rect.width * 2, rect.height * 2, BufferedImage.TYPE_INT_RGB); Graphics2D imageGraphics = (Graphics2D)image.getGraphics(); imageGraphics.scale(2, 2); imageGraphics.translate(-rect.x, -rect.y); imageGraphics.setClip(rect.x, rect.y, rect.width, rect.height); paintRoutine.consume(imageGraphics); image.flush(); imageGraphics.dispose(); ((Graphics2D)g).scale(0.5, 0.5); g.drawImage(image, rect.x * 2, rect.y * 2, null); } } /** * Configures composite to use for drawing text with the given graphics container. * <p/> * The whole idea is that <a href="http://en.wikipedia.org/wiki/X_Rendering_Extension">XRender-based</a> pipeline doesn't support * {@link AlphaComposite#SRC} and we should use {@link AlphaComposite#SRC_OVER} instead. * * @param g target graphics container */ public static void setupComposite(@NotNull Graphics2D g) { g.setComposite(X_RENDER_ACTIVE.getValue() ? AlphaComposite.SrcOver : AlphaComposite.Src); } /** @see #pump() */ @TestOnly public static void dispatchAllInvocationEvents() { assert SwingUtilities.isEventDispatchThread() : Thread.currentThread(); final EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); while (true) { AWTEvent event = eventQueue.peekEvent(); if (event == null) break; try { AWTEvent event1 = eventQueue.getNextEvent(); if (event1 instanceof InvocationEvent) { ((InvocationEvent)event1).dispatch(); } } catch (Exception e) { LOG.error(e); //? } } } /** @see #dispatchAllInvocationEvents() */ @TestOnly public static void pump() { assert !SwingUtilities.isEventDispatchThread(); final BlockingQueue<Object> queue = new LinkedBlockingQueue<Object>(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { queue.offer(queue); } }); try { queue.take(); } catch (InterruptedException e) { LOG.error(e); } } public static void addAwtListener(final AWTEventListener listener, long mask, Disposable parent) { Toolkit.getDefaultToolkit().addAWTEventListener(listener, mask); Disposer.register(parent, new Disposable() { @Override public void dispose() { Toolkit.getDefaultToolkit().removeAWTEventListener(listener); } }); } public static void drawVDottedLine(Graphics2D g, int lineX, int startY, int endY, @Nullable final Color bgColor, final Color fgColor) { if (bgColor != null) { g.setColor(bgColor); drawLine(g, lineX, startY, lineX, endY); } g.setColor(fgColor); for (int i = (startY / 2) * 2; i < endY; i += 2) { g.drawRect(lineX, i, 0, 0); } } public static void drawHDottedLine(Graphics2D g, int startX, int endX, int lineY, @Nullable final Color bgColor, final Color fgColor) { if (bgColor != null) { g.setColor(bgColor); drawLine(g, startX, lineY, endX, lineY); } g.setColor(fgColor); for (int i = (startX / 2) * 2; i < endX; i += 2) { g.drawRect(i, lineY, 0, 0); } } public static void drawDottedLine(Graphics2D g, int x1, int y1, int x2, int y2, @Nullable final Color bgColor, final Color fgColor) { if (x1 == x2) { drawVDottedLine(g, x1, y1, y2, bgColor, fgColor); } else if (y1 == y2) { drawHDottedLine(g, x1, x2, y1, bgColor, fgColor); } else { throw new IllegalArgumentException("Only vertical or horizontal lines are supported"); } } public static void drawStringWithHighlighting(Graphics g, String s, int x, int y, Color foreground, Color highlighting) { g.setColor(highlighting); for (int i = x - 1; i <= x + 1; i++) { for (int j = y - 1; j <= y + 1; j++) { g.drawString(s, i, j); } } g.setColor(foreground); g.drawString(s, x, y); } public static boolean isFocusAncestor(@NotNull final JComponent component) { final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (owner == null) return false; if (owner == component) return true; return SwingUtilities.isDescendingFrom(owner, component); } public static boolean isCloseClick(MouseEvent e) { return isCloseClick(e, MouseEvent.MOUSE_PRESSED); } public static boolean isCloseClick(MouseEvent e, int effectiveType) { if (e.isPopupTrigger() || e.getID() != effectiveType) return false; return e.getButton() == MouseEvent.BUTTON2 || e.getButton() == MouseEvent.BUTTON1 && e.isShiftDown(); } public static boolean isActionClick(MouseEvent e) { return isActionClick(e, MouseEvent.MOUSE_PRESSED); } public static boolean isActionClick(MouseEvent e, int effectiveType) { return isActionClick(e, effectiveType, false); } public static boolean isActionClick(MouseEvent e, int effectiveType, boolean allowShift) { if (!allowShift && isCloseClick(e) || e.isPopupTrigger() || e.getID() != effectiveType) return false; return e.getButton() == MouseEvent.BUTTON1; } @NotNull public static Color getBgFillColor(@NotNull JComponent c) { final Component parent = findNearestOpaque(c); return parent == null ? c.getBackground() : parent.getBackground(); } @Nullable public static Component findNearestOpaque(JComponent c) { Component eachParent = c; while (eachParent != null) { if (eachParent.isOpaque()) return eachParent; eachParent = eachParent.getParent(); } return null; } @NonNls public static String getCssFontDeclaration(final Font font) { return getCssFontDeclaration(font, null, null, null); } @Language("HTML") @NonNls public static String getCssFontDeclaration(final Font font, @Nullable Color fgColor, @Nullable Color linkColor, @Nullable String liImg) { URL resource = liImg != null ? SystemInfo.class.getResource(liImg) : null; @NonNls String fontFamilyAndSize = "font-family:'" + font.getFamily() + "'; font-size:" + font.getSize() + "pt;"; @NonNls @Language("HTML") String body = "body, div, td, p {" + fontFamilyAndSize + " " + (fgColor != null ? "color:#" + ColorUtil.toHex(fgColor)+";" : "") + "}\n"; if (resource != null) { body += "ul {list-style-image:url('" + resource.toExternalForm() + "');}\n"; } @NonNls String link = linkColor != null ? "a {" + fontFamilyAndSize + " color:#"+ColorUtil.toHex(linkColor) + ";}\n" : ""; return "<style>\n" + body + link + "</style>"; } public static boolean isWinLafOnVista() { return SystemInfo.isWinVistaOrNewer && "Windows".equals(UIManager.getLookAndFeel().getName()); } public static boolean isStandardMenuLAF() { return isWinLafOnVista() || isUnderNimbusLookAndFeel() || isUnderGTKLookAndFeel(); } public static Color getFocusedFillColor() { return toAlpha(getListSelectionBackground(), 100); } public static Color getFocusedBoundsColor() { return getBoundsColor(); } public static Color getBoundsColor() { return getBorderColor(); } public static Color getBoundsColor(boolean focused) { return focused ? getFocusedBoundsColor() : getBoundsColor(); } public static Color toAlpha(final Color color, final int alpha) { Color actual = color != null ? color : Color.black; return new Color(actual.getRed(), actual.getGreen(), actual.getBlue(), alpha); } public static void requestFocus(@NotNull final JComponent c) { if (c.isShowing()) { c.requestFocus(); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { c.requestFocus(); } }); } } //todo maybe should do for all kind of listeners via the AWTEventMulticaster class public static void dispose(final Component c) { if (c == null) return; final MouseListener[] mouseListeners = c.getMouseListeners(); for (MouseListener each : mouseListeners) { c.removeMouseListener(each); } final MouseMotionListener[] motionListeners = c.getMouseMotionListeners(); for (MouseMotionListener each : motionListeners) { c.removeMouseMotionListener(each); } final MouseWheelListener[] mouseWheelListeners = c.getMouseWheelListeners(); for (MouseWheelListener each : mouseWheelListeners) { c.removeMouseWheelListener(each); } } public static void disposeProgress(final JProgressBar progress) { if (!isUnderNativeMacLookAndFeel()) return; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (isToDispose(progress)) { progress.getUI().uninstallUI(progress); progress.putClientProperty("isDisposed", Boolean.TRUE); } } }); } private static boolean isToDispose(final JProgressBar progress) { final ProgressBarUI ui = progress.getUI(); if (ui == null) return false; if (Boolean.TYPE.equals(progress.getClientProperty("isDisposed"))) return false; try { final Field progressBarField = ReflectionUtil.findField(ui.getClass(), JProgressBar.class, "progressBar"); progressBarField.setAccessible(true); return progressBarField.get(ui) != null; } catch (NoSuchFieldException e) { return true; } catch (IllegalAccessException e) { return true; } } @Nullable public static Component findUltimateParent(Component c) { if (c == null) return null; Component eachParent = c; while (true) { if (eachParent.getParent() == null) return eachParent; eachParent = eachParent.getParent(); } } public static Color getHeaderActiveColor() { return ACTIVE_HEADER_COLOR; } public static Color getHeaderInactiveColor() { return INACTIVE_HEADER_COLOR; } public static Color getBorderColor() { return isUnderDarcula() ? Gray._50 : BORDER_COLOR; } public static Font getTitledBorderFont() { Font defFont = getLabelFont(); return defFont.deriveFont(Math.max(defFont.getSize() - 2f, 11f)); } /** * @deprecated use getBorderColor instead */ public static Color getBorderInactiveColor() { return getBorderColor(); } /** * @deprecated use getBorderColor instead */ public static Color getBorderActiveColor() { return getBorderColor(); } /** * @deprecated use getBorderColor instead */ public static Color getBorderSeparatorColor() { return getBorderColor(); } @Nullable public static StyleSheet loadStyleSheet(@Nullable URL url) { if (url == null) return null; try { StyleSheet styleSheet = new StyleSheet(); styleSheet.loadRules(new InputStreamReader(url.openStream(), CharsetToolkit.UTF8), url); return styleSheet; } catch (IOException e) { LOG.warn(url + " loading failed", e); return null; } } public static HTMLEditorKit getHTMLEditorKit() { Font font = getLabelFont(); @NonNls String family = !SystemInfo.isWindows && font != null ? font.getFamily() : "Tahoma"; int size = font != null ? font.getSize() : 11; final String customCss = String.format("body, div, p { font-family: %s; font-size: %s; } p { margin-top: 0; }", family, size); final StyleSheet style = new StyleSheet(); style.addStyleSheet(isUnderDarcula() ? (StyleSheet)UIManager.getDefaults().get("StyledEditorKit.JBDefaultStyle") : DEFAULT_HTML_KIT_CSS); style.addRule(customCss); return new HTMLEditorKit() { @Override public StyleSheet getStyleSheet() { return style; } }; } public static void removeScrollBorder(final Component c) { new AwtVisitor(c) { @Override public boolean visit(final Component component) { if (component instanceof JScrollPane) { if (!hasNonPrimitiveParents(c, component)) { final JScrollPane scrollPane = (JScrollPane)component; Integer keepBorderSides = (Integer)scrollPane.getClientProperty(KEEP_BORDER_SIDES); if (keepBorderSides != null) { if (scrollPane.getBorder() instanceof LineBorder) { Color color = ((LineBorder)scrollPane.getBorder()).getLineColor(); scrollPane.setBorder(new SideBorder(color, keepBorderSides.intValue())); } else { scrollPane.setBorder(new SideBorder(getBoundsColor(), keepBorderSides.intValue())); } } else { scrollPane.setBorder(new SideBorder(getBoundsColor(), SideBorder.NONE)); } } } return false; } }; } public static boolean hasNonPrimitiveParents(Component stopParent, Component c) { Component eachParent = c.getParent(); while (true) { if (eachParent == null || eachParent == stopParent) return false; if (!isPrimitive(eachParent)) return true; eachParent = eachParent.getParent(); } } public static boolean isPrimitive(Component c) { return c instanceof JPanel || c instanceof JLayeredPane; } public static Point getCenterPoint(Dimension container, Dimension child) { return getCenterPoint(new Rectangle(new Point(), container), child); } public static Point getCenterPoint(Rectangle container, Dimension child) { Point result = new Point(); Point containerLocation = container.getLocation(); Dimension containerSize = container.getSize(); result.x = containerLocation.x + containerSize.width / 2 - child.width / 2; result.y = containerLocation.y + containerSize.height / 2 - child.height / 2; return result; } public static String toHtml(String html) { return toHtml(html, 0); } @NonNls public static String toHtml(String html, final int hPadding) { html = CLOSE_TAG_PATTERN.matcher(html).replaceAll("<$1$2></$1>"); Font font = getLabelFont(); @NonNls String family = font != null ? font.getFamily() : "Tahoma"; int size = font != null ? font.getSize() : 11; return "<html><style>body { font-family: " + family + "; font-size: " + size + ";} ul li {list-style-type:circle;}</style>" + addPadding(html, hPadding) + "</html>"; } public static String addPadding(final String html, int hPadding) { return String.format("<p style=\"margin: 0 %dpx 0 %dpx;\">%s</p>", hPadding, hPadding, html); } public static String convertSpace2Nbsp(String html) { @NonNls StringBuilder result = new StringBuilder(); int currentPos = 0; int braces = 0; while (currentPos < html.length()) { String each = html.substring(currentPos, currentPos + 1); if ("<".equals(each)) { braces++; } else if (">".equals(each)) { braces--; } if (" ".equals(each) && braces == 0) { result.append("&nbsp;"); } else { result.append(each); } currentPos++; } return result.toString(); } public static void invokeLaterIfNeeded(@NotNull Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { SwingUtilities.invokeLater(runnable); } } /** * Invoke and wait in the event dispatch thread * or in the current thread if the current thread * is event queue thread. * * @param runnable a runnable to invoke * @see #invokeAndWaitIfNeeded(com.intellij.util.ThrowableRunnable) */ public static void invokeAndWaitIfNeeded(@NotNull Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { try { SwingUtilities.invokeAndWait(runnable); } catch (Exception e) { LOG.error(e); } } } public static void invokeAndWaitIfNeeded(@NotNull final ThrowableRunnable runnable) throws Throwable { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { final Ref<Throwable> ref = new Ref<Throwable>(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { try { runnable.run(); } catch (Throwable throwable) { ref.set(throwable); } } }); if (!ref.isNull()) throw ref.get(); } } public static boolean isFocusProxy(@Nullable Component c) { return c instanceof JComponent && Boolean.TRUE.equals(((JComponent)c).getClientProperty(FOCUS_PROXY_KEY)); } public static void setFocusProxy(JComponent c, boolean isProxy) { c.putClientProperty(FOCUS_PROXY_KEY, isProxy ? Boolean.TRUE : null); } public static void maybeInstall(InputMap map, String action, KeyStroke stroke) { if (map.get(stroke) == null) { map.put(stroke, action); } } /** * Avoid blinking while changing background. * * @param component component. * @param background new background. */ public static void changeBackGround(final Component component, final Color background) { final Color oldBackGround = component.getBackground(); if (background == null || !background.equals(oldBackGround)) { component.setBackground(background); } } public static void initDefaultLAF() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); if (ourSystemFontData == null) { final Font font = getLabelFont(); ourSystemFontData = Pair.create(font.getName(), font.getSize()); } } catch (Exception ignored) { } } @Nullable public static Pair<String, Integer> getSystemFontData() { return ourSystemFontData; } public static void addKeyboardShortcut(final JComponent target, final AbstractButton button, final KeyStroke keyStroke) { target.registerKeyboardAction( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (button.isEnabled()) { button.doClick(); } } }, keyStroke, JComponent.WHEN_FOCUSED ); } public static void installComboBoxCopyAction(JComboBox comboBox) { final Component editorComponent = comboBox.getEditor().getEditorComponent(); if (!(editorComponent instanceof JTextComponent)) return; final InputMap inputMap = ((JTextComponent)editorComponent).getInputMap(); for (KeyStroke keyStroke : inputMap.allKeys()) { if (DefaultEditorKit.copyAction.equals(inputMap.get(keyStroke))) { comboBox.getInputMap().put(keyStroke, DefaultEditorKit.copyAction); } } comboBox.getActionMap().put(DefaultEditorKit.copyAction, new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { if (!(e.getSource() instanceof JComboBox)) return; final JComboBox comboBox = (JComboBox)e.getSource(); final String text; final Object selectedItem = comboBox.getSelectedItem(); if (selectedItem instanceof String) { text = (String)selectedItem; } else { final Component component = comboBox.getRenderer().getListCellRendererComponent(new JList(), selectedItem, 0, false, false); if (component instanceof JLabel) { text = ((JLabel)component).getText(); } else if (component != null) { final String str = component.toString(); // skip default Component.toString and handle SimpleColoredComponent case text = str == null || str.startsWith(component.getClass().getName() + "[") ? null : str; } else { text = null; } } if (text != null) { final JTextField textField = new JTextField(text); textField.selectAll(); textField.copy(); } } }); } @Nullable public static ComboPopup getComboBoxPopup(JComboBox comboBox) { final ComboBoxUI ui = comboBox.getUI(); if (ui instanceof BasicComboBoxUI) { try { final Field popup = BasicComboBoxUI.class.getDeclaredField("popup"); popup.setAccessible(true); return (ComboPopup)popup.get(ui); } catch (NoSuchFieldException e) { return null; } catch (IllegalAccessException e) { return null; } } return null; } @SuppressWarnings({"HardCodedStringLiteral"}) public static void fixFormattedField(JFormattedTextField field) { if (SystemInfo.isMac) { final Toolkit toolkit = Toolkit.getDefaultToolkit(); final int commandKeyMask = toolkit.getMenuShortcutKeyMask(); final InputMap inputMap = field.getInputMap(); final KeyStroke copyKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, commandKeyMask); inputMap.put(copyKeyStroke, "copy-to-clipboard"); final KeyStroke pasteKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_V, commandKeyMask); inputMap.put(pasteKeyStroke, "paste-from-clipboard"); final KeyStroke cutKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_X, commandKeyMask); inputMap.put(cutKeyStroke, "cut-to-clipboard"); } } public static boolean isPrinting(Graphics g) { return g instanceof PrintGraphics; } public static int getSelectedButton(ButtonGroup group) { Enumeration<AbstractButton> enumeration = group.getElements(); int i = 0; while (enumeration.hasMoreElements()) { AbstractButton button = enumeration.nextElement(); if (group.isSelected(button.getModel())) { return i; } i++; } return -1; } public static void setSelectedButton(ButtonGroup group, int index) { Enumeration<AbstractButton> enumeration = group.getElements(); int i = 0; while (enumeration.hasMoreElements()) { AbstractButton button = enumeration.nextElement(); group.setSelected(button.getModel(), index == i); i++; } } public static boolean isSelectionButtonDown(MouseEvent e) { return e.isShiftDown() || e.isControlDown() || e.isMetaDown(); } @SuppressWarnings("deprecation") public static void setComboBoxEditorBounds(int x, int y, int width, int height, JComponent editor) { if (SystemInfo.isMac && isUnderAquaLookAndFeel()) { // fix for too wide combobox editor, see AquaComboBoxUI.layoutContainer: // it adds +4 pixels to editor width. WTF?! editor.reshape(x, y, width - 4, height - 1); } else { editor.reshape(x, y, width, height); } } public static int fixComboBoxHeight(final int height) { return SystemInfo.isMac && isUnderAquaLookAndFeel() ? 28 : height; } /** * The main difference from javax.swing.SwingUtilities#isDescendingFrom(Component, Component) is that this method * uses getInvoker() instead of getParent() when it meets JPopupMenu * @param child child component * @param parent parent component * @return true if parent if a top parent of child, false otherwise * * @see javax.swing.SwingUtilities#isDescendingFrom(java.awt.Component, java.awt.Component) */ public static boolean isDescendingFrom(@Nullable Component child, @NotNull Component parent) { while (child != null && child != parent) { child = child instanceof JPopupMenu ? ((JPopupMenu)child).getInvoker() : child.getParent(); } return child == parent; } @Nullable public static <T> T getParentOfType(Class<? extends T> cls, Component c) { Component eachParent = c; while (eachParent != null) { if (cls.isAssignableFrom(eachParent.getClass())) { @SuppressWarnings({"unchecked"}) final T t = (T)eachParent; return t; } eachParent = eachParent.getParent(); } return null; } public static void scrollListToVisibleIfNeeded(@NotNull final JList list) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { final int selectedIndex = list.getSelectedIndex(); if (selectedIndex >= 0) { final Rectangle visibleRect = list.getVisibleRect(); final Rectangle cellBounds = list.getCellBounds(selectedIndex, selectedIndex); if (!visibleRect.contains(cellBounds)) { list.scrollRectToVisible(cellBounds); } } } }); } @Nullable public static <T extends JComponent> T findComponentOfType(JComponent parent, Class<T> cls) { if (parent == null || cls.isAssignableFrom(parent.getClass())) { @SuppressWarnings({"unchecked"}) final T t = (T)parent; return t; } for (Component component : parent.getComponents()) { if (component instanceof JComponent) { T comp = findComponentOfType((JComponent)component, cls); if (comp != null) return comp; } } return null; } public static <T extends JComponent> List<T> findComponentsOfType(JComponent parent, Class<T> cls) { final ArrayList<T> result = new ArrayList<T>(); findComponentsOfType(parent, cls, result); return result; } private static <T extends JComponent> void findComponentsOfType(JComponent parent, Class<T> cls, ArrayList<T> result) { if (parent == null) return; if (cls.isAssignableFrom(parent.getClass())) { @SuppressWarnings({"unchecked"}) final T t = (T)parent; result.add(t); } for (Component c : parent.getComponents()) { if (c instanceof JComponent) { findComponentsOfType((JComponent)c, cls, result); } } } public static class TextPainter { private final List<Pair<String, LineInfo>> myLines = new ArrayList<Pair<String, LineInfo>>(); private boolean myDrawShadow; private Color myShadowColor; private float myLineSpacing; public TextPainter() { myDrawShadow = /*isUnderAquaLookAndFeel() ||*/ isUnderDarcula(); myShadowColor = isUnderDarcula() ? Gray._0.withAlpha(100) : Gray._220; myLineSpacing = 1.0f; } public TextPainter withShadow(final boolean drawShadow) { myDrawShadow = drawShadow; return this; } public TextPainter withShadow(final boolean drawShadow, final Color shadowColor) { myDrawShadow = drawShadow; myShadowColor = shadowColor; return this; } public TextPainter withLineSpacing(final float lineSpacing) { myLineSpacing = lineSpacing; return this; } public TextPainter appendLine(final String text) { if (text == null || text.isEmpty()) return this; myLines.add(Pair.create(text, new LineInfo())); return this; } public TextPainter underlined(@Nullable final Color color) { if (!myLines.isEmpty()) { final LineInfo info = myLines.get(myLines.size() - 1).getSecond(); info.underlined = true; info.underlineColor = color; } return this; } public TextPainter withBullet(final char c) { if (!myLines.isEmpty()) { final LineInfo info = myLines.get(myLines.size() - 1).getSecond(); info.withBullet = true; info.bulletChar = c; } return this; } public TextPainter withBullet() { return withBullet('\u2022'); } public TextPainter underlined() { return underlined(null); } public TextPainter smaller() { if (!myLines.isEmpty()) { myLines.get(myLines.size() - 1).getSecond().smaller = true; } return this; } public TextPainter center() { if (!myLines.isEmpty()) { myLines.get(myLines.size() - 1).getSecond().center = true; } return this; } /** * _position(block width, block height) => (x, y) of the block */ public void draw(@NotNull final Graphics g, final PairFunction<Integer, Integer, Pair<Integer, Integer>> _position) { final int[] maxWidth = {0}; final int[] height = {0}; final int[] maxBulletWidth = {0}; ContainerUtil.process(myLines, new Processor<Pair<String, LineInfo>>() { @Override public boolean process(final Pair<String, LineInfo> pair) { final LineInfo info = pair.getSecond(); Font old = null; if (info.smaller) { old = g.getFont(); g.setFont(old.deriveFont(old.getSize() * 0.70f)); } final FontMetrics fm = g.getFontMetrics(); final int bulletWidth = info.withBullet ? fm.stringWidth(" " + info.bulletChar) : 0; maxBulletWidth[0] = Math.max(maxBulletWidth[0], bulletWidth); maxWidth[0] = Math.max(fm.stringWidth(pair.getFirst().replace("<shortcut>", "").replace("</shortcut>", "") + bulletWidth), maxWidth[0]); height[0] += (fm.getHeight() + fm.getLeading()) * myLineSpacing; if (old != null) { g.setFont(old); } return true; } }); final Pair<Integer, Integer> position = _position.fun(maxWidth[0] + 20, height[0]); assert position != null; final int[] yOffset = {position.getSecond()}; ContainerUtil.process(myLines, new Processor<Pair<String, LineInfo>>() { @Override public boolean process(final Pair<String, LineInfo> pair) { final LineInfo info = pair.getSecond(); String text = pair.first; String shortcut = ""; if (pair.first.contains("<shortcut>")) { shortcut = text.substring(text.indexOf("<shortcut>") + "<shortcut>".length(), text.indexOf("</shortcut>")); text = text.substring(0, text.indexOf("<shortcut>")); } Font old = null; if (info.smaller) { old = g.getFont(); g.setFont(old.deriveFont(old.getSize() * 0.70f)); } final int x = position.getFirst() + maxBulletWidth[0] + 10; final FontMetrics fm = g.getFontMetrics(); int xOffset = x; if (info.center) { xOffset = x + (maxWidth[0] - fm.stringWidth(text)) / 2; } if (myDrawShadow) { int xOff = isUnderDarcula() ? 1 : 0; int yOff = 1; Color oldColor = g.getColor(); g.setColor(myShadowColor); if (info.withBullet) { g.drawString(info.bulletChar + " ", x - fm.stringWidth(" " + info.bulletChar) + xOff, yOffset[0] + yOff); } g.drawString(text, xOffset + xOff, yOffset[0] + yOff); g.setColor(oldColor); } if (info.withBullet) { g.drawString(info.bulletChar + " ", x - fm.stringWidth(" " + info.bulletChar), yOffset[0]); } g.drawString(text, xOffset, yOffset[0]); if (!StringUtil.isEmpty(shortcut)) { Color oldColor = g.getColor(); if (isUnderDarcula()) { g.setColor(new Color(60, 118, 249)); } g.drawString(shortcut, xOffset + fm.stringWidth(text + (isUnderDarcula() ? " " : "")), yOffset[0]); g.setColor(oldColor); } if (info.underlined) { Color c = null; if (info.underlineColor != null) { c = g.getColor(); g.setColor(info.underlineColor); } g.drawLine(x - maxBulletWidth[0] - 10, yOffset[0] + fm.getDescent(), x + maxWidth[0] + 10, yOffset[0] + fm.getDescent()); if (c != null) { g.setColor(c); } if (myDrawShadow) { c = g.getColor(); g.setColor(myShadowColor); g.drawLine(x - maxBulletWidth[0] - 10, yOffset[0] + fm.getDescent() + 1, x + maxWidth[0] + 10, yOffset[0] + fm.getDescent() + 1); g.setColor(c); } } yOffset[0] += (fm.getHeight() + fm.getLeading()) * myLineSpacing; if (old != null) { g.setFont(old); } return true; } }); } private static class LineInfo { private boolean underlined; private boolean withBullet; private char bulletChar; private Color underlineColor; private boolean smaller; private boolean center; } } @Nullable public static JRootPane getRootPane(Component c) { JRootPane root = getParentOfType(JRootPane.class, c); if (root != null) return root; Component eachParent = c; while (eachParent != null) { if (eachParent instanceof JComponent) { @SuppressWarnings({"unchecked"}) WeakReference<JRootPane> pane = (WeakReference<JRootPane>)((JComponent)eachParent).getClientProperty(ROOT_PANE); if (pane != null) return pane.get(); } eachParent = eachParent.getParent(); } return null; } public static void setFutureRootPane(JComponent c, JRootPane pane) { c.putClientProperty(ROOT_PANE, new WeakReference<JRootPane>(pane)); } public static boolean isMeaninglessFocusOwner(@Nullable Component c) { if (c == null || !c.isShowing()) return true; return c instanceof JFrame || c instanceof JDialog || c instanceof JWindow || c instanceof JRootPane || isFocusProxy(c); } public static Timer createNamedTimer(@NonNls @NotNull final String name, int delay, @NotNull ActionListener listener) { return new Timer(delay, listener) { @Override public String toString() { return name; } }; } public static boolean isDialogRootPane(JRootPane rootPane) { if (rootPane != null) { final Object isDialog = rootPane.getClientProperty("DIALOG_ROOT_PANE"); return isDialog instanceof Boolean && ((Boolean)isDialog).booleanValue(); } return false; } @Nullable public static JComponent mergeComponentsWithAnchor(PanelWithAnchor... panels) { return mergeComponentsWithAnchor(Arrays.asList(panels)); } @Nullable public static JComponent mergeComponentsWithAnchor(Collection<? extends PanelWithAnchor> panels) { JComponent maxWidthAnchor = null; int maxWidth = 0; for (PanelWithAnchor panel : panels) { JComponent anchor = panel != null ? panel.getAnchor() : null; if (anchor != null) { int anchorWidth = anchor.getPreferredSize().width; if (maxWidth < anchorWidth) { maxWidth = anchorWidth; maxWidthAnchor = anchor; } } } for (PanelWithAnchor panel : panels) { if (panel != null) { panel.setAnchor(maxWidthAnchor); } } return maxWidthAnchor; } public static void setNotOpaqueRecursively(@NotNull Component component) { if (!isUnderAquaLookAndFeel()) return; if (component.getBackground().equals(getPanelBackground()) || component instanceof JScrollPane || component instanceof JViewport || component instanceof JLayeredPane) { if (component instanceof JComponent) { ((JComponent)component).setOpaque(false); } if (component instanceof Container) { for (Component c : ((Container)component).getComponents()) { setNotOpaqueRecursively(c); } } } } public static void addInsets(@NotNull JComponent component, @NotNull Insets insets) { if (component.getBorder() != null) { component.setBorder(new CompoundBorder(new EmptyBorder(insets), component.getBorder())); } else { component.setBorder(new EmptyBorder(insets)); } } public static Dimension addInsets(@NotNull Dimension dimension, @NotNull Insets insets) { Dimension ans = new Dimension(dimension); ans.width += insets.left; ans.width += insets.right; ans.height += insets.top; ans.height += insets.bottom; return ans; } public static void adjustWindowToMinimumSize(final Window window) { if (window == null) return; final Dimension minSize = window.getMinimumSize(); final Dimension size = window.getSize(); final Dimension newSize = new Dimension(Math.max(size.width, minSize.width), Math.max(size.height, minSize.height)); if (!newSize.equals(size)) { //noinspection SSBasedInspection SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (window.isShowing()) { window.setSize(newSize); } } }); } } @Nullable public static Color getColorAt(final Icon icon, final int x, final int y) { if (0 <= x && x < icon.getIconWidth() && 0 <= y && y < icon.getIconHeight()) { final BufferedImage image = createImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB); icon.paintIcon(null, image.getGraphics(), 0, 0); final int[] pixels = new int[1]; final PixelGrabber pixelGrabber = new PixelGrabber(image, x, y, 1, 1, pixels, 0, 1); try { pixelGrabber.grabPixels(); return new Color(pixels[0]); } catch (InterruptedException ignored) { } } return null; } public static void addBorder(JComponent component, Border border) { if (component == null) return; if (component.getBorder() != null) { component.setBorder(new CompoundBorder(border, component.getBorder())); } else { component.setBorder(border); } } private static final Color DECORATED_ROW_BG_COLOR = new JBColor(new Color(242, 245, 249), new Color(65, 69, 71)); public static Color getDecoratedRowColor() { return DECORATED_ROW_BG_COLOR; } @NotNull public static Paint getGradientPaint(float x1, float y1, @NotNull Color c1, float x2, float y2, @NotNull Color c2) { return (Registry.is("ui.no.bangs.and.whistles", false)) ? ColorUtil.mix(c1, c2, .5) : new GradientPaint(x1, y1, c1, x2, y2, c2); } @Nullable public static Point getLocationOnScreen(@NotNull JComponent component) { int dx = 0; int dy = 0; for (Container c = component; c != null; c = c.getParent()) { if (c.isShowing()) { Point locationOnScreen = c.getLocationOnScreen(); locationOnScreen.translate(dx, dy); return locationOnScreen; } else { Point location = c.getLocation(); dx += location.x; dy += location.y; } } return null; } @NotNull public static Window getActiveWindow() { Window[] windows = Window.getWindows(); for (Window each : windows) { if (each.isVisible() && each.isActive()) return each; } return JOptionPane.getRootFrame(); } public static void setAutoRequestFocus (final Window onWindow, final boolean set){ if (SystemInfo.isMac) return; if (SystemInfo.isJavaVersionAtLeast("1.7")) { try { Method setAutoRequestFocusMethod = onWindow.getClass().getMethod("setAutoRequestFocus",new Class [] {boolean.class}); setAutoRequestFocusMethod.invoke(onWindow, set); } catch (NoSuchMethodException e) { LOG.debug(e); } catch (InvocationTargetException e) { LOG.debug(e); } catch (IllegalAccessException e) { LOG.debug(e); } } } //May have no usages but it's useful in runtime (Debugger "watches", some logging etc.) public static String getDebugText(Component c) { StringBuilder builder = new StringBuilder(); getAllTextsRecursivelyImpl(c, builder); return builder.toString(); } private static void getAllTextsRecursivelyImpl(Component component, StringBuilder builder) { String candidate = ""; int limit = builder.length() > 60 ? 20 : 40; if (component instanceof JLabel) candidate = ((JLabel)component).getText(); if (component instanceof JTextComponent) candidate = ((JTextComponent)component).getText(); if (component instanceof AbstractButton) candidate = ((AbstractButton)component).getText(); if (StringUtil.isNotEmpty(candidate)) { builder.append(candidate.length() > limit ? (candidate.substring(0, limit - 3) + "...") : candidate).append('|'); } if (component instanceof Container) { Component[] components = ((Container)component).getComponents(); for (Component child : components) { getAllTextsRecursivelyImpl(child, builder); } } } public static boolean isAncestor(@NotNull Component ancestor, @Nullable Component descendant) { while (descendant != null) { if (descendant == ancestor) { return true; } descendant = descendant.getParent(); } return false; } public static void addUndoRedoActions(JTextComponent textComponent) { final UndoManager undoManager = new UndoManager(); textComponent.getDocument().addUndoableEditListener(undoManager); textComponent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, SystemInfo.isMac? InputEvent.META_MASK : InputEvent.CTRL_MASK), "undoKeystroke"); textComponent.getActionMap().put("undoKeystroke", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (undoManager.canUndo()) { undoManager.undo(); } } }); textComponent.getInputMap().put( KeyStroke.getKeyStroke(KeyEvent.VK_Z, (SystemInfo.isMac? InputEvent.META_MASK : InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK), "redoKeystroke"); textComponent.getActionMap().put("redoKeystroke", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (undoManager.canRedo()) { undoManager.redo(); } } }); } public static void playSoundFromResource(final String resourceName) { final Class callerClass = ReflectionUtil.getGrandCallerClass(); if (callerClass == null) return; playSoundFromStream(new Factory<InputStream>() { @Override public InputStream create() { return callerClass.getResourceAsStream(resourceName); } }); } public static void playSoundFromStream(final Factory<InputStream> streamProducer) { new Thread(new Runnable() { // The wrapper thread is unnecessary, unless it blocks on the // Clip finishing; see comments. public void run() { try { Clip clip = AudioSystem.getClip(); InputStream stream = streamProducer.create(); if (!stream.markSupported()) stream = new BufferedInputStream(stream); AudioInputStream inputStream = AudioSystem.getAudioInputStream(stream); clip.open(inputStream); clip.start(); } catch (Exception ignore) { LOG.info(ignore); } } }).start(); } }
platform/util/src/com/intellij/util/ui/UIUtil.java
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.ui; import com.intellij.BundleBase; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.ui.*; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.swing.*; import javax.swing.Timer; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.plaf.ComboBoxUI; import javax.swing.plaf.ProgressBarUI; import javax.swing.plaf.basic.BasicComboBoxUI; import javax.swing.plaf.basic.ComboPopup; import javax.swing.text.DefaultEditorKit; import javax.swing.text.JTextComponent; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; import javax.swing.undo.UndoManager; import java.awt.*; import java.awt.event.*; import java.awt.font.FontRenderContext; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ImageObserver; import java.awt.image.PixelGrabber; import java.beans.PropertyChangeListener; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.util.*; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.regex.Pattern; /** * @author max */ @SuppressWarnings("StaticMethodOnlyUsedInOneClass") public class UIUtil { @NonNls public static final String BORDER_LINE = "<hr size=1 noshade>"; private static final StyleSheet DEFAULT_HTML_KIT_CSS; static { // save the default JRE CSS and .. HTMLEditorKit kit = new HTMLEditorKit(); DEFAULT_HTML_KIT_CSS = kit.getStyleSheet(); // .. erase global ref to this CSS so no one can alter it kit.setStyleSheet(null); } public static int getMultiClickInterval() { Object property = Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval"); if (property instanceof Integer) { return (Integer)property; } return 500; } private static final AtomicNotNullLazyValue<Boolean> X_RENDER_ACTIVE = new AtomicNotNullLazyValue<Boolean>() { @NotNull @Override protected Boolean compute() { if (!SystemInfo.isXWindow) { return false; } try { final Class<?> clazz = ClassLoader.getSystemClassLoader().loadClass("sun.awt.X11GraphicsEnvironment"); final Method method = clazz.getMethod("isXRenderAvailable"); return (Boolean)method.invoke(null); } catch (Throwable e) { return false; } } }; private static final String[] STANDARD_FONT_SIZES = {"8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48", "72"}; public static void applyStyle(@NotNull ComponentStyle componentStyle, @NotNull Component comp) { if (!(comp instanceof JComponent)) return; JComponent c = (JComponent)comp; if (isUnderAquaBasedLookAndFeel()) { c.putClientProperty("JComponent.sizeVariant", componentStyle == ComponentStyle.REGULAR ? "regular" : componentStyle == ComponentStyle.SMALL ? "small" : "mini"); } else { c.setFont(getFont( componentStyle == ComponentStyle.REGULAR ? FontSize.NORMAL : componentStyle == ComponentStyle.SMALL ? FontSize.SMALL : FontSize.MINI, c.getFont())); } Container p = c.getParent(); if (p != null) { SwingUtilities.updateComponentTreeUI(p); } } public static Cursor getTextCursor(final Color backgroundColor) { return SystemInfo.isMac && ColorUtil.isDark(backgroundColor) ? MacUIUtil.getInvertedTextCursor() : Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR); } /** * Draws two horizontal lines, the first at {@code topY}, the second at {@code bottomY}. * The purpose of this method (and the ground of the name) is to draw two lines framing a horizontal filled rectangle. * * @param g Graphics context to draw with. * @param startX x-start point. * @param endX x-end point. * @param topY y-coordinate of the first line. * @param bottomY y-coordinate of the second line. * @param color color of the lines. */ public static void drawFramingLines(@NotNull Graphics2D g, int startX, int endX, int topY, int bottomY, @NotNull Color color) { drawLine(g, startX, topY, endX, topY, null, color); drawLine(g, startX, bottomY, endX, bottomY, null, color); } private static final GrayFilter DEFAULT_GRAY_FILTER = new GrayFilter(true, 65); private static final GrayFilter DARCULA_GRAY_FILTER = new GrayFilter(true, 30); public static GrayFilter getGrayFilter() { return isUnderDarcula() ? DARCULA_GRAY_FILTER : DEFAULT_GRAY_FILTER; } public static boolean isAppleRetina() { return isRetina() && SystemInfo.isAppleJvm; } public enum FontSize {NORMAL, SMALL, MINI} public enum ComponentStyle {REGULAR, SMALL, MINI} public enum FontColor {NORMAL, BRIGHTER} public static final char MNEMONIC = BundleBase.MNEMONIC; @NonNls public static final String HTML_MIME = "text/html"; @NonNls public static final String JSLIDER_ISFILLED = "JSlider.isFilled"; @NonNls public static final String ARIAL_FONT_NAME = "Arial"; @NonNls public static final String TABLE_FOCUS_CELL_BACKGROUND_PROPERTY = "Table.focusCellBackground"; @NonNls public static final String CENTER_TOOLTIP_DEFAULT = "ToCenterTooltip"; @NonNls public static final String CENTER_TOOLTIP_STRICT = "ToCenterTooltip.default"; public static final Pattern CLOSE_TAG_PATTERN = Pattern.compile("<\\s*([^<>/ ]+)([^<>]*)/\\s*>", Pattern.CASE_INSENSITIVE); @NonNls public static final String FOCUS_PROXY_KEY = "isFocusProxy"; public static Key<Integer> KEEP_BORDER_SIDES = Key.create("keepBorderSides"); private static final Logger LOG = Logger.getInstance("#com.intellij.util.ui.UIUtil"); private static final Color UNFOCUSED_SELECTION_COLOR = Gray._212; private static final Color ACTIVE_HEADER_COLOR = new Color(160, 186, 213); private static final Color INACTIVE_HEADER_COLOR = Gray._128; private static final Color BORDER_COLOR = Color.LIGHT_GRAY; public static final Color AQUA_SEPARATOR_FOREGROUND_COLOR = Gray._190; public static final Color AQUA_SEPARATOR_BACKGROUND_COLOR = Gray._240; public static final Color TRANSPARENT_COLOR = new Color(0, 0, 0, 0); public static final int DEFAULT_HGAP = 10; public static final int DEFAULT_VGAP = 4; public static final int LARGE_VGAP = 12; public static final Insets PANEL_REGULAR_INSETS = new Insets(8, 12, 8, 12); public static final Insets PANEL_SMALL_INSETS = new Insets(5, 8, 5, 8); public static final Border DEBUG_MARKER_BORDER = new Border() { private final Insets empty = new Insets(0, 0, 0, 0); @Override public Insets getBorderInsets(Component c) { return empty; } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Graphics g2 = g.create(); try { g2.setColor(JBColor.RED); drawDottedRectangle(g2, x, y, x + width - 1, y + height - 1); } finally { g2.dispose(); } } @Override public boolean isBorderOpaque() { return true; } }; // accessed only from EDT private static final HashMap<Color, BufferedImage> ourAppleDotSamples = new HashMap<Color, BufferedImage>(); private static volatile Pair<String, Integer> ourSystemFontData = null; @NonNls private static final String ROOT_PANE = "JRootPane.future"; private static final Ref<Boolean> ourRetina = Ref.create(SystemInfo.isMac ? null : false); private UIUtil() { } public static boolean isRetina() { if (GraphicsEnvironment.isHeadless()) return false; //Temporary workaround for HiDPI on Windows/Linux if ("true".equalsIgnoreCase(System.getProperty("is.hidpi"))) { return true; } synchronized (ourRetina) { if (ourRetina.isNull()) { ourRetina.set(false); // in case HiDPIScaledImage.drawIntoImage is not called for some reason if (SystemInfo.isJavaVersionAtLeast("1.6.0_33") && SystemInfo.isAppleJvm) { if (!"false".equals(System.getProperty("ide.mac.retina"))) { ourRetina.set(IsRetina.isRetina()); return ourRetina.get(); } } else if (SystemInfo.isJavaVersionAtLeast("1.7.0_40") && SystemInfo.isOracleJvm) { try { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); final GraphicsDevice device = env.getDefaultScreenDevice(); Field field = device.getClass().getDeclaredField("scale"); if (field != null) { field.setAccessible(true); Object scale = field.get(device); if (scale instanceof Integer && ((Integer)scale).intValue() == 2) { ourRetina.set(true); return true; } } } catch (AWTError ignore) {} catch (Exception ignore) {} } ourRetina.set(false); } return ourRetina.get(); } } public static boolean hasLeakingAppleListeners() { // in version 1.6.0_29 Apple introduced a memory leak in JViewport class - they add a PropertyChangeListeners to the CToolkit // but never remove them: // JViewport.java: // public JViewport() { // ... // final Toolkit toolkit = Toolkit.getDefaultToolkit(); // if(toolkit instanceof CToolkit) // { // final boolean isRunningInHiDPI = ((CToolkit)toolkit).runningInHiDPI(); // if(isRunningInHiDPI) setScrollMode(0); // toolkit.addPropertyChangeListener("apple.awt.contentScaleFactor", new PropertyChangeListener() { ... }); // } // } return SystemInfo.isMac && System.getProperty("java.runtime.version").startsWith("1.6.0_29"); } public static void removeLeakingAppleListeners() { if (!hasLeakingAppleListeners()) return; Toolkit toolkit = Toolkit.getDefaultToolkit(); String name = "apple.awt.contentScaleFactor"; for (PropertyChangeListener each : toolkit.getPropertyChangeListeners(name)) { toolkit.removePropertyChangeListener(name, each); } } public static String getHtmlBody(String text) { return getHtmlBody(new Html(text)); } public static String getHtmlBody(Html html) { String text = html.getText(); String result; if (!text.startsWith("<html>")) { result = text.replaceAll("\n", "<br>"); } else { final int bodyIdx = text.indexOf("<body>"); final int closedBodyIdx = text.indexOf("</body>"); if (bodyIdx != -1 && closedBodyIdx != -1) { result = text.substring(bodyIdx + "<body>".length(), closedBodyIdx); } else { text = StringUtil.trimStart(text, "<html>").trim(); text = StringUtil.trimEnd(text, "</html>").trim(); text = StringUtil.trimStart(text, "<body>").trim(); text = StringUtil.trimEnd(text, "</body>").trim(); result = text; } } return html.isKeepFont() ? result : result.replaceAll("<font(.*?)>", "").replaceAll("</font>", ""); } public static void drawLinePickedOut(Graphics graphics, int x, int y, int x1, int y1) { if (x == x1) { int minY = Math.min(y, y1); int maxY = Math.max(y, y1); graphics.drawLine(x, minY + 1, x1, maxY - 1); } else if (y == y1) { int minX = Math.min(x, x1); int maxX = Math.max(x, x1); graphics.drawLine(minX + 1, y, maxX - 1, y1); } else { drawLine(graphics, x, y, x1, y1); } } public static boolean isReallyTypedEvent(KeyEvent e) { char c = e.getKeyChar(); if (c < 0x20 || c == 0x7F) return false; if (SystemInfo.isMac) { return !e.isMetaDown() && !e.isControlDown(); } return !e.isAltDown() && !e.isControlDown(); } public static int getStringY(@NotNull final String string, @NotNull final Rectangle bounds, @NotNull final Graphics2D g) { final int centerY = bounds.height / 2; final Font font = g.getFont(); final FontRenderContext frc = g.getFontRenderContext(); final Rectangle stringBounds = font.getStringBounds(string, frc).getBounds(); return (int)(centerY - stringBounds.height / 2.0 - stringBounds.y); } public static void setEnabled(Component component, boolean enabled, boolean recursively) { component.setEnabled(enabled); if (component instanceof JComboBox && isUnderAquaLookAndFeel()) { // On Mac JComboBox instances have children: com.apple.laf.AquaComboBoxButton and javax.swing.CellRendererPane. // Disabling these children results in ugly UI: WEB-10733 return; } if (component instanceof JLabel) { Color color = enabled ? getLabelForeground() : getLabelDisabledForeground(); if (color != null) { component.setForeground(color); } } if (recursively && enabled == component.isEnabled()) { if (component instanceof Container) { final Container container = (Container)component; final int subComponentCount = container.getComponentCount(); for (int i = 0; i < subComponentCount; i++) { setEnabled(container.getComponent(i), enabled, recursively); } } } } public static void drawLine(Graphics g, int x1, int y1, int x2, int y2) { g.drawLine(x1, y1, x2, y2); } public static void drawLine(Graphics2D g, int x1, int y1, int x2, int y2, @Nullable Color bgColor, @Nullable Color fgColor) { Color oldFg = g.getColor(); Color oldBg = g.getBackground(); if (fgColor != null) { g.setColor(fgColor); } if (bgColor != null) { g.setBackground(bgColor); } drawLine(g, x1, y1, x2, y2); if (fgColor != null) { g.setColor(oldFg); } if (bgColor != null) { g.setBackground(oldBg); } } @NotNull public static String[] splitText(String text, FontMetrics fontMetrics, int widthLimit, char separator) { ArrayList<String> lines = new ArrayList<String>(); String currentLine = ""; StringBuilder currentAtom = new StringBuilder(); for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); currentAtom.append(ch); if (ch == separator) { currentLine += currentAtom.toString(); currentAtom.setLength(0); } String s = currentLine + currentAtom.toString(); int width = fontMetrics.stringWidth(s); if (width >= widthLimit - fontMetrics.charWidth('w')) { if (!currentLine.isEmpty()) { lines.add(currentLine); currentLine = ""; } else { lines.add(currentAtom.toString()); currentAtom.setLength(0); } } } String s = currentLine + currentAtom.toString(); if (!s.isEmpty()) { lines.add(s); } return ArrayUtil.toStringArray(lines); } public static void setActionNameAndMnemonic(@NotNull String text, @NotNull Action action) { assignMnemonic(text, action); text = text.replaceAll("&", ""); action.putValue(Action.NAME, text); } public static void assignMnemonic(@NotNull String text, @NotNull Action action) { int mnemoPos = text.indexOf('&'); if (mnemoPos >= 0 && mnemoPos < text.length() - 2) { String mnemoChar = text.substring(mnemoPos + 1, mnemoPos + 2).trim(); if (mnemoChar.length() == 1) { action.putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnemoChar.charAt(0))); } } } public static Font getLabelFont(@NotNull FontSize size) { return getFont(size, null); } @NotNull public static Font getFont(@NotNull FontSize size, @Nullable Font base) { if (base == null) base = getLabelFont(); return base.deriveFont(getFontSize(size)); } public static float getFontSize(FontSize size) { int defSize = getLabelFont().getSize(); switch (size) { case SMALL: return Math.max(defSize - 2f, 11f); case MINI: return Math.max(defSize - 4f, 9f); default: return defSize; } } public static Color getLabelFontColor(FontColor fontColor) { Color defColor = getLabelForeground(); if (fontColor == FontColor.BRIGHTER) { return new JBColor(new Color(Math.min(defColor.getRed() + 50, 255), Math.min(defColor.getGreen() + 50, 255), Math.min( defColor.getBlue() + 50, 255)), defColor.darker()); } return defColor; } public static int getScrollBarWidth() { return UIManager.getInt("ScrollBar.width"); } public static Font getLabelFont() { return UIManager.getFont("Label.font"); } public static Color getLabelBackground() { return UIManager.getColor("Label.background"); } public static Color getLabelForeground() { return UIManager.getColor("Label.foreground"); } public static Color getLabelDisabledForeground() { final Color color = UIManager.getColor("Label.disabledForeground"); if (color != null) return color; return UIManager.getColor("Label.disabledText"); } /** @deprecated to remove in IDEA 14 */ @SuppressWarnings("UnusedDeclaration") public static Icon getOptionPanelWarningIcon() { return getWarningIcon(); } /** @deprecated to remove in IDEA 14 */ @SuppressWarnings("UnusedDeclaration") public static Icon getOptionPanelQuestionIcon() { return getQuestionIcon(); } @NotNull public static String removeMnemonic(@NotNull String s) { if (s.indexOf('&') != -1) { s = StringUtil.replace(s, "&", ""); } if (s.indexOf('_') != -1) { s = StringUtil.replace(s, "_", ""); } if (s.indexOf(MNEMONIC) != -1) { s = StringUtil.replace(s, String.valueOf(MNEMONIC), ""); } return s; } public static int getDisplayMnemonicIndex(@NotNull String s) { int idx = s.indexOf('&'); if (idx >= 0 && idx != s.length() - 1 && idx == s.lastIndexOf('&')) return idx; idx = s.indexOf(MNEMONIC); if (idx >= 0 && idx != s.length() - 1 && idx == s.lastIndexOf(MNEMONIC)) return idx; return -1; } public static String replaceMnemonicAmpersand(final String value) { return BundleBase.replaceMnemonicAmpersand(value); } public static Color getTableHeaderBackground() { return UIManager.getColor("TableHeader.background"); } public static Color getTreeTextForeground() { return UIManager.getColor("Tree.textForeground"); } public static Color getTreeSelectionBackground() { if (isUnderNimbusLookAndFeel()) { Color color = UIManager.getColor("Tree.selectionBackground"); if (color != null) return color; color = UIManager.getColor("nimbusSelectionBackground"); if (color != null) return color; } return UIManager.getColor("Tree.selectionBackground"); } public static Color getTreeTextBackground() { return UIManager.getColor("Tree.textBackground"); } public static Color getListSelectionForeground() { final Color color = UIManager.getColor("List.selectionForeground"); if (color == null) { return UIManager.getColor("List[Selected].textForeground"); // Nimbus } return color; } public static Color getFieldForegroundColor() { return UIManager.getColor("field.foreground"); } public static Color getTableSelectionBackground() { if (isUnderNimbusLookAndFeel()) { Color color = UIManager.getColor("Table[Enabled+Selected].textBackground"); if (color != null) return color; color = UIManager.getColor("nimbusSelectionBackground"); if (color != null) return color; } return UIManager.getColor("Table.selectionBackground"); } public static Color getActiveTextColor() { return UIManager.getColor("textActiveText"); } public static Color getInactiveTextColor() { return UIManager.getColor("textInactiveText"); } public static Color getSlightlyDarkerColor(Color c) { float[] hsl = Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(), new float[3]); return new Color(Color.HSBtoRGB(hsl[0], hsl[1], hsl[2] - .08f > 0 ? hsl[2] - .08f : hsl[2])); } /** * @deprecated use com.intellij.util.ui.UIUtil#getTextFieldBackground() */ public static Color getActiveTextFieldBackgroundColor() { return getTextFieldBackground(); } public static Color getInactiveTextFieldBackgroundColor() { return UIManager.getColor("TextField.inactiveBackground"); } public static Font getTreeFont() { return UIManager.getFont("Tree.font"); } public static Font getListFont() { return UIManager.getFont("List.font"); } public static Color getTreeSelectionForeground() { return UIManager.getColor("Tree.selectionForeground"); } /** * @deprecated use com.intellij.util.ui.UIUtil#getInactiveTextColor() */ public static Color getTextInactiveTextColor() { return getInactiveTextColor(); } public static void installPopupMenuColorAndFonts(final JComponent contentPane) { LookAndFeel.installColorsAndFont(contentPane, "PopupMenu.background", "PopupMenu.foreground", "PopupMenu.font"); } public static void installPopupMenuBorder(final JComponent contentPane) { LookAndFeel.installBorder(contentPane, "PopupMenu.border"); } public static Color getTreeSelectionBorderColor() { return UIManager.getColor("Tree.selectionBorderColor"); } public static int getTreeRightChildIndent() { return UIManager.getInt("Tree.rightChildIndent"); } public static int getTreeLeftChildIndent() { return UIManager.getInt("Tree.leftChildIndent"); } public static Color getToolTipBackground() { return UIManager.getColor("ToolTip.background"); } public static Color getToolTipForeground() { return UIManager.getColor("ToolTip.foreground"); } public static Color getComboBoxDisabledForeground() { return UIManager.getColor("ComboBox.disabledForeground"); } public static Color getComboBoxDisabledBackground() { return UIManager.getColor("ComboBox.disabledBackground"); } public static Color getButtonSelectColor() { return UIManager.getColor("Button.select"); } public static Integer getPropertyMaxGutterIconWidth(final String propertyPrefix) { return (Integer)UIManager.get(propertyPrefix + ".maxGutterIconWidth"); } public static Color getMenuItemDisabledForeground() { return UIManager.getColor("MenuItem.disabledForeground"); } public static Object getMenuItemDisabledForegroundObject() { return UIManager.get("MenuItem.disabledForeground"); } public static Object getTabbedPanePaintContentBorder(final JComponent c) { return c.getClientProperty("TabbedPane.paintContentBorder"); } public static boolean isMenuCrossMenuMnemonics() { return UIManager.getBoolean("Menu.crossMenuMnemonic"); } public static Color getTableBackground() { // Under GTK+ L&F "Table.background" often has main panel color, which looks ugly return isUnderGTKLookAndFeel() ? getTreeTextBackground() : UIManager.getColor("Table.background"); } public static Color getTableBackground(final boolean isSelected) { return isSelected ? getTableSelectionBackground() : getTableBackground(); } public static Color getTableSelectionForeground() { if (isUnderNimbusLookAndFeel()) { return UIManager.getColor("Table[Enabled+Selected].textForeground"); } return UIManager.getColor("Table.selectionForeground"); } public static Color getTableForeground() { return UIManager.getColor("Table.foreground"); } public static Color getTableForeground(final boolean isSelected) { return isSelected ? getTableSelectionForeground() : getTableForeground(); } public static Color getTableGridColor() { return UIManager.getColor("Table.gridColor"); } public static Color getListBackground() { if (isUnderNimbusLookAndFeel()) { final Color color = UIManager.getColor("List.background"); //noinspection UseJBColor return new Color(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); } // Under GTK+ L&F "Table.background" often has main panel color, which looks ugly return isUnderGTKLookAndFeel() ? getTreeTextBackground() : UIManager.getColor("List.background"); } public static Color getListBackground(boolean isSelected) { return isSelected ? getListSelectionBackground() : getListBackground(); } public static Color getListForeground() { return UIManager.getColor("List.foreground"); } public static Color getListForeground(boolean isSelected) { return isSelected ? getListSelectionForeground() : getListForeground(); } public static Color getPanelBackground() { return UIManager.getColor("Panel.background"); } public static Color getTreeBackground() { return UIManager.getColor("Tree.background"); } public static Color getTreeForeground() { return UIManager.getColor("Tree.foreground"); } public static Color getTableFocusCellBackground() { return UIManager.getColor(TABLE_FOCUS_CELL_BACKGROUND_PROPERTY); } public static Color getListSelectionBackground() { if (isUnderNimbusLookAndFeel()) { return UIManager.getColor("List[Selected].textBackground"); // Nimbus } return UIManager.getColor("List.selectionBackground"); } public static Color getListUnfocusedSelectionBackground() { return isUnderDarcula() ? Gray._52 : UNFOCUSED_SELECTION_COLOR; } public static Color getTreeSelectionBackground(boolean focused) { return focused ? getTreeSelectionBackground() : getTreeUnfocusedSelectionBackground(); } public static Color getTreeUnfocusedSelectionBackground() { Color background = getTreeTextBackground(); return ColorUtil.isDark(background) ? new JBColor(Gray._30, new Color(13, 41, 62)) : UNFOCUSED_SELECTION_COLOR; } public static Color getTextFieldForeground() { return UIManager.getColor("TextField.foreground"); } public static Color getTextFieldBackground() { return isUnderGTKLookAndFeel() ? UIManager.getColor("EditorPane.background") : UIManager.getColor("TextField.background"); } public static Font getButtonFont() { return UIManager.getFont("Button.font"); } public static Font getToolTipFont() { return UIManager.getFont("ToolTip.font"); } public static Color getTabbedPaneBackground() { return UIManager.getColor("TabbedPane.background"); } public static void setSliderIsFilled(final JSlider slider, final boolean value) { slider.putClientProperty("JSlider.isFilled", Boolean.valueOf(value)); } public static Color getLabelTextForeground() { return UIManager.getColor("Label.textForeground"); } public static Color getControlColor() { return UIManager.getColor("control"); } public static Font getOptionPaneMessageFont() { return UIManager.getFont("OptionPane.messageFont"); } public static Font getMenuFont() { return UIManager.getFont("Menu.font"); } public static Color getSeparatorForeground() { return UIManager.getColor("Separator.foreground"); } public static Color getSeparatorBackground() { return UIManager.getColor("Separator.background"); } public static Color getSeparatorShadow() { return UIManager.getColor("Separator.shadow"); } public static Color getSeparatorHighlight() { return UIManager.getColor("Separator.highlight"); } public static Color getSeparatorColorUnderNimbus() { return UIManager.getColor("nimbusBlueGrey"); } public static Color getSeparatorColor() { Color separatorColor = getSeparatorForeground(); if (isUnderAlloyLookAndFeel()) { separatorColor = getSeparatorShadow(); } if (isUnderNimbusLookAndFeel()) { separatorColor = getSeparatorColorUnderNimbus(); } //under GTK+ L&F colors set hard if (isUnderGTKLookAndFeel()) { separatorColor = Gray._215; } return separatorColor; } public static Border getTableFocusCellHighlightBorder() { return UIManager.getBorder("Table.focusCellHighlightBorder"); } public static void setLineStyleAngled(final ClientPropertyHolder component) { component.putClientProperty("JTree.lineStyle", "Angled"); } public static void setLineStyleAngled(final JTree component) { component.putClientProperty("JTree.lineStyle", "Angled"); } public static Color getTableFocusCellForeground() { return UIManager.getColor("Table.focusCellForeground"); } /** * @deprecated use com.intellij.util.ui.UIUtil#getPanelBackground() instead */ public static Color getPanelBackgound() { return getPanelBackground(); } public static Border getTextFieldBorder() { return UIManager.getBorder("TextField.border"); } public static Border getButtonBorder() { return UIManager.getBorder("Button.border"); } public static Icon getErrorIcon() { return UIManager.getIcon("OptionPane.errorIcon"); } public static Icon getInformationIcon() { return UIManager.getIcon("OptionPane.informationIcon"); } public static Icon getQuestionIcon() { return UIManager.getIcon("OptionPane.questionIcon"); } public static Icon getWarningIcon() { return UIManager.getIcon("OptionPane.warningIcon"); } public static Icon getBalloonInformationIcon() { return AllIcons.General.BalloonInformation; } public static Icon getBalloonWarningIcon() { return AllIcons.General.BalloonWarning; } public static Icon getBalloonErrorIcon() { return AllIcons.General.BalloonError; } public static Icon getRadioButtonIcon() { return UIManager.getIcon("RadioButton.icon"); } public static Icon getTreeNodeIcon(boolean expanded, boolean selected, boolean focused) { boolean white = (selected && focused) || isUnderDarcula(); Icon selectedIcon = getTreeSelectedExpandedIcon(); Icon notSelectedIcon = getTreeExpandedIcon(); int width = Math.max(selectedIcon.getIconWidth(), notSelectedIcon.getIconWidth()); int height = Math.max(selectedIcon.getIconWidth(), notSelectedIcon.getIconWidth()); return new CenteredIcon(expanded ? (white ? getTreeSelectedExpandedIcon() : getTreeExpandedIcon()) : (white ? getTreeSelectedCollapsedIcon() : getTreeCollapsedIcon()), width, height, false); } public static Icon getTreeCollapsedIcon() { return UIManager.getIcon("Tree.collapsedIcon"); } public static Icon getTreeExpandedIcon() { return UIManager.getIcon("Tree.expandedIcon"); } public static Icon getTreeIcon(boolean expanded) { return expanded ? getTreeExpandedIcon() : getTreeCollapsedIcon(); } public static Icon getTreeSelectedCollapsedIcon() { return isUnderAquaBasedLookAndFeel() || isUnderNimbusLookAndFeel() || isUnderGTKLookAndFeel() || isUnderDarcula() || isUnderIntelliJLaF() ? AllIcons.Mac.Tree_white_right_arrow : getTreeCollapsedIcon(); } public static Icon getTreeSelectedExpandedIcon() { return isUnderAquaBasedLookAndFeel() || isUnderNimbusLookAndFeel() || isUnderGTKLookAndFeel() || isUnderDarcula() || isUnderIntelliJLaF() ? AllIcons.Mac.Tree_white_down_arrow : getTreeExpandedIcon(); } public static Border getTableHeaderCellBorder() { return UIManager.getBorder("TableHeader.cellBorder"); } public static Color getWindowColor() { return UIManager.getColor("window"); } public static Color getTextAreaForeground() { return UIManager.getColor("TextArea.foreground"); } public static Color getOptionPaneBackground() { return UIManager.getColor("OptionPane.background"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderAlloyLookAndFeel() { return UIManager.getLookAndFeel().getName().contains("Alloy"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderAlloyIDEALookAndFeel() { return isUnderAlloyLookAndFeel() && UIManager.getLookAndFeel().getName().contains("IDEA"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderWindowsLookAndFeel() { return UIManager.getLookAndFeel().getName().equals("Windows"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderWindowsClassicLookAndFeel() { return UIManager.getLookAndFeel().getName().equals("Windows Classic"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderNimbusLookAndFeel() { return UIManager.getLookAndFeel().getName().contains("Nimbus"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderAquaLookAndFeel() { return SystemInfo.isMac && UIManager.getLookAndFeel().getName().contains("Mac OS X"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderJGoodiesLookAndFeel() { return UIManager.getLookAndFeel().getName().contains("JGoodies"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderAquaBasedLookAndFeel() { return SystemInfo.isMac && (isUnderAquaLookAndFeel() || isUnderDarcula()); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderDarcula() { return UIManager.getLookAndFeel().getName().contains("Darcula"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderIntelliJLaF() { return UIManager.getLookAndFeel().getName().contains("IntelliJ"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderGTKLookAndFeel() { return UIManager.getLookAndFeel().getName().contains("GTK"); } public static final Color GTK_AMBIANCE_TEXT_COLOR = new Color(223, 219, 210); public static final Color GTK_AMBIANCE_BACKGROUND_COLOR = new Color(67, 66, 63); @SuppressWarnings({"HardCodedStringLiteral"}) @Nullable public static String getGtkThemeName() { final LookAndFeel laf = UIManager.getLookAndFeel(); if (laf != null && "GTKLookAndFeel".equals(laf.getClass().getSimpleName())) { try { final Method method = laf.getClass().getDeclaredMethod("getGtkThemeName"); method.setAccessible(true); final Object theme = method.invoke(laf); if (theme != null) { return theme.toString(); } } catch (Exception ignored) { } } return null; } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isMurrineBasedTheme() { final String gtkTheme = getGtkThemeName(); return "Ambiance".equalsIgnoreCase(gtkTheme) || "Radiance".equalsIgnoreCase(gtkTheme) || "Dust".equalsIgnoreCase(gtkTheme) || "Dust Sand".equalsIgnoreCase(gtkTheme); } public static Color shade(final Color c, final double factor, final double alphaFactor) { assert factor >= 0 : factor; return new Color( Math.min((int)Math.round(c.getRed() * factor), 255), Math.min((int)Math.round(c.getGreen() * factor), 255), Math.min((int)Math.round(c.getBlue() * factor), 255), Math.min((int)Math.round(c.getAlpha() * alphaFactor), 255) ); } public static Color mix(final Color c1, final Color c2, final double factor) { assert 0 <= factor && factor <= 1.0 : factor; final double backFactor = 1.0 - factor; return new Color( Math.min((int)Math.round(c1.getRed() * backFactor + c2.getRed() * factor), 255), Math.min((int)Math.round(c1.getGreen() * backFactor + c2.getGreen() * factor), 255), Math.min((int)Math.round(c1.getBlue() * backFactor + c2.getBlue() * factor), 255) ); } public static boolean isFullRowSelectionLAF() { return isUnderGTKLookAndFeel(); } public static boolean isUnderNativeMacLookAndFeel() { return isUnderAquaLookAndFeel() || isUnderDarcula(); } public static int getListCellHPadding() { return isUnderNativeMacLookAndFeel() ? 7 : 2; } public static int getListCellVPadding() { return 1; } public static Insets getListCellPadding() { return new Insets(getListCellVPadding(), getListCellHPadding(), getListCellVPadding(), getListCellHPadding()); } public static Insets getListViewportPadding() { return isUnderNativeMacLookAndFeel() ? new Insets(1, 0, 1, 0) : new Insets(5, 5, 5, 5); } public static boolean isToUseDottedCellBorder() { return !isUnderNativeMacLookAndFeel(); } public static boolean isControlKeyDown(MouseEvent mouseEvent) { return SystemInfo.isMac ? mouseEvent.isMetaDown() : mouseEvent.isControlDown(); } public static String[] getValidFontNames(final boolean familyName) { Set<String> result = new TreeSet<String>(); // adds fonts that can display symbols at [A, Z] + [a, z] + [0, 9] for (Font font : GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts()) { try { if (isValidFont(font)) { result.add(familyName ? font.getFamily() : font.getName()); } } catch (Exception ignore) { // JRE has problems working with the font. Just skip. } } // add label font (if isn't listed among above) Font labelFont = getLabelFont(); if (labelFont != null && isValidFont(labelFont)) { result.add(familyName ? labelFont.getFamily() : labelFont.getName()); } return ArrayUtil.toStringArray(result); } public static String[] getStandardFontSizes() { return STANDARD_FONT_SIZES; } public static boolean isValidFont(@NotNull Font font) { try { return font.canDisplay('a') && font.canDisplay('z') && font.canDisplay('A') && font.canDisplay('Z') && font.canDisplay('0') && font.canDisplay('1'); } catch (Exception e) { // JRE has problems working with the font. Just skip. return false; } } public static void setupEnclosingDialogBounds(final JComponent component) { component.revalidate(); component.repaint(); final Window window = SwingUtilities.windowForComponent(component); if (window != null && (window.getSize().height < window.getMinimumSize().height || window.getSize().width < window.getMinimumSize().width)) { window.pack(); } } public static String displayPropertiesToCSS(Font font, Color fg) { @NonNls StringBuilder rule = new StringBuilder("body {"); if (font != null) { rule.append(" font-family: "); rule.append(font.getFamily()); rule.append(" ; "); rule.append(" font-size: "); rule.append(font.getSize()); rule.append("pt ;"); if (font.isBold()) { rule.append(" font-weight: 700 ; "); } if (font.isItalic()) { rule.append(" font-style: italic ; "); } } if (fg != null) { rule.append(" color: #"); appendColor(fg, rule); rule.append(" ; "); } rule.append(" }"); return rule.toString(); } public static void appendColor(final Color color, final StringBuilder sb) { if (color.getRed() < 16) sb.append('0'); sb.append(Integer.toHexString(color.getRed())); if (color.getGreen() < 16) sb.append('0'); sb.append(Integer.toHexString(color.getGreen())); if (color.getBlue() < 16) sb.append('0'); sb.append(Integer.toHexString(color.getBlue())); } /** * @param g graphics. * @param x top left X coordinate. * @param y top left Y coordinate. * @param x1 right bottom X coordinate. * @param y1 right bottom Y coordinate. */ public static void drawDottedRectangle(Graphics g, int x, int y, int x1, int y1) { int i1; for (i1 = x; i1 <= x1; i1 += 2) { drawLine(g, i1, y, i1, y); } for (i1 = i1 != x1 + 1 ? y + 2 : y + 1; i1 <= y1; i1 += 2) { drawLine(g, x1, i1, x1, i1); } for (i1 = i1 != y1 + 1 ? x1 - 2 : x1 - 1; i1 >= x; i1 -= 2) { drawLine(g, i1, y1, i1, y1); } for (i1 = i1 != x - 1 ? y1 - 2 : y1 - 1; i1 >= y; i1 -= 2) { drawLine(g, x, i1, x, i1); } } /** * Should be invoked only in EDT. * * @param g Graphics surface * @param startX Line start X coordinate * @param endX Line end X coordinate * @param lineY Line Y coordinate * @param bgColor Background color (optional) * @param fgColor Foreground color (optional) * @param opaque If opaque the image will be dr */ public static void drawBoldDottedLine(final Graphics2D g, final int startX, final int endX, final int lineY, final Color bgColor, final Color fgColor, final boolean opaque) { if ((SystemInfo.isMac && !isRetina()) || SystemInfo.isLinux) { drawAppleDottedLine(g, startX, endX, lineY, bgColor, fgColor, opaque); } else { drawBoringDottedLine(g, startX, endX, lineY, bgColor, fgColor, opaque); } } public static void drawSearchMatch(final Graphics2D g, final int startX, final int endX, final int height) { Color c1 = new Color(255, 234, 162); Color c2 = new Color(255, 208, 66); drawSearchMatch(g, startX, endX, height, c1, c2); } public static void drawSearchMatch(Graphics2D g, int startX, int endX, int height, Color c1, Color c2) { final boolean drawRound = endX - startX > 4; final Composite oldComposite = g.getComposite(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f)); g.setPaint(getGradientPaint(startX, 2, c1, startX, height - 5, c2)); if (isRetina()) { g.fillRoundRect(startX - 1, 2, endX - startX + 1, height - 4, 5, 5); g.setComposite(oldComposite); return; } g.fillRect(startX, 3, endX - startX, height - 5); if (drawRound) { g.drawLine(startX - 1, 4, startX - 1, height - 4); g.drawLine(endX, 4, endX, height - 4); g.setColor(new Color(100, 100, 100, 50)); g.drawLine(startX - 1, 4, startX - 1, height - 4); g.drawLine(endX, 4, endX, height - 4); g.drawLine(startX, 3, endX - 1, 3); g.drawLine(startX, height - 3, endX - 1, height - 3); } g.setComposite(oldComposite); } public static void drawRectPickedOut(Graphics2D g, int x, int y, int w, int h) { g.drawLine(x + 1, y, x + w - 1, y); g.drawLine(x + w, y + 1, x + w, y + h - 1); g.drawLine(x + w - 1, y + h, x + 1, y + h); g.drawLine(x, y + 1, x, y + h - 1); } private static void drawBoringDottedLine(final Graphics2D g, final int startX, final int endX, final int lineY, final Color bgColor, final Color fgColor, final boolean opaque) { final Color oldColor = g.getColor(); // Fill 2 lines with background color if (opaque && bgColor != null) { g.setColor(bgColor); drawLine(g, startX, lineY, endX, lineY); drawLine(g, startX, lineY + 1, endX, lineY + 1); } // Draw dotted line: // // CCC CCC CCC ... // CCC CCC CCC ... // // (where "C" - colored pixel, " " - white pixel) final int step = 4; final int startPosCorrection = startX % step < 3 ? 0 : 1; g.setColor(fgColor != null ? fgColor : oldColor); // Now draw bold line segments for (int dotXi = (startX / step + startPosCorrection) * step; dotXi < endX; dotXi += step) { g.drawLine(dotXi, lineY, dotXi + 1, lineY); g.drawLine(dotXi, lineY + 1, dotXi + 1, lineY + 1); } // restore color g.setColor(oldColor); } public static void drawGradientHToolbarBackground(final Graphics g, final int width, final int height) { final Graphics2D g2d = (Graphics2D)g; g2d.setPaint(getGradientPaint(0, 0, Gray._215, 0, height, Gray._200)); g2d.fillRect(0, 0, width, height); } public static void drawHeader(Graphics g, int x, int width, int height, boolean active, boolean drawTopLine) { drawHeader(g, x, width, height, active, false, drawTopLine, true); } public static void drawHeader(Graphics g, int x, int width, int height, boolean active, boolean toolWindow, boolean drawTopLine, boolean drawBottomLine) { g.setColor(getPanelBackground()); g.fillRect(x, 0, width, height); ((Graphics2D)g).setPaint(getGradientPaint(0, 0, new Color(0, 0, 0, 5), 0, height, new Color(0, 0, 0, 20))); g.fillRect(x, 0, width, height); g.setColor(new Color(0, 0, 0, toolWindow ? 90 : 50)); if (drawTopLine) g.drawLine(x, 0, width, 0); if (drawBottomLine) g.drawLine(x, height - 1, width, height - 1); g.setColor(isUnderDarcula() ? Gray._255.withAlpha(30) : new Color(255, 255, 255, 100)); g.drawLine(x, drawTopLine ? 1 : 0, width, drawTopLine ? 1 : 0); if (active) { g.setColor(new Color(100, 150, 230, toolWindow ? 50 : 30)); g.fillRect(x, 0, width, height); } } public static void drawDoubleSpaceDottedLine(final Graphics2D g, final int start, final int end, final int xOrY, final Color fgColor, boolean horizontal) { g.setColor(fgColor); for (int dot = start; dot < end; dot += 3) { if (horizontal) { g.drawLine(dot, xOrY, dot, xOrY); } else { g.drawLine(xOrY, dot, xOrY, dot); } } } private static void drawAppleDottedLine(final Graphics2D g, final int startX, final int endX, final int lineY, final Color bgColor, final Color fgColor, final boolean opaque) { final Color oldColor = g.getColor(); // Fill 3 lines with background color if (opaque && bgColor != null) { g.setColor(bgColor); drawLine(g, startX, lineY, endX, lineY); drawLine(g, startX, lineY + 1, endX, lineY + 1); drawLine(g, startX, lineY + 2, endX, lineY + 2); } // Draw apple like dotted line: // // CCC CCC CCC ... // CCC CCC CCC ... // CCC CCC CCC ... // // (where "C" - colored pixel, " " - white pixel) final int step = 4; final int startPosCorrection = startX % step < 3 ? 0 : 1; // Optimization - lets draw dotted line using dot sample image. // draw one dot by pixel: // save old settings final Composite oldComposite = g.getComposite(); // draw image "over" on top of background g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); // sample final BufferedImage image = getAppleDotStamp(fgColor, oldColor); // Now copy our dot several times final int dotX0 = (startX / step + startPosCorrection) * step; for (int dotXi = dotX0; dotXi < endX; dotXi += step) { g.drawImage(image, dotXi, lineY, null); } //restore previous settings g.setComposite(oldComposite); } private static BufferedImage getAppleDotStamp(final Color fgColor, final Color oldColor) { final Color color = fgColor != null ? fgColor : oldColor; // let's avoid of generating tons of GC and store samples for different colors BufferedImage sample = ourAppleDotSamples.get(color); if (sample == null) { sample = createAppleDotStamp(color); ourAppleDotSamples.put(color, sample); } return sample; } private static BufferedImage createAppleDotStamp(final Color color) { final BufferedImage image = createImage(3, 3, BufferedImage.TYPE_INT_ARGB); final Graphics2D g = image.createGraphics(); g.setColor(color); // Each dot: // | 20% | 50% | 20% | // | 80% | 80% | 80% | // | 50% | 100% | 50% | g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .2f)); g.drawLine(0, 0, 0, 0); g.drawLine(2, 0, 2, 0); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0.7f)); g.drawLine(0, 1, 2, 1); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f)); g.drawLine(1, 2, 1, 2); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .5f)); g.drawLine(1, 0, 1, 0); g.drawLine(0, 2, 0, 2); g.drawLine(2, 2, 2, 2); // dispose graphics g.dispose(); return image; } public static void applyRenderingHints(final Graphics g) { Toolkit tk = Toolkit.getDefaultToolkit(); //noinspection HardCodedStringLiteral Map map = (Map)tk.getDesktopProperty("awt.font.desktophints"); if (map != null) { ((Graphics2D)g).addRenderingHints(map); } } public static BufferedImage createImage(int width, int height, int type) { if (isRetina()) { return RetinaImage.create(width, height, type); } //noinspection UndesirableClassUsage return new BufferedImage(width, height, type); } public static void drawImage(Graphics g, Image image, int x, int y, ImageObserver observer) { if (image instanceof JBHiDPIScaledImage) { final Graphics2D newG = (Graphics2D)g.create(x, y, image.getWidth(observer), image.getHeight(observer)); newG.scale(0.5, 0.5); Image img = ((JBHiDPIScaledImage)image).getDelegate(); if (img == null) { img = image; } newG.drawImage(img, 0, 0, observer); newG.scale(1, 1); newG.dispose(); } else { g.drawImage(image, x, y, observer); } } public static void drawImage(Graphics g, BufferedImage image, BufferedImageOp op, int x, int y) { if (image instanceof JBHiDPIScaledImage) { final Graphics2D newG = (Graphics2D)g.create(x, y, image.getWidth(null), image.getHeight(null)); newG.scale(0.5, 0.5); Image img = ((JBHiDPIScaledImage)image).getDelegate(); if (img == null) { img = image; } newG.drawImage((BufferedImage)img, op, 0, 0); newG.scale(1, 1); newG.dispose(); } else { ((Graphics2D)g).drawImage(image, op, x, y); } } public static void paintWithXorOnRetina(@NotNull Dimension size, @NotNull Graphics g, Consumer<Graphics2D> paintRoutine) { paintWithXorOnRetina(size, g, true, paintRoutine); } /** * Direct painting into component's graphics with XORMode is broken on retina-mode so we need to paint into an intermediate buffer first. */ public static void paintWithXorOnRetina(@NotNull Dimension size, @NotNull Graphics g, boolean useRetinaCondition, Consumer<Graphics2D> paintRoutine) { if (!useRetinaCondition || !isRetina() || Registry.is("ide.mac.retina.disableDrawingFix", false)) { paintRoutine.consume((Graphics2D)g); } else { Rectangle rect = g.getClipBounds(); if (rect == null) rect = new Rectangle(size); //noinspection UndesirableClassUsage Image image = new BufferedImage(rect.width * 2, rect.height * 2, BufferedImage.TYPE_INT_RGB); Graphics2D imageGraphics = (Graphics2D)image.getGraphics(); imageGraphics.scale(2, 2); imageGraphics.translate(-rect.x, -rect.y); imageGraphics.setClip(rect.x, rect.y, rect.width, rect.height); paintRoutine.consume(imageGraphics); image.flush(); imageGraphics.dispose(); ((Graphics2D)g).scale(0.5, 0.5); g.drawImage(image, rect.x * 2, rect.y * 2, null); } } /** * Configures composite to use for drawing text with the given graphics container. * <p/> * The whole idea is that <a href="http://en.wikipedia.org/wiki/X_Rendering_Extension">XRender-based</a> pipeline doesn't support * {@link AlphaComposite#SRC} and we should use {@link AlphaComposite#SRC_OVER} instead. * * @param g target graphics container */ public static void setupComposite(@NotNull Graphics2D g) { g.setComposite(X_RENDER_ACTIVE.getValue() ? AlphaComposite.SrcOver : AlphaComposite.Src); } /** @see #pump() */ @TestOnly public static void dispatchAllInvocationEvents() { assert SwingUtilities.isEventDispatchThread() : Thread.currentThread(); final EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); while (true) { AWTEvent event = eventQueue.peekEvent(); if (event == null) break; try { AWTEvent event1 = eventQueue.getNextEvent(); if (event1 instanceof InvocationEvent) { ((InvocationEvent)event1).dispatch(); } } catch (Exception e) { LOG.error(e); //? } } } /** @see #dispatchAllInvocationEvents() */ @TestOnly public static void pump() { assert !SwingUtilities.isEventDispatchThread(); final BlockingQueue<Object> queue = new LinkedBlockingQueue<Object>(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { queue.offer(queue); } }); try { queue.take(); } catch (InterruptedException e) { LOG.error(e); } } public static void addAwtListener(final AWTEventListener listener, long mask, Disposable parent) { Toolkit.getDefaultToolkit().addAWTEventListener(listener, mask); Disposer.register(parent, new Disposable() { @Override public void dispose() { Toolkit.getDefaultToolkit().removeAWTEventListener(listener); } }); } public static void drawVDottedLine(Graphics2D g, int lineX, int startY, int endY, @Nullable final Color bgColor, final Color fgColor) { if (bgColor != null) { g.setColor(bgColor); drawLine(g, lineX, startY, lineX, endY); } g.setColor(fgColor); for (int i = (startY / 2) * 2; i < endY; i += 2) { g.drawRect(lineX, i, 0, 0); } } public static void drawHDottedLine(Graphics2D g, int startX, int endX, int lineY, @Nullable final Color bgColor, final Color fgColor) { if (bgColor != null) { g.setColor(bgColor); drawLine(g, startX, lineY, endX, lineY); } g.setColor(fgColor); for (int i = (startX / 2) * 2; i < endX; i += 2) { g.drawRect(i, lineY, 0, 0); } } public static void drawDottedLine(Graphics2D g, int x1, int y1, int x2, int y2, @Nullable final Color bgColor, final Color fgColor) { if (x1 == x2) { drawVDottedLine(g, x1, y1, y2, bgColor, fgColor); } else if (y1 == y2) { drawHDottedLine(g, x1, x2, y1, bgColor, fgColor); } else { throw new IllegalArgumentException("Only vertical or horizontal lines are supported"); } } public static void drawStringWithHighlighting(Graphics g, String s, int x, int y, Color foreground, Color highlighting) { g.setColor(highlighting); for (int i = x - 1; i <= x + 1; i++) { for (int j = y - 1; j <= y + 1; j++) { g.drawString(s, i, j); } } g.setColor(foreground); g.drawString(s, x, y); } public static boolean isFocusAncestor(@NotNull final JComponent component) { final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (owner == null) return false; if (owner == component) return true; return SwingUtilities.isDescendingFrom(owner, component); } public static boolean isCloseClick(MouseEvent e) { return isCloseClick(e, MouseEvent.MOUSE_PRESSED); } public static boolean isCloseClick(MouseEvent e, int effectiveType) { if (e.isPopupTrigger() || e.getID() != effectiveType) return false; return e.getButton() == MouseEvent.BUTTON2 || e.getButton() == MouseEvent.BUTTON1 && e.isShiftDown(); } public static boolean isActionClick(MouseEvent e) { return isActionClick(e, MouseEvent.MOUSE_PRESSED); } public static boolean isActionClick(MouseEvent e, int effectiveType) { return isActionClick(e, effectiveType, false); } public static boolean isActionClick(MouseEvent e, int effectiveType, boolean allowShift) { if (!allowShift && isCloseClick(e) || e.isPopupTrigger() || e.getID() != effectiveType) return false; return e.getButton() == MouseEvent.BUTTON1; } @NotNull public static Color getBgFillColor(@NotNull JComponent c) { final Component parent = findNearestOpaque(c); return parent == null ? c.getBackground() : parent.getBackground(); } @Nullable public static Component findNearestOpaque(JComponent c) { Component eachParent = c; while (eachParent != null) { if (eachParent.isOpaque()) return eachParent; eachParent = eachParent.getParent(); } return null; } @NonNls public static String getCssFontDeclaration(final Font font) { return getCssFontDeclaration(font, null, null, null); } @Language("HTML") @NonNls public static String getCssFontDeclaration(final Font font, @Nullable Color fgColor, @Nullable Color linkColor, @Nullable String liImg) { URL resource = liImg != null ? SystemInfo.class.getResource(liImg) : null; @NonNls String fontFamilyAndSize = "font-family:'" + font.getFamily() + "'; font-size:" + font.getSize() + "pt;"; @NonNls @Language("HTML") String body = "body, div, td, p {" + fontFamilyAndSize + " " + (fgColor != null ? "color:#" + ColorUtil.toHex(fgColor)+";" : "") + "}\n"; if (resource != null) { body += "ul {list-style-image:url('" + resource.toExternalForm() + "');}\n"; } @NonNls String link = linkColor != null ? "a {" + fontFamilyAndSize + " color:#"+ColorUtil.toHex(linkColor) + ";}\n" : ""; return "<style>\n" + body + link + "</style>"; } public static boolean isWinLafOnVista() { return SystemInfo.isWinVistaOrNewer && "Windows".equals(UIManager.getLookAndFeel().getName()); } public static boolean isStandardMenuLAF() { return isWinLafOnVista() || isUnderNimbusLookAndFeel() || isUnderGTKLookAndFeel(); } public static Color getFocusedFillColor() { return toAlpha(getListSelectionBackground(), 100); } public static Color getFocusedBoundsColor() { return getBoundsColor(); } public static Color getBoundsColor() { return getBorderColor(); } public static Color getBoundsColor(boolean focused) { return focused ? getFocusedBoundsColor() : getBoundsColor(); } public static Color toAlpha(final Color color, final int alpha) { Color actual = color != null ? color : Color.black; return new Color(actual.getRed(), actual.getGreen(), actual.getBlue(), alpha); } public static void requestFocus(@NotNull final JComponent c) { if (c.isShowing()) { c.requestFocus(); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { c.requestFocus(); } }); } } //todo maybe should do for all kind of listeners via the AWTEventMulticaster class public static void dispose(final Component c) { if (c == null) return; final MouseListener[] mouseListeners = c.getMouseListeners(); for (MouseListener each : mouseListeners) { c.removeMouseListener(each); } final MouseMotionListener[] motionListeners = c.getMouseMotionListeners(); for (MouseMotionListener each : motionListeners) { c.removeMouseMotionListener(each); } final MouseWheelListener[] mouseWheelListeners = c.getMouseWheelListeners(); for (MouseWheelListener each : mouseWheelListeners) { c.removeMouseWheelListener(each); } } public static void disposeProgress(final JProgressBar progress) { if (!isUnderNativeMacLookAndFeel()) return; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (isToDispose(progress)) { progress.getUI().uninstallUI(progress); progress.putClientProperty("isDisposed", Boolean.TRUE); } } }); } private static boolean isToDispose(final JProgressBar progress) { final ProgressBarUI ui = progress.getUI(); if (ui == null) return false; if (Boolean.TYPE.equals(progress.getClientProperty("isDisposed"))) return false; try { final Field progressBarField = ReflectionUtil.findField(ui.getClass(), JProgressBar.class, "progressBar"); progressBarField.setAccessible(true); return progressBarField.get(ui) != null; } catch (NoSuchFieldException e) { return true; } catch (IllegalAccessException e) { return true; } } @Nullable public static Component findUltimateParent(Component c) { if (c == null) return null; Component eachParent = c; while (true) { if (eachParent.getParent() == null) return eachParent; eachParent = eachParent.getParent(); } } public static Color getHeaderActiveColor() { return ACTIVE_HEADER_COLOR; } public static Color getHeaderInactiveColor() { return INACTIVE_HEADER_COLOR; } public static Color getBorderColor() { return isUnderDarcula() ? Gray._50 : BORDER_COLOR; } public static Font getTitledBorderFont() { Font defFont = getLabelFont(); return defFont.deriveFont(Math.max(defFont.getSize() - 2f, 11f)); } /** * @deprecated use getBorderColor instead */ public static Color getBorderInactiveColor() { return getBorderColor(); } /** * @deprecated use getBorderColor instead */ public static Color getBorderActiveColor() { return getBorderColor(); } /** * @deprecated use getBorderColor instead */ public static Color getBorderSeparatorColor() { return getBorderColor(); } @Nullable public static StyleSheet loadStyleSheet(@Nullable URL url) { if (url == null) return null; try { StyleSheet styleSheet = new StyleSheet(); styleSheet.loadRules(new InputStreamReader(url.openStream(), CharsetToolkit.UTF8), url); return styleSheet; } catch (IOException e) { LOG.warn(url + " loading failed", e); return null; } } public static HTMLEditorKit getHTMLEditorKit() { Font font = getLabelFont(); @NonNls String family = font != null ? font.getFamily() : "Tahoma"; int size = font != null ? font.getSize() : 11; final String customCss = String.format("body, div, p { font-family: %s; font-size: %s; } p { margin-top: 0; }", family, size); final StyleSheet style = new StyleSheet(); style.addStyleSheet(isUnderDarcula() ? (StyleSheet)UIManager.getDefaults().get("StyledEditorKit.JBDefaultStyle") : DEFAULT_HTML_KIT_CSS); style.addRule(customCss); return new HTMLEditorKit() { @Override public StyleSheet getStyleSheet() { return style; } }; } public static void removeScrollBorder(final Component c) { new AwtVisitor(c) { @Override public boolean visit(final Component component) { if (component instanceof JScrollPane) { if (!hasNonPrimitiveParents(c, component)) { final JScrollPane scrollPane = (JScrollPane)component; Integer keepBorderSides = (Integer)scrollPane.getClientProperty(KEEP_BORDER_SIDES); if (keepBorderSides != null) { if (scrollPane.getBorder() instanceof LineBorder) { Color color = ((LineBorder)scrollPane.getBorder()).getLineColor(); scrollPane.setBorder(new SideBorder(color, keepBorderSides.intValue())); } else { scrollPane.setBorder(new SideBorder(getBoundsColor(), keepBorderSides.intValue())); } } else { scrollPane.setBorder(new SideBorder(getBoundsColor(), SideBorder.NONE)); } } } return false; } }; } public static boolean hasNonPrimitiveParents(Component stopParent, Component c) { Component eachParent = c.getParent(); while (true) { if (eachParent == null || eachParent == stopParent) return false; if (!isPrimitive(eachParent)) return true; eachParent = eachParent.getParent(); } } public static boolean isPrimitive(Component c) { return c instanceof JPanel || c instanceof JLayeredPane; } public static Point getCenterPoint(Dimension container, Dimension child) { return getCenterPoint(new Rectangle(new Point(), container), child); } public static Point getCenterPoint(Rectangle container, Dimension child) { Point result = new Point(); Point containerLocation = container.getLocation(); Dimension containerSize = container.getSize(); result.x = containerLocation.x + containerSize.width / 2 - child.width / 2; result.y = containerLocation.y + containerSize.height / 2 - child.height / 2; return result; } public static String toHtml(String html) { return toHtml(html, 0); } @NonNls public static String toHtml(String html, final int hPadding) { html = CLOSE_TAG_PATTERN.matcher(html).replaceAll("<$1$2></$1>"); Font font = getLabelFont(); @NonNls String family = font != null ? font.getFamily() : "Tahoma"; int size = font != null ? font.getSize() : 11; return "<html><style>body { font-family: " + family + "; font-size: " + size + ";} ul li {list-style-type:circle;}</style>" + addPadding(html, hPadding) + "</html>"; } public static String addPadding(final String html, int hPadding) { return String.format("<p style=\"margin: 0 %dpx 0 %dpx;\">%s</p>", hPadding, hPadding, html); } public static String convertSpace2Nbsp(String html) { @NonNls StringBuilder result = new StringBuilder(); int currentPos = 0; int braces = 0; while (currentPos < html.length()) { String each = html.substring(currentPos, currentPos + 1); if ("<".equals(each)) { braces++; } else if (">".equals(each)) { braces--; } if (" ".equals(each) && braces == 0) { result.append("&nbsp;"); } else { result.append(each); } currentPos++; } return result.toString(); } public static void invokeLaterIfNeeded(@NotNull Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { SwingUtilities.invokeLater(runnable); } } /** * Invoke and wait in the event dispatch thread * or in the current thread if the current thread * is event queue thread. * * @param runnable a runnable to invoke * @see #invokeAndWaitIfNeeded(com.intellij.util.ThrowableRunnable) */ public static void invokeAndWaitIfNeeded(@NotNull Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { try { SwingUtilities.invokeAndWait(runnable); } catch (Exception e) { LOG.error(e); } } } public static void invokeAndWaitIfNeeded(@NotNull final ThrowableRunnable runnable) throws Throwable { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { final Ref<Throwable> ref = new Ref<Throwable>(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { try { runnable.run(); } catch (Throwable throwable) { ref.set(throwable); } } }); if (!ref.isNull()) throw ref.get(); } } public static boolean isFocusProxy(@Nullable Component c) { return c instanceof JComponent && Boolean.TRUE.equals(((JComponent)c).getClientProperty(FOCUS_PROXY_KEY)); } public static void setFocusProxy(JComponent c, boolean isProxy) { c.putClientProperty(FOCUS_PROXY_KEY, isProxy ? Boolean.TRUE : null); } public static void maybeInstall(InputMap map, String action, KeyStroke stroke) { if (map.get(stroke) == null) { map.put(stroke, action); } } /** * Avoid blinking while changing background. * * @param component component. * @param background new background. */ public static void changeBackGround(final Component component, final Color background) { final Color oldBackGround = component.getBackground(); if (background == null || !background.equals(oldBackGround)) { component.setBackground(background); } } public static void initDefaultLAF() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); if (ourSystemFontData == null) { final Font font = getLabelFont(); ourSystemFontData = Pair.create(font.getName(), font.getSize()); } } catch (Exception ignored) { } } @Nullable public static Pair<String, Integer> getSystemFontData() { return ourSystemFontData; } public static void addKeyboardShortcut(final JComponent target, final AbstractButton button, final KeyStroke keyStroke) { target.registerKeyboardAction( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (button.isEnabled()) { button.doClick(); } } }, keyStroke, JComponent.WHEN_FOCUSED ); } public static void installComboBoxCopyAction(JComboBox comboBox) { final Component editorComponent = comboBox.getEditor().getEditorComponent(); if (!(editorComponent instanceof JTextComponent)) return; final InputMap inputMap = ((JTextComponent)editorComponent).getInputMap(); for (KeyStroke keyStroke : inputMap.allKeys()) { if (DefaultEditorKit.copyAction.equals(inputMap.get(keyStroke))) { comboBox.getInputMap().put(keyStroke, DefaultEditorKit.copyAction); } } comboBox.getActionMap().put(DefaultEditorKit.copyAction, new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { if (!(e.getSource() instanceof JComboBox)) return; final JComboBox comboBox = (JComboBox)e.getSource(); final String text; final Object selectedItem = comboBox.getSelectedItem(); if (selectedItem instanceof String) { text = (String)selectedItem; } else { final Component component = comboBox.getRenderer().getListCellRendererComponent(new JList(), selectedItem, 0, false, false); if (component instanceof JLabel) { text = ((JLabel)component).getText(); } else if (component != null) { final String str = component.toString(); // skip default Component.toString and handle SimpleColoredComponent case text = str == null || str.startsWith(component.getClass().getName() + "[") ? null : str; } else { text = null; } } if (text != null) { final JTextField textField = new JTextField(text); textField.selectAll(); textField.copy(); } } }); } @Nullable public static ComboPopup getComboBoxPopup(JComboBox comboBox) { final ComboBoxUI ui = comboBox.getUI(); if (ui instanceof BasicComboBoxUI) { try { final Field popup = BasicComboBoxUI.class.getDeclaredField("popup"); popup.setAccessible(true); return (ComboPopup)popup.get(ui); } catch (NoSuchFieldException e) { return null; } catch (IllegalAccessException e) { return null; } } return null; } @SuppressWarnings({"HardCodedStringLiteral"}) public static void fixFormattedField(JFormattedTextField field) { if (SystemInfo.isMac) { final Toolkit toolkit = Toolkit.getDefaultToolkit(); final int commandKeyMask = toolkit.getMenuShortcutKeyMask(); final InputMap inputMap = field.getInputMap(); final KeyStroke copyKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, commandKeyMask); inputMap.put(copyKeyStroke, "copy-to-clipboard"); final KeyStroke pasteKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_V, commandKeyMask); inputMap.put(pasteKeyStroke, "paste-from-clipboard"); final KeyStroke cutKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_X, commandKeyMask); inputMap.put(cutKeyStroke, "cut-to-clipboard"); } } public static boolean isPrinting(Graphics g) { return g instanceof PrintGraphics; } public static int getSelectedButton(ButtonGroup group) { Enumeration<AbstractButton> enumeration = group.getElements(); int i = 0; while (enumeration.hasMoreElements()) { AbstractButton button = enumeration.nextElement(); if (group.isSelected(button.getModel())) { return i; } i++; } return -1; } public static void setSelectedButton(ButtonGroup group, int index) { Enumeration<AbstractButton> enumeration = group.getElements(); int i = 0; while (enumeration.hasMoreElements()) { AbstractButton button = enumeration.nextElement(); group.setSelected(button.getModel(), index == i); i++; } } public static boolean isSelectionButtonDown(MouseEvent e) { return e.isShiftDown() || e.isControlDown() || e.isMetaDown(); } @SuppressWarnings("deprecation") public static void setComboBoxEditorBounds(int x, int y, int width, int height, JComponent editor) { if (SystemInfo.isMac && isUnderAquaLookAndFeel()) { // fix for too wide combobox editor, see AquaComboBoxUI.layoutContainer: // it adds +4 pixels to editor width. WTF?! editor.reshape(x, y, width - 4, height - 1); } else { editor.reshape(x, y, width, height); } } public static int fixComboBoxHeight(final int height) { return SystemInfo.isMac && isUnderAquaLookAndFeel() ? 28 : height; } /** * The main difference from javax.swing.SwingUtilities#isDescendingFrom(Component, Component) is that this method * uses getInvoker() instead of getParent() when it meets JPopupMenu * @param child child component * @param parent parent component * @return true if parent if a top parent of child, false otherwise * * @see javax.swing.SwingUtilities#isDescendingFrom(java.awt.Component, java.awt.Component) */ public static boolean isDescendingFrom(@Nullable Component child, @NotNull Component parent) { while (child != null && child != parent) { child = child instanceof JPopupMenu ? ((JPopupMenu)child).getInvoker() : child.getParent(); } return child == parent; } @Nullable public static <T> T getParentOfType(Class<? extends T> cls, Component c) { Component eachParent = c; while (eachParent != null) { if (cls.isAssignableFrom(eachParent.getClass())) { @SuppressWarnings({"unchecked"}) final T t = (T)eachParent; return t; } eachParent = eachParent.getParent(); } return null; } public static void scrollListToVisibleIfNeeded(@NotNull final JList list) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { final int selectedIndex = list.getSelectedIndex(); if (selectedIndex >= 0) { final Rectangle visibleRect = list.getVisibleRect(); final Rectangle cellBounds = list.getCellBounds(selectedIndex, selectedIndex); if (!visibleRect.contains(cellBounds)) { list.scrollRectToVisible(cellBounds); } } } }); } @Nullable public static <T extends JComponent> T findComponentOfType(JComponent parent, Class<T> cls) { if (parent == null || cls.isAssignableFrom(parent.getClass())) { @SuppressWarnings({"unchecked"}) final T t = (T)parent; return t; } for (Component component : parent.getComponents()) { if (component instanceof JComponent) { T comp = findComponentOfType((JComponent)component, cls); if (comp != null) return comp; } } return null; } public static <T extends JComponent> List<T> findComponentsOfType(JComponent parent, Class<T> cls) { final ArrayList<T> result = new ArrayList<T>(); findComponentsOfType(parent, cls, result); return result; } private static <T extends JComponent> void findComponentsOfType(JComponent parent, Class<T> cls, ArrayList<T> result) { if (parent == null) return; if (cls.isAssignableFrom(parent.getClass())) { @SuppressWarnings({"unchecked"}) final T t = (T)parent; result.add(t); } for (Component c : parent.getComponents()) { if (c instanceof JComponent) { findComponentsOfType((JComponent)c, cls, result); } } } public static class TextPainter { private final List<Pair<String, LineInfo>> myLines = new ArrayList<Pair<String, LineInfo>>(); private boolean myDrawShadow; private Color myShadowColor; private float myLineSpacing; public TextPainter() { myDrawShadow = /*isUnderAquaLookAndFeel() ||*/ isUnderDarcula(); myShadowColor = isUnderDarcula() ? Gray._0.withAlpha(100) : Gray._220; myLineSpacing = 1.0f; } public TextPainter withShadow(final boolean drawShadow) { myDrawShadow = drawShadow; return this; } public TextPainter withShadow(final boolean drawShadow, final Color shadowColor) { myDrawShadow = drawShadow; myShadowColor = shadowColor; return this; } public TextPainter withLineSpacing(final float lineSpacing) { myLineSpacing = lineSpacing; return this; } public TextPainter appendLine(final String text) { if (text == null || text.isEmpty()) return this; myLines.add(Pair.create(text, new LineInfo())); return this; } public TextPainter underlined(@Nullable final Color color) { if (!myLines.isEmpty()) { final LineInfo info = myLines.get(myLines.size() - 1).getSecond(); info.underlined = true; info.underlineColor = color; } return this; } public TextPainter withBullet(final char c) { if (!myLines.isEmpty()) { final LineInfo info = myLines.get(myLines.size() - 1).getSecond(); info.withBullet = true; info.bulletChar = c; } return this; } public TextPainter withBullet() { return withBullet('\u2022'); } public TextPainter underlined() { return underlined(null); } public TextPainter smaller() { if (!myLines.isEmpty()) { myLines.get(myLines.size() - 1).getSecond().smaller = true; } return this; } public TextPainter center() { if (!myLines.isEmpty()) { myLines.get(myLines.size() - 1).getSecond().center = true; } return this; } /** * _position(block width, block height) => (x, y) of the block */ public void draw(@NotNull final Graphics g, final PairFunction<Integer, Integer, Pair<Integer, Integer>> _position) { final int[] maxWidth = {0}; final int[] height = {0}; final int[] maxBulletWidth = {0}; ContainerUtil.process(myLines, new Processor<Pair<String, LineInfo>>() { @Override public boolean process(final Pair<String, LineInfo> pair) { final LineInfo info = pair.getSecond(); Font old = null; if (info.smaller) { old = g.getFont(); g.setFont(old.deriveFont(old.getSize() * 0.70f)); } final FontMetrics fm = g.getFontMetrics(); final int bulletWidth = info.withBullet ? fm.stringWidth(" " + info.bulletChar) : 0; maxBulletWidth[0] = Math.max(maxBulletWidth[0], bulletWidth); maxWidth[0] = Math.max(fm.stringWidth(pair.getFirst().replace("<shortcut>", "").replace("</shortcut>", "") + bulletWidth), maxWidth[0]); height[0] += (fm.getHeight() + fm.getLeading()) * myLineSpacing; if (old != null) { g.setFont(old); } return true; } }); final Pair<Integer, Integer> position = _position.fun(maxWidth[0] + 20, height[0]); assert position != null; final int[] yOffset = {position.getSecond()}; ContainerUtil.process(myLines, new Processor<Pair<String, LineInfo>>() { @Override public boolean process(final Pair<String, LineInfo> pair) { final LineInfo info = pair.getSecond(); String text = pair.first; String shortcut = ""; if (pair.first.contains("<shortcut>")) { shortcut = text.substring(text.indexOf("<shortcut>") + "<shortcut>".length(), text.indexOf("</shortcut>")); text = text.substring(0, text.indexOf("<shortcut>")); } Font old = null; if (info.smaller) { old = g.getFont(); g.setFont(old.deriveFont(old.getSize() * 0.70f)); } final int x = position.getFirst() + maxBulletWidth[0] + 10; final FontMetrics fm = g.getFontMetrics(); int xOffset = x; if (info.center) { xOffset = x + (maxWidth[0] - fm.stringWidth(text)) / 2; } if (myDrawShadow) { int xOff = isUnderDarcula() ? 1 : 0; int yOff = 1; Color oldColor = g.getColor(); g.setColor(myShadowColor); if (info.withBullet) { g.drawString(info.bulletChar + " ", x - fm.stringWidth(" " + info.bulletChar) + xOff, yOffset[0] + yOff); } g.drawString(text, xOffset + xOff, yOffset[0] + yOff); g.setColor(oldColor); } if (info.withBullet) { g.drawString(info.bulletChar + " ", x - fm.stringWidth(" " + info.bulletChar), yOffset[0]); } g.drawString(text, xOffset, yOffset[0]); if (!StringUtil.isEmpty(shortcut)) { Color oldColor = g.getColor(); if (isUnderDarcula()) { g.setColor(new Color(60, 118, 249)); } g.drawString(shortcut, xOffset + fm.stringWidth(text + (isUnderDarcula() ? " " : "")), yOffset[0]); g.setColor(oldColor); } if (info.underlined) { Color c = null; if (info.underlineColor != null) { c = g.getColor(); g.setColor(info.underlineColor); } g.drawLine(x - maxBulletWidth[0] - 10, yOffset[0] + fm.getDescent(), x + maxWidth[0] + 10, yOffset[0] + fm.getDescent()); if (c != null) { g.setColor(c); } if (myDrawShadow) { c = g.getColor(); g.setColor(myShadowColor); g.drawLine(x - maxBulletWidth[0] - 10, yOffset[0] + fm.getDescent() + 1, x + maxWidth[0] + 10, yOffset[0] + fm.getDescent() + 1); g.setColor(c); } } yOffset[0] += (fm.getHeight() + fm.getLeading()) * myLineSpacing; if (old != null) { g.setFont(old); } return true; } }); } private static class LineInfo { private boolean underlined; private boolean withBullet; private char bulletChar; private Color underlineColor; private boolean smaller; private boolean center; } } @Nullable public static JRootPane getRootPane(Component c) { JRootPane root = getParentOfType(JRootPane.class, c); if (root != null) return root; Component eachParent = c; while (eachParent != null) { if (eachParent instanceof JComponent) { @SuppressWarnings({"unchecked"}) WeakReference<JRootPane> pane = (WeakReference<JRootPane>)((JComponent)eachParent).getClientProperty(ROOT_PANE); if (pane != null) return pane.get(); } eachParent = eachParent.getParent(); } return null; } public static void setFutureRootPane(JComponent c, JRootPane pane) { c.putClientProperty(ROOT_PANE, new WeakReference<JRootPane>(pane)); } public static boolean isMeaninglessFocusOwner(@Nullable Component c) { if (c == null || !c.isShowing()) return true; return c instanceof JFrame || c instanceof JDialog || c instanceof JWindow || c instanceof JRootPane || isFocusProxy(c); } public static Timer createNamedTimer(@NonNls @NotNull final String name, int delay, @NotNull ActionListener listener) { return new Timer(delay, listener) { @Override public String toString() { return name; } }; } public static boolean isDialogRootPane(JRootPane rootPane) { if (rootPane != null) { final Object isDialog = rootPane.getClientProperty("DIALOG_ROOT_PANE"); return isDialog instanceof Boolean && ((Boolean)isDialog).booleanValue(); } return false; } @Nullable public static JComponent mergeComponentsWithAnchor(PanelWithAnchor... panels) { return mergeComponentsWithAnchor(Arrays.asList(panels)); } @Nullable public static JComponent mergeComponentsWithAnchor(Collection<? extends PanelWithAnchor> panels) { JComponent maxWidthAnchor = null; int maxWidth = 0; for (PanelWithAnchor panel : panels) { JComponent anchor = panel != null ? panel.getAnchor() : null; if (anchor != null) { int anchorWidth = anchor.getPreferredSize().width; if (maxWidth < anchorWidth) { maxWidth = anchorWidth; maxWidthAnchor = anchor; } } } for (PanelWithAnchor panel : panels) { if (panel != null) { panel.setAnchor(maxWidthAnchor); } } return maxWidthAnchor; } public static void setNotOpaqueRecursively(@NotNull Component component) { if (!isUnderAquaLookAndFeel()) return; if (component.getBackground().equals(getPanelBackground()) || component instanceof JScrollPane || component instanceof JViewport || component instanceof JLayeredPane) { if (component instanceof JComponent) { ((JComponent)component).setOpaque(false); } if (component instanceof Container) { for (Component c : ((Container)component).getComponents()) { setNotOpaqueRecursively(c); } } } } public static void addInsets(@NotNull JComponent component, @NotNull Insets insets) { if (component.getBorder() != null) { component.setBorder(new CompoundBorder(new EmptyBorder(insets), component.getBorder())); } else { component.setBorder(new EmptyBorder(insets)); } } public static Dimension addInsets(@NotNull Dimension dimension, @NotNull Insets insets) { Dimension ans = new Dimension(dimension); ans.width += insets.left; ans.width += insets.right; ans.height += insets.top; ans.height += insets.bottom; return ans; } public static void adjustWindowToMinimumSize(final Window window) { if (window == null) return; final Dimension minSize = window.getMinimumSize(); final Dimension size = window.getSize(); final Dimension newSize = new Dimension(Math.max(size.width, minSize.width), Math.max(size.height, minSize.height)); if (!newSize.equals(size)) { //noinspection SSBasedInspection SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (window.isShowing()) { window.setSize(newSize); } } }); } } @Nullable public static Color getColorAt(final Icon icon, final int x, final int y) { if (0 <= x && x < icon.getIconWidth() && 0 <= y && y < icon.getIconHeight()) { final BufferedImage image = createImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB); icon.paintIcon(null, image.getGraphics(), 0, 0); final int[] pixels = new int[1]; final PixelGrabber pixelGrabber = new PixelGrabber(image, x, y, 1, 1, pixels, 0, 1); try { pixelGrabber.grabPixels(); return new Color(pixels[0]); } catch (InterruptedException ignored) { } } return null; } public static void addBorder(JComponent component, Border border) { if (component == null) return; if (component.getBorder() != null) { component.setBorder(new CompoundBorder(border, component.getBorder())); } else { component.setBorder(border); } } private static final Color DECORATED_ROW_BG_COLOR = new JBColor(new Color(242, 245, 249), new Color(65, 69, 71)); public static Color getDecoratedRowColor() { return DECORATED_ROW_BG_COLOR; } @NotNull public static Paint getGradientPaint(float x1, float y1, @NotNull Color c1, float x2, float y2, @NotNull Color c2) { return (Registry.is("ui.no.bangs.and.whistles", false)) ? ColorUtil.mix(c1, c2, .5) : new GradientPaint(x1, y1, c1, x2, y2, c2); } @Nullable public static Point getLocationOnScreen(@NotNull JComponent component) { int dx = 0; int dy = 0; for (Container c = component; c != null; c = c.getParent()) { if (c.isShowing()) { Point locationOnScreen = c.getLocationOnScreen(); locationOnScreen.translate(dx, dy); return locationOnScreen; } else { Point location = c.getLocation(); dx += location.x; dy += location.y; } } return null; } @NotNull public static Window getActiveWindow() { Window[] windows = Window.getWindows(); for (Window each : windows) { if (each.isVisible() && each.isActive()) return each; } return JOptionPane.getRootFrame(); } public static void setAutoRequestFocus (final Window onWindow, final boolean set){ if (SystemInfo.isMac) return; if (SystemInfo.isJavaVersionAtLeast("1.7")) { try { Method setAutoRequestFocusMethod = onWindow.getClass().getMethod("setAutoRequestFocus",new Class [] {boolean.class}); setAutoRequestFocusMethod.invoke(onWindow, set); } catch (NoSuchMethodException e) { LOG.debug(e); } catch (InvocationTargetException e) { LOG.debug(e); } catch (IllegalAccessException e) { LOG.debug(e); } } } //May have no usages but it's useful in runtime (Debugger "watches", some logging etc.) public static String getDebugText(Component c) { StringBuilder builder = new StringBuilder(); getAllTextsRecursivelyImpl(c, builder); return builder.toString(); } private static void getAllTextsRecursivelyImpl(Component component, StringBuilder builder) { String candidate = ""; int limit = builder.length() > 60 ? 20 : 40; if (component instanceof JLabel) candidate = ((JLabel)component).getText(); if (component instanceof JTextComponent) candidate = ((JTextComponent)component).getText(); if (component instanceof AbstractButton) candidate = ((AbstractButton)component).getText(); if (StringUtil.isNotEmpty(candidate)) { builder.append(candidate.length() > limit ? (candidate.substring(0, limit - 3) + "...") : candidate).append('|'); } if (component instanceof Container) { Component[] components = ((Container)component).getComponents(); for (Component child : components) { getAllTextsRecursivelyImpl(child, builder); } } } public static boolean isAncestor(@NotNull Component ancestor, @Nullable Component descendant) { while (descendant != null) { if (descendant == ancestor) { return true; } descendant = descendant.getParent(); } return false; } public static void addUndoRedoActions(JTextComponent textComponent) { final UndoManager undoManager = new UndoManager(); textComponent.getDocument().addUndoableEditListener(undoManager); textComponent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, SystemInfo.isMac? InputEvent.META_MASK : InputEvent.CTRL_MASK), "undoKeystroke"); textComponent.getActionMap().put("undoKeystroke", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (undoManager.canUndo()) { undoManager.undo(); } } }); textComponent.getInputMap().put( KeyStroke.getKeyStroke(KeyEvent.VK_Z, (SystemInfo.isMac? InputEvent.META_MASK : InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK), "redoKeystroke"); textComponent.getActionMap().put("redoKeystroke", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (undoManager.canRedo()) { undoManager.redo(); } } }); } public static void playSoundFromResource(final String resourceName) { final Class callerClass = ReflectionUtil.getGrandCallerClass(); if (callerClass == null) return; playSoundFromStream(new Factory<InputStream>() { @Override public InputStream create() { return callerClass.getResourceAsStream(resourceName); } }); } public static void playSoundFromStream(final Factory<InputStream> streamProducer) { new Thread(new Runnable() { // The wrapper thread is unnecessary, unless it blocks on the // Clip finishing; see comments. public void run() { try { Clip clip = AudioSystem.getClip(); InputStream stream = streamProducer.create(); if (!stream.markSupported()) stream = new BufferedInputStream(stream); AudioInputStream inputStream = AudioSystem.getAudioInputStream(stream); clip.open(inputStream); clip.start(); } catch (Exception ignore) { LOG.info(ignore); } } }).start(); } }
Use Tahoma in HTMLEditorKit on Windows
platform/util/src/com/intellij/util/ui/UIUtil.java
Use Tahoma in HTMLEditorKit on Windows
<ide><path>latform/util/src/com/intellij/util/ui/UIUtil.java <ide> <ide> public static HTMLEditorKit getHTMLEditorKit() { <ide> Font font = getLabelFont(); <del> @NonNls String family = font != null ? font.getFamily() : "Tahoma"; <add> @NonNls String family = !SystemInfo.isWindows && font != null ? font.getFamily() : "Tahoma"; <ide> int size = font != null ? font.getSize() : 11; <ide> <ide> final String customCss = String.format("body, div, p { font-family: %s; font-size: %s; } p { margin-top: 0; }", family, size);
Java
epl-1.0
5e40917f03a2d3e5e14adbcd9824ea78dc8b92cb
0
rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt
/******************************************************************************* * Copyright (c) 2004, 2007 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.chart.ui.swt.wizard; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Vector; import java.util.Map.Entry; import org.eclipse.birt.chart.exception.ChartException; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.ChartWithoutAxes; import org.eclipse.birt.chart.model.attribute.AxisType; import org.eclipse.birt.chart.model.attribute.ChartDimension; import org.eclipse.birt.chart.model.attribute.DataType; import org.eclipse.birt.chart.model.attribute.Orientation; import org.eclipse.birt.chart.model.component.Axis; import org.eclipse.birt.chart.model.component.MarkerLine; import org.eclipse.birt.chart.model.component.MarkerRange; import org.eclipse.birt.chart.model.component.Series; import org.eclipse.birt.chart.model.data.BaseSampleData; import org.eclipse.birt.chart.model.data.OrthogonalSampleData; import org.eclipse.birt.chart.model.data.Query; import org.eclipse.birt.chart.model.data.SeriesDefinition; import org.eclipse.birt.chart.model.type.StockSeries; import org.eclipse.birt.chart.ui.extension.i18n.Messages; import org.eclipse.birt.chart.ui.swt.ChartPreviewPainter; import org.eclipse.birt.chart.ui.swt.interfaces.IChartPreviewPainter; import org.eclipse.birt.chart.ui.swt.interfaces.IChartSubType; import org.eclipse.birt.chart.ui.swt.interfaces.IChartType; import org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider; import org.eclipse.birt.chart.ui.swt.interfaces.ISeriesUIProvider; import org.eclipse.birt.chart.ui.swt.interfaces.ITaskChangeListener; import org.eclipse.birt.chart.ui.swt.interfaces.ITaskPreviewable; import org.eclipse.birt.chart.ui.util.ChartCacheManager; import org.eclipse.birt.chart.ui.util.ChartHelpContextIds; import org.eclipse.birt.chart.ui.util.ChartUIConstants; import org.eclipse.birt.chart.ui.util.ChartUIUtil; import org.eclipse.birt.chart.ui.util.UIHelper; import org.eclipse.birt.chart.util.ChartUtil; import org.eclipse.birt.core.ui.frameworks.taskwizard.SimpleTask; import org.eclipse.birt.core.ui.frameworks.taskwizard.WizardBase; import org.eclipse.birt.core.ui.frameworks.taskwizard.interfaces.IWizardContext; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.TreeIterator; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.util.EContentAdapter; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; /** * TaskSelectType */ public class TaskSelectType extends SimpleTask implements SelectionListener, ITaskChangeListener, ITaskPreviewable { /** * * TaskSelectTypeUIDescriptor is used to create UI in misc area according to * the order of index */ public abstract class TaskSelectTypeUIDescriptor { private boolean bVisible = true; public boolean isVisible( ) { return bVisible; } public void setVisible( boolean bVisible ) { this.bVisible = bVisible; } public abstract int getIndex( ); public abstract void createControl( Composite parent ); } private Chart chartModel = null; private ChartAdapter adapter = null; private Composite cmpType = null; private Composite cmpMisc = null; private Composite cmpRight = null; private Composite cmpLeft = null; private Composite cmpTypeButtons = null; private Composite cmpSubTypes = null; protected IChartPreviewPainter previewPainter = null; private Canvas previewCanvas = null; private LinkedHashMap<String, IChartType> htTypes = null; private RowData rowData = new RowData( 80, 80 ); protected String sSubType = null; protected String sType = null; private String sOldType = null; // Stored in IChartType protected String sDimension = null; private Table table = null; private Vector<String> vSubTypeNames = null; protected Orientation orientation = null; private Label lblOrientation = null; private Button cbOrientation = null; private Label lblMultipleY = null; protected Combo cbMultipleY = null; private Label lblSeriesType = null; private Combo cbSeriesType = null; private Combo cbDimension = null; private SashForm foSashForm; protected int pageMargin = 80; private static final String LEADING_BLANKS = " "; //$NON-NLS-1$ private static Hashtable<String, Series> htSeriesNames = null; private static String[] outputFormats, outputDisplayNames; static { try { outputFormats = ChartUtil.getSupportedOutputFormats( ); outputDisplayNames = ChartUtil.getSupportedOutputDisplayNames( ); } catch ( ChartException e ) { WizardBase.displayException( e ); outputFormats = new String[0]; outputDisplayNames = new String[0]; } } protected List<TaskSelectTypeUIDescriptor> lstDescriptor = new LinkedList<TaskSelectTypeUIDescriptor>( ); public TaskSelectType( ) { super( Messages.getString( "TaskSelectType.TaskExp" ) ); //$NON-NLS-1$ setDescription( Messages.getString( "TaskSelectType.Task.Description" ) ); //$NON-NLS-1$ if ( chartModel != null ) { sType = chartModel.getType( ); sOldType = sType; sSubType = chartModel.getSubType( ); sDimension = translateDimensionString( chartModel.getDimension( ) .getName( ) ); if ( chartModel instanceof ChartWithAxes ) { orientation = ( (ChartWithAxes) chartModel ).getOrientation( ); } } htTypes = new LinkedHashMap<String, IChartType>( ); } public void createControl( Composite parent ) { if ( topControl == null || topControl.isDisposed( ) ) { topControl = new Composite( parent, SWT.NONE ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginWidth = pageMargin; topControl.setLayout( gridLayout ); topControl.setLayoutData( new GridData( GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL ) ); if ( context != null ) { chartModel = ( (ChartWizardContext) context ).getModel( ); } placeComponents( ); updateAdapters( ); } // Update dimension combo and related sub-types in case of axes changed // outside if ( ( (ChartWizardContext) getContext( ) ).isMoreAxesSupported( ) ) { updateDimensionCombo( sType ); createAndDisplayTypesSheet( sType ); setDefaultSubtypeSelection( ); cmpMisc.layout( ); } doPreview( ); bindHelp( ); } protected void bindHelp( ) { ChartUIUtil.bindHelp( getControl( ), ChartHelpContextIds.TASK_SELECT_TYPE ); } private void placeComponents( ) { foSashForm = new SashForm( topControl, SWT.VERTICAL ); { GridLayout layout = new GridLayout( ); foSashForm.setLayout( layout ); GridData gridData = new GridData( GridData.FILL_BOTH ); // TODO verify Bug 194391 in Linux gridData.heightHint = 570; foSashForm.setLayoutData( gridData ); } createPreviewArea( ); createTypeArea( ); setDefaultTypeSelection( ); refreshChart( ); populateSeriesTypesList( ); } private void createPreviewArea( ) { Composite cmpPreview = new Composite( foSashForm, SWT.NONE ); cmpPreview.setLayout( new GridLayout( ) ); GridData gridData = new GridData( GridData.FILL_BOTH ); gridData.horizontalSpan = 2; gridData.heightHint = 270; cmpPreview.setLayoutData( gridData ); Label label = new Label( cmpPreview, SWT.NONE ); { label.setText( Messages.getString( "TaskSelectType.Label.Preview" ) ); //$NON-NLS-1$ label.setFont( JFaceResources.getBannerFont( ) ); } previewCanvas = new Canvas( cmpPreview, SWT.BORDER ); previewCanvas.setLayoutData( new GridData( GridData.FILL_BOTH ) ); previewCanvas.setBackground( Display.getDefault( ) .getSystemColor( SWT.COLOR_WIDGET_BACKGROUND ) ); previewPainter = createPreviewPainter( ); } private void createTypeArea( ) { ScrolledComposite sc = new ScrolledComposite( foSashForm, SWT.V_SCROLL ); { GridLayout layout = new GridLayout( ); sc.setLayout( layout ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); sc.setLayoutData( gridData ); sc.setExpandHorizontal( true ); sc.setExpandVertical( true ); } cmpType = new Composite( sc, SWT.NONE ); cmpType.setLayout( new GridLayout( 2, false ) ); cmpType.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); sc.setContent( cmpType ); createTypeTable( ); addChartTypes( ); createDetails( ); Point size = cmpType.computeSize( SWT.DEFAULT, SWT.DEFAULT ); sc.setMinSize( size ); } private void createDetails( ) { cmpRight = new Composite( cmpType, SWT.NONE ); cmpRight.setLayout( new GridLayout( ) ); cmpRight.setLayoutData( new GridData( GridData.FILL_BOTH ) ); createComposite( new Vector<IChartSubType>( ) ); createMiscArea( ); } private void createMiscArea( ) { cmpMisc = new Composite( cmpRight, SWT.NONE ); cmpMisc.setLayout( new GridLayout( 4, false ) ); cmpMisc.setLayoutData( new GridData( GridData.FILL_BOTH ) ); addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) { public int getIndex( ) { return 10; } public void createControl( Composite parent ) { Label lblDimension = new Label( parent, SWT.WRAP ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); lblDimension.setLayoutData( gd ); lblDimension.setText( Messages.getString( "TaskSelectType.Label.Dimension" ) ); //$NON-NLS-1$ } // Add the ComboBox for Dimensions cbDimension = new Combo( parent, SWT.DROP_DOWN | SWT.READ_ONLY ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); cbDimension.setLayoutData( gd ); cbDimension.addSelectionListener( TaskSelectType.this ); } } } ); addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) { public int getIndex( ) { return 30; } public void createControl( Composite parent ) { lblMultipleY = new Label( parent, SWT.WRAP ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); lblMultipleY.setLayoutData( gd ); lblMultipleY.setText( Messages.getString( "TaskSelectType.Label.MultipleYAxis" ) ); //$NON-NLS-1$ } // Add the checkBox for Multiple Y Axis cbMultipleY = new Combo( parent, SWT.DROP_DOWN | SWT.READ_ONLY ); { cbMultipleY.setItems( new String[]{ Messages.getString( "TaskSelectType.Selection.None" ), //$NON-NLS-1$ Messages.getString( "TaskSelectType.Selection.SecondaryAxis" ), //$NON-NLS-1$ Messages.getString( "TaskSelectType.Selection.MoreAxes" ) //$NON-NLS-1$ } ); GridData gd = new GridData( GridData.FILL_HORIZONTAL ); cbMultipleY.setLayoutData( gd ); cbMultipleY.addSelectionListener( TaskSelectType.this ); int axisNum = ChartUIUtil.getOrthogonalAxisNumber( chartModel ); selectMultipleAxis( axisNum ); } } } ); addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) { public int getIndex( ) { return 40; } public void createControl( Composite parent ) { lblSeriesType = new Label( parent, SWT.WRAP ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalIndent = 10; lblSeriesType.setLayoutData( gd ); lblSeriesType.setText( Messages.getString( "TaskSelectType.Label.SeriesType" ) ); //$NON-NLS-1$ lblSeriesType.setEnabled( false ); } // Add the ComboBox for Series Type cbSeriesType = new Combo( parent, SWT.DROP_DOWN | SWT.READ_ONLY ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); cbSeriesType.setLayoutData( gd ); cbSeriesType.setEnabled( false ); cbSeriesType.addSelectionListener( TaskSelectType.this ); } } } ); addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) { public int getIndex( ) { return 50; } public void createControl( Composite parent ) { lblOrientation = new Label( parent, SWT.WRAP ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); lblOrientation.setLayoutData( gd ); lblOrientation.setText( Messages.getString( "TaskSelectType.Label.Oritention" ) ); //$NON-NLS-1$ } // Add the CheckBox for Orientation cbOrientation = new Button( parent, SWT.CHECK ); { cbOrientation.setText( Messages.getString( "TaskSelectType.Label.FlipAxis" ) ); //$NON-NLS-1$ GridData gd = new GridData( ); cbOrientation.setLayoutData( gd ); cbOrientation.addSelectionListener( TaskSelectType.this ); } if ( TaskSelectType.this.orientation == Orientation.HORIZONTAL_LITERAL ) { cbOrientation.setSelection( true ); } else { cbOrientation.setSelection( false ); } } } ); addOptionalUIDescriptor( ); createUIDescriptors( cmpMisc ); } /** * This method initializes table * */ private void createTypeTable( ) { cmpLeft = new Composite( cmpType, SWT.NONE ); cmpLeft.setLayout( new GridLayout( ) ); cmpLeft.setLayoutData( new GridData( GridData.FILL_BOTH ) ); Label lblTypes = new Label( cmpLeft, SWT.WRAP ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); lblTypes.setLayoutData( gd ); lblTypes.setText( Messages.getString( "TaskSelectType.Label.SelectChartType" ) ); //$NON-NLS-1$ } table = new Table( cmpLeft, SWT.BORDER ); { GridData gd = new GridData( GridData.FILL_BOTH ); table.setLayoutData( gd ); table.setToolTipText( Messages.getString( "TaskSelectType.Label.ChartTypes" ) ); //$NON-NLS-1$ table.addSelectionListener( this ); } } /** * */ private void addChartTypes( ) { populateTypesTable( ); updateUI( ); } /** * */ private void populateTypesTable( ) { htTypes.clear( ); Collection<IChartType> cTypes = ChartUIExtensionsImpl.instance( ) .getUIChartTypeExtensions( getContext( ).getClass( ) .getSimpleName( ) ); Iterator<IChartType> iterTypes = cTypes.iterator( ); while ( iterTypes.hasNext( ) ) { IChartType type = iterTypes.next( ); // Only support enabled chart types if ( ( (ChartWizardContext) context ).isEnabled( type.getName( ) ) ) { htTypes.put( type.getName( ), type ); } } } private void updateUI( ) { Iterator<String> iter = htTypes.keySet( ).iterator( ); while ( iter.hasNext( ) ) { String sTypeTmp = iter.next( ); TableItem tItem = new TableItem( table, SWT.NONE ); tItem.setText( LEADING_BLANKS + ( htTypes.get( sTypeTmp ) ).getDisplayName( ) ); tItem.setData( ( htTypes.get( sTypeTmp ) ).getName( ) ); tItem.setImage( ( htTypes.get( sTypeTmp ) ).getImage( ) ); } } protected Chart getChartModel( ) { return chartModel; } /** * This method initializes cmpSubTypes * */ private void createComposite( Vector<IChartSubType> vSubTypes ) { Label lblSubtypes = new Label( cmpRight, SWT.NO_FOCUS ); { lblSubtypes.setText( Messages.getString( "TaskSelectType.Label.SelectSubtype" ) ); //$NON-NLS-1$ GridData gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalIndent = 5; lblSubtypes.setLayoutData( gd ); } GridData gdTypes = new GridData( GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL ); cmpSubTypes = new Composite( cmpRight, SWT.NONE ); createGroups( vSubTypes ); cmpSubTypes.setLayoutData( gdTypes ); cmpSubTypes.setToolTipText( Messages.getString( "TaskSelectType.Label.ChartSubtypes" ) ); //$NON-NLS-1$ cmpSubTypes.setLayout( new GridLayout( ) ); cmpSubTypes.setVisible( true ); } /** * This method initializes cmpTypeButtons * */ private void createGroups( Vector<IChartSubType> vSubTypes ) { vSubTypeNames = new Vector<String>( ); if ( cmpTypeButtons != null && !cmpTypeButtons.isDisposed( ) ) { // Remove existing buttons cmpTypeButtons.dispose( ); } cmpTypeButtons = new Composite( cmpSubTypes, SWT.NONE ); RowLayout rowLayout = new RowLayout( ); rowLayout.marginTop = 0; rowLayout.marginLeft = 0; rowLayout.marginBottom = 12; rowLayout.marginRight = 12; rowLayout.spacing = 4; cmpTypeButtons.setLayout( rowLayout ); // Add new buttons for this type for ( int iC = 0; iC < vSubTypes.size( ); iC++ ) { IChartSubType subType = vSubTypes.get( iC ); vSubTypeNames.add( subType.getName( ) ); Button btnType = new Button( cmpTypeButtons, SWT.TOGGLE ); btnType.setData( subType.getName( ) ); btnType.setImage( subType.getImage( ) ); btnType.setLayoutData( rowData ); btnType.addSelectionListener( this ); btnType.setToolTipText( subType.getDescription( ) ); btnType.getImage( ).setBackground( btnType.getBackground( ) ); btnType.setVisible( true ); cmpTypeButtons.layout( true ); } cmpTypeButtons.setLayoutData( new GridData( GridData.FILL_BOTH ) ); cmpSubTypes.layout( true ); } private void populateSeriesTypes( Collection<IChartType> allChartType, Series series, Orientation orientation ) { Iterator<IChartType> iterTypes = allChartType.iterator( ); while ( iterTypes.hasNext( ) ) { IChartType type = iterTypes.next( ); Series newSeries = type.getSeries( ); if ( htSeriesNames == null ) { htSeriesNames = new Hashtable<String, Series>( 20 ); } if ( type.canCombine( ) ) { // Horizontal Stock is not supported and can't be mixed with // other charts if ( !( newSeries instanceof StockSeries ) || ( orientation.getValue( ) == Orientation.VERTICAL ) ) { String sDisplayName = newSeries.getDisplayName( ); htSeriesNames.put( sDisplayName, newSeries ); cbSeriesType.add( sDisplayName ); } if ( type.getName( ).equals( chartModel.getType( ) ) ) { cbSeriesType.select( cbSeriesType.getItemCount( ) - 1 ); } } } } /* * This method translates the dimension string from the model to that * maintained by the UI (for readability). */ private String translateDimensionString( String sDimensionValue ) { String dimensionName = ""; //$NON-NLS-1$ if ( sDimensionValue.equals( ChartDimension.TWO_DIMENSIONAL_LITERAL.getName( ) ) ) { dimensionName = IChartType.TWO_DIMENSION_TYPE; } else if ( sDimensionValue.equals( ChartDimension.TWO_DIMENSIONAL_WITH_DEPTH_LITERAL.getName( ) ) ) { dimensionName = IChartType.TWO_DIMENSION_WITH_DEPTH_TYPE; } else if ( sDimensionValue.equals( ChartDimension.THREE_DIMENSIONAL_LITERAL.getName( ) ) ) { dimensionName = IChartType.THREE_DIMENSION_TYPE; } return dimensionName; } public void widgetDefaultSelected( SelectionEvent e ) { } public void widgetSelected( SelectionEvent e ) { // Indicates whether need to update chart model boolean needUpdateModel = false; Object oSelected = e.getSource( ); if ( oSelected.getClass( ).equals( Button.class ) ) { needUpdateModel = true; if ( oSelected.equals( cbOrientation ) ) { if ( cbOrientation.getSelection( ) ) { orientation = Orientation.HORIZONTAL_LITERAL; } else { orientation = Orientation.VERTICAL_LITERAL; } createAndDisplayTypesSheet( sType ); setDefaultSubtypeSelection( ); populateSeriesTypesList( ); ChartCacheManager.getInstance( ).cacheOrientation( sType, orientation ); } else { Button btn = (Button) e.getSource( ); if ( btn.getSelection( ) ) { if ( this.sSubType != null && !getSubtypeFromButton( btn ).equals( sSubType ) ) { int iTypeIndex = vSubTypeNames.indexOf( sSubType ); if ( iTypeIndex >= 0 ) { ( (Button) cmpTypeButtons.getChildren( )[iTypeIndex] ).setSelection( false ); cmpTypeButtons.redraw( ); } } // Cache label position for stacked or non-stacked case. ChartUIUtil.saveLabelPositionIntoCache( getSeriesDefinitionForProcessing( ) ); sSubType = getSubtypeFromButton( btn ); ChartCacheManager.getInstance( ).cacheSubtype( sType, sSubType ); } else { if ( this.sSubType != null && getSubtypeFromButton( btn ).equals( sSubType ) ) { // Clicking on the same button should not cause it to be // unselected btn.setSelection( true ); // Disable the statement to avoid when un-check all // stacked attributes of series on format tab, the // default chart is painted as side-by-side, but it // can't select stacked button to change chart type to // stacked in chart type tab. // needUpdateModel = false; } } } } else if ( oSelected.getClass( ).equals( Table.class ) ) { sType = ( (String) ( (TableItem) e.item ).getData( ) ).trim( ); if ( !sOldType.equals( sType ) ) { sOldType = sType; // Get orientation for non-xtab case. In xtab, orientation won't // be changed if ( !getDataServiceProvider( ).checkState( IDataServiceProvider.PART_CHART ) ) { // Get the cached orientation if ( chartModel != null && chartModel instanceof ChartWithAxes ) { Orientation lastOrientation = ChartCacheManager.getInstance( ) .findOrientation( sType ); if ( lastOrientation != null && this.orientation != lastOrientation ) { this.orientation = lastOrientation; this.rotateAxisTitle( (ChartWithAxes) chartModel ); } if ( lastOrientation == null ) { this.orientation = htTypes.get( sType ) .getDefaultOrientation( ); } } } if ( chartModel != null && chartModel instanceof ChartWithAxes && ChartCacheManager.getInstance( ) .findCategory( sType ) != null ) { boolean bCategory = ChartCacheManager.getInstance( ) .findCategory( sType ) .booleanValue( ); ( (Axis) ( (ChartWithAxes) chartModel ).getAxes( ).get( 0 ) ).setCategoryAxis( bCategory ); } sSubType = null; createAndDisplayTypesSheet( sType ); setDefaultSubtypeSelection( ); cmpMisc.layout( ); needUpdateModel = true; } } else if ( oSelected.equals( cbMultipleY ) ) { needUpdateModel = true; lblSeriesType.setEnabled( isTwoAxesEnabled( ) ); Axis xAxis = ( (Axis) ( (ChartWithAxes) chartModel ).getAxes( ) .get( 0 ) ); ( (ChartWizardContext) getContext( ) ).setMoreAxesSupported( cbMultipleY.getSelectionIndex( ) == 2 ); if ( chartModel instanceof ChartWithoutAxes ) { throw new IllegalArgumentException( Messages.getString( "TaskSelectType.Exception.CannotSupportAxes" ) ); //$NON-NLS-1$ } // Prevent notifications rendering preview ChartAdapter.beginIgnoreNotifications( ); int iAxisNumber = ChartUIUtil.getOrthogonalAxisNumber( chartModel ); if ( cbMultipleY.getSelectionIndex( ) == 0 ) { // Remove series type cache ChartCacheManager.getInstance( ).cacheSeriesType( null ); // Keeps one axis if ( iAxisNumber > 1 ) { ChartUIUtil.removeLastAxes( (ChartWithAxes) chartModel, iAxisNumber - 1 ); } } else if ( cbMultipleY.getSelectionIndex( ) == 1 ) { // Keeps two axes if ( iAxisNumber == 1 ) { ChartUIUtil.addAxis( (ChartWithAxes) chartModel ); } else if ( iAxisNumber > 2 ) { ChartUIUtil.removeLastAxes( (ChartWithAxes) chartModel, iAxisNumber - 2 ); } } ChartAdapter.endIgnoreNotifications( ); if ( xAxis.getAssociatedAxes( ).size( ) > 1 ) { String lastSeriesType = ChartCacheManager.getInstance( ) .findSeriesType( ); if ( lastSeriesType != null ) { cbSeriesType.setText( lastSeriesType ); } else { Axis overlayAxis = (Axis) xAxis.getAssociatedAxes( ) .get( 1 ); String sDisplayName = ( (SeriesDefinition) overlayAxis.getSeriesDefinitions( ) .get( 0 ) ).getDesignTimeSeries( ).getDisplayName( ); cbSeriesType.setText( sDisplayName ); } changeOverlaySeriesType( ); } cbSeriesType.setEnabled( isTwoAxesEnabled( ) ); // Update dimension combo and related sub-types if ( updateDimensionCombo( sType ) ) { createAndDisplayTypesSheet( sType ); setDefaultSubtypeSelection( ); } // Pack to display enough space for combo cmpMisc.layout( ); } else if ( oSelected.equals( cbDimension ) ) { String newDimension = cbDimension.getItem( cbDimension.getSelectionIndex( ) ); if ( !newDimension.equals( sDimension ) ) { sDimension = newDimension; ChartCacheManager.getInstance( ).cacheDimension( sType, sDimension ); createAndDisplayTypesSheet( sType ); setDefaultSubtypeSelection( ); needUpdateModel = true; } } else if ( oSelected.equals( cbSeriesType ) ) { // if ( !cbSeriesType.getText( ).equals( oldSeriesName ) ) // { needUpdateModel = true; changeOverlaySeriesType( ); // } } // Following operations need new model if ( needUpdateModel ) { // Update apply button ChartAdapter.notifyUpdateApply( ); // Update chart model refreshChart( ); if ( oSelected.getClass( ).equals( Table.class ) ) { // Ensure populate list after chart model generated populateSeriesTypesList( ); } else if ( oSelected.equals( cbOrientation ) ) { // Auto rotates Axis title when transposing if ( chartModel instanceof ChartWithAxes ) { rotateAxisTitle( (ChartWithAxes) chartModel ); } } // Preview after all model changes doPreview( ); } } /** * Updates the dimension combo according to chart type and axes number * * @param sSelectedType * Chart type * @return whether the dimension is changed after updating */ private boolean updateDimensionCombo( String sSelectedType ) { // Remember last selection boolean isOldExist = false; // Update valid dimension list IChartType chartType = htTypes.get( sSelectedType ); String[] dimensionArray = chartType.getSupportedDimensions( ); int axesNum = ChartUIUtil.getOrthogonalAxisNumber( chartModel ); if ( sDimension == null ) { // Initialize dimension sDimension = chartType.getDefaultDimension( ); isOldExist = true; } cbDimension.removeAll( ); for ( int i = 0; i < dimensionArray.length; i++ ) { boolean isSupported = chartType.isDimensionSupported( dimensionArray[i], (ChartWizardContext) context, axesNum, 0 ); if ( isSupported ) { cbDimension.add( dimensionArray[i] ); } if ( !isOldExist && sDimension.equals( dimensionArray[i] ) ) { isOldExist = isSupported; } } String cache = ChartCacheManager.getInstance( ) .getDimension( sSelectedType ); if ( cache != null ) { sDimension = cache; isOldExist = true; } // Select the previous selection or the default if ( !isOldExist ) { sDimension = chartType.getDefaultDimension( ); } cbDimension.setText( sDimension ); return !isOldExist; } private boolean isTwoAxesEnabled( ) { return cbMultipleY.getSelectionIndex( ) == 1; } private void updateAdapters( ) { if ( container instanceof ChartWizard ) { // Refresh all adapters EContentAdapter adapter = ( (ChartWizard) container ).getAdapter( ); chartModel.eAdapters( ).remove( adapter ); TreeIterator<EObject> iterator = chartModel.eAllContents( ); while ( iterator.hasNext( ) ) { EObject oModel = iterator.next( ); oModel.eAdapters( ).remove( adapter ); } chartModel.eAdapters( ).add( adapter ); } else { // For extension case, create an adapter and add change listener EList<Adapter> adapters = chartModel.eAdapters( ); if ( adapters.isEmpty( ) ) { // Get the previous adapter if existent if ( adapter == null ) { adapter = new ChartAdapter( container ); adapter.addListener( this ); } adapters.add( adapter ); } else { if ( adapters.get( 0 ) instanceof ChartAdapter ) { ( (ChartAdapter) adapters.get( 0 ) ).addListener( this ); } } } } private boolean is3D( ) { return IChartType.THREE_DIMENSION_TYPE.equals( sDimension ); } private void changeOverlaySeriesType( ) { // cache the second axis series type if it can be combined. if ( getCurrentChartType( ).canCombine( ) ) { ChartCacheManager.getInstance( ) .cacheSeriesType( cbSeriesType.getText( ) ); } boolean bException = false; try { // CHANGE ALL OVERLAY SERIES TO NEW SELECTED TYPE Axis XAxis = (Axis) ( (ChartWithAxes) chartModel ).getAxes( ) .get( 0 ); int iSeriesDefinitionIndex = 0 + ( (Axis) XAxis.getAssociatedAxes( ) .get( 0 ) ).getSeriesDefinitions( ).size( ); // SINCE // THIS IS FOR THE ORTHOGONAL OVERLAY SERIES DEFINITION int iOverlaySeriesCount = ( (Axis) XAxis.getAssociatedAxes( ) .get( 1 ) ).getSeriesDefinitions( ).size( ); // DISABLE NOTIFICATIONS WHILE MODEL UPDATE TAKES PLACE ChartAdapter.beginIgnoreNotifications( ); for ( int i = 0; i < iOverlaySeriesCount; i++ ) { Series lastSeries = ( (SeriesDefinition) ( (Axis) XAxis.getAssociatedAxes( ) .get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getDesignTimeSeries( ); if ( !lastSeries.getDisplayName( ) .equals( cbSeriesType.getText( ) ) ) { Series newSeries = (Series) EcoreUtil.copy( htSeriesNames.get( cbSeriesType.getText( ) ) ); newSeries.translateFrom( lastSeries, iSeriesDefinitionIndex, chartModel ); // ADD THE MODEL ADAPTERS TO THE NEW SERIES newSeries.eAdapters( ).addAll( chartModel.eAdapters( ) ); // UPDATE THE SERIES DEFINITION WITH THE SERIES INSTANCE ( (SeriesDefinition) ( (Axis) XAxis.getAssociatedAxes( ) .get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getSeries( ) .clear( ); ( (SeriesDefinition) ( (Axis) XAxis.getAssociatedAxes( ) .get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getSeries( ) .add( newSeries ); ChartUIUtil.setSeriesName( chartModel ); } } } catch ( Exception e ) { bException = true; WizardBase.showException( e.getLocalizedMessage( ) ); } finally { // ENABLE NOTIFICATIONS IN CASE EXCEPTIONS OCCUR ChartAdapter.endIgnoreNotifications( ); } if ( !bException ) { WizardBase.removeException( ); } } private void populateSeriesTypesList( ) { if ( cbSeriesType == null ) { return; } // Populate Series Types List cbSeriesType.removeAll( ); Series series = getSeriesDefinitionForProcessing( ).getDesignTimeSeries( ); if ( getCurrentChartType( ).canCombine( ) ) { populateSeriesTypes( ChartUIExtensionsImpl.instance( ) .getUIChartTypeExtensions( getContext( ).getClass( ) .getSimpleName( ) ), series, this.orientation ); } else { String seriesName = series.getDisplayName( ); cbSeriesType.add( seriesName ); cbSeriesType.select( 0 ); } // Select the appropriate current series type if overlay series exists if ( this.chartModel instanceof ChartWithAxes ) { Axis xAxis = ( (Axis) ( (ChartWithAxes) chartModel ).getAxes( ) .get( 0 ) ); if ( xAxis.getAssociatedAxes( ).size( ) > 1 ) { // Set series name from cache or model String lastType = ChartCacheManager.getInstance( ) .findSeriesType( ); Axis overlayAxis = (Axis) xAxis.getAssociatedAxes( ).get( 1 ); if ( !overlayAxis.getSeriesDefinitions( ).isEmpty( ) ) { Series oseries = ( (SeriesDefinition) overlayAxis.getSeriesDefinitions( ) .get( 0 ) ).getDesignTimeSeries( ); String sDisplayName = oseries.getDisplayName( ); if ( lastType != null ) { cbSeriesType.setText( lastType ); } else { cbSeriesType.setText( sDisplayName ); } String seriesName = oseries.getSeriesIdentifier( ) .toString( ); if ( seriesName.trim( ).length( ) != 0 ) { Iterator<Entry<String, Series>> itr = htSeriesNames.entrySet( ) .iterator( ); while ( itr.hasNext( ) ) { Entry<String, Series> entry = itr.next( ); entry.getValue( ).setSeriesIdentifier( seriesName ); } } } // Update overlay series changeOverlaySeriesType( ); } } } /** * This method populates the subtype panel (creating its components if * necessary). It gets called when the type selection changes or when the * dimension selection changes (since not all sub types are supported for * all dimension selections). * * @param sSelectedType * Type from Type List */ private void createAndDisplayTypesSheet( String sSelectedType ) { IChartType chartType = htTypes.get( sSelectedType ); if ( cbOrientation != null ) { lblOrientation.setEnabled( chartType.supportsTransposition( ) && !is3D( ) ); cbOrientation.setEnabled( chartType.supportsTransposition( ) && !is3D( ) ); } // Update dimension updateDimensionCombo( sSelectedType ); if ( this.sDimension == null ) { this.sDimension = chartType.getDefaultDimension( ); } if ( this.orientation == null ) { this.orientation = chartType.getDefaultOrientation( ); } // Show the subtypes for the selected type based on current selections // of dimension and orientation Vector<IChartSubType> vSubTypes = new Vector<IChartSubType>( chartType.getChartSubtypes( sDimension, orientation ) ); if ( vSubTypes.size( ) == 0 ) { vSubTypes = new Vector<IChartSubType>( chartType.getChartSubtypes( chartType.getDefaultDimension( ), chartType.getDefaultOrientation( ) ) ); this.sDimension = chartType.getDefaultDimension( ); this.orientation = chartType.getDefaultOrientation( ); } // If two orientations are not supported, to get the default. if ( cbOrientation == null || !cbOrientation.isEnabled( ) ) { this.orientation = chartType.getDefaultOrientation( ); } // Cache the orientation for each chart type. ChartCacheManager.getInstance( ).cacheOrientation( sType, orientation ); if ( chartModel == null ) { ChartCacheManager.getInstance( ).cacheCategory( sType, true ); } else if ( chartModel instanceof ChartWithAxes ) { ChartCacheManager.getInstance( ) .cacheCategory( sType, ( (Axis) ( (ChartWithAxes) chartModel ).getAxes( ) .get( 0 ) ).isCategoryAxis( ) ); } // Update the UI with information for selected type createGroups( vSubTypes ); if ( this.cbOrientation != null ) { if ( this.orientation == Orientation.HORIZONTAL_LITERAL ) { this.cbOrientation.setSelection( true ); } else { this.cbOrientation.setSelection( false ); } } cmpRight.layout( ); } private void setDefaultSubtypeSelection( ) { if ( sSubType == null ) { // Try to get cached subtype sSubType = ChartCacheManager.getInstance( ).findSubtype( sType ); } if ( sSubType == null ) { // Get the default subtype ( (Button) cmpTypeButtons.getChildren( )[0] ).setSelection( true ); sSubType = getSubtypeFromButton( cmpTypeButtons.getChildren( )[0] ); ChartCacheManager.getInstance( ).cacheSubtype( sType, sSubType ); } else { Control[] buttons = cmpTypeButtons.getChildren( ); boolean bSelected = false; for ( int iB = 0; iB < buttons.length; iB++ ) { if ( getSubtypeFromButton( buttons[iB] ).equals( sSubType ) ) { ( (Button) buttons[iB] ).setSelection( true ); bSelected = true; break; } } // If specified subType is not found, select default if ( !bSelected ) { ( (Button) cmpTypeButtons.getChildren( )[0] ).setSelection( true ); sSubType = getSubtypeFromButton( cmpTypeButtons.getChildren( )[0] ); ChartCacheManager.getInstance( ).cacheSubtype( sType, sSubType ); } } cmpTypeButtons.redraw( ); } private void setDefaultTypeSelection( ) { if ( table.getItems( ).length > 0 ) { if ( sType == null ) { table.select( 0 ); sType = (String) ( table.getSelection( )[0] ).getData( ); } else { TableItem[] tiAll = table.getItems( ); for ( int iTI = 0; iTI < tiAll.length; iTI++ ) { if ( tiAll[iTI].getData( ).equals( sType ) ) { table.select( iTI ); break; } } } sOldType = sType; createAndDisplayTypesSheet( sType ); setDefaultSubtypeSelection( ); } } public void dispose( ) { super.dispose( ); lstDescriptor.clear( ); chartModel = null; adapter = null; if ( previewPainter != null ) { previewPainter.dispose( ); } previewPainter = null; sSubType = null; sType = null; sDimension = null; vSubTypeNames = null; orientation = null; } private void refreshChart( ) { // DISABLE PREVIEW REFRESH DURING CONVERSION ChartAdapter.beginIgnoreNotifications( ); IChartType chartType = htTypes.get( sType ); boolean bException = false; try { chartModel = chartType.getModel( sSubType, this.orientation, this.sDimension, this.chartModel ); updateAdapters( ); } catch ( Exception e ) { bException = true; WizardBase.showException( e.getLocalizedMessage( ) ); } if ( !bException ) { WizardBase.removeException( ); } // RE-ENABLE PREVIEW REFRESH ChartAdapter.endIgnoreNotifications( ); updateSelection( ); ( (ChartWizardContext) context ).setModel( chartModel ); ( (ChartWizardContext) context ).setChartType( chartType ); setContext( context ); } private SeriesDefinition getSeriesDefinitionForProcessing( ) { // TODO Attention: all index is 0 SeriesDefinition sd = null; if ( chartModel instanceof ChartWithAxes ) { sd = ( (SeriesDefinition) ( (Axis) ( (Axis) ( (ChartWithAxes) chartModel ).getAxes( ) .get( 0 ) ).getAssociatedAxes( ).get( 0 ) ).getSeriesDefinitions( ) .get( 0 ) ); } else if ( chartModel instanceof ChartWithoutAxes ) { sd = (SeriesDefinition) ( (SeriesDefinition) ( (ChartWithoutAxes) chartModel ).getSeriesDefinitions( ) .get( 0 ) ).getSeriesDefinitions( ).get( 0 ); } return sd; } /** * Updates UI selection according to Chart type * */ protected void updateSelection( ) { boolean bOutXtab = !getDataServiceProvider( ).checkState( IDataServiceProvider.PART_CHART ); if ( chartModel instanceof ChartWithAxes ) { if ( cbMultipleY != null ) { lblMultipleY.setEnabled( bOutXtab && !is3D( ) ); cbMultipleY.setEnabled( bOutXtab && !is3D( ) ); } if ( cbSeriesType != null ) { lblSeriesType.setEnabled( bOutXtab && isTwoAxesEnabled( ) ); cbSeriesType.setEnabled( bOutXtab && isTwoAxesEnabled( ) ); } } else { if ( cbMultipleY != null ) { cbMultipleY.select( 0 ); ( (ChartWizardContext) getContext( ) ).setMoreAxesSupported( false ); lblMultipleY.setEnabled( false ); cbMultipleY.setEnabled( false ); } if ( cbSeriesType != null ) { lblSeriesType.setEnabled( false ); cbSeriesType.setEnabled( false ); } } if ( cbOrientation != null ) { lblOrientation.setEnabled( bOutXtab && lblOrientation.isEnabled( ) ); cbOrientation.setEnabled( bOutXtab && cbOrientation.isEnabled( ) ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.frameworks.taskwizard.interfaces.ITask#getContext() */ public IWizardContext getContext( ) { ChartWizardContext context = (ChartWizardContext) super.getContext( ); context.setModel( this.chartModel ); return context; } /* * (non-Javadoc) * * @see org.eclipse.birt.frameworks.taskwizard.interfaces.ITask#setContext(org.eclipse.birt.frameworks.taskwizard.interfaces.IWizardContext) */ public void setContext( IWizardContext context ) { super.setContext( context ); this.chartModel = ( (ChartWizardContext) context ).getModel( ); if ( chartModel != null ) { this.sType = ( (ChartWizardContext) context ).getChartType( ) .getName( ); this.sSubType = chartModel.getSubType( ); this.sDimension = translateDimensionString( chartModel.getDimension( ) .getName( ) ); if ( chartModel instanceof ChartWithAxes ) { this.orientation = ( (ChartWithAxes) chartModel ).getOrientation( ); int iYAxesCount = ChartUIUtil.getOrthogonalAxisNumber( chartModel ); // IF THE UI HAS BEEN INITIALIZED...I.E. IF setContext() IS // CALLED AFTER getUI() if ( iYAxesCount > 1 && ( lblMultipleY != null && !lblMultipleY.isDisposed( ) ) ) { lblMultipleY.setEnabled( !is3D( ) ); cbMultipleY.setEnabled( !is3D( ) ); lblSeriesType.setEnabled( !is3D( ) && isTwoAxesEnabled( ) ); cbSeriesType.setEnabled( !is3D( ) && isTwoAxesEnabled( ) ); selectMultipleAxis( iYAxesCount ); // TODO: Update the series type based on series type for the // second Y axis } } } } private void selectMultipleAxis( int yAxisNum ) { if ( ( (ChartWizardContext) getContext( ) ).isMoreAxesSupported( ) ) { cbMultipleY.select( 2 ); } else { if ( yAxisNum > 2 ) { cbMultipleY.select( 2 ); ( (ChartWizardContext) getContext( ) ).setMoreAxesSupported( true ); } else { cbMultipleY.select( yAxisNum > 0 ? yAxisNum - 1 : 0 ); } } } public void changeTask( Notification notification ) { doPreview( ); } private void checkDataTypeForChartWithAxes( Chart cm ) { // To check the data type of base series and orthogonal series in chart // with axes List sdList = new ArrayList( ); sdList.addAll( ChartUIUtil.getBaseSeriesDefinitions( cm ) ); for ( int i = 0; i < sdList.size( ); i++ ) { SeriesDefinition sd = (SeriesDefinition) sdList.get( i ); Series series = sd.getDesignTimeSeries( ); checkDataTypeForBaseSeries( ChartUIUtil.getDataQuery( sd, 0 ), series ); } sdList.clear( ); sdList.addAll( ChartUIUtil.getAllOrthogonalSeriesDefinitions( cm ) ); for ( int i = 0; i < sdList.size( ); i++ ) { SeriesDefinition sd = (SeriesDefinition) sdList.get( i ); Series series = sd.getDesignTimeSeries( ); checkDataTypeForOrthoSeries( ChartUIUtil.getDataQuery( sd, 0 ), series ); } } protected IDataServiceProvider getDataServiceProvider( ) { return ( (ChartWizardContext) getContext( ) ).getDataServiceProvider( ); } private String getSubtypeFromButton( Control button ) { return (String) button.getData( ); } private void checkDataTypeForBaseSeries( Query query, Series series ) { checkDataTypeImpl( query, series, true ); } private void checkDataTypeForOrthoSeries( Query query, Series series ) { checkDataTypeImpl( query, series, false ); } private void checkDataTypeImpl( Query query, Series series, boolean isBaseSeries ) { String expression = query.getDefinition( ); Axis axis = null; for ( EObject o = query; o != null; ) { o = o.eContainer( ); if ( o instanceof Axis ) { axis = (Axis) o; break; } } Collection<ISeriesUIProvider> cRegisteredEntries = ChartUIExtensionsImpl.instance( ) .getSeriesUIComponents( getContext( ).getClass( ).getSimpleName( ) ); Iterator<ISeriesUIProvider> iterEntries = cRegisteredEntries.iterator( ); String sSeries = null; while ( iterEntries.hasNext( ) ) { ISeriesUIProvider provider = iterEntries.next( ); sSeries = provider.getSeriesClass( ); if ( sSeries.equals( series.getClass( ).getName( ) ) ) { if ( chartModel instanceof ChartWithAxes ) { DataType dataType = getDataServiceProvider( ).getDataType( expression ); SeriesDefinition baseSD = (SeriesDefinition) ( ChartUIUtil.getBaseSeriesDefinitions( chartModel ).get( 0 ) ); SeriesDefinition orthSD = null; orthSD = (SeriesDefinition) series.eContainer( ); String aggFunc = null; try { aggFunc = ChartUtil.getAggregateFuncExpr( orthSD, baseSD ); } catch ( ChartException e ) { WizardBase.showException( e.getLocalizedMessage( ) ); } if ( baseSD != null ) { // If aggregation is set to count/distinctcount on base // series, don't change data type to numeric. if ( !isBaseSeries && baseSD != orthSD && ChartUtil.isMagicAggregate( aggFunc ) ) { dataType = DataType.NUMERIC_LITERAL; } } if ( isValidatedAxis( dataType, axis.getType( ) ) ) { break; } AxisType[] axisTypes = provider.getCompatibleAxisType( series ); for ( int i = 0; i < axisTypes.length; i++ ) { if ( isValidatedAxis( dataType, axisTypes[i] ) ) { axisNotification( axis, axisTypes[i] ); // Avoid modifying model to notify an event loop ChartAdapter.beginIgnoreNotifications( ); axis.setType( axisTypes[i] ); ChartAdapter.endIgnoreNotifications( ); break; } } } try { provider.validateSeriesBindingType( series, getDataServiceProvider( ) ); } catch ( ChartException ce ) { WizardBase.showException( Messages.getFormattedString( "TaskSelectData.Warning.TypeCheck",//$NON-NLS-1$ new String[]{ ce.getLocalizedMessage( ), series.getDisplayName( ) } ) ); } break; } } } private boolean isValidatedAxis( DataType dataType, AxisType axisType ) { if ( dataType == null ) { return true; } else if ( ( dataType == DataType.DATE_TIME_LITERAL ) && ( axisType == AxisType.DATE_TIME_LITERAL ) ) { return true; } else if ( ( dataType == DataType.NUMERIC_LITERAL ) && ( ( axisType == AxisType.LINEAR_LITERAL ) || ( axisType == AxisType.LOGARITHMIC_LITERAL ) ) ) { return true; } else if ( ( dataType == DataType.TEXT_LITERAL ) && ( axisType == AxisType.TEXT_LITERAL ) ) { return true; } return false; } private void axisNotification( Axis axis, AxisType type ) { ChartAdapter.beginIgnoreNotifications( ); { convertSampleData( axis, type ); axis.setFormatSpecifier( null ); EList markerLines = axis.getMarkerLines( ); for ( int i = 0; i < markerLines.size( ); i++ ) { ( (MarkerLine) markerLines.get( i ) ).setFormatSpecifier( null ); } EList markerRanges = axis.getMarkerRanges( ); for ( int i = 0; i < markerRanges.size( ); i++ ) { ( (MarkerRange) markerRanges.get( i ) ).setFormatSpecifier( null ); } } ChartAdapter.endIgnoreNotifications( ); } private void convertSampleData( Axis axis, AxisType axisType ) { if ( ( axis.getAssociatedAxes( ) != null ) && ( axis.getAssociatedAxes( ).size( ) != 0 ) ) { BaseSampleData bsd = (BaseSampleData) chartModel.getSampleData( ) .getBaseSampleData( ) .get( 0 ); bsd.setDataSetRepresentation( ChartUIUtil.getConvertedSampleDataRepresentation( axisType, bsd.getDataSetRepresentation( ), 0 ) ); } else { int iStartIndex = getFirstSeriesDefinitionIndexForAxis( axis ); int iEndIndex = iStartIndex + axis.getSeriesDefinitions( ).size( ); int iOSDSize = chartModel.getSampleData( ) .getOrthogonalSampleData( ) .size( ); for ( int i = 0; i < iOSDSize; i++ ) { OrthogonalSampleData osd = (OrthogonalSampleData) chartModel.getSampleData( ) .getOrthogonalSampleData( ) .get( i ); if ( osd.getSeriesDefinitionIndex( ) >= iStartIndex && osd.getSeriesDefinitionIndex( ) < iEndIndex ) { osd.setDataSetRepresentation( ChartUIUtil.getConvertedSampleDataRepresentation( axisType, osd.getDataSetRepresentation( ), i ) ); } } } } private int getFirstSeriesDefinitionIndexForAxis( Axis axis ) { List axisList = ( (Axis) ( (ChartWithAxes) chartModel ).getAxes( ) .get( 0 ) ).getAssociatedAxes( ); int index = 0; for ( int i = 0; i < axisList.size( ); i++ ) { if ( axis.equals( axisList.get( i ) ) ) { index = i; break; } } int iTmp = 0; for ( int i = 0; i < index; i++ ) { iTmp += ChartUIUtil.getAxisYForProcessing( (ChartWithAxes) chartModel, i ) .getSeriesDefinitions( ) .size( ); } return iTmp; } /* * (non-Javadoc) * * @see org.eclipse.birt.core.ui.frameworks.taskwizard.SimpleTask#getImage() */ public Image getImage( ) { return UIHelper.getImage( ChartUIConstants.IMAGE_TASK_TYPE ); } /** * Rotates Axis Title when transposing * * @param cwa * chart model */ private void rotateAxisTitle( ChartWithAxes cwa ) { boolean bRender = false; ChartAdapter.beginIgnoreNotifications( ); Axis aX = ChartUIUtil.getAxisXForProcessing( cwa ); if ( aX.getTitle( ).isVisible( ) ) { bRender = true; } double curRotation = aX.getTitle( ) .getCaption( ) .getFont( ) .getRotation( ); aX.getTitle( ) .getCaption( ) .getFont( ) .setRotation( curRotation >= 0 ? 90 - curRotation : -90 - curRotation ); EList aYs = aX.getAssociatedAxes( ); for ( int i = 0; i < aYs.size( ); i++ ) { Axis aY = (Axis) aYs.get( i ); if ( aY.getTitle( ).isVisible( ) ) { bRender = true; } curRotation = aY.getTitle( ).getCaption( ).getFont( ).getRotation( ); aY.getTitle( ) .getCaption( ) .getFont( ) .setRotation( curRotation >= 0 ? 90 - curRotation : -90 - curRotation ); } ChartAdapter.endIgnoreNotifications( ); if ( bRender ) { doPreview( ); } } public IChartPreviewPainter createPreviewPainter( ) { ChartPreviewPainter painter = new ChartPreviewPainter( (ChartWizardContext) getContext( ) ); getPreviewCanvas( ).addPaintListener( painter ); getPreviewCanvas( ).addControlListener( painter ); painter.setPreview( getPreviewCanvas( ) ); return painter; } public void doPreview( ) { ChartUIUtil.prepareLivePreview( chartModel, getDataServiceProvider( ) ); // Repaint chart. if ( previewPainter != null ) { // To update data type after chart type conversion if ( chartModel instanceof ChartWithAxes ) { ChartAdapter.beginIgnoreNotifications( ); checkDataTypeForChartWithAxes( chartModel ); ChartAdapter.endIgnoreNotifications( ); } previewPainter.renderModel( chartModel ); } } public Canvas getPreviewCanvas( ) { return previewCanvas; } public boolean isPreviewable( ) { return true; } protected IChartType getCurrentChartType( ) { return htTypes.get( sType ); } private void createUIDescriptors( Composite parent ) { for ( TaskSelectTypeUIDescriptor descriptor : lstDescriptor ) { if ( descriptor.isVisible( ) ) { descriptor.createControl( parent ); } } } protected final void addTypeUIDescriptor( TaskSelectTypeUIDescriptor newDescriptor ) { if ( newDescriptor.getIndex( ) < 0 ) { // add to the last if it's negative lstDescriptor.add( newDescriptor ); return; } int lastIndex = -1; for ( int i = 0; i < lstDescriptor.size( ); i++ ) { TaskSelectTypeUIDescriptor descriptor = lstDescriptor.get( i ); if ( newDescriptor.getIndex( ) > lastIndex && newDescriptor.getIndex( ) <= descriptor.getIndex( ) ) { lstDescriptor.add( i, newDescriptor ); return; } lastIndex = descriptor.getIndex( ); } lstDescriptor.add( newDescriptor ); } protected void addOptionalUIDescriptor( ) { addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) { public int getIndex( ) { return 20; } public void createControl( Composite parent ) { Label lblOutput = new Label( parent, SWT.WRAP ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalIndent = 10; lblOutput.setLayoutData( gd ); lblOutput.setText( Messages.getString( "TaskSelectType.Label.OutputFormat" ) ); //$NON-NLS-1$ } // Add the ComboBox for Output Format final Combo cbOutput = new Combo( parent, SWT.DROP_DOWN | SWT.READ_ONLY ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); cbOutput.setLayoutData( gd ); cbOutput.addListener( SWT.Selection, new Listener( ) { public void handleEvent( Event event ) { String outputFormat = outputFormats[cbOutput.getSelectionIndex( )]; ( (ChartWizardContext) getContext( ) ).setOutputFormat( outputFormat ); // Update apply button if ( container != null && container instanceof ChartWizard ) { ( (ChartWizard) container ).updateApplyButton( ); } } } ); } cbOutput.setItems( outputDisplayNames ); String sCurrentFormat = ( (ChartWizardContext) getContext( ) ).getOutputFormat( ); for ( int index = 0; index < outputFormats.length; index++ ) { if ( outputFormats[index].equals( sCurrentFormat ) ) { cbOutput.select( index ); break; } } } } ); } }
chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/TaskSelectType.java
/******************************************************************************* * Copyright (c) 2004, 2007 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.chart.ui.swt.wizard; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Vector; import java.util.Map.Entry; import org.eclipse.birt.chart.exception.ChartException; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.ChartWithoutAxes; import org.eclipse.birt.chart.model.attribute.AxisType; import org.eclipse.birt.chart.model.attribute.ChartDimension; import org.eclipse.birt.chart.model.attribute.DataType; import org.eclipse.birt.chart.model.attribute.Orientation; import org.eclipse.birt.chart.model.component.Axis; import org.eclipse.birt.chart.model.component.MarkerLine; import org.eclipse.birt.chart.model.component.MarkerRange; import org.eclipse.birt.chart.model.component.Series; import org.eclipse.birt.chart.model.data.BaseSampleData; import org.eclipse.birt.chart.model.data.OrthogonalSampleData; import org.eclipse.birt.chart.model.data.Query; import org.eclipse.birt.chart.model.data.SeriesDefinition; import org.eclipse.birt.chart.model.type.StockSeries; import org.eclipse.birt.chart.ui.extension.i18n.Messages; import org.eclipse.birt.chart.ui.swt.ChartPreviewPainter; import org.eclipse.birt.chart.ui.swt.interfaces.IChartPreviewPainter; import org.eclipse.birt.chart.ui.swt.interfaces.IChartSubType; import org.eclipse.birt.chart.ui.swt.interfaces.IChartType; import org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider; import org.eclipse.birt.chart.ui.swt.interfaces.ISeriesUIProvider; import org.eclipse.birt.chart.ui.swt.interfaces.ITaskChangeListener; import org.eclipse.birt.chart.ui.swt.interfaces.ITaskPreviewable; import org.eclipse.birt.chart.ui.util.ChartCacheManager; import org.eclipse.birt.chart.ui.util.ChartHelpContextIds; import org.eclipse.birt.chart.ui.util.ChartUIConstants; import org.eclipse.birt.chart.ui.util.ChartUIUtil; import org.eclipse.birt.chart.ui.util.UIHelper; import org.eclipse.birt.chart.util.ChartUtil; import org.eclipse.birt.core.ui.frameworks.taskwizard.SimpleTask; import org.eclipse.birt.core.ui.frameworks.taskwizard.WizardBase; import org.eclipse.birt.core.ui.frameworks.taskwizard.interfaces.IWizardContext; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.TreeIterator; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.util.EContentAdapter; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; /** * TaskSelectType */ public class TaskSelectType extends SimpleTask implements SelectionListener, ITaskChangeListener, ITaskPreviewable { /** * * TaskSelectTypeUIDescriptor is used to create UI in misc area according to * the order of index */ public abstract class TaskSelectTypeUIDescriptor { private boolean bVisible = true; public boolean isVisible( ) { return bVisible; } public void setVisible( boolean bVisible ) { this.bVisible = bVisible; } public abstract int getIndex( ); public abstract void createControl( Composite parent ); } private Chart chartModel = null; private ChartAdapter adapter = null; private Composite cmpType = null; private Composite cmpMisc = null; private Composite cmpRight = null; private Composite cmpLeft = null; private Composite cmpTypeButtons = null; private Composite cmpSubTypes = null; protected IChartPreviewPainter previewPainter = null; private Canvas previewCanvas = null; private LinkedHashMap<String, IChartType> htTypes = null; private RowData rowData = new RowData( 80, 80 ); protected String sSubType = null; protected String sType = null; private String sOldType = null; // Stored in IChartType protected String sDimension = null; private Table table = null; private Vector<String> vSubTypeNames = null; protected Orientation orientation = null; private Label lblOrientation = null; private Button cbOrientation = null; private Label lblMultipleY = null; protected Combo cbMultipleY = null; private Label lblSeriesType = null; private Combo cbSeriesType = null; private Combo cbDimension = null; private SashForm foSashForm; protected int pageMargin = 80; private static final String LEADING_BLANKS = " "; //$NON-NLS-1$ private static Hashtable<String, Series> htSeriesNames = null; private static String[] outputFormats, outputDisplayNames; static { try { outputFormats = ChartUtil.getSupportedOutputFormats( ); outputDisplayNames = ChartUtil.getSupportedOutputDisplayNames( ); } catch ( ChartException e ) { WizardBase.displayException( e ); outputFormats = new String[0]; outputDisplayNames = new String[0]; } } protected List<TaskSelectTypeUIDescriptor> lstDescriptor = new LinkedList<TaskSelectTypeUIDescriptor>( ); public TaskSelectType( ) { super( Messages.getString( "TaskSelectType.TaskExp" ) ); //$NON-NLS-1$ setDescription( Messages.getString( "TaskSelectType.Task.Description" ) ); //$NON-NLS-1$ if ( chartModel != null ) { sType = chartModel.getType( ); sOldType = sType; sSubType = chartModel.getSubType( ); sDimension = translateDimensionString( chartModel.getDimension( ) .getName( ) ); if ( chartModel instanceof ChartWithAxes ) { orientation = ( (ChartWithAxes) chartModel ).getOrientation( ); } } htTypes = new LinkedHashMap<String, IChartType>( ); } public void createControl( Composite parent ) { if ( topControl == null || topControl.isDisposed( ) ) { topControl = new Composite( parent, SWT.NONE ); GridLayout gridLayout = new GridLayout( 2, false ); gridLayout.marginWidth = pageMargin; topControl.setLayout( gridLayout ); topControl.setLayoutData( new GridData( GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL ) ); if ( context != null ) { chartModel = ( (ChartWizardContext) context ).getModel( ); } placeComponents( ); updateAdapters( ); } // Update dimension combo and related sub-types in case of axes changed // outside if ( ( (ChartWizardContext) getContext( ) ).isMoreAxesSupported( ) ) { updateDimensionCombo( sType ); createAndDisplayTypesSheet( sType ); setDefaultSubtypeSelection( ); cmpMisc.layout( ); } doPreview( ); bindHelp( ); } protected void bindHelp( ) { ChartUIUtil.bindHelp( getControl( ), ChartHelpContextIds.TASK_SELECT_TYPE ); } private void placeComponents( ) { foSashForm = new SashForm( topControl, SWT.VERTICAL ); { GridLayout layout = new GridLayout( ); foSashForm.setLayout( layout ); GridData gridData = new GridData( GridData.FILL_BOTH ); // TODO verify Bug 194391 in Linux gridData.heightHint = 570; foSashForm.setLayoutData( gridData ); } createPreviewArea( ); createTypeArea( ); setDefaultTypeSelection( ); refreshChart( ); populateSeriesTypesList( ); } private void createPreviewArea( ) { Composite cmpPreview = new Composite( foSashForm, SWT.NONE ); cmpPreview.setLayout( new GridLayout( ) ); GridData gridData = new GridData( GridData.FILL_BOTH ); gridData.horizontalSpan = 2; gridData.heightHint = 270; cmpPreview.setLayoutData( gridData ); Label label = new Label( cmpPreview, SWT.NONE ); { label.setText( Messages.getString( "TaskSelectType.Label.Preview" ) ); //$NON-NLS-1$ label.setFont( JFaceResources.getBannerFont( ) ); } previewCanvas = new Canvas( cmpPreview, SWT.BORDER ); previewCanvas.setLayoutData( new GridData( GridData.FILL_BOTH ) ); previewCanvas.setBackground( Display.getDefault( ) .getSystemColor( SWT.COLOR_WIDGET_BACKGROUND ) ); previewPainter = createPreviewPainter( ); } private void createTypeArea( ) { ScrolledComposite sc = new ScrolledComposite( foSashForm, SWT.V_SCROLL ); { GridLayout layout = new GridLayout( ); sc.setLayout( layout ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); sc.setLayoutData( gridData ); sc.setExpandHorizontal( true ); sc.setExpandVertical( true ); } cmpType = new Composite( sc, SWT.NONE ); cmpType.setLayout( new GridLayout( 2, false ) ); cmpType.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); sc.setContent( cmpType ); createTypeTable( ); addChartTypes( ); createDetails( ); Point size = cmpType.computeSize( SWT.DEFAULT, SWT.DEFAULT ); sc.setMinSize( size ); } private void createDetails( ) { cmpRight = new Composite( cmpType, SWT.NONE ); cmpRight.setLayout( new GridLayout( ) ); cmpRight.setLayoutData( new GridData( GridData.FILL_BOTH ) ); createComposite( new Vector<IChartSubType>( ) ); createMiscArea( ); } private void createMiscArea( ) { cmpMisc = new Composite( cmpRight, SWT.NONE ); cmpMisc.setLayout( new GridLayout( 4, false ) ); cmpMisc.setLayoutData( new GridData( GridData.FILL_BOTH ) ); addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) { public int getIndex( ) { return 10; } public void createControl( Composite parent ) { Label lblDimension = new Label( parent, SWT.WRAP ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); lblDimension.setLayoutData( gd ); lblDimension.setText( Messages.getString( "TaskSelectType.Label.Dimension" ) ); //$NON-NLS-1$ } // Add the ComboBox for Dimensions cbDimension = new Combo( parent, SWT.DROP_DOWN | SWT.READ_ONLY ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); cbDimension.setLayoutData( gd ); cbDimension.addSelectionListener( TaskSelectType.this ); } } } ); addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) { public int getIndex( ) { return 30; } public void createControl( Composite parent ) { lblMultipleY = new Label( parent, SWT.WRAP ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); lblMultipleY.setLayoutData( gd ); lblMultipleY.setText( Messages.getString( "TaskSelectType.Label.MultipleYAxis" ) ); //$NON-NLS-1$ } // Add the checkBox for Multiple Y Axis cbMultipleY = new Combo( parent, SWT.DROP_DOWN | SWT.READ_ONLY ); { cbMultipleY.setItems( new String[]{ Messages.getString( "TaskSelectType.Selection.None" ), //$NON-NLS-1$ Messages.getString( "TaskSelectType.Selection.SecondaryAxis" ), //$NON-NLS-1$ Messages.getString( "TaskSelectType.Selection.MoreAxes" ) //$NON-NLS-1$ } ); GridData gd = new GridData( GridData.FILL_HORIZONTAL ); cbMultipleY.setLayoutData( gd ); cbMultipleY.addSelectionListener( TaskSelectType.this ); int axisNum = ChartUIUtil.getOrthogonalAxisNumber( chartModel ); selectMultipleAxis( axisNum ); } } } ); addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) { public int getIndex( ) { return 40; } public void createControl( Composite parent ) { lblSeriesType = new Label( parent, SWT.WRAP ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalIndent = 10; lblSeriesType.setLayoutData( gd ); lblSeriesType.setText( Messages.getString( "TaskSelectType.Label.SeriesType" ) ); //$NON-NLS-1$ lblSeriesType.setEnabled( false ); } // Add the ComboBox for Series Type cbSeriesType = new Combo( parent, SWT.DROP_DOWN | SWT.READ_ONLY ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); cbSeriesType.setLayoutData( gd ); cbSeriesType.setEnabled( false ); cbSeriesType.addSelectionListener( TaskSelectType.this ); } } } ); addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) { public int getIndex( ) { return 50; } public void createControl( Composite parent ) { lblOrientation = new Label( parent, SWT.WRAP ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); lblOrientation.setLayoutData( gd ); lblOrientation.setText( Messages.getString( "TaskSelectType.Label.Oritention" ) ); //$NON-NLS-1$ } // Add the CheckBox for Orientation cbOrientation = new Button( parent, SWT.CHECK ); { cbOrientation.setText( Messages.getString( "TaskSelectType.Label.FlipAxis" ) ); //$NON-NLS-1$ GridData gd = new GridData( ); cbOrientation.setLayoutData( gd ); cbOrientation.addSelectionListener( TaskSelectType.this ); } if ( TaskSelectType.this.orientation == Orientation.HORIZONTAL_LITERAL ) { cbOrientation.setSelection( true ); } else { cbOrientation.setSelection( false ); } } } ); addOptionalUIDescriptor( ); createUIDescriptors( cmpMisc ); } /** * This method initializes table * */ private void createTypeTable( ) { cmpLeft = new Composite( cmpType, SWT.NONE ); cmpLeft.setLayout( new GridLayout( ) ); cmpLeft.setLayoutData( new GridData( GridData.FILL_BOTH ) ); Label lblTypes = new Label( cmpLeft, SWT.WRAP ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); lblTypes.setLayoutData( gd ); lblTypes.setText( Messages.getString( "TaskSelectType.Label.SelectChartType" ) ); //$NON-NLS-1$ } table = new Table( cmpLeft, SWT.BORDER ); { GridData gd = new GridData( GridData.FILL_BOTH ); table.setLayoutData( gd ); table.setToolTipText( Messages.getString( "TaskSelectType.Label.ChartTypes" ) ); //$NON-NLS-1$ table.addSelectionListener( this ); } } /** * */ private void addChartTypes( ) { populateTypesTable( ); updateUI( ); } /** * */ private void populateTypesTable( ) { htTypes.clear( ); Collection<IChartType> cTypes = ChartUIExtensionsImpl.instance( ) .getUIChartTypeExtensions( getContext( ).getClass( ) .getSimpleName( ) ); Iterator<IChartType> iterTypes = cTypes.iterator( ); while ( iterTypes.hasNext( ) ) { IChartType type = iterTypes.next( ); // Only support enabled chart types if ( ( (ChartWizardContext) context ).isEnabled( type.getName( ) ) ) { htTypes.put( type.getName( ), type ); } } } private void updateUI( ) { Iterator<String> iter = htTypes.keySet( ).iterator( ); while ( iter.hasNext( ) ) { String sTypeTmp = iter.next( ); TableItem tItem = new TableItem( table, SWT.NONE ); tItem.setText( LEADING_BLANKS + ( htTypes.get( sTypeTmp ) ).getDisplayName( ) ); tItem.setData( ( htTypes.get( sTypeTmp ) ).getName( ) ); tItem.setImage( ( htTypes.get( sTypeTmp ) ).getImage( ) ); } } protected Chart getChartModel( ) { return chartModel; } /** * This method initializes cmpSubTypes * */ private void createComposite( Vector<IChartSubType> vSubTypes ) { Label lblSubtypes = new Label( cmpRight, SWT.NO_FOCUS ); { lblSubtypes.setText( Messages.getString( "TaskSelectType.Label.SelectSubtype" ) ); //$NON-NLS-1$ GridData gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalIndent = 5; lblSubtypes.setLayoutData( gd ); } GridData gdTypes = new GridData( GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL ); cmpSubTypes = new Composite( cmpRight, SWT.NONE ); createGroups( vSubTypes ); cmpSubTypes.setLayoutData( gdTypes ); cmpSubTypes.setToolTipText( Messages.getString( "TaskSelectType.Label.ChartSubtypes" ) ); //$NON-NLS-1$ cmpSubTypes.setLayout( new GridLayout( ) ); cmpSubTypes.setVisible( true ); } /** * This method initializes cmpTypeButtons * */ private void createGroups( Vector<IChartSubType> vSubTypes ) { vSubTypeNames = new Vector<String>( ); if ( cmpTypeButtons != null && !cmpTypeButtons.isDisposed( ) ) { // Remove existing buttons cmpTypeButtons.dispose( ); } cmpTypeButtons = new Composite( cmpSubTypes, SWT.NONE ); RowLayout rowLayout = new RowLayout( ); rowLayout.marginTop = 0; rowLayout.marginLeft = 0; rowLayout.marginBottom = 12; rowLayout.marginRight = 12; rowLayout.spacing = 4; cmpTypeButtons.setLayout( rowLayout ); // Add new buttons for this type for ( int iC = 0; iC < vSubTypes.size( ); iC++ ) { IChartSubType subType = vSubTypes.get( iC ); vSubTypeNames.add( subType.getName( ) ); Button btnType = new Button( cmpTypeButtons, SWT.TOGGLE ); btnType.setData( subType.getName( ) ); btnType.setImage( subType.getImage( ) ); btnType.setLayoutData( rowData ); btnType.addSelectionListener( this ); btnType.setToolTipText( subType.getDescription( ) ); btnType.getImage( ).setBackground( btnType.getBackground( ) ); btnType.setVisible( true ); cmpTypeButtons.layout( true ); } cmpTypeButtons.setLayoutData( new GridData( GridData.FILL_BOTH ) ); cmpSubTypes.layout( true ); } private void populateSeriesTypes( Collection<IChartType> allChartType, Series series, Orientation orientation ) { Iterator<IChartType> iterTypes = allChartType.iterator( ); while ( iterTypes.hasNext( ) ) { IChartType type = iterTypes.next( ); Series newSeries = type.getSeries( ); if ( htSeriesNames == null ) { htSeriesNames = new Hashtable<String, Series>( 20 ); } if ( type.canCombine( ) ) { // Horizontal Stock is not supported and can't be mixed with // other charts if ( !( newSeries instanceof StockSeries ) || ( orientation.getValue( ) == Orientation.VERTICAL ) ) { String sDisplayName = newSeries.getDisplayName( ); htSeriesNames.put( sDisplayName, newSeries ); cbSeriesType.add( sDisplayName ); } if ( type.getName( ).equals( chartModel.getType( ) ) ) { cbSeriesType.select( cbSeriesType.getItemCount( ) - 1 ); } } } } /* * This method translates the dimension string from the model to that * maintained by the UI (for readability). */ private String translateDimensionString( String sDimensionValue ) { String dimensionName = ""; //$NON-NLS-1$ if ( sDimensionValue.equals( ChartDimension.TWO_DIMENSIONAL_LITERAL.getName( ) ) ) { dimensionName = IChartType.TWO_DIMENSION_TYPE; } else if ( sDimensionValue.equals( ChartDimension.TWO_DIMENSIONAL_WITH_DEPTH_LITERAL.getName( ) ) ) { dimensionName = IChartType.TWO_DIMENSION_WITH_DEPTH_TYPE; } else if ( sDimensionValue.equals( ChartDimension.THREE_DIMENSIONAL_LITERAL.getName( ) ) ) { dimensionName = IChartType.THREE_DIMENSION_TYPE; } return dimensionName; } public void widgetDefaultSelected( SelectionEvent e ) { } public void widgetSelected( SelectionEvent e ) { // Indicates whether need to update chart model boolean needUpdateModel = false; Object oSelected = e.getSource( ); if ( oSelected.getClass( ).equals( Button.class ) ) { needUpdateModel = true; if ( oSelected.equals( cbOrientation ) ) { if ( cbOrientation.getSelection( ) ) { orientation = Orientation.HORIZONTAL_LITERAL; } else { orientation = Orientation.VERTICAL_LITERAL; } createAndDisplayTypesSheet( sType ); setDefaultSubtypeSelection( ); populateSeriesTypesList( ); ChartCacheManager.getInstance( ).cacheOrientation( sType, orientation ); } else { Button btn = (Button) e.getSource( ); if ( btn.getSelection( ) ) { if ( this.sSubType != null && !getSubtypeFromButton( btn ).equals( sSubType ) ) { int iTypeIndex = vSubTypeNames.indexOf( sSubType ); if ( iTypeIndex >= 0 ) { ( (Button) cmpTypeButtons.getChildren( )[iTypeIndex] ).setSelection( false ); cmpTypeButtons.redraw( ); } } // Cache label position for stacked or non-stacked case. ChartUIUtil.saveLabelPositionIntoCache( getSeriesDefinitionForProcessing( ) ); sSubType = getSubtypeFromButton( btn ); ChartCacheManager.getInstance( ).cacheSubtype( sType, sSubType ); } else { if ( this.sSubType != null && getSubtypeFromButton( btn ).equals( sSubType ) ) { // Clicking on the same button should not cause it to be // unselected btn.setSelection( true ); // Disable the statement to avoid when un-check all // stacked attributes of series on format tab, the // default chart is painted as side-by-side, but it // can't select stacked button to change chart type to // stacked in chart type tab. // needUpdateModel = false; } } } } else if ( oSelected.getClass( ).equals( Table.class ) ) { sType = ( (String) ( (TableItem) e.item ).getData( ) ).trim( ); if ( !sOldType.equals( sType ) ) { sOldType = sType; // Get orientation for non-xtab case. In xtab, orientation won't // be changed if ( !getDataServiceProvider( ).checkState( IDataServiceProvider.PART_CHART ) ) { // Get the cached orientation if ( chartModel != null && chartModel instanceof ChartWithAxes ) { Orientation lastOrientation = ChartCacheManager.getInstance( ) .findOrientation( sType ); if ( lastOrientation != null && this.orientation != lastOrientation ) { this.orientation = lastOrientation; this.rotateAxisTitle( (ChartWithAxes) chartModel ); } if ( lastOrientation == null ) { this.orientation = htTypes.get( sType ) .getDefaultOrientation( ); } } } if ( chartModel != null && chartModel instanceof ChartWithAxes && ChartCacheManager.getInstance( ) .findCategory( sType ) != null ) { boolean bCategory = ChartCacheManager.getInstance( ) .findCategory( sType ) .booleanValue( ); ( (Axis) ( (ChartWithAxes) chartModel ).getAxes( ).get( 0 ) ).setCategoryAxis( bCategory ); } sSubType = null; createAndDisplayTypesSheet( sType ); setDefaultSubtypeSelection( ); cmpMisc.layout( ); needUpdateModel = true; } } else if ( oSelected.equals( cbMultipleY ) ) { needUpdateModel = true; lblSeriesType.setEnabled( isTwoAxesEnabled( ) ); Axis xAxis = ( (Axis) ( (ChartWithAxes) chartModel ).getAxes( ) .get( 0 ) ); ( (ChartWizardContext) getContext( ) ).setMoreAxesSupported( cbMultipleY.getSelectionIndex( ) == 2 ); if ( chartModel instanceof ChartWithoutAxes ) { throw new IllegalArgumentException( Messages.getString( "TaskSelectType.Exception.CannotSupportAxes" ) ); //$NON-NLS-1$ } // Prevent notifications rendering preview ChartAdapter.beginIgnoreNotifications( ); int iAxisNumber = ChartUIUtil.getOrthogonalAxisNumber( chartModel ); if ( cbMultipleY.getSelectionIndex( ) == 0 ) { // Remove series type cache ChartCacheManager.getInstance( ).cacheSeriesType( null ); // Keeps one axis if ( iAxisNumber > 1 ) { ChartUIUtil.removeLastAxes( (ChartWithAxes) chartModel, iAxisNumber - 1 ); } } else if ( cbMultipleY.getSelectionIndex( ) == 1 ) { // Keeps two axes if ( iAxisNumber == 1 ) { ChartUIUtil.addAxis( (ChartWithAxes) chartModel ); } else if ( iAxisNumber > 2 ) { ChartUIUtil.removeLastAxes( (ChartWithAxes) chartModel, iAxisNumber - 2 ); } } ChartAdapter.endIgnoreNotifications( ); if ( xAxis.getAssociatedAxes( ).size( ) > 1 ) { String lastSeriesType = ChartCacheManager.getInstance( ) .findSeriesType( ); if ( lastSeriesType != null ) { cbSeriesType.setText( lastSeriesType ); } else { Axis overlayAxis = (Axis) xAxis.getAssociatedAxes( ) .get( 1 ); String sDisplayName = ( (SeriesDefinition) overlayAxis.getSeriesDefinitions( ) .get( 0 ) ).getDesignTimeSeries( ).getDisplayName( ); cbSeriesType.setText( sDisplayName ); } changeOverlaySeriesType( ); } cbSeriesType.setEnabled( isTwoAxesEnabled( ) ); // Update dimension combo and related sub-types if ( updateDimensionCombo( sType ) ) { createAndDisplayTypesSheet( sType ); setDefaultSubtypeSelection( ); } // Pack to display enough space for combo cmpMisc.layout( ); } else if ( oSelected.equals( cbDimension ) ) { String newDimension = cbDimension.getItem( cbDimension.getSelectionIndex( ) ); if ( !newDimension.equals( sDimension ) ) { sDimension = newDimension; ChartCacheManager.getInstance( ).cacheDimension( sType, sDimension ); createAndDisplayTypesSheet( sType ); setDefaultSubtypeSelection( ); needUpdateModel = true; } } else if ( oSelected.equals( cbSeriesType ) ) { // if ( !cbSeriesType.getText( ).equals( oldSeriesName ) ) // { needUpdateModel = true; changeOverlaySeriesType( ); // } } // Following operations need new model if ( needUpdateModel ) { // Update apply button ChartAdapter.notifyUpdateApply( ); // Update chart model refreshChart( ); if ( oSelected.getClass( ).equals( Table.class ) ) { // Ensure populate list after chart model generated populateSeriesTypesList( ); } else if ( oSelected.equals( cbOrientation ) ) { // Auto rotates Axis title when transposing if ( chartModel instanceof ChartWithAxes ) { rotateAxisTitle( (ChartWithAxes) chartModel ); } } // Preview after all model changes doPreview( ); } } /** * Updates the dimension combo according to chart type and axes number * * @param sSelectedType * Chart type * @return whether the dimension is changed after updating */ private boolean updateDimensionCombo( String sSelectedType ) { // Remember last selection boolean isOldExist = false; // Update valid dimension list IChartType chartType = htTypes.get( sSelectedType ); String[] dimensionArray = chartType.getSupportedDimensions( ); int axesNum = ChartUIUtil.getOrthogonalAxisNumber( chartModel ); if ( sDimension == null ) { // Initialize dimension sDimension = chartType.getDefaultDimension( ); isOldExist = true; } cbDimension.removeAll( ); for ( int i = 0; i < dimensionArray.length; i++ ) { boolean isSupported = chartType.isDimensionSupported( dimensionArray[i], (ChartWizardContext) context, axesNum, 0 ); if ( isSupported ) { cbDimension.add( dimensionArray[i] ); } if ( !isOldExist && sDimension.equals( dimensionArray[i] ) ) { isOldExist = isSupported; } } String cache = ChartCacheManager.getInstance( ) .getDimension( sSelectedType ); if ( cache != null ) { sDimension = cache; isOldExist = true; } // Select the previous selection or the default if ( !isOldExist ) { sDimension = chartType.getDefaultDimension( ); } cbDimension.setText( sDimension ); return !isOldExist; } private boolean isTwoAxesEnabled( ) { return cbMultipleY.getSelectionIndex( ) == 1; } private void updateAdapters( ) { if ( container instanceof ChartWizard ) { // Refresh all adapters EContentAdapter adapter = ( (ChartWizard) container ).getAdapter( ); chartModel.eAdapters( ).remove( adapter ); TreeIterator<EObject> iterator = chartModel.eAllContents( ); while ( iterator.hasNext( ) ) { EObject oModel = iterator.next( ); oModel.eAdapters( ).remove( adapter ); } chartModel.eAdapters( ).add( adapter ); } else { // For extension case, create an adapter and add change listener EList<Adapter> adapters = chartModel.eAdapters( ); if ( adapters.isEmpty( ) ) { // Get the previous adapter if existent if ( adapter == null ) { adapter = new ChartAdapter( container ); adapter.addListener( this ); } adapters.add( adapter ); } else { if ( adapters.get( 0 ) instanceof ChartAdapter ) { ( (ChartAdapter) adapters.get( 0 ) ).addListener( this ); } } } } private boolean is3D( ) { return IChartType.THREE_DIMENSION_TYPE.equals( sDimension ); } private void changeOverlaySeriesType( ) { // cache the second axis series type if it can be combined. if ( getCurrentChartType( ).canCombine( ) ) { ChartCacheManager.getInstance( ) .cacheSeriesType( cbSeriesType.getText( ) ); } boolean bException = false; try { // CHANGE ALL OVERLAY SERIES TO NEW SELECTED TYPE Axis XAxis = (Axis) ( (ChartWithAxes) chartModel ).getAxes( ) .get( 0 ); int iSeriesDefinitionIndex = 0 + ( (Axis) XAxis.getAssociatedAxes( ) .get( 0 ) ).getSeriesDefinitions( ).size( ); // SINCE // THIS IS FOR THE ORTHOGONAL OVERLAY SERIES DEFINITION int iOverlaySeriesCount = ( (Axis) XAxis.getAssociatedAxes( ) .get( 1 ) ).getSeriesDefinitions( ).size( ); // DISABLE NOTIFICATIONS WHILE MODEL UPDATE TAKES PLACE ChartAdapter.beginIgnoreNotifications( ); for ( int i = 0; i < iOverlaySeriesCount; i++ ) { Series newSeries = (Series) EcoreUtil.copy( htSeriesNames.get( cbSeriesType.getText( ) ) ); newSeries.translateFrom( ( (SeriesDefinition) ( (Axis) XAxis.getAssociatedAxes( ) .get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getDesignTimeSeries( ), iSeriesDefinitionIndex, chartModel ); // ADD THE MODEL ADAPTERS TO THE NEW SERIES newSeries.eAdapters( ).addAll( chartModel.eAdapters( ) ); // UPDATE THE SERIES DEFINITION WITH THE SERIES INSTANCE ( (SeriesDefinition) ( (Axis) XAxis.getAssociatedAxes( ) .get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getSeries( ) .clear( ); ( (SeriesDefinition) ( (Axis) XAxis.getAssociatedAxes( ) .get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getSeries( ) .add( newSeries ); ChartUIUtil.setSeriesName( chartModel ); } } catch ( Exception e ) { bException = true; WizardBase.showException( e.getLocalizedMessage( ) ); } finally { // ENABLE NOTIFICATIONS IN CASE EXCEPTIONS OCCUR ChartAdapter.endIgnoreNotifications( ); } if ( !bException ) { WizardBase.removeException( ); } } private void populateSeriesTypesList( ) { if ( cbSeriesType == null ) { return; } // Populate Series Types List cbSeriesType.removeAll( ); Series series = getSeriesDefinitionForProcessing( ).getDesignTimeSeries( ); if ( getCurrentChartType( ).canCombine( ) ) { populateSeriesTypes( ChartUIExtensionsImpl.instance( ) .getUIChartTypeExtensions( getContext( ).getClass( ) .getSimpleName( ) ), series, this.orientation ); } else { String seriesName = series.getDisplayName( ); cbSeriesType.add( seriesName ); cbSeriesType.select( 0 ); } // Select the appropriate current series type if overlay series exists if ( this.chartModel instanceof ChartWithAxes ) { Axis xAxis = ( (Axis) ( (ChartWithAxes) chartModel ).getAxes( ) .get( 0 ) ); if ( xAxis.getAssociatedAxes( ).size( ) > 1 ) { // Set series name from cache or model String lastType = ChartCacheManager.getInstance( ) .findSeriesType( ); Axis overlayAxis = (Axis) xAxis.getAssociatedAxes( ).get( 1 ); if ( !overlayAxis.getSeriesDefinitions( ).isEmpty( ) ) { Series oseries = ( (SeriesDefinition) overlayAxis.getSeriesDefinitions( ) .get( 0 ) ).getDesignTimeSeries( ); String sDisplayName = oseries.getDisplayName( ); if ( lastType != null ) { cbSeriesType.setText( lastType ); } else { cbSeriesType.setText( sDisplayName ); } String seriesName = oseries.getSeriesIdentifier( ) .toString( ); if ( seriesName.trim( ).length( ) != 0 ) { Iterator<Entry<String, Series>> itr = htSeriesNames.entrySet( ) .iterator( ); while ( itr.hasNext( ) ) { Entry<String, Series> entry = itr.next( ); entry.getValue( ).setSeriesIdentifier( seriesName ); } } } // Update overlay series changeOverlaySeriesType( ); } } } /** * This method populates the subtype panel (creating its components if * necessary). It gets called when the type selection changes or when the * dimension selection changes (since not all sub types are supported for * all dimension selections). * * @param sSelectedType * Type from Type List */ private void createAndDisplayTypesSheet( String sSelectedType ) { IChartType chartType = htTypes.get( sSelectedType ); if ( cbOrientation != null ) { lblOrientation.setEnabled( chartType.supportsTransposition( ) && !is3D( ) ); cbOrientation.setEnabled( chartType.supportsTransposition( ) && !is3D( ) ); } // Update dimension updateDimensionCombo( sSelectedType ); if ( this.sDimension == null ) { this.sDimension = chartType.getDefaultDimension( ); } if ( this.orientation == null ) { this.orientation = chartType.getDefaultOrientation( ); } // Show the subtypes for the selected type based on current selections // of dimension and orientation Vector<IChartSubType> vSubTypes = new Vector<IChartSubType>( chartType.getChartSubtypes( sDimension, orientation ) ); if ( vSubTypes.size( ) == 0 ) { vSubTypes = new Vector<IChartSubType>( chartType.getChartSubtypes( chartType.getDefaultDimension( ), chartType.getDefaultOrientation( ) ) ); this.sDimension = chartType.getDefaultDimension( ); this.orientation = chartType.getDefaultOrientation( ); } // If two orientations are not supported, to get the default. if ( cbOrientation == null || !cbOrientation.isEnabled( ) ) { this.orientation = chartType.getDefaultOrientation( ); } // Cache the orientation for each chart type. ChartCacheManager.getInstance( ).cacheOrientation( sType, orientation ); if ( chartModel == null ) { ChartCacheManager.getInstance( ).cacheCategory( sType, true ); } else if ( chartModel instanceof ChartWithAxes ) { ChartCacheManager.getInstance( ) .cacheCategory( sType, ( (Axis) ( (ChartWithAxes) chartModel ).getAxes( ) .get( 0 ) ).isCategoryAxis( ) ); } // Update the UI with information for selected type createGroups( vSubTypes ); if ( this.cbOrientation != null ) { if ( this.orientation == Orientation.HORIZONTAL_LITERAL ) { this.cbOrientation.setSelection( true ); } else { this.cbOrientation.setSelection( false ); } } cmpRight.layout( ); } private void setDefaultSubtypeSelection( ) { if ( sSubType == null ) { // Try to get cached subtype sSubType = ChartCacheManager.getInstance( ).findSubtype( sType ); } if ( sSubType == null ) { // Get the default subtype ( (Button) cmpTypeButtons.getChildren( )[0] ).setSelection( true ); sSubType = getSubtypeFromButton( cmpTypeButtons.getChildren( )[0] ); ChartCacheManager.getInstance( ).cacheSubtype( sType, sSubType ); } else { Control[] buttons = cmpTypeButtons.getChildren( ); boolean bSelected = false; for ( int iB = 0; iB < buttons.length; iB++ ) { if ( getSubtypeFromButton( buttons[iB] ).equals( sSubType ) ) { ( (Button) buttons[iB] ).setSelection( true ); bSelected = true; break; } } // If specified subType is not found, select default if ( !bSelected ) { ( (Button) cmpTypeButtons.getChildren( )[0] ).setSelection( true ); sSubType = getSubtypeFromButton( cmpTypeButtons.getChildren( )[0] ); ChartCacheManager.getInstance( ).cacheSubtype( sType, sSubType ); } } cmpTypeButtons.redraw( ); } private void setDefaultTypeSelection( ) { if ( table.getItems( ).length > 0 ) { if ( sType == null ) { table.select( 0 ); sType = (String) ( table.getSelection( )[0] ).getData( ); } else { TableItem[] tiAll = table.getItems( ); for ( int iTI = 0; iTI < tiAll.length; iTI++ ) { if ( tiAll[iTI].getData( ).equals( sType ) ) { table.select( iTI ); break; } } } sOldType = sType; createAndDisplayTypesSheet( sType ); setDefaultSubtypeSelection( ); } } public void dispose( ) { super.dispose( ); lstDescriptor.clear( ); chartModel = null; adapter = null; if ( previewPainter != null ) { previewPainter.dispose( ); } previewPainter = null; sSubType = null; sType = null; sDimension = null; vSubTypeNames = null; orientation = null; } private void refreshChart( ) { // DISABLE PREVIEW REFRESH DURING CONVERSION ChartAdapter.beginIgnoreNotifications( ); IChartType chartType = htTypes.get( sType ); boolean bException = false; try { chartModel = chartType.getModel( sSubType, this.orientation, this.sDimension, this.chartModel ); updateAdapters( ); } catch ( Exception e ) { bException = true; WizardBase.showException( e.getLocalizedMessage( ) ); } if ( !bException ) { WizardBase.removeException( ); } // RE-ENABLE PREVIEW REFRESH ChartAdapter.endIgnoreNotifications( ); updateSelection( ); ( (ChartWizardContext) context ).setModel( chartModel ); ( (ChartWizardContext) context ).setChartType( chartType ); setContext( context ); } private SeriesDefinition getSeriesDefinitionForProcessing( ) { // TODO Attention: all index is 0 SeriesDefinition sd = null; if ( chartModel instanceof ChartWithAxes ) { sd = ( (SeriesDefinition) ( (Axis) ( (Axis) ( (ChartWithAxes) chartModel ).getAxes( ) .get( 0 ) ).getAssociatedAxes( ).get( 0 ) ).getSeriesDefinitions( ) .get( 0 ) ); } else if ( chartModel instanceof ChartWithoutAxes ) { sd = (SeriesDefinition) ( (SeriesDefinition) ( (ChartWithoutAxes) chartModel ).getSeriesDefinitions( ) .get( 0 ) ).getSeriesDefinitions( ).get( 0 ); } return sd; } /** * Updates UI selection according to Chart type * */ protected void updateSelection( ) { boolean bOutXtab = !getDataServiceProvider( ).checkState( IDataServiceProvider.PART_CHART ); if ( chartModel instanceof ChartWithAxes ) { if ( cbMultipleY != null ) { lblMultipleY.setEnabled( bOutXtab && !is3D( ) ); cbMultipleY.setEnabled( bOutXtab && !is3D( ) ); } if ( cbSeriesType != null ) { lblSeriesType.setEnabled( bOutXtab && isTwoAxesEnabled( ) ); cbSeriesType.setEnabled( bOutXtab && isTwoAxesEnabled( ) ); } } else { if ( cbMultipleY != null ) { cbMultipleY.select( 0 ); ( (ChartWizardContext) getContext( ) ).setMoreAxesSupported( false ); lblMultipleY.setEnabled( false ); cbMultipleY.setEnabled( false ); } if ( cbSeriesType != null ) { lblSeriesType.setEnabled( false ); cbSeriesType.setEnabled( false ); } } if ( cbOrientation != null ) { lblOrientation.setEnabled( bOutXtab && lblOrientation.isEnabled( ) ); cbOrientation.setEnabled( bOutXtab && cbOrientation.isEnabled( ) ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.frameworks.taskwizard.interfaces.ITask#getContext() */ public IWizardContext getContext( ) { ChartWizardContext context = (ChartWizardContext) super.getContext( ); context.setModel( this.chartModel ); return context; } /* * (non-Javadoc) * * @see org.eclipse.birt.frameworks.taskwizard.interfaces.ITask#setContext(org.eclipse.birt.frameworks.taskwizard.interfaces.IWizardContext) */ public void setContext( IWizardContext context ) { super.setContext( context ); this.chartModel = ( (ChartWizardContext) context ).getModel( ); if ( chartModel != null ) { this.sType = ( (ChartWizardContext) context ).getChartType( ) .getName( ); this.sSubType = chartModel.getSubType( ); this.sDimension = translateDimensionString( chartModel.getDimension( ) .getName( ) ); if ( chartModel instanceof ChartWithAxes ) { this.orientation = ( (ChartWithAxes) chartModel ).getOrientation( ); int iYAxesCount = ChartUIUtil.getOrthogonalAxisNumber( chartModel ); // IF THE UI HAS BEEN INITIALIZED...I.E. IF setContext() IS // CALLED AFTER getUI() if ( iYAxesCount > 1 && ( lblMultipleY != null && !lblMultipleY.isDisposed( ) ) ) { lblMultipleY.setEnabled( !is3D( ) ); cbMultipleY.setEnabled( !is3D( ) ); lblSeriesType.setEnabled( !is3D( ) && isTwoAxesEnabled( ) ); cbSeriesType.setEnabled( !is3D( ) && isTwoAxesEnabled( ) ); selectMultipleAxis( iYAxesCount ); // TODO: Update the series type based on series type for the // second Y axis } } } } private void selectMultipleAxis( int yAxisNum ) { if ( ( (ChartWizardContext) getContext( ) ).isMoreAxesSupported( ) ) { cbMultipleY.select( 2 ); } else { if ( yAxisNum > 2 ) { cbMultipleY.select( 2 ); ( (ChartWizardContext) getContext( ) ).setMoreAxesSupported( true ); } else { cbMultipleY.select( yAxisNum > 0 ? yAxisNum - 1 : 0 ); } } } public void changeTask( Notification notification ) { doPreview( ); } private void checkDataTypeForChartWithAxes( Chart cm ) { // To check the data type of base series and orthogonal series in chart // with axes List sdList = new ArrayList( ); sdList.addAll( ChartUIUtil.getBaseSeriesDefinitions( cm ) ); for ( int i = 0; i < sdList.size( ); i++ ) { SeriesDefinition sd = (SeriesDefinition) sdList.get( i ); Series series = sd.getDesignTimeSeries( ); checkDataTypeForBaseSeries( ChartUIUtil.getDataQuery( sd, 0 ), series ); } sdList.clear( ); sdList.addAll( ChartUIUtil.getAllOrthogonalSeriesDefinitions( cm ) ); for ( int i = 0; i < sdList.size( ); i++ ) { SeriesDefinition sd = (SeriesDefinition) sdList.get( i ); Series series = sd.getDesignTimeSeries( ); checkDataTypeForOrthoSeries( ChartUIUtil.getDataQuery( sd, 0 ), series ); } } protected IDataServiceProvider getDataServiceProvider( ) { return ( (ChartWizardContext) getContext( ) ).getDataServiceProvider( ); } private String getSubtypeFromButton( Control button ) { return (String) button.getData( ); } private void checkDataTypeForBaseSeries( Query query, Series series ) { checkDataTypeImpl( query, series, true ); } private void checkDataTypeForOrthoSeries( Query query, Series series ) { checkDataTypeImpl( query, series, false ); } private void checkDataTypeImpl( Query query, Series series, boolean isBaseSeries ) { String expression = query.getDefinition( ); Axis axis = null; for ( EObject o = query; o != null; ) { o = o.eContainer( ); if ( o instanceof Axis ) { axis = (Axis) o; break; } } Collection<ISeriesUIProvider> cRegisteredEntries = ChartUIExtensionsImpl.instance( ) .getSeriesUIComponents( getContext( ).getClass( ).getSimpleName( ) ); Iterator<ISeriesUIProvider> iterEntries = cRegisteredEntries.iterator( ); String sSeries = null; while ( iterEntries.hasNext( ) ) { ISeriesUIProvider provider = iterEntries.next( ); sSeries = provider.getSeriesClass( ); if ( sSeries.equals( series.getClass( ).getName( ) ) ) { if ( chartModel instanceof ChartWithAxes ) { DataType dataType = getDataServiceProvider( ).getDataType( expression ); SeriesDefinition baseSD = (SeriesDefinition) ( ChartUIUtil.getBaseSeriesDefinitions( chartModel ).get( 0 ) ); SeriesDefinition orthSD = null; orthSD = (SeriesDefinition) series.eContainer( ); String aggFunc = null; try { aggFunc = ChartUtil.getAggregateFuncExpr( orthSD, baseSD ); } catch ( ChartException e ) { WizardBase.showException( e.getLocalizedMessage( ) ); } if ( baseSD != null ) { // If aggregation is set to count/distinctcount on base // series, don't change data type to numeric. if ( !isBaseSeries && baseSD != orthSD && ChartUtil.isMagicAggregate( aggFunc ) ) { dataType = DataType.NUMERIC_LITERAL; } } if ( isValidatedAxis( dataType, axis.getType( ) ) ) { break; } AxisType[] axisTypes = provider.getCompatibleAxisType( series ); for ( int i = 0; i < axisTypes.length; i++ ) { if ( isValidatedAxis( dataType, axisTypes[i] ) ) { axisNotification( axis, axisTypes[i] ); // Avoid modifying model to notify an event loop ChartAdapter.beginIgnoreNotifications( ); axis.setType( axisTypes[i] ); ChartAdapter.endIgnoreNotifications( ); break; } } } try { provider.validateSeriesBindingType( series, getDataServiceProvider( ) ); } catch ( ChartException ce ) { WizardBase.showException( Messages.getFormattedString( "TaskSelectData.Warning.TypeCheck",//$NON-NLS-1$ new String[]{ ce.getLocalizedMessage( ), series.getDisplayName( ) } ) ); } break; } } } private boolean isValidatedAxis( DataType dataType, AxisType axisType ) { if ( dataType == null ) { return true; } else if ( ( dataType == DataType.DATE_TIME_LITERAL ) && ( axisType == AxisType.DATE_TIME_LITERAL ) ) { return true; } else if ( ( dataType == DataType.NUMERIC_LITERAL ) && ( ( axisType == AxisType.LINEAR_LITERAL ) || ( axisType == AxisType.LOGARITHMIC_LITERAL ) ) ) { return true; } else if ( ( dataType == DataType.TEXT_LITERAL ) && ( axisType == AxisType.TEXT_LITERAL ) ) { return true; } return false; } private void axisNotification( Axis axis, AxisType type ) { ChartAdapter.beginIgnoreNotifications( ); { convertSampleData( axis, type ); axis.setFormatSpecifier( null ); EList markerLines = axis.getMarkerLines( ); for ( int i = 0; i < markerLines.size( ); i++ ) { ( (MarkerLine) markerLines.get( i ) ).setFormatSpecifier( null ); } EList markerRanges = axis.getMarkerRanges( ); for ( int i = 0; i < markerRanges.size( ); i++ ) { ( (MarkerRange) markerRanges.get( i ) ).setFormatSpecifier( null ); } } ChartAdapter.endIgnoreNotifications( ); } private void convertSampleData( Axis axis, AxisType axisType ) { if ( ( axis.getAssociatedAxes( ) != null ) && ( axis.getAssociatedAxes( ).size( ) != 0 ) ) { BaseSampleData bsd = (BaseSampleData) chartModel.getSampleData( ) .getBaseSampleData( ) .get( 0 ); bsd.setDataSetRepresentation( ChartUIUtil.getConvertedSampleDataRepresentation( axisType, bsd.getDataSetRepresentation( ), 0 ) ); } else { int iStartIndex = getFirstSeriesDefinitionIndexForAxis( axis ); int iEndIndex = iStartIndex + axis.getSeriesDefinitions( ).size( ); int iOSDSize = chartModel.getSampleData( ) .getOrthogonalSampleData( ) .size( ); for ( int i = 0; i < iOSDSize; i++ ) { OrthogonalSampleData osd = (OrthogonalSampleData) chartModel.getSampleData( ) .getOrthogonalSampleData( ) .get( i ); if ( osd.getSeriesDefinitionIndex( ) >= iStartIndex && osd.getSeriesDefinitionIndex( ) < iEndIndex ) { osd.setDataSetRepresentation( ChartUIUtil.getConvertedSampleDataRepresentation( axisType, osd.getDataSetRepresentation( ), i ) ); } } } } private int getFirstSeriesDefinitionIndexForAxis( Axis axis ) { List axisList = ( (Axis) ( (ChartWithAxes) chartModel ).getAxes( ) .get( 0 ) ).getAssociatedAxes( ); int index = 0; for ( int i = 0; i < axisList.size( ); i++ ) { if ( axis.equals( axisList.get( i ) ) ) { index = i; break; } } int iTmp = 0; for ( int i = 0; i < index; i++ ) { iTmp += ChartUIUtil.getAxisYForProcessing( (ChartWithAxes) chartModel, i ) .getSeriesDefinitions( ) .size( ); } return iTmp; } /* * (non-Javadoc) * * @see org.eclipse.birt.core.ui.frameworks.taskwizard.SimpleTask#getImage() */ public Image getImage( ) { return UIHelper.getImage( ChartUIConstants.IMAGE_TASK_TYPE ); } /** * Rotates Axis Title when transposing * * @param cwa * chart model */ private void rotateAxisTitle( ChartWithAxes cwa ) { boolean bRender = false; ChartAdapter.beginIgnoreNotifications( ); Axis aX = ChartUIUtil.getAxisXForProcessing( cwa ); if ( aX.getTitle( ).isVisible( ) ) { bRender = true; } double curRotation = aX.getTitle( ) .getCaption( ) .getFont( ) .getRotation( ); aX.getTitle( ) .getCaption( ) .getFont( ) .setRotation( curRotation >= 0 ? 90 - curRotation : -90 - curRotation ); EList aYs = aX.getAssociatedAxes( ); for ( int i = 0; i < aYs.size( ); i++ ) { Axis aY = (Axis) aYs.get( i ); if ( aY.getTitle( ).isVisible( ) ) { bRender = true; } curRotation = aY.getTitle( ).getCaption( ).getFont( ).getRotation( ); aY.getTitle( ) .getCaption( ) .getFont( ) .setRotation( curRotation >= 0 ? 90 - curRotation : -90 - curRotation ); } ChartAdapter.endIgnoreNotifications( ); if ( bRender ) { doPreview( ); } } public IChartPreviewPainter createPreviewPainter( ) { ChartPreviewPainter painter = new ChartPreviewPainter( (ChartWizardContext) getContext( ) ); getPreviewCanvas( ).addPaintListener( painter ); getPreviewCanvas( ).addControlListener( painter ); painter.setPreview( getPreviewCanvas( ) ); return painter; } public void doPreview( ) { ChartUIUtil.prepareLivePreview( chartModel, getDataServiceProvider( ) ); // Repaint chart. if ( previewPainter != null ) { // To update data type after chart type conversion if ( chartModel instanceof ChartWithAxes ) { ChartAdapter.beginIgnoreNotifications( ); checkDataTypeForChartWithAxes( chartModel ); ChartAdapter.endIgnoreNotifications( ); } previewPainter.renderModel( chartModel ); } } public Canvas getPreviewCanvas( ) { return previewCanvas; } public boolean isPreviewable( ) { return true; } protected IChartType getCurrentChartType( ) { return htTypes.get( sType ); } private void createUIDescriptors( Composite parent ) { for ( TaskSelectTypeUIDescriptor descriptor : lstDescriptor ) { if ( descriptor.isVisible( ) ) { descriptor.createControl( parent ); } } } protected final void addTypeUIDescriptor( TaskSelectTypeUIDescriptor newDescriptor ) { if ( newDescriptor.getIndex( ) < 0 ) { // add to the last if it's negative lstDescriptor.add( newDescriptor ); return; } int lastIndex = -1; for ( int i = 0; i < lstDescriptor.size( ); i++ ) { TaskSelectTypeUIDescriptor descriptor = lstDescriptor.get( i ); if ( newDescriptor.getIndex( ) > lastIndex && newDescriptor.getIndex( ) <= descriptor.getIndex( ) ) { lstDescriptor.add( i, newDescriptor ); return; } lastIndex = descriptor.getIndex( ); } lstDescriptor.add( newDescriptor ); } protected void addOptionalUIDescriptor( ) { addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) { public int getIndex( ) { return 20; } public void createControl( Composite parent ) { Label lblOutput = new Label( parent, SWT.WRAP ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalIndent = 10; lblOutput.setLayoutData( gd ); lblOutput.setText( Messages.getString( "TaskSelectType.Label.OutputFormat" ) ); //$NON-NLS-1$ } // Add the ComboBox for Output Format final Combo cbOutput = new Combo( parent, SWT.DROP_DOWN | SWT.READ_ONLY ); { GridData gd = new GridData( GridData.FILL_HORIZONTAL ); cbOutput.setLayoutData( gd ); cbOutput.addListener( SWT.Selection, new Listener( ) { public void handleEvent( Event event ) { String outputFormat = outputFormats[cbOutput.getSelectionIndex( )]; ( (ChartWizardContext) getContext( ) ).setOutputFormat( outputFormat ); // Update apply button if ( container != null && container instanceof ChartWizard ) { ( (ChartWizard) container ).updateApplyButton( ); } } } ); } cbOutput.setItems( outputDisplayNames ); String sCurrentFormat = ( (ChartWizardContext) getContext( ) ).getOutputFormat( ); for ( int index = 0; index < outputFormats.length; index++ ) { if ( outputFormats[index].equals( sCurrentFormat ) ) { cbOutput.select( index ); break; } } } } ); } }
Fix Bugzilla#254981:Secondary Y-axis format is reset when viewing chart type tab on multiple Y-axis line or area chart.
chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/TaskSelectType.java
Fix Bugzilla#254981:Secondary Y-axis format is reset when viewing chart type tab on multiple Y-axis line or area chart.
<ide><path>hart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/TaskSelectType.java <ide> ChartAdapter.beginIgnoreNotifications( ); <ide> for ( int i = 0; i < iOverlaySeriesCount; i++ ) <ide> { <del> Series newSeries = (Series) EcoreUtil.copy( htSeriesNames.get( cbSeriesType.getText( ) ) ); <del> newSeries.translateFrom( ( (SeriesDefinition) ( (Axis) XAxis.getAssociatedAxes( ) <del> .get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getDesignTimeSeries( ), <del> iSeriesDefinitionIndex, <del> chartModel ); <del> // ADD THE MODEL ADAPTERS TO THE NEW SERIES <del> newSeries.eAdapters( ).addAll( chartModel.eAdapters( ) ); <del> // UPDATE THE SERIES DEFINITION WITH THE SERIES INSTANCE <del> ( (SeriesDefinition) ( (Axis) XAxis.getAssociatedAxes( ) <del> .get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getSeries( ) <del> .clear( ); <del> ( (SeriesDefinition) ( (Axis) XAxis.getAssociatedAxes( ) <del> .get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getSeries( ) <del> .add( newSeries ); <del> ChartUIUtil.setSeriesName( chartModel ); <add> Series lastSeries = ( (SeriesDefinition) ( (Axis) XAxis.getAssociatedAxes( ) <add> .get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getDesignTimeSeries( ); <add> if ( !lastSeries.getDisplayName( ) <add> .equals( cbSeriesType.getText( ) ) ) <add> { <add> Series newSeries = (Series) EcoreUtil.copy( htSeriesNames.get( cbSeriesType.getText( ) ) ); <add> newSeries.translateFrom( lastSeries, <add> iSeriesDefinitionIndex, <add> chartModel ); <add> // ADD THE MODEL ADAPTERS TO THE NEW SERIES <add> newSeries.eAdapters( ).addAll( chartModel.eAdapters( ) ); <add> // UPDATE THE SERIES DEFINITION WITH THE SERIES INSTANCE <add> ( (SeriesDefinition) ( (Axis) XAxis.getAssociatedAxes( ) <add> .get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getSeries( ) <add> .clear( ); <add> ( (SeriesDefinition) ( (Axis) XAxis.getAssociatedAxes( ) <add> .get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getSeries( ) <add> .add( newSeries ); <add> ChartUIUtil.setSeriesName( chartModel ); <add> } <ide> } <ide> } <ide> catch ( Exception e )
Java
mit
f8ee3c1aa0bd3ed13a9575cbdeffea7028f1b7d3
0
kentwang/algs4,kentwang/algs4,kentwang/algs4
/***************************************************************************** * Compilation: javac-algs4 Percolation.java * Executtion: java-algs4 Percolation * * Percolation system class "Percolation" */ /** * */ public class Percolation { private int[] states; // states of all cells, 0/1 private int dim; // dimension of the percolation private WeightedQuickUnionUF cells; /*************************************************/ /* Define public methods for the Percolation API */ /** * Initializes an empty Percolation class "Percolation" with all sites closed * @param N, dimension of the system */ public Percolation(int N) { states = new int[N * N + 2]; // SYNTAX, avoid NULL dim = N; cells = new WeightedQuickUnionUF(N * N + 2); // SYNTAX, additional top and bottom cells for (int j = 0; j < N * N; j++) { states[j] = 0; } states[N * N] = 1; states[N * N + 1] = 1; } /** * open the site (i, j) if it is not open */ public void open(int i, int j) { isInRange(i, j); // validate indice if (isOpen(i, j)) return; int siteIndex = coord2Index(i, j); // index of new site states[siteIndex] = 1; // open site (i, j) /** union to top/bottom if first/last row **/ if(i == 1) cell.union(siteIndex, dim * dim); if(i == dim) cell.union(siteIndex, dim * dim + 1); /** union neighbor cells **/ if (inRangeBoolean(i - 1, j) && isOpen(i - 1, j)) cells.union(coord2Index(i - 1, j), siteIndex); if (inRangeBoolean(i + 1, j) && isOpen(i + 1, j)) cells.union(coord2Index(i + 1, j), siteIndex); if (inRangeBoolean(i, j - 1) && isOpen(i, j - 1)) cells.union(coord2Index(i, j - 1), siteIndex); if (inRangeBoolean(i, j + 1) && isOpen(i, j + 1)) cells.union(coord2Index(i, j + 1), siteIndex); } /** * check if site (i, j) is open */ public boolean isOpen(int i, int j) { return states[coord2Index(i, j)] == 1; } /** * check if site (i, j) is full, connected to the top cell */ public boolean isFull(int i, int j) { isInRange(i, j); return cells.connected(coord2Index(i, j), dim * dim); } /** * check if the system can percolate */ public boolean percolates() { return cells.connected(dim * dim, dim * dim + 1); } /****************************************/ /* Define private methods for the class */ /** * check if the location (i, j) is with in our range */ private void isInRange(int i, int j) { if (i <= 0 || i > dim || j <= 0 || j > dim) throw new IndexOutOfBoundsException(); } private boolean inRangeBoolean(int i, int j) { return !(i <= 0 || i > dim || j <= 0 || j > dim); } /** * Translate (i, j) to index */ private int coord2Index(int i, int j) { return (i - 1) * dim + j - 1; } /** * A test main function */ public static void main(String[] args) { int N = StdIn.readInt(); Percolation percolationItem = new Percolation(N); /** * test public interfatces */ while (!StdIn.isEmpty()) { int i = StdIn.readInt(); int j = StdIn.readInt(); percolationItem.open(i, j); } StdOut.println(percolationItem.percolates()); } }
perlocation/Percolation.java
/***************************************************************************** * Compilation: javac-algs4 Percolation.java * Executtion: java-algs4 Percolation * * Percolation system class "Percolation" */ /** * */ public class Percolation { private int[] states; // states of all cells, 0/1 private int dim; // dimension of the percolation private WeightedQuickUnionUF cells; /*************************************************/ /* Define public methods for the Percolation API */ /** * Initializes an empty Percolation class "Percolation" with all sites closed * @param N, dimension of the system */ public Percolation(int N) { states = new int[N * N + 2]; // SYNTAX, avoid NULL dim = N; cells = new WeightedQuickUnionUF(N * N + 2); // SYNTAX, additional top and bottom cells for (int j = 0; j < N * N; j++) { states[j] = 0; } states[N * N] = 1; states[N * N + 1] = 1; for (int k = 0; k < dim; k++) { // union top and bottom 5 to top and bottom cells.union(k, dim * dim); // union top cells.union(dim * dim - k - 1, dim * dim + 1); // union bottom } } /** * open the site (i, j) if it is not open */ public void open(int i, int j) { isInRange(i, j); // validate indice if (isOpen(i, j)) return; states[coord2Index(i, j)] = 1; /** union neighbor cells **/ if (inRangeBoolean(i - 1, j) && isOpen(i - 1, j)) cells.union(coord2Index(i - 1, j), coord2Index(i, j)); if (inRangeBoolean(i + 1, j) && isOpen(i + 1, j)) cells.union(coord2Index(i + 1, j), coord2Index(i, j)); if (inRangeBoolean(i, j - 1) && isOpen(i, j - 1)) cells.union(coord2Index(i, j - 1), coord2Index(i, j)); if (inRangeBoolean(i, j + 1) && isOpen(i, j + 1)) cells.union(coord2Index(i, j + 1), coord2Index(i, j)); } /** * check if site (i, j) is open */ public boolean isOpen(int i, int j) { return states[coord2Index(i, j)] == 1; } /** * check if site (i, j) is full, connected to the top cell */ public boolean isFull(int i, int j) { isInRange(i, j); return cells.connected(coord2Index(i, j), dim * dim); } /** * check if the system can percolate */ public boolean percolates() { return cells.connected(dim * dim, dim * dim + 1); } /****************************************/ /* Define private methods for the class */ /** * check if the location (i, j) is with in our range */ private void isInRange(int i, int j) { if (i <= 0 || i > dim || j <= 0 || j > dim) throw new IndexOutOfBoundsException(); } private boolean inRangeBoolean(int i, int j) { return !(i <= 0 || i > dim || j <= 0 || j > dim); } /** * Translate (i, j) to index */ private int coord2Index(int i, int j) { return (i - 1) * dim + j - 1; } /** * A test main function */ public static void main(String[] args) { int N = StdIn.readInt(); Percolation percolationItem = new Percolation(N); /** * test public interfatces */ while (!StdIn.isEmpty()) { int i = StdIn.readInt(); int j = StdIn.readInt(); percolationItem.open(i, j); } StdOut.println(percolationItem.percolates()); } }
Initialization doesn't connect first/last row to top/bottom
perlocation/Percolation.java
Initialization doesn't connect first/last row to top/bottom
<ide><path>erlocation/Percolation.java <ide> } <ide> states[N * N] = 1; <ide> states[N * N + 1] = 1; <del> for (int k = 0; k < dim; k++) { // union top and bottom 5 to top and bottom <del> cells.union(k, dim * dim); // union top <del> cells.union(dim * dim - k - 1, dim * dim + 1); // union bottom <del> } <ide> } <ide> <ide> /** <ide> public void open(int i, int j) { <ide> isInRange(i, j); // validate indice <ide> if (isOpen(i, j)) return; <del> states[coord2Index(i, j)] = 1; <add> int siteIndex = coord2Index(i, j); // index of new site <add> states[siteIndex] = 1; // open site (i, j) <add> <add> /** union to top/bottom if first/last row **/ <add> if(i == 1) cell.union(siteIndex, dim * dim); <add> if(i == dim) cell.union(siteIndex, dim * dim + 1); <add> <ide> /** union neighbor cells **/ <ide> if (inRangeBoolean(i - 1, j) && isOpen(i - 1, j)) <del> cells.union(coord2Index(i - 1, j), coord2Index(i, j)); <add> cells.union(coord2Index(i - 1, j), siteIndex); <ide> if (inRangeBoolean(i + 1, j) && isOpen(i + 1, j)) <del> cells.union(coord2Index(i + 1, j), coord2Index(i, j)); <add> cells.union(coord2Index(i + 1, j), siteIndex); <ide> if (inRangeBoolean(i, j - 1) && isOpen(i, j - 1)) <del> cells.union(coord2Index(i, j - 1), coord2Index(i, j)); <add> cells.union(coord2Index(i, j - 1), siteIndex); <ide> if (inRangeBoolean(i, j + 1) && isOpen(i, j + 1)) <del> cells.union(coord2Index(i, j + 1), coord2Index(i, j)); <add> cells.union(coord2Index(i, j + 1), siteIndex); <ide> } <ide> <ide> /**
Java
epl-1.0
error: pathspec 'rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/rules/DiscoverEmbeddedJSFHibernateLibraryRuleProvider.java' did not match any file(s) known to git
9bc19d7a0b352c7ab1945450f70c94ca52b942e9
1
johnsteele/windup,OndraZizka/windup,johnsteele/windup,windup/windup,jsight/windup,OndraZizka/windup,OndraZizka/windup,johnsteele/windup,windup/windup,johnsteele/windup,OndraZizka/windup,jsight/windup,Maarc/windup,windup/windup,Maarc/windup,Maarc/windup,jsight/windup,windup/windup,jsight/windup,Maarc/windup
package org.jboss.windup.rules.apps.javaee.rules; import org.jboss.windup.config.AbstractRuleProvider; import org.jboss.windup.config.GraphRewrite; import org.jboss.windup.config.loader.RuleLoaderContext; import org.jboss.windup.config.metadata.RuleMetadata; import org.jboss.windup.config.operation.iteration.AbstractIterationOperation; import org.jboss.windup.config.phase.InitialAnalysisPhase; import org.jboss.windup.config.query.Query; import org.jboss.windup.config.query.QueryPropertyComparisonType; import org.jboss.windup.graph.GraphContext; import org.jboss.windup.graph.model.LinkModel; import org.jboss.windup.graph.model.resource.FileModel; import org.jboss.windup.graph.service.LinkService; import org.jboss.windup.reporting.category.IssueCategoryRegistry; import org.jboss.windup.reporting.model.ClassificationModel; import org.jboss.windup.reporting.model.TechnologyTagLevel; import org.jboss.windup.reporting.service.ClassificationService; import org.jboss.windup.reporting.service.TechnologyTagService; import org.jboss.windup.rules.apps.java.model.JarArchiveModel; import org.ocpsoft.rewrite.config.Configuration; import org.ocpsoft.rewrite.config.ConfigurationBuilder; import org.ocpsoft.rewrite.context.EvaluationContext; @RuleMetadata(phase = InitialAnalysisPhase.class, perform = "Discover Java libraries embedded") public class DiscoverEmbeddedJSFHibernateLibraryRuleProvider extends AbstractRuleProvider { @Override public Configuration getConfiguration(RuleLoaderContext context) { String ruleIDPrefix = getClass().getSimpleName(); int ruleIDSuffix = 1; return ConfigurationBuilder.begin() .addRule() .when(Query.fromType(JarArchiveModel.class) .withProperty(FileModel.FILE_PATH, QueryPropertyComparisonType.REGEX, ".*WEB-INF/lib/.*hibernate.*\\.jar$")) .perform( new AbstractIterationOperation<JarArchiveModel>() { public void perform(GraphRewrite event, EvaluationContext context, JarArchiveModel fileResourceModel) { ClassificationService classificationService = new ClassificationService(event.getGraphContext()); ClassificationModel classificationModel = classificationService.attachClassification(event, context, fileResourceModel, IssueCategoryRegistry.MANDATORY, "Hibernate embedded library", "The application has a Hibernate library embedded. \n" + "Red Hat JBoss EAP brings Hibernate library as a module with a version that has been tested and supported by Red Hat. (ref. link \"Red Hat JBoss EAP: Component Details\"). \n" + "There are two options for using the Hibernate library: \n" + "\n" + "1. to keep it embedded as it is now: this approach is low effort but the application does not use a tested and supported library. \n" + "2. to switch to use the Hibernate library in the EAP module: there's the effort to remove the embedded library and configure the application to use the module's library but then the application will rely on a tested and supported version of the Hibernate library. \n" + "\n" + "In the links below there are the informations needed for both EAP 6 and 7."); classificationModel.setEffort(3); GraphContext graphContext = event.getGraphContext(); LinkService linkService = new LinkService(graphContext); LinkModel componentDetailsLink = linkService.create(); componentDetailsLink.setDescription("Red Hat JBoss EAP: Component Details"); componentDetailsLink.setLink("https://access.redhat.com/articles/112673"); classificationService.attachLink(classificationModel, componentDetailsLink); LinkModel documentationEAP6Link = linkService.create(); documentationEAP6Link.setDescription("Red Hat JBoss EAP 6: Hibernate and JPA Migration Changes"); documentationEAP6Link.setLink( "https://access.redhat.com/documentation/en-US/JBoss_Enterprise_Application_Platform/6.4/html/Migration_Guide/sect-Changes_Dependent_on_Your_Application_Architecture_and_Components.html#sect-Hibernate_and_JPA_Changes"); classificationService.attachLink(classificationModel, documentationEAP6Link); LinkModel documentationEAP7Link = linkService.create(); documentationEAP7Link.setDescription("Red Hat JBoss EAP 7: Hibernate and JPA Migration Changes"); documentationEAP7Link.setLink( "https://access.redhat.com/documentation/en-us/red_hat_jboss_enterprise_application_platform/7.0/html/migration_guide/application_migration_changes#hibernate_and_jpa_migration_changes"); classificationService.attachLink(classificationModel, documentationEAP7Link); TechnologyTagService technologyTagService = new TechnologyTagService(event.getGraphContext()); technologyTagService.addTagToFileModel(fileResourceModel, "Hibernate embedded JAR library", TechnologyTagLevel.INFORMATIONAL); } }) .withId(ruleIDPrefix + "_" + ruleIDSuffix++) .addRule() .when(Query.fromType(JarArchiveModel.class) .withProperty(FileModel.FILE_PATH, QueryPropertyComparisonType.REGEX, ".*WEB-INF/lib/.*jsf.*\\.jar$")) .perform( new AbstractIterationOperation<JarArchiveModel>() { public void perform(GraphRewrite event, EvaluationContext context, JarArchiveModel fileResourceModel) { ClassificationService classificationService = new ClassificationService(event.getGraphContext()); ClassificationModel classificationModel = classificationService.attachClassification(event, context, fileResourceModel, IssueCategoryRegistry.MANDATORY, "JSF embedded library", "The application has a JSF library embedded. \n" + "Red Hat JBoss EAP brings JSF library as a module with a version that has been tested and supported by Red Hat. (ref. link \"Red Hat JBoss EAP: Component Details\"). \n" + "There are two options for using the JSF library: \n" + "\n" + "1. to keep it embedded as it is now: this approach is low effort but the application does not use a tested and supported library. \n" + "2. to switch to use the JSF library in the EAP module: there's the effort to remove the embedded library and configure the application to use the module's library but then the application will rely on a tested and supported version of the JSF library. \n" + "\n" + "In the links below there are the informations needed for both EAP 6 and 7."); classificationModel.setEffort(3); GraphContext graphContext = event.getGraphContext(); LinkService linkService = new LinkService(graphContext); LinkModel componentDetailsLink = linkService.create(); componentDetailsLink.setDescription("Red Hat JBoss EAP: Component Details"); componentDetailsLink.setLink("https://access.redhat.com/articles/112673"); classificationService.attachLink(classificationModel, componentDetailsLink); LinkModel documentationEAP6Link = linkService.create(); documentationEAP6Link.setDescription("Red Hat JBoss EAP 6: JavaServer Faces (JSF) Code Changes"); documentationEAP6Link.setLink( "https://access.redhat.com/documentation/en-US/JBoss_Enterprise_Application_Platform/6.4/html/Migration_Guide/sect-Changes_Dependent_on_Your_Application_Architecture_and_Components.html#sect-JSF_changes"); classificationService.attachLink(classificationModel, documentationEAP6Link); LinkModel jsf12WithEAP6Link = linkService.create(); jsf12WithEAP6Link.setDescription("How to use JSF 1.2 with EAP 6"); jsf12WithEAP6Link.setLink("https://access.redhat.com/solutions/690953"); classificationService.attachLink(classificationModel, jsf12WithEAP6Link); LinkModel documentationEAP7Link = linkService.create(); documentationEAP7Link.setDescription("Red Hat JBoss EAP 7: JavaServer Faces (JSF) Code Changes"); documentationEAP7Link.setLink( "https://access.redhat.com/documentation/en-us/red_hat_jboss_enterprise_application_platform/7.0/html/migration_guide/application_migration_changes#migrate_jsf_code_changes"); classificationService.attachLink(classificationModel, documentationEAP7Link); LinkModel jsf12WithEAP7Link = linkService.create(); jsf12WithEAP7Link.setDescription("How to use JSF 1.2 with EAP 7?"); jsf12WithEAP7Link.setLink("https://access.redhat.com/solutions/2773121"); classificationService.attachLink(classificationModel, jsf12WithEAP7Link); TechnologyTagService technologyTagService = new TechnologyTagService(event.getGraphContext()); technologyTagService.addTagToFileModel(fileResourceModel, "Embedded JAR library", TechnologyTagLevel.INFORMATIONAL); } }) .withId(ruleIDPrefix + "_" + ruleIDSuffix++); } }
rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/rules/DiscoverEmbeddedJSFHibernateLibraryRuleProvider.java
WINDUPRULE-226 Rule for Detecting Hibernate and JSF embedded library
rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/rules/DiscoverEmbeddedJSFHibernateLibraryRuleProvider.java
WINDUPRULE-226 Rule for Detecting Hibernate and JSF embedded library
<ide><path>ules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/rules/DiscoverEmbeddedJSFHibernateLibraryRuleProvider.java <add>package org.jboss.windup.rules.apps.javaee.rules; <add> <add>import org.jboss.windup.config.AbstractRuleProvider; <add>import org.jboss.windup.config.GraphRewrite; <add>import org.jboss.windup.config.loader.RuleLoaderContext; <add>import org.jboss.windup.config.metadata.RuleMetadata; <add>import org.jboss.windup.config.operation.iteration.AbstractIterationOperation; <add>import org.jboss.windup.config.phase.InitialAnalysisPhase; <add>import org.jboss.windup.config.query.Query; <add>import org.jboss.windup.config.query.QueryPropertyComparisonType; <add>import org.jboss.windup.graph.GraphContext; <add>import org.jboss.windup.graph.model.LinkModel; <add>import org.jboss.windup.graph.model.resource.FileModel; <add>import org.jboss.windup.graph.service.LinkService; <add>import org.jboss.windup.reporting.category.IssueCategoryRegistry; <add>import org.jboss.windup.reporting.model.ClassificationModel; <add>import org.jboss.windup.reporting.model.TechnologyTagLevel; <add>import org.jboss.windup.reporting.service.ClassificationService; <add>import org.jboss.windup.reporting.service.TechnologyTagService; <add>import org.jboss.windup.rules.apps.java.model.JarArchiveModel; <add>import org.ocpsoft.rewrite.config.Configuration; <add>import org.ocpsoft.rewrite.config.ConfigurationBuilder; <add>import org.ocpsoft.rewrite.context.EvaluationContext; <add> <add>@RuleMetadata(phase = InitialAnalysisPhase.class, perform = "Discover Java libraries embedded") <add>public class DiscoverEmbeddedJSFHibernateLibraryRuleProvider extends AbstractRuleProvider <add>{ <add> <add> @Override <add> public Configuration getConfiguration(RuleLoaderContext context) <add> { <add> String ruleIDPrefix = getClass().getSimpleName(); <add> int ruleIDSuffix = 1; <add> return ConfigurationBuilder.begin() <add> .addRule() <add> .when(Query.fromType(JarArchiveModel.class) <add> .withProperty(FileModel.FILE_PATH, QueryPropertyComparisonType.REGEX, ".*WEB-INF/lib/.*hibernate.*\\.jar$")) <add> .perform( <add> new AbstractIterationOperation<JarArchiveModel>() <add> { <add> public void perform(GraphRewrite event, EvaluationContext context, JarArchiveModel fileResourceModel) <add> { <add> ClassificationService classificationService = new ClassificationService(event.getGraphContext()); <add> ClassificationModel classificationModel = classificationService.attachClassification(event, context, <add> fileResourceModel, <add> IssueCategoryRegistry.MANDATORY, <add> "Hibernate embedded library", <add> "The application has a Hibernate library embedded. \n" <add> + "Red Hat JBoss EAP brings Hibernate library as a module with a version that has been tested and supported by Red Hat. (ref. link \"Red Hat JBoss EAP: Component Details\"). \n" <add> + "There are two options for using the Hibernate library: \n" <add> + "\n" <add> + "1. to keep it embedded as it is now: this approach is low effort but the application does not use a tested and supported library. \n" <add> + "2. to switch to use the Hibernate library in the EAP module: there's the effort to remove the embedded library and configure the application to use the module's library but then the application will rely on a tested and supported version of the Hibernate library. \n" <add> + "\n" <add> + "In the links below there are the informations needed for both EAP 6 and 7."); <add> classificationModel.setEffort(3); <add> GraphContext graphContext = event.getGraphContext(); <add> LinkService linkService = new LinkService(graphContext); <add> LinkModel componentDetailsLink = linkService.create(); <add> componentDetailsLink.setDescription("Red Hat JBoss EAP: Component Details"); <add> componentDetailsLink.setLink("https://access.redhat.com/articles/112673"); <add> classificationService.attachLink(classificationModel, componentDetailsLink); <add> <add> LinkModel documentationEAP6Link = linkService.create(); <add> documentationEAP6Link.setDescription("Red Hat JBoss EAP 6: Hibernate and JPA Migration Changes"); <add> documentationEAP6Link.setLink( <add> "https://access.redhat.com/documentation/en-US/JBoss_Enterprise_Application_Platform/6.4/html/Migration_Guide/sect-Changes_Dependent_on_Your_Application_Architecture_and_Components.html#sect-Hibernate_and_JPA_Changes"); <add> classificationService.attachLink(classificationModel, documentationEAP6Link); <add> LinkModel documentationEAP7Link = linkService.create(); <add> documentationEAP7Link.setDescription("Red Hat JBoss EAP 7: Hibernate and JPA Migration Changes"); <add> documentationEAP7Link.setLink( <add> "https://access.redhat.com/documentation/en-us/red_hat_jboss_enterprise_application_platform/7.0/html/migration_guide/application_migration_changes#hibernate_and_jpa_migration_changes"); <add> classificationService.attachLink(classificationModel, documentationEAP7Link); <add> <add> TechnologyTagService technologyTagService = new TechnologyTagService(event.getGraphContext()); <add> technologyTagService.addTagToFileModel(fileResourceModel, "Hibernate embedded JAR library", <add> TechnologyTagLevel.INFORMATIONAL); <add> <add> } <add> }) <add> .withId(ruleIDPrefix + "_" + ruleIDSuffix++) <add> .addRule() <add> .when(Query.fromType(JarArchiveModel.class) <add> .withProperty(FileModel.FILE_PATH, QueryPropertyComparisonType.REGEX, ".*WEB-INF/lib/.*jsf.*\\.jar$")) <add> .perform( <add> new AbstractIterationOperation<JarArchiveModel>() <add> { <add> public void perform(GraphRewrite event, EvaluationContext context, JarArchiveModel fileResourceModel) <add> { <add> ClassificationService classificationService = new ClassificationService(event.getGraphContext()); <add> ClassificationModel classificationModel = classificationService.attachClassification(event, context, <add> fileResourceModel, <add> IssueCategoryRegistry.MANDATORY, <add> "JSF embedded library", <add> "The application has a JSF library embedded. \n" <add> + "Red Hat JBoss EAP brings JSF library as a module with a version that has been tested and supported by Red Hat. (ref. link \"Red Hat JBoss EAP: Component Details\"). \n" <add> + "There are two options for using the JSF library: \n" <add> + "\n" <add> + "1. to keep it embedded as it is now: this approach is low effort but the application does not use a tested and supported library. \n" <add> + "2. to switch to use the JSF library in the EAP module: there's the effort to remove the embedded library and configure the application to use the module's library but then the application will rely on a tested and supported version of the JSF library. \n" <add> + "\n" <add> + "In the links below there are the informations needed for both EAP 6 and 7."); <add> classificationModel.setEffort(3); <add> GraphContext graphContext = event.getGraphContext(); <add> LinkService linkService = new LinkService(graphContext); <add> LinkModel componentDetailsLink = linkService.create(); <add> componentDetailsLink.setDescription("Red Hat JBoss EAP: Component Details"); <add> componentDetailsLink.setLink("https://access.redhat.com/articles/112673"); <add> classificationService.attachLink(classificationModel, componentDetailsLink); <add> LinkModel documentationEAP6Link = linkService.create(); <add> documentationEAP6Link.setDescription("Red Hat JBoss EAP 6: JavaServer Faces (JSF) Code Changes"); <add> documentationEAP6Link.setLink( <add> "https://access.redhat.com/documentation/en-US/JBoss_Enterprise_Application_Platform/6.4/html/Migration_Guide/sect-Changes_Dependent_on_Your_Application_Architecture_and_Components.html#sect-JSF_changes"); <add> classificationService.attachLink(classificationModel, documentationEAP6Link); <add> LinkModel jsf12WithEAP6Link = linkService.create(); <add> jsf12WithEAP6Link.setDescription("How to use JSF 1.2 with EAP 6"); <add> jsf12WithEAP6Link.setLink("https://access.redhat.com/solutions/690953"); <add> classificationService.attachLink(classificationModel, jsf12WithEAP6Link); <add> LinkModel documentationEAP7Link = linkService.create(); <add> documentationEAP7Link.setDescription("Red Hat JBoss EAP 7: JavaServer Faces (JSF) Code Changes"); <add> documentationEAP7Link.setLink( <add> "https://access.redhat.com/documentation/en-us/red_hat_jboss_enterprise_application_platform/7.0/html/migration_guide/application_migration_changes#migrate_jsf_code_changes"); <add> classificationService.attachLink(classificationModel, documentationEAP7Link); <add> LinkModel jsf12WithEAP7Link = linkService.create(); <add> jsf12WithEAP7Link.setDescription("How to use JSF 1.2 with EAP 7?"); <add> jsf12WithEAP7Link.setLink("https://access.redhat.com/solutions/2773121"); <add> classificationService.attachLink(classificationModel, jsf12WithEAP7Link); <add> <add> TechnologyTagService technologyTagService = new TechnologyTagService(event.getGraphContext()); <add> technologyTagService.addTagToFileModel(fileResourceModel, "Embedded JAR library", <add> TechnologyTagLevel.INFORMATIONAL); <add> <add> } <add> }) <add> .withId(ruleIDPrefix + "_" + ruleIDSuffix++); <add> } <add> <add>}
JavaScript
mit
5d7a85afd8cafff30b13fa63d20f78d9830d6c2b
0
SerkanSipahi/app-decorators,SerkanSipahi/app-decorators
system.config.js
System.config({ globalEvaluationScope: false });
removed unused system.config.js
system.config.js
removed unused system.config.js
<ide><path>ystem.config.js <del>System.config({ globalEvaluationScope: false });
Java
agpl-3.0
1eaffba3172052637544c22a4a34ba8a88cbe7bb
0
MarkehMe/FactionsPlus
package markehme.factionsplus.Cmds; import org.bukkit.Location; import org.bukkit.entity.Player; import markehme.factionsplus.EssentialsIntegration; import markehme.factionsplus.Utilities; import markehme.factionsplus.Cmds.req.ReqJailsEnabled; import markehme.factionsplus.MCore.FactionData; import markehme.factionsplus.MCore.FactionDataColls; import markehme.factionsplus.MCore.LConf; import markehme.factionsplus.MCore.FPUConf; import markehme.factionsplus.util.FPPerm; import com.massivecraft.factions.cmd.req.ReqFactionsEnabled; import com.massivecraft.factions.cmd.req.ReqHasFaction; import com.massivecraft.factions.entity.UPlayer; import com.massivecraft.massivecore.cmd.req.ReqHasPerm; import com.massivecraft.massivecore.util.Txt; public class CmdUnJail extends FPCommand { public CmdUnJail() { this.aliases.add( "unjail" ); this.fpidentifier = "unjail"; this.requiredArgs.add( "player" ); this.errorOnToManyArgs = false; this.addRequirements(ReqFactionsEnabled.get()); this.addRequirements(ReqHasFaction.get()); this.addRequirements(ReqJailsEnabled.get()); this.addRequirements(ReqHasPerm.get(FPPerm.JAIL.node)); this.setHelp(LConf.get().cmdDescUnJail); this.setDesc(LConf.get().cmdDescUnJail); } @Override public void performfp() { Player jp = Utilities.getPlayer(this.arg(0)); if(jp == null) { msg(Txt.parse(LConf.get().jailsPlayerNeverOnServer)); return; } UPlayer ujPlayer = UPlayer.get(jp); if(sender instanceof Player && !usender.isUsingAdminMode()) { if(!FPUConf.get(usender.getUniverse()).whoCanJail.get(usender.getRole())) { msg(Txt.parse(LConf.get().jailsNotHighEnoughRanking)); return; } if(usender.getFactionId() != ujPlayer.getFactionId()) { msg(Txt.parse(LConf.get().jailsPlayerNotApartOfFaction, this.arg(0))); return; } } FactionData jfData = FactionDataColls.get().getForUniverse(usender.getUniverse()).get(usenderFaction.getId()); if(!jfData.isJailed(ujPlayer)) { msg(Txt.parse(LConf.get().jailsPlayerNotInJail, this.arg(0))); return; } msg(Txt.parse(LConf.get().jailsPlayerUnJailed, this.arg(0))); Location unteleportLocation = jfData.jailedPlayerIDs.get(jp.getUniqueId().toString()).asBukkitLocation(); jfData.jailedPlayerIDs.remove(jp.getUniqueId().toString()); // If the player is online remove them from the jail if(jp.isOnline()) { if(!EssentialsIntegration.handleTeleport(jp.getPlayer(), unteleportLocation)) { jp.getPlayer().teleport(unteleportLocation); } } } }
src/markehme/factionsplus/Cmds/CmdUnJail.java
package markehme.factionsplus.Cmds; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import markehme.factionsplus.EssentialsIntegration; import markehme.factionsplus.FactionsPlusJail; import markehme.factionsplus.Cmds.req.ReqJailsEnabled; import markehme.factionsplus.MCore.FactionData; import markehme.factionsplus.MCore.FactionDataColls; import markehme.factionsplus.MCore.LConf; import markehme.factionsplus.MCore.FPUConf; import markehme.factionsplus.util.FPPerm; import com.massivecraft.factions.cmd.req.ReqFactionsEnabled; import com.massivecraft.factions.cmd.req.ReqHasFaction; import com.massivecraft.factions.entity.UPlayer; import com.massivecraft.massivecore.cmd.req.ReqHasPerm; import com.massivecraft.massivecore.cmd.req.ReqIsPlayer; import com.massivecraft.massivecore.util.Txt; public class CmdUnJail extends FPCommand { public CmdUnJail() { this.aliases.add( "unjail" ); this.fpidentifier = "unjail"; this.requiredArgs.add( "player" ); this.errorOnToManyArgs = false; this.addRequirements(ReqFactionsEnabled.get()); this.addRequirements(ReqHasFaction.get()); this.addRequirements(ReqJailsEnabled.get()); this.addRequirements(ReqHasPerm.get(FPPerm.JAIL.node)); this.setHelp(LConf.get().cmdDescUnJail); this.setDesc(LConf.get().cmdDescUnJail); } @Override public void performfp() { OfflinePlayer jp = Bukkit.getPlayer(this.arg(0)); if(jp == null) { jp = Bukkit.getOfflinePlayer(this.arg(0)); } if(jp == null) { msg(Txt.parse(LConf.get().jailsPlayerNeverOnServer)); return; } UPlayer ujPlayer = UPlayer.get(jp); if(sender instanceof Player && !usender.isUsingAdminMode()) { if(!FPUConf.get(usender.getUniverse()).whoCanJail.get(usender.getRole())) { msg(Txt.parse(LConf.get().jailsNotHighEnoughRanking)); return; } if(usender.getFactionId() != ujPlayer.getFactionId()) { msg(Txt.parse(LConf.get().jailsPlayerNotApartOfFaction, this.arg(0))); return; } } FactionData jfData = FactionDataColls.get().getForUniverse(usender.getUniverse()).get(usenderFaction.getId()); if(!jfData.isJailed(ujPlayer)) { msg(Txt.parse(LConf.get().jailsPlayerNotInJail, this.arg(0))); return; } msg(Txt.parse(LConf.get().jailsPlayerUnJailed, this.arg(0))); Location unteleportLocation = jfData.jailedPlayerIDs.get(jp.getUniqueId().toString()).asBukkitLocation(); jfData.jailedPlayerIDs.remove(jp.getUniqueId().toString()); // If the player is online remove them from the jail if(jp.isOnline()) { if(!EssentialsIntegration.handleTeleport(jp.getPlayer(), unteleportLocation)) { jp.getPlayer().teleport(unteleportLocation); } } } }
Fixing this up
src/markehme/factionsplus/Cmds/CmdUnJail.java
Fixing this up
<ide><path>rc/markehme/factionsplus/Cmds/CmdUnJail.java <ide> package markehme.factionsplus.Cmds; <ide> <del>import org.bukkit.Bukkit; <ide> import org.bukkit.Location; <del>import org.bukkit.OfflinePlayer; <ide> import org.bukkit.entity.Player; <ide> <ide> import markehme.factionsplus.EssentialsIntegration; <del>import markehme.factionsplus.FactionsPlusJail; <add>import markehme.factionsplus.Utilities; <ide> import markehme.factionsplus.Cmds.req.ReqJailsEnabled; <ide> import markehme.factionsplus.MCore.FactionData; <ide> import markehme.factionsplus.MCore.FactionDataColls; <ide> import markehme.factionsplus.MCore.FPUConf; <ide> import markehme.factionsplus.util.FPPerm; <ide> <del> <ide> import com.massivecraft.factions.cmd.req.ReqFactionsEnabled; <ide> import com.massivecraft.factions.cmd.req.ReqHasFaction; <ide> import com.massivecraft.factions.entity.UPlayer; <ide> import com.massivecraft.massivecore.cmd.req.ReqHasPerm; <del>import com.massivecraft.massivecore.cmd.req.ReqIsPlayer; <ide> import com.massivecraft.massivecore.util.Txt; <del> <del> <ide> <ide> public class CmdUnJail extends FPCommand { <ide> <ide> @Override <ide> public void performfp() { <ide> <del> OfflinePlayer jp = Bukkit.getPlayer(this.arg(0)); <del> <del> if(jp == null) { <del> jp = Bukkit.getOfflinePlayer(this.arg(0)); <del> } <add> Player jp = Utilities.getPlayer(this.arg(0)); <ide> <ide> if(jp == null) { <ide> msg(Txt.parse(LConf.get().jailsPlayerNeverOnServer));
Java
apache-2.0
789e95ac2b12ea77d868a95842b322b3c2209e02
0
wjacl/ldcs,wjacl/ldcs
package com.wja.ldcs.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.wja.base.system.entity.Org; import com.wja.base.system.entity.User; import com.wja.base.system.service.OrgService; import com.wja.base.system.service.UserService; import com.wja.base.web.RequestThreadLocal; @Service public class PrivilegeControlService { @Autowired private OrgService orgService; @Autowired private UserService userService; /** * 给主播数据查询添加数据权限控制 * * @param params * @see [类、类#方法、类#成员] */ public void liveDataAddDataAuthori(Map<String, Object> params) { User user = RequestThreadLocal.currUser.get(); if (user != null) { List<Org> orgs = new ArrayList<>(); orgs.add(user.getOrg()); if (User.TYPE_LEADER.equals(user.getType())) { // 领导用户,可以查看所在部门及子部门下的经纪人下的主播 this.orgService.getAllChildOrg(user.getOrg(), orgs, null, null); this.addBrokerIdCondition(orgs, params); } else if (User.TYPE_NORMAL_STAFF.equals(user.getType())) { // 普通员工用户,只可查看所在部门的经纪人下的主播数据 this.addBrokerIdCondition(orgs, params); } else { // 经纪人,只可查看所负责的主播 params.put("brokerId_eq_String", user.getId()); } } } private void addBrokerIdCondition(List<Org> orgs, Map<String, Object> params) { List<String> ids = new ArrayList<>(); for (Org org : orgs) { ids.add(org.getId()); } Map<String, Object> p = new HashMap<String, Object>(); p.put("org.id_in_String", ids); List<User> us = this.userService.query(p); ids.clear(); for (User u : us) { ids.add(u.getId()); } params.put("brokerId_in_string", ids); } /** * 向查询条件中添加数据权限控制 * * @param params * @see [类、类#方法、类#成员] */ public void addDataAuthori(Map<String, Object> params) { User user = RequestThreadLocal.currUser.get(); if (user != null) { List<Org> orgs = new ArrayList<>(); orgs.add(user.getOrg()); if (User.TYPE_LEADER.equals(user.getType())) { // 领导用户,可以查看所在部门及子部门 this.orgService.getAllChildOrg(user.getOrg(), orgs, null, null); List<String> orgIds = new ArrayList<>(); for (Org org : orgs) { orgIds.add(org.getId()); } params.put("broker.org.id_in_String", orgIds); } else if (User.TYPE_NORMAL_STAFF.equals(user.getType())) { // 普通员工用户,只可查看所在部门人员,不可查看子部门 params.put("broker.org.id_eq_String", user.getOrg().getId()); } else { // 经纪人,只可查看所负责的主播 params.put("broker.id_eq_String", user.getId()); } } } }
ldcs/src/com/wja/ldcs/service/PrivilegeControlService.java
package com.wja.ldcs.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.wja.base.system.entity.Org; import com.wja.base.system.entity.User; import com.wja.base.system.service.OrgService; import com.wja.base.system.service.UserService; import com.wja.base.web.RequestThreadLocal; @Service public class PrivilegeControlService { @Autowired private OrgService orgService; @Autowired private UserService userService; /** * 给主播数据查询添加数据权限控制 * * @param params * @see [类、类#方法、类#成员] */ public void liveDataAddDataAuthori(Map<String, Object> params) { User user = RequestThreadLocal.currUser.get(); if (user != null) { List<Org> orgs = new ArrayList<>(); orgs.add(user.getOrg()); if (User.TYPE_LEADER.equals(user.getType())) { // 领导用户,可以查看所在部门及子部门下的经纪人下的主播 this.orgService.getAllChildOrg(user.getOrg(), orgs, null, null); this.addBrokerIdCondition(orgs, params); } else if (User.TYPE_NORMAL_STAFF.equals(user.getType())) { // 普通员工用户,只可查看所在部门的经纪人下的主播数据 this.addBrokerIdCondition(orgs, params); } else { // 经纪人,只可查看所负责的主播 params.put("brokerId_eq_String", user.getId()); } } } private void addBrokerIdCondition(List<Org> orgs, Map<String, Object> params) { List<String> ids = new ArrayList<>(); for (Org org : orgs) { ids.add(org.getId()); } Map<String, Object> p = new HashMap<String, Object>(); p.put("org.id_in_String", ids); List<User> us = this.userService.query(p); ids.clear(); for (User u : us) { ids.add(u.getId()); } params.put("brokerId_in_String", ids); } /** * 向查询条件中添加数据权限控制 * * @param params * @see [类、类#方法、类#成员] */ public void addDataAuthori(Map<String, Object> params) { User user = RequestThreadLocal.currUser.get(); if (user != null) { List<Org> orgs = new ArrayList<>(); orgs.add(user.getOrg()); if (User.TYPE_LEADER.equals(user.getType())) { // 领导用户,可以查看所在部门及子部门 this.orgService.getAllChildOrg(user.getOrg(), orgs, null, null); List<String> orgIds = new ArrayList<>(); for (Org org : orgs) { orgIds.add(org.getId()); } params.put("broker.org.id_in_String", orgIds); } else if (User.TYPE_NORMAL_STAFF.equals(user.getType())) { // 普通员工用户,只可查看所在部门人员,不可查看子部门 params.put("broker.org.id_eq_String", user.getOrg().getId()); } else { // 经纪人,只可查看所负责的主播 params.put("broker.id_eq_String", user.getId()); } } } }
修改直播数据的权限控制
ldcs/src/com/wja/ldcs/service/PrivilegeControlService.java
修改直播数据的权限控制
<ide><path>dcs/src/com/wja/ldcs/service/PrivilegeControlService.java <ide> for (User u : us) { <ide> ids.add(u.getId()); <ide> } <del> params.put("brokerId_in_String", ids); <add> params.put("brokerId_in_string", ids); <ide> } <ide> <ide> /**
JavaScript
mit
4d0247744ba09ac4e140c04210e78578f2aaf8f8
0
iuriikyian/lang-flashcards,iuriikyian/lang-flashcards,iuriikyian/lang-flashcards,iuriikyian/lang-flashcards,iuriikyian/lang-flashcards
define(['underscore', 'zepto', 'backbone'], function(_, $, Backbone){ var CardView = Backbone.View.extend({ template : _.template($('#cardView').html()), events : { 'click .content' : '_onContentClick', 'click .header .back-button' : '_onBack', 'click .header .menu-button' : '_onShowMenu', 'click .header .title .selected' : '_onToggleSelected' }, initialize : function(options){ this.card = options.card; }, render : function(){ $(this.el).empty(); $(this.el).append(this.template({ card : this.card, })); var height = $(window).height(); var headerHeight = this.$('.header').height(); var contentHeight = height - headerHeight; var $content = this.$('.content'); var $cardSide = this.$('.content .card-side'); var linesHeight = $cardSide.height(); $content.height(contentHeight); $cardSide.css({ 'padding-top' : ((contentHeight - linesHeight) / 2) + 'px' }); }, setCard : function(card){ this.card = card; }, _onBack : function(){ this.trigger('back', {}); }, _onShowMenu : function(){ this.trigger('show:menu', {}); }, _onContentClick : function(evt){ var width = $(window).width(); if(evt.clientX > width * 0.9){ return this.trigger('card:show-next'); } if(evt.clientX < width * 0.1){ return this.trigger('card:show-prev'); } return this.trigger('card:flip'); }, _onToggleSelected : function(){ var $selected = this.$('.header .title .selected'); $selected.toggleClass('fa-square-o'); $selected.toggleClass('fa-check-square-o'); this.trigger('card:toggle-select', $selected.hasClass('fa-check-square-o')); } }); return CardView; });
www/js/app/CardView.js
define(['underscore', 'zepto', 'backbone'], function(_, $, Backbone){ var CardView = Backbone.View.extend({ template : _.template($('#cardView').html()), events : { 'click .content' : '_onContentClick', 'click .header .back-button' : '_onBack', 'click .header .menu-button' : '_onShowMenu', 'click .header .title .selected' : '_onToggleSelected' }, initialize : function(options){ this.card = options.card; }, render : function(){ $(this.el).empty(); $(this.el).append(this.template({ card : this.card, })); var height = $(window).height(); var headerHeight = this.$('.header').height(); var contentHeight = height - headerHeight; var $content = this.$('.content'); var $cardSide = this.$('.content .card-side'); var linesHeight = $cardSide.height(); $content.height(contentHeight); $cardSide.css({ 'padding-top' : ((contentHeight - linesHeight) / 2) + 'px' }); }, setCard : function(card){ this.card = card; }, _onBack : function(){ this.trigger('back', {}); }, _onShowMenu : function(){ this.trigger('show:menu', {}); }, _onContentClick : function(evt){ var width = $(window).width(); if(evt.offsetX > width * 0.9){ return this.trigger('card:show-next'); } if(evt.offsetX < width * 0.1){ return this.trigger('card:show-prev'); } return this.trigger('card:flip'); }, _onToggleSelected : function(){ var $selected = this.$('.header .title .selected'); $selected.toggleClass('fa-square-o'); $selected.toggleClass('fa-check-square-o'); this.trigger('card:toggle-select', $selected.hasClass('fa-check-square-o')); } }); return CardView; });
fixed click location calculation in FF
www/js/app/CardView.js
fixed click location calculation in FF
<ide><path>ww/js/app/CardView.js <ide> <ide> _onContentClick : function(evt){ <ide> var width = $(window).width(); <del> if(evt.offsetX > width * 0.9){ <add> if(evt.clientX > width * 0.9){ <ide> return this.trigger('card:show-next'); <ide> } <del> if(evt.offsetX < width * 0.1){ <add> if(evt.clientX < width * 0.1){ <ide> return this.trigger('card:show-prev'); <ide> } <ide> return this.trigger('card:flip');
Java
mit
f090cc18237a4260f7f2ca73ab0bd864c20d5949
0
Shalantor/Android-Basics-Nanodegree-Udacity
package com.example.georgekaraolanis.project10_inventoryapp.data; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.util.Log; import com.example.georgekaraolanis.project10_inventoryapp.data.InventoryContract.InventoryEntry; public class InventoryItemProvider extends ContentProvider{ /*tag for logging*/ public static final String LOG_TAG = InventoryItemProvider.class.getSimpleName(); /*URI matcher code for list of items */ private static final int ITEMS = 100; /*URI matcher code for one item */ private static final int ITEM_ID = 101; /*URI matcher*/ private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); /*Static initializer for what uris the matcher should recognize as accepted*/ static { uriMatcher.addURI(InventoryContract.CONTENT_AUTHORITY, InventoryContract.PATH_INVENTORY, ITEMS); uriMatcher.addURI(InventoryContract.CONTENT_AUTHORITY, InventoryContract.PATH_INVENTORY + "/#", ITEM_ID); } /*The db helper object*/ private InventoryDbHelper dbHelper; @Override public boolean onCreate() { dbHelper = new InventoryDbHelper(getContext()); return true; } @Override public Cursor query(Uri uri,String[] projection,String selection, String[] selectionArgs, String sortOrder) { /*Get readable database*/ SQLiteDatabase database = dbHelper.getReadableDatabase(); /*Cursor to return*/ Cursor cursor; /*Get the match from the uri matcher*/ int match = uriMatcher.match(uri); /*Check the match*/ switch (match) { case ITEMS: cursor = database.query(InventoryEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); break; case ITEM_ID: selection = InventoryEntry._ID + "=?"; selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) }; cursor = database.query(InventoryEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); break; default: throw new IllegalArgumentException("Cannot query unknown URI " + uri); } /*Set notification uri on cursor. If the uri changes, we need to change cursor*/ cursor.setNotificationUri(getContext().getContentResolver(),uri); /*Return the cursor*/ return cursor; } @Override public String getType(Uri uri) { final int match = uriMatcher.match(uri); switch (match) { case ITEMS: return InventoryEntry.CONTENT_LIST_TYPE; case ITEM_ID: return InventoryEntry.CONTENT_ITEM_TYPE; default: throw new IllegalStateException("Unknown URI " + uri + " with match " + match); } } @Override public Uri insert(Uri uri,ContentValues values) { final int match = uriMatcher.match(uri); switch (match) { case ITEMS: return insertItem(uri, values); default: throw new IllegalArgumentException("Insertion is not supported for " + uri); } } /*Insert an item into database*/ private Uri insertItem(Uri uri, ContentValues values){ /*Check that the item name is not null*/ String name = values.getAsString(InventoryEntry.COLUMN_ITEM_NAME); if (name == null) { throw new IllegalArgumentException("Item requires a name"); } /*Check that image path is not null*/ String imagePath = values.getAsString(InventoryEntry.COLUMN_ITEM_IMAGE); if (imagePath == null) { throw new IllegalArgumentException("Item requires an image"); } /*Check that quantity is greater than or equal to zero*/ Integer quantity = values.getAsInteger(InventoryEntry.COLUMN_ITEM_QUANTITY); if (quantity != null && quantity < 0) { throw new IllegalArgumentException("Item requires a valid quantity"); } /*Check that price is greater than or equal to zero*/ Float price = values.getAsFloat(InventoryEntry.COLUMN_ITEM_PRICE); if (price != null && price < 0) { throw new IllegalArgumentException("Item requires a valid price"); } /*Get writeable database*/ SQLiteDatabase database = dbHelper.getWritableDatabase(); /*Insert new item with the given values*/ long id = database.insert(InventoryEntry.TABLE_NAME,null,values); if (id == -1) { Log.e(LOG_TAG, "Failed to insert row for " + uri); return null; } /*Notify listeners that we have new data*/ getContext().getContentResolver().notifyChange(uri, null); /*Return uri with the new id*/ return ContentUris.withAppendedId(uri, id); } @Override public int delete(Uri uri,String selection,String[] selectionArgs) { /*Get writeable database*/ SQLiteDatabase database = dbHelper.getWritableDatabase(); /*Number of deleted rows*/ int rowsDeleted; final int match = uriMatcher.match(uri); switch (match) { case ITEMS: rowsDeleted = database.delete(InventoryEntry.TABLE_NAME, selection, selectionArgs); break; case ITEM_ID: selection = InventoryEntry._ID + "=?"; selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) }; rowsDeleted = database.delete(InventoryEntry.TABLE_NAME, selection, selectionArgs); break; default: throw new IllegalArgumentException("Can not delete for " + uri); } /*Check how many rows got deleted*/ if (rowsDeleted != 0) { getContext().getContentResolver().notifyChange(uri, null); } /*Return number of deleted rows*/ return rowsDeleted; } @Override public int update(Uri uri,ContentValues values,String selection,String[] selectionArgs) { final int match = uriMatcher.match(uri); switch (match) { case ITEMS: return updateItem(uri, values, selection, selectionArgs); case ITEM_ID: selection = InventoryEntry._ID + "=?"; selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) }; return updateItem(uri, values, selection, selectionArgs); default: throw new IllegalArgumentException("Update is not supported for " + uri); } } /*Update an item*/ private int updateItem(Uri uri, ContentValues values, String selection, String[] selectionArgs){ /*Check that name is not null*/ if (values.containsKey(InventoryEntry.COLUMN_ITEM_NAME)){ String name = values.getAsString(InventoryEntry.COLUMN_ITEM_NAME); if (name == null) { throw new IllegalArgumentException("Item requires a name"); } } /*Check image path*/ if (values.containsKey(InventoryEntry.COLUMN_ITEM_IMAGE)){ String imagePath = values.getAsString(InventoryEntry.COLUMN_ITEM_IMAGE); if (imagePath == null) { throw new IllegalArgumentException("Item requires an image"); } } /*Check item quantity*/ if (values.containsKey(InventoryEntry.COLUMN_ITEM_QUANTITY)){ Integer quantity = values.getAsInteger(InventoryEntry.COLUMN_ITEM_QUANTITY); if (quantity != null && quantity < 0) { throw new IllegalArgumentException("Item requires a valid quantity"); } } /*Check item price*/ if (values.containsKey(InventoryEntry.COLUMN_ITEM_PRICE)){ Float price = values.getAsFloat(InventoryEntry.COLUMN_ITEM_PRICE); if (price != null && price < 0) { throw new IllegalArgumentException("Item requires a valid price"); } } /*If there are no values to update, then don't try to update the database*/ if (values.size() == 0) { return 0; } /*Else get writeable database*/ SQLiteDatabase database = dbHelper.getWritableDatabase(); /*Perform update*/ int rowsUpdated = database.update(InventoryEntry.TABLE_NAME, values, selection, selectionArgs); /*Check if necessary to notify listeners*/ if (rowsUpdated != 0) { getContext().getContentResolver().notifyChange(uri, null); } /*Return numbers of updated rows*/ return rowsUpdated; } }
Project10-InventoryApp/app/src/main/java/com/example/georgekaraolanis/project10_inventoryapp/data/InventoryItemProvider.java
package com.example.georgekaraolanis.project10_inventoryapp.data; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.util.Log; import com.example.georgekaraolanis.project10_inventoryapp.data.InventoryContract.InventoryEntry; public class InventoryItemProvider extends ContentProvider{ /*tag for logging*/ public static final String LOG_TAG = InventoryItemProvider.class.getSimpleName(); /*URI matcher code for list of items */ private static final int ITEMS = 100; /*URI matcher code for one item */ private static final int ITEM_ID = 101; /*URI matcher*/ private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); /*Static initializer for what uris the matcher should recognize as accepted*/ static { uriMatcher.addURI(InventoryContract.CONTENT_AUTHORITY, InventoryContract.PATH_INVENTORY, ITEMS); uriMatcher.addURI(InventoryContract.CONTENT_AUTHORITY, InventoryContract.PATH_INVENTORY + "/#", ITEM_ID); } /*The db helper object*/ private InventoryDbHelper dbHelper; @Override public boolean onCreate() { dbHelper = new InventoryDbHelper(getContext()); return true; } @Override public Cursor query(Uri uri,String[] projection,String selection, String[] selectionArgs, String sortOrder) { /*Get readable database*/ SQLiteDatabase database = dbHelper.getReadableDatabase(); /*Cursor to return*/ Cursor cursor; /*Get the match from the uri matcher*/ int match = uriMatcher.match(uri); /*Check the match*/ switch (match) { case ITEMS: cursor = database.query(InventoryEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); break; case ITEM_ID: selection = InventoryEntry._ID + "=?"; selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) }; cursor = database.query(InventoryEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); break; default: throw new IllegalArgumentException("Cannot query unknown URI " + uri); } /*Set notification uri on cursor. If the uri changes, we need to change cursor*/ cursor.setNotificationUri(getContext().getContentResolver(),uri); /*Return the cursor*/ return cursor; } @Override public String getType(Uri uri) { final int match = uriMatcher.match(uri); switch (match) { case ITEMS: return InventoryEntry.CONTENT_LIST_TYPE; case ITEM_ID: return InventoryEntry.CONTENT_ITEM_TYPE; default: throw new IllegalStateException("Unknown URI " + uri + " with match " + match); } } @Override public Uri insert(Uri uri,ContentValues values) { final int match = uriMatcher.match(uri); switch (match) { case ITEMS: return insertItem(uri, values); default: throw new IllegalArgumentException("Insertion is not supported for " + uri); } } /*Insert an item into database*/ private Uri insertItem(Uri uri, ContentValues values){ /*Check that the item name is not null*/ String name = values.getAsString(InventoryEntry.COLUMN_ITEM_NAME); if (name == null) { throw new IllegalArgumentException("Item requires a name"); } /*Check that image path is not null*/ String imagePath = values.getAsString(InventoryEntry.COLUMN_ITEM_IMAGE); if (imagePath == null) { throw new IllegalArgumentException("Item requires an image"); } /*Check that quantity is greater than or equal to zero*/ Integer quantity = values.getAsInteger(InventoryEntry.COLUMN_ITEM_QUANTITY); if (quantity != null && quantity < 0) { throw new IllegalArgumentException("Item requires a valid quantity"); } /*Check that price is greater than or equal to zero*/ Float price = values.getAsFloat(InventoryEntry.COLUMN_ITEM_PRICE); if (price != null && price < 0) { throw new IllegalArgumentException("Item requires a valid price"); } /*Get writeable database*/ SQLiteDatabase database = dbHelper.getWritableDatabase(); /*Insert new item with the given values*/ long id = database.insert(InventoryEntry.TABLE_NAME,null,values); if (id == -1) { Log.e(LOG_TAG, "Failed to insert row for " + uri); return null; } /*Notify listeners that we have new data*/ getContext().getContentResolver().notifyChange(uri, null); /*Return uri with the new id*/ return ContentUris.withAppendedId(uri, id); } @Override public int delete(Uri uri,String selection,String[] selectionArgs) { return 0; } @Override public int update(Uri uri,ContentValues values,String selection,String[] selectionArgs) { final int match = uriMatcher.match(uri); switch (match) { case ITEMS: return updateItem(uri, values, selection, selectionArgs); case ITEM_ID: selection = InventoryEntry._ID + "=?"; selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) }; return updateItem(uri, values, selection, selectionArgs); default: throw new IllegalArgumentException("Update is not supported for " + uri); } } /*Update an item*/ private int updateItem(Uri uri, ContentValues values, String selection, String[] selectionArgs){ /*Check that name is not null*/ if (values.containsKey(InventoryEntry.COLUMN_ITEM_NAME)){ String name = values.getAsString(InventoryEntry.COLUMN_ITEM_NAME); if (name == null) { throw new IllegalArgumentException("Item requires a name"); } } /*Check image path*/ if (values.containsKey(InventoryEntry.COLUMN_ITEM_IMAGE)){ String imagePath = values.getAsString(InventoryEntry.COLUMN_ITEM_IMAGE); if (imagePath == null) { throw new IllegalArgumentException("Item requires an image"); } } /*Check item quantity*/ if (values.containsKey(InventoryEntry.COLUMN_ITEM_QUANTITY)){ Integer quantity = values.getAsInteger(InventoryEntry.COLUMN_ITEM_QUANTITY); if (quantity != null && quantity < 0) { throw new IllegalArgumentException("Item requires a valid quantity"); } } /*Check item price*/ if (values.containsKey(InventoryEntry.COLUMN_ITEM_PRICE)){ Float price = values.getAsFloat(InventoryEntry.COLUMN_ITEM_PRICE); if (price != null && price < 0) { throw new IllegalArgumentException("Item requires a valid price"); } } /*If there are no values to update, then don't try to update the database*/ if (values.size() == 0) { return 0; } /*Else get writeable database*/ SQLiteDatabase database = dbHelper.getWritableDatabase(); /*Perform update*/ int rowsUpdated = database.update(InventoryEntry.TABLE_NAME, values, selection, selectionArgs); /*Check if necessary to notify listeners*/ if (rowsUpdated != 0) { getContext().getContentResolver().notifyChange(uri, null); } /*Return numbers of updated rows*/ return rowsUpdated; } }
Project10: Implement delete method
Project10-InventoryApp/app/src/main/java/com/example/georgekaraolanis/project10_inventoryapp/data/InventoryItemProvider.java
Project10: Implement delete method
<ide><path>roject10-InventoryApp/app/src/main/java/com/example/georgekaraolanis/project10_inventoryapp/data/InventoryItemProvider.java <ide> <ide> @Override <ide> public int delete(Uri uri,String selection,String[] selectionArgs) { <del> return 0; <add> <add> /*Get writeable database*/ <add> SQLiteDatabase database = dbHelper.getWritableDatabase(); <add> <add> /*Number of deleted rows*/ <add> int rowsDeleted; <add> <add> final int match = uriMatcher.match(uri); <add> switch (match) { <add> case ITEMS: <add> rowsDeleted = database.delete(InventoryEntry.TABLE_NAME, selection, selectionArgs); <add> break; <add> case ITEM_ID: <add> selection = InventoryEntry._ID + "=?"; <add> selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) }; <add> rowsDeleted = database.delete(InventoryEntry.TABLE_NAME, selection, selectionArgs); <add> break; <add> default: <add> throw new IllegalArgumentException("Can not delete for " + uri); <add> } <add> <add> /*Check how many rows got deleted*/ <add> if (rowsDeleted != 0) { <add> getContext().getContentResolver().notifyChange(uri, null); <add> } <add> <add> /*Return number of deleted rows*/ <add> return rowsDeleted; <ide> } <ide> <ide> @Override <ide> return rowsUpdated; <ide> } <ide> <add> <add> <ide> }
JavaScript
bsd-3-clause
a95e3ba32716ac35d76bab18dd2fd9f863c17b9e
0
oysnet/czagenda-api,oysnet/czagenda-api,oysnet/czagenda-api
var Base = require('./base.js').Base; var util = require("util"); var settings = require('../settings.js') var utils = require('../libs/utils.js'); var errors = require('./errors.js'); var redis = require('../libs/redis-client'); var log = require('czagenda-log').from(__filename); var crypto = require('crypto'); function User() { this._attributs = { login : null, firstName : null, lastName : null, email : null, password : null, isActive : false, isStaff : false, isSuperuser : false, lastSeen : null, joinedDate : null, groups : null, gravatar : null }; Base.call(this, 'user'); this.initialData = { login : null, password : null } } User.publicAttributes = Base.publicAttributes.concat(['login', 'firstName', 'lastName', 'isActive', 'isStaff', 'isSuperuser', 'lastSeen', 'joinedDate', 'groups', 'gravatar']); User.staffAttributes = User.publicAttributes.concat(Base.staffAttributes).concat(['email', 'password']); User.publicWriteAttributes = ['firstName', 'lastName', 'email', 'isActive', 'password']; User.staffWriteAttributes = User.publicWriteAttributes.concat([ 'isStaff', 'isSuperuser', 'login']); User.hiddenPassword = 'HIDDEN-PASSWORD'; util.inherits(User, Base); User.prototype.hasPerm = function (perm, user, callback) { switch (perm) { case 'read': case 'create': callback(null, true); break; case 'write': case 'del': callback(null, user.isStaff === true || user.isSuperuser === true || user.id === this.id); break; default: return false; } } User.prototype._validate = function(callback) { //this.validateString('login', false, 2, 30); if (this.initialData.login !== null) { if (this.initialData.login !== this.login) { this.addValidationError('login', 'is not editable'); } } else { this.validateRegexp('login', '^[\-_\.0-9a-zA-Z]{2,30}$', false); } this.validateString('firstName', true, null, 128); this.validateString('lastName', true, null, 128); this.validateEmail('email'); callback(null); } User.prototype._generateHash = function() { h = crypto.createHash('md5') h.update(this._type); h.update(this.email); if (this.firstName !== null) { h.update(this.firstName); } if (this.lastName !== null) { h.update(this.lastName); } h.update(this.login); this._data['hash'] = h.digest('hex') } User.prototype._generateId = function() { return '/user/' + this.login; } User.prototype._preSave = function(callback) { if(this.id === null) { this._data.groups = this._data.id + '/groups'; this._data.joinedDate = this._data.createDate; } // restore initial password if it is unchanged if (this.password == User.hiddenPassword) { this._data.password = this.initialData.password; } h = crypto.createHash('md5') h.update(this.email); this._data.gravatar = h.digest('hex'); callback(null); } User.prototype._postSave = function(err, next) { if(err === null) { redis.redisClient.hmset(redis.USER_PREFIX + this.id, "isActive", this.isActive, "isStaff", this.isStaff, "isSuperuser", this.isSuperuser, function(err, res) { if(err !== null) { log.critical('REDIS USER: error on hmset ', redis.USER_PREFIX + this.id, "isActive", this.isActive, "isStaff", this.isStaff, "isSuperuser", this.isSuperuser) } next(); }.bind(this)) } else { next(); } } User.prototype._postDel = function(err, next) { if (err === null || err instanceof errors.ObjectDoesNotExist) { redis.redisClient.del(redis.USER_PREFIX + this.id, function (err, res) { if (err !== null) { log.critical('REDIS USER: error on del ', redis.USER_PREFIX + this.id); } next(); }.bind(this)) } else { next(); } } User.prototype.serialize = function(keys) { var obj = Base.prototype.serialize.call(this, keys); if (keys.indexOf('password') !== -1) { obj.password = User.hiddenPassword; } return obj; } User.get = function(options, callback) { Base.get(options, User, function(err, obj) { // save initial agenda value to check perms if(err === null) { obj.initialData = { login : obj.login, password : obj.passsword } } callback(err, obj); }) } /* User.get = function(options, callback) { Base.get(options, User, callback) } */ User.search = function(query, attrs, callback) { Base.search(query, settings.elasticsearch.index, 'user', attrs, User, callback) } User.count = function(query, callback) { Base.count(query, settings.elasticsearch.index, 'user', callback) } exports.User = User;
models/user.js
var Base = require('./base.js').Base; var util = require("util"); var settings = require('../settings.js') var utils = require('../libs/utils.js'); var errors = require('./errors.js'); var redis = require('../libs/redis-client'); var log = require('czagenda-log').from(__filename); var crypto = require('crypto'); function User() { this._attributs = { login : null, firstName : null, lastName : null, email : null, password : null, isActive : false, isStaff : false, isSuperuser : false, lastSeen : null, joinedDate : null, groups : null, gravatar : null }; Base.call(this, 'user'); this.initialData = { login : null } } User.publicAttributes = Base.publicAttributes.concat(['login', 'firstName', 'lastName', 'isActive', 'isStaff', 'isSuperuser', 'lastSeen', 'joinedDate', 'groups', 'gravatar']); User.staffAttributes = User.publicAttributes.concat(Base.staffAttributes).concat(['email', 'password']); User.publicWriteAttributes = ['firstName', 'lastName', 'email', 'isActive', 'password']; User.staffWriteAttributes = User.publicWriteAttributes.concat([ 'isStaff', 'isSuperuser', 'login']); util.inherits(User, Base); User.prototype.hasPerm = function (perm, user, callback) { switch (perm) { case 'read': case 'create': callback(null, true); break; case 'write': case 'del': callback(null, user.isStaff === true || user.isSuperuser === true || user.id === this.id); break; default: return false; } } User.prototype._validate = function(callback) { //this.validateString('login', false, 2, 30); if (this.initialData.login !== null) { if (this.initialData.login !== this.login) { this.addValidationError('login', 'is not editable'); } } else { this.validateRegexp('login', '^[\-_\.0-9a-zA-Z]{2,30}$', false); } this.validateString('firstName', true, null, 128); this.validateString('lastName', true, null, 128); this.validateEmail('email'); callback(null); } User.prototype._generateHash = function() { h = crypto.createHash('md5') h.update(this._type); h.update(this.email); if (this.firstName !== null) { h.update(this.firstName); } if (this.lastName !== null) { h.update(this.lastName); } h.update(this.login); this._data['hash'] = h.digest('hex') } User.prototype._generateId = function() { return '/user/' + this.login; } User.prototype._preSave = function(callback) { if(this.id === null) { this._data.groups = this._data.id + '/groups'; this._data.joinedDate = this._data.createDate; } h = crypto.createHash('md5') h.update(this.email); this._data.gravatar = h.digest('hex'); callback(null); } User.prototype._postSave = function(err, next) { if(err === null) { redis.redisClient.hmset(redis.USER_PREFIX + this.id, "isActive", this.isActive, "isStaff", this.isStaff, "isSuperuser", this.isSuperuser, function(err, res) { if(err !== null) { log.critical('REDIS USER: error on hmset ', redis.USER_PREFIX + this.id, "isActive", this.isActive, "isStaff", this.isStaff, "isSuperuser", this.isSuperuser) } next(); }.bind(this)) } else { next(); } } User.prototype._postDel = function(err, next) { if (err === null || err instanceof errors.ObjectDoesNotExist) { redis.redisClient.del(redis.USER_PREFIX + this.id, function (err, res) { if (err !== null) { log.critical('REDIS USER: error on del ', redis.USER_PREFIX + this.id); } next(); }.bind(this)) } else { next(); } } User.get = function(options, callback) { Base.get(options, User, function(err, obj) { // save initial agenda value to check perms if(err === null) { obj.initialData = { login : obj.login } } callback(err, obj); }) } /* User.get = function(options, callback) { Base.get(options, User, callback) } */ User.search = function(query, attrs, callback) { Base.search(query, settings.elasticsearch.index, 'user', attrs, User, callback) } User.count = function(query, callback) { Base.count(query, settings.elasticsearch.index, 'user', callback) } exports.User = User;
user hidden password
models/user.js
user hidden password
<ide><path>odels/user.js <ide> Base.call(this, 'user'); <ide> <ide> this.initialData = { <del> login : null <add> login : null, <add> password : null <ide> } <ide> <ide> } <ide> <ide> User.staffWriteAttributes = User.publicWriteAttributes.concat([ 'isStaff', 'isSuperuser', 'login']); <ide> <add>User.hiddenPassword = 'HIDDEN-PASSWORD'; <ide> <ide> util.inherits(User, Base); <ide> <ide> this.validateRegexp('login', '^[\-_\.0-9a-zA-Z]{2,30}$', false); <ide> } <ide> <del> <ide> this.validateString('firstName', true, null, 128); <ide> this.validateString('lastName', true, null, 128); <ide> this.validateEmail('email'); <ide> this._data.joinedDate = this._data.createDate; <ide> } <ide> <add> // restore initial password if it is unchanged <add> if (this.password == User.hiddenPassword) { <add> this._data.password = this.initialData.password; <add> } <add> <ide> h = crypto.createHash('md5') <ide> h.update(this.email); <ide> <ide> <ide> } <ide> <add>User.prototype.serialize = function(keys) { <add> <add> var obj = Base.prototype.serialize.call(this, keys); <add> <add> if (keys.indexOf('password') !== -1) { <add> obj.password = User.hiddenPassword; <add> } <add> <add> return obj; <add> <add>} <add> <add> <ide> User.get = function(options, callback) { <ide> Base.get(options, User, function(err, obj) { <ide> <ide> // save initial agenda value to check perms <ide> if(err === null) { <ide> obj.initialData = { <del> login : obj.login <add> login : obj.login, <add> password : obj.passsword <ide> } <ide> } <ide>
Java
mit
173f8be4f0749e6f46c36c20c1a1f44f889aab2d
0
jakobehmsen/duro
package duro.reflang; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTreeVisitor; import duro.reflang.antlr4_2.DuroBaseVisitor; import duro.reflang.antlr4_2.DuroLexer; import duro.reflang.antlr4_2.DuroParser.AccessContext; import duro.reflang.antlr4_2.DuroParser.AssignmentContext; import duro.reflang.antlr4_2.DuroParser.BehaviorParamsContext; import duro.reflang.antlr4_2.DuroParser.BinaryMessageContext; import duro.reflang.antlr4_2.DuroParser.BinaryMessageOperandChainContext; import duro.reflang.antlr4_2.DuroParser.BinaryMessageOperandContext; import duro.reflang.antlr4_2.DuroParser.ClosureContext; import duro.reflang.antlr4_2.DuroParser.DictContext; import duro.reflang.antlr4_2.DuroParser.DictEntryContext; import duro.reflang.antlr4_2.DuroParser.ExpressionContext; import duro.reflang.antlr4_2.DuroParser.GroupingContext; import duro.reflang.antlr4_2.DuroParser.IdContext; import duro.reflang.antlr4_2.DuroParser.IndexAccessContext; import duro.reflang.antlr4_2.DuroParser.IntegerContext; import duro.reflang.antlr4_2.DuroParser.InterfaceIdContext; import duro.reflang.antlr4_2.DuroParser.MessageChainContext; import duro.reflang.antlr4_2.DuroParser.MessageExchangeContext; import duro.reflang.antlr4_2.DuroParser.MultiArgMessageArgNoParChainContext; import duro.reflang.antlr4_2.DuroParser.MultiArgMessageArgNoParContext; import duro.reflang.antlr4_2.DuroParser.MultiArgMessageArgsNoParContext; import duro.reflang.antlr4_2.DuroParser.MultiArgMessageArgsWithParContext; import duro.reflang.antlr4_2.DuroParser.MultiArgMessageNoParContext; import duro.reflang.antlr4_2.DuroParser.MultiArgMessageWithParContext; import duro.reflang.antlr4_2.DuroParser.ParArgContext; import duro.reflang.antlr4_2.DuroParser.ProgramContext; import duro.reflang.antlr4_2.DuroParser.PseudoVarContext; import duro.reflang.antlr4_2.DuroParser.SelectorContext; import duro.reflang.antlr4_2.DuroParser.SelfMultiArgMessageNoParContext; import duro.reflang.antlr4_2.DuroParser.SelfMultiArgMessageWithParContext; import duro.reflang.antlr4_2.DuroParser.SlotAccessContext; import duro.reflang.antlr4_2.DuroParser.SlotAssignmentContext; import duro.reflang.antlr4_2.DuroParser.StringContext; import duro.reflang.antlr4_2.DuroParser.VariableDeclarationContext; import duro.runtime.Instruction; import duro.runtime.Selector; public class BodyVisitor extends DuroBaseVisitor<Object> { private Hashtable<Selector, PrimitiveVisitorFactory> primitiveMap; private MessageCollector errors; private ArrayList<Runnable> endHandlers; private ArrayList<Instruction> instructions; private boolean mustBeExpression; private OrdinalAllocator idToParameterOrdinalMap; private OrdinalAllocator idToVariableOrdinalMap; public BodyVisitor(Hashtable<Selector, PrimitiveVisitorFactory> primitiveMap, MessageCollector errors, ArrayList<Runnable> endHandlers) { this.primitiveMap = primitiveMap; this.errors = errors; this.endHandlers = endHandlers; this.instructions = new ArrayList<Instruction>(); this.mustBeExpression = true; this.idToParameterOrdinalMap = new OrdinalAllocator(); this.idToVariableOrdinalMap = new OrdinalAllocator(); } public BodyVisitor(Hashtable<Selector, PrimitiveVisitorFactory> primitiveMap, MessageCollector errors, ArrayList<Runnable> endHandlers, ArrayList<Instruction> instructions, boolean mustBeExpression, OrdinalAllocator idToParameterOrdinalMap, OrdinalAllocator idToVariableOrdinalMap) { this.primitiveMap = primitiveMap; this.errors = errors; this.endHandlers = endHandlers; this.instructions = instructions; this.mustBeExpression = mustBeExpression; this.idToParameterOrdinalMap = idToParameterOrdinalMap; this.idToVariableOrdinalMap = idToVariableOrdinalMap; } @Override public Object visitProgram(ProgramContext ctx) { BodyVisitor rootExpressionInterceptor = new BodyVisitor(primitiveMap, errors, endHandlers, instructions, false, idToParameterOrdinalMap, idToVariableOrdinalMap); for(int i = 0; i < ctx.expression().size() ; i++) ctx.expression(i).accept(rootExpressionInterceptor); instructions.add(new Instruction(Instruction.OPCODE_FINISH)); return null; } @Override public Object visitInterfaceId(InterfaceIdContext ctx) { idToVariableOrdinalMap = idToVariableOrdinalMap.newInnerStart(); String interfaceId = ctx.id().getText(); instructions.add(new Instruction(Instruction.OPCODE_EXTEND_INTER_ID, interfaceId)); ctx.expression().accept(this); instructions.add(new Instruction(Instruction.OPCODE_SHRINK_INTER_ID)); idToVariableOrdinalMap = idToVariableOrdinalMap.getOuter(); return null; } @Override public Object visitMessageExchange(MessageExchangeContext ctx) { if(!mustBeExpression) { if(ctx.messageChain() != null) { BodyVisitor messageExchangeVisitor = new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap); ctx.receiver().accept(messageExchangeVisitor); MessageChainContext chain = ctx.messageChain(); while(chain != null) { messageExchangeVisitor.mustBeExpression = chain.messageChain() != null; chain.accept(messageExchangeVisitor); chain = chain.messageChain(); } } else { ctx.receiver().accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, false, idToParameterOrdinalMap, idToVariableOrdinalMap)); } } else { super.visitMessageExchange(ctx); } return false; } @Override public Object visitBinaryMessageOperand(BinaryMessageOperandContext ctx) { if(!mustBeExpression) { if(ctx.binaryMessageOperandChain() != null) { BodyVisitor messageExchangeVisitor = new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap); ctx.receiver().accept(messageExchangeVisitor); BinaryMessageOperandChainContext chain = ctx.binaryMessageOperandChain(); while(chain != null) { messageExchangeVisitor.mustBeExpression = chain.binaryMessageOperandChain() != null; chain.accept(messageExchangeVisitor); chain = chain.binaryMessageOperandChain(); } } else { ctx.receiver().accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, false, idToParameterOrdinalMap, idToVariableOrdinalMap)); } } else { super.visitBinaryMessageOperand(ctx); } return false; } @Override public Object visitMultiArgMessageArgNoPar(MultiArgMessageArgNoParContext ctx) { if(!mustBeExpression) { if(ctx.multiArgMessageArgNoParChain() != null) { BodyVisitor messageExchangeVisitor = new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap); ctx.receiver().accept(messageExchangeVisitor); MultiArgMessageArgNoParChainContext chain = ctx.multiArgMessageArgNoParChain(); while(chain != null) { messageExchangeVisitor.mustBeExpression = chain.multiArgMessageArgNoParChain() != null; chain.accept(messageExchangeVisitor); chain = chain.multiArgMessageArgNoParChain(); } } else { ctx.receiver().accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, false, idToParameterOrdinalMap, idToVariableOrdinalMap)); } } else { super.visitMultiArgMessageArgNoPar(ctx); } return false; } @Override public Object visitVariableDeclaration(VariableDeclarationContext ctx) { if(!idToVariableOrdinalMap.isDeclaredLocally(ctx.id().getText()) && !idToParameterOrdinalMap.isDeclared(ctx.id().getText())) { idToVariableOrdinalMap.declare(ctx.id().getText()); if(ctx.expression() == null) { if(mustBeExpression) instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL)); } else { ctx.expression().accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap)); if(mustBeExpression) instructions.add(new Instruction(Instruction.OPCODE_DUP)); idToVariableOrdinalMap.declare(ctx.id().getText(), instructions, variableOrdinal -> new Instruction(Instruction.OPCODE_STORE_LOC, variableOrdinal)); } } else { appendError(ctx, "Variable '" + ctx.id().getText() + "' is already declared in this scope."); } return null; } @Override public Object visitBinaryMessage(BinaryMessageContext ctx) { visitChildren(ctx); String id = ctx.BIN_OP().getText(); instructions.add(new Instruction(Instruction.OPCODE_SEND, id, 1)); if(!mustBeExpression) instructions.add(new Instruction(Instruction.OPCODE_POP)); return null; } @Override public Object visitSelfMultiArgMessageNoPar(SelfMultiArgMessageNoParContext ctx) { appendMultiArgMessageNoPar(ctx.multiArgMessageNoPar(), true); return null; } @Override public Object visitMultiArgMessageNoPar(MultiArgMessageNoParContext ctx) { appendMultiArgMessageNoPar(ctx, false); return null; } private void appendMultiArgMessageNoPar(MultiArgMessageNoParContext ctx, boolean isForSelf) { String id = ctx.ID_UNCAP().getText() + ctx.ID_CAP().stream().map(x -> x.getText()).collect(Collectors.joining()); ArrayList<ParserRuleContext> args = new ArrayList<ParserRuleContext>(); for(MultiArgMessageArgsNoParContext argsCtx: ctx.multiArgMessageArgsNoPar()) { for(MultiArgMessageArgNoParContext argCtx: argsCtx.multiArgMessageArgNoPar()) args.add(argCtx); } appendMultiArgMessage(id, args, isForSelf); } @Override public Object visitSelfMultiArgMessageWithPar(SelfMultiArgMessageWithParContext ctx) { appendMultiArgMessageWithPar(ctx.multiArgMessageWithPar(), true); return null; } @Override public Object visitMultiArgMessageWithPar(MultiArgMessageWithParContext ctx) { appendMultiArgMessageWithPar(ctx, false); return null; } private void appendMultiArgMessageWithPar(MultiArgMessageWithParContext ctx, boolean isForSelf) { String id = ctx.ID_UNCAP().getText() + ctx.ID_CAP().stream().map(x -> x.getText()).collect(Collectors.joining()); ArrayList<ParserRuleContext> args = new ArrayList<ParserRuleContext>(); for(MultiArgMessageArgsWithParContext argsCtx: ctx.multiArgMessageArgsWithPar()) { for(ExpressionContext argCtx: argsCtx.expression()) args.add(argCtx); } appendMultiArgMessage(id, args, isForSelf); } protected void appendMultiArgMessage(String id, List<ParserRuleContext> args, boolean isForSelf) { int parameterCount = args.size(); PrimitiveVisitorFactory primitiveVisitorFactory = primitiveMap.get(Selector.get(id, parameterCount)); if(primitiveVisitorFactory != null) { PrimitiveVisitor primitiveInterceptor = primitiveVisitorFactory.create(primitiveMap, errors, endHandlers, instructions, mustBeExpression, idToParameterOrdinalMap, idToVariableOrdinalMap); primitiveInterceptor.visitPrimitive(id, args); } else { if(isForSelf) instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS)); ParseTreeVisitor<Object> argsVisitor = mustBeExpression ? this : new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap); for(ParserRuleContext argCtx: args) argCtx.accept(argsVisitor); instructions.add(new Instruction(Instruction.OPCODE_SEND, id, parameterCount)); if(!mustBeExpression) instructions.add(new Instruction(Instruction.OPCODE_POP)); } } @Override public Object visitGrouping(GroupingContext ctx) { BodyVisitor expressionVisitor = new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap); appendGroup(ctx.expression(), mustBeExpression, expressionVisitor); return null; } @Override public Object visitAssignment(AssignmentContext ctx) { String id = ctx.id().getText(); switch(ctx.op.getType()) { case DuroLexer.ASSIGN: { // newValue, newValue if(idToVariableOrdinalMap.isDeclared(id)) appendAssignVariable(ctx.expression(), id); else { instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS)); appendAssignSlot(ctx.expression(), id, mustBeExpression); } break; } case DuroLexer.ASSIGN_PROTO: { instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS)); appendAssignProto(ctx.expression(), id, mustBeExpression); break; } } // Quoted member assignment for this if(ctx.op.getType() == DuroLexer.ASSIGN_QUOTED) { instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS)); appendAssignQuoted(ctx.behaviorParams(), ctx.expression(), id, mustBeExpression); } return null; } @Override public Object visitSlotAssignment(SlotAssignmentContext ctx) { String id = ctx.id().getText(); switch(ctx.op.getType()) { case DuroLexer.ASSIGN: { appendAssignSlot(ctx.expression(), id, mustBeExpression); break; } case DuroLexer.ASSIGN_PROTO: { appendAssignProto(ctx.expression(), id, mustBeExpression); break; } case DuroLexer.ASSIGN_QUOTED: { appendAssignQuoted(ctx.behaviorParams(), ctx.expression(), id, mustBeExpression); break; } } return null; } public Object visitIndexAssignment(duro.reflang.antlr4_2.DuroParser.IndexAssignmentContext ctx) { // receiver ExpressionContext indexCtx = ctx.expression(0); indexCtx.accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap)); // receiver, index ExpressionContext valueCtx = ctx.expression(1); valueCtx.accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap)); // receiver, index, value instructions.add(new Instruction(Instruction.OPCODE_SEND, "[]", 2)); // result if(!mustBeExpression) instructions.add(new Instruction(Instruction.OPCODE_POP)); return null; } private void appendAssignVariable(ExpressionContext valueCtx, String id) { valueCtx.accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap)); if(mustBeExpression) instructions.add(new Instruction(Instruction.OPCODE_DUP)); // Variable assignment idToVariableOrdinalMap.ordinalFor(id, instructions, firstOrdinal -> new Instruction(Instruction.OPCODE_STORE_LOC, firstOrdinal)); } private void appendAssignSlot(ExpressionContext valueCtx, String id, boolean returnValue) { appendAssignSlot(valueCtx, id, Instruction.OPCODE_SET, returnValue); } private void appendAssignProto(ExpressionContext valueCtx, String id, boolean returnValue) { appendAssignSlot(valueCtx, id, Instruction.OPCODE_SET_PROTO, returnValue); } private void appendAssignSlot(ExpressionContext valueCtx, String id, int opcodeAssign, boolean returnValue) { // receiver valueCtx.accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap)); // receiver, newValue if(returnValue) instructions.add(new Instruction(Instruction.OPCODE_DUP1)); // newValue, receiver, newValue instructions.add(new Instruction(opcodeAssign, id, 0)); // newValue | e } private void appendAssignQuoted(BehaviorParamsContext paramsCtx, ExpressionContext valueCtx, String id, boolean returnValue) { BodyVisitor functionBodyInterceptor = new BodyVisitor(primitiveMap, errors, endHandlers); for(IdContext parameterIdNode: paramsCtx.id()) { String parameterId = parameterIdNode.getText(); functionBodyInterceptor.idToParameterOrdinalMap.declare(parameterId); } valueCtx.accept(functionBodyInterceptor); functionBodyInterceptor.instructions.add(new Instruction(Instruction.OPCODE_RET)); int parameterCount = functionBodyInterceptor.idToParameterOrdinalMap.size(); int selectorParameterCount = functionBodyInterceptor.idToParameterOrdinalMap.sizeExceptEnd(); int variableCount = functionBodyInterceptor.idToVariableOrdinalMap.size(); functionBodyInterceptor.idToParameterOrdinalMap.generate(); functionBodyInterceptor.idToVariableOrdinalMap.generate(); onEnd(() -> { Instruction[] bodyInstructions = functionBodyInterceptor.instructions.toArray(new Instruction[functionBodyInterceptor.instructions.size()]); return new Instruction(Instruction.OPCODE_SP_NEW_BEHAVIOR, parameterCount, variableCount, bodyInstructions); }); if(returnValue) instructions.add(new Instruction(Instruction.OPCODE_DUP1)); instructions.add(new Instruction(Instruction.OPCODE_SET, id, selectorParameterCount)); } @Override public Object visitSlotAccess(SlotAccessContext ctx) { if(mustBeExpression) { String id = getSelectorId(ctx.selector()); instructions.add(new Instruction(Instruction.OPCODE_GET, id, 0)); } return null; } @Override public Object visitIndexAccess(IndexAccessContext ctx) { if(mustBeExpression) { ctx.expression().accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap)); instructions.add(new Instruction(Instruction.OPCODE_SEND, "[]", 1)); } return null; } @Override public Object visitAccess(AccessContext ctx) { if(mustBeExpression) { String id = ctx.id().getText(); if(idToParameterOrdinalMap.isDeclared(id)) { // Load argument idToParameterOrdinalMap.ordinalFor(id, instructions, parameterOrdinal -> new Instruction(Instruction.OPCODE_LOAD_ARG, parameterOrdinal)); return null; } if(idToVariableOrdinalMap.isDeclared(id)) { // Load variable idToVariableOrdinalMap.ordinalFor(id, instructions, variableOrdinal -> new Instruction(Instruction.OPCODE_LOAD_LOC, variableOrdinal)); return null; } // Get member instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS)); instructions.add(new Instruction(Instruction.OPCODE_GET, id, 0)); } return null; } @Override public Object visitParArg(ParArgContext ctx) { idToParameterOrdinalMap.declare(ctx.id().getText(), instructions, parameterOrdinal -> new Instruction(Instruction.OPCODE_LOAD_ARG, parameterOrdinal)); return null; } @Override public Object visitDict(DictContext ctx) { instructions.add(new Instruction(Instruction.OPCODE_SP_NEW_DICT)); for(DictEntryContext entryCtx: ctx.dictEntry()) { instructions.add(new Instruction(Instruction.OPCODE_DUP)); String id = getSelectorId(entryCtx.selector()); switch(entryCtx.op.getType()) { case DuroLexer.ASSIGN: appendAssignSlot(entryCtx.expression(), id, false); break; case DuroLexer.ASSIGN_PROTO: appendAssignProto(entryCtx.expression(), id, false); break; case DuroLexer.ASSIGN_QUOTED: appendAssignQuoted(entryCtx.behaviorParams(), entryCtx.expression(), id, false); break; } } return null; } @Override public Object visitClosure(ClosureContext ctx) { if(mustBeExpression) { OrdinalAllocator newIdToVariableOrdinalMap = idToVariableOrdinalMap.newInnerEnd(); OrdinalAllocator newIdToParameterOrdinalMap = idToParameterOrdinalMap.newInnerEnd(); BodyVisitor closureBodyInterceptor = new BodyVisitor(primitiveMap, errors, endHandlers, new ArrayList<Instruction>(), true, newIdToParameterOrdinalMap, newIdToVariableOrdinalMap); for(IdContext parameterIdNode: ctx.behaviorParams().id()) { String parameterId = parameterIdNode.getText(); closureBodyInterceptor.idToParameterOrdinalMap.declare(parameterId); } appendGroup(ctx.expression(), true, closureBodyInterceptor); closureBodyInterceptor.instructions.add(new Instruction(Instruction.OPCODE_RET)); int parameterCount = closureBodyInterceptor.idToParameterOrdinalMap.size(); int closureParameterCount = closureBodyInterceptor.idToParameterOrdinalMap.sizeExceptEnd(); int variableCount = closureBodyInterceptor.idToVariableOrdinalMap.size(); closureBodyInterceptor.idToParameterOrdinalMap.generate(); closureBodyInterceptor.idToVariableOrdinalMap.generate(); onEnd(() -> { Instruction[] bodyInstructions = closureBodyInterceptor.instructions.toArray(new Instruction[closureBodyInterceptor.instructions.size()]); return new Instruction(Instruction.OPCODE_SP_NEW_BEHAVIOR, parameterCount, variableCount, bodyInstructions); }); newIdToParameterOrdinalMap.getLocalParameterOffset(instructions, closureParameterOffset -> new Instruction(Instruction.OPCODE_SP_NEW_CLOSURE, closureParameterOffset, closureParameterCount)); } return null; } private void appendGroup(List<ExpressionContext> group, boolean lastMustBeExpression, BodyVisitor expressionVisitor) { // Only last expression have a pop instruction appended for(int i = 0; i < group.size(); i++) { if(lastMustBeExpression) expressionVisitor.mustBeExpression = i == group.size() - 1; // If last else expressionVisitor.mustBeExpression = false; group.get(i).accept(expressionVisitor); } } @Override public Object visitPseudoVar(PseudoVarContext ctx) { switch(ctx.PSEUDO_VAR().getText()) { case "this": instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS)); break; case "null": instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL)); break; case "true": instructions.add(new Instruction(Instruction.OPCODE_LOAD_TRUE)); break; case "false": instructions.add(new Instruction(Instruction.OPCODE_LOAD_FALSE)); break; case "frame": instructions.add(new Instruction(Instruction.OPCODE_LOAD_FRAME)); break; } return null; } @Override public Object visitInteger(IntegerContext ctx) { if(mustBeExpression) { int value = Integer.parseInt(ctx.INT().getText()); instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, value)); } return null; } @Override public Object visitString(StringContext ctx) { if(mustBeExpression) { String rawString = ctx.getText(); // Should the string enter properly prepared? // - i.e., no need for filtering the string. String string = extractStringLiteral(rawString); instructions.add(new Instruction(Instruction.OPCODE_LOAD_STRING, string)); } return null; } private static String getSelectorId(SelectorContext ctx) { return ctx.getText(); } private static String extractStringLiteral(String rawString) { return rawString.substring(1, rawString.length() - 1) .replace("\\n", "\n") .replace("\\r", "\r") .replace("\\t", "\t"); } private void onEnd(Supplier<Instruction> instructionSup) { int index = instructions.size(); instructions.add(null); endHandlers.add(() -> { Instruction instruction = instructionSup.get(); instructions.set(index, instruction); }); } private void appendError(ParserRuleContext ctx, String message) { appendError(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine(), message); } private void appendError(int line, int charPositionInLine, String message) { errors.appendMessage(line, charPositionInLine, message); } }
eclipse/src/duro/reflang/BodyVisitor.java
package duro.reflang; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTreeVisitor; import duro.reflang.antlr4_2.DuroBaseVisitor; import duro.reflang.antlr4_2.DuroLexer; import duro.reflang.antlr4_2.DuroParser.AccessContext; import duro.reflang.antlr4_2.DuroParser.AssignmentContext; import duro.reflang.antlr4_2.DuroParser.BehaviorParamsContext; import duro.reflang.antlr4_2.DuroParser.BinaryMessageContext; import duro.reflang.antlr4_2.DuroParser.BinaryMessageOperandChainContext; import duro.reflang.antlr4_2.DuroParser.BinaryMessageOperandContext; import duro.reflang.antlr4_2.DuroParser.ClosureContext; import duro.reflang.antlr4_2.DuroParser.DictContext; import duro.reflang.antlr4_2.DuroParser.DictEntryContext; import duro.reflang.antlr4_2.DuroParser.ExpressionContext; import duro.reflang.antlr4_2.DuroParser.GroupingContext; import duro.reflang.antlr4_2.DuroParser.IdContext; import duro.reflang.antlr4_2.DuroParser.IndexAccessContext; import duro.reflang.antlr4_2.DuroParser.IntegerContext; import duro.reflang.antlr4_2.DuroParser.InterfaceIdContext; import duro.reflang.antlr4_2.DuroParser.MessageChainContext; import duro.reflang.antlr4_2.DuroParser.MessageExchangeContext; import duro.reflang.antlr4_2.DuroParser.MultiArgMessageArgNoParChainContext; import duro.reflang.antlr4_2.DuroParser.MultiArgMessageArgNoParContext; import duro.reflang.antlr4_2.DuroParser.MultiArgMessageArgsNoParContext; import duro.reflang.antlr4_2.DuroParser.MultiArgMessageArgsWithParContext; import duro.reflang.antlr4_2.DuroParser.MultiArgMessageNoParContext; import duro.reflang.antlr4_2.DuroParser.MultiArgMessageWithParContext; import duro.reflang.antlr4_2.DuroParser.ParArgContext; import duro.reflang.antlr4_2.DuroParser.ProgramContext; import duro.reflang.antlr4_2.DuroParser.PseudoVarContext; import duro.reflang.antlr4_2.DuroParser.SelectorContext; import duro.reflang.antlr4_2.DuroParser.SelfMultiArgMessageNoParContext; import duro.reflang.antlr4_2.DuroParser.SelfMultiArgMessageWithParContext; import duro.reflang.antlr4_2.DuroParser.SelfSingleArgMessageNoParContext; import duro.reflang.antlr4_2.DuroParser.SingleArgMessageNoParContext; import duro.reflang.antlr4_2.DuroParser.SlotAccessContext; import duro.reflang.antlr4_2.DuroParser.SlotAssignmentContext; import duro.reflang.antlr4_2.DuroParser.StringContext; import duro.reflang.antlr4_2.DuroParser.VariableDeclarationContext; import duro.runtime.Instruction; import duro.runtime.Selector; public class BodyVisitor extends DuroBaseVisitor<Object> { private Hashtable<Selector, PrimitiveVisitorFactory> primitiveMap; private MessageCollector errors; private ArrayList<Runnable> endHandlers; private ArrayList<Instruction> instructions; private boolean mustBeExpression; private OrdinalAllocator idToParameterOrdinalMap; private OrdinalAllocator idToVariableOrdinalMap; public BodyVisitor(Hashtable<Selector, PrimitiveVisitorFactory> primitiveMap, MessageCollector errors, ArrayList<Runnable> endHandlers) { this.primitiveMap = primitiveMap; this.errors = errors; this.endHandlers = endHandlers; this.instructions = new ArrayList<Instruction>(); this.mustBeExpression = true; this.idToParameterOrdinalMap = new OrdinalAllocator(); this.idToVariableOrdinalMap = new OrdinalAllocator(); } public BodyVisitor(Hashtable<Selector, PrimitiveVisitorFactory> primitiveMap, MessageCollector errors, ArrayList<Runnable> endHandlers, ArrayList<Instruction> instructions, boolean mustBeExpression, OrdinalAllocator idToParameterOrdinalMap, OrdinalAllocator idToVariableOrdinalMap) { this.primitiveMap = primitiveMap; this.errors = errors; this.endHandlers = endHandlers; this.instructions = instructions; this.mustBeExpression = mustBeExpression; this.idToParameterOrdinalMap = idToParameterOrdinalMap; this.idToVariableOrdinalMap = idToVariableOrdinalMap; } @Override public Object visitProgram(ProgramContext ctx) { BodyVisitor rootExpressionInterceptor = new BodyVisitor(primitiveMap, errors, endHandlers, instructions, false, idToParameterOrdinalMap, idToVariableOrdinalMap); for(int i = 0; i < ctx.expression().size() ; i++) ctx.expression(i).accept(rootExpressionInterceptor); instructions.add(new Instruction(Instruction.OPCODE_FINISH)); return null; } @Override public Object visitInterfaceId(InterfaceIdContext ctx) { idToVariableOrdinalMap = idToVariableOrdinalMap.newInnerStart(); String interfaceId = ctx.id().getText(); instructions.add(new Instruction(Instruction.OPCODE_EXTEND_INTER_ID, interfaceId)); ctx.expression().accept(this); instructions.add(new Instruction(Instruction.OPCODE_SHRINK_INTER_ID)); idToVariableOrdinalMap = idToVariableOrdinalMap.getOuter(); return null; } @Override public Object visitMessageExchange(MessageExchangeContext ctx) { if(!mustBeExpression) { if(ctx.messageChain() != null) { BodyVisitor messageExchangeVisitor = new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap); ctx.receiver().accept(messageExchangeVisitor); MessageChainContext chain = ctx.messageChain(); while(chain != null) { messageExchangeVisitor.mustBeExpression = chain.messageChain() != null; chain.accept(messageExchangeVisitor); chain = chain.messageChain(); } } else { ctx.receiver().accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, false, idToParameterOrdinalMap, idToVariableOrdinalMap)); } } else { super.visitMessageExchange(ctx); } return false; } @Override public Object visitBinaryMessageOperand(BinaryMessageOperandContext ctx) { if(!mustBeExpression) { if(ctx.binaryMessageOperandChain() != null) { BodyVisitor messageExchangeVisitor = new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap); ctx.receiver().accept(messageExchangeVisitor); BinaryMessageOperandChainContext chain = ctx.binaryMessageOperandChain(); while(chain != null) { messageExchangeVisitor.mustBeExpression = chain.binaryMessageOperandChain() != null; chain.accept(messageExchangeVisitor); chain = chain.binaryMessageOperandChain(); } } else { ctx.receiver().accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, false, idToParameterOrdinalMap, idToVariableOrdinalMap)); } } else { super.visitBinaryMessageOperand(ctx); } return false; } @Override public Object visitMultiArgMessageArgNoPar(MultiArgMessageArgNoParContext ctx) { if(!mustBeExpression) { if(ctx.multiArgMessageArgNoParChain() != null) { BodyVisitor messageExchangeVisitor = new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap); ctx.multiArgMessageArgNoParReceiver().accept(messageExchangeVisitor); MultiArgMessageArgNoParChainContext chain = ctx.multiArgMessageArgNoParChain(); while(chain != null) { messageExchangeVisitor.mustBeExpression = chain.multiArgMessageArgNoParChain() != null; chain.accept(messageExchangeVisitor); chain = chain.multiArgMessageArgNoParChain(); } } else { ctx.multiArgMessageArgNoParReceiver().accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, false, idToParameterOrdinalMap, idToVariableOrdinalMap)); } } else { super.visitMultiArgMessageArgNoPar(ctx); } return false; } @Override public Object visitVariableDeclaration(VariableDeclarationContext ctx) { if(!idToVariableOrdinalMap.isDeclaredLocally(ctx.id().getText()) && !idToParameterOrdinalMap.isDeclared(ctx.id().getText())) { idToVariableOrdinalMap.declare(ctx.id().getText()); if(ctx.expression() == null) { if(mustBeExpression) instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL)); } else { ctx.expression().accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap)); if(mustBeExpression) instructions.add(new Instruction(Instruction.OPCODE_DUP)); idToVariableOrdinalMap.declare(ctx.id().getText(), instructions, variableOrdinal -> new Instruction(Instruction.OPCODE_STORE_LOC, variableOrdinal)); } } else { appendError(ctx, "Variable '" + ctx.id().getText() + "' is already declared in this scope."); } return null; } @Override public Object visitBinaryMessage(BinaryMessageContext ctx) { visitChildren(ctx); String id = ctx.BIN_OP().getText(); instructions.add(new Instruction(Instruction.OPCODE_SEND, id, 1)); if(!mustBeExpression) instructions.add(new Instruction(Instruction.OPCODE_POP)); return null; } @Override public Object visitSelfMultiArgMessageNoPar(SelfMultiArgMessageNoParContext ctx) { appendMultiArgMessageNoPar(ctx.multiArgMessageNoPar(), true); return null; } @Override public Object visitMultiArgMessageNoPar(MultiArgMessageNoParContext ctx) { appendMultiArgMessageNoPar(ctx, false); return null; } private void appendMultiArgMessageNoPar(MultiArgMessageNoParContext ctx, boolean isForSelf) { String id = ctx.ID_UNCAP().getText() + ctx.ID_CAP().stream().map(x -> x.getText()).collect(Collectors.joining()); ArrayList<ParserRuleContext> args = new ArrayList<ParserRuleContext>(); for(MultiArgMessageArgsNoParContext argsCtx: ctx.multiArgMessageArgsNoPar()) { for(MultiArgMessageArgNoParContext argCtx: argsCtx.multiArgMessageArgNoPar()) args.add(argCtx); } appendMultiArgMessage(id, args, isForSelf); } @Override public Object visitSelfMultiArgMessageWithPar(SelfMultiArgMessageWithParContext ctx) { appendMultiArgMessageWithPar(ctx.multiArgMessageWithPar(), true); return null; } @Override public Object visitMultiArgMessageWithPar(MultiArgMessageWithParContext ctx) { appendMultiArgMessageWithPar(ctx, false); return null; } private void appendMultiArgMessageWithPar(MultiArgMessageWithParContext ctx, boolean isForSelf) { String id = ctx.ID_UNCAP().getText() + ctx.ID_CAP().stream().map(x -> x.getText()).collect(Collectors.joining()); ArrayList<ParserRuleContext> args = new ArrayList<ParserRuleContext>(); for(MultiArgMessageArgsWithParContext argsCtx: ctx.multiArgMessageArgsWithPar()) { for(ExpressionContext argCtx: argsCtx.expression()) args.add(argCtx); } appendMultiArgMessage(id, args, isForSelf); } @Override public Object visitSelfSingleArgMessageNoPar(SelfSingleArgMessageNoParContext ctx) { appendMultiArgMessage(ctx.singleArgMessageNoPar().ID_UNCAP().getText(), Arrays.asList(ctx.singleArgMessageNoPar().singleArgMessageArgsNoPar()), true); return null; } @Override public Object visitSingleArgMessageNoPar(SingleArgMessageNoParContext ctx) { appendMultiArgMessage(ctx.ID_UNCAP().getText(), Arrays.asList(ctx .singleArgMessageArgsNoPar()), false); return null; } protected void appendMultiArgMessage(String id, List<ParserRuleContext> args, boolean isForSelf) { int parameterCount = args.size(); PrimitiveVisitorFactory primitiveVisitorFactory = primitiveMap.get(Selector.get(id, parameterCount)); if(primitiveVisitorFactory != null) { PrimitiveVisitor primitiveInterceptor = primitiveVisitorFactory.create(primitiveMap, errors, endHandlers, instructions, mustBeExpression, idToParameterOrdinalMap, idToVariableOrdinalMap); primitiveInterceptor.visitPrimitive(id, args); } else { if(isForSelf) instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS)); ParseTreeVisitor<Object> argsVisitor = mustBeExpression ? this : new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap); for(ParserRuleContext argCtx: args) argCtx.accept(argsVisitor); instructions.add(new Instruction(Instruction.OPCODE_SEND, id, parameterCount)); if(!mustBeExpression) instructions.add(new Instruction(Instruction.OPCODE_POP)); } } @Override public Object visitGrouping(GroupingContext ctx) { BodyVisitor expressionVisitor = new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap); appendGroup(ctx.expression(), mustBeExpression, expressionVisitor); return null; } @Override public Object visitAssignment(AssignmentContext ctx) { String id = ctx.id().getText(); switch(ctx.op.getType()) { case DuroLexer.ASSIGN: { // newValue, newValue if(idToVariableOrdinalMap.isDeclared(id)) appendAssignVariable(ctx.expression(), id); else { instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS)); appendAssignSlot(ctx.expression(), id, mustBeExpression); } break; } case DuroLexer.ASSIGN_PROTO: { instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS)); appendAssignProto(ctx.expression(), id, mustBeExpression); break; } } // Quoted member assignment for this if(ctx.op.getType() == DuroLexer.ASSIGN_QUOTED) { instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS)); appendAssignQuoted(ctx.behaviorParams(), ctx.expression(), id, mustBeExpression); } return null; } @Override public Object visitSlotAssignment(SlotAssignmentContext ctx) { String id = ctx.id().getText(); switch(ctx.op.getType()) { case DuroLexer.ASSIGN: { appendAssignSlot(ctx.expression(), id, mustBeExpression); break; } case DuroLexer.ASSIGN_PROTO: { appendAssignProto(ctx.expression(), id, mustBeExpression); break; } case DuroLexer.ASSIGN_QUOTED: { appendAssignQuoted(ctx.behaviorParams(), ctx.expression(), id, mustBeExpression); break; } } return null; } public Object visitIndexAssignment(duro.reflang.antlr4_2.DuroParser.IndexAssignmentContext ctx) { // receiver ExpressionContext indexCtx = ctx.expression(0); indexCtx.accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap)); // receiver, index ExpressionContext valueCtx = ctx.expression(1); valueCtx.accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap)); // receiver, index, value instructions.add(new Instruction(Instruction.OPCODE_SEND, "[]", 2)); // result if(!mustBeExpression) instructions.add(new Instruction(Instruction.OPCODE_POP)); return null; } private void appendAssignVariable(ExpressionContext valueCtx, String id) { valueCtx.accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap)); if(mustBeExpression) instructions.add(new Instruction(Instruction.OPCODE_DUP)); // Variable assignment idToVariableOrdinalMap.ordinalFor(id, instructions, firstOrdinal -> new Instruction(Instruction.OPCODE_STORE_LOC, firstOrdinal)); } private void appendAssignSlot(ExpressionContext valueCtx, String id, boolean returnValue) { appendAssignSlot(valueCtx, id, Instruction.OPCODE_SET, returnValue); } private void appendAssignProto(ExpressionContext valueCtx, String id, boolean returnValue) { appendAssignSlot(valueCtx, id, Instruction.OPCODE_SET_PROTO, returnValue); } private void appendAssignSlot(ExpressionContext valueCtx, String id, int opcodeAssign, boolean returnValue) { // receiver valueCtx.accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap)); // receiver, newValue if(returnValue) instructions.add(new Instruction(Instruction.OPCODE_DUP1)); // newValue, receiver, newValue instructions.add(new Instruction(opcodeAssign, id, 0)); // newValue | e } private void appendAssignQuoted(BehaviorParamsContext paramsCtx, ExpressionContext valueCtx, String id, boolean returnValue) { BodyVisitor functionBodyInterceptor = new BodyVisitor(primitiveMap, errors, endHandlers); for(IdContext parameterIdNode: paramsCtx.id()) { String parameterId = parameterIdNode.getText(); functionBodyInterceptor.idToParameterOrdinalMap.declare(parameterId); } valueCtx.accept(functionBodyInterceptor); functionBodyInterceptor.instructions.add(new Instruction(Instruction.OPCODE_RET)); int parameterCount = functionBodyInterceptor.idToParameterOrdinalMap.size(); int selectorParameterCount = functionBodyInterceptor.idToParameterOrdinalMap.sizeExceptEnd(); int variableCount = functionBodyInterceptor.idToVariableOrdinalMap.size(); functionBodyInterceptor.idToParameterOrdinalMap.generate(); functionBodyInterceptor.idToVariableOrdinalMap.generate(); onEnd(() -> { Instruction[] bodyInstructions = functionBodyInterceptor.instructions.toArray(new Instruction[functionBodyInterceptor.instructions.size()]); return new Instruction(Instruction.OPCODE_SP_NEW_BEHAVIOR, parameterCount, variableCount, bodyInstructions); }); if(returnValue) instructions.add(new Instruction(Instruction.OPCODE_DUP1)); instructions.add(new Instruction(Instruction.OPCODE_SET, id, selectorParameterCount)); } @Override public Object visitSlotAccess(SlotAccessContext ctx) { if(mustBeExpression) { String id = getSelectorId(ctx.selector()); instructions.add(new Instruction(Instruction.OPCODE_GET, id, 0)); } return null; } @Override public Object visitIndexAccess(IndexAccessContext ctx) { if(mustBeExpression) { ctx.expression().accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap)); instructions.add(new Instruction(Instruction.OPCODE_SEND, "[]", 1)); } return null; } @Override public Object visitAccess(AccessContext ctx) { if(mustBeExpression) { String id = ctx.id().getText(); if(idToParameterOrdinalMap.isDeclared(id)) { // Load argument idToParameterOrdinalMap.ordinalFor(id, instructions, parameterOrdinal -> new Instruction(Instruction.OPCODE_LOAD_ARG, parameterOrdinal)); return null; } if(idToVariableOrdinalMap.isDeclared(id)) { // Load variable idToVariableOrdinalMap.ordinalFor(id, instructions, variableOrdinal -> new Instruction(Instruction.OPCODE_LOAD_LOC, variableOrdinal)); return null; } // Get member instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS)); instructions.add(new Instruction(Instruction.OPCODE_GET, id, 0)); } return null; } @Override public Object visitParArg(ParArgContext ctx) { idToParameterOrdinalMap.declare(ctx.id().getText(), instructions, parameterOrdinal -> new Instruction(Instruction.OPCODE_LOAD_ARG, parameterOrdinal)); return null; } @Override public Object visitDict(DictContext ctx) { instructions.add(new Instruction(Instruction.OPCODE_SP_NEW_DICT)); for(DictEntryContext entryCtx: ctx.dictEntry()) { instructions.add(new Instruction(Instruction.OPCODE_DUP)); String id = getSelectorId(entryCtx.selector()); switch(entryCtx.op.getType()) { case DuroLexer.ASSIGN: appendAssignSlot(entryCtx.expression(), id, false); break; case DuroLexer.ASSIGN_PROTO: appendAssignProto(entryCtx.expression(), id, false); break; case DuroLexer.ASSIGN_QUOTED: appendAssignQuoted(entryCtx.behaviorParams(), entryCtx.expression(), id, false); break; } } return null; } @Override public Object visitClosure(ClosureContext ctx) { if(mustBeExpression) { OrdinalAllocator newIdToVariableOrdinalMap = idToVariableOrdinalMap.newInnerEnd(); OrdinalAllocator newIdToParameterOrdinalMap = idToParameterOrdinalMap.newInnerEnd(); BodyVisitor closureBodyInterceptor = new BodyVisitor(primitiveMap, errors, endHandlers, new ArrayList<Instruction>(), true, newIdToParameterOrdinalMap, newIdToVariableOrdinalMap); for(IdContext parameterIdNode: ctx.behaviorParams().id()) { String parameterId = parameterIdNode.getText(); closureBodyInterceptor.idToParameterOrdinalMap.declare(parameterId); } appendGroup(ctx.expression(), true, closureBodyInterceptor); closureBodyInterceptor.instructions.add(new Instruction(Instruction.OPCODE_RET)); int parameterCount = closureBodyInterceptor.idToParameterOrdinalMap.size(); int closureParameterCount = closureBodyInterceptor.idToParameterOrdinalMap.sizeExceptEnd(); int variableCount = closureBodyInterceptor.idToVariableOrdinalMap.size(); closureBodyInterceptor.idToParameterOrdinalMap.generate(); closureBodyInterceptor.idToVariableOrdinalMap.generate(); onEnd(() -> { Instruction[] bodyInstructions = closureBodyInterceptor.instructions.toArray(new Instruction[closureBodyInterceptor.instructions.size()]); return new Instruction(Instruction.OPCODE_SP_NEW_BEHAVIOR, parameterCount, variableCount, bodyInstructions); }); newIdToParameterOrdinalMap.getLocalParameterOffset(instructions, closureParameterOffset -> new Instruction(Instruction.OPCODE_SP_NEW_CLOSURE, closureParameterOffset, closureParameterCount)); } return null; } private void appendGroup(List<ExpressionContext> group, boolean lastMustBeExpression, BodyVisitor expressionVisitor) { // Only last expression have a pop instruction appended for(int i = 0; i < group.size(); i++) { if(lastMustBeExpression) expressionVisitor.mustBeExpression = i == group.size() - 1; // If last else expressionVisitor.mustBeExpression = false; group.get(i).accept(expressionVisitor); } } @Override public Object visitPseudoVar(PseudoVarContext ctx) { switch(ctx.PSEUDO_VAR().getText()) { case "this": instructions.add(new Instruction(Instruction.OPCODE_LOAD_THIS)); break; case "null": instructions.add(new Instruction(Instruction.OPCODE_LOAD_NULL)); break; case "true": instructions.add(new Instruction(Instruction.OPCODE_LOAD_TRUE)); break; case "false": instructions.add(new Instruction(Instruction.OPCODE_LOAD_FALSE)); break; case "frame": instructions.add(new Instruction(Instruction.OPCODE_LOAD_FRAME)); break; } return null; } @Override public Object visitInteger(IntegerContext ctx) { if(mustBeExpression) { int value = Integer.parseInt(ctx.INT().getText()); instructions.add(new Instruction(Instruction.OPCODE_LOAD_INT, value)); } return null; } @Override public Object visitString(StringContext ctx) { if(mustBeExpression) { String rawString = ctx.getText(); // Should the string enter properly prepared? // - i.e., no need for filtering the string. String string = extractStringLiteral(rawString); instructions.add(new Instruction(Instruction.OPCODE_LOAD_STRING, string)); } return null; } private static String getSelectorId(SelectorContext ctx) { return ctx.getText(); } private static String extractStringLiteral(String rawString) { return rawString.substring(1, rawString.length() - 1) .replace("\\n", "\n") .replace("\\r", "\r") .replace("\\t", "\t"); } private void onEnd(Supplier<Instruction> instructionSup) { int index = instructions.size(); instructions.add(null); endHandlers.add(() -> { Instruction instruction = instructionSup.get(); instructions.set(index, instruction); }); } private void appendError(ParserRuleContext ctx, String message) { appendError(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine(), message); } private void appendError(int line, int charPositionInLine, String message) { errors.appendMessage(line, charPositionInLine, message); } }
Removed support for single arg no parenthesis message in compilation logic. Signed-off-by: Jakob Brandsborg Ehmsen <[email protected]>
eclipse/src/duro/reflang/BodyVisitor.java
Removed support for single arg no parenthesis message in compilation logic.
<ide><path>clipse/src/duro/reflang/BodyVisitor.java <ide> import duro.reflang.antlr4_2.DuroParser.SelectorContext; <ide> import duro.reflang.antlr4_2.DuroParser.SelfMultiArgMessageNoParContext; <ide> import duro.reflang.antlr4_2.DuroParser.SelfMultiArgMessageWithParContext; <del>import duro.reflang.antlr4_2.DuroParser.SelfSingleArgMessageNoParContext; <del>import duro.reflang.antlr4_2.DuroParser.SingleArgMessageNoParContext; <ide> import duro.reflang.antlr4_2.DuroParser.SlotAccessContext; <ide> import duro.reflang.antlr4_2.DuroParser.SlotAssignmentContext; <ide> import duro.reflang.antlr4_2.DuroParser.StringContext; <ide> if(!mustBeExpression) { <ide> if(ctx.multiArgMessageArgNoParChain() != null) { <ide> BodyVisitor messageExchangeVisitor = new BodyVisitor(primitiveMap, errors, endHandlers, instructions, true, idToParameterOrdinalMap, idToVariableOrdinalMap); <del> ctx.multiArgMessageArgNoParReceiver().accept(messageExchangeVisitor); <add> ctx.receiver().accept(messageExchangeVisitor); <ide> <ide> MultiArgMessageArgNoParChainContext chain = ctx.multiArgMessageArgNoParChain(); <ide> <ide> } <ide> <ide> } else { <del> ctx.multiArgMessageArgNoParReceiver().accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, false, idToParameterOrdinalMap, idToVariableOrdinalMap)); <add> ctx.receiver().accept(new BodyVisitor(primitiveMap, errors, endHandlers, instructions, false, idToParameterOrdinalMap, idToVariableOrdinalMap)); <ide> } <ide> } else { <ide> super.visitMultiArgMessageArgNoPar(ctx); <ide> } <ide> <ide> appendMultiArgMessage(id, args, isForSelf); <del> } <del> <del> @Override <del> public Object visitSelfSingleArgMessageNoPar(SelfSingleArgMessageNoParContext ctx) { <del> appendMultiArgMessage(ctx.singleArgMessageNoPar().ID_UNCAP().getText(), Arrays.asList(ctx.singleArgMessageNoPar().singleArgMessageArgsNoPar()), true); <del> <del> return null; <del> } <del> <del> @Override <del> public Object visitSingleArgMessageNoPar(SingleArgMessageNoParContext ctx) { <del> appendMultiArgMessage(ctx.ID_UNCAP().getText(), Arrays.asList(ctx .singleArgMessageArgsNoPar()), false); <del> <del> return null; <ide> } <ide> <ide> protected void appendMultiArgMessage(String id, List<ParserRuleContext> args, boolean isForSelf) {
Java
mit
bcb64dce19e928897c3bd5f73116a89402d19590
0
aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.util.Optional; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); String[] columnNames = {"Integer", "Integer", "Boolean"}; Object[][] data = { {50, 50, false}, {13, 13, true}, {0, 0, false}, {20, 20, true}, {99, 99, false} }; TableModel model = new DefaultTableModel(data, columnNames) { @Override public Class<?> getColumnClass(int column) { return getValueAt(0, column).getClass(); } @Override public boolean isCellEditable(int row, int column) { return column != 0; } }; JTable table = new JTable(model) { @Override public void updateUI() { super.updateUI(); putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); setAutoCreateRowSorter(true); setRowHeight(26); getColumnModel().getColumn(1).setCellRenderer(new SliderRenderer()); getColumnModel().getColumn(1).setCellEditor(new SliderEditor()); } @Override public Color getSelectionBackground() { Color bc = super.getSelectionBackground(); return Optional.ofNullable(bc).map(Color::brighter).orElse(bc); } }; add(new JScrollPane(table)); setPreferredSize(new Dimension(320, 240)); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } // delegation pattern class SliderRenderer implements TableCellRenderer { private final JSlider renderer = new JSlider(); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { renderer.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); if (value instanceof Integer) { renderer.setValue((Integer) value); } return renderer; } } class SliderEditor extends AbstractCellEditor implements TableCellEditor { private final JSlider renderer = new JSlider(); private int prev; protected SliderEditor() { super(); renderer.setOpaque(true); renderer.addChangeListener(e -> { Object o = SwingUtilities.getAncestorOfClass(JTable.class, renderer); if (o instanceof JTable) { JTable table = (JTable) o; int value = renderer.getValue(); if (table.isEditing() && value != prev) { int row = table.convertRowIndexToModel(table.getEditingRow()); table.getModel().setValueAt(value, row, 0); table.getModel().setValueAt(value, row, 1); prev = value; } } }); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { renderer.setValue((Integer) value); renderer.setBackground(table.getSelectionBackground()); return renderer; } @Override public Object getCellEditorValue() { return renderer.getValue(); } } // // inheritance to extend a class // class SliderRenderer extends JSlider implements TableCellRenderer { // @Override public void updateUI() { // super.updateUI(); // setName("Table.cellRenderer"); // setOpaque(true); // } // // @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // this.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); // if (value instanceof Integer) { // this.setValue(((Integer) value).intValue()); // } // return this; // } // // // Overridden for performance reasons. ----> // @Override public boolean isOpaque() { // Color back = getBackground(); // Object o = SwingUtilities.getAncestorOfClass(JTable.class, this); // if (o instanceof JTable) { // JTable table = (JTable) o; // boolean colorMatch = Objects.nonNull(back) && back.equals(table.getBackground()) && table.isOpaque(); // return !colorMatch && super.isOpaque(); // } else { // return super.isOpaque(); // } // } // // @Override protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { // // // System.out.println(propertyName); // // if ((propertyName == "font" || propertyName == "foreground") && oldValue != newValue) { // // super.firePropertyChange(propertyName, oldValue, newValue); // // } // } // // @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { // /* Overridden for performance reasons. */ // } // // @Override public void repaint(long tm, int x, int y, int width, int height) { // /* Overridden for performance reasons. */ // } // // @Override public void repaint(Rectangle r) { // /* Overridden for performance reasons. */ // } // // @Override public void repaint() { // /* Overridden for performance reasons. */ // } // // @Override public void invalidate() { // /* Overridden for performance reasons. */ // } // // @Override public void validate() { // /* Overridden for performance reasons. */ // } // // @Override public void revalidate() { // /* Overridden for performance reasons. */ // } // // <---- Overridden for performance reasons. // } // // class SliderEditor extends JSlider implements TableCellEditor { // private transient ChangeListener handler; // private int prev; // @Override public void updateUI() { // removeChangeListener(handler); // super.updateUI(); // setOpaque(true); // handler = e -> { // Object o = SwingUtilities.getAncestorOfClass(JTable.class, this); // if (o instanceof JTable) { // JTable table = (JTable) o; // int value = getValue(); // if (table.isEditing() && value != prev) { // int row = table.convertRowIndexToModel(table.getEditingRow()); // table.getModel().setValueAt(value, row, 0); // table.getModel().setValueAt(value, row, 1); // prev = value; // } // } // }; // addChangeListener(handler); // } // // @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { // Integer i = (Integer) value; // this.setBackground(table.getSelectionBackground()); // this.setValue(i.intValue()); // return this; // } // // @Override public Object getCellEditorValue() { // return Integer.valueOf(getValue()); // } // // // Copied from AbstractCellEditor // // protected EventListenerList listenerList = new EventListenerList(); // // protected transient ChangeEvent changeEvent; // @Override public boolean isCellEditable(EventObject e) { // return true; // } // // @Override public boolean shouldSelectCell(EventObject anEvent) { // return true; // } // // @Override public boolean stopCellEditing() { // fireEditingStopped(); // return true; // } // // @Override public void cancelCellEditing() { // fireEditingCanceled(); // } // // @Override public void addCellEditorListener(CellEditorListener l) { // listenerList.add(CellEditorListener.class, l); // } // // @Override public void removeCellEditorListener(CellEditorListener l) { // listenerList.remove(CellEditorListener.class, l); // } // // public CellEditorListener[] getCellEditorListeners() { // return listenerList.getListeners(CellEditorListener.class); // } // // protected void fireEditingStopped() { // // Guaranteed to return a non-null array // Object[] listeners = listenerList.getListenerList(); // // Process the listeners last to first, notifying // // those that are interested in this event // for (int i = listeners.length - 2; i >= 0; i -= 2) { // if (listeners[i] == CellEditorListener.class) { // // Lazily create the event: // if (Objects.isNull(changeEvent)) { // changeEvent = new ChangeEvent(this); // } // ((CellEditorListener) listeners[i + 1]).editingStopped(changeEvent); // } // } // } // // protected void fireEditingCanceled() { // // Guaranteed to return a non-null array // Object[] listeners = listenerList.getListenerList(); // // Process the listeners last to first, notifying // // those that are interested in this event // for (int i = listeners.length - 2; i >= 0; i -= 2) { // if (listeners[i] == CellEditorListener.class) { // // Lazily create the event: // if (Objects.isNull(changeEvent)) { // changeEvent = new ChangeEvent(this); // } // ((CellEditorListener) listeners[i + 1]).editingCanceled(changeEvent); // } // } // } // }
SliderInTableCell/src/java/example/MainPanel.java
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.util.Optional; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); String[] columnNames = {"Integer", "Integer", "Boolean"}; Object[][] data = { {50, 50, false}, {13, 13, true}, {0, 0, false}, {20, 20, true}, {99, 99, false} }; TableModel model = new DefaultTableModel(data, columnNames) { @Override public Class<?> getColumnClass(int column) { return getValueAt(0, column).getClass(); } @Override public boolean isCellEditable(int row, int column) { return column != 0; } }; JTable table = new JTable(model) { @Override public void updateUI() { super.updateUI(); putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); setAutoCreateRowSorter(true); setRowHeight(26); getColumnModel().getColumn(1).setCellRenderer(new SliderRednerer()); getColumnModel().getColumn(1).setCellEditor(new SliderEditor()); } @Override public Color getSelectionBackground() { Color bc = super.getSelectionBackground(); return Optional.ofNullable(bc).map(Color::brighter).orElse(bc); } }; add(new JScrollPane(table)); setPreferredSize(new Dimension(320, 240)); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } // delegation pattern class SliderRednerer implements TableCellRenderer { private final JSlider renderer = new JSlider(); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { renderer.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); if (value instanceof Integer) { renderer.setValue(((Integer) value).intValue()); } return renderer; } } class SliderEditor extends AbstractCellEditor implements TableCellEditor { private final JSlider renderer = new JSlider(); private int prev; protected SliderEditor() { super(); renderer.setOpaque(true); renderer.addChangeListener(e -> { Object o = SwingUtilities.getAncestorOfClass(JTable.class, renderer); if (o instanceof JTable) { JTable table = (JTable) o; int value = renderer.getValue(); if (table.isEditing() && value != prev) { int row = table.convertRowIndexToModel(table.getEditingRow()); table.getModel().setValueAt(value, row, 0); table.getModel().setValueAt(value, row, 1); prev = value; } } }); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { Integer i = (Integer) value; renderer.setBackground(table.getSelectionBackground()); renderer.setValue(i.intValue()); return renderer; } @Override public Object getCellEditorValue() { return Integer.valueOf(renderer.getValue()); } } // // inheritence to extend a class // class SliderRednerer extends JSlider implements TableCellRenderer { // @Override public void updateUI() { // super.updateUI(); // setName("Table.cellRenderer"); // setOpaque(true); // } // @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // this.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); // if (value instanceof Integer) { // this.setValue(((Integer) value).intValue()); // } // return this; // } // // Overridden for performance reasons. ----> // @Override public boolean isOpaque() { // Color back = getBackground(); // Object o = SwingUtilities.getAncestorOfClass(JTable.class, this); // if (o instanceof JTable) { // JTable table = (JTable) o; // boolean colorMatch = Objects.nonNull(back) && back.equals(table.getBackground()) && table.isOpaque(); // return !colorMatch && super.isOpaque(); // } else { // return super.isOpaque(); // } // } // @Override protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { // // // System.out.println(propertyName); // // if ((propertyName == "font" || propertyName == "foreground") && oldValue != newValue) { // // super.firePropertyChange(propertyName, oldValue, newValue); // // } // } // @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { /* Overridden for performance reasons. */ } // @Override public void repaint(long tm, int x, int y, int width, int height) { /* Overridden for performance reasons. */ } // @Override public void repaint(Rectangle r) { /* Overridden for performance reasons. */ } // @Override public void repaint() { /* Overridden for performance reasons. */ } // @Override public void invalidate() { /* Overridden for performance reasons. */ } // @Override public void validate() { /* Overridden for performance reasons. */ } // @Override public void revalidate() { /* Overridden for performance reasons. */ } // // <---- Overridden for performance reasons. // } // // class SliderEditor extends JSlider implements TableCellEditor { // private transient ChangeListener handler; // private int prev; // @Override public void updateUI() { // removeChangeListener(handler); // super.updateUI(); // setOpaque(true); // handler = e -> { // Object o = SwingUtilities.getAncestorOfClass(JTable.class, this); // if (o instanceof JTable) { // JTable table = (JTable) o; // int value = getValue(); // if (table.isEditing() && value != prev) { // int row = table.convertRowIndexToModel(table.getEditingRow()); // table.getModel().setValueAt(value, row, 0); // table.getModel().setValueAt(value, row, 1); // prev = value; // } // } // }; // addChangeListener(handler); // } // @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { // Integer i = (Integer) value; // this.setBackground(table.getSelectionBackground()); // this.setValue(i.intValue()); // return this; // } // @Override public Object getCellEditorValue() { // return Integer.valueOf(getValue()); // } // // // Copied from AbstractCellEditor // // protected EventListenerList listenerList = new EventListenerList(); // // protected transient ChangeEvent changeEvent; // @Override public boolean isCellEditable(EventObject e) { // return true; // } // @Override public boolean shouldSelectCell(EventObject anEvent) { // return true; // } // @Override public boolean stopCellEditing() { // fireEditingStopped(); // return true; // } // @Override public void cancelCellEditing() { // fireEditingCanceled(); // } // @Override public void addCellEditorListener(CellEditorListener l) { // listenerList.add(CellEditorListener.class, l); // } // @Override public void removeCellEditorListener(CellEditorListener l) { // listenerList.remove(CellEditorListener.class, l); // } // public CellEditorListener[] getCellEditorListeners() { // return listenerList.getListeners(CellEditorListener.class); // } // protected void fireEditingStopped() { // // Guaranteed to return a non-null array // Object[] listeners = listenerList.getListenerList(); // // Process the listeners last to first, notifying // // those that are interested in this event // for (int i = listeners.length - 2; i >= 0; i -= 2) { // if (listeners[i] == CellEditorListener.class) { // // Lazily create the event: // if (Objects.isNull(changeEvent)) { // changeEvent = new ChangeEvent(this); // } // ((CellEditorListener) listeners[i + 1]).editingStopped(changeEvent); // } // } // } // protected void fireEditingCanceled() { // // Guaranteed to return a non-null array // Object[] listeners = listenerList.getListenerList(); // // Process the listeners last to first, notifying // // those that are interested in this event // for (int i = listeners.length - 2; i >= 0; i -= 2) { // if (listeners[i] == CellEditorListener.class) { // // Lazily create the event: // if (Objects.isNull(changeEvent)) { // changeEvent = new ChangeEvent(this); // } // ((CellEditorListener) listeners[i + 1]).editingCanceled(changeEvent); // } // } // } // }
refactor: fix typo Rednerer should be Renderer
SliderInTableCell/src/java/example/MainPanel.java
refactor: fix typo Rednerer should be Renderer
<ide><path>liderInTableCell/src/java/example/MainPanel.java <ide> putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); <ide> setAutoCreateRowSorter(true); <ide> setRowHeight(26); <del> getColumnModel().getColumn(1).setCellRenderer(new SliderRednerer()); <add> getColumnModel().getColumn(1).setCellRenderer(new SliderRenderer()); <ide> getColumnModel().getColumn(1).setCellEditor(new SliderEditor()); <ide> } <ide> <ide> } <ide> <ide> // delegation pattern <del>class SliderRednerer implements TableCellRenderer { <add>class SliderRenderer implements TableCellRenderer { <ide> private final JSlider renderer = new JSlider(); <ide> <ide> @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { <ide> renderer.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); <ide> if (value instanceof Integer) { <del> renderer.setValue(((Integer) value).intValue()); <add> renderer.setValue((Integer) value); <ide> } <ide> return renderer; <ide> } <ide> } <ide> <ide> @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { <del> Integer i = (Integer) value; <add> renderer.setValue((Integer) value); <ide> renderer.setBackground(table.getSelectionBackground()); <del> renderer.setValue(i.intValue()); <ide> return renderer; <ide> } <ide> <ide> @Override public Object getCellEditorValue() { <del> return Integer.valueOf(renderer.getValue()); <add> return renderer.getValue(); <ide> } <ide> } <ide> <del>// // inheritence to extend a class <del>// class SliderRednerer extends JSlider implements TableCellRenderer { <add>// // inheritance to extend a class <add>// class SliderRenderer extends JSlider implements TableCellRenderer { <ide> // @Override public void updateUI() { <ide> // super.updateUI(); <ide> // setName("Table.cellRenderer"); <ide> // setOpaque(true); <ide> // } <add>// <ide> // @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { <ide> // this.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); <ide> // if (value instanceof Integer) { <ide> // } <ide> // return this; <ide> // } <add>// <ide> // // Overridden for performance reasons. ----> <ide> // @Override public boolean isOpaque() { <ide> // Color back = getBackground(); <ide> // return super.isOpaque(); <ide> // } <ide> // } <add>// <ide> // @Override protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { <ide> // // // System.out.println(propertyName); <ide> // // if ((propertyName == "font" || propertyName == "foreground") && oldValue != newValue) { <ide> // // super.firePropertyChange(propertyName, oldValue, newValue); <ide> // // } <ide> // } <del>// @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { /* Overridden for performance reasons. */ } <del>// @Override public void repaint(long tm, int x, int y, int width, int height) { /* Overridden for performance reasons. */ } <del>// @Override public void repaint(Rectangle r) { /* Overridden for performance reasons. */ } <del>// @Override public void repaint() { /* Overridden for performance reasons. */ } <del>// @Override public void invalidate() { /* Overridden for performance reasons. */ } <del>// @Override public void validate() { /* Overridden for performance reasons. */ } <del>// @Override public void revalidate() { /* Overridden for performance reasons. */ } <add>// <add>// @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { <add>// /* Overridden for performance reasons. */ <add>// } <add>// <add>// @Override public void repaint(long tm, int x, int y, int width, int height) { <add>// /* Overridden for performance reasons. */ <add>// } <add>// <add>// @Override public void repaint(Rectangle r) { <add>// /* Overridden for performance reasons. */ <add>// } <add>// <add>// @Override public void repaint() { <add>// /* Overridden for performance reasons. */ <add>// } <add>// <add>// @Override public void invalidate() { <add>// /* Overridden for performance reasons. */ <add>// } <add>// <add>// @Override public void validate() { <add>// /* Overridden for performance reasons. */ <add>// } <add>// <add>// @Override public void revalidate() { <add>// /* Overridden for performance reasons. */ <add>// } <ide> // // <---- Overridden for performance reasons. <ide> // } <ide> // <ide> // }; <ide> // addChangeListener(handler); <ide> // } <add>// <ide> // @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { <ide> // Integer i = (Integer) value; <ide> // this.setBackground(table.getSelectionBackground()); <ide> // this.setValue(i.intValue()); <ide> // return this; <ide> // } <add>// <ide> // @Override public Object getCellEditorValue() { <ide> // return Integer.valueOf(getValue()); <ide> // } <ide> // @Override public boolean isCellEditable(EventObject e) { <ide> // return true; <ide> // } <add>// <ide> // @Override public boolean shouldSelectCell(EventObject anEvent) { <ide> // return true; <ide> // } <add>// <ide> // @Override public boolean stopCellEditing() { <ide> // fireEditingStopped(); <ide> // return true; <ide> // } <add>// <ide> // @Override public void cancelCellEditing() { <ide> // fireEditingCanceled(); <ide> // } <add>// <ide> // @Override public void addCellEditorListener(CellEditorListener l) { <ide> // listenerList.add(CellEditorListener.class, l); <ide> // } <add>// <ide> // @Override public void removeCellEditorListener(CellEditorListener l) { <ide> // listenerList.remove(CellEditorListener.class, l); <ide> // } <add>// <ide> // public CellEditorListener[] getCellEditorListeners() { <ide> // return listenerList.getListeners(CellEditorListener.class); <ide> // } <add>// <ide> // protected void fireEditingStopped() { <ide> // // Guaranteed to return a non-null array <ide> // Object[] listeners = listenerList.getListenerList(); <ide> // } <ide> // } <ide> // } <add>// <ide> // protected void fireEditingCanceled() { <ide> // // Guaranteed to return a non-null array <ide> // Object[] listeners = listenerList.getListenerList();
Java
mit
e5f4b7720da11ac9956464537fc422ddf2e6330f
0
DerTyan/Landlord,jcdesimp/Landlord
package com.jcdesimp.landlord; import com.jcdesimp.landlord.landManagement.LandManagerView; import com.jcdesimp.landlord.persistantData.Friend; import com.jcdesimp.landlord.persistantData.OwnedLand; import org.bukkit.*; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.jcdesimp.landlord.DarkBladee12.ParticleAPI.ParticleEffect; import java.util.ArrayList; import java.util.List; import static org.bukkit.Bukkit.getOfflinePlayer; import static org.bukkit.Bukkit.getPlayer; import static org.bukkit.Bukkit.getWorld; import static org.bukkit.util.NumberConversions.ceil; /** * Command Executor class for LandLord */ @SuppressWarnings("UnusedParameters") public class LandlordCommandExecutor implements CommandExecutor { private Landlord plugin; //pointer to main class public LandlordCommandExecutor(Landlord plugin){ this.plugin = plugin; } /** * Main command handler * @param sender who sent the command * @param label exact command (or alias) run * @param args given with command * @return boolean */ @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(cmd.getName().equalsIgnoreCase("landlord")){ // If the player typed /land then do the following... /* * **************************************************************** * Use private methods below to define command implementation * call those methods from within these cases * **************************************************************** */ if(args.length == 0){ //landlord return landlord_help(sender, args, label); } else if(args[0].equalsIgnoreCase("help")) { //landlord claim return landlord_help(sender, args, label); } else if(args[0].equalsIgnoreCase("claim") || args[0].equalsIgnoreCase("buy")) { //landlord claim return landlord_claim(sender, args); } else if(args[0].equalsIgnoreCase("unclaim") || args[0].equalsIgnoreCase("sell")) { //landlord unclaim return landlord_unclaim(sender, args, label); } else if(args[0].equalsIgnoreCase("addfriend") || args[0].equalsIgnoreCase("friend")) { //landlord addfriend return landlord_addfriend(sender, args); } else if(args[0].equalsIgnoreCase("friendall")) { //landlord addfriend return landlord_friendall(sender, args); } else if(args[0].equalsIgnoreCase("unfriendall")) { //landlord addfriend return landlord_unfriendall(sender, args); } else if(args[0].equalsIgnoreCase("remfriend") || args[0].equalsIgnoreCase("unfriend")) { return landlord_remfriend(sender, args); } else if(args[0].equalsIgnoreCase("map")) { return landlord_map(sender, args); //sender.sendMessage(ChatColor.RED+"Land map is temporarily disabled!"); //return true; } else if(args[0].equalsIgnoreCase("manage")) { return landlord_manage(sender, args); } else if(args[0].equalsIgnoreCase("list")) { return landlord_list(sender, args, label); } else if(args[0].equalsIgnoreCase("listplayer")) { return landlord_listplayer(sender, args, label); } else if(args[0].equalsIgnoreCase("clearworld")) { return landlord_clearWorld(sender, args, label); } else if(args[0].equalsIgnoreCase("reload")) { return landlord_reload(sender, args, label); } else if(args[0].equalsIgnoreCase("info")) { return landlord_info(sender, args, label); } else if(args[0].equalsIgnoreCase("friends")) { return landlord_friends(sender,args,label); } else { return landlord_help(sender, args, label); } } //If this has happened the function will return true. // If this hasn't happened the value of false will be returned. return false; } /* * ********************************************************** * private methods for handling each command functionality * ********************************************************** */ /** * Called when base command /landlord or aliases (/ll /land) * are executed with no parameters * * @param sender who executed the command * @return boolean */ private boolean landlord(CommandSender sender, String[] args, String label) { sender.sendMessage(ChatColor.DARK_GREEN + "--|| Landlord v"+Landlord.getInstance().getDescription().getVersion() + " Created by " + ChatColor.BLUE+"Jcdesimp "+ChatColor.DARK_GREEN +"||--\n"+ //ChatColor.GRAY+"(Aliases: /landlord, /land, or /ll)\n"+ ChatColor.DARK_GREEN+"Type " +ChatColor.YELLOW+"/"+label+" help "+ChatColor.DARK_GREEN +"for a list of commands"); return true; } private boolean landlord_help(CommandSender sender, String[] args, String label) { //check if page number is valid int pageNumber = 1; if (args.length > 1 && args[0].equals("help")){ try{ pageNumber = Integer.parseInt(args[1]);} catch (NumberFormatException e){ sender.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } } //List<OwnedLand> myLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getName()).findList(); String header = ChatColor.DARK_GREEN + "--|| Landlord v"+Landlord.getInstance().getDescription().getVersion() + " Created by " + ChatColor.BLUE+"Jcdesimp "+ChatColor.DARK_GREEN +"||--\n"+ ChatColor.GRAY+"(Aliases: /landlord, /land, or /ll)\n"; ArrayList<String> helpList = new ArrayList<String>(); helpList.add(ChatColor.DARK_AQUA+"/"+label + " help [page #]" + ChatColor.RESET + " - Show this help message.\n"); String claim = ChatColor.DARK_AQUA+"/"+label + " claim (or "+"/"+label +" buy)" + ChatColor.RESET + " - Claim this chunk.\n"; if(plugin.hasVault()){ if(plugin.getvHandler().hasEconomy() && plugin.getConfig().getDouble("economy.buyPrice", 100.0)>0){ claim += ChatColor.YELLOW+""+ChatColor.ITALIC+" Costs "+plugin.getvHandler().formatCash(plugin.getConfig().getDouble("economy.buyPrice", 100.0))+" to claim.\n"; } } helpList.add(claim); String unclaim = ChatColor.DARK_AQUA+"/"+label + " unclaim [x,z] [world] (or "+"/"+label +" sell)" + ChatColor.RESET + " - Unclaim this chunk.\n"; if (plugin.hasVault() && plugin.getvHandler().hasEconomy() && plugin.getConfig().getDouble("economy.sellPrice", 50.0) > 0) { if(plugin.getConfig().getBoolean("options.regenOnUnclaim",false)) { unclaim+=ChatColor.RED+""+ChatColor.ITALIC +" Regenerates Chunk!"; } unclaim += ChatColor.YELLOW + "" + ChatColor.ITALIC + " Get " + plugin.getvHandler().formatCash(plugin.getConfig().getDouble("economy.sellPrice", 50.0)) + " per unclaim.\n"; } else if(plugin.getConfig().getBoolean("options.regenOnUnclaim",false)) { unclaim+=ChatColor.RED+""+ChatColor.ITALIC +" Regenerates Chunk!\n"; } helpList.add(unclaim); helpList.add(ChatColor.DARK_AQUA+"/"+label + " addfriend <player>" + ChatColor.RESET + " - Add friend to this land.\n"); helpList.add(ChatColor.DARK_AQUA+"/"+label + " unfriend <player>" + ChatColor.RESET + " - Remove friend from this land.\n"); helpList.add(ChatColor.DARK_AQUA+"/"+label + " friendall <player>" + ChatColor.RESET + " - Add friend to all your land.\n"); helpList.add(ChatColor.DARK_AQUA+"/"+label + " unfriendall <player>" + ChatColor.RESET + " - Remove friend from all your land.\n"); helpList.add(ChatColor.DARK_AQUA+"/"+label + " friends" + ChatColor.RESET + " - List friends of this land.\n"); helpList.add(ChatColor.DARK_AQUA+"/"+label + " manage" + ChatColor.RESET + " - Manage permissions for this land.\n"); helpList.add(ChatColor.DARK_AQUA+"/"+label + " list" + ChatColor.RESET + " - List all your owned land.\n"); if(sender.hasPermission("landlord.player.map") && plugin.getConfig().getBoolean("options.enableMap",true)){ helpList.add(ChatColor.DARK_AQUA+"/"+label + " map" + ChatColor.RESET + " - Toggle the land map.\n"); } if(sender.hasPermission("landlord.player.info") && plugin.getConfig().getBoolean("options.enableMap",true)){ helpList.add(ChatColor.DARK_AQUA+"/"+label + " info" + ChatColor.RESET + " - View info about this chunk.\n"); } if(sender.hasPermission("landlord.admin.list")){ helpList.add(ChatColor.DARK_AQUA+"/"+label + " listplayer <player>" + ChatColor.RESET + " - List land owned by another player.\n"); } if(sender.hasPermission("landlord.admin.clearworld")){ String clearHelp = ChatColor.DARK_AQUA+"/"+label + " clearworld <world> [player]" + ChatColor.RESET + " - Delete all land owned by a player in a world." + " Delete all land of a world from console.\n"; if(plugin.getConfig().getBoolean("options.regenOnUnclaim",false)){ clearHelp += ChatColor.YELLOW+""+ChatColor.ITALIC+" Does not regenerate chunks.\n"; } helpList.add(clearHelp); } if(sender.hasPermission("landlord.admin.reload")){ helpList.add(ChatColor.DARK_AQUA+"/"+label + " reload" + ChatColor.RESET + " - Reloads the Landlord config file.\n"); } //OwnedLand curr = myLand.get(0); //Amount to be displayed per page final int numPerPage = 5; int numPages = ceil((double)helpList.size()/(double)numPerPage); if(pageNumber > numPages){ sender.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } String pMsg = header; if (pageNumber == numPages){ for(int i = (numPerPage*pageNumber-numPerPage); i<helpList.size(); i++){ pMsg+=helpList.get(i); } pMsg+=ChatColor.DARK_GREEN+"------------------------------"; } else { for(int i = (numPerPage*pageNumber-numPerPage); i<(numPerPage*pageNumber); i++){ pMsg+=helpList.get(i); } pMsg+=ChatColor.DARK_GREEN+"--- do"+ChatColor.YELLOW+" /"+label+" help "+(pageNumber+1)+ChatColor.DARK_GREEN+" for next page ---"; } sender.sendMessage(pMsg); return true; } /** * Called when landlord claim command is executed * This command must be run by a player * @param sender who executed the command * @param args given with command * @return boolean */ private boolean landlord_claim(CommandSender sender, String[] args) { //is sender a player if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { Player player = (Player) sender; if(!player.hasPermission("landlord.player.own")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } //sender.sendMessage(ChatColor.GOLD + "Current Location: " + player.getLocation().toString()); Chunk currChunk = player.getLocation().getChunk(); if(plugin.hasWorldGuard()){ if(!plugin.getWgHandler().canClaim(player,currChunk)){ player.sendMessage(ChatColor.RED+"You cannot claim here."); return true; } } OwnedLand land = OwnedLand.landFromProperties(player, currChunk); OwnedLand dbLand = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); if(dbLand != null){ //Check if they already own this land if (dbLand.ownerUUID().equals(player.getUniqueId())){ player.sendMessage(ChatColor.YELLOW + "You already own this land!"); return true; } player.sendMessage(ChatColor.YELLOW + "Someone else owns this land."); return true; } int limit = plugin.getConfig().getInt("limits.landLimit",10); if(player.hasPermission("landlord.limit.extra5")){ limit+=limit+=plugin.getConfig().getInt("limits.extra5",0); } else if(player.hasPermission("landlord.limit.extra4")){ limit+=limit+=plugin.getConfig().getInt("limits.extra4",0); } else if(player.hasPermission("landlord.limit.extra3")){ limit+=limit+=plugin.getConfig().getInt("limits.extra3",0); } else if(player.hasPermission("landlord.limit.extra2")){ limit+=limit+=plugin.getConfig().getInt("limits.extra2",0); } else if(player.hasPermission("landlord.limit.extra")){ limit+=limit+=plugin.getConfig().getInt("limits.extra",0); } if(limit >= 0 && !player.hasPermission("landlord.limit.override")){ if(plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getUniqueId().toString()).findRowCount() >= limit){ player.sendMessage(ChatColor.RED+"You can only own " + limit + " chunks of land."); return true; } } // if(plugin.hasVault()){ if(plugin.getvHandler().hasEconomy()){ Double amt = plugin.getConfig().getDouble("economy.buyPrice", 100.0); if(amt > 0){ if(!plugin.getvHandler().chargeCash(player, amt)){ player.sendMessage(ChatColor.RED+"It costs " + plugin.getvHandler().formatCash(amt) + " to purchase land."); return true; } else { player.sendMessage(ChatColor.YELLOW+"You have been charged " + plugin.getvHandler().formatCash(amt) + " to purchase land."); } } } } Landlord.getInstance().getDatabase().save(land); land.highlightLand(player, ParticleEffect.HAPPY_VILLAGER); sender.sendMessage( ChatColor.GREEN + "Successfully claimed chunk (" + currChunk.getX() + ", " + currChunk.getZ() + ") in world \'" + currChunk.getWorld().getName() + "\'." ); if(plugin.getConfig().getBoolean("options.soundEffects",true)){ player.playSound(player.getLocation(),Sound.FIREWORK_TWINKLE2,10,10); } plugin.getMapManager().updateAll(); //sender.sendMessage(ChatColor.DARK_GREEN + "Land claim command executed!"); } return true; } /** * Called when landlord unclaim command is executed * This command must be run by a player * @param sender who executed the command * @param args given with command * @return boolean */ private boolean landlord_unclaim(CommandSender sender, String[] args, String label) { //is sender a plater if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { Player player = (Player) sender; if(!player.hasPermission("landlord.player.own") && !player.hasPermission("landlord.admin.unclaim")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } //sender.sendMessage(ChatColor.GOLD + "Current Location: " + player.getLocation().toString()); Chunk currChunk = player.getLocation().getChunk(); int x = currChunk.getX(); int z = currChunk.getZ(); String worldname = currChunk.getWorld().getName(); if(args.length>1){ try{ String[] coords = args[1].split(","); //System.out.println("COORDS: "+coords); x = Integer.parseInt(coords[0]); z = Integer.parseInt(coords[1]); currChunk = currChunk.getWorld().getChunkAt(x,z); if(args.length>2){ if(plugin.getServer().getWorld(worldname) == null){ player.sendMessage(ChatColor.RED + "World \'"+worldname + "\' does not exist."); return true; } currChunk = getWorld(worldname).getChunkAt(x, z); } } catch (NumberFormatException e){ //e.printStackTrace(); player.sendMessage(ChatColor.RED+"usage: /"+label +" "+ args[0]+ " [x,z] [world]"); return true; } catch (ArrayIndexOutOfBoundsException e){ player.sendMessage(ChatColor.RED+"usage: /"+label +" "+ args[0]+" [x,z] [world]"); return true; } } OwnedLand dbLand = OwnedLand.getLandFromDatabase(x, z, worldname); if (dbLand == null || (!dbLand.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.unclaim"))){ player.sendMessage(ChatColor.RED + "You do not own this land."); return true; } if(plugin.hasVault()){ if(plugin.getvHandler().hasEconomy()){ Double amt = plugin.getConfig().getDouble("economy.sellPrice", 100.0); if(amt > 0){ if(plugin.getvHandler().giveCash(player, amt)){ player.sendMessage(ChatColor.GREEN+"Land sold for " + plugin.getvHandler().formatCash(amt) + "."); //return true; } } } } if(!player.getUniqueId().equals(dbLand.ownerUUID())){ player.sendMessage(ChatColor.YELLOW+"Unclaimed " + getOfflinePlayer(dbLand.ownerUUID()).getName() + "'s land."); } plugin.getDatabase().delete(dbLand); dbLand.highlightLand(player, ParticleEffect.WITCH_MAGIC); sender.sendMessage( ChatColor.YELLOW + "Successfully unclaimed chunk (" + currChunk.getX() + ", " + currChunk.getZ() + ") in world \'" + currChunk.getWorld().getName() + "\'." ); //Regen land if enabled if(plugin.getConfig().getBoolean("options.regenOnUnclaim",false)){ currChunk.getWorld().regenerateChunk(currChunk.getX(),currChunk.getZ()); } if(plugin.getConfig().getBoolean("options.soundEffects",true)){ player.playSound(player.getLocation(),Sound.ENDERMAN_HIT,10,.5f); } plugin.getMapManager().updateAll(); } return true; } /** * Adds a friend to an owned chunk * Called when landlord addfriend command is executed * This command must be run by a player * @param sender who executed the command * @param args given with command * @return boolean */ private boolean landlord_addfriend(CommandSender sender, String[] args) { //is sender a player if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { if (args.length < 2){ sender.sendMessage(ChatColor.RED + "usage: /land addfriend <player>"); return true; } Player player = (Player) sender; if(!player.hasPermission("landlord.player.own")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } Chunk currChunk = player.getLocation().getChunk(); OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); //Does land exist, and if so does player own it if( land == null || (!land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.modifyfriends")) ){ player.sendMessage(ChatColor.RED + "You do not own this land."); return true; } // OfflinePlayer possible = getOfflinePlayer(args[1]); if (!possible.hasPlayedBefore() && !possible.isOnline()) { player.sendMessage(ChatColor.RED+"That player is not recognized."); return true; } Friend friend = Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1])); /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ if (! land.addFriend(friend)) { player.sendMessage(ChatColor.YELLOW + "Player " + args[1] + " is already a friend of this land."); return true; } if(plugin.getConfig().getBoolean("options.particleEffects",true)){ land.highlightLand(player, ParticleEffect.HEART, 2); } plugin.getDatabase().save(land); if(plugin.getConfig().getBoolean("options.soundEffects",true)){ player.playSound(player.getLocation(),Sound.ORB_PICKUP,10,.2f); } sender.sendMessage(ChatColor.GREEN + "Player " + args[1] +" is now a friend of this land."); plugin.getMapManager().updateAll(); } return true; } private boolean landlord_friendall(CommandSender sender, String[] args) { //is sender a player if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "usage: /land friendall <player>"); return true; } Player player = (Player) sender; if (!player.hasPermission("landlord.player.own")) { player.sendMessage(ChatColor.RED + "You do not have permission."); return true; } List<OwnedLand> pLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getUniqueId()).findList(); OfflinePlayer possible = getOfflinePlayer(args[1]); if (!possible.hasPlayedBefore() && !possible.isOnline()) { player.sendMessage(ChatColor.RED + "That player is not recognized."); return true; } if (pLand.size() > 0){ for(OwnedLand l : pLand){ l.addFriend(Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1]))); } plugin.getDatabase().save(pLand); player.sendMessage(ChatColor.GREEN+args[1]+" has been added as a friend to all of your land."); return true; } else { player.sendMessage(ChatColor.YELLOW+"You do not own any land!"); } } return true; } private boolean landlord_unfriendall(CommandSender sender, String[] args) { //is sender a player if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "usage: /land unfriendall <player>"); return true; } Player player = (Player) sender; if (!player.hasPermission("landlord.player.own")) { player.sendMessage(ChatColor.RED + "You do not have permission."); return true; } List<OwnedLand> pLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getUniqueId()).findList(); OfflinePlayer possible = getOfflinePlayer(args[1]); if (!possible.hasPlayedBefore() && !possible.isOnline()) { player.sendMessage(ChatColor.RED + "That player is not recognized."); return true; } if (pLand.size() > 0){ for(OwnedLand l : pLand){ l.removeFriend(Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1]))); } plugin.getDatabase().save(pLand); player.sendMessage(ChatColor.GREEN+args[1]+" has been removed as a friend from all of your land."); return true; } else { player.sendMessage(ChatColor.YELLOW+"You do not own any land!"); } } return true; } /** * Removes a friend from an owned chunk * Called when landlord remfriend is executed * @param sender who executed the command * @param args given with command * @return boolean */ private boolean landlord_remfriend(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { if (args.length < 2){ sender.sendMessage(ChatColor.RED + "usage: /land unfriend <player>"); return true; } Player player = (Player) sender; if(!player.hasPermission("landlord.player.own")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } Chunk currChunk = player.getLocation().getChunk(); /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ Friend frd = Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1])); OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); if( land == null || (!land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.modifyfriends")) ){ player.sendMessage(ChatColor.RED + "You do not own this land."); return true; } if(!land.removeFriend(frd)){ player.sendMessage(ChatColor.YELLOW + "Player " + args[1] + " is not a friend of this land."); return true; } if(plugin.getConfig().getBoolean("options.particleEffects",true)) { land.highlightLand(player, ParticleEffect.ANGRY_VILLAGER, 2); } plugin.getDatabase().save(land); if(plugin.getConfig().getBoolean("options.soundEffects",true)){ player.playSound(player.getLocation(),Sound.ZOMBIE_INFECT,10,.5f); } player.sendMessage(ChatColor.GREEN + "Player " + args[1] + " is no longer a friend of this land."); } return true; } private boolean landlord_friends(CommandSender sender, String[] args, String label) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { Player player = (Player) sender; if(!player.hasPermission("landlord.player.own")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } Chunk currChunk = player.getLocation().getChunk(); OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); if( land == null || ( !land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.friends") ) ){ player.sendMessage(ChatColor.RED + "You do not own this land."); return true; } if(!land.getOwnerName().equals(player.getUniqueId())){ //player.sendMessage(ChatColor.YELLOW+"Viewing friends of someone else's land."); } if(plugin.getConfig().getBoolean("options.particleEffects",true)) { land.highlightLand(player, ParticleEffect.HEART, 3); } //check if page number is valid int pageNumber = 1; if (args.length > 1 && args[0].equals("friends")){ try { pageNumber = Integer.parseInt(args[1]); } catch (NumberFormatException e){ player.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } } //List<OwnedLand> myLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getName()).findList(); String header = ChatColor.DARK_GREEN + "----- Friends of this Land -----\n"; ArrayList<String> friendList = new ArrayList<String>(); if(land.getFriends().isEmpty()){ player.sendMessage(ChatColor.YELLOW+"This land has no friends."); return true; } for(Friend f: land.getFriends()){ String fr = ChatColor.DARK_GREEN+" - "+ChatColor.GOLD+f.getName()+ChatColor.DARK_GREEN+" - "; /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ if(Bukkit.getOfflinePlayer(f.getUUID()).isOnline()){ fr+= ChatColor.GREEN+""+ChatColor.ITALIC+" Online"; } else { fr+= ChatColor.RED+""+ChatColor.ITALIC+" Offline"; } fr+="\n"; friendList.add(fr); } //Amount to be displayed per page final int numPerPage = 8; int numPages = ceil((double)friendList.size()/(double)numPerPage); if(pageNumber > numPages){ sender.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } String pMsg = header; if (pageNumber == numPages){ for(int i = (numPerPage*pageNumber-numPerPage); i<friendList.size(); i++){ pMsg+=friendList.get(i); } pMsg+=ChatColor.DARK_GREEN+"------------------------------"; } else { for(int i = (numPerPage*pageNumber-numPerPage); i<(numPerPage*pageNumber); i++){ pMsg+=friendList.get(i); } pMsg+=ChatColor.DARK_GREEN+"--- do"+ChatColor.YELLOW+" /"+label+" friends "+(pageNumber+1)+ChatColor.DARK_GREEN+" for next page ---"; } player.sendMessage(pMsg); } return true; } /** * Toggles the land map display * @param sender who executed the command * @param args given with command * @return boolean */ private boolean landlord_map(CommandSender sender, String[] args) { if(!plugin.getConfig().getBoolean("options.enableMap", true)){ sender.sendMessage(ChatColor.YELLOW+"Land Map is disabled."); return true; } if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { Player player = (Player) sender; if(!player.hasPermission("landlord.player.map")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } try { plugin.getMapManager().toggleMap(player); } catch (Exception e) { sender.sendMessage(ChatColor.RED+"Map unavailable."); } } return true; } /** * Command for managing player land perms * @param sender who executed the command * @param args given with command * @return boolean */ private boolean landlord_manage(CommandSender sender, String[] args){ if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { Player player = (Player) sender; if(!player.hasPermission("landlord.player.own")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } if(plugin.getFlagManager().getRegisteredFlags().size() <= 0){ player.sendMessage(ChatColor.RED+"There is nothing to manage!"); return true; } Chunk currChunk = player.getLocation().getChunk(); OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); if( land == null || ( !land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.manage") ) ){ player.sendMessage(ChatColor.RED + "You do not own this land."); return true; } if(!land.ownerUUID().equals(player.getUniqueId())){ player.sendMessage(ChatColor.YELLOW+"Managing someone else's land."); } plugin.getManageViewManager().activateView(player, land); } return true; } /** * Display a list of all owned land to a player * @param sender who executed the command * @param args given with command * @return boolean */ private boolean landlord_list(CommandSender sender, String[] args, String label){ if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { Player player = (Player) sender; if(!player.hasPermission("landlord.player.own")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } //check if page number is valid int pageNumber = 1; if (args.length > 1){ try{ pageNumber = Integer.parseInt(args[1]);} catch (NumberFormatException e){ player.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } } List<OwnedLand> myLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getUniqueId().toString()).findList(); if(myLand.size()==0){ player.sendMessage(ChatColor.YELLOW+"You do not own any land!"); } else { String header = ChatColor.DARK_GREEN+" | ( X, Z ) - World Name | \n"; ArrayList<String> landList = new ArrayList<String>(); //OwnedLand curr = myLand.get(0); for (OwnedLand aMyLand : myLand) { landList.add((ChatColor.GOLD + " (" + aMyLand.getX() + ", " + aMyLand.getZ() + ") - " + aMyLand.getWorldName()) + "\n") ; } //Amount to be displayed per page final int numPerPage = 7; int numPages = ceil((double)landList.size()/(double)numPerPage); if(pageNumber > numPages){ player.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } String pMsg = ChatColor.DARK_GREEN+"--- " +ChatColor.YELLOW+"Your Owned Land"+ChatColor.DARK_GREEN+" ---"+ChatColor.YELLOW+" Page "+pageNumber+ChatColor.DARK_GREEN+" ---\n"+header; if (pageNumber == numPages){ for(int i = (numPerPage*pageNumber-numPerPage); i<landList.size(); i++){ pMsg+=landList.get(i); } pMsg+=ChatColor.DARK_GREEN+"------------------------------"; } else { for(int i = (numPerPage*pageNumber-numPerPage); i<(numPerPage*pageNumber); i++){ pMsg+=landList.get(i); } pMsg+=ChatColor.DARK_GREEN+"--- do"+ChatColor.YELLOW+" /"+label+" list "+(pageNumber+1)+ChatColor.DARK_GREEN+" for next page ---"; } player.sendMessage(pMsg); } } return true; } private boolean landlord_listplayer(CommandSender sender, String[] args, String label){ String owner; //sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); if(args.length>1){ owner = args[1]; } else { sender.sendMessage(ChatColor.RED+"usage: /" + label + " listplayer <player> [page#]"); return true; } //Player player = (Player) sender; if(!sender.hasPermission("landlord.admin.list")){ sender.sendMessage(ChatColor.RED+"You do not have permission."); return true; } //check if page number is valid int pageNumber = 1; if (args.length > 2){ try{ pageNumber = Integer.parseInt(args[2]);} catch (NumberFormatException e){ sender.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } } /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ OfflinePlayer possible = getOfflinePlayer(args[1]); if (!possible.hasPlayedBefore() && !possible.isOnline()) { sender.sendMessage(ChatColor.YELLOW+ owner +" does not own any land!"); return true; } List<OwnedLand> myLand = plugin.getDatabase().find(OwnedLand.class).where().ieq("ownerName", getOfflinePlayer(owner).getUniqueId().toString()).findList(); if(myLand.size()==0){ sender.sendMessage(ChatColor.YELLOW+ owner +" does not own any land!"); } else { String header = ChatColor.DARK_GREEN+" | ( X, Z ) - World Name | \n"; ArrayList<String> landList = new ArrayList<String>(); //OwnedLand curr = myLand.get(0); for (OwnedLand aMyLand : myLand) { landList.add((ChatColor.GOLD + " (" + aMyLand.getX() + ", " + aMyLand.getZ() + ") - " + aMyLand.getWorldName()) + "\n") ; } //Amount to be displayed per page final int numPerPage = 7; int numPages = ceil((double)landList.size()/(double)numPerPage); if(pageNumber > numPages){ sender.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } String pMsg = ChatColor.DARK_GREEN+"--- " +ChatColor.YELLOW+ owner +"'s Owned Land"+ChatColor.DARK_GREEN+" ---"+ChatColor.YELLOW+" Page "+pageNumber+ChatColor.DARK_GREEN+" ---\n"+header; if (pageNumber == numPages){ for(int i = (numPerPage*pageNumber-numPerPage); i<landList.size(); i++){ pMsg+=landList.get(i); } pMsg+=ChatColor.DARK_GREEN+"------------------------------"; } else { for(int i = (numPerPage*pageNumber-numPerPage); i<(numPerPage*pageNumber); i++){ pMsg+=landList.get(i); } pMsg+=ChatColor.DARK_GREEN+"--- do"+ChatColor.YELLOW+" /"+label+" listplayer "+(pageNumber+1)+ChatColor.DARK_GREEN+" for next page ---"; } sender.sendMessage(pMsg); } return true; } private boolean landlord_clearWorld(CommandSender sender, String[] args, String label){ if(!sender.hasPermission("landlord.admin.clearworld")){ sender.sendMessage(ChatColor.RED+"You do not have permission."); return true; } if(args.length > 1){ List<OwnedLand> land; if(args.length > 2){ /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ OfflinePlayer possible = getOfflinePlayer(args[2]); if (!possible.hasPlayedBefore() && !possible.isOnline()) { sender.sendMessage(ChatColor.RED+"That player is not recognized."); return true; } land = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",possible.getUniqueId().toString()).eq("worldName",args[1]).findList(); } else { if(sender instanceof Player){ sender.sendMessage(ChatColor.RED+"You can only delete entire worlds from the console."); return true; } land = plugin.getDatabase().find(OwnedLand.class).where().eq("worldName",args[1]).findList(); } if(land.isEmpty()){ sender.sendMessage(ChatColor.RED + "No land to remove."); return true; } plugin.getDatabase().delete(land); plugin.getMapManager().updateAll(); sender.sendMessage(ChatColor.GREEN+"Land(s) deleted!"); } else { sender.sendMessage(ChatColor.RED + "format: " + label + " clearworld <world> [<player>]"); } return true; } /** * Reload landlord configuration file * @param sender who executed the command * @param args given with command * @param label exact command (or alias) run * @return boolean of success */ private boolean landlord_reload(CommandSender sender, String[] args, String label){ if(sender.hasPermission("landlord.admin.reload")){ plugin.reloadConfig(); sender.sendMessage(ChatColor.GREEN+"Landlord config reloaded."); return true; } sender.sendMessage(ChatColor.RED+"You do not have permission."); return true; } private boolean landlord_info(CommandSender sender, String[] args, String label){ if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { Player player = (Player) sender; if(!player.hasPermission("landlord.player.info")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } Chunk currChunk = player.getLocation().getChunk(); OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); String owner = ChatColor.GRAY + "" + ChatColor.ITALIC + "None"; if( land != null ){ /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ owner = ChatColor.GOLD + land.getOwnerUsername(); } else { land = OwnedLand.landFromProperties(null,currChunk); } if(plugin.getConfig().getBoolean("options.particleEffects")){ land.highlightLand(player, ParticleEffect.DRIP_LAVA); } String msg = ChatColor.DARK_GREEN + "--- You are in chunk " + ChatColor.GOLD + "(" + currChunk.getX() + ", " + currChunk.getZ() + ") " + ChatColor.DARK_GREEN + " in world \"" + ChatColor.GOLD + currChunk.getWorld().getName() + ChatColor.DARK_GREEN + "\"\n"+ "----- Owned by: " + owner; player.sendMessage(msg); } return true; } }
src/com/jcdesimp/landlord/LandlordCommandExecutor.java
package com.jcdesimp.landlord; import com.jcdesimp.landlord.landManagement.LandManagerView; import com.jcdesimp.landlord.persistantData.Friend; import com.jcdesimp.landlord.persistantData.OwnedLand; import org.bukkit.*; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.jcdesimp.landlord.DarkBladee12.ParticleAPI.ParticleEffect; import java.util.ArrayList; import java.util.List; import static org.bukkit.Bukkit.getOfflinePlayer; import static org.bukkit.Bukkit.getPlayer; import static org.bukkit.Bukkit.getWorld; import static org.bukkit.util.NumberConversions.ceil; /** * Command Executor class for LandLord */ @SuppressWarnings("UnusedParameters") public class LandlordCommandExecutor implements CommandExecutor { private Landlord plugin; //pointer to main class public LandlordCommandExecutor(Landlord plugin){ this.plugin = plugin; } /** * Main command handler * @param sender who sent the command * @param label exact command (or alias) run * @param args given with command * @return boolean */ @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(cmd.getName().equalsIgnoreCase("landlord")){ // If the player typed /land then do the following... /* * **************************************************************** * Use private methods below to define command implementation * call those methods from within these cases * **************************************************************** */ if(args.length == 0){ //landlord return landlord_help(sender, args, label); } else if(args[0].equalsIgnoreCase("help")) { //landlord claim return landlord_help(sender, args, label); } else if(args[0].equalsIgnoreCase("claim") || args[0].equalsIgnoreCase("buy")) { //landlord claim return landlord_claim(sender, args); } else if(args[0].equalsIgnoreCase("unclaim") || args[0].equalsIgnoreCase("sell")) { //landlord unclaim return landlord_unclaim(sender, args, label); } else if(args[0].equalsIgnoreCase("addfriend") || args[0].equalsIgnoreCase("friend")) { //landlord addfriend return landlord_addfriend(sender, args); } else if(args[0].equalsIgnoreCase("friendall")) { //landlord addfriend return landlord_friendall(sender, args); } else if(args[0].equalsIgnoreCase("unfriendall")) { //landlord addfriend return landlord_unfriendall(sender, args); } else if(args[0].equalsIgnoreCase("remfriend") || args[0].equalsIgnoreCase("unfriend")) { return landlord_remfriend(sender, args); } else if(args[0].equalsIgnoreCase("map")) { return landlord_map(sender, args); //sender.sendMessage(ChatColor.RED+"Land map is temporarily disabled!"); //return true; } else if(args[0].equalsIgnoreCase("manage")) { return landlord_manage(sender, args); } else if(args[0].equalsIgnoreCase("list")) { return landlord_list(sender, args, label); } else if(args[0].equalsIgnoreCase("listplayer")) { return landlord_listplayer(sender, args, label); } else if(args[0].equalsIgnoreCase("clearworld")) { return landlord_clearWorld(sender, args, label); } else if(args[0].equalsIgnoreCase("reload")) { return landlord_reload(sender, args, label); } else if(args[0].equalsIgnoreCase("info")) { return landlord_info(sender, args, label); } else if(args[0].equalsIgnoreCase("friends")) { return landlord_friends(sender,args,label); } else { return landlord_help(sender, args, label); } } //If this has happened the function will return true. // If this hasn't happened the value of false will be returned. return false; } /* * ********************************************************** * private methods for handling each command functionality * ********************************************************** */ /** * Called when base command /landlord or aliases (/ll /land) * are executed with no parameters * * @param sender who executed the command * @return boolean */ private boolean landlord(CommandSender sender, String[] args, String label) { sender.sendMessage(ChatColor.DARK_GREEN + "--|| Landlord v"+Landlord.getInstance().getDescription().getVersion() + " Created by " + ChatColor.BLUE+"Jcdesimp "+ChatColor.DARK_GREEN +"||--\n"+ //ChatColor.GRAY+"(Aliases: /landlord, /land, or /ll)\n"+ ChatColor.DARK_GREEN+"Type " +ChatColor.YELLOW+"/"+label+" help "+ChatColor.DARK_GREEN +"for a list of commands"); return true; } private boolean landlord_help(CommandSender sender, String[] args, String label) { //check if page number is valid int pageNumber = 1; if (args.length > 1 && args[0].equals("help")){ try{ pageNumber = Integer.parseInt(args[1]);} catch (NumberFormatException e){ sender.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } } //List<OwnedLand> myLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getName()).findList(); String header = ChatColor.DARK_GREEN + "--|| Landlord v"+Landlord.getInstance().getDescription().getVersion() + " Created by " + ChatColor.BLUE+"Jcdesimp "+ChatColor.DARK_GREEN +"||--\n"+ ChatColor.GRAY+"(Aliases: /landlord, /land, or /ll)\n"; ArrayList<String> helpList = new ArrayList<String>(); helpList.add(ChatColor.DARK_AQUA+"/"+label + " help [page #]" + ChatColor.RESET + " - Show this help message.\n"); String claim = ChatColor.DARK_AQUA+"/"+label + " claim (or "+"/"+label +" buy)" + ChatColor.RESET + " - Claim this chunk.\n"; if(plugin.hasVault()){ if(plugin.getvHandler().hasEconomy() && plugin.getConfig().getDouble("economy.buyPrice", 100.0)>0){ claim += ChatColor.YELLOW+""+ChatColor.ITALIC+" Costs "+plugin.getvHandler().formatCash(plugin.getConfig().getDouble("economy.buyPrice", 100.0))+" to claim.\n"; } } helpList.add(claim); String unclaim = ChatColor.DARK_AQUA+"/"+label + " unclaim [x,z] [world] (or "+"/"+label +" sell)" + ChatColor.RESET + " - Unclaim this chunk.\n"; if (plugin.hasVault() && plugin.getvHandler().hasEconomy() && plugin.getConfig().getDouble("economy.sellPrice", 50.0) > 0) { if(plugin.getConfig().getBoolean("options.regenOnUnclaim",false)) { unclaim+=ChatColor.RED+""+ChatColor.ITALIC +" Regenerates Chunk!"; } unclaim += ChatColor.YELLOW + "" + ChatColor.ITALIC + " Get " + plugin.getvHandler().formatCash(plugin.getConfig().getDouble("economy.sellPrice", 50.0)) + " per unclaim.\n"; } else if(plugin.getConfig().getBoolean("options.regenOnUnclaim",false)) { unclaim+=ChatColor.RED+""+ChatColor.ITALIC +" Regenerates Chunk!\n"; } helpList.add(unclaim); helpList.add(ChatColor.DARK_AQUA+"/"+label + " addfriend <player>" + ChatColor.RESET + " - Add friend to this land.\n"); helpList.add(ChatColor.DARK_AQUA+"/"+label + " unfriend <player>" + ChatColor.RESET + " - Remove friend from this land.\n"); helpList.add(ChatColor.DARK_AQUA+"/"+label + " friendall <player>" + ChatColor.RESET + " - Add friend to all your land.\n"); helpList.add(ChatColor.DARK_AQUA+"/"+label + " unfriendall <player>" + ChatColor.RESET + " - Remove friend from all your land.\n"); helpList.add(ChatColor.DARK_AQUA+"/"+label + " friends" + ChatColor.RESET + " - List friends of this land.\n"); helpList.add(ChatColor.DARK_AQUA+"/"+label + " manage" + ChatColor.RESET + " - Manage permissions for this land.\n"); helpList.add(ChatColor.DARK_AQUA+"/"+label + " list" + ChatColor.RESET + " - List all your owned land.\n"); if(sender.hasPermission("landlord.player.map") && plugin.getConfig().getBoolean("options.enableMap",true)){ helpList.add(ChatColor.DARK_AQUA+"/"+label + " map" + ChatColor.RESET + " - Toggle the land map.\n"); } if(sender.hasPermission("landlord.player.info") && plugin.getConfig().getBoolean("options.enableMap",true)){ helpList.add(ChatColor.DARK_AQUA+"/"+label + " info" + ChatColor.RESET + " - View info about this chunk.\n"); } if(sender.hasPermission("landlord.admin.list")){ helpList.add(ChatColor.DARK_AQUA+"/"+label + " listplayer <player>" + ChatColor.RESET + " - List land owned by another player.\n"); } if(sender.hasPermission("landlord.admin.clearworld")){ String clearHelp = ChatColor.DARK_AQUA+"/"+label + " clearworld <world> [player]" + ChatColor.RESET + " - Delete all land owned by a player in a world." + " Delete all land of a world from console.\n"; if(plugin.getConfig().getBoolean("options.regenOnUnclaim",false)){ clearHelp += ChatColor.YELLOW+""+ChatColor.ITALIC+" Does not regenerate chunks.\n"; } helpList.add(clearHelp); } if(sender.hasPermission("landlord.admin.reload")){ helpList.add(ChatColor.DARK_AQUA+"/"+label + " reload" + ChatColor.RESET + " - Reloads the Landlord config file.\n"); } //OwnedLand curr = myLand.get(0); //Amount to be displayed per page final int numPerPage = 5; int numPages = ceil((double)helpList.size()/(double)numPerPage); if(pageNumber > numPages){ sender.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } String pMsg = header; if (pageNumber == numPages){ for(int i = (numPerPage*pageNumber-numPerPage); i<helpList.size(); i++){ pMsg+=helpList.get(i); } pMsg+=ChatColor.DARK_GREEN+"------------------------------"; } else { for(int i = (numPerPage*pageNumber-numPerPage); i<(numPerPage*pageNumber); i++){ pMsg+=helpList.get(i); } pMsg+=ChatColor.DARK_GREEN+"--- do"+ChatColor.YELLOW+" /"+label+" help "+(pageNumber+1)+ChatColor.DARK_GREEN+" for next page ---"; } sender.sendMessage(pMsg); return true; } /** * Called when landlord claim command is executed * This command must be run by a player * @param sender who executed the command * @param args given with command * @return boolean */ private boolean landlord_claim(CommandSender sender, String[] args) { //is sender a player if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { Player player = (Player) sender; if(!player.hasPermission("landlord.player.own")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } //sender.sendMessage(ChatColor.GOLD + "Current Location: " + player.getLocation().toString()); Chunk currChunk = player.getLocation().getChunk(); if(plugin.hasWorldGuard()){ if(!plugin.getWgHandler().canClaim(player,currChunk)){ player.sendMessage(ChatColor.RED+"You cannot claim here."); return true; } } OwnedLand land = OwnedLand.landFromProperties(player, currChunk); OwnedLand dbLand = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); if(dbLand != null){ //Check if they already own this land if (dbLand.ownerUUID().equals(player.getUniqueId())){ player.sendMessage(ChatColor.YELLOW + "You already own this land!"); return true; } player.sendMessage(ChatColor.YELLOW + "Someone else owns this land."); return true; } int limit = plugin.getConfig().getInt("limits.landLimit",10); if(player.hasPermission("landlord.limit.extra5")){ limit+=limit+=plugin.getConfig().getInt("limits.extra5",0); } else if(player.hasPermission("landlord.limit.extra4")){ limit+=limit+=plugin.getConfig().getInt("limits.extra4",0); } else if(player.hasPermission("landlord.limit.extra3")){ limit+=limit+=plugin.getConfig().getInt("limits.extra3",0); } else if(player.hasPermission("landlord.limit.extra2")){ limit+=limit+=plugin.getConfig().getInt("limits.extra2",0); } else if(player.hasPermission("landlord.limit.extra")){ limit+=limit+=plugin.getConfig().getInt("limits.extra",0); } if(limit >= 0 && !player.hasPermission("landlord.limit.override")){ if(plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getUniqueId().toString()).findRowCount() >= limit){ player.sendMessage(ChatColor.RED+"You can only own " + limit + " chunks of land."); return true; } } // if(plugin.hasVault()){ if(plugin.getvHandler().hasEconomy()){ Double amt = plugin.getConfig().getDouble("economy.buyPrice", 100.0); if(amt > 0){ if(!plugin.getvHandler().chargeCash(player, amt)){ player.sendMessage(ChatColor.RED+"It costs " + plugin.getvHandler().formatCash(amt) + " to purchase land."); return true; } else { player.sendMessage(ChatColor.YELLOW+"You have been charged " + plugin.getvHandler().formatCash(amt) + " to purchase land."); } } } } Landlord.getInstance().getDatabase().save(land); land.highlightLand(player, ParticleEffect.HAPPY_VILLAGER); sender.sendMessage( ChatColor.GREEN + "Successfully claimed chunk (" + currChunk.getX() + ", " + currChunk.getZ() + ") in world \'" + currChunk.getWorld().getName() + "\'." ); if(plugin.getConfig().getBoolean("options.soundEffects",true)){ player.playSound(player.getLocation(),Sound.FIREWORK_TWINKLE2,10,10); } plugin.getMapManager().updateAll(); //sender.sendMessage(ChatColor.DARK_GREEN + "Land claim command executed!"); } return true; } /** * Called when landlord unclaim command is executed * This command must be run by a player * @param sender who executed the command * @param args given with command * @return boolean */ private boolean landlord_unclaim(CommandSender sender, String[] args, String label) { //is sender a plater if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { Player player = (Player) sender; if(!player.hasPermission("landlord.player.own") && !player.hasPermission("landlord.admin.unclaim")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } //sender.sendMessage(ChatColor.GOLD + "Current Location: " + player.getLocation().toString()); Chunk currChunk = player.getLocation().getChunk(); int x = currChunk.getX(); int z = currChunk.getZ(); String worldname = currChunk.getWorld().getName(); if(args.length>1){ try{ String[] coords = args[1].split(","); //System.out.println("COORDS: "+coords); x = Integer.parseInt(coords[0]); z = Integer.parseInt(coords[1]); currChunk = currChunk.getWorld().getChunkAt(x,z); if(args.length>2){ if(plugin.getServer().getWorld(worldname) == null){ player.sendMessage(ChatColor.RED + "World \'"+worldname + "\' does not exist."); return true; } currChunk = getWorld(worldname).getChunkAt(x, z); } } catch (NumberFormatException e){ //e.printStackTrace(); player.sendMessage(ChatColor.RED+"usage: /"+label +" "+ args[0]+ " [x,z] [world]"); return true; } catch (ArrayIndexOutOfBoundsException e){ player.sendMessage(ChatColor.RED+"usage: /"+label +" "+ args[0]+" [x,z] [world]"); return true; } } OwnedLand dbLand = OwnedLand.getLandFromDatabase(x, z, worldname); if (dbLand == null || (!dbLand.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.unclaim"))){ player.sendMessage(ChatColor.RED + "You do not own this land."); return true; } if(plugin.hasVault()){ if(plugin.getvHandler().hasEconomy()){ Double amt = plugin.getConfig().getDouble("economy.sellPrice", 100.0); if(amt > 0){ if(plugin.getvHandler().giveCash(player, amt)){ player.sendMessage(ChatColor.GREEN+"Land sold for " + plugin.getvHandler().formatCash(amt) + "."); //return true; } } } } if(!player.getUniqueId().equals(dbLand.ownerUUID())){ player.sendMessage(ChatColor.YELLOW+"Unclaimed " + getOfflinePlayer(dbLand.ownerUUID()).getName() + "'s land."); } plugin.getDatabase().delete(dbLand); dbLand.highlightLand(player, ParticleEffect.WITCH_MAGIC); sender.sendMessage( ChatColor.YELLOW + "Successfully unclaimed chunk (" + currChunk.getX() + ", " + currChunk.getZ() + ") in world \'" + currChunk.getWorld().getName() + "\'." ); //Regen land if enabled if(plugin.getConfig().getBoolean("options.regenOnUnclaim",false)){ currChunk.getWorld().regenerateChunk(currChunk.getX(),currChunk.getZ()); } if(plugin.getConfig().getBoolean("options.soundEffects",true)){ player.playSound(player.getLocation(),Sound.ENDERMAN_HIT,10,.5f); } plugin.getMapManager().updateAll(); } return true; } /** * Adds a friend to an owned chunk * Called when landlord addfriend command is executed * This command must be run by a player * @param sender who executed the command * @param args given with command * @return boolean */ private boolean landlord_addfriend(CommandSender sender, String[] args) { //is sender a player if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { if (args.length < 2){ sender.sendMessage(ChatColor.RED + "usage: /land addfriend <player>"); return true; } Player player = (Player) sender; if(!player.hasPermission("landlord.player.own")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } Chunk currChunk = player.getLocation().getChunk(); OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); //Does land exist, and if so does player own it if( land == null || (!land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.modifyfriends")) ){ player.sendMessage(ChatColor.RED + "You do not own this land."); return true; } // OfflinePlayer possible = getOfflinePlayer(args[1]); if (!possible.hasPlayedBefore() && !possible.isOnline()) { player.sendMessage(ChatColor.RED+"That player is not recognized."); return true; } Friend friend = Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1])); /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ if (! land.addFriend(friend)) { player.sendMessage(ChatColor.YELLOW + "Player " + args[1] + " is already a friend of this land."); return true; } if(plugin.getConfig().getBoolean("options.particleEffects",true)){ land.highlightLand(player, ParticleEffect.HEART, 2); } plugin.getDatabase().save(land); if(plugin.getConfig().getBoolean("options.soundEffects",true)){ player.playSound(player.getLocation(),Sound.ORB_PICKUP,10,.2f); } sender.sendMessage(ChatColor.GREEN + "Player " + args[1] +" is now a friend of this land."); plugin.getMapManager().updateAll(); } return true; } private boolean landlord_friendall(CommandSender sender, String[] args) { //is sender a player if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "usage: /land friendall <player>"); return true; } Player player = (Player) sender; if (!player.hasPermission("landlord.player.own")) { player.sendMessage(ChatColor.RED + "You do not have permission."); return true; } List<OwnedLand> pLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getUniqueId()).findList(); OfflinePlayer possible = getOfflinePlayer(args[1]); if (!possible.hasPlayedBefore() && !possible.isOnline()) { player.sendMessage(ChatColor.RED + "That player is not recognized."); return true; } if (pLand.size() > 0){ for(OwnedLand l : pLand){ l.addFriend(Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1]))); } plugin.getDatabase().save(pLand); player.sendMessage(ChatColor.GREEN+args[1]+" has been added as a friend to all of your land."); return true; } else { player.sendMessage(ChatColor.YELLOW+"You do not own any land!"); } } return true; } private boolean landlord_unfriendall(CommandSender sender, String[] args) { //is sender a player if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "usage: /land unfriendall <player>"); return true; } Player player = (Player) sender; if (!player.hasPermission("landlord.player.own")) { player.sendMessage(ChatColor.RED + "You do not have permission."); return true; } List<OwnedLand> pLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getUniqueId()).findList(); OfflinePlayer possible = getOfflinePlayer(args[1]); if (!possible.hasPlayedBefore() && !possible.isOnline()) { player.sendMessage(ChatColor.RED + "That player is not recognized."); return true; } if (pLand.size() > 0){ for(OwnedLand l : pLand){ l.removeFriend(Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1]))); } plugin.getDatabase().save(pLand); player.sendMessage(ChatColor.GREEN+args[1]+" has been removed as a friend from all of your land."); return true; } else { player.sendMessage(ChatColor.YELLOW+"You do not own any land!"); } } return true; } /** * Removes a friend from an owned chunk * Called when landlord remfriend is executed * @param sender who executed the command * @param args given with command * @return boolean */ private boolean landlord_remfriend(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { if (args.length < 2){ sender.sendMessage(ChatColor.RED + "usage: /land unfriend <player>"); return true; } Player player = (Player) sender; if(!player.hasPermission("landlord.player.own")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } Chunk currChunk = player.getLocation().getChunk(); /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ Friend frd = Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1])); OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); if( land == null || (!land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.modifyfriends")) ){ player.sendMessage(ChatColor.RED + "You do not own this land."); return true; } if(!land.removeFriend(frd)){ player.sendMessage(ChatColor.YELLOW + "Player " + args[1] + " is not a friend of this land."); return true; } if(plugin.getConfig().getBoolean("options.particleEffects",true)) { land.highlightLand(player, ParticleEffect.ANGRY_VILLAGER, 2); } plugin.getDatabase().save(land); if(plugin.getConfig().getBoolean("options.soundEffects",true)){ player.playSound(player.getLocation(),Sound.ZOMBIE_INFECT,10,.5f); } player.sendMessage(ChatColor.GREEN + "Player " + args[1] + " is no longer a friend of this land."); } return true; } private boolean landlord_friends(CommandSender sender, String[] args, String label) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { Player player = (Player) sender; if(!player.hasPermission("landlord.player.own")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } Chunk currChunk = player.getLocation().getChunk(); OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); if( land == null || ( !land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.friends") ) ){ player.sendMessage(ChatColor.RED + "You do not own this land."); return true; } if(!land.getOwnerName().equals(player.getUniqueId())){ //player.sendMessage(ChatColor.YELLOW+"Viewing friends of someone else's land."); } if(plugin.getConfig().getBoolean("options.particleEffects",true)) { land.highlightLand(player, ParticleEffect.HEART, 3); } //check if page number is valid int pageNumber = 1; if (args.length > 1 && args[0].equals("friends")){ try { pageNumber = Integer.parseInt(args[1]); } catch (NumberFormatException e){ player.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } } //List<OwnedLand> myLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getName()).findList(); String header = ChatColor.DARK_GREEN + "----- Friends of this Land -----\n"; ArrayList<String> friendList = new ArrayList<String>(); if(land.getFriends().isEmpty()){ player.sendMessage(ChatColor.YELLOW+"This land has no friends."); return true; } for(Friend f: land.getFriends()){ String fr = ChatColor.DARK_GREEN+" - "+ChatColor.GOLD+f.getName()+ChatColor.DARK_GREEN+" - "; /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ if(Bukkit.getOfflinePlayer(f.getUUID()).isOnline()){ fr+= ChatColor.GREEN+""+ChatColor.ITALIC+" Online"; } else { fr+= ChatColor.RED+""+ChatColor.ITALIC+" Offline"; } fr+="\n"; friendList.add(fr); } //Amount to be displayed per page final int numPerPage = 8; int numPages = ceil((double)friendList.size()/(double)numPerPage); if(pageNumber > numPages){ sender.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } String pMsg = header; if (pageNumber == numPages){ for(int i = (numPerPage*pageNumber-numPerPage); i<friendList.size(); i++){ pMsg+=friendList.get(i); } pMsg+=ChatColor.DARK_GREEN+"------------------------------"; } else { for(int i = (numPerPage*pageNumber-numPerPage); i<(numPerPage*pageNumber); i++){ pMsg+=friendList.get(i); } pMsg+=ChatColor.DARK_GREEN+"--- do"+ChatColor.YELLOW+" /"+label+" friends "+(pageNumber+1)+ChatColor.DARK_GREEN+" for next page ---"; } player.sendMessage(pMsg); } return true; } /** * Toggles the land map display * @param sender who executed the command * @param args given with command * @return boolean */ private boolean landlord_map(CommandSender sender, String[] args) { if(!plugin.getConfig().getBoolean("options.enableMap", true)){ sender.sendMessage(ChatColor.YELLOW+"Land Map is disabled."); return true; } if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { Player player = (Player) sender; if(!player.hasPermission("landlord.player.map")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } try { plugin.getMapManager().toggleMap(player); } catch (Exception e) { sender.sendMessage(ChatColor.RED+"Map unavailable."); } } return true; } /** * Command for managing player land perms * @param sender who executed the command * @param args given with command * @return boolean */ private boolean landlord_manage(CommandSender sender, String[] args){ if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { Player player = (Player) sender; if(!player.hasPermission("landlord.player.own")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } if(plugin.getFlagManager().getRegisteredFlags().size() <= 0){ player.sendMessage(ChatColor.RED+"There is nothing to manage!"); return true; } Chunk currChunk = player.getLocation().getChunk(); OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); if( land == null || ( !land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.manage") ) ){ player.sendMessage(ChatColor.RED + "You do not own this land."); return true; } if(!land.ownerUUID().equals(player.getUniqueId())){ player.sendMessage(ChatColor.YELLOW+"Managing someone else's land."); } plugin.getManageViewManager().activateView(player, land); } return true; } /** * Display a list of all owned land to a player * @param sender who executed the command * @param args given with command * @return boolean */ private boolean landlord_list(CommandSender sender, String[] args, String label){ if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { Player player = (Player) sender; if(!player.hasPermission("landlord.player.own")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } //check if page number is valid int pageNumber = 1; if (args.length > 1){ try{ pageNumber = Integer.parseInt(args[1]);} catch (NumberFormatException e){ player.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } } List<OwnedLand> myLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getUniqueId().toString()).findList(); if(myLand.size()==0){ player.sendMessage(ChatColor.YELLOW+"You do not own any land!"); } else { String header = ChatColor.DARK_GREEN+" | ( X, Z ) - World Name | \n"; ArrayList<String> landList = new ArrayList<String>(); //OwnedLand curr = myLand.get(0); for (OwnedLand aMyLand : myLand) { landList.add((ChatColor.GOLD + " (" + aMyLand.getX() + ", " + aMyLand.getZ() + ") - " + aMyLand.getWorldName()) + "\n") ; } //Amount to be displayed per page final int numPerPage = 7; int numPages = ceil((double)landList.size()/(double)numPerPage); if(pageNumber > numPages){ player.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } String pMsg = ChatColor.DARK_GREEN+"--- " +ChatColor.YELLOW+"Your Owned Land"+ChatColor.DARK_GREEN+" ---"+ChatColor.YELLOW+" Page "+pageNumber+ChatColor.DARK_GREEN+" ---\n"+header; if (pageNumber == numPages){ for(int i = (numPerPage*pageNumber-numPerPage); i<landList.size(); i++){ pMsg+=landList.get(i); } pMsg+=ChatColor.DARK_GREEN+"------------------------------"; } else { for(int i = (numPerPage*pageNumber-numPerPage); i<(numPerPage*pageNumber); i++){ pMsg+=landList.get(i); } pMsg+=ChatColor.DARK_GREEN+"--- do"+ChatColor.YELLOW+" /"+label+" list "+(pageNumber+1)+ChatColor.DARK_GREEN+" for next page ---"; } player.sendMessage(pMsg); } } return true; } private boolean landlord_listplayer(CommandSender sender, String[] args, String label){ String owner; //sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); if(args.length>1){ owner = args[1]; } else { sender.sendMessage(ChatColor.RED+"usage: /" + label + " listplayer <player> [page#]"); return true; } //Player player = (Player) sender; if(!sender.hasPermission("landlord.admin.list")){ sender.sendMessage(ChatColor.RED+"You do not have permission."); return true; } //check if page number is valid int pageNumber = 1; if (args.length > 2){ try{ pageNumber = Integer.parseInt(args[2]);} catch (NumberFormatException e){ sender.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } } /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ OfflinePlayer possible = getOfflinePlayer(args[1]); if (!possible.hasPlayedBefore() && !possible.isOnline()) { sender.sendMessage(ChatColor.YELLOW+ owner +" does not own any land!"); return true; } List<OwnedLand> myLand = plugin.getDatabase().find(OwnedLand.class).where().ieq("ownerName", getOfflinePlayer(owner).getUniqueId().toString()).findList(); if(myLand.size()==0){ sender.sendMessage(ChatColor.YELLOW+ owner +" does not own any land!"); } else { String header = ChatColor.DARK_GREEN+" | ( X, Z ) - World Name | \n"; ArrayList<String> landList = new ArrayList<String>(); //OwnedLand curr = myLand.get(0); for (OwnedLand aMyLand : myLand) { landList.add((ChatColor.GOLD + " (" + aMyLand.getX() + ", " + aMyLand.getZ() + ") - " + aMyLand.getWorldName()) + "\n") ; } //Amount to be displayed per page final int numPerPage = 7; int numPages = ceil((double)landList.size()/(double)numPerPage); if(pageNumber > numPages){ sender.sendMessage(ChatColor.RED+"That is not a valid page number."); return true; } String pMsg = ChatColor.DARK_GREEN+"--- " +ChatColor.YELLOW+ owner +"'s Owned Land"+ChatColor.DARK_GREEN+" ---"+ChatColor.YELLOW+" Page "+pageNumber+ChatColor.DARK_GREEN+" ---\n"+header; if (pageNumber == numPages){ for(int i = (numPerPage*pageNumber-numPerPage); i<landList.size(); i++){ pMsg+=landList.get(i); } pMsg+=ChatColor.DARK_GREEN+"------------------------------"; } else { for(int i = (numPerPage*pageNumber-numPerPage); i<(numPerPage*pageNumber); i++){ pMsg+=landList.get(i); } pMsg+=ChatColor.DARK_GREEN+"--- do"+ChatColor.YELLOW+" /"+label+" list "+(pageNumber+1)+ChatColor.DARK_GREEN+" for next page ---"; } sender.sendMessage(pMsg); } return true; } private boolean landlord_clearWorld(CommandSender sender, String[] args, String label){ if(!sender.hasPermission("landlord.admin.clearworld")){ sender.sendMessage(ChatColor.RED+"You do not have permission."); return true; } if(args.length > 1){ List<OwnedLand> land; if(args.length > 2){ /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ OfflinePlayer possible = getOfflinePlayer(args[2]); if (!possible.hasPlayedBefore() && !possible.isOnline()) { sender.sendMessage(ChatColor.RED+"That player is not recognized."); return true; } land = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",possible.getUniqueId().toString()).eq("worldName",args[1]).findList(); } else { if(sender instanceof Player){ sender.sendMessage(ChatColor.RED+"You can only delete entire worlds from the console."); return true; } land = plugin.getDatabase().find(OwnedLand.class).where().eq("worldName",args[1]).findList(); } if(land.isEmpty()){ sender.sendMessage(ChatColor.RED + "No land to remove."); return true; } plugin.getDatabase().delete(land); plugin.getMapManager().updateAll(); sender.sendMessage(ChatColor.GREEN+"Land(s) deleted!"); } else { sender.sendMessage(ChatColor.RED + "format: " + label + " clearworld <world> [<player>]"); } return true; } /** * Reload landlord configuration file * @param sender who executed the command * @param args given with command * @param label exact command (or alias) run * @return boolean of success */ private boolean landlord_reload(CommandSender sender, String[] args, String label){ if(sender.hasPermission("landlord.admin.reload")){ plugin.reloadConfig(); sender.sendMessage(ChatColor.GREEN+"Landlord config reloaded."); return true; } sender.sendMessage(ChatColor.RED+"You do not have permission."); return true; } private boolean landlord_info(CommandSender sender, String[] args, String label){ if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); } else { Player player = (Player) sender; if(!player.hasPermission("landlord.player.info")){ player.sendMessage(ChatColor.RED+"You do not have permission."); return true; } Chunk currChunk = player.getLocation().getChunk(); OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); String owner = ChatColor.GRAY + "" + ChatColor.ITALIC + "None"; if( land != null ){ /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ owner = ChatColor.GOLD + land.getOwnerUsername(); } else { land = OwnedLand.landFromProperties(null,currChunk); } if(plugin.getConfig().getBoolean("options.particleEffects")){ land.highlightLand(player, ParticleEffect.DRIP_LAVA); } String msg = ChatColor.DARK_GREEN + "--- You are in chunk " + ChatColor.GOLD + "(" + currChunk.getX() + ", " + currChunk.getZ() + ") " + ChatColor.DARK_GREEN + " in world \"" + ChatColor.GOLD + currChunk.getWorld().getName() + ChatColor.DARK_GREEN + "\"\n"+ "----- Owned by: " + owner; player.sendMessage(msg); } return true; } }
Fixed minor typo in listplayer command
src/com/jcdesimp/landlord/LandlordCommandExecutor.java
Fixed minor typo in listplayer command
<ide><path>rc/com/jcdesimp/landlord/LandlordCommandExecutor.java <ide> for(int i = (numPerPage*pageNumber-numPerPage); i<(numPerPage*pageNumber); i++){ <ide> pMsg+=landList.get(i); <ide> } <del> pMsg+=ChatColor.DARK_GREEN+"--- do"+ChatColor.YELLOW+" /"+label+" list "+(pageNumber+1)+ChatColor.DARK_GREEN+" for next page ---"; <add> pMsg+=ChatColor.DARK_GREEN+"--- do"+ChatColor.YELLOW+" /"+label+" listplayer "+(pageNumber+1)+ChatColor.DARK_GREEN+" for next page ---"; <ide> } <ide> <ide> sender.sendMessage(pMsg);
Java
apache-2.0
99a591c441e1c77691c4ca5d004b034334a19f1b
0
arx-deidentifier/arx,arx-deidentifier/arx,RaffaelBild/arx,RaffaelBild/arx
/* * ARX: Powerful Data Anonymization * Copyright 2012 - 2017 Fabian Prasser, Florian Kohlmayer and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.deidentifier.arx.algorithm; import java.util.Comparator; import java.util.PriorityQueue; import org.deidentifier.arx.framework.check.NodeChecker; import org.deidentifier.arx.framework.check.history.History.StorageStrategy; import org.deidentifier.arx.framework.lattice.SolutionSpace; import org.deidentifier.arx.framework.lattice.Transformation; import org.deidentifier.arx.metric.InformationLoss; import cern.colt.list.LongArrayList; import de.linearbits.jhpl.PredictiveProperty; /** * * @author Fabian Prasser * @author Raffael Bild * @author Johanna Eicher * @author Helmut Spengler */ public class LIGHTNINGAlgorithm extends AbstractAlgorithm{ /** * Creates a new instance * @param solutionSpace * @param checker * @param timeLimit * @param checkLimit * @return */ public static AbstractAlgorithm create(SolutionSpace solutionSpace, NodeChecker checker, int timeLimit, int checkLimit) { return new LIGHTNINGAlgorithm(solutionSpace, checker, timeLimit, checkLimit); } /** Property */ private final PredictiveProperty propertyChecked; /** Property */ private final PredictiveProperty propertyExpanded; /** Property */ private final PredictiveProperty propertyInsufficientUtility; /** The number indicating how often a depth-first-search will be performed */ private final int stepping; /** Time limit */ private final int timeLimit; /** The start time */ private long timeStart; /** The number of checks */ private int checkCount; /** The number of checks */ private final int checkLimit; /** * Constructor * @param space * @param checker * @param timeLimit * @param checkLimit */ private LIGHTNINGAlgorithm(SolutionSpace space, NodeChecker checker, int timeLimit, int checkLimit) { super(space, checker); this.checker.getHistory().setStorageStrategy(StorageStrategy.ALL); int stepping = space.getTop().getLevel(); this.stepping = stepping > 0 ? stepping : 1; this.propertyChecked = space.getPropertyChecked(); this.propertyExpanded = space.getPropertyExpanded(); this.propertyInsufficientUtility = space.getPropertyInsufficientUtility(); this.solutionSpace.setAnonymityPropertyPredictable(false); this.timeLimit = timeLimit; this.checkLimit = checkLimit; if (timeLimit <= 0) { throw new IllegalArgumentException("Invalid time limit. Must be greater than zero."); } if (checkLimit <= 0) { throw new IllegalArgumentException("Invalid step limit. Must be greater than zero."); } } @Override public void traverse() { timeStart = System.currentTimeMillis(); checkCount = 0; PriorityQueue<Long> queue = new PriorityQueue<Long>(stepping, new Comparator<Long>() { @Override public int compare(Long arg0, Long arg1) { return solutionSpace.getUtility(arg0).compareTo(solutionSpace.getUtility(arg1)); } }); Transformation bottom = solutionSpace.getBottom(); assureChecked(bottom); queue.add(bottom.getIdentifier()); Transformation next; int step = 0; Long nextId; while ((nextId = queue.poll()) != null) { next = solutionSpace.getTransformation(nextId); if (!prune(next)) { step++; if (step % stepping == 0) { dfs(queue, next); } else { expand(queue, next); } if (mustStop()) { return; } } } } /** * Makes sure that the given Transformation has been checked * @param transformation */ private void assureChecked(final Transformation transformation) { if (!transformation.hasProperty(propertyChecked)) { transformation.setChecked(checker.check(transformation, true)); trackOptimum(transformation); checkCount++; double progressSteps = (double)checkCount / (double)checkLimit; double progressTime = (double)(System.currentTimeMillis() - timeStart) / (double)timeLimit; progress(Math.max(progressSteps, progressTime)); } } /** * Performs a depth first search (without backtracking) starting from the the given transformation * @param queue * @param transformation */ private void dfs(PriorityQueue<Long> queue, Transformation transformation) { if (mustStop()) { return; } Transformation next = expand(queue, transformation); if (next != null) { queue.remove(next.getIdentifier()); dfs(queue, next); } } /** * Returns the successor with minimal information loss, if any, null otherwise. * @param queue * @param transformation * @return */ private Transformation expand(PriorityQueue<Long> queue, Transformation transformation) { Transformation result = null; LongArrayList list = transformation.getSuccessors(); for (int i = 0; i < list.size(); i++) { long id = list.getQuick(i); Transformation successor = solutionSpace.getTransformation(id); if (!successor.hasProperty(propertyExpanded) && !successor.hasProperty(propertyInsufficientUtility)) { assureChecked(successor); queue.add(successor.getIdentifier()); if (result == null || successor.getInformationLoss().compareTo(result.getInformationLoss()) < 0) { result = successor; } } if (mustStop()) { return null; } } transformation.setProperty(propertyExpanded); return result; } /** * Returns whether we have exceeded the allowed number of steps or time. * @return */ private boolean mustStop() { return ((int)(System.currentTimeMillis() - timeStart) > timeLimit) || (checkCount >= checkLimit); } /** * Returns whether we can prune this Transformation * @param transformation * @return */ private boolean prune(Transformation transformation) { // Already expanded if (transformation.hasProperty(propertyExpanded) || transformation.hasProperty(propertyInsufficientUtility)){ return true; } // If a current optimum has been discovered Transformation optimum = getGlobalOptimum(); if (optimum != null) { // We can compare lower bounds on quality InformationLoss<?> bound = transformation.getLowerBound(); if (bound.compareTo(optimum.getInformationLoss()) >= 0) { transformation.setProperty(propertyInsufficientUtility); return true; } } // We have to process this transformation return false; } }
src/main/org/deidentifier/arx/algorithm/LIGHTNINGAlgorithm.java
/* * ARX: Powerful Data Anonymization * Copyright 2012 - 2017 Fabian Prasser, Florian Kohlmayer and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.deidentifier.arx.algorithm; import java.util.Comparator; import java.util.PriorityQueue; import org.deidentifier.arx.framework.check.NodeChecker; import org.deidentifier.arx.framework.check.history.History.StorageStrategy; import org.deidentifier.arx.framework.lattice.SolutionSpace; import org.deidentifier.arx.framework.lattice.Transformation; import org.deidentifier.arx.metric.InformationLoss; import cern.colt.list.LongArrayList; import de.linearbits.jhpl.PredictiveProperty; /** * * @author Fabian Prasser * @author Raffael Bild * @author Johanna Eicher * @author Helmut Spengler */ public class LIGHTNINGAlgorithm extends AbstractAlgorithm{ /** * Creates a new instance * @param solutionSpace * @param checker * @param timeLimit * @param checkLimit * @return */ public static AbstractAlgorithm create(SolutionSpace solutionSpace, NodeChecker checker, int timeLimit, int checkLimit) { return new LIGHTNINGAlgorithm(solutionSpace, checker, timeLimit, checkLimit); } /** Property */ private final PredictiveProperty propertyChecked; /** Property */ private final PredictiveProperty propertyExpanded; /** Property */ private final PredictiveProperty propertyInsufficientUtility; /** The number indicating how often a depth-first-search will be performed */ private final int stepping; /** Time limit */ private final int timeLimit; /** The start time */ private long timeStart; /** The number of checks */ private int checkCount; /** The number of checks */ private final int checkLimit; /** * Constructor * @param space * @param checker * @param timeLimit * @param checkLimit */ private LIGHTNINGAlgorithm(SolutionSpace space, NodeChecker checker, int timeLimit, int checkLimit) { super(space, checker); this.checker.getHistory().setStorageStrategy(StorageStrategy.ALL); int stepping = space.getTop().getLevel(); this.stepping = stepping > 0 ? stepping : 1; this.propertyChecked = space.getPropertyChecked(); this.propertyExpanded = space.getPropertyExpanded(); this.propertyInsufficientUtility = space.getPropertyInsufficientUtility(); this.solutionSpace.setAnonymityPropertyPredictable(false); this.timeLimit = timeLimit; this.checkLimit = checkLimit; if (timeLimit <= 0) { throw new IllegalArgumentException("Invalid time limit. Must be greater than zero."); } if (checkLimit <= 0) { throw new IllegalArgumentException("Invalid step limit. Must be greater than zero."); } } @Override public void traverse() { timeStart = System.currentTimeMillis(); checkCount = 0; PriorityQueue<Long> queue = new PriorityQueue<Long>(stepping, new Comparator<Long>() { @Override public int compare(Long arg0, Long arg1) { return solutionSpace.getUtility(arg0).compareTo(solutionSpace.getUtility(arg1)); } }); Transformation bottom = solutionSpace.getBottom(); assureChecked(bottom); queue.add(bottom.getIdentifier()); Transformation next; int step = 0; Long nextId; while ((nextId = queue.poll()) != null) { next = solutionSpace.getTransformation(nextId); if (!prune(next)) { step++; if (step % stepping == 0) { dfs(queue, next); } else { expand(queue, next); } if (mustStop()) { return; } } } } /** * Makes sure that the given Transformation has been checked * @param transformation */ private void assureChecked(final Transformation transformation) { if (!transformation.hasProperty(propertyChecked)) { transformation.setChecked(checker.check(transformation, true)); trackOptimum(transformation); checkCount++; double progressSteps = (double)checkCount / (double)checkLimit; double progressTime = (double)(System.currentTimeMillis() - timeStart) / (double)timeLimit; progress(Math.max(progressSteps, progressTime)); } } /** * Performs a depth first search (without backtracking) starting from the the given transformation * @param queue * @param transformation */ private void dfs(PriorityQueue<Long> queue, Transformation transformation) { if (mustStop()) { return; } Transformation next = expand(queue, transformation); if (next != null) { queue.remove(next); dfs(queue, next); } } /** * Returns the successor with minimal information loss, if any, null otherwise. * @param queue * @param transformation * @return */ private Transformation expand(PriorityQueue<Long> queue, Transformation transformation) { Transformation result = null; LongArrayList list = transformation.getSuccessors(); for (int i = 0; i < list.size(); i++) { long id = list.getQuick(i); Transformation successor = solutionSpace.getTransformation(id); if (!successor.hasProperty(propertyExpanded) && !successor.hasProperty(propertyInsufficientUtility)) { assureChecked(successor); queue.add(successor.getIdentifier()); if (result == null || successor.getInformationLoss().compareTo(result.getInformationLoss()) < 0) { result = successor; } } if (mustStop()) { return null; } } transformation.setProperty(propertyExpanded); return result; } /** * Returns whether we have exceeded the allowed number of steps or time. * @return */ private boolean mustStop() { return ((int)(System.currentTimeMillis() - timeStart) > timeLimit) || (checkCount >= checkLimit); } /** * Returns whether we can prune this Transformation * @param transformation * @return */ private boolean prune(Transformation transformation) { // Already expanded if (transformation.hasProperty(propertyExpanded) || transformation.hasProperty(propertyInsufficientUtility)){ return true; } // If a current optimum has been discovered Transformation optimum = getGlobalOptimum(); if (optimum != null) { // We can compare lower bounds on quality InformationLoss<?> bound = transformation.getLowerBound(); if (bound.compareTo(optimum.getInformationLoss()) >= 0) { transformation.setProperty(propertyInsufficientUtility); return true; } } // We have to process this transformation return false; } }
Fix bug in lightning
src/main/org/deidentifier/arx/algorithm/LIGHTNINGAlgorithm.java
Fix bug in lightning
<ide><path>rc/main/org/deidentifier/arx/algorithm/LIGHTNINGAlgorithm.java <ide> } <ide> Transformation next = expand(queue, transformation); <ide> if (next != null) { <del> queue.remove(next); <add> queue.remove(next.getIdentifier()); <ide> dfs(queue, next); <ide> } <ide> }
Java
mit
7f8d32fcd82163e689f193271c7677914712a8d7
0
gilleain/signatures
package signature; import org.junit.Test; import signature.chemistry.Molecule; import signature.chemistry.MoleculeSignature; public class LargeMoleculeTest { public void addRing(int atomToAttachTo, int ringSize, Molecule molecule) { int numberOfAtoms = molecule.getAtomCount(); int previous = atomToAttachTo; for (int i = 0; i < ringSize; i++) { molecule.addAtom("C"); int current = numberOfAtoms + i; molecule.addSingleBond(previous, current); previous = current; } molecule.addSingleBond(numberOfAtoms, numberOfAtoms + (ringSize - 1)); } public Molecule makeMinimalMultiRing(int ringCount, int ringSize) { Molecule mol = new Molecule(); mol.addAtom("C"); for (int i = 0; i < ringCount; i++) { addRing(0, ringSize, mol); } return mol; } public Molecule makeTetrakisTriphenylPhosphoranylRhodium() { Molecule ttpr = new Molecule(); ttpr.addAtom("Rh"); for (int i = 1; i < 5; i++) { ttpr.addAtom("P"); ttpr.addSingleBond(0, i); } for (int j = 1; j < 5; j++) { for (int k = 0; k < 3; k++) { addRing(j, 6, ttpr); } } return ttpr; } @Test public void ttprTest() { Molecule ttpr = makeTetrakisTriphenylPhosphoranylRhodium(); MoleculeSignature molSig = new MoleculeSignature(ttpr); String sigString = molSig.toCanonicalString(); System.out.println(sigString); } @Test public void testMinimalMol() { Molecule mol = makeMinimalMultiRing(6, 3); MoleculeSignature molSig = new MoleculeSignature(mol); String sigString = molSig.toCanonicalString(); System.out.println(mol); System.out.println("result " + sigString); } public Molecule makeChain(int length) { Molecule chain = new Molecule(); int previous = -1; for (int i = 0; i < length; i++) { chain.addAtom("C"); if (previous != -1) { chain.addSingleBond(previous, i); } previous = i; } return chain; } @Test public void testLongChains() { int length = 10; Molecule chain = makeChain(length); MoleculeSignature molSig = new MoleculeSignature(chain); String sigString = molSig.toCanonicalString(); System.out.println(sigString); } public static void main(String[] args) { // new LargeMoleculeTest().testMinimalMol(); new LargeMoleculeTest().ttprTest(); } }
src/test/java/signature/LargeMoleculeTest.java
package signature; import org.junit.Test; import signature.chemistry.Molecule; import signature.chemistry.MoleculeSignature; public class LargeMoleculeTest { public void addPhenyl(int atomToAttachTo, Molecule molecule) { int numberOfAtoms = molecule.getAtomCount(); int previous = atomToAttachTo; for (int i = 0; i < 6; i++) { molecule.addAtom("C"); molecule.addSingleBond(previous, numberOfAtoms + i); } molecule.addSingleBond(numberOfAtoms, numberOfAtoms + 5); } public Molecule makeTetrakisTriphenylPhosphoranylRhodium() { Molecule ttpr = new Molecule(); ttpr.addAtom("Rh"); for (int i = 1; i < 5; i++) { ttpr.addAtom("P"); ttpr.addSingleBond(0, i); } for (int j = 1; j < 5; j++) { for (int k = 0; k < 3; k++) { addPhenyl(j, ttpr); } } return ttpr; } @Test public void ttprTest() { Molecule ttpr = makeTetrakisTriphenylPhosphoranylRhodium(); MoleculeSignature molSig = new MoleculeSignature(ttpr); String sigString = molSig.toCanonicalString(); System.out.println(sigString); } public Molecule makeChain(int length) { Molecule chain = new Molecule(); int previous = -1; for (int i = 0; i < length; i++) { chain.addAtom("C"); if (previous != -1) { chain.addSingleBond(previous, i); } previous = i; } return chain; } @Test public void testLongChains() { int length = 100; Molecule chain = makeChain(length); MoleculeSignature molSig = new MoleculeSignature(chain); String sigString = molSig.toCanonicalString(); System.out.println(sigString); } }
Smaller test case for multiple rings
src/test/java/signature/LargeMoleculeTest.java
Smaller test case for multiple rings
<ide><path>rc/test/java/signature/LargeMoleculeTest.java <ide> <ide> public class LargeMoleculeTest { <ide> <del> public void addPhenyl(int atomToAttachTo, Molecule molecule) { <add> public void addRing(int atomToAttachTo, int ringSize, Molecule molecule) { <ide> int numberOfAtoms = molecule.getAtomCount(); <ide> int previous = atomToAttachTo; <del> for (int i = 0; i < 6; i++) { <add> for (int i = 0; i < ringSize; i++) { <ide> molecule.addAtom("C"); <del> molecule.addSingleBond(previous, numberOfAtoms + i); <add> int current = numberOfAtoms + i; <add> molecule.addSingleBond(previous, current); <add> previous = current; <ide> } <del> molecule.addSingleBond(numberOfAtoms, numberOfAtoms + 5); <add> molecule.addSingleBond(numberOfAtoms, numberOfAtoms + (ringSize - 1)); <add> } <add> <add> public Molecule makeMinimalMultiRing(int ringCount, int ringSize) { <add> Molecule mol = new Molecule(); <add> mol.addAtom("C"); <add> for (int i = 0; i < ringCount; i++) { <add> addRing(0, ringSize, mol); <add> } <add> return mol; <ide> } <ide> <ide> public Molecule makeTetrakisTriphenylPhosphoranylRhodium() { <ide> <ide> for (int j = 1; j < 5; j++) { <ide> for (int k = 0; k < 3; k++) { <del> addPhenyl(j, ttpr); <add> addRing(j, 6, ttpr); <ide> } <ide> } <ide> return ttpr; <ide> MoleculeSignature molSig = new MoleculeSignature(ttpr); <ide> String sigString = molSig.toCanonicalString(); <ide> System.out.println(sigString); <add> } <add> <add> @Test <add> public void testMinimalMol() { <add> Molecule mol = makeMinimalMultiRing(6, 3); <add> MoleculeSignature molSig = new MoleculeSignature(mol); <add> String sigString = molSig.toCanonicalString(); <add> System.out.println(mol); <add> System.out.println("result " + sigString); <ide> } <ide> <ide> public Molecule makeChain(int length) { <ide> <ide> @Test <ide> public void testLongChains() { <del> int length = 100; <add> int length = 10; <ide> Molecule chain = makeChain(length); <ide> MoleculeSignature molSig = new MoleculeSignature(chain); <ide> String sigString = molSig.toCanonicalString(); <ide> System.out.println(sigString); <ide> } <add> <add> public static void main(String[] args) { <add>// new LargeMoleculeTest().testMinimalMol(); <add> new LargeMoleculeTest().ttprTest(); <add> } <ide> <ide> }
Java
apache-2.0
edab7d35b246960907bc6520c27836a699156cb8
0
google/data-transfer-project,google/data-transfer-project,google/data-transfer-project,google/data-transfer-project,google/data-transfer-project
/* * Copyright 2018 The Data Transfer Project Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.datatransferproject.transfer; import com.google.common.base.Stopwatch; import com.google.inject.Provider; import org.datatransferproject.api.launcher.DtpInternalMetricRecorder; import org.datatransferproject.api.launcher.Monitor; import org.datatransferproject.launcher.monitor.events.EventCode; import org.datatransferproject.spi.cloud.storage.JobStore; import org.datatransferproject.spi.transfer.idempotentexecutor.IdempotentImportExecutor; import org.datatransferproject.spi.transfer.provider.ExportResult; import org.datatransferproject.spi.transfer.provider.Exporter; import org.datatransferproject.spi.transfer.provider.ImportResult; import org.datatransferproject.spi.transfer.provider.Importer; import org.datatransferproject.spi.transfer.types.ContinuationData; import org.datatransferproject.types.common.ExportInformation; import org.datatransferproject.types.common.models.ContainerResource; import org.datatransferproject.types.transfer.auth.AuthData; import org.datatransferproject.types.transfer.errors.ErrorDetail; import org.datatransferproject.types.transfer.retry.RetryException; import org.datatransferproject.types.transfer.retry.RetryStrategyLibrary; import org.datatransferproject.types.transfer.retry.RetryingCallable; import javax.inject.Inject; import java.io.IOException; import java.time.Clock; import java.util.Collection; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import static java.lang.String.format; /** Implementation of {@link InMemoryDataCopier}. */ final class PortabilityInMemoryDataCopier implements InMemoryDataCopier { private static final AtomicInteger COPY_ITERATION_COUNTER = new AtomicInteger(); /** * Lazy evaluate exporter and importer as their providers depend on the polled {@code * PortabilityJob} which is not available at startup. */ private final Provider<Exporter> exporterProvider; private final Provider<Importer> importerProvider; private final IdempotentImportExecutor idempotentImportExecutor; private final Provider<RetryStrategyLibrary> retryStrategyLibraryProvider; private final Monitor monitor; private final DtpInternalMetricRecorder metricRecorder; private final JobStore jobStore; @Inject public PortabilityInMemoryDataCopier( Provider<Exporter> exporterProvider, Provider<Importer> importerProvider, Provider<RetryStrategyLibrary> retryStrategyLibraryProvider, Monitor monitor, IdempotentImportExecutor idempotentImportExecutor, DtpInternalMetricRecorder dtpInternalMetricRecorder, JobStore jobStore) { this.exporterProvider = exporterProvider; this.importerProvider = importerProvider; this.retryStrategyLibraryProvider = retryStrategyLibraryProvider; this.monitor = monitor; this.idempotentImportExecutor = idempotentImportExecutor; this.metricRecorder = dtpInternalMetricRecorder; this.jobStore = jobStore; } /** Kicks off transfer job {@code jobId} from {@code exporter} to {@code importer}. */ @Override public Collection<ErrorDetail> copy( AuthData exportAuthData, AuthData importAuthData, UUID jobId, Optional<ExportInformation> exportInfo) throws IOException, CopyException { idempotentImportExecutor.setJobId(jobId); return copyHelper(jobId, exportAuthData, importAuthData, exportInfo); } /** * Transfers data from the given {@code exporter} optionally starting at the point specified in * the provided {@code exportInformation}. Imports the data using the provided {@code importer}. * If there is more data to required to be exported, recursively copies using the specific {@link * ExportInformation} to continue the process. * * @param exportAuthData The auth data for the export * @param importAuthData The auth data for the import * @param exportInformation Any pagination or resource information to use for subsequent calls. */ private Collection<ErrorDetail> copyHelper( UUID jobId, AuthData exportAuthData, AuthData importAuthData, Optional<ExportInformation> exportInformation) throws CopyException { String jobIdPrefix = "Job " + jobId + ": "; final int copyIteration = COPY_ITERATION_COUNTER.incrementAndGet(); monitor.debug(() -> jobIdPrefix + "Copy iteration: " + copyIteration); RetryStrategyLibrary retryStrategyLibrary = retryStrategyLibraryProvider.get(); // NOTE: order is important below, do the import of all the items, then do continuation // then do sub resources, this ensures all parents are populated before children get // processed. monitor.debug( () -> jobIdPrefix + "Starting export, copy iteration: " + copyIteration, EventCode.COPIER_STARTED_EXPORT); CallableExporter callableExporter = new CallableExporter( exporterProvider, jobId, exportAuthData, exportInformation, metricRecorder); RetryingCallable<ExportResult> retryingExporter = new RetryingCallable<>(callableExporter, retryStrategyLibrary, Clock.systemUTC(), monitor); ExportResult<?> exportResult; boolean exportSuccess = false; Stopwatch exportStopwatch = Stopwatch.createStarted(); try { exportResult = retryingExporter.call(); exportSuccess = exportResult.getType() != ExportResult.ResultType.ERROR; } catch (RetryException | RuntimeException e) { throw new CopyException(jobIdPrefix + "Error happened during export", e); } finally { metricRecorder.exportPageFinished( JobMetadata.getDataType(), JobMetadata.getExportService(), exportSuccess, exportStopwatch.elapsed()); } monitor.debug( () -> jobIdPrefix + "Finished export, copy iteration: " + copyIteration, EventCode.COPIER_FINISHED_EXPORT); if (exportResult.getExportedData() != null) { monitor.debug( () -> jobIdPrefix + "Starting import, copy iteration: " + copyIteration, EventCode.COPIER_STARTED_IMPORT); CallableImporter callableImporter = new CallableImporter( importerProvider, jobId, idempotentImportExecutor, importAuthData, exportResult.getExportedData(), metricRecorder); RetryingCallable<ImportResult> retryingImporter = new RetryingCallable<>( callableImporter, retryStrategyLibrary, Clock.systemUTC(), monitor); boolean importSuccess = false; Stopwatch importStopwatch = Stopwatch.createStarted(); try { ImportResult importResult = retryingImporter.call(); importSuccess = importResult.getType() == ImportResult.ResultType.OK; if (importSuccess) { try { jobStore.addCounts(jobId, importResult.getCounts().orElse(null)); } catch (IOException e) { monitor.debug(() -> jobIdPrefix + "Unable to add counts to job: ", e); } } } catch (RetryException | RuntimeException e) { monitor.severe(() -> format("Got error importing data: %s", e), e); if (e.getClass() == RetryException.class && e.getCause().getClass() == DestinationMemoryFullException.class) { throw (DestinationMemoryFullException) e.getCause(); } } finally { metricRecorder.importPageFinished( JobMetadata.getDataType(), JobMetadata.getImportService(), importSuccess, importStopwatch.elapsed()); } monitor.debug( () -> jobIdPrefix + "Finished import, copy iteration: " + copyIteration, EventCode.COPIER_FINISHED_IMPORT); } // Import and Export were successful, determine what to do next ContinuationData continuationData = exportResult.getContinuationData(); if (null != continuationData) { // Process the next page of items for the resource if (null != continuationData.getPaginationData()) { monitor.debug( () -> jobIdPrefix + "Starting off a new copy iteration with pagination info, copy iteration: " + copyIteration); copyHelper( jobId, exportAuthData, importAuthData, Optional.of( new ExportInformation( continuationData.getPaginationData(), exportInformation.isPresent() ? exportInformation.get().getContainerResource() : null))); } // Start processing sub-resources if (continuationData.getContainerResources() != null && !continuationData.getContainerResources().isEmpty()) { for (ContainerResource resource : continuationData.getContainerResources()) { monitor.debug( () -> jobIdPrefix + "Starting off a new copy iteration with a new container resource, copy iteration: " + copyIteration); copyHelper( jobId, exportAuthData, importAuthData, Optional.of(new ExportInformation(null, resource))); } } } return idempotentImportExecutor.getErrors(); } }
portability-transfer/src/main/java/org/datatransferproject/transfer/PortabilityInMemoryDataCopier.java
/* * Copyright 2018 The Data Transfer Project Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.datatransferproject.transfer; import static java.lang.String.format; import com.google.common.base.Stopwatch; import com.google.inject.Provider; import java.io.IOException; import java.time.Clock; import java.util.Collection; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import javax.inject.Inject; import org.datatransferproject.api.launcher.DtpInternalMetricRecorder; import org.datatransferproject.api.launcher.Monitor; import org.datatransferproject.launcher.monitor.events.EventCode; import org.datatransferproject.spi.cloud.storage.JobStore; import org.datatransferproject.spi.transfer.idempotentexecutor.IdempotentImportExecutor; import org.datatransferproject.spi.transfer.provider.ExportResult; import org.datatransferproject.spi.transfer.provider.Exporter; import org.datatransferproject.spi.transfer.provider.ImportResult; import org.datatransferproject.spi.transfer.provider.Importer; import org.datatransferproject.spi.transfer.types.ContinuationData; import org.datatransferproject.types.common.ExportInformation; import org.datatransferproject.types.common.models.ContainerResource; import org.datatransferproject.types.transfer.auth.AuthData; import org.datatransferproject.types.transfer.errors.ErrorDetail; import org.datatransferproject.types.transfer.retry.RetryException; import org.datatransferproject.types.transfer.retry.RetryStrategyLibrary; import org.datatransferproject.types.transfer.retry.RetryingCallable; /** Implementation of {@link InMemoryDataCopier}. */ final class PortabilityInMemoryDataCopier implements InMemoryDataCopier { private static final AtomicInteger COPY_ITERATION_COUNTER = new AtomicInteger(); /** * Lazy evaluate exporter and importer as their providers depend on the polled {@code * PortabilityJob} which is not available at startup. */ private final Provider<Exporter> exporterProvider; private final Provider<Importer> importerProvider; private final IdempotentImportExecutor idempotentImportExecutor; private final Provider<RetryStrategyLibrary> retryStrategyLibraryProvider; private final Monitor monitor; private final DtpInternalMetricRecorder metricRecorder; private final JobStore jobStore; @Inject public PortabilityInMemoryDataCopier( Provider<Exporter> exporterProvider, Provider<Importer> importerProvider, Provider<RetryStrategyLibrary> retryStrategyLibraryProvider, Monitor monitor, IdempotentImportExecutor idempotentImportExecutor, DtpInternalMetricRecorder dtpInternalMetricRecorder, JobStore jobStore) { this.exporterProvider = exporterProvider; this.importerProvider = importerProvider; this.retryStrategyLibraryProvider = retryStrategyLibraryProvider; this.monitor = monitor; this.idempotentImportExecutor = idempotentImportExecutor; this.metricRecorder = dtpInternalMetricRecorder; this.jobStore = jobStore; } /** Kicks off transfer job {@code jobId} from {@code exporter} to {@code importer}. */ @Override public Collection<ErrorDetail> copy( AuthData exportAuthData, AuthData importAuthData, UUID jobId, Optional<ExportInformation> exportInfo) throws IOException, CopyException { idempotentImportExecutor.setJobId(jobId); return copyHelper(jobId, exportAuthData, importAuthData, exportInfo); } /** * Transfers data from the given {@code exporter} optionally starting at the point specified in * the provided {@code exportInformation}. Imports the data using the provided {@code importer}. * If there is more data to required to be exported, recursively copies using the specific {@link * ExportInformation} to continue the process. * * @param exportAuthData The auth data for the export * @param importAuthData The auth data for the import * @param exportInformation Any pagination or resource information to use for subsequent calls. */ private Collection<ErrorDetail> copyHelper( UUID jobId, AuthData exportAuthData, AuthData importAuthData, Optional<ExportInformation> exportInformation) throws CopyException { String jobIdPrefix = "Job " + jobId + ": "; final int i = COPY_ITERATION_COUNTER.incrementAndGet(); monitor.debug(() -> jobIdPrefix + "Copy iteration: " + i); RetryStrategyLibrary retryStrategyLibrary = retryStrategyLibraryProvider.get(); // NOTE: order is important below, do the import of all the items, then do continuation // then do sub resources, this ensures all parents are populated before children get // processed. monitor.debug(() -> jobIdPrefix + "Starting export", EventCode.COPIER_STARTED_EXPORT); CallableExporter callableExporter = new CallableExporter( exporterProvider, jobId, exportAuthData, exportInformation, metricRecorder); RetryingCallable<ExportResult> retryingExporter = new RetryingCallable<>(callableExporter, retryStrategyLibrary, Clock.systemUTC(), monitor); ExportResult<?> exportResult; boolean exportSuccess = false; Stopwatch exportStopwatch = Stopwatch.createStarted(); try { exportResult = retryingExporter.call(); exportSuccess = exportResult.getType() != ExportResult.ResultType.ERROR; } catch (RetryException | RuntimeException e) { throw new CopyException(jobIdPrefix + "Error happened during export", e); } finally { metricRecorder.exportPageFinished( JobMetadata.getDataType(), JobMetadata.getExportService(), exportSuccess, exportStopwatch.elapsed()); } monitor.debug(() -> jobIdPrefix + "Finished export", EventCode.COPIER_FINISHED_EXPORT); if (exportResult.getExportedData() != null) { monitor.debug(() -> jobIdPrefix + "Starting import", EventCode.COPIER_STARTED_IMPORT); CallableImporter callableImporter = new CallableImporter( importerProvider, jobId, idempotentImportExecutor, importAuthData, exportResult.getExportedData(), metricRecorder); RetryingCallable<ImportResult> retryingImporter = new RetryingCallable<>( callableImporter, retryStrategyLibrary, Clock.systemUTC(), monitor); boolean importSuccess = false; Stopwatch importStopwatch = Stopwatch.createStarted(); try { ImportResult importResult = retryingImporter.call(); importSuccess = importResult.getType() == ImportResult.ResultType.OK; if (importSuccess) { try { jobStore.addCounts(jobId, importResult.getCounts().orElse(null)); } catch (IOException e) { monitor.debug(() -> jobIdPrefix + "Unable to add counts to job: ", e); } } } catch (RetryException | RuntimeException e) { monitor.severe(() -> format("Got error importing data: %s", e), e); if (e.getClass() == RetryException.class && e.getCause().getClass() == DestinationMemoryFullException.class) { throw (DestinationMemoryFullException) e.getCause(); } } finally { metricRecorder.importPageFinished( JobMetadata.getDataType(), JobMetadata.getImportService(), importSuccess, importStopwatch.elapsed()); } monitor.debug(() -> jobIdPrefix + "Finished import", EventCode.COPIER_FINISHED_IMPORT); } // Import and Export were successful, determine what to do next ContinuationData continuationData = exportResult.getContinuationData(); if (null != continuationData) { // Process the next page of items for the resource if (null != continuationData.getPaginationData()) { monitor.debug(() -> jobIdPrefix + "Starting off a new copy iteration with pagination info"); copyHelper( jobId, exportAuthData, importAuthData, Optional.of( new ExportInformation( continuationData.getPaginationData(), exportInformation.isPresent() ? exportInformation.get().getContainerResource() : null))); } // Start processing sub-resources if (continuationData.getContainerResources() != null && !continuationData.getContainerResources().isEmpty()) { for (ContainerResource resource : continuationData.getContainerResources()) { copyHelper( jobId, exportAuthData, importAuthData, Optional.of(new ExportInformation(null, resource))); } } } return idempotentImportExecutor.getErrors(); } }
Add more logging about the copy iteration that we are on
portability-transfer/src/main/java/org/datatransferproject/transfer/PortabilityInMemoryDataCopier.java
Add more logging about the copy iteration that we are on
<ide><path>ortability-transfer/src/main/java/org/datatransferproject/transfer/PortabilityInMemoryDataCopier.java <ide> */ <ide> package org.datatransferproject.transfer; <ide> <del>import static java.lang.String.format; <del> <ide> import com.google.common.base.Stopwatch; <ide> import com.google.inject.Provider; <del>import java.io.IOException; <del>import java.time.Clock; <del>import java.util.Collection; <del>import java.util.Optional; <del>import java.util.UUID; <del>import java.util.concurrent.atomic.AtomicInteger; <del>import javax.inject.Inject; <ide> import org.datatransferproject.api.launcher.DtpInternalMetricRecorder; <ide> import org.datatransferproject.api.launcher.Monitor; <ide> import org.datatransferproject.launcher.monitor.events.EventCode; <ide> import org.datatransferproject.types.transfer.retry.RetryStrategyLibrary; <ide> import org.datatransferproject.types.transfer.retry.RetryingCallable; <ide> <add>import javax.inject.Inject; <add>import java.io.IOException; <add>import java.time.Clock; <add>import java.util.Collection; <add>import java.util.Optional; <add>import java.util.UUID; <add>import java.util.concurrent.atomic.AtomicInteger; <add> <add>import static java.lang.String.format; <add> <ide> /** Implementation of {@link InMemoryDataCopier}. */ <ide> final class PortabilityInMemoryDataCopier implements InMemoryDataCopier { <ide> <ide> <ide> private final Provider<Importer> importerProvider; <ide> private final IdempotentImportExecutor idempotentImportExecutor; <del> <ide> private final Provider<RetryStrategyLibrary> retryStrategyLibraryProvider; <ide> private final Monitor monitor; <ide> private final DtpInternalMetricRecorder metricRecorder; <ide> throws CopyException { <ide> <ide> String jobIdPrefix = "Job " + jobId + ": "; <del> final int i = COPY_ITERATION_COUNTER.incrementAndGet(); <del> monitor.debug(() -> jobIdPrefix + "Copy iteration: " + i); <add> final int copyIteration = COPY_ITERATION_COUNTER.incrementAndGet(); <add> monitor.debug(() -> jobIdPrefix + "Copy iteration: " + copyIteration); <ide> <ide> RetryStrategyLibrary retryStrategyLibrary = retryStrategyLibraryProvider.get(); <ide> <ide> // NOTE: order is important below, do the import of all the items, then do continuation <ide> // then do sub resources, this ensures all parents are populated before children get <ide> // processed. <del> monitor.debug(() -> jobIdPrefix + "Starting export", EventCode.COPIER_STARTED_EXPORT); <add> monitor.debug( <add> () -> jobIdPrefix + "Starting export, copy iteration: " + copyIteration, <add> EventCode.COPIER_STARTED_EXPORT); <ide> CallableExporter callableExporter = <ide> new CallableExporter( <ide> exporterProvider, jobId, exportAuthData, exportInformation, metricRecorder); <ide> exportSuccess, <ide> exportStopwatch.elapsed()); <ide> } <del> monitor.debug(() -> jobIdPrefix + "Finished export", EventCode.COPIER_FINISHED_EXPORT); <add> monitor.debug( <add> () -> jobIdPrefix + "Finished export, copy iteration: " + copyIteration, <add> EventCode.COPIER_FINISHED_EXPORT); <ide> <ide> if (exportResult.getExportedData() != null) { <del> monitor.debug(() -> jobIdPrefix + "Starting import", EventCode.COPIER_STARTED_IMPORT); <add> monitor.debug( <add> () -> jobIdPrefix + "Starting import, copy iteration: " + copyIteration, <add> EventCode.COPIER_STARTED_IMPORT); <ide> CallableImporter callableImporter = <ide> new CallableImporter( <ide> importerProvider, <ide> importSuccess, <ide> importStopwatch.elapsed()); <ide> } <del> monitor.debug(() -> jobIdPrefix + "Finished import", EventCode.COPIER_FINISHED_IMPORT); <add> monitor.debug( <add> () -> jobIdPrefix + "Finished import, copy iteration: " + copyIteration, <add> EventCode.COPIER_FINISHED_IMPORT); <ide> } <ide> <ide> // Import and Export were successful, determine what to do next <ide> if (null != continuationData) { <ide> // Process the next page of items for the resource <ide> if (null != continuationData.getPaginationData()) { <del> monitor.debug(() -> jobIdPrefix + "Starting off a new copy iteration with pagination info"); <add> monitor.debug( <add> () -> <add> jobIdPrefix <add> + "Starting off a new copy iteration with pagination info, copy iteration: " <add> + copyIteration); <ide> copyHelper( <ide> jobId, <ide> exportAuthData, <ide> if (continuationData.getContainerResources() != null <ide> && !continuationData.getContainerResources().isEmpty()) { <ide> for (ContainerResource resource : continuationData.getContainerResources()) { <add> monitor.debug( <add> () -> <add> jobIdPrefix <add> + "Starting off a new copy iteration with a new container resource, copy iteration: " <add> + copyIteration); <ide> copyHelper( <ide> jobId, <ide> exportAuthData,
Java
bsd-3-clause
c0c75723fc14344cfdffe2eafd08ccb51e34d84b
0
bobbylight/RSyntaxTextArea,bobbylight/RSyntaxTextArea
/* * This library is distributed under a modified BSD license. See the included * LICENSE file for details. */ package org.fife.ui.rtextarea; import org.fife.ui.SwingRunnerExtension; import org.fife.ui.rsyntaxtextarea.AbstractRSyntaxTextAreaTest; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import javax.swing.*; import java.util.Arrays; /** * Unit tests for the {@link ClipboardHistoryPopup} class. * * @author Robert Futrell * @version 1.0 */ @ExtendWith(SwingRunnerExtension.class) class ClipboardHistoryPopupTest extends AbstractRSyntaxTextAreaTest { private JFrame frame; private RSyntaxTextArea textArea; @BeforeEach void setUp() { frame = new JFrame(); textArea = createTextArea(); frame.add(textArea); frame.pack(); } @Test void testGetPreferredSize() { Assertions.assertNotNull(new ClipboardHistoryPopup(frame, textArea).getPreferredSize()); } @Test void testSetContents() { new ClipboardHistoryPopup(frame, textArea).setContents(Arrays.asList( "one", "two", "three" )); } }
RSyntaxTextArea/src/test/java/org/fife/ui/rtextarea/ClipboardHistoryPopupTest.java
/* * This library is distributed under a modified BSD license. See the included * LICENSE file for details. */ package org.fife.ui.rtextarea; import org.fife.ui.SwingRunnerExtension; import org.fife.ui.rsyntaxtextarea.AbstractRSyntaxTextAreaTest; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import javax.swing.*; import java.util.Arrays; /** * Unit tests for the {@link ClipboardHistoryPopup} class. * * @author Robert Futrell * @version 1.0 */ @ExtendWith(SwingRunnerExtension.class) class ClipboardHistoryPopupTest extends AbstractRSyntaxTextAreaTest { private JFrame frame; private RSyntaxTextArea textArea; @BeforeEach void setUp() { frame = new JFrame(); textArea = createTextArea(); frame.add(textArea); frame.pack(); } @Test @Disabled("These tests run locally, but not in CI environment for some reason") void testGetPreferredSize() { Assertions.assertNotNull(new ClipboardHistoryPopup(frame, textArea).getPreferredSize()); } @Test @Disabled("These tests run locally, but not in CI environment for some reason") void testSetContents() { new ClipboardHistoryPopup(frame, textArea).setContents(Arrays.asList( "one", "two", "three" )); } }
Running with failing tests to remember what the error is
RSyntaxTextArea/src/test/java/org/fife/ui/rtextarea/ClipboardHistoryPopupTest.java
Running with failing tests to remember what the error is
<ide><path>SyntaxTextArea/src/test/java/org/fife/ui/rtextarea/ClipboardHistoryPopupTest.java <ide> <ide> <ide> @Test <del> @Disabled("These tests run locally, but not in CI environment for some reason") <ide> void testGetPreferredSize() { <ide> Assertions.assertNotNull(new ClipboardHistoryPopup(frame, textArea).getPreferredSize()); <ide> } <ide> <ide> <ide> @Test <del> @Disabled("These tests run locally, but not in CI environment for some reason") <ide> void testSetContents() { <ide> new ClipboardHistoryPopup(frame, textArea).setContents(Arrays.asList( <ide> "one", "two", "three"
Java
apache-2.0
0e439b83e76ee830125f7a0a32f8b601467b7c93
0
s-webber/oakgp
package org.oakgp.node; import java.util.function.Function; import org.oakgp.Assignments; import org.oakgp.Type; /** * Represents a constant value. * <p> * Return the same value each time is it evaluated. */ public final class ConstantNode implements Node { private final Object value; private final Type type; /** * Constructs a new {@code ConstantNode} that represents the specified value. * * @param value * the value to be represented by the {@code ConstantNode} * @param type * the {@code Type} that the value represented by this node is of */ public ConstantNode(Object value, Type type) { this.value = value; this.type = type; } /** * Returns the value specified when this {@code ConstantNode} was constructed. */ @Override public Object evaluate(Assignments assignments) { return value; } @Override public int getNodeCount() { return 1; } @Override public Node replaceAt(int index, Function<Node, Node> replacement) { return replacement.apply(this); } @Override public Node getAt(int index) { return this; } @Override public Type getType() { return type; } @Override public int hashCode() { return value.hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } else if (o instanceof ConstantNode) { ConstantNode c = (ConstantNode) o; return this.type == c.type && this.value.equals(c.value); } else { return false; } } @Override public String toString() { return value.toString(); } }
src/main/java/org/oakgp/node/ConstantNode.java
package org.oakgp.node; import java.util.function.Function; import org.oakgp.Assignments; import org.oakgp.Type; /** * Represents a constant value. * <p> * Return the same value each time is it evaluated. */ public final class ConstantNode implements Node { private final Object value; private final Type type; /** * Constructs a new {@code ConstantNode} that represents the specified value. * * @param value * the value to be represented by the {@code ConstantNode} * @param type * the {@code Type} that the value represented by this node is of */ public ConstantNode(Object value, Type type) { this.value = value; this.type = type; } /** * Returns the value specified when this {@code ConstantNode} was constructed. */ @Override public Object evaluate(Assignments assignments) { return value; } @Override public int getNodeCount() { return 1; } @Override public Node replaceAt(int index, Function<Node, Node> replacement) { return replacement.apply(this); } @Override public Node getAt(int index) { return this; } @Override public Type getType() { return type; } @Override public int hashCode() { return value.hashCode(); } @Override public boolean equals(Object o) { if (o instanceof ConstantNode) { ConstantNode c = (ConstantNode) o; return this.value.equals(c.value) && this.type == c.type; } else { return false; } } @Override public String toString() { return value.toString(); } }
ConstantNode.equals(Object)
src/main/java/org/oakgp/node/ConstantNode.java
ConstantNode.equals(Object)
<ide><path>rc/main/java/org/oakgp/node/ConstantNode.java <ide> <ide> @Override <ide> public boolean equals(Object o) { <del> if (o instanceof ConstantNode) { <add> if (this == o) { <add> return true; <add> } else if (o instanceof ConstantNode) { <ide> ConstantNode c = (ConstantNode) o; <del> return this.value.equals(c.value) && this.type == c.type; <add> return this.type == c.type && this.value.equals(c.value); <ide> } else { <ide> return false; <ide> }
Java
apache-2.0
48f023fe14d0e09b1200735c600efc5d3da73a2d
0
Akylas/StickyListHeaders
package se.emilsjolander.stickylistheaders; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; /** * * the view that wrapps a divider header and a normal list item. The listview sees this as 1 item * * @author Emil Sjölander */ public class WrapperView extends ViewGroup { View mItem; Drawable mDivider; int mDividerHeight; View mHeader; int mItemTop; WrapperView(Context c) { super(c); setClipChildren(false); } public boolean hasHeader() { return mHeader != null; } public View getItem() { return mItem; } public int getItemTop() { return mItemTop; } public View getHeader() { return mHeader; } void update(View item, View header, Drawable divider, int dividerHeight) { //a wrapperview item can be null. Useful to show empty section but still show the header //only remove the current item if it is not the same as the new item. this can happen if wrapping a recycled view if (this.mItem != item) { removeView(this.mItem); this.mItem = item; if (item != null) { final ViewParent parent = item.getParent(); if(parent != null && parent != this) { if(parent instanceof ViewGroup) { ((ViewGroup) parent).removeView(item); } } addView(item); } } //same logik as above but for the header if (this.mHeader != header) { if (this.mHeader != null) { removeView(this.mHeader); } this.mHeader = header; if (mHeader != null) { final ViewParent parent = mHeader.getParent(); if(parent != this && !(parent instanceof StickyListHeadersListViewAbstract)) { if(parent instanceof ViewGroup) { ((ViewGroup) parent).removeView(mHeader); } addView(mHeader); } // if (mHeader.getVisibility() != View.VISIBLE) { // mHeader.setVisibility(View.VISIBLE); // } } } if (this.mDivider != divider) { this.mDivider = divider; this.mDividerHeight = dividerHeight; invalidate(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = MeasureSpec.getSize(widthMeasureSpec); int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(measuredWidth, MeasureSpec.EXACTLY); int measuredHeight = 0; //measure header or divider. when there is a header visible it acts as the divider if (mHeader != null) { ViewGroup.LayoutParams params = mHeader.getLayoutParams(); if (params != null && params.height > 0) { mHeader.measure(childWidthMeasureSpec, MeasureSpec.makeMeasureSpec(params.height, MeasureSpec.EXACTLY)); } else { mHeader.measure(childWidthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); } measuredHeight += mHeader.getMeasuredHeight(); } else if (mDivider != null && mItem != null && mItem.getVisibility()!=View.GONE) { measuredHeight += mDividerHeight; } //measure item if (mItem != null) { ViewGroup.LayoutParams params = mItem.getLayoutParams(); //enable hiding listview item,ex. toggle off items in group if(mItem.getVisibility()==View.GONE){ mItem.measure(childWidthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.EXACTLY)); }else if (params != null && params.height >= 0) { mItem.measure(childWidthMeasureSpec, MeasureSpec.makeMeasureSpec(params.height, MeasureSpec.EXACTLY)); measuredHeight += mItem.getMeasuredHeight(); } else { mItem.measure(childWidthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); measuredHeight += mItem.getMeasuredHeight(); } } //if height was specifically set in heightMeasureSpec, then use it. //very usefull for insertion or removal animation. int mode = MeasureSpec.getMode(heightMeasureSpec); setMeasuredDimension(measuredWidth,(mode != MeasureSpec.EXACTLY)?measuredHeight:MeasureSpec.getSize(heightMeasureSpec)); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { l = 0; t = 0; r = getWidth(); b = getHeight(); if (mHeader != null) { int headerHeight = mHeader.getMeasuredHeight(); mHeader.layout(l, t, r, headerHeight); mItemTop = headerHeight; } else if (mDivider != null) { mDivider.setBounds(l, t, r, mDividerHeight); mItemTop = mDividerHeight; } else { mItemTop = t; } if (mItem != null) { mItem.layout(l, mItemTop, r, b); } } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); if (mHeader == null && mDivider != null && mItem != null && mItem.getVisibility()!=View.GONE) { // Drawable.setBounds() does not seem to work pre-honeycomb. So have // to do this instead if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { canvas.clipRect(0, 0, getWidth(), mDividerHeight); } mDivider.draw(canvas); } } }
library/src/se/emilsjolander/stickylistheaders/WrapperView.java
package se.emilsjolander.stickylistheaders; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; /** * * the view that wrapps a divider header and a normal list item. The listview sees this as 1 item * * @author Emil Sjölander */ public class WrapperView extends ViewGroup { View mItem; Drawable mDivider; int mDividerHeight; View mHeader; int mItemTop; WrapperView(Context c) { super(c); setClipChildren(false); } public boolean hasHeader() { return mHeader != null; } public View getItem() { return mItem; } public int getItemTop() { return mItemTop; } public View getHeader() { return mHeader; } void update(View item, View header, Drawable divider, int dividerHeight) { //a wrapperview item can be null. Useful to show empty section but still show the header //only remove the current item if it is not the same as the new item. this can happen if wrapping a recycled view if (this.mItem != item) { removeView(this.mItem); this.mItem = item; if (item != null) { final ViewParent parent = item.getParent(); if(parent != null && parent != this) { if(parent instanceof ViewGroup) { ((ViewGroup) parent).removeView(item); } } addView(item); } } //same logik as above but for the header if (this.mHeader != header) { if (this.mHeader != null) { removeView(this.mHeader); } this.mHeader = header; if (mHeader != null) { final ViewParent parent = mHeader.getParent(); if(parent != this && !(parent instanceof StickyListHeadersListViewAbstract)) { if(parent instanceof ViewGroup) { ((ViewGroup) parent).removeView(mHeader); } addView(mHeader); } // if (mHeader.getVisibility() != View.VISIBLE) { // mHeader.setVisibility(View.VISIBLE); // } } } if (this.mDivider != divider) { this.mDivider = divider; this.mDividerHeight = dividerHeight; invalidate(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = MeasureSpec.getSize(widthMeasureSpec); int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(measuredWidth, MeasureSpec.EXACTLY); int measuredHeight = 0; //measure header or divider. when there is a header visible it acts as the divider if (mHeader != null) { ViewGroup.LayoutParams params = mHeader.getLayoutParams(); if (params != null && params.height > 0) { mHeader.measure(childWidthMeasureSpec, MeasureSpec.makeMeasureSpec(params.height, MeasureSpec.EXACTLY)); } else { mHeader.measure(childWidthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); } measuredHeight += mHeader.getMeasuredHeight(); } else if (mDivider != null && mItem != null && mItem.getVisibility()!=View.GONE) { measuredHeight += mDividerHeight; } //measure item if (mItem != null) { ViewGroup.LayoutParams params = mItem.getLayoutParams(); //enable hiding listview item,ex. toggle off items in group if(mItem.getVisibility()==View.GONE){ mItem.measure(childWidthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.EXACTLY)); }else if (params != null && params.height >= 0) { mItem.measure(childWidthMeasureSpec, MeasureSpec.makeMeasureSpec(params.height, MeasureSpec.EXACTLY)); measuredHeight += mItem.getMeasuredHeight(); } else { mItem.measure(childWidthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); measuredHeight += mItem.getMeasuredHeight(); } } //if height was specifically set in heightMeasureSpec, then use it. //very usefull for insertion or removal animation. setMeasuredDimension(measuredWidth,(heightMeasureSpec <= 0)?measuredHeight:MeasureSpec.getSize(heightMeasureSpec)); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { l = 0; t = 0; r = getWidth(); b = getHeight(); if (mHeader != null) { int headerHeight = mHeader.getMeasuredHeight(); mHeader.layout(l, t, r, headerHeight); mItemTop = headerHeight; } else if (mDivider != null) { mDivider.setBounds(l, t, r, mDividerHeight); mItemTop = mDividerHeight; } else { mItemTop = t; } if (mItem != null) { mItem.layout(l, mItemTop, r, b); } } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); if (mHeader == null && mDivider != null && mItem != null && mItem.getVisibility()!=View.GONE) { // Drawable.setBounds() does not seem to work pre-honeycomb. So have // to do this instead if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { canvas.clipRect(0, 0, getWidth(), mDividerHeight); } mDivider.draw(canvas); } } }
better size handling
library/src/se/emilsjolander/stickylistheaders/WrapperView.java
better size handling
<ide><path>ibrary/src/se/emilsjolander/stickylistheaders/WrapperView.java <ide> <ide> //if height was specifically set in heightMeasureSpec, then use it. <ide> //very usefull for insertion or removal animation. <del> setMeasuredDimension(measuredWidth,(heightMeasureSpec <= 0)?measuredHeight:MeasureSpec.getSize(heightMeasureSpec)); <add> int mode = MeasureSpec.getMode(heightMeasureSpec); <add> setMeasuredDimension(measuredWidth,(mode != MeasureSpec.EXACTLY)?measuredHeight:MeasureSpec.getSize(heightMeasureSpec)); <ide> } <ide> <ide> @Override
Java
epl-1.0
8fd3d92161434f5bec640517e31c67b605fa1021
0
CityOfLearning/ForgeEssentials,planetguy32/ForgeEssentials,liachmodded/ForgeEssentials,ForgeEssentials/ForgeEssentialsMain,aschmois/ForgeEssentialsMain,Techjar/ForgeEssentials
package com.forgeessentials.permission; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; import com.forgeessentials.api.permissions.IPermRegisterEvent; import com.forgeessentials.api.permissions.RegGroup; import com.forgeessentials.core.moduleLauncher.CallableMap.FECallable; import com.forgeessentials.util.OutputHandler; import com.google.common.collect.HashMultimap; public class PermRegLoader { protected HashSet<String> mods; protected TreeSet<String> perms; protected HashMultimap<RegGroup, PermissionChecker> registerredPerms; private Set<FECallable> data; public PermRegLoader(Set<FECallable> calls) { mods = new HashSet<String>(); data = calls; } protected void loadAllPerms() { PermissionRegistrationEvent event = new PermissionRegistrationEvent(); String modid; for (FECallable call : data) { modid = call.getIdent(); mods.add(modid); try { call.call(event); } catch (Exception e) { OutputHandler.felog.severe("Error trying to load permissions from \"" + modid + "\"!"); e.printStackTrace(); } } perms = event.registerred; registerredPerms = event.perms; } protected void clearMethods() { data = null; } private class PermissionRegistrationEvent implements IPermRegisterEvent { private HashMultimap<RegGroup, PermissionChecker> perms; private TreeSet<String> registerred; private PermissionRegistrationEvent() { perms = HashMultimap.create(); registerred = new TreeSet<String>(); } @Override public void registerPermissionLevel(String permission, RegGroup group) { registerPermissionLevel(permission, group, false); } @Override public void registerPermission(String permission) { registerred.add(permission.toLowerCase()); } @Override public void registerPermissionLevel(String permission, RegGroup group, boolean alone) { Permission deny = new Permission(permission.toLowerCase(), false); Permission allow = new Permission(permission.toLowerCase(), true); if (!deny.isAll) { registerred.add(permission.toLowerCase()); } if (group == null) { perms.put(RegGroup.ZONE, deny); } else if (group == RegGroup.ZONE) { perms.put(RegGroup.ZONE, allow); } else { perms.put(group, allow); if (alone) return; for (RegGroup g : getHigherGroups(group)) { perms.put(g, allow); } for (RegGroup g : getLowerGroups(group)) { perms.put(g, deny); } } } private RegGroup[] getHigherGroups(RegGroup g) { switch (g) { case GUESTS: return new RegGroup[] { RegGroup.MEMBERS, RegGroup.ZONE_ADMINS, RegGroup.OWNERS }; case MEMBERS: return new RegGroup[] { RegGroup.ZONE_ADMINS, RegGroup.OWNERS }; case ZONE_ADMINS: return new RegGroup[] { RegGroup.OWNERS }; default: return new RegGroup[] {}; } } private RegGroup[] getLowerGroups(RegGroup g) { switch (g) { case MEMBERS: return new RegGroup[] { RegGroup.GUESTS }; case ZONE_ADMINS: return new RegGroup[] { RegGroup.MEMBERS, RegGroup.GUESTS }; case OWNERS: return new RegGroup[] { RegGroup.MEMBERS, RegGroup.GUESTS, RegGroup.ZONE_ADMINS }; default: return new RegGroup[] {}; } } @Override public void registerPermissionProp(String permission, String globalDefault) { PermissionProp prop = new PermissionProp(permission.toLowerCase(), globalDefault); perms.put(RegGroup.ZONE, prop); } @Override public void registerPermissionProp(String permission, int globalDefault) { PermissionProp prop = new PermissionProp(permission.toLowerCase(), "" + globalDefault); perms.put(RegGroup.ZONE, prop); } @Override public void registerPermissionProp(String permission, float globalDefault) { PermissionProp prop = new PermissionProp(permission.toLowerCase(), "" + globalDefault); perms.put(RegGroup.ZONE, prop); } @Override public void registerGroupPermissionprop(String permission, String value, RegGroup group) { PermissionProp prop = new PermissionProp(permission.toLowerCase(), "" + value); perms.put(group, prop); } @Override public void registerGroupPermissionprop(String permission, int value, RegGroup group) { PermissionProp prop = new PermissionProp(permission, "" + value); perms.put(group, prop); } @Override public void registerGroupPermissionprop(String permission, float value, RegGroup group) { PermissionProp prop = new PermissionProp(permission, "" + value); perms.put(group, prop); } } }
src/main/java/com/forgeessentials/permission/PermRegLoader.java
package com.forgeessentials.permission; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; import com.forgeessentials.api.permissions.IPermRegisterEvent; import com.forgeessentials.api.permissions.RegGroup; import com.forgeessentials.core.moduleLauncher.CallableMap.FECallable; import com.forgeessentials.util.OutputHandler; import com.google.common.collect.HashMultimap; public class PermRegLoader { protected HashSet<String> mods; protected TreeSet<String> perms; protected HashMultimap<RegGroup, PermissionChecker> registerredPerms; private Set<FECallable> data; public PermRegLoader(Set<FECallable> calls) { mods = new HashSet<String>(); data = calls; } protected void loadAllPerms() { PermissionRegistrationEvent event = new PermissionRegistrationEvent(); String modid; for (FECallable call : data) { modid = call.getIdent(); mods.add(modid); try { call.call(event); } catch (Exception e) { OutputHandler.felog.severe("Error trying to load permissions from \"" + modid + "\"!"); e.printStackTrace(); } } perms = event.registerred; registerredPerms = event.perms; } protected void clearMethods() { data = null; } private class PermissionRegistrationEvent implements IPermRegisterEvent { private HashMultimap<RegGroup, PermissionChecker> perms; private TreeSet<String> registerred; private PermissionRegistrationEvent() { perms = HashMultimap.create(); registerred = new TreeSet<String>(); } @Override public void registerPermissionLevel(String permission, RegGroup group) { registerPermissionLevel(permission, group, false); } @Override public void registerPermission(String permission) { registerred.add(permission); } @Override public void registerPermissionLevel(String permission, RegGroup group, boolean alone) { Permission deny = new Permission(permission, false); Permission allow = new Permission(permission, true); if (!deny.isAll) { registerred.add(permission); } if (group == null) { perms.put(RegGroup.ZONE, deny); } else if (group == RegGroup.ZONE) { perms.put(RegGroup.ZONE, allow); } else { perms.put(group, allow); if (alone) return; for (RegGroup g : getHigherGroups(group)) { perms.put(g, allow); } for (RegGroup g : getLowerGroups(group)) { perms.put(g, deny); } } } private RegGroup[] getHigherGroups(RegGroup g) { switch (g) { case GUESTS: return new RegGroup[] { RegGroup.MEMBERS, RegGroup.ZONE_ADMINS, RegGroup.OWNERS }; case MEMBERS: return new RegGroup[] { RegGroup.ZONE_ADMINS, RegGroup.OWNERS }; case ZONE_ADMINS: return new RegGroup[] { RegGroup.OWNERS }; default: return new RegGroup[] {}; } } private RegGroup[] getLowerGroups(RegGroup g) { switch (g) { case MEMBERS: return new RegGroup[] { RegGroup.GUESTS }; case ZONE_ADMINS: return new RegGroup[] { RegGroup.MEMBERS, RegGroup.GUESTS }; case OWNERS: return new RegGroup[] { RegGroup.MEMBERS, RegGroup.GUESTS, RegGroup.ZONE_ADMINS }; default: return new RegGroup[] {}; } } @Override public void registerPermissionProp(String permission, String globalDefault) { PermissionProp prop = new PermissionProp(permission, globalDefault); perms.put(RegGroup.ZONE, prop); } @Override public void registerPermissionProp(String permission, int globalDefault) { PermissionProp prop = new PermissionProp(permission, "" + globalDefault); perms.put(RegGroup.ZONE, prop); } @Override public void registerPermissionProp(String permission, float globalDefault) { PermissionProp prop = new PermissionProp(permission, "" + globalDefault); perms.put(RegGroup.ZONE, prop); } @Override public void registerGroupPermissionprop(String permission, String value, RegGroup group) { PermissionProp prop = new PermissionProp(permission, "" + value); perms.put(group, prop); } @Override public void registerGroupPermissionprop(String permission, int value, RegGroup group) { PermissionProp prop = new PermissionProp(permission, "" + value); perms.put(group, prop); } @Override public void registerGroupPermissionprop(String permission, float value, RegGroup group) { PermissionProp prop = new PermissionProp(permission, "" + value); perms.put(group, prop); } } }
Register permissions in all-lowercase Easier to type this way.
src/main/java/com/forgeessentials/permission/PermRegLoader.java
Register permissions in all-lowercase Easier to type this way.
<ide><path>rc/main/java/com/forgeessentials/permission/PermRegLoader.java <ide> @Override <ide> public void registerPermission(String permission) <ide> { <del> registerred.add(permission); <add> registerred.add(permission.toLowerCase()); <ide> } <ide> <ide> @Override <ide> public void registerPermissionLevel(String permission, RegGroup group, boolean alone) <ide> { <del> Permission deny = new Permission(permission, false); <del> Permission allow = new Permission(permission, true); <add> Permission deny = new Permission(permission.toLowerCase(), false); <add> Permission allow = new Permission(permission.toLowerCase(), true); <ide> <ide> if (!deny.isAll) <ide> { <del> registerred.add(permission); <add> registerred.add(permission.toLowerCase()); <ide> } <ide> <ide> if (group == null) <ide> @Override <ide> public void registerPermissionProp(String permission, String globalDefault) <ide> { <del> PermissionProp prop = new PermissionProp(permission, globalDefault); <add> PermissionProp prop = new PermissionProp(permission.toLowerCase(), globalDefault); <ide> perms.put(RegGroup.ZONE, prop); <ide> } <ide> <ide> @Override <ide> public void registerPermissionProp(String permission, int globalDefault) <ide> { <del> PermissionProp prop = new PermissionProp(permission, "" + globalDefault); <add> PermissionProp prop = new PermissionProp(permission.toLowerCase(), "" + globalDefault); <ide> perms.put(RegGroup.ZONE, prop); <ide> } <ide> <ide> @Override <ide> public void registerPermissionProp(String permission, float globalDefault) <ide> { <del> PermissionProp prop = new PermissionProp(permission, "" + globalDefault); <add> PermissionProp prop = new PermissionProp(permission.toLowerCase(), "" + globalDefault); <ide> perms.put(RegGroup.ZONE, prop); <ide> } <ide> <ide> @Override <ide> public void registerGroupPermissionprop(String permission, String value, RegGroup group) <ide> { <del> PermissionProp prop = new PermissionProp(permission, "" + value); <add> PermissionProp prop = new PermissionProp(permission.toLowerCase(), "" + value); <ide> perms.put(group, prop); <ide> } <ide>
JavaScript
mit
1e0252c94009a8caca2ee5f2ee28fcc471c2b162
0
hoxton-one/deepstream.io-performance,hoxton-one/deepstream.io-performance
var cluster = require( 'cluster' ); var numCPUs = require( 'os' ).cpus().length; var conf = require( '../conf' ).server; var spawn = require( 'child_process' ).spawn; var deepstreamConfig = conf.deepstreams; var completedDeepStreams = 0; var maxDeepstreams = deepstreamConfig.length; var deepstream; var performanceUsage; if( cluster.isMaster ) { console.log( 'Running deepstream cluster with ' + maxDeepstreams + ' nodes on machine with ' + numCPUs + ' cores' ); for( var i = 0; i < numCPUs && i < maxDeepstreams; i++ ) { setTimeout( startDeepstream( deepstreamConfig[ i ] ), conf.spawningSpeed * i ); } cluster.on( 'online', onDeepstreamOnline ); cluster.on( 'exit', onDeepstreamExited ); } else { deepstream = require( './server' )( onDeepstreamStarted ); if( conf.totalTestTime !== -1 ) { setTimeout( function() { deepstream.stop(); process.exit(); }, conf.totalTestTime ); } } function startDeepstream( port ) { return function() { cluster.fork( { PORT: port } ); } } function onDeepstreamStarted( port ) { console.log( 'deepstream with PID:' + process.pid + ' listening on port ' + port ); } function onDeepstreamOnline( worker ) { var pid = worker.process.pid; console.log( 'deepstream spawned with PID:' + pid ); performanceUsage = spawn( 'bash' ); performanceUsage.stdin.write( 'rm -rf stats && mkdir stats\n' ); //Using top performanceUsage.stdin.write( 'top -p ' + pid + ' -b -d 1 > stats/' + pid + '.txt &\n' ); } function onDeepstreamExited( worker, code, signal ) { if( signal ) { console.log( "Worker was killed by signal: " + signal ); } else if( code !== 0 ) { console.log( "Worker exited with error code: " + code ); } completedDeepStreams++; if( completedDeepStreams === numCPUs || completedDeepStreams === maxDeepstreams ) { console.log( 'Server Performance Tests Finished' ); } performanceUsage.stdin.end(); } function validateConfig() { if( !maxDeepstreams ) { throw 'No array of deepstream ports provided'; } if( maxDeepstreams > numCPUs ) { console.warn( 'Attempting to run ' + maxDeepstreams + ' deepstream instances on a ' + numCPUs + ' cpu machine' ); } }
server/cluster.js
var cluster = require( 'cluster' ); var numCPUs = require( 'os' ).cpus().length; var conf = require( '../conf' ).server; var spawn = require( 'child_process' ).spawn; var deepstreamConfig = conf.deepstreams; var completedDeepStreams = 0; var maxDeepstreams = deepstreamConfig.length; var deepstream; var performanceUsage; if( cluster.isMaster ) { console.log( 'Running deepstream cluster with ' + maxDeepstreams + ' nodes on machine with ' + numCPUs + ' cores' ); for( var i = 0; i < numCPUs && i < maxDeepstreams; i++ ) { setTimeout( startDeepstream( deepstreamConfig[ i ] ), conf.spawningSpeed * i ); } cluster.on( 'online', onDeepstreamOnline ); cluster.on( 'exit', onDeepstreamExited ); } else { deepstream = require( './server' )( onDeepstreamStarted ); if( conf.totalTestTime !== -1 ) { setTimeout( function() { deepstream.stop(); process.exit(); }, conf.totalTestTime ); } } function startDeepstream( port ) { return function() { cluster.fork( { PORT: port } ); } } function onDeepstreamStarted( port ) { console.log( 'deepstream with PID:' + process.pid + ' listening on port ' + port ); } function onDeepstreamOnline( worker ) { var pid = worker.process.pid; console.log( 'deepstream spawned with PID:' + pid ); performanceUsage = spawn( 'bash' ); performanceUsage.stdin.write( 'rm -rf stats && mkdir stats\n' ); //Using pidstat performanceUsage.stdin.write( 'pidstat -p ' + pid + ' -r 1 > stats/' + pid + '-memory.txt &\n' ); performanceUsage.stdin.write( 'pidstat -p ' + pid + ' 1 > stats/' + pid + '-cpu.txt &\n' ); } function onDeepstreamExited( worker, code, signal ) { if( signal ) { console.log( "Worker was killed by signal: " + signal ); } else if( code !== 0 ) { console.log( "Worker exited with error code: " + code ); } completedDeepStreams++; if( completedDeepStreams === numCPUs || completedDeepStreams === maxDeepstreams ) { console.log( 'Server Performance Tests Finished' ); } performanceUsage.stdin.end(); } function validateConfig() { if( !maxDeepstreams ) { throw 'No array of deepstream ports provided'; } if( maxDeepstreams > numCPUs ) { console.warn( 'Attempting to run ' + maxDeepstreams + ' deepstream instances on a ' + numCPUs + ' cpu machine' ); } }
Using top instead of systat
server/cluster.js
Using top instead of systat
<ide><path>erver/cluster.js <ide> console.log( 'deepstream spawned with PID:' + pid ); <ide> performanceUsage = spawn( 'bash' ); <ide> performanceUsage.stdin.write( 'rm -rf stats && mkdir stats\n' ); <del> //Using pidstat <del> performanceUsage.stdin.write( 'pidstat -p ' + pid + ' -r 1 > stats/' + pid + '-memory.txt &\n' ); <del> performanceUsage.stdin.write( 'pidstat -p ' + pid + ' 1 > stats/' + pid + '-cpu.txt &\n' ); <add> //Using top <add> performanceUsage.stdin.write( 'top -p ' + pid + ' -b -d 1 > stats/' + pid + '.txt &\n' ); <ide> } <ide> <ide> function onDeepstreamExited( worker, code, signal ) {
Java
apache-2.0
1521fd980b1b0db679a2f4494405bc1a0b1a660e
0
euclio/learnalanguage
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; @SuppressWarnings("serial") public class LearningGUI extends JFrame { private final Compiler compiler; private final Runner runner; private static final int TERMINAL_COLS = 60; private static final int TERMINAL_ROWS = 4; private static final String TERMINAL_TEXT = "Welcome to LearnALanguage\n"; private static final Font TERMINAL_FONT = new Font("Monospaced", Font.PLAIN, 12); private static final Dimension WINDOW_DIMENSION = new Dimension(1024, 768); private String className = "Test"; private String[] args = new String[0]; public LearningGUI(String title) { super(title); // Initialize the top panel JPanel optionsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); JButton compileButton = new JButton("Compile"); compileButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { compiler.compile(className + ".java"); } }); optionsPanel.add(compileButton); JButton runButton = new JButton("Run!"); runButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { runner.run(className, args); } }); optionsPanel.add(runButton); // Create the panel that holds the code editor JEditorPane editor = new JEditorPane(); editor.setContentType("text/java"); JScrollPane editorPane = new JScrollPane(editor); editorPane.setBorder(BorderFactory.createTitledBorder("Editor")); // Create the panel that holds the console LearningConsole console = new LearningConsole(TERMINAL_TEXT, TERMINAL_ROWS, TERMINAL_COLS); console.setEditable(false); console.setFont(TERMINAL_FONT); console.setCaretPosition(console.getDocument().getLength()); JScrollPane consolePane = new JScrollPane(console); consolePane.setBorder(BorderFactory.createTitledBorder("Console")); compiler = new Compiler(editor, console); runner = new Runner(console); // Add the components to the main window this.setJMenuBar(new LearningMenuBar()); this.add(optionsPanel, BorderLayout.NORTH); this.add(editorPane, BorderLayout.CENTER); this.add(consolePane, BorderLayout.EAST); // Final Options for GUI this.setSize(WINDOW_DIMENSION); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
src/LearningGUI.java
import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.EventListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; @SuppressWarnings("serial") public class LearningGUI extends JFrame { private final Compiler compiler = new Compiler(); private static final int EDITOR_COLS = 80; private static final int EDITOR_ROWS = 80; private static final Font EDITOR_FONT = new Font("Monospaced", Font.PLAIN, 14); private static final int TERMINAL_COLS = 60; private static final int TERMINAL_ROWS = 4; private static final String TERMINAL_TEXT = "Welcome to LearnALanguage\n"; private static final Font TERMINAL_FONT = new Font("Monospaced", Font.PLAIN, 12); private static final Dimension WINDOW_DIMENSION = new Dimension(1024, 768); public LearningGUI(String title) { super(title); // Initialize the top panel JPanel optionsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); JButton compileButton = new JButton("Compile"); compileButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { compiler.compile("Test.java"); } }); optionsPanel.add(compileButton); JButton run = new JButton("Run!"); optionsPanel.add(run); // Create the panel that holds the code editor JEditorPane editor = new JEditorPane(); editor.setContentType("text/java"); JScrollPane editorPane = new JScrollPane(editor); editorPane.setBorder(BorderFactory.createTitledBorder("Editor")); compiler.setSource(editor); // Create the panel that holds the console JTextArea console = new JTextArea(TERMINAL_TEXT, TERMINAL_ROWS, TERMINAL_COLS); console.setEditable(false); console.setFont(TERMINAL_FONT); JScrollPane consolePane = new JScrollPane(console); consolePane.setBorder(BorderFactory.createTitledBorder("Console")); compiler.setOutput(console); // Add the components to the main window this.setJMenuBar(new LearningMenuBar()); this.add(optionsPanel, BorderLayout.NORTH); this.add(editorPane, BorderLayout.CENTER); this.add(consolePane, BorderLayout.EAST); // Final Options for GUI this.setSize(WINDOW_DIMENSION); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
Added ability to run compiled classes from the GUI
src/LearningGUI.java
Added ability to run compiled classes from the GUI
<ide><path>rc/LearningGUI.java <ide> import java.awt.BorderLayout; <del>import java.awt.Container; <add> <ide> import java.awt.Dimension; <ide> import java.awt.FlowLayout; <ide> import java.awt.Font; <del>import java.awt.GridBagLayout; <add> <ide> import java.awt.event.ActionEvent; <ide> import java.awt.event.ActionListener; <ide> import java.awt.event.WindowAdapter; <ide> import java.awt.event.WindowEvent; <del>import java.util.EventListener; <ide> <ide> import javax.swing.BorderFactory; <ide> import javax.swing.JButton; <ide> import javax.swing.JFrame; <ide> import javax.swing.JPanel; <ide> import javax.swing.JScrollPane; <del>import javax.swing.JSplitPane; <del>import javax.swing.JTextArea; <ide> <ide> @SuppressWarnings("serial") <ide> public class LearningGUI extends JFrame { <del> private final Compiler compiler = new Compiler(); <del> <del> private static final int EDITOR_COLS = 80; <del> private static final int EDITOR_ROWS = 80; <del> private static final Font EDITOR_FONT = new Font("Monospaced", Font.PLAIN, 14); <del> <add> private final Compiler compiler; <add> private final Runner runner; <add> <ide> private static final int TERMINAL_COLS = 60; <ide> private static final int TERMINAL_ROWS = 4; <ide> private static final String TERMINAL_TEXT = "Welcome to LearnALanguage\n"; <ide> Font.PLAIN, 12); <ide> <ide> private static final Dimension WINDOW_DIMENSION = new Dimension(1024, 768); <add> <add> private String className = "Test"; <add> private String[] args = new String[0]; <ide> <ide> public LearningGUI(String title) { <ide> super(title); <ide> <ide> JButton compileButton = new JButton("Compile"); <ide> compileButton.addActionListener(new ActionListener() { <del> public void actionPerformed(ActionEvent e) { <del> compiler.compile("Test.java"); <del> } <add> public void actionPerformed(ActionEvent e) { <add> compiler.compile(className + ".java"); <add> } <ide> }); <ide> optionsPanel.add(compileButton); <del> <del> JButton run = new JButton("Run!"); <del> optionsPanel.add(run); <del> <add> <add> JButton runButton = new JButton("Run!"); <add> runButton.addActionListener(new ActionListener() { <add> public void actionPerformed(ActionEvent e) { <add> runner.run(className, args); <add> } <add> }); <add> optionsPanel.add(runButton); <add> <ide> // Create the panel that holds the code editor <ide> JEditorPane editor = new JEditorPane(); <ide> editor.setContentType("text/java"); <ide> JScrollPane editorPane = new JScrollPane(editor); <ide> editorPane.setBorder(BorderFactory.createTitledBorder("Editor")); <del> compiler.setSource(editor); <ide> <del> // Create the panel that holds the console <del> JTextArea console = new JTextArea(TERMINAL_TEXT, TERMINAL_ROWS, TERMINAL_COLS); <add> // Create the panel that holds the console <add> LearningConsole console = new LearningConsole(TERMINAL_TEXT, <add> TERMINAL_ROWS, TERMINAL_COLS); <ide> console.setEditable(false); <ide> console.setFont(TERMINAL_FONT); <add> console.setCaretPosition(console.getDocument().getLength()); <ide> JScrollPane consolePane = new JScrollPane(console); <ide> consolePane.setBorder(BorderFactory.createTitledBorder("Console")); <del> compiler.setOutput(console); <del> <del> <del> <add> compiler = new Compiler(editor, console); <add> runner = new Runner(console); <ide> // Add the components to the main window <ide> this.setJMenuBar(new LearningMenuBar()); <ide> this.add(optionsPanel, BorderLayout.NORTH); <ide> this.add(editorPane, BorderLayout.CENTER); <ide> this.add(consolePane, BorderLayout.EAST); <del> <add> <ide> // Final Options for GUI <del> <add> <ide> this.setSize(WINDOW_DIMENSION); <del> <add> <ide> this.addWindowListener(new WindowAdapter() { <ide> @Override <ide> public void windowClosing(WindowEvent e) {
JavaScript
mit
33bfa90c51129805091f7837a4c50f6a8e396616
0
mcwehner/nabtext
/* Nabtext - an implementation of the GNU Gettext API */ //:m4_ifdef(`MO_PARSER', `m4_include(`binaryfile.js')') // TODO - Handle the selective inclusion of binaryfile.js better (ideally by // somehow making it a requirement specified by the .mo parser) var XHR = (function () { function createRequest () { var requestConstructors = [ function () { return new ActiveXObject("Microsoft.XMLHTTP"); }, function () { return new XMLHttpRequest(); } ]; for (var i = 0; i < requestConstructors.length; ++i) { try { return requestConstructors[i](); } catch (ex) { // noop } } throw new Error("Unable to create request object."); } function sendRequest (options) { if ("undefined" == typeof(options.async)) { options.async = false; } var request = createRequest(); var requestCallback = function (responseData) { if (request.status == "200" || request.status == "206" || request.status == "0") { options.success({ data : (options.binary ? new BinaryFile(responseData) : responseData), status : request.status, length : request.getResponseHeader("Content-Length") }); } else { if (options.error) { options.error(); } } }; if (typeof(request.onload) != "undefined") { request.onload = function () { requestCallback(request.responseText); }; } else { request.onreadystatechange = function () { if (request.readyState == 4) { requestCallback(request.responseBody); } }; } request.open("GET", options.url, options.async); if (request.overrideMimeType) { request.overrideMimeType("text/plain; charset=x-user-defined"); } request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 1970 00:00:00 GMT"); request.send(null); } return sendRequest; }()); /* Gettext */ // constructor var Gettext = function () { // TODO - Make the locale strings case-insensitive throughout the // library (as they're supposed to be, according to BCP 47). this.strings = { "en-US" : {} }; this.meta = { "en-US" : {} }; this.pluralFunctions = { "en-US" : function (n) { return (n != 1 ? 1 : 0); } }; this.locale = "en-US"; }; // class methods var parsers = {}; Gettext.addParser = function (mimeType, parser, binary) { parsers[mimeType] = { parser: parser, binary: binary }; }; // public interface Gettext.prototype.setlocale = function (locale) { if (locale) { this.locale = locale; this.strings[locale] = this.strings[locale] || {}; this.meta[locale] = this.meta[locale] || {}; } return this.locale; }; Gettext.prototype.sprintf = function () { var RE_CONVERSION = /(?:%(?:(\d+)\$)?([0\- ]*)(\d+|\*(?:\d+\$)?)?(?:\.(\d+|\*(?:\d+\$)?))?([diouxXeEfFcs%]))/g; // There must at least be a format string. if ("undefined" == typeof(arguments) || "string" != typeof(arguments[0])) { throw new TypeError("first argument to `sprintf' must be a string."); } var formatString = arguments[0]; var formatArgs = Array.prototype.slice.call(arguments); var lastFormatArg = 0; return formatString.replace(RE_CONVERSION, function (str, position, flagString, width, precision, specifier) { position = Number(position) || lastFormatArg + 1; lastFormatArg = position; var arg = formatArgs[position]; var flags = { alternate : (flagString.indexOf("#") != -1), zeroPadding : (flagString.indexOf("0") != -1), negativeWidth : (flagString.indexOf("-") != -1), signedPositiveSpace : (flagString.indexOf(" ") != -1), alwaysSign : (flagString.indexOf("+") != -1), localeGrouping : (flagString.indexOf("'") != -1) }; // Allows for a specified argument to be the width or precision var getVariableWidth = function (widthString) { return Number(widthString.replace(/\*(?:(\d+)\$)?/, function (s, i) { return formatArgs[ ("undefined" == typeof(i)) ? (position + 1) : i ]; })); }; if ("undefined" != typeof(width) && width) width = getVariableWidth(width); if ("undefined" != typeof(precision) && precision) precision = getVariableWidth(precision); var replacement = (function () { switch (specifier) { case "d": case "i": return parseInt(arg).toString(); // TODO - Add alternate behavior. case "o": return Math.abs(Number(arg)).toString(8); case "u": return Math.abs(Number(arg)).toString(); case "x": case "X": return (flags.alternate ? "0x" : "" ) + Number(arg).toString(16); // TODO - Add alternate behavior. case "e": case "E": return Number(arg); // TODO - Add alternate behavior. case "f": case "F": return Number(arg); case "%": return "%"; case "s": return String(arg); case "c": return String.fromCharCode(arg); default: return str; } })(); // FF treats things like `str.substr(0, undefined)' as the same thing // as `str.substr(0, 0)', which produces the empty string. I need a // better way to do this. if (precision || precision === 0) { if (specifier.match(/^[diouxXs]$/)) replacement = replacement.substr(0, precision); else if (specifier.match(/^[eE]$/)) replacement = replacement.toExponential(precision); else if (specifier.match(/^[fF]$/)) replacement = replacement.toPrecision(precision); } // Handles case like xX, eE, and fF which differ only by case if (specifier.toUpperCase() == specifier) { replacement = replacement.toUpperCase(); } // padding if ("undefined" != typeof(width) && width > replacement.length) { var padStr = new Array(width - replacement.length + 1).join( (flags.negativeWidth || !flags.zeroPadding) ? " " : "0" ); replacement = flags.negativeWidth ? (replacement + padStr) : (padStr + replacement); } return replacement; }); }; Gettext.prototype.load = function (options) { var self = this; if (!(options.mimeType in parsers)) { throw new Error(this.sprintf('MIME type "%s" is not supported.', options.mimeType)); } XHR({ url : options.url, binary : parsers[options.mimeType].binary, success : function (response) { self.setlocale(options.locale || self.locale); self.strings[self.locale] = parsers[options.mimeType].parser.call(self, response.data); var metaParts = self.strings[self.locale][""].split("\n"); delete self.strings[self.locale][""]; for (var part; part = metaParts.pop(), metaParts.length > 0; ) { var m = part.match(/^([^:]+):\s*(.*)$/); if (m) self.meta[self.locale][ m[1] ] = m[2]; } self.pluralFunctions[self.locale] = (function () { var pluralExpression = self.meta[self.locale]["Plural-Forms"] ? self.meta[self.locale]["Plural-Forms"].match(/plural=([^;]+)/)[1] : "throw new Error()" ; var pluralFunc = new Function("n", "return " + pluralExpression + ";"); // MCW: We want to make sure this is a valid expression, as // improper use of the gettext toolchain (e.g., failing to // use `msginit' or setting the correct headers by hand) is // sometimes causing our expression to be the string // "EXPRESSION". try { for (var i = 0; i < 10; ++i) { pluralFunc(i); } } catch (e) { throw new EvalError( "The pluralization expression '" + pluralExpression + "' is not valid." + " Make sure that the Plural-Forms header is set correctly in your translation file." ); } return function (n) { var plural = pluralFunc(n); if (plural === true || plural === false) return plural ? 1 : 0; else return plural; }; })(); }, error : function () { throw new Error(self.sprintf('Failed to load "%s"', url)); } }); }; Gettext.prototype.gettext = function (messageId) { // TODO - If the current locale (somehow) doesn't exist in the // `strings' object, this will probably break. return this.strings[this.locale][messageId] || messageId; }; Gettext.prototype.ngettext = function (/* messageId*, count */) { var args = Array.prototype.slice.call(arguments, 0, arguments.length - 1); var count = arguments[arguments.length - 1]; var key = args.join("\0"); if (key in this.strings[this.locale]) { return this.strings[this.locale][key].split("\0")[ this.pluralFunctions[this.locale](count) ]; } else { return args[ this.pluralFunctions[this.locale](count) ]; } }; Gettext.prototype.dgettext = function (domain, messageId) { // TODO - Implement domains? return this.gettext(messageId); }; Gettext.prototype.dcgettext = function (domain, messageId, category) { // TODO - Implement domains, categories? return this.gettext(messageId); }; Gettext.prototype.dngettext = function (domain, messageId, messageIdPlural, count) { // TODO - Implement domains? return this.ngettext(messageId, messageIdPlural, count); }; Gettext.prototype.dcngettext = function (domain, messageId, messageIdPlural, count, category) { // TODO - Implement domains, categories? return this.ngettext(messageId, messageIdPlural, count); }; Gettext.prototype.pgettext = function (context, messageId) { // TODO - Implement contexts? return this.gettext(messageId); }; Gettext.prototype.dpgettext = function (domain, context, messageId) { // TODO - Implement domains, contexts? return this.gettext(messageId); }; Gettext.prototype.dcpgettext = function (domain, context, messageId, category) { // TODO - Implement domains, contexts, categories? return this.gettext(messageId); }; Gettext.prototype.npgettext = function (context, messageId, messageIdPlural, count) { // TODO - Implement contexts? return this.ngettext(messageId, messageIdPlural, count); }; Gettext.prototype.dnpgettext = function (domain, context, messageId, messageIdPlural, count) { // TODO - Implement domains, contexts? return this.ngettext(messageId, messageIdPlural, count); }; Gettext.prototype.dcnpgettext = function (domain, context, messageId, messageIdPlural, count, category) { // TODO - Implement domains, contexts, categories? return this.ngettext(messageId, messageIdPlural, count); }; //:m4_ifdef(`MO_PARSER', `m4_include(`parsers/mo.js')') //:m4_ifdef(`PO_PARSER', `m4_include(`parsers/po.js')')
src/nabtext.core.js
/* Nabtext - an implementation of the GNU Gettext API */ //:m4_ifdef(`MO_PARSER', `m4_include(`binaryfile.js')') // TODO - Handle the selective inclusion of binaryfile.js better (ideally by // somehow making it a requirement specified by the .mo parser) var XHR = (function () { function createRequest () { var requestConstructors = [ function () { return new ActiveXObject("Microsoft.XMLHTTP"); }, function () { return new XMLHttpRequest(); } ]; for (var i = 0; i < requestConstructors.length; ++i) { try { return requestConstructors[i](); } catch (ex) { // noop } } throw new Error("Unable to create request object."); } function sendRequest (options) { if ("undefined" == typeof(options.async)) { options.async = false; } var request = createRequest(); var requestCallback = function (responseData) { if (request.status == "200" || request.status == "206" || request.status == "0") { options.success({ data : (options.binary ? new BinaryFile(responseData) : responseData), status : request.status, length : request.getResponseHeader("Content-Length") }); } else { if (options.error) { options.error(); } } }; if (typeof(request.onload) != "undefined") { request.onload = function () { requestCallback(request.responseText); }; } else { request.onreadystatechange = function () { if (request.readyState == 4) { requestCallback(request.responseBody); } }; } request.open("GET", options.url, options.async); if (request.overrideMimeType) { request.overrideMimeType("text/plain; charset=x-user-defined"); } request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 1970 00:00:00 GMT"); request.send(null); } return sendRequest; }()); /* Gettext */ // constructor var Gettext = function () { // TODO - Make the locale strings case-insensitive throughout the // library (as they're supposed to be, according to BCP 47). this.strings = { "en-US" : {} }; this.meta = { "en-US" : {} }; this.pluralFunctions = { "en-US" : function (n) { return (n != 1); } }; this.locale = "en-US"; }; // class methods var parsers = {}; Gettext.addParser = function (mimeType, parser, binary) { parsers[mimeType] = { parser: parser, binary: binary }; }; // public interface Gettext.prototype.setlocale = function (locale) { if (locale) { this.locale = locale; this.strings[locale] = this.strings[locale] || {}; this.meta[locale] = this.meta[locale] || {}; } return this.locale; }; Gettext.prototype.sprintf = function () { var RE_CONVERSION = /(?:%(?:(\d+)\$)?([0\- ]*)(\d+|\*(?:\d+\$)?)?(?:\.(\d+|\*(?:\d+\$)?))?([diouxXeEfFcs%]))/g; // There must at least be a format string. if ("undefined" == typeof(arguments) || "string" != typeof(arguments[0])) { throw new TypeError("first argument to `sprintf' must be a string."); } var formatString = arguments[0]; var formatArgs = Array.prototype.slice.call(arguments); var lastFormatArg = 0; return formatString.replace(RE_CONVERSION, function (str, position, flagString, width, precision, specifier) { position = Number(position) || lastFormatArg + 1; lastFormatArg = position; var arg = formatArgs[position]; var flags = { alternate : (flagString.indexOf("#") != -1), zeroPadding : (flagString.indexOf("0") != -1), negativeWidth : (flagString.indexOf("-") != -1), signedPositiveSpace : (flagString.indexOf(" ") != -1), alwaysSign : (flagString.indexOf("+") != -1), localeGrouping : (flagString.indexOf("'") != -1) }; // Allows for a specified argument to be the width or precision var getVariableWidth = function (widthString) { return Number(widthString.replace(/\*(?:(\d+)\$)?/, function (s, i) { return formatArgs[ ("undefined" == typeof(i)) ? (position + 1) : i ]; })); }; if ("undefined" != typeof(width) && width) width = getVariableWidth(width); if ("undefined" != typeof(precision) && precision) precision = getVariableWidth(precision); var replacement = (function () { switch (specifier) { case "d": case "i": return parseInt(arg).toString(); // TODO - Add alternate behavior. case "o": return Math.abs(Number(arg)).toString(8); case "u": return Math.abs(Number(arg)).toString(); case "x": case "X": return (flags.alternate ? "0x" : "" ) + Number(arg).toString(16); // TODO - Add alternate behavior. case "e": case "E": return Number(arg); // TODO - Add alternate behavior. case "f": case "F": return Number(arg); case "%": return "%"; case "s": return String(arg); case "c": return String.fromCharCode(arg); default: return str; } })(); // FF treats things like `str.substr(0, undefined)' as the same thing // as `str.substr(0, 0)', which produces the empty string. I need a // better way to do this. if (precision || precision === 0) { if (specifier.match(/^[diouxXs]$/)) replacement = replacement.substr(0, precision); else if (specifier.match(/^[eE]$/)) replacement = replacement.toExponential(precision); else if (specifier.match(/^[fF]$/)) replacement = replacement.toPrecision(precision); } // Handles case like xX, eE, and fF which differ only by case if (specifier.toUpperCase() == specifier) { replacement = replacement.toUpperCase(); } // padding if ("undefined" != typeof(width) && width > replacement.length) { var padStr = new Array(width - replacement.length + 1).join( (flags.negativeWidth || !flags.zeroPadding) ? " " : "0" ); replacement = flags.negativeWidth ? (replacement + padStr) : (padStr + replacement); } return replacement; }); }; Gettext.prototype.load = function (options) { var self = this; if (!(options.mimeType in parsers)) { throw new Error(this.sprintf('MIME type "%s" is not supported.', options.mimeType)); } XHR({ url : options.url, binary : parsers[options.mimeType].binary, success : function (response) { self.setlocale(options.locale || self.locale); self.strings[self.locale] = parsers[options.mimeType].parser.call(self, response.data); var metaParts = self.strings[self.locale][""].split("\n"); delete self.strings[self.locale][""]; for (var part; part = metaParts.pop(), metaParts.length > 0; ) { var m = part.match(/^([^:]+):\s*(.*)$/); if (m) self.meta[self.locale][ m[1] ] = m[2]; } self.pluralFunctions[self.locale] = (function () { var pluralExpression = self.meta[self.locale]["Plural-Forms"] ? self.meta[self.locale]["Plural-Forms"].match(/plural=([^;]+)/)[1] : "throw new Error()" ; var pluralFunc = new Function("n", "return " + pluralExpression + ";"); // MCW: We want to make sure this is a valid expression, as // improper use of the gettext toolchain (e.g., failing to // use `msginit' or setting the correct headers by hand) is // sometimes causing our expression to be the string // "EXPRESSION". try { for (var i = 0; i < 10; ++i) { pluralFunc(i); } } catch (e) { throw new EvalError( "The pluralization expression '" + pluralExpression + "' is not valid." + " Make sure that the Plural-Forms header is set correctly in your translation file." ); } return function (n) { var plural = pluralFunc(n); if (plural === true || plural === false) return plural ? 1 : 0; else return plural; }; })(); }, error : function () { throw new Error(self.sprintf('Failed to load "%s"', url)); } }); }; Gettext.prototype.gettext = function (messageId) { // TODO - If the current locale (somehow) doesn't exist in the // `strings' object, this will probably break. return this.strings[this.locale][messageId] || messageId; }; Gettext.prototype.ngettext = function (/* messageId*, count */) { var args = Array.prototype.slice.call(arguments, 0, arguments.length - 1); var count = arguments[arguments.length - 1]; var key = args.join("\0"); if (key in this.strings[this.locale]) { return this.strings[this.locale][key].split("\0")[ this.pluralFunctions[this.locale](count) ]; } else { return args[ this.pluralFunctions[this.locale](count) ]; } }; Gettext.prototype.dgettext = function (domain, messageId) { // TODO - Implement domains? return this.gettext(messageId); }; Gettext.prototype.dcgettext = function (domain, messageId, category) { // TODO - Implement domains, categories? return this.gettext(messageId); }; Gettext.prototype.dngettext = function (domain, messageId, messageIdPlural, count) { // TODO - Implement domains? return this.ngettext(messageId, messageIdPlural, count); }; Gettext.prototype.dcngettext = function (domain, messageId, messageIdPlural, count, category) { // TODO - Implement domains, categories? return this.ngettext(messageId, messageIdPlural, count); }; Gettext.prototype.pgettext = function (context, messageId) { // TODO - Implement contexts? return this.gettext(messageId); }; Gettext.prototype.dpgettext = function (domain, context, messageId) { // TODO - Implement domains, contexts? return this.gettext(messageId); }; Gettext.prototype.dcpgettext = function (domain, context, messageId, category) { // TODO - Implement domains, contexts, categories? return this.gettext(messageId); }; Gettext.prototype.npgettext = function (context, messageId, messageIdPlural, count) { // TODO - Implement contexts? return this.ngettext(messageId, messageIdPlural, count); }; Gettext.prototype.dnpgettext = function (domain, context, messageId, messageIdPlural, count) { // TODO - Implement domains, contexts? return this.ngettext(messageId, messageIdPlural, count); }; Gettext.prototype.dcnpgettext = function (domain, context, messageId, messageIdPlural, count, category) { // TODO - Implement domains, contexts, categories? return this.ngettext(messageId, messageIdPlural, count); }; //:m4_ifdef(`MO_PARSER', `m4_include(`parsers/mo.js')') //:m4_ifdef(`PO_PARSER', `m4_include(`parsers/po.js')')
Fixed default pluralization function.
src/nabtext.core.js
Fixed default pluralization function.
<ide><path>rc/nabtext.core.js <ide> // library (as they're supposed to be, according to BCP 47). <ide> this.strings = { "en-US" : {} }; <ide> this.meta = { "en-US" : {} }; <del> this.pluralFunctions = { "en-US" : function (n) { return (n != 1); } }; <add> this.pluralFunctions = { "en-US" : function (n) { return (n != 1 ? 1 : 0); } }; <ide> this.locale = "en-US"; <ide> }; <ide>
Java
apache-2.0
a4b0ab72a8d9f49cc5780c1f36faafda7c372e7d
0
mbdevpl/open-fortran-parser-xml,mbdevpl/open-fortran-parser-xml,mbdevpl/open-fortran-parser-xml
package fortran.ofp; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import org.antlr.runtime.Token; import org.w3c.dom.Attr; import org.w3c.dom.Element; import fortran.ofp.parser.java.IActionEnums; import fortran.ofp.parser.java.IFortranParser; /** * XML output generator for Open Fortran Parser. * * @author Mateusz Bysiek https://mbdevpl.github.io/ */ public class XMLPrinter extends XMLPrinterBase { private static final Logger LOG = Logger.getLogger(XMLPrinter.class.getName()); public XMLPrinter(String[] args, IFortranParser parser, String filename) { super(args, parser, filename); } protected void genericOperationForceOpen(int nodesCount) { ArrayList<Element> nodes = contextNodes(-nodesCount, nodesCount); contextOpen("operation"); if (nodesCount == 2) setAttribute("type", "unary"); else if (nodesCount > 2) setAttribute("type", "multiary"); else cleanUpAfterError("didn't expect nodesCount=" + nodesCount); for (Element node : nodes) { boolean needsTransform = !node.getTagName().equals("operand") && !node.getTagName().equals("operator"); if (needsTransform) contextOpen("operand"); moveHere(node); if (needsTransform) contextClose(); } } protected void genericOperationOpen(int numberOfOperators) { if (numberOfOperators > 0) { int nodesCount = 2 * numberOfOperators + 1; genericOperationForceOpen(nodesCount); } } protected void genericOperationClose(int numberOfOperators) { if (numberOfOperators > 0) contextClose(); } protected void genericLoopControl(boolean hasStep) { String[] contexts = { "lower-bound", "upper-bound", "step" }; int takenNodesCount = hasStep ? 3 : 2; ArrayList<Element> takenNodes = contextNodes(-takenNodesCount, takenNodesCount); context = contextNode(-takenNodesCount - 1); for (int i = 0; i < takenNodes.size(); ++i) { contextOpen(contexts[i]); moveHere(takenNodes.get(i)); contextClose(); } contextClose(); } public void generic_name_list_part(Token id) { contextOpen("name"); setAttribute("id", id); if (verbosity >= 100) super.generic_name_list_part(id); contextClose(); } public void generic_name_list__begin() { if (context.getTagName().equals("specification") || context.getTagName().equals("file")) contextOpen("declaration"); super.generic_name_list__begin(); } public void specification_part(int numUseStmts, int numImportStmts, int numImplStmts, int numDeclConstructs) { if (context.getTagName().equals("header")) { contextClose("header"); contextOpen("body"); } if (context.getTagName().equals("declaration")) { LOG.log(Level.FINER, "closing unclosed declaration at specification_part"); contextClose("declaration"); } if (!context.getTagName().equals("specification")) contextOpen("specification"); contextCloseAllInner("specification"); if (verbosity >= 80) super.specification_part(numUseStmts, numImportStmts, numImplStmts, numDeclConstructs); setAttribute("uses", numUseStmts); setAttribute("imports", numImportStmts); setAttribute("implicits", numImplStmts); setAttribute("declarations", numDeclConstructs); contextClose(); contextOpen("statement"); } public void declaration_construct() { contextClose("declaration"); if (verbosity >= 100) super.declaration_construct(); contextOpen("declaration"); } public void execution_part_construct() { if (verbosity >= 100) super.execution_part_construct(); } public void specification_stmt() { if (verbosity >= 100) super.specification_stmt(); } public void executable_construct() { if (verbosity >= 100) super.executable_construct(); } public void action_stmt() { if (contextTryFind("statement") == null) { // TODO this ugly workaround should be removed contextClose(); Element element = contextNode(-1); contextOpen("statement"); moveHere(element); } if (verbosity >= 100) super.action_stmt(); contextClose("statement"); contextOpen("statement"); } public void keyword() { if (verbosity >= 100) super.keyword(); } public void name(Token id) { super.name(id); } public void constant(Token id) { super.constant(id); } public void scalar_constant() { if (verbosity >= 100) super.scalar_constant(); } public void literal_constant() { if (verbosity >= 100) super.literal_constant(); contextClose("literal"); } public void label(Token lbl) { boolean closedLoop = false; Element outerContext = context; while (outerContext != root) { if (outerContext.getTagName().equals("loop") && outerContext.getAttribute("label").equals(lbl.getText())) { context = outerContext; closedLoop = true; break; } outerContext = (Element) outerContext.getParentNode(); } super.label(lbl); if (closedLoop) contextOpen("statement"); } public void type_param_value(boolean hasExpr, boolean hasAsterisk, boolean hasColon) { Element value = hasExpr ? contextNode(-1): null; contextOpen("type-attribute"); if (hasExpr) moveHere(value); super.type_param_value(hasExpr, hasAsterisk, hasColon); contextClose(); } public void intrinsic_type_spec(Token keyword1, Token keyword2, int type, boolean hasKindSelector) { if (!context.getTagName().equals("declaration")) { // TODO: ensure being in body contextOpen("declaration"); } setAttribute("type", "variable"); super.intrinsic_type_spec(keyword1, keyword2, type, hasKindSelector); } public void kind_selector(Token token1, Token token2, boolean hasExpression) { if (hasExpression) { Element value = contextNode(-1); contextOpen("kind"); moveHere(value); } else { contextOpen("kind"); setAttribute("value", token2); } super.kind_selector(token1, token2, hasExpression); contextClose(); } public void int_literal_constant(Token digitString, Token kindParam) { if (kindParam != null) { Element kind = contextNode(-1); assert kind.getTagName().equals("kind-param"); contextOpen("literal"); moveHere(kind); } else { contextOpen("literal"); } setAttribute("type", "int"); setAttribute("value", digitString); super.int_literal_constant(digitString, kindParam); } public void boz_literal_constant(Token constant) { contextOpen("literal"); setAttribute("type", "int"); setAttribute("value", constant); super.boz_literal_constant(constant); } public void real_literal_constant(Token realConstant, Token kindParam) { if (kindParam != null) { Element kind = contextNode(-1); assert kind.getTagName().equals("kind-param"); contextOpen("literal"); moveHere(kind); } else { contextOpen("literal"); } setAttribute("type", "real"); setAttribute("value", realConstant); super.real_literal_constant(realConstant, kindParam); } public void char_selector(Token tk1, Token tk2, int kindOrLen1, int kindOrLen2, boolean hasAsterisk) { int[] attribute_types = new int[]{kindOrLen2, kindOrLen1}; contextOpen("type-attributes"); Element localContext = context; contextClose(); Element value = null; for(int attribute_type: attribute_types) { switch (attribute_type) { case IActionEnums.KindLenParam_none: break; case IActionEnums.KindLenParam_len: value = contextNode(-2); moveTo(localContext, value); contextRename(value, "type-attribute", "length"); break; case IActionEnums.KindLenParam_kind: value = contextNode(-2); Element prevContext = context; context = localContext; contextOpen("kind"); moveHere(value); contextClose(); context = prevContext; break; default: throw new IllegalArgumentException(Integer.toString(attribute_type)); } } context = localContext; if (value == null) { contextClose(); context.removeChild(localContext); } super.char_selector(tk1, tk2, kindOrLen1, kindOrLen2, hasAsterisk); if (value != null) contextClose(); } public void char_length(boolean hasTypeParamValue) { Element value = contextNode(-1); contextOpen("length"); moveHere(value); if (hasTypeParamValue) { moveHere(contextNodes(value)); context.removeChild(value); } super.char_length(hasTypeParamValue); contextClose(); } public void scalar_int_literal_constant() { if (verbosity >= 100) super.scalar_int_literal_constant(); contextClose("literal"); } public void char_literal_constant(Token digitString, Token id, Token str) { contextOpen("literal"); setAttribute("type", "char"); setAttribute("value", str); super.char_literal_constant(digitString, id, str); } public void logical_literal_constant(Token logicalValue, boolean isTrue, Token kindParam) { if (kindParam != null) { Element kind = contextNode(-1); assert kind.getTagName().equals("kind-param"); contextOpen("literal"); moveHere(kind); } else { contextOpen("literal"); } setAttribute("type", "bool"); setAttribute("value", isTrue); super.logical_literal_constant(logicalValue, isTrue, kindParam); } public void derived_type_stmt(Token label, Token keyword, Token id, Token eos, boolean hasTypeAttrSpecList, boolean hasGenericNameList) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "type"); super.derived_type_stmt(label, keyword, id, eos, hasTypeAttrSpecList, hasGenericNameList); } public void derived_type_spec(Token typeName, boolean hasTypeParamSpecList) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "variable"); super.derived_type_spec(typeName, hasTypeParamSpecList); } public void array_constructor() { context = contextNode(-1); // temporarily reopen previously-closed context if (verbosity >= 100) super.array_constructor(); contextClose(); // re-close previously closed context } public void ac_spec() { context = contextNode(-1); // temporarily reopen previously-closed context if (verbosity >= 100) super.ac_spec(); contextClose(); // re-close previously closed context } public void ac_value() { contextClose("value"); if (verbosity >= 100) super.ac_value(); contextOpen("value"); } public void ac_value_list__begin() { contextOpen("array-constructor-values"); if (verbosity >= 100) super.ac_value_list__begin(); contextOpen("value"); } public void ac_value_list(int count) { contextClose("value"); contextCloseAllInner("array-constructor-values", "array-constructor"); setAttribute("count", count); if (verbosity >= 100) super.ac_value_list(count); contextClose(); } public void ac_implied_do() { super.ac_implied_do(); contextRename("array-constructor-values", "array-constructor"); contextOpen("value"); } public void ac_implied_do_control(boolean hasStride) { genericLoopControl(hasStride); Element element = contextNode(-1); contextClose("value"); contextOpen("header"); moveHere(element); // contextClose("index-variable"); super.ac_implied_do_control(hasStride); contextClose(); } public void type_declaration_stmt(Token label, int numAttributes, Token eos) { super.type_declaration_stmt(label, numAttributes, eos); } public void declaration_type_spec(Token udtKeyword, int type) { ArrayList<Element> typeDeclarations = contextNodes(); contextOpen("type"); setAttribute("hasLength", false); setAttribute("hasKind", false); setAttribute("hasAttributes", false); Attr n; for (Element declaration : typeDeclarations) { switch (declaration.getTagName()) { case "intrinsic-type-spec": n = getAttribute("name"); if (n != null) new IllegalArgumentException(declaration.getTagName()); setAttribute("name", declaration.getAttribute("keyword1")); setAttribute("type", "intrinsic"); break; case "derived-type-spec": n = getAttribute("name"); if (n != null) new IllegalArgumentException(declaration.getTagName()); setAttribute("name", declaration.getAttribute("typeName")); setAttribute("type", "derived"); break; case "length": setAttribute("hasLength", true); break; case "kind": setAttribute("hasKind", true); break; case "type-attributes": setAttribute("hasAttributes", true); break; default: break; } moveHere(declaration); } super.declaration_type_spec(udtKeyword, type); contextClose(); } public void attr_spec(Token attrKeyword, int attr) { String nestIn = ""; switch (attr) { case IActionEnums.AttrSpec_access: // private break; case IActionEnums.AttrSpec_language_binding: // bind break; case IActionEnums.AttrSpec_ALLOCATABLE: nestIn = "allocatable"; break; case IActionEnums.AttrSpec_ASYNCHRONOUS: nestIn = "asynchronous"; break; case IActionEnums.AttrSpec_CODIMENSION: nestIn = "codimension"; break; case IActionEnums.AttrSpec_DIMENSION: // dimension break; case IActionEnums.AttrSpec_EXTERNAL: nestIn = "external"; break; case IActionEnums.AttrSpec_INTENT: // intent break; case IActionEnums.AttrSpec_INTRINSIC: nestIn = "intrinsic"; break; case IActionEnums.AttrSpec_OPTIONAL: nestIn = "optional"; break; case IActionEnums.AttrSpec_PARAMETER: nestIn = "parameter"; break; case IActionEnums.AttrSpec_POINTER: nestIn = "pointer"; break; case IActionEnums.AttrSpec_PROTECTED: nestIn = "protected"; break; case IActionEnums.AttrSpec_SAVE: nestIn = "save"; break; case IActionEnums.AttrSpec_TARGET: nestIn = "target"; break; case IActionEnums.AttrSpec_VALUE: nestIn = "value"; break; case IActionEnums.AttrSpec_VOLATILE: nestIn = "volatile"; break; default: throw new IllegalArgumentException(Integer.toString(attr) + " - " + attrKeyword); } if (nestIn.length() > 0) contextOpen("attribute-" + nestIn); super.attr_spec(attrKeyword, attr); if (nestIn.length() > 0) contextClose(); } public void entity_decl(Token id, boolean hasArraySpec, boolean hasCoarraySpec, boolean hasCharLength, boolean hasInitialization) { contextCloseAllInner("variable"); super.entity_decl(id, hasArraySpec, hasCoarraySpec, hasCharLength, hasInitialization); setAttribute("name", id); setAttribute("hasInitialValue", hasInitialization); contextClose(); contextOpen("variable"); } public void entity_decl_list__begin() { super.entity_decl_list__begin(); contextOpen("variable"); } public void entity_decl_list(int count) { contextClose("variable"); super.entity_decl_list(count); } public void initialization(boolean hasExpr, boolean hasNullInit) { Element initialValue = contextNode(-1); contextOpen("initial-value"); moveHere(initialValue); super.initialization(hasExpr, hasNullInit); contextClose(); } public void access_spec(Token keyword, int type) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); super.access_spec(keyword, type); } public void language_binding_spec(Token keyword, Token id, boolean hasName) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); super.language_binding_spec(keyword, id, hasName); } public void array_spec(int count) { contextCloseAllInner("dimensions"); if (verbosity >= 100) super.array_spec(count); setAttribute("count", count); contextClose(); } public void array_spec_element(int type) { Element value = null; Element value2 = null; switch (type) { case IActionEnums.ArraySpecElement_expr_colon_expr: value2 = contextNode(-2); case IActionEnums.ArraySpecElement_expr: case IActionEnums.ArraySpecElement_expr_colon: case IActionEnums.ArraySpecElement_expr_colon_asterisk: value = contextNode(-1); break; case IActionEnums.ArraySpecElement_asterisk: case IActionEnums.ArraySpecElement_colon: break; default: throw new IllegalArgumentException(Integer.toString(type)); } if (!context.getTagName().equals("dimensions")) contextOpen("dimensions"); contextOpen("dimension"); switch (type) { case IActionEnums.ArraySpecElement_expr: setAttribute("type", "simple"); // (a) moveHere(value); break; case IActionEnums.ArraySpecElement_expr_colon: setAttribute("type", "upper-bound-assumed-shape"); // (a:) moveHere(value); break; case IActionEnums.ArraySpecElement_expr_colon_expr: setAttribute("type", "range"); // (a:b) contextOpen("range"); contextOpen("lower-bound"); moveHere(value2); contextClose(); contextOpen("upper-bound"); moveHere(value); contextClose(); contextClose(); break; case IActionEnums.ArraySpecElement_expr_colon_asterisk: setAttribute("type", "upper-bound-assumed-size"); // (a:*) moveHere(value); break; case IActionEnums.ArraySpecElement_asterisk: setAttribute("type", "assumed-size"); // (*) break; case IActionEnums.ArraySpecElement_colon: setAttribute("type", "assumed-shape"); // (:) break; default: throw new IllegalArgumentException(Integer.toString(type)); } super.array_spec_element(type); contextClose(); } public void intent_spec(Token intentKeyword1, Token intentKeyword2, int intent) { contextOpen("intent"); switch (intent) { case IActionEnums.IntentSpec_IN: setAttribute("type", "in"); break; case IActionEnums.IntentSpec_OUT: setAttribute("type", "out"); break; case IActionEnums.IntentSpec_INOUT: setAttribute("type", "inout"); break; default: throw new IllegalArgumentException(Integer.toString(intent)); } if (verbosity >= 100) super.intent_spec(intentKeyword1, intentKeyword2, intent); contextClose(); } public void access_id_list__begin() { // contextOpen("access-list"); if (verbosity >= 100) super.access_id_list__begin(); } public void access_id_list(int count) { super.access_id_list(count); // contextClose("access-list"); } public void allocatable_decl_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "allocatables"); super.allocatable_decl_list__begin(); } public void asynchronous_stmt(Token label, Token keyword, Token eos) { if (!context.getTagName().equals("declaration")) { Element value = contextNode(-1); if (value.getTagName() != "names") cleanUpAfterError("tag name is not 'names' but '" + value.getTagName() + "'"); contextOpen("declaration"); moveHere(value); } super.asynchronous_stmt(label, keyword, eos); } public void codimension_decl_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "codimensions"); super.codimension_decl_list__begin(); } public void data_stmt_object() { if (verbosity >= 100) super.data_stmt_object(); } public void data_stmt_object_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "data"); super.data_stmt_object_list__begin(); } public void data_stmt_value(Token asterisk) { contextCloseAllInner("values"); if (verbosity >= 100) super.data_stmt_value(asterisk); } public void hollerith_literal_constant(Token hollerithConstant) { contextOpen("literal"); setAttribute("type", "hollerith"); setAttribute("value", hollerithConstant); super.hollerith_literal_constant(hollerithConstant); } public void dimension_stmt(Token label, Token keyword, Token eos, int count) { contextCloseAllInner("variables"); setAttribute("count", count); super.dimension_stmt(label, keyword, eos, count); contextClose(); setAttribute("type", "variable-dimensions"); } public void dimension_decl(Token id) { Element value = contextNode(-1); if (!context.getTagName().equals("variables")) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); contextOpen("variables"); } contextOpen("variable"); setAttribute("name", id); moveHere(value); /* if (contextTryFind("declaration") == null) { contextOpen("declaration"); setAttribute("type", "dimension"); } */ super.dimension_decl(id); contextClose("variable"); } public void named_constant_def_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "parameter"); super.named_constant_def_list__begin(); } public void named_constant_def(Token id) { Element value = contextNode(-1); contextOpen("constant"); setAttribute("name", id); moveHere(value); if (verbosity >= 100) super.named_constant_def(id); contextClose(); } public void pointer_stmt(Token label, Token keyword, Token eos) { super.pointer_stmt(label, keyword, eos); if (!context.getTagName().equals("declaration")) LOG.warning("pointer_stmt in unexpected context"); setAttribute("type", "pointer"); } public void pointer_decl_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); super.pointer_decl_list__begin(); } public void pointer_decl(Token id, boolean hasSpecList) { contextOpen("name"); super.pointer_decl(id, hasSpecList); setAttribute("id", id); contextClose("name"); } public void save_stmt(Token label, Token keyword, Token eos, boolean hasSavedEntityList) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "save"); super.save_stmt(label, keyword, eos, hasSavedEntityList); } public void saved_entity(Token id, boolean isCommonBlockName) { contextOpen("name"); super.saved_entity(id, isCommonBlockName); setAttribute("id", id); contextClose(); } public void target_decl_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "targets"); if (verbosity >= 100) super.target_decl_list__begin(); } public void target_decl_list(int count) { // TODO Auto-generated method stub super.target_decl_list(count); } public void value_stmt(Token label, Token keyword, Token eos) { // TODO: get also label node if there is one Element value = contextNode(-1); if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "value"); moveHere(value); super.value_stmt(label, keyword, eos); } public void volatile_stmt(Token label, Token keyword, Token eos) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "volatile"); super.volatile_stmt(label, keyword, eos); } public void implicit_stmt(Token label, Token implicitKeyword, Token noneKeyword, Token eos, boolean hasImplicitSpecList) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); if (verbosity >= 20) super.implicit_stmt(label, implicitKeyword, noneKeyword, eos, hasImplicitSpecList); setAttribute("type", "implicit"); setAttribute("subtype", noneKeyword == null ? "some" : "none"); contextClose("declaration"); contextOpen("declaration"); } public void letter_spec(Token id1, Token id2) { contextOpen("letter-range"); setAttribute("begin", id1); setAttribute("end", id2); if (verbosity >= 100) super.letter_spec(id1, id2); contextClose(); } public void namelist_stmt(Token label, Token keyword, Token eos, int count) { contextCloseAllInner("namelists"); super.namelist_stmt(label, keyword, eos, count); setAttribute("count", count); } public void namelist_group_name(Token id) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "namelists"); contextOpen("namelists"); contextOpen("names"); if (verbosity >= 100) super.namelist_group_name(id); setAttribute("id", id); } public void namelist_group_object_list(int count) { contextCloseAllInner("names"); setAttribute("count", count); if (verbosity >= 100) super.namelist_group_object_list(count); contextClose(); } public void equivalence_set_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "equivalence"); super.equivalence_set_list__begin(); contextOpen("equivalent"); } public void equivalence_set_list(int count) { contextClose("equivalent"); super.equivalence_set_list(count); } public void equivalence_object() { contextClose("equivalent"); if (verbosity >= 100) super.equivalence_object(); contextOpen("equivalent"); } public void equivalence_object_list__begin() { // TODO Auto-generated method stub super.equivalence_object_list__begin(); } public void equivalence_object_list(int count) { // TODO Auto-generated method stub super.equivalence_object_list(count); } public void common_block_name(Token id) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "common"); super.common_block_name(id); } public void variable() { if (verbosity >= 100) super.variable(); setAttribute("type", "variable"); contextClose("name"); } public void designator_or_func_ref() { if (verbosity >= 100) super.designator_or_func_ref(); setAttribute("type", "ambiguous"); contextClose("name"); } public void substring_range(boolean hasLowerBound, boolean hasUpperBound) { Element lowerBound = null; Element upperBound = null; if (hasLowerBound) lowerBound = contextNode(-1); if (hasUpperBound) { upperBound = lowerBound; if (hasLowerBound) lowerBound = contextNode(-2); else lowerBound = null; } contextOpen("name"); contextOpen("range"); if (lowerBound != null) { contextOpen("lower-bound"); moveHere(lowerBound); contextClose(); } if (upperBound != null) { contextOpen("upper-bound"); moveHere(upperBound); contextClose(); } if (verbosity >= 100) super.substring_range(hasLowerBound, hasUpperBound); contextClose(); } public void data_ref(int numPartRef) { for (int i = 1; i < numPartRef; ++i) { assert context.getTagName().equals("name"); Element innerName = context; ArrayList<Element> elements = contextNodes(); Attr innerNameId = getAttribute("id"); contextClose(); assert context.getTagName().equals("name"); moveHere(elements); setAttribute("id", getAttribute("id").getValue() + "%" + innerNameId.getValue()); context.removeChild(innerName); } super.data_ref(numPartRef); } public void part_ref(Token id, boolean hasSectionSubscriptList, boolean hasImageSelector) { Element e = null; if (hasSectionSubscriptList) { e = contextNode(-1); if (!e.getTagName().equals("subscripts")) cleanUpAfterError("tag name is not 'subscripts' but '" + e.getTagName() + "'"); } contextOpen("name"); setAttribute("id", id); setAttribute("hasSubscripts", hasSectionSubscriptList); if (hasSectionSubscriptList) moveHere(e); if (verbosity >= 60) super.part_ref(id, hasSectionSubscriptList, hasImageSelector); } public void section_subscript(boolean hasLowerBound, boolean hasUpperBound, boolean hasStride, boolean isAmbiguous) { // contextCloseAllInner("subscript"); Element outerContext = context; contextOpen("subscript"); if (!hasLowerBound && !hasUpperBound && !hasStride) setAttribute("type", "empty"); else if (hasLowerBound && !hasUpperBound && !hasStride) { setAttribute("type", "simple"); moveHere(contextNode(outerContext, -2)); } else { setAttribute("type", "range"); Element lowerBound = null; Element upperBound = null; Element step = null; contextOpen("range"); if (hasLowerBound) { lowerBound = contextOpen("lower-bound"); contextClose(); } if (hasUpperBound) { upperBound = contextOpen("upper-bound"); contextClose(); } if (hasStride) { step = contextOpen("step"); contextClose(); } contextClose(); if (hasStride) moveTo(step, contextNode(outerContext, -2)); if (hasUpperBound) moveTo(upperBound, contextNode(outerContext, -2)); if (hasLowerBound) moveTo(lowerBound, contextNode(outerContext, -2)); } if (verbosity >= 80) super.section_subscript(hasLowerBound, hasUpperBound, hasStride, isAmbiguous); contextClose(); } public void section_subscript_list__begin() { super.section_subscript_list__begin(); // contextOpen("subscript"); } public void section_subscript_list(int count) { // contextClose("subscript"); super.section_subscript_list(count); } public void allocate_stmt(Token label, Token allocateKeyword, Token eos, boolean hasTypeSpec, boolean hasAllocOptList) { /* if (hasAllocOptList) cleanUpAfterError("didn't expect hasAllocOptList=" + hasAllocOptList); */ int movedCount = 1 + (hasAllocOptList ? 1 : 0); ArrayList<Element> elements = contextNodes(-movedCount, movedCount); contextOpen("allocate"); moveHere(elements); super.allocate_stmt(label, allocateKeyword, eos, hasTypeSpec, hasAllocOptList); contextClose(); } public void alloc_opt(Token allocOpt) { contextCloseAllInner("keyword-arguments"); Element element = contextNode(-1); contextOpen("keyword-argument"); setAttribute("name", allocOpt); moveHere(element); if (verbosity >= 100) super.alloc_opt(allocOpt); contextClose(); } public void allocation(boolean hasAllocateShapeSpecList, boolean hasAllocateCoarraySpec) { if (hasAllocateShapeSpecList || hasAllocateCoarraySpec) cleanUpAfterError("didn't expect hasAllocateShapeSpecList=" + hasAllocateShapeSpecList + " hasAllocateCoarraySpec=" + hasAllocateCoarraySpec); Element element = contextNode(-1); if (element.getTagName().equals("expression")) context = element; else { contextOpen("expression"); moveHere(element); } super.allocation(hasAllocateShapeSpecList, hasAllocateCoarraySpec); contextClose(); } public void allocate_object() { setAttribute("type", "variable"); contextClose("name"); Element element = contextNode(-1); contextOpen("expression"); moveHere(element); if (verbosity >= 100) super.allocate_object(); contextClose(); } public void nullify_stmt(Token label, Token nullifyKeyword, Token eos) { ArrayList<Element> elements = contextNodes(); contextOpen("nullify"); moveHere(elements); super.nullify_stmt(label, nullifyKeyword, eos); contextClose(); } public void pointer_object() { contextCloseAllInner("pointers"); Element pointer = contextNode(-1); contextOpen("pointer"); moveHere(pointer); if (verbosity >= 100) super.pointer_object(); contextClose(); } public void deallocate_stmt(Token label, Token deallocateKeyword, Token eos, boolean hasDeallocOptList) { Element element2 = hasDeallocOptList ? contextNode(-2) : null; Element element = contextNode(-1); contextOpen("deallocate"); if (hasDeallocOptList) moveHere(element2); moveHere(element); super.deallocate_stmt(label, deallocateKeyword, eos, hasDeallocOptList); contextClose(); } public void dealloc_opt(Token id) { contextCloseAllInner("keyword-arguments"); Element element = contextNode(-1); contextOpen("keyword-argument"); setAttribute("name", id); moveHere(element); if (verbosity >= 100) super.dealloc_opt(id); contextClose(); } public void primary() { context = contextNode(-1); // temporarily reopen previously-closed context if (verbosity >= 100) super.primary(); contextClose(); // re-close previously closed context } public void parenthesized_expr() { context = contextNode(-1); // temporarily reopen previously-closed context if (verbosity >= 100) super.parenthesized_expr(); contextClose(); // re-close previously closed context } public void power_operand(boolean hasPowerOperand) { /* if (!hasPowerOperand) cleanUpAfterError("didn't expect hasPowerOperand=" + hasPowerOperand); */ int numPowerOp = hasPowerOperand ? 1 : 0; genericOperationOpen(numPowerOp); if (verbosity >= 100) super.power_operand(hasPowerOperand); genericOperationClose(numPowerOp); } public void power_operand__power_op(Token powerOp) { if (verbosity >= 100) super.power_operand__power_op(powerOp); cleanUpAfterError(); } public void mult_operand(int numMultOps) { genericOperationOpen(numMultOps); if (verbosity >= 100) super.mult_operand(numMultOps); genericOperationClose(numMultOps); } public void mult_operand__mult_op(Token multOp) { Element element = contextNode(-1); contextOpen("operand"); moveHere(element); if (verbosity >= 100) super.mult_operand__mult_op(multOp); contextClose(); } public void signed_operand(Token addOp) { if (addOp != null) genericOperationForceOpen(2); if (verbosity >= 100) super.signed_operand(addOp); if (addOp != null) genericOperationClose(1); } public void add_operand(int numAddOps) { genericOperationOpen(numAddOps); if (verbosity >= 100) super.add_operand(numAddOps); genericOperationClose(numAddOps); } public void add_operand__add_op(Token addOp) { // same as mult_operand__mult_op() Element element = contextNode(-1); contextOpen("operand"); moveHere(element); if (verbosity >= 100) super.add_operand__add_op(addOp); contextClose(); } public void level_2_expr(int numConcatOps) { genericOperationOpen(numConcatOps); if (verbosity >= 100) super.level_2_expr(numConcatOps); genericOperationClose(numConcatOps); } public void power_op(Token powerKeyword) { contextOpen("operator"); setAttribute("operator", powerKeyword); if (verbosity >= 100) super.power_op(powerKeyword); contextClose(); } public void mult_op(Token multKeyword) { contextOpen("operator"); setAttribute("operator", multKeyword); if (verbosity >= 100) super.mult_op(multKeyword); contextClose(); } public void add_op(Token addKeyword) { contextOpen("operator"); setAttribute("operator", addKeyword); if (verbosity >= 100) super.add_op(addKeyword); contextClose(); } public void level_3_expr(Token relOp) { int numRelOp = relOp == null ? 0 : 1; genericOperationOpen(numRelOp); if (verbosity >= 80) super.level_3_expr(relOp); genericOperationClose(numRelOp); } public void concat_op(Token concatKeyword) { contextOpen("operator"); if (verbosity >= 100) super.concat_op(concatKeyword); setAttribute("operator", "//"); contextClose(); } public void rel_op(Token relOp) { contextOpen("operator"); setAttribute("operator", relOp); if (verbosity >= 100) super.rel_op(relOp); contextClose(); } public void and_operand(boolean hasNotOp, int numAndOps) { if (hasNotOp) if (numAndOps == 0) genericOperationForceOpen(2); else { int nodesCount = 2 * numAndOps + 2; ArrayList<Element> nodes = contextNodes(-nodesCount, 2); Element reference = contextNode(-nodesCount + 2); Element operation = contextOpen("operation"); setAttribute("type", "unary"); for (Element node : nodes) { boolean needsTransform = !node.getTagName().equals("operand") && !node.getTagName().equals("operator"); if (needsTransform) contextOpen("operand"); moveHere(node); if (needsTransform) contextClose(); } contextClose(); context.removeChild(operation); context.insertBefore(operation, reference); genericOperationOpen(numAndOps); // cleanUpAfterError("didn't expect hasNotOp=" + hasNotOp + " numAndOps=" + numAndOps); } else genericOperationOpen(numAndOps); if (verbosity >= 100) super.and_operand(hasNotOp, numAndOps); if (hasNotOp) genericOperationClose(numAndOps > 0 ? numAndOps : 1); else genericOperationClose(numAndOps); } public void and_operand__not_op(boolean hasNotOp) { if (hasNotOp) { genericOperationForceOpen(2); genericOperationClose(1); // cleanUpAfterError("didn't expect hasNotOp=" + hasNotOp); } // same as mult_operand__mult_op() Element element = contextNode(-1); contextOpen("operand"); moveHere(element); if (verbosity >= 100) super.and_operand__not_op(hasNotOp); contextClose(); } public void or_operand(int numOrOps) { genericOperationOpen(numOrOps); if (verbosity >= 100) super.or_operand(numOrOps); genericOperationClose(numOrOps); } public void equiv_operand(int numEquivOps) { genericOperationOpen(numEquivOps); if (verbosity >= 100) super.equiv_operand(numEquivOps); genericOperationClose(numEquivOps); } public void equiv_operand__equiv_op(Token equivOp) { // same as mult_operand__mult_op() Element element = contextNode(-1); contextOpen("operand"); moveHere(element); if (verbosity >= 100) super.equiv_operand__equiv_op(equivOp); contextClose(); } public void not_op(Token notOp) { contextOpen("operator"); setAttribute("operator", notOp); if (verbosity >= 100) super.not_op(notOp); contextClose(); } public void and_op(Token andOp) { contextOpen("operator"); setAttribute("operator", andOp); if (verbosity >= 100) super.and_op(andOp); contextClose(); } public void or_op(Token orOp) { contextOpen("operator"); setAttribute("operator", orOp); if (verbosity >= 100) super.or_op(orOp); contextClose(); } public void equiv_op(Token equivOp) { contextOpen("operator"); setAttribute("operator", equivOp); if (verbosity >= 100) super.equiv_op(equivOp); contextClose(); } public void assignment_stmt(Token label, Token eos) { ArrayList<Element> nodes = contextNodes(); if (nodes.size() < 2) cleanUpAfterError("there should be at least 2 nodes for 'assignment' but " + nodes.size() + " found"); Element target = contextNode(-2); Element value = contextNode(-1); contextOpen("assignment"); contextOpen("target"); moveHere(target); contextClose(); contextOpen("value"); moveHere(value); contextClose(); if (verbosity >= 100) super.assignment_stmt(label, eos); contextClose(); } public void pointer_assignment_stmt(Token label, Token eos, boolean hasBoundsSpecList, boolean hasBoundsRemappingList) { Element value = contextNode(-1); contextClose(); Element target = contextNode(-1); contextOpen("pointer-assignment"); contextOpen("target"); moveHere(target); contextClose(); contextOpen("value"); moveHere(value); contextClose(); super.pointer_assignment_stmt(label, eos, hasBoundsSpecList, hasBoundsRemappingList); contextClose(); } public void forall_construct() { if (verbosity >= 100) super.forall_construct(); contextClose("loop"); contextOpen("statement"); } public void forall_construct_stmt(Token label, Token id, Token forallKeyword, Token eos) { contextRename("statement", "loop"); setAttribute("type", "forall"); ArrayList<Element> elements = contextNodes(); contextOpen("header"); moveHere(elements); contextClose(); super.forall_construct_stmt(label, id, forallKeyword, eos); contextOpen("body"); contextOpen("statement"); } public void forall_header() { if (verbosity >= 100) super.forall_header(); } public void forall_triplet_spec(Token id, boolean hasStride) { contextOpen("index-variable"); setAttribute("name", id); contextClose(); Element element = contextNode(-1); context.removeChild(element); context.insertBefore(element, contextNode(hasStride ? -3 : -2)); genericLoopControl(hasStride); context = contextNode(-1); super.forall_triplet_spec(id, hasStride); contextClose(); } public void forall_assignment_stmt(boolean isPointerAssignment) { Element assignment = contextNode(-1); if (!context.getTagName().equals("header")) cleanUpAfterError("didn't expect <" + context.getTagName() + ">"); contextClose(); contextOpen("body"); contextOpen("statement"); moveHere(assignment); context = assignment; // temporarily reopen assignment context if (!context.getTagName().equals("assignment")) cleanUpAfterError("didn't expect <" + context.getTagName() + ">"); if (verbosity >= 100) super.forall_assignment_stmt(isPointerAssignment); contextClose(); // re-close assignment context contextClose(); contextClose(); } public void end_forall_stmt(Token label, Token endKeyword, Token forallKeyword, Token id, Token eos) { contextCloseAllInner("loop"); super.end_forall_stmt(label, endKeyword, forallKeyword, id, eos); } public void forall_stmt__begin() { contextRename("statement", "loop"); setAttribute("type", "forall"); if (verbosity >= 100) super.forall_stmt__begin(); contextOpen("header"); } public void forall_stmt(Token label, Token forallKeyword) { contextCloseAllInner("loop"); super.forall_stmt(label, forallKeyword); contextClose(); contextOpen("statement"); // TODO: temporary workaround } public void block() { contextCloseAllInner("body"); if (verbosity >= 100) super.block(); } public void if_construct() { contextCloseAllInner("if"); if (verbosity >= 100) super.if_construct(); contextClose(); contextOpen("statement"); } public void if_then_stmt(Token label, Token id, Token ifKeyword, Token thenKeyword, Token eos) { contextRename("statement", "if"); ArrayList<Element> nodes = contextNodes(); contextOpen("header"); moveHere(nodes); contextClose(); if (verbosity >= 80) super.if_then_stmt(label, id, ifKeyword, thenKeyword, eos); contextOpen("body"); contextOpen("statement"); } public void else_if_stmt(Token label, Token elseKeyword, Token ifKeyword, Token thenKeyword, Token id, Token eos) { Element condition = contextNode(-1); contextClose("body"); contextOpen("header"); setAttribute("type", "else-if"); moveHere(condition); contextClose(); if (verbosity >= 80) super.else_if_stmt(label, elseKeyword, ifKeyword, thenKeyword, id, eos); contextOpen("body"); setAttribute("type", "else-if"); contextOpen("statement"); } public void else_stmt(Token label, Token elseKeyword, Token id, Token eos) { contextClose("body"); if (verbosity >= 80) super.else_stmt(label, elseKeyword, id, eos); contextOpen("body"); setAttribute("type", "else"); contextOpen("statement"); } public void end_if_stmt(Token label, Token endKeyword, Token ifKeyword, Token id, Token eos) { contextCloseAllInner("if"); if (verbosity >= 80) super.end_if_stmt(label, endKeyword, ifKeyword, id, eos); } public void if_stmt__begin() { contextRename("statement", "if"); if (verbosity >= 100) super.if_stmt__begin(); contextOpen("header"); // will be filled by if_stmt() contextClose(); contextOpen("body"); contextOpen("statement"); } public void if_stmt(Token label, Token ifKeyword) { contextClose("body"); Element ifHeader = contextNode(-2); Element ifBody = contextNode(-1); Element statementToBeFixed = contextNode(ifBody, 0); Element ifCondition = contextNode(statementToBeFixed, 0); if (!ifBody.getTagName().equals("body")) cleanUpAfterError("if body node must be named body"); moveTo(ifHeader, ifCondition); contextCloseAllInner("if"); super.if_stmt(label, ifKeyword); contextClose(); contextOpen("statement"); } public void block_construct() { if (verbosity >= 100) super.block_construct(); } public void case_construct() { contextCloseAllInner("select"); if (verbosity >= 100) super.case_construct(); contextClose(); contextOpen("statement"); } public void select_case_stmt(Token label, Token id, Token selectKeyword, Token caseKeyword, Token eos) { contextRename("statement", "select"); ArrayList<Element> nodes = contextNodes(); contextOpen("header"); moveHere(nodes); contextClose(); super.select_case_stmt(label, id, selectKeyword, caseKeyword, eos); contextOpen("body"); } public void case_stmt(Token label, Token caseKeyword, Token id, Token eos) { super.case_stmt(label, caseKeyword, id, eos); contextOpen("body"); contextOpen("statement"); } public void end_select_stmt(Token label, Token endKeyword, Token selectKeyword, Token id, Token eos) { contextCloseAllInner("select"); super.end_select_stmt(label, endKeyword, selectKeyword, id, eos); } public void case_selector(Token defaultToken) { if (!context.getTagName().equals("case") && contextTryFind("case") != null) { contextClose("case"); contextOpen("case"); setAttribute("type", "default"); contextOpen("header"); contextClose(); } super.case_selector(defaultToken); } public void case_value_range() { contextClose("value-range"); if (verbosity >= 100) super.case_value_range(); contextOpen("value-range"); contextOpen("value"); } public void case_value_range_list__begin() { if (context.getTagName().equals("body") && ((Element) context.getParentNode()).getTagName().equals("case")) { contextClose("body"); contextClose("case"); } contextOpen("case"); setAttribute("type", "specific"); contextOpen("header"); super.case_value_range_list__begin(); contextOpen("value-range"); contextOpen("value"); } public void case_value_range_list(int count) { super.case_value_range_list(count); contextClose("header"); } public void case_value_range_suffix() { contextCloseAllInner("value-range"); if (verbosity >= 100) super.case_value_range_suffix(); } public void case_value() { contextClose("value"); if (verbosity >= 100) super.case_value(); contextOpen("value"); } public void associate_construct() { super.associate_construct(); contextClose("associate"); contextOpen("statement"); } public void associate_stmt(Token label, Token id, Token associateKeyword, Token eos) { Element element = contextNode(-1); contextRename("statement", "associate"); contextOpen("header"); moveHere(element); contextClose(); super.associate_stmt(label, id, associateKeyword, eos); contextOpen("body"); contextOpen("statement"); } public void association(Token id) { context = contextNode(-1); assert context.getNodeName().equals("keyword-argument"); setAttribute("argument-name", id); if (verbosity >= 100) super.association(id); contextClose(); } public void selector() { Element element = contextNode(-1); contextOpen("keyword-argument"); moveHere(element); if (verbosity >= 100) super.selector(); contextClose(); } public void end_associate_stmt(Token label, Token endKeyword, Token associateKeyword, Token id, Token eos) { contextClose("body"); super.end_associate_stmt(label, endKeyword, associateKeyword, id, eos); } public void type_guard_stmt(Token label, Token typeKeyword, Token isOrDefaultKeyword, Token selectConstructName, Token eos) { // TODO Auto-generated method stub contextOpen("statement"); super.type_guard_stmt(label, typeKeyword, isOrDefaultKeyword, selectConstructName, eos); } public void do_construct() { contextCloseAllInner("loop"); if (verbosity >= 100) super.do_construct(); contextClose(); contextOpen("statement"); } public void block_do_construct() { if (verbosity >= 100) super.block_do_construct(); } public void do_stmt(Token label, Token id, Token doKeyword, Token digitString, Token eos, boolean hasLoopControl) { if (!hasLoopControl) { contextRename("statement", "loop"); setAttribute("type", "do-label"); } /* if (digitString != null) // TODO: is this needed? setAttribute("label", digitString); */ super.do_stmt(label, id, doKeyword, digitString, eos, hasLoopControl); contextOpen("body"); contextOpen("statement"); } public void label_do_stmt(Token label, Token id, Token doKeyword, Token digitString, Token eos, boolean hasLoopControl) { super.label_do_stmt(label, id, doKeyword, digitString, eos, hasLoopControl); cleanUpAfterError("didn't expect label-do-stmt"); } public void loop_control(Token whileKeyword, int doConstructType, boolean hasOptExpr) { /* if(hasOptExpr) cleanUpAfterError("didn't expect hasOptExpr=" + hasOptExpr); */ if (doConstructType == 1701) genericLoopControl(hasOptExpr); contextRename("statement", "loop"); String loopType = ""; switch (doConstructType) { case IActionEnums.DoConstruct_concurrent: loopType = "do-concurrent"; break; case IActionEnums.DoConstruct_variable: loopType = "do"; break; case IActionEnums.DoConstruct_while: loopType = "do-while"; break; default: throw new IllegalArgumentException(Integer.toString(doConstructType)); } setAttribute("type", loopType); Element element = contextNode(-1); contextOpen("header"); moveHere(element); super.loop_control(whileKeyword, doConstructType, hasOptExpr); contextClose(); } public void do_variable(Token id) { contextOpen("index-variable"); setAttribute("name", id); super.do_variable(id); contextClose(); } public void end_do() { if (verbosity >= 100) super.end_do(); } public void end_do_stmt(Token label, Token endKeyword, Token doKeyword, Token id, Token eos) { contextCloseAllInner("loop"); if (verbosity >= 80) super.end_do_stmt(label, endKeyword, doKeyword, id, eos); } public void do_term_action_stmt(Token label, Token endKeyword, Token doKeyword, Token id, Token eos, boolean inserted) { contextCloseAllInner("loop"); if (verbosity >= 80) super.do_term_action_stmt(label, endKeyword, doKeyword, id, eos, inserted); } public void cycle_stmt(Token label, Token cycleKeyword, Token id, Token eos) { contextOpen("cycle"); if (verbosity >= 80) super.cycle_stmt(label, cycleKeyword, id, eos); contextClose(); } public void exit_stmt(Token label, Token exitKeyword, Token id, Token eos) { contextOpen("exit"); if (verbosity >= 80) super.exit_stmt(label, exitKeyword, id, eos); contextClose(); } public void goto_stmt(Token label, Token goKeyword, Token toKeyword, Token target_label, Token eos) { // TODO Auto-generated method stub super.goto_stmt(label, goKeyword, toKeyword, target_label, eos); } public void continue_stmt(Token label, Token continueKeyword, Token eos) { Element labelNode = contextNodesCount() > 0 ? contextNode(-1) : null; labelNode = labelNode != null && labelNode.getTagName() == "label" ? labelNode : null; contextOpen("statement"); contextOpen("continue"); if (labelNode != null) moveHere(labelNode); super.continue_stmt(label, continueKeyword, eos); contextClose(); } public void stop_stmt(Token label, Token stopKeyword, Token eos, boolean hasStopCode) { if (hasStopCode) { Element value = contextNode(-1); contextOpen("stop"); moveHere(value); Attr stopCode = getAttribute("digitString", value); setAttribute("code", stopCode.getValue()); } else { contextOpen("stop"); setAttribute("code", ""); } if (verbosity >= 60) super.stop_stmt(label, stopKeyword, eos, hasStopCode); contextClose(); } public void open_stmt(Token label, Token openKeyword, Token eos) { Element args = contextNode(-1); contextOpen("open"); moveHere(args); super.open_stmt(label, openKeyword, eos); contextClose(); } public void connect_spec(Token id) { contextCloseAllInner("keyword-argument"); setAttribute("argument-name", id); contextClose(); if (verbosity >= 100) super.connect_spec(id); contextOpen("keyword-argument"); } public void connect_spec_list__begin() { super.connect_spec_list__begin(); contextOpen("keyword-argument"); } public void connect_spec_list(int count) { contextClose("keyword-argument"); super.connect_spec_list(count); } public void close_stmt(Token label, Token closeKeyword, Token eos) { Element args = contextNode(-1); contextOpen("close"); moveHere(args); super.close_stmt(label, closeKeyword, eos); contextClose(); } public void close_spec(Token closeSpec) { contextCloseAllInner("keyword-argument"); setAttribute("argument-name", closeSpec); contextClose(); if (verbosity >= 100) super.close_spec(closeSpec); contextOpen("keyword-argument"); } public void close_spec_list__begin() { super.close_spec_list__begin(); contextOpen("keyword-argument"); } public void close_spec_list(int count) { contextClose("keyword-argument"); super.close_spec_list(count); } public void read_stmt(Token label, Token readKeyword, Token eos, boolean hasInputItemList) { Element outerContext = context; contextOpen("read"); if (hasInputItemList) moveHere(contextNode(outerContext, -3)); moveHere(contextNode(outerContext, -2)); super.read_stmt(label, readKeyword, eos, hasInputItemList); contextClose(); } public void write_stmt(Token label, Token writeKeyword, Token eos, boolean hasOutputItemList) { Element args = contextNode(-1); Element outputs = null; if (hasOutputItemList) { outputs = args; args = contextNode(-2); } contextOpen("write"); moveHere(args); if (hasOutputItemList) moveHere(outputs); super.write_stmt(label, writeKeyword, eos, hasOutputItemList); contextClose(); } public void print_stmt(Token label, Token printKeyword, Token eos, boolean hasOutputItemList) { Element outputs = hasOutputItemList ? contextNode(-1) : null; Element format = contextNode(hasOutputItemList ? -2 : -1); contextOpen("print"); moveHere(format); if (hasOutputItemList) moveHere(outputs); super.print_stmt(label, printKeyword, eos, hasOutputItemList); contextClose(); } public void io_control_spec(boolean hasExpression, Token keyword, boolean hasAsterisk) { if (hasExpression) { Element element = contextNode(-1); contextOpen("io-control"); moveHere(element); } else contextOpen("io-control"); setAttribute("argument-name", keyword == null ? "" : keyword); super.io_control_spec(hasExpression, keyword, hasAsterisk); contextClose("io-control"); } public void format() { Element label = null; if (contextNodesCount() > 0) { Element node = contextNode(-1); if (node.getNodeName().equals("literal")) label = node; } contextOpen("print-format"); setAttribute("type", label == null ? "*" : "label"); if (label != null) moveHere(label); if (verbosity >= 100) super.format(); contextClose(); } public void input_item() { Element element = contextNode(-1); contextOpen("input"); moveHere(element); if (verbosity >= 100) super.input_item(); contextClose("input"); } public void output_item() { Element element = contextNode(-1); contextOpen("output"); moveHere(element); if (verbosity >= 100) super.output_item(); contextClose(); } public void io_implied_do() { ArrayList<Element> elements = contextNodes(); Element header = contextNode(-1); contextOpen("loop"); setAttribute("type", "implied-do"); contextOpen("body"); for (Element node : elements) if (node.getTagName().equals("expression")) moveHere(node); contextClose(); moveHere(header); super.io_implied_do(); contextClose(); } public void io_implied_do_object() { context = contextNode(-1); contextRename("expression"); if (verbosity >= 100) super.io_implied_do_object(); contextClose(); } public void io_implied_do_control(boolean hasStride) { genericLoopControl(hasStride); Element element = contextNode(-1); contextOpen("header"); moveHere(element); super.io_implied_do_control(hasStride); contextClose(); } public void format_stmt(Token label, Token formatKeyword, Token eos) { Element labelNode = (label != null) ? contextNode(-2) : null; context = contextNode(-1); if (label != null) moveHere(0, labelNode); if (verbosity >= 60) super.format_stmt(label, formatKeyword, eos); contextClose(); if (context.getTagName().equals("declaration")) setAttribute("type", "format"); } public void format_specification(boolean hasFormatItemList) { Element items = hasFormatItemList ? contextNode(-1) : null; contextOpen("format"); if (hasFormatItemList) moveHere(items); if (verbosity >= 60) super.format_specification(hasFormatItemList); contextClose(); } public void main_program__begin() { contextOpen("program"); if (verbosity >= 100) super.main_program__begin(); contextOpen("header"); } public void ext_function_subprogram(boolean hasPrefix) { context = contextNode(-1); // temporarily reopen previously-closed context if (verbosity >= 100) super.ext_function_subprogram(hasPrefix); contextClose(); // re-close previously closed context } public void main_program(boolean hasProgramStmt, boolean hasExecutionPart, boolean hasInternalSubprogramPart) { super.main_program(hasProgramStmt, hasExecutionPart, hasInternalSubprogramPart); contextClose("program"); } public void program_stmt(Token label, Token programKeyword, Token id, Token eos) { contextClose("header"); if (verbosity >= 20) super.program_stmt(label, programKeyword, id, eos); setAttribute("name", id); contextOpen("body"); contextOpen("specification"); contextOpen("declaration"); } public void end_program_stmt(Token label, Token endKeyword, Token programKeyword, Token id, Token eos) { if (contextTryFind("program") == null) { // TODO: this workaround should not be needed ArrayList<Element> nodes = contextNodes(); contextOpen("program"); moveHere(nodes); } contextCloseAllInner("program"); super.end_program_stmt(label, endKeyword, programKeyword, id, eos); } public void module() { contextCloseAllInner("module"); if (verbosity >= 100) super.module(); contextClose(); } public void module_stmt__begin() { contextOpen("module"); if (verbosity >= 100) super.module_stmt__begin(); contextOpen("header"); } public void module_stmt(Token label, Token moduleKeyword, Token id, Token eos) { contextClose("header"); setAttribute("name", id); super.module_stmt(label, moduleKeyword, id, eos); contextOpen("body"); contextOpen("specification"); contextOpen("declaration"); } public void end_module_stmt(Token label, Token endKeyword, Token moduleKeyword, Token id, Token eos) { if (!context.getTagName().equals("members")) { ArrayList<String> hierarchy = contextNameHierarchy(); String[] expected = { "body", "module" }; if (hierarchy.size() >= 2 && (Arrays.equals(hierarchy.subList(0, 2).toArray(), expected) || (hierarchy.size() >= 3 && Arrays.equals(hierarchy.subList(1, 3).toArray(), expected)))) { contextClose("body"); contextOpen("members"); } /* else System.err.println("Context hierarchy for 'end module' statement: " + hierarchy); */ } contextClose("members"); super.end_module_stmt(label, endKeyword, moduleKeyword, id, eos); } public void module_subprogram(boolean hasPrefix) { super.module_subprogram(hasPrefix); } public void use_stmt(Token label, Token useKeyword, Token id, Token onlyKeyword, Token eos, boolean hasModuleNature, boolean hasRenameList, boolean hasOnly) { if (context.getTagName().equals("declaration")) { LOG.log(Level.FINE, "closing unclosed declaration at use_stmt id={0}", id.getText()); contextClose("declaration"); } if (!context.getTagName().equals("use")) contextOpen("use"); setAttribute("name", id); super.use_stmt(label, useKeyword, id, onlyKeyword, eos, hasModuleNature, hasRenameList, hasOnly); contextClose("use"); contextOpen("declaration"); } public void module_nature(Token nature) { if (context.getTagName().equals("declaration")) { LOG.log(Level.FINE, "closing unclosed declaration at module_nature nature={0}", nature.getText()); contextClose("declaration"); } if (!context.getTagName().equals("use")) contextOpen("use"); contextOpen("nature"); setAttribute("name", nature); if (verbosity >= 80) super.module_nature(nature); contextClose("nature"); } public void rename_list__begin() { if (context.getTagName().equals("declaration")) { LOG.log(Level.FINE, "closing unclosed declaration at rename_list__begin"); contextClose("declaration"); } if (!context.getTagName().equals("use")) contextOpen("use"); super.rename_list__begin(); } public void only_list__begin() { if (context.getTagName().equals("declaration")) { LOG.log(Level.FINE, "closing unclosed declaration at only_list__begin"); contextClose("declaration"); } if (!context.getTagName().equals("use")) contextOpen("use"); super.only_list__begin(); } public void block_data() { if (verbosity >= 100) super.block_data(); contextClose("block-data"); } public void block_data_stmt__begin() { contextOpen("block-data"); if (verbosity >= 100) super.block_data_stmt__begin(); contextOpen("specification"); contextOpen("declaration"); } public void interface_block() { // TODO Auto-generated method stub super.interface_block(); } public void interface_specification() { // TODO Auto-generated method stub super.interface_specification(); } public void interface_stmt__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); contextOpen("interface"); if (verbosity >= 100) super.interface_stmt__begin(); contextOpen("header"); } public void interface_stmt(Token label, Token abstractToken, Token keyword, Token eos, boolean hasGenericSpec) { if (contextTryFind("declaration") == null) // interface_stmt__begin is not always emitted contextOpen("declaration"); if (contextTryFind("interface") == null) { contextOpen("interface"); contextOpen("header"); } contextClose("header"); super.interface_stmt(label, abstractToken, keyword, eos, hasGenericSpec); if (abstractToken != null) setAttribute("type", abstractToken); contextOpen("body"); contextOpen("specification"); contextOpen("declaration"); } public void end_interface_stmt(Token label, Token kw1, Token kw2, Token eos, boolean hasGenericSpec) { contextCloseAllInner("interface"); super.end_interface_stmt(label, kw1, kw2, eos, hasGenericSpec); contextClose(); if (!context.getTagName().equals("declaration")) cleanUpAfterError("expected interface to be within declaration context, but its in " + context.getTagName()); setAttribute("type", "interface"); } public void interface_body(boolean hasPrefix) { // TODO Auto-generated method stub super.interface_body(hasPrefix); } public void generic_spec(Token keyword, Token name, int type) { contextOpen("name"); setAttribute("id", name); super.generic_spec(keyword, name, type); contextClose(); } public void import_stmt(Token label, Token importKeyword, Token eos, boolean hasGenericNameList) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "import"); super.import_stmt(label, importKeyword, eos, hasGenericNameList); contextClose("declaration"); } public void external_stmt(Token label, Token externalKeyword, Token eos) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); if (verbosity >= 80) super.external_stmt(label, externalKeyword, eos); setAttribute("type", "external"); } public void procedure_declaration_stmt(Token label, Token procedureKeyword, Token eos, boolean hasProcInterface, int count) { // TODO Auto-generated method stub super.procedure_declaration_stmt(label, procedureKeyword, eos, hasProcInterface, count); } public void proc_decl(Token id, boolean hasNullInit) { contextOpen("procedure"); setAttribute("name", id); if (verbosity >= 80) super.proc_decl(id, hasNullInit); contextClose(); } public void proc_decl_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "procedures"); super.proc_decl_list__begin(); } public void intrinsic_stmt(Token label, Token intrinsicKeyword, Token eos) { Element condition = contextNode(-1); if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "intrinsic"); moveHere(condition); super.intrinsic_stmt(label, intrinsicKeyword, eos); } public void call_stmt(Token label, Token callKeyword, Token eos, boolean hasActualArgSpecList) { Element name = contextNode(-1); Element arguments = null; if (name.getTagName() == "arguments") { arguments = name; name = contextNode(-2); } else if (name.getTagName() != "name") cleanUpAfterError("tag name is not 'name' but '" + name.getTagName() + "'"); contextOpen("call"); moveHere(name); if (arguments != null) moveHere(arguments); super.call_stmt(label, callKeyword, eos, hasActualArgSpecList); contextClose(); } public void procedure_designator() { if (verbosity >= 100) super.procedure_designator(); setAttribute("type", "procedure"); contextClose("name"); } public void actual_arg_spec(Token keyword) { boolean inArgumentContext = contextTryFind("argument") != null; if (!inArgumentContext) contextOpen("argument"); setAttribute("name", keyword); if (verbosity >= 100) super.actual_arg_spec(keyword); if (inArgumentContext) contextClose("argument"); } public void actual_arg_spec_list__begin() { super.actual_arg_spec_list__begin(); contextOpen("argument"); } public void actual_arg_spec_list(int count) { contextClose("argument"); super.actual_arg_spec_list(count); } public void actual_arg(boolean hasExpr, Token label) { boolean inArgumentContext = contextTryFind("argument") != null; if (!inArgumentContext) { if (hasExpr) { Element element = contextNode(-1); contextOpen("argument"); moveHere(element); } else contextOpen("argument"); } if (verbosity >= 60) super.actual_arg(hasExpr, label); if (inArgumentContext) contextClose("argument"); } public void function_subprogram(boolean hasExePart, boolean hasIntSubProg) { super.function_subprogram(hasExePart, hasIntSubProg); if (context.getTagName().equals("function")) contextClose("function"); } public void function_stmt__begin() { contextOpen("function"); contextOpen("header"); if (verbosity >= 100) super.function_stmt__begin(); } public void function_stmt(Token label, Token keyword, Token name, Token eos, boolean hasGenericNameList, boolean hasSuffix) { contextClose("header"); super.function_stmt(label, keyword, name, eos, hasGenericNameList, hasSuffix); setAttribute("name", name); contextOpen("body"); contextOpen("specification"); contextOpen("declaration"); } public void prefix_spec(boolean isDecTypeSpec) { super.prefix_spec(isDecTypeSpec); if (isDecTypeSpec) contextClose("declaration"); } public void end_function_stmt(Token label, Token keyword1, Token keyword2, Token name, Token eos) { contextCloseAllInner("function"); super.end_function_stmt(label, keyword1, keyword2, name, eos); } public void subroutine_stmt__begin() { contextOpen("subroutine"); contextOpen("header"); if (verbosity >= 100) super.subroutine_stmt__begin(); } public void subroutine_stmt(Token label, Token keyword, Token name, Token eos, boolean hasPrefix, boolean hasDummyArgList, boolean hasBindingSpec, boolean hasArgSpecifier) { super.subroutine_stmt(label, keyword, name, eos, hasPrefix, hasDummyArgList, hasBindingSpec, hasArgSpecifier); contextClose("header"); setAttribute("name", name); contextOpen("body"); contextOpen("specification"); contextOpen("declaration"); } public void dummy_arg(Token dummy) { contextOpen("argument"); setAttribute("name", dummy); if (verbosity >= 100) super.dummy_arg(dummy); contextClose(); } public void end_subroutine_stmt(Token label, Token keyword1, Token keyword2, Token name, Token eos) { contextCloseAllInner("subroutine"); super.end_subroutine_stmt(label, keyword1, keyword2, name, eos); contextClose(); } public void return_stmt(Token label, Token keyword, Token eos, boolean hasScalarIntExpr) { if (hasScalarIntExpr) { Element element = contextNode(-1); contextOpen("return"); contextOpen("value"); moveHere(element); contextClose(); } else contextOpen("return"); setAttribute("hasValue", hasScalarIntExpr); super.return_stmt(label, keyword, eos, hasScalarIntExpr); contextClose(); } public void contains_stmt(Token label, Token keyword, Token eos) { ArrayList<String> hierarchy = contextNameHierarchy(); boolean acceptedContext = false; if (hierarchy.size() >= 3) { Object[] hierarchyArray = hierarchy.subList(0, 3).toArray(); for (String enclosingGroup : new String[] { "subroutine", "program", "module" }) { acceptedContext = Arrays.equals(hierarchyArray, new String[] { "statement", "body", enclosingGroup }); if (acceptedContext) break; } } /* if (!acceptedContext) cleanUpAfterError("Context hierarchy for 'contains' statement is invalid: " + hierarchy); */ if (acceptedContext) contextClose("body"); super.contains_stmt(label, keyword, eos); if (acceptedContext) contextOpen("members"); } public void separate_module_subprogram(boolean hasExecutionPart, boolean hasInternalSubprogramPart) { super.separate_module_subprogram(hasExecutionPart, hasInternalSubprogramPart); contextClose("subroutine"); } public void separate_module_subprogram__begin() { contextOpen("subroutine"); super.separate_module_subprogram__begin(); contextOpen("header"); } public void mp_subprogram_stmt(Token label, Token moduleKeyword, Token procedureKeyword, Token name, Token eos) { contextClose("header"); setAttribute("name", name); super.mp_subprogram_stmt(label, moduleKeyword, procedureKeyword, name, eos); contextOpen("body"); } public void end_mp_subprogram_stmt(Token label, Token keyword1, Token keyword2, Token name, Token eos) { contextCloseAllInner("subroutine"); super.end_mp_subprogram_stmt(label, keyword1, keyword2, name, eos); } public void start_of_file(String filename, String path) { if (contextTryFind("file") != null) { if (context.getTagName().equals("declaration")) { LOG.log(Level.FINER, "closing unclosed declaration at start_of_file"); contextClose("declaration"); } contextOpen("declaration"); setAttribute("type", "include"); } contextOpen("file"); if (verbosity >= 100) super.start_of_file(filename, path); if (path.equals("ERROR_FILE_NOT_FOUND")) setAttribute("path", filename); else setAttribute("path", path); } public void end_of_file(String filename, String path) { contextCloseAllInner("file"); if (verbosity >= 100) super.end_of_file(filename, path); contextClose(); } public void next_token(Token tk) { System.err.println("next_token"); System.err.println(tk); } }
src/fortran/ofp/XMLPrinter.java
package fortran.ofp; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import org.antlr.runtime.Token; import org.w3c.dom.Attr; import org.w3c.dom.Element; import fortran.ofp.parser.java.IActionEnums; import fortran.ofp.parser.java.IFortranParser; /** * XML output generator for Open Fortran Parser. * * @author Mateusz Bysiek https://mbdevpl.github.io/ */ public class XMLPrinter extends XMLPrinterBase { private static final Logger LOG = Logger.getLogger(XMLPrinter.class.getName()); public XMLPrinter(String[] args, IFortranParser parser, String filename) { super(args, parser, filename); } protected void genericOperationForceOpen(int nodesCount) { ArrayList<Element> nodes = contextNodes(-nodesCount, nodesCount); contextOpen("operation"); if (nodesCount == 2) setAttribute("type", "unary"); else if (nodesCount > 2) setAttribute("type", "multiary"); else cleanUpAfterError("didn't expect nodesCount=" + nodesCount); for (Element node : nodes) { boolean needsTransform = !node.getTagName().equals("operand") && !node.getTagName().equals("operator"); if (needsTransform) contextOpen("operand"); moveHere(node); if (needsTransform) contextClose(); } } protected void genericOperationOpen(int numberOfOperators) { if (numberOfOperators > 0) { int nodesCount = 2 * numberOfOperators + 1; genericOperationForceOpen(nodesCount); } } protected void genericOperationClose(int numberOfOperators) { if (numberOfOperators > 0) contextClose(); } protected void genericLoopControl(boolean hasStep) { String[] contexts = { "lower-bound", "upper-bound", "step" }; int takenNodesCount = hasStep ? 3 : 2; ArrayList<Element> takenNodes = contextNodes(-takenNodesCount, takenNodesCount); context = contextNode(-takenNodesCount - 1); for (int i = 0; i < takenNodes.size(); ++i) { contextOpen(contexts[i]); moveHere(takenNodes.get(i)); contextClose(); } contextClose(); } public void generic_name_list_part(Token id) { contextOpen("name"); setAttribute("id", id); if (verbosity >= 100) super.generic_name_list_part(id); contextClose(); } public void generic_name_list__begin() { if (context.getTagName().equals("specification") || context.getTagName().equals("file")) contextOpen("declaration"); super.generic_name_list__begin(); } public void specification_part(int numUseStmts, int numImportStmts, int numImplStmts, int numDeclConstructs) { if (context.getTagName().equals("header")) { contextClose("header"); contextOpen("body"); } if (context.getTagName().equals("declaration")) { LOG.log(Level.FINER, "closing unclosed declaration at specification_part"); contextClose("declaration"); } if (!context.getTagName().equals("specification")) contextOpen("specification"); contextCloseAllInner("specification"); if (verbosity >= 80) super.specification_part(numUseStmts, numImportStmts, numImplStmts, numDeclConstructs); setAttribute("uses", numUseStmts); setAttribute("imports", numImportStmts); setAttribute("implicits", numImplStmts); setAttribute("declarations", numDeclConstructs); contextClose(); contextOpen("statement"); } public void declaration_construct() { contextClose("declaration"); if (verbosity >= 100) super.declaration_construct(); contextOpen("declaration"); } public void execution_part_construct() { if (verbosity >= 100) super.execution_part_construct(); } public void specification_stmt() { if (verbosity >= 100) super.specification_stmt(); } public void executable_construct() { if (verbosity >= 100) super.executable_construct(); } public void action_stmt() { if (contextTryFind("statement") == null) { // TODO this ugly workaround should be removed contextClose(); Element element = contextNode(-1); contextOpen("statement"); moveHere(element); } if (verbosity >= 100) super.action_stmt(); contextClose("statement"); contextOpen("statement"); } public void keyword() { if (verbosity >= 100) super.keyword(); } public void name(Token id) { super.name(id); } public void constant(Token id) { super.constant(id); } public void scalar_constant() { if (verbosity >= 100) super.scalar_constant(); } public void literal_constant() { if (verbosity >= 100) super.literal_constant(); contextClose("literal"); } public void label(Token lbl) { boolean closedLoop = false; Element outerContext = context; while (outerContext != root) { if (outerContext.getTagName().equals("loop") && outerContext.getAttribute("label").equals(lbl.getText())) { context = outerContext; closedLoop = true; break; } outerContext = (Element) outerContext.getParentNode(); } super.label(lbl); if (closedLoop) contextOpen("statement"); } public void type_param_value(boolean hasExpr, boolean hasAsterisk, boolean hasColon) { Element value = hasExpr ? contextNode(-1): null; contextOpen("type-attribute"); if (hasExpr) moveHere(value); super.type_param_value(hasExpr, hasAsterisk, hasColon); contextClose(); } public void intrinsic_type_spec(Token keyword1, Token keyword2, int type, boolean hasKindSelector) { if (!context.getTagName().equals("declaration")) { // TODO: ensure being in body contextOpen("declaration"); } setAttribute("type", "variable"); super.intrinsic_type_spec(keyword1, keyword2, type, hasKindSelector); } public void kind_selector(Token token1, Token token2, boolean hasExpression) { if (hasExpression) { Element value = contextNode(-1); contextOpen("kind"); moveHere(value); } else { contextOpen("kind"); setAttribute("value", token2); } super.kind_selector(token1, token2, hasExpression); contextClose(); } public void int_literal_constant(Token digitString, Token kindParam) { if (kindParam != null) { Element kind = contextNode(-1); assert kind.getTagName().equals("kind-param"); contextOpen("literal"); moveHere(kind); } else { contextOpen("literal"); } setAttribute("type", "int"); setAttribute("value", digitString); super.int_literal_constant(digitString, kindParam); } public void boz_literal_constant(Token constant) { contextOpen("literal"); setAttribute("type", "int"); setAttribute("value", constant); super.boz_literal_constant(constant); } public void real_literal_constant(Token realConstant, Token kindParam) { if (kindParam != null) { Element kind = contextNode(-1); assert kind.getTagName().equals("kind-param"); contextOpen("literal"); moveHere(kind); } else { contextOpen("literal"); } setAttribute("type", "real"); setAttribute("value", realConstant); super.real_literal_constant(realConstant, kindParam); } public void char_selector(Token tk1, Token tk2, int kindOrLen1, int kindOrLen2, boolean hasAsterisk) { int[] attribute_types = new int[]{kindOrLen2, kindOrLen1}; contextOpen("type-attributes"); Element localContext = context; contextClose(); Element value = null; for(int attribute_type: attribute_types) { switch (attribute_type) { case IActionEnums.KindLenParam_none: break; case IActionEnums.KindLenParam_len: value = contextNode(-2); moveTo(localContext, value); contextRename(value, "type-attribute", "length"); break; case IActionEnums.KindLenParam_kind: value = contextNode(-2); Element prevContext = context; context = localContext; contextOpen("kind"); moveHere(value); contextClose(); context = prevContext; break; default: throw new IllegalArgumentException(Integer.toString(attribute_type)); } } context = localContext; if (value == null) { contextClose(); context.removeChild(localContext); } super.char_selector(tk1, tk2, kindOrLen1, kindOrLen2, hasAsterisk); if (value != null) contextClose(); } public void char_length(boolean hasTypeParamValue) { Element value = contextNode(-1); contextOpen("length"); moveHere(value); if (hasTypeParamValue) { moveHere(contextNodes(value)); context.removeChild(value); } super.char_length(hasTypeParamValue); contextClose(); } public void scalar_int_literal_constant() { if (verbosity >= 100) super.scalar_int_literal_constant(); contextClose("literal"); } public void char_literal_constant(Token digitString, Token id, Token str) { contextOpen("literal"); setAttribute("type", "char"); setAttribute("value", str); super.char_literal_constant(digitString, id, str); } public void logical_literal_constant(Token logicalValue, boolean isTrue, Token kindParam) { if (kindParam != null) { Element kind = contextNode(-1); assert kind.getTagName().equals("kind-param"); contextOpen("literal"); moveHere(kind); } else { contextOpen("literal"); } setAttribute("type", "bool"); setAttribute("value", isTrue); super.logical_literal_constant(logicalValue, isTrue, kindParam); } public void derived_type_stmt(Token label, Token keyword, Token id, Token eos, boolean hasTypeAttrSpecList, boolean hasGenericNameList) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "type"); super.derived_type_stmt(label, keyword, id, eos, hasTypeAttrSpecList, hasGenericNameList); } public void derived_type_spec(Token typeName, boolean hasTypeParamSpecList) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "variable"); super.derived_type_spec(typeName, hasTypeParamSpecList); } public void array_constructor() { context = contextNode(-1); // temporarily reopen previously-closed context if (verbosity >= 100) super.array_constructor(); contextClose(); // re-close previously closed context } public void ac_spec() { context = contextNode(-1); // temporarily reopen previously-closed context if (verbosity >= 100) super.ac_spec(); contextClose(); // re-close previously closed context } public void ac_value() { contextClose("value"); if (verbosity >= 100) super.ac_value(); contextOpen("value"); } public void ac_value_list__begin() { contextOpen("array-constructor-values"); if (verbosity >= 100) super.ac_value_list__begin(); contextOpen("value"); } public void ac_value_list(int count) { contextClose("value"); contextCloseAllInner("array-constructor-values", "array-constructor"); setAttribute("count", count); if (verbosity >= 100) super.ac_value_list(count); contextClose(); } public void ac_implied_do() { super.ac_implied_do(); contextRename("array-constructor-values", "array-constructor"); contextOpen("value"); } public void ac_implied_do_control(boolean hasStride) { genericLoopControl(hasStride); Element element = contextNode(-1); contextClose("value"); contextOpen("header"); moveHere(element); // contextClose("index-variable"); super.ac_implied_do_control(hasStride); contextClose(); } public void type_declaration_stmt(Token label, int numAttributes, Token eos) { super.type_declaration_stmt(label, numAttributes, eos); } public void declaration_type_spec(Token udtKeyword, int type) { ArrayList<Element> typeDeclarations = contextNodes(); contextOpen("type"); setAttribute("hasLength", false); setAttribute("hasKind", false); setAttribute("hasAttributes", false); Attr n; for (Element declaration : typeDeclarations) { switch (declaration.getTagName()) { case "intrinsic-type-spec": n = getAttribute("name"); if (n != null) new IllegalArgumentException(declaration.getTagName()); setAttribute("name", declaration.getAttribute("keyword1")); setAttribute("type", "intrinsic"); break; case "derived-type-spec": n = getAttribute("name"); if (n != null) new IllegalArgumentException(declaration.getTagName()); setAttribute("name", declaration.getAttribute("typeName")); setAttribute("type", "derived"); break; case "length": setAttribute("hasLength", true); break; case "kind": setAttribute("hasKind", true); break; case "type-attributes": setAttribute("hasAttributes", true); break; default: break; } moveHere(declaration); } super.declaration_type_spec(udtKeyword, type); contextClose(); } public void attr_spec(Token attrKeyword, int attr) { String nestIn = ""; switch (attr) { case IActionEnums.AttrSpec_access: // private break; case IActionEnums.AttrSpec_language_binding: // bind break; case IActionEnums.AttrSpec_ALLOCATABLE: nestIn = "allocatable"; break; case IActionEnums.AttrSpec_ASYNCHRONOUS: nestIn = "asynchronous"; break; case IActionEnums.AttrSpec_CODIMENSION: nestIn = "codimension"; break; case IActionEnums.AttrSpec_DIMENSION: // dimension break; case IActionEnums.AttrSpec_EXTERNAL: nestIn = "external"; break; case IActionEnums.AttrSpec_INTENT: // intent break; case IActionEnums.AttrSpec_INTRINSIC: nestIn = "intrinsic"; break; case IActionEnums.AttrSpec_OPTIONAL: nestIn = "optional"; break; case IActionEnums.AttrSpec_PARAMETER: nestIn = "parameter"; break; case IActionEnums.AttrSpec_POINTER: nestIn = "pointer"; break; case IActionEnums.AttrSpec_PROTECTED: nestIn = "protected"; break; case IActionEnums.AttrSpec_SAVE: nestIn = "save"; break; case IActionEnums.AttrSpec_TARGET: nestIn = "target"; break; case IActionEnums.AttrSpec_VALUE: nestIn = "value"; break; case IActionEnums.AttrSpec_VOLATILE: nestIn = "volatile"; break; default: throw new IllegalArgumentException(Integer.toString(attr) + " - " + attrKeyword); } if (nestIn.length() > 0) contextOpen("attribute-" + nestIn); super.attr_spec(attrKeyword, attr); if (nestIn.length() > 0) contextClose(); } public void entity_decl(Token id, boolean hasArraySpec, boolean hasCoarraySpec, boolean hasCharLength, boolean hasInitialization) { contextCloseAllInner("variable"); super.entity_decl(id, hasArraySpec, hasCoarraySpec, hasCharLength, hasInitialization); setAttribute("name", id); setAttribute("hasInitialValue", hasInitialization); contextClose(); contextOpen("variable"); } public void entity_decl_list__begin() { super.entity_decl_list__begin(); contextOpen("variable"); } public void entity_decl_list(int count) { contextClose("variable"); super.entity_decl_list(count); } public void initialization(boolean hasExpr, boolean hasNullInit) { Element initialValue = contextNode(-1); contextOpen("initial-value"); moveHere(initialValue); super.initialization(hasExpr, hasNullInit); contextClose(); } public void access_spec(Token keyword, int type) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); super.access_spec(keyword, type); } public void language_binding_spec(Token keyword, Token id, boolean hasName) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); super.language_binding_spec(keyword, id, hasName); } public void array_spec(int count) { contextCloseAllInner("dimensions"); if (verbosity >= 100) super.array_spec(count); setAttribute("count", count); contextClose(); } public void array_spec_element(int type) { Element value = null; Element value2 = null; switch (type) { case IActionEnums.ArraySpecElement_expr_colon_expr: value2 = contextNode(-2); case IActionEnums.ArraySpecElement_expr: case IActionEnums.ArraySpecElement_expr_colon: case IActionEnums.ArraySpecElement_expr_colon_asterisk: value = contextNode(-1); break; case IActionEnums.ArraySpecElement_asterisk: case IActionEnums.ArraySpecElement_colon: break; default: throw new IllegalArgumentException(Integer.toString(type)); } if (!context.getTagName().equals("dimensions")) contextOpen("dimensions"); contextOpen("dimension"); switch (type) { case IActionEnums.ArraySpecElement_expr: setAttribute("type", "simple"); // (a) moveHere(value); break; case IActionEnums.ArraySpecElement_expr_colon: setAttribute("type", "upper-bound-assumed-shape"); // (a:) moveHere(value); break; case IActionEnums.ArraySpecElement_expr_colon_expr: setAttribute("type", "range"); // (a:b) contextOpen("range"); contextOpen("lower-bound"); moveHere(value2); contextClose(); contextOpen("upper-bound"); moveHere(value); contextClose(); contextClose(); break; case IActionEnums.ArraySpecElement_expr_colon_asterisk: setAttribute("type", "upper-bound-assumed-size"); // (a:*) moveHere(value); break; case IActionEnums.ArraySpecElement_asterisk: setAttribute("type", "assumed-size"); // (*) break; case IActionEnums.ArraySpecElement_colon: setAttribute("type", "assumed-shape"); // (:) break; default: throw new IllegalArgumentException(Integer.toString(type)); } super.array_spec_element(type); contextClose(); } public void intent_spec(Token intentKeyword1, Token intentKeyword2, int intent) { contextOpen("intent"); switch (intent) { case IActionEnums.IntentSpec_IN: setAttribute("type", "in"); break; case IActionEnums.IntentSpec_OUT: setAttribute("type", "out"); break; case IActionEnums.IntentSpec_INOUT: setAttribute("type", "inout"); break; default: throw new IllegalArgumentException(Integer.toString(intent)); } if (verbosity >= 100) super.intent_spec(intentKeyword1, intentKeyword2, intent); contextClose(); } public void access_id_list__begin() { // contextOpen("access-list"); if (verbosity >= 100) super.access_id_list__begin(); } public void access_id_list(int count) { super.access_id_list(count); // contextClose("access-list"); } public void allocatable_decl_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "allocatables"); super.allocatable_decl_list__begin(); } public void asynchronous_stmt(Token label, Token keyword, Token eos) { if (!context.getTagName().equals("declaration")) { Element value = contextNode(-1); if (value.getTagName() != "names") cleanUpAfterError("tag name is not 'names' but '" + value.getTagName() + "'"); contextOpen("declaration"); moveHere(value); } super.asynchronous_stmt(label, keyword, eos); } public void codimension_decl_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "codimensions"); super.codimension_decl_list__begin(); } public void data_stmt_object() { if (verbosity >= 100) super.data_stmt_object(); } public void data_stmt_object_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "data"); super.data_stmt_object_list__begin(); } public void data_stmt_value(Token asterisk) { contextCloseAllInner("values"); if (verbosity >= 100) super.data_stmt_value(asterisk); } public void hollerith_literal_constant(Token hollerithConstant) { contextOpen("literal"); setAttribute("type", "hollerith"); setAttribute("value", hollerithConstant); super.hollerith_literal_constant(hollerithConstant); } public void dimension_stmt(Token label, Token keyword, Token eos, int count) { contextCloseAllInner("variables"); setAttribute("count", count); super.dimension_stmt(label, keyword, eos, count); contextClose(); setAttribute("type", "variable-dimensions"); } public void dimension_decl(Token id) { Element value = contextNode(-1); if (!context.getTagName().equals("variables")) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); contextOpen("variables"); } contextOpen("variable"); setAttribute("name", id); moveHere(value); /* if (contextTryFind("declaration") == null) { contextOpen("declaration"); setAttribute("type", "dimension"); } */ super.dimension_decl(id); contextClose("variable"); } public void named_constant_def_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "parameter"); super.named_constant_def_list__begin(); } public void named_constant_def(Token id) { Element value = contextNode(-1); contextOpen("constant"); setAttribute("name", id); moveHere(value); if (verbosity >= 100) super.named_constant_def(id); contextClose(); } public void pointer_stmt(Token label, Token keyword, Token eos) { super.pointer_stmt(label, keyword, eos); if (!context.getTagName().equals("declaration")) LOG.warning("pointer_stmt in unexpected context"); setAttribute("type", "pointer"); } public void pointer_decl_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); super.pointer_decl_list__begin(); } public void pointer_decl(Token id, boolean hasSpecList) { contextOpen("name"); super.pointer_decl(id, hasSpecList); setAttribute("id", id); contextClose("name"); } public void save_stmt(Token label, Token keyword, Token eos, boolean hasSavedEntityList) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "save"); super.save_stmt(label, keyword, eos, hasSavedEntityList); } public void saved_entity(Token id, boolean isCommonBlockName) { contextOpen("name"); super.saved_entity(id, isCommonBlockName); setAttribute("id", id); contextClose(); } public void target_decl_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "targets"); if (verbosity >= 100) super.target_decl_list__begin(); } public void target_decl_list(int count) { // TODO Auto-generated method stub super.target_decl_list(count); } public void value_stmt(Token label, Token keyword, Token eos) { // TODO: get also label node if there is one Element value = contextNode(-1); if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "value"); moveHere(value); super.value_stmt(label, keyword, eos); } public void volatile_stmt(Token label, Token keyword, Token eos) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "volatile"); super.volatile_stmt(label, keyword, eos); } public void implicit_stmt(Token label, Token implicitKeyword, Token noneKeyword, Token eos, boolean hasImplicitSpecList) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); if (verbosity >= 20) super.implicit_stmt(label, implicitKeyword, noneKeyword, eos, hasImplicitSpecList); setAttribute("type", "implicit"); setAttribute("subtype", noneKeyword == null ? "some" : "none"); contextClose("declaration"); contextOpen("declaration"); } public void letter_spec(Token id1, Token id2) { contextOpen("letter-range"); setAttribute("begin", id1); setAttribute("end", id2); if (verbosity >= 100) super.letter_spec(id1, id2); contextClose(); } public void namelist_stmt(Token label, Token keyword, Token eos, int count) { contextCloseAllInner("namelists"); super.namelist_stmt(label, keyword, eos, count); setAttribute("count", count); } public void namelist_group_name(Token id) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "namelists"); contextOpen("namelists"); contextOpen("names"); if (verbosity >= 100) super.namelist_group_name(id); setAttribute("id", id); } public void namelist_group_object_list(int count) { contextCloseAllInner("names"); setAttribute("count", count); if (verbosity >= 100) super.namelist_group_object_list(count); contextClose(); } public void equivalence_set_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "equivalence"); super.equivalence_set_list__begin(); contextOpen("equivalent"); } public void equivalence_set_list(int count) { contextClose("equivalent"); super.equivalence_set_list(count); } public void equivalence_object() { contextClose("equivalent"); if (verbosity >= 100) super.equivalence_object(); contextOpen("equivalent"); } public void equivalence_object_list__begin() { // TODO Auto-generated method stub super.equivalence_object_list__begin(); } public void equivalence_object_list(int count) { // TODO Auto-generated method stub super.equivalence_object_list(count); } public void common_block_name(Token id) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "common"); super.common_block_name(id); } public void variable() { if (verbosity >= 100) super.variable(); setAttribute("type", "variable"); contextClose("name"); } public void designator_or_func_ref() { if (verbosity >= 100) super.designator_or_func_ref(); setAttribute("type", "ambiguous"); contextClose("name"); } public void substring_range(boolean hasLowerBound, boolean hasUpperBound) { Element lowerBound = null; Element upperBound = null; if (hasLowerBound) lowerBound = contextNode(-1); if (hasUpperBound) { upperBound = lowerBound; if (hasLowerBound) lowerBound = contextNode(-2); else lowerBound = null; } contextOpen("name"); contextOpen("range"); if (lowerBound != null) { contextOpen("lower-bound"); moveHere(lowerBound); contextClose(); } if (upperBound != null) { contextOpen("upper-bound"); moveHere(upperBound); contextClose(); } if (verbosity >= 100) super.substring_range(hasLowerBound, hasUpperBound); contextClose(); } public void data_ref(int numPartRef) { for (int i = 1; i < numPartRef; ++i) { assert context.getTagName().equals("name"); Element innerName = context; ArrayList<Element> elements = contextNodes(); Attr innerNameId = getAttribute("id"); contextClose(); assert context.getTagName().equals("name"); moveHere(elements); setAttribute("id", getAttribute("id").getValue() + "%" + innerNameId.getValue()); context.removeChild(innerName); } super.data_ref(numPartRef); } public void part_ref(Token id, boolean hasSectionSubscriptList, boolean hasImageSelector) { Element e = null; if (hasSectionSubscriptList) { e = contextNode(-1); if (!e.getTagName().equals("subscripts")) cleanUpAfterError("tag name is not 'subscripts' but '" + e.getTagName() + "'"); } contextOpen("name"); setAttribute("id", id); setAttribute("hasSubscripts", hasSectionSubscriptList); if (hasSectionSubscriptList) moveHere(e); if (verbosity >= 60) super.part_ref(id, hasSectionSubscriptList, hasImageSelector); } public void section_subscript(boolean hasLowerBound, boolean hasUpperBound, boolean hasStride, boolean isAmbiguous) { // contextCloseAllInner("subscript"); Element outerContext = context; contextOpen("subscript"); if (!hasLowerBound && !hasUpperBound && !hasStride) setAttribute("type", "empty"); else if (hasLowerBound && !hasUpperBound && !hasStride) { setAttribute("type", "simple"); moveHere(contextNode(outerContext, -2)); } else { setAttribute("type", "range"); Element lowerBound = null; Element upperBound = null; Element step = null; contextOpen("range"); if (hasLowerBound) { lowerBound = contextOpen("lower-bound"); contextClose(); } if (hasUpperBound) { upperBound = contextOpen("upper-bound"); contextClose(); } if (hasStride) { step = contextOpen("step"); contextClose(); } contextClose(); if (hasStride) moveTo(step, contextNode(outerContext, -2)); if (hasUpperBound) moveTo(upperBound, contextNode(outerContext, -2)); if (hasLowerBound) moveTo(lowerBound, contextNode(outerContext, -2)); } if (verbosity >= 80) super.section_subscript(hasLowerBound, hasUpperBound, hasStride, isAmbiguous); contextClose(); } public void section_subscript_list__begin() { super.section_subscript_list__begin(); // contextOpen("subscript"); } public void section_subscript_list(int count) { // contextClose("subscript"); super.section_subscript_list(count); } public void allocate_stmt(Token label, Token allocateKeyword, Token eos, boolean hasTypeSpec, boolean hasAllocOptList) { /* if (hasAllocOptList) cleanUpAfterError("didn't expect hasAllocOptList=" + hasAllocOptList); */ int movedCount = 1 + (hasAllocOptList ? 1 : 0); ArrayList<Element> elements = contextNodes(-movedCount, movedCount); contextOpen("allocate"); moveHere(elements); super.allocate_stmt(label, allocateKeyword, eos, hasTypeSpec, hasAllocOptList); contextClose(); } public void alloc_opt(Token allocOpt) { contextCloseAllInner("keyword-arguments"); Element element = contextNode(-1); contextOpen("keyword-argument"); setAttribute("name", allocOpt); moveHere(element); if (verbosity >= 100) super.alloc_opt(allocOpt); contextClose(); } public void allocation(boolean hasAllocateShapeSpecList, boolean hasAllocateCoarraySpec) { if (hasAllocateShapeSpecList || hasAllocateCoarraySpec) cleanUpAfterError("didn't expect hasAllocateShapeSpecList=" + hasAllocateShapeSpecList + " hasAllocateCoarraySpec=" + hasAllocateCoarraySpec); Element element = contextNode(-1); if (element.getTagName().equals("expression")) context = element; else { contextOpen("expression"); moveHere(element); } super.allocation(hasAllocateShapeSpecList, hasAllocateCoarraySpec); contextClose(); } public void allocate_object() { setAttribute("type", "variable"); contextClose("name"); Element element = contextNode(-1); contextOpen("expression"); moveHere(element); if (verbosity >= 100) super.allocate_object(); contextClose(); } public void nullify_stmt(Token label, Token nullifyKeyword, Token eos) { ArrayList<Element> elements = contextNodes(); contextOpen("nullify"); moveHere(elements); super.nullify_stmt(label, nullifyKeyword, eos); contextClose(); } public void pointer_object() { contextCloseAllInner("pointers"); Element pointer = contextNode(-1); contextOpen("pointer"); moveHere(pointer); if (verbosity >= 100) super.pointer_object(); contextClose(); } public void deallocate_stmt(Token label, Token deallocateKeyword, Token eos, boolean hasDeallocOptList) { Element element2 = hasDeallocOptList ? contextNode(-2) : null; Element element = contextNode(-1); contextOpen("deallocate"); if (hasDeallocOptList) moveHere(element2); moveHere(element); super.deallocate_stmt(label, deallocateKeyword, eos, hasDeallocOptList); contextClose(); } public void dealloc_opt(Token id) { contextCloseAllInner("keyword-arguments"); Element element = contextNode(-1); contextOpen("keyword-argument"); setAttribute("name", id); moveHere(element); if (verbosity >= 100) super.dealloc_opt(id); contextClose(); } public void primary() { context = contextNode(-1); // temporarily reopen previously-closed context if (verbosity >= 100) super.primary(); contextClose(); // re-close previously closed context } public void parenthesized_expr() { context = contextNode(-1); // temporarily reopen previously-closed context if (verbosity >= 100) super.parenthesized_expr(); contextClose(); // re-close previously closed context } public void power_operand(boolean hasPowerOperand) { /* if (!hasPowerOperand) cleanUpAfterError("didn't expect hasPowerOperand=" + hasPowerOperand); */ int numPowerOp = hasPowerOperand ? 1 : 0; genericOperationOpen(numPowerOp); if (verbosity >= 100) super.power_operand(hasPowerOperand); genericOperationClose(numPowerOp); } public void power_operand__power_op(Token powerOp) { if (verbosity >= 100) super.power_operand__power_op(powerOp); cleanUpAfterError(); } public void mult_operand(int numMultOps) { genericOperationOpen(numMultOps); if (verbosity >= 100) super.mult_operand(numMultOps); genericOperationClose(numMultOps); } public void mult_operand__mult_op(Token multOp) { Element element = contextNode(-1); contextOpen("operand"); moveHere(element); if (verbosity >= 100) super.mult_operand__mult_op(multOp); contextClose(); } public void signed_operand(Token addOp) { if (addOp != null) genericOperationForceOpen(2); if (verbosity >= 100) super.signed_operand(addOp); if (addOp != null) genericOperationClose(1); } public void add_operand(int numAddOps) { genericOperationOpen(numAddOps); if (verbosity >= 100) super.add_operand(numAddOps); genericOperationClose(numAddOps); } public void add_operand__add_op(Token addOp) { // same as mult_operand__mult_op() Element element = contextNode(-1); contextOpen("operand"); moveHere(element); if (verbosity >= 100) super.add_operand__add_op(addOp); contextClose(); } public void level_2_expr(int numConcatOps) { genericOperationOpen(numConcatOps); if (verbosity >= 100) super.level_2_expr(numConcatOps); genericOperationClose(numConcatOps); } public void power_op(Token powerKeyword) { contextOpen("operator"); setAttribute("operator", powerKeyword); if (verbosity >= 100) super.power_op(powerKeyword); contextClose(); } public void mult_op(Token multKeyword) { contextOpen("operator"); setAttribute("operator", multKeyword); if (verbosity >= 100) super.mult_op(multKeyword); contextClose(); } public void add_op(Token addKeyword) { contextOpen("operator"); setAttribute("operator", addKeyword); if (verbosity >= 100) super.add_op(addKeyword); contextClose(); } public void level_3_expr(Token relOp) { int numRelOp = relOp == null ? 0 : 1; genericOperationOpen(numRelOp); if (verbosity >= 80) super.level_3_expr(relOp); genericOperationClose(numRelOp); } public void concat_op(Token concatKeyword) { contextOpen("operator"); if (verbosity >= 100) super.concat_op(concatKeyword); setAttribute("operator", "//"); contextClose(); } public void rel_op(Token relOp) { contextOpen("operator"); setAttribute("operator", relOp); if (verbosity >= 100) super.rel_op(relOp); contextClose(); } public void and_operand(boolean hasNotOp, int numAndOps) { if (hasNotOp) if (numAndOps == 0) genericOperationForceOpen(2); else { int nodesCount = 2 * numAndOps + 2; ArrayList<Element> nodes = contextNodes(-nodesCount, 2); Element reference = contextNode(-nodesCount + 2); Element operation = contextOpen("operation"); setAttribute("type", "unary"); for (Element node : nodes) { boolean needsTransform = !node.getTagName().equals("operand") && !node.getTagName().equals("operator"); if (needsTransform) contextOpen("operand"); moveHere(node); if (needsTransform) contextClose(); } contextClose(); context.removeChild(operation); context.insertBefore(operation, reference); genericOperationOpen(numAndOps); // cleanUpAfterError("didn't expect hasNotOp=" + hasNotOp + " numAndOps=" + numAndOps); } else genericOperationOpen(numAndOps); if (verbosity >= 100) super.and_operand(hasNotOp, numAndOps); if (hasNotOp) genericOperationClose(numAndOps > 0 ? numAndOps : 1); else genericOperationClose(numAndOps); } public void and_operand__not_op(boolean hasNotOp) { if (hasNotOp) { genericOperationForceOpen(2); genericOperationClose(1); // cleanUpAfterError("didn't expect hasNotOp=" + hasNotOp); } // same as mult_operand__mult_op() Element element = contextNode(-1); contextOpen("operand"); moveHere(element); if (verbosity >= 100) super.and_operand__not_op(hasNotOp); contextClose(); } public void or_operand(int numOrOps) { genericOperationOpen(numOrOps); if (verbosity >= 100) super.or_operand(numOrOps); genericOperationClose(numOrOps); } public void equiv_operand(int numEquivOps) { genericOperationOpen(numEquivOps); if (verbosity >= 100) super.equiv_operand(numEquivOps); genericOperationClose(numEquivOps); } public void equiv_operand__equiv_op(Token equivOp) { // same as mult_operand__mult_op() Element element = contextNode(-1); contextOpen("operand"); moveHere(element); if (verbosity >= 100) super.equiv_operand__equiv_op(equivOp); contextClose(); } public void not_op(Token notOp) { contextOpen("operator"); setAttribute("operator", notOp); if (verbosity >= 100) super.not_op(notOp); contextClose(); } public void and_op(Token andOp) { contextOpen("operator"); setAttribute("operator", andOp); if (verbosity >= 100) super.and_op(andOp); contextClose(); } public void or_op(Token orOp) { contextOpen("operator"); setAttribute("operator", orOp); if (verbosity >= 100) super.or_op(orOp); contextClose(); } public void equiv_op(Token equivOp) { contextOpen("operator"); setAttribute("operator", equivOp); if (verbosity >= 100) super.equiv_op(equivOp); contextClose(); } public void assignment_stmt(Token label, Token eos) { ArrayList<Element> nodes = contextNodes(); if (nodes.size() < 2) cleanUpAfterError("there should be at least 2 nodes for 'assignment' but " + nodes.size() + " found"); Element target = contextNode(-2); Element value = contextNode(-1); contextOpen("assignment"); contextOpen("target"); moveHere(target); contextClose(); contextOpen("value"); moveHere(value); contextClose(); if (verbosity >= 100) super.assignment_stmt(label, eos); contextClose(); } public void pointer_assignment_stmt(Token label, Token eos, boolean hasBoundsSpecList, boolean hasBoundsRemappingList) { Element value = contextNode(-1); contextClose(); Element target = contextNode(-1); contextOpen("pointer-assignment"); contextOpen("target"); moveHere(target); contextClose(); contextOpen("value"); moveHere(value); contextClose(); super.pointer_assignment_stmt(label, eos, hasBoundsSpecList, hasBoundsRemappingList); contextClose(); } public void forall_construct() { if (verbosity >= 100) super.forall_construct(); contextClose("loop"); contextOpen("statement"); } public void forall_construct_stmt(Token label, Token id, Token forallKeyword, Token eos) { contextRename("statement", "loop"); setAttribute("type", "forall"); ArrayList<Element> elements = contextNodes(); contextOpen("header"); moveHere(elements); contextClose(); super.forall_construct_stmt(label, id, forallKeyword, eos); contextOpen("body"); contextOpen("statement"); } public void forall_header() { if (verbosity >= 100) super.forall_header(); } public void forall_triplet_spec(Token id, boolean hasStride) { contextOpen("index-variable"); setAttribute("name", id); contextClose(); Element element = contextNode(-1); context.removeChild(element); context.insertBefore(element, contextNode(hasStride ? -3 : -2)); genericLoopControl(hasStride); context = contextNode(-1); super.forall_triplet_spec(id, hasStride); contextClose(); } public void forall_assignment_stmt(boolean isPointerAssignment) { Element assignment = contextNode(-1); if (!context.getTagName().equals("header")) cleanUpAfterError("didn't expect <" + context.getTagName() + ">"); contextClose(); contextOpen("body"); contextOpen("statement"); moveHere(assignment); context = assignment; // temporarily reopen assignment context if (!context.getTagName().equals("assignment")) cleanUpAfterError("didn't expect <" + context.getTagName() + ">"); if (verbosity >= 100) super.forall_assignment_stmt(isPointerAssignment); contextClose(); // re-close assignment context contextClose(); contextClose(); } public void end_forall_stmt(Token label, Token endKeyword, Token forallKeyword, Token id, Token eos) { contextCloseAllInner("loop"); super.end_forall_stmt(label, endKeyword, forallKeyword, id, eos); } public void forall_stmt__begin() { contextRename("statement", "loop"); setAttribute("type", "forall"); if (verbosity >= 100) super.forall_stmt__begin(); contextOpen("header"); } public void forall_stmt(Token label, Token forallKeyword) { contextCloseAllInner("loop"); super.forall_stmt(label, forallKeyword); contextClose(); contextOpen("statement"); // TODO: temporary workaround } public void block() { contextCloseAllInner("body"); if (verbosity >= 100) super.block(); } public void if_construct() { contextCloseAllInner("if"); if (verbosity >= 100) super.if_construct(); contextClose(); contextOpen("statement"); } public void if_then_stmt(Token label, Token id, Token ifKeyword, Token thenKeyword, Token eos) { contextRename("statement", "if"); ArrayList<Element> nodes = contextNodes(); contextOpen("header"); moveHere(nodes); contextClose(); if (verbosity >= 80) super.if_then_stmt(label, id, ifKeyword, thenKeyword, eos); contextOpen("body"); contextOpen("statement"); } public void else_if_stmt(Token label, Token elseKeyword, Token ifKeyword, Token thenKeyword, Token id, Token eos) { Element condition = contextNode(-1); contextClose("body"); contextOpen("header"); setAttribute("type", "else-if"); moveHere(condition); contextClose(); if (verbosity >= 80) super.else_if_stmt(label, elseKeyword, ifKeyword, thenKeyword, id, eos); contextOpen("body"); setAttribute("type", "else-if"); contextOpen("statement"); } public void else_stmt(Token label, Token elseKeyword, Token id, Token eos) { contextClose("body"); if (verbosity >= 80) super.else_stmt(label, elseKeyword, id, eos); contextOpen("body"); setAttribute("type", "else"); contextOpen("statement"); } public void end_if_stmt(Token label, Token endKeyword, Token ifKeyword, Token id, Token eos) { contextCloseAllInner("if"); if (verbosity >= 80) super.end_if_stmt(label, endKeyword, ifKeyword, id, eos); } public void if_stmt__begin() { contextRename("statement", "if"); if (verbosity >= 100) super.if_stmt__begin(); contextOpen("header"); // will be filled by if_stmt() contextClose(); contextOpen("body"); contextOpen("statement"); } public void if_stmt(Token label, Token ifKeyword) { contextClose("body"); Element ifHeader = contextNode(-2); Element ifBody = contextNode(-1); Element statementToBeFixed = contextNode(ifBody, 0); Element ifCondition = contextNode(statementToBeFixed, 0); if (!ifBody.getTagName().equals("body")) cleanUpAfterError("if body node must be named body"); moveTo(ifHeader, ifCondition); contextCloseAllInner("if"); super.if_stmt(label, ifKeyword); contextClose(); contextOpen("statement"); } public void block_construct() { if (verbosity >= 100) super.block_construct(); } public void case_construct() { contextCloseAllInner("select"); if (verbosity >= 100) super.case_construct(); contextClose(); contextOpen("statement"); } public void select_case_stmt(Token label, Token id, Token selectKeyword, Token caseKeyword, Token eos) { contextRename("statement", "select"); ArrayList<Element> nodes = contextNodes(); contextOpen("header"); moveHere(nodes); contextClose(); super.select_case_stmt(label, id, selectKeyword, caseKeyword, eos); contextOpen("body"); } public void case_stmt(Token label, Token caseKeyword, Token id, Token eos) { super.case_stmt(label, caseKeyword, id, eos); contextOpen("body"); contextOpen("statement"); } public void end_select_stmt(Token label, Token endKeyword, Token selectKeyword, Token id, Token eos) { contextCloseAllInner("select"); super.end_select_stmt(label, endKeyword, selectKeyword, id, eos); } public void case_selector(Token defaultToken) { if (!context.getTagName().equals("case") && contextTryFind("case") != null) { contextClose("case"); contextOpen("case"); setAttribute("type", "default"); contextOpen("header"); contextClose(); } super.case_selector(defaultToken); } public void case_value_range() { contextClose("value-range"); if (verbosity >= 100) super.case_value_range(); contextOpen("value-range"); contextOpen("value"); } public void case_value_range_list__begin() { if (context.getTagName().equals("body") && ((Element) context.getParentNode()).getTagName().equals("case")) { contextClose("body"); contextClose("case"); } contextOpen("case"); setAttribute("type", "specific"); contextOpen("header"); super.case_value_range_list__begin(); contextOpen("value-range"); contextOpen("value"); } public void case_value_range_list(int count) { super.case_value_range_list(count); contextClose("header"); } public void case_value_range_suffix() { contextCloseAllInner("value-range"); if (verbosity >= 100) super.case_value_range_suffix(); } public void case_value() { contextClose("value"); if (verbosity >= 100) super.case_value(); contextOpen("value"); } public void associate_construct() { super.associate_construct(); contextClose("associate"); contextOpen("statement"); } public void associate_stmt(Token label, Token id, Token associateKeyword, Token eos) { Element element = contextNode(-1); contextRename("statement", "associate"); contextOpen("header"); moveHere(element); contextClose(); super.associate_stmt(label, id, associateKeyword, eos); contextOpen("body"); contextOpen("statement"); } public void association(Token id) { context = contextNode(-1); assert context.getNodeName().equals("keyword-argument"); setAttribute("argument-name", id); if (verbosity >= 100) super.association(id); contextClose(); } public void selector() { Element element = contextNode(-1); contextOpen("keyword-argument"); moveHere(element); if (verbosity >= 100) super.selector(); contextClose(); } public void end_associate_stmt(Token label, Token endKeyword, Token associateKeyword, Token id, Token eos) { contextClose("body"); super.end_associate_stmt(label, endKeyword, associateKeyword, id, eos); } public void type_guard_stmt(Token label, Token typeKeyword, Token isOrDefaultKeyword, Token selectConstructName, Token eos) { // TODO Auto-generated method stub contextOpen("statement"); super.type_guard_stmt(label, typeKeyword, isOrDefaultKeyword, selectConstructName, eos); } public void do_construct() { contextCloseAllInner("loop"); if (verbosity >= 100) super.do_construct(); contextClose(); contextOpen("statement"); } public void block_do_construct() { if (verbosity >= 100) super.block_do_construct(); } public void do_stmt(Token label, Token id, Token doKeyword, Token digitString, Token eos, boolean hasLoopControl) { if (!hasLoopControl) { contextRename("statement", "loop"); setAttribute("type", "do-label"); } /* if (digitString != null) // TODO: is this needed? setAttribute("label", digitString); */ super.do_stmt(label, id, doKeyword, digitString, eos, hasLoopControl); contextOpen("body"); contextOpen("statement"); } public void label_do_stmt(Token label, Token id, Token doKeyword, Token digitString, Token eos, boolean hasLoopControl) { super.label_do_stmt(label, id, doKeyword, digitString, eos, hasLoopControl); cleanUpAfterError("didn't expect label-do-stmt"); } public void loop_control(Token whileKeyword, int doConstructType, boolean hasOptExpr) { /* if(hasOptExpr) cleanUpAfterError("didn't expect hasOptExpr=" + hasOptExpr); */ if (doConstructType == 1701) genericLoopControl(hasOptExpr); contextRename("statement", "loop"); String loopType = ""; switch (doConstructType) { case IActionEnums.DoConstruct_concurrent: loopType = "do-concurrent"; break; case IActionEnums.DoConstruct_variable: loopType = "do"; break; case IActionEnums.DoConstruct_while: loopType = "do-while"; break; default: throw new IllegalArgumentException(Integer.toString(doConstructType)); } setAttribute("type", loopType); Element element = contextNode(-1); contextOpen("header"); moveHere(element); super.loop_control(whileKeyword, doConstructType, hasOptExpr); contextClose(); } public void do_variable(Token id) { contextOpen("index-variable"); setAttribute("name", id); super.do_variable(id); contextClose(); } public void end_do() { if (verbosity >= 100) super.end_do(); } public void end_do_stmt(Token label, Token endKeyword, Token doKeyword, Token id, Token eos) { contextCloseAllInner("loop"); if (verbosity >= 80) super.end_do_stmt(label, endKeyword, doKeyword, id, eos); } public void do_term_action_stmt(Token label, Token endKeyword, Token doKeyword, Token id, Token eos, boolean inserted) { contextCloseAllInner("loop"); if (verbosity >= 80) super.do_term_action_stmt(label, endKeyword, doKeyword, id, eos, inserted); } public void cycle_stmt(Token label, Token cycleKeyword, Token id, Token eos) { contextOpen("cycle"); if (verbosity >= 80) super.cycle_stmt(label, cycleKeyword, id, eos); contextClose(); } public void exit_stmt(Token label, Token exitKeyword, Token id, Token eos) { contextOpen("exit"); if (verbosity >= 80) super.exit_stmt(label, exitKeyword, id, eos); contextClose(); } public void goto_stmt(Token label, Token goKeyword, Token toKeyword, Token target_label, Token eos) { // TODO Auto-generated method stub super.goto_stmt(label, goKeyword, toKeyword, target_label, eos); } public void continue_stmt(Token label, Token continueKeyword, Token eos) { Element labelNode = contextNodesCount() > 0 ? contextNode(-1) : null; labelNode = labelNode != null && labelNode.getTagName() == "label" ? labelNode : null; contextOpen("statement"); contextOpen("continue"); if (labelNode != null) moveHere(labelNode); super.continue_stmt(label, continueKeyword, eos); contextClose(); } public void stop_stmt(Token label, Token stopKeyword, Token eos, boolean hasStopCode) { if (hasStopCode) { Element value = contextNode(-1); contextOpen("stop"); moveHere(value); Attr stopCode = getAttribute("digitString", value); setAttribute("code", stopCode.getValue()); } else { contextOpen("stop"); setAttribute("code", ""); } if (verbosity >= 60) super.stop_stmt(label, stopKeyword, eos, hasStopCode); contextClose(); } public void open_stmt(Token label, Token openKeyword, Token eos) { Element args = contextNode(-1); contextOpen("open"); moveHere(args); super.open_stmt(label, openKeyword, eos); contextClose(); } public void connect_spec(Token id) { contextCloseAllInner("keyword-argument"); setAttribute("argument-name", id); contextClose(); if (verbosity >= 100) super.connect_spec(id); contextOpen("keyword-argument"); } public void connect_spec_list__begin() { super.connect_spec_list__begin(); contextOpen("keyword-argument"); } public void connect_spec_list(int count) { contextClose("keyword-argument"); super.connect_spec_list(count); } public void close_stmt(Token label, Token closeKeyword, Token eos) { Element args = contextNode(-1); contextOpen("close"); moveHere(args); super.close_stmt(label, closeKeyword, eos); contextClose(); } public void close_spec(Token closeSpec) { contextCloseAllInner("keyword-argument"); setAttribute("argument-name", closeSpec); contextClose(); if (verbosity >= 100) super.close_spec(closeSpec); contextOpen("keyword-argument"); } public void close_spec_list__begin() { super.close_spec_list__begin(); contextOpen("keyword-argument"); } public void close_spec_list(int count) { contextClose("keyword-argument"); super.close_spec_list(count); } public void read_stmt(Token label, Token readKeyword, Token eos, boolean hasInputItemList) { Element outerContext = context; contextOpen("read"); if (hasInputItemList) moveHere(contextNode(outerContext, -3)); moveHere(contextNode(outerContext, -2)); super.read_stmt(label, readKeyword, eos, hasInputItemList); contextClose(); } public void write_stmt(Token label, Token writeKeyword, Token eos, boolean hasOutputItemList) { Element args = contextNode(-1); Element outputs = null; if (hasOutputItemList) { outputs = args; args = contextNode(-2); } contextOpen("write"); moveHere(args); if (hasOutputItemList) moveHere(outputs); super.write_stmt(label, writeKeyword, eos, hasOutputItemList); contextClose(); } public void print_stmt(Token label, Token printKeyword, Token eos, boolean hasOutputItemList) { Element outputs = hasOutputItemList ? contextNode(-1) : null; Element format = contextNode(hasOutputItemList ? -2 : -1); contextOpen("print"); moveHere(format); if (hasOutputItemList) moveHere(outputs); super.print_stmt(label, printKeyword, eos, hasOutputItemList); contextClose(); } public void io_control_spec(boolean hasExpression, Token keyword, boolean hasAsterisk) { if (hasExpression) { Element element = contextNode(-1); contextOpen("io-control"); moveHere(element); } else contextOpen("io-control"); setAttribute("argument-name", keyword == null ? "" : keyword); super.io_control_spec(hasExpression, keyword, hasAsterisk); contextClose("io-control"); } public void format() { Element label = null; if (contextNodesCount() > 0) { Element node = contextNode(-1); if (node.getNodeName().equals("literal")) label = node; } contextOpen("print-format"); setAttribute("type", label == null ? "*" : "label"); if (label != null) moveHere(label); if (verbosity >= 100) super.format(); contextClose(); } public void input_item() { Element element = contextNode(-1); contextOpen("input"); moveHere(element); if (verbosity >= 100) super.input_item(); contextClose("input"); } public void output_item() { Element element = contextNode(-1); contextOpen("output"); moveHere(element); if (verbosity >= 100) super.output_item(); contextClose(); } public void io_implied_do() { ArrayList<Element> elements = contextNodes(); Element header = contextNode(-1); contextOpen("loop"); setAttribute("type", "implied-do"); contextOpen("body"); for (Element node : elements) if (node.getTagName().equals("expression")) moveHere(node); contextClose(); moveHere(header); super.io_implied_do(); contextClose(); } public void io_implied_do_object() { context = contextNode(-1); contextRename("expression"); if (verbosity >= 100) super.io_implied_do_object(); contextClose(); } public void io_implied_do_control(boolean hasStride) { genericLoopControl(hasStride); Element element = contextNode(-1); contextOpen("header"); moveHere(element); super.io_implied_do_control(hasStride); contextClose(); } public void format_stmt(Token label, Token formatKeyword, Token eos) { Element labelNode = (label != null) ? contextNode(-2) : null; context = contextNode(-1); if (label != null) moveHere(0, labelNode); if (verbosity >= 60) super.format_stmt(label, formatKeyword, eos); contextClose(); } public void format_specification(boolean hasFormatItemList) { Element items = hasFormatItemList ? contextNode(-1) : null; contextOpen("format"); if (hasFormatItemList) moveHere(items); if (verbosity >= 60) super.format_specification(hasFormatItemList); contextClose(); } public void main_program__begin() { contextOpen("program"); if (verbosity >= 100) super.main_program__begin(); contextOpen("header"); } public void ext_function_subprogram(boolean hasPrefix) { context = contextNode(-1); // temporarily reopen previously-closed context if (verbosity >= 100) super.ext_function_subprogram(hasPrefix); contextClose(); // re-close previously closed context } public void main_program(boolean hasProgramStmt, boolean hasExecutionPart, boolean hasInternalSubprogramPart) { super.main_program(hasProgramStmt, hasExecutionPart, hasInternalSubprogramPart); contextClose("program"); } public void program_stmt(Token label, Token programKeyword, Token id, Token eos) { contextClose("header"); if (verbosity >= 20) super.program_stmt(label, programKeyword, id, eos); setAttribute("name", id); contextOpen("body"); contextOpen("specification"); contextOpen("declaration"); } public void end_program_stmt(Token label, Token endKeyword, Token programKeyword, Token id, Token eos) { if (contextTryFind("program") == null) { // TODO: this workaround should not be needed ArrayList<Element> nodes = contextNodes(); contextOpen("program"); moveHere(nodes); } contextCloseAllInner("program"); super.end_program_stmt(label, endKeyword, programKeyword, id, eos); } public void module() { contextCloseAllInner("module"); if (verbosity >= 100) super.module(); contextClose(); } public void module_stmt__begin() { contextOpen("module"); if (verbosity >= 100) super.module_stmt__begin(); contextOpen("header"); } public void module_stmt(Token label, Token moduleKeyword, Token id, Token eos) { contextClose("header"); setAttribute("name", id); super.module_stmt(label, moduleKeyword, id, eos); contextOpen("body"); contextOpen("specification"); contextOpen("declaration"); } public void end_module_stmt(Token label, Token endKeyword, Token moduleKeyword, Token id, Token eos) { if (!context.getTagName().equals("members")) { ArrayList<String> hierarchy = contextNameHierarchy(); String[] expected = { "body", "module" }; if (hierarchy.size() >= 2 && (Arrays.equals(hierarchy.subList(0, 2).toArray(), expected) || (hierarchy.size() >= 3 && Arrays.equals(hierarchy.subList(1, 3).toArray(), expected)))) { contextClose("body"); contextOpen("members"); } /* else System.err.println("Context hierarchy for 'end module' statement: " + hierarchy); */ } contextClose("members"); super.end_module_stmt(label, endKeyword, moduleKeyword, id, eos); } public void module_subprogram(boolean hasPrefix) { super.module_subprogram(hasPrefix); } public void use_stmt(Token label, Token useKeyword, Token id, Token onlyKeyword, Token eos, boolean hasModuleNature, boolean hasRenameList, boolean hasOnly) { if (context.getTagName().equals("declaration")) { LOG.log(Level.FINE, "closing unclosed declaration at use_stmt id={0}", id.getText()); contextClose("declaration"); } if (!context.getTagName().equals("use")) contextOpen("use"); setAttribute("name", id); super.use_stmt(label, useKeyword, id, onlyKeyword, eos, hasModuleNature, hasRenameList, hasOnly); contextClose("use"); contextOpen("declaration"); } public void module_nature(Token nature) { if (context.getTagName().equals("declaration")) { LOG.log(Level.FINE, "closing unclosed declaration at module_nature nature={0}", nature.getText()); contextClose("declaration"); } if (!context.getTagName().equals("use")) contextOpen("use"); contextOpen("nature"); setAttribute("name", nature); if (verbosity >= 80) super.module_nature(nature); contextClose("nature"); } public void rename_list__begin() { if (context.getTagName().equals("declaration")) { LOG.log(Level.FINE, "closing unclosed declaration at rename_list__begin"); contextClose("declaration"); } if (!context.getTagName().equals("use")) contextOpen("use"); super.rename_list__begin(); } public void only_list__begin() { if (context.getTagName().equals("declaration")) { LOG.log(Level.FINE, "closing unclosed declaration at only_list__begin"); contextClose("declaration"); } if (!context.getTagName().equals("use")) contextOpen("use"); super.only_list__begin(); } public void block_data() { if (verbosity >= 100) super.block_data(); contextClose("block-data"); } public void block_data_stmt__begin() { contextOpen("block-data"); if (verbosity >= 100) super.block_data_stmt__begin(); contextOpen("specification"); contextOpen("declaration"); } public void interface_block() { // TODO Auto-generated method stub super.interface_block(); } public void interface_specification() { // TODO Auto-generated method stub super.interface_specification(); } public void interface_stmt__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); contextOpen("interface"); if (verbosity >= 100) super.interface_stmt__begin(); contextOpen("header"); } public void interface_stmt(Token label, Token abstractToken, Token keyword, Token eos, boolean hasGenericSpec) { if (contextTryFind("declaration") == null) // interface_stmt__begin is not always emitted contextOpen("declaration"); if (contextTryFind("interface") == null) { contextOpen("interface"); contextOpen("header"); } contextClose("header"); super.interface_stmt(label, abstractToken, keyword, eos, hasGenericSpec); if (abstractToken != null) setAttribute("type", abstractToken); contextOpen("body"); contextOpen("specification"); contextOpen("declaration"); } public void end_interface_stmt(Token label, Token kw1, Token kw2, Token eos, boolean hasGenericSpec) { contextCloseAllInner("interface"); super.end_interface_stmt(label, kw1, kw2, eos, hasGenericSpec); contextClose(); if (!context.getTagName().equals("declaration")) cleanUpAfterError("expected interface to be within declaration context, but its in " + context.getTagName()); setAttribute("type", "interface"); } public void interface_body(boolean hasPrefix) { // TODO Auto-generated method stub super.interface_body(hasPrefix); } public void generic_spec(Token keyword, Token name, int type) { contextOpen("name"); setAttribute("id", name); super.generic_spec(keyword, name, type); contextClose(); } public void import_stmt(Token label, Token importKeyword, Token eos, boolean hasGenericNameList) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "import"); super.import_stmt(label, importKeyword, eos, hasGenericNameList); contextClose("declaration"); } public void external_stmt(Token label, Token externalKeyword, Token eos) { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); if (verbosity >= 80) super.external_stmt(label, externalKeyword, eos); setAttribute("type", "external"); } public void procedure_declaration_stmt(Token label, Token procedureKeyword, Token eos, boolean hasProcInterface, int count) { // TODO Auto-generated method stub super.procedure_declaration_stmt(label, procedureKeyword, eos, hasProcInterface, count); } public void proc_decl(Token id, boolean hasNullInit) { contextOpen("procedure"); setAttribute("name", id); if (verbosity >= 80) super.proc_decl(id, hasNullInit); contextClose(); } public void proc_decl_list__begin() { if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "procedures"); super.proc_decl_list__begin(); } public void intrinsic_stmt(Token label, Token intrinsicKeyword, Token eos) { Element condition = contextNode(-1); if (!context.getTagName().equals("declaration")) contextOpen("declaration"); setAttribute("type", "intrinsic"); moveHere(condition); super.intrinsic_stmt(label, intrinsicKeyword, eos); } public void call_stmt(Token label, Token callKeyword, Token eos, boolean hasActualArgSpecList) { Element name = contextNode(-1); Element arguments = null; if (name.getTagName() == "arguments") { arguments = name; name = contextNode(-2); } else if (name.getTagName() != "name") cleanUpAfterError("tag name is not 'name' but '" + name.getTagName() + "'"); contextOpen("call"); moveHere(name); if (arguments != null) moveHere(arguments); super.call_stmt(label, callKeyword, eos, hasActualArgSpecList); contextClose(); } public void procedure_designator() { if (verbosity >= 100) super.procedure_designator(); setAttribute("type", "procedure"); contextClose("name"); } public void actual_arg_spec(Token keyword) { boolean inArgumentContext = contextTryFind("argument") != null; if (!inArgumentContext) contextOpen("argument"); setAttribute("name", keyword); if (verbosity >= 100) super.actual_arg_spec(keyword); if (inArgumentContext) contextClose("argument"); } public void actual_arg_spec_list__begin() { super.actual_arg_spec_list__begin(); contextOpen("argument"); } public void actual_arg_spec_list(int count) { contextClose("argument"); super.actual_arg_spec_list(count); } public void actual_arg(boolean hasExpr, Token label) { boolean inArgumentContext = contextTryFind("argument") != null; if (!inArgumentContext) { if (hasExpr) { Element element = contextNode(-1); contextOpen("argument"); moveHere(element); } else contextOpen("argument"); } if (verbosity >= 60) super.actual_arg(hasExpr, label); if (inArgumentContext) contextClose("argument"); } public void function_subprogram(boolean hasExePart, boolean hasIntSubProg) { super.function_subprogram(hasExePart, hasIntSubProg); if (context.getTagName().equals("function")) contextClose("function"); } public void function_stmt__begin() { contextOpen("function"); contextOpen("header"); if (verbosity >= 100) super.function_stmt__begin(); } public void function_stmt(Token label, Token keyword, Token name, Token eos, boolean hasGenericNameList, boolean hasSuffix) { contextClose("header"); super.function_stmt(label, keyword, name, eos, hasGenericNameList, hasSuffix); setAttribute("name", name); contextOpen("body"); contextOpen("specification"); contextOpen("declaration"); } public void prefix_spec(boolean isDecTypeSpec) { super.prefix_spec(isDecTypeSpec); if (isDecTypeSpec) contextClose("declaration"); } public void end_function_stmt(Token label, Token keyword1, Token keyword2, Token name, Token eos) { contextCloseAllInner("function"); super.end_function_stmt(label, keyword1, keyword2, name, eos); } public void subroutine_stmt__begin() { contextOpen("subroutine"); contextOpen("header"); if (verbosity >= 100) super.subroutine_stmt__begin(); } public void subroutine_stmt(Token label, Token keyword, Token name, Token eos, boolean hasPrefix, boolean hasDummyArgList, boolean hasBindingSpec, boolean hasArgSpecifier) { super.subroutine_stmt(label, keyword, name, eos, hasPrefix, hasDummyArgList, hasBindingSpec, hasArgSpecifier); contextClose("header"); setAttribute("name", name); contextOpen("body"); contextOpen("specification"); contextOpen("declaration"); } public void dummy_arg(Token dummy) { contextOpen("argument"); setAttribute("name", dummy); if (verbosity >= 100) super.dummy_arg(dummy); contextClose(); } public void end_subroutine_stmt(Token label, Token keyword1, Token keyword2, Token name, Token eos) { contextCloseAllInner("subroutine"); super.end_subroutine_stmt(label, keyword1, keyword2, name, eos); contextClose(); } public void return_stmt(Token label, Token keyword, Token eos, boolean hasScalarIntExpr) { if (hasScalarIntExpr) { Element element = contextNode(-1); contextOpen("return"); contextOpen("value"); moveHere(element); contextClose(); } else contextOpen("return"); setAttribute("hasValue", hasScalarIntExpr); super.return_stmt(label, keyword, eos, hasScalarIntExpr); contextClose(); } public void contains_stmt(Token label, Token keyword, Token eos) { ArrayList<String> hierarchy = contextNameHierarchy(); boolean acceptedContext = false; if (hierarchy.size() >= 3) { Object[] hierarchyArray = hierarchy.subList(0, 3).toArray(); for (String enclosingGroup : new String[] { "subroutine", "program", "module" }) { acceptedContext = Arrays.equals(hierarchyArray, new String[] { "statement", "body", enclosingGroup }); if (acceptedContext) break; } } /* if (!acceptedContext) cleanUpAfterError("Context hierarchy for 'contains' statement is invalid: " + hierarchy); */ if (acceptedContext) contextClose("body"); super.contains_stmt(label, keyword, eos); if (acceptedContext) contextOpen("members"); } public void separate_module_subprogram(boolean hasExecutionPart, boolean hasInternalSubprogramPart) { super.separate_module_subprogram(hasExecutionPart, hasInternalSubprogramPart); contextClose("subroutine"); } public void separate_module_subprogram__begin() { contextOpen("subroutine"); super.separate_module_subprogram__begin(); contextOpen("header"); } public void mp_subprogram_stmt(Token label, Token moduleKeyword, Token procedureKeyword, Token name, Token eos) { contextClose("header"); setAttribute("name", name); super.mp_subprogram_stmt(label, moduleKeyword, procedureKeyword, name, eos); contextOpen("body"); } public void end_mp_subprogram_stmt(Token label, Token keyword1, Token keyword2, Token name, Token eos) { contextCloseAllInner("subroutine"); super.end_mp_subprogram_stmt(label, keyword1, keyword2, name, eos); } public void start_of_file(String filename, String path) { if (contextTryFind("file") != null) { if (context.getTagName().equals("declaration")) { LOG.log(Level.FINER, "closing unclosed declaration at start_of_file"); contextClose("declaration"); } contextOpen("declaration"); setAttribute("type", "include"); } contextOpen("file"); if (verbosity >= 100) super.start_of_file(filename, path); if (path.equals("ERROR_FILE_NOT_FOUND")) setAttribute("path", filename); else setAttribute("path", path); } public void end_of_file(String filename, String path) { contextCloseAllInner("file"); if (verbosity >= 100) super.end_of_file(filename, path); contextClose(); } public void next_token(Token tk) { System.err.println("next_token"); System.err.println(tk); } }
add type to format declaration
src/fortran/ofp/XMLPrinter.java
add type to format declaration
<ide><path>rc/fortran/ofp/XMLPrinter.java <ide> if (verbosity >= 60) <ide> super.format_stmt(label, formatKeyword, eos); <ide> contextClose(); <add> if (context.getTagName().equals("declaration")) <add> setAttribute("type", "format"); <ide> } <ide> <ide> public void format_specification(boolean hasFormatItemList) {
Java
apache-2.0
bfa372c2968a24f2f22165d1066978a227738da3
0
tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.psi; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; /** * * Created by tangzx on 2016/12/3. */ public class LuaPsiTreeUtil { public interface ElementProcessor<T extends PsiElement> { boolean accept(T t); } public static void walkUpLabel(PsiElement current, ElementProcessor<LuaLabelStat> processor) { PsiElement prev = current.getPrevSibling(); while (true) { if (prev == null) prev = current.getParent(); if (prev == null || prev instanceof PsiFile) break; if (prev instanceof LuaLabelStat && !processor.accept((LuaLabelStat) prev)) break; current = prev; prev = prev.getPrevSibling(); } } public static <T extends PsiElement> void walkTopLevelInFile(PsiElement element, Class<T> cls, ElementProcessor<T> processor) { if (element == null || processor == null) return; PsiElement parent = element; while (!(parent.getParent() instanceof PsiFile)) parent = parent.getParent(); for(PsiElement child = parent; child != null; child = child.getPrevSibling()) { if (cls.isInstance(child)) { if (!processor.accept(cls.cast(child))) { break; } } } } /** * 向上寻找 local function 定义 * @param current 当前搜导起点 * @param processor 处理器 */ public static void walkUpLocalFuncDef(PsiElement current, ElementProcessor<LuaLocalFuncDef> processor) { if (current == null || processor == null) return; boolean continueSearch = true; int treeDeep = 0; int funcDeep = 0; PsiElement curr = current; do { if (curr instanceof LuaLocalFuncDef) { LuaLocalFuncDef localFuncDef = (LuaLocalFuncDef) curr; //todo 第一级local function不能使用 continueSearch = processor.accept(localFuncDef); funcDeep++; } PsiElement prevSibling = curr.getPrevSibling(); if (prevSibling == null) { treeDeep++; prevSibling = curr.getParent(); } curr = prevSibling; } while (continueSearch && !(curr instanceof PsiFile)); } /** * 向上寻找 local 定义 * @param element 当前搜索起点 * @param processor 处理器 */ public static void walkUpLocalNameDef(PsiElement element, ElementProcessor<LuaNameDef> processor) { if (element == null || processor == null) return; boolean continueSearch = true; PsiElement curr = element; do { PsiElement next = curr.getPrevSibling(); boolean isParent = false; if (next == null) { next = curr.getParent(); isParent = true; } curr = next; if (curr instanceof LuaLocalDef) { LuaLocalDef localDef = (LuaLocalDef) curr; // 跳过类似 // local name = name //skip if (!localDef.getNode().getTextRange().contains(element.getNode().getTextRange())) { LuaNameList nameList = localDef.getNameList(); continueSearch = resolveInNameList(nameList, processor); } } else if (isParent) { if (curr instanceof LuaFuncBody) { continueSearch = resolveInFuncBody((LuaFuncBody) curr, processor); } // for name = x, y do end else if (curr instanceof LuaForAStat) { LuaForAStat forAStat = (LuaForAStat) curr; continueSearch = processor.accept(forAStat.getParamNameDef()); } // for name in xxx do end else if (curr instanceof LuaForBStat) { LuaForBStat forBStat = (LuaForBStat) curr; continueSearch = resolveInNameList(forBStat.getParamNameDefList(), processor); } } } while (continueSearch && !(curr instanceof PsiFile)); } private static boolean resolveInFuncBody(LuaFuncBody funcBody, ElementProcessor<LuaNameDef> processor) { if (funcBody != null) { for (LuaParamNameDef parDef : funcBody.getParamNameDefList()) { if (!processor.accept(parDef)) return false; } } return true; } private static boolean resolveInNameList(LuaNameList nameList, ElementProcessor<LuaNameDef> processor) { if (nameList != null) { for (LuaNameDef nameDef : nameList.getNameDefList()) { if (!processor.accept(nameDef)) return false; } } return true; } private static boolean resolveInNameList(List<LuaParamNameDef> nameList, ElementProcessor<LuaNameDef> processor) { if (nameList != null) { for (LuaNameDef nameDef : nameList) { if (!processor.accept(nameDef)) return false; } } return true; } @Nullable public static <T extends PsiElement> T findElementOfClassAtOffset(@NotNull PsiFile file, int offset, @NotNull Class<T> clazz, boolean strictStart) { T t = PsiTreeUtil.findElementOfClassAtOffset(file, offset, clazz, strictStart); if (t == null) t = PsiTreeUtil.findElementOfClassAtOffset(file, offset - 1, clazz, strictStart); return t; } public static <T extends PsiElement> T getParentOfType(@Nullable PsiElement element, @NotNull Class<T> aClass, @NotNull Class... skips) { if (element == null) { return null; } else { element = element.getParent(); while(element != null && !aClass.isInstance(element) && PsiTreeUtil.instanceOf(element, skips)) { if (element instanceof PsiFile) { return null; } element = element.getParent(); } @SuppressWarnings("unchecked") T e = (T) element; return e; } } }
src/main/java/com/tang/intellij/lua/psi/LuaPsiTreeUtil.java
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.psi; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; /** * * Created by tangzx on 2016/12/3. */ public class LuaPsiTreeUtil { public interface ElementProcessor<T extends PsiElement> { boolean accept(T t); } public static void walkUpLabel(PsiElement current, ElementProcessor<LuaLabelStat> processor) { PsiElement prev = current.getPrevSibling(); while (true) { if (prev == null) prev = current.getParent(); if (prev == null || prev instanceof PsiFile) break; if (prev instanceof LuaLabelStat && !processor.accept((LuaLabelStat) prev)) break; current = prev; prev = prev.getPrevSibling(); } } public static <T extends PsiElement> void walkTopLevelInFile(PsiElement element, Class<T> cls, ElementProcessor<T> processor) { if (element == null || processor == null) return; PsiElement parent = element; while (!(parent.getParent() instanceof PsiFile)) parent = parent.getParent(); for(PsiElement child = parent; child != null; child = child.getPrevSibling()) { if (cls.isInstance(child)) { if (!processor.accept(cls.cast(child))) { break; } } } } /** * 向上寻找 local function 定义 * @param current 当前搜导起点 * @param processor 处理器 */ public static void walkUpLocalFuncDef(PsiElement current, ElementProcessor<LuaLocalFuncDef> processor) { if (current == null || processor == null) return; boolean continueSearch = true; int treeDeep = 0; int funcDeep = 0; PsiElement curr = current; do { if (curr instanceof LuaLocalFuncDef) { LuaLocalFuncDef localFuncDef = (LuaLocalFuncDef) curr; //todo 第一级local function不能使用 continueSearch = processor.accept(localFuncDef); funcDeep++; } PsiElement prevSibling = curr.getPrevSibling(); if (prevSibling == null) { treeDeep++; prevSibling = curr.getParent(); } curr = prevSibling; } while (continueSearch && !(curr instanceof PsiFile)); } /** * 向上寻找 local 定义 * @param element 当前搜索起点 * @param processor 处理器 */ public static void walkUpLocalNameDef(PsiElement element, ElementProcessor<LuaNameDef> processor) { if (element == null || processor == null) return; boolean continueSearch = true; boolean searchParList = false; PsiElement curr = element; do { PsiElement next = curr.getPrevSibling(); if (next == null) { next = curr.getParent(); } curr = next; if (curr instanceof LuaLocalDef) { LuaLocalDef localDef = (LuaLocalDef) curr; // 跳过类似 // local name = name //skip if (!localDef.getNode().getTextRange().contains(element.getNode().getTextRange())) { LuaNameList nameList = localDef.getNameList(); continueSearch = resolveInNameList(nameList, processor); } } else { //check if we can search in params // // local name // function(name) end //skip this `name` // name = nil // // for i, name in paris(name) do end // skip first `name` if (!searchParList && curr instanceof LuaBlock) { LuaBlock block = (LuaBlock) curr; searchParList = block.getNode().getStartOffset() <= curr.getNode().getStartOffset(); } if (curr instanceof LuaFuncBody) { //参数部分 if (searchParList) continueSearch = resolveInFuncBody((LuaFuncBody) curr, processor); } // for name = x, y do end else if (curr instanceof LuaForAStat) { LuaForAStat forAStat = (LuaForAStat) curr; if (searchParList) continueSearch = processor.accept(forAStat.getParamNameDef()); } // for name in xxx do end else if (curr instanceof LuaForBStat) { LuaForBStat forBStat = (LuaForBStat) curr; if (searchParList) continueSearch = resolveInNameList(forBStat.getParamNameDefList(), processor); } } } while (continueSearch && !(curr instanceof PsiFile)); } private static boolean resolveInFuncBody(LuaFuncBody funcBody, ElementProcessor<LuaNameDef> processor) { if (funcBody != null) { for (LuaParamNameDef parDef : funcBody.getParamNameDefList()) { if (!processor.accept(parDef)) return false; } } return true; } private static boolean resolveInNameList(LuaNameList nameList, ElementProcessor<LuaNameDef> processor) { if (nameList != null) { for (LuaNameDef nameDef : nameList.getNameDefList()) { if (!processor.accept(nameDef)) return false; } } return true; } private static boolean resolveInNameList(List<LuaParamNameDef> nameList, ElementProcessor<LuaNameDef> processor) { if (nameList != null) { for (LuaNameDef nameDef : nameList) { if (!processor.accept(nameDef)) return false; } } return true; } @Nullable public static <T extends PsiElement> T findElementOfClassAtOffset(@NotNull PsiFile file, int offset, @NotNull Class<T> clazz, boolean strictStart) { T t = PsiTreeUtil.findElementOfClassAtOffset(file, offset, clazz, strictStart); if (t == null) t = PsiTreeUtil.findElementOfClassAtOffset(file, offset - 1, clazz, strictStart); return t; } public static <T extends PsiElement> T getParentOfType(@Nullable PsiElement element, @NotNull Class<T> aClass, @NotNull Class... skips) { if (element == null) { return null; } else { element = element.getParent(); while(element != null && !aClass.isInstance(element) && PsiTreeUtil.instanceOf(element, skips)) { if (element instanceof PsiFile) { return null; } element = element.getParent(); } @SuppressWarnings("unchecked") T e = (T) element; return e; } } }
optimize walkUpLocalNameDef()
src/main/java/com/tang/intellij/lua/psi/LuaPsiTreeUtil.java
optimize walkUpLocalNameDef()
<ide><path>rc/main/java/com/tang/intellij/lua/psi/LuaPsiTreeUtil.java <ide> if (element == null || processor == null) <ide> return; <ide> boolean continueSearch = true; <del> boolean searchParList = false; <ide> <ide> PsiElement curr = element; <ide> do { <ide> PsiElement next = curr.getPrevSibling(); <add> boolean isParent = false; <ide> if (next == null) { <ide> next = curr.getParent(); <add> isParent = true; <ide> } <ide> curr = next; <ide> <ide> LuaNameList nameList = localDef.getNameList(); <ide> continueSearch = resolveInNameList(nameList, processor); <ide> } <del> } else { <del> //check if we can search in params <del> // <del> // local name <del> // function(name) end //skip this `name` <del> // name = nil <del> // <del> // for i, name in paris(name) do end // skip first `name` <del> if (!searchParList && curr instanceof LuaBlock) { <del> LuaBlock block = (LuaBlock) curr; <del> searchParList = block.getNode().getStartOffset() <= curr.getNode().getStartOffset(); <del> } <del> <add> } else if (isParent) { <ide> if (curr instanceof LuaFuncBody) { <del> //参数部分 <del> if (searchParList) continueSearch = resolveInFuncBody((LuaFuncBody) curr, processor); <add> continueSearch = resolveInFuncBody((LuaFuncBody) curr, processor); <ide> } <ide> // for name = x, y do end <ide> else if (curr instanceof LuaForAStat) { <ide> LuaForAStat forAStat = (LuaForAStat) curr; <del> if (searchParList) continueSearch = processor.accept(forAStat.getParamNameDef()); <add> continueSearch = processor.accept(forAStat.getParamNameDef()); <ide> } <ide> // for name in xxx do end <ide> else if (curr instanceof LuaForBStat) { <ide> LuaForBStat forBStat = (LuaForBStat) curr; <del> if (searchParList) continueSearch = resolveInNameList(forBStat.getParamNameDefList(), processor); <add> continueSearch = resolveInNameList(forBStat.getParamNameDefList(), processor); <ide> } <ide> } <ide> } while (continueSearch && !(curr instanceof PsiFile));
JavaScript
bsd-3-clause
79a7fa2bd1a18ba138fa4c7cf22ea9abb101c149
0
ipython/ipython,ipython/ipython
//---------------------------------------------------------------------------- // Copyright (C) 2008-2011 The IPython Development Team // // Distributed under the terms of the BSD License. The full license is in // the file COPYING, distributed as part of this software. //---------------------------------------------------------------------------- //============================================================================ // CodeCell //============================================================================ /** * An extendable module that provide base functionnality to create cell for notebook. * @module IPython * @namespace IPython * @submodule CodeCell */ /* local util for codemirror */ var posEq = function(a, b) {return a.line == b.line && a.ch == b.ch;}; /** * * function to delete until previous non blanking space character * or first multiple of 4 tabstop. * @private */ CodeMirror.commands.delSpaceToPrevTabStop = function(cm){ var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to); if (!posEq(from, to)) { cm.replaceRange("", from, to); return; } var cur = cm.getCursor(), line = cm.getLine(cur.line); var tabsize = cm.getOption('tabSize'); var chToPrevTabStop = cur.ch-(Math.ceil(cur.ch/tabsize)-1)*tabsize; from = {ch:cur.ch-chToPrevTabStop,line:cur.line}; var select = cm.getRange(from,cur); if( select.match(/^\ +$/) !== null){ cm.replaceRange("",from,cur); } else { cm.deleteH(-1,"char"); } }; var IPython = (function (IPython) { "use strict"; var utils = IPython.utils; var key = IPython.utils.keycodes; /** * A Cell conceived to write code. * * The kernel doesn't have to be set at creation time, in that case * it will be null and set_kernel has to be called later. * @class CodeCell * @extends IPython.Cell * * @constructor * @param {Object|null} kernel * @param {object|undefined} [options] * @param [options.cm_config] {object} config to pass to CodeMirror */ var CodeCell = function (kernel, options) { this.kernel = kernel || null; this.collapsed = false; // create all attributed in constructor function // even if null for V8 VM optimisation this.input_prompt_number = null; this.celltoolbar = null; this.output_area = null; this.last_msg_id = null; this.completer = null; var cm_overwrite_options = { onKeyEvent: $.proxy(this.handle_keyevent,this) }; options = this.mergeopt(CodeCell, options, {cm_config:cm_overwrite_options}); IPython.Cell.apply(this,[options]); // Attributes we want to override in this subclass. this.cell_type = "code"; var that = this; this.element.focusout( function() { that.auto_highlight(); } ); }; CodeCell.options_default = { cm_config : { extraKeys: { "Tab" : "indentMore", "Shift-Tab" : "indentLess", "Backspace" : "delSpaceToPrevTabStop", "Cmd-/" : "toggleComment", "Ctrl-/" : "toggleComment" }, mode: 'ipython', theme: 'ipython', matchBrackets: true, autoCloseBrackets: true } }; CodeCell.msg_cells = {}; CodeCell.prototype = new IPython.Cell(); /** * @method auto_highlight */ CodeCell.prototype.auto_highlight = function () { this._auto_highlight(IPython.config.cell_magic_highlight); }; /** @method create_element */ CodeCell.prototype.create_element = function () { IPython.Cell.prototype.create_element.apply(this, arguments); var cell = $('<div></div>').addClass('cell border-box-sizing code_cell'); cell.attr('tabindex','2'); var input = $('<div></div>').addClass('input'); var prompt = $('<div/>').addClass('prompt input_prompt'); var inner_cell = $('<div/>').addClass('inner_cell'); this.celltoolbar = new IPython.CellToolbar(this); inner_cell.append(this.celltoolbar.element); var input_area = $('<div/>').addClass('input_area'); this.code_mirror = CodeMirror(input_area.get(0), this.cm_config); $(this.code_mirror.getInputField()).attr("spellcheck", "false"); inner_cell.append(input_area); input.append(prompt).append(inner_cell); var widget_area = $('<div/>') .addClass('widget-area') .hide(); this.widget_area = widget_area; var widget_prompt = $('<div/>') .addClass('prompt') .appendTo(widget_area); var widget_subarea = $('<div/>') .addClass('widget-subarea') .appendTo(widget_area); this.widget_subarea = widget_subarea; var widget_clear_buton = $('<button />') .addClass('close') .html('&times;') .click(function() { widget_area.slideUp('', function(){ widget_subarea.html(''); }); }) .appendTo(widget_prompt); var output = $('<div></div>'); cell.append(input).append(widget_area).append(output); this.element = cell; this.output_area = new IPython.OutputArea(output, true); this.completer = new IPython.Completer(this); }; /** @method bind_events */ CodeCell.prototype.bind_events = function () { IPython.Cell.prototype.bind_events.apply(this); var that = this; this.element.focusout( function() { that.auto_highlight(); } ); }; CodeCell.prototype.handle_keyevent = function (editor, event) { // console.log('CM', this.mode, event.which, event.type) if (this.mode === 'command') { return true; } else if (this.mode === 'edit') { return this.handle_codemirror_keyevent(editor, event); } }; /** * This method gets called in CodeMirror's onKeyDown/onKeyPress * handlers and is used to provide custom key handling. Its return * value is used to determine if CodeMirror should ignore the event: * true = ignore, false = don't ignore. * @method handle_codemirror_keyevent */ CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) { var that = this; // whatever key is pressed, first, cancel the tooltip request before // they are sent, and remove tooltip if any, except for tab again var tooltip_closed = null; if (event.type === 'keydown' && event.which != key.TAB ) { tooltip_closed = IPython.tooltip.remove_and_cancel_tooltip(); } var cur = editor.getCursor(); if (event.keyCode === key.ENTER){ this.auto_highlight(); } if (event.keyCode === key.ENTER && (event.shiftKey || event.ctrlKey || event.altKey)) { // Always ignore shift-enter in CodeMirror as we handle it. return true; } else if (event.which === 40 && event.type === 'keypress' && IPython.tooltip.time_before_tooltip >= 0) { // triger on keypress (!) otherwise inconsistent event.which depending on plateform // browser and keyboard layout ! // Pressing '(' , request tooltip, don't forget to reappend it // The second argument says to hide the tooltip if the docstring // is actually empty IPython.tooltip.pending(that, true); } else if (event.which === key.UPARROW && event.type === 'keydown') { // If we are not at the top, let CM handle the up arrow and // prevent the global keydown handler from handling it. if (!that.at_top()) { event.stop(); return false; } else { return true; } } else if (event.which === key.ESC && event.type === 'keydown') { // First see if the tooltip is active and if so cancel it. if (tooltip_closed) { // The call to remove_and_cancel_tooltip above in L177 doesn't pass // force=true. Because of this it won't actually close the tooltip // if it is in sticky mode. Thus, we have to check again if it is open // and close it with force=true. if (!IPython.tooltip._hidden) { IPython.tooltip.remove_and_cancel_tooltip(true); } // If we closed the tooltip, don't let CM or the global handlers // handle this event. event.stop(); return true; } if (that.code_mirror.options.keyMap === "vim-insert") { // vim keyMap is active and in insert mode. In this case we leave vim // insert mode, but remain in notebook edit mode. // Let' CM handle this event and prevent global handling. event.stop(); return false; } else { // vim keyMap is not active. Leave notebook edit mode. // Don't let CM handle the event, defer to global handling. return true; } } else if (event.which === key.DOWNARROW && event.type === 'keydown') { // If we are not at the bottom, let CM handle the down arrow and // prevent the global keydown handler from handling it. if (!that.at_bottom()) { event.stop(); return false; } else { return true; } } else if (event.keyCode === key.TAB && event.type === 'keydown' && event.shiftKey) { if (editor.somethingSelected()){ var anchor = editor.getCursor("anchor"); var head = editor.getCursor("head"); if( anchor.line != head.line){ return false; } } IPython.tooltip.request(that); event.stop(); return true; } else if (event.keyCode === key.TAB && event.type == 'keydown') { // Tab completion. IPython.tooltip.remove_and_cancel_tooltip(); if (editor.somethingSelected()) { return false; } var pre_cursor = editor.getRange({line:cur.line,ch:0},cur); if (pre_cursor.trim() === "") { // Don't autocomplete if the part of the line before the cursor // is empty. In this case, let CodeMirror handle indentation. return false; } else { event.stop(); this.completer.startCompletion(); return true; } } else { // keypress/keyup also trigger on TAB press, and we don't want to // use those to disable tab completion. return false; } return false; }; // Kernel related calls. CodeCell.prototype.set_kernel = function (kernel) { this.kernel = kernel; }; /** * Execute current code cell to the kernel * @method execute */ CodeCell.prototype.execute = function () { this.output_area.clear_output(); // Clear widget area this.widget_subarea.html(''); this.widget_subarea.height(''); this.widget_area.height(''); this.widget_area.hide(); this.set_input_prompt('*'); this.element.addClass("running"); if (this.last_msg_id) { this.kernel.clear_callbacks_for_msg(this.last_msg_id); } var callbacks = this.get_callbacks(); var old_msg_id = this.last_msg_id; this.last_msg_id = this.kernel.execute(this.get_text(), callbacks, {silent: false, store_history: true}); if (old_msg_id) { delete CodeCell.msg_cells[old_msg_id]; } CodeCell.msg_cells[this.last_msg_id] = this; }; /** * Construct the default callbacks for * @method get_callbacks */ CodeCell.prototype.get_callbacks = function () { return { shell : { reply : $.proxy(this._handle_execute_reply, this), payload : { set_next_input : $.proxy(this._handle_set_next_input, this), page : $.proxy(this._open_with_pager, this) } }, iopub : { output : $.proxy(this.output_area.handle_output, this.output_area), clear_output : $.proxy(this.output_area.handle_clear_output, this.output_area), }, input : $.proxy(this._handle_input_request, this) }; }; CodeCell.prototype._open_with_pager = function (payload) { $([IPython.events]).trigger('open_with_text.Pager', payload); }; /** * @method _handle_execute_reply * @private */ CodeCell.prototype._handle_execute_reply = function (msg) { this.set_input_prompt(msg.content.execution_count); this.element.removeClass("running"); $([IPython.events]).trigger('set_dirty.Notebook', {value: true}); }; /** * @method _handle_set_next_input * @private */ CodeCell.prototype._handle_set_next_input = function (payload) { var data = {'cell': this, 'text': payload.text}; $([IPython.events]).trigger('set_next_input.Notebook', data); }; /** * @method _handle_input_request * @private */ CodeCell.prototype._handle_input_request = function (msg) { this.output_area.append_raw_input(msg); }; // Basic cell manipulation. CodeCell.prototype.select = function () { var cont = IPython.Cell.prototype.select.apply(this); if (cont) { this.code_mirror.refresh(); this.auto_highlight(); } return cont; }; CodeCell.prototype.render = function () { var cont = IPython.Cell.prototype.render.apply(this); // Always execute, even if we are already in the rendered state return cont; }; CodeCell.prototype.unrender = function () { // CodeCell is always rendered return false; }; CodeCell.prototype.edit_mode = function () { var cont = IPython.Cell.prototype.edit_mode.apply(this); if (cont) { this.focus_editor(); } return cont; } CodeCell.prototype.select_all = function () { var start = {line: 0, ch: 0}; var nlines = this.code_mirror.lineCount(); var last_line = this.code_mirror.getLine(nlines-1); var end = {line: nlines-1, ch: last_line.length}; this.code_mirror.setSelection(start, end); }; CodeCell.prototype.collapse_output = function () { this.collapsed = true; this.output_area.collapse(); }; CodeCell.prototype.expand_output = function () { this.collapsed = false; this.output_area.expand(); this.output_area.unscroll_area(); }; CodeCell.prototype.scroll_output = function () { this.output_area.expand(); this.output_area.scroll_if_long(); }; CodeCell.prototype.toggle_output = function () { this.collapsed = Boolean(1 - this.collapsed); this.output_area.toggle_output(); }; CodeCell.prototype.toggle_output_scroll = function () { this.output_area.toggle_scroll(); }; CodeCell.input_prompt_classical = function (prompt_value, lines_number) { var ns; if (prompt_value == undefined) { ns = "&nbsp;"; } else { ns = encodeURIComponent(prompt_value); } return 'In&nbsp;[' + ns + ']:'; }; CodeCell.input_prompt_continuation = function (prompt_value, lines_number) { var html = [CodeCell.input_prompt_classical(prompt_value, lines_number)]; for(var i=1; i < lines_number; i++) { html.push(['...:']); } return html.join('<br/>'); }; CodeCell.input_prompt_function = CodeCell.input_prompt_classical; CodeCell.prototype.set_input_prompt = function (number) { var nline = 1; if (this.code_mirror !== undefined) { nline = this.code_mirror.lineCount(); } this.input_prompt_number = number; var prompt_html = CodeCell.input_prompt_function(this.input_prompt_number, nline); this.element.find('div.input_prompt').html(prompt_html); }; CodeCell.prototype.clear_input = function () { this.code_mirror.setValue(''); }; CodeCell.prototype.get_text = function () { return this.code_mirror.getValue(); }; CodeCell.prototype.set_text = function (code) { return this.code_mirror.setValue(code); }; CodeCell.prototype.at_top = function () { var cursor = this.code_mirror.getCursor(); if (cursor.line === 0 && cursor.ch === 0) { return true; } else { return false; } }; CodeCell.prototype.at_bottom = function () { var cursor = this.code_mirror.getCursor(); if (cursor.line === (this.code_mirror.lineCount()-1) && cursor.ch === this.code_mirror.getLine(cursor.line).length) { return true; } else { return false; } }; CodeCell.prototype.clear_output = function (wait) { this.output_area.clear_output(wait); this.set_input_prompt(); }; // JSON serialization CodeCell.prototype.fromJSON = function (data) { IPython.Cell.prototype.fromJSON.apply(this, arguments); if (data.cell_type === 'code') { if (data.input !== undefined) { this.set_text(data.input); // make this value the starting point, so that we can only undo // to this state, instead of a blank cell this.code_mirror.clearHistory(); this.auto_highlight(); } if (data.prompt_number !== undefined) { this.set_input_prompt(data.prompt_number); } else { this.set_input_prompt(); } this.output_area.trusted = data.trusted || false; this.output_area.fromJSON(data.outputs); if (data.collapsed !== undefined) { if (data.collapsed) { this.collapse_output(); } else { this.expand_output(); } } } }; CodeCell.prototype.toJSON = function () { var data = IPython.Cell.prototype.toJSON.apply(this); data.input = this.get_text(); // is finite protect against undefined and '*' value if (isFinite(this.input_prompt_number)) { data.prompt_number = this.input_prompt_number; } var outputs = this.output_area.toJSON(); data.outputs = outputs; data.language = 'python'; data.trusted = this.output_area.trusted; data.collapsed = this.collapsed; return data; }; IPython.CodeCell = CodeCell; return IPython; }(IPython));
IPython/html/static/notebook/js/codecell.js
//---------------------------------------------------------------------------- // Copyright (C) 2008-2011 The IPython Development Team // // Distributed under the terms of the BSD License. The full license is in // the file COPYING, distributed as part of this software. //---------------------------------------------------------------------------- //============================================================================ // CodeCell //============================================================================ /** * An extendable module that provide base functionnality to create cell for notebook. * @module IPython * @namespace IPython * @submodule CodeCell */ /* local util for codemirror */ var posEq = function(a, b) {return a.line == b.line && a.ch == b.ch;}; /** * * function to delete until previous non blanking space character * or first multiple of 4 tabstop. * @private */ CodeMirror.commands.delSpaceToPrevTabStop = function(cm){ var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to); if (!posEq(from, to)) { cm.replaceRange("", from, to); return; } var cur = cm.getCursor(), line = cm.getLine(cur.line); var tabsize = cm.getOption('tabSize'); var chToPrevTabStop = cur.ch-(Math.ceil(cur.ch/tabsize)-1)*tabsize; from = {ch:cur.ch-chToPrevTabStop,line:cur.line}; var select = cm.getRange(from,cur); if( select.match(/^\ +$/) !== null){ cm.replaceRange("",from,cur); } else { cm.deleteH(-1,"char"); } }; var IPython = (function (IPython) { "use strict"; var utils = IPython.utils; var key = IPython.utils.keycodes; /** * A Cell conceived to write code. * * The kernel doesn't have to be set at creation time, in that case * it will be null and set_kernel has to be called later. * @class CodeCell * @extends IPython.Cell * * @constructor * @param {Object|null} kernel * @param {object|undefined} [options] * @param [options.cm_config] {object} config to pass to CodeMirror */ var CodeCell = function (kernel, options) { this.kernel = kernel || null; this.collapsed = false; // create all attributed in constructor function // even if null for V8 VM optimisation this.input_prompt_number = null; this.celltoolbar = null; this.output_area = null; this.last_msg_id = null; this.completer = null; var cm_overwrite_options = { onKeyEvent: $.proxy(this.handle_keyevent,this) }; options = this.mergeopt(CodeCell, options, {cm_config:cm_overwrite_options}); IPython.Cell.apply(this,[options]); // Attributes we want to override in this subclass. this.cell_type = "code"; var that = this; this.element.focusout( function() { that.auto_highlight(); } ); }; CodeCell.options_default = { cm_config : { extraKeys: { "Tab" : "indentMore", "Shift-Tab" : "indentLess", "Backspace" : "delSpaceToPrevTabStop", "Cmd-/" : "toggleComment", "Ctrl-/" : "toggleComment" }, mode: 'ipython', theme: 'ipython', matchBrackets: true } }; CodeCell.msg_cells = {}; CodeCell.prototype = new IPython.Cell(); /** * @method auto_highlight */ CodeCell.prototype.auto_highlight = function () { this._auto_highlight(IPython.config.cell_magic_highlight); }; /** @method create_element */ CodeCell.prototype.create_element = function () { IPython.Cell.prototype.create_element.apply(this, arguments); var cell = $('<div></div>').addClass('cell border-box-sizing code_cell'); cell.attr('tabindex','2'); var input = $('<div></div>').addClass('input'); var prompt = $('<div/>').addClass('prompt input_prompt'); var inner_cell = $('<div/>').addClass('inner_cell'); this.celltoolbar = new IPython.CellToolbar(this); inner_cell.append(this.celltoolbar.element); var input_area = $('<div/>').addClass('input_area'); this.code_mirror = CodeMirror(input_area.get(0), this.cm_config); $(this.code_mirror.getInputField()).attr("spellcheck", "false"); inner_cell.append(input_area); input.append(prompt).append(inner_cell); var widget_area = $('<div/>') .addClass('widget-area') .hide(); this.widget_area = widget_area; var widget_prompt = $('<div/>') .addClass('prompt') .appendTo(widget_area); var widget_subarea = $('<div/>') .addClass('widget-subarea') .appendTo(widget_area); this.widget_subarea = widget_subarea; var widget_clear_buton = $('<button />') .addClass('close') .html('&times;') .click(function() { widget_area.slideUp('', function(){ widget_subarea.html(''); }); }) .appendTo(widget_prompt); var output = $('<div></div>'); cell.append(input).append(widget_area).append(output); this.element = cell; this.output_area = new IPython.OutputArea(output, true); this.completer = new IPython.Completer(this); }; /** @method bind_events */ CodeCell.prototype.bind_events = function () { IPython.Cell.prototype.bind_events.apply(this); var that = this; this.element.focusout( function() { that.auto_highlight(); } ); }; CodeCell.prototype.handle_keyevent = function (editor, event) { // console.log('CM', this.mode, event.which, event.type) if (this.mode === 'command') { return true; } else if (this.mode === 'edit') { return this.handle_codemirror_keyevent(editor, event); } }; /** * This method gets called in CodeMirror's onKeyDown/onKeyPress * handlers and is used to provide custom key handling. Its return * value is used to determine if CodeMirror should ignore the event: * true = ignore, false = don't ignore. * @method handle_codemirror_keyevent */ CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) { var that = this; // whatever key is pressed, first, cancel the tooltip request before // they are sent, and remove tooltip if any, except for tab again var tooltip_closed = null; if (event.type === 'keydown' && event.which != key.TAB ) { tooltip_closed = IPython.tooltip.remove_and_cancel_tooltip(); } var cur = editor.getCursor(); if (event.keyCode === key.ENTER){ this.auto_highlight(); } if (event.keyCode === key.ENTER && (event.shiftKey || event.ctrlKey || event.altKey)) { // Always ignore shift-enter in CodeMirror as we handle it. return true; } else if (event.which === 40 && event.type === 'keypress' && IPython.tooltip.time_before_tooltip >= 0) { // triger on keypress (!) otherwise inconsistent event.which depending on plateform // browser and keyboard layout ! // Pressing '(' , request tooltip, don't forget to reappend it // The second argument says to hide the tooltip if the docstring // is actually empty IPython.tooltip.pending(that, true); } else if (event.which === key.UPARROW && event.type === 'keydown') { // If we are not at the top, let CM handle the up arrow and // prevent the global keydown handler from handling it. if (!that.at_top()) { event.stop(); return false; } else { return true; } } else if (event.which === key.ESC && event.type === 'keydown') { // First see if the tooltip is active and if so cancel it. if (tooltip_closed) { // The call to remove_and_cancel_tooltip above in L177 doesn't pass // force=true. Because of this it won't actually close the tooltip // if it is in sticky mode. Thus, we have to check again if it is open // and close it with force=true. if (!IPython.tooltip._hidden) { IPython.tooltip.remove_and_cancel_tooltip(true); } // If we closed the tooltip, don't let CM or the global handlers // handle this event. event.stop(); return true; } if (that.code_mirror.options.keyMap === "vim-insert") { // vim keyMap is active and in insert mode. In this case we leave vim // insert mode, but remain in notebook edit mode. // Let' CM handle this event and prevent global handling. event.stop(); return false; } else { // vim keyMap is not active. Leave notebook edit mode. // Don't let CM handle the event, defer to global handling. return true; } } else if (event.which === key.DOWNARROW && event.type === 'keydown') { // If we are not at the bottom, let CM handle the down arrow and // prevent the global keydown handler from handling it. if (!that.at_bottom()) { event.stop(); return false; } else { return true; } } else if (event.keyCode === key.TAB && event.type === 'keydown' && event.shiftKey) { if (editor.somethingSelected()){ var anchor = editor.getCursor("anchor"); var head = editor.getCursor("head"); if( anchor.line != head.line){ return false; } } IPython.tooltip.request(that); event.stop(); return true; } else if (event.keyCode === key.TAB && event.type == 'keydown') { // Tab completion. IPython.tooltip.remove_and_cancel_tooltip(); if (editor.somethingSelected()) { return false; } var pre_cursor = editor.getRange({line:cur.line,ch:0},cur); if (pre_cursor.trim() === "") { // Don't autocomplete if the part of the line before the cursor // is empty. In this case, let CodeMirror handle indentation. return false; } else { event.stop(); this.completer.startCompletion(); return true; } } else { // keypress/keyup also trigger on TAB press, and we don't want to // use those to disable tab completion. return false; } return false; }; // Kernel related calls. CodeCell.prototype.set_kernel = function (kernel) { this.kernel = kernel; }; /** * Execute current code cell to the kernel * @method execute */ CodeCell.prototype.execute = function () { this.output_area.clear_output(); // Clear widget area this.widget_subarea.html(''); this.widget_subarea.height(''); this.widget_area.height(''); this.widget_area.hide(); this.set_input_prompt('*'); this.element.addClass("running"); if (this.last_msg_id) { this.kernel.clear_callbacks_for_msg(this.last_msg_id); } var callbacks = this.get_callbacks(); var old_msg_id = this.last_msg_id; this.last_msg_id = this.kernel.execute(this.get_text(), callbacks, {silent: false, store_history: true}); if (old_msg_id) { delete CodeCell.msg_cells[old_msg_id]; } CodeCell.msg_cells[this.last_msg_id] = this; }; /** * Construct the default callbacks for * @method get_callbacks */ CodeCell.prototype.get_callbacks = function () { return { shell : { reply : $.proxy(this._handle_execute_reply, this), payload : { set_next_input : $.proxy(this._handle_set_next_input, this), page : $.proxy(this._open_with_pager, this) } }, iopub : { output : $.proxy(this.output_area.handle_output, this.output_area), clear_output : $.proxy(this.output_area.handle_clear_output, this.output_area), }, input : $.proxy(this._handle_input_request, this) }; }; CodeCell.prototype._open_with_pager = function (payload) { $([IPython.events]).trigger('open_with_text.Pager', payload); }; /** * @method _handle_execute_reply * @private */ CodeCell.prototype._handle_execute_reply = function (msg) { this.set_input_prompt(msg.content.execution_count); this.element.removeClass("running"); $([IPython.events]).trigger('set_dirty.Notebook', {value: true}); }; /** * @method _handle_set_next_input * @private */ CodeCell.prototype._handle_set_next_input = function (payload) { var data = {'cell': this, 'text': payload.text}; $([IPython.events]).trigger('set_next_input.Notebook', data); }; /** * @method _handle_input_request * @private */ CodeCell.prototype._handle_input_request = function (msg) { this.output_area.append_raw_input(msg); }; // Basic cell manipulation. CodeCell.prototype.select = function () { var cont = IPython.Cell.prototype.select.apply(this); if (cont) { this.code_mirror.refresh(); this.auto_highlight(); } return cont; }; CodeCell.prototype.render = function () { var cont = IPython.Cell.prototype.render.apply(this); // Always execute, even if we are already in the rendered state return cont; }; CodeCell.prototype.unrender = function () { // CodeCell is always rendered return false; }; CodeCell.prototype.edit_mode = function () { var cont = IPython.Cell.prototype.edit_mode.apply(this); if (cont) { this.focus_editor(); } return cont; } CodeCell.prototype.select_all = function () { var start = {line: 0, ch: 0}; var nlines = this.code_mirror.lineCount(); var last_line = this.code_mirror.getLine(nlines-1); var end = {line: nlines-1, ch: last_line.length}; this.code_mirror.setSelection(start, end); }; CodeCell.prototype.collapse_output = function () { this.collapsed = true; this.output_area.collapse(); }; CodeCell.prototype.expand_output = function () { this.collapsed = false; this.output_area.expand(); this.output_area.unscroll_area(); }; CodeCell.prototype.scroll_output = function () { this.output_area.expand(); this.output_area.scroll_if_long(); }; CodeCell.prototype.toggle_output = function () { this.collapsed = Boolean(1 - this.collapsed); this.output_area.toggle_output(); }; CodeCell.prototype.toggle_output_scroll = function () { this.output_area.toggle_scroll(); }; CodeCell.input_prompt_classical = function (prompt_value, lines_number) { var ns; if (prompt_value == undefined) { ns = "&nbsp;"; } else { ns = encodeURIComponent(prompt_value); } return 'In&nbsp;[' + ns + ']:'; }; CodeCell.input_prompt_continuation = function (prompt_value, lines_number) { var html = [CodeCell.input_prompt_classical(prompt_value, lines_number)]; for(var i=1; i < lines_number; i++) { html.push(['...:']); } return html.join('<br/>'); }; CodeCell.input_prompt_function = CodeCell.input_prompt_classical; CodeCell.prototype.set_input_prompt = function (number) { var nline = 1; if (this.code_mirror !== undefined) { nline = this.code_mirror.lineCount(); } this.input_prompt_number = number; var prompt_html = CodeCell.input_prompt_function(this.input_prompt_number, nline); this.element.find('div.input_prompt').html(prompt_html); }; CodeCell.prototype.clear_input = function () { this.code_mirror.setValue(''); }; CodeCell.prototype.get_text = function () { return this.code_mirror.getValue(); }; CodeCell.prototype.set_text = function (code) { return this.code_mirror.setValue(code); }; CodeCell.prototype.at_top = function () { var cursor = this.code_mirror.getCursor(); if (cursor.line === 0 && cursor.ch === 0) { return true; } else { return false; } }; CodeCell.prototype.at_bottom = function () { var cursor = this.code_mirror.getCursor(); if (cursor.line === (this.code_mirror.lineCount()-1) && cursor.ch === this.code_mirror.getLine(cursor.line).length) { return true; } else { return false; } }; CodeCell.prototype.clear_output = function (wait) { this.output_area.clear_output(wait); this.set_input_prompt(); }; // JSON serialization CodeCell.prototype.fromJSON = function (data) { IPython.Cell.prototype.fromJSON.apply(this, arguments); if (data.cell_type === 'code') { if (data.input !== undefined) { this.set_text(data.input); // make this value the starting point, so that we can only undo // to this state, instead of a blank cell this.code_mirror.clearHistory(); this.auto_highlight(); } if (data.prompt_number !== undefined) { this.set_input_prompt(data.prompt_number); } else { this.set_input_prompt(); } this.output_area.trusted = data.trusted || false; this.output_area.fromJSON(data.outputs); if (data.collapsed !== undefined) { if (data.collapsed) { this.collapse_output(); } else { this.expand_output(); } } } }; CodeCell.prototype.toJSON = function () { var data = IPython.Cell.prototype.toJSON.apply(this); data.input = this.get_text(); // is finite protect against undefined and '*' value if (isFinite(this.input_prompt_number)) { data.prompt_number = this.input_prompt_number; } var outputs = this.output_area.toJSON(); data.outputs = outputs; data.language = 'python'; data.trusted = this.output_area.trusted; data.collapsed = this.collapsed; return data; }; IPython.CodeCell = CodeCell; return IPython; }(IPython));
Added automatic close of Brackets.
IPython/html/static/notebook/js/codecell.js
Added automatic close of Brackets.
<ide><path>Python/html/static/notebook/js/codecell.js <ide> }, <ide> mode: 'ipython', <ide> theme: 'ipython', <del> matchBrackets: true <add> matchBrackets: true, <add> autoCloseBrackets: true <ide> } <ide> }; <ide>
JavaScript
mit
0223d493b9f562323bb0749fcbb591b4d098d205
0
vikramthyagarajan/node-excel-stream
'use strict'; const _ = require('lodash'); const Excel = require('exceljs'); const Stream = require('stream'); class ExcelWriter { /** * options currently contains all are required. Arrays can be empty- * sheets: [{ * name: String, //Name shwos up * key: String, // Identifier to push data to this sheet * headers: [{ * text: String, * key: String, * default: any * }] * }] */ constructor(options) { this.stream = Stream.Transform({ write: function(chunk, encoding, next) { this.push(chunk); next(); } }); this.options = options ? options: {sheets: []}; if (this.options.debug) { console.log('creating workbook'); } this.workbook = new Excel.stream.xlsx.WorkbookWriter({ stream: this.stream }); this.worksheets = {}; this.rowCount = 0; this.sheetRowCount = {}; this.afterInit = this._createWorkbookLayout(); } /** * Function that starts writing the sheets etc given in the options * and keeps the workbook reader from writing data */ _createWorkbookLayout() { let error; this.options.sheets.map((sheetSpec) => { if (!sheetSpec.key) { error = 'No key specified for sheet: ' + sheetSpec.name; } if (this.options.debug) { console.log('creating sheet', sheetSpec.name); } let sheet = this.workbook.addWorksheet(sheetSpec.name); let headerNames = _.map(sheetSpec.headers, 'name'); sheet.addRow(headerNames).commit(); this.worksheets[sheetSpec.key] = sheet; }); return new Promise((resolve, reject) => { if (error) { reject(this._dataError(error)); } else resolve(); }); } _dataError(message) { return new Error(message); } addData(sheetKey, dataObj) { return this.afterInit.then(() => { let sheet = this.worksheets[sheetKey]; let sheetSpec = _.find(this.options.sheets, {key: sheetKey}); let rowData = []; if (!sheet) throw this._dataError('No such sheet key: ' + sheetKey); if (!sheetSpec) throw this._dataError('No such sheet key ' + sheetKey + ' in the spec. Check options'); sheetSpec.headers.map((header, index) => { let defaultValue = ''; if (header.default !== undefined && header.default !== null) { defaultValue = header.default; } if ( dataObj.hasOwnProperty(header.key)) { rowData[index] = dataObj[header.key]; } else rowData[index] = defaultValue; }); return Promise.resolve({ sheet: sheet, data: rowData }); }) .then((rowObj) => { let sheet = rowObj.sheet; let data = rowObj.data; this.rowCount++; this.sheetRowCount[sheetKey] = this.sheetRowCount[sheetKey]? this.sheetRowCount[sheetKey] + 1: 1; return sheet.addRow(data).commit(); }); } save() { return this.afterInit.then(() => { _.map(this.worksheets, (worksheet, worksheetName) => { worksheet.commit(); }); if (this.options.debug) { console.log('written ' + this.rowCount + ' rows in total'); console.log('written rows in each sheet -', this.sheetRowCount); console.log('commiting and closing the workbook'); } return this.workbook.commit() .then(() => { return this.stream; }); }); } } module.exports = ExcelWriter;
src/excel-writer.js
'use strict'; const _ = require('lodash'); const Excel = require('exceljs'); const Stream = require('stream'); class ExcelWriter { /** * options currently contains all are required. Arrays can be empty- * sheets: [{ * name: String, //Name shwos up * key: String, // Identifier to push data to this sheet * headers: [{ * text: String, * key: String, * default: any * }] * }] */ constructor(options) { this.stream = Stream.Transform({ write: function(chunk, encoding, next) { this.push(chunk); next(); } }); this.options = options ? options: {sheets: []}; if (this.options.debug) { console.log('creating workbook'); } this.workbook = new Excel.stream.xlsx.WorkbookWriter({ stream: this.stream }); this.worksheets = {}; this.rowCount = 0; this.sheetRowCount = {}; this.afterInit = this._createWorkbookLayout(); } /** * Function that starts writing the sheets etc given in the options * and keeps the workbook reader from writing data */ _createWorkbookLayout() { let error; this.options.sheets.map((sheetSpec) => { if (!sheetSpec.key) { error = 'No key specified for sheet: ' + sheetSpec.name; } if (this.options.debug) { console.log('creating sheet', sheetSpec.name); } let sheet = this.workbook.addWorksheet(sheetSpec.name); let headerNames = _.map(sheetSpec.headers, 'name'); sheet.addRow(headerNames).commit(); this.worksheets[sheetSpec.key] = sheet; }); return new Promise((resolve, reject) => { if (error) { reject(this._dataError(error)); } else resolve(); }); } _dataError(message) { return new Error(message); } addData(sheetKey, dataObj) { return this.afterInit.then(() => { let sheet = this.worksheets[sheetKey]; let sheetSpec = _.find(this.options.sheets, {key: sheetKey}); let rowData = []; if (!sheet) throw this._dataError('No such sheet key: ' + sheetKey); if (!sheetSpec) throw this._dataError('No such sheet key ' + sheetKey + ' in the spec. Check options'); sheetSpec.headers.map((header, index) => { let defaultValue = ''; if (header.default !== undefined && header.default !== null) { defaultValue = header.default; } if ( dataObj.hasOwnProperty(header.key])) { rowData[index] = dataObj[header.key]; } else rowData[index] = defaultValue; }); return Promise.resolve({ sheet: sheet, data: rowData }); }) .then((rowObj) => { let sheet = rowObj.sheet; let data = rowObj.data; this.rowCount++; this.sheetRowCount[sheetKey] = this.sheetRowCount[sheetKey]? this.sheetRowCount[sheetKey] + 1: 1; return sheet.addRow(data).commit(); }); } save() { return this.afterInit.then(() => { _.map(this.worksheets, (worksheet, worksheetName) => { worksheet.commit(); }); if (this.options.debug) { console.log('written ' + this.rowCount + ' rows in total'); console.log('written rows in each sheet -', this.sheetRowCount); console.log('commiting and closing the workbook'); } return this.workbook.commit() .then(() => { return this.stream; }); }); } } module.exports = ExcelWriter;
Update excel-writer.js
src/excel-writer.js
Update excel-writer.js
<ide><path>rc/excel-writer.js <ide> if (header.default !== undefined && header.default !== null) { <ide> defaultValue = header.default; <ide> } <del> if ( dataObj.hasOwnProperty(header.key])) { <add> if ( dataObj.hasOwnProperty(header.key)) { <ide> rowData[index] = dataObj[header.key]; <ide> } <ide> else rowData[index] = defaultValue;
Java
apache-2.0
51759ddd4d2c895b46e4f475065959a014de0f65
0
hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak
package com.sequenceiq.datalake.service; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import com.sequenceiq.cloudbreak.api.endpoint.v4.events.EventV4Endpoint; import com.sequenceiq.cloudbreak.api.endpoint.v4.events.responses.CloudbreakEventV4Response; import com.sequenceiq.cloudbreak.auth.ThreadBasedUserCrnProvider; import com.sequenceiq.cloudbreak.auth.crn.Crn; import com.sequenceiq.cloudbreak.auth.crn.CrnParseException; import com.sequenceiq.cloudbreak.common.exception.BadRequestException; import com.sequenceiq.cloudbreak.common.exception.CloudbreakServiceException; import com.sequenceiq.cloudbreak.common.exception.NotFoundException; import com.sequenceiq.cloudbreak.structuredevent.event.CloudbreakEventService; import com.sequenceiq.cloudbreak.structuredevent.event.StructuredEventContainer; import com.sequenceiq.cloudbreak.structuredevent.event.StructuredEventType; import com.sequenceiq.cloudbreak.structuredevent.event.StructuredNotificationEvent; import com.sequenceiq.cloudbreak.structuredevent.event.cdp.CDPOperationDetails; import com.sequenceiq.cloudbreak.structuredevent.event.cdp.CDPStructuredEvent; import com.sequenceiq.cloudbreak.structuredevent.event.cdp.CDPStructuredNotificationEvent; import com.sequenceiq.cloudbreak.structuredevent.service.db.CDPStructuredEventDBService; import com.sequenceiq.datalake.entity.SdxCluster; import com.sequenceiq.datalake.repository.SdxClusterRepository; import com.sequenceiq.datalake.service.sdx.SdxService; @Service public class SdxEventsService { private static final Logger LOGGER = LoggerFactory.getLogger(SdxEventsService.class); @Inject private SdxClusterRepository sdxClusterRepository; @Inject private SdxService sdxService; @Inject private CDPStructuredEventDBService cdpStructuredEventDBService; @Inject private EventV4Endpoint eventV4Endpoint; public List<CDPStructuredEvent> getDatalakeAuditEvents(String environmentCrn, List<StructuredEventType> types) { List<CDPStructuredEvent> dlEvents; List<List<CDPStructuredEvent>> cbEvents; ensureNonDeletedNonDetachedDatalakeExists(environmentCrn); List<SdxCluster> datalakes = getDatalakes(environmentCrn); dlEvents = retrieveDatalakeServiceEvents(types, datalakes.stream().map(SdxCluster::getCrn).collect(toList())); cbEvents = datalakes.stream().map(this::retrieveCloudbreakServiceEvents).collect(toList()); List<CDPStructuredEvent> combinedEvents = new ArrayList<>(); cbEvents.forEach(combinedEvents::addAll); combinedEvents.addAll(dlEvents); if (combinedEvents.isEmpty()) { LOGGER.info("No events from datalake and cloudbreak service"); return List.of(); } return getSortedEvents(combinedEvents); } public List<CDPStructuredEvent> getPagedDatalakeAuditEvents(String environmentCrn, List<StructuredEventType> types, Integer page, Integer size) { List<CDPStructuredEvent> dlEvents; List<List<CDPStructuredEvent>> cbEvents; PageRequest pageable = PageRequest.of(page, size, Sort.by("timestamp").descending()); ensureNonDeletedNonDetachedDatalakeExists(environmentCrn); List<SdxCluster> datalakes = getDatalakes(environmentCrn); dlEvents = retrievePagableDatalakeServiceEvents(types, datalakes.stream().map(SdxCluster::getCrn).collect(toList()), pageable); cbEvents = datalakes.stream().map(datalake -> retrievePagedCloudbreakServiceEvents(datalake, page, size)).collect(toList()); List<CDPStructuredEvent> combinedEvents = new ArrayList<>(); cbEvents.forEach(combinedEvents::addAll); combinedEvents.addAll(dlEvents); if (combinedEvents.isEmpty()) { LOGGER.info("No events from datalake and cloudbreak service"); return List.of(); } return sortAndFilterBasedOnPageSize(combinedEvents, size); } private List<CDPStructuredEvent> retrievePagableDatalakeServiceEvents(List<StructuredEventType> types, List<String> datalakeCrns, PageRequest pageable) { Page<CDPStructuredEvent> pagedResponse = cdpStructuredEventDBService.getPagedEventsOfResources(types, datalakeCrns, pageable); if (pagedResponse != null && !pagedResponse.getContent().isEmpty()) { return pagedResponse.getContent(); } else { LOGGER.info("No events from datalake service"); return List.of(); } } private List<CDPStructuredEvent> retrieveDatalakeServiceEvents(List<StructuredEventType> types, List<String> datalakeCrns) { List<CDPStructuredEvent> response = cdpStructuredEventDBService.getEventsOfResources(types, datalakeCrns); if (response != null && !response.isEmpty()) { return response; } else { LOGGER.info("No events from datalake service"); return List.of(); } } private List<CDPStructuredEvent> retrievePagedCloudbreakServiceEvents(SdxCluster sdxCluster, Integer page, Integer size) { if (sdxCluster.getDeleted() != null) { return Collections.emptyList(); } try { // Get and translate the cloudbreak events List<CloudbreakEventV4Response> cloudbreakEventV4Responses = ThreadBasedUserCrnProvider.doAsInternalActor(() -> eventV4Endpoint.getPagedCloudbreakEventListByStack(sdxCluster.getName(), page, size, getAccountId(sdxCluster.getEnvCrn())) ); return cloudbreakEventV4Responses.stream().map(entry -> convert(entry, sdxCluster.getCrn())).collect(toList()); } catch (Exception exception) { LOGGER.error("Failed to retrieve paged cloudbreak service events!", exception); throw new CloudbreakServiceException("Failed to retrieve paged cloudbreak service events!", exception); } } private List<CDPStructuredEvent> retrieveCloudbreakServiceEvents(SdxCluster sdxCluster) { if (sdxCluster.getDeleted() != null) { return Collections.emptyList(); } try { // Get and translate the cloudbreak events StructuredEventContainer structuredEventContainer = ThreadBasedUserCrnProvider.doAsInternalActor(() -> eventV4Endpoint.structured(sdxCluster.getName(), getAccountId(sdxCluster.getEnvCrn())) ); return structuredEventContainer.getNotification().stream().map(entry -> convert(entry, sdxCluster.getCrn())).collect(toList()); } catch (Exception exception) { LOGGER.error("Failed to retrieve cloudbreak service events!", exception); throw new CloudbreakServiceException("Failed to retrieve cloudbreak service events!", exception); } } private List<CDPStructuredEvent> sortAndFilterBasedOnPageSize(List<CDPStructuredEvent> eventList, Integer size) { return eventList.stream().sorted(Comparator.comparingLong(f -> f.getOperation().getTimestamp())).collect(toList()) .subList(0, (eventList.size() > size) ? size : eventList.size()); } private List<CDPStructuredEvent> getSortedEvents(List<CDPStructuredEvent> eventList) { return eventList.stream().sorted(Comparator.comparingLong(f -> f.getOperation().getTimestamp())).collect(toList()); } private String getAccountId(String crnString) { try { Crn crn = Crn.safeFromString(crnString); return crn.getAccountId(); } catch (NullPointerException | CrnParseException e) { throw new BadRequestException("Cannot parse CRN to find account ID: " + crnString); } } /** * Get SdxCluster's that are or were provisioned within the environment identified by the provided CRN. * * @param environmentCrn an environment CRN * @return a list of SdxCluster's related to the environment */ private List<SdxCluster> getDatalakes(String environmentCrn) { return sdxClusterRepository.findByAccountIdAndEnvCrn(getAccountId(environmentCrn), environmentCrn); } /** * Ensure there exists SdxCluster that is provisioned within the environment that is non-deleted and non-detached. * * @param environmentCrn an environment CRN */ private void ensureNonDeletedNonDetachedDatalakeExists(String environmentCrn) { LOGGER.info("Looking for datalake associated with environment Crn {}", environmentCrn); List<SdxCluster> sdxClusters = sdxService.listSdxByEnvCrn(environmentCrn); sdxClusters.forEach(sdxCluster -> LOGGER.info("Found SDX cluster {}", sdxCluster)); if (sdxClusters.isEmpty()) { LOGGER.error("Datalake not found for environment with Crn:{}", environmentCrn); throw new NotFoundException( "No non-deleted and non-detached datalake found for environment with Crn:" + environmentCrn ); } } /** * Converts a collection of {@code CloudbreakEventV4Response} to {@code CDPStructuredEvent}. * * @param cloudbreakEventV4Response Event response from cloudbreak. * @param datalakeCrn Crn of data lake. * @return CDP structured Event */ private CDPStructuredEvent convert(CloudbreakEventV4Response cloudbreakEventV4Response, String datalakeCrn) { CDPStructuredNotificationEvent cdpStructuredNotificationEvent = new CDPStructuredNotificationEvent(); CDPOperationDetails cdpOperationDetails = new CDPOperationDetails(); cdpOperationDetails.setTimestamp(cloudbreakEventV4Response.getEventTimestamp()); cdpOperationDetails.setEventType(StructuredEventType.NOTIFICATION); cdpOperationDetails.setResourceName(cloudbreakEventV4Response.getClusterName()); cdpOperationDetails.setResourceId(cloudbreakEventV4Response.getClusterId()); cdpOperationDetails.setResourceCrn(datalakeCrn); cdpOperationDetails.setResourceEvent(cloudbreakEventV4Response.getEventType()); cdpOperationDetails.setResourceType(CloudbreakEventService.DATALAKE_RESOURCE_TYPE); cdpStructuredNotificationEvent.setOperation(cdpOperationDetails); cdpStructuredNotificationEvent.setStatusReason(cloudbreakEventV4Response.getEventMessage()); return cdpStructuredNotificationEvent; } /** * Converts a collection of {@code StructuredNotificationEvent} to {@code CDPStructuredEvent}. * * @param structuredNotificationEvent Event response from cloudbreak. * @param datalakeCrn Crn of data lake. * @return CDP structured Event */ private CDPStructuredEvent convert(StructuredNotificationEvent structuredNotificationEvent, String datalakeCrn) { CDPStructuredNotificationEvent cdpStructuredNotificationEvent = new CDPStructuredNotificationEvent(); CDPOperationDetails cdpOperationDetails = new CDPOperationDetails(); cdpOperationDetails.setTimestamp(structuredNotificationEvent.getOperation().getTimestamp()); cdpOperationDetails.setEventType(StructuredEventType.NOTIFICATION); cdpOperationDetails.setResourceName(structuredNotificationEvent.getOperation().getResourceName()); cdpOperationDetails.setResourceId(structuredNotificationEvent.getOperation().getResourceId()); cdpOperationDetails.setResourceCrn(datalakeCrn); cdpOperationDetails.setResourceEvent(structuredNotificationEvent.getOperation().getEventType().name()); cdpOperationDetails.setResourceType(CloudbreakEventService.DATALAKE_RESOURCE_TYPE); cdpStructuredNotificationEvent.setOperation(cdpOperationDetails); cdpStructuredNotificationEvent.setStatusReason(structuredNotificationEvent.getNotificationDetails().getNotification()); return cdpStructuredNotificationEvent; } }
datalake/src/main/java/com/sequenceiq/datalake/service/SdxEventsService.java
package com.sequenceiq.datalake.service; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import com.sequenceiq.cloudbreak.api.endpoint.v4.events.EventV4Endpoint; import com.sequenceiq.cloudbreak.api.endpoint.v4.events.responses.CloudbreakEventV4Response; import com.sequenceiq.cloudbreak.auth.ThreadBasedUserCrnProvider; import com.sequenceiq.cloudbreak.auth.crn.Crn; import com.sequenceiq.cloudbreak.auth.crn.CrnParseException; import com.sequenceiq.cloudbreak.common.exception.BadRequestException; import com.sequenceiq.cloudbreak.common.exception.CloudbreakServiceException; import com.sequenceiq.cloudbreak.common.exception.NotFoundException; import com.sequenceiq.cloudbreak.structuredevent.event.CloudbreakEventService; import com.sequenceiq.cloudbreak.structuredevent.event.StructuredEventContainer; import com.sequenceiq.cloudbreak.structuredevent.event.StructuredEventType; import com.sequenceiq.cloudbreak.structuredevent.event.StructuredNotificationEvent; import com.sequenceiq.cloudbreak.structuredevent.event.cdp.CDPOperationDetails; import com.sequenceiq.cloudbreak.structuredevent.event.cdp.CDPStructuredEvent; import com.sequenceiq.cloudbreak.structuredevent.event.cdp.CDPStructuredNotificationEvent; import com.sequenceiq.cloudbreak.structuredevent.service.db.CDPStructuredEventDBService; import com.sequenceiq.datalake.entity.SdxCluster; import com.sequenceiq.datalake.repository.SdxClusterRepository; import com.sequenceiq.datalake.service.sdx.SdxService; @Service public class SdxEventsService { private static final Logger LOGGER = LoggerFactory.getLogger(SdxEventsService.class); @Inject private SdxClusterRepository sdxClusterRepository; @Inject private SdxService sdxService; @Inject private CDPStructuredEventDBService cdpStructuredEventDBService; @Inject private EventV4Endpoint eventV4Endpoint; public List<CDPStructuredEvent> getDatalakeAuditEvents(String environmentCrn, List<StructuredEventType> types) { List<CDPStructuredEvent> dlEvents; List<List<CDPStructuredEvent>> cbEvents; ensureNonDeletedNonDetachedDatalakeExists(environmentCrn); List<SdxCluster> datalakes = getDatalakes(environmentCrn); dlEvents = retrieveDatalakeServiceEvents(types, datalakes.stream().map(SdxCluster::getCrn).collect(toList())); cbEvents = datalakes.stream().map(this::retrieveCloudbreakServiceEvents).collect(toList()); List<CDPStructuredEvent> combinedEvents = new ArrayList<>(); cbEvents.forEach(combinedEvents::addAll); combinedEvents.addAll(dlEvents); if (combinedEvents.isEmpty()) { LOGGER.info("No events from datalake and cloudbreak service"); return List.of(); } return getSortedEvents(combinedEvents); } public List<CDPStructuredEvent> getPagedDatalakeAuditEvents(String environmentCrn, List<StructuredEventType> types, Integer page, Integer size) { List<CDPStructuredEvent> dlEvents; List<List<CDPStructuredEvent>> cbEvents; PageRequest pageable = PageRequest.of(page, size, Sort.by("timestamp").descending()); ensureNonDeletedNonDetachedDatalakeExists(environmentCrn); List<SdxCluster> datalakes = getDatalakes(environmentCrn); dlEvents = retrievePagableDatalakeServiceEvents(types, datalakes.stream().map(SdxCluster::getCrn).collect(toList()), pageable); cbEvents = datalakes.stream().map(datalake -> retrievePagedCloudbreakServiceEvents(datalake, page, size)).collect(toList()); List<CDPStructuredEvent> combinedEvents = new ArrayList<>(); cbEvents.forEach(combinedEvents::addAll); combinedEvents.addAll(dlEvents); if (combinedEvents.isEmpty()) { LOGGER.info("No events from datalake and cloudbreak service"); return List.of(); } return sortAndFilterBasedOnPageSize(combinedEvents, size); } private List<CDPStructuredEvent> retrievePagableDatalakeServiceEvents(List<StructuredEventType> types, List<String> datalakeCrns, PageRequest pageable) { Page<CDPStructuredEvent> pagedResponse = cdpStructuredEventDBService.getPagedEventsOfResources(types, datalakeCrns, pageable); if (pagedResponse != null && !pagedResponse.getContent().isEmpty()) { return pagedResponse.getContent(); } else { LOGGER.info("No events from datalake service"); return List.of(); } } private List<CDPStructuredEvent> retrieveDatalakeServiceEvents(List<StructuredEventType> types, List<String> datalakeCrns) { List<CDPStructuredEvent> response = cdpStructuredEventDBService.getEventsOfResources(types, datalakeCrns); if (response != null && !response.isEmpty()) { return response; } else { LOGGER.info("No events from datalake service"); return List.of(); } } private List<CDPStructuredEvent> retrievePagedCloudbreakServiceEvents(SdxCluster sdxCluster, Integer page, Integer size) { try { // Get and translate the cloudbreak events List<CloudbreakEventV4Response> cloudbreakEventV4Responses = ThreadBasedUserCrnProvider.doAsInternalActor(() -> eventV4Endpoint.getPagedCloudbreakEventListByStack(sdxCluster.getName(), page, size, getAccountId(sdxCluster.getEnvCrn())) ); return cloudbreakEventV4Responses.stream().map(entry -> convert(entry, sdxCluster.getCrn())).collect(toList()); } catch (Exception exception) { LOGGER.error("Failed to retrieve paged cloudbreak service events!", exception); throw new CloudbreakServiceException("Failed to retrieve paged cloudbreak service events!", exception); } } private List<CDPStructuredEvent> retrieveCloudbreakServiceEvents(SdxCluster sdxCluster) { try { // Get and translate the cloudbreak events StructuredEventContainer structuredEventContainer = ThreadBasedUserCrnProvider.doAsInternalActor(() -> eventV4Endpoint.structured(sdxCluster.getName(), getAccountId(sdxCluster.getEnvCrn())) ); return structuredEventContainer.getNotification().stream().map(entry -> convert(entry, sdxCluster.getCrn())).collect(toList()); } catch (Exception exception) { LOGGER.error("Failed to retrieve cloudbreak service events!", exception); throw new CloudbreakServiceException("Failed to retrieve cloudbreak service events!", exception); } } private List<CDPStructuredEvent> sortAndFilterBasedOnPageSize(List<CDPStructuredEvent> eventList, Integer size) { return eventList.stream().sorted(Comparator.comparingLong(f -> f.getOperation().getTimestamp())).collect(toList()) .subList(0, (eventList.size() > size) ? size : eventList.size()); } private List<CDPStructuredEvent> getSortedEvents(List<CDPStructuredEvent> eventList) { return eventList.stream().sorted(Comparator.comparingLong(f -> f.getOperation().getTimestamp())).collect(toList()); } private String getAccountId(String crnString) { try { Crn crn = Crn.safeFromString(crnString); return crn.getAccountId(); } catch (NullPointerException | CrnParseException e) { throw new BadRequestException("Cannot parse CRN to find account ID: " + crnString); } } /** * Get SdxCluster's that are or were provisioned within the environment identified by the provided CRN. * * @param environmentCrn an environment CRN * @return a list of SdxCluster's related to the environment */ private List<SdxCluster> getDatalakes(String environmentCrn) { return sdxClusterRepository.findByAccountIdAndEnvCrn(getAccountId(environmentCrn), environmentCrn); } /** * Ensure there exists SdxCluster that is provisioned within the environment that is non-deleted and non-detached. * * @param environmentCrn an environment CRN */ private void ensureNonDeletedNonDetachedDatalakeExists(String environmentCrn) { LOGGER.info("Looking for datalake associated with environment Crn {}", environmentCrn); List<SdxCluster> sdxClusters = sdxService.listSdxByEnvCrn(environmentCrn); sdxClusters.forEach(sdxCluster -> LOGGER.info("Found SDX cluster {}", sdxCluster)); if (sdxClusters.isEmpty()) { LOGGER.error("Datalake not found for environment with Crn:{}", environmentCrn); throw new NotFoundException( "No non-deleted and non-detached datalake found for environment with Crn:" + environmentCrn ); } } /** * Converts a collection of {@code CloudbreakEventV4Response} to {@code CDPStructuredEvent}. * * @param cloudbreakEventV4Response Event response from cloudbreak. * @param datalakeCrn Crn of data lake. * @return CDP structured Event */ private CDPStructuredEvent convert(CloudbreakEventV4Response cloudbreakEventV4Response, String datalakeCrn) { CDPStructuredNotificationEvent cdpStructuredNotificationEvent = new CDPStructuredNotificationEvent(); CDPOperationDetails cdpOperationDetails = new CDPOperationDetails(); cdpOperationDetails.setTimestamp(cloudbreakEventV4Response.getEventTimestamp()); cdpOperationDetails.setEventType(StructuredEventType.NOTIFICATION); cdpOperationDetails.setResourceName(cloudbreakEventV4Response.getClusterName()); cdpOperationDetails.setResourceId(cloudbreakEventV4Response.getClusterId()); cdpOperationDetails.setResourceCrn(datalakeCrn); cdpOperationDetails.setResourceEvent(cloudbreakEventV4Response.getEventType()); cdpOperationDetails.setResourceType(CloudbreakEventService.DATALAKE_RESOURCE_TYPE); cdpStructuredNotificationEvent.setOperation(cdpOperationDetails); cdpStructuredNotificationEvent.setStatusReason(cloudbreakEventV4Response.getEventMessage()); return cdpStructuredNotificationEvent; } /** * Converts a collection of {@code StructuredNotificationEvent} to {@code CDPStructuredEvent}. * * @param structuredNotificationEvent Event response from cloudbreak. * @param datalakeCrn Crn of data lake. * @return CDP structured Event */ private CDPStructuredEvent convert(StructuredNotificationEvent structuredNotificationEvent, String datalakeCrn) { CDPStructuredNotificationEvent cdpStructuredNotificationEvent = new CDPStructuredNotificationEvent(); CDPOperationDetails cdpOperationDetails = new CDPOperationDetails(); cdpOperationDetails.setTimestamp(structuredNotificationEvent.getOperation().getTimestamp()); cdpOperationDetails.setEventType(StructuredEventType.NOTIFICATION); cdpOperationDetails.setResourceName(structuredNotificationEvent.getOperation().getResourceName()); cdpOperationDetails.setResourceId(structuredNotificationEvent.getOperation().getResourceId()); cdpOperationDetails.setResourceCrn(datalakeCrn); cdpOperationDetails.setResourceEvent(structuredNotificationEvent.getOperation().getEventType().name()); cdpOperationDetails.setResourceType(CloudbreakEventService.DATALAKE_RESOURCE_TYPE); cdpStructuredNotificationEvent.setOperation(cdpOperationDetails); cdpStructuredNotificationEvent.setStatusReason(structuredNotificationEvent.getNotificationDetails().getNotification()); return cdpStructuredNotificationEvent; } }
CB-16451: Fix issue when getting SDX events for environment with deleted datalakes.
datalake/src/main/java/com/sequenceiq/datalake/service/SdxEventsService.java
CB-16451: Fix issue when getting SDX events for environment with deleted datalakes.
<ide><path>atalake/src/main/java/com/sequenceiq/datalake/service/SdxEventsService.java <ide> import static java.util.stream.Collectors.toList; <ide> <ide> import java.util.ArrayList; <add>import java.util.Collections; <ide> import java.util.Comparator; <ide> import java.util.List; <ide> <ide> } <ide> <ide> private List<CDPStructuredEvent> retrievePagedCloudbreakServiceEvents(SdxCluster sdxCluster, Integer page, Integer size) { <add> if (sdxCluster.getDeleted() != null) { <add> return Collections.emptyList(); <add> } <add> <ide> try { <ide> // Get and translate the cloudbreak events <ide> List<CloudbreakEventV4Response> cloudbreakEventV4Responses = ThreadBasedUserCrnProvider.doAsInternalActor(() -> <ide> } <ide> <ide> private List<CDPStructuredEvent> retrieveCloudbreakServiceEvents(SdxCluster sdxCluster) { <add> if (sdxCluster.getDeleted() != null) { <add> return Collections.emptyList(); <add> } <add> <ide> try { <ide> // Get and translate the cloudbreak events <ide> StructuredEventContainer structuredEventContainer = ThreadBasedUserCrnProvider.doAsInternalActor(() ->
Java
unlicense
43e758c382a5df6fa3d518627b78c7b315a10574
0
skeeto/NativeGuide,skeeto/NativeGuide
package com.nullprogram.guide; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Field; import java.util.logging.Logger; /** * This is a utility class for loading native libraries from the * classpath. The JVM is unable to load libraries from inside .jar * files. This class works around that by copying them out to a * temporary directory on the filesystem. * * When using this utility class, imagine you are registering all * versions of your native library. It would be used like this, for * example, * * <pre> * NativeGuide.prepare(Arch.LINUX_32, "/x86/libexample.so"); * NativeGuide.prepare(Arch.LINUX_64, "/amd64/libexample.so"); * NativeGuide.prepare(Arch.WINDOWS_32, "/x86/example.dll"); * NativeGuide.prepare(Arch.WINDOWS_64, "/amd64/example.dll"); * </pre> * * Libraries not used by the running architecture will be ignored. */ public final class NativeGuide { /** Name of this class's logger. */ private static final String LOGGER_NAME = NativeGuide.class.getName(); /** This class's logger. */ private static final Logger LOG = Logger.getLogger(LOGGER_NAME); /** Size of the copying buffer. */ private static final int BUFFER_SIZE = 1024 * 10; /** A 32-bit architecture. */ private static final int BITS_32 = 32; /** A 64-bit architecture. */ private static final int BITS_64 = 64; /** Path separator for this operating system. */ private static final String SEP = System.getProperty("path.separator"); /** The determined architecture. */ private static Arch architecture = Arch.UNKNOWN; /** Base temporary path for native libaries. */ private static String base = null; /** Hidden constructor. */ private NativeGuide() { } /** * Prepare the temporary directory and add it to java.library.path. * @throws IOException if the directory could not be prepared */ private static synchronized void setUpTemp() throws IOException { if (base != null) { /* The work has already been done. */ return; } int suffix = (int) (Math.random() * Integer.MAX_VALUE); File dir = new File(System.getProperty("java.io.tmpdir"), "NativeGuide-" + System.getProperty("user.name") + "-" + suffix); if (dir.exists() && !dir.isDirectory()) { throw new IOException("NativeGuide directory is a file"); } else if (!dir.exists()) { dir.mkdir(); dir.deleteOnExit(); } /* Insert this path in java.library.path. */ String orig = System.getProperty("java.library.path"); base = dir.getAbsolutePath(); System.setProperty("java.library.path", orig + SEP + base); /* Force reread of java.library.path property. */ try { Field sysPath = ClassLoader.class.getDeclaredField("sys_paths"); sysPath.setAccessible(true); sysPath.set(null, null); } catch (Exception e) { LOG.severe("Could not modify java.library.path property."); } } /** * Load a native library resource by first copying it to a * temporary directory. If the given architecture doesn't match * the running system, nothing is done. * @param arch the architecture of the library * @param path the path to the library as a resource * @throws IOException if the library doesn't exist or could not load */ public static void load(final Arch arch, final String path) throws IOException { if (isArchitecture(arch)) { setUpTemp(); System.load(copyToTemp(path).getAbsolutePath()); } } /** * Prepare a native library to be loaded by copying it to a * temporary directory. The directory is automatically added to * java.library.path. If the given architecture doesn't match the * running system, nothing is done. * @param arch the architecture of the library * @param path the path to the library as a resource * @throws IOException if the library does not exist */ public static void prepare(final Arch arch, final String path) throws IOException { if (isArchitecture(arch)) { setUpTemp(); copyToTemp(path); } } /** * Load a native library resource by first copying it to a * temporary directory. If the given architecture doesn't match * the running system, nothing is done. This method allows for * non-predefined architectures. * @param arch the os.arch string * @param os the os.name string * @param path the path to the library as a resource * @throws IOException if the library doesn't exist or could not load */ public static void load(final String arch, final String os, final String path) throws IOException { if (isArchitecture(arch, os)) { setUpTemp(); System.load(copyToTemp(path).getAbsolutePath()); } } /** * Prepare a native library to be loaded by copying it to a * temporary directory. The directory is automatically added to * java.library.path. If the given architecture doesn't match the * running system, nothing is done. This method allows for * non-predefined architectures. * @param arch the os.arch string * @param os the os.name string * @param path the path to the library as a resource * @throws IOException if the library does not exist */ public static void prepare(final String arch, final String os, final String path) throws IOException { if (isArchitecture(arch, os)) { setUpTemp(); copyToTemp(path); } } /** * Copy the given resource to the temporary directory. * @param path the path of the resource * @return the file to which it was copied * @throws IOException if copying failed or the resource was not found */ private static File copyToTemp(final String path) throws IOException { String name = new File(path).getName(); File file = new File(base, name); boolean exists = file.isFile(); InputStream in = NativeGuide.class.getResourceAsStream(path); in = new BufferedInputStream(in); in.available(); // Triggers exception if resource doesn't exist OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); byte[] bytes = new byte[BUFFER_SIZE]; for (int n = 0; n != -1; n = in.read(bytes)) { out.write(bytes, 0, n); } } catch (IOException e) { /* On some OSes, we might get an IOException trying to * overwrite an existing library file if there is * another process using it. If this happens, ignore * errors. */ if (!exists) { throw e; } LOG.info(name + " exists but could not be written."); } finally { if (out != null) { try { out.close(); } catch (IOException ioe) { /* Ignore. */ LOG.warning(name + " could not close file."); } } } /* Try to clean up after the JVM exits. */ file.deleteOnExit(); return file; } /** * Determine if the given architecture is the one being run. * @param arch the architecture being queried * @return true if the given architecture matches */ private static boolean isArchitecture(final Arch arch) { if (architecture == Arch.UNKNOWN) { architecture = getArchitecture(); } return architecture == arch; } /** * Determine if the given architecture is the one being run. * @param arch the os.arch string * @param os the os.name string * @return true if the given architecture matches */ private static boolean isArchitecture(final String arch, final String os) { return System.getProperty("os.arch").equals(arch) && System.getProperty("os.name").equals(os); } /** * Determine the JVM's native architecture. * @return the native architecture code */ public static Arch getArchitecture() { int bits = BITS_32; if (System.getProperty("os.arch").indexOf("64") != -1) { bits = BITS_64; } String os = System.getProperty("os.name"); if (os.startsWith("Windows")) { if (bits == BITS_32) { return Arch.WINDOWS_32; } else { return Arch.WINDOWS_64; } } else if (os.equals("Linux")) { if (bits == BITS_32) { return Arch.LINUX_32; } else { return Arch.LINUX_64; } } else if (os.equals("Mac OS X")) { if (bits == BITS_32) { return Arch.MAC_32; } else { return Arch.MAC_64; } } else { return Arch.UNKNOWN; } } }
src/com/nullprogram/guide/NativeGuide.java
package com.nullprogram.guide; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Field; import java.util.logging.Logger; /** * This is a utility class for loading native libraries from the * classpath. The JVM is unable to load libraries from inside .jar * files. This class works around that by copying them out to a * temporary directory on the filesystem. * * When using this utility class, imagine you are registering all * versions of your native library. It would be used like this, for * example, * * <pre> * NativeGuide.prepare(Arch.LINUX_32, "/x86/libexample.so"); * NativeGuide.prepare(Arch.LINUX_64, "/amd64/libexample.so"); * NativeGuide.prepare(Arch.WINDOWS_32, "/x86/example.dll"); * NativeGuide.prepare(Arch.WINDOWS_64, "/amd64/example.dll"); * </pre> * * Libraries not used by the running architecture will be ignored. */ public final class NativeGuide { /** Name of this class's logger. */ private static final String LOGGER_NAME = NativeGuide.class.getName(); /** This class's logger. */ private static final Logger LOG = Logger.getLogger(LOGGER_NAME); /** Size of the copying buffer. */ private static final int BUFFER_SIZE = 1024 * 10; /** A 32-bit architecture. */ private static final int BITS_32 = 32; /** A 64-bit architecture. */ private static final int BITS_64 = 64; /** Path separator for this operating system. */ private static final String SEP = System.getProperty("path.separator"); /** The determined architecture. */ private static Arch architecture = Arch.UNKNOWN; /** Base temporary path for native libaries. */ private static String base = null; /** Hidden constructor. */ private NativeGuide() { } /** * Prepare the temporary directory and add it to java.library.path. * @throws IOException if the directory could not be prepared */ private static synchronized void setUpTemp() throws IOException { if (base != null) { /* The work has already been done. */ return; } File dir = new File(System.getProperty("java.io.tmpdir"), "NativeGuide-" + System.getProperty("user.name")); if (dir.exists() && !dir.isDirectory()) { throw new IOException("NativeGuide directory is a file"); } else if (!dir.exists()) { dir.mkdir(); } /* Insert this path in java.library.path. */ String orig = System.getProperty("java.library.path"); base = dir.getAbsolutePath(); System.setProperty("java.library.path", orig + SEP + base); /* Force reread of java.library.path property. */ try { Field sysPath = ClassLoader.class.getDeclaredField("sys_paths"); sysPath.setAccessible(true); sysPath.set(null, null); } catch (Exception e) { LOG.severe("Could not modify java.library.path property."); } } /** * Load a native library resource by first copying it to a * temporary directory. If the given architecture doesn't match * the running system, nothing is done. * @param arch the architecture of the library * @param path the path to the library as a resource * @throws IOException if the library doesn't exist or could not load */ public static void load(final Arch arch, final String path) throws IOException { if (isArchitecture(arch)) { setUpTemp(); System.load(copyToTemp(path).getAbsolutePath()); } } /** * Prepare a native library to be loaded by copying it to a * temporary directory. The directory is automatically added to * java.library.path. If the given architecture doesn't match the * running system, nothing is done. * @param arch the architecture of the library * @param path the path to the library as a resource * @throws IOException if the library does not exist */ public static void prepare(final Arch arch, final String path) throws IOException { if (isArchitecture(arch)) { setUpTemp(); copyToTemp(path); } } /** * Load a native library resource by first copying it to a * temporary directory. If the given architecture doesn't match * the running system, nothing is done. This method allows for * non-predefined architectures. * @param arch the os.arch string * @param os the os.name string * @param path the path to the library as a resource * @throws IOException if the library doesn't exist or could not load */ public static void load(final String arch, final String os, final String path) throws IOException { if (isArchitecture(arch, os)) { setUpTemp(); System.load(copyToTemp(path).getAbsolutePath()); } } /** * Prepare a native library to be loaded by copying it to a * temporary directory. The directory is automatically added to * java.library.path. If the given architecture doesn't match the * running system, nothing is done. This method allows for * non-predefined architectures. * @param arch the os.arch string * @param os the os.name string * @param path the path to the library as a resource * @throws IOException if the library does not exist */ public static void prepare(final String arch, final String os, final String path) throws IOException { if (isArchitecture(arch, os)) { setUpTemp(); copyToTemp(path); } } /** * Copy the given resource to the temporary directory. * @param path the path of the resource * @return the file to which it was copied * @throws IOException if copying failed or the resource was not found */ private static File copyToTemp(final String path) throws IOException { String name = new File(path).getName(); File file = new File(base, name); boolean exists = file.isFile(); InputStream in = NativeGuide.class.getResourceAsStream(path); in = new BufferedInputStream(in); in.available(); // Triggers exception if resource doesn't exist OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); byte[] bytes = new byte[BUFFER_SIZE]; for (int n = 0; n != -1; n = in.read(bytes)) { out.write(bytes, 0, n); } } catch (IOException e) { /* On some OSes, we might get an IOException trying to * overwrite an existing library file if there is * another process using it. If this happens, ignore * errors. */ if (!exists) { throw e; } LOG.info(name + " exists but could not be written."); } finally { if (out != null) { try { out.close(); } catch (IOException ioe) { /* Ignore. */ LOG.warning(name + " could not close file."); } } } /* Try to clean up after the JVM exits. */ file.deleteOnExit(); return file; } /** * Determine if the given architecture is the one being run. * @param arch the architecture being queried * @return true if the given architecture matches */ private static boolean isArchitecture(final Arch arch) { if (architecture == Arch.UNKNOWN) { architecture = getArchitecture(); } return architecture == arch; } /** * Determine if the given architecture is the one being run. * @param arch the os.arch string * @param os the os.name string * @return true if the given architecture matches */ private static boolean isArchitecture(final String arch, final String os) { return System.getProperty("os.arch").equals(arch) && System.getProperty("os.name").equals(os); } /** * Determine the JVM's native architecture. * @return the native architecture code */ public static Arch getArchitecture() { int bits = BITS_32; if (System.getProperty("os.arch").indexOf("64") != -1) { bits = BITS_64; } String os = System.getProperty("os.name"); if (os.startsWith("Windows")) { if (bits == BITS_32) { return Arch.WINDOWS_32; } else { return Arch.WINDOWS_64; } } else if (os.equals("Linux")) { if (bits == BITS_32) { return Arch.LINUX_32; } else { return Arch.LINUX_64; } } else if (os.equals("Mac OS X")) { if (bits == BITS_32) { return Arch.MAC_32; } else { return Arch.MAC_64; } } else { return Arch.UNKNOWN; } } }
Add a random suffix to avoid clobbering.
src/com/nullprogram/guide/NativeGuide.java
Add a random suffix to avoid clobbering.
<ide><path>rc/com/nullprogram/guide/NativeGuide.java <ide> /* The work has already been done. */ <ide> return; <ide> } <add> int suffix = (int) (Math.random() * Integer.MAX_VALUE); <ide> File dir = new File(System.getProperty("java.io.tmpdir"), <del> "NativeGuide-" + System.getProperty("user.name")); <add> "NativeGuide-" + System.getProperty("user.name") + <add> "-" + suffix); <ide> if (dir.exists() && !dir.isDirectory()) { <ide> throw new IOException("NativeGuide directory is a file"); <ide> } else if (!dir.exists()) { <ide> dir.mkdir(); <add> dir.deleteOnExit(); <ide> } <ide> <ide> /* Insert this path in java.library.path. */
Java
apache-2.0
0c0cafa413b77d5f217b3814d51932a23d01803c
0
bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.execution; import com.facebook.presto.metadata.Split; import com.facebook.presto.spi.HostAddress; import com.facebook.presto.spi.Node; import com.facebook.presto.spi.NodeManager; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.AbstractIterator; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import com.google.common.net.InetAddresses; import org.weakref.jmx.Managed; import javax.inject.Inject; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import static com.facebook.presto.spi.StandardErrorCode.NO_NODES_AVAILABLE; import static com.facebook.presto.util.Failures.checkCondition; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public class NodeScheduler { private final String coordinatorNodeId; private final NodeManager nodeManager; private final AtomicLong scheduleLocal = new AtomicLong(); private final AtomicLong scheduleRack = new AtomicLong(); private final AtomicLong scheduleRandom = new AtomicLong(); private final int minCandidates; private final boolean locationAwareScheduling; private final boolean includeCoordinator; private final int maxSplitsPerNode; private final int maxSplitsPerNodePerTaskWhenFull; private final NodeTaskMap nodeTaskMap; private final boolean doubleScheduling; @Inject public NodeScheduler(NodeManager nodeManager, NodeSchedulerConfig config, NodeTaskMap nodeTaskMap) { this.nodeManager = nodeManager; this.coordinatorNodeId = nodeManager.getCurrentNode().getNodeIdentifier(); this.minCandidates = config.getMinCandidates(); this.locationAwareScheduling = config.isLocationAwareSchedulingEnabled(); this.includeCoordinator = config.isIncludeCoordinator(); this.doubleScheduling = config.isMultipleTasksPerNodeEnabled(); this.maxSplitsPerNode = config.getMaxSplitsPerNode(); this.maxSplitsPerNodePerTaskWhenFull = config.getMaxPendingSplitsPerNodePerTask(); this.nodeTaskMap = checkNotNull(nodeTaskMap, "nodeTaskMap is null"); checkArgument(maxSplitsPerNode > maxSplitsPerNodePerTaskWhenFull, "maxSplitsPerNode must be > maxSplitsPerNodePerTaskWhenFull"); } @Managed public long getScheduleLocal() { return scheduleLocal.get(); } @Managed public long getScheduleRack() { return scheduleRack.get(); } @Managed public long getScheduleRandom() { return scheduleRandom.get(); } @Managed public void reset() { scheduleLocal.set(0); scheduleRack.set(0); scheduleRandom.set(0); } public NodeSelector createNodeSelector(String dataSourceName) { // this supplier is thread-safe. TODO: this logic should probably move to the scheduler since the choice of which node to run in should be // done as close to when the the split is about to be scheduled Supplier<NodeMap> nodeMap = Suppliers.memoizeWithExpiration(() -> { ImmutableSetMultimap.Builder<HostAddress, Node> byHostAndPort = ImmutableSetMultimap.builder(); ImmutableSetMultimap.Builder<InetAddress, Node> byHost = ImmutableSetMultimap.builder(); ImmutableSetMultimap.Builder<Rack, Node> byRack = ImmutableSetMultimap.builder(); Set<Node> nodes; if (dataSourceName != null) { nodes = nodeManager.getActiveDatasourceNodes(dataSourceName); } else { nodes = nodeManager.getActiveNodes(); } for (Node node : nodes) { try { byHostAndPort.put(node.getHostAndPort(), node); InetAddress host = InetAddress.getByName(node.getHttpUri().getHost()); byHost.put(host, node); byRack.put(Rack.of(host), node); } catch (UnknownHostException e) { // ignore } } return new NodeMap(byHostAndPort.build(), byHost.build(), byRack.build()); }, 5, TimeUnit.SECONDS); return new NodeSelector(nodeMap); } public class NodeSelector { private final AtomicReference<Supplier<NodeMap>> nodeMap; public NodeSelector(Supplier<NodeMap> nodeMap) { this.nodeMap = new AtomicReference<>(nodeMap); } public void lockDownNodes() { nodeMap.set(Suppliers.ofInstance(nodeMap.get().get())); } public List<Node> allNodes() { return ImmutableList.copyOf(nodeMap.get().get().getNodesByHostAndPort().values()); } public Node selectCurrentNode() { // TODO: this is a hack to force scheduling on the coordinator return nodeManager.getCurrentNode(); } public List<Node> selectRandomNodes(int limit) { checkArgument(limit > 0, "limit must be at least 1"); List<Node> selected = new ArrayList<>(limit); for (Node node : lazyShuffle(nodeMap.get().get().getNodesByHostAndPort().values())) { if (includeCoordinator || !coordinatorNodeId.equals(node.getNodeIdentifier())) { selected.add(node); } if (selected.size() >= limit) { break; } } if (doubleScheduling && !selected.isEmpty()) { // Cycle the nodes until we reach the limit int uniqueNodes = selected.size(); int i = 0; while (selected.size() < limit) { if (i >= uniqueNodes) { i = 0; } selected.add(selected.get(i)); i++; } } return selected; } /** * Identifies the nodes for running the specified splits. * * @param splits the splits that need to be assigned to nodes * @return a multimap from node to splits only for splits for which we could identify a node to schedule on. * If we cannot find an assignment for a split, it is not included in the map. */ public Multimap<Node, Split> computeAssignments(Set<Split> splits, Iterable<RemoteTask> existingTasks) { Multimap<Node, Split> assignment = HashMultimap.create(); Map<Node, Integer> assignmentCount = new HashMap<>(); // maintain a temporary local cache of partitioned splits on the node Map<Node, Integer> splitCountByNode = new HashMap<>(); Map<String, Integer> queuedSplitCountByNode = new HashMap<>(); for (RemoteTask task : existingTasks) { String nodeId = task.getNodeId(); queuedSplitCountByNode.put(nodeId, queuedSplitCountByNode.getOrDefault(nodeId, 0) + task.getQueuedPartitionedSplitCount()); } for (Split split : splits) { List<Node> candidateNodes; if (locationAwareScheduling || !split.isRemotelyAccessible()) { candidateNodes = selectCandidateNodes(nodeMap.get().get(), split); } else { candidateNodes = selectRandomNodes(minCandidates); } checkCondition(!candidateNodes.isEmpty(), NO_NODES_AVAILABLE, "No nodes available to run query"); // compute and cache number of splits currently assigned to each node candidateNodes.stream() .filter(node -> !splitCountByNode.containsKey(node)) .forEach(node -> splitCountByNode.put(node, nodeTaskMap.getPartitionedSplitsOnNode(node))); Node chosenNode = null; int min = Integer.MAX_VALUE; for (Node node : candidateNodes) { int totalSplitCount = assignmentCount.getOrDefault(node, 0) + splitCountByNode.get(node); if (totalSplitCount < min && totalSplitCount < maxSplitsPerNode) { chosenNode = node; min = totalSplitCount; } } if (chosenNode == null) { for (Node node : candidateNodes) { int assignedSplitCount = assignmentCount.getOrDefault(node, 0); int queuedSplitCount = queuedSplitCountByNode.getOrDefault(node.getNodeIdentifier(), 0); int totalSplitCount = queuedSplitCount + assignedSplitCount; if (totalSplitCount < min && totalSplitCount < maxSplitsPerNodePerTaskWhenFull) { chosenNode = node; min = totalSplitCount; } } } if (chosenNode != null) { assignment.put(chosenNode, split); assignmentCount.put(chosenNode, assignmentCount.getOrDefault(chosenNode, 0) + 1); } } return assignment; } private List<Node> selectCandidateNodes(NodeMap nodeMap, Split split) { Set<Node> chosen = new LinkedHashSet<>(minCandidates); String coordinatorIdentifier = nodeManager.getCurrentNode().getNodeIdentifier(); // first look for nodes that match the hint for (HostAddress hint : split.getAddresses()) { nodeMap.getNodesByHostAndPort().get(hint).stream() .filter(node -> includeCoordinator || !coordinatorIdentifier.equals(node.getNodeIdentifier())) .filter(chosen::add) .forEach(node -> scheduleLocal.incrementAndGet()); InetAddress address; try { address = hint.toInetAddress(); } catch (UnknownHostException e) { // skip addresses that don't resolve continue; } // consider a split with a host hint without a port as being accessible // by all nodes in that host if (!hint.hasPort() || split.isRemotelyAccessible()) { nodeMap.getNodesByHost().get(address).stream() .filter(node -> includeCoordinator || !coordinatorIdentifier.equals(node.getNodeIdentifier())) .filter(chosen::add) .forEach(node -> scheduleLocal.incrementAndGet()); } } // add nodes in same rack, if below the minimum count if (split.isRemotelyAccessible() && chosen.size() < minCandidates) { for (HostAddress hint : split.getAddresses()) { InetAddress address; try { address = hint.toInetAddress(); } catch (UnknownHostException e) { // skip addresses that don't resolve continue; } for (Node node : nodeMap.getNodesByRack().get(Rack.of(address))) { if (includeCoordinator || !coordinatorIdentifier.equals(node.getNodeIdentifier())) { if (chosen.add(node)) { scheduleRack.incrementAndGet(); } if (chosen.size() == minCandidates) { break; } } } if (chosen.size() == minCandidates) { break; } } } // add some random nodes if below the minimum count if (split.isRemotelyAccessible()) { if (chosen.size() < minCandidates) { for (Node node : lazyShuffle(nodeMap.getNodesByHost().values())) { if (includeCoordinator || !coordinatorIdentifier.equals(node.getNodeIdentifier())) { if (chosen.add(node)) { scheduleRandom.incrementAndGet(); } if (chosen.size() == minCandidates) { break; } } } } } // if the chosen set is empty and the hint includes the coordinator, // force pick the coordinator if (chosen.isEmpty() && !includeCoordinator) { HostAddress coordinatorHostAddress = nodeManager.getCurrentNode().getHostAndPort(); if (split.getAddresses().stream().anyMatch(host -> canSplitRunOnHost(split, coordinatorHostAddress, host))) { chosen.add(nodeManager.getCurrentNode()); } } return ImmutableList.copyOf(chosen); } private boolean canSplitRunOnHost(Split split, HostAddress coordinatorHost, HostAddress host) { // Exact match of the coordinator if (host.equals(coordinatorHost)) { return true; } // If the split is remotely accessible or the split location doesn't specify a port, // we can ignore the coordinator's port and match just the ip address return (!host.hasPort() || split.isRemotelyAccessible()) && host.getHostText().equals(coordinatorHost.getHostText()); } } private static <T> Iterable<T> lazyShuffle(Iterable<T> iterable) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new AbstractIterator<T>() { private final List<T> list = Lists.newArrayList(iterable); private int limit = list.size(); @Override protected T computeNext() { if (limit == 0) { return endOfData(); } int position = ThreadLocalRandom.current().nextInt(limit); T result = list.get(position); list.set(position, list.get(limit - 1)); limit--; return result; } }; } }; } private static class NodeMap { private final SetMultimap<HostAddress, Node> nodesByHostAndPort; private final SetMultimap<InetAddress, Node> nodesByHost; private final SetMultimap<Rack, Node> nodesByRack; public NodeMap(SetMultimap<HostAddress, Node> nodesByHostAndPort, SetMultimap<InetAddress, Node> nodesByHost, SetMultimap<Rack, Node> nodesByRack) { this.nodesByHostAndPort = nodesByHostAndPort; this.nodesByHost = nodesByHost; this.nodesByRack = nodesByRack; } private SetMultimap<HostAddress, Node> getNodesByHostAndPort() { return nodesByHostAndPort; } public SetMultimap<InetAddress, Node> getNodesByHost() { return nodesByHost; } public SetMultimap<Rack, Node> getNodesByRack() { return nodesByRack; } } private static class Rack { private final int id; public static Rack of(InetAddress address) { // TODO: we need a plugin for this int id = InetAddresses.coerceToInteger(address) & 0xFF_FF_FF_00; return new Rack(id); } private Rack(int id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Rack rack = (Rack) o; if (id != rack.id) { return false; } return true; } @Override public int hashCode() { return id; } } }
presto-main/src/main/java/com/facebook/presto/execution/NodeScheduler.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.execution; import com.facebook.presto.metadata.Split; import com.facebook.presto.spi.HostAddress; import com.facebook.presto.spi.Node; import com.facebook.presto.spi.NodeManager; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.AbstractIterator; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import com.google.common.net.InetAddresses; import org.weakref.jmx.Managed; import javax.inject.Inject; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import static com.facebook.presto.spi.StandardErrorCode.NO_NODES_AVAILABLE; import static com.facebook.presto.util.Failures.checkCondition; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public class NodeScheduler { private final String coordinatorNodeId; private final NodeManager nodeManager; private final AtomicLong scheduleLocal = new AtomicLong(); private final AtomicLong scheduleRack = new AtomicLong(); private final AtomicLong scheduleRandom = new AtomicLong(); private final int minCandidates; private final boolean locationAwareScheduling; private final boolean includeCoordinator; private final int maxSplitsPerNode; private final int maxSplitsPerNodePerTaskWhenFull; private final NodeTaskMap nodeTaskMap; private final boolean doubleScheduling; @Inject public NodeScheduler(NodeManager nodeManager, NodeSchedulerConfig config, NodeTaskMap nodeTaskMap) { this.nodeManager = nodeManager; this.coordinatorNodeId = nodeManager.getCurrentNode().getNodeIdentifier(); this.minCandidates = config.getMinCandidates(); this.locationAwareScheduling = config.isLocationAwareSchedulingEnabled(); this.includeCoordinator = config.isIncludeCoordinator(); this.doubleScheduling = config.isMultipleTasksPerNodeEnabled(); this.maxSplitsPerNode = config.getMaxSplitsPerNode(); this.maxSplitsPerNodePerTaskWhenFull = config.getMaxPendingSplitsPerNodePerTask(); this.nodeTaskMap = checkNotNull(nodeTaskMap, "nodeTaskMap is null"); checkArgument(maxSplitsPerNode > maxSplitsPerNodePerTaskWhenFull, "maxSplitsPerNode must be > maxSplitsPerNodePerTaskWhenFull"); } @Managed public long getScheduleLocal() { return scheduleLocal.get(); } @Managed public long getScheduleRack() { return scheduleRack.get(); } @Managed public long getScheduleRandom() { return scheduleRandom.get(); } @Managed public void reset() { scheduleLocal.set(0); scheduleRack.set(0); scheduleRandom.set(0); } public NodeSelector createNodeSelector(String dataSourceName) { // this supplier is thread-safe. TODO: this logic should probably move to the scheduler since the choice of which node to run in should be // done as close to when the the split is about to be scheduled Supplier<NodeMap> nodeMap = Suppliers.memoizeWithExpiration(() -> { ImmutableSetMultimap.Builder<HostAddress, Node> byHostAndPort = ImmutableSetMultimap.builder(); ImmutableSetMultimap.Builder<InetAddress, Node> byHost = ImmutableSetMultimap.builder(); ImmutableSetMultimap.Builder<Rack, Node> byRack = ImmutableSetMultimap.builder(); Set<Node> nodes; if (dataSourceName != null) { nodes = nodeManager.getActiveDatasourceNodes(dataSourceName); } else { nodes = nodeManager.getActiveNodes(); } for (Node node : nodes) { try { byHostAndPort.put(node.getHostAndPort(), node); InetAddress host = InetAddress.getByName(node.getHttpUri().getHost()); byHost.put(host, node); byRack.put(Rack.of(host), node); } catch (UnknownHostException e) { // ignore } } return new NodeMap(byHostAndPort.build(), byHost.build(), byRack.build()); }, 5, TimeUnit.SECONDS); return new NodeSelector(nodeMap); } public class NodeSelector { private final AtomicReference<Supplier<NodeMap>> nodeMap; public NodeSelector(Supplier<NodeMap> nodeMap) { this.nodeMap = new AtomicReference<>(nodeMap); } public void lockDownNodes() { nodeMap.set(Suppliers.ofInstance(nodeMap.get().get())); } public List<Node> allNodes() { return ImmutableList.copyOf(nodeMap.get().get().getNodesByHostAndPort().values()); } public Node selectCurrentNode() { // TODO: this is a hack to force scheduling on the coordinator return nodeManager.getCurrentNode(); } public List<Node> selectRandomNodes(int limit) { checkArgument(limit > 0, "limit must be at least 1"); List<Node> selected = new ArrayList<>(limit); for (Node node : lazyShuffle(nodeMap.get().get().getNodesByHostAndPort().values())) { if (includeCoordinator || !coordinatorNodeId.equals(node.getNodeIdentifier())) { selected.add(node); } if (selected.size() >= limit) { break; } } if (doubleScheduling && !selected.isEmpty()) { // Cycle the nodes until we reach the limit int uniqueNodes = selected.size(); int i = 0; while (selected.size() < limit) { if (i >= uniqueNodes) { i = 0; } selected.add(selected.get(i)); i++; } } return selected; } /** * Identifies the nodes for running the specified splits. * * @param splits the splits that need to be assigned to nodes * @return a multimap from node to splits only for splits for which we could identify a node to schedule on. * If we cannot find an assignment for a split, it is not included in the map. */ public Multimap<Node, Split> computeAssignments(Set<Split> splits, Iterable<RemoteTask> existingTasks) { Multimap<Node, Split> assignment = HashMultimap.create(); Map<Node, Integer> assignmentCount = new HashMap<>(); // maintain a temporary local cache of partitioned splits on the node Map<Node, Integer> splitCountByNode = new HashMap<>(); Map<String, Integer> queuedSplitCountByNode = new HashMap<>(); for (RemoteTask task : existingTasks) { String nodeId = task.getNodeId(); if (!queuedSplitCountByNode.containsKey(nodeId)) { queuedSplitCountByNode.put(nodeId, 0); } queuedSplitCountByNode.put(nodeId, queuedSplitCountByNode.get(nodeId) + task.getQueuedPartitionedSplitCount()); } for (Split split : splits) { List<Node> candidateNodes; if (locationAwareScheduling || !split.isRemotelyAccessible()) { candidateNodes = selectCandidateNodes(nodeMap.get().get(), split); } else { candidateNodes = selectRandomNodes(minCandidates); } checkCondition(!candidateNodes.isEmpty(), NO_NODES_AVAILABLE, "No nodes available to run query"); // compute and cache number of splits currently assigned to each node candidateNodes.stream() .filter(node -> !splitCountByNode.containsKey(node)) .forEach(node -> splitCountByNode.put(node, nodeTaskMap.getPartitionedSplitsOnNode(node))); Node chosenNode = null; int min = Integer.MAX_VALUE; for (Node node : candidateNodes) { int assignedSplitCount = assignmentCount.containsKey(node) ? assignmentCount.get(node) : 0; int totalSplitCount = assignedSplitCount + splitCountByNode.get(node); if (totalSplitCount < min && totalSplitCount < maxSplitsPerNode) { chosenNode = node; min = totalSplitCount; } } if (chosenNode == null) { for (Node node : candidateNodes) { int assignedSplitCount = assignmentCount.containsKey(node) ? assignmentCount.get(node) : 0; int queuedSplitCount = 0; if (queuedSplitCountByNode.containsKey(node.getNodeIdentifier())) { queuedSplitCount = queuedSplitCountByNode.get(node.getNodeIdentifier()); } int totalSplitCount = queuedSplitCount + assignedSplitCount; if (totalSplitCount < min && totalSplitCount < maxSplitsPerNodePerTaskWhenFull) { chosenNode = node; min = totalSplitCount; } } } if (chosenNode != null) { assignment.put(chosenNode, split); int count = assignmentCount.containsKey(chosenNode) ? assignmentCount.get(chosenNode) : 0; assignmentCount.put(chosenNode, count + 1); } } return assignment; } private List<Node> selectCandidateNodes(NodeMap nodeMap, Split split) { Set<Node> chosen = new LinkedHashSet<>(minCandidates); String coordinatorIdentifier = nodeManager.getCurrentNode().getNodeIdentifier(); // first look for nodes that match the hint for (HostAddress hint : split.getAddresses()) { nodeMap.getNodesByHostAndPort().get(hint).stream() .filter(node -> includeCoordinator || !coordinatorIdentifier.equals(node.getNodeIdentifier())) .filter(chosen::add) .forEach(node -> scheduleLocal.incrementAndGet()); InetAddress address; try { address = hint.toInetAddress(); } catch (UnknownHostException e) { // skip addresses that don't resolve continue; } // consider a split with a host hint without a port as being accessible // by all nodes in that host if (!hint.hasPort() || split.isRemotelyAccessible()) { nodeMap.getNodesByHost().get(address).stream() .filter(node -> includeCoordinator || !coordinatorIdentifier.equals(node.getNodeIdentifier())) .filter(chosen::add) .forEach(node -> scheduleLocal.incrementAndGet()); } } // add nodes in same rack, if below the minimum count if (split.isRemotelyAccessible() && chosen.size() < minCandidates) { for (HostAddress hint : split.getAddresses()) { InetAddress address; try { address = hint.toInetAddress(); } catch (UnknownHostException e) { // skip addresses that don't resolve continue; } for (Node node : nodeMap.getNodesByRack().get(Rack.of(address))) { if (includeCoordinator || !coordinatorIdentifier.equals(node.getNodeIdentifier())) { if (chosen.add(node)) { scheduleRack.incrementAndGet(); } if (chosen.size() == minCandidates) { break; } } } if (chosen.size() == minCandidates) { break; } } } // add some random nodes if below the minimum count if (split.isRemotelyAccessible()) { if (chosen.size() < minCandidates) { for (Node node : lazyShuffle(nodeMap.getNodesByHost().values())) { if (includeCoordinator || !coordinatorIdentifier.equals(node.getNodeIdentifier())) { if (chosen.add(node)) { scheduleRandom.incrementAndGet(); } if (chosen.size() == minCandidates) { break; } } } } } // if the chosen set is empty and the hint includes the coordinator, // force pick the coordinator if (chosen.isEmpty() && !includeCoordinator) { HostAddress coordinatorHostAddress = nodeManager.getCurrentNode().getHostAndPort(); if (split.getAddresses().stream().anyMatch(host -> canSplitRunOnHost(split, coordinatorHostAddress, host))) { chosen.add(nodeManager.getCurrentNode()); } } return ImmutableList.copyOf(chosen); } private boolean canSplitRunOnHost(Split split, HostAddress coordinatorHost, HostAddress host) { // Exact match of the coordinator if (host.equals(coordinatorHost)) { return true; } // If the split is remotely accessible or the split location doesn't specify a port, // we can ignore the coordinator's port and match just the ip address return (!host.hasPort() || split.isRemotelyAccessible()) && host.getHostText().equals(coordinatorHost.getHostText()); } } private static <T> Iterable<T> lazyShuffle(Iterable<T> iterable) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new AbstractIterator<T>() { private final List<T> list = Lists.newArrayList(iterable); private int limit = list.size(); @Override protected T computeNext() { if (limit == 0) { return endOfData(); } int position = ThreadLocalRandom.current().nextInt(limit); T result = list.get(position); list.set(position, list.get(limit - 1)); limit--; return result; } }; } }; } private static class NodeMap { private final SetMultimap<HostAddress, Node> nodesByHostAndPort; private final SetMultimap<InetAddress, Node> nodesByHost; private final SetMultimap<Rack, Node> nodesByRack; public NodeMap(SetMultimap<HostAddress, Node> nodesByHostAndPort, SetMultimap<InetAddress, Node> nodesByHost, SetMultimap<Rack, Node> nodesByRack) { this.nodesByHostAndPort = nodesByHostAndPort; this.nodesByHost = nodesByHost; this.nodesByRack = nodesByRack; } private SetMultimap<HostAddress, Node> getNodesByHostAndPort() { return nodesByHostAndPort; } public SetMultimap<InetAddress, Node> getNodesByHost() { return nodesByHost; } public SetMultimap<Rack, Node> getNodesByRack() { return nodesByRack; } } private static class Rack { private final int id; public static Rack of(InetAddress address) { // TODO: we need a plugin for this int id = InetAddresses.coerceToInteger(address) & 0xFF_FF_FF_00; return new Rack(id); } private Rack(int id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Rack rack = (Rack) o; if (id != rack.id) { return false; } return true; } @Override public int hashCode() { return id; } } }
Use Map.getOrDefault
presto-main/src/main/java/com/facebook/presto/execution/NodeScheduler.java
Use Map.getOrDefault
<ide><path>resto-main/src/main/java/com/facebook/presto/execution/NodeScheduler.java <ide> <ide> for (RemoteTask task : existingTasks) { <ide> String nodeId = task.getNodeId(); <del> if (!queuedSplitCountByNode.containsKey(nodeId)) { <del> queuedSplitCountByNode.put(nodeId, 0); <del> } <del> queuedSplitCountByNode.put(nodeId, queuedSplitCountByNode.get(nodeId) + task.getQueuedPartitionedSplitCount()); <add> queuedSplitCountByNode.put(nodeId, queuedSplitCountByNode.getOrDefault(nodeId, 0) + task.getQueuedPartitionedSplitCount()); <ide> } <ide> <ide> for (Split split : splits) { <ide> int min = Integer.MAX_VALUE; <ide> <ide> for (Node node : candidateNodes) { <del> int assignedSplitCount = assignmentCount.containsKey(node) ? assignmentCount.get(node) : 0; <del> int totalSplitCount = assignedSplitCount + splitCountByNode.get(node); <add> int totalSplitCount = assignmentCount.getOrDefault(node, 0) + splitCountByNode.get(node); <ide> <ide> if (totalSplitCount < min && totalSplitCount < maxSplitsPerNode) { <ide> chosenNode = node; <ide> } <ide> if (chosenNode == null) { <ide> for (Node node : candidateNodes) { <del> int assignedSplitCount = assignmentCount.containsKey(node) ? assignmentCount.get(node) : 0; <del> int queuedSplitCount = 0; <del> if (queuedSplitCountByNode.containsKey(node.getNodeIdentifier())) { <del> queuedSplitCount = queuedSplitCountByNode.get(node.getNodeIdentifier()); <del> } <add> int assignedSplitCount = assignmentCount.getOrDefault(node, 0); <add> int queuedSplitCount = queuedSplitCountByNode.getOrDefault(node.getNodeIdentifier(), 0); <ide> int totalSplitCount = queuedSplitCount + assignedSplitCount; <ide> if (totalSplitCount < min && totalSplitCount < maxSplitsPerNodePerTaskWhenFull) { <ide> chosenNode = node; <ide> } <ide> if (chosenNode != null) { <ide> assignment.put(chosenNode, split); <del> int count = assignmentCount.containsKey(chosenNode) ? assignmentCount.get(chosenNode) : 0; <del> assignmentCount.put(chosenNode, count + 1); <add> assignmentCount.put(chosenNode, assignmentCount.getOrDefault(chosenNode, 0) + 1); <ide> } <ide> } <ide> return assignment;
JavaScript
apache-2.0
25266b135ea7e2e806e7c849a0e814a2a174ade7
0
atodorov-storpool/one,OpenNebula/one,baby-gnu/one,hsanjuan/one,ohamada/one,baby-gnu/one,juanmont/one,unistra/one,ohamada/one,alvarosimon/one,ohamada/one,abelCoronado93/one,alvarosimon/one,abelCoronado93/one,baby-gnu/one,ohamada/one,fasrc/one,juanmont/one,goberle/one,fasrc/one,goberle/one,OpenNebula/one,hsanjuan/one,juanmont/one,fasrc/one,atodorov-storpool/one,unistra/one,unistra/one,baby-gnu/one,juanmont/one,goberle/one,juanmont/one,hsanjuan/one,alvarosimon/one,unistra/one,juanmont/one,OpenNebula/one,fasrc/one,goberle/one,abelCoronado93/one,unistra/one,hsanjuan/one,OpenNebula/one,fasrc/one,abelCoronado93/one,OpenNebula/one,goberle/one,atodorov-storpool/one,atodorov-storpool/one,alvarosimon/one,alvarosimon/one,unistra/one,abelCoronado93/one,atodorov-storpool/one,abelCoronado93/one,juanmont/one,OpenNebula/one,abelCoronado93/one,goberle/one,ohamada/one,juanmont/one,baby-gnu/one,unistra/one,ohamada/one,OpenNebula/one,atodorov-storpool/one,atodorov-storpool/one,hsanjuan/one,alvarosimon/one,atodorov-storpool/one,baby-gnu/one,baby-gnu/one,fasrc/one,alvarosimon/one,OpenNebula/one,goberle/one,hsanjuan/one,ohamada/one,ohamada/one,atodorov-storpool/one,baby-gnu/one,hsanjuan/one,hsanjuan/one,fasrc/one,alvarosimon/one,goberle/one,fasrc/one,OpenNebula/one,juanmont/one,abelCoronado93/one,unistra/one
define(function(require) { /* DEPENDENCIES */ require('foundation.tab'); var BaseFormPanel = require('utils/form-panels/form-panel'); var Sunstone = require('sunstone'); var Locale = require('utils/locale'); var Tips = require('utils/tips'); var TemplateUtils = require('utils/template-utils'); var WizardFields = require('utils/wizard-fields'); var VNetsTable = require('tabs/vnets-tab/datatable'); var Utils = require('../utils/common'); /* TEMPLATES */ var TemplateWizardHTML = require('hbs!./create/wizard'); var TemplateAdvancedHTML = require('hbs!./create/advanced'); /* CONSTANTS */ var FORM_PANEL_ID = require('./create/formPanelId'); var TAB_ID = require('../tabId'); /* CONSTRUCTOR */ function FormPanel() { this.formPanelId = FORM_PANEL_ID; this.tabId = TAB_ID; this.actions = { 'create': { 'title': Locale.tr("Create Security Group"), 'buttonText': Locale.tr("Create"), 'resetButton': true }, 'update': { 'title': Locale.tr("Update Security Group"), 'buttonText': Locale.tr("Update"), 'resetButton': false } }; BaseFormPanel.call(this); } FormPanel.FORM_PANEL_ID = FORM_PANEL_ID; FormPanel.prototype = Object.create(BaseFormPanel.prototype); FormPanel.prototype.constructor = FormPanel; FormPanel.prototype.htmlWizard = _htmlWizard; FormPanel.prototype.htmlAdvanced = _htmlAdvanced; FormPanel.prototype.submitWizard = _submitWizard; FormPanel.prototype.submitAdvanced = _submitAdvanced; FormPanel.prototype.onShow = _onShow; FormPanel.prototype.fill = _fill; FormPanel.prototype.setup = _setup; return FormPanel; /* FUNCTION DEFINITIONS */ function _htmlWizard() { var opts = { info: false, select: true }; this.vnetsTable = new VNetsTable("new_sg_rule", opts); return TemplateWizardHTML({ 'formPanelId': this.formPanelId, 'vnetsTableHTML': this.vnetsTable.dataTableHTML }); } function _htmlAdvanced() { return TemplateAdvancedHTML({formPanelId: this.formPanelId}); } function _setup(context) { var that = this; context.foundation('abide', 'reflow'); context.off("change", '.security_group_rule_protocol'); context.on("change", '.security_group_rule_protocol', function(){ $('.range_row', context).hide(); $('.range_row input', context).removeAttr('required'); $('.icmp_type_wrapper', context).hide(); switch ($(this).val()) { case "TCP": case "UDP": $('.range_row', context).show(); $(".range_row select", context).trigger("change"); break; case "ICMP": $('.icmp_type_wrapper', context).show(); break; case "IPSEC": case "ALL": break; } }); context.off("change", '.security_group_rule_network_sel'); context.on("change", '.security_group_rule_network_sel', function(){ $('.security_group_rule_network',context).hide(); $('div.security_group_rule_network input',context).removeAttr('required'); that.vnetsTable.idInput().removeAttr("required"); $('.vnet_select',context).hide(); switch ($(this).val()) { case "ANY": break; case "NETWORK": $('.security_group_rule_network',context).show(); $('div.security_group_rule_network input',context).attr('required', ''); break; case "VNET": $('.vnet_select',context).show(); that.vnetsTable.idInput().attr("required", ""); that.vnetsTable.refreshResourceTableSelect(); break; } }); context.off("change", '.security_group_rule_range_sel'); context.on("change", '.security_group_rule_range_sel', function(){ switch ($(this).val()) { case "ALL": $('.security_group_rule_range', context).hide(); $(".security_group_rule_range input", context).removeAttr('required'); break; case "RANGE": $('.security_group_rule_range', context).show(); $(".security_group_rule_range input", context).attr('required', ''); break; } }); $('#rules_form_wizard',context).off('invalid.fndtn.abide'); $('#rules_form_wizard',context).off('valid.fndtn.abide'); $('#rules_form_wizard',context).on('invalid.fndtn.abide', function () { }).on('valid.fndtn.abide', function() { var rule = {}; rule["PROTOCOL"] = $(".security_group_rule_protocol", context).val(); rule["RULE_TYPE"] = $(".security_group_rule_type", context).val(); switch ($('.security_group_rule_range_sel', context).val()) { case "ALL": break; case "RANGE": rule["RANGE"] = $(".security_group_rule_range input", context).val(); break; } switch ($('.security_group_rule_network_sel', context).val()) { case "ANY": break; case "NETWORK": rule["IP"] = $('#security_group_rule_first_ip', context).val(); rule["SIZE"] = $('#security_group_rule_size', context).val(); break; case "VNET": rule["NETWORK_ID"] = that.vnetsTable.retrieveResourceTableSelect(); break; } if (rule["PROTOCOL"] == "ICMP" ){ var icmp_type_val = $(".security_group_rule_icmp_type", context).val(); if (icmp_type_val != ""){ rule["ICMP_TYPE"] = icmp_type_val; } } var text = Utils.sgRuleToSt(rule); $(".security_group_rules tbody", context).append( '<tr>\ <td>'+text.PROTOCOL+'</td>\ <td>'+text.RULE_TYPE+'</td>\ <td>'+text.RANGE+'</td>\ <td>'+text.NETWORK+'</td>\ <td>'+text.ICMP_TYPE+'</td>\ <td>\ <a href="#"><i class="fa fa-times-circle remove-tab"></i></a>\ </td>\ </tr>'); // Add data to tr element $(".security_group_rules tbody", context).children("tr").last().data("rule", rule); // Reset new rule fields $('#new_rule_wizard select option', context).prop('selected', function() { return this.defaultSelected; }); $('#new_rule_wizard select', context).trigger("change"); $('#new_rule_wizard input', context).val(""); that.vnetsTable.resetResourceTableSelect(); }); context.off("click", ".security_group_rules i.remove-tab"); context.on("click", ".security_group_rules i.remove-tab", function(){ var tr = $(this).closest('tr'); tr.remove(); }); context.foundation(); this.vnetsTable.initialize(); Tips.setup(); $('#new_rule_wizard select', context).trigger("change"); return false; } function _submitWizard(context) { var name = $('#security_group_name', context).val(); var description = $('#security_group_description', context).val(); var rules = []; $(".security_group_rules tbody tr").each(function(){ rules.push($(this).data("rule")); }); var security_group_json = { "NAME" : name, "DESCRIPTION": description, "RULE" : rules }; if (this.action == "create") { security_group_json = { "security_group" : security_group_json }; Sunstone.runAction("SecurityGroup.create",security_group_json); return false; } else if (this.action == "update") { delete security_group_json["NAME"]; Sunstone.runAction( "SecurityGroup.update", this.resourceId, TemplateUtils.templateToString(security_group_json)); return false; } } function _submitAdvanced(context) { if (this.action == "create") { var template = $('textarea#template', context).val(); var security_group_json = {security_group: {security_group_raw: template}}; Sunstone.runAction("SecurityGroup.create",security_group_json); return false; } else if (this.action == "update") { var template_raw = $('textarea#template', context).val(); Sunstone.runAction("SecurityGroup.update", this.resourceId, template_raw); return false; } } function _onShow(context) { this.vnetsTable.refreshResourceTableSelect(); } function _fill(context, element) { var that = this; this.resourceId = element.ID; // Populates the Avanced mode Tab $('#template', context).val(TemplateUtils.templateToString(element.TEMPLATE).replace(/^[\r\n]+$/g, "")); $('#security_group_name',context).val( TemplateUtils.escapeDoubleQuotes(TemplateUtils.htmlDecode( element.NAME ))). prop("disabled", true); $('#security_group_description', context).val( TemplateUtils.escapeDoubleQuotes(TemplateUtils.htmlDecode( element.TEMPLATE.DESCRIPTION )) ); var rules = element.TEMPLATE.RULE; if (!rules) { //empty rules = []; } else if (rules.constructor != Array) { //>1 rule rules = [rules]; } $.each(rules, function(){ var text = Utils.sgRuleToSt(this); $(".security_group_rules tbody", context).append( '<tr>\ <td>'+text.PROTOCOL+'</td>\ <td>'+text.RULE_TYPE+'</td>\ <td>'+text.RANGE+'</td>\ <td>'+text.NETWORK+'</td>\ <td>'+text.ICMP_TYPE+'</td>\ <td>\ <a href="#"><i class="fa fa-times-circle remove-tab"></i></a>\ </td>\ </tr>'); $(".security_group_rules tbody", context).children("tr").last().data("rule", this); }); } });
src/sunstone/public/app/tabs/secgroups-tab/form-panels/create.js
define(function(require) { /* DEPENDENCIES */ require('foundation.tab'); var BaseFormPanel = require('utils/form-panels/form-panel'); var Sunstone = require('sunstone'); var Locale = require('utils/locale'); var Tips = require('utils/tips'); var TemplateUtils = require('utils/template-utils'); var WizardFields = require('utils/wizard-fields'); var VNetsTable = require('tabs/vnets-tab/datatable'); var Utils = require('../utils/common'); /* TEMPLATES */ var TemplateWizardHTML = require('hbs!./create/wizard'); var TemplateAdvancedHTML = require('hbs!./create/advanced'); /* CONSTANTS */ var FORM_PANEL_ID = require('./create/formPanelId'); var TAB_ID = require('../tabId'); /* CONSTRUCTOR */ function FormPanel() { this.formPanelId = FORM_PANEL_ID; this.tabId = TAB_ID; this.actions = { 'create': { 'title': Locale.tr("Create Security Group"), 'buttonText': Locale.tr("Create"), 'resetButton': true }, 'update': { 'title': Locale.tr("Update Security Group"), 'buttonText': Locale.tr("Update"), 'resetButton': false } }; BaseFormPanel.call(this); } FormPanel.FORM_PANEL_ID = FORM_PANEL_ID; FormPanel.prototype = Object.create(BaseFormPanel.prototype); FormPanel.prototype.constructor = FormPanel; FormPanel.prototype.htmlWizard = _htmlWizard; FormPanel.prototype.htmlAdvanced = _htmlAdvanced; FormPanel.prototype.submitWizard = _submitWizard; FormPanel.prototype.submitAdvanced = _submitAdvanced; FormPanel.prototype.onShow = _onShow; FormPanel.prototype.fill = _fill; FormPanel.prototype.setup = _setup; return FormPanel; /* FUNCTION DEFINITIONS */ function _htmlWizard() { var opts = { info: false, select: true }; this.vnetsTable = new VNetsTable("new_sg_rule", opts); return TemplateWizardHTML({ 'formPanelId': this.formPanelId, 'vnetsTableHTML': this.vnetsTable.dataTableHTML }); } function _htmlAdvanced() { return TemplateAdvancedHTML({formPanelId: this.formPanelId}); } function _setup(context) { var that = this; context.off("change", '.security_group_rule_protocol'); context.on("change", '.security_group_rule_protocol', function(){ $('.range_row', context).hide(); $('.range_row input', context).removeAttr('required'); $('.icmp_type_wrapper', context).hide(); switch ($(this).val()) { case "TCP": case "UDP": $('.range_row', context).show(); $(".range_row select", context).trigger("change"); break; case "ICMP": $('.icmp_type_wrapper', context).show(); break; case "IPSEC": case "ALL": break; } }); context.off("change", '.security_group_rule_network_sel'); context.on("change", '.security_group_rule_network_sel', function(){ $('.security_group_rule_network',context).hide(); $('div.security_group_rule_network input',context).removeAttr('required'); that.vnetsTable.idInput().removeAttr("required"); $('.vnet_select',context).hide(); switch ($(this).val()) { case "ANY": break; case "NETWORK": $('.security_group_rule_network',context).show(); $('div.security_group_rule_network input',context).attr('required', ''); break; case "VNET": $('.vnet_select',context).show(); that.vnetsTable.idInput().attr("required", ""); that.vnetsTable.refreshResourceTableSelect(); break; } }); context.off("change", '.security_group_rule_range_sel'); context.on("change", '.security_group_rule_range_sel', function(){ switch ($(this).val()) { case "ALL": $('.security_group_rule_range', context).hide(); $(".security_group_rule_range input", context).removeAttr('required'); break; case "RANGE": $('.security_group_rule_range', context).show(); $(".security_group_rule_range input", context).attr('required', ''); break; } }); $('#rules_form_wizard',context).off('invalid'); $('#rules_form_wizard',context).off('valid'); $('#rules_form_wizard',context).on('invalid', function () { }).on('valid', function() { var rule = {}; rule["PROTOCOL"] = $(".security_group_rule_protocol", context).val(); rule["RULE_TYPE"] = $(".security_group_rule_type", context).val(); switch ($('.security_group_rule_range_sel', context).val()) { case "ALL": break; case "RANGE": rule["RANGE"] = $(".security_group_rule_range input", context).val(); break; } switch ($('.security_group_rule_network_sel', context).val()) { case "ANY": break; case "NETWORK": rule["IP"] = $('#security_group_rule_first_ip', context).val(); rule["SIZE"] = $('#security_group_rule_size', context).val(); break; case "VNET": rule["NETWORK_ID"] = that.vnetsTable.retrieveResourceTableSelect(); break; } if (rule["PROTOCOL"] == "ICMP" ){ var icmp_type_val = $(".security_group_rule_icmp_type", context).val(); if (icmp_type_val != ""){ rule["ICMP_TYPE"] = icmp_type_val; } } var text = Utils.sgRuleToSt(rule); $(".security_group_rules tbody", context).append( '<tr>\ <td>'+text.PROTOCOL+'</td>\ <td>'+text.RULE_TYPE+'</td>\ <td>'+text.RANGE+'</td>\ <td>'+text.NETWORK+'</td>\ <td>'+text.ICMP_TYPE+'</td>\ <td>\ <a href="#"><i class="fa fa-times-circle remove-tab"></i></a>\ </td>\ </tr>'); // Add data to tr element $(".security_group_rules tbody", context).children("tr").last().data("rule", rule); // Reset new rule fields $('#new_rule_wizard select option', context).prop('selected', function() { return this.defaultSelected; }); $('#new_rule_wizard select', context).trigger("change"); $('#new_rule_wizard input', context).val(""); that.vnetsTable.resetResourceTableSelect(); }); context.off("click", ".security_group_rules i.remove-tab"); context.on("click", ".security_group_rules i.remove-tab", function(){ var tr = $(this).closest('tr'); tr.remove(); }); context.foundation(); this.vnetsTable.initialize(); Tips.setup(); $('#new_rule_wizard select', context).trigger("change"); return false; } function _submitWizard(context) { var name = $('#security_group_name', context).val(); var description = $('#security_group_description', context).val(); var rules = []; $(".security_group_rules tbody tr").each(function(){ rules.push($(this).data("rule")); }); var security_group_json = { "NAME" : name, "DESCRIPTION": description, "RULE" : rules }; if (this.action == "create") { security_group_json = { "security_group" : security_group_json }; Sunstone.runAction("SecurityGroup.create",security_group_json); return false; } else if (this.action == "update") { delete security_group_json["NAME"]; Sunstone.runAction( "SecurityGroup.update", this.resourceId, TemplateUtils.templateToString(security_group_json)); return false; } } function _submitAdvanced(context) { if (this.action == "create") { var template = $('textarea#template', context).val(); var security_group_json = {security_group: {security_group_raw: template}}; Sunstone.runAction("SecurityGroup.create",security_group_json); return false; } else if (this.action == "update") { var template_raw = $('textarea#template', context).val(); Sunstone.runAction("SecurityGroup.update", this.resourceId, template_raw); return false; } } function _onShow(context) { this.vnetsTable.refreshResourceTableSelect(); } function _fill(context, element) { var that = this; this.resourceId = element.ID; // Populates the Avanced mode Tab $('#template', context).val(TemplateUtils.templateToString(element.TEMPLATE).replace(/^[\r\n]+$/g, "")); $('#security_group_name',context).val( TemplateUtils.escapeDoubleQuotes(TemplateUtils.htmlDecode( element.NAME ))). prop("disabled", true); $('#security_group_description', context).val( TemplateUtils.escapeDoubleQuotes(TemplateUtils.htmlDecode( element.TEMPLATE.DESCRIPTION )) ); var rules = element.TEMPLATE.RULE; if (!rules) { //empty rules = []; } else if (rules.constructor != Array) { //>1 rule rules = [rules]; } $.each(rules, function(){ var text = Utils.sgRuleToSt(this); $(".security_group_rules tbody", context).append( '<tr>\ <td>'+text.PROTOCOL+'</td>\ <td>'+text.RULE_TYPE+'</td>\ <td>'+text.RANGE+'</td>\ <td>'+text.NETWORK+'</td>\ <td>'+text.ICMP_TYPE+'</td>\ <td>\ <a href="#"><i class="fa fa-times-circle remove-tab"></i></a>\ </td>\ </tr>'); $(".security_group_rules tbody", context).children("tr").last().data("rule", this); }); } });
bug #3945: Fix abide event for add rule form
src/sunstone/public/app/tabs/secgroups-tab/form-panels/create.js
bug #3945: Fix abide event for add rule form
<ide><path>rc/sunstone/public/app/tabs/secgroups-tab/form-panels/create.js <ide> <ide> function _setup(context) { <ide> var that = this; <add> context.foundation('abide', 'reflow'); <ide> <ide> context.off("change", '.security_group_rule_protocol'); <ide> context.on("change", '.security_group_rule_protocol', function(){ <ide> } <ide> }); <ide> <del> $('#rules_form_wizard',context).off('invalid'); <del> $('#rules_form_wizard',context).off('valid'); <del> <del> $('#rules_form_wizard',context).on('invalid', function () { <del> <del> }).on('valid', function() { <add> $('#rules_form_wizard',context).off('invalid.fndtn.abide'); <add> $('#rules_form_wizard',context).off('valid.fndtn.abide'); <add> <add> $('#rules_form_wizard',context).on('invalid.fndtn.abide', function () { <add> <add> }).on('valid.fndtn.abide', function() { <ide> var rule = {}; <ide> <ide> rule["PROTOCOL"] = $(".security_group_rule_protocol", context).val();
Java
apache-2.0
bf7d79fdaf8a72d8039da66d1c1cf7e3b5acd2a8
0
signed/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,semonte/intellij-community,apixandru/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ibinti/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,youdonghai/intellij-community,da1z/intellij-community,semonte/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,signed/intellij-community,apixandru/intellij-community,ibinti/intellij-community,semonte/intellij-community,vvv1559/intellij-community,signed/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,signed/intellij-community,allotria/intellij-community,youdonghai/intellij-community,signed/intellij-community,allotria/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,da1z/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,da1z/intellij-community,signed/intellij-community,FHannes/intellij-community,apixandru/intellij-community,xfournet/intellij-community,semonte/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,apixandru/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,apixandru/intellij-community,da1z/intellij-community,da1z/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,FHannes/intellij-community,apixandru/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,da1z/intellij-community,FHannes/intellij-community,asedunov/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,xfournet/intellij-community,FHannes/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ibinti/intellij-community,allotria/intellij-community,signed/intellij-community,allotria/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,signed/intellij-community,signed/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,asedunov/intellij-community,asedunov/intellij-community,ibinti/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,da1z/intellij-community,apixandru/intellij-community,da1z/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,asedunov/intellij-community,signed/intellij-community,signed/intellij-community,apixandru/intellij-community,xfournet/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,FHannes/intellij-community,da1z/intellij-community,FHannes/intellij-community,da1z/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,da1z/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.fileTemplates.actions; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.codeInsight.template.impl.TemplateImpl; import com.intellij.ide.IdeView; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.fileTemplates.ui.CreateFromTemplateDialog; import com.intellij.ide.util.DirectoryChooserUtil; import com.intellij.ide.util.EditorHelper; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.HashSet; import java.util.Set; public abstract class CreateFromTemplateActionBase extends AnAction { public CreateFromTemplateActionBase(final String title, final String description, final Icon icon) { super (title,description,icon); } @Override public final void actionPerformed(AnActionEvent e){ DataContext dataContext = e.getDataContext(); IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext); if (view == null) { return; } PsiDirectory dir = getTargetDirectory(dataContext, view); if (dir == null) return; Project project = dir.getProject(); FileTemplate selectedTemplate = getTemplate(project, dir); if (selectedTemplate != null){ AnAction action = getReplacedAction(selectedTemplate); if (action != null) { action.actionPerformed(e); } else { FileTemplateManager.getInstance(project).addRecentName(selectedTemplate.getName()); final AttributesDefaults defaults = getAttributesDefaults(dataContext); final CreateFromTemplateDialog dialog = new CreateFromTemplateDialog(project, dir, selectedTemplate, defaults, defaults != null ? defaults.getDefaultProperties() : null); PsiElement createdElement = dialog.create(); if (createdElement != null) { elementCreated(dialog, createdElement); view.selectElement(createdElement); if (selectedTemplate.isLiveTemplateEnabled() && createdElement instanceof PsiFile) { startLiveTemplate((PsiFile)createdElement); } } } } } public static void startLiveTemplate(PsiFile file) { Project project = file.getProject(); final Editor editor = EditorHelper.openInEditor(file); if (editor == null) return; final TemplateImpl template = new TemplateImpl("", file.getText(), ""); template.setInline(true); int count = template.getSegmentsCount(); if (count == 0) return; Set<String> variables = new HashSet<>(); for (int i = 0; i < count; i++) { variables.add(template.getSegmentName(i)); } variables.removeAll(TemplateImpl.INTERNAL_VARS_SET); for (String variable : variables) { template.addVariable(variable, null, "\"" + variable + "\"", true); } WriteCommandAction.runWriteCommandAction(project, () -> editor.getDocument().setText(template.getTemplateText())); //ensure caret at the start of the template editor.getCaretModel().moveToOffset(0); TemplateManager.getInstance(project).startTemplate(editor, template); } @Nullable protected PsiDirectory getTargetDirectory(DataContext dataContext, IdeView view) { return DirectoryChooserUtil.getOrChooseDirectory(view); } @Nullable protected AnAction getReplacedAction(final FileTemplate selectedTemplate) { return null; } protected abstract FileTemplate getTemplate(final Project project, final PsiDirectory dir); @Nullable public AttributesDefaults getAttributesDefaults(DataContext dataContext) { return null; } protected void elementCreated(CreateFromTemplateDialog dialog, PsiElement createdElement) { } }
platform/lang-impl/src/com/intellij/ide/fileTemplates/actions/CreateFromTemplateActionBase.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.fileTemplates.actions; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.codeInsight.template.impl.TemplateImpl; import com.intellij.ide.IdeView; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.fileTemplates.ui.CreateFromTemplateDialog; import com.intellij.ide.util.DirectoryChooserUtil; import com.intellij.ide.util.EditorHelper; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.HashSet; import java.util.Set; public abstract class CreateFromTemplateActionBase extends AnAction { public CreateFromTemplateActionBase(final String title, final String description, final Icon icon) { super (title,description,icon); } @Override public final void actionPerformed(AnActionEvent e){ DataContext dataContext = e.getDataContext(); IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext); if (view == null) { return; } PsiDirectory dir = getTargetDirectory(dataContext, view); if (dir == null) return; Project project = dir.getProject(); FileTemplate selectedTemplate = getTemplate(project, dir); if (selectedTemplate != null){ AnAction action = getReplacedAction(selectedTemplate); if (action != null) { action.actionPerformed(e); } else { FileTemplateManager.getInstance(project).addRecentName(selectedTemplate.getName()); final AttributesDefaults defaults = getAttributesDefaults(dataContext); final CreateFromTemplateDialog dialog = new CreateFromTemplateDialog(project, dir, selectedTemplate, defaults, defaults != null ? defaults.getDefaultProperties() : null); PsiElement createdElement = dialog.create(); if (createdElement != null) { elementCreated(dialog, createdElement); view.selectElement(createdElement); if (selectedTemplate.isLiveTemplateEnabled() && createdElement instanceof PsiFile) { startLiveTemplate((PsiFile)createdElement); } } } } } public static void startLiveTemplate(PsiFile file) { Project project = file.getProject(); final Editor editor = EditorHelper.openInEditor(file); if (editor == null) return; final TemplateImpl template = new TemplateImpl("", file.getText(), ""); template.setInline(true); int count = template.getSegmentsCount(); if (count == 0) return; Set<String> variables = new HashSet<>(); for (int i = 0; i < count; i++) { variables.add(template.getSegmentName(i)); } variables.removeAll(TemplateImpl.INTERNAL_VARS_SET); for (String variable : variables) { template.addVariable(variable, null, "\"" + variable + "\"", true); } WriteCommandAction.runWriteCommandAction(project, () -> editor.getDocument().setText(template.getTemplateText())); TemplateManager.getInstance(project).startTemplate(editor, template); } @Nullable protected PsiDirectory getTargetDirectory(DataContext dataContext, IdeView view) { return DirectoryChooserUtil.getOrChooseDirectory(view); } @Nullable protected AnAction getReplacedAction(final FileTemplate selectedTemplate) { return null; } protected abstract FileTemplate getTemplate(final Project project, final PsiDirectory dir); @Nullable public AttributesDefaults getAttributesDefaults(DataContext dataContext) { return null; } protected void elementCreated(CreateFromTemplateDialog dialog, PsiElement createdElement) { } }
live templates inside file templates: ensure caret at the 0 position as state could be restored from the history and caret would be in the middle of inline template (IDEA-163994)
platform/lang-impl/src/com/intellij/ide/fileTemplates/actions/CreateFromTemplateActionBase.java
live templates inside file templates: ensure caret at the 0 position as state could be restored from the history and caret would be in the middle of inline template (IDEA-163994)
<ide><path>latform/lang-impl/src/com/intellij/ide/fileTemplates/actions/CreateFromTemplateActionBase.java <ide> /* <del> * Copyright 2000-2009 JetBrains s.r.o. <add> * Copyright 2000-2016 JetBrains s.r.o. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> template.addVariable(variable, null, "\"" + variable + "\"", true); <ide> } <ide> WriteCommandAction.runWriteCommandAction(project, () -> editor.getDocument().setText(template.getTemplateText())); <add> //ensure caret at the start of the template <add> editor.getCaretModel().moveToOffset(0); <ide> TemplateManager.getInstance(project).startTemplate(editor, template); <ide> } <ide>
JavaScript
apache-2.0
f2d3cd02c332810a0213de5f44bd4ba7f884b27b
0
ssorj/blinky,ssorj/blinky,ssorj/blinky,ssorj/blinky
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ "use strict"; const $ = document.querySelector.bind(document); const $$ = document.querySelectorAll.bind(document); Element.prototype.$ = function () { return this.querySelector.apply(this, arguments); }; Element.prototype.$$ = function () { return this.querySelectorAll.apply(this, arguments); }; class Gesso { constructor() { this._minFetchInterval = 500; this._maxFetchInterval = 60 * 1000; this._fetchStates = new Map(); // By path } openRequest(method, url, loadHandler) { let request = new XMLHttpRequest(); request.open(method, url); if (loadHandler != null) { request.addEventListener("load", loadHandler); } return request; } _getFetchState(path) { let state = this._fetchStates[path]; if (state == null) { state = { currentInterval: null, currentTimeoutId: null, failedAttempts: 0, etag: null, timestamp: null }; this._fetchStates[path] = state; } return state; } fetch(path, dataHandler) { console.log("Fetching data from", path); let state = this._getFetchState(path); let request = this.openRequest("GET", path, (event) => { if (event.target.status >= 200 && event.target.status < 300) { state.failedAttempts = 0; state.etag = event.target.getResponseHeader("ETag"); dataHandler(JSON.parse(event.target.responseText)); } else if (event.target.status == 304) { state.failedAttempts = 0; } state.timestamp = new Date().getTime(); }); request.addEventListener("error", (event) => { console.log("Fetch failed"); state.failedAttempts++; }); let etag = state.etag; if (etag) { request.setRequestHeader("If-None-Match", etag); } request.send(); return state; } fetchPeriodically(path, dataHandler) { let state = this._getFetchState(path); clearTimeout(state.currentTimeoutId); state.currentInterval = this._minFetchInterval; this._doFetchPeriodically(path, dataHandler, state); return state; } _doFetchPeriodically(path, dataHandler, state) { if (state.currentInterval >= this._maxFetchInterval) { setInterval(() => { this.fetch(path, dataHandler); }, this._maxFetchInterval); return; } state.currentTimeoutId = setTimeout(() => { this._doFetchPeriodically(path, dataHandler, state); }, state.currentInterval); state.currentInterval = Math.min(state.currentInterval * 2, this._maxFetchInterval); this.fetch(path, dataHandler); } parseQueryString(str) { if (str.startsWith("?")) { str = str.slice(1); } let qvars = str.split(/[&;]/); let obj = {}; for (let i = 0; i < qvars.length; i++) { let [name, value] = qvars[i].split("=", 2); name = decodeURIComponent(name); value = decodeURIComponent(value); obj[name] = value; } return obj; } emitQueryString(obj) { let tokens = []; for (let name in obj) { if (!obj.hasOwnProperty(name)) { continue; } let value = obj[name]; name = decodeURIComponent(name); value = decodeURIComponent(value); tokens.push(name + "=" + value); } return tokens.join(";"); } createElement(parent, tag, options) { let elem = document.createElement(tag); if (parent != null) { parent.appendChild(elem); } if (options != null) { if (typeof options === "string" || typeof options === "number") { this.createText(elem, options); } else if (typeof options === "object") { if (options.hasOwnProperty("text")) { let text = options["text"]; if (text != null) { this.createText(elem, text); } delete options["text"]; } for (let key of Object.keys(options)) { elem.setAttribute(key, options[key]); } } else { throw `illegal argument: ${options}`; } } return elem; } createText(parent, text) { let node = document.createTextNode(text); if (parent != null) { parent.appendChild(node); } return node; } _setSelector(elem, selector) { if (selector == null) { return; } if (selector.startsWith("#")) { elem.setAttribute("id", selector.slice(1)); } else { elem.setAttribute("class", selector); } } createDiv(parent, selector, options) { let elem = this.createElement(parent, "div", options); this._setSelector(elem, selector); return elem; } createSpan(parent, selector, options) { let elem = this.createElement(parent, "span", options); this._setSelector(elem, selector); return elem; } createLink(parent, href, options) { let elem = this.createElement(parent, "a", options); if (href != null) { elem.setAttribute("href", href); } return elem; } createTable(parent, headings, rows, options) { let elem = this.createElement(parent, "table", options); let thead = this.createElement(elem, "thead"); let tbody = this.createElement(elem, "tbody"); if (headings) { let tr = this.createElement(thead, "tr"); for (let heading of headings) { this.createElement(tr, "th", heading); } } for (let row of rows) { let tr = this.createElement(tbody, "tr"); for (let cell of row) { this.createElement(tr, "td", cell); } } return elem; } replaceElement(oldElement, newElement) { oldElement.parentNode.replaceChild(newElement, oldElement); } formatDuration(millis, suffixes) { if (millis == null) { return "-"; } if (suffixes == null) { suffixes = [ " years", " weeks", " days", " hours", " minutes", " seconds", " millis", ]; } let prefix = ""; if (millis < 0) { prefix = "-"; } millis = Math.abs(millis); let seconds = Math.round(millis / 1000); let minutes = Math.round(millis / 60 / 1000); let hours = Math.round(millis / 3600 / 1000); let days = Math.round(millis / 86400 / 1000); let weeks = Math.round(millis / 432000 / 1000); let years = Math.round(millis / 31536000 / 1000); if (years > 1) return `${prefix}${years}${suffixes[0]}`; if (weeks > 1) return `${prefix}${weeks}${suffixes[1]}`; if (days > 1) return `${prefix}${days}${suffixes[2]}`; if (hours > 1) return `${prefix}${hours}${suffixes[3]}`; if (minutes > 1) return `${prefix}${minutes}${suffixes[4]}`; if (seconds > 1) return `${prefix}${seconds}${suffixes[5]}`; if (millis == 0) return "0"; return `${prefix}${Math.round(millis)}${suffixes[6]}`; } formatDurationBrief(millis) { return this.formatDuration(millis, ["y", "w", "d", "h", "m", "s", "ms"]); } }
files/gesso.js
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ "use strict"; const $ = document.querySelector.bind(document); const $$ = document.querySelectorAll.bind(document); Element.prototype.$ = function () { return this.querySelector.apply(this, arguments); }; Element.prototype.$$ = function () { return this.querySelectorAll.apply(this, arguments); }; class Gesso { constructor() { this._minFetchInterval = 500; this._maxFetchInterval = 60 * 1000; this._fetchStates = new Map(); // By path } openRequest(method, url, loadHandler) { let request = new XMLHttpRequest(); request.open(method, url); if (loadHandler != null) { request.addEventListener("load", loadHandler); } return request; } _getFetchState(path) { let state = this._fetchStates[path]; if (state == null) { state = { currentInterval: null, currentTimeoutId: null, failedAttempts: 0, etag: null, timestamp: null }; this._fetchStates[path] = state; } return state; } fetch(path, dataHandler) { console.log("Fetching data from", path); let state = this._getFetchState(path); let request = this.openRequest("GET", path, (event) => { if (event.target.status >= 200 && event.target.status < 300) { state.failedAttempts = 0; state.etag = event.target.getResponseHeader("ETag"); dataHandler(JSON.parse(event.target.responseText)); } else if (event.target.status == 304) { state.failedAttempts = 0; } state.timestamp = new Date().getTime(); }); request.addEventListener("error", (event) => { console.log("Fetch failed"); state.failedAttempts++; }); let etag = state.etag; if (etag) { request.setRequestHeader("If-None-Match", etag); } request.send(); return state; } fetchPeriodically(path, dataHandler) { let state = this._getFetchState(path); clearTimeout(state.currentTimeoutId); state.currentInterval = this._minFetchInterval; this._doFetchPeriodically(path, dataHandler, state); return state; } _doFetchPeriodically(path, dataHandler, state) { if (state.currentInterval >= this._maxFetchInterval) { setInterval(() => { this.fetch(path, dataHandler); }, this._maxFetchInterval); return; } state.currentTimeoutId = setTimeout(() => { this._doFetchPeriodically(path, dataHandler, state); }, state.currentInterval); state.currentInterval = Math.min(state.currentInterval * 2, this._maxFetchInterval); this.fetch(path, dataHandler); } parseQueryString(str) { if (str.startsWith("?")) { str = str.slice(1); } let qvars = str.split(/[&;]/); let obj = {}; for (let i = 0; i < qvars.length; i++) { let [name, value] = qvars[i].split("=", 2); name = decodeURIComponent(name); value = decodeURIComponent(value); obj[name] = value; } return obj; } emitQueryString(obj) { let tokens = []; for (let name in obj) { if (!obj.hasOwnProperty(name)) { continue; } let value = obj[name]; name = decodeURIComponent(name); value = decodeURIComponent(value); tokens.push(name + "=" + value); } return tokens.join(";"); } createElement(parent, tag, options) { let elem = document.createElement(tag); if (parent != null) { parent.appendChild(elem); } if (options != null) { if (typeof options === "string" || typeof options === "number") { this.createText(elem, options); } else if (typeof options === "object") { if (options.hasOwnProperty("text")) { let text = options["text"]; if (text != null) { this.createText(elem, text); } delete options["text"]; } for (let key of Object.keys(options)) { elem.setAttribute(key, options[key]); } } else { throw `illegal argument: ${options}`; } } return elem; } createText(parent, text) { let node = document.createTextNode(text); if (parent != null) { parent.appendChild(node); } return node; } _setSelector(elem, selector) { if (selector == null) { return; } if (selector.startsWith("#")) { elem.setAttribute("id", selector.slice(1)); } else { elem.setAttribute("class", selector); } } createDiv(parent, selector, options) { let elem = this.createElement(parent, "div", options); this._setSelector(elem, selector); return elem; } createSpan(parent, selector, options) { let elem = this.createElement(parent, "span", options); this._setSelector(elem, selector); return elem; } createLink(parent, href, options) { let elem = this.createElement(parent, "a", options); if (href != null) { elem.setAttribute("href", href); } return elem; } createTable(parent, headings, rows, options) { let elem = this.createElement(parent, "table", options); let thead = this.createElement(elem, "thead"); let tbody = this.createElement(elem, "tbody"); if (headings) { let tr = this.createElement(thead, "tr"); for (let heading of headings) { this.createElement(tr, "th", heading); } } for (let row of rows) { let tr = this.createElement(tbody, "tr"); for (let cell of row) { this.createElement(tr, "td", cell); } } return elem; } replaceElement(oldElement, newElement) { oldElement.parentNode.replaceChild(newElement, oldElement); } formatDuration(millis, suffixes) { if (millis == null) { return "-"; } if (suffixes == null) { suffixes = [ " years", " weeks", " days", " hours", " minutes", " seconds", " millis", ]; } let prefix = ""; if (millis < 0) { prefix = "-"; } millis = Math.abs(millis); let seconds = Math.round(millis / 1000); let minutes = Math.round(millis / 60 / 1000); let hours = Math.round(millis / 3600 / 1000); let days = Math.round(millis / 86400 / 1000); let weeks = Math.round(millis / 432000 / 1000); let years = Math.round(millis / 31536000 / 1000); if (years > 1) return `${years}${suffixes[0]}`; if (weeks > 1) return `${weeks}${suffixes[1]}`; if (days > 1) return `${days}${suffixes[2]}`; if (hours > 1) return `${hours}${suffixes[3]}`; if (minutes > 1) return `${minutes}${suffixes[4]}`; if (seconds > 1) return `${seconds}${suffixes[5]}`; if (millis == 0) return "0"; return `${prefix}${Math.round(millis)}${suffixes[6]}`; } formatDurationBrief(millis) { return this.formatDuration(millis, ["y", "w", "d", "h", "m", "s", "ms"]); } }
Update gesso
files/gesso.js
Update gesso
<ide><path>iles/gesso.js <ide> let weeks = Math.round(millis / 432000 / 1000); <ide> let years = Math.round(millis / 31536000 / 1000); <ide> <del> if (years > 1) return `${years}${suffixes[0]}`; <del> if (weeks > 1) return `${weeks}${suffixes[1]}`; <del> if (days > 1) return `${days}${suffixes[2]}`; <del> if (hours > 1) return `${hours}${suffixes[3]}`; <del> if (minutes > 1) return `${minutes}${suffixes[4]}`; <del> if (seconds > 1) return `${seconds}${suffixes[5]}`; <add> if (years > 1) return `${prefix}${years}${suffixes[0]}`; <add> if (weeks > 1) return `${prefix}${weeks}${suffixes[1]}`; <add> if (days > 1) return `${prefix}${days}${suffixes[2]}`; <add> if (hours > 1) return `${prefix}${hours}${suffixes[3]}`; <add> if (minutes > 1) return `${prefix}${minutes}${suffixes[4]}`; <add> if (seconds > 1) return `${prefix}${seconds}${suffixes[5]}`; <ide> if (millis == 0) return "0"; <ide> <ide> return `${prefix}${Math.round(millis)}${suffixes[6]}`;
Java
mit
error: pathspec 'src/main/test/org/jenkins/ci/plugins/jenkinslint/checker/JobDescriptionCheckerTestCase.java' did not match any file(s) known to git
2d284fcc8eaa40fdf2f3f46f32a577302c375197
1
v1v/jenkinslint-plugin,jenkinsci/jenkinslint-plugin,jenkinsci/jenkinslint-plugin
package org.jenkins.ci.plugins.jenkinslint.checker; import hudson.model.FreeStyleProject; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * JobDescriptionChecker Test Case. * * @author Victor Martinez */ public class JobDescriptionCheckerTestCase { private JobDescriptionChecker checker = new JobDescriptionChecker("JobDescriptionChecker", false, false); @Rule public JenkinsRule j = new JenkinsRule(); @Test public void testDefaultJob() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); assertTrue(checker.executeCheck(project)); } @Test public void testEmptyJobName() throws Exception { FreeStyleProject project = j.createFreeStyleProject(""); assertTrue(checker.executeCheck(project)); } @Test public void testJobDescription() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); project.setDescription("Some Description"); assertFalse(checker.executeCheck(project)); } }
src/main/test/org/jenkins/ci/plugins/jenkinslint/checker/JobDescriptionCheckerTestCase.java
Added JobDescription Checker Test Case
src/main/test/org/jenkins/ci/plugins/jenkinslint/checker/JobDescriptionCheckerTestCase.java
Added JobDescription Checker Test Case
<ide><path>rc/main/test/org/jenkins/ci/plugins/jenkinslint/checker/JobDescriptionCheckerTestCase.java <add>package org.jenkins.ci.plugins.jenkinslint.checker; <add> <add>import hudson.model.FreeStyleProject; <add>import org.junit.Rule; <add>import org.junit.Test; <add>import org.jvnet.hudson.test.JenkinsRule; <add> <add>import static org.junit.Assert.assertFalse; <add>import static org.junit.Assert.assertTrue; <add> <add>/** <add> * JobDescriptionChecker Test Case. <add> * <add> * @author Victor Martinez <add> */ <add>public class JobDescriptionCheckerTestCase { <add> private JobDescriptionChecker checker = new JobDescriptionChecker("JobDescriptionChecker", false, false); <add> <add> @Rule public JenkinsRule j = new JenkinsRule(); <add> @Test public void testDefaultJob() throws Exception { <add> FreeStyleProject project = j.createFreeStyleProject(); <add> assertTrue(checker.executeCheck(project)); <add> } <add> @Test public void testEmptyJobName() throws Exception { <add> FreeStyleProject project = j.createFreeStyleProject(""); <add> assertTrue(checker.executeCheck(project)); <add> } <add> @Test public void testJobDescription() throws Exception { <add> FreeStyleProject project = j.createFreeStyleProject(); <add> project.setDescription("Some Description"); <add> assertFalse(checker.executeCheck(project)); <add> } <add>}
Java
apache-2.0
49c7e9f0c1db4e7351b23f25937acd9c59939695
0
Onegini/android-example-app
/* * Copyright (c) 2016-2017 Onegini B.V. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.onegini.mobile.exampleapp.view.activity; import static com.onegini.mobile.exampleapp.Constants.COMMAND_RECEIVED_FINGERPRINT; import static com.onegini.mobile.exampleapp.Constants.COMMAND_SHOW_SCANNING; import static com.onegini.mobile.exampleapp.Constants.COMMAND_START; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import com.onegini.mobile.exampleapp.R; import com.onegini.mobile.exampleapp.util.AnimationUtils; import com.onegini.mobile.exampleapp.view.handler.FingerprintAuthenticationRequestHandler; public class FingerprintActivity extends AuthenticationActivity { @Bind(R.id.action_text) TextView actionTextView; @Bind(R.id.content_fingerprint) LinearLayout layoutFingerprint; @Bind(R.id.content_accept_deny) LinearLayout layoutAcceptDeny; @Bind(R.id.fallback_to_pin_button) Button fallbackToPinButton; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fingerprint); ButterKnife.bind(this); initialize(); } @Override protected void initialize() { parseIntent(); updateTexts(); setFingerprintAuthenticationPermissionVisibility(false); setupUi(); } protected void setupUi() { if (COMMAND_START.equals(command)) { actionTextView.setText(R.string.scan_fingerprint); FingerprintAuthenticationRequestHandler.CALLBACK.acceptAuthenticationRequest(); } else if (COMMAND_SHOW_SCANNING.equals(command)) { actionTextView.setText(R.string.verifying); } else if (COMMAND_RECEIVED_FINGERPRINT.equals(command)) { actionTextView.setText(R.string.try_again); actionTextView.setAnimation(AnimationUtils.getBlinkAnimation()); } } @SuppressWarnings("unused") @OnClick(R.id.fallback_to_pin_button) public void onFallbackToPinButtonClick() { if (FingerprintAuthenticationRequestHandler.CALLBACK != null) { FingerprintAuthenticationRequestHandler.CALLBACK.fallbackToPin(); finish(); } } protected void setFingerprintAuthenticationPermissionVisibility(final boolean isVisible) { layoutAcceptDeny.setVisibility(isVisible ? View.VISIBLE : View.GONE); layoutFingerprint.setVisibility(isVisible ? View.GONE : View.VISIBLE); fallbackToPinButton.setVisibility(isVisible ? View.GONE : View.VISIBLE); } }
app/src/main/java/com/onegini/mobile/exampleapp/view/activity/FingerprintActivity.java
/* * Copyright (c) 2016-2017 Onegini B.V. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.onegini.mobile.exampleapp.view.activity; import static com.onegini.mobile.exampleapp.Constants.COMMAND_RECEIVED_FINGERPRINT; import static com.onegini.mobile.exampleapp.Constants.COMMAND_SHOW_SCANNING; import static com.onegini.mobile.exampleapp.Constants.COMMAND_START; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import com.onegini.mobile.exampleapp.R; import com.onegini.mobile.exampleapp.util.AnimationUtils; import com.onegini.mobile.exampleapp.view.handler.FingerprintAuthenticationRequestHandler; public class FingerprintActivity extends AuthenticationActivity { @Bind(R.id.action_text) TextView actionTextView; @Bind(R.id.content_fingerprint) LinearLayout layoutFingerprint; @Bind(R.id.content_accept_deny) LinearLayout layoutAcceptDeny; @Bind(R.id.fallback_to_pin_button) Button fallbackToPinButton; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fingerprint); ButterKnife.bind(this); initialize(); } @Override protected void initialize() { parseIntent(); updateTexts(); setupUi(); setFingerprintAuthenticationPermissionVisibility(false); } protected void setupUi() { if (COMMAND_START.equals(command)) { actionTextView.setText(R.string.scan_fingerprint); FingerprintAuthenticationRequestHandler.CALLBACK.acceptAuthenticationRequest(); } else if (COMMAND_SHOW_SCANNING.equals(command)) { actionTextView.setText(R.string.verifying); } else if (COMMAND_RECEIVED_FINGERPRINT.equals(command)) { actionTextView.setText(R.string.try_again); actionTextView.setAnimation(AnimationUtils.getBlinkAnimation()); } } @SuppressWarnings("unused") @OnClick(R.id.fallback_to_pin_button) public void onFallbackToPinButtonClick() { if (FingerprintAuthenticationRequestHandler.CALLBACK != null) { FingerprintAuthenticationRequestHandler.CALLBACK.fallbackToPin(); finish(); } } protected void setFingerprintAuthenticationPermissionVisibility(final boolean isVisible) { layoutAcceptDeny.setVisibility(isVisible ? View.VISIBLE : View.GONE); layoutFingerprint.setVisibility(isVisible ? View.GONE : View.VISIBLE); fallbackToPinButton.setVisibility(isVisible ? View.GONE : View.VISIBLE); } }
Fix accepting the mobile authentication with fingerprint
app/src/main/java/com/onegini/mobile/exampleapp/view/activity/FingerprintActivity.java
Fix accepting the mobile authentication with fingerprint
<ide><path>pp/src/main/java/com/onegini/mobile/exampleapp/view/activity/FingerprintActivity.java <ide> protected void initialize() { <ide> parseIntent(); <ide> updateTexts(); <add> setFingerprintAuthenticationPermissionVisibility(false); <ide> setupUi(); <del> setFingerprintAuthenticationPermissionVisibility(false); <ide> } <ide> <ide> protected void setupUi() {
Java
bsd-3-clause
c4da6ad2c9c4095a5c66c3e872e1bd8eabb2233e
0
interdroid/ibis-ipl,interdroid/ibis-ipl,interdroid/ibis-ipl
// $Id$ /** * The context of the solve method. The fields in this class are cloned * for every recursion of the solve() method. */ public class SATContext implements java.io.Serializable { /** The variables to assign to, in order of decreasing use count. */ int varlist[]; /** The number of open terms of each clause. */ int terms[]; /* The number of open terms of each clause. */ /** The assignments to all variables. */ int assignments[]; /** Satisified flags for all clausses in the problem. */ boolean satisfied[]; /** The number of still unsatisfied clauses. */ int unsatisfied; /** Constructs a Context with the specified elements. */ private SATContext( int vl[], int tl[], int al[], boolean sat[], int us ){ varlist = vl; terms = tl; assignments = al; satisfied = sat; unsatisfied = us; } /** Constructs an empty Context. */ SATContext( int clauseCount ){ satisfied = new boolean[clauseCount]; unsatisfied = clauseCount; } /** Returns a clone of Context. */ public Object clone() { return new SATContext( (int []) varlist.clone(), (int []) terms.clone(), (int []) assignments.clone(), (boolean []) satisfied.clone(), unsatisfied ); } /** Propagates any unit clauses in the problem. */ private int propagateUnitClauses( SATProblem p ) { for( int i=0; i<terms.length; i++ ){ if( !satisfied[i] && terms[i] == 1 ){ Clause c = p.clauses[i]; int arr[] = c.pos; int var = -1; // Now search for the variable that isn't satisfied. for( int j=0; j<arr.length; j++ ){ int v = arr[j]; if( assignments[v] == -1 ){ if( var != -1 ){ System.err.println( "A unit clause with multiple unassigned variables???" ); return 0; } } } if( var != -1 ){ // We have found the unassigned one, propagate it. int res = propagatePosAssignment( p, var ); if( res != 0 ){ // The problem is now conflicting/satisfied, we're // done. return res; } } else { // Keep searching for the unassigned variable arr = c.neg; for( int j=0; j<arr.length; j++ ){ int v = arr[j]; if( assignments[v] == -1 ){ if( var != -1 ){ System.err.println( "A unit clause with multiple unassigned variables???" ); return 0; } } } if( var != -1 ){ // We have found the unassigned one, propagate it. int res = propagatePosAssignment( p, var ); if( res != 0 ){ // The problem is now conflicting/satisfied, we're // done. return res; } } } } } return 0; } /** * Propagates the fact that variable 'var' is true. * @return -1 if the problem is now in conflict, 1 if the problem is now satisified, 2 if there are now unit clauses, or 0 otherwise */ public int propagatePosAssignment( SATProblem p, int var ) { assignments[var] = 1; boolean haveUnitClauses = false; // Deduct this clause from all clauses that contain this as a // negative term. IntVector neg = p.getNegClauses( var ); int sz = neg.size(); for( int i=0; i<sz; i++ ){ int cno = neg.get( i ); if( !satisfied[cno] ){ unsatisfied--; } terms[cno]--; if( terms[cno] == 0 ){ // We now have a term that cannot be satisfied. Conflict. return -1; } if( terms[cno] == 1 ){ haveUnitClauses = true; } } // Mark all clauses that contain this variable as a positive // term as satisfied. IntVector pos = p.getPosClauses( var ); sz = pos.size(); for( int i=0; i<sz; i++ ){ int cno = pos.get( i ); if( !satisfied[cno] ){ unsatisfied--; } satisfied[cno] = true; } if( unsatisfied == 0 ){ // All clauses are now satisfied, we have a winner! return 1; } if( haveUnitClauses ){ propagateUnitClauses( p ); } return 0; } /** Propagates the fact that variable 'var' is false. */ public int propagateNegAssignment( SATProblem p, int var ) { assignments[var] = 0; boolean haveUnitClauses = false; // Deduct this clause from all clauses that contain this as a // Positive term. IntVector neg = p.getPosClauses( var ); int sz = neg.size(); for( int i=0; i<sz; i++ ){ int cno = neg.get( i ); if( !satisfied[cno] ){ unsatisfied--; } terms[cno]--; if( terms[cno] == 0 ){ // We now have a term that cannot be satisfied. Conflict. return -1; } if( terms[cno] == 1 ){ haveUnitClauses = true; } } // Mark all clauses that contain this variable as a negative // term as satisfied. IntVector pos = p.getNegClauses( var ); sz = pos.size(); for( int i=0; i<sz; i++ ){ int cno = pos.get( i ); if( !satisfied[cno] ){ unsatisfied--; } satisfied[cno] = true; } if( unsatisfied == 0 ){ // All clauses are now satisfied, we have a winner! return 1; } if( haveUnitClauses ){ propagateUnitClauses( p ); } return 0; } }
apps/satin/sat/SATContext.java
// $Id$ /** * The context of the solve method. The fields in this class are cloned * for every recursion of the solve() method. */ public class SATContext implements java.io.Serializable { /** The variables to assign to, in order of decreasing use count. */ int varlist[]; /** The number of open terms of each clause. */ int terms[]; /* The number of open terms of each clause. */ /** The assignments to all variables. */ int assignments[]; /** Satisified flags for all clausses in the problem. */ boolean satisfied[]; /** The number of still unsatisfied clauses. */ int unsatisfied; /** Constructs a Context with the specified elements. */ private SATContext( int vl[], int tl[], int al[], boolean sat[], int us ){ varlist = vl; terms = tl; assignments = al; satisfied = sat; unsatisfied = us; } /** Constructs an empty Context. */ SATContext( int clauseCount ){ satisfied = new boolean[clauseCount]; unsatisfied = clauseCount; } /** Returns a clone of Context. */ public Object clone() { return new SATContext( (int []) varlist.clone(), (int []) terms.clone(), (int []) assignments.clone(), (boolean []) satisfied.clone(), unsatisfied ); } /** * Propagates the fact that variable 'var' is true. * @return -1 if the problem is now in conflict, 1 if the problem is now satisified, or 0 otherwise */ public int propagatePosAssignment( SATProblem p, int var ) { assignments[var] = 1; // Deduct this clause from all clauses that contain this as a // negative term. IntVector neg = p.getNegClauses( var ); int sz = neg.size(); for( int i=0; i<sz; i++ ){ int cno = neg.get( i ); if( !satisfied[cno] ){ unsatisfied--; } terms[cno]--; if( terms[cno] == 0 ){ // We now have a term that cannot be satisfied. Conflict. return -1; } } // Mark all clauses that contain this variable as a positive // term as satisfied. IntVector pos = p.getPosClauses( var ); sz = pos.size(); for( int i=0; i<sz; i++ ){ int cno = pos.get( i ); if( !satisfied[cno] ){ unsatisfied--; } satisfied[cno] = true; } if( unsatisfied == 0 ){ // All clauses are now satisfied, we have a winner! return 1; } return 0; } /** Propagates the fact that variable 'var' is false. */ public int propagateNegAssignment( SATProblem p, int var ) { assignments[var] = 0; // Deduct this clause from all clauses that contain this as a // Positive term. IntVector neg = p.getPosClauses( var ); int sz = neg.size(); for( int i=0; i<sz; i++ ){ int cno = neg.get( i ); if( !satisfied[cno] ){ unsatisfied--; } terms[cno]--; if( terms[cno] == 0 ){ // We now have a term that cannot be satisfied. Conflict. return -1; } } // Mark all clauses that contain this variable as a negative // term as satisfied. IntVector pos = p.getNegClauses( var ); sz = pos.size(); for( int i=0; i<sz; i++ ){ int cno = pos.get( i ); if( !satisfied[cno] ){ unsatisfied--; } satisfied[cno] = true; } if( unsatisfied == 0 ){ // All clauses are now satisfied, we have a winner! return 1; } return 0; } }
CvR: + Added unit propagation. git-svn-id: f22e84ca493ccad7df8d2727bca69d1c9fc2e5c5@1076 aaf88347-d911-0410-b711-e54d386773bb
apps/satin/sat/SATContext.java
<ide><path>pps/satin/sat/SATContext.java <ide> ); <ide> } <ide> <add> /** Propagates any unit clauses in the problem. */ <add> private int propagateUnitClauses( SATProblem p ) <add> { <add> for( int i=0; i<terms.length; i++ ){ <add> if( !satisfied[i] && terms[i] == 1 ){ <add> Clause c = p.clauses[i]; <add> int arr[] = c.pos; <add> int var = -1; <add> <add> // Now search for the variable that isn't satisfied. <add> for( int j=0; j<arr.length; j++ ){ <add> int v = arr[j]; <add> <add> if( assignments[v] == -1 ){ <add> if( var != -1 ){ <add> System.err.println( "A unit clause with multiple unassigned variables???" ); <add> return 0; <add> } <add> } <add> } <add> if( var != -1 ){ <add> // We have found the unassigned one, propagate it. <add> int res = propagatePosAssignment( p, var ); <add> if( res != 0 ){ <add> // The problem is now conflicting/satisfied, we're <add> // done. <add> return res; <add> } <add> } <add> else { <add> // Keep searching for the unassigned variable <add> arr = c.neg; <add> for( int j=0; j<arr.length; j++ ){ <add> int v = arr[j]; <add> <add> if( assignments[v] == -1 ){ <add> if( var != -1 ){ <add> System.err.println( "A unit clause with multiple unassigned variables???" ); <add> return 0; <add> } <add> } <add> } <add> if( var != -1 ){ <add> // We have found the unassigned one, propagate it. <add> int res = propagatePosAssignment( p, var ); <add> if( res != 0 ){ <add> // The problem is now conflicting/satisfied, we're <add> // done. <add> return res; <add> } <add> } <add> } <add> } <add> } <add> return 0; <add> } <add> <ide> /** <ide> * Propagates the fact that variable 'var' is true. <del> * @return -1 if the problem is now in conflict, 1 if the problem is now satisified, or 0 otherwise <add> * @return -1 if the problem is now in conflict, 1 if the problem is now satisified, 2 if there are now unit clauses, or 0 otherwise <ide> */ <ide> public int propagatePosAssignment( SATProblem p, int var ) <ide> { <ide> assignments[var] = 1; <add> boolean haveUnitClauses = false; <ide> <ide> // Deduct this clause from all clauses that contain this as a <ide> // negative term. <ide> // We now have a term that cannot be satisfied. Conflict. <ide> return -1; <ide> } <add> if( terms[cno] == 1 ){ <add> haveUnitClauses = true; <add> } <ide> } <ide> <ide> // Mark all clauses that contain this variable as a positive <ide> // All clauses are now satisfied, we have a winner! <ide> return 1; <ide> } <add> if( haveUnitClauses ){ <add> propagateUnitClauses( p ); <add> } <ide> return 0; <ide> } <ide> <ide> public int propagateNegAssignment( SATProblem p, int var ) <ide> { <ide> assignments[var] = 0; <add> boolean haveUnitClauses = false; <ide> <ide> // Deduct this clause from all clauses that contain this as a <ide> // Positive term. <ide> // We now have a term that cannot be satisfied. Conflict. <ide> return -1; <ide> } <del> } <del> <del> // Mark all clauses that contain this variable as a negative <del> // term as satisfied. <add> if( terms[cno] == 1 ){ <add> haveUnitClauses = true; <add> } <add> } <add> <add> // Mark all clauses that contain this variable as a negative <add> // term as satisfied. <ide> IntVector pos = p.getNegClauses( var ); <ide> sz = pos.size(); <ide> for( int i=0; i<sz; i++ ){ <ide> // All clauses are now satisfied, we have a winner! <ide> return 1; <ide> } <add> if( haveUnitClauses ){ <add> propagateUnitClauses( p ); <add> } <ide> return 0; <ide> } <ide> }
Java
apache-2.0
870a510d89221d146cbb8f154063f15ebc1f1b28
0
zplesac/android_connectionbuddy,zplesac/android_connectify
package com.zplesac.connectifty; import com.zplesac.connectifty.interfaces.ConnectivityChangeListener; import com.zplesac.connectifty.models.ConnectifyEvent; import com.zplesac.connectifty.models.ConnectifyState; import com.zplesac.connectifty.models.ConnectifyType; import com.zplesac.connectifty.receivers.NetworkChangeReceiver; import android.content.Context; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import java.util.HashMap; /** * Created by Željko Plesac on 06/10/14. */ public class Connectify { private static final String ACTION_CONNECTIVITY_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE"; private static final String ACTION_WIFI_STATE_CHANGE = "android.net.wifi.WIFI_STATE_CHANGED"; private static HashMap<String, NetworkChangeReceiver> receiversHashMap = new HashMap<String, NetworkChangeReceiver>(); private static volatile Connectify instance; private ConnectifyConfiguration configuration; protected Connectify() { // empty constructor } /** * Returns singleton class instance. */ public static Connectify getInstance() { if (instance == null) { synchronized (Connectify.class) { if (instance == null) { instance = new Connectify(); } } } return instance; } public synchronized void init(ConnectifyConfiguration configuration) { if (configuration == null) { throw new IllegalArgumentException(); } if (this.configuration == null) { this.configuration = configuration; } } public ConnectifyConfiguration getConfiguration() { return configuration; } /** * Register for connectivity events. Must be called separately for each activity/context. */ public void registerForConnectivityEvents(Object object, ConnectivityChangeListener listener) { boolean hasConnection = hasNetworkConnection(); if (ConnectifyPreferences.containsInternetConnection(object) && ConnectifyPreferences.getInternetConnection(object) != hasConnection) { ConnectifyPreferences.setInternetConnection(object, hasConnection); if (hasConnection) { listener.onConnectionChange(new ConnectifyEvent(ConnectifyState.CONNECTED)); } else { listener.onConnectionChange(new ConnectifyEvent(ConnectifyState.DISCONNECTED)); } } else if (!ConnectifyPreferences.containsInternetConnection(object)) { ConnectifyPreferences.setInternetConnection(object, hasConnection); if (hasConnection) { listener.onConnectionChange(new ConnectifyEvent(ConnectifyState.CONNECTED)); } else { listener.onConnectionChange(new ConnectifyEvent(ConnectifyState.DISCONNECTED)); } } IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_CONNECTIVITY_CHANGE); filter.addAction(ACTION_WIFI_STATE_CHANGE); NetworkChangeReceiver receiver = new NetworkChangeReceiver(object, listener); if (!receiversHashMap.containsKey(object.toString())) { receiversHashMap.put(object.toString(), receiver); } configuration.getContext().registerReceiver(receiver, filter); } /** * Unregister from connectivity events. */ public void unregisterFromConnectivityEvents(Object object) { NetworkChangeReceiver receiver = receiversHashMap.get(object.toString()); configuration.getContext().unregisterReceiver(receiver); receiversHashMap.remove(object.toString()); receiver = null; } /** * Returns true if application has internet connection. */ public boolean hasNetworkConnection() { ConnectivityManager connectivityManager = (ConnectivityManager) configuration.getContext().getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager != null) { NetworkInfo networkInfoMobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo networkInfoWiFi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); return (networkInfoMobile != null && networkInfoMobile.isConnected() || networkInfoWiFi.isConnected()); } else { return false; } } /** * Get network connection type from ConnectivityManager. * * @return ConnectivityType which is available on current device. */ public ConnectifyType getNetworkType() { ConnectivityManager connectivityManager = (ConnectivityManager) configuration.getContext().getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager != null) { NetworkInfo networkInfoMobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo networkInfoWiFi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (networkInfoMobile != null && networkInfoMobile.isConnected() && networkInfoWiFi.isConnected()) { return ConnectifyType.BOTH; } else if (networkInfoMobile != null && networkInfoMobile.isConnected()) { return ConnectifyType.MOBILE; } else if (networkInfoWiFi.isConnected()) { return ConnectifyType.WIFI; } else { return ConnectifyType.NONE; } } else { return ConnectifyType.NONE; } } }
connectify/src/main/java/com/zplesac/connectifty/Connectify.java
package com.zplesac.connectifty; import com.zplesac.connectifty.interfaces.ConnectivityChangeListener; import com.zplesac.connectifty.models.ConnectifyEvent; import com.zplesac.connectifty.models.ConnectifyState; import com.zplesac.connectifty.models.ConnectifyType; import com.zplesac.connectifty.receivers.NetworkChangeReceiver; import android.content.Context; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import java.util.HashMap; /** * Created by Željko Plesac on 06/10/14. */ public class Connectify { private static HashMap<String, NetworkChangeReceiver> receiversHashMap = new HashMap<String, NetworkChangeReceiver>(); private static final String ACTION_CONNECTIVITY_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE"; private static final String ACTION_WIFI_STATE_CHANGE = "android.net.wifi.WIFI_STATE_CHANGED"; private static volatile Connectify instance; private ConnectifyConfiguration configuration; protected Connectify() { // empty constructor } /** * Returns singleton class instance. * */ public static Connectify getInstance() { if (instance == null) { synchronized (Connectify.class) { if (instance == null) { instance = new Connectify(); } } } return instance; } public synchronized void init(ConnectifyConfiguration configuration) { if (configuration == null) { throw new IllegalArgumentException(); } if (this.configuration == null) { this.configuration = configuration; } } public ConnectifyConfiguration getConfiguration() { return configuration; } /** * Register for connectivity events. Must be called separately for each activity/context. */ public void registerForConnectivityEvents(Object object, ConnectivityChangeListener listener) { boolean hasConnection = hasNetworkConnection(); if (ConnectifyPreferences.containsInternetConnection(object) && ConnectifyPreferences.getInternetConnection(object) != hasConnection) { ConnectifyPreferences.setInternetConnection(object, hasConnection); if (hasConnection) { listener.onConnectionChange(new ConnectifyEvent(ConnectifyState.CONNECTED)); } else { listener.onConnectionChange(new ConnectifyEvent(ConnectifyState.DISCONNECTED)); } } else if (!ConnectifyPreferences.containsInternetConnection(object)) { ConnectifyPreferences.setInternetConnection(object, hasConnection); if (hasConnection) { listener.onConnectionChange(new ConnectifyEvent(ConnectifyState.CONNECTED)); } else { listener.onConnectionChange(new ConnectifyEvent(ConnectifyState.DISCONNECTED)); } } IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_CONNECTIVITY_CHANGE); filter.addAction(ACTION_WIFI_STATE_CHANGE); NetworkChangeReceiver receiver = new NetworkChangeReceiver(object, listener); if (!receiversHashMap.containsKey(object.toString())) { receiversHashMap.put(object.toString(), receiver); } configuration.getContext().registerReceiver(receiver, filter); } /** * Unregister from connectivity events. */ public void unregisterFromConnectivityEvents(Object object) { NetworkChangeReceiver receiver = receiversHashMap.get(object.toString()); configuration.getContext().unregisterReceiver(receiver); receiversHashMap.remove(object.toString()); receiver = null; } /** * Returns true if application has internet connection. */ public boolean hasNetworkConnection() { ConnectivityManager connectivityManager = (ConnectivityManager) configuration.getContext().getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager != null) { NetworkInfo networkInfoMobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo networkInfoWiFi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); return (networkInfoMobile != null && networkInfoMobile.isConnected() || networkInfoWiFi.isConnected()); } else { return false; } } /** * Get network connection type from ConnectivityManager. * * @return ConnectivityType which is available on current device. */ public ConnectifyType getNetworkType() { ConnectivityManager connectivityManager = (ConnectivityManager) configuration.getContext().getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager != null) { NetworkInfo networkInfoMobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo networkInfoWiFi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (networkInfoMobile != null && networkInfoMobile.isConnected() && networkInfoWiFi.isConnected()) { return ConnectifyType.BOTH; } else if (networkInfoMobile != null && networkInfoMobile.isConnected()) { return ConnectifyType.MOBILE; } else if(networkInfoWiFi.isConnected()){ return ConnectifyType.WIFI; } else{ return ConnectifyType.NONE; } } else { return ConnectifyType.NONE; } } }
checkstyle fixes
connectify/src/main/java/com/zplesac/connectifty/Connectify.java
checkstyle fixes
<ide><path>onnectify/src/main/java/com/zplesac/connectifty/Connectify.java <ide> */ <ide> public class Connectify { <ide> <del> private static HashMap<String, NetworkChangeReceiver> receiversHashMap = new HashMap<String, NetworkChangeReceiver>(); <del> <ide> private static final String ACTION_CONNECTIVITY_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE"; <ide> private static final String ACTION_WIFI_STATE_CHANGE = "android.net.wifi.WIFI_STATE_CHANGED"; <add> <add> private static HashMap<String, NetworkChangeReceiver> receiversHashMap = new HashMap<String, NetworkChangeReceiver>(); <ide> <ide> private static volatile Connectify instance; <ide> <ide> <ide> /** <ide> * Returns singleton class instance. <del> * */ <add> */ <ide> public static Connectify getInstance() { <ide> if (instance == null) { <ide> synchronized (Connectify.class) { <ide> return ConnectifyType.BOTH; <ide> } else if (networkInfoMobile != null && networkInfoMobile.isConnected()) { <ide> return ConnectifyType.MOBILE; <del> } else if(networkInfoWiFi.isConnected()){ <add> } else if (networkInfoWiFi.isConnected()) { <ide> return ConnectifyType.WIFI; <del> } <del> else{ <add> } else { <ide> return ConnectifyType.NONE; <ide> } <ide> } else {
JavaScript
apache-2.0
186728c34c18623b4f3f1659e7c377d42649a197
0
xcesek/KobylyBot,xcesek/KobylyBot
const sendApi = require('./send-api.js'); var userData = []; exports.processTextMessage = function (messageText, senderID) { if (messageText.indexOf('omsa') > -1) { sendApi.sendQuickReply(senderID); } else { sendApi.sendTextMessage(senderID, "Nerozumiem, čo tým myslíte. " ); } };
bot/bot.js
const sendApi = require('./send-api.js'); var userData = []; exports.processTextMessage = function (messageText, senderID) { if (messageText.contains('omsa')) { sendApi.sendQuickReply(senderID); } else { sendApi.sendTextMessage(senderID, "Nerozumiem, čo tým myslíte. " ); } };
Commit
bot/bot.js
Commit
<ide><path>ot/bot.js <ide> <ide> exports.processTextMessage = function (messageText, senderID) { <ide> <del> if (messageText.contains('omsa')) { <add> if (messageText.indexOf('omsa') > -1) { <ide> sendApi.sendQuickReply(senderID); <ide> } else { <ide> sendApi.sendTextMessage(senderID, "Nerozumiem, čo tým myslíte. " );
Java
apache-2.0
fb37e38528bca21625e93a0608e2a1b9ee79f3ec
0
howardliu-cn/my-gear
package cn.howardliu.gear.spring.boot.autoconfigure; import com.alibaba.druid.pool.DruidDataSource; import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.annotation.PostConstruct; import javax.sql.DataSource; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; import java.util.Set; import static cn.howardliu.gear.spring.boot.autoconfigure.MybatisDruidProperties.MYBATIS_DRUID_PREFIX; /** * <p> * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration Auto-Configuration} for Mybatis integrate with Druid. * <p> * Contributes: * <ul> * <li>{@link DruidDataSource}</li> * <li>{@link DataSourceTransactionManager}</li> * </ul> * <p> * If {@link org.mybatis.spring.annotation.MapperScan} is used, or a * configuration file is specified as a property, those will be considered, * otherwise this auto-configuration will attempt to register mappers based on * the interface definitions in or under the root auto-configuration package. * * @author liuxh * @version 1.0.0 * @since 1.0.0 */ @Configuration @ConditionalOnClass({DataSource.class, DruidDataSource.class, DataSourceTransactionManager.class}) @ConditionalOnProperty(prefix = MYBATIS_DRUID_PREFIX, name = {"jdbcUrl", "username", "password"}) @EnableConfigurationProperties(MybatisDruidProperties.class) @AutoConfigureBefore({MybatisAutoConfiguration.class, DataSourceAutoConfiguration.class}) public class MyBatisDruidAutoConfiguration { private static final Logger logger = LoggerFactory.getLogger(MyBatisDruidAutoConfiguration.class); private final MybatisDruidProperties properties; public MyBatisDruidAutoConfiguration(MybatisDruidProperties properties) { this.properties = properties; } @Bean(initMethod = "init", destroyMethod = "close") @ConditionalOnMissingBean(DataSource.class) public DruidDataSource dataSource() throws SQLException { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(this.properties.getDriverClassName()); dataSource.setUrl(this.properties.getJdbcUrl()); dataSource.setUsername(this.properties.getUsername()); dataSource.setPassword(this.properties.getPassword()); dataSource.setInitialSize(this.properties.getInitialPoolSize()); dataSource.setMinIdle(this.properties.getMinPoolSize()); dataSource.setMaxActive(this.properties.getMaxPoolWait()); dataSource.setMaxWait(60000); dataSource.setTimeBetweenEvictionRunsMillis(6000); dataSource.setMinEvictableIdleTimeMillis(300000); dataSource.setValidationQuery("SELECT 'x' FROM dual"); dataSource.setTestWhileIdle(true); dataSource.setTestOnBorrow(false); dataSource.setTestOnReturn(false); dataSource.setPoolPreparedStatements(true); dataSource.setMaxPoolPreparedStatementPerConnectionSize(20); dataSource.setFilters("stat"); dataSource.setConnectionInitSqls(connectionInitSqls()); return dataSource; } private Collection<String> connectionInitSqls() { Set<String> connectionInitSqls = new HashSet<>(1); if ("utf8mb4".equals(this.properties.getDefaultCharacter())) { connectionInitSqls.add("set names utf8mb4;"); } return connectionInitSqls; } @Bean @ConditionalOnMissingBean public DataSourceTransactionManager transactionManager(DataSource dataSource) throws SQLException { return new DataSourceTransactionManager(dataSource); } @Configuration @ConditionalOnMissingClass("com.alibaba.druid.pool.DruidDataSource") public static class DruidDataSourceNotFoundConfiguration { @PostConstruct public void afterPropertiesSet() { logger.debug("No {} found.", DruidDataSource.class.getName()); } } @Configuration @ConditionalOnMissingBean(DruidDataSource.class) public static class DruidDataSourceNotCreateConfiguration { @PostConstruct public void afterPropertiesSet() { logger.debug("No {} bean created.", DruidDataSource.class.getName()); } } }
gear-spring-boot/spring-boot-autoconfigure-mybatis-druid/src/main/java/cn/howardliu/gear/spring/boot/autoconfigure/MyBatisDruidAutoConfiguration.java
package cn.howardliu.gear.spring.boot.autoconfigure; import com.alibaba.druid.pool.DruidDataSource; import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.annotation.PostConstruct; import javax.sql.DataSource; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; import java.util.Set; import static cn.howardliu.gear.spring.boot.autoconfigure.MybatisDruidProperties.MYBATIS_DRUID_PREFIX; /** * <p> * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration Auto-Configuration} for Mybatis integrate with Druid. * <p> * Contributes: * <ul> * <li>{@link DruidDataSource}</li> * <li>{@link DataSourceTransactionManager}</li> * </ul> * <p> * If {@link org.mybatis.spring.annotation.MapperScan} is used, or a * configuration file is specified as a property, those will be considered, * otherwise this auto-configuration will attempt to register mappers based on * the interface definitions in or under the root auto-configuration package. * * @author liuxh * @version 1.0.0 * @since 1.0.0 */ @Configuration @ConditionalOnClass({DataSource.class, DruidDataSource.class, DataSourceTransactionManager.class}) @ConditionalOnProperty(prefix = MYBATIS_DRUID_PREFIX, name = {"jdbcUrl", "username", "password"}) @EnableConfigurationProperties(MybatisDruidProperties.class) @AutoConfigureBefore({MybatisAutoConfiguration.class, DataSourceAutoConfiguration.class}) public class MyBatisDruidAutoConfiguration { private static final Logger logger = LoggerFactory.getLogger(MyBatisDruidAutoConfiguration.class); private final MybatisDruidProperties properties; public MyBatisDruidAutoConfiguration(MybatisDruidProperties properties) { this.properties = properties; } @Bean(initMethod = "init", destroyMethod = "close") @ConditionalOnMissingBean(DataSource.class) public DruidDataSource dataSource() throws SQLException { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(this.properties.getDriverClassName()); dataSource.setUrl(this.properties.getJdbcUrl()); dataSource.setUsername(this.properties.getUsername()); dataSource.setPassword(this.properties.getPassword()); dataSource.setInitialSize(this.properties.getInitialPoolSize()); dataSource.setMinIdle(this.properties.getMinPoolSize()); dataSource.setMaxActive(this.properties.getMaxPoolWait()); dataSource.setMaxWait(60000); dataSource.setTimeBetweenEvictionRunsMillis(6000); dataSource.setMinEvictableIdleTimeMillis(300000); dataSource.setValidationQuery("SELECT 'x'"); dataSource.setTestWhileIdle(true); dataSource.setTestOnBorrow(false); dataSource.setTestOnReturn(false); dataSource.setPoolPreparedStatements(true); dataSource.setMaxPoolPreparedStatementPerConnectionSize(20); dataSource.setFilters("stat"); dataSource.setConnectionInitSqls(connectionInitSqls()); return dataSource; } private Collection<String> connectionInitSqls() { Set<String> connectionInitSqls = new HashSet<>(1); if ("utf8mb4".equals(this.properties.getDefaultCharacter())) { connectionInitSqls.add("set names utf8mb4;"); } return connectionInitSqls; } @Bean @ConditionalOnMissingBean public DataSourceTransactionManager transactionManager(DataSource dataSource) throws SQLException { return new DataSourceTransactionManager(dataSource); } @Configuration @ConditionalOnMissingClass("com.alibaba.druid.pool.DruidDataSource") public static class DruidDataSourceNotFoundConfiguration { @PostConstruct public void afterPropertiesSet() { logger.debug("No {} found.", DruidDataSource.class.getName()); } } @Configuration @ConditionalOnMissingBean(DruidDataSource.class) public static class DruidDataSourceNotCreateConfiguration { @PostConstruct public void afterPropertiesSet() { logger.debug("No {} bean created.", DruidDataSource.class.getName()); } } }
SELECT 'x' FROM dual
gear-spring-boot/spring-boot-autoconfigure-mybatis-druid/src/main/java/cn/howardliu/gear/spring/boot/autoconfigure/MyBatisDruidAutoConfiguration.java
SELECT 'x' FROM dual
<ide><path>ear-spring-boot/spring-boot-autoconfigure-mybatis-druid/src/main/java/cn/howardliu/gear/spring/boot/autoconfigure/MyBatisDruidAutoConfiguration.java <ide> dataSource.setMaxWait(60000); <ide> dataSource.setTimeBetweenEvictionRunsMillis(6000); <ide> dataSource.setMinEvictableIdleTimeMillis(300000); <del> dataSource.setValidationQuery("SELECT 'x'"); <add> dataSource.setValidationQuery("SELECT 'x' FROM dual"); <ide> dataSource.setTestWhileIdle(true); <ide> dataSource.setTestOnBorrow(false); <ide> dataSource.setTestOnReturn(false);
JavaScript
agpl-3.0
a124422f768767d6ca12bc9d283c728c5734a1ff
0
Agora-Project/agora-meteor,Agora-Project/agora-meteor
Meteor.publish(null, function() { return Meteor.roles.find({}); }); Meteor.publish("myself", function() { if (this.userId) { return Meteor.users.find({ _id: this.userId }, { fields: { 'isBanned': 1, 'createdAt': 1 } }); } else { return this.ready(); } }); Meteor.publish("users", function() { if (Roles.userIsInRole(this.userId, ['moderator'])) { return Meteor.users.find({}); } else { return Meteor.users.find({}, { fields: { "emails" : 0, "services" : 0, "defaultEmail" : 0 //Exclude defaultEmail from the sent data } }); } }); Meteor.publish("forum", function(id) { if (!id) { id = Post.findOne({ isRoot: true })._id; } return [ Post.find({ _id: id }), Link.find({ $or: [ { sourceId: id }, { targetId: id } ] }) ]; });
server/publish.js
Meteor.publish(null, function() { return Meteor.roles.find({}); }); Meteor.publish("myself", function() { if (this.userId) { return Meteor.users.find({ _id: this.userId }, { fields: { 'isBanned': 1, 'createdAt': 1 } }); } else { return this.ready(); } }); Meteor.publish("users", function() { return Meteor.users.find({}); }); Meteor.publish("forum", function(id) { if (!id) { id = Post.findOne({ isRoot: true })._id; } return [ Post.find({ _id: id }), Link.find({ $or: [ { sourceId: id }, { targetId: id } ] }) ]; });
Restricted user data that non-moderators have access to.
server/publish.js
Restricted user data that non-moderators have access to.
<ide><path>erver/publish.js <ide> }); <ide> <ide> Meteor.publish("users", function() { <del> return Meteor.users.find({}); <add> if (Roles.userIsInRole(this.userId, ['moderator'])) { <add> return Meteor.users.find({}); <add> } else { <add> return Meteor.users.find({}, { <add> fields: { <add> "emails" : 0, <add> "services" : 0, <add> "defaultEmail" : 0 //Exclude defaultEmail from the sent data <add> } <add> }); <add> } <ide> }); <ide> <ide> Meteor.publish("forum", function(id) {
Java
apache-2.0
ace15624bfdb0e6a255128d633d9ccae472ebfec
0
gpolitis/jitsi,ibauersachs/jitsi,pplatek/jitsi,martin7890/jitsi,459below/jitsi,tuijldert/jitsi,HelioGuilherme66/jitsi,459below/jitsi,marclaporte/jitsi,jitsi/jitsi,459below/jitsi,level7systems/jitsi,HelioGuilherme66/jitsi,bhatvv/jitsi,ringdna/jitsi,HelioGuilherme66/jitsi,jibaro/jitsi,jitsi/jitsi,tuijldert/jitsi,mckayclarey/jitsi,procandi/jitsi,procandi/jitsi,mckayclarey/jitsi,dkcreinoso/jitsi,ringdna/jitsi,iant-gmbh/jitsi,martin7890/jitsi,HelioGuilherme66/jitsi,cobratbq/jitsi,jibaro/jitsi,gpolitis/jitsi,bebo/jitsi,martin7890/jitsi,bhatvv/jitsi,tuijldert/jitsi,laborautonomo/jitsi,level7systems/jitsi,iant-gmbh/jitsi,iant-gmbh/jitsi,pplatek/jitsi,procandi/jitsi,pplatek/jitsi,459below/jitsi,laborautonomo/jitsi,iant-gmbh/jitsi,marclaporte/jitsi,damencho/jitsi,tuijldert/jitsi,martin7890/jitsi,HelioGuilherme66/jitsi,gpolitis/jitsi,tuijldert/jitsi,cobratbq/jitsi,ibauersachs/jitsi,bhatvv/jitsi,dkcreinoso/jitsi,mckayclarey/jitsi,bhatvv/jitsi,procandi/jitsi,bebo/jitsi,dkcreinoso/jitsi,martin7890/jitsi,pplatek/jitsi,ibauersachs/jitsi,jibaro/jitsi,cobratbq/jitsi,ringdna/jitsi,bhatvv/jitsi,bebo/jitsi,damencho/jitsi,laborautonomo/jitsi,ringdna/jitsi,marclaporte/jitsi,jibaro/jitsi,cobratbq/jitsi,gpolitis/jitsi,bebo/jitsi,marclaporte/jitsi,level7systems/jitsi,laborautonomo/jitsi,dkcreinoso/jitsi,mckayclarey/jitsi,procandi/jitsi,ibauersachs/jitsi,459below/jitsi,mckayclarey/jitsi,damencho/jitsi,damencho/jitsi,level7systems/jitsi,marclaporte/jitsi,iant-gmbh/jitsi,gpolitis/jitsi,level7systems/jitsi,pplatek/jitsi,laborautonomo/jitsi,jibaro/jitsi,bebo/jitsi,ringdna/jitsi,dkcreinoso/jitsi,jitsi/jitsi,cobratbq/jitsi,jitsi/jitsi,jitsi/jitsi,damencho/jitsi,ibauersachs/jitsi
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.service.protocol.jabber; import net.java.sip.communicator.service.protocol.*; import java.util.*; /** * The Jabber implementation of a sip-communicator AccountID * * @author Damian Minkov * @author Sebastien Vincent * @author Pawel Domas */ public class JabberAccountID extends AccountID { /** * Default properties prefix used in jitsi-defaults.properties file * for Jabber protocol. */ private static final String JBR_DEFAULTS_PREFIX = AccountID.DEFAULTS_PREFIX +"jabber."; /** * Account suffix for Google service. */ public static final String GOOGLE_USER_SUFFIX = "gmail.com"; /** * XMPP server for Google service. */ public static final String GOOGLE_CONNECT_SRV = "talk.google.com"; /** * The default value of stun server port for jabber accounts. */ public static final String DEFAULT_STUN_PORT = "3478"; /** * Indicates if keep alive packets should be send. */ public static final String SEND_KEEP_ALIVE = "SEND_KEEP_ALIVE"; /** * Indicates if gmail notifications should be enabled. */ public static final String GMAIL_NOTIFICATIONS_ENABLED = "GMAIL_NOTIFICATIONS_ENABLED"; /** * Always call with gtalk property. * * It is used to bypass capabilities checks: some softwares do not advertise * GTalk support (but they support it). */ public static final String BYPASS_GTALK_CAPABILITIES = "BYPASS_GTALK_CAPABILITIES"; /** * Indicates if Google Contacts should be enabled. */ public static final String GOOGLE_CONTACTS_ENABLED = "GOOGLE_CONTACTS_ENABLED"; /** * Domain name that will bypass GTalk caps. */ public static final String TELEPHONY_BYPASS_GTALK_CAPS = "TELEPHONY_BYPASS_GTALK_CAPS"; /** * The override domain for phone call. * * If Jabber account is able to call PSTN number and if domain name of the * switch is different than the domain of the account (gw.domain.org vs * domain.org), you can use this property to set the switch domain. */ public static final String OVERRIDE_PHONE_SUFFIX = "OVERRIDE_PHONE_SUFFIX"; /** * Creates an account id from the specified id and account properties. * @param id the id identifying this account * @param accountProperties any other properties necessary for the account. */ public JabberAccountID(String id, Map<String, String> accountProperties) { super( id, accountProperties, ProtocolNames.JABBER, getServiceName(accountProperties)); } /** * Default constructor for serialization purposes. */ public JabberAccountID() { this(null, new HashMap<String, String>()); } /** * Returns the override phone suffix. * * @return the phone suffix */ public String getOverridePhoneSuffix() { return getAccountPropertyString(OVERRIDE_PHONE_SUFFIX); } /** * Returns the actual name of this protocol: {@link ProtocolNames#JABBER}. * * @return Jabber: the name of this protocol. */ public String getSystemProtocolName() { return ProtocolNames.JABBER; } /** * Returns the alwaysCallWithGtalk value. * * @return the alwaysCallWithGtalk value */ public boolean getBypassGtalkCaps() { return getAccountPropertyBoolean(BYPASS_GTALK_CAPABILITIES, false); } /** * Returns telephony domain that bypass GTalk caps. * * @return telephony domain */ public String getTelephonyDomainBypassCaps() { return getAccountPropertyString(TELEPHONY_BYPASS_GTALK_CAPS); } /** * Gets if Jingle is disabled for this account. * * @return True if jingle is disabled for this account. False otherwise. */ public boolean isJingleDisabled() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_CALLING_DISABLED_FOR_ACCOUNT, false); } /** * Determines whether sending of keep alive packets is enabled. * * @return <tt>true</tt> if keep alive packets are to be sent for this * account and <tt>false</tt> otherwise. */ public boolean isSendKeepAlive() { return getAccountPropertyBoolean(SEND_KEEP_ALIVE, true); } /** * Determines whether SIP Communicator should be querying Gmail servers * for unread mail messages. * * @return <tt>true</tt> if we are to enable Gmail notifications and * <tt>false</tt> otherwise. */ public boolean isGmailNotificationEnabled() { return getAccountPropertyBoolean(GMAIL_NOTIFICATIONS_ENABLED, false); } /** * Determines whether SIP Communicator should use Google Contacts as * ContactSource * * @return <tt>true</tt> if we are to enable Google Contacts and * <tt>false</tt> otherwise. */ public boolean isGoogleContactsEnabled() { return getAccountPropertyBoolean(GOOGLE_CONTACTS_ENABLED, true); } /** * Sets the override value of the phone suffix. * * @param phoneSuffix the phone name suffix (the domain name after the @ * sign) */ public void setOverridePhoneSufix(String phoneSuffix) { setOrRemoveIfEmpty(OVERRIDE_PHONE_SUFFIX, phoneSuffix); } /** * Sets value for alwaysCallWithGtalk. * * @param bypassGtalkCaps true to enable, false otherwise */ public void setBypassGtalkCaps(boolean bypassGtalkCaps) { putAccountProperty(BYPASS_GTALK_CAPABILITIES, bypassGtalkCaps); } /** * Sets telephony domain that bypass GTalk caps. * * @param text telephony domain to set */ public void setTelephonyDomainBypassCaps(String text) { setOrRemoveIfEmpty(TELEPHONY_BYPASS_GTALK_CAPS, text); } /** * Sets if Jingle is disabled for this account. * * @param disabled True if jingle is disabled for this account. * False otherwise. */ public void setDisableJingle(boolean disabled) { putAccountProperty( ProtocolProviderFactory.IS_CALLING_DISABLED_FOR_ACCOUNT, disabled ); } /** * Specifies whether SIP Communicator should send send keep alive packets * to keep this account registered. * * @param sendKeepAlive <tt>true</tt> if we are to send keep alive packets * and <tt>false</tt> otherwise. */ public void setSendKeepAlive(boolean sendKeepAlive) { putAccountProperty(SEND_KEEP_ALIVE, sendKeepAlive); } /** * Specifies whether SIP Communicator should be querying Gmail servers * for unread mail messages. * * @param enabled <tt>true</tt> if we are to enable Gmail notification and * <tt>false</tt> otherwise. */ public void setGmailNotificationEnabled(boolean enabled) { putAccountProperty(GMAIL_NOTIFICATIONS_ENABLED, enabled); } /** * Specifies whether SIP Communicator should use Google Contacts as * ContactSource. * * @param enabled <tt>true</tt> if we are to enable Google Contacts and * <tt>false</tt> otherwise. */ public void setGoogleContactsEnabled(boolean enabled) { putAccountProperty(GOOGLE_CONTACTS_ENABLED, enabled); } /** * Returns the resource. * @return the resource */ public String getResource() { return getAccountPropertyString(ProtocolProviderFactory.RESOURCE); } /** * Sets the resource. * @param resource the resource for the jabber account */ public void setResource(String resource) { putAccountProperty(ProtocolProviderFactory.RESOURCE, resource); } /** * Returns the priority property. * @return priority */ public int getPriority() { return getAccountPropertyInt( ProtocolProviderFactory.RESOURCE_PRIORITY, 30); } /** * Sets the priority property. * @param priority the priority to set */ public void setPriority(int priority) { putAccountProperty( ProtocolProviderFactory.RESOURCE_PRIORITY, priority); } /** * Indicates if ice should be used for this account. * @return <tt>true</tt> if ICE should be used for this account, otherwise * returns <tt>false</tt> */ public boolean isUseIce() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_USE_ICE, true); } /** * Sets the <tt>useIce</tt> property. * @param isUseIce <tt>true</tt> to indicate that ICE should be used for * this account, <tt>false</tt> - otherwise. */ public void setUseIce(boolean isUseIce) { putAccountProperty(ProtocolProviderFactory.IS_USE_ICE, isUseIce); } /** * Indicates if ice should be used for this account. * @return <tt>true</tt> if ICE should be used for this account, otherwise * returns <tt>false</tt> */ public boolean isUseGoogleIce() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_USE_GOOGLE_ICE, true); } /** * Sets the <tt>useGoogleIce</tt> property. * @param isUseIce <tt>true</tt> to indicate that ICE should be used for * this account, <tt>false</tt> - otherwise. */ public void setUseGoogleIce(boolean isUseIce) { putAccountProperty( ProtocolProviderFactory.IS_USE_GOOGLE_ICE, isUseIce); } /** * Indicates if the stun server should be automatically discovered. * @return <tt>true</tt> if the stun server should be automatically * discovered, otherwise returns <tt>false</tt>. */ public boolean isAutoDiscoverStun() { return getAccountPropertyBoolean( ProtocolProviderFactory.AUTO_DISCOVER_STUN, true); } /** * Sets the <tt>autoDiscoverStun</tt> property. * @param isAutoDiscover <tt>true</tt> to indicate that stun server should * be auto-discovered, <tt>false</tt> - otherwise. */ public void setAutoDiscoverStun(boolean isAutoDiscover) { putAccountProperty( ProtocolProviderFactory.AUTO_DISCOVER_STUN, isAutoDiscover); } /** * Sets the <tt>useDefaultStunServer</tt> property. * @param isUseDefaultStunServer <tt>true</tt> to indicate that default * stun server should be used if no others are available, <tt>false</tt> * otherwise. */ public void setUseDefaultStunServer(boolean isUseDefaultStunServer) { putAccountProperty( ProtocolProviderFactory.USE_DEFAULT_STUN_SERVER, isUseDefaultStunServer ); } /** * Sets the <tt>autoDiscoverJingleNodes</tt> property. * * @param isAutoDiscover <tt>true</tt> to indicate that relay server should * be auto-discovered, <tt>false</tt> - otherwise. */ public void setAutoDiscoverJingleNodes(boolean isAutoDiscover) { putAccountProperty( ProtocolProviderFactory.AUTO_DISCOVER_JINGLE_NODES, isAutoDiscover ); } /** * Indicates if the JingleNodes relay server should be automatically * discovered. * * @return <tt>true</tt> if the relay server should be automatically * discovered, otherwise returns <tt>false</tt>. */ public boolean isAutoDiscoverJingleNodes() { return getAccountPropertyBoolean( ProtocolProviderFactory.AUTO_DISCOVER_JINGLE_NODES, true); } /** * Sets the <tt>useJingleNodes</tt> property. * * @param isUseJingleNodes <tt>true</tt> to indicate that Jingle Nodes * should be used for this account, <tt>false</tt> - otherwise. */ public void setUseJingleNodes(boolean isUseJingleNodes) { putAccountProperty( ProtocolProviderFactory.IS_USE_JINGLE_NODES, isUseJingleNodes); } /** * Indicates if JingleNodes relay should be used. * * @return <tt>true</tt> if JingleNodes should be used, <tt>false</tt> * otherwise */ public boolean isUseJingleNodes() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_USE_JINGLE_NODES, true); } /** * Indicates if UPnP should be used for this account. * @return <tt>true</tt> if UPnP should be used for this account, otherwise * returns <tt>false</tt> */ public boolean isUseUPNP() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_USE_UPNP, true); } /** * Sets the <tt>useUPNP</tt> property. * @param isUseUPNP <tt>true</tt> to indicate that UPnP should be used for * this account, <tt>false</tt> - otherwise. */ public void setUseUPNP(boolean isUseUPNP) { putAccountProperty(ProtocolProviderFactory.IS_USE_UPNP, isUseUPNP); } /** * Indicates if non-TLS is allowed for this account * @return <tt>true</tt> if non-TLS is allowed for this account, otherwise * returns <tt>false</tt> */ public boolean isAllowNonSecure() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_ALLOW_NON_SECURE, false); } /** * Sets the <tt>isAllowNonSecure</tt> property. * @param isAllowNonSecure <tt>true</tt> to indicate that non-TLS is allowed * for this account, <tt>false</tt> - otherwise. */ public void setAllowNonSecure(boolean isAllowNonSecure) { putAccountProperty( ProtocolProviderFactory.IS_ALLOW_NON_SECURE, isAllowNonSecure); } /** * Indicates if message carbons are allowed for this account * @return <tt>true</tt> if message carbons are allowed for this account, * otherwise returns <tt>false</tt> */ public boolean isCarbonDisabled() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_CARBON_DISABLED, false); } /** * Sets the <tt>IS_CARBON_DISABLED</tt> property. * @param isCarbonEnabled <tt>true</tt> to indicate that message carbons are * allowed for this account, <tt>false</tt> - otherwise. */ public void setDisableCarbon(boolean isCarbonEnabled) { putAccountProperty( ProtocolProviderFactory.IS_CARBON_DISABLED, isCarbonEnabled); } /** * Is resource auto generate enabled. * * @return true if resource is auto generated */ public boolean isResourceAutogenerated() { return getAccountPropertyBoolean( ProtocolProviderFactory.AUTO_GENERATE_RESOURCE, true ); } /** * Set whether resource autogenerate is enabled. * @param resourceAutogenerated */ public void setResourceAutogenerated(boolean resourceAutogenerated) { putAccountProperty( ProtocolProviderFactory.AUTO_GENERATE_RESOURCE, resourceAutogenerated ); } /** * Returns the default sms server. * * @return the account default sms server */ public String getSmsServerAddress() { return getAccountPropertyString( ProtocolProviderFactory.SMS_SERVER_ADDRESS); } /** * Sets the default sms server. * * @param serverAddress the sms server to set as default */ public void setSmsServerAddress(String serverAddress) { setOrRemoveIfEmpty( ProtocolProviderFactory.SMS_SERVER_ADDRESS, serverAddress); } /** * Returns the service name - the server we are logging to * if it is null which is not supposed to be - we return for compatibility * the string we used in the first release for creating AccountID * (Using this string is wrong, but used for compatibility for now) * @param accountProperties Map * @return String */ private static String getServiceName(Map<String, String> accountProperties) { return accountProperties.get(ProtocolProviderFactory.SERVER_ADDRESS); } /** * Returns the list of JingleNodes trackers/relays that this account is * currently configured to use. * * @return the list of JingleNodes trackers/relays that this account is * currently configured to use. */ public List<JingleNodeDescriptor> getJingleNodes() { Map<String, String> accountProperties = getAccountProperties(); List<JingleNodeDescriptor> serList = new ArrayList<JingleNodeDescriptor>(); for (int i = 0; i < JingleNodeDescriptor.MAX_JN_RELAY_COUNT; i ++) { JingleNodeDescriptor node = JingleNodeDescriptor.loadDescriptor( accountProperties, JingleNodeDescriptor.JN_PREFIX + i); // If we don't find a relay server with the given index, it means // that there're no more servers left in the table so we've nothing // more to do here. if (node == null) break; serList.add(node); } return serList; } /** * Determines whether this account's provider is supposed to auto discover * JingleNodes relay. * * @return <tt>true</tt> if this provider would need to discover JingleNodes * relay, <tt>false</tt> otherwise */ public boolean isJingleNodesAutoDiscoveryEnabled() { return getAccountPropertyBoolean( ProtocolProviderFactory.AUTO_DISCOVER_JINGLE_NODES, true); } /** * Determines whether this account's provider is supposed to auto discover * JingleNodes relay by searching our contacts. * * @return <tt>true</tt> if this provider would need to discover JingleNodes * relay by searching buddies, <tt>false</tt> otherwise */ public boolean isJingleNodesSearchBuddiesEnabled() { return getAccountPropertyBoolean( ProtocolProviderFactory.JINGLE_NODES_SEARCH_BUDDIES, false); } /** * Determines whether this account's provider uses JingleNodes relay (if * available). * * @return <tt>true</tt> if this provider would use JingleNodes relay (if * available), <tt>false</tt> otherwise */ public boolean isJingleNodesRelayEnabled() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_USE_JINGLE_NODES, true); } /** * Determines whether this account's provider allow non-secure connection * * @return <tt>true</tt> if this provider would allow non-secure connection, * <tt>false</tt> otherwise */ public boolean allowNonSecureConnection() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_ALLOW_NON_SECURE, false); } /** * {@inheritDoc} */ protected String getDefaultString(String key) { return JabberAccountID.getDefaultStr(key); } /** * Gets default property value for given <tt>key</tt>. * * @param key the property key * @return default property value for given<tt>key</tt> */ public static String getDefaultStr(String key) { String value = ProtocolProviderActivator .getConfigurationService() .getString(JBR_DEFAULTS_PREFIX +key); if(value == null) value = AccountID.getDefaultStr(key); return value; } /** * Gets default boolean property value for given <tt>key</tt>. * * @param key the property key * @return default property value for given<tt>key</tt> */ public static boolean getDefaultBool(String key) { return Boolean.parseBoolean(getDefaultStr(key)); } }
src/net/java/sip/communicator/service/protocol/jabber/JabberAccountID.java
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.service.protocol.jabber; import net.java.sip.communicator.service.protocol.*; import java.util.*; /** * The Jabber implementation of a sip-communicator AccountID * * @author Damian Minkov * @author Sebastien Vincent * @author Pawel Domas */ public class JabberAccountID extends AccountID { /** * Default properties prefix used in jitsi-defaults.properties file * for Jabber protocol. */ private static final String JBR_DEFAULTS_PREFIX = AccountID.DEFAULTS_PREFIX +"jabber."; /** * Account suffix for Google service. */ public static final String GOOGLE_USER_SUFFIX = "gmail.com"; /** * XMPP server for Google service. */ public static final String GOOGLE_CONNECT_SRV = "talk.google.com"; /** * The default value of stun server port for jabber accounts. */ public static final String DEFAULT_STUN_PORT = "3478"; /** * Indicates if keep alive packets should be send. */ public static final String SEND_KEEP_ALIVE = "SEND_KEEP_ALIVE"; /** * Indicates if gmail notifications should be enabled. */ public static final String GMAIL_NOTIFICATIONS_ENABLED = "GMAIL_NOTIFICATIONS_ENABLED"; /** * Always call with gtalk property. * * It is used to bypass capabilities checks: some softwares do not advertise * GTalk support (but they support it). */ public static final String BYPASS_GTALK_CAPABILITIES = "BYPASS_GTALK_CAPABILITIES"; /** * Indicates if Google Contacts should be enabled. */ public static final String GOOGLE_CONTACTS_ENABLED = "GOOGLE_CONTACTS_ENABLED"; /** * Domain name that will bypass GTalk caps. */ public static final String TELEPHONY_BYPASS_GTALK_CAPS = "TELEPHONY_BYPASS_GTALK_CAPS"; /** * The override domain for phone call. * * If Jabber account is able to call PSTN number and if domain name of the * switch is different than the domain of the account (gw.domain.org vs * domain.org), you can use this property to set the switch domain. */ public static final String OVERRIDE_PHONE_SUFFIX = "OVERRIDE_PHONE_SUFFIX"; /** * Creates an account id from the specified id and account properties. * @param id the id identifying this account * @param accountProperties any other properties necessary for the account. */ public JabberAccountID(String id, Map<String, String> accountProperties) { super( id, accountProperties, ProtocolNames.JABBER, getServiceName(accountProperties)); } /** * Default constructor for serialization purposes. */ public JabberAccountID() { this(null, new HashMap<String, String>()); } /** * Returns the override phone suffix. * * @return the phone suffix */ public String getOverridePhoneSuffix() { return getAccountPropertyString(OVERRIDE_PHONE_SUFFIX); } /** * Returns the alwaysCallWithGtalk value. * * @return the alwaysCallWithGtalk value */ public boolean getBypassGtalkCaps() { return getAccountPropertyBoolean(BYPASS_GTALK_CAPABILITIES, false); } /** * Returns telephony domain that bypass GTalk caps. * * @return telephony domain */ public String getTelephonyDomainBypassCaps() { return getAccountPropertyString(TELEPHONY_BYPASS_GTALK_CAPS); } /** * Gets if Jingle is disabled for this account. * * @return True if jingle is disabled for this account. False otherwise. */ public boolean isJingleDisabled() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_CALLING_DISABLED_FOR_ACCOUNT, false); } /** * Determines whether sending of keep alive packets is enabled. * * @return <tt>true</tt> if keep alive packets are to be sent for this * account and <tt>false</tt> otherwise. */ public boolean isSendKeepAlive() { return getAccountPropertyBoolean(SEND_KEEP_ALIVE, true); } /** * Determines whether SIP Communicator should be querying Gmail servers * for unread mail messages. * * @return <tt>true</tt> if we are to enable Gmail notifications and * <tt>false</tt> otherwise. */ public boolean isGmailNotificationEnabled() { return getAccountPropertyBoolean(GMAIL_NOTIFICATIONS_ENABLED, false); } /** * Determines whether SIP Communicator should use Google Contacts as * ContactSource * * @return <tt>true</tt> if we are to enable Google Contacts and * <tt>false</tt> otherwise. */ public boolean isGoogleContactsEnabled() { return getAccountPropertyBoolean(GOOGLE_CONTACTS_ENABLED, true); } /** * Sets the override value of the phone suffix. * * @param phoneSuffix the phone name suffix (the domain name after the @ * sign) */ public void setOverridePhoneSufix(String phoneSuffix) { setOrRemoveIfEmpty(OVERRIDE_PHONE_SUFFIX, phoneSuffix); } /** * Sets value for alwaysCallWithGtalk. * * @param bypassGtalkCaps true to enable, false otherwise */ public void setBypassGtalkCaps(boolean bypassGtalkCaps) { putAccountProperty(BYPASS_GTALK_CAPABILITIES, bypassGtalkCaps); } /** * Sets telephony domain that bypass GTalk caps. * * @param text telephony domain to set */ public void setTelephonyDomainBypassCaps(String text) { setOrRemoveIfEmpty(TELEPHONY_BYPASS_GTALK_CAPS, text); } /** * Sets if Jingle is disabled for this account. * * @param disabled True if jingle is disabled for this account. * False otherwise. */ public void setDisableJingle(boolean disabled) { putAccountProperty( ProtocolProviderFactory.IS_CALLING_DISABLED_FOR_ACCOUNT, disabled ); } /** * Specifies whether SIP Communicator should send send keep alive packets * to keep this account registered. * * @param sendKeepAlive <tt>true</tt> if we are to send keep alive packets * and <tt>false</tt> otherwise. */ public void setSendKeepAlive(boolean sendKeepAlive) { putAccountProperty(SEND_KEEP_ALIVE, sendKeepAlive); } /** * Specifies whether SIP Communicator should be querying Gmail servers * for unread mail messages. * * @param enabled <tt>true</tt> if we are to enable Gmail notification and * <tt>false</tt> otherwise. */ public void setGmailNotificationEnabled(boolean enabled) { putAccountProperty(GMAIL_NOTIFICATIONS_ENABLED, enabled); } /** * Specifies whether SIP Communicator should use Google Contacts as * ContactSource. * * @param enabled <tt>true</tt> if we are to enable Google Contacts and * <tt>false</tt> otherwise. */ public void setGoogleContactsEnabled(boolean enabled) { putAccountProperty(GOOGLE_CONTACTS_ENABLED, enabled); } /** * Returns the resource. * @return the resource */ public String getResource() { return getAccountPropertyString(ProtocolProviderFactory.RESOURCE); } /** * Sets the resource. * @param resource the resource for the jabber account */ public void setResource(String resource) { putAccountProperty(ProtocolProviderFactory.RESOURCE, resource); } /** * Returns the priority property. * @return priority */ public int getPriority() { return getAccountPropertyInt( ProtocolProviderFactory.RESOURCE_PRIORITY, 30); } /** * Sets the priority property. * @param priority the priority to set */ public void setPriority(int priority) { putAccountProperty( ProtocolProviderFactory.RESOURCE_PRIORITY, priority); } /** * Indicates if ice should be used for this account. * @return <tt>true</tt> if ICE should be used for this account, otherwise * returns <tt>false</tt> */ public boolean isUseIce() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_USE_ICE, true); } /** * Sets the <tt>useIce</tt> property. * @param isUseIce <tt>true</tt> to indicate that ICE should be used for * this account, <tt>false</tt> - otherwise. */ public void setUseIce(boolean isUseIce) { putAccountProperty(ProtocolProviderFactory.IS_USE_ICE, isUseIce); } /** * Indicates if ice should be used for this account. * @return <tt>true</tt> if ICE should be used for this account, otherwise * returns <tt>false</tt> */ public boolean isUseGoogleIce() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_USE_GOOGLE_ICE, true); } /** * Sets the <tt>useGoogleIce</tt> property. * @param isUseIce <tt>true</tt> to indicate that ICE should be used for * this account, <tt>false</tt> - otherwise. */ public void setUseGoogleIce(boolean isUseIce) { putAccountProperty( ProtocolProviderFactory.IS_USE_GOOGLE_ICE, isUseIce); } /** * Indicates if the stun server should be automatically discovered. * @return <tt>true</tt> if the stun server should be automatically * discovered, otherwise returns <tt>false</tt>. */ public boolean isAutoDiscoverStun() { return getAccountPropertyBoolean( ProtocolProviderFactory.AUTO_DISCOVER_STUN, true); } /** * Sets the <tt>autoDiscoverStun</tt> property. * @param isAutoDiscover <tt>true</tt> to indicate that stun server should * be auto-discovered, <tt>false</tt> - otherwise. */ public void setAutoDiscoverStun(boolean isAutoDiscover) { putAccountProperty( ProtocolProviderFactory.AUTO_DISCOVER_STUN, isAutoDiscover); } /** * Sets the <tt>useDefaultStunServer</tt> property. * @param isUseDefaultStunServer <tt>true</tt> to indicate that default * stun server should be used if no others are available, <tt>false</tt> * otherwise. */ public void setUseDefaultStunServer(boolean isUseDefaultStunServer) { putAccountProperty( ProtocolProviderFactory.USE_DEFAULT_STUN_SERVER, isUseDefaultStunServer ); } /** * Sets the <tt>autoDiscoverJingleNodes</tt> property. * * @param isAutoDiscover <tt>true</tt> to indicate that relay server should * be auto-discovered, <tt>false</tt> - otherwise. */ public void setAutoDiscoverJingleNodes(boolean isAutoDiscover) { putAccountProperty( ProtocolProviderFactory.AUTO_DISCOVER_JINGLE_NODES, isAutoDiscover ); } /** * Indicates if the JingleNodes relay server should be automatically * discovered. * * @return <tt>true</tt> if the relay server should be automatically * discovered, otherwise returns <tt>false</tt>. */ public boolean isAutoDiscoverJingleNodes() { return getAccountPropertyBoolean( ProtocolProviderFactory.AUTO_DISCOVER_JINGLE_NODES, true); } /** * Sets the <tt>useJingleNodes</tt> property. * * @param isUseJingleNodes <tt>true</tt> to indicate that Jingle Nodes * should be used for this account, <tt>false</tt> - otherwise. */ public void setUseJingleNodes(boolean isUseJingleNodes) { putAccountProperty( ProtocolProviderFactory.IS_USE_JINGLE_NODES, isUseJingleNodes); } /** * Indicates if JingleNodes relay should be used. * * @return <tt>true</tt> if JingleNodes should be used, <tt>false</tt> * otherwise */ public boolean isUseJingleNodes() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_USE_JINGLE_NODES, true); } /** * Indicates if UPnP should be used for this account. * @return <tt>true</tt> if UPnP should be used for this account, otherwise * returns <tt>false</tt> */ public boolean isUseUPNP() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_USE_UPNP, true); } /** * Sets the <tt>useUPNP</tt> property. * @param isUseUPNP <tt>true</tt> to indicate that UPnP should be used for * this account, <tt>false</tt> - otherwise. */ public void setUseUPNP(boolean isUseUPNP) { putAccountProperty(ProtocolProviderFactory.IS_USE_UPNP, isUseUPNP); } /** * Indicates if non-TLS is allowed for this account * @return <tt>true</tt> if non-TLS is allowed for this account, otherwise * returns <tt>false</tt> */ public boolean isAllowNonSecure() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_ALLOW_NON_SECURE, false); } /** * Sets the <tt>isAllowNonSecure</tt> property. * @param isAllowNonSecure <tt>true</tt> to indicate that non-TLS is allowed * for this account, <tt>false</tt> - otherwise. */ public void setAllowNonSecure(boolean isAllowNonSecure) { putAccountProperty( ProtocolProviderFactory.IS_ALLOW_NON_SECURE, isAllowNonSecure); } /** * Indicates if message carbons are allowed for this account * @return <tt>true</tt> if message carbons are allowed for this account, * otherwise returns <tt>false</tt> */ public boolean isCarbonDisabled() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_CARBON_DISABLED, false); } /** * Sets the <tt>IS_CARBON_DISABLED</tt> property. * @param isCarbonEnabled <tt>true</tt> to indicate that message carbons are * allowed for this account, <tt>false</tt> - otherwise. */ public void setDisableCarbon(boolean isCarbonEnabled) { putAccountProperty( ProtocolProviderFactory.IS_CARBON_DISABLED, isCarbonEnabled); } /** * Is resource auto generate enabled. * * @return true if resource is auto generated */ public boolean isResourceAutogenerated() { return getAccountPropertyBoolean( ProtocolProviderFactory.AUTO_GENERATE_RESOURCE, true ); } /** * Set whether resource autogenerate is enabled. * @param resourceAutogenerated */ public void setResourceAutogenerated(boolean resourceAutogenerated) { putAccountProperty( ProtocolProviderFactory.AUTO_GENERATE_RESOURCE, resourceAutogenerated ); } /** * Returns the default sms server. * * @return the account default sms server */ public String getSmsServerAddress() { return getAccountPropertyString( ProtocolProviderFactory.SMS_SERVER_ADDRESS); } /** * Sets the default sms server. * * @param serverAddress the sms server to set as default */ public void setSmsServerAddress(String serverAddress) { setOrRemoveIfEmpty( ProtocolProviderFactory.SMS_SERVER_ADDRESS, serverAddress); } /** * Returns the service name - the server we are logging to * if it is null which is not supposed to be - we return for compatibility * the string we used in the first release for creating AccountID * (Using this string is wrong, but used for compatibility for now) * @param accountProperties Map * @return String */ private static String getServiceName(Map<String, String> accountProperties) { return accountProperties.get(ProtocolProviderFactory.SERVER_ADDRESS); } /** * Determines whether this account's provider is supposed to auto discover * STUN and TURN servers. * * @return <tt>true</tt> if this provider would need to discover STUN/TURN * servers and false otherwise. */ public boolean isStunServerDiscoveryEnabled() { return getAccountPropertyBoolean( ProtocolProviderFactory.AUTO_DISCOVER_STUN, true); } /** * Determines whether this account's provider uses the default STUN server * provided by SIP Communicator if there is no other STUN/TURN server * discovered/configured. * * @return <tt>true</tt> if this provider would use the default STUN server, * <tt>false</tt> otherwise */ public boolean isUseDefaultStunServer() { return getAccountPropertyBoolean( ProtocolProviderFactory.USE_DEFAULT_STUN_SERVER, true); } /** * Returns the list of JingleNodes trackers/relays that this account is * currently configured to use. * * @return the list of JingleNodes trackers/relays that this account is * currently configured to use. */ public List<JingleNodeDescriptor> getJingleNodes() { Map<String, String> accountProperties = getAccountProperties(); List<JingleNodeDescriptor> serList = new ArrayList<JingleNodeDescriptor>(); for (int i = 0; i < JingleNodeDescriptor.MAX_JN_RELAY_COUNT; i ++) { JingleNodeDescriptor node = JingleNodeDescriptor.loadDescriptor( accountProperties, JingleNodeDescriptor.JN_PREFIX + i); // If we don't find a relay server with the given index, it means // that there're no more servers left in the table so we've nothing // more to do here. if (node == null) break; serList.add(node); } return serList; } /** * Determines whether this account's provider is supposed to auto discover * JingleNodes relay. * * @return <tt>true</tt> if this provider would need to discover JingleNodes * relay, <tt>false</tt> otherwise */ public boolean isJingleNodesAutoDiscoveryEnabled() { return getAccountPropertyBoolean( ProtocolProviderFactory.AUTO_DISCOVER_JINGLE_NODES, true); } /** * Determines whether this account's provider is supposed to auto discover * JingleNodes relay by searching our contacts. * * @return <tt>true</tt> if this provider would need to discover JingleNodes * relay by searching buddies, <tt>false</tt> otherwise */ public boolean isJingleNodesSearchBuddiesEnabled() { return getAccountPropertyBoolean( ProtocolProviderFactory.JINGLE_NODES_SEARCH_BUDDIES, false); } /** * Determines whether this account's provider uses JingleNodes relay (if * available). * * @return <tt>true</tt> if this provider would use JingleNodes relay (if * available), <tt>false</tt> otherwise */ public boolean isJingleNodesRelayEnabled() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_USE_JINGLE_NODES, true); } /** * Determines whether this account's provider uses UPnP (if available). * * @return <tt>true</tt> if this provider would use UPnP (if available), * <tt>false</tt> otherwise */ public boolean isUPNPEnabled() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_USE_UPNP, true); } /** * Determines whether this account's provider allow non-secure connection * * @return <tt>true</tt> if this provider would allow non-secure connection, * <tt>false</tt> otherwise */ public boolean allowNonSecureConnection() { return getAccountPropertyBoolean( ProtocolProviderFactory.IS_ALLOW_NON_SECURE, false); } /** * {@inheritDoc} */ protected String getDefaultString(String key) { return JabberAccountID.getDefaultStr(key); } /** * Gets default property value for given <tt>key</tt>. * * @param key the property key * @return default property value for given<tt>key</tt> */ public static String getDefaultStr(String key) { String value = ProtocolProviderActivator .getConfigurationService() .getString(JBR_DEFAULTS_PREFIX +key); if(value == null) value = AccountID.getDefaultStr(key); return value; } /** * Gets default boolean property value for given <tt>key</tt>. * * @param key the property key * @return default property value for given<tt>key</tt> */ public static boolean getDefaultBool(String key) { return Boolean.parseBoolean(getDefaultStr(key)); } }
Moves generic ICE methods from Jabber to service.protocol so that they can be reused by SIP
src/net/java/sip/communicator/service/protocol/jabber/JabberAccountID.java
Moves generic ICE methods from Jabber to service.protocol so that they can be reused by SIP
<ide><path>rc/net/java/sip/communicator/service/protocol/jabber/JabberAccountID.java <ide> } <ide> <ide> /** <add> * Returns the actual name of this protocol: {@link ProtocolNames#JABBER}. <add> * <add> * @return Jabber: the name of this protocol. <add> */ <add> public String getSystemProtocolName() <add> { <add> return ProtocolNames.JABBER; <add> } <add> <add> /** <ide> * Returns the alwaysCallWithGtalk value. <ide> * <ide> * @return the alwaysCallWithGtalk value <ide> } <ide> <ide> /** <del> * Determines whether this account's provider is supposed to auto discover <del> * STUN and TURN servers. <del> * <del> * @return <tt>true</tt> if this provider would need to discover STUN/TURN <del> * servers and false otherwise. <del> */ <del> public boolean isStunServerDiscoveryEnabled() <del> { <del> return <del> getAccountPropertyBoolean( <del> ProtocolProviderFactory.AUTO_DISCOVER_STUN, <del> true); <del> } <del> <del> /** <del> * Determines whether this account's provider uses the default STUN server <del> * provided by SIP Communicator if there is no other STUN/TURN server <del> * discovered/configured. <del> * <del> * @return <tt>true</tt> if this provider would use the default STUN server, <del> * <tt>false</tt> otherwise <del> */ <del> public boolean isUseDefaultStunServer() <del> { <del> return <del> getAccountPropertyBoolean( <del> ProtocolProviderFactory.USE_DEFAULT_STUN_SERVER, <del> true); <del> } <del> <del> /** <ide> * Returns the list of JingleNodes trackers/relays that this account is <ide> * currently configured to use. <ide> * <ide> } <ide> <ide> /** <del> * Determines whether this account's provider uses UPnP (if available). <del> * <del> * @return <tt>true</tt> if this provider would use UPnP (if available), <del> * <tt>false</tt> otherwise <del> */ <del> public boolean isUPNPEnabled() <del> { <del> return getAccountPropertyBoolean( <del> ProtocolProviderFactory.IS_USE_UPNP, <del> true); <del> } <del> <del> /** <ide> * Determines whether this account's provider allow non-secure connection <ide> * <ide> * @return <tt>true</tt> if this provider would allow non-secure connection,
Java
apache-2.0
6c6ba66a3fb4f6af4fd536f2faa6d295ed013b36
0
stepancheg/async-http-client,Aulust/async-http-client,jxauchengchao/async-http-client,junjiemars/async-http-client,ooon/async-http-client,elijah513/async-http-client,bomgar/async-http-client,thinker-fang/async-http-client,liuyb02/async-http-client,afelisatti/async-http-client,hgl888/async-http-client,fengshao0907/async-http-client,magiccao/async-http-client,nemoyixin/async-http-client,wyyl1/async-http-client,Aulust/async-http-client,olksdr/async-http-client,dotta/async-http-client,drmaas/async-http-client,craigwblake/async-http-client-1,ALEXGUOQ/async-http-client
/* * Copyright (c) 2012 Sonatype, Inc. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package org.asynchttpclient.providers.grizzly; import org.asynchttpclient.AsyncHandler; import org.asynchttpclient.AsyncHttpClientConfig; import org.asynchttpclient.AsyncHttpProvider; import org.asynchttpclient.HttpResponseBodyPart; import org.asynchttpclient.HttpResponseHeaders; import org.asynchttpclient.HttpResponseStatus; import org.asynchttpclient.ListenableFuture; import org.asynchttpclient.ProxyServer; import org.asynchttpclient.Request; import org.asynchttpclient.Response; import org.asynchttpclient.ntlm.NTLMEngine; import org.asynchttpclient.providers.grizzly.bodyhandler.BodyHandler; import org.asynchttpclient.providers.grizzly.bodyhandler.BodyHandlerFactory; import org.asynchttpclient.providers.grizzly.bodyhandler.ExpectHandler; import org.asynchttpclient.providers.grizzly.filters.AsyncHttpClientEventFilter; import org.asynchttpclient.providers.grizzly.filters.AsyncHttpClientFilter; import org.asynchttpclient.providers.grizzly.filters.AsyncHttpClientTransportFilter; import org.asynchttpclient.providers.grizzly.filters.AsyncSpdyClientEventFilter; import org.asynchttpclient.providers.grizzly.filters.ClientEncodingFilter; import org.asynchttpclient.providers.grizzly.filters.SwitchingSSLFilter; import org.asynchttpclient.util.AsyncHttpProviderUtils; import org.asynchttpclient.util.ProxyUtils; import org.asynchttpclient.util.SslUtils; import org.glassfish.grizzly.CompletionHandler; import org.glassfish.grizzly.Connection; import org.glassfish.grizzly.WriteResult; import org.glassfish.grizzly.filterchain.Filter; import org.glassfish.grizzly.filterchain.FilterChain; import org.glassfish.grizzly.filterchain.FilterChainBuilder; import org.glassfish.grizzly.filterchain.FilterChainContext; import org.glassfish.grizzly.http.ContentEncoding; import org.glassfish.grizzly.http.GZipContentEncoding; import org.glassfish.grizzly.http.HttpClientFilter; import org.glassfish.grizzly.http.HttpContent; import org.glassfish.grizzly.http.HttpRequestPacket; import org.glassfish.grizzly.http.Method; import org.glassfish.grizzly.npn.ClientSideNegotiator; import org.glassfish.grizzly.spdy.NextProtoNegSupport; import org.glassfish.grizzly.spdy.SpdyFramingFilter; import org.glassfish.grizzly.spdy.SpdyHandlerFilter; import org.glassfish.grizzly.spdy.SpdyMode; import org.glassfish.grizzly.spdy.SpdySession; import org.glassfish.grizzly.ssl.SSLBaseFilter; import org.glassfish.grizzly.ssl.SSLConnectionContext; import org.glassfish.grizzly.ssl.SSLUtils; import org.glassfish.grizzly.http.util.Header; import org.glassfish.grizzly.impl.SafeFutureImpl; import org.glassfish.grizzly.nio.transport.TCPNIOTransport; import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder; import org.glassfish.grizzly.ssl.SSLEngineConfigurator; import org.glassfish.grizzly.ssl.SSLFilter; import org.glassfish.grizzly.strategies.SameThreadIOStrategy; import org.glassfish.grizzly.strategies.WorkerThreadIOStrategy; import org.glassfish.grizzly.utils.DelayedExecutor; import org.glassfish.grizzly.utils.IdleTimeoutFilter; import org.glassfish.grizzly.websockets.WebSocketClientFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import java.io.File; import java.io.IOException; import java.util.LinkedHashSet; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static org.asynchttpclient.providers.grizzly.GrizzlyAsyncHttpProviderConfig.Property; import static org.asynchttpclient.providers.grizzly.GrizzlyAsyncHttpProviderConfig.Property.CONNECTION_POOL; import static org.asynchttpclient.providers.grizzly.GrizzlyAsyncHttpProviderConfig.Property.MAX_HTTP_PACKET_HEADER_SIZE; import static org.glassfish.grizzly.asyncqueue.AsyncQueueWriter.AUTO_SIZE; /** * A Grizzly 2.0-based implementation of {@link AsyncHttpProvider}. * * @author The Grizzly Team * @since 1.7.0 */ @SuppressWarnings("rawtypes") public class GrizzlyAsyncHttpProvider implements AsyncHttpProvider { public static final Logger LOGGER = LoggerFactory.getLogger(GrizzlyAsyncHttpProvider.class); public final static NTLMEngine NTLM_ENGINE = new NTLMEngine(); private final BodyHandlerFactory bodyHandlerFactory; private final AsyncHttpClientConfig clientConfig; private ConnectionManager connectionManager; private DelayedExecutor.Resolver<Connection> resolver; private DelayedExecutor timeoutExecutor; final TCPNIOTransport clientTransport; // ------------------------------------------------------------ Constructors public GrizzlyAsyncHttpProvider(final AsyncHttpClientConfig clientConfig) { this.clientConfig = clientConfig; final TCPNIOTransportBuilder builder = TCPNIOTransportBuilder.newInstance(); clientTransport = builder.build(); initializeTransport(clientConfig); try { clientTransport.start(); } catch (IOException ioe) { throw new RuntimeException(ioe); } bodyHandlerFactory = new BodyHandlerFactory(this); } // ------------------------------------------ Methods from AsyncHttpProvider /** * {@inheritDoc} */ public <T> ListenableFuture<T> execute(final Request request, final AsyncHandler<T> handler) throws IOException { if (clientTransport.isStopped()) { throw new IOException("AsyncHttpClient has been closed."); } final ProxyServer proxy = ProxyUtils.getProxyServer(clientConfig, request); final GrizzlyResponseFuture<T> future = new GrizzlyResponseFuture<T>(this, request, handler, proxy); future.setDelegate(SafeFutureImpl.<T>create()); final CompletionHandler<Connection> connectHandler = new CompletionHandler<Connection>() { @Override public void cancelled() { future.cancel(true); } @Override public void failed(final Throwable throwable) { future.abort(throwable); } @Override public void completed(final Connection c) { try { touchConnection(c, request); execute(c, request, handler, future); } catch (Exception e) { failed(e); } } @Override public void updated(final Connection c) { // no-op } }; connectionManager.doTrackedConnection(request, future, connectHandler); return future; } /** * {@inheritDoc} */ public void close() { try { connectionManager.destroy(); clientTransport.shutdownNow(); final ExecutorService service = clientConfig.executorService(); // service may be null due to a custom configuration that // leverages Grizzly's SameThreadIOStrategy. if (service != null) { service.shutdown(); } if (timeoutExecutor != null) { timeoutExecutor.stop(); } } catch (IOException ignored) { } } /** * {@inheritDoc} */ public Response prepareResponse(HttpResponseStatus status, HttpResponseHeaders headers, List<HttpResponseBodyPart> bodyParts) { return new GrizzlyResponse(status, headers, bodyParts, clientConfig.isRfc6265CookieEncoding()); } // ---------------------------------------------------------- Public Methods public AsyncHttpClientConfig getClientConfig() { return clientConfig; } public ConnectionManager getConnectionManager() { return connectionManager; } public DelayedExecutor.Resolver<Connection> getResolver() { return resolver; } // ------------------------------------------------------- Protected Methods @SuppressWarnings({"unchecked"}) public <T> ListenableFuture<T> execute(final Connection c, final Request request, final AsyncHandler<T> handler, final GrizzlyResponseFuture<T> future) { Utils.addRequestInFlight(c); if (HttpTransactionContext.get(c) == null) { HttpTransactionContext.create(this, future, request, handler, c); } c.write(request, createWriteCompletionHandler(future)); return future; } void initializeTransport(final AsyncHttpClientConfig clientConfig) { final FilterChainBuilder secure = FilterChainBuilder.stateless(); secure.add(new AsyncHttpClientTransportFilter()); final int timeout = clientConfig.getRequestTimeoutInMs(); if (timeout > 0) { int delay = 500; //noinspection ConstantConditions if (timeout < delay) { delay = timeout - 10; if (delay <= 0) { delay = timeout; } } timeoutExecutor = IdleTimeoutFilter.createDefaultIdleDelayedExecutor(delay, TimeUnit.MILLISECONDS); timeoutExecutor.start(); final IdleTimeoutFilter.TimeoutResolver timeoutResolver = new IdleTimeoutFilter.TimeoutResolver() { @Override public long getTimeout(FilterChainContext ctx) { final HttpTransactionContext context = HttpTransactionContext.get(ctx.getConnection()); if (context != null) { if (context.isWSRequest()) { return clientConfig.getWebSocketIdleTimeoutInMs(); } int requestTimeout = AsyncHttpProviderUtils.requestTimeout(clientConfig, context.getRequest()); if (requestTimeout > 0) { return requestTimeout; } } return IdleTimeoutFilter.FOREVER; } }; final IdleTimeoutFilter timeoutFilter = new IdleTimeoutFilter(timeoutExecutor, timeoutResolver, new IdleTimeoutFilter.TimeoutHandler() { public void onTimeout(Connection connection) { timeout(connection); } }); secure.add(timeoutFilter); resolver = timeoutFilter.getResolver(); } SSLContext context = clientConfig.getSSLContext(); if (context == null) { try { context = SslUtils.getSSLContext(); } catch (Exception e) { throw new IllegalStateException(e); } } final SSLEngineConfigurator configurator = new SSLEngineConfigurator(context, true, false, false); final SwitchingSSLFilter filter = new SwitchingSSLFilter(configurator); secure.add(filter); GrizzlyAsyncHttpProviderConfig providerConfig = (GrizzlyAsyncHttpProviderConfig) clientConfig.getAsyncHttpProviderConfig(); boolean npnEnabled = NextProtoNegSupport.isEnabled(); boolean spdyEnabled = clientConfig.isSpdyEnabled(); if (spdyEnabled) { // if NPN isn't available, check to see if it has been explicitly // disabled. If it has, we assume the user knows what they are doing // and we enable SPDY without NPN - this effectively disables standard // HTTP/1.1 support. if (!npnEnabled && providerConfig != null) { if ((Boolean) providerConfig.getProperty(Property.NPN_ENABLED)) { // NPN hasn't been disabled, so it's most likely a configuration problem. // Log a warning and disable spdy support. LOGGER.warn("Next Protocol Negotiation support is not available. SPDY support has been disabled."); spdyEnabled = false; } } } final AsyncHttpClientEventFilter eventFilter; final EventHandler handler = new EventHandler(this); if (providerConfig != null) { eventFilter = new AsyncHttpClientEventFilter(handler, (Integer) providerConfig .getProperty( MAX_HTTP_PACKET_HEADER_SIZE)); } else { eventFilter = new AsyncHttpClientEventFilter(handler); } handler.cleanup = eventFilter; ContentEncoding[] encodings = eventFilter.getContentEncodings(); if (encodings.length > 0) { for (ContentEncoding encoding : encodings) { eventFilter.removeContentEncoding(encoding); } } if (clientConfig.isCompressionEnabled()) { eventFilter.addContentEncoding( new GZipContentEncoding(512, 512, new ClientEncodingFilter())); } secure.add(eventFilter); final AsyncHttpClientFilter clientFilter = new AsyncHttpClientFilter(this, clientConfig); secure.add(clientFilter); secure.add(new WebSocketClientFilter()); clientTransport.getAsyncQueueIO().getWriter() .setMaxPendingBytesPerConnection(AUTO_SIZE); if (providerConfig != null) { final TransportCustomizer customizer = (TransportCustomizer) providerConfig.getProperty(Property.TRANSPORT_CUSTOMIZER); if (customizer != null) { customizer.customize(clientTransport, secure); } else { doDefaultTransportConfig(); } } else { doDefaultTransportConfig(); } // FilterChain for the standard HTTP case has been configured, we now // copy it and modify for SPDY purposes. if (spdyEnabled) { FilterChainBuilder spdyFilterChain = createSpdyFilterChain(secure, npnEnabled); ProtocolNegotiator pn = new ProtocolNegotiator(spdyFilterChain.build()); NextProtoNegSupport.getInstance() .setClientSideNegotiator(clientTransport, pn); } // Install the HTTP filter chain. //clientTransport.setProcessor(fcb.build()); FilterChainBuilder nonSecure = FilterChainBuilder.stateless(); nonSecure.addAll(secure); int idx = nonSecure.indexOfType(SSLFilter.class); nonSecure.remove(idx); final ConnectionPool pool; if (providerConfig != null) { pool = (ConnectionPool) providerConfig.getProperty(CONNECTION_POOL); } else { pool = null; } connectionManager = new ConnectionManager(this, pool, secure, nonSecure); } // ------------------------------------------------- Package Private Methods void touchConnection(final Connection c, final Request request) { int requestTimeout = AsyncHttpProviderUtils.requestTimeout(clientConfig, request); if (requestTimeout > 0) { if (resolver != null) { resolver.setTimeoutMillis(c, System.currentTimeMillis() + requestTimeout); } } } // --------------------------------------------------------- Private Methods private FilterChainBuilder createSpdyFilterChain(final FilterChainBuilder fcb, final boolean npnEnabled) { FilterChainBuilder spdyFcb = FilterChainBuilder.stateless(); spdyFcb.addAll(fcb); int idx = spdyFcb.indexOfType(SSLFilter.class); Filter f = spdyFcb.get(idx); // Adjust the SSLFilter to support NPN if (npnEnabled) { SSLBaseFilter sslBaseFilter = (SSLBaseFilter) f; NextProtoNegSupport.getInstance().configure(sslBaseFilter); } // Remove the HTTP Client filter - this will be replaced by the // SPDY framing and handler filters. idx = spdyFcb.indexOfType(HttpClientFilter.class); spdyFcb.set(idx, new SpdyFramingFilter()); final SpdyMode spdyMode = ((npnEnabled) ? SpdyMode.NPN : SpdyMode.PLAIN); AsyncSpdyClientEventFilter spdyFilter = new AsyncSpdyClientEventFilter(new EventHandler(this), spdyMode, clientConfig.executorService()); spdyFilter.setInitialWindowSize(clientConfig.getSpdyInitialWindowSize()); spdyFilter.setMaxConcurrentStreams(clientConfig.getSpdyMaxConcurrentStreams()); spdyFcb.add(idx + 1, spdyFilter); // Remove the WebSocket filter - not currently supported. idx = spdyFcb.indexOfType(WebSocketClientFilter.class); spdyFcb.remove(idx); return spdyFcb; } private void doDefaultTransportConfig() { final ExecutorService service = clientConfig.executorService(); if (service != null) { clientTransport.setIOStrategy(WorkerThreadIOStrategy.getInstance()); clientTransport.setWorkerThreadPool(service); } else { clientTransport.setIOStrategy(SameThreadIOStrategy.getInstance()); } } private <T> CompletionHandler<WriteResult> createWriteCompletionHandler(final GrizzlyResponseFuture<T> future) { return new CompletionHandler<WriteResult>() { public void cancelled() { future.cancel(true); } public void failed(Throwable throwable) { future.abort(throwable); } public void completed(WriteResult result) { } public void updated(WriteResult result) { // no-op } }; } void timeout(final Connection c) { final HttpTransactionContext context = HttpTransactionContext.get(c); if (context != null) { HttpTransactionContext.set(c, null); context.abort(new TimeoutException("Timeout exceeded")); } } @SuppressWarnings({"unchecked"}) public boolean sendRequest(final FilterChainContext ctx, final Request request, final HttpRequestPacket requestPacket) throws IOException { boolean isWriteComplete = true; if (requestHasEntityBody(request)) { final HttpTransactionContext context = HttpTransactionContext.get(ctx.getConnection()); BodyHandler handler = bodyHandlerFactory.getBodyHandler(request); if (requestPacket.getHeaders().contains(Header.Expect) && requestPacket.getHeaders().getValue(1).equalsIgnoreCase("100-Continue")) { // We have to set the content-length now as the headers will be flushed // before the FileBodyHandler is invoked. If we don't do it here, and // the user didn't explicitly set the length, then the transfer-encoding // will be chunked and zero-copy file transfer will not occur. final File f = request.getFile(); if (f != null) { requestPacket.setContentLengthLong(f.length()); } handler = new ExpectHandler(handler); } context.setBodyHandler(handler); if (LOGGER.isDebugEnabled()) { LOGGER.debug("REQUEST: {}", requestPacket); } isWriteComplete = handler.doHandle(ctx, request, requestPacket); } else { HttpContent content = HttpContent.builder(requestPacket).last(true).build(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("REQUEST: {}", requestPacket); } ctx.write(content, ctx.getTransportContext().getCompletionHandler()); } return isWriteComplete; } public static boolean requestHasEntityBody(final Request request) { final String method = request.getMethod(); return (Method.POST.matchesMethod(method) || Method.PUT.matchesMethod(method) || Method.PATCH.matchesMethod(method) || Method.DELETE.matchesMethod(method)); } // ----------------------------------------------------------- Inner Classes // ---------------------------------------------------------- Nested Classes private static final class ProtocolNegotiator implements ClientSideNegotiator { private static final String SPDY = "spdy/3"; private static final String HTTP = "HTTP/1.1"; private final FilterChain spdyFilterChain; private final SpdyHandlerFilter spdyHandlerFilter; // -------------------------------------------------------- Constructors private ProtocolNegotiator(final FilterChain spdyFilterChain) { this.spdyFilterChain = spdyFilterChain; int idx = spdyFilterChain.indexOfType(SpdyHandlerFilter.class); spdyHandlerFilter = (SpdyHandlerFilter) spdyFilterChain.get(idx); } // ----------------------------------- Methods from ClientSideNegotiator @Override public boolean wantNegotiate(SSLEngine engine) { GrizzlyAsyncHttpProvider.LOGGER.info("ProtocolSelector::wantNegotiate"); return true; } @Override public String selectProtocol(SSLEngine engine, LinkedHashSet<String> strings) { GrizzlyAsyncHttpProvider.LOGGER.info("ProtocolSelector::selectProtocol: " + strings); final Connection connection = NextProtoNegSupport.getConnection(engine); // Give preference to SPDY/3. If not available, check for HTTP as a // fallback if (strings.contains(SPDY)) { GrizzlyAsyncHttpProvider.LOGGER.info("ProtocolSelector::selecting: " + SPDY); SSLConnectionContext sslCtx = SSLUtils.getSslConnectionContext(connection); sslCtx.setNewConnectionFilterChain(spdyFilterChain); final SpdySession spdySession = new SpdySession(connection, false, spdyHandlerFilter); spdySession.setLocalInitialWindowSize(spdyHandlerFilter.getInitialWindowSize()); spdySession.setLocalMaxConcurrentStreams(spdyHandlerFilter.getMaxConcurrentStreams()); Utils.setSpdyConnection(connection); SpdySession.bind(connection, spdySession); return SPDY; } else if (strings.contains(HTTP)) { GrizzlyAsyncHttpProvider.LOGGER.info("ProtocolSelector::selecting: " + HTTP); // Use the default HTTP FilterChain. return HTTP; } else { GrizzlyAsyncHttpProvider.LOGGER.info("ProtocolSelector::selecting NONE"); // no protocol support. Will close the connection when // onNoDeal is invoked return ""; } } @Override public void onNoDeal(SSLEngine engine) { GrizzlyAsyncHttpProvider.LOGGER.info("ProtocolSelector::onNoDeal"); final Connection connection = NextProtoNegSupport.getConnection(engine); connection.closeSilently(); } } public static interface Cleanup { void cleanup(final FilterChainContext ctx); } }
providers/grizzly/src/main/java/org/asynchttpclient/providers/grizzly/GrizzlyAsyncHttpProvider.java
/* * Copyright (c) 2012 Sonatype, Inc. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package org.asynchttpclient.providers.grizzly; import org.asynchttpclient.AsyncHandler; import org.asynchttpclient.AsyncHttpClientConfig; import org.asynchttpclient.AsyncHttpProvider; import org.asynchttpclient.HttpResponseBodyPart; import org.asynchttpclient.HttpResponseHeaders; import org.asynchttpclient.HttpResponseStatus; import org.asynchttpclient.ListenableFuture; import org.asynchttpclient.ProxyServer; import org.asynchttpclient.Request; import org.asynchttpclient.Response; import org.asynchttpclient.ntlm.NTLMEngine; import org.asynchttpclient.providers.grizzly.bodyhandler.BodyHandler; import org.asynchttpclient.providers.grizzly.bodyhandler.BodyHandlerFactory; import org.asynchttpclient.providers.grizzly.bodyhandler.ExpectHandler; import org.asynchttpclient.providers.grizzly.filters.AsyncHttpClientEventFilter; import org.asynchttpclient.providers.grizzly.filters.AsyncHttpClientFilter; import org.asynchttpclient.providers.grizzly.filters.AsyncHttpClientTransportFilter; import org.asynchttpclient.providers.grizzly.filters.AsyncSpdyClientEventFilter; import org.asynchttpclient.providers.grizzly.filters.ClientEncodingFilter; import org.asynchttpclient.providers.grizzly.filters.SwitchingSSLFilter; import org.asynchttpclient.util.AsyncHttpProviderUtils; import org.asynchttpclient.util.ProxyUtils; import org.asynchttpclient.util.SslUtils; import org.glassfish.grizzly.CompletionHandler; import org.glassfish.grizzly.Connection; import org.glassfish.grizzly.WriteResult; import org.glassfish.grizzly.filterchain.Filter; import org.glassfish.grizzly.filterchain.FilterChain; import org.glassfish.grizzly.filterchain.FilterChainBuilder; import org.glassfish.grizzly.filterchain.FilterChainContext; import org.glassfish.grizzly.http.ContentEncoding; import org.glassfish.grizzly.http.GZipContentEncoding; import org.glassfish.grizzly.http.HttpClientFilter; import org.glassfish.grizzly.http.HttpContent; import org.glassfish.grizzly.http.HttpRequestPacket; import org.glassfish.grizzly.http.Method; import org.glassfish.grizzly.npn.ClientSideNegotiator; import org.glassfish.grizzly.spdy.NextProtoNegSupport; import org.glassfish.grizzly.spdy.SpdyFramingFilter; import org.glassfish.grizzly.spdy.SpdyHandlerFilter; import org.glassfish.grizzly.spdy.SpdyMode; import org.glassfish.grizzly.spdy.SpdySession; import org.glassfish.grizzly.ssl.SSLBaseFilter; import org.glassfish.grizzly.ssl.SSLConnectionContext; import org.glassfish.grizzly.ssl.SSLUtils; import org.glassfish.grizzly.http.util.Header; import org.glassfish.grizzly.impl.SafeFutureImpl; import org.glassfish.grizzly.nio.transport.TCPNIOTransport; import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder; import org.glassfish.grizzly.ssl.SSLEngineConfigurator; import org.glassfish.grizzly.ssl.SSLFilter; import org.glassfish.grizzly.strategies.SameThreadIOStrategy; import org.glassfish.grizzly.strategies.WorkerThreadIOStrategy; import org.glassfish.grizzly.utils.DelayedExecutor; import org.glassfish.grizzly.utils.IdleTimeoutFilter; import org.glassfish.grizzly.websockets.WebSocketClientFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import java.io.File; import java.io.IOException; import java.util.LinkedHashSet; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static org.asynchttpclient.providers.grizzly.GrizzlyAsyncHttpProviderConfig.Property; import static org.asynchttpclient.providers.grizzly.GrizzlyAsyncHttpProviderConfig.Property.CONNECTION_POOL; import static org.asynchttpclient.providers.grizzly.GrizzlyAsyncHttpProviderConfig.Property.MAX_HTTP_PACKET_HEADER_SIZE; import static org.glassfish.grizzly.asyncqueue.AsyncQueueWriter.AUTO_SIZE; /** * A Grizzly 2.0-based implementation of {@link AsyncHttpProvider}. * * @author The Grizzly Team * @since 1.7.0 */ @SuppressWarnings("rawtypes") public class GrizzlyAsyncHttpProvider implements AsyncHttpProvider { public static final Logger LOGGER = LoggerFactory.getLogger(GrizzlyAsyncHttpProvider.class); public final static NTLMEngine NTLM_ENGINE = new NTLMEngine(); private final BodyHandlerFactory bodyHandlerFactory; private final AsyncHttpClientConfig clientConfig; private ConnectionManager connectionManager; private DelayedExecutor.Resolver<Connection> resolver; private DelayedExecutor timeoutExecutor; final TCPNIOTransport clientTransport; // ------------------------------------------------------------ Constructors public GrizzlyAsyncHttpProvider(final AsyncHttpClientConfig clientConfig) { this.clientConfig = clientConfig; final TCPNIOTransportBuilder builder = TCPNIOTransportBuilder.newInstance(); clientTransport = builder.build(); initializeTransport(clientConfig); try { clientTransport.start(); } catch (IOException ioe) { throw new RuntimeException(ioe); } bodyHandlerFactory = new BodyHandlerFactory(this); } // ------------------------------------------ Methods from AsyncHttpProvider /** * {@inheritDoc} */ public <T> ListenableFuture<T> execute(final Request request, final AsyncHandler<T> handler) throws IOException { if (clientTransport.isStopped()) { throw new IOException("AsyncHttpClient has been closed."); } final ProxyServer proxy = ProxyUtils.getProxyServer(clientConfig, request); final GrizzlyResponseFuture<T> future = new GrizzlyResponseFuture<T>(this, request, handler, proxy); future.setDelegate(SafeFutureImpl.<T>create()); final CompletionHandler<Connection> connectHandler = new CompletionHandler<Connection>() { @Override public void cancelled() { future.cancel(true); } @Override public void failed(final Throwable throwable) { future.abort(throwable); } @Override public void completed(final Connection c) { try { touchConnection(c, request); execute(c, request, handler, future); } catch (Exception e) { failed(e); } } @Override public void updated(final Connection c) { // no-op } }; connectionManager.doTrackedConnection(request, future, connectHandler); return future; } /** * {@inheritDoc} */ public void close() { try { connectionManager.destroy(); clientTransport.shutdownNow(); final ExecutorService service = clientConfig.executorService(); // service may be null due to a custom configuration that // leverages Grizzly's SameThreadIOStrategy. if (service != null) { service.shutdown(); } if (timeoutExecutor != null) { timeoutExecutor.stop(); } } catch (IOException ignored) { } } /** * {@inheritDoc} */ public Response prepareResponse(HttpResponseStatus status, HttpResponseHeaders headers, List<HttpResponseBodyPart> bodyParts) { return new GrizzlyResponse(status, headers, bodyParts, clientConfig.isRfc6265CookieEncoding()); } // ---------------------------------------------------------- Public Methods public AsyncHttpClientConfig getClientConfig() { return clientConfig; } public ConnectionManager getConnectionManager() { return connectionManager; } public DelayedExecutor.Resolver<Connection> getResolver() { return resolver; } // ------------------------------------------------------- Protected Methods @SuppressWarnings({"unchecked"}) public <T> ListenableFuture<T> execute(final Connection c, final Request request, final AsyncHandler<T> handler, final GrizzlyResponseFuture<T> future) { Utils.addRequestInFlight(c); if (HttpTransactionContext.get(c) == null) { HttpTransactionContext.create(this, future, request, handler, c); } c.write(request, createWriteCompletionHandler(future)); return future; } void initializeTransport(final AsyncHttpClientConfig clientConfig) { final FilterChainBuilder secure = FilterChainBuilder.stateless(); secure.add(new AsyncHttpClientTransportFilter()); final int timeout = clientConfig.getRequestTimeoutInMs(); if (timeout > 0) { int delay = 500; //noinspection ConstantConditions if (timeout < delay) { delay = timeout - 10; if (delay <= 0) { delay = timeout; } } timeoutExecutor = IdleTimeoutFilter.createDefaultIdleDelayedExecutor(delay, TimeUnit.MILLISECONDS); timeoutExecutor.start(); final IdleTimeoutFilter.TimeoutResolver timeoutResolver = new IdleTimeoutFilter.TimeoutResolver() { @Override public long getTimeout(FilterChainContext ctx) { final HttpTransactionContext context = HttpTransactionContext.get(ctx.getConnection()); if (context != null) { if (context.isWSRequest()) { return clientConfig.getWebSocketIdleTimeoutInMs(); } int requestTimeout = AsyncHttpProviderUtils.requestTimeout(clientConfig, context.getRequest()); if (requestTimeout > 0) { return requestTimeout; } } return IdleTimeoutFilter.FOREVER; } }; final IdleTimeoutFilter timeoutFilter = new IdleTimeoutFilter(timeoutExecutor, timeoutResolver, new IdleTimeoutFilter.TimeoutHandler() { public void onTimeout(Connection connection) { timeout(connection); } }); secure.add(timeoutFilter); resolver = timeoutFilter.getResolver(); } SSLContext context = clientConfig.getSSLContext(); if (context == null) { try { context = SslUtils.getSSLContext(); } catch (Exception e) { throw new IllegalStateException(e); } } final SSLEngineConfigurator configurator = new SSLEngineConfigurator(context, true, false, false); final SwitchingSSLFilter filter = new SwitchingSSLFilter(configurator); secure.add(filter); GrizzlyAsyncHttpProviderConfig providerConfig = (GrizzlyAsyncHttpProviderConfig) clientConfig.getAsyncHttpProviderConfig(); boolean npnEnabled = NextProtoNegSupport.isEnabled(); boolean spdyEnabled = clientConfig.isSpdyEnabled(); if (spdyEnabled) { // if NPN isn't available, check to see if it has been explicitly // disabled. If it has, we assume the user knows what they are doing // and we enable SPDY without NPN - this effectively disables standard // HTTP/1.1 support. if (!npnEnabled && providerConfig != null) { if ((Boolean) providerConfig.getProperty(Property.NPN_ENABLED)) { // NPN hasn't been disabled, so it's most likely a configuration problem. // Log a warning and disable spdy support. LOGGER.warn("Next Protocol Negotiation support is not available. SPDY support has been disabled."); spdyEnabled = false; } } } final AsyncHttpClientEventFilter eventFilter; final EventHandler handler = new EventHandler(this); if (providerConfig != null) { eventFilter = new AsyncHttpClientEventFilter(handler, (Integer) providerConfig .getProperty( MAX_HTTP_PACKET_HEADER_SIZE)); } else { eventFilter = new AsyncHttpClientEventFilter(handler); } handler.cleanup = eventFilter; ContentEncoding[] encodings = eventFilter.getContentEncodings(); if (encodings.length > 0) { for (ContentEncoding encoding : encodings) { eventFilter.removeContentEncoding(encoding); } } if (clientConfig.isCompressionEnabled()) { eventFilter.addContentEncoding( new GZipContentEncoding(512, 512, new ClientEncodingFilter())); } secure.add(eventFilter); final AsyncHttpClientFilter clientFilter = new AsyncHttpClientFilter(this, clientConfig); secure.add(clientFilter); secure.add(new WebSocketClientFilter()); clientTransport.getAsyncQueueIO().getWriter() .setMaxPendingBytesPerConnection(AUTO_SIZE); if (providerConfig != null) { final TransportCustomizer customizer = (TransportCustomizer) providerConfig.getProperty(Property.TRANSPORT_CUSTOMIZER); if (customizer != null) { customizer.customize(clientTransport, secure); } else { doDefaultTransportConfig(); } } else { doDefaultTransportConfig(); } // FilterChain for the standard HTTP case has been configured, we now // copy it and modify for SPDY purposes. if (spdyEnabled) { FilterChainBuilder spdyFilterChain = createSpdyFilterChain(secure, npnEnabled); ProtocolNegotiator pn = new ProtocolNegotiator(spdyFilterChain.build()); NextProtoNegSupport.getInstance() .setClientSideNegotiator(clientTransport, pn); } // Install the HTTP filter chain. //clientTransport.setProcessor(fcb.build()); FilterChainBuilder nonSecure = FilterChainBuilder.stateless(); nonSecure.addAll(secure); int idx = nonSecure.indexOfType(SSLFilter.class); nonSecure.remove(idx); final ConnectionPool pool; if (providerConfig != null) { pool = (ConnectionPool) providerConfig.getProperty(CONNECTION_POOL); } else { pool = null; } connectionManager = new ConnectionManager(this, pool, secure, nonSecure); } // ------------------------------------------------- Package Private Methods void touchConnection(final Connection c, final Request request) { int requestTimeout = AsyncHttpProviderUtils.requestTimeout(clientConfig, request); if (requestTimeout > 0) { if (resolver != null) { resolver.setTimeoutMillis(c, System.currentTimeMillis() + requestTimeout); } } } // --------------------------------------------------------- Private Methods private FilterChainBuilder createSpdyFilterChain(final FilterChainBuilder fcb, final boolean npnEnabled) { FilterChainBuilder spdyFcb = FilterChainBuilder.stateless(); spdyFcb.addAll(fcb); int idx = spdyFcb.indexOfType(SSLFilter.class); Filter f = spdyFcb.get(idx); // Adjust the SSLFilter to support NPN if (npnEnabled) { SSLBaseFilter sslBaseFilter = (SSLBaseFilter) f; NextProtoNegSupport.getInstance().configure(sslBaseFilter); } // Remove the HTTP Client filter - this will be replaced by the // SPDY framing and handler filters. idx = spdyFcb.indexOfType(HttpClientFilter.class); spdyFcb.set(idx, new SpdyFramingFilter()); final SpdyMode spdyMode = ((npnEnabled) ? SpdyMode.NPN : SpdyMode.PLAIN); AsyncSpdyClientEventFilter spdyFilter = new AsyncSpdyClientEventFilter(new EventHandler(this), spdyMode, clientConfig.executorService()); spdyFilter.setInitialWindowSize(clientConfig.getSpdyInitialWindowSize()); spdyFilter.setMaxConcurrentStreams(clientConfig.getSpdyMaxConcurrentStreams()); spdyFcb.add(idx + 1, spdyFilter); // Remove the WebSocket filter - not currently supported. idx = spdyFcb.indexOfType(WebSocketClientFilter.class); spdyFcb.remove(idx); return spdyFcb; } private void doDefaultTransportConfig() { final ExecutorService service = clientConfig.executorService(); if (service != null) { clientTransport.setIOStrategy(WorkerThreadIOStrategy.getInstance()); clientTransport.setWorkerThreadPool(service); } else { clientTransport.setIOStrategy(SameThreadIOStrategy.getInstance()); } } private <T> CompletionHandler<WriteResult> createWriteCompletionHandler(final GrizzlyResponseFuture<T> future) { return new CompletionHandler<WriteResult>() { public void cancelled() { future.cancel(true); } public void failed(Throwable throwable) { future.abort(throwable); } public void completed(WriteResult result) { } public void updated(WriteResult result) { // no-op } }; } void timeout(final Connection c) { final HttpTransactionContext context = HttpTransactionContext.get(c); if (context != null) { HttpTransactionContext.set(c, null); context.abort(new TimeoutException("Timeout exceeded")); } } @SuppressWarnings({"unchecked"}) public boolean sendRequest(final FilterChainContext ctx, final Request request, final HttpRequestPacket requestPacket) throws IOException { boolean isWriteComplete = true; if (requestHasEntityBody(request)) { final HttpTransactionContext context = HttpTransactionContext.get(ctx.getConnection()); BodyHandler handler = bodyHandlerFactory.getBodyHandler(request); if (requestPacket.getHeaders().contains(Header.Expect) && requestPacket.getHeaders().getValue(1).equalsIgnoreCase("100-Continue")) { // We have to set the content-length now as the headers will be flushed // before the FileBodyHandler is invoked. If we don't do it here, and // the user didn't explicitly set the length, then the transfer-encoding // will be chunked and zero-copy file transfer will not occur. final File f = request.getFile(); if (f != null) { requestPacket.setContentLengthLong(f.length()); } handler = new ExpectHandler(handler); } context.setBodyHandler(handler); isWriteComplete = handler.doHandle(ctx, request, requestPacket); } else { HttpContent content = HttpContent.builder(requestPacket).last(true).build(); ctx.write(content, ctx.getTransportContext().getCompletionHandler()); } LOGGER.debug("REQUEST: {}", requestPacket); return isWriteComplete; } public static boolean requestHasEntityBody(final Request request) { final String method = request.getMethod(); return (Method.POST.matchesMethod(method) || Method.PUT.matchesMethod(method) || Method.PATCH.matchesMethod(method) || Method.DELETE.matchesMethod(method)); } // ----------------------------------------------------------- Inner Classes // ---------------------------------------------------------- Nested Classes private static final class ProtocolNegotiator implements ClientSideNegotiator { private static final String SPDY = "spdy/3"; private static final String HTTP = "HTTP/1.1"; private final FilterChain spdyFilterChain; private final SpdyHandlerFilter spdyHandlerFilter; // -------------------------------------------------------- Constructors private ProtocolNegotiator(final FilterChain spdyFilterChain) { this.spdyFilterChain = spdyFilterChain; int idx = spdyFilterChain.indexOfType(SpdyHandlerFilter.class); spdyHandlerFilter = (SpdyHandlerFilter) spdyFilterChain.get(idx); } // ----------------------------------- Methods from ClientSideNegotiator @Override public boolean wantNegotiate(SSLEngine engine) { GrizzlyAsyncHttpProvider.LOGGER.info("ProtocolSelector::wantNegotiate"); return true; } @Override public String selectProtocol(SSLEngine engine, LinkedHashSet<String> strings) { GrizzlyAsyncHttpProvider.LOGGER.info("ProtocolSelector::selectProtocol: " + strings); final Connection connection = NextProtoNegSupport.getConnection(engine); // Give preference to SPDY/3. If not available, check for HTTP as a // fallback if (strings.contains(SPDY)) { GrizzlyAsyncHttpProvider.LOGGER.info("ProtocolSelector::selecting: " + SPDY); SSLConnectionContext sslCtx = SSLUtils.getSslConnectionContext(connection); sslCtx.setNewConnectionFilterChain(spdyFilterChain); final SpdySession spdySession = new SpdySession(connection, false, spdyHandlerFilter); spdySession.setLocalInitialWindowSize(spdyHandlerFilter.getInitialWindowSize()); spdySession.setLocalMaxConcurrentStreams(spdyHandlerFilter.getMaxConcurrentStreams()); Utils.setSpdyConnection(connection); SpdySession.bind(connection, spdySession); return SPDY; } else if (strings.contains(HTTP)) { GrizzlyAsyncHttpProvider.LOGGER.info("ProtocolSelector::selecting: " + HTTP); // Use the default HTTP FilterChain. return HTTP; } else { GrizzlyAsyncHttpProvider.LOGGER.info("ProtocolSelector::selecting NONE"); // no protocol support. Will close the connection when // onNoDeal is invoked return ""; } } @Override public void onNoDeal(SSLEngine engine) { GrizzlyAsyncHttpProvider.LOGGER.info("ProtocolSelector::onNoDeal"); final Connection connection = NextProtoNegSupport.getConnection(engine); connection.closeSilently(); } } public static interface Cleanup { void cleanup(final FilterChainContext ctx); } }
Ensure ordered logging of requests.
providers/grizzly/src/main/java/org/asynchttpclient/providers/grizzly/GrizzlyAsyncHttpProvider.java
Ensure ordered logging of requests.
<ide><path>roviders/grizzly/src/main/java/org/asynchttpclient/providers/grizzly/GrizzlyAsyncHttpProvider.java <ide> handler = new ExpectHandler(handler); <ide> } <ide> context.setBodyHandler(handler); <add> if (LOGGER.isDebugEnabled()) { <add> LOGGER.debug("REQUEST: {}", requestPacket); <add> } <ide> isWriteComplete = handler.doHandle(ctx, request, requestPacket); <ide> } else { <ide> HttpContent content = HttpContent.builder(requestPacket).last(true).build(); <add> if (LOGGER.isDebugEnabled()) { <add> LOGGER.debug("REQUEST: {}", requestPacket); <add> } <ide> ctx.write(content, ctx.getTransportContext().getCompletionHandler()); <ide> } <del> LOGGER.debug("REQUEST: {}", requestPacket); <add> <ide> <ide> return isWriteComplete; <ide> }
Java
apache-2.0
7852c3c4e20088714bd1808d90c1fb907479bd60
0
jerome-jacob/selenium,meksh/selenium,minhthuanit/selenium,asashour/selenium,juangj/selenium,joshuaduffy/selenium,jsakamoto/selenium,petruc/selenium,yukaReal/selenium,sankha93/selenium,alb-i986/selenium,MCGallaspy/selenium,TheBlackTuxCorp/selenium,SeleniumHQ/selenium,asashour/selenium,misttechnologies/selenium,clavery/selenium,i17c/selenium,Appdynamics/selenium,carsonmcdonald/selenium,tarlabs/selenium,gemini-testing/selenium,eric-stanley/selenium,rovner/selenium,twalpole/selenium,chrisblock/selenium,5hawnknight/selenium,dibagga/selenium,gabrielsimas/selenium,Herst/selenium,Dude-X/selenium,sag-enorman/selenium,gemini-testing/selenium,customcommander/selenium,pulkitsinghal/selenium,meksh/selenium,SevInf/IEDriver,gorlemik/selenium,quoideneuf/selenium,dandv/selenium,dcjohnson1989/selenium,alexec/selenium,compstak/selenium,Dude-X/selenium,uchida/selenium,rrussell39/selenium,telefonicaid/selenium,AutomatedTester/selenium,s2oBCN/selenium,Sravyaksr/selenium,gorlemik/selenium,dcjohnson1989/selenium,lilredindy/selenium,joshbruning/selenium,carsonmcdonald/selenium,lukeis/selenium,asashour/selenium,gabrielsimas/selenium,joshuaduffy/selenium,denis-vilyuzhanin/selenium-fastview,jsakamoto/selenium,o-schneider/selenium,xmhubj/selenium,joshbruning/selenium,lukeis/selenium,telefonicaid/selenium,joshuaduffy/selenium,actmd/selenium,joshmgrant/selenium,eric-stanley/selenium,pulkitsinghal/selenium,bartolkaruza/selenium,wambat/selenium,lilredindy/selenium,compstak/selenium,MeetMe/selenium,HtmlUnit/selenium,SouWilliams/selenium,dibagga/selenium,mach6/selenium,jknguyen/josephknguyen-selenium,HtmlUnit/selenium,bartolkaruza/selenium,vveliev/selenium,TheBlackTuxCorp/selenium,bartolkaruza/selenium,tkurnosova/selenium,stupidnetizen/selenium,jsarenik/jajomojo-selenium,temyers/selenium,dcjohnson1989/selenium,onedox/selenium,gemini-testing/selenium,MeetMe/selenium,livioc/selenium,xmhubj/selenium,SouWilliams/selenium,BlackSmith/selenium,joshmgrant/selenium,vveliev/selenium,onedox/selenium,customcommander/selenium,arunsingh/selenium,amikey/selenium,gotcha/selenium,chrsmithdemos/selenium,bmannix/selenium,dkentw/selenium,bartolkaruza/selenium,rovner/selenium,s2oBCN/selenium,gemini-testing/selenium,MCGallaspy/selenium,amar-sharma/selenium,misttechnologies/selenium,markodolancic/selenium,isaksky/selenium,dkentw/selenium,yukaReal/selenium,aluedeke/chromedriver,amar-sharma/selenium,gabrielsimas/selenium,tbeadle/selenium,gregerrag/selenium,RamaraoDonta/ramarao-clone,orange-tv-blagnac/selenium,markodolancic/selenium,sevaseva/selenium,gorlemik/selenium,jknguyen/josephknguyen-selenium,isaksky/selenium,mach6/selenium,clavery/selenium,customcommander/selenium,manuelpirez/selenium,temyers/selenium,arunsingh/selenium,krosenvold/selenium,knorrium/selenium,petruc/selenium,TikhomirovSergey/selenium,xsyntrex/selenium,mojwang/selenium,wambat/selenium,meksh/selenium,Ardesco/selenium,BlackSmith/selenium,RamaraoDonta/ramarao-clone,AutomatedTester/selenium,lilredindy/selenium,eric-stanley/selenium,amar-sharma/selenium,temyers/selenium,wambat/selenium,titusfortner/selenium,asolntsev/selenium,uchida/selenium,Sravyaksr/selenium,joshmgrant/selenium,lrowe/selenium,SouWilliams/selenium,clavery/selenium,uchida/selenium,mach6/selenium,thanhpete/selenium,onedox/selenium,lrowe/selenium,s2oBCN/selenium,kalyanjvn1/selenium,minhthuanit/selenium,jsarenik/jajomojo-selenium,livioc/selenium,stupidnetizen/selenium,meksh/selenium,gotcha/selenium,Dude-X/selenium,isaksky/selenium,onedox/selenium,gurayinan/selenium,o-schneider/selenium,Tom-Trumper/selenium,twalpole/selenium,soundcloud/selenium,lmtierney/selenium,vinay-qa/vinayit-android-server-apk,HtmlUnit/selenium,knorrium/selenium,livioc/selenium,DrMarcII/selenium,HtmlUnit/selenium,lukeis/selenium,meksh/selenium,skurochkin/selenium,lmtierney/selenium,skurochkin/selenium,tkurnosova/selenium,DrMarcII/selenium,mestihudson/selenium,pulkitsinghal/selenium,amar-sharma/selenium,gabrielsimas/selenium,lilredindy/selenium,anshumanchatterji/selenium,krmahadevan/selenium,titusfortner/selenium,Herst/selenium,chrsmithdemos/selenium,krosenvold/selenium,alexec/selenium,customcommander/selenium,rovner/selenium,dbo/selenium,blackboarddd/selenium,rovner/selenium,dcjohnson1989/selenium,arunsingh/selenium,HtmlUnit/selenium,HtmlUnit/selenium,asolntsev/selenium,s2oBCN/selenium,AutomatedTester/selenium,aluedeke/chromedriver,onedox/selenium,jsakamoto/selenium,jsarenik/jajomojo-selenium,soundcloud/selenium,lummyare/lummyare-lummy,yukaReal/selenium,sri85/selenium,denis-vilyuzhanin/selenium-fastview,davehunt/selenium,onedox/selenium,uchida/selenium,freynaud/selenium,telefonicaid/selenium,vinay-qa/vinayit-android-server-apk,compstak/selenium,rplevka/selenium,denis-vilyuzhanin/selenium-fastview,isaksky/selenium,sri85/selenium,gorlemik/selenium,o-schneider/selenium,gurayinan/selenium,lummyare/lummyare-test,isaksky/selenium,xsyntrex/selenium,blueyed/selenium,chrisblock/selenium,i17c/selenium,AutomatedTester/selenium,sri85/selenium,pulkitsinghal/selenium,livioc/selenium,carlosroh/selenium,blackboarddd/selenium,dandv/selenium,rovner/selenium,amikey/selenium,bmannix/selenium,juangj/selenium,livioc/selenium,denis-vilyuzhanin/selenium-fastview,chrsmithdemos/selenium,sebady/selenium,onedox/selenium,SevInf/IEDriver,gurayinan/selenium,freynaud/selenium,titusfortner/selenium,joshuaduffy/selenium,lrowe/selenium,gabrielsimas/selenium,dkentw/selenium,SeleniumHQ/selenium,asashour/selenium,SeleniumHQ/selenium,gregerrag/selenium,denis-vilyuzhanin/selenium-fastview,blackboarddd/selenium,gotcha/selenium,thanhpete/selenium,blackboarddd/selenium,sag-enorman/selenium,SevInf/IEDriver,lummyare/lummyare-lummy,dbo/selenium,tarlabs/selenium,thanhpete/selenium,wambat/selenium,Tom-Trumper/selenium,orange-tv-blagnac/selenium,wambat/selenium,Herst/selenium,SevInf/IEDriver,aluedeke/chromedriver,valfirst/selenium,petruc/selenium,joshmgrant/selenium,skurochkin/selenium,lukeis/selenium,eric-stanley/selenium,dkentw/selenium,krosenvold/selenium,jsakamoto/selenium,kalyanjvn1/selenium,krosenvold/selenium,Jarob22/selenium,tbeadle/selenium,wambat/selenium,sag-enorman/selenium,doungni/selenium,meksh/selenium,RamaraoDonta/ramarao-clone,MeetMe/selenium,minhthuanit/selenium,dimacus/selenium,MCGallaspy/selenium,GorK-ChO/selenium,blackboarddd/selenium,orange-tv-blagnac/selenium,xsyntrex/selenium,temyers/selenium,sankha93/selenium,asolntsev/selenium,aluedeke/chromedriver,joshbruning/selenium,Jarob22/selenium,TikhomirovSergey/selenium,i17c/selenium,thanhpete/selenium,TheBlackTuxCorp/selenium,kalyanjvn1/selenium,markodolancic/selenium,Ardesco/selenium,vveliev/selenium,zenefits/selenium,houchj/selenium,lummyare/lummyare-test,sri85/selenium,dibagga/selenium,stupidnetizen/selenium,joshmgrant/selenium,orange-tv-blagnac/selenium,aluedeke/chromedriver,joshmgrant/selenium,telefonicaid/selenium,actmd/selenium,TikhomirovSergey/selenium,skurochkin/selenium,dandv/selenium,kalyanjvn1/selenium,jsakamoto/selenium,clavery/selenium,jerome-jacob/selenium,MeetMe/selenium,alb-i986/selenium,vveliev/selenium,houchj/selenium,orange-tv-blagnac/selenium,actmd/selenium,isaksky/selenium,5hawnknight/selenium,temyers/selenium,xmhubj/selenium,mestihudson/selenium,GorK-ChO/selenium,uchida/selenium,uchida/selenium,isaksky/selenium,Dude-X/selenium,Sravyaksr/selenium,alb-i986/selenium,mach6/selenium,lilredindy/selenium,amikey/selenium,gregerrag/selenium,GorK-ChO/selenium,dcjohnson1989/selenium,sebady/selenium,yukaReal/selenium,tbeadle/selenium,valfirst/selenium,thanhpete/selenium,doungni/selenium,dimacus/selenium,Jarob22/selenium,krmahadevan/selenium,lummyare/lummyare-test,doungni/selenium,SevInf/IEDriver,slongwang/selenium,actmd/selenium,carsonmcdonald/selenium,mestihudson/selenium,p0deje/selenium,SouWilliams/selenium,jsakamoto/selenium,zenefits/selenium,actmd/selenium,joshmgrant/selenium,joshuaduffy/selenium,joshmgrant/selenium,gorlemik/selenium,titusfortner/selenium,rovner/selenium,compstak/selenium,gabrielsimas/selenium,rrussell39/selenium,gabrielsimas/selenium,asolntsev/selenium,petruc/selenium,chrsmithdemos/selenium,carsonmcdonald/selenium,BlackSmith/selenium,gotcha/selenium,mach6/selenium,doungni/selenium,valfirst/selenium,asashour/selenium,yukaReal/selenium,5hawnknight/selenium,alb-i986/selenium,actmd/selenium,dcjohnson1989/selenium,chrisblock/selenium,temyers/selenium,sebady/selenium,AutomatedTester/selenium,alexec/selenium,soundcloud/selenium,alexec/selenium,BlackSmith/selenium,anshumanchatterji/selenium,HtmlUnit/selenium,jerome-jacob/selenium,carlosroh/selenium,rplevka/selenium,jabbrwcky/selenium,sri85/selenium,Dude-X/selenium,carsonmcdonald/selenium,skurochkin/selenium,temyers/selenium,gregerrag/selenium,titusfortner/selenium,lukeis/selenium,vinay-qa/vinayit-android-server-apk,mojwang/selenium,jknguyen/josephknguyen-selenium,bartolkaruza/selenium,lummyare/lummyare-lummy,sevaseva/selenium,uchida/selenium,davehunt/selenium,lrowe/selenium,customcommander/selenium,krosenvold/selenium,chrsmithdemos/selenium,carlosroh/selenium,compstak/selenium,valfirst/selenium,dkentw/selenium,i17c/selenium,asolntsev/selenium,gemini-testing/selenium,xsyntrex/selenium,bmannix/selenium,BlackSmith/selenium,anshumanchatterji/selenium,carsonmcdonald/selenium,Sravyaksr/selenium,BlackSmith/selenium,jabbrwcky/selenium,SeleniumHQ/selenium,vveliev/selenium,denis-vilyuzhanin/selenium-fastview,jsarenik/jajomojo-selenium,arunsingh/selenium,alexec/selenium,Ardesco/selenium,Dude-X/selenium,sevaseva/selenium,MeetMe/selenium,joshbruning/selenium,dimacus/selenium,jerome-jacob/selenium,soundcloud/selenium,houchj/selenium,alb-i986/selenium,Appdynamics/selenium,bmannix/selenium,slongwang/selenium,dimacus/selenium,bayandin/selenium,tarlabs/selenium,o-schneider/selenium,bmannix/selenium,Tom-Trumper/selenium,SeleniumHQ/selenium,mojwang/selenium,DrMarcII/selenium,manuelpirez/selenium,asashour/selenium,pulkitsinghal/selenium,denis-vilyuzhanin/selenium-fastview,lilredindy/selenium,stupidnetizen/selenium,joshuaduffy/selenium,mach6/selenium,telefonicaid/selenium,chrsmithdemos/selenium,knorrium/selenium,HtmlUnit/selenium,GorK-ChO/selenium,yukaReal/selenium,gorlemik/selenium,SevInf/IEDriver,sevaseva/selenium,JosephCastro/selenium,5hawnknight/selenium,stupidnetizen/selenium,lrowe/selenium,sevaseva/selenium,thanhpete/selenium,quoideneuf/selenium,valfirst/selenium,lmtierney/selenium,i17c/selenium,krmahadevan/selenium,sri85/selenium,amar-sharma/selenium,rovner/selenium,dbo/selenium,orange-tv-blagnac/selenium,RamaraoDonta/ramarao-clone,amar-sharma/selenium,anshumanchatterji/selenium,joshuaduffy/selenium,DrMarcII/selenium,SeleniumHQ/selenium,slongwang/selenium,SouWilliams/selenium,slongwang/selenium,mojwang/selenium,Tom-Trumper/selenium,joshmgrant/selenium,sankha93/selenium,misttechnologies/selenium,p0deje/selenium,p0deje/selenium,misttechnologies/selenium,mestihudson/selenium,Ardesco/selenium,o-schneider/selenium,JosephCastro/selenium,joshbruning/selenium,arunsingh/selenium,TheBlackTuxCorp/selenium,gorlemik/selenium,lummyare/lummyare-lummy,gotcha/selenium,gotcha/selenium,DrMarcII/selenium,o-schneider/selenium,krmahadevan/selenium,sankha93/selenium,quoideneuf/selenium,markodolancic/selenium,joshbruning/selenium,rrussell39/selenium,BlackSmith/selenium,asashour/selenium,uchida/selenium,lrowe/selenium,p0deje/selenium,markodolancic/selenium,Ardesco/selenium,bmannix/selenium,davehunt/selenium,sevaseva/selenium,jerome-jacob/selenium,lmtierney/selenium,vinay-qa/vinayit-android-server-apk,stupidnetizen/selenium,dkentw/selenium,MCGallaspy/selenium,tkurnosova/selenium,lummyare/lummyare-test,gregerrag/selenium,misttechnologies/selenium,oddui/selenium,mach6/selenium,carsonmcdonald/selenium,Appdynamics/selenium,soundcloud/selenium,manuelpirez/selenium,MeetMe/selenium,denis-vilyuzhanin/selenium-fastview,davehunt/selenium,Sravyaksr/selenium,kalyanjvn1/selenium,petruc/selenium,juangj/selenium,GorK-ChO/selenium,freynaud/selenium,rplevka/selenium,clavery/selenium,sebady/selenium,soundcloud/selenium,xmhubj/selenium,HtmlUnit/selenium,amikey/selenium,tbeadle/selenium,dcjohnson1989/selenium,gorlemik/selenium,RamaraoDonta/ramarao-clone,valfirst/selenium,asolntsev/selenium,dandv/selenium,BlackSmith/selenium,blueyed/selenium,lmtierney/selenium,chrsmithdemos/selenium,p0deje/selenium,oddui/selenium,krmahadevan/selenium,Ardesco/selenium,lrowe/selenium,SevInf/IEDriver,krmahadevan/selenium,twalpole/selenium,livioc/selenium,dibagga/selenium,sebady/selenium,jerome-jacob/selenium,jabbrwcky/selenium,vinay-qa/vinayit-android-server-apk,p0deje/selenium,SeleniumHQ/selenium,gurayinan/selenium,TheBlackTuxCorp/selenium,knorrium/selenium,meksh/selenium,dkentw/selenium,SouWilliams/selenium,temyers/selenium,denis-vilyuzhanin/selenium-fastview,slongwang/selenium,skurochkin/selenium,eric-stanley/selenium,xmhubj/selenium,bmannix/selenium,kalyanjvn1/selenium,carlosroh/selenium,mestihudson/selenium,blackboarddd/selenium,rrussell39/selenium,blackboarddd/selenium,sevaseva/selenium,zenefits/selenium,tkurnosova/selenium,juangj/selenium,SeleniumHQ/selenium,manuelpirez/selenium,p0deje/selenium,blueyed/selenium,dibagga/selenium,xmhubj/selenium,bartolkaruza/selenium,sevaseva/selenium,gotcha/selenium,p0deje/selenium,bartolkaruza/selenium,gabrielsimas/selenium,sebady/selenium,zenefits/selenium,pulkitsinghal/selenium,sri85/selenium,dbo/selenium,gemini-testing/selenium,rrussell39/selenium,juangj/selenium,dimacus/selenium,Sravyaksr/selenium,amar-sharma/selenium,sankha93/selenium,houchj/selenium,petruc/selenium,Sravyaksr/selenium,krosenvold/selenium,SevInf/IEDriver,tkurnosova/selenium,stupidnetizen/selenium,tarlabs/selenium,tarlabs/selenium,alb-i986/selenium,Tom-Trumper/selenium,compstak/selenium,gemini-testing/selenium,asashour/selenium,markodolancic/selenium,misttechnologies/selenium,onedox/selenium,carlosroh/selenium,dibagga/selenium,customcommander/selenium,dibagga/selenium,xsyntrex/selenium,MeetMe/selenium,jsakamoto/selenium,joshmgrant/selenium,5hawnknight/selenium,gurayinan/selenium,oddui/selenium,compstak/selenium,JosephCastro/selenium,dimacus/selenium,5hawnknight/selenium,arunsingh/selenium,kalyanjvn1/selenium,jsarenik/jajomojo-selenium,davehunt/selenium,aluedeke/chromedriver,dcjohnson1989/selenium,customcommander/selenium,carsonmcdonald/selenium,soundcloud/selenium,Herst/selenium,pulkitsinghal/selenium,quoideneuf/selenium,amikey/selenium,quoideneuf/selenium,TheBlackTuxCorp/selenium,asolntsev/selenium,gregerrag/selenium,isaksky/selenium,joshuaduffy/selenium,sebady/selenium,bayandin/selenium,sag-enorman/selenium,sag-enorman/selenium,Jarob22/selenium,houchj/selenium,TikhomirovSergey/selenium,alexec/selenium,Tom-Trumper/selenium,sri85/selenium,eric-stanley/selenium,lummyare/lummyare-lummy,TheBlackTuxCorp/selenium,krosenvold/selenium,tbeadle/selenium,Sravyaksr/selenium,jerome-jacob/selenium,clavery/selenium,valfirst/selenium,blackboarddd/selenium,titusfortner/selenium,mestihudson/selenium,TikhomirovSergey/selenium,quoideneuf/selenium,lukeis/selenium,jerome-jacob/selenium,jknguyen/josephknguyen-selenium,lummyare/lummyare-lummy,sebady/selenium,asashour/selenium,MeetMe/selenium,slongwang/selenium,twalpole/selenium,JosephCastro/selenium,arunsingh/selenium,houchj/selenium,livioc/selenium,pulkitsinghal/selenium,bayandin/selenium,GorK-ChO/selenium,Ardesco/selenium,alb-i986/selenium,davehunt/selenium,oddui/selenium,gotcha/selenium,vveliev/selenium,SouWilliams/selenium,houchj/selenium,jabbrwcky/selenium,RamaraoDonta/ramarao-clone,pulkitsinghal/selenium,lilredindy/selenium,skurochkin/selenium,yukaReal/selenium,bayandin/selenium,Herst/selenium,jsakamoto/selenium,livioc/selenium,wambat/selenium,rplevka/selenium,knorrium/selenium,aluedeke/chromedriver,xsyntrex/selenium,dbo/selenium,misttechnologies/selenium,Herst/selenium,knorrium/selenium,vveliev/selenium,TheBlackTuxCorp/selenium,yukaReal/selenium,mestihudson/selenium,alexec/selenium,juangj/selenium,titusfortner/selenium,Jarob22/selenium,jabbrwcky/selenium,clavery/selenium,Jarob22/selenium,davehunt/selenium,i17c/selenium,aluedeke/chromedriver,tkurnosova/selenium,chrisblock/selenium,jknguyen/josephknguyen-selenium,tbeadle/selenium,lukeis/selenium,krmahadevan/selenium,chrisblock/selenium,Jarob22/selenium,doungni/selenium,Dude-X/selenium,blackboarddd/selenium,quoideneuf/selenium,arunsingh/selenium,blueyed/selenium,juangj/selenium,lummyare/lummyare-lummy,rrussell39/selenium,lmtierney/selenium,soundcloud/selenium,gemini-testing/selenium,freynaud/selenium,sankha93/selenium,jabbrwcky/selenium,Appdynamics/selenium,blueyed/selenium,yukaReal/selenium,lukeis/selenium,AutomatedTester/selenium,zenefits/selenium,manuelpirez/selenium,anshumanchatterji/selenium,i17c/selenium,MCGallaspy/selenium,bartolkaruza/selenium,doungni/selenium,lummyare/lummyare-test,bayandin/selenium,oddui/selenium,petruc/selenium,chrisblock/selenium,misttechnologies/selenium,TikhomirovSergey/selenium,gregerrag/selenium,knorrium/selenium,jknguyen/josephknguyen-selenium,sri85/selenium,compstak/selenium,s2oBCN/selenium,Sravyaksr/selenium,rplevka/selenium,tbeadle/selenium,actmd/selenium,MCGallaspy/selenium,tarlabs/selenium,doungni/selenium,lummyare/lummyare-test,twalpole/selenium,titusfortner/selenium,Dude-X/selenium,thanhpete/selenium,meksh/selenium,amikey/selenium,doungni/selenium,minhthuanit/selenium,lrowe/selenium,gurayinan/selenium,bayandin/selenium,rplevka/selenium,vveliev/selenium,s2oBCN/selenium,Herst/selenium,AutomatedTester/selenium,mojwang/selenium,5hawnknight/selenium,lummyare/lummyare-test,Appdynamics/selenium,carsonmcdonald/selenium,telefonicaid/selenium,SouWilliams/selenium,zenefits/selenium,freynaud/selenium,telefonicaid/selenium,xmhubj/selenium,dbo/selenium,lummyare/lummyare-test,blueyed/selenium,isaksky/selenium,zenefits/selenium,rrussell39/selenium,bmannix/selenium,GorK-ChO/selenium,freynaud/selenium,SeleniumHQ/selenium,xsyntrex/selenium,tarlabs/selenium,TikhomirovSergey/selenium,mojwang/selenium,kalyanjvn1/selenium,zenefits/selenium,TikhomirovSergey/selenium,sankha93/selenium,meksh/selenium,s2oBCN/selenium,sag-enorman/selenium,Appdynamics/selenium,dandv/selenium,joshmgrant/selenium,orange-tv-blagnac/selenium,twalpole/selenium,sag-enorman/selenium,minhthuanit/selenium,blueyed/selenium,houchj/selenium,twalpole/selenium,slongwang/selenium,customcommander/selenium,davehunt/selenium,stupidnetizen/selenium,actmd/selenium,oddui/selenium,eric-stanley/selenium,dbo/selenium,RamaraoDonta/ramarao-clone,carlosroh/selenium,minhthuanit/selenium,markodolancic/selenium,o-schneider/selenium,Ardesco/selenium,krosenvold/selenium,titusfortner/selenium,chrsmithdemos/selenium,knorrium/selenium,rplevka/selenium,slongwang/selenium,vveliev/selenium,gregerrag/selenium,customcommander/selenium,asolntsev/selenium,kalyanjvn1/selenium,dandv/selenium,carlosroh/selenium,dibagga/selenium,tarlabs/selenium,RamaraoDonta/ramarao-clone,sevaseva/selenium,freynaud/selenium,tarlabs/selenium,gurayinan/selenium,TheBlackTuxCorp/selenium,zenefits/selenium,rrussell39/selenium,titusfortner/selenium,joshbruning/selenium,SouWilliams/selenium,s2oBCN/selenium,minhthuanit/selenium,telefonicaid/selenium,jsarenik/jajomojo-selenium,markodolancic/selenium,juangj/selenium,vinay-qa/vinayit-android-server-apk,onedox/selenium,rplevka/selenium,stupidnetizen/selenium,lrowe/selenium,titusfortner/selenium,gregerrag/selenium,JosephCastro/selenium,JosephCastro/selenium,MCGallaspy/selenium,dkentw/selenium,jabbrwcky/selenium,rplevka/selenium,Jarob22/selenium,SeleniumHQ/selenium,DrMarcII/selenium,DrMarcII/selenium,alexec/selenium,dibagga/selenium,5hawnknight/selenium,quoideneuf/selenium,actmd/selenium,gorlemik/selenium,AutomatedTester/selenium,xsyntrex/selenium,s2oBCN/selenium,tkurnosova/selenium,bayandin/selenium,slongwang/selenium,amar-sharma/selenium,vinay-qa/vinayit-android-server-apk,DrMarcII/selenium,GorK-ChO/selenium,joshbruning/selenium,blueyed/selenium,p0deje/selenium,chrisblock/selenium,lmtierney/selenium,valfirst/selenium,minhthuanit/selenium,telefonicaid/selenium,lilredindy/selenium,skurochkin/selenium,Appdynamics/selenium,Tom-Trumper/selenium,juangj/selenium,petruc/selenium,thanhpete/selenium,BlackSmith/selenium,alb-i986/selenium,amikey/selenium,MCGallaspy/selenium,Tom-Trumper/selenium,sag-enorman/selenium,valfirst/selenium,5hawnknight/selenium,orange-tv-blagnac/selenium,oddui/selenium,bayandin/selenium,Appdynamics/selenium,JosephCastro/selenium,krmahadevan/selenium,misttechnologies/selenium,tbeadle/selenium,sankha93/selenium,bmannix/selenium,twalpole/selenium,chrisblock/selenium,manuelpirez/selenium,MCGallaspy/selenium,lummyare/lummyare-lummy,jknguyen/josephknguyen-selenium,amikey/selenium,manuelpirez/selenium,blueyed/selenium,knorrium/selenium,krmahadevan/selenium,soundcloud/selenium,rovner/selenium,livioc/selenium,dandv/selenium,quoideneuf/selenium,eric-stanley/selenium,xmhubj/selenium,oddui/selenium,mojwang/selenium,Tom-Trumper/selenium,MeetMe/selenium,freynaud/selenium,eric-stanley/selenium,lilredindy/selenium,tbeadle/selenium,o-schneider/selenium,jsarenik/jajomojo-selenium,dcjohnson1989/selenium,anshumanchatterji/selenium,sag-enorman/selenium,temyers/selenium,lummyare/lummyare-lummy,i17c/selenium,gemini-testing/selenium,xsyntrex/selenium,vinay-qa/vinayit-android-server-apk,gotcha/selenium,rrussell39/selenium,mojwang/selenium,valfirst/selenium,skurochkin/selenium,krosenvold/selenium,minhthuanit/selenium,valfirst/selenium,gabrielsimas/selenium,amikey/selenium,alb-i986/selenium,Dude-X/selenium,joshuaduffy/selenium,compstak/selenium,dbo/selenium,oddui/selenium,tkurnosova/selenium,sankha93/selenium,DrMarcII/selenium,wambat/selenium,orange-tv-blagnac/selenium,xmhubj/selenium,TikhomirovSergey/selenium,davehunt/selenium,amar-sharma/selenium,jerome-jacob/selenium,arunsingh/selenium,alexec/selenium,joshbruning/selenium,wambat/selenium,anshumanchatterji/selenium,dimacus/selenium,jabbrwcky/selenium,aluedeke/chromedriver,dimacus/selenium,carlosroh/selenium,carlosroh/selenium,AutomatedTester/selenium,petruc/selenium,lmtierney/selenium,manuelpirez/selenium,gurayinan/selenium,bayandin/selenium,mojwang/selenium,SeleniumHQ/selenium,gurayinan/selenium,uchida/selenium,sebady/selenium,mestihudson/selenium,RamaraoDonta/ramarao-clone,lmtierney/selenium,freynaud/selenium,o-schneider/selenium,jsarenik/jajomojo-selenium,jsakamoto/selenium,dandv/selenium,Herst/selenium,jabbrwcky/selenium,GorK-ChO/selenium,i17c/selenium,dandv/selenium,Appdynamics/selenium,dkentw/selenium,Ardesco/selenium,lukeis/selenium,twalpole/selenium,thanhpete/selenium,Jarob22/selenium,mach6/selenium,clavery/selenium,vinay-qa/vinayit-android-server-apk,Herst/selenium,lummyare/lummyare-test,mach6/selenium,tkurnosova/selenium,dbo/selenium,jknguyen/josephknguyen-selenium,manuelpirez/selenium,HtmlUnit/selenium,rovner/selenium,clavery/selenium,chrsmithdemos/selenium,anshumanchatterji/selenium,mestihudson/selenium,jsarenik/jajomojo-selenium,JosephCastro/selenium,houchj/selenium,markodolancic/selenium,anshumanchatterji/selenium,doungni/selenium,asolntsev/selenium,jknguyen/josephknguyen-selenium,bartolkaruza/selenium,SevInf/IEDriver,JosephCastro/selenium,dimacus/selenium,chrisblock/selenium
/* Copyright 2010 WebDriver committers Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.android.app; import org.openqa.selenium.android.ActivityController; import org.openqa.selenium.android.Logger; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import android.graphics.Bitmap; import android.net.http.SslError; import android.util.Log; import android.webkit.SslErrorHandler; import android.webkit.WebView; import android.webkit.WebViewClient; /** * This class overrides WebView default behavior when loading new URL. It makes sure that the URL * is always loaded by the WebView and updates progress bar according to the page loading * progress. */ final class WebDriverWebViewClient extends WebViewClient { private final MainActivity context; private final ActivityController controller = ActivityController.getInstance(); private final String LOG_TAG = WebDriverWebView.class.getName(); public WebDriverWebViewClient(MainActivity context) { this.context = context; } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Logger.log(Log.DEBUG, LOG_TAG, "onReceiveError: " + description + ", error code: " + errorCode); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { DesiredCapabilities caps = MainActivity.getDesiredCapabilities(); Object cap = caps.getCapability(CapabilityType.ACCEPT_SSL_CERTS); boolean shouldAcceptSslCerts = (cap == null ? false : (Boolean) cap); Logger.log(Log.DEBUG, LOG_TAG, "onReceivedSslError: " + error.toString() + ", shouldAcceptSslCerts: " + shouldAcceptSslCerts); if (shouldAcceptSslCerts) { handler.proceed(); } else { super.onReceivedSslError(view, handler, error); } } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { context.setLastUrlLoaded(url); context.setCurrentUrl(url); context.setProgressBarVisibility(true); // Showing progress bar in title context.setProgress(0); context.setPageHasStartedLoading(true); controller.notifyPageStartedLoading(); super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); context.setProgressBarVisibility(false); // Hiding progress bar in title context.setLastUrlLoaded(url); // If it is a html fragment or the current url loaded, the page is // not reloaded and the onProgessChanged function is not called. if (url.contains("#") && context.currentUrl().equals(url.split("#")[0])) { controller.notifyPageDoneLoading(); } } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }
android/src/java/org/openqa/selenium/android/app/WebDriverWebViewClient.java
/* Copyright 2010 WebDriver committers Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.android.app; import org.openqa.selenium.android.ActivityController; import org.openqa.selenium.android.Logger; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import android.graphics.Bitmap; import android.net.http.SslError; import android.util.Log; import android.webkit.SslErrorHandler; import android.webkit.WebView; import android.webkit.WebViewClient; /** * This class overrides WebView default behavior when loading new URL. It makes sure that the URL * is always loaded by the WebView and updates progress bar according to the page loading * progress. */ final class WebDriverWebViewClient extends WebViewClient { private final MainActivity context; private final ActivityController controller = ActivityController.getInstance(); private final String LOG_TAG = WebDriverWebView.class.getName(); public WebDriverWebViewClient(MainActivity context) { this.context = context; } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Logger.log(Log.DEBUG, LOG_TAG, "onReceiveError: " + description + ", error code: " + errorCode); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { DesiredCapabilities caps = MainActivity.getDesiredCapabilities(); boolean shouldAcceptSslCerts = false; try { shouldAcceptSslCerts = (Boolean) caps.getCapability(CapabilityType.ACCEPT_SSL_CERTS); } catch (NullPointerException npe) { // Ignore, we just leave shouldAcceptSslCerts to false } Logger.log(Log.DEBUG, LOG_TAG, "onReceivedSslError: " + error.toString() + ", shouldAcceptSslCerts: " + shouldAcceptSslCerts); if (shouldAcceptSslCerts) { handler.proceed(); } else { super.onReceivedSslError(view, handler, error); } } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { context.setLastUrlLoaded(url); context.setCurrentUrl(url); context.setProgressBarVisibility(true); // Showing progress bar in title context.setProgress(0); context.setPageHasStartedLoading(true); controller.notifyPageStartedLoading(); super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); context.setProgressBarVisibility(false); // Hiding progress bar in title context.setLastUrlLoaded(url); // If it is a html fragment or the current url loaded, the page is // not reloaded and the onProgessChanged function is not called. if (url.contains("#") && context.currentUrl().equals(url.split("#")[0])) { controller.notifyPageDoneLoading(); } } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }
DouniaBerrada: Cleaning up Android WebView client code r12254
android/src/java/org/openqa/selenium/android/app/WebDriverWebViewClient.java
DouniaBerrada: Cleaning up Android WebView client code
<ide><path>ndroid/src/java/org/openqa/selenium/android/app/WebDriverWebViewClient.java <ide> @Override <ide> public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { <ide> DesiredCapabilities caps = MainActivity.getDesiredCapabilities(); <del> boolean shouldAcceptSslCerts = false; <del> try { <del> shouldAcceptSslCerts = (Boolean) caps.getCapability(CapabilityType.ACCEPT_SSL_CERTS); <del> } catch (NullPointerException npe) { <del> // Ignore, we just leave shouldAcceptSslCerts to false <del> } <add> Object cap = caps.getCapability(CapabilityType.ACCEPT_SSL_CERTS); <add> boolean shouldAcceptSslCerts = (cap == null ? false : (Boolean) cap); <ide> Logger.log(Log.DEBUG, LOG_TAG, "onReceivedSslError: " + error.toString() <ide> + ", shouldAcceptSslCerts: " + shouldAcceptSslCerts); <ide>
Java
apache-2.0
bacea0539740981c5fee618a0f19597589449743
0
WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules
/* * Copyright (c) 2012-2014 LabKey Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.labkey.wnprc_ehr.table; import org.labkey.api.data.AbstractTableInfo; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; import org.labkey.api.data.DataColumn; import org.labkey.api.data.RenderContext; import org.labkey.api.data.TableInfo; import org.labkey.api.data.WrappedColumn; import org.labkey.api.ehr.EHRService; import org.labkey.api.ldk.table.AbstractTableCustomizer; import org.labkey.api.query.FieldKey; import org.labkey.api.query.QueryForeignKey; import org.labkey.api.query.QueryService; import org.labkey.api.query.UserSchema; import org.labkey.api.util.PageFlowUtil; import org.labkey.api.util.StringExpressionFactory; import org.labkey.api.view.ActionURL; import java.io.IOException; import java.io.Writer; /** * User: bimber * Date: 12/7/12 * Time: 2:22 PM */ public class WNPRC_EHRCustomizer extends AbstractTableCustomizer { public WNPRC_EHRCustomizer() { } public void customize(TableInfo table) { if (table instanceof AbstractTableInfo) { customizeColumns((AbstractTableInfo)table); if (table.getName().equalsIgnoreCase("Animal") && table.getSchema().getName().equalsIgnoreCase("study")) customizeAnimalTable((AbstractTableInfo) table); else if (table.getName().equalsIgnoreCase("Birth") && table.getSchema().getName().equalsIgnoreCase("study")) customizeBirthTable((AbstractTableInfo) table); else if (table.getName().equalsIgnoreCase("protocol") && table.getSchema().getName().equalsIgnoreCase("ehr")) customizeProtocolTable((AbstractTableInfo)table); else if (table.getName().equalsIgnoreCase("breeding_encounters") && table.getSchema().getName().equalsIgnoreCase("study")) { customizeBreedingEncountersTable((AbstractTableInfo) table); } else if (table.getName().equalsIgnoreCase("pregnancies") && table.getSchema().getName().equalsIgnoreCase("study")) { customizePregnanciesTable((AbstractTableInfo) table); } } } private void customizeColumns(AbstractTableInfo ti) { ColumnInfo project = ti.getColumn("project"); if (project != null) { project.setFormat("00000000"); } customizeRoomCol(ti, "room"); customizeRoomCol(ti, "room1"); customizeRoomCol(ti, "room2"); } private void customizeRoomCol(AbstractTableInfo ti, String columnName) { ColumnInfo room = ti.getColumn(columnName); if (room != null) { if (!ti.getName().equalsIgnoreCase("rooms")) { // Configure the FK to show the raw value to improve performance, since the database can avoid // doing the join in many cases Container ehrContainer = EHRService.get().getEHRStudyContainer(ti.getUserSchema().getContainer()); if (ehrContainer != null) { UserSchema us = getUserSchema(ti, "ehr_lookups", ehrContainer); if (us != null) { room.setFk(new QueryForeignKey(us, ehrContainer, "rooms", "room", "room", true)); } } } } } private void customizeBirthTable(AbstractTableInfo ti) { ColumnInfo cond = ti.getColumn("cond"); if (cond != null) { cond.setLabel("Housing Condition"); UserSchema us = getUserSchema(ti, "ehr_lookups"); if (us != null) { cond.setFk(new QueryForeignKey(us, null, "housing_condition_codes", "value", "title")); } } } private void customizeAnimalTable(AbstractTableInfo ds) { if (ds.getColumn("MHCtyping") != null) return; UserSchema us = getStudyUserSchema(ds); if (us == null){ return; } if (ds.getColumn("demographicsMHC") == null) { ColumnInfo col = getWrappedIdCol(us, ds, "MHCtyping", "demographicsMHC"); col.setLabel("MHC SSP Typing"); col.setDescription("Summarizes MHC SSP typing results for the common alleles"); ds.addColumn(col); ColumnInfo col2 = getWrappedIdCol(us, ds, "ViralLoad", "demographicsVL"); col2.setLabel("Viral Loads"); col2.setDescription("This field calculates the most recent viral load for this animal"); ds.addColumn(col2); ColumnInfo col3 = getWrappedIdCol(us, ds, "ViralStatus", "demographicsViralStatus"); col3.setLabel("Viral Status"); col3.setDescription("This calculates the viral status of the animal based on tracking project assignments"); ds.addColumn(col3); ColumnInfo col18 = getWrappedIdCol(us, ds, "Virology", "demographicsVirology"); col18.setLabel("Virology"); col18.setDescription("This calculates the distinct pathogens listed as positive for this animal from the virology table"); ds.addColumn(col18); ColumnInfo col4 = getWrappedIdCol(us, ds, "IrregularObs", "demographicsObs"); col4.setLabel("Irregular Obs"); col4.setDescription("Shows any irregular observations from each animal today or yesterday."); ds.addColumn(col4); ColumnInfo col7 = getWrappedIdCol(us, ds, "activeAssignments", "demographicsAssignments"); col7.setLabel("Assignments - Active"); col7.setDescription("Contains summaries of the assignments for each animal, including the project numbers, availability codes and a count"); ds.addColumn(col7); ColumnInfo col6 = getWrappedIdCol(us, ds, "totalAssignments", "demographicsAssignmentHistory"); col6.setLabel("Assignments - Total"); col6.setDescription("Contains summaries of the total assignments this animal has ever had, including the project numbers and a count"); ds.addColumn(col6); ColumnInfo col5 = getWrappedIdCol(us, ds, "assignmentSummary", "demographicsAssignmentSummary"); col5.setLabel("Assignments - Detailed"); col5.setDescription("Contains more detailed summaries of the active assignments for each animal, including a breakdown between research, breeding, training, etc."); ds.addColumn(col5); ColumnInfo col10 = getWrappedIdCol(us, ds, "DaysAlone", "demographicsDaysAlone"); col10.setLabel("Days Alone"); col10.setDescription("Calculates the total number of days each animal has been single housed, if applicable."); ds.addColumn(col10); ColumnInfo bloodCol = getWrappedIdCol(us, ds, "AvailBlood", "demographicsBloodSummary"); bloodCol.setLabel("Blood Remaining"); bloodCol.setDescription("Calculates the total blood draw and remaining, which is determine by weight and blood drawn in the past 30 days."); ds.addColumn(bloodCol); ColumnInfo col17 = getWrappedIdCol(us, ds, "MostRecentTB", "demographicsMostRecentTBDate"); col17.setLabel("TB Tests"); col17.setDescription("Calculates the most recent TB date for this animal, time since TB and the last eye TB tested"); ds.addColumn(col17); ColumnInfo col16 = getWrappedIdCol(us, ds, "Surgery", "demographicsSurgery"); col16.setLabel("Surgical History"); col16.setDescription("Calculates whether this animal has ever had any surgery or a surgery flagged as major"); ds.addColumn(col16); ColumnInfo col19 = getWrappedIdCol(us, ds, "CurrentBehavior", "CurrentBehaviorNotes"); col19.setLabel("Behavior - Current"); col19.setDescription("This calculates the current behavior(s) for the animal, based on the behavior abstract table"); ds.addColumn(col19); } if (ds.getColumn("totalOffspring") == null) { ColumnInfo col15 = getWrappedIdCol(us, ds, "totalOffspring", "demographicsTotalOffspring"); col15.setLabel("Number of Offspring"); col15.setDescription("Shows the total offspring of each animal"); ds.addColumn(col15); } } private void customizeProtocolTable(AbstractTableInfo table) { ColumnInfo protocolCol = table.getColumn("protocol"); if (protocolCol != null && table.getColumn("pdf") == null) { ColumnInfo col = table.addColumn(new WrappedColumn(protocolCol, "pdf")); col.setLabel("PDF"); col.setURL(StringExpressionFactory.create("/query/WNPRC/WNPRC_Units/Animal_Services/Compliance_Training/Private/Protocol_PDFs/executeQuery.view?schemaName=lists&query.queryName=ProtocolPDFs&query.protocol~eq=${pdf}", true)); } if (table.getColumn("totalProjects") == null) { UserSchema us = getUserSchema(table, "ehr"); if (us != null) { ColumnInfo col2 = table.addColumn(new WrappedColumn(protocolCol, "totalProjects")); col2.setLabel("Total Projects"); col2.setUserEditable(false); col2.setIsUnselectable(true); col2.setFk(new QueryForeignKey(us, null, "protocolTotalProjects", "protocol", "protocol")); } } //TODO: Make this work with an Ext UI that does not over write the values /* ColumnInfo contactsColumn = table.getColumn("contacts"); contactsColumn.setDisplayColumnFactory(new DisplayColumnFactory() { @Override public DisplayColumn createRenderer(ColumnInfo colInfo) { return new ContactsColumn(colInfo); } });*/ if (table.getColumn("expirationDate") == null) { UserSchema us = getUserSchema(table, "ehr"); if (us != null) { ColumnInfo col2 = table.addColumn(new WrappedColumn(protocolCol, "expirationDate")); col2.setLabel("Expiration Date"); col2.setUserEditable(false); col2.setIsUnselectable(true); col2.setFk(new QueryForeignKey(us, null, "protocolExpirationDate", "protocol", "protocol")); } } if (table.getColumn("countsBySpecies") == null) { UserSchema us = getUserSchema(table, "ehr"); if (us != null) { ColumnInfo col2 = table.addColumn(new WrappedColumn(protocolCol, "countsBySpecies")); col2.setLabel("Max Animals Per Species"); col2.setUserEditable(false); col2.setIsUnselectable(true); col2.setFk(new QueryForeignKey(us, null, "protocolCountsBySpecies", "protocol", "protocol")); } } } private void customizeBreedingEncountersTable(AbstractTableInfo ti) { customizeSireIdColumn(ti); } private void customizePregnanciesTable(AbstractTableInfo ti) { customizeSireIdColumn(ti); } private void customizeSireIdColumn(AbstractTableInfo ti) { ColumnInfo sireid = ti.getColumn("sireid"); if (sireid != null) { UserSchema us = getUserSchema(ti, "study"); if (us != null) { sireid.setDisplayColumnFactory(colInfo -> new DataColumn(colInfo){ public void renderGridCellContents(RenderContext ctx, Writer out) throws IOException { ActionURL url = new ActionURL("ehr", "participantView.view", us.getContainer()); String[] ids = ((String)ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "sireid"))).split(","); String urlString = ""; for (int i = 0; i < ids.length; i++) { String id = ids[i]; url.replaceParameter("participantId", id); urlString += "<a href=\"" + PageFlowUtil.filter(url) + "\">"; urlString += PageFlowUtil.filter(id); urlString += "</a>"; if (i + 1 < ids.length) { urlString += ","; } } out.write(urlString); } }); } } } private ColumnInfo getWrappedIdCol(UserSchema us, AbstractTableInfo ds, String name, String queryName) { String ID_COL = "Id"; WrappedColumn col = new WrappedColumn(ds.getColumn(ID_COL), name); col.setReadOnly(true); col.setIsUnselectable(true); col.setUserEditable(false); col.setFk(new QueryForeignKey(us, null, queryName, ID_COL, ID_COL)); return col; } private UserSchema getStudyUserSchema(AbstractTableInfo ds) { return getUserSchema(ds, "study"); } public UserSchema getUserSchema(AbstractTableInfo ds, String name) { UserSchema us = ds.getUserSchema(); if (us != null) { if (name.equalsIgnoreCase(us.getName())) return us; return QueryService.get().getUserSchema(us.getUser(), us.getContainer(), name); } return null; } //TODO: Look how to use another UI to allow for better support for virtual columns /* public static class ContactsColumn extends DataColumn { public ContactsColumn(ColumnInfo colInfo) { super(colInfo); } @Override public Object getValue(RenderContext ctx) { Object value = super.getValue(ctx); StringBuffer readableContacts = new StringBuffer(); if(value != null) { //TODO:parse the value into integers to display users String contacts = value.toString(); if (contacts.contains(",")) { List<String> contactList = new ArrayList<>(Arrays.asList(contacts.split(","))); Iterator<String> contactsIterator = contactList.iterator(); while (contactsIterator.hasNext()) { User singleContact = UserManager.getUser(Integer.parseInt(contactsIterator.next())); readableContacts.append(singleContact.getDisplayName(singleContact)); readableContacts.append(" "); System.out.println("readable contact "+readableContacts); } return readableContacts; } if (NumberUtils.isNumber(contacts)){ User singleContact = UserManager.getUser(Integer.parseInt(contacts)); readableContacts.append(singleContact.getDisplayName(singleContact)); return readableContacts; } } return readableContacts; } @Override public Object getDisplayValue(RenderContext ctx) { return getValue(ctx); } @Override public String getFormattedValue(RenderContext ctx) { return h(getValue(ctx)); } }*/ }
WNPRC_EHR/src/org/labkey/wnprc_ehr/table/WNPRC_EHRCustomizer.java
/* * Copyright (c) 2012-2014 LabKey Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.labkey.wnprc_ehr.table; import org.labkey.api.data.AbstractTableInfo; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; import org.labkey.api.data.DataColumn; import org.labkey.api.data.RenderContext; import org.labkey.api.data.TableInfo; import org.labkey.api.data.WrappedColumn; import org.labkey.api.ehr.EHRService; import org.labkey.api.ldk.table.AbstractTableCustomizer; import org.labkey.api.query.FieldKey; import org.labkey.api.query.QueryForeignKey; import org.labkey.api.query.QueryService; import org.labkey.api.query.UserSchema; import org.labkey.api.util.PageFlowUtil; import org.labkey.api.util.StringExpressionFactory; import org.labkey.api.view.ActionURL; import java.io.IOException; import java.io.Writer; /** * User: bimber * Date: 12/7/12 * Time: 2:22 PM */ public class WNPRC_EHRCustomizer extends AbstractTableCustomizer { public WNPRC_EHRCustomizer() { } public void customize(TableInfo table) { if (table instanceof AbstractTableInfo) { customizeColumns((AbstractTableInfo)table); if (table.getName().equalsIgnoreCase("Animal") && table.getSchema().getName().equalsIgnoreCase("study")) customizeAnimalTable((AbstractTableInfo) table); else if (table.getName().equalsIgnoreCase("Birth") && table.getSchema().getName().equalsIgnoreCase("study")) customizeBirthTable((AbstractTableInfo) table); else if (table.getName().equalsIgnoreCase("protocol") && table.getSchema().getName().equalsIgnoreCase("ehr")) customizeProtocolTable((AbstractTableInfo)table); else if (table.getName().equalsIgnoreCase("breeding_encounters") && table.getSchema().getName().equalsIgnoreCase("study")) { customizeBreedingEncountersTable((AbstractTableInfo)table); } } } private void customizeColumns(AbstractTableInfo ti) { ColumnInfo project = ti.getColumn("project"); if (project != null) { project.setFormat("00000000"); } customizeRoomCol(ti, "room"); customizeRoomCol(ti, "room1"); customizeRoomCol(ti, "room2"); } private void customizeRoomCol(AbstractTableInfo ti, String columnName) { ColumnInfo room = ti.getColumn(columnName); if (room != null) { if (!ti.getName().equalsIgnoreCase("rooms")) { // Configure the FK to show the raw value to improve performance, since the database can avoid // doing the join in many cases Container ehrContainer = EHRService.get().getEHRStudyContainer(ti.getUserSchema().getContainer()); if (ehrContainer != null) { UserSchema us = getUserSchema(ti, "ehr_lookups", ehrContainer); if (us != null) { room.setFk(new QueryForeignKey(us, ehrContainer, "rooms", "room", "room", true)); } } } } } private void customizeBirthTable(AbstractTableInfo ti) { ColumnInfo cond = ti.getColumn("cond"); if (cond != null) { cond.setLabel("Housing Condition"); UserSchema us = getUserSchema(ti, "ehr_lookups"); if (us != null) { cond.setFk(new QueryForeignKey(us, null, "housing_condition_codes", "value", "title")); } } } private void customizeAnimalTable(AbstractTableInfo ds) { if (ds.getColumn("MHCtyping") != null) return; UserSchema us = getStudyUserSchema(ds); if (us == null){ return; } if (ds.getColumn("demographicsMHC") == null) { ColumnInfo col = getWrappedIdCol(us, ds, "MHCtyping", "demographicsMHC"); col.setLabel("MHC SSP Typing"); col.setDescription("Summarizes MHC SSP typing results for the common alleles"); ds.addColumn(col); ColumnInfo col2 = getWrappedIdCol(us, ds, "ViralLoad", "demographicsVL"); col2.setLabel("Viral Loads"); col2.setDescription("This field calculates the most recent viral load for this animal"); ds.addColumn(col2); ColumnInfo col3 = getWrappedIdCol(us, ds, "ViralStatus", "demographicsViralStatus"); col3.setLabel("Viral Status"); col3.setDescription("This calculates the viral status of the animal based on tracking project assignments"); ds.addColumn(col3); ColumnInfo col18 = getWrappedIdCol(us, ds, "Virology", "demographicsVirology"); col18.setLabel("Virology"); col18.setDescription("This calculates the distinct pathogens listed as positive for this animal from the virology table"); ds.addColumn(col18); ColumnInfo col4 = getWrappedIdCol(us, ds, "IrregularObs", "demographicsObs"); col4.setLabel("Irregular Obs"); col4.setDescription("Shows any irregular observations from each animal today or yesterday."); ds.addColumn(col4); ColumnInfo col7 = getWrappedIdCol(us, ds, "activeAssignments", "demographicsAssignments"); col7.setLabel("Assignments - Active"); col7.setDescription("Contains summaries of the assignments for each animal, including the project numbers, availability codes and a count"); ds.addColumn(col7); ColumnInfo col6 = getWrappedIdCol(us, ds, "totalAssignments", "demographicsAssignmentHistory"); col6.setLabel("Assignments - Total"); col6.setDescription("Contains summaries of the total assignments this animal has ever had, including the project numbers and a count"); ds.addColumn(col6); ColumnInfo col5 = getWrappedIdCol(us, ds, "assignmentSummary", "demographicsAssignmentSummary"); col5.setLabel("Assignments - Detailed"); col5.setDescription("Contains more detailed summaries of the active assignments for each animal, including a breakdown between research, breeding, training, etc."); ds.addColumn(col5); ColumnInfo col10 = getWrappedIdCol(us, ds, "DaysAlone", "demographicsDaysAlone"); col10.setLabel("Days Alone"); col10.setDescription("Calculates the total number of days each animal has been single housed, if applicable."); ds.addColumn(col10); ColumnInfo bloodCol = getWrappedIdCol(us, ds, "AvailBlood", "demographicsBloodSummary"); bloodCol.setLabel("Blood Remaining"); bloodCol.setDescription("Calculates the total blood draw and remaining, which is determine by weight and blood drawn in the past 30 days."); ds.addColumn(bloodCol); ColumnInfo col17 = getWrappedIdCol(us, ds, "MostRecentTB", "demographicsMostRecentTBDate"); col17.setLabel("TB Tests"); col17.setDescription("Calculates the most recent TB date for this animal, time since TB and the last eye TB tested"); ds.addColumn(col17); ColumnInfo col16 = getWrappedIdCol(us, ds, "Surgery", "demographicsSurgery"); col16.setLabel("Surgical History"); col16.setDescription("Calculates whether this animal has ever had any surgery or a surgery flagged as major"); ds.addColumn(col16); ColumnInfo col19 = getWrappedIdCol(us, ds, "CurrentBehavior", "CurrentBehaviorNotes"); col19.setLabel("Behavior - Current"); col19.setDescription("This calculates the current behavior(s) for the animal, based on the behavior abstract table"); ds.addColumn(col19); } if (ds.getColumn("totalOffspring") == null) { ColumnInfo col15 = getWrappedIdCol(us, ds, "totalOffspring", "demographicsTotalOffspring"); col15.setLabel("Number of Offspring"); col15.setDescription("Shows the total offspring of each animal"); ds.addColumn(col15); } } private void customizeProtocolTable(AbstractTableInfo table) { ColumnInfo protocolCol = table.getColumn("protocol"); if (protocolCol != null && table.getColumn("pdf") == null) { ColumnInfo col = table.addColumn(new WrappedColumn(protocolCol, "pdf")); col.setLabel("PDF"); col.setURL(StringExpressionFactory.create("/query/WNPRC/WNPRC_Units/Animal_Services/Compliance_Training/Private/Protocol_PDFs/executeQuery.view?schemaName=lists&query.queryName=ProtocolPDFs&query.protocol~eq=${pdf}", true)); } if (table.getColumn("totalProjects") == null) { UserSchema us = getUserSchema(table, "ehr"); if (us != null) { ColumnInfo col2 = table.addColumn(new WrappedColumn(protocolCol, "totalProjects")); col2.setLabel("Total Projects"); col2.setUserEditable(false); col2.setIsUnselectable(true); col2.setFk(new QueryForeignKey(us, null, "protocolTotalProjects", "protocol", "protocol")); } } //TODO: Make this work with an Ext UI that does not over write the values /* ColumnInfo contactsColumn = table.getColumn("contacts"); contactsColumn.setDisplayColumnFactory(new DisplayColumnFactory() { @Override public DisplayColumn createRenderer(ColumnInfo colInfo) { return new ContactsColumn(colInfo); } });*/ if (table.getColumn("expirationDate") == null) { UserSchema us = getUserSchema(table, "ehr"); if (us != null) { ColumnInfo col2 = table.addColumn(new WrappedColumn(protocolCol, "expirationDate")); col2.setLabel("Expiration Date"); col2.setUserEditable(false); col2.setIsUnselectable(true); col2.setFk(new QueryForeignKey(us, null, "protocolExpirationDate", "protocol", "protocol")); } } if (table.getColumn("countsBySpecies") == null) { UserSchema us = getUserSchema(table, "ehr"); if (us != null) { ColumnInfo col2 = table.addColumn(new WrappedColumn(protocolCol, "countsBySpecies")); col2.setLabel("Max Animals Per Species"); col2.setUserEditable(false); col2.setIsUnselectable(true); col2.setFk(new QueryForeignKey(us, null, "protocolCountsBySpecies", "protocol", "protocol")); } } } private void customizeBreedingEncountersTable(AbstractTableInfo ti) { ColumnInfo sireid = ti.getColumn("sireid"); if (sireid != null) { UserSchema us = getUserSchema(ti, "study"); if (us != null) { sireid.setDisplayColumnFactory(colInfo -> new DataColumn(colInfo){ public void renderGridCellContents(RenderContext ctx, Writer out) throws IOException { ActionURL url = new ActionURL("ehr", "participantView.view", us.getContainer()); String[] ids = ((String)ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "sireid"))).split(","); String urlString = ""; for (int i = 0; i < ids.length; i++) { String id = ids[i]; url.replaceParameter("participantId", id); urlString += "<a href=\"" + PageFlowUtil.filter(url) + "\">"; urlString += PageFlowUtil.filter(id); urlString += "</a>"; if (i + 1 < ids.length) { urlString += ","; } } out.write(urlString); } }); } } } private ColumnInfo getWrappedIdCol(UserSchema us, AbstractTableInfo ds, String name, String queryName) { String ID_COL = "Id"; WrappedColumn col = new WrappedColumn(ds.getColumn(ID_COL), name); col.setReadOnly(true); col.setIsUnselectable(true); col.setUserEditable(false); col.setFk(new QueryForeignKey(us, null, queryName, ID_COL, ID_COL)); return col; } private UserSchema getStudyUserSchema(AbstractTableInfo ds) { return getUserSchema(ds, "study"); } public UserSchema getUserSchema(AbstractTableInfo ds, String name) { UserSchema us = ds.getUserSchema(); if (us != null) { if (name.equalsIgnoreCase(us.getName())) return us; return QueryService.get().getUserSchema(us.getUser(), us.getContainer(), name); } return null; } //TODO: Look how to use another UI to allow for better support for virtual columns /* public static class ContactsColumn extends DataColumn { public ContactsColumn(ColumnInfo colInfo) { super(colInfo); } @Override public Object getValue(RenderContext ctx) { Object value = super.getValue(ctx); StringBuffer readableContacts = new StringBuffer(); if(value != null) { //TODO:parse the value into integers to display users String contacts = value.toString(); if (contacts.contains(",")) { List<String> contactList = new ArrayList<>(Arrays.asList(contacts.split(","))); Iterator<String> contactsIterator = contactList.iterator(); while (contactsIterator.hasNext()) { User singleContact = UserManager.getUser(Integer.parseInt(contactsIterator.next())); readableContacts.append(singleContact.getDisplayName(singleContact)); readableContacts.append(" "); System.out.println("readable contact "+readableContacts); } return readableContacts; } if (NumberUtils.isNumber(contacts)){ User singleContact = UserManager.getUser(Integer.parseInt(contacts)); readableContacts.append(singleContact.getDisplayName(singleContact)); return readableContacts; } } return readableContacts; } @Override public Object getDisplayValue(RenderContext ctx) { return getValue(ctx); } @Override public String getFormattedValue(RenderContext ctx) { return h(getValue(ctx)); } }*/ }
customize the sireid column on pregnancies table to link to multiple animals if necessary
WNPRC_EHR/src/org/labkey/wnprc_ehr/table/WNPRC_EHRCustomizer.java
customize the sireid column on pregnancies table to link to multiple animals if necessary
<ide><path>NPRC_EHR/src/org/labkey/wnprc_ehr/table/WNPRC_EHRCustomizer.java <ide> else if (table.getName().equalsIgnoreCase("protocol") && table.getSchema().getName().equalsIgnoreCase("ehr")) <ide> customizeProtocolTable((AbstractTableInfo)table); <ide> else if (table.getName().equalsIgnoreCase("breeding_encounters") && table.getSchema().getName().equalsIgnoreCase("study")) { <del> customizeBreedingEncountersTable((AbstractTableInfo)table); <add> customizeBreedingEncountersTable((AbstractTableInfo) table); <add> } else if (table.getName().equalsIgnoreCase("pregnancies") && table.getSchema().getName().equalsIgnoreCase("study")) { <add> customizePregnanciesTable((AbstractTableInfo) table); <ide> } <ide> } <ide> } <ide> <ide> private void customizeBreedingEncountersTable(AbstractTableInfo ti) <ide> { <add> customizeSireIdColumn(ti); <add> } <add> <add> private void customizePregnanciesTable(AbstractTableInfo ti) { <add> customizeSireIdColumn(ti); <add> } <add> <add> private void customizeSireIdColumn(AbstractTableInfo ti) { <ide> ColumnInfo sireid = ti.getColumn("sireid"); <ide> if (sireid != null) <ide> {
Java
apache-2.0
b9fc639dfd7f3f32ae7fe4ddf9363fd9a51e0615
0
ubikloadpack/jmeter,fj11/jmeter,d0k1/jmeter,hemikak/jmeter,liwangbest/jmeter,hizhangqi/jmeter-1,max3163/jmeter,ubikloadpack/jmeter,max3163/jmeter,vherilier/jmeter,etnetera/jmeter,kyroskoh/jmeter,liwangbest/jmeter,irfanah/jmeter,tuanhq/jmeter,d0k1/jmeter,liwangbest/jmeter,vherilier/jmeter,d0k1/jmeter,ra0077/jmeter,hizhangqi/jmeter-1,kschroeder/jmeter,etnetera/jmeter,ThiagoGarciaAlves/jmeter,kyroskoh/jmeter,kschroeder/jmeter,etnetera/jmeter,ubikfsabbe/jmeter,ra0077/jmeter,ubikfsabbe/jmeter,fj11/jmeter,fj11/jmeter,ubikfsabbe/jmeter,kschroeder/jmeter,ThiagoGarciaAlves/jmeter,hemikak/jmeter,max3163/jmeter,thomsonreuters/jmeter,etnetera/jmeter,DoctorQ/jmeter,d0k1/jmeter,ra0077/jmeter,ubikfsabbe/jmeter,max3163/jmeter,DoctorQ/jmeter,DoctorQ/jmeter,thomsonreuters/jmeter,ubikloadpack/jmeter,etnetera/jmeter,ubikloadpack/jmeter,kyroskoh/jmeter,tuanhq/jmeter,vherilier/jmeter,vherilier/jmeter,thomsonreuters/jmeter,hemikak/jmeter,ThiagoGarciaAlves/jmeter,hemikak/jmeter,irfanah/jmeter,hizhangqi/jmeter-1,ra0077/jmeter,tuanhq/jmeter,irfanah/jmeter
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.save; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.util.Iterator; import java.util.Map; import java.util.Properties; import org.apache.jmeter.junit.JMeterTestCase; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.save.converters.BooleanPropertyConverter; import org.apache.jmeter.save.converters.HashTreeConverter; import org.apache.jmeter.save.converters.IntegerPropertyConverter; import org.apache.jmeter.save.converters.LongPropertyConverter; import org.apache.jmeter.save.converters.MultiPropertyConverter; import org.apache.jmeter.save.converters.SampleResultConverter; import org.apache.jmeter.save.converters.StringPropertyConverter; import org.apache.jmeter.save.converters.TestElementConverter; import org.apache.jmeter.save.converters.TestElementPropertyConverter; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.collections.HashTree; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.alias.CannotResolveClassException; import com.thoughtworks.xstream.alias.ClassMapper; import com.thoughtworks.xstream.converters.Converter; /** * @author Mike Stover * @author <a href="mailto:kcassell&#X0040;apache.org">Keith Cassell </a> */ public class SaveService { private static XStream saver = new XStream(); private static Logger log = LoggingManager.getLoggerForClass(); // Version information for test plan header static String version = "1.0"; static String propertiesVersion = "";//read from properties file private static final String PROPVERSION = "1.5"; // Helper method to simplify alias creation from properties private static void makeAlias(String alias, String clazz) { try { saver.alias(alias, Class.forName(clazz)); } catch (ClassNotFoundException e) { log.warn("Could not set up alias " + alias + " " + e.toString()); } } private static void initProps() { // Load the alias properties Properties nameMap = new Properties(); try { nameMap.load(new FileInputStream(JMeterUtils.getJMeterHome() + JMeterUtils.getPropDefault("saveservice_properties", "/bin/saveservice.properties"))); // now create the aliases Iterator it = nameMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry me = (Map.Entry) it.next(); String key = (String) me.getKey(); String val = (String) me.getValue(); if (!key.startsWith("_")) { makeAlias(key, val); } else { //process special keys if (key.equalsIgnoreCase("_version")) { val = extractVersion(val); log.info("Using SaveService properties file " + val); propertiesVersion = val; } else { key = key.substring(1); try { if (val.trim().equals("collection")) { saver .registerConverter((Converter)Class.forName(key) .getConstructor( new Class[] { ClassMapper.class, String.class}).newInstance( new Object[] { saver.getClassMapper(), "class"})); } else if(val.trim().equals("mapping")) { saver .registerConverter((Converter)Class.forName(key) .getConstructor( new Class[] { ClassMapper.class}).newInstance( new Object[] { saver.getClassMapper()})); } else { saver.registerConverter((Converter)Class.forName(key).newInstance()); } } catch (Exception e1) { log.warn("Can't register a converter: " + key,e1); } } } } } catch (Exception e) { log.error("Bad saveservice properties file", e); } } static { initProps(); /*saver.registerConverter(new StringPropertyConverter()); saver.registerConverter(new BooleanPropertyConverter()); saver.registerConverter(new IntegerPropertyConverter()); saver.registerConverter(new LongPropertyConverter()); saver.registerConverter(new TestElementConverter(saver.getClassMapper(), "class")); saver.registerConverter(new MultiPropertyConverter( saver.getClassMapper(), "class")); saver.registerConverter(new TestElementPropertyConverter(saver .getClassMapper(), "class")); saver.registerConverter(new HashTreeConverter(saver.getClassMapper(), "class")); saver .registerConverter(new ScriptWrapperConverter(saver .getClassMapper())); saver.registerConverter(new SampleResultConverter(saver.getClassMapper(), "class")); saver.registerConverter(new TestResultWrapperConverter(saver .getClassMapper(), "class"));*/ checkVersions(); } public static void saveTree(HashTree tree, Writer writer) throws Exception { ScriptWrapper wrapper = new ScriptWrapper(); wrapper.testPlan = tree; saver.toXML(wrapper, writer); } public static void saveElement(Object el,Writer writer) throws Exception { saver.toXML(el,writer); } public static Object loadElement(InputStream in) throws Exception { return saver.fromXML(new InputStreamReader(in)); } public static Object loadElement(Reader in) throws Exception { return saver.fromXML(in); } public synchronized static void saveSampleResult(SampleResult res, Writer writer) throws Exception { saver.toXML(res, writer); writer.write('\n'); } public synchronized static void saveTestElement(TestElement elem, Writer writer) throws Exception { saver.toXML(elem,writer); writer.write('\n'); } static boolean versionsOK = true; // Extract version digits from String of the form #Revision: n.mm # // (where # is actually $ above) private static final String REVPFX = "$Revision: "; private static final String REVSFX = " $"; private static String extractVersion(String rev) { if (rev.length() > REVPFX.length() + REVSFX.length()) { return rev.substring(REVPFX.length(), rev.length() - REVSFX.length()); } else { return rev; } } private static void checkVersion(Class clazz, String expected) { String actual = "*NONE*"; try { actual = (String) clazz.getMethod("getVersion", null).invoke(null, null); actual = extractVersion(actual); } catch (Exception e) { //Not needed } if (0 != actual.compareTo(expected)) { versionsOK = false; log.warn("Version mismatch: expected '" + expected + "' found '" + actual + "' in " + clazz.getName()); } } private static void checkVersions() { versionsOK = true; checkVersion(BooleanPropertyConverter.class, "1.4"); checkVersion(HashTreeConverter.class, "1.2"); checkVersion(IntegerPropertyConverter.class, "1.3"); checkVersion(LongPropertyConverter.class, "1.3"); checkVersion(MultiPropertyConverter.class, "1.3"); checkVersion(SampleResultConverter.class, "1.5"); checkVersion(StringPropertyConverter.class, "1.6"); checkVersion(TestElementConverter.class, "1.2"); checkVersion(TestElementPropertyConverter.class, "1.3"); checkVersion(ScriptWrapperConverter.class, "1.3"); if (!PROPVERSION.equalsIgnoreCase(propertiesVersion)) { log.warn("Property file - expected " + PROPVERSION + ", found " + propertiesVersion); } if (versionsOK) { log.info("All converter versions present and correct"); } } public static TestResultWrapper loadTestResults(InputStream reader) throws Exception { TestResultWrapper wrapper = (TestResultWrapper) saver .fromXML(new InputStreamReader(reader)); return wrapper; } public static HashTree loadTree(InputStream reader) throws Exception { if (!reader.markSupported()) { reader = new BufferedInputStream(reader); } reader.mark(Integer.MAX_VALUE); ScriptWrapper wrapper = null; try { wrapper = (ScriptWrapper) saver.fromXML(new InputStreamReader(reader)); return wrapper.testPlan; } catch (CannotResolveClassException e) { log.warn("Problem loading new style: ", e); reader.reset(); return OldSaveService.loadSubTree(reader); } } public static class Test extends JMeterTestCase { public Test() { super(); } public Test(String name) { super(name); } public void testVersions() throws Exception { initProps(); checkVersions(); assertTrue("Unexpected version found", versionsOK); assertEquals("Property Version mismatch", PROPVERSION, propertiesVersion); } } }
src/core/org/apache/jmeter/save/SaveService.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.save; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.util.Iterator; import java.util.Map; import java.util.Properties; import org.apache.jmeter.junit.JMeterTestCase; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.save.converters.BooleanPropertyConverter; import org.apache.jmeter.save.converters.HashTreeConverter; import org.apache.jmeter.save.converters.IntegerPropertyConverter; import org.apache.jmeter.save.converters.LongPropertyConverter; import org.apache.jmeter.save.converters.MultiPropertyConverter; import org.apache.jmeter.save.converters.SampleResultConverter; import org.apache.jmeter.save.converters.StringPropertyConverter; import org.apache.jmeter.save.converters.TestElementConverter; import org.apache.jmeter.save.converters.TestElementPropertyConverter; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.collections.HashTree; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.alias.ClassMapper; import com.thoughtworks.xstream.converters.Converter; /** * @author Mike Stover * @author <a href="mailto:kcassell&#X0040;apache.org">Keith Cassell </a> */ public class SaveService { private static XStream saver = new XStream(); private static Logger log = LoggingManager.getLoggerForClass(); // Version information for test plan header static String version = "1.0"; static String propertiesVersion = "";//read from properties file private static final String PROPVERSION = "1.5"; // Helper method to simplify alias creation from properties private static void makeAlias(String alias, String clazz) { try { saver.alias(alias, Class.forName(clazz)); } catch (ClassNotFoundException e) { log.warn("Could not set up alias " + alias + " " + e.toString()); } } private static void initProps() { // Load the alias properties Properties nameMap = new Properties(); try { nameMap.load(new FileInputStream(JMeterUtils.getJMeterHome() + JMeterUtils.getPropDefault("saveservice_properties", "/bin/saveservice.properties"))); // now create the aliases Iterator it = nameMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry me = (Map.Entry) it.next(); String key = (String) me.getKey(); String val = (String) me.getValue(); if (!key.startsWith("_")) { makeAlias(key, val); } else { //process special keys if (key.equalsIgnoreCase("_version")) { val = extractVersion(val); log.info("Using SaveService properties file " + val); propertiesVersion = val; } else { key = key.substring(1); try { if (val.trim().equals("collection")) { saver .registerConverter((Converter)Class.forName(key) .getConstructor( new Class[] { ClassMapper.class, String.class}).newInstance( new Object[] { saver.getClassMapper(), "class"})); } else if(val.trim().equals("mapping")) { saver .registerConverter((Converter)Class.forName(key) .getConstructor( new Class[] { ClassMapper.class}).newInstance( new Object[] { saver.getClassMapper()})); } else { saver.registerConverter((Converter)Class.forName(key).newInstance()); } } catch (Exception e1) { log.warn("Can't register a converter: " + key,e1); } } } } } catch (Exception e) { log.error("Bad saveservice properties file", e); } } static { initProps(); /*saver.registerConverter(new StringPropertyConverter()); saver.registerConverter(new BooleanPropertyConverter()); saver.registerConverter(new IntegerPropertyConverter()); saver.registerConverter(new LongPropertyConverter()); saver.registerConverter(new TestElementConverter(saver.getClassMapper(), "class")); saver.registerConverter(new MultiPropertyConverter( saver.getClassMapper(), "class")); saver.registerConverter(new TestElementPropertyConverter(saver .getClassMapper(), "class")); saver.registerConverter(new HashTreeConverter(saver.getClassMapper(), "class")); saver .registerConverter(new ScriptWrapperConverter(saver .getClassMapper())); saver.registerConverter(new SampleResultConverter(saver.getClassMapper(), "class")); saver.registerConverter(new TestResultWrapperConverter(saver .getClassMapper(), "class"));*/ checkVersions(); } public static void saveTree(HashTree tree, Writer writer) throws Exception { ScriptWrapper wrapper = new ScriptWrapper(); wrapper.testPlan = tree; saver.toXML(wrapper, writer); } public static void saveElement(Object el,Writer writer) throws Exception { saver.toXML(el,writer); } public static Object loadElement(InputStream in) throws Exception { return saver.fromXML(new InputStreamReader(in)); } public static Object loadElement(Reader in) throws Exception { return saver.fromXML(in); } public synchronized static void saveSampleResult(SampleResult res, Writer writer) throws Exception { saver.toXML(res, writer); writer.write('\n'); } public synchronized static void saveTestElement(TestElement elem, Writer writer) throws Exception { saver.toXML(elem,writer); writer.write('\n'); } static boolean versionsOK = true; // Extract version digits from String of the form #Revision: n.mm # // (where # is actually $ above) private static final String REVPFX = "$Revision: "; private static final String REVSFX = " $"; private static String extractVersion(String rev) { if (rev.length() > REVPFX.length() + REVSFX.length()) { return rev.substring(REVPFX.length(), rev.length() - REVSFX.length()); } else { return rev; } } private static void checkVersion(Class clazz, String expected) { String actual = "*NONE*"; try { actual = (String) clazz.getMethod("getVersion", null).invoke(null, null); actual = extractVersion(actual); } catch (Exception e) { //Not needed } if (0 != actual.compareTo(expected)) { versionsOK = false; log.warn("Version mismatch: expected '" + expected + "' found '" + actual + "' in " + clazz.getName()); } } private static void checkVersions() { versionsOK = true; checkVersion(BooleanPropertyConverter.class, "1.4"); checkVersion(HashTreeConverter.class, "1.2"); checkVersion(IntegerPropertyConverter.class, "1.3"); checkVersion(LongPropertyConverter.class, "1.3"); checkVersion(MultiPropertyConverter.class, "1.3"); checkVersion(SampleResultConverter.class, "1.5"); checkVersion(StringPropertyConverter.class, "1.6"); checkVersion(TestElementConverter.class, "1.2"); checkVersion(TestElementPropertyConverter.class, "1.3"); checkVersion(ScriptWrapperConverter.class, "1.3"); if (!PROPVERSION.equalsIgnoreCase(propertiesVersion)) { log.warn("Property file - expected " + PROPVERSION + ", found " + propertiesVersion); } if (versionsOK) { log.info("All converter versions present and correct"); } } public static TestResultWrapper loadTestResults(InputStream reader) throws Exception { TestResultWrapper wrapper = (TestResultWrapper) saver .fromXML(new InputStreamReader(reader)); return wrapper; } public static HashTree loadTree(InputStream reader) throws Exception { if (!reader.markSupported()) { reader = new BufferedInputStream(reader); } reader.mark(Integer.MAX_VALUE); ScriptWrapper wrapper = null; try { wrapper = (ScriptWrapper) saver.fromXML(new InputStreamReader(reader)); return wrapper.testPlan; } catch (RuntimeException e) { log.warn("Problem loading new style: ", e); reader.reset(); return OldSaveService.loadSubTree(reader); } } public static class Test extends JMeterTestCase { public Test() { super(); } public Test(String name) { super(name); } public void testVersions() throws Exception { initProps(); checkVersions(); assertTrue("Unexpected version found", versionsOK); assertEquals("Property Version mismatch", PROPVERSION, propertiesVersion); } } }
Only catch expected exception git-svn-id: 7c053b8fbd1fb5868f764c6f9536fc6a9bbe7da9@325277 13f79535-47bb-0310-9956-ffa450edef68
src/core/org/apache/jmeter/save/SaveService.java
Only catch expected exception
<ide><path>rc/core/org/apache/jmeter/save/SaveService.java <ide> import org.apache.log.Logger; <ide> <ide> import com.thoughtworks.xstream.XStream; <add>import com.thoughtworks.xstream.alias.CannotResolveClassException; <ide> import com.thoughtworks.xstream.alias.ClassMapper; <ide> import com.thoughtworks.xstream.converters.Converter; <ide> <ide> wrapper = (ScriptWrapper) saver.fromXML(new InputStreamReader(reader)); <ide> return wrapper.testPlan; <ide> } <del> catch (RuntimeException e) <add> catch (CannotResolveClassException e) <ide> { <ide> log.warn("Problem loading new style: ", e); <ide> reader.reset();
Java
apache-2.0
66a205cd724e5352231532cc81fc2637b1e7fbb9
0
retomerz/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,supersven/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,samthor/intellij-community,da1z/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,SerCeMan/intellij-community,amith01994/intellij-community,petteyg/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,slisson/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,apixandru/intellij-community,izonder/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,samthor/intellij-community,wreckJ/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,semonte/intellij-community,FHannes/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,caot/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,caot/intellij-community,clumsy/intellij-community,signed/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,ahb0327/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,FHannes/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,retomerz/intellij-community,jagguli/intellij-community,clumsy/intellij-community,signed/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,supersven/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,fitermay/intellij-community,allotria/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,holmes/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,signed/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,allotria/intellij-community,retomerz/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,semonte/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,ryano144/intellij-community,semonte/intellij-community,robovm/robovm-studio,holmes/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,da1z/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,allotria/intellij-community,fnouama/intellij-community,ryano144/intellij-community,amith01994/intellij-community,clumsy/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,signed/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,semonte/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,FHannes/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,kool79/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,allotria/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,slisson/intellij-community,holmes/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,petteyg/intellij-community,caot/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,robovm/robovm-studio,semonte/intellij-community,vvv1559/intellij-community,signed/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,diorcety/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,supersven/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,vladmm/intellij-community,ibinti/intellij-community,slisson/intellij-community,da1z/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,izonder/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,kool79/intellij-community,robovm/robovm-studio,adedayo/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,asedunov/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,caot/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,caot/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,samthor/intellij-community,signed/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,caot/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,ryano144/intellij-community,apixandru/intellij-community,semonte/intellij-community,kdwink/intellij-community,clumsy/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,signed/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,diorcety/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,slisson/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,supersven/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,ryano144/intellij-community,FHannes/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,allotria/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,allotria/intellij-community,kdwink/intellij-community,robovm/robovm-studio,hurricup/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,xfournet/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,samthor/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,caot/intellij-community,samthor/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,petteyg/intellij-community,kool79/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,caot/intellij-community,vladmm/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,semonte/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,diorcety/intellij-community,izonder/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,ryano144/intellij-community,blademainer/intellij-community,apixandru/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,holmes/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,allotria/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,caot/intellij-community,asedunov/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,holmes/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,izonder/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,semonte/intellij-community,signed/intellij-community,ahb0327/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,fnouama/intellij-community,asedunov/intellij-community,dslomov/intellij-community,caot/intellij-community,da1z/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,samthor/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,izonder/intellij-community,apixandru/intellij-community,supersven/intellij-community,samthor/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,asedunov/intellij-community,kool79/intellij-community,vladmm/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,apixandru/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,semonte/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,fnouama/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,fnouama/intellij-community,kool79/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,signed/intellij-community,robovm/robovm-studio,FHannes/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,allotria/intellij-community,dslomov/intellij-community,ibinti/intellij-community,signed/intellij-community,Distrotech/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,da1z/intellij-community,fitermay/intellij-community,kool79/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,supersven/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,izonder/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,petteyg/intellij-community,vladmm/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,xfournet/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,signed/intellij-community,xfournet/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,ibinti/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,supersven/intellij-community,dslomov/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,amith01994/intellij-community,blademainer/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,orekyuu/intellij-community
package org.editorconfig.configmanagement; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.ex.EditorSettingsExternalizable; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileDocumentManagerListener; import com.intellij.openapi.fileEditor.impl.TrailingSpacesStripper; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.VirtualFile; import org.editorconfig.plugincomponents.SettingsProviderComponent; import org.editorconfig.core.EditorConfig; import org.editorconfig.Utils; import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class EditorSettingsManager implements FileDocumentManagerListener { // Handles the following EditorConfig settings: private static final String trimTrailingWhitespaceKey = "trim_trailing_whitespace"; private static final String insertFinalNewlineKey = "insert_final_newline"; private static final Map<String, String> trimMap; static { Map<String, String> map = new HashMap<String, String>(); map.put("true", EditorSettingsExternalizable.STRIP_TRAILING_SPACES_WHOLE); map.put("false", EditorSettingsExternalizable.STRIP_TRAILING_SPACES_NONE); trimMap = Collections.unmodifiableMap(map); } private static final Map<String, String> newlineMap; static { Map<String, String> map = new HashMap<String, String>(); map.put("true", TrailingSpacesStripper.ENSURE_NEWLINE); map.put("false", TrailingSpacesStripper.DONT_ENSURE_NEWLINE); newlineMap = Collections.unmodifiableMap(map); } private static final Logger LOG = Logger.getInstance("#org.editorconfig.configmanagement.EditorSettingsManager"); @Override public void beforeAllDocumentsSaving() { // Not used } @Override public void beforeDocumentSaving(@NotNull Document document) { // This is fired when any document is saved, regardless of whether it is part of a save-all or // a save-one operation final VirtualFile file = FileDocumentManager.getInstance().getFile(document); applySettings(file); } @Override public void beforeFileContentReload(VirtualFile file, @NotNull Document document) { //Not used } @Override public void fileWithNoDocumentChanged(@NotNull VirtualFile file) { //Not used } @Override public void fileContentReloaded(VirtualFile file, @NotNull Document document) { //Not used } @Override public void fileContentLoaded(@NotNull VirtualFile file, @NotNull Document document) { //Not used } @Override public void unsavedDocumentsDropped() { //Not used } private void applySettings(VirtualFile file) { // Get editorconfig settings final String filePath = file.getCanonicalPath(); final SettingsProviderComponent settingsProvider = SettingsProviderComponent.getInstance(); final List<EditorConfig.OutPair> outPairs = settingsProvider.getOutPairs(filePath); // Apply trailing spaces setting final String trimTrailingWhitespace = Utils.configValueForKey(outPairs, trimTrailingWhitespaceKey); applyConfigValueToUserData(file, TrailingSpacesStripper.OVERRIDE_STRIP_TRAILING_SPACES_KEY, trimTrailingWhitespaceKey, trimTrailingWhitespace, trimMap); // Apply final newline setting final String insertFinalNewline = Utils.configValueForKey(outPairs, insertFinalNewlineKey); applyConfigValueToUserData(file, TrailingSpacesStripper.OVERRIDE_ENSURE_NEWLINE_KEY, insertFinalNewlineKey, insertFinalNewline, newlineMap); } private void applyConfigValueToUserData(VirtualFile file, Key userDataKey, String editorConfigKey, String configValue, Map<String, String> configMap) { if (configValue.isEmpty()) { file.putUserData(userDataKey, null); } else { final String data = configMap.get(configValue); if (data == null) { LOG.warn(Utils.invalidConfigMessage(configValue, editorConfigKey, file.getCanonicalPath())); } else { file.putUserData(userDataKey, data); LOG.debug("Applied " + editorConfigKey + " settings for: " + file.getCanonicalPath()); } } } }
src/org/editorconfig/configmanagement/EditorSettingsManager.java
package org.editorconfig.configmanagement; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.ex.EditorSettingsExternalizable; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileDocumentManagerListener; import com.intellij.openapi.fileEditor.impl.TrailingSpacesStripper; import com.intellij.openapi.vfs.VirtualFile; import org.editorconfig.plugincomponents.SettingsProviderComponent; import org.editorconfig.core.EditorConfig; import org.editorconfig.Utils; import org.jetbrains.annotations.NotNull; import java.util.List; public class EditorSettingsManager implements FileDocumentManagerListener { // Handles the following EditorConfig settings: private static final String trimTrailingWhitespaceKey = "trim_trailing_whitespace"; private static final String insertFinalNewlineKey = "insert_final_newline"; private static final Logger LOG = Logger.getInstance("#org.editorconfig.configmanagement.EditorSettingsManager"); @Override public void beforeAllDocumentsSaving() { // Not used } @Override public void beforeDocumentSaving(@NotNull Document document) { // This is fired when any document is saved, regardless of whether it is part of a save-all or // a save-one operation LOG.debug("Saving one document"); VirtualFile file = FileDocumentManager.getInstance().getFile(document); applySettings(file); } @Override public void beforeFileContentReload(VirtualFile file, @NotNull Document document) { //Not used } @Override public void fileWithNoDocumentChanged(@NotNull VirtualFile file) { //Not used } @Override public void fileContentReloaded(VirtualFile file, @NotNull Document document) { //Not used } @Override public void fileContentLoaded(@NotNull VirtualFile file, @NotNull Document document) { //Not used } @Override public void unsavedDocumentsDropped() { //Not used } private void applySettings(VirtualFile file) { // Get editorconfig settings String filePath = file.getCanonicalPath(); SettingsProviderComponent settingsProvider = SettingsProviderComponent.getInstance(); List<EditorConfig.OutPair> outPairs = settingsProvider.getOutPairs(filePath); String trimTrailingWhitespace = Utils.configValueForKey(outPairs, trimTrailingWhitespaceKey); String insertFinalNewline = Utils.configValueForKey(outPairs, insertFinalNewlineKey); // Apply trailing spaces setting if (trimTrailingWhitespace.equals("true")) { file.putUserData(TrailingSpacesStripper.OVERRIDE_STRIP_TRAILING_SPACES_KEY, EditorSettingsExternalizable.STRIP_TRAILING_SPACES_WHOLE); } else if (trimTrailingWhitespace.equals("false")) { file.putUserData(TrailingSpacesStripper.OVERRIDE_STRIP_TRAILING_SPACES_KEY, EditorSettingsExternalizable.STRIP_TRAILING_SPACES_NONE); } else { if (!trimTrailingWhitespace.isEmpty()) { LOG.warn(Utils.invalidConfigMessage(trimTrailingWhitespace, trimTrailingWhitespaceKey, filePath)); } file.putUserData(TrailingSpacesStripper.OVERRIDE_STRIP_TRAILING_SPACES_KEY, null); } // Apply final newline setting if (insertFinalNewline.equals("true")) { file.putUserData(TrailingSpacesStripper.OVERRIDE_ENSURE_NEWLINE_KEY, TrailingSpacesStripper.ENSURE_NEWLINE); } else if (insertFinalNewline.equals("false")) { file.putUserData(TrailingSpacesStripper.OVERRIDE_ENSURE_NEWLINE_KEY, TrailingSpacesStripper.DONT_ENSURE_NEWLINE); } else { if (!insertFinalNewline.isEmpty()) { LOG.warn(Utils.invalidConfigMessage(insertFinalNewline, insertFinalNewlineKey, filePath)); } file.putUserData(TrailingSpacesStripper.OVERRIDE_ENSURE_NEWLINE_KEY, null); } LOG.debug("Applied editor settings for: " + filePath); } }
Tidied up userData logic in EditorSettingsManager
src/org/editorconfig/configmanagement/EditorSettingsManager.java
Tidied up userData logic in EditorSettingsManager
<ide><path>rc/org/editorconfig/configmanagement/EditorSettingsManager.java <ide> import com.intellij.openapi.fileEditor.FileDocumentManager; <ide> import com.intellij.openapi.fileEditor.FileDocumentManagerListener; <ide> import com.intellij.openapi.fileEditor.impl.TrailingSpacesStripper; <add>import com.intellij.openapi.util.Key; <ide> import com.intellij.openapi.vfs.VirtualFile; <ide> import org.editorconfig.plugincomponents.SettingsProviderComponent; <ide> import org.editorconfig.core.EditorConfig; <ide> import org.editorconfig.Utils; <ide> import org.jetbrains.annotations.NotNull; <ide> <add>import java.util.Collections; <add>import java.util.HashMap; <ide> import java.util.List; <add>import java.util.Map; <ide> <ide> public class EditorSettingsManager implements FileDocumentManagerListener { <ide> // Handles the following EditorConfig settings: <ide> private static final String trimTrailingWhitespaceKey = "trim_trailing_whitespace"; <ide> private static final String insertFinalNewlineKey = "insert_final_newline"; <add> private static final Map<String, String> trimMap; <add> static { <add> Map<String, String> map = new HashMap<String, String>(); <add> map.put("true", EditorSettingsExternalizable.STRIP_TRAILING_SPACES_WHOLE); <add> map.put("false", EditorSettingsExternalizable.STRIP_TRAILING_SPACES_NONE); <add> trimMap = Collections.unmodifiableMap(map); <add> } <add> private static final Map<String, String> newlineMap; <add> static { <add> Map<String, String> map = new HashMap<String, String>(); <add> map.put("true", TrailingSpacesStripper.ENSURE_NEWLINE); <add> map.put("false", TrailingSpacesStripper.DONT_ENSURE_NEWLINE); <add> newlineMap = Collections.unmodifiableMap(map); <add> } <ide> <ide> private static final Logger LOG = Logger.getInstance("#org.editorconfig.configmanagement.EditorSettingsManager"); <ide> <ide> public void beforeDocumentSaving(@NotNull Document document) { <ide> // This is fired when any document is saved, regardless of whether it is part of a save-all or <ide> // a save-one operation <del> LOG.debug("Saving one document"); <del> VirtualFile file = FileDocumentManager.getInstance().getFile(document); <add> final VirtualFile file = FileDocumentManager.getInstance().getFile(document); <ide> applySettings(file); <ide> } <ide> <ide> <ide> private void applySettings(VirtualFile file) { <ide> // Get editorconfig settings <del> String filePath = file.getCanonicalPath(); <del> SettingsProviderComponent settingsProvider = SettingsProviderComponent.getInstance(); <del> List<EditorConfig.OutPair> outPairs = settingsProvider.getOutPairs(filePath); <del> String trimTrailingWhitespace = Utils.configValueForKey(outPairs, trimTrailingWhitespaceKey); <del> String insertFinalNewline = Utils.configValueForKey(outPairs, insertFinalNewlineKey); <add> final String filePath = file.getCanonicalPath(); <add> final SettingsProviderComponent settingsProvider = SettingsProviderComponent.getInstance(); <add> final List<EditorConfig.OutPair> outPairs = settingsProvider.getOutPairs(filePath); <ide> // Apply trailing spaces setting <del> if (trimTrailingWhitespace.equals("true")) { <del> file.putUserData(TrailingSpacesStripper.OVERRIDE_STRIP_TRAILING_SPACES_KEY, <del> EditorSettingsExternalizable.STRIP_TRAILING_SPACES_WHOLE); <del> } else if (trimTrailingWhitespace.equals("false")) { <del> file.putUserData(TrailingSpacesStripper.OVERRIDE_STRIP_TRAILING_SPACES_KEY, <del> EditorSettingsExternalizable.STRIP_TRAILING_SPACES_NONE); <add> final String trimTrailingWhitespace = Utils.configValueForKey(outPairs, trimTrailingWhitespaceKey); <add> applyConfigValueToUserData(file, TrailingSpacesStripper.OVERRIDE_STRIP_TRAILING_SPACES_KEY, <add> trimTrailingWhitespaceKey, trimTrailingWhitespace, trimMap); <add> // Apply final newline setting <add> final String insertFinalNewline = Utils.configValueForKey(outPairs, insertFinalNewlineKey); <add> applyConfigValueToUserData(file, TrailingSpacesStripper.OVERRIDE_ENSURE_NEWLINE_KEY, <add> insertFinalNewlineKey, insertFinalNewline, newlineMap); <add> } <add> <add> private void applyConfigValueToUserData(VirtualFile file, Key userDataKey, String editorConfigKey, <add> String configValue, Map<String, String> configMap) { <add> if (configValue.isEmpty()) { <add> file.putUserData(userDataKey, null); <ide> } else { <del> if (!trimTrailingWhitespace.isEmpty()) { <del> LOG.warn(Utils.invalidConfigMessage(trimTrailingWhitespace, trimTrailingWhitespaceKey, filePath)); <add> final String data = configMap.get(configValue); <add> if (data == null) { <add> LOG.warn(Utils.invalidConfigMessage(configValue, editorConfigKey, file.getCanonicalPath())); <add> } else { <add> file.putUserData(userDataKey, data); <add> LOG.debug("Applied " + editorConfigKey + " settings for: " + file.getCanonicalPath()); <ide> } <del> file.putUserData(TrailingSpacesStripper.OVERRIDE_STRIP_TRAILING_SPACES_KEY, null); <ide> } <del> // Apply final newline setting <del> if (insertFinalNewline.equals("true")) { <del> file.putUserData(TrailingSpacesStripper.OVERRIDE_ENSURE_NEWLINE_KEY, <del> TrailingSpacesStripper.ENSURE_NEWLINE); <del> } else if (insertFinalNewline.equals("false")) { <del> file.putUserData(TrailingSpacesStripper.OVERRIDE_ENSURE_NEWLINE_KEY, <del> TrailingSpacesStripper.DONT_ENSURE_NEWLINE); <del> } else { <del> if (!insertFinalNewline.isEmpty()) { <del> LOG.warn(Utils.invalidConfigMessage(insertFinalNewline, insertFinalNewlineKey, filePath)); <del> } <del> file.putUserData(TrailingSpacesStripper.OVERRIDE_ENSURE_NEWLINE_KEY, null); <del> } <del> LOG.debug("Applied editor settings for: " + filePath); <del> <ide> } <ide> }
JavaScript
mit
a65387a29a1e903a0f73c99e259eaa12958bae9d
0
unexpectedjs/unexpected-sinon,unexpectedjs/unexpected-sinon
/*global unexpected:true, sinon, Promise:true*/ /* exported Promise, sinon */ unexpected = require('unexpected'); unexpected.output.preferredWidth = 80; unexpected.installPlugin(require('./lib/unexpected-sinon')); require('./test/monkeyPatchSinonStackFrames'); Promise = require('rsvp'); sinon = require('sinon');
bootstrap-unexpected-markdown.js
/*global unexpected:true, Promise:true*/ /* exported Promise */ unexpected = require('unexpected'); unexpected.output.preferredWidth = 80; unexpected.installPlugin(require('./lib/unexpected-sinon')); require('./test/monkeyPatchSinonStackFrames'); Promise = require('rsvp');
Unbreak documentation tests.
bootstrap-unexpected-markdown.js
Unbreak documentation tests.
<ide><path>ootstrap-unexpected-markdown.js <del>/*global unexpected:true, Promise:true*/ <del>/* exported Promise */ <add>/*global unexpected:true, sinon, Promise:true*/ <add>/* exported Promise, sinon */ <ide> unexpected = require('unexpected'); <ide> unexpected.output.preferredWidth = 80; <ide> unexpected.installPlugin(require('./lib/unexpected-sinon')); <ide> require('./test/monkeyPatchSinonStackFrames'); <ide> Promise = require('rsvp'); <add>sinon = require('sinon');
Java
apache-2.0
7b1a5f49994d248b9e0bf411cfc05a0aeec05a41
0
jnidzwetzki/scalephant,jnidzwetzki/scalephant,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb
/******************************************************************************* * * Copyright (C) 2015-2018 the BBoxDB project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package org.bboxdb.distribution.partitioner; import java.util.List; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import org.bboxdb.commons.math.BoundingBox; import org.bboxdb.distribution.DistributionGroupConfigurationCache; import org.bboxdb.distribution.DistributionGroupName; import org.bboxdb.distribution.TupleStoreConfigurationCache; import org.bboxdb.distribution.membership.BBoxDBInstance; import org.bboxdb.distribution.partitioner.regionsplit.SamplingBasedSplitStrategy; import org.bboxdb.distribution.partitioner.regionsplit.SplitpointStrategy; import org.bboxdb.distribution.placement.ResourceAllocationException; import org.bboxdb.distribution.region.DistributionRegion; import org.bboxdb.distribution.region.DistributionRegionCallback; import org.bboxdb.distribution.region.DistributionRegionIdMapper; import org.bboxdb.distribution.region.DistributionRegionSyncer; import org.bboxdb.distribution.region.DistributionRegionSyncerHelper; import org.bboxdb.distribution.zookeeper.ZookeeperException; import org.bboxdb.distribution.zookeeper.ZookeeperNotFoundException; import org.bboxdb.misc.BBoxDBException; import org.bboxdb.storage.entity.DistributionGroupConfiguration; import org.bboxdb.storage.tuplestore.manager.TupleStoreManagerRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; public class KDtreeSpacePartitioner implements SpacePartitioner { /** * The distribution group adapter */ private DistributionGroupZookeeperAdapter distributionGroupZookeeperAdapter; /** * The name of the distribution group */ private DistributionGroupName distributionGroupName; /** * The distribution region syncer */ private DistributionRegionSyncer distributionRegionSyncer; /** * The space partitioner context */ private SpacePartitionerContext spacePartitionerContext; /** * Is the space partitoner active? */ private volatile boolean active; /** * The logger */ private final static Logger logger = LoggerFactory.getLogger(KDtreeSpacePartitioner.class); /** * Reread and handle the dgroup version * @throws ZookeeperException */ @Override public void init(final SpacePartitionerContext spacePartitionerContext) throws ZookeeperException { this.distributionGroupZookeeperAdapter = spacePartitionerContext.getDistributionGroupAdapter(); this.distributionGroupName = spacePartitionerContext.getDistributionGroupName(); this.spacePartitionerContext = spacePartitionerContext; this.active = true; handleGroupCreated(); } /** * Distribution region has recreated, clear local mappings */ private void handleGroupCreated() { TupleStoreConfigurationCache.getInstance().clear(); DistributionGroupConfigurationCache.getInstance().clear(); spacePartitionerContext.getDistributionRegionMapper().clear(); this.distributionRegionSyncer = new DistributionRegionSyncer(spacePartitionerContext); logger.info("Root element for {} is deleted", distributionGroupName); if(distributionRegionSyncer != null) { distributionRegionSyncer.getDistributionRegionMapper().clear(); } // Rescan tree distributionRegionSyncer.getRootNode(); } /** * Get the root node * @return */ @Override public DistributionRegion getRootNode() { if(distributionRegionSyncer == null) { return null; } if(! active) { logger.error("Get root node on a non active space partitoner called"); return null; } return distributionRegionSyncer.getRootNode(); } /** * Split the node at the given position * @param regionToSplit * @param splitPosition * @throws ZookeeperException * @throws ResourceAllocationException * @throws ZookeeperNotFoundException */ @Override public void splitRegion(final DistributionRegion regionToSplit, final TupleStoreManagerRegistry tupleStoreManagerRegistry) throws BBoxDBException { try { final SplitpointStrategy splitpointStrategy = new SamplingBasedSplitStrategy( tupleStoreManagerRegistry); final int splitDimension = getSplitDimension(regionToSplit); final double splitPosition = splitpointStrategy.getSplitPoint(splitDimension, regionToSplit); splitNode(regionToSplit, splitPosition); } catch (Exception e) { throw new BBoxDBException(e); } } /** * Split the node at the given split point * @param regionToSplit * @param splitPosition * @throws BBoxDBException * @throws ResourceAllocationException */ public void splitNode(final DistributionRegion regionToSplit, final double splitPosition) throws BBoxDBException, ResourceAllocationException { try { logger.debug("Write split at pos {} into zookeeper", splitPosition); final String parentPath = distributionGroupZookeeperAdapter.getZookeeperPathForDistributionRegion(regionToSplit); // Only one system executes the split, therefore we can determine the child ids // Calculate the covering bounding boxes final BoundingBox parentBox = regionToSplit.getConveringBox(); final int splitDimension = getSplitDimension(regionToSplit); final BoundingBox leftBoundingBox = parentBox.splitAndGetLeft(splitPosition, splitDimension, true); final BoundingBox rightBoundingBox = parentBox.splitAndGetRight(splitPosition, splitDimension, false); final String fullname = distributionGroupName.getFullname(); final String leftPath = distributionGroupZookeeperAdapter.createNewChild(parentPath, 0, leftBoundingBox, fullname); final String rightPath = distributionGroupZookeeperAdapter.createNewChild(parentPath, 1, rightBoundingBox, fullname); // Update state distributionGroupZookeeperAdapter.setStateForDistributionGroup(parentPath, DistributionRegionState.SPLITTING); waitUntilChildrenAreCreated(regionToSplit); // Allocate systems (the data of the left node is stored locally) SpacePartitionerHelper.copySystemsToRegion(regionToSplit, regionToSplit.getDirectChildren().get(0), this, distributionGroupZookeeperAdapter); SpacePartitionerHelper.allocateSystemsToRegion(regionToSplit.getDirectChildren().get(1), this, regionToSplit.getSystems(), distributionGroupZookeeperAdapter); // update state distributionGroupZookeeperAdapter.setStateForDistributionGroup(leftPath, DistributionRegionState.ACTIVE); distributionGroupZookeeperAdapter.setStateForDistributionGroup(rightPath, DistributionRegionState.ACTIVE); waitForSplitZookeeperCallback(regionToSplit); } catch (ZookeeperException | ZookeeperNotFoundException e) { throw new BBoxDBException(e); } } @Override public boolean isMergingSupported(final DistributionRegion distributionRegion) { return ! distributionRegion.isLeafRegion(); } @Override public boolean isSplittingSupported(final DistributionRegion distributionRegion) { return distributionRegion.isLeafRegion(); } @Override public void prepareMerge(final DistributionRegion regionToMerge) throws BBoxDBException { try { logger.debug("Merging region: {}", regionToMerge); final String zookeeperPath = distributionGroupZookeeperAdapter .getZookeeperPathForDistributionRegion(regionToMerge); distributionGroupZookeeperAdapter.setStateForDistributionGroup(zookeeperPath, DistributionRegionState.ACTIVE); final List<DistributionRegion> childRegions = regionToMerge.getDirectChildren(); for(final DistributionRegion childRegion : childRegions) { final String zookeeperPathChild = distributionGroupZookeeperAdapter .getZookeeperPathForDistributionRegion(childRegion); distributionGroupZookeeperAdapter.setStateForDistributionGroup(zookeeperPathChild, DistributionRegionState.MERGING); } } catch (ZookeeperException e) { throw new BBoxDBException(e); } } @Override public void mergeComplete(final DistributionRegion regionToMerge) throws BBoxDBException { try { final List<DistributionRegion> childRegions = regionToMerge.getDirectChildren(); for(final DistributionRegion childRegion : childRegions) { logger.info("Merge done deleting: {}", childRegion.getIdentifier()); distributionGroupZookeeperAdapter.deleteChild(childRegion); } } catch (ZookeeperException e) { throw new BBoxDBException(e); } } /** * Wait for zookeeper split callback * @param regionToSplit */ private void waitUntilChildrenAreCreated(final DistributionRegion regionToSplit) { final Predicate<DistributionRegion> predicate = (r) -> r.getDirectChildren().size() == 2; DistributionRegionSyncerHelper.waitForPredicate(predicate, regionToSplit, distributionRegionSyncer); } /** * Wait for zookeeper split callback * @param regionToSplit */ private void waitForSplitZookeeperCallback(final DistributionRegion regionToSplit) { final Predicate<DistributionRegion> predicate = (r) -> isSplitForNodeComplete(r); DistributionRegionSyncerHelper.waitForPredicate(predicate, regionToSplit, distributionRegionSyncer); } /** * Allocate the given list of systems to a region * @param region * @param allocationSystems * @throws ZookeeperException */ @Override public void allocateSystemsToRegion(final DistributionRegion region, final Set<BBoxDBInstance> allocationSystems) throws ZookeeperException { final List<String> systemNames = allocationSystems.stream() .map(s -> s.getStringValue()) .collect(Collectors.toList()); logger.info("Allocating region {} to {}", region.getIdentifier(), systemNames); // Resource allocation successfully, write data to zookeeper for(final BBoxDBInstance instance : allocationSystems) { distributionGroupZookeeperAdapter.addSystemToDistributionRegion(region, instance); } } /** * Is the split for the given node complete? * @param region * @return */ private boolean isSplitForNodeComplete(final DistributionRegion region) { if(region.getDirectChildren().size() != 2) { return false; } final boolean unreadyChild = region.getDirectChildren().stream() .anyMatch(r -> r.getState() != DistributionRegionState.ACTIVE); return ! unreadyChild; } /** * Get the dimension of the distribution region * @return */ private int getDimension() { try { final DistributionGroupConfigurationCache instance = DistributionGroupConfigurationCache.getInstance(); final DistributionGroupConfiguration config = instance.getDistributionGroupConfiguration(distributionGroupName); return config.getDimensions(); } catch (ZookeeperNotFoundException e) { throw new RuntimeException(e); } } /** * Returns the dimension of the split * @return */ @VisibleForTesting public int getSplitDimension(final DistributionRegion distributionRegion) { return distributionRegion.getLevel() % getDimension(); } /** * Register a new callback * @param callback * @return */ @Override public boolean registerCallback(final DistributionRegionCallback callback) { return spacePartitionerContext.getCallbacks().add(callback); } /** * Unregister a callback * @param callback * @return */ @Override public boolean unregisterCallback(final DistributionRegionCallback callback) { return spacePartitionerContext.getCallbacks().remove(callback); } /** * Get the region id mapper */ @Override public DistributionRegionIdMapper getDistributionRegionIdMapper() { return spacePartitionerContext.getDistributionRegionMapper(); } @Override public void shutdown() { logger.info("Shutdown space partitioner for instance {}", spacePartitionerContext.getDistributionGroupName()); this.active = false; } }
bboxdb-server/src/main/java/org/bboxdb/distribution/partitioner/KDtreeSpacePartitioner.java
/******************************************************************************* * * Copyright (C) 2015-2018 the BBoxDB project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package org.bboxdb.distribution.partitioner; import java.util.List; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import org.bboxdb.commons.math.BoundingBox; import org.bboxdb.distribution.DistributionGroupConfigurationCache; import org.bboxdb.distribution.DistributionGroupName; import org.bboxdb.distribution.TupleStoreConfigurationCache; import org.bboxdb.distribution.membership.BBoxDBInstance; import org.bboxdb.distribution.partitioner.regionsplit.SamplingBasedSplitStrategy; import org.bboxdb.distribution.partitioner.regionsplit.SplitpointStrategy; import org.bboxdb.distribution.placement.ResourceAllocationException; import org.bboxdb.distribution.region.DistributionRegion; import org.bboxdb.distribution.region.DistributionRegionCallback; import org.bboxdb.distribution.region.DistributionRegionIdMapper; import org.bboxdb.distribution.region.DistributionRegionSyncer; import org.bboxdb.distribution.region.DistributionRegionSyncerHelper; import org.bboxdb.distribution.zookeeper.ZookeeperException; import org.bboxdb.distribution.zookeeper.ZookeeperNotFoundException; import org.bboxdb.misc.BBoxDBException; import org.bboxdb.storage.entity.DistributionGroupConfiguration; import org.bboxdb.storage.tuplestore.manager.TupleStoreManagerRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; public class KDtreeSpacePartitioner implements SpacePartitioner { /** * The distribution group adapter */ private DistributionGroupZookeeperAdapter distributionGroupZookeeperAdapter; /** * The name of the distribution group */ private DistributionGroupName distributionGroupName; /** * The distribution region syncer */ private DistributionRegionSyncer distributionRegionSyncer; /** * The space partitioner context */ private SpacePartitionerContext spacePartitionerContext; /** * Is the space partitoner active? */ private volatile boolean active; /** * The logger */ private final static Logger logger = LoggerFactory.getLogger(KDtreeSpacePartitioner.class); /** * Reread and handle the dgroup version * @throws ZookeeperException */ @Override public void init(final SpacePartitionerContext spacePartitionerContext) throws ZookeeperException { this.distributionGroupZookeeperAdapter = spacePartitionerContext.getDistributionGroupAdapter(); this.distributionGroupName = spacePartitionerContext.getDistributionGroupName(); this.spacePartitionerContext = spacePartitionerContext; this.active = true; handleGroupCreated(); } /** * Distribution region has recreated, clear local mappings */ private void handleGroupCreated() { TupleStoreConfigurationCache.getInstance().clear(); DistributionGroupConfigurationCache.getInstance().clear(); spacePartitionerContext.getDistributionRegionMapper().clear(); this.distributionRegionSyncer = new DistributionRegionSyncer(spacePartitionerContext); logger.info("Root element for {} is deleted", distributionGroupName); if(distributionRegionSyncer != null) { distributionRegionSyncer.getDistributionRegionMapper().clear(); } // Rescan tree distributionRegionSyncer.getRootNode(); } /** * Get the root node * @return */ @Override public DistributionRegion getRootNode() { if(distributionRegionSyncer == null) { return null; } if(! active) { logger.error("Get root node on a non active space partitoner called"); return null; } return distributionRegionSyncer.getRootNode(); } /** * Split the node at the given position * @param regionToSplit * @param splitPosition * @throws ZookeeperException * @throws ResourceAllocationException * @throws ZookeeperNotFoundException */ @Override public void splitRegion(final DistributionRegion regionToSplit, final TupleStoreManagerRegistry tupleStoreManagerRegistry) throws BBoxDBException { try { final SplitpointStrategy splitpointStrategy = new SamplingBasedSplitStrategy( tupleStoreManagerRegistry); final int splitDimension = getSplitDimension(regionToSplit); final double splitPosition = splitpointStrategy.getSplitPoint(splitDimension, regionToSplit); splitNode(regionToSplit, splitPosition); } catch (Exception e) { throw new BBoxDBException(e); } } /** * Split the node at the given split point * @param regionToSplit * @param splitPosition * @throws BBoxDBException * @throws ResourceAllocationException */ public void splitNode(final DistributionRegion regionToSplit, final double splitPosition) throws BBoxDBException, ResourceAllocationException { try { logger.debug("Write split at pos {} into zookeeper", splitPosition); final String parentPath = distributionGroupZookeeperAdapter.getZookeeperPathForDistributionRegion(regionToSplit); // Only one system executes the split, therefore we can determine the child ids // Calculate the covering bounding boxes final BoundingBox parentBox = regionToSplit.getConveringBox(); final int splitDimension = getSplitDimension(regionToSplit); final BoundingBox leftBoundingBox = parentBox.splitAndGetLeft(splitPosition, splitDimension, true); final BoundingBox rightBoundingBox = parentBox.splitAndGetRight(splitPosition, splitDimension, false); final String fullname = distributionGroupName.getFullname(); final String leftPath = distributionGroupZookeeperAdapter.createNewChild(parentPath, 0, leftBoundingBox, fullname); final String rightPath = distributionGroupZookeeperAdapter.createNewChild(parentPath, 1, rightBoundingBox, fullname); // Update state distributionGroupZookeeperAdapter.setStateForDistributionGroup(parentPath, DistributionRegionState.SPLITTING); waitUntilChildrenAreCreated(regionToSplit); // Allocate systems (the data of the left node is stored locally) SpacePartitionerHelper.copySystemsToRegion(regionToSplit, regionToSplit.getDirectChildren().get(0), this, distributionGroupZookeeperAdapter); SpacePartitionerHelper.allocateSystemsToRegion(regionToSplit.getDirectChildren().get(1), this, regionToSplit.getSystems(), distributionGroupZookeeperAdapter); // update state distributionGroupZookeeperAdapter.setStateForDistributionGroup(leftPath, DistributionRegionState.ACTIVE); distributionGroupZookeeperAdapter.setStateForDistributionGroup(rightPath, DistributionRegionState.ACTIVE); waitForSplitZookeeperCallback(regionToSplit); } catch (ZookeeperException | ZookeeperNotFoundException e) { throw new BBoxDBException(e); } } @Override public boolean isMergingSupported(final DistributionRegion distributionRegion) { return ! distributionRegion.isLeafRegion(); } @Override public boolean isSplittingSupported(final DistributionRegion distributionRegion) { return distributionRegion.isLeafRegion(); } @Override public void prepareMerge(final DistributionRegion regionToMerge) throws BBoxDBException { try { logger.debug("Merging region: {}", regionToMerge); final String zookeeperPath = distributionGroupZookeeperAdapter .getZookeeperPathForDistributionRegion(regionToMerge); distributionGroupZookeeperAdapter.setStateForDistributionGroup(zookeeperPath, DistributionRegionState.ACTIVE); final List<DistributionRegion> childRegions = regionToMerge.getDirectChildren(); for(final DistributionRegion childRegion : childRegions) { final String zookeeperPathChild = distributionGroupZookeeperAdapter .getZookeeperPathForDistributionRegion(childRegion); distributionGroupZookeeperAdapter.setStateForDistributionGroup(zookeeperPathChild, DistributionRegionState.MERGING); } } catch (ZookeeperException e) { throw new BBoxDBException(e); } } @Override public void mergeComplete(final DistributionRegion regionToMerge) throws BBoxDBException { try { final List<DistributionRegion> childRegions = regionToMerge.getDirectChildren(); for(final DistributionRegion childRegion : childRegions) { logger.info("Merge done deleting: {}", childRegion.getIdentifier()); distributionGroupZookeeperAdapter.deleteChild(childRegion); } } catch (ZookeeperException e) { throw new BBoxDBException(e); } } /** * Wait for zookeeper split callback * @param regionToSplit */ private void waitUntilChildrenAreCreated(final DistributionRegion regionToSplit) { final Predicate<DistributionRegion> predicate = (r) -> r.getDirectChildren().size() == 2; DistributionRegionSyncerHelper.waitForPredicate(predicate, regionToSplit, distributionRegionSyncer); } /** * Wait for zookeeper split callback * @param regionToSplit */ private void waitForSplitZookeeperCallback(final DistributionRegion regionToSplit) { final Predicate<DistributionRegion> predicate = (r) -> isSplitForNodeComplete(r); DistributionRegionSyncerHelper.waitForPredicate(predicate, regionToSplit, distributionRegionSyncer); } /** * Allocate the given list of systems to a region * @param region * @param allocationSystems * @throws ZookeeperException */ @Override public void allocateSystemsToRegion(final DistributionRegion region, final Set<BBoxDBInstance> allocationSystems) throws ZookeeperException { final List<String> systemNames = allocationSystems.stream() .map(s -> s.getStringValue()) .collect(Collectors.toList()); logger.info("Allocating region {} to {}", region.getIdentifier(), systemNames); // Resource allocation successfully, write data to zookeeper for(final BBoxDBInstance instance : allocationSystems) { distributionGroupZookeeperAdapter.addSystemToDistributionRegion(region, instance); } } /** * Is the split for the given node complete? * @param region * @return */ private boolean isSplitForNodeComplete(final DistributionRegion region) { if(region.getDirectChildren().size() != 2) { return false; } final boolean unreadyChild = region.getDirectChildren().stream() .anyMatch(r -> r.getState() != DistributionRegionState.ACTIVE); return ! unreadyChild; } /** * Get the dimension of the distribution region * @return */ private int getDimension() { try { final DistributionGroupConfigurationCache instance = DistributionGroupConfigurationCache.getInstance(); final DistributionGroupConfiguration config = instance.getDistributionGroupConfiguration(distributionGroupName); return config.getDimensions(); } catch (ZookeeperNotFoundException e) { throw new RuntimeException(e); } } /** * Returns the dimension of the split * @return */ @VisibleForTesting public int getSplitDimension(final DistributionRegion distributionRegion) { return distributionRegion.getLevel() % getDimension(); } /** * Register a new callback * @param callback * @return */ @Override public boolean registerCallback(final DistributionRegionCallback callback) { return spacePartitionerContext.getCallbacks().add(callback); } /** * Unregister a callback * @param callback * @return */ @Override public boolean unregisterCallback(final DistributionRegionCallback callback) { return spacePartitionerContext.getCallbacks().remove(callback); } /** * Get the region id mapper */ @Override public DistributionRegionIdMapper getDistributionRegionIdMapper() { return spacePartitionerContext.getDistributionRegionMapper(); } @Override public void shutdown() { // TODO Auto-generated method stub } }
Handle shutdown call
bboxdb-server/src/main/java/org/bboxdb/distribution/partitioner/KDtreeSpacePartitioner.java
Handle shutdown call
<ide><path>boxdb-server/src/main/java/org/bboxdb/distribution/partitioner/KDtreeSpacePartitioner.java <ide> <ide> @Override <ide> public void shutdown() { <del> // TODO Auto-generated method stub <del> <add> logger.info("Shutdown space partitioner for instance {}", <add> spacePartitionerContext.getDistributionGroupName()); <add> <add> this.active = false; <ide> } <ide> }
Java
bsd-2-clause
07ed0a11199105ef1f6b6da0dc5dbad75d46d0d9
0
saalfeldlab/template-building,saalfeldlab/template-building,saalfeldlab/template-building,saalfeldlab/template-building,saalfeldlab/template-building
package process; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import org.janelia.utility.parse.ParseUtils; import ij.IJ; import ij.ImagePlus; import io.AffineImglib2IO; import io.WritingHelper; import io.nii.NiftiIo; import io.nii.Nifti_Writer; import loci.formats.FormatException; import net.imglib2.FinalInterval; import net.imglib2.RandomAccessible; import net.imglib2.exception.ImgLibException; import net.imglib2.img.Img; import net.imglib2.img.display.imagej.ImageJFunctions; import net.imglib2.img.imageplus.ImagePlusImg; import net.imglib2.img.imageplus.ImagePlusImgs; import net.imglib2.interpolation.InterpolatorFactory; import net.imglib2.interpolation.randomaccess.NLinearInterpolatorFactory; import net.imglib2.interpolation.randomaccess.NearestNeighborInterpolatorFactory; import net.imglib2.realtransform.AffineTransform; import net.imglib2.realtransform.AffineTransform3D; import net.imglib2.realtransform.DeformationFieldTransform; import net.imglib2.realtransform.InverseRealTransform; import net.imglib2.realtransform.InvertibleRealTransform; import net.imglib2.realtransform.InvertibleRealTransformSequence; import net.imglib2.realtransform.RealViews; import net.imglib2.realtransform.ants.ANTSDeformationField; import net.imglib2.realtransform.ants.ANTSLoadAffine; import net.imglib2.type.NativeType; import net.imglib2.type.numeric.NumericType; import net.imglib2.type.numeric.integer.ShortType; import net.imglib2.type.numeric.integer.UnsignedByteType; import net.imglib2.type.numeric.integer.UnsignedShortType; import net.imglib2.type.numeric.real.FloatType; import net.imglib2.util.Util; import net.imglib2.view.IntervalView; import net.imglib2.view.Views; import sc.fiji.io.Nrrd_Reader; import util.RenderUtil; /** * Renders images transformed/registered. * * Currently the final (implied) upsampling transform is hard-coded in : it resmples up by a factor of 4 in x and y and 2 in z. * After that, it upsamples z again by a factor of (~ 2.02) to resample the images to a resolution of 0.188268 um isotropic. * * * @author John Bogovic * */ public class RenderTransformed { public static void main( String[] args ) throws FormatException, IOException { String imF = args[ 0 ]; String outF = args[ 1 ]; String outputIntervalF = args[ 2 ]; System.out.println( "imf: " + imF ); // LOAD THE IMAGE ImagePlus ip = null; if( imF.endsWith( "nii" )) { ip = NiftiIo.readNifti( new File( imF )); } else { ip = IJ.openImage( imF ); } ImagePlus baseIp = null; if( imF.endsWith( "nii" )) { try { baseIp = NiftiIo.readNifti( new File( imF ) ); } catch ( FormatException e ) { e.printStackTrace(); } catch ( IOException e ) { e.printStackTrace(); } } else if( imF.endsWith( "nrrd" )) { Nrrd_Reader nr = new Nrrd_Reader(); File imFile = new File( imF ); baseIp = nr.load( imFile.getParent(), imFile.getName()); System.out.println( "baseIp"); } else { baseIp = IJ.openImage( imF ); } double rx = ip.getCalibration().pixelWidth; double ry = ip.getCalibration().pixelHeight; double rz = ip.getCalibration().pixelDepth; AffineTransform3D resInXfm = null; if( rx == 0 ){ rx = 1.0; System.err.println( "WARNING: rx = 0 setting to 1.0" ); } if( ry == 0 ){ ry = 1.0; System.err.println( "WARNING: ry = 0 setting to 1.0" ); } if( rz == 0 ){ rz = 1.0; System.err.println( "WARNING: rz = 0 setting to 1.0" ); } if( rx != 1.0 || ry != 1.0 || rz != 1.0 ) { resInXfm = new AffineTransform3D(); resInXfm.set( rx, 0.0, 0.0, 0.0, 0.0, ry, 0.0, 0.0, 0.0, 0.0, rz, 0.0 ); System.out.println( "transform for input resolutions : " + resInXfm ); } FinalInterval renderInterval = null; if( outputIntervalF.equals("infer")) { System.out.println("trying to infer output interval"); renderInterval = inferOutputInterval( args, baseIp, new double[]{ rx, ry, rz }); System.out.println("Rendering to interval: " + Util.printInterval( renderInterval )); } else { renderInterval = parseInterval( outputIntervalF ); } System.out.println( "writing to: " + outF ); System.out.println("allocating"); ImagePlus ipout = null; if( baseIp.getBitDepth() == 8 ) { ImagePlusImg< UnsignedByteType, ? > out = ImagePlusImgs.unsignedBytes( renderInterval.dimension( 0 ), renderInterval.dimension( 1 ), renderInterval.dimension( 2 )); ipout = doIt( ImageJFunctions.wrapByte( baseIp ), out, resInXfm, args, renderInterval ); } else if( baseIp.getBitDepth() == 16 ) { ImagePlusImg< UnsignedShortType, ? > out = ImagePlusImgs.unsignedShorts( renderInterval.dimension( 0 ), renderInterval.dimension( 1 ), renderInterval.dimension( 2 )); ipout = doIt( ImageJFunctions.wrapShort( baseIp ), out, resInXfm, args, renderInterval ); } else if( baseIp.getBitDepth() == 32 ) { ImagePlusImg< FloatType, ? > out = ImagePlusImgs.floats( renderInterval.dimension( 0 ), renderInterval.dimension( 1 ), renderInterval.dimension( 2 )); ipout = doIt( ImageJFunctions.wrapFloat( baseIp ), out, resInXfm, args, renderInterval ); } else{ return; } System.out.println("saving to: " + outF ); WritingHelper.write( ipout, outF ); } public static InvertibleRealTransform loadTransform( String filePath, boolean invert ) throws IOException { if( filePath.endsWith( "mat" )) { try { AffineTransform3D xfm = ANTSLoadAffine.loadAffine( filePath ); if( invert ) { System.out.println("inverting"); System.out.println( "xfm: " + xfm ); return xfm.inverse().copy(); } System.out.println( "xfm: " + xfm ); return xfm; } catch ( IOException e ) { e.printStackTrace(); } } else if( filePath.endsWith( "txt" )) { if( Files.readAllLines( Paths.get( filePath ) ).get( 0 ).startsWith( "#Insight Transform File" )) { System.out.println("Reading itk transform file"); try { AffineTransform3D xfm = ANTSLoadAffine.loadAffine( filePath ); if( invert ) { System.out.println("inverting"); return xfm.inverse().copy(); } return xfm; } catch ( IOException e ) { e.printStackTrace(); } } else { System.out.println("Reading imglib2 transform file"); try { AffineTransform xfm = AffineImglib2IO.readXfm( 3, new File( filePath ) ); System.out.println( Arrays.toString(xfm.getRowPackedCopy() )); if( invert ) { System.out.println("inverting"); return xfm.inverse().copy(); } return xfm; } catch ( IOException e ) { e.printStackTrace(); } } } else { ImagePlus displacementIp = null; if( filePath.endsWith( "nii" )) { try { displacementIp = NiftiIo.readNifti( new File( filePath ) ); } catch ( FormatException e ) { e.printStackTrace(); } catch ( IOException e ) { e.printStackTrace(); } } else { displacementIp = IJ.openImage( filePath ); } if( displacementIp == null ) return null; ANTSDeformationField dfield = new ANTSDeformationField( displacementIp ); System.out.println( "DISPLACEMENT INTERVAL: " + Util.printInterval( dfield.getDefInterval() )); if( invert ) { // System.out.println( "WARNING: ITERATIVE INVERSE OF DISPLACEMENT FIELD IS UNTESTED "); // InvertibleDeformationFieldTransform<FloatType> invxfm = new InvertibleDeformationFieldTransform<FloatType>( // new DeformationFieldTransform<FloatType>( dfield.getDefField() )); // // return new InverseRealTransform( invxfm ); System.err.println("Inverse deformation fields are not yet supported."); return null; } return dfield; } return null; } public static FinalInterval inferOutputInterval( String[] args, ImagePlus ip, double[] resIn ) { int i = 0; AffineTransform3D resOutXfm = null; while( i < args.length ) { if( args[ i ].equals( "-r" )) { i++; double[] outputResolution = ParseUtils.parseDoubleArray( args[ i ] ); i++; resOutXfm = new AffineTransform3D(); resOutXfm.set( outputResolution[ 0 ], 0.0, 0.0, 0.0, 0.0, outputResolution[ 1 ], 0.0, 0.0, 0.0, 0.0, outputResolution[ 2 ], 0.0 ); System.out.println( "output Resolution " + Arrays.toString( outputResolution )); continue; } i++; } return new FinalInterval( (long)Math.round( ip.getWidth() * resIn[ 0 ] / resOutXfm.get( 0, 0 )), (long)Math.round( ip.getHeight() * resIn[ 1 ] / resOutXfm.get( 1, 1 )), (long)Math.round( ip.getNSlices() * resIn[ 2 ] / resOutXfm.get( 2, 2 ))); } public static <T extends NumericType<T> & NativeType<T> > ImagePlus doIt( Img<T> baseImg, ImagePlusImg< T, ? > out, AffineTransform3D resInXfm, String[] args, FinalInterval renderInterval ) throws IOException { // Concatenate all the transforms InvertibleRealTransformSequence totalXfm = new InvertibleRealTransformSequence(); if( resInXfm != null ) { totalXfm.add( resInXfm ); System.out.println( "resInXfm: " + resInXfm ); } int nThreads = 8; AffineTransform3D resOutXfm = null; InterpolatorFactory<T,RandomAccessible<T>> interp = new NLinearInterpolatorFactory<T>(); int i = 3; while( i < args.length ) { boolean invert = false; if( args[ i ].equals( "-i" )) { invert = true; i++; } if( args[ i ].equals( "-q" )) { i++; nThreads = Integer.parseInt( args[ i ] ); i++; System.out.println( "argument specifies " + nThreads + " threads" ); continue; } if( args[ i ].equals( "-t" )) { i++; String interpArg = args[ i ].toLowerCase(); if( interpArg.equals( "nearest" ) || interpArg.equals( "near")) interp = new NearestNeighborInterpolatorFactory<T>(); i++; System.out.println( "using" + interp + " interpolation" ); continue; } if( args[ i ].equals( "-r" )) { i++; double[] outputResolution = ParseUtils.parseDoubleArray( args[ i ] ); i++; resOutXfm = new AffineTransform3D(); resOutXfm.set( outputResolution[ 0 ], 0.0, 0.0, 0.0, 0.0, outputResolution[ 1 ], 0.0, 0.0, 0.0, 0.0, outputResolution[ 2 ], 0.0 ); System.out.println( "output Resolution " + Arrays.toString( outputResolution )); continue; } if( invert ) System.out.println( "loading transform from " + args[ i ] + " AND INVERTING" ); else System.out.println( "loading transform from " + args[ i ]); InvertibleRealTransform xfm = loadTransform( args[ i ], invert ); if( xfm == null ) { System.err.println(" failed to load transform "); System.exit( 1 ); } totalXfm.add( xfm ); i++; } if( resOutXfm != null ) totalXfm.add( resOutXfm.inverse() ); System.out.println("transforming"); IntervalView< T > imgHiXfm = Views.interval( Views.raster( RealViews.transform( Views.interpolate( Views.extendZero( baseImg ), interp ), totalXfm )), renderInterval ); IntervalView< T > outTranslated = Views.translate( out, renderInterval.min( 0 ), renderInterval.min( 1 ), renderInterval.min( 2 )); System.out.println("copying with " + nThreads + " threads"); RenderUtil.copyToImageStack( imgHiXfm, outTranslated, nThreads ); ImagePlus ipout = null; try { ipout = out.getImagePlus(); } catch ( ImgLibException e ) { // TODO Auto-generated catch block e.printStackTrace(); } if (resOutXfm != null ) { ipout.getCalibration().pixelWidth = resOutXfm.get( 0, 0 ); ipout.getCalibration().pixelHeight = resOutXfm.get( 1, 1 ); ipout.getCalibration().pixelDepth = resOutXfm.get( 2, 2 ); } if( ipout.getNSlices() == 1 && ipout.getNChannels() > 1 ) { ipout.setDimensions( ipout.getNSlices(), ipout.getNChannels(), ipout.getNFrames() ); } return ipout; } public static FinalInterval parseInterval( String outSz ) { FinalInterval destInterval = null; if ( outSz.contains( ":" ) ) { String[] minMax = outSz.split( ":" ); System.out.println( " " + minMax[ 0 ] ); System.out.println( " " + minMax[ 1 ] ); long[] min = ParseUtils.parseLongArray( minMax[ 0 ] ); long[] max = ParseUtils.parseLongArray( minMax[ 1 ] ); destInterval = new FinalInterval( min, max ); } else { long[] outputSize = ParseUtils.parseLongArray( outSz ); destInterval = new FinalInterval( outputSize ); } return destInterval; } }
src/main/java/process/RenderTransformed.java
package process; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import org.janelia.utility.parse.ParseUtils; import ij.IJ; import ij.ImagePlus; import io.AffineImglib2IO; import io.nii.NiftiIo; import io.nii.Nifti_Writer; import loci.formats.FormatException; import net.imglib2.FinalInterval; import net.imglib2.RandomAccessible; import net.imglib2.exception.ImgLibException; import net.imglib2.img.Img; import net.imglib2.img.display.imagej.ImageJFunctions; import net.imglib2.img.imageplus.ImagePlusImg; import net.imglib2.img.imageplus.ImagePlusImgs; import net.imglib2.interpolation.InterpolatorFactory; import net.imglib2.interpolation.randomaccess.NLinearInterpolatorFactory; import net.imglib2.interpolation.randomaccess.NearestNeighborInterpolatorFactory; import net.imglib2.realtransform.AffineTransform; import net.imglib2.realtransform.AffineTransform3D; import net.imglib2.realtransform.InverseRealTransform; import net.imglib2.realtransform.InvertibleDeformationFieldTransform; import net.imglib2.realtransform.InvertibleRealTransform; import net.imglib2.realtransform.InvertibleRealTransformSequence; import net.imglib2.realtransform.RealViews; import net.imglib2.realtransform.ants.ANTSDeformationField; import net.imglib2.realtransform.ants.ANTSLoadAffine; import net.imglib2.type.NativeType; import net.imglib2.type.numeric.NumericType; import net.imglib2.type.numeric.integer.UnsignedByteType; import net.imglib2.type.numeric.integer.UnsignedShortType; import net.imglib2.type.numeric.real.FloatType; import net.imglib2.util.Util; import net.imglib2.view.IntervalView; import net.imglib2.view.Views; import util.RenderUtil; /** * Renders images transformed/registered. * * Currently the final (implied) upsampling transform is hard-coded in : it resmples up by a factor of 4 in x and y and 2 in z. * After that, it upsamples z again by a factor of (~ 2.02) to resample the images to a resolution of 0.188268 um isotropic. * * * @author John Bogovic * */ public class RenderTransformed { public static void main( String[] args ) throws FormatException, IOException { String imF = args[ 0 ]; String outF = args[ 1 ]; String outputIntervalF = args[ 2 ]; System.out.println( "imf: " + imF ); // LOAD THE IMAGE ImagePlus ip = null; if( imF.endsWith( "nii" )) { ip = NiftiIo.readNifti( new File( imF )); } else { ip = IJ.openImage( imF ); } ImagePlus baseIp = null; if( imF.endsWith( "nii" )) { try { baseIp = NiftiIo.readNifti( new File( imF ) ); } catch ( FormatException e ) { e.printStackTrace(); } catch ( IOException e ) { e.printStackTrace(); } } else { baseIp = IJ.openImage( imF ); } double rx = ip.getCalibration().pixelWidth; double ry = ip.getCalibration().pixelHeight; double rz = ip.getCalibration().pixelDepth; AffineTransform3D resInXfm = null; if( rx == 0 ){ rx = 1.0; System.err.println( "WARNING: rx = 0 setting to 1.0" ); } if( ry == 0 ){ ry = 1.0; System.err.println( "WARNING: ry = 0 setting to 1.0" ); } if( rz == 0 ){ rz = 1.0; System.err.println( "WARNING: rz = 0 setting to 1.0" ); } if( rx != 1.0 || ry != 1.0 || rz != 1.0 ) { resInXfm = new AffineTransform3D(); resInXfm.set( rx, 0.0, 0.0, 0.0, 0.0, ry, 0.0, 0.0, 0.0, 0.0, rz, 0.0 ); } FinalInterval renderInterval = null; if( outputIntervalF.equals("infer")) { System.out.println("trying to infer output interval"); renderInterval = inferOutputInterval( args, baseIp, new double[]{ rx, ry, rz }); System.out.println("Rendering to interval: " + Util.printInterval( renderInterval )); } else { renderInterval = parseInterval( outputIntervalF ); } System.out.println( "writing to: " + outF ); System.out.println("allocating"); ImagePlus ipout = null; if( baseIp.getBitDepth() == 8 ) { System.out.println("bytes"); System.out.println("bytes"); System.out.println("bytes"); ImagePlusImg< UnsignedByteType, ? > out = ImagePlusImgs.unsignedBytes( renderInterval.dimension( 0 ), renderInterval.dimension( 1 ), renderInterval.dimension( 2 )); ipout = doIt( ImageJFunctions.wrapByte( baseIp ), out, resInXfm, args, renderInterval ); } else if( baseIp.getBitDepth() == 16 ) { System.out.println("shorts"); System.out.println("shorts"); System.out.println("shorts"); ImagePlusImg< UnsignedShortType, ? > out = ImagePlusImgs.unsignedShorts( renderInterval.dimension( 0 ), renderInterval.dimension( 1 ), renderInterval.dimension( 2 )); ipout = doIt( ImageJFunctions.wrapShort( baseIp ), out, resInXfm, args, renderInterval ); } else if( baseIp.getBitDepth() == 32 ) { System.out.println("floats"); System.out.println("floats"); System.out.println("floats"); ImagePlusImg< FloatType, ? > out = ImagePlusImgs.floats( renderInterval.dimension( 0 ), renderInterval.dimension( 1 ), renderInterval.dimension( 2 )); ipout = doIt( ImageJFunctions.wrapFloat( baseIp ), out, resInXfm, args, renderInterval ); } else{ return; } System.out.println("saving to: " + outF ); WritingHelper.write( ipout, outF ); } public static InvertibleRealTransform loadTransform( String filePath, boolean invert ) throws IOException { if( filePath.endsWith( "mat" )) { try { AffineTransform3D xfm = ANTSLoadAffine.loadAffine( filePath ); if( invert ) { System.out.println("inverting"); System.out.println( "xfm: " + xfm ); return xfm.inverse().copy(); } System.out.println( "xfm: " + xfm ); return xfm; } catch ( IOException e ) { e.printStackTrace(); } } else if( filePath.endsWith( "txt" )) { if( Files.readAllLines( Paths.get( filePath ) ).get( 0 ).startsWith( "#Insight Transform File" )) { System.out.println("Reading itk transform file"); try { AffineTransform3D xfm = ANTSLoadAffine.loadAffine( filePath ); if( invert ) { System.out.println("inverting"); return xfm.inverse().copy(); } return xfm; } catch ( IOException e ) { e.printStackTrace(); } } else { System.out.println("Reading imglib2 transform file"); try { AffineTransform xfm = AffineImglib2IO.readXfm( 3, new File( filePath ) ); if( invert ) { System.out.println("inverting"); return xfm.inverse().copy(); } return xfm; } catch ( IOException e ) { e.printStackTrace(); } } } else { ImagePlus displacementIp = null; if( filePath.endsWith( "nii" )) { try { displacementIp = NiftiIo.readNifti( new File( filePath ) ); } catch ( FormatException e ) { e.printStackTrace(); } catch ( IOException e ) { e.printStackTrace(); } } else { displacementIp = IJ.openImage( filePath ); } if( displacementIp == null ) return null; ANTSDeformationField dfield = new ANTSDeformationField( displacementIp ); System.out.println( "DISPLACEMENT INTERVAL: " + Util.printInterval( dfield.getDefInterval() )); if( invert ) { //System.out.println( "cant invert displacement field here"); InvertibleDeformationFieldTransform<FloatType> invxfm = new InvertibleDeformationFieldTransform<FloatType>( dfield.getDefField()); return new InverseRealTransform( invxfm ); } return dfield; } return null; } public static FinalInterval inferOutputInterval( String[] args, ImagePlus ip, double[] resIn ) { int i = 0; AffineTransform3D resOutXfm = null; while( i < args.length ) { if( args[ i ].equals( "-r" )) { i++; double[] outputResolution = ParseUtils.parseDoubleArray( args[ i ] ); i++; resOutXfm = new AffineTransform3D(); resOutXfm.set( outputResolution[ 0 ], 0.0, 0.0, 0.0, 0.0, outputResolution[ 1 ], 0.0, 0.0, 0.0, 0.0, outputResolution[ 2 ], 0.0 ); System.out.println( "output Resolution " + Arrays.toString( outputResolution )); continue; } i++; } return new FinalInterval( (long)Math.round( ip.getWidth() * resIn[ 0 ] / resOutXfm.get( 0, 0 )), (long)Math.round( ip.getHeight() * resIn[ 1 ] / resOutXfm.get( 1, 1 )), (long)Math.round( ip.getNSlices() * resIn[ 2 ] / resOutXfm.get( 2, 2 ))); } public static <T extends NumericType<T> & NativeType<T> > ImagePlus doIt( Img<T> baseImg, ImagePlusImg< T, ? > out, AffineTransform3D resInXfm, String[] args, FinalInterval renderInterval ) throws IOException { // Concatenate all the transforms InvertibleRealTransformSequence totalXfm = new InvertibleRealTransformSequence(); if( resInXfm != null ) { totalXfm.add( resInXfm ); System.out.println( "resInXfm: " + resInXfm ); } int nThreads = 8; AffineTransform3D resOutXfm = null; InterpolatorFactory<T,RandomAccessible<T>> interp = new NLinearInterpolatorFactory<T>(); int i = 3; while( i < args.length ) { boolean invert = false; if( args[ i ].equals( "-i" )) { invert = true; i++; } if( args[ i ].equals( "-q" )) { i++; nThreads = Integer.parseInt( args[ i ] ); i++; System.out.println( "argument specifies " + nThreads + " threads" ); continue; } if( args[ i ].equals( "-t" )) { i++; String interpArg = args[ i ].toLowerCase(); if( interpArg.equals( "nearest" ) || interpArg.equals( "near")) interp = new NearestNeighborInterpolatorFactory<T>(); i++; System.out.println( "using" + interp + " interpolation" ); continue; } if( args[ i ].equals( "-r" )) { i++; double[] outputResolution = ParseUtils.parseDoubleArray( args[ i ] ); i++; resOutXfm = new AffineTransform3D(); resOutXfm.set( outputResolution[ 0 ], 0.0, 0.0, 0.0, 0.0, outputResolution[ 1 ], 0.0, 0.0, 0.0, 0.0, outputResolution[ 2 ], 0.0 ); System.out.println( "output Resolution " + Arrays.toString( outputResolution )); continue; } if( invert ) System.out.println( "loading transform from " + args[ i ] + " AND INVERTING" ); else System.out.println( "loading transform from " + args[ i ]); InvertibleRealTransform xfm = loadTransform( args[ i ], invert ); if( xfm == null ) { System.err.println(" failed to load transform "); System.exit( 1 ); } totalXfm.add( xfm ); i++; } if( resOutXfm != null ) totalXfm.add( resOutXfm.inverse() ); System.out.println("transforming"); IntervalView< T > imgHiXfm = Views.interval( Views.raster( RealViews.transform( Views.interpolate( Views.extendZero( baseImg ), interp ), totalXfm )), renderInterval ); IntervalView< T > outTranslated = Views.translate( out, renderInterval.min( 0 ), renderInterval.min( 1 ), renderInterval.min( 2 )); System.out.println("copying with " + nThreads + " threads"); RenderUtil.copyToImageStack( imgHiXfm, outTranslated, nThreads ); ImagePlus ipout = null; try { ipout = out.getImagePlus(); } catch ( ImgLibException e ) { // TODO Auto-generated catch block e.printStackTrace(); } if (resOutXfm != null ) { ipout.getCalibration().pixelWidth = resOutXfm.get( 0, 0 ); ipout.getCalibration().pixelHeight = resOutXfm.get( 1, 1 ); ipout.getCalibration().pixelDepth = resOutXfm.get( 2, 2 ); } if( ipout.getNSlices() == 1 && ipout.getNChannels() > 1 ) { ipout.setDimensions( ipout.getNSlices(), ipout.getNChannels(), ipout.getNFrames() ); } return ipout; } public static FinalInterval parseInterval( String outSz ) { FinalInterval destInterval = null; if ( outSz.contains( ":" ) ) { String[] minMax = outSz.split( ":" ); System.out.println( " " + minMax[ 0 ] ); System.out.println( " " + minMax[ 1 ] ); long[] min = ParseUtils.parseLongArray( minMax[ 0 ] ); long[] max = ParseUtils.parseLongArray( minMax[ 1 ] ); destInterval = new FinalInterval( min, max ); } else { long[] outputSize = ParseUtils.parseLongArray( outSz ); destInterval = new FinalInterval( outputSize ); } return destInterval; } }
rendering changes * add nrrd dfield support * remove support for iterative dfield inverse
src/main/java/process/RenderTransformed.java
rendering changes
<ide><path>rc/main/java/process/RenderTransformed.java <ide> import ij.IJ; <ide> import ij.ImagePlus; <ide> import io.AffineImglib2IO; <add>import io.WritingHelper; <ide> import io.nii.NiftiIo; <ide> import io.nii.Nifti_Writer; <ide> import loci.formats.FormatException; <ide> import net.imglib2.interpolation.randomaccess.NearestNeighborInterpolatorFactory; <ide> import net.imglib2.realtransform.AffineTransform; <ide> import net.imglib2.realtransform.AffineTransform3D; <add>import net.imglib2.realtransform.DeformationFieldTransform; <ide> import net.imglib2.realtransform.InverseRealTransform; <del>import net.imglib2.realtransform.InvertibleDeformationFieldTransform; <add> <ide> import net.imglib2.realtransform.InvertibleRealTransform; <ide> import net.imglib2.realtransform.InvertibleRealTransformSequence; <ide> import net.imglib2.realtransform.RealViews; <ide> import net.imglib2.realtransform.ants.ANTSLoadAffine; <ide> import net.imglib2.type.NativeType; <ide> import net.imglib2.type.numeric.NumericType; <add>import net.imglib2.type.numeric.integer.ShortType; <ide> import net.imglib2.type.numeric.integer.UnsignedByteType; <ide> import net.imglib2.type.numeric.integer.UnsignedShortType; <ide> import net.imglib2.type.numeric.real.FloatType; <ide> import net.imglib2.util.Util; <ide> import net.imglib2.view.IntervalView; <ide> import net.imglib2.view.Views; <add>import sc.fiji.io.Nrrd_Reader; <ide> import util.RenderUtil; <ide> <ide> /** <ide> e.printStackTrace(); <ide> } <ide> } <add> else if( imF.endsWith( "nrrd" )) <add> { <add> Nrrd_Reader nr = new Nrrd_Reader(); <add> File imFile = new File( imF ); <add> <add> baseIp = nr.load( imFile.getParent(), imFile.getName()); <add> System.out.println( "baseIp"); <add> } <ide> else <ide> { <ide> baseIp = IJ.openImage( imF ); <ide> resInXfm.set( rx, 0.0, 0.0, 0.0, <ide> 0.0, ry, 0.0, 0.0, <ide> 0.0, 0.0, rz, 0.0 ); <add> System.out.println( "transform for input resolutions : " + resInXfm ); <ide> } <ide> <ide> FinalInterval renderInterval = null; <ide> ImagePlus ipout = null; <ide> if( baseIp.getBitDepth() == 8 ) <ide> { <del> System.out.println("bytes"); <del> System.out.println("bytes"); <del> System.out.println("bytes"); <ide> ImagePlusImg< UnsignedByteType, ? > out = ImagePlusImgs.unsignedBytes( <ide> renderInterval.dimension( 0 ), <ide> renderInterval.dimension( 1 ), <ide> } <ide> else if( baseIp.getBitDepth() == 16 ) <ide> { <del> System.out.println("shorts"); <del> System.out.println("shorts"); <del> System.out.println("shorts"); <ide> ImagePlusImg< UnsignedShortType, ? > out = ImagePlusImgs.unsignedShorts( <ide> renderInterval.dimension( 0 ), <ide> renderInterval.dimension( 1 ), <ide> renderInterval.dimension( 2 )); <ide> <add> <ide> ipout = doIt( ImageJFunctions.wrapShort( baseIp ), out, resInXfm, args, renderInterval ); <ide> } <ide> else if( baseIp.getBitDepth() == 32 ) <ide> { <del> System.out.println("floats"); <del> System.out.println("floats"); <del> System.out.println("floats"); <ide> ImagePlusImg< FloatType, ? > out = ImagePlusImgs.floats( <ide> renderInterval.dimension( 0 ), <ide> renderInterval.dimension( 1 ), <ide> try <ide> { <ide> AffineTransform xfm = AffineImglib2IO.readXfm( 3, new File( filePath ) ); <add> System.out.println( Arrays.toString(xfm.getRowPackedCopy() )); <ide> if( invert ) <ide> { <ide> System.out.println("inverting"); <ide> <ide> if( invert ) <ide> { <del> //System.out.println( "cant invert displacement field here"); <del> InvertibleDeformationFieldTransform<FloatType> invxfm = new InvertibleDeformationFieldTransform<FloatType>( <del> dfield.getDefField()); <del> <del> return new InverseRealTransform( invxfm ); <add>// System.out.println( "WARNING: ITERATIVE INVERSE OF DISPLACEMENT FIELD IS UNTESTED "); <add>// InvertibleDeformationFieldTransform<FloatType> invxfm = new InvertibleDeformationFieldTransform<FloatType>( <add>// new DeformationFieldTransform<FloatType>( dfield.getDefField() )); <add>// <add>// return new InverseRealTransform( invxfm ); <add> System.err.println("Inverse deformation fields are not yet supported."); <add> return null; <ide> } <ide> return dfield; <ide> }
Java
apache-2.0
31274d7e64ff6b16158a6f2ba2c4a3d6159b95b5
0
pstorch/cgeo,brok85/cgeo,samueltardieu/cgeo,schwabe/cgeo,KublaikhanGeek/cgeo,ThibaultR/cgeo,xiaoyanit/cgeo,pstorch/cgeo,vishwakulkarni/cgeo,superspindel/cgeo,kumy/cgeo,ThibaultR/cgeo,auricgoldfinger/cgeo,marco-dev/c-geo-opensource,S-Bartfast/cgeo,mucek4/cgeo,brok85/cgeo,vishwakulkarni/cgeo,KublaikhanGeek/cgeo,kumy/cgeo,S-Bartfast/cgeo,SammysHP/cgeo,matej116/cgeo,Bananeweizen/cgeo,lewurm/cgeo,rsudev/c-geo-opensource,lewurm/cgeo,madankb/cgeo,yummy222/cgeo,Bananeweizen/cgeo,SammysHP/cgeo,mucek4/cgeo,mucek4/cgeo,tobiasge/cgeo,superspindel/cgeo,yummy222/cgeo,marco-dev/c-geo-opensource,samueltardieu/cgeo,superspindel/cgeo,schwabe/cgeo,Huertix/cgeo,samueltardieu/cgeo,cgeo/cgeo,cgeo/cgeo,kumy/cgeo,pstorch/cgeo,tobiasge/cgeo,xiaoyanit/cgeo,Bananeweizen/cgeo,KublaikhanGeek/cgeo,lewurm/cgeo,ThibaultR/cgeo,rsudev/c-geo-opensource,tobiasge/cgeo,madankb/cgeo,auricgoldfinger/cgeo,auricgoldfinger/cgeo,vishwakulkarni/cgeo,xiaoyanit/cgeo,S-Bartfast/cgeo,yummy222/cgeo,rsudev/c-geo-opensource,brok85/cgeo,Huertix/cgeo,schwabe/cgeo,madankb/cgeo,SammysHP/cgeo,cgeo/cgeo,marco-dev/c-geo-opensource,cgeo/cgeo,schwabe/cgeo,matej116/cgeo,matej116/cgeo,Huertix/cgeo
package cgeo.geocaching.connector.gc; import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.DataStore; import cgeo.geocaching.Geocache; import cgeo.geocaching.Image; import cgeo.geocaching.LogEntry; import cgeo.geocaching.PocketQueryList; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; import cgeo.geocaching.Trackable; import cgeo.geocaching.TrackableLog; import cgeo.geocaching.Waypoint; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.enumerations.LogTypeTrackable; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.files.LocParser; import cgeo.geocaching.gcvote.GCVote; import cgeo.geocaching.gcvote.GCVoteRating; import cgeo.geocaching.geopoint.DistanceParser; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.loaders.RecaptchaReceiver; import cgeo.geocaching.network.Network; import cgeo.geocaching.network.Parameters; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.ui.DirectionImage; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.JsonUtils; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.MatcherWrapper; import cgeo.geocaching.utils.RxUtils; import cgeo.geocaching.utils.SynchronizedDateFormat; import cgeo.geocaching.utils.TextUtils; import ch.boye.httpclientandroidlib.HttpResponse; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.functions.Action1; import rx.functions.Func0; import rx.functions.Func2; import android.net.Uri; import android.text.Html; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.EnumSet; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.regex.Pattern; public abstract class GCParser { private final static SynchronizedDateFormat dateTbIn1 = new SynchronizedDateFormat("EEEEE, dd MMMMM yyyy", Locale.ENGLISH); // Saturday, 28 March 2009 private final static SynchronizedDateFormat dateTbIn2 = new SynchronizedDateFormat("EEEEE, MMMMM dd, yyyy", Locale.ENGLISH); // Saturday, March 28, 2009 private static SearchResult parseSearch(final String url, final String pageContent, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { if (StringUtils.isBlank(pageContent)) { Log.e("GCParser.parseSearch: No page given"); return null; } final List<String> cids = new ArrayList<>(); String page = pageContent; final SearchResult searchResult = new SearchResult(); searchResult.setUrl(url); searchResult.viewstates = GCLogin.getViewstates(page); // recaptcha if (showCaptcha) { final String recaptchaJsParam = TextUtils.getMatch(page, GCConstants.PATTERN_SEARCH_RECAPTCHA, false, null); if (recaptchaJsParam != null) { recaptchaReceiver.setKey(recaptchaJsParam.trim()); recaptchaReceiver.fetchChallenge(); } if (recaptchaReceiver != null && StringUtils.isNotBlank(recaptchaReceiver.getChallenge())) { recaptchaReceiver.notifyNeed(); } } if (!page.contains("SearchResultsTable")) { // there are no results. aborting here avoids a wrong error log in the next parsing step return searchResult; } int startPos = page.indexOf("<div id=\"ctl00_ContentBody_ResultsPanel\""); if (startPos == -1) { Log.e("GCParser.parseSearch: ID \"ctl00_ContentBody_dlResults\" not found on page"); return null; } page = page.substring(startPos); // cut on <table startPos = page.indexOf('>'); final int endPos = page.indexOf("ctl00_ContentBody_UnitTxt"); if (startPos == -1 || endPos == -1) { Log.e("GCParser.parseSearch: ID \"ctl00_ContentBody_UnitTxt\" not found on page"); return null; } page = page.substring(startPos + 1, endPos - startPos + 1); // cut between <table> and </table> final String[] rows = StringUtils.splitByWholeSeparator(page, "<tr class="); final int rowsCount = rows.length; int excludedCaches = 0; final ArrayList<Geocache> caches = new ArrayList<>(); for (int z = 1; z < rowsCount; z++) { final Geocache cache = new Geocache(); final String row = rows[z]; // check for cache type presence if (!row.contains("images/wpttypes")) { continue; } try { final MatcherWrapper matcherGuidAndDisabled = new MatcherWrapper(GCConstants.PATTERN_SEARCH_GUIDANDDISABLED, row); while (matcherGuidAndDisabled.find()) { if (matcherGuidAndDisabled.groupCount() > 0) { if (matcherGuidAndDisabled.group(2) != null) { cache.setName(Html.fromHtml(matcherGuidAndDisabled.group(2).trim()).toString()); } if (matcherGuidAndDisabled.group(3) != null) { cache.setLocation(Html.fromHtml(matcherGuidAndDisabled.group(3).trim()).toString()); } final String attr = matcherGuidAndDisabled.group(1); if (attr != null) { cache.setDisabled(attr.contains("Strike")); cache.setArchived(attr.contains("OldWarning")); } } } } catch (final RuntimeException e) { // failed to parse GUID and/or Disabled Log.w("GCParser.parseSearch: Failed to parse GUID and/or Disabled data", e); } if (Settings.isExcludeDisabledCaches() && (cache.isDisabled() || cache.isArchived())) { // skip disabled and archived caches excludedCaches++; continue; } cache.setGeocode(TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_GEOCODE, true, 1, cache.getGeocode(), true)); // cache type cache.setType(CacheType.getByPattern(TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_TYPE, null))); // cache direction - image if (Settings.getLoadDirImg()) { final String direction = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_DIRECTION_DISTANCE, false, null); if (direction != null) { cache.setDirectionImg(direction); } } // cache distance - estimated distance for basic members final String distance = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_DIRECTION_DISTANCE, false, 2, null, false); if (distance != null) { cache.setDistance(DistanceParser.parseDistance(distance, !Settings.isUseImperialUnits())); } // difficulty/terrain final MatcherWrapper matcherDT = new MatcherWrapper(GCConstants.PATTERN_SEARCH_DIFFICULTY_TERRAIN, row); if (matcherDT.find()) { final Float difficulty = parseStars(matcherDT.group(1)); if (difficulty != null) { cache.setDifficulty(difficulty); } final Float terrain = parseStars(matcherDT.group(3)); if (terrain != null) { cache.setTerrain(terrain); } } // size final String container = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_CONTAINER, false, null); cache.setSize(CacheSize.getById(container)); // date hidden, makes sorting event caches easier final String dateHidden = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_HIDDEN_DATE, false, null); if (StringUtils.isNotBlank(dateHidden)) { try { final Date date = GCLogin.parseGcCustomDate(dateHidden); if (date != null) { cache.setHidden(date); } } catch (final ParseException e) { Log.e("Error parsing event date from search", e); } } // cache inventory final MatcherWrapper matcherTbs = new MatcherWrapper(GCConstants.PATTERN_SEARCH_TRACKABLES, row); String inventoryPre = null; while (matcherTbs.find()) { if (matcherTbs.groupCount() > 0) { try { cache.setInventoryItems(Integer.parseInt(matcherTbs.group(1))); } catch (final NumberFormatException e) { Log.e("Error parsing trackables count", e); } inventoryPre = matcherTbs.group(2); } } if (StringUtils.isNotBlank(inventoryPre)) { final MatcherWrapper matcherTbsInside = new MatcherWrapper(GCConstants.PATTERN_SEARCH_TRACKABLESINSIDE, inventoryPre); while (matcherTbsInside.find()) { if (matcherTbsInside.groupCount() == 2 && matcherTbsInside.group(2) != null && !matcherTbsInside.group(2).equalsIgnoreCase("premium member only cache") && cache.getInventoryItems() <= 0) { cache.setInventoryItems(1); } } } // premium cache cache.setPremiumMembersOnly(row.contains("/images/icons/16/premium_only.png")); // found it cache.setFound(row.contains("/images/icons/16/found.png") || row.contains("uxUserLogDate\" class=\"Success\"")); // id String result = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_ID, null); if (null != result) { cache.setCacheId(result); cids.add(cache.getCacheId()); } // favorite count try { result = getNumberString(TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_FAVORITE, false, 1, null, true)); if (null != result) { cache.setFavoritePoints(Integer.parseInt(result)); } } catch (final NumberFormatException e) { Log.w("GCParser.parseSearch: Failed to parse favorite count", e); } caches.add(cache); } searchResult.addAndPutInCache(caches); // total caches found try { final String result = TextUtils.getMatch(page, GCConstants.PATTERN_SEARCH_TOTALCOUNT, false, 1, null, true); if (null != result) { searchResult.setTotalCountGC(Integer.parseInt(result) - excludedCaches); } } catch (final NumberFormatException e) { Log.w("GCParser.parseSearch: Failed to parse cache count", e); } String recaptchaText = null; if (recaptchaReceiver != null && StringUtils.isNotBlank(recaptchaReceiver.getChallenge())) { recaptchaReceiver.waitForUser(); recaptchaText = recaptchaReceiver.getText(); } if (!cids.isEmpty() && (Settings.isGCPremiumMember() || showCaptcha) && ((recaptchaReceiver == null || StringUtils.isBlank(recaptchaReceiver.getChallenge())) || StringUtils.isNotBlank(recaptchaText))) { Log.i("Trying to get .loc for " + cids.size() + " caches"); try { // get coordinates for parsed caches final Parameters params = new Parameters( "__EVENTTARGET", "", "__EVENTARGUMENT", ""); GCLogin.putViewstates(params, searchResult.viewstates); for (final String cid : cids) { params.put("CID", cid); } if (StringUtils.isNotBlank(recaptchaText) && recaptchaReceiver != null) { params.put("recaptcha_challenge_field", recaptchaReceiver.getChallenge()); params.put("recaptcha_response_field", recaptchaText); } params.put("ctl00$ContentBody$uxDownloadLoc", "Download Waypoints"); final String coordinates = Network.getResponseData(Network.postRequest("http://www.geocaching.com/seek/nearest.aspx", params), false); if (StringUtils.contains(coordinates, "You have not agreed to the license agreement. The license agreement is required before you can start downloading GPX or LOC files from Geocaching.com")) { Log.i("User has not agreed to the license agreement. Can\'t download .loc file."); searchResult.setError(StatusCode.UNAPPROVED_LICENSE); return searchResult; } LocParser.parseLoc(searchResult, coordinates); } catch (final RuntimeException e) { Log.e("GCParser.parseSearch.CIDs", e); } } // get direction images if (Settings.getLoadDirImg()) { final Set<Geocache> cachesReloaded = searchResult.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB); for (final Geocache cache : cachesReloaded) { if (cache.getCoords() == null && StringUtils.isNotEmpty(cache.getDirectionImg())) { DirectionImage.getDrawable(cache.getDirectionImg()); } } } return searchResult; } private static Float parseStars(final String value) { final float floatValue = Float.parseFloat(StringUtils.replaceChars(value, ',', '.')); return floatValue >= 0.5 && floatValue <= 5.0 ? floatValue : null; } static SearchResult parseCache(final String page, final CancellableHandler handler) { final ImmutablePair<StatusCode, Geocache> parsed = parseCacheFromText(page, handler); // attention: parseCacheFromText already stores implicitly through searchResult.addCache if (parsed.left != StatusCode.NO_ERROR) { return new SearchResult(parsed.left); } final Geocache cache = parsed.right; getExtraOnlineInfo(cache, page, handler); // too late: it is already stored through parseCacheFromText cache.setDetailedUpdatedNow(); if (CancellableHandler.isCancelled(handler)) { return null; } // save full detailed caches CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_cache); DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB)); // update progress message so user knows we're still working. This is more of a place holder than // actual indication of what the program is doing CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_render); return new SearchResult(cache); } static SearchResult parseAndSaveCacheFromText(final String page, @Nullable final CancellableHandler handler) { final ImmutablePair<StatusCode, Geocache> parsed = parseCacheFromText(page, handler); final SearchResult result = new SearchResult(parsed.left); if (parsed.left == StatusCode.NO_ERROR) { result.addAndPutInCache(Collections.singletonList(parsed.right)); DataStore.saveLogsWithoutTransaction(parsed.right.getGeocode(), getLogsFromDetails(page).toBlocking().toIterable()); } return result; } /** * Parse cache from text and return either an error code or a cache object in a pair. Note that inline logs are * not parsed nor saved, while the cache itself is. * * @param pageIn * the page text to parse * @param handler * the handler to send the progress notifications to * @return a pair, with a {@link StatusCode} on the left, and a non-null cache object on the right * iff the status code is {@link StatusCode.NO_ERROR}. */ static private ImmutablePair<StatusCode, Geocache> parseCacheFromText(final String pageIn, @Nullable final CancellableHandler handler) { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_details); if (StringUtils.isBlank(pageIn)) { Log.e("GCParser.parseCache: No page given"); return null; } if (pageIn.contains(GCConstants.STRING_UNPUBLISHED_OTHER) || pageIn.contains(GCConstants.STRING_UNPUBLISHED_FROM_SEARCH)) { return ImmutablePair.of(StatusCode.UNPUBLISHED_CACHE, null); } if (pageIn.contains(GCConstants.STRING_PREMIUMONLY_1) || pageIn.contains(GCConstants.STRING_PREMIUMONLY_2)) { return ImmutablePair.of(StatusCode.PREMIUM_ONLY, null); } final String cacheName = Html.fromHtml(TextUtils.getMatch(pageIn, GCConstants.PATTERN_NAME, true, "")).toString(); if (GCConstants.STRING_UNKNOWN_ERROR.equalsIgnoreCase(cacheName)) { return ImmutablePair.of(StatusCode.UNKNOWN_ERROR, null); } // first handle the content with line breaks, then trim everything for easier matching and reduced memory consumption in parsed fields String personalNoteWithLineBreaks = ""; final MatcherWrapper matcher = new MatcherWrapper(GCConstants.PATTERN_PERSONALNOTE, pageIn); if (matcher.find()) { personalNoteWithLineBreaks = matcher.group(1).trim(); } final String page = TextUtils.replaceWhitespace(pageIn); final Geocache cache = new Geocache(); cache.setDisabled(page.contains(GCConstants.STRING_DISABLED)); cache.setArchived(page.contains(GCConstants.STRING_ARCHIVED)); cache.setPremiumMembersOnly(TextUtils.matches(page, GCConstants.PATTERN_PREMIUMMEMBERS)); cache.setFavorite(TextUtils.matches(page, GCConstants.PATTERN_FAVORITE)); // cache geocode cache.setGeocode(TextUtils.getMatch(page, GCConstants.PATTERN_GEOCODE, true, cache.getGeocode())); // cache id cache.setCacheId(TextUtils.getMatch(page, GCConstants.PATTERN_CACHEID, true, cache.getCacheId())); // cache guid cache.setGuid(TextUtils.getMatch(page, GCConstants.PATTERN_GUID, true, cache.getGuid())); // name cache.setName(cacheName); // owner real name cache.setOwnerUserId(Network.decode(TextUtils.getMatch(page, GCConstants.PATTERN_OWNER_USERID, true, cache.getOwnerUserId()))); cache.setUserModifiedCoords(false); String tableInside = page; final int pos = tableInside.indexOf(GCConstants.STRING_CACHEDETAILS); if (pos == -1) { Log.e("GCParser.parseCache: ID \"cacheDetails\" not found on page"); return null; } tableInside = tableInside.substring(pos); if (StringUtils.isNotBlank(tableInside)) { // cache terrain String result = TextUtils.getMatch(tableInside, GCConstants.PATTERN_TERRAIN, true, null); if (result != null) { try { cache.setTerrain(Float.parseFloat(StringUtils.replaceChars(result, '_', '.'))); } catch (final NumberFormatException e) { Log.e("Error parsing terrain value", e); } } // cache difficulty result = TextUtils.getMatch(tableInside, GCConstants.PATTERN_DIFFICULTY, true, null); if (result != null) { try { cache.setDifficulty(Float.parseFloat(StringUtils.replaceChars(result, '_', '.'))); } catch (final NumberFormatException e) { Log.e("Error parsing difficulty value", e); } } // owner cache.setOwnerDisplayName(StringEscapeUtils.unescapeHtml4(TextUtils.getMatch(tableInside, GCConstants.PATTERN_OWNER_DISPLAYNAME, true, cache.getOwnerDisplayName()))); // hidden try { String hiddenString = TextUtils.getMatch(tableInside, GCConstants.PATTERN_HIDDEN, true, null); if (StringUtils.isNotBlank(hiddenString)) { cache.setHidden(GCLogin.parseGcCustomDate(hiddenString)); } if (cache.getHiddenDate() == null) { // event date hiddenString = TextUtils.getMatch(tableInside, GCConstants.PATTERN_HIDDENEVENT, true, null); if (StringUtils.isNotBlank(hiddenString)) { cache.setHidden(GCLogin.parseGcCustomDate(hiddenString)); } } } catch (final ParseException e) { // failed to parse cache hidden date Log.w("GCParser.parseCache: Failed to parse cache hidden (event) date", e); } // favorite try { cache.setFavoritePoints(Integer.parseInt(TextUtils.getMatch(tableInside, GCConstants.PATTERN_FAVORITECOUNT, true, "0"))); } catch (final NumberFormatException e) { Log.e("Error parsing favorite count", e); } // cache size cache.setSize(CacheSize.getById(TextUtils.getMatch(tableInside, GCConstants.PATTERN_SIZE, true, CacheSize.NOT_CHOSEN.id))); } // cache found cache.setFound(TextUtils.matches(page, GCConstants.PATTERN_FOUND) || TextUtils.matches(page, GCConstants.PATTERN_FOUND_ALTERNATIVE)); // cache type cache.setType(CacheType.getByGuid(TextUtils.getMatch(page, GCConstants.PATTERN_TYPE, true, cache.getType().id))); // on watchlist cache.setOnWatchlist(TextUtils.matches(page, GCConstants.PATTERN_WATCHLIST)); // latitude and longitude. Can only be retrieved if user is logged in String latlon = TextUtils.getMatch(page, GCConstants.PATTERN_LATLON, true, ""); if (StringUtils.isNotEmpty(latlon)) { try { cache.setCoords(new Geopoint(latlon)); cache.setReliableLatLon(true); } catch (final Geopoint.GeopointException e) { Log.w("GCParser.parseCache: Failed to parse cache coordinates", e); } } // cache location cache.setLocation(TextUtils.getMatch(page, GCConstants.PATTERN_LOCATION, true, "")); // cache hint final String result = TextUtils.getMatch(page, GCConstants.PATTERN_HINT, false, null); if (result != null) { // replace linebreak and paragraph tags final String hint = GCConstants.PATTERN_LINEBREAK.matcher(result).replaceAll("\n"); cache.setHint(StringUtils.replace(hint, "</p>", "").trim()); } cache.checkFields(); // cache personal note cache.setPersonalNote(personalNoteWithLineBreaks); // cache short description cache.setShortDescription(TextUtils.getMatch(page, GCConstants.PATTERN_SHORTDESC, true, "")); // cache description final String longDescription = TextUtils.getMatch(page, GCConstants.PATTERN_DESC, true, ""); String relatedWebPage = TextUtils.getMatch(page, GCConstants.PATTERN_RELATED_WEB_PAGE, true, ""); if (StringUtils.isNotEmpty(relatedWebPage)) { relatedWebPage = String.format("<a href=\"%s\"><b>%s</b></a><br/><br/>", relatedWebPage, relatedWebPage); } cache.setDescription(relatedWebPage + longDescription); // cache attributes try { final String attributesPre = TextUtils.getMatch(page, GCConstants.PATTERN_ATTRIBUTES, true, null); if (null != attributesPre) { final MatcherWrapper matcherAttributesInside = new MatcherWrapper(GCConstants.PATTERN_ATTRIBUTESINSIDE, attributesPre); final ArrayList<String> attributes = new ArrayList<>(); while (matcherAttributesInside.find()) { if (matcherAttributesInside.groupCount() > 1 && !matcherAttributesInside.group(2).equalsIgnoreCase("blank")) { // by default, use the tooltip of the attribute String attribute = matcherAttributesInside.group(2).toLowerCase(Locale.US); // if the image name can be recognized, use the image name as attribute final String imageName = matcherAttributesInside.group(1).trim(); if (StringUtils.isNotEmpty(imageName)) { final int start = imageName.lastIndexOf('/'); final int end = imageName.lastIndexOf('.'); if (start >= 0 && end >= 0) { attribute = imageName.substring(start + 1, end).replace('-', '_').toLowerCase(Locale.US); } } attributes.add(attribute); } } cache.setAttributes(attributes); } } catch (final RuntimeException e) { // failed to parse cache attributes Log.w("GCParser.parseCache: Failed to parse cache attributes", e); } // cache spoilers try { if (CancellableHandler.isCancelled(handler)) { return null; } CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_spoilers); final MatcherWrapper matcherSpoilersInside = new MatcherWrapper(GCConstants.PATTERN_SPOILER_IMAGE, page); while (matcherSpoilersInside.find()) { // the original spoiler URL (include .../display/... contains a low-resolution image // if we shorten the URL we get the original-resolution image final String url = matcherSpoilersInside.group(1).replace("/display", ""); String title = null; if (matcherSpoilersInside.group(3) != null) { title = matcherSpoilersInside.group(3); } String description = null; if (matcherSpoilersInside.group(4) != null) { description = matcherSpoilersInside.group(4); } cache.addSpoiler(new Image(url, title, description)); } } catch (final RuntimeException e) { // failed to parse cache spoilers Log.w("GCParser.parseCache: Failed to parse cache spoilers", e); } // cache inventory try { cache.setInventoryItems(0); final MatcherWrapper matcherInventory = new MatcherWrapper(GCConstants.PATTERN_INVENTORY, page); if (matcherInventory.find()) { if (cache.getInventory() == null) { cache.setInventory(new ArrayList<Trackable>()); } if (matcherInventory.groupCount() > 1) { final String inventoryPre = matcherInventory.group(2); if (StringUtils.isNotBlank(inventoryPre)) { final MatcherWrapper matcherInventoryInside = new MatcherWrapper(GCConstants.PATTERN_INVENTORYINSIDE, inventoryPre); while (matcherInventoryInside.find()) { if (matcherInventoryInside.groupCount() > 0) { final Trackable inventoryItem = new Trackable(); inventoryItem.setGuid(matcherInventoryInside.group(1)); inventoryItem.setName(matcherInventoryInside.group(2)); cache.getInventory().add(inventoryItem); cache.setInventoryItems(cache.getInventoryItems() + 1); } } } } } } catch (final RuntimeException e) { // failed to parse cache inventory Log.w("GCParser.parseCache: Failed to parse cache inventory (2)", e); } // cache logs counts try { final String countlogs = TextUtils.getMatch(page, GCConstants.PATTERN_COUNTLOGS, true, null); if (null != countlogs) { final MatcherWrapper matcherLog = new MatcherWrapper(GCConstants.PATTERN_COUNTLOG, countlogs); while (matcherLog.find()) { final String typeStr = matcherLog.group(1); final String countStr = getNumberString(matcherLog.group(2)); if (StringUtils.isNotBlank(typeStr) && LogType.UNKNOWN != LogType.getByIconName(typeStr) && StringUtils.isNotBlank(countStr)) { cache.getLogCounts().put(LogType.getByIconName(typeStr), Integer.parseInt(countStr)); } } } } catch (final NumberFormatException e) { // failed to parse logs Log.w("GCParser.parseCache: Failed to parse cache log count", e); } // waypoints - reset collection cache.setWaypoints(Collections.<Waypoint> emptyList(), false); // add waypoint for original coordinates in case of user-modified listing-coordinates try { final String originalCoords = TextUtils.getMatch(page, GCConstants.PATTERN_LATLON_ORIG, false, null); if (null != originalCoords) { final Waypoint waypoint = new Waypoint(CgeoApplication.getInstance().getString(R.string.cache_coordinates_original), WaypointType.ORIGINAL, false); waypoint.setCoords(new Geopoint(originalCoords)); cache.addOrChangeWaypoint(waypoint, false); cache.setUserModifiedCoords(true); } } catch (final Geopoint.GeopointException ignored) { } int wpBegin = page.indexOf("<table class=\"Table\" id=\"ctl00_ContentBody_Waypoints\">"); if (wpBegin != -1) { // parse waypoints if (CancellableHandler.isCancelled(handler)) { return null; } CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_waypoints); String wpList = page.substring(wpBegin); int wpEnd = wpList.indexOf("</p>"); if (wpEnd > -1 && wpEnd <= wpList.length()) { wpList = wpList.substring(0, wpEnd); } if (!wpList.contains("No additional waypoints to display.")) { wpEnd = wpList.indexOf("</table>"); wpList = wpList.substring(0, wpEnd); wpBegin = wpList.indexOf("<tbody>"); wpEnd = wpList.indexOf("</tbody>"); if (wpBegin >= 0 && wpEnd >= 0 && wpEnd <= wpList.length()) { wpList = wpList.substring(wpBegin + 7, wpEnd); } final String[] wpItems = StringUtils.splitByWholeSeparator(wpList, "<tr"); for (int j = 1; j < wpItems.length; j++) { String[] wp = StringUtils.splitByWholeSeparator(wpItems[j], "<td"); // waypoint name // res is null during the unit tests final String name = TextUtils.getMatch(wp[6], GCConstants.PATTERN_WPNAME, true, 1, CgeoApplication.getInstance().getString(R.string.waypoint), true); // waypoint type final String resulttype = TextUtils.getMatch(wp[3], GCConstants.PATTERN_WPTYPE, null); final Waypoint waypoint = new Waypoint(name, WaypointType.findById(resulttype), false); // waypoint prefix waypoint.setPrefix(TextUtils.getMatch(wp[4], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON, true, 2, waypoint.getPrefix(), false)); // waypoint lookup waypoint.setLookup(TextUtils.getMatch(wp[5], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON, true, 2, waypoint.getLookup(), false)); // waypoint latitude and longitude latlon = Html.fromHtml(TextUtils.getMatch(wp[7], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON, false, 2, "", false)).toString().trim(); if (!StringUtils.startsWith(latlon, "???")) { waypoint.setLatlon(latlon); waypoint.setCoords(new Geopoint(latlon)); } j++; if (wpItems.length > j) { wp = StringUtils.splitByWholeSeparator(wpItems[j], "<td"); } // waypoint note waypoint.setNote(TextUtils.getMatch(wp[3], GCConstants.PATTERN_WPNOTE, waypoint.getNote())); cache.addOrChangeWaypoint(waypoint, false); } } } cache.parseWaypointsFromNote(); // last check for necessary cache conditions if (StringUtils.isBlank(cache.getGeocode())) { return ImmutablePair.of(StatusCode.UNKNOWN_ERROR, null); } cache.setDetailedUpdatedNow(); return ImmutablePair.of(StatusCode.NO_ERROR, cache); } private static String getNumberString(final String numberWithPunctuation) { return StringUtils.replaceChars(numberWithPunctuation, ".,", ""); } public static SearchResult searchByNextPage(final SearchResult search, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { if (search == null) { return null; } final String[] viewstates = search.getViewstates(); final String url = search.getUrl(); if (StringUtils.isBlank(url)) { Log.e("GCParser.searchByNextPage: No url found"); return search; } if (GCLogin.isEmpty(viewstates)) { Log.e("GCParser.searchByNextPage: No viewstate given"); return search; } final Parameters params = new Parameters( "__EVENTTARGET", "ctl00$ContentBody$pgrBottom$ctl08", "__EVENTARGUMENT", ""); GCLogin.putViewstates(params, viewstates); final String page = GCLogin.getInstance().postRequestLogged(url, params); if (!GCLogin.getInstance().getLoginStatus(page)) { Log.e("GCParser.postLogTrackable: Can not log in geocaching"); return search; } if (StringUtils.isBlank(page)) { Log.e("GCParser.searchByNextPage: No data from server"); return search; } final SearchResult searchResult = parseSearch(url, page, showCaptcha, recaptchaReceiver); if (searchResult == null || CollectionUtils.isEmpty(searchResult.getGeocodes())) { Log.w("GCParser.searchByNextPage: No cache parsed"); return search; } // search results don't need to be filtered so load GCVote ratings here GCVote.loadRatings(new ArrayList<>(searchResult.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB))); // save to application search.setError(searchResult.getError()); search.setViewstates(searchResult.viewstates); for (final String geocode : searchResult.getGeocodes()) { search.addGeocode(geocode); } return search; } /** * Possibly hide caches found or hidden by user. This mutates its params argument when possible. * * @param params * the parameters to mutate, or null to create a new Parameters if needed * @param my * @param addF * @return the original params if not null, maybe augmented with f=1, or a new Parameters with f=1 or null otherwise */ private static Parameters addFToParams(final Parameters params, final boolean my, final boolean addF) { if (!my && Settings.isExcludeMyCaches() && addF) { if (params == null) { return new Parameters("f", "1"); } params.put("f", "1"); Log.i("Skipping caches found or hidden by user."); } return params; } /** * @param cacheType * @param listId * @param showCaptcha * @param params * the parameters to add to the request URI * @param recaptchaReceiver * @return */ @Nullable private static SearchResult searchByAny(final CacheType cacheType, final boolean my, final boolean showCaptcha, final Parameters params, final RecaptchaReceiver recaptchaReceiver) { insertCacheType(params, cacheType); final String uri = "http://www.geocaching.com/seek/nearest.aspx"; final String fullUri = uri + "?" + addFToParams(params, my, true); final String page = GCLogin.getInstance().getRequestLogged(uri, addFToParams(params, my, true)); if (StringUtils.isBlank(page)) { Log.e("GCParser.searchByAny: No data from server"); return null; } assert page != null; final SearchResult searchResult = parseSearch(fullUri, page, showCaptcha, recaptchaReceiver); if (searchResult == null || CollectionUtils.isEmpty(searchResult.getGeocodes())) { Log.e("GCParser.searchByAny: No cache parsed"); return searchResult; } final SearchResult search = searchResult.filterSearchResults(Settings.isExcludeDisabledCaches(), false, cacheType); GCLogin.getInstance().getLoginStatus(page); return search; } public static SearchResult searchByCoords(final @NonNull Geopoint coords, final CacheType cacheType, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { final Parameters params = new Parameters("lat", Double.toString(coords.getLatitude()), "lng", Double.toString(coords.getLongitude())); return searchByAny(cacheType, false, showCaptcha, params, recaptchaReceiver); } public static SearchResult searchByKeyword(final @NonNull String keyword, final CacheType cacheType, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { if (StringUtils.isBlank(keyword)) { Log.e("GCParser.searchByKeyword: No keyword given"); return null; } final Parameters params = new Parameters("key", keyword); return searchByAny(cacheType, false, showCaptcha, params, recaptchaReceiver); } private static boolean isSearchForMyCaches(final String userName) { if (userName.equalsIgnoreCase(Settings.getGcCredentials().left)) { Log.i("Overriding users choice because of self search, downloading all caches."); return true; } return false; } public static SearchResult searchByUsername(final String userName, final CacheType cacheType, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { if (StringUtils.isBlank(userName)) { Log.e("GCParser.searchByUsername: No user name given"); return null; } final Parameters params = new Parameters("ul", userName); return searchByAny(cacheType, isSearchForMyCaches(userName), showCaptcha, params, recaptchaReceiver); } public static SearchResult searchByPocketQuery(final String pocketGuid, final CacheType cacheType, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { if (StringUtils.isBlank(pocketGuid)) { Log.e("GCParser.searchByPocket: No guid name given"); return null; } final Parameters params = new Parameters("pq", pocketGuid); return searchByAny(cacheType, false, showCaptcha, params, recaptchaReceiver); } public static SearchResult searchByOwner(final String userName, final CacheType cacheType, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { if (StringUtils.isBlank(userName)) { Log.e("GCParser.searchByOwner: No user name given"); return null; } final Parameters params = new Parameters("u", userName); return searchByAny(cacheType, isSearchForMyCaches(userName), showCaptcha, params, recaptchaReceiver); } public static SearchResult searchByAddress(final String address, final CacheType cacheType, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { if (StringUtils.isBlank(address)) { Log.e("GCParser.searchByAddress: No address given"); return null; } final ObjectNode response = Network.requestJSON("http://www.geocaching.com/api/geocode", new Parameters("q", address)); if (response == null) { return null; } if (!StringUtils.equalsIgnoreCase(response.path("status").asText(), "success")) { return null; } final JsonNode data = response.path("data"); final JsonNode latNode = data.get("lat"); final JsonNode lngNode = data.get("lng"); if (latNode == null || lngNode == null) { return null; } return searchByCoords(new Geopoint(latNode.asDouble(), lngNode.asDouble()), cacheType, showCaptcha, recaptchaReceiver); } @Nullable public static Trackable searchTrackable(final String geocode, final String guid, final String id) { if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid) && StringUtils.isBlank(id)) { Log.w("GCParser.searchTrackable: No geocode nor guid nor id given"); return null; } Trackable trackable = new Trackable(); final Parameters params = new Parameters(); if (StringUtils.isNotBlank(geocode)) { params.put("tracker", geocode); trackable.setGeocode(geocode); } else if (StringUtils.isNotBlank(guid)) { params.put("guid", guid); } else if (StringUtils.isNotBlank(id)) { params.put("id", id); } final String page = GCLogin.getInstance().getRequestLogged("http://www.geocaching.com/track/details.aspx", params); if (StringUtils.isBlank(page)) { Log.e("GCParser.searchTrackable: No data from server"); return trackable; } assert page != null; trackable = parseTrackable(page, geocode); if (trackable == null) { Log.w("GCParser.searchTrackable: No trackable parsed"); return null; } return trackable; } public static List<PocketQueryList> searchPocketQueryList() { final Parameters params = new Parameters(); final String page = GCLogin.getInstance().getRequestLogged("http://www.geocaching.com/pocket/default.aspx", params); if (StringUtils.isBlank(page)) { Log.e("GCParser.searchPocketQueryList: No data from server"); return null; } final String subPage = StringUtils.substringAfter(page, "class=\"PocketQueryListTable"); if (StringUtils.isEmpty(subPage)) { Log.e("GCParser.searchPocketQueryList: class \"PocketQueryListTable\" not found on page"); return Collections.emptyList(); } final List<PocketQueryList> list = new ArrayList<>(); final MatcherWrapper matcherPocket = new MatcherWrapper(GCConstants.PATTERN_LIST_PQ, subPage); while (matcherPocket.find()) { int maxCaches; try { maxCaches = Integer.parseInt(matcherPocket.group(1)); } catch (final NumberFormatException e) { maxCaches = 0; Log.e("GCParser.searchPocketQueryList: Unable to parse max caches", e); } final String guid = Html.fromHtml(matcherPocket.group(2)).toString(); final String name = Html.fromHtml(matcherPocket.group(3)).toString(); final PocketQueryList pqList = new PocketQueryList(guid, name, maxCaches); list.add(pqList); } // just in case, lets sort the resulting list Collections.sort(list, new Comparator<PocketQueryList>() { @Override public int compare(final PocketQueryList left, final PocketQueryList right) { return String.CASE_INSENSITIVE_ORDER.compare(left.getName(), right.getName()); } }); return list; } public static ImmutablePair<StatusCode, String> postLog(final String geocode, final String cacheid, final String[] viewstates, final LogType logType, final int year, final int month, final int day, final String log, final List<TrackableLog> trackables) { if (GCLogin.isEmpty(viewstates)) { Log.e("GCParser.postLog: No viewstate given"); return new ImmutablePair<>(StatusCode.LOG_POST_ERROR, ""); } if (StringUtils.isBlank(log)) { Log.e("GCParser.postLog: No log text given"); return new ImmutablePair<>(StatusCode.NO_LOG_TEXT, ""); } final String logInfo = log.replace("\n", "\r\n").trim(); // windows' eol and remove leading and trailing whitespaces Log.i("Trying to post log for cache #" + cacheid + " - action: " + logType + "; date: " + year + "." + month + "." + day + ", log: " + logInfo + "; trackables: " + (trackables != null ? trackables.size() : "0")); final Parameters params = new Parameters( "__EVENTTARGET", "", "__EVENTARGUMENT", "", "__LASTFOCUS", "", "ctl00$ContentBody$LogBookPanel1$ddLogType", Integer.toString(logType.id), "ctl00$ContentBody$LogBookPanel1$uxDateVisited", GCLogin.getCustomGcDateFormat().format(new GregorianCalendar(year, month - 1, day).getTime()), "ctl00$ContentBody$LogBookPanel1$uxDateVisited$Month", Integer.toString(month), "ctl00$ContentBody$LogBookPanel1$uxDateVisited$Day", Integer.toString(day), "ctl00$ContentBody$LogBookPanel1$uxDateVisited$Year", Integer.toString(year), "ctl00$ContentBody$LogBookPanel1$DateTimeLogged", String.format("%02d", month) + "/" + String.format("%02d", day) + "/" + String.format("%04d", year), "ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Month", Integer.toString(month), "ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Day", Integer.toString(day), "ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Year", Integer.toString(year), "ctl00$ContentBody$LogBookPanel1$LogButton", "Submit Log Entry", "ctl00$ContentBody$LogBookPanel1$uxLogInfo", logInfo, "ctl00$ContentBody$LogBookPanel1$btnSubmitLog", "Submit Log Entry", "ctl00$ContentBody$LogBookPanel1$uxLogCreationSource", "Old", "ctl00$ContentBody$uxVistOtherListingGC", ""); GCLogin.putViewstates(params, viewstates); if (trackables != null && !trackables.isEmpty()) { // we have some trackables to proceed final StringBuilder hdnSelected = new StringBuilder(); for (final TrackableLog tb : trackables) { if (tb.action != LogTypeTrackable.DO_NOTHING) { hdnSelected.append(Integer.toString(tb.id)); hdnSelected.append(tb.action.action); hdnSelected.append(','); } } params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnSelectedActions", hdnSelected.toString(), // selected trackables "ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnCurrentFilter", ""); } final String uri = new Uri.Builder().scheme("http").authority("www.geocaching.com").path("/seek/log.aspx").encodedQuery("ID=" + cacheid).build().toString(); final GCLogin gcLogin = GCLogin.getInstance(); String page = gcLogin.postRequestLogged(uri, params); if (!gcLogin.getLoginStatus(page)) { Log.e("GCParser.postLog: Cannot log in geocaching"); return new ImmutablePair<>(StatusCode.NOT_LOGGED_IN, ""); } // maintenance, archived needs to be confirmed final MatcherWrapper matcher = new MatcherWrapper(GCConstants.PATTERN_MAINTENANCE, page); try { if (matcher.find() && matcher.groupCount() > 0) { final String[] viewstatesConfirm = GCLogin.getViewstates(page); if (GCLogin.isEmpty(viewstatesConfirm)) { Log.e("GCParser.postLog: No viewstate for confirm log"); return new ImmutablePair<>(StatusCode.LOG_POST_ERROR, ""); } params.clear(); GCLogin.putViewstates(params, viewstatesConfirm); params.put("__EVENTTARGET", ""); params.put("__EVENTARGUMENT", ""); params.put("__LASTFOCUS", ""); params.put("ctl00$ContentBody$LogBookPanel1$btnConfirm", "Yes"); params.put("ctl00$ContentBody$LogBookPanel1$uxLogInfo", logInfo); params.put("ctl00$ContentBody$uxVistOtherListingGC", ""); if (trackables != null && !trackables.isEmpty()) { // we have some trackables to proceed final StringBuilder hdnSelected = new StringBuilder(); for (final TrackableLog tb : trackables) { final String action = Integer.toString(tb.id) + tb.action.action; final StringBuilder paramText = new StringBuilder("ctl00$ContentBody$LogBookPanel1$uxTrackables$repTravelBugs$ctl"); if (tb.ctl < 10) { paramText.append('0'); } paramText.append(tb.ctl).append("$ddlAction"); params.put(paramText.toString(), action); if (tb.action != LogTypeTrackable.DO_NOTHING) { hdnSelected.append(action); hdnSelected.append(','); } } params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnSelectedActions", hdnSelected.toString()); // selected trackables params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnCurrentFilter", ""); } page = Network.getResponseData(Network.postRequest(uri, params)); } } catch (final RuntimeException e) { Log.e("GCParser.postLog.confim", e); } try { final MatcherWrapper matcherOk = new MatcherWrapper(GCConstants.PATTERN_OK1, page); if (matcherOk.find()) { Log.i("Log successfully posted to cache #" + cacheid); if (geocode != null) { DataStore.saveVisitDate(geocode); } gcLogin.getLoginStatus(page); // the log-successful-page contains still the old value if (gcLogin.getActualCachesFound() >= 0) { gcLogin.setActualCachesFound(gcLogin.getActualCachesFound() + 1); } final String logID = TextUtils.getMatch(page, GCConstants.PATTERN_LOG_IMAGE_UPLOAD, ""); return new ImmutablePair<>(StatusCode.NO_ERROR, logID); } } catch (final Exception e) { Log.e("GCParser.postLog.check", e); } Log.e("GCParser.postLog: Failed to post log because of unknown error"); return new ImmutablePair<>(StatusCode.LOG_POST_ERROR, ""); } /** * Upload an image to a log that has already been posted * * @param logId * the ID of the log to upload the image to. Found on page returned when log is uploaded * @param caption * of the image; max 50 chars * @param description * of the image; max 250 chars * @param imageUri * the URI for the image to be uploaded * @return status code to indicate success or failure */ public static ImmutablePair<StatusCode, String> uploadLogImage(final String logId, final String caption, final String description, final Uri imageUri) { final String uri = new Uri.Builder().scheme("http").authority("www.geocaching.com").path("/seek/upload.aspx").encodedQuery("LID=" + logId).build().toString(); final String page = GCLogin.getInstance().getRequestLogged(uri, null); if (StringUtils.isBlank(page)) { Log.e("GCParser.uploadLogImage: No data from server"); return new ImmutablePair<>(StatusCode.UNKNOWN_ERROR, null); } assert page != null; final String[] viewstates = GCLogin.getViewstates(page); final Parameters uploadParams = new Parameters( "__EVENTTARGET", "", "__EVENTARGUMENT", "", "ctl00$ContentBody$ImageUploadControl1$uxFileCaption", caption, "ctl00$ContentBody$ImageUploadControl1$uxFileDesc", description, "ctl00$ContentBody$ImageUploadControl1$uxUpload", "Upload"); GCLogin.putViewstates(uploadParams, viewstates); final File image = new File(imageUri.getPath()); final String response = Network.getResponseData(Network.postRequest(uri, uploadParams, "ctl00$ContentBody$ImageUploadControl1$uxFileUpload", "image/jpeg", image)); final MatcherWrapper matcherUrl = new MatcherWrapper(GCConstants.PATTERN_IMAGE_UPLOAD_URL, response); if (matcherUrl.find()) { Log.i("Logimage successfully uploaded."); final String uploadedImageUrl = matcherUrl.group(1); return ImmutablePair.of(StatusCode.NO_ERROR, uploadedImageUrl); } Log.e("GCParser.uploadLogIMage: Failed to upload image because of unknown error"); return ImmutablePair.of(StatusCode.LOGIMAGE_POST_ERROR, null); } /** * Post a log to GC.com. * * @return status code of the upload and ID of the log */ public static StatusCode postLogTrackable(final String tbid, final String trackingCode, final String[] viewstates, final LogType logType, final int year, final int month, final int day, final String log) { if (GCLogin.isEmpty(viewstates)) { Log.e("GCParser.postLogTrackable: No viewstate given"); return StatusCode.LOG_POST_ERROR; } if (StringUtils.isBlank(log)) { Log.e("GCParser.postLogTrackable: No log text given"); return StatusCode.NO_LOG_TEXT; } Log.i("Trying to post log for trackable #" + trackingCode + " - action: " + logType + "; date: " + year + "." + month + "." + day + ", log: " + log); final String logInfo = log.replace("\n", "\r\n"); // windows' eol final Calendar currentDate = Calendar.getInstance(); final Parameters params = new Parameters( "__EVENTTARGET", "", "__EVENTARGUMENT", "", "__LASTFOCUS", "", "ctl00$ContentBody$LogBookPanel1$ddLogType", Integer.toString(logType.id), "ctl00$ContentBody$LogBookPanel1$tbCode", trackingCode); GCLogin.putViewstates(params, viewstates); if (currentDate.get(Calendar.YEAR) == year && (currentDate.get(Calendar.MONTH) + 1) == month && currentDate.get(Calendar.DATE) == day) { params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged", ""); params.put("ctl00$ContentBody$LogBookPanel1$uxDateVisited", ""); } else { params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged", Integer.toString(month) + "/" + Integer.toString(day) + "/" + Integer.toString(year)); params.put("ctl00$ContentBody$LogBookPanel1$uxDateVisited", GCLogin.getCustomGcDateFormat().format(new GregorianCalendar(year, month - 1, day).getTime())); } params.put( "ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Day", Integer.toString(day), "ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Month", Integer.toString(month), "ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Year", Integer.toString(year), "ctl00$ContentBody$LogBookPanel1$uxDateVisited$Day", Integer.toString(day), "ctl00$ContentBody$LogBookPanel1$uxDateVisited$Month", Integer.toString(month), "ctl00$ContentBody$LogBookPanel1$uxDateVisited$Year", Integer.toString(year), "ctl00$ContentBody$LogBookPanel1$uxLogInfo", logInfo, "ctl00$ContentBody$LogBookPanel1$btnSubmitLog", "Submit Log Entry", "ctl00$ContentBody$uxVistOtherTrackableTB", "", "ctl00$ContentBody$LogBookPanel1$LogButton", "Submit Log Entry", "ctl00$ContentBody$uxVistOtherListingGC", ""); final String uri = new Uri.Builder().scheme("http").authority("www.geocaching.com").path("/track/log.aspx").encodedQuery("wid=" + tbid).build().toString(); final String page = GCLogin.getInstance().postRequestLogged(uri, params); if (!GCLogin.getInstance().getLoginStatus(page)) { Log.e("GCParser.postLogTrackable: Cannot log in geocaching"); return StatusCode.NOT_LOGGED_IN; } try { final MatcherWrapper matcherOk = new MatcherWrapper(GCConstants.PATTERN_OK2, page); if (matcherOk.find()) { Log.i("Log successfully posted to trackable #" + trackingCode); return StatusCode.NO_ERROR; } } catch (final Exception e) { Log.e("GCParser.postLogTrackable.check", e); } Log.e("GCParser.postLogTrackable: Failed to post log because of unknown error"); return StatusCode.LOG_POST_ERROR; } /** * Adds the cache to the watchlist of the user. * * @param cache * the cache to add * @return <code>false</code> if an error occurred, <code>true</code> otherwise */ static boolean addToWatchlist(final Geocache cache) { final String uri = "http://www.geocaching.com/my/watchlist.aspx?w=" + cache.getCacheId(); final String page = GCLogin.getInstance().postRequestLogged(uri, null); if (StringUtils.isBlank(page)) { Log.e("GCParser.addToWatchlist: No data from server"); return false; // error } final boolean guidOnPage = isGuidContainedInPage(cache, page); if (guidOnPage) { Log.i("GCParser.addToWatchlist: cache is on watchlist"); cache.setOnWatchlist(true); } else { Log.e("GCParser.addToWatchlist: cache is not on watchlist"); } return guidOnPage; // on watchlist (=added) / else: error } /** * Removes the cache from the watch list * * @param cache * the cache to remove * @return <code>false</code> if an error occurred, <code>true</code> otherwise */ static boolean removeFromWatchlist(final Geocache cache) { final String uri = "http://www.geocaching.com/my/watchlist.aspx?ds=1&action=rem&id=" + cache.getCacheId(); String page = GCLogin.getInstance().postRequestLogged(uri, null); if (StringUtils.isBlank(page)) { Log.e("GCParser.removeFromWatchlist: No data from server"); return false; // error } // removing cache from list needs approval by hitting "Yes" button final Parameters params = new Parameters( "__EVENTTARGET", "", "__EVENTARGUMENT", "", "ctl00$ContentBody$btnYes", "Yes"); GCLogin.transferViewstates(page, params); page = Network.getResponseData(Network.postRequest(uri, params)); final boolean guidOnPage = isGuidContainedInPage(cache, page); if (!guidOnPage) { Log.i("GCParser.removeFromWatchlist: cache removed from watchlist"); cache.setOnWatchlist(false); } else { Log.e("GCParser.removeFromWatchlist: cache not removed from watchlist"); } return !guidOnPage; // on watch list (=error) / not on watch list } /** * Checks if a page contains the guid of a cache * * @param cache the geocache * @param page * the page to search in, may be null * @return true if the page contains the guid of the cache, false otherwise */ private static boolean isGuidContainedInPage(final Geocache cache, final String page) { if (StringUtils.isBlank(page) || StringUtils.isBlank(cache.getGuid())) { return false; } return Pattern.compile(cache.getGuid(), Pattern.CASE_INSENSITIVE).matcher(page).find(); } @Nullable static String requestHtmlPage(@Nullable final String geocode, @Nullable final String guid, final String log, final String numlogs) { final Parameters params = new Parameters("decrypt", "y"); if (StringUtils.isNotBlank(geocode)) { params.put("wp", geocode); } else if (StringUtils.isNotBlank(guid)) { params.put("guid", guid); } params.put("log", log); params.put("numlogs", numlogs); return GCLogin.getInstance().getRequestLogged("http://www.geocaching.com/seek/cache_details.aspx", params); } /** * Adds the cache to the favorites of the user. * * This must not be called from the UI thread. * * @param cache * the cache to add * @return <code>false</code> if an error occurred, <code>true</code> otherwise */ static boolean addToFavorites(final Geocache cache) { return changeFavorite(cache, true); } private static boolean changeFavorite(final Geocache cache, final boolean add) { final String userToken = getUserToken(cache); if (StringUtils.isEmpty(userToken)) { return false; } final String uri = "http://www.geocaching.com/datastore/favorites.svc/update?u=" + userToken + "&f=" + Boolean.toString(add); final HttpResponse response = Network.postRequest(uri, null); if (response != null && response.getStatusLine().getStatusCode() == 200) { Log.i("GCParser.changeFavorite: cache added/removed to/from favorites"); cache.setFavorite(add); cache.setFavoritePoints(cache.getFavoritePoints() + (add ? 1 : -1)); return true; } Log.e("GCParser.changeFavorite: cache not added/removed to/from favorites"); return false; } private static String getUserToken(final Geocache cache) { final String page = requestHtmlPage(cache.getGeocode(), null, "n", "0"); return TextUtils.getMatch(page, GCConstants.PATTERN_USERTOKEN, ""); } /** * Removes the cache from the favorites. * * This must not be called from the UI thread. * * @param cache * the cache to remove * @return <code>false</code> if an error occurred, <code>true</code> otherwise */ static boolean removeFromFavorites(final Geocache cache) { return changeFavorite(cache, false); } /** * Parse a trackable HTML description into a Trackable object * * @param page * the HTML page to parse, already processed through {@link TextUtils#replaceWhitespace} * @return the parsed trackable, or null if none could be parsed */ static Trackable parseTrackable(final String page, final String possibleTrackingcode) { if (StringUtils.isBlank(page)) { Log.e("GCParser.parseTrackable: No page given"); return null; } if (page.contains(GCConstants.ERROR_TB_DOES_NOT_EXIST) || page.contains(GCConstants.ERROR_TB_ARITHMETIC_OVERFLOW) || page.contains(GCConstants.ERROR_TB_ELEMENT_EXCEPTION)) { return null; } final Trackable trackable = new Trackable(); // trackable geocode trackable.setGeocode(TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_GEOCODE, true, StringUtils.upperCase(possibleTrackingcode))); if (trackable.getGeocode() == null) { Log.e("GCParser.parseTrackable: could not figure out trackable geocode"); return null; } // trackable id trackable.setGuid(TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_GUID, true, trackable.getGuid())); // trackable icon trackable.setIconUrl(TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_ICON, true, trackable.getIconUrl())); // trackable name trackable.setName(Html.fromHtml(TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_NAME, true, "")).toString()); // trackable type if (StringUtils.isNotBlank(trackable.getName())) { trackable.setType(TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_TYPE, true, trackable.getType())); } // trackable owner name try { final MatcherWrapper matcherOwner = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE_OWNER, page); if (matcherOwner.find() && matcherOwner.groupCount() > 0) { trackable.setOwnerGuid(matcherOwner.group(1)); trackable.setOwner(matcherOwner.group(2).trim()); } } catch (final RuntimeException e) { // failed to parse trackable owner name Log.w("GCParser.parseTrackable: Failed to parse trackable owner name", e); } // trackable origin trackable.setOrigin(TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_ORIGIN, true, trackable.getOrigin())); // trackable spotted try { final MatcherWrapper matcherSpottedCache = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE_SPOTTEDCACHE, page); if (matcherSpottedCache.find() && matcherSpottedCache.groupCount() > 0) { trackable.setSpottedGuid(matcherSpottedCache.group(1)); trackable.setSpottedName(matcherSpottedCache.group(2).trim()); trackable.setSpottedType(Trackable.SPOTTED_CACHE); } final MatcherWrapper matcherSpottedUser = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE_SPOTTEDUSER, page); if (matcherSpottedUser.find() && matcherSpottedUser.groupCount() > 0) { trackable.setSpottedGuid(matcherSpottedUser.group(1)); trackable.setSpottedName(matcherSpottedUser.group(2).trim()); trackable.setSpottedType(Trackable.SPOTTED_USER); } if (TextUtils.matches(page, GCConstants.PATTERN_TRACKABLE_SPOTTEDUNKNOWN)) { trackable.setSpottedType(Trackable.SPOTTED_UNKNOWN); } if (TextUtils.matches(page, GCConstants.PATTERN_TRACKABLE_SPOTTEDOWNER)) { trackable.setSpottedType(Trackable.SPOTTED_OWNER); } } catch (final RuntimeException e) { // failed to parse trackable last known place Log.w("GCParser.parseTrackable: Failed to parse trackable last known place", e); } // released date - can be missing on the page final String releaseString = TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_RELEASES, false, null); if (releaseString != null) { try { trackable.setReleased(dateTbIn1.parse(releaseString)); } catch (final ParseException ignore) { if (trackable.getReleased() == null) { try { trackable.setReleased(dateTbIn2.parse(releaseString)); } catch (final ParseException e) { Log.e("Could not parse trackable release " + releaseString, e); } } } } // trackable distance final String distance = TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_DISTANCE, false, null); if (null != distance) { try { trackable.setDistance(DistanceParser.parseDistance(distance, !Settings.isUseImperialUnits())); } catch (final NumberFormatException e) { Log.e("GCParser.parseTrackable: Failed to parse distance", e); } } // trackable goal trackable.setGoal(convertLinks(TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_GOAL, true, trackable.getGoal()))); // trackable details & image try { final MatcherWrapper matcherDetailsImage = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE_DETAILSIMAGE, page); if (matcherDetailsImage.find() && matcherDetailsImage.groupCount() > 0) { final String image = StringUtils.trim(matcherDetailsImage.group(3)); final String details = StringUtils.trim(matcherDetailsImage.group(4)); if (StringUtils.isNotEmpty(image)) { trackable.setImage(image); } if (StringUtils.isNotEmpty(details) && !StringUtils.equals(details, "No additional details available.")) { trackable.setDetails(convertLinks(details)); } } } catch (final RuntimeException e) { // failed to parse trackable details & image Log.w("GCParser.parseTrackable: Failed to parse trackable details & image", e); } if (StringUtils.isEmpty(trackable.getDetails()) && page.contains(GCConstants.ERROR_TB_NOT_ACTIVATED)) { trackable.setDetails(CgeoApplication.getInstance().getString(R.string.trackable_not_activated)); } // trackable logs try { final MatcherWrapper matcherLogs = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE_LOG, page); /* * 1. Type (image) * 2. Date * 3. Author * 4. Cache-GUID * 5. <ignored> (strike-through property for ancient caches) * 6. Cache-name * 7. Log text */ while (matcherLogs.find()) { long date = 0; try { date = GCLogin.parseGcCustomDate(matcherLogs.group(2)).getTime(); } catch (final ParseException ignore) { } final LogEntry logDone = new LogEntry( Html.fromHtml(matcherLogs.group(3)).toString().trim(), date, LogType.getByIconName(matcherLogs.group(1)), matcherLogs.group(7).trim()); if (matcherLogs.group(4) != null && matcherLogs.group(6) != null) { logDone.cacheGuid = matcherLogs.group(4); logDone.cacheName = matcherLogs.group(6); } // Apply the pattern for images in a trackable log entry against each full log (group(0)) final String logEntry = matcherLogs.group(0); final MatcherWrapper matcherLogImages = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE_LOG_IMAGES, logEntry); /* * 1. Image URL * 2. Image title */ while (matcherLogImages.find()) { final Image logImage = new Image(matcherLogImages.group(1), matcherLogImages.group(2)); logDone.addLogImage(logImage); } trackable.getLogs().add(logDone); } } catch (final Exception e) { // failed to parse logs Log.w("GCParser.parseCache: Failed to parse cache logs", e); } // tracking code if (!StringUtils.equalsIgnoreCase(trackable.getGeocode(), possibleTrackingcode)) { trackable.setTrackingcode(possibleTrackingcode); } if (CgeoApplication.getInstance() != null) { DataStore.saveTrackable(trackable); } return trackable; } private static String convertLinks(final String input) { if (input == null) { return null; } return StringUtils.replace(input, "../", GCConstants.GC_URL); } /** * Extract logs from a cache details page. * * @param page * the text of the details page * @return a list of log entries which will be empty if the logs could not be retrieved * */ @NonNull private static Observable<LogEntry> getLogsFromDetails(final String page) { // extract embedded JSON data from page return parseLogs(false, TextUtils.getMatch(page, GCConstants.PATTERN_LOGBOOK, "")); } private enum SpecialLogs { FRIENDS("sf"), OWN("sp"); final String paramName; SpecialLogs(final String paramName) { this.paramName = paramName; } private String getParamName() { return this.paramName; } } /** * Extract special logs (friends, own) through seperate request. * * @param page * The page to extrat userToken from * @param logType * The logType to request * @return Observable<LogEntry> The logs */ private static Observable<LogEntry> getSpecialLogs(final String page, final SpecialLogs logType) { return Observable.defer(new Func0<Observable<? extends LogEntry>>() { @Override public Observable<? extends LogEntry> call() { final MatcherWrapper userTokenMatcher = new MatcherWrapper(GCConstants.PATTERN_USERTOKEN, page); if (!userTokenMatcher.find()) { Log.e("GCParser.loadLogsFromDetails: unable to extract userToken"); return Observable.empty(); } final String userToken = userTokenMatcher.group(1); final Parameters params = new Parameters( "tkn", userToken, "idx", "1", "num", String.valueOf(GCConstants.NUMBER_OF_LOGS), logType.getParamName(), Boolean.toString(Boolean.TRUE), "decrypt", "true"); final HttpResponse response = Network.getRequest("http://www.geocaching.com/seek/geocache.logbook", params); if (response == null) { Log.e("GCParser.loadLogsFromDetails: cannot log logs, response is null"); return Observable.empty(); } final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { Log.e("GCParser.loadLogsFromDetails: error " + statusCode + " when requesting log information"); return Observable.empty(); } final String rawResponse = Network.getResponseData(response); if (rawResponse == null) { Log.e("GCParser.loadLogsFromDetails: unable to read whole response"); return Observable.empty(); } return parseLogs(true, rawResponse); } }).subscribeOn(RxUtils.networkScheduler); } private static Observable<LogEntry> parseLogs(final boolean markAsFriendsLog, final String rawResponse) { return Observable.create(new OnSubscribe<LogEntry>() { @Override public void call(final Subscriber<? super LogEntry> subscriber) { // for non logged in users the log book is not shown if (StringUtils.isBlank(rawResponse)) { subscriber.onCompleted(); return; } try { final ObjectNode resp = (ObjectNode) JsonUtils.reader.readTree(rawResponse); if (!resp.path("status").asText().equals("success")) { Log.e("GCParser.loadLogsFromDetails: status is " + resp.path("status").asText("[absent]")); subscriber.onCompleted(); return; } final ArrayNode data = (ArrayNode) resp.get("data"); for (final JsonNode entry: data) { // FIXME: use the "LogType" field instead of the "LogTypeImage" one. final String logIconNameExt = entry.path("LogTypeImage").asText(".gif"); final String logIconName = logIconNameExt.substring(0, logIconNameExt.length() - 4); long date = 0; try { date = GCLogin.parseGcCustomDate(entry.get("Visited").asText()).getTime(); } catch (ParseException | NullPointerException e) { Log.e("GCParser.loadLogsFromDetails: failed to parse log date", e); } // TODO: we should update our log data structure to be able to record // proper coordinates, and make them clickable. In the meantime, it is // better to integrate those coordinates into the text rather than not // display them at all. final String latLon = entry.path("LatLonString").asText(); final String logText = (StringUtils.isEmpty(latLon) ? "" : (latLon + "<br/><br/>")) + TextUtils.removeControlCharacters(entry.path("LogText").asText()); final LogEntry logDone = new LogEntry( TextUtils.removeControlCharacters(entry.path("UserName").asText()), date, LogType.getByIconName(logIconName), logText); logDone.found = entry.path("GeocacheFindCount").asInt(); logDone.friend = markAsFriendsLog; final ArrayNode images = (ArrayNode) entry.get("Images"); for (final JsonNode image: images) { final String url = "http://imgcdn.geocaching.com/cache/log/large/" + image.path("FileName").asText(); final String title = TextUtils.removeControlCharacters(image.path("Name").asText()); final Image logImage = new Image(url, title); logDone.addLogImage(logImage); } subscriber.onNext(logDone); } } catch (final IOException e) { Log.w("GCParser.loadLogsFromDetails: Failed to parse cache logs", e); } subscriber.onCompleted(); } }); } @NonNull public static List<LogType> parseTypes(final String page) { if (StringUtils.isEmpty(page)) { return Collections.emptyList(); } final List<LogType> types = new ArrayList<>(); final MatcherWrapper typeBoxMatcher = new MatcherWrapper(GCConstants.PATTERN_TYPEBOX, page); if (typeBoxMatcher.find() && typeBoxMatcher.groupCount() > 0) { final String typesText = typeBoxMatcher.group(1); final MatcherWrapper typeMatcher = new MatcherWrapper(GCConstants.PATTERN_TYPE2, typesText); while (typeMatcher.find()) { if (typeMatcher.groupCount() > 1) { try { final int type = Integer.parseInt(typeMatcher.group(2)); if (type > 0) { types.add(LogType.getById(type)); } } catch (final NumberFormatException e) { Log.e("Error parsing log types", e); } } } } // we don't support this log type types.remove(LogType.UPDATE_COORDINATES); return types; } public static List<TrackableLog> parseTrackableLog(final String page) { if (StringUtils.isEmpty(page)) { return null; } String table = StringUtils.substringBetween(page, "<table id=\"tblTravelBugs\"", "</table>"); // if no trackables are currently in the account, the table is not available, so return an empty list instead of null if (StringUtils.isBlank(table)) { return Collections.emptyList(); } table = StringUtils.substringBetween(table, "<tbody>", "</tbody>"); if (StringUtils.isBlank(table)) { Log.e("GCParser.parseTrackableLog: tbody not found on page"); return null; } final List<TrackableLog> trackableLogs = new ArrayList<>(); final MatcherWrapper trackableMatcher = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE, page); while (trackableMatcher.find()) { if (trackableMatcher.groupCount() > 0) { final String trackCode = trackableMatcher.group(1); final String name = Html.fromHtml(trackableMatcher.group(2)).toString(); try { final Integer ctl = Integer.valueOf(trackableMatcher.group(3)); final Integer id = Integer.valueOf(trackableMatcher.group(5)); if (trackCode != null && ctl != null && id != null) { final TrackableLog entry = new TrackableLog(trackCode, name, id, ctl); Log.i("Trackable in inventory (#" + entry.ctl + "/" + entry.id + "): " + entry.trackCode + " - " + entry.name); trackableLogs.add(entry); } } catch (final NumberFormatException e) { Log.e("GCParser.parseTrackableLog", e); } } } return trackableLogs; } /** * Insert the right cache type restriction in parameters * * @param params * the parameters to insert the restriction into * @param cacheType * the type of cache, or null to include everything */ static private void insertCacheType(final Parameters params, final CacheType cacheType) { params.put("tx", cacheType.guid); } private static void getExtraOnlineInfo(final Geocache cache, final String page, final CancellableHandler handler) { // This method starts the page parsing for logs in the background, as well as retrieve the friends and own logs // if requested. It merges them and stores them in the background, while the rating is retrieved if needed and // stored. Then we wait for the log merging and saving to be completed before returning. if (CancellableHandler.isCancelled(handler)) { return; } final Observable<LogEntry> logs = getLogsFromDetails(page).subscribeOn(RxUtils.computationScheduler); Observable<LogEntry> specialLogs; if (Settings.isFriendLogsWanted()) { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_logs); specialLogs = Observable.merge(getSpecialLogs(page, SpecialLogs.FRIENDS), getSpecialLogs(page, SpecialLogs.OWN)); } else { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_logs); specialLogs = Observable.empty(); } final Observable<List<LogEntry>> mergedLogs = Observable.zip(logs.toList(), specialLogs.toList(), new Func2<List<LogEntry>, List<LogEntry>, List<LogEntry>>() { @Override public List<LogEntry> call(final List<LogEntry> logEntries, final List<LogEntry> specialLogEntries) { mergeFriendsLogs(logEntries, specialLogEntries); return logEntries; } }).cache(); mergedLogs.subscribe(new Action1<List<LogEntry>>() { @Override public void call(final List<LogEntry> logEntries) { DataStore.saveLogsWithoutTransaction(cache.getGeocode(), logEntries); } }); if (Settings.isRatingWanted() && !CancellableHandler.isCancelled(handler)) { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_gcvote); final GCVoteRating rating = GCVote.getRating(cache.getGuid(), cache.getGeocode()); if (rating != null) { cache.setRating(rating.getRating()); cache.setVotes(rating.getVotes()); cache.setMyVote(rating.getMyVote()); } } // Wait for completion of logs parsing, retrieving and merging mergedLogs.toBlocking().last(); } /** * Merge log entries and mark them as friends logs (personal and friends) to identify * them on friends/personal logs tab. * * @param mergedLogs * the list to merge logs with * @param logsToMerge * the list of logs to merge */ private static void mergeFriendsLogs(final List<LogEntry> mergedLogs, final Iterable<LogEntry> logsToMerge) { for (final LogEntry log : logsToMerge) { if (mergedLogs.contains(log)) { mergedLogs.get(mergedLogs.indexOf(log)).friend = true; } else { mergedLogs.add(log); } } } public static boolean uploadModifiedCoordinates(final Geocache cache, final Geopoint wpt) { return editModifiedCoordinates(cache, wpt); } public static boolean deleteModifiedCoordinates(final Geocache cache) { return editModifiedCoordinates(cache, null); } public static boolean editModifiedCoordinates(final Geocache cache, final Geopoint wpt) { final String userToken = getUserToken(cache); if (StringUtils.isEmpty(userToken)) { return false; } final ObjectNode jo = new ObjectNode(JsonUtils.factory); final ObjectNode dto = jo.putObject("dto").put("ut", userToken); if (wpt != null) { dto.putObject("data").put("lat", wpt.getLatitudeE6() / 1E6).put("lng", wpt.getLongitudeE6() / 1E6); } final String uriSuffix = wpt != null ? "SetUserCoordinate" : "ResetUserCoordinate"; final String uriPrefix = "http://www.geocaching.com/seek/cache_details.aspx/"; final HttpResponse response = Network.postJsonRequest(uriPrefix + uriSuffix, jo); Log.i("Sending to " + uriPrefix + uriSuffix + " :" + jo.toString()); if (response != null && response.getStatusLine().getStatusCode() == 200) { Log.i("GCParser.editModifiedCoordinates - edited on GC.com"); return true; } Log.e("GCParser.deleteModifiedCoordinates - cannot delete modified coords"); return false; } public static boolean uploadPersonalNote(final Geocache cache) { final String userToken = getUserToken(cache); if (StringUtils.isEmpty(userToken)) { return false; } final ObjectNode jo = new ObjectNode(JsonUtils.factory); jo.putObject("dto").put("et", StringUtils.defaultString(cache.getPersonalNote())).put("ut", userToken); final String uriSuffix = "SetUserCacheNote"; final String uriPrefix = "http://www.geocaching.com/seek/cache_details.aspx/"; final HttpResponse response = Network.postJsonRequest(uriPrefix + uriSuffix, jo); Log.i("Sending to " + uriPrefix + uriSuffix + " :" + jo.toString()); if (response != null && response.getStatusLine().getStatusCode() == 200) { Log.i("GCParser.uploadPersonalNote - uploaded to GC.com"); return true; } Log.e("GCParser.uploadPersonalNote - cannot upload personal note"); return false; } }
main/src/cgeo/geocaching/connector/gc/GCParser.java
package cgeo.geocaching.connector.gc; import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.DataStore; import cgeo.geocaching.Geocache; import cgeo.geocaching.Image; import cgeo.geocaching.LogEntry; import cgeo.geocaching.PocketQueryList; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; import cgeo.geocaching.Trackable; import cgeo.geocaching.TrackableLog; import cgeo.geocaching.Waypoint; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.enumerations.LogTypeTrackable; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.files.LocParser; import cgeo.geocaching.gcvote.GCVote; import cgeo.geocaching.gcvote.GCVoteRating; import cgeo.geocaching.geopoint.DistanceParser; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.loaders.RecaptchaReceiver; import cgeo.geocaching.network.Network; import cgeo.geocaching.network.Parameters; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.ui.DirectionImage; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.JsonUtils; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.MatcherWrapper; import cgeo.geocaching.utils.RxUtils; import cgeo.geocaching.utils.SynchronizedDateFormat; import cgeo.geocaching.utils.TextUtils; import ch.boye.httpclientandroidlib.HttpResponse; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.functions.Action1; import rx.functions.Func0; import rx.functions.Func2; import android.net.Uri; import android.text.Html; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.EnumSet; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.regex.Pattern; public abstract class GCParser { private final static SynchronizedDateFormat dateTbIn1 = new SynchronizedDateFormat("EEEEE, dd MMMMM yyyy", Locale.ENGLISH); // Saturday, 28 March 2009 private final static SynchronizedDateFormat dateTbIn2 = new SynchronizedDateFormat("EEEEE, MMMMM dd, yyyy", Locale.ENGLISH); // Saturday, March 28, 2009 private static SearchResult parseSearch(final String url, final String pageContent, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { if (StringUtils.isBlank(pageContent)) { Log.e("GCParser.parseSearch: No page given"); return null; } final List<String> cids = new ArrayList<>(); String page = pageContent; final SearchResult searchResult = new SearchResult(); searchResult.setUrl(url); searchResult.viewstates = GCLogin.getViewstates(page); // recaptcha if (showCaptcha) { final String recaptchaJsParam = TextUtils.getMatch(page, GCConstants.PATTERN_SEARCH_RECAPTCHA, false, null); if (recaptchaJsParam != null) { recaptchaReceiver.setKey(recaptchaJsParam.trim()); recaptchaReceiver.fetchChallenge(); } if (recaptchaReceiver != null && StringUtils.isNotBlank(recaptchaReceiver.getChallenge())) { recaptchaReceiver.notifyNeed(); } } if (!page.contains("SearchResultsTable")) { // there are no results. aborting here avoids a wrong error log in the next parsing step return searchResult; } int startPos = page.indexOf("<div id=\"ctl00_ContentBody_ResultsPanel\""); if (startPos == -1) { Log.e("GCParser.parseSearch: ID \"ctl00_ContentBody_dlResults\" not found on page"); return null; } page = page.substring(startPos); // cut on <table startPos = page.indexOf('>'); final int endPos = page.indexOf("ctl00_ContentBody_UnitTxt"); if (startPos == -1 || endPos == -1) { Log.e("GCParser.parseSearch: ID \"ctl00_ContentBody_UnitTxt\" not found on page"); return null; } page = page.substring(startPos + 1, endPos - startPos + 1); // cut between <table> and </table> final String[] rows = StringUtils.splitByWholeSeparator(page, "<tr class="); final int rowsCount = rows.length; int excludedCaches = 0; final ArrayList<Geocache> caches = new ArrayList<>(); for (int z = 1; z < rowsCount; z++) { final Geocache cache = new Geocache(); final String row = rows[z]; // check for cache type presence if (!row.contains("images/wpttypes")) { continue; } try { final MatcherWrapper matcherGuidAndDisabled = new MatcherWrapper(GCConstants.PATTERN_SEARCH_GUIDANDDISABLED, row); while (matcherGuidAndDisabled.find()) { if (matcherGuidAndDisabled.groupCount() > 0) { if (matcherGuidAndDisabled.group(2) != null) { cache.setName(Html.fromHtml(matcherGuidAndDisabled.group(2).trim()).toString()); } if (matcherGuidAndDisabled.group(3) != null) { cache.setLocation(Html.fromHtml(matcherGuidAndDisabled.group(3).trim()).toString()); } final String attr = matcherGuidAndDisabled.group(1); if (attr != null) { cache.setDisabled(attr.contains("Strike")); cache.setArchived(attr.contains("OldWarning")); } } } } catch (final RuntimeException e) { // failed to parse GUID and/or Disabled Log.w("GCParser.parseSearch: Failed to parse GUID and/or Disabled data", e); } if (Settings.isExcludeDisabledCaches() && (cache.isDisabled() || cache.isArchived())) { // skip disabled and archived caches excludedCaches++; continue; } cache.setGeocode(TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_GEOCODE, true, 1, cache.getGeocode(), true)); // cache type cache.setType(CacheType.getByPattern(TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_TYPE, null))); // cache direction - image if (Settings.getLoadDirImg()) { final String direction = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_DIRECTION_DISTANCE, false, 1, null, false); if (direction != null) { cache.setDirectionImg(direction); } } // cache distance - estimated distance for basic members final String distance = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_DIRECTION_DISTANCE, false, 2, null, false); if (distance != null) { cache.setDistance(DistanceParser.parseDistance(distance, !Settings.isUseImperialUnits())); } // difficulty/terrain final MatcherWrapper matcherDT = new MatcherWrapper(GCConstants.PATTERN_SEARCH_DIFFICULTY_TERRAIN, row); if (matcherDT.find()) { final Float difficulty = parseStars(matcherDT.group(1)); if (difficulty != null) { cache.setDifficulty(difficulty); } final Float terrain = parseStars(matcherDT.group(3)); if (terrain != null) { cache.setTerrain(terrain); } } // size final String container = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_CONTAINER, false, 1, null, false); cache.setSize(CacheSize.getById(container)); // date hidden, makes sorting event caches easier final String dateHidden = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_HIDDEN_DATE, false, 1, null, false); if (StringUtils.isNotBlank(dateHidden)) { try { final Date date = GCLogin.parseGcCustomDate(dateHidden); if (date != null) { cache.setHidden(date); } } catch (final ParseException e) { Log.e("Error parsing event date from search", e); } } // cache inventory final MatcherWrapper matcherTbs = new MatcherWrapper(GCConstants.PATTERN_SEARCH_TRACKABLES, row); String inventoryPre = null; while (matcherTbs.find()) { if (matcherTbs.groupCount() > 0) { try { cache.setInventoryItems(Integer.parseInt(matcherTbs.group(1))); } catch (final NumberFormatException e) { Log.e("Error parsing trackables count", e); } inventoryPre = matcherTbs.group(2); } } if (StringUtils.isNotBlank(inventoryPre)) { final MatcherWrapper matcherTbsInside = new MatcherWrapper(GCConstants.PATTERN_SEARCH_TRACKABLESINSIDE, inventoryPre); while (matcherTbsInside.find()) { if (matcherTbsInside.groupCount() == 2 && matcherTbsInside.group(2) != null && !matcherTbsInside.group(2).equalsIgnoreCase("premium member only cache") && cache.getInventoryItems() <= 0) { cache.setInventoryItems(1); } } } // premium cache cache.setPremiumMembersOnly(row.contains("/images/icons/16/premium_only.png")); // found it cache.setFound(row.contains("/images/icons/16/found.png") || row.contains("uxUserLogDate\" class=\"Success\"")); // id String result = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_ID, null); if (null != result) { cache.setCacheId(result); cids.add(cache.getCacheId()); } // favorite count try { result = getNumberString(TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_FAVORITE, false, 1, null, true)); if (null != result) { cache.setFavoritePoints(Integer.parseInt(result)); } } catch (final NumberFormatException e) { Log.w("GCParser.parseSearch: Failed to parse favorite count", e); } caches.add(cache); } searchResult.addAndPutInCache(caches); // total caches found try { final String result = TextUtils.getMatch(page, GCConstants.PATTERN_SEARCH_TOTALCOUNT, false, 1, null, true); if (null != result) { searchResult.setTotalCountGC(Integer.parseInt(result) - excludedCaches); } } catch (final NumberFormatException e) { Log.w("GCParser.parseSearch: Failed to parse cache count", e); } String recaptchaText = null; if (recaptchaReceiver != null && StringUtils.isNotBlank(recaptchaReceiver.getChallenge())) { recaptchaReceiver.waitForUser(); recaptchaText = recaptchaReceiver.getText(); } if (!cids.isEmpty() && (Settings.isGCPremiumMember() || showCaptcha) && ((recaptchaReceiver == null || StringUtils.isBlank(recaptchaReceiver.getChallenge())) || StringUtils.isNotBlank(recaptchaText))) { Log.i("Trying to get .loc for " + cids.size() + " caches"); try { // get coordinates for parsed caches final Parameters params = new Parameters( "__EVENTTARGET", "", "__EVENTARGUMENT", ""); GCLogin.putViewstates(params, searchResult.viewstates); for (final String cid : cids) { params.put("CID", cid); } if (StringUtils.isNotBlank(recaptchaText) && recaptchaReceiver != null) { params.put("recaptcha_challenge_field", recaptchaReceiver.getChallenge()); params.put("recaptcha_response_field", recaptchaText); } params.put("ctl00$ContentBody$uxDownloadLoc", "Download Waypoints"); final String coordinates = Network.getResponseData(Network.postRequest("http://www.geocaching.com/seek/nearest.aspx", params), false); if (StringUtils.contains(coordinates, "You have not agreed to the license agreement. The license agreement is required before you can start downloading GPX or LOC files from Geocaching.com")) { Log.i("User has not agreed to the license agreement. Can\'t download .loc file."); searchResult.setError(StatusCode.UNAPPROVED_LICENSE); return searchResult; } LocParser.parseLoc(searchResult, coordinates); } catch (final RuntimeException e) { Log.e("GCParser.parseSearch.CIDs", e); } } // get direction images if (Settings.getLoadDirImg()) { final Set<Geocache> cachesReloaded = searchResult.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB); for (final Geocache cache : cachesReloaded) { if (cache.getCoords() == null && StringUtils.isNotEmpty(cache.getDirectionImg())) { DirectionImage.getDrawable(cache.getDirectionImg()); } } } return searchResult; } private static Float parseStars(final String value) { final float floatValue = Float.parseFloat(StringUtils.replaceChars(value, ',', '.')); return floatValue >= 0.5 && floatValue <= 5.0 ? floatValue : null; } static SearchResult parseCache(final String page, final CancellableHandler handler) { final ImmutablePair<StatusCode, Geocache> parsed = parseCacheFromText(page, handler); // attention: parseCacheFromText already stores implicitly through searchResult.addCache if (parsed.left != StatusCode.NO_ERROR) { return new SearchResult(parsed.left); } final Geocache cache = parsed.right; getExtraOnlineInfo(cache, page, handler); // too late: it is already stored through parseCacheFromText cache.setDetailedUpdatedNow(); if (CancellableHandler.isCancelled(handler)) { return null; } // save full detailed caches CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_cache); DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB)); // update progress message so user knows we're still working. This is more of a place holder than // actual indication of what the program is doing CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_render); return new SearchResult(cache); } static SearchResult parseAndSaveCacheFromText(final String page, @Nullable final CancellableHandler handler) { final ImmutablePair<StatusCode, Geocache> parsed = parseCacheFromText(page, handler); final SearchResult result = new SearchResult(parsed.left); if (parsed.left == StatusCode.NO_ERROR) { result.addAndPutInCache(Collections.singletonList(parsed.right)); DataStore.saveLogsWithoutTransaction(parsed.right.getGeocode(), getLogsFromDetails(page).toBlocking().toIterable()); } return result; } /** * Parse cache from text and return either an error code or a cache object in a pair. Note that inline logs are * not parsed nor saved, while the cache itself is. * * @param pageIn * the page text to parse * @param handler * the handler to send the progress notifications to * @return a pair, with a {@link StatusCode} on the left, and a non-null cache object on the right * iff the status code is {@link StatusCode.NO_ERROR}. */ static private ImmutablePair<StatusCode, Geocache> parseCacheFromText(final String pageIn, @Nullable final CancellableHandler handler) { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_details); if (StringUtils.isBlank(pageIn)) { Log.e("GCParser.parseCache: No page given"); return null; } if (pageIn.contains(GCConstants.STRING_UNPUBLISHED_OTHER) || pageIn.contains(GCConstants.STRING_UNPUBLISHED_FROM_SEARCH)) { return ImmutablePair.of(StatusCode.UNPUBLISHED_CACHE, null); } if (pageIn.contains(GCConstants.STRING_PREMIUMONLY_1) || pageIn.contains(GCConstants.STRING_PREMIUMONLY_2)) { return ImmutablePair.of(StatusCode.PREMIUM_ONLY, null); } final String cacheName = Html.fromHtml(TextUtils.getMatch(pageIn, GCConstants.PATTERN_NAME, true, "")).toString(); if (GCConstants.STRING_UNKNOWN_ERROR.equalsIgnoreCase(cacheName)) { return ImmutablePair.of(StatusCode.UNKNOWN_ERROR, null); } // first handle the content with line breaks, then trim everything for easier matching and reduced memory consumption in parsed fields String personalNoteWithLineBreaks = ""; final MatcherWrapper matcher = new MatcherWrapper(GCConstants.PATTERN_PERSONALNOTE, pageIn); if (matcher.find()) { personalNoteWithLineBreaks = matcher.group(1).trim(); } final String page = TextUtils.replaceWhitespace(pageIn); final Geocache cache = new Geocache(); cache.setDisabled(page.contains(GCConstants.STRING_DISABLED)); cache.setArchived(page.contains(GCConstants.STRING_ARCHIVED)); cache.setPremiumMembersOnly(TextUtils.matches(page, GCConstants.PATTERN_PREMIUMMEMBERS)); cache.setFavorite(TextUtils.matches(page, GCConstants.PATTERN_FAVORITE)); // cache geocode cache.setGeocode(TextUtils.getMatch(page, GCConstants.PATTERN_GEOCODE, true, cache.getGeocode())); // cache id cache.setCacheId(TextUtils.getMatch(page, GCConstants.PATTERN_CACHEID, true, cache.getCacheId())); // cache guid cache.setGuid(TextUtils.getMatch(page, GCConstants.PATTERN_GUID, true, cache.getGuid())); // name cache.setName(cacheName); // owner real name cache.setOwnerUserId(Network.decode(TextUtils.getMatch(page, GCConstants.PATTERN_OWNER_USERID, true, cache.getOwnerUserId()))); cache.setUserModifiedCoords(false); String tableInside = page; final int pos = tableInside.indexOf(GCConstants.STRING_CACHEDETAILS); if (pos == -1) { Log.e("GCParser.parseCache: ID \"cacheDetails\" not found on page"); return null; } tableInside = tableInside.substring(pos); if (StringUtils.isNotBlank(tableInside)) { // cache terrain String result = TextUtils.getMatch(tableInside, GCConstants.PATTERN_TERRAIN, true, null); if (result != null) { try { cache.setTerrain(Float.parseFloat(StringUtils.replaceChars(result, '_', '.'))); } catch (final NumberFormatException e) { Log.e("Error parsing terrain value", e); } } // cache difficulty result = TextUtils.getMatch(tableInside, GCConstants.PATTERN_DIFFICULTY, true, null); if (result != null) { try { cache.setDifficulty(Float.parseFloat(StringUtils.replaceChars(result, '_', '.'))); } catch (final NumberFormatException e) { Log.e("Error parsing difficulty value", e); } } // owner cache.setOwnerDisplayName(StringEscapeUtils.unescapeHtml4(TextUtils.getMatch(tableInside, GCConstants.PATTERN_OWNER_DISPLAYNAME, true, cache.getOwnerDisplayName()))); // hidden try { String hiddenString = TextUtils.getMatch(tableInside, GCConstants.PATTERN_HIDDEN, true, null); if (StringUtils.isNotBlank(hiddenString)) { cache.setHidden(GCLogin.parseGcCustomDate(hiddenString)); } if (cache.getHiddenDate() == null) { // event date hiddenString = TextUtils.getMatch(tableInside, GCConstants.PATTERN_HIDDENEVENT, true, null); if (StringUtils.isNotBlank(hiddenString)) { cache.setHidden(GCLogin.parseGcCustomDate(hiddenString)); } } } catch (final ParseException e) { // failed to parse cache hidden date Log.w("GCParser.parseCache: Failed to parse cache hidden (event) date", e); } // favorite try { cache.setFavoritePoints(Integer.parseInt(TextUtils.getMatch(tableInside, GCConstants.PATTERN_FAVORITECOUNT, true, "0"))); } catch (final NumberFormatException e) { Log.e("Error parsing favorite count", e); } // cache size cache.setSize(CacheSize.getById(TextUtils.getMatch(tableInside, GCConstants.PATTERN_SIZE, true, CacheSize.NOT_CHOSEN.id))); } // cache found cache.setFound(TextUtils.matches(page, GCConstants.PATTERN_FOUND) || TextUtils.matches(page, GCConstants.PATTERN_FOUND_ALTERNATIVE)); // cache type cache.setType(CacheType.getByGuid(TextUtils.getMatch(page, GCConstants.PATTERN_TYPE, true, cache.getType().id))); // on watchlist cache.setOnWatchlist(TextUtils.matches(page, GCConstants.PATTERN_WATCHLIST)); // latitude and longitude. Can only be retrieved if user is logged in String latlon = TextUtils.getMatch(page, GCConstants.PATTERN_LATLON, true, ""); if (StringUtils.isNotEmpty(latlon)) { try { cache.setCoords(new Geopoint(latlon)); cache.setReliableLatLon(true); } catch (final Geopoint.GeopointException e) { Log.w("GCParser.parseCache: Failed to parse cache coordinates", e); } } // cache location cache.setLocation(TextUtils.getMatch(page, GCConstants.PATTERN_LOCATION, true, "")); // cache hint final String result = TextUtils.getMatch(page, GCConstants.PATTERN_HINT, false, null); if (result != null) { // replace linebreak and paragraph tags final String hint = GCConstants.PATTERN_LINEBREAK.matcher(result).replaceAll("\n"); cache.setHint(StringUtils.replace(hint, "</p>", "").trim()); } cache.checkFields(); // cache personal note cache.setPersonalNote(personalNoteWithLineBreaks); // cache short description cache.setShortDescription(TextUtils.getMatch(page, GCConstants.PATTERN_SHORTDESC, true, "")); // cache description final String longDescription = TextUtils.getMatch(page, GCConstants.PATTERN_DESC, true, ""); String relatedWebPage = TextUtils.getMatch(page, GCConstants.PATTERN_RELATED_WEB_PAGE, true, ""); if (StringUtils.isNotEmpty(relatedWebPage)) { relatedWebPage = String.format("<a href=\"%s\"><b>%s</b></a><br/><br/>", relatedWebPage, relatedWebPage); } cache.setDescription(relatedWebPage + longDescription); // cache attributes try { final String attributesPre = TextUtils.getMatch(page, GCConstants.PATTERN_ATTRIBUTES, true, null); if (null != attributesPre) { final MatcherWrapper matcherAttributesInside = new MatcherWrapper(GCConstants.PATTERN_ATTRIBUTESINSIDE, attributesPre); final ArrayList<String> attributes = new ArrayList<>(); while (matcherAttributesInside.find()) { if (matcherAttributesInside.groupCount() > 1 && !matcherAttributesInside.group(2).equalsIgnoreCase("blank")) { // by default, use the tooltip of the attribute String attribute = matcherAttributesInside.group(2).toLowerCase(Locale.US); // if the image name can be recognized, use the image name as attribute final String imageName = matcherAttributesInside.group(1).trim(); if (StringUtils.isNotEmpty(imageName)) { final int start = imageName.lastIndexOf('/'); final int end = imageName.lastIndexOf('.'); if (start >= 0 && end >= 0) { attribute = imageName.substring(start + 1, end).replace('-', '_').toLowerCase(Locale.US); } } attributes.add(attribute); } } cache.setAttributes(attributes); } } catch (final RuntimeException e) { // failed to parse cache attributes Log.w("GCParser.parseCache: Failed to parse cache attributes", e); } // cache spoilers try { if (CancellableHandler.isCancelled(handler)) { return null; } CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_spoilers); final MatcherWrapper matcherSpoilersInside = new MatcherWrapper(GCConstants.PATTERN_SPOILER_IMAGE, page); while (matcherSpoilersInside.find()) { // the original spoiler URL (include .../display/... contains a low-resolution image // if we shorten the URL we get the original-resolution image final String url = matcherSpoilersInside.group(1).replace("/display", ""); String title = null; if (matcherSpoilersInside.group(3) != null) { title = matcherSpoilersInside.group(3); } String description = null; if (matcherSpoilersInside.group(4) != null) { description = matcherSpoilersInside.group(4); } cache.addSpoiler(new Image(url, title, description)); } } catch (final RuntimeException e) { // failed to parse cache spoilers Log.w("GCParser.parseCache: Failed to parse cache spoilers", e); } // cache inventory try { cache.setInventoryItems(0); final MatcherWrapper matcherInventory = new MatcherWrapper(GCConstants.PATTERN_INVENTORY, page); if (matcherInventory.find()) { if (cache.getInventory() == null) { cache.setInventory(new ArrayList<Trackable>()); } if (matcherInventory.groupCount() > 1) { final String inventoryPre = matcherInventory.group(2); if (StringUtils.isNotBlank(inventoryPre)) { final MatcherWrapper matcherInventoryInside = new MatcherWrapper(GCConstants.PATTERN_INVENTORYINSIDE, inventoryPre); while (matcherInventoryInside.find()) { if (matcherInventoryInside.groupCount() > 0) { final Trackable inventoryItem = new Trackable(); inventoryItem.setGuid(matcherInventoryInside.group(1)); inventoryItem.setName(matcherInventoryInside.group(2)); cache.getInventory().add(inventoryItem); cache.setInventoryItems(cache.getInventoryItems() + 1); } } } } } } catch (final RuntimeException e) { // failed to parse cache inventory Log.w("GCParser.parseCache: Failed to parse cache inventory (2)", e); } // cache logs counts try { final String countlogs = TextUtils.getMatch(page, GCConstants.PATTERN_COUNTLOGS, true, null); if (null != countlogs) { final MatcherWrapper matcherLog = new MatcherWrapper(GCConstants.PATTERN_COUNTLOG, countlogs); while (matcherLog.find()) { final String typeStr = matcherLog.group(1); final String countStr = getNumberString(matcherLog.group(2)); if (StringUtils.isNotBlank(typeStr) && LogType.UNKNOWN != LogType.getByIconName(typeStr) && StringUtils.isNotBlank(countStr)) { cache.getLogCounts().put(LogType.getByIconName(typeStr), Integer.parseInt(countStr)); } } } } catch (final NumberFormatException e) { // failed to parse logs Log.w("GCParser.parseCache: Failed to parse cache log count", e); } // waypoints - reset collection cache.setWaypoints(Collections.<Waypoint> emptyList(), false); // add waypoint for original coordinates in case of user-modified listing-coordinates try { final String originalCoords = TextUtils.getMatch(page, GCConstants.PATTERN_LATLON_ORIG, false, null); if (null != originalCoords) { final Waypoint waypoint = new Waypoint(CgeoApplication.getInstance().getString(R.string.cache_coordinates_original), WaypointType.ORIGINAL, false); waypoint.setCoords(new Geopoint(originalCoords)); cache.addOrChangeWaypoint(waypoint, false); cache.setUserModifiedCoords(true); } } catch (final Geopoint.GeopointException ignored) { } int wpBegin = page.indexOf("<table class=\"Table\" id=\"ctl00_ContentBody_Waypoints\">"); if (wpBegin != -1) { // parse waypoints if (CancellableHandler.isCancelled(handler)) { return null; } CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_waypoints); String wpList = page.substring(wpBegin); int wpEnd = wpList.indexOf("</p>"); if (wpEnd > -1 && wpEnd <= wpList.length()) { wpList = wpList.substring(0, wpEnd); } if (!wpList.contains("No additional waypoints to display.")) { wpEnd = wpList.indexOf("</table>"); wpList = wpList.substring(0, wpEnd); wpBegin = wpList.indexOf("<tbody>"); wpEnd = wpList.indexOf("</tbody>"); if (wpBegin >= 0 && wpEnd >= 0 && wpEnd <= wpList.length()) { wpList = wpList.substring(wpBegin + 7, wpEnd); } final String[] wpItems = StringUtils.splitByWholeSeparator(wpList, "<tr"); for (int j = 1; j < wpItems.length; j++) { String[] wp = StringUtils.splitByWholeSeparator(wpItems[j], "<td"); // waypoint name // res is null during the unit tests final String name = TextUtils.getMatch(wp[6], GCConstants.PATTERN_WPNAME, true, 1, CgeoApplication.getInstance().getString(R.string.waypoint), true); // waypoint type final String resulttype = TextUtils.getMatch(wp[3], GCConstants.PATTERN_WPTYPE, null); final Waypoint waypoint = new Waypoint(name, WaypointType.findById(resulttype), false); // waypoint prefix waypoint.setPrefix(TextUtils.getMatch(wp[4], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON, true, 2, waypoint.getPrefix(), false)); // waypoint lookup waypoint.setLookup(TextUtils.getMatch(wp[5], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON, true, 2, waypoint.getLookup(), false)); // waypoint latitude and longitude latlon = Html.fromHtml(TextUtils.getMatch(wp[7], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON, false, 2, "", false)).toString().trim(); if (!StringUtils.startsWith(latlon, "???")) { waypoint.setLatlon(latlon); waypoint.setCoords(new Geopoint(latlon)); } j++; if (wpItems.length > j) { wp = StringUtils.splitByWholeSeparator(wpItems[j], "<td"); } // waypoint note waypoint.setNote(TextUtils.getMatch(wp[3], GCConstants.PATTERN_WPNOTE, waypoint.getNote())); cache.addOrChangeWaypoint(waypoint, false); } } } cache.parseWaypointsFromNote(); // last check for necessary cache conditions if (StringUtils.isBlank(cache.getGeocode())) { return ImmutablePair.of(StatusCode.UNKNOWN_ERROR, null); } cache.setDetailedUpdatedNow(); return ImmutablePair.of(StatusCode.NO_ERROR, cache); } private static String getNumberString(final String numberWithPunctuation) { return StringUtils.replaceChars(numberWithPunctuation, ".,", ""); } public static SearchResult searchByNextPage(final SearchResult search, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { if (search == null) { return null; } final String[] viewstates = search.getViewstates(); final String url = search.getUrl(); if (StringUtils.isBlank(url)) { Log.e("GCParser.searchByNextPage: No url found"); return search; } if (GCLogin.isEmpty(viewstates)) { Log.e("GCParser.searchByNextPage: No viewstate given"); return search; } final Parameters params = new Parameters( "__EVENTTARGET", "ctl00$ContentBody$pgrBottom$ctl08", "__EVENTARGUMENT", ""); GCLogin.putViewstates(params, viewstates); final String page = GCLogin.getInstance().postRequestLogged(url, params); if (!GCLogin.getInstance().getLoginStatus(page)) { Log.e("GCParser.postLogTrackable: Can not log in geocaching"); return search; } if (StringUtils.isBlank(page)) { Log.e("GCParser.searchByNextPage: No data from server"); return search; } final SearchResult searchResult = parseSearch(url, page, showCaptcha, recaptchaReceiver); if (searchResult == null || CollectionUtils.isEmpty(searchResult.getGeocodes())) { Log.w("GCParser.searchByNextPage: No cache parsed"); return search; } // search results don't need to be filtered so load GCVote ratings here GCVote.loadRatings(new ArrayList<>(searchResult.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB))); // save to application search.setError(searchResult.getError()); search.setViewstates(searchResult.viewstates); for (final String geocode : searchResult.getGeocodes()) { search.addGeocode(geocode); } return search; } /** * Possibly hide caches found or hidden by user. This mutates its params argument when possible. * * @param params * the parameters to mutate, or null to create a new Parameters if needed * @param my * @param addF * @return the original params if not null, maybe augmented with f=1, or a new Parameters with f=1 or null otherwise */ private static Parameters addFToParams(final Parameters params, final boolean my, final boolean addF) { if (!my && Settings.isExcludeMyCaches() && addF) { if (params == null) { return new Parameters("f", "1"); } params.put("f", "1"); Log.i("Skipping caches found or hidden by user."); } return params; } /** * @param cacheType * @param listId * @param showCaptcha * @param params * the parameters to add to the request URI * @param recaptchaReceiver * @return */ @Nullable private static SearchResult searchByAny(final CacheType cacheType, final boolean my, final boolean showCaptcha, final Parameters params, final RecaptchaReceiver recaptchaReceiver) { insertCacheType(params, cacheType); final String uri = "http://www.geocaching.com/seek/nearest.aspx"; final String fullUri = uri + "?" + addFToParams(params, my, true); final String page = GCLogin.getInstance().getRequestLogged(uri, addFToParams(params, my, true)); if (StringUtils.isBlank(page)) { Log.e("GCParser.searchByAny: No data from server"); return null; } assert page != null; final SearchResult searchResult = parseSearch(fullUri, page, showCaptcha, recaptchaReceiver); if (searchResult == null || CollectionUtils.isEmpty(searchResult.getGeocodes())) { Log.e("GCParser.searchByAny: No cache parsed"); return searchResult; } final SearchResult search = searchResult.filterSearchResults(Settings.isExcludeDisabledCaches(), false, cacheType); GCLogin.getInstance().getLoginStatus(page); return search; } public static SearchResult searchByCoords(final @NonNull Geopoint coords, final CacheType cacheType, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { final Parameters params = new Parameters("lat", Double.toString(coords.getLatitude()), "lng", Double.toString(coords.getLongitude())); return searchByAny(cacheType, false, showCaptcha, params, recaptchaReceiver); } public static SearchResult searchByKeyword(final @NonNull String keyword, final CacheType cacheType, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { if (StringUtils.isBlank(keyword)) { Log.e("GCParser.searchByKeyword: No keyword given"); return null; } final Parameters params = new Parameters("key", keyword); return searchByAny(cacheType, false, showCaptcha, params, recaptchaReceiver); } private static boolean isSearchForMyCaches(final String userName) { if (userName.equalsIgnoreCase(Settings.getGcCredentials().left)) { Log.i("Overriding users choice because of self search, downloading all caches."); return true; } return false; } public static SearchResult searchByUsername(final String userName, final CacheType cacheType, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { if (StringUtils.isBlank(userName)) { Log.e("GCParser.searchByUsername: No user name given"); return null; } final Parameters params = new Parameters("ul", userName); return searchByAny(cacheType, isSearchForMyCaches(userName), showCaptcha, params, recaptchaReceiver); } public static SearchResult searchByPocketQuery(final String pocketGuid, final CacheType cacheType, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { if (StringUtils.isBlank(pocketGuid)) { Log.e("GCParser.searchByPocket: No guid name given"); return null; } final Parameters params = new Parameters("pq", pocketGuid); return searchByAny(cacheType, false, showCaptcha, params, recaptchaReceiver); } public static SearchResult searchByOwner(final String userName, final CacheType cacheType, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { if (StringUtils.isBlank(userName)) { Log.e("GCParser.searchByOwner: No user name given"); return null; } final Parameters params = new Parameters("u", userName); return searchByAny(cacheType, isSearchForMyCaches(userName), showCaptcha, params, recaptchaReceiver); } public static SearchResult searchByAddress(final String address, final CacheType cacheType, final boolean showCaptcha, final RecaptchaReceiver recaptchaReceiver) { if (StringUtils.isBlank(address)) { Log.e("GCParser.searchByAddress: No address given"); return null; } final ObjectNode response = Network.requestJSON("http://www.geocaching.com/api/geocode", new Parameters("q", address)); if (response == null) { return null; } if (!StringUtils.equalsIgnoreCase(response.path("status").asText(), "success")) { return null; } final JsonNode data = response.path("data"); final JsonNode latNode = data.get("lat"); final JsonNode lngNode = data.get("lng"); if (latNode == null || lngNode == null) { return null; } return searchByCoords(new Geopoint(latNode.asDouble(), lngNode.asDouble()), cacheType, showCaptcha, recaptchaReceiver); } @Nullable public static Trackable searchTrackable(final String geocode, final String guid, final String id) { if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid) && StringUtils.isBlank(id)) { Log.w("GCParser.searchTrackable: No geocode nor guid nor id given"); return null; } Trackable trackable = new Trackable(); final Parameters params = new Parameters(); if (StringUtils.isNotBlank(geocode)) { params.put("tracker", geocode); trackable.setGeocode(geocode); } else if (StringUtils.isNotBlank(guid)) { params.put("guid", guid); } else if (StringUtils.isNotBlank(id)) { params.put("id", id); } final String page = GCLogin.getInstance().getRequestLogged("http://www.geocaching.com/track/details.aspx", params); if (StringUtils.isBlank(page)) { Log.e("GCParser.searchTrackable: No data from server"); return trackable; } assert page != null; trackable = parseTrackable(page, geocode); if (trackable == null) { Log.w("GCParser.searchTrackable: No trackable parsed"); return null; } return trackable; } public static List<PocketQueryList> searchPocketQueryList() { final Parameters params = new Parameters(); final String page = GCLogin.getInstance().getRequestLogged("http://www.geocaching.com/pocket/default.aspx", params); if (StringUtils.isBlank(page)) { Log.e("GCParser.searchPocketQueryList: No data from server"); return null; } final String subPage = StringUtils.substringAfter(page, "class=\"PocketQueryListTable"); if (StringUtils.isEmpty(subPage)) { Log.e("GCParser.searchPocketQueryList: class \"PocketQueryListTable\" not found on page"); return Collections.emptyList(); } final List<PocketQueryList> list = new ArrayList<>(); final MatcherWrapper matcherPocket = new MatcherWrapper(GCConstants.PATTERN_LIST_PQ, subPage); while (matcherPocket.find()) { int maxCaches; try { maxCaches = Integer.parseInt(matcherPocket.group(1)); } catch (final NumberFormatException e) { maxCaches = 0; Log.e("GCParser.searchPocketQueryList: Unable to parse max caches", e); } final String guid = Html.fromHtml(matcherPocket.group(2)).toString(); final String name = Html.fromHtml(matcherPocket.group(3)).toString(); final PocketQueryList pqList = new PocketQueryList(guid, name, maxCaches); list.add(pqList); } // just in case, lets sort the resulting list Collections.sort(list, new Comparator<PocketQueryList>() { @Override public int compare(final PocketQueryList left, final PocketQueryList right) { return String.CASE_INSENSITIVE_ORDER.compare(left.getName(), right.getName()); } }); return list; } public static ImmutablePair<StatusCode, String> postLog(final String geocode, final String cacheid, final String[] viewstates, final LogType logType, final int year, final int month, final int day, final String log, final List<TrackableLog> trackables) { if (GCLogin.isEmpty(viewstates)) { Log.e("GCParser.postLog: No viewstate given"); return new ImmutablePair<>(StatusCode.LOG_POST_ERROR, ""); } if (StringUtils.isBlank(log)) { Log.e("GCParser.postLog: No log text given"); return new ImmutablePair<>(StatusCode.NO_LOG_TEXT, ""); } final String logInfo = log.replace("\n", "\r\n").trim(); // windows' eol and remove leading and trailing whitespaces Log.i("Trying to post log for cache #" + cacheid + " - action: " + logType + "; date: " + year + "." + month + "." + day + ", log: " + logInfo + "; trackables: " + (trackables != null ? trackables.size() : "0")); final Parameters params = new Parameters( "__EVENTTARGET", "", "__EVENTARGUMENT", "", "__LASTFOCUS", "", "ctl00$ContentBody$LogBookPanel1$ddLogType", Integer.toString(logType.id), "ctl00$ContentBody$LogBookPanel1$uxDateVisited", GCLogin.getCustomGcDateFormat().format(new GregorianCalendar(year, month - 1, day).getTime()), "ctl00$ContentBody$LogBookPanel1$uxDateVisited$Month", Integer.toString(month), "ctl00$ContentBody$LogBookPanel1$uxDateVisited$Day", Integer.toString(day), "ctl00$ContentBody$LogBookPanel1$uxDateVisited$Year", Integer.toString(year), "ctl00$ContentBody$LogBookPanel1$DateTimeLogged", String.format("%02d", month) + "/" + String.format("%02d", day) + "/" + String.format("%04d", year), "ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Month", Integer.toString(month), "ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Day", Integer.toString(day), "ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Year", Integer.toString(year), "ctl00$ContentBody$LogBookPanel1$LogButton", "Submit Log Entry", "ctl00$ContentBody$LogBookPanel1$uxLogInfo", logInfo, "ctl00$ContentBody$LogBookPanel1$btnSubmitLog", "Submit Log Entry", "ctl00$ContentBody$LogBookPanel1$uxLogCreationSource", "Old", "ctl00$ContentBody$uxVistOtherListingGC", ""); GCLogin.putViewstates(params, viewstates); if (trackables != null && !trackables.isEmpty()) { // we have some trackables to proceed final StringBuilder hdnSelected = new StringBuilder(); for (final TrackableLog tb : trackables) { if (tb.action != LogTypeTrackable.DO_NOTHING) { hdnSelected.append(Integer.toString(tb.id)); hdnSelected.append(tb.action.action); hdnSelected.append(','); } } params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnSelectedActions", hdnSelected.toString(), // selected trackables "ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnCurrentFilter", ""); } final String uri = new Uri.Builder().scheme("http").authority("www.geocaching.com").path("/seek/log.aspx").encodedQuery("ID=" + cacheid).build().toString(); final GCLogin gcLogin = GCLogin.getInstance(); String page = gcLogin.postRequestLogged(uri, params); if (!gcLogin.getLoginStatus(page)) { Log.e("GCParser.postLog: Cannot log in geocaching"); return new ImmutablePair<>(StatusCode.NOT_LOGGED_IN, ""); } // maintenance, archived needs to be confirmed final MatcherWrapper matcher = new MatcherWrapper(GCConstants.PATTERN_MAINTENANCE, page); try { if (matcher.find() && matcher.groupCount() > 0) { final String[] viewstatesConfirm = GCLogin.getViewstates(page); if (GCLogin.isEmpty(viewstatesConfirm)) { Log.e("GCParser.postLog: No viewstate for confirm log"); return new ImmutablePair<>(StatusCode.LOG_POST_ERROR, ""); } params.clear(); GCLogin.putViewstates(params, viewstatesConfirm); params.put("__EVENTTARGET", ""); params.put("__EVENTARGUMENT", ""); params.put("__LASTFOCUS", ""); params.put("ctl00$ContentBody$LogBookPanel1$btnConfirm", "Yes"); params.put("ctl00$ContentBody$LogBookPanel1$uxLogInfo", logInfo); params.put("ctl00$ContentBody$uxVistOtherListingGC", ""); if (trackables != null && !trackables.isEmpty()) { // we have some trackables to proceed final StringBuilder hdnSelected = new StringBuilder(); for (final TrackableLog tb : trackables) { final String action = Integer.toString(tb.id) + tb.action.action; final StringBuilder paramText = new StringBuilder("ctl00$ContentBody$LogBookPanel1$uxTrackables$repTravelBugs$ctl"); if (tb.ctl < 10) { paramText.append('0'); } paramText.append(tb.ctl).append("$ddlAction"); params.put(paramText.toString(), action); if (tb.action != LogTypeTrackable.DO_NOTHING) { hdnSelected.append(action); hdnSelected.append(','); } } params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnSelectedActions", hdnSelected.toString()); // selected trackables params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnCurrentFilter", ""); } page = Network.getResponseData(Network.postRequest(uri, params)); } } catch (final RuntimeException e) { Log.e("GCParser.postLog.confim", e); } try { final MatcherWrapper matcherOk = new MatcherWrapper(GCConstants.PATTERN_OK1, page); if (matcherOk.find()) { Log.i("Log successfully posted to cache #" + cacheid); if (geocode != null) { DataStore.saveVisitDate(geocode); } gcLogin.getLoginStatus(page); // the log-successful-page contains still the old value if (gcLogin.getActualCachesFound() >= 0) { gcLogin.setActualCachesFound(gcLogin.getActualCachesFound() + 1); } final String logID = TextUtils.getMatch(page, GCConstants.PATTERN_LOG_IMAGE_UPLOAD, ""); return new ImmutablePair<>(StatusCode.NO_ERROR, logID); } } catch (final Exception e) { Log.e("GCParser.postLog.check", e); } Log.e("GCParser.postLog: Failed to post log because of unknown error"); return new ImmutablePair<>(StatusCode.LOG_POST_ERROR, ""); } /** * Upload an image to a log that has already been posted * * @param logId * the ID of the log to upload the image to. Found on page returned when log is uploaded * @param caption * of the image; max 50 chars * @param description * of the image; max 250 chars * @param imageUri * the URI for the image to be uploaded * @return status code to indicate success or failure */ public static ImmutablePair<StatusCode, String> uploadLogImage(final String logId, final String caption, final String description, final Uri imageUri) { final String uri = new Uri.Builder().scheme("http").authority("www.geocaching.com").path("/seek/upload.aspx").encodedQuery("LID=" + logId).build().toString(); final String page = GCLogin.getInstance().getRequestLogged(uri, null); if (StringUtils.isBlank(page)) { Log.e("GCParser.uploadLogImage: No data from server"); return new ImmutablePair<>(StatusCode.UNKNOWN_ERROR, null); } assert page != null; final String[] viewstates = GCLogin.getViewstates(page); final Parameters uploadParams = new Parameters( "__EVENTTARGET", "", "__EVENTARGUMENT", "", "ctl00$ContentBody$ImageUploadControl1$uxFileCaption", caption, "ctl00$ContentBody$ImageUploadControl1$uxFileDesc", description, "ctl00$ContentBody$ImageUploadControl1$uxUpload", "Upload"); GCLogin.putViewstates(uploadParams, viewstates); final File image = new File(imageUri.getPath()); final String response = Network.getResponseData(Network.postRequest(uri, uploadParams, "ctl00$ContentBody$ImageUploadControl1$uxFileUpload", "image/jpeg", image)); final MatcherWrapper matcherUrl = new MatcherWrapper(GCConstants.PATTERN_IMAGE_UPLOAD_URL, response); if (matcherUrl.find()) { Log.i("Logimage successfully uploaded."); final String uploadedImageUrl = matcherUrl.group(1); return ImmutablePair.of(StatusCode.NO_ERROR, uploadedImageUrl); } Log.e("GCParser.uploadLogIMage: Failed to upload image because of unknown error"); return ImmutablePair.of(StatusCode.LOGIMAGE_POST_ERROR, null); } /** * Post a log to GC.com. * * @return status code of the upload and ID of the log */ public static StatusCode postLogTrackable(final String tbid, final String trackingCode, final String[] viewstates, final LogType logType, final int year, final int month, final int day, final String log) { if (GCLogin.isEmpty(viewstates)) { Log.e("GCParser.postLogTrackable: No viewstate given"); return StatusCode.LOG_POST_ERROR; } if (StringUtils.isBlank(log)) { Log.e("GCParser.postLogTrackable: No log text given"); return StatusCode.NO_LOG_TEXT; } Log.i("Trying to post log for trackable #" + trackingCode + " - action: " + logType + "; date: " + year + "." + month + "." + day + ", log: " + log); final String logInfo = log.replace("\n", "\r\n"); // windows' eol final Calendar currentDate = Calendar.getInstance(); final Parameters params = new Parameters( "__EVENTTARGET", "", "__EVENTARGUMENT", "", "__LASTFOCUS", "", "ctl00$ContentBody$LogBookPanel1$ddLogType", Integer.toString(logType.id), "ctl00$ContentBody$LogBookPanel1$tbCode", trackingCode); GCLogin.putViewstates(params, viewstates); if (currentDate.get(Calendar.YEAR) == year && (currentDate.get(Calendar.MONTH) + 1) == month && currentDate.get(Calendar.DATE) == day) { params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged", ""); params.put("ctl00$ContentBody$LogBookPanel1$uxDateVisited", ""); } else { params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged", Integer.toString(month) + "/" + Integer.toString(day) + "/" + Integer.toString(year)); params.put("ctl00$ContentBody$LogBookPanel1$uxDateVisited", GCLogin.getCustomGcDateFormat().format(new GregorianCalendar(year, month - 1, day).getTime())); } params.put( "ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Day", Integer.toString(day), "ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Month", Integer.toString(month), "ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Year", Integer.toString(year), "ctl00$ContentBody$LogBookPanel1$uxDateVisited$Day", Integer.toString(day), "ctl00$ContentBody$LogBookPanel1$uxDateVisited$Month", Integer.toString(month), "ctl00$ContentBody$LogBookPanel1$uxDateVisited$Year", Integer.toString(year), "ctl00$ContentBody$LogBookPanel1$uxLogInfo", logInfo, "ctl00$ContentBody$LogBookPanel1$btnSubmitLog", "Submit Log Entry", "ctl00$ContentBody$uxVistOtherTrackableTB", "", "ctl00$ContentBody$LogBookPanel1$LogButton", "Submit Log Entry", "ctl00$ContentBody$uxVistOtherListingGC", ""); final String uri = new Uri.Builder().scheme("http").authority("www.geocaching.com").path("/track/log.aspx").encodedQuery("wid=" + tbid).build().toString(); final String page = GCLogin.getInstance().postRequestLogged(uri, params); if (!GCLogin.getInstance().getLoginStatus(page)) { Log.e("GCParser.postLogTrackable: Cannot log in geocaching"); return StatusCode.NOT_LOGGED_IN; } try { final MatcherWrapper matcherOk = new MatcherWrapper(GCConstants.PATTERN_OK2, page); if (matcherOk.find()) { Log.i("Log successfully posted to trackable #" + trackingCode); return StatusCode.NO_ERROR; } } catch (final Exception e) { Log.e("GCParser.postLogTrackable.check", e); } Log.e("GCParser.postLogTrackable: Failed to post log because of unknown error"); return StatusCode.LOG_POST_ERROR; } /** * Adds the cache to the watchlist of the user. * * @param cache * the cache to add * @return <code>false</code> if an error occurred, <code>true</code> otherwise */ static boolean addToWatchlist(final Geocache cache) { final String uri = "http://www.geocaching.com/my/watchlist.aspx?w=" + cache.getCacheId(); final String page = GCLogin.getInstance().postRequestLogged(uri, null); if (StringUtils.isBlank(page)) { Log.e("GCParser.addToWatchlist: No data from server"); return false; // error } final boolean guidOnPage = isGuidContainedInPage(cache, page); if (guidOnPage) { Log.i("GCParser.addToWatchlist: cache is on watchlist"); cache.setOnWatchlist(true); } else { Log.e("GCParser.addToWatchlist: cache is not on watchlist"); } return guidOnPage; // on watchlist (=added) / else: error } /** * Removes the cache from the watch list * * @param cache * the cache to remove * @return <code>false</code> if an error occurred, <code>true</code> otherwise */ static boolean removeFromWatchlist(final Geocache cache) { final String uri = "http://www.geocaching.com/my/watchlist.aspx?ds=1&action=rem&id=" + cache.getCacheId(); String page = GCLogin.getInstance().postRequestLogged(uri, null); if (StringUtils.isBlank(page)) { Log.e("GCParser.removeFromWatchlist: No data from server"); return false; // error } // removing cache from list needs approval by hitting "Yes" button final Parameters params = new Parameters( "__EVENTTARGET", "", "__EVENTARGUMENT", "", "ctl00$ContentBody$btnYes", "Yes"); GCLogin.transferViewstates(page, params); page = Network.getResponseData(Network.postRequest(uri, params)); final boolean guidOnPage = isGuidContainedInPage(cache, page); if (!guidOnPage) { Log.i("GCParser.removeFromWatchlist: cache removed from watchlist"); cache.setOnWatchlist(false); } else { Log.e("GCParser.removeFromWatchlist: cache not removed from watchlist"); } return !guidOnPage; // on watch list (=error) / not on watch list } /** * Checks if a page contains the guid of a cache * * @param cache the geocache * @param page * the page to search in, may be null * @return true if the page contains the guid of the cache, false otherwise */ private static boolean isGuidContainedInPage(final Geocache cache, final String page) { if (StringUtils.isBlank(page) || StringUtils.isBlank(cache.getGuid())) { return false; } return Pattern.compile(cache.getGuid(), Pattern.CASE_INSENSITIVE).matcher(page).find(); } @Nullable static String requestHtmlPage(@Nullable final String geocode, @Nullable final String guid, final String log, final String numlogs) { final Parameters params = new Parameters("decrypt", "y"); if (StringUtils.isNotBlank(geocode)) { params.put("wp", geocode); } else if (StringUtils.isNotBlank(guid)) { params.put("guid", guid); } params.put("log", log); params.put("numlogs", numlogs); return GCLogin.getInstance().getRequestLogged("http://www.geocaching.com/seek/cache_details.aspx", params); } /** * Adds the cache to the favorites of the user. * * This must not be called from the UI thread. * * @param cache * the cache to add * @return <code>false</code> if an error occurred, <code>true</code> otherwise */ static boolean addToFavorites(final Geocache cache) { return changeFavorite(cache, true); } private static boolean changeFavorite(final Geocache cache, final boolean add) { final String userToken = getUserToken(cache); if (StringUtils.isEmpty(userToken)) { return false; } final String uri = "http://www.geocaching.com/datastore/favorites.svc/update?u=" + userToken + "&f=" + Boolean.toString(add); final HttpResponse response = Network.postRequest(uri, null); if (response != null && response.getStatusLine().getStatusCode() == 200) { Log.i("GCParser.changeFavorite: cache added/removed to/from favorites"); cache.setFavorite(add); cache.setFavoritePoints(cache.getFavoritePoints() + (add ? 1 : -1)); return true; } Log.e("GCParser.changeFavorite: cache not added/removed to/from favorites"); return false; } private static String getUserToken(final Geocache cache) { final String page = requestHtmlPage(cache.getGeocode(), null, "n", "0"); return TextUtils.getMatch(page, GCConstants.PATTERN_USERTOKEN, ""); } /** * Removes the cache from the favorites. * * This must not be called from the UI thread. * * @param cache * the cache to remove * @return <code>false</code> if an error occurred, <code>true</code> otherwise */ static boolean removeFromFavorites(final Geocache cache) { return changeFavorite(cache, false); } /** * Parse a trackable HTML description into a Trackable object * * @param page * the HTML page to parse, already processed through {@link TextUtils#replaceWhitespace} * @return the parsed trackable, or null if none could be parsed */ static Trackable parseTrackable(final String page, final String possibleTrackingcode) { if (StringUtils.isBlank(page)) { Log.e("GCParser.parseTrackable: No page given"); return null; } if (page.contains(GCConstants.ERROR_TB_DOES_NOT_EXIST) || page.contains(GCConstants.ERROR_TB_ARITHMETIC_OVERFLOW) || page.contains(GCConstants.ERROR_TB_ELEMENT_EXCEPTION)) { return null; } final Trackable trackable = new Trackable(); // trackable geocode trackable.setGeocode(TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_GEOCODE, true, StringUtils.upperCase(possibleTrackingcode))); if (trackable.getGeocode() == null) { Log.e("GCParser.parseTrackable: could not figure out trackable geocode"); return null; } // trackable id trackable.setGuid(TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_GUID, true, trackable.getGuid())); // trackable icon trackable.setIconUrl(TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_ICON, true, trackable.getIconUrl())); // trackable name trackable.setName(Html.fromHtml(TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_NAME, true, "")).toString()); // trackable type if (StringUtils.isNotBlank(trackable.getName())) { trackable.setType(TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_TYPE, true, trackable.getType())); } // trackable owner name try { final MatcherWrapper matcherOwner = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE_OWNER, page); if (matcherOwner.find() && matcherOwner.groupCount() > 0) { trackable.setOwnerGuid(matcherOwner.group(1)); trackable.setOwner(matcherOwner.group(2).trim()); } } catch (final RuntimeException e) { // failed to parse trackable owner name Log.w("GCParser.parseTrackable: Failed to parse trackable owner name", e); } // trackable origin trackable.setOrigin(TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_ORIGIN, true, trackable.getOrigin())); // trackable spotted try { final MatcherWrapper matcherSpottedCache = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE_SPOTTEDCACHE, page); if (matcherSpottedCache.find() && matcherSpottedCache.groupCount() > 0) { trackable.setSpottedGuid(matcherSpottedCache.group(1)); trackable.setSpottedName(matcherSpottedCache.group(2).trim()); trackable.setSpottedType(Trackable.SPOTTED_CACHE); } final MatcherWrapper matcherSpottedUser = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE_SPOTTEDUSER, page); if (matcherSpottedUser.find() && matcherSpottedUser.groupCount() > 0) { trackable.setSpottedGuid(matcherSpottedUser.group(1)); trackable.setSpottedName(matcherSpottedUser.group(2).trim()); trackable.setSpottedType(Trackable.SPOTTED_USER); } if (TextUtils.matches(page, GCConstants.PATTERN_TRACKABLE_SPOTTEDUNKNOWN)) { trackable.setSpottedType(Trackable.SPOTTED_UNKNOWN); } if (TextUtils.matches(page, GCConstants.PATTERN_TRACKABLE_SPOTTEDOWNER)) { trackable.setSpottedType(Trackable.SPOTTED_OWNER); } } catch (final RuntimeException e) { // failed to parse trackable last known place Log.w("GCParser.parseTrackable: Failed to parse trackable last known place", e); } // released date - can be missing on the page final String releaseString = TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_RELEASES, false, null); if (releaseString != null) { try { trackable.setReleased(dateTbIn1.parse(releaseString)); } catch (final ParseException ignore) { if (trackable.getReleased() == null) { try { trackable.setReleased(dateTbIn2.parse(releaseString)); } catch (final ParseException e) { Log.e("Could not parse trackable release " + releaseString, e); } } } } // trackable distance final String distance = TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_DISTANCE, false, null); if (null != distance) { try { trackable.setDistance(DistanceParser.parseDistance(distance, !Settings.isUseImperialUnits())); } catch (final NumberFormatException e) { Log.e("GCParser.parseTrackable: Failed to parse distance", e); } } // trackable goal trackable.setGoal(convertLinks(TextUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_GOAL, true, trackable.getGoal()))); // trackable details & image try { final MatcherWrapper matcherDetailsImage = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE_DETAILSIMAGE, page); if (matcherDetailsImage.find() && matcherDetailsImage.groupCount() > 0) { final String image = StringUtils.trim(matcherDetailsImage.group(3)); final String details = StringUtils.trim(matcherDetailsImage.group(4)); if (StringUtils.isNotEmpty(image)) { trackable.setImage(image); } if (StringUtils.isNotEmpty(details) && !StringUtils.equals(details, "No additional details available.")) { trackable.setDetails(convertLinks(details)); } } } catch (final RuntimeException e) { // failed to parse trackable details & image Log.w("GCParser.parseTrackable: Failed to parse trackable details & image", e); } if (StringUtils.isEmpty(trackable.getDetails()) && page.contains(GCConstants.ERROR_TB_NOT_ACTIVATED)) { trackable.setDetails(CgeoApplication.getInstance().getString(R.string.trackable_not_activated)); } // trackable logs try { final MatcherWrapper matcherLogs = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE_LOG, page); /* * 1. Type (image) * 2. Date * 3. Author * 4. Cache-GUID * 5. <ignored> (strike-through property for ancient caches) * 6. Cache-name * 7. Log text */ while (matcherLogs.find()) { long date = 0; try { date = GCLogin.parseGcCustomDate(matcherLogs.group(2)).getTime(); } catch (final ParseException ignore) { } final LogEntry logDone = new LogEntry( Html.fromHtml(matcherLogs.group(3)).toString().trim(), date, LogType.getByIconName(matcherLogs.group(1)), matcherLogs.group(7).trim()); if (matcherLogs.group(4) != null && matcherLogs.group(6) != null) { logDone.cacheGuid = matcherLogs.group(4); logDone.cacheName = matcherLogs.group(6); } // Apply the pattern for images in a trackable log entry against each full log (group(0)) final String logEntry = matcherLogs.group(0); final MatcherWrapper matcherLogImages = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE_LOG_IMAGES, logEntry); /* * 1. Image URL * 2. Image title */ while (matcherLogImages.find()) { final Image logImage = new Image(matcherLogImages.group(1), matcherLogImages.group(2)); logDone.addLogImage(logImage); } trackable.getLogs().add(logDone); } } catch (final Exception e) { // failed to parse logs Log.w("GCParser.parseCache: Failed to parse cache logs", e); } // tracking code if (!StringUtils.equalsIgnoreCase(trackable.getGeocode(), possibleTrackingcode)) { trackable.setTrackingcode(possibleTrackingcode); } if (CgeoApplication.getInstance() != null) { DataStore.saveTrackable(trackable); } return trackable; } private static String convertLinks(final String input) { if (input == null) { return null; } return StringUtils.replace(input, "../", GCConstants.GC_URL); } /** * Extract logs from a cache details page. * * @param page * the text of the details page * @return a list of log entries which will be empty if the logs could not be retrieved * */ @NonNull private static Observable<LogEntry> getLogsFromDetails(final String page) { // extract embedded JSON data from page return parseLogs(false, TextUtils.getMatch(page, GCConstants.PATTERN_LOGBOOK, "")); } private enum SpecialLogs { FRIENDS("sf"), OWN("sp"); final String paramName; SpecialLogs(final String paramName) { this.paramName = paramName; } private String getParamName() { return this.paramName; } } /** * Extract special logs (friends, own) through seperate request. * * @param page * The page to extrat userToken from * @param logType * The logType to request * @return Observable<LogEntry> The logs */ private static Observable<LogEntry> getSpecialLogs(final String page, final SpecialLogs logType) { return Observable.defer(new Func0<Observable<? extends LogEntry>>() { @Override public Observable<? extends LogEntry> call() { final MatcherWrapper userTokenMatcher = new MatcherWrapper(GCConstants.PATTERN_USERTOKEN, page); if (!userTokenMatcher.find()) { Log.e("GCParser.loadLogsFromDetails: unable to extract userToken"); return Observable.empty(); } final String userToken = userTokenMatcher.group(1); final Parameters params = new Parameters( "tkn", userToken, "idx", "1", "num", String.valueOf(GCConstants.NUMBER_OF_LOGS), logType.getParamName(), Boolean.toString(Boolean.TRUE), "decrypt", "true"); final HttpResponse response = Network.getRequest("http://www.geocaching.com/seek/geocache.logbook", params); if (response == null) { Log.e("GCParser.loadLogsFromDetails: cannot log logs, response is null"); return Observable.empty(); } final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { Log.e("GCParser.loadLogsFromDetails: error " + statusCode + " when requesting log information"); return Observable.empty(); } final String rawResponse = Network.getResponseData(response); if (rawResponse == null) { Log.e("GCParser.loadLogsFromDetails: unable to read whole response"); return Observable.empty(); } return parseLogs(true, rawResponse); } }).subscribeOn(RxUtils.networkScheduler); } private static Observable<LogEntry> parseLogs(final boolean markAsFriendsLog, final String rawResponse) { return Observable.create(new OnSubscribe<LogEntry>() { @Override public void call(final Subscriber<? super LogEntry> subscriber) { // for non logged in users the log book is not shown if (StringUtils.isBlank(rawResponse)) { subscriber.onCompleted(); return; } try { final ObjectNode resp = (ObjectNode) JsonUtils.reader.readTree(rawResponse); if (!resp.path("status").asText().equals("success")) { Log.e("GCParser.loadLogsFromDetails: status is " + resp.path("status").asText("[absent]")); subscriber.onCompleted(); return; } final ArrayNode data = (ArrayNode) resp.get("data"); for (final JsonNode entry: data) { // FIXME: use the "LogType" field instead of the "LogTypeImage" one. final String logIconNameExt = entry.path("LogTypeImage").asText(".gif"); final String logIconName = logIconNameExt.substring(0, logIconNameExt.length() - 4); long date = 0; try { date = GCLogin.parseGcCustomDate(entry.get("Visited").asText()).getTime(); } catch (ParseException | NullPointerException e) { Log.e("GCParser.loadLogsFromDetails: failed to parse log date", e); } // TODO: we should update our log data structure to be able to record // proper coordinates, and make them clickable. In the meantime, it is // better to integrate those coordinates into the text rather than not // display them at all. final String latLon = entry.path("LatLonString").asText(); final String logText = (StringUtils.isEmpty(latLon) ? "" : (latLon + "<br/><br/>")) + TextUtils.removeControlCharacters(entry.path("LogText").asText()); final LogEntry logDone = new LogEntry( TextUtils.removeControlCharacters(entry.path("UserName").asText()), date, LogType.getByIconName(logIconName), logText); logDone.found = entry.path("GeocacheFindCount").asInt(); logDone.friend = markAsFriendsLog; final ArrayNode images = (ArrayNode) entry.get("Images"); for (final JsonNode image: images) { final String url = "http://imgcdn.geocaching.com/cache/log/large/" + image.path("FileName").asText(); final String title = TextUtils.removeControlCharacters(image.path("Name").asText()); final Image logImage = new Image(url, title); logDone.addLogImage(logImage); } subscriber.onNext(logDone); } } catch (final IOException e) { Log.w("GCParser.loadLogsFromDetails: Failed to parse cache logs", e); } subscriber.onCompleted(); } }); } @NonNull public static List<LogType> parseTypes(final String page) { if (StringUtils.isEmpty(page)) { return Collections.emptyList(); } final List<LogType> types = new ArrayList<>(); final MatcherWrapper typeBoxMatcher = new MatcherWrapper(GCConstants.PATTERN_TYPEBOX, page); if (typeBoxMatcher.find() && typeBoxMatcher.groupCount() > 0) { final String typesText = typeBoxMatcher.group(1); final MatcherWrapper typeMatcher = new MatcherWrapper(GCConstants.PATTERN_TYPE2, typesText); while (typeMatcher.find()) { if (typeMatcher.groupCount() > 1) { try { final int type = Integer.parseInt(typeMatcher.group(2)); if (type > 0) { types.add(LogType.getById(type)); } } catch (final NumberFormatException e) { Log.e("Error parsing log types", e); } } } } // we don't support this log type types.remove(LogType.UPDATE_COORDINATES); return types; } public static List<TrackableLog> parseTrackableLog(final String page) { if (StringUtils.isEmpty(page)) { return null; } String table = StringUtils.substringBetween(page, "<table id=\"tblTravelBugs\"", "</table>"); // if no trackables are currently in the account, the table is not available, so return an empty list instead of null if (StringUtils.isBlank(table)) { return Collections.emptyList(); } table = StringUtils.substringBetween(table, "<tbody>", "</tbody>"); if (StringUtils.isBlank(table)) { Log.e("GCParser.parseTrackableLog: tbody not found on page"); return null; } final List<TrackableLog> trackableLogs = new ArrayList<>(); final MatcherWrapper trackableMatcher = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE, page); while (trackableMatcher.find()) { if (trackableMatcher.groupCount() > 0) { final String trackCode = trackableMatcher.group(1); final String name = Html.fromHtml(trackableMatcher.group(2)).toString(); try { final Integer ctl = Integer.valueOf(trackableMatcher.group(3)); final Integer id = Integer.valueOf(trackableMatcher.group(5)); if (trackCode != null && ctl != null && id != null) { final TrackableLog entry = new TrackableLog(trackCode, name, id, ctl); Log.i("Trackable in inventory (#" + entry.ctl + "/" + entry.id + "): " + entry.trackCode + " - " + entry.name); trackableLogs.add(entry); } } catch (final NumberFormatException e) { Log.e("GCParser.parseTrackableLog", e); } } } return trackableLogs; } /** * Insert the right cache type restriction in parameters * * @param params * the parameters to insert the restriction into * @param cacheType * the type of cache, or null to include everything */ static private void insertCacheType(final Parameters params, final CacheType cacheType) { params.put("tx", cacheType.guid); } private static void getExtraOnlineInfo(final Geocache cache, final String page, final CancellableHandler handler) { // This method starts the page parsing for logs in the background, as well as retrieve the friends and own logs // if requested. It merges them and stores them in the background, while the rating is retrieved if needed and // stored. Then we wait for the log merging and saving to be completed before returning. if (CancellableHandler.isCancelled(handler)) { return; } final Observable<LogEntry> logs = getLogsFromDetails(page).subscribeOn(RxUtils.computationScheduler); Observable<LogEntry> specialLogs; if (Settings.isFriendLogsWanted()) { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_logs); specialLogs = Observable.merge(getSpecialLogs(page, SpecialLogs.FRIENDS), getSpecialLogs(page, SpecialLogs.OWN)); } else { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_logs); specialLogs = Observable.empty(); } final Observable<List<LogEntry>> mergedLogs = Observable.zip(logs.toList(), specialLogs.toList(), new Func2<List<LogEntry>, List<LogEntry>, List<LogEntry>>() { @Override public List<LogEntry> call(final List<LogEntry> logEntries, final List<LogEntry> specialLogEntries) { mergeFriendsLogs(logEntries, specialLogEntries); return logEntries; } }).cache(); mergedLogs.subscribe(new Action1<List<LogEntry>>() { @Override public void call(final List<LogEntry> logEntries) { DataStore.saveLogsWithoutTransaction(cache.getGeocode(), logEntries); } }); if (Settings.isRatingWanted() && !CancellableHandler.isCancelled(handler)) { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_gcvote); final GCVoteRating rating = GCVote.getRating(cache.getGuid(), cache.getGeocode()); if (rating != null) { cache.setRating(rating.getRating()); cache.setVotes(rating.getVotes()); cache.setMyVote(rating.getMyVote()); } } // Wait for completion of logs parsing, retrieving and merging mergedLogs.toBlocking().last(); } /** * Merge log entries and mark them as friends logs (personal and friends) to identify * them on friends/personal logs tab. * * @param mergedLogs * the list to merge logs with * @param logsToMerge * the list of logs to merge */ private static void mergeFriendsLogs(final List<LogEntry> mergedLogs, final Iterable<LogEntry> logsToMerge) { for (final LogEntry log : logsToMerge) { if (mergedLogs.contains(log)) { mergedLogs.get(mergedLogs.indexOf(log)).friend = true; } else { mergedLogs.add(log); } } } public static boolean uploadModifiedCoordinates(final Geocache cache, final Geopoint wpt) { return editModifiedCoordinates(cache, wpt); } public static boolean deleteModifiedCoordinates(final Geocache cache) { return editModifiedCoordinates(cache, null); } public static boolean editModifiedCoordinates(final Geocache cache, final Geopoint wpt) { final String userToken = getUserToken(cache); if (StringUtils.isEmpty(userToken)) { return false; } final ObjectNode jo = new ObjectNode(JsonUtils.factory); final ObjectNode dto = jo.putObject("dto").put("ut", userToken); if (wpt != null) { dto.putObject("data").put("lat", wpt.getLatitudeE6() / 1E6).put("lng", wpt.getLongitudeE6() / 1E6); } final String uriSuffix = wpt != null ? "SetUserCoordinate" : "ResetUserCoordinate"; final String uriPrefix = "http://www.geocaching.com/seek/cache_details.aspx/"; final HttpResponse response = Network.postJsonRequest(uriPrefix + uriSuffix, jo); Log.i("Sending to " + uriPrefix + uriSuffix + " :" + jo.toString()); if (response != null && response.getStatusLine().getStatusCode() == 200) { Log.i("GCParser.editModifiedCoordinates - edited on GC.com"); return true; } Log.e("GCParser.deleteModifiedCoordinates - cannot delete modified coords"); return false; } public static boolean uploadPersonalNote(final Geocache cache) { final String userToken = getUserToken(cache); if (StringUtils.isEmpty(userToken)) { return false; } final ObjectNode jo = new ObjectNode(JsonUtils.factory); jo.putObject("dto").put("et", StringUtils.defaultString(cache.getPersonalNote())).put("ut", userToken); final String uriSuffix = "SetUserCacheNote"; final String uriPrefix = "http://www.geocaching.com/seek/cache_details.aspx/"; final HttpResponse response = Network.postJsonRequest(uriPrefix + uriSuffix, jo); Log.i("Sending to " + uriPrefix + uriSuffix + " :" + jo.toString()); if (response != null && response.getStatusLine().getStatusCode() == 200) { Log.i("GCParser.uploadPersonalNote - uploaded to GC.com"); return true; } Log.e("GCParser.uploadPersonalNote - cannot upload personal note"); return false; } }
Use lesser-arguments form of getMatch when possible
main/src/cgeo/geocaching/connector/gc/GCParser.java
Use lesser-arguments form of getMatch when possible
<ide><path>ain/src/cgeo/geocaching/connector/gc/GCParser.java <ide> <ide> // cache direction - image <ide> if (Settings.getLoadDirImg()) { <del> final String direction = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_DIRECTION_DISTANCE, false, 1, null, false); <add> final String direction = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_DIRECTION_DISTANCE, false, null); <ide> if (direction != null) { <ide> cache.setDirectionImg(direction); <ide> } <ide> } <ide> <ide> // size <del> final String container = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_CONTAINER, false, 1, null, false); <add> final String container = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_CONTAINER, false, null); <ide> cache.setSize(CacheSize.getById(container)); <ide> <ide> // date hidden, makes sorting event caches easier <del> final String dateHidden = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_HIDDEN_DATE, false, 1, null, false); <add> final String dateHidden = TextUtils.getMatch(row, GCConstants.PATTERN_SEARCH_HIDDEN_DATE, false, null); <ide> if (StringUtils.isNotBlank(dateHidden)) { <ide> try { <ide> final Date date = GCLogin.parseGcCustomDate(dateHidden);
JavaScript
mit
4b5674412469034bb5be926e1bdd2fe47190350c
0
Ritoplz/ritoplz
'use strict' import { createStore, applyMiddleware, compose } from 'redux' import axios from 'axios' import thunk from 'redux-thunk' import rootReducer from '../reducers' const configureStore = initialState => { return createStore( rootReducer, initialState, compose( applyMiddleware(thunk), typeof window === 'object' && typeof window.devToolsExtension !== 'undefined' ? window.devToolsExtension() : f => f ) ) } export default configureStore
store/configureStore.js
'use strict' import { createStore, applyMiddleware } from 'redux' import axios from 'axios' import thunk from 'redux-thunk' import rootReducer from '../reducers' const configureStore = initialState => { return createStore( rootReducer, initialState, applyMiddleware(thunk) ) } export default configureStore
Add Redux DevTools
store/configureStore.js
Add Redux DevTools
<ide><path>tore/configureStore.js <ide> 'use strict' <ide> <del>import { createStore, applyMiddleware } from 'redux' <add>import { createStore, applyMiddleware, compose } from 'redux' <ide> import axios from 'axios' <ide> import thunk from 'redux-thunk' <ide> <ide> return createStore( <ide> rootReducer, <ide> initialState, <del> applyMiddleware(thunk) <add> compose( <add> applyMiddleware(thunk), <add> typeof window === 'object' && typeof window.devToolsExtension !== 'undefined' <add> ? window.devToolsExtension() <add> : f => f <add> ) <ide> ) <ide> } <ide>
Java
apache-2.0
fdc64ac684a46c391cbfa3263046ce058fe17f3c
0
maksimov/dasein-cloud-cloudstack,daniellemayne/dasein-cloud-cloudstack_old,daniellemayne/dasein-cloud-cloudstack,greese/dasein-cloud-cloudstack,maksimov/dasein-cloud-cloudstack_old,dasein-cloud/dasein-cloud-cloudstack
/** * Copyright (C) 2009-2013 enstratius, Inc. * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.dasein.cloud.cloudstack.compute; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.ProviderContext; import org.dasein.cloud.Requirement; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.Tag; import org.dasein.cloud.cloudstack.CSCloud; import org.dasein.cloud.cloudstack.CSException; import org.dasein.cloud.cloudstack.CSMethod; import org.dasein.cloud.cloudstack.CSServiceProvider; import org.dasein.cloud.cloudstack.CSTopology; import org.dasein.cloud.cloudstack.CSVersion; import org.dasein.cloud.cloudstack.Param; import org.dasein.cloud.cloudstack.network.Network; import org.dasein.cloud.cloudstack.network.SecurityGroup; import org.dasein.cloud.compute.AbstractVMSupport; import org.dasein.cloud.compute.Architecture; import org.dasein.cloud.compute.ImageClass; import org.dasein.cloud.compute.Platform; import org.dasein.cloud.compute.VMLaunchOptions; import org.dasein.cloud.compute.VirtualMachine; import org.dasein.cloud.compute.VirtualMachineProduct; import org.dasein.cloud.compute.VmState; import org.dasein.cloud.network.RawAddress; import org.dasein.cloud.util.APITrace; import org.dasein.util.CalendarWrapper; import org.dasein.util.uom.storage.Gigabyte; import org.dasein.util.uom.storage.Megabyte; import org.dasein.util.uom.storage.Storage; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class VirtualMachines extends AbstractVMSupport { static public final Logger logger = Logger.getLogger(VirtualMachines.class); static private final String DEPLOY_VIRTUAL_MACHINE = "deployVirtualMachine"; static private final String DESTROY_VIRTUAL_MACHINE = "destroyVirtualMachine"; static private final String LIST_VIRTUAL_MACHINES = "listVirtualMachines"; static private final String LIST_SERVICE_OFFERINGS = "listServiceOfferings"; static private final String REBOOT_VIRTUAL_MACHINE = "rebootVirtualMachine"; static private final String START_VIRTUAL_MACHINE = "startVirtualMachine"; static private final String STOP_VIRTUAL_MACHINE = "stopVirtualMachine"; static private Properties cloudMappings; static private Map<String,Map<String,String>> customNetworkMappings; static private Map<String,Map<String,Set<String>>> customServiceMappings; static private Map<String,Map<Architecture,Collection<VirtualMachineProduct>>> productCache = new HashMap<String, Map<Architecture, Collection<VirtualMachineProduct>>>(); private CSCloud provider; public VirtualMachines(CSCloud provider) { super(provider); this.provider = provider; } @Override public int getCostFactor(@Nonnull VmState state) throws InternalException, CloudException { return 100; } @Override public int getMaximumVirtualMachineCount() throws CloudException, InternalException { return -2; } @Override public @Nullable VirtualMachineProduct getProduct(@Nonnull String productId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.getProduct"); try { for( Architecture architecture : Architecture.values() ) { for( VirtualMachineProduct product : listProducts(architecture) ) { if( product.getProviderProductId().equals(productId) ) { return product; } } } if( logger.isDebugEnabled() ) { logger.debug("Unknown product ID for cloud.com: " + productId); } return null; } finally { APITrace.end(); } } @Override public @Nonnull String getProviderTermForServer(@Nonnull Locale locale) { return "virtual machine"; } @Override public @Nullable VirtualMachine getVirtualMachine(@Nonnull String serverId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.getVirtualMachine"); try { CSMethod method = new CSMethod(provider); try { Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("id", serverId)), LIST_VIRTUAL_MACHINES); NodeList matches = doc.getElementsByTagName("virtualmachine"); if( matches.getLength() < 1 ) { return null; } for( int i=0; i<matches.getLength(); i++ ) { VirtualMachine s = toVirtualMachine(matches.item(i)); if( s != null && s.getProviderVirtualMachineId().equals(serverId) ) { return s; } } } catch( CloudException e ) { if( e.getMessage().contains("does not exist") ) { return null; } throw e; } return null; } finally { APITrace.end(); } } @Override public @Nonnull Requirement identifyImageRequirement(@Nonnull ImageClass cls) throws CloudException, InternalException { return (cls.equals(ImageClass.MACHINE) ? Requirement.REQUIRED : Requirement.NONE); } @Override public @Nonnull Requirement identifyPasswordRequirement(Platform platform) throws CloudException, InternalException { return Requirement.NONE; } @Override public @Nonnull Requirement identifyRootVolumeRequirement() throws CloudException, InternalException { return Requirement.NONE; } @Override public @Nonnull Requirement identifyShellKeyRequirement(Platform platform) throws CloudException, InternalException { return Requirement.OPTIONAL; } @Override public @Nonnull Requirement identifyStaticIPRequirement() throws CloudException, InternalException { return Requirement.NONE; } @Override public @Nonnull Requirement identifyVlanRequirement() throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.identifyVlanRequirement"); try { if( provider.getServiceProvider().equals(CSServiceProvider.DATAPIPE) ) { return Requirement.NONE; } if( provider.getVersion().greaterThan(CSVersion.CS21) ) { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was set for this request"); } String regionId = ctx.getRegionId(); if( regionId == null ) { throw new CloudException("No region was set for this request"); } return (provider.getDataCenterServices().requiresNetwork(regionId) ? Requirement.REQUIRED : Requirement.OPTIONAL); } return Requirement.OPTIONAL; } finally { APITrace.end(); } } @Override public boolean isAPITerminationPreventable() throws CloudException, InternalException { return false; } @Override public boolean isBasicAnalyticsSupported() throws CloudException, InternalException { return false; } @Override public boolean isExtendedAnalyticsSupported() throws CloudException, InternalException { return false; } @Override public boolean isSubscribed() throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.isSubscribed"); try { CSMethod method = new CSMethod(provider); try { method.get(method.buildUrl(CSTopology.LIST_ZONES, new Param("available", "true")), CSTopology.LIST_ZONES); return true; } catch( CSException e ) { int code = e.getHttpCode(); if( code == HttpServletResponse.SC_FORBIDDEN || code == 401 || code == 531 ) { return false; } throw e; } catch( CloudException e ) { int code = e.getHttpCode(); if( code == HttpServletResponse.SC_FORBIDDEN || code == HttpServletResponse.SC_UNAUTHORIZED ) { return false; } throw e; } } finally { APITrace.end(); } } @Override public boolean isUserDataSupported() throws CloudException, InternalException { return true; } @Override public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions withLaunchOptions) throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.launch"); try { String id = withLaunchOptions.getStandardProductId(); VirtualMachineProduct product = getProduct(id); if( product == null ) { throw new CloudException("Invalid product ID: " + id); } if( provider.getVersion().greaterThan(CSVersion.CS21) ) { return launch22(withLaunchOptions.getMachineImageId(), product, withLaunchOptions.getDataCenterId(), withLaunchOptions.getFriendlyName(), withLaunchOptions.getBootstrapKey(), withLaunchOptions.getVlanId(), withLaunchOptions.getFirewallIds(), withLaunchOptions.getUserData()); } else { return launch21(withLaunchOptions.getMachineImageId(), product, withLaunchOptions.getDataCenterId(), withLaunchOptions.getFriendlyName()); } } finally { APITrace.end(); } } @Override @Deprecated @SuppressWarnings("deprecation") public @Nonnull VirtualMachine launch(@Nonnull String imageId, @Nonnull VirtualMachineProduct product, @Nonnull String inZoneId, @Nonnull String name, @Nonnull String description, @Nullable String usingKey, @Nullable String withVlanId, boolean withMonitoring, boolean asSandbox, @Nullable String[] protectedByFirewalls, @Nullable Tag ... tags) throws InternalException, CloudException { if( provider.getVersion().greaterThan(CSVersion.CS21) ) { StringBuilder userData = new StringBuilder(); if( tags != null && tags.length > 0 ) { for( Tag tag : tags ) { userData.append(tag.getKey()); userData.append("="); userData.append(tag.getValue()); userData.append("\n"); } } else { userData.append("created=Dasein Cloud\n"); } return launch22(imageId, product, inZoneId, name, usingKey, withVlanId, protectedByFirewalls, userData.toString()); } else { return launch21(imageId, product, inZoneId, name); } } private VirtualMachine launch21(String imageId, VirtualMachineProduct product, String inZoneId, String name) throws InternalException, CloudException { CSMethod method = new CSMethod(provider); return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, new Param("zoneId", getContext().getRegionId()), new Param("serviceOfferingId", product.getProviderProductId()), new Param("templateId", imageId), new Param("displayName", name) ), DEPLOY_VIRTUAL_MACHINE)); } private void load() { try { InputStream input = VirtualMachines.class.getResourceAsStream("/cloudMappings.cfg"); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); Properties properties = new Properties(); String line; while( (line = reader.readLine()) != null ) { if( line.startsWith("#") ) { continue; } int idx = line.indexOf('='); if( idx < 0 || line.endsWith("=") ) { continue; } String cloudUrl = line.substring(0, idx); String cloudId = line.substring(idx+1); properties.put(cloudUrl, cloudId); } cloudMappings = properties; } catch( Throwable ignore ) { // ignore } try { InputStream input = VirtualMachines.class.getResourceAsStream("/customNetworkMappings.cfg"); HashMap<String,Map<String,String>> mapping = new HashMap<String,Map<String,String>>(); Properties properties = new Properties(); properties.load(input); for( Object key : properties.keySet() ) { String[] trueKey = ((String)key).split(","); Map<String,String> current = mapping.get(trueKey[0]); if( current == null ) { current = new HashMap<String,String>(); mapping.put(trueKey[0], current); } current.put(trueKey[1], (String)properties.get(key)); } customNetworkMappings = mapping; } catch( Throwable ignore ) { // ignore } try { InputStream input = VirtualMachines.class.getResourceAsStream("/customServiceMappings.cfg"); HashMap<String,Map<String,Set<String>>> mapping = new HashMap<String,Map<String,Set<String>>>(); Properties properties = new Properties(); properties.load(input); for( Object key : properties.keySet() ) { String value = (String)properties.get(key); if( value != null ) { String[] trueKey = ((String)key).split(","); Map<String,Set<String>> tmp = mapping.get(trueKey[0]); if( tmp == null ) { tmp =new HashMap<String,Set<String>>(); mapping.put(trueKey[0], tmp); } TreeSet<String> m = new TreeSet<String>(); String[] offerings = value.split(","); if( offerings == null || offerings.length < 1 ) { m.add(value); } else { Collections.addAll(m, offerings); } tmp.put(trueKey[1], m); } } customServiceMappings = mapping; } catch( Throwable ignore ) { // ignore } } private @Nonnull VirtualMachine launch22(@Nonnull String imageId, @Nonnull VirtualMachineProduct product, @Nullable String inZoneId, @Nonnull String name, @Nullable String withKeypair, @Nullable String targetVlanId, @Nullable String[] protectedByFirewalls, @Nullable String userData) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); List<String> vlans = null; if( ctx == null ) { throw new InternalException("No context was provided for this request"); } String regionId = ctx.getRegionId(); if( regionId == null ) { throw new InternalException("No region is established for this request"); } String prdId = product.getProviderProductId(); if( customNetworkMappings == null ) { load(); } if( customNetworkMappings != null ) { String cloudId = cloudMappings.getProperty(ctx.getEndpoint()); if( cloudId != null ) { Map<String,String> map = customNetworkMappings.get(cloudId); if( map != null ) { String id = map.get(prdId); if( id != null ) { targetVlanId = id; } } } } if( targetVlanId != null && targetVlanId.length() < 1 ) { targetVlanId = null; } if( userData == null ) { userData = ""; } String securityGroupIds = null; Param[] params; if( protectedByFirewalls != null && protectedByFirewalls.length > 0 ) { StringBuilder str = new StringBuilder(); int idx = 0; for( String fw : protectedByFirewalls ) { fw = fw.trim(); if( !fw.equals("") ) { str.append(fw); if( (idx++) < protectedByFirewalls.length-1 ) { str.append(","); } } } securityGroupIds = str.toString(); } int count = 4; if( userData != null && userData.length() > 0 ) { count++; } if( withKeypair != null ) { count++; } if( targetVlanId == null ) { Network vlan = provider.getNetworkServices().getVlanSupport(); if( vlan != null && vlan.isSubscribed() ) { if( provider.getDataCenterServices().requiresNetwork(regionId) ) { vlans = vlan.findFreeNetworks(); } } } else { vlans = new ArrayList<String>(); vlans.add(targetVlanId); } if( vlans != null && vlans.size() > 0 ) { count++; } if( securityGroupIds != null && securityGroupIds.length() > 0 ) { if( !provider.getServiceProvider().equals(CSServiceProvider.DATAPIPE) && !provider.getDataCenterServices().supportsSecurityGroups(regionId, vlans == null || vlans.size() < 1) ) { securityGroupIds = null; } else { count++; } } else if( provider.getDataCenterServices().supportsSecurityGroups(regionId, vlans == null || vlans.size() < 1) ) { /* String sgId = null; if( withVlanId == null ) { Collection<Firewall> firewalls = provider.getNetworkServices().getFirewallSupport().list(); for( Firewall fw : firewalls ) { if( fw.getName().equalsIgnoreCase("default") && fw.getProviderVlanId() == null ) { sgId = fw.getProviderFirewallId(); break; } } if( sgId == null ) { try { sgId = provider.getNetworkServices().getFirewallSupport().create("default", "Default security group"); } catch( Throwable t ) { logger.warn("Unable to create a default security group, gonna try anyways: " + t.getMessage()); } } if( sgId != null ) { securityGroupIds = sgId; } } else { Collection<Firewall> firewalls = provider.getNetworkServices().getFirewallSupport().list(); for( Firewall fw : firewalls ) { if( (fw.getName().equalsIgnoreCase("default") || fw.getName().equalsIgnoreCase("default-" + withVlanId)) && withVlanId.equals(fw.getProviderVlanId()) ) { sgId = fw.getProviderFirewallId(); break; } } if( sgId == null ) { try { sgId = provider.getNetworkServices().getFirewallSupport().createInVLAN("default-" + withVlanId, "Default " + withVlanId + " security group", withVlanId); } catch( Throwable t ) { logger.warn("Unable to create a default security group, gonna try anyways: " + t.getMessage()); } } } if( sgId != null ) { securityGroupIds = sgId; count++; } */ } params = new Param[count]; params[0] = new Param("zoneId", getContext().getRegionId()); params[1] = new Param("serviceOfferingId", prdId); params[2] = new Param("templateId", imageId); params[3] = new Param("displayName", name); int i = 4; if( userData != null && userData.length() > 0 ) { try { params[i++] = new Param("userdata", new String(Base64.encodeBase64(userData.getBytes("utf-8")), "utf-8")); } catch( UnsupportedEncodingException e ) { e.printStackTrace(); } } if( withKeypair != null ) { params[i++] = new Param("keypair", withKeypair); } if( securityGroupIds != null && securityGroupIds.length() > 0 ) { params[i++] = new Param("securitygroupids", securityGroupIds); } if( vlans != null && vlans.size() > 0 ) { CloudException lastError = null; for( String withVlanId : vlans ) { params[i] = new Param("networkIds", withVlanId); try { CSMethod method = new CSMethod(provider); return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, params), DEPLOY_VIRTUAL_MACHINE)); } catch( CloudException e ) { if( e.getMessage().contains("sufficient address capacity") ) { lastError = e; continue; } throw e; } } if( lastError == null ) { throw lastError; } throw new CloudException("Unable to identify a network into which a VM can be launched"); } else { CSMethod method = new CSMethod(provider); return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, params), DEPLOY_VIRTUAL_MACHINE)); } } private @Nonnull VirtualMachine launch(@Nonnull Document doc) throws InternalException, CloudException { NodeList matches = doc.getElementsByTagName("deployvirtualmachineresponse"); String serverId = null; for( int i=0; i<matches.getLength(); i++ ) { NodeList attrs = matches.item(i).getChildNodes(); for( int j=0; j<attrs.getLength(); j++ ) { Node node = attrs.item(j); if( node != null && (node.getNodeName().equalsIgnoreCase("virtualmachineid") || node.getNodeName().equalsIgnoreCase("id")) ) { serverId = node.getFirstChild().getNodeValue(); break; } } if( serverId != null ) { break; } } if( serverId == null ) { throw new CloudException("Could not launch server"); } // TODO: very odd logic below; figure out what it thinks it is doing VirtualMachine vm = null; Document responseDoc = provider.waitForJob(doc, "Launch Server"); //parse vm from job completion response to capture vm passwords on initial launch. if (responseDoc != null){ NodeList nodeList = responseDoc.getElementsByTagName("virtualmachine"); if (nodeList.getLength() > 0) { Node virtualMachine = nodeList.item(0); vm = toVirtualMachine(virtualMachine); if( vm != null ) { return vm; } } } if (vm == null){ long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE*20); while( System.currentTimeMillis() < timeout ) { try { vm = getVirtualMachine(serverId); } catch( Throwable ignore ) { } if( vm != null ) { return vm; } try { Thread.sleep(5000L); } catch( InterruptedException ignore ) { } } } vm = getVirtualMachine(serverId); if( vm == null ) { throw new CloudException("No virtual machine provided: " + serverId); } return vm; } @Override public @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listFirewalls"); try { SecurityGroup support = provider.getNetworkServices().getFirewallSupport(); if( support == null ) { return Collections.emptyList(); } return support.listFirewallsForVM(vmId); } finally { APITrace.end(); } } private void setFirewalls(@Nonnull VirtualMachine vm) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.setFirewalls"); try { SecurityGroup support = provider.getNetworkServices().getFirewallSupport(); if( support == null ) { return; } ArrayList<String> ids = new ArrayList<String>(); for( String id : support.listFirewallsForVM(vm.getProviderVirtualMachineId()) ) { ids.add(id); } vm.setProviderFirewallIds(ids.toArray(new String[ids.size()])); } finally { APITrace.end(); } } @Override public @Nonnull Iterable<VirtualMachineProduct> listProducts(@Nonnull Architecture architecture) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listProducts"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was configured for this request"); } Map<Architecture,Collection<VirtualMachineProduct>> cached; //String endpoint = provider.getContext().getEndpoint(); // No longer caching by endpoint- different accounts may return different products... // so we'll cache by account instead. String accountId = provider.getContext().getAccountNumber(); if( productCache.containsKey(accountId) ) { cached = productCache.get(accountId); if( cached.containsKey(architecture) ) { Collection<VirtualMachineProduct> products = cached.get(architecture); if( products != null ) { return products; } } } else { cached = new HashMap<Architecture, Collection<VirtualMachineProduct>>(); productCache.put(accountId, cached); } List<VirtualMachineProduct> products; Set<String> mapping = null; if( customServiceMappings == null ) { load(); } if( customServiceMappings != null ) { String cloudId = cloudMappings.getProperty(provider.getContext().getEndpoint()); if( cloudId != null ) { Map<String,Set<String>> map = customServiceMappings.get(cloudId); if( map != null ) { mapping = map.get(provider.getContext().getRegionId()); } } } products = new ArrayList<VirtualMachineProduct>(); CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(LIST_SERVICE_OFFERINGS, new Param("zoneId", ctx.getRegionId())), LIST_SERVICE_OFFERINGS); NodeList matches = doc.getElementsByTagName("serviceoffering"); for( int i=0; i<matches.getLength(); i++ ) { String id = null, name = null; Node node = matches.item(i); NodeList attributes; int memory = 0; int cpu = 0; attributes = node.getChildNodes(); for( int j=0; j<attributes.getLength(); j++ ) { Node n = attributes.item(j); String value; if( n.getChildNodes().getLength() > 0 ) { value = n.getFirstChild().getNodeValue(); } else { value = null; } if( n.getNodeName().equals("id") ) { id = value; } else if( n.getNodeName().equals("name") ) { name = value; } else if( n.getNodeName().equals("cpunumber") ) { cpu = Integer.parseInt(value); } else if( n.getNodeName().equals("memory") ) { memory = Integer.parseInt(value); } if( id != null && name != null && cpu > 0 && memory > 0 ) { break; } } if( id != null ) { if( mapping == null || mapping.contains(id) ) { VirtualMachineProduct product; product = new VirtualMachineProduct(); product.setProviderProductId(id); product.setName(name + " (" + cpu + " CPU/" + memory + "MB RAM)"); product.setDescription(name + " (" + cpu + " CPU/" + memory + "MB RAM)"); product.setRamSize(new Storage<Megabyte>(memory, Storage.MEGABYTE)); product.setCpuCount(cpu); product.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE)); products.add(product); } } } cached.put(architecture, products); return products; } finally { APITrace.end(); } } private transient Collection<Architecture> architectures; @Override public Iterable<Architecture> listSupportedArchitectures() throws InternalException, CloudException { if( architectures == null ) { ArrayList<Architecture> a = new ArrayList<Architecture>(); a.add(Architecture.I32); a.add(Architecture.I64); architectures = Collections.unmodifiableList(a); } return architectures; } @Override public @Nonnull Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listVirtualMachineStatus"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was specified for this request"); } CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("zoneId", ctx.getRegionId())), LIST_VIRTUAL_MACHINES); ArrayList<ResourceStatus> servers = new ArrayList<ResourceStatus>(); NodeList matches = doc.getElementsByTagName("virtualmachine"); for( int i=0; i<matches.getLength(); i++ ) { Node node = matches.item(i); if( node != null ) { ResourceStatus vm = toStatus(node); if( vm != null ) { servers.add(vm); } } } return servers; } finally { APITrace.end(); } } @Override public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listVirtualMachines"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was specified for this request"); } CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("zoneId", ctx.getRegionId())), LIST_VIRTUAL_MACHINES); ArrayList<VirtualMachine> servers = new ArrayList<VirtualMachine>(); NodeList matches = doc.getElementsByTagName("virtualmachine"); for( int i=0; i<matches.getLength(); i++ ) { Node node = matches.item(i); if( node != null ) { VirtualMachine vm = toVirtualMachine(node); if( vm != null ) { servers.add(vm); } } } return servers; } finally { APITrace.end(); } } @Override public void reboot(@Nonnull String serverId) throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.reboot"); try { CSMethod method = new CSMethod(provider); method.get(method.buildUrl(REBOOT_VIRTUAL_MACHINE, new Param("id", serverId)), REBOOT_VIRTUAL_MACHINE); } finally { APITrace.end(); } } @Override public void start(@Nonnull String serverId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.start"); try { CSMethod method = new CSMethod(provider); method.get(method.buildUrl(START_VIRTUAL_MACHINE, new Param("id", serverId)), START_VIRTUAL_MACHINE); } finally { APITrace.end(); } } @Override public void stop(@Nonnull String vmId, boolean force) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.stop"); try { CSMethod method = new CSMethod(provider); method.get(method.buildUrl(STOP_VIRTUAL_MACHINE, new Param("id", vmId), new Param("forced", String.valueOf(force))), STOP_VIRTUAL_MACHINE); } finally { APITrace.end(); } } @Override public boolean supportsPauseUnpause(@Nonnull VirtualMachine vm) { return false; } @Override public boolean supportsStartStop(@Nonnull VirtualMachine vm) { return true; } @Override public boolean supportsSuspendResume(@Nonnull VirtualMachine vm) { return false; } @Override public void terminate(@Nonnull String serverId, @Nullable String explanation) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.terminate"); try { CSMethod method = new CSMethod(provider); method.get(method.buildUrl(DESTROY_VIRTUAL_MACHINE, new Param("id", serverId)), DESTROY_VIRTUAL_MACHINE); } finally { APITrace.end(); } } private @Nullable ResourceStatus toStatus(@Nullable Node node) throws CloudException, InternalException { if( node == null ) { return null; } NodeList attributes = node.getChildNodes(); VmState state = null; String serverId = null; for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); String name = attribute.getNodeName().toLowerCase(); String value; if( attribute.getChildNodes().getLength() > 0 ) { value = attribute.getFirstChild().getNodeValue(); } else { value = null; } if( name.equals("virtualmachineid") || name.equals("id") ) { serverId = value; } else if( name.equals("state") ) { if( value == null ) { state = VmState.PENDING; } else if( value.equalsIgnoreCase("stopped") ) { state = VmState.STOPPED; } else if( value.equalsIgnoreCase("running") ) { state = VmState.RUNNING; } else if( value.equalsIgnoreCase("stopping") ) { state = VmState.STOPPING; } else if( value.equalsIgnoreCase("starting") ) { state = VmState.PENDING; } else if( value.equalsIgnoreCase("creating") ) { state = VmState.PENDING; } else if( value.equalsIgnoreCase("migrating") ) { state = VmState.REBOOTING; } else if( value.equalsIgnoreCase("destroyed") ) { state = VmState.TERMINATED; } else if( value.equalsIgnoreCase("error") ) { logger.warn("VM is in an error state."); return null; } else if( value.equalsIgnoreCase("expunging") ) { state = VmState.TERMINATED; } else if( value.equalsIgnoreCase("ha") ) { state = VmState.REBOOTING; } else { throw new CloudException("Unexpected server state: " + value); } } if( serverId != null && state != null ) { break; } } if( serverId == null ) { return null; } if( state == null ) { state = VmState.PENDING; } return new ResourceStatus(serverId, state); } private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException { if( node == null ) { return null; } HashMap<String,String> properties = new HashMap<String,String>(); VirtualMachine server = new VirtualMachine(); NodeList attributes = node.getChildNodes(); String productId = null; server.setTags(properties); server.setArchitecture(Architecture.I64); server.setProviderOwnerId(provider.getContext().getAccountNumber()); server.setClonable(false); server.setImagable(false); server.setPausable(true); server.setPersistent(true); for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); String name = attribute.getNodeName().toLowerCase(); String value; if( attribute.getChildNodes().getLength() > 0 ) { value = attribute.getFirstChild().getNodeValue(); } else { value = null; } if( name.equals("virtualmachineid") || name.equals("id") ) { server.setProviderVirtualMachineId(value); } else if( name.equals("name") ) { server.setDescription(value); } /* else if( name.equals("haenable") ) { server.setPersistent(value != null && value.equalsIgnoreCase("true")); } */ else if( name.equals("displayname") ) { server.setName(value); } else if( name.equals("ipaddress") ) { // v2.1 if( value != null ) { server.setPrivateAddresses(new RawAddress(value)); } server.setPrivateDnsAddress(value); } else if( name.equals("password") ) { server.setRootPassword(value); } else if( name.equals("nic") ) { // v2.2 if( attribute.hasChildNodes() ) { NodeList parts = attribute.getChildNodes(); String addr = null; for( int j=0; j<parts.getLength(); j++ ) { Node part = parts.item(j); if( part.getNodeName().equalsIgnoreCase("ipaddress") ) { if( part.hasChildNodes() ) { addr = part.getFirstChild().getNodeValue(); if( addr != null ) { addr = addr.trim(); } } } else if( part.getNodeName().equalsIgnoreCase("networkid") ) { server.setProviderVlanId(part.getFirstChild().getNodeValue().trim()); } } if( addr != null ) { boolean pub = false; if( !addr.startsWith("10.") && !addr.startsWith("192.168.") ) { if( addr.startsWith("172.") ) { String[] nums = addr.split("\\."); if( nums.length != 4 ) { pub = true; } else { try { int x = Integer.parseInt(nums[1]); if( x < 16 || x > 31 ) { pub = true; } } catch( NumberFormatException ignore ) { // ignore } } } else { pub = true; } } if( pub ) { server.setPublicAddresses(new RawAddress(addr)); if( server.getPublicDnsAddress() == null ) { server.setPublicDnsAddress(addr); } } else { server.setPrivateAddresses(new RawAddress(addr)); if( server.getPrivateDnsAddress() == null ) { server.setPrivateDnsAddress(addr); } } } } } else if( name.equals("osarchitecture") ) { if( value != null && value.equals("32") ) { server.setArchitecture(Architecture.I32); } else { server.setArchitecture(Architecture.I64); } } else if( name.equals("created") ) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278 try { server.setCreationTimestamp(df.parse(value).getTime()); } catch( ParseException e ) { logger.warn("Invalid date: " + value); server.setLastBootTimestamp(0L); } } else if( name.equals("state") ) { VmState state; //(Running, Stopped, Stopping, Starting, Creating, Migrating, HA). if( value.equalsIgnoreCase("stopped") ) { state = VmState.STOPPED; server.setImagable(true); } else if( value.equalsIgnoreCase("running") ) { state = VmState.RUNNING; } else if( value.equalsIgnoreCase("stopping") ) { state = VmState.STOPPING; } else if( value.equalsIgnoreCase("starting") ) { state = VmState.PENDING; } else if( value.equalsIgnoreCase("creating") ) { state = VmState.PENDING; } else if( value.equalsIgnoreCase("migrating") ) { state = VmState.REBOOTING; } else if( value.equalsIgnoreCase("destroyed") ) { state = VmState.TERMINATED; } else if( value.equalsIgnoreCase("error") ) { logger.warn("VM is in an error state."); return null; } else if( value.equalsIgnoreCase("expunging") ) { state = VmState.TERMINATED; } else if( value.equalsIgnoreCase("ha") ) { state = VmState.REBOOTING; } else { throw new CloudException("Unexpected server state: " + value); } server.setCurrentState(state); } else if( name.equals("zoneid") ) { server.setProviderRegionId(value); server.setProviderDataCenterId(value); } else if( name.equals("templateid") ) { server.setProviderMachineImageId(value); } else if( name.equals("templatename") ) { server.setPlatform(Platform.guess(value)); } else if( name.equals("serviceofferingid") ) { productId = value; } else if( value != null ) { properties.put(name, value); } } if( server.getName() == null ) { server.setName(server.getProviderVirtualMachineId()); } if( server.getDescription() == null ) { server.setDescription(server.getName()); } server.setProviderAssignedIpAddressId(null); if( server.getProviderRegionId() == null ) { server.setProviderRegionId(provider.getContext().getRegionId()); } if( server.getProviderDataCenterId() == null ) { server.setProviderDataCenterId(provider.getContext().getRegionId()); } if( productId != null ) { server.setProductId(productId); } setFirewalls(server); return server; } }
src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java
/** * Copyright (C) 2009-2013 enstratius, Inc. * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.dasein.cloud.cloudstack.compute; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.ProviderContext; import org.dasein.cloud.Requirement; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.Tag; import org.dasein.cloud.cloudstack.CSCloud; import org.dasein.cloud.cloudstack.CSException; import org.dasein.cloud.cloudstack.CSMethod; import org.dasein.cloud.cloudstack.CSServiceProvider; import org.dasein.cloud.cloudstack.CSTopology; import org.dasein.cloud.cloudstack.CSVersion; import org.dasein.cloud.cloudstack.Param; import org.dasein.cloud.cloudstack.network.Network; import org.dasein.cloud.cloudstack.network.SecurityGroup; import org.dasein.cloud.compute.AbstractVMSupport; import org.dasein.cloud.compute.Architecture; import org.dasein.cloud.compute.ImageClass; import org.dasein.cloud.compute.Platform; import org.dasein.cloud.compute.VMLaunchOptions; import org.dasein.cloud.compute.VirtualMachine; import org.dasein.cloud.compute.VirtualMachineProduct; import org.dasein.cloud.compute.VmState; import org.dasein.cloud.network.RawAddress; import org.dasein.cloud.util.APITrace; import org.dasein.util.CalendarWrapper; import org.dasein.util.uom.storage.Gigabyte; import org.dasein.util.uom.storage.Megabyte; import org.dasein.util.uom.storage.Storage; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class VirtualMachines extends AbstractVMSupport { static public final Logger logger = Logger.getLogger(VirtualMachines.class); static private final String DEPLOY_VIRTUAL_MACHINE = "deployVirtualMachine"; static private final String DESTROY_VIRTUAL_MACHINE = "destroyVirtualMachine"; static private final String LIST_VIRTUAL_MACHINES = "listVirtualMachines"; static private final String LIST_SERVICE_OFFERINGS = "listServiceOfferings"; static private final String REBOOT_VIRTUAL_MACHINE = "rebootVirtualMachine"; static private final String START_VIRTUAL_MACHINE = "startVirtualMachine"; static private final String STOP_VIRTUAL_MACHINE = "stopVirtualMachine"; static private Properties cloudMappings; static private Map<String,Map<String,String>> customNetworkMappings; static private Map<String,Map<String,Set<String>>> customServiceMappings; static private Map<String,Map<Architecture,Collection<VirtualMachineProduct>>> productCache = new HashMap<String, Map<Architecture, Collection<VirtualMachineProduct>>>(); private CSCloud provider; public VirtualMachines(CSCloud provider) { super(provider); this.provider = provider; } @Override public int getCostFactor(@Nonnull VmState state) throws InternalException, CloudException { return 100; } @Override public int getMaximumVirtualMachineCount() throws CloudException, InternalException { return -2; } @Override public @Nullable VirtualMachineProduct getProduct(@Nonnull String productId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.getProduct"); try { for( Architecture architecture : Architecture.values() ) { for( VirtualMachineProduct product : listProducts(architecture) ) { if( product.getProviderProductId().equals(productId) ) { return product; } } } if( logger.isDebugEnabled() ) { logger.debug("Unknown product ID for cloud.com: " + productId); } return null; } finally { APITrace.end(); } } @Override public @Nonnull String getProviderTermForServer(@Nonnull Locale locale) { return "virtual machine"; } @Override public @Nullable VirtualMachine getVirtualMachine(@Nonnull String serverId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.getVirtualMachine"); try { CSMethod method = new CSMethod(provider); try { Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("id", serverId)), LIST_VIRTUAL_MACHINES); NodeList matches = doc.getElementsByTagName("virtualmachine"); if( matches.getLength() < 1 ) { return null; } for( int i=0; i<matches.getLength(); i++ ) { VirtualMachine s = toVirtualMachine(matches.item(i)); if( s != null && s.getProviderVirtualMachineId().equals(serverId) ) { return s; } } } catch( CloudException e ) { if( e.getMessage().contains("does not exist") ) { return null; } throw e; } return null; } finally { APITrace.end(); } } @Override public @Nonnull Requirement identifyImageRequirement(@Nonnull ImageClass cls) throws CloudException, InternalException { return (cls.equals(ImageClass.MACHINE) ? Requirement.REQUIRED : Requirement.NONE); } @Override public @Nonnull Requirement identifyPasswordRequirement(Platform platform) throws CloudException, InternalException { return Requirement.NONE; } @Override public @Nonnull Requirement identifyRootVolumeRequirement() throws CloudException, InternalException { return Requirement.NONE; } @Override public @Nonnull Requirement identifyShellKeyRequirement(Platform platform) throws CloudException, InternalException { return Requirement.OPTIONAL; } @Override public @Nonnull Requirement identifyStaticIPRequirement() throws CloudException, InternalException { return Requirement.NONE; } @Override public @Nonnull Requirement identifyVlanRequirement() throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.identifyVlanRequirement"); try { if( provider.getServiceProvider().equals(CSServiceProvider.DATAPIPE) ) { return Requirement.NONE; } if( provider.getVersion().greaterThan(CSVersion.CS21) ) { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was set for this request"); } String regionId = ctx.getRegionId(); if( regionId == null ) { throw new CloudException("No region was set for this request"); } return (provider.getDataCenterServices().requiresNetwork(regionId) ? Requirement.REQUIRED : Requirement.OPTIONAL); } return Requirement.OPTIONAL; } finally { APITrace.end(); } } @Override public boolean isAPITerminationPreventable() throws CloudException, InternalException { return false; } @Override public boolean isBasicAnalyticsSupported() throws CloudException, InternalException { return false; } @Override public boolean isExtendedAnalyticsSupported() throws CloudException, InternalException { return false; } @Override public boolean isSubscribed() throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.isSubscribed"); try { CSMethod method = new CSMethod(provider); try { method.get(method.buildUrl(CSTopology.LIST_ZONES, new Param("available", "true")), CSTopology.LIST_ZONES); return true; } catch( CSException e ) { int code = e.getHttpCode(); if( code == HttpServletResponse.SC_FORBIDDEN || code == 401 || code == 531 ) { return false; } throw e; } catch( CloudException e ) { int code = e.getHttpCode(); if( code == HttpServletResponse.SC_FORBIDDEN || code == HttpServletResponse.SC_UNAUTHORIZED ) { return false; } throw e; } } finally { APITrace.end(); } } @Override public boolean isUserDataSupported() throws CloudException, InternalException { return true; } @Override public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions withLaunchOptions) throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.launch"); try { String id = withLaunchOptions.getStandardProductId(); VirtualMachineProduct product = getProduct(id); if( product == null ) { throw new CloudException("Invalid product ID: " + id); } if( provider.getVersion().greaterThan(CSVersion.CS21) ) { return launch22(withLaunchOptions.getMachineImageId(), product, withLaunchOptions.getDataCenterId(), withLaunchOptions.getFriendlyName(), withLaunchOptions.getBootstrapKey(), withLaunchOptions.getVlanId(), withLaunchOptions.getFirewallIds(), withLaunchOptions.getUserData()); } else { return launch21(withLaunchOptions.getMachineImageId(), product, withLaunchOptions.getDataCenterId(), withLaunchOptions.getFriendlyName()); } } finally { APITrace.end(); } } @Override @Deprecated @SuppressWarnings("deprecation") public @Nonnull VirtualMachine launch(@Nonnull String imageId, @Nonnull VirtualMachineProduct product, @Nonnull String inZoneId, @Nonnull String name, @Nonnull String description, @Nullable String usingKey, @Nullable String withVlanId, boolean withMonitoring, boolean asSandbox, @Nullable String[] protectedByFirewalls, @Nullable Tag ... tags) throws InternalException, CloudException { if( provider.getVersion().greaterThan(CSVersion.CS21) ) { StringBuilder userData = new StringBuilder(); if( tags != null && tags.length > 0 ) { for( Tag tag : tags ) { userData.append(tag.getKey()); userData.append("="); userData.append(tag.getValue()); userData.append("\n"); } } else { userData.append("created=Dasein Cloud\n"); } return launch22(imageId, product, inZoneId, name, usingKey, withVlanId, protectedByFirewalls, userData.toString()); } else { return launch21(imageId, product, inZoneId, name); } } private VirtualMachine launch21(String imageId, VirtualMachineProduct product, String inZoneId, String name) throws InternalException, CloudException { CSMethod method = new CSMethod(provider); return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, new Param("zoneId", getContext().getRegionId()), new Param("serviceOfferingId", product.getProviderProductId()), new Param("templateId", imageId), new Param("displayName", name) ), DEPLOY_VIRTUAL_MACHINE)); } private void load() { try { InputStream input = VirtualMachines.class.getResourceAsStream("/cloudMappings.cfg"); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); Properties properties = new Properties(); String line; while( (line = reader.readLine()) != null ) { if( line.startsWith("#") ) { continue; } int idx = line.indexOf('='); if( idx < 0 || line.endsWith("=") ) { continue; } String cloudUrl = line.substring(0, idx); String cloudId = line.substring(idx+1); properties.put(cloudUrl, cloudId); } cloudMappings = properties; } catch( Throwable ignore ) { // ignore } try { InputStream input = VirtualMachines.class.getResourceAsStream("/customNetworkMappings.cfg"); HashMap<String,Map<String,String>> mapping = new HashMap<String,Map<String,String>>(); Properties properties = new Properties(); properties.load(input); for( Object key : properties.keySet() ) { String[] trueKey = ((String)key).split(","); Map<String,String> current = mapping.get(trueKey[0]); if( current == null ) { current = new HashMap<String,String>(); mapping.put(trueKey[0], current); } current.put(trueKey[1], (String)properties.get(key)); } customNetworkMappings = mapping; } catch( Throwable ignore ) { // ignore } try { InputStream input = VirtualMachines.class.getResourceAsStream("/customServiceMappings.cfg"); HashMap<String,Map<String,Set<String>>> mapping = new HashMap<String,Map<String,Set<String>>>(); Properties properties = new Properties(); properties.load(input); for( Object key : properties.keySet() ) { String value = (String)properties.get(key); if( value != null ) { String[] trueKey = ((String)key).split(","); Map<String,Set<String>> tmp = mapping.get(trueKey[0]); if( tmp == null ) { tmp =new HashMap<String,Set<String>>(); mapping.put(trueKey[0], tmp); } TreeSet<String> m = new TreeSet<String>(); String[] offerings = value.split(","); if( offerings == null || offerings.length < 1 ) { m.add(value); } else { Collections.addAll(m, offerings); } tmp.put(trueKey[1], m); } } customServiceMappings = mapping; } catch( Throwable ignore ) { // ignore } } private @Nonnull VirtualMachine launch22(@Nonnull String imageId, @Nonnull VirtualMachineProduct product, @Nullable String inZoneId, @Nonnull String name, @Nullable String withKeypair, @Nullable String targetVlanId, @Nullable String[] protectedByFirewalls, @Nullable String userData) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); List<String> vlans = null; if( ctx == null ) { throw new InternalException("No context was provided for this request"); } String regionId = ctx.getRegionId(); if( regionId == null ) { throw new InternalException("No region is established for this request"); } String prdId = product.getProviderProductId(); if( customNetworkMappings == null ) { load(); } if( customNetworkMappings != null ) { String cloudId = cloudMappings.getProperty(ctx.getEndpoint()); if( cloudId != null ) { Map<String,String> map = customNetworkMappings.get(cloudId); if( map != null ) { String id = map.get(prdId); if( id != null ) { targetVlanId = id; } } } } if( targetVlanId != null && targetVlanId.length() < 1 ) { targetVlanId = null; } if( userData == null ) { userData = ""; } String securityGroupIds = null; Param[] params; if( protectedByFirewalls != null && protectedByFirewalls.length > 0 ) { StringBuilder str = new StringBuilder(); int idx = 0; for( String fw : protectedByFirewalls ) { fw = fw.trim(); if( !fw.equals("") ) { str.append(fw); if( (idx++) < protectedByFirewalls.length-1 ) { str.append(","); } } } securityGroupIds = str.toString(); } int count = 4; if( userData != null && userData.length() > 0 ) { count++; } if( withKeypair != null ) { count++; } if( targetVlanId == null ) { Network vlan = provider.getNetworkServices().getVlanSupport(); if( vlan != null && vlan.isSubscribed() ) { if( provider.getDataCenterServices().requiresNetwork(regionId) ) { vlans = vlan.findFreeNetworks(); } } } else { vlans = new ArrayList<String>(); vlans.add(targetVlanId); } if( vlans != null && vlans.size() > 0 ) { count++; } if( securityGroupIds != null && securityGroupIds.length() > 0 ) { if( !provider.getServiceProvider().equals(CSServiceProvider.DATAPIPE) && !provider.getDataCenterServices().supportsSecurityGroups(regionId, vlans == null || vlans.size() < 1) ) { securityGroupIds = null; } else { count++; } } else if( provider.getDataCenterServices().supportsSecurityGroups(regionId, vlans == null || vlans.size() < 1) ) { /* String sgId = null; if( withVlanId == null ) { Collection<Firewall> firewalls = provider.getNetworkServices().getFirewallSupport().list(); for( Firewall fw : firewalls ) { if( fw.getName().equalsIgnoreCase("default") && fw.getProviderVlanId() == null ) { sgId = fw.getProviderFirewallId(); break; } } if( sgId == null ) { try { sgId = provider.getNetworkServices().getFirewallSupport().create("default", "Default security group"); } catch( Throwable t ) { logger.warn("Unable to create a default security group, gonna try anyways: " + t.getMessage()); } } if( sgId != null ) { securityGroupIds = sgId; } } else { Collection<Firewall> firewalls = provider.getNetworkServices().getFirewallSupport().list(); for( Firewall fw : firewalls ) { if( (fw.getName().equalsIgnoreCase("default") || fw.getName().equalsIgnoreCase("default-" + withVlanId)) && withVlanId.equals(fw.getProviderVlanId()) ) { sgId = fw.getProviderFirewallId(); break; } } if( sgId == null ) { try { sgId = provider.getNetworkServices().getFirewallSupport().createInVLAN("default-" + withVlanId, "Default " + withVlanId + " security group", withVlanId); } catch( Throwable t ) { logger.warn("Unable to create a default security group, gonna try anyways: " + t.getMessage()); } } } if( sgId != null ) { securityGroupIds = sgId; count++; } */ } params = new Param[count]; params[0] = new Param("zoneId", getContext().getRegionId()); params[1] = new Param("serviceOfferingId", prdId); params[2] = new Param("templateId", imageId); params[3] = new Param("displayName", name); int i = 4; if( userData != null && userData.length() > 0 ) { try { params[i++] = new Param("userdata", new String(Base64.encodeBase64(userData.getBytes("utf-8")), "utf-8")); } catch( UnsupportedEncodingException e ) { e.printStackTrace(); } } if( withKeypair != null ) { params[i++] = new Param("keypair", withKeypair); } if( securityGroupIds != null && securityGroupIds.length() > 0 ) { params[i++] = new Param("securitygroupids", securityGroupIds); } if( vlans != null && vlans.size() > 0 ) { CloudException lastError = null; for( String withVlanId : vlans ) { params[i] = new Param("networkIds", withVlanId); try { CSMethod method = new CSMethod(provider); return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, params), DEPLOY_VIRTUAL_MACHINE)); } catch( CloudException e ) { if( e.getMessage().contains("sufficient address capacity") ) { lastError = e; continue; } throw e; } } if( lastError == null ) { throw lastError; } throw new CloudException("Unable to identify a network into which a VM can be launched"); } else { CSMethod method = new CSMethod(provider); return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, params), DEPLOY_VIRTUAL_MACHINE)); } } private @Nonnull VirtualMachine launch(@Nonnull Document doc) throws InternalException, CloudException { NodeList matches = doc.getElementsByTagName("deployvirtualmachineresponse"); String serverId = null; for( int i=0; i<matches.getLength(); i++ ) { NodeList attrs = matches.item(i).getChildNodes(); for( int j=0; j<attrs.getLength(); j++ ) { Node node = attrs.item(j); if( node != null && (node.getNodeName().equalsIgnoreCase("virtualmachineid") || node.getNodeName().equalsIgnoreCase("id")) ) { serverId = node.getFirstChild().getNodeValue(); break; } } if( serverId != null ) { break; } } if( serverId == null ) { throw new CloudException("Could not launch server"); } // TODO: very odd logic below; figure out what it thinks it is doing long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE*20); VirtualMachine vm = null; while( System.currentTimeMillis() < timeout ) { try { vm = getVirtualMachine(serverId); } catch( Throwable ignore ) { } if( vm != null ) { return vm; } try { Thread.sleep(5000L); } catch( InterruptedException ignore ) { } } provider.waitForJob(doc, "Launch Server"); vm = getVirtualMachine(serverId); if( vm == null ) { throw new CloudException("No virtual machine provided: " + serverId); } return vm; } @Override public @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listFirewalls"); try { SecurityGroup support = provider.getNetworkServices().getFirewallSupport(); if( support == null ) { return Collections.emptyList(); } return support.listFirewallsForVM(vmId); } finally { APITrace.end(); } } private void setFirewalls(@Nonnull VirtualMachine vm) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.setFirewalls"); try { SecurityGroup support = provider.getNetworkServices().getFirewallSupport(); if( support == null ) { return; } ArrayList<String> ids = new ArrayList<String>(); for( String id : support.listFirewallsForVM(vm.getProviderVirtualMachineId()) ) { ids.add(id); } vm.setProviderFirewallIds(ids.toArray(new String[ids.size()])); } finally { APITrace.end(); } } @Override public @Nonnull Iterable<VirtualMachineProduct> listProducts(@Nonnull Architecture architecture) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listProducts"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was configured for this request"); } Map<Architecture,Collection<VirtualMachineProduct>> cached; //String endpoint = provider.getContext().getEndpoint(); // No longer caching by endpoint- different accounts may return different products... // so we'll cache by account instead. String accountId = provider.getContext().getAccountNumber(); if( productCache.containsKey(accountId) ) { cached = productCache.get(accountId); if( cached.containsKey(architecture) ) { Collection<VirtualMachineProduct> products = cached.get(architecture); if( products != null ) { return products; } } } else { cached = new HashMap<Architecture, Collection<VirtualMachineProduct>>(); productCache.put(accountId, cached); } List<VirtualMachineProduct> products; Set<String> mapping = null; if( customServiceMappings == null ) { load(); } if( customServiceMappings != null ) { String cloudId = cloudMappings.getProperty(provider.getContext().getEndpoint()); if( cloudId != null ) { Map<String,Set<String>> map = customServiceMappings.get(cloudId); if( map != null ) { mapping = map.get(provider.getContext().getRegionId()); } } } products = new ArrayList<VirtualMachineProduct>(); CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(LIST_SERVICE_OFFERINGS, new Param("zoneId", ctx.getRegionId())), LIST_SERVICE_OFFERINGS); NodeList matches = doc.getElementsByTagName("serviceoffering"); for( int i=0; i<matches.getLength(); i++ ) { String id = null, name = null; Node node = matches.item(i); NodeList attributes; int memory = 0; int cpu = 0; attributes = node.getChildNodes(); for( int j=0; j<attributes.getLength(); j++ ) { Node n = attributes.item(j); String value; if( n.getChildNodes().getLength() > 0 ) { value = n.getFirstChild().getNodeValue(); } else { value = null; } if( n.getNodeName().equals("id") ) { id = value; } else if( n.getNodeName().equals("name") ) { name = value; } else if( n.getNodeName().equals("cpunumber") ) { cpu = Integer.parseInt(value); } else if( n.getNodeName().equals("memory") ) { memory = Integer.parseInt(value); } if( id != null && name != null && cpu > 0 && memory > 0 ) { break; } } if( id != null ) { if( mapping == null || mapping.contains(id) ) { VirtualMachineProduct product; product = new VirtualMachineProduct(); product.setProviderProductId(id); product.setName(name + " (" + cpu + " CPU/" + memory + "MB RAM)"); product.setDescription(name + " (" + cpu + " CPU/" + memory + "MB RAM)"); product.setRamSize(new Storage<Megabyte>(memory, Storage.MEGABYTE)); product.setCpuCount(cpu); product.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE)); products.add(product); } } } cached.put(architecture, products); return products; } finally { APITrace.end(); } } private transient Collection<Architecture> architectures; @Override public Iterable<Architecture> listSupportedArchitectures() throws InternalException, CloudException { if( architectures == null ) { ArrayList<Architecture> a = new ArrayList<Architecture>(); a.add(Architecture.I32); a.add(Architecture.I64); architectures = Collections.unmodifiableList(a); } return architectures; } @Override public @Nonnull Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listVirtualMachineStatus"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was specified for this request"); } CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("zoneId", ctx.getRegionId())), LIST_VIRTUAL_MACHINES); ArrayList<ResourceStatus> servers = new ArrayList<ResourceStatus>(); NodeList matches = doc.getElementsByTagName("virtualmachine"); for( int i=0; i<matches.getLength(); i++ ) { Node node = matches.item(i); if( node != null ) { ResourceStatus vm = toStatus(node); if( vm != null ) { servers.add(vm); } } } return servers; } finally { APITrace.end(); } } @Override public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.listVirtualMachines"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was specified for this request"); } CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("zoneId", ctx.getRegionId())), LIST_VIRTUAL_MACHINES); ArrayList<VirtualMachine> servers = new ArrayList<VirtualMachine>(); NodeList matches = doc.getElementsByTagName("virtualmachine"); for( int i=0; i<matches.getLength(); i++ ) { Node node = matches.item(i); if( node != null ) { VirtualMachine vm = toVirtualMachine(node); if( vm != null ) { servers.add(vm); } } } return servers; } finally { APITrace.end(); } } @Override public void reboot(@Nonnull String serverId) throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.reboot"); try { CSMethod method = new CSMethod(provider); method.get(method.buildUrl(REBOOT_VIRTUAL_MACHINE, new Param("id", serverId)), REBOOT_VIRTUAL_MACHINE); } finally { APITrace.end(); } } @Override public void start(@Nonnull String serverId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.start"); try { CSMethod method = new CSMethod(provider); method.get(method.buildUrl(START_VIRTUAL_MACHINE, new Param("id", serverId)), START_VIRTUAL_MACHINE); } finally { APITrace.end(); } } @Override public void stop(@Nonnull String vmId, boolean force) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.stop"); try { CSMethod method = new CSMethod(provider); method.get(method.buildUrl(STOP_VIRTUAL_MACHINE, new Param("id", vmId), new Param("forced", String.valueOf(force))), STOP_VIRTUAL_MACHINE); } finally { APITrace.end(); } } @Override public boolean supportsPauseUnpause(@Nonnull VirtualMachine vm) { return false; } @Override public boolean supportsStartStop(@Nonnull VirtualMachine vm) { return true; } @Override public boolean supportsSuspendResume(@Nonnull VirtualMachine vm) { return false; } @Override public void terminate(@Nonnull String serverId, @Nullable String explanation) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.terminate"); try { CSMethod method = new CSMethod(provider); method.get(method.buildUrl(DESTROY_VIRTUAL_MACHINE, new Param("id", serverId)), DESTROY_VIRTUAL_MACHINE); } finally { APITrace.end(); } } private @Nullable ResourceStatus toStatus(@Nullable Node node) throws CloudException, InternalException { if( node == null ) { return null; } NodeList attributes = node.getChildNodes(); VmState state = null; String serverId = null; for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); String name = attribute.getNodeName().toLowerCase(); String value; if( attribute.getChildNodes().getLength() > 0 ) { value = attribute.getFirstChild().getNodeValue(); } else { value = null; } if( name.equals("virtualmachineid") || name.equals("id") ) { serverId = value; } else if( name.equals("state") ) { if( value == null ) { state = VmState.PENDING; } else if( value.equalsIgnoreCase("stopped") ) { state = VmState.STOPPED; } else if( value.equalsIgnoreCase("running") ) { state = VmState.RUNNING; } else if( value.equalsIgnoreCase("stopping") ) { state = VmState.STOPPING; } else if( value.equalsIgnoreCase("starting") ) { state = VmState.PENDING; } else if( value.equalsIgnoreCase("creating") ) { state = VmState.PENDING; } else if( value.equalsIgnoreCase("migrating") ) { state = VmState.REBOOTING; } else if( value.equalsIgnoreCase("destroyed") ) { state = VmState.TERMINATED; } else if( value.equalsIgnoreCase("error") ) { logger.warn("VM is in an error state."); return null; } else if( value.equalsIgnoreCase("expunging") ) { state = VmState.TERMINATED; } else if( value.equalsIgnoreCase("ha") ) { state = VmState.REBOOTING; } else { throw new CloudException("Unexpected server state: " + value); } } if( serverId != null && state != null ) { break; } } if( serverId == null ) { return null; } if( state == null ) { state = VmState.PENDING; } return new ResourceStatus(serverId, state); } private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException { if( node == null ) { return null; } HashMap<String,String> properties = new HashMap<String,String>(); VirtualMachine server = new VirtualMachine(); NodeList attributes = node.getChildNodes(); String productId = null; server.setTags(properties); server.setArchitecture(Architecture.I64); server.setProviderOwnerId(provider.getContext().getAccountNumber()); server.setClonable(false); server.setImagable(false); server.setPausable(true); server.setPersistent(true); for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); String name = attribute.getNodeName().toLowerCase(); String value; if( attribute.getChildNodes().getLength() > 0 ) { value = attribute.getFirstChild().getNodeValue(); } else { value = null; } if( name.equals("virtualmachineid") || name.equals("id") ) { server.setProviderVirtualMachineId(value); } else if( name.equals("name") ) { server.setDescription(value); } /* else if( name.equals("haenable") ) { server.setPersistent(value != null && value.equalsIgnoreCase("true")); } */ else if( name.equals("displayname") ) { server.setName(value); } else if( name.equals("ipaddress") ) { // v2.1 if( value != null ) { server.setPrivateAddresses(new RawAddress(value)); } server.setPrivateDnsAddress(value); } else if( name.equals("password") ) { server.setRootPassword(value); } else if( name.equals("nic") ) { // v2.2 if( attribute.hasChildNodes() ) { NodeList parts = attribute.getChildNodes(); String addr = null; for( int j=0; j<parts.getLength(); j++ ) { Node part = parts.item(j); if( part.getNodeName().equalsIgnoreCase("ipaddress") ) { if( part.hasChildNodes() ) { addr = part.getFirstChild().getNodeValue(); if( addr != null ) { addr = addr.trim(); } } } else if( part.getNodeName().equalsIgnoreCase("networkid") ) { server.setProviderVlanId(part.getFirstChild().getNodeValue().trim()); } } if( addr != null ) { boolean pub = false; if( !addr.startsWith("10.") && !addr.startsWith("192.168.") ) { if( addr.startsWith("172.") ) { String[] nums = addr.split("\\."); if( nums.length != 4 ) { pub = true; } else { try { int x = Integer.parseInt(nums[1]); if( x < 16 || x > 31 ) { pub = true; } } catch( NumberFormatException ignore ) { // ignore } } } else { pub = true; } } if( pub ) { server.setPublicAddresses(new RawAddress(addr)); if( server.getPublicDnsAddress() == null ) { server.setPublicDnsAddress(addr); } } else { server.setPrivateAddresses(new RawAddress(addr)); if( server.getPrivateDnsAddress() == null ) { server.setPrivateDnsAddress(addr); } } } } } else if( name.equals("osarchitecture") ) { if( value != null && value.equals("32") ) { server.setArchitecture(Architecture.I32); } else { server.setArchitecture(Architecture.I64); } } else if( name.equals("created") ) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278 try { server.setCreationTimestamp(df.parse(value).getTime()); } catch( ParseException e ) { logger.warn("Invalid date: " + value); server.setLastBootTimestamp(0L); } } else if( name.equals("state") ) { VmState state; //(Running, Stopped, Stopping, Starting, Creating, Migrating, HA). if( value.equalsIgnoreCase("stopped") ) { state = VmState.STOPPED; server.setImagable(true); } else if( value.equalsIgnoreCase("running") ) { state = VmState.RUNNING; } else if( value.equalsIgnoreCase("stopping") ) { state = VmState.STOPPING; } else if( value.equalsIgnoreCase("starting") ) { state = VmState.PENDING; } else if( value.equalsIgnoreCase("creating") ) { state = VmState.PENDING; } else if( value.equalsIgnoreCase("migrating") ) { state = VmState.REBOOTING; } else if( value.equalsIgnoreCase("destroyed") ) { state = VmState.TERMINATED; } else if( value.equalsIgnoreCase("error") ) { logger.warn("VM is in an error state."); return null; } else if( value.equalsIgnoreCase("expunging") ) { state = VmState.TERMINATED; } else if( value.equalsIgnoreCase("ha") ) { state = VmState.REBOOTING; } else { throw new CloudException("Unexpected server state: " + value); } server.setCurrentState(state); } else if( name.equals("zoneid") ) { server.setProviderRegionId(value); server.setProviderDataCenterId(value); } else if( name.equals("templateid") ) { server.setProviderMachineImageId(value); } else if( name.equals("templatename") ) { server.setPlatform(Platform.guess(value)); } else if( name.equals("serviceofferingid") ) { productId = value; } else if( value != null ) { properties.put(name, value); } } if( server.getName() == null ) { server.setName(server.getProviderVirtualMachineId()); } if( server.getDescription() == null ) { server.setDescription(server.getName()); } server.setProviderAssignedIpAddressId(null); if( server.getProviderRegionId() == null ) { server.setProviderRegionId(provider.getContext().getRegionId()); } if( server.getProviderDataCenterId() == null ) { server.setProviderDataCenterId(provider.getContext().getRegionId()); } if( productId != null ) { server.setProductId(productId); } setFirewalls(server); return server; } }
[bugzid:2887] Parsing job response to extract vm password on initial launch.
src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java
[bugzid:2887] Parsing job response to extract vm password on initial launch.
<ide><path>rc/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java <ide> throw new CloudException("Could not launch server"); <ide> } <ide> // TODO: very odd logic below; figure out what it thinks it is doing <del> long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE*20); <add> <ide> VirtualMachine vm = null; <ide> <del> while( System.currentTimeMillis() < timeout ) { <del> try { vm = getVirtualMachine(serverId); } <del> catch( Throwable ignore ) { } <del> if( vm != null ) { <del> return vm; <del> } <del> try { Thread.sleep(5000L); } <del> catch( InterruptedException ignore ) { } <del> } <del> provider.waitForJob(doc, "Launch Server"); <add> Document responseDoc = provider.waitForJob(doc, "Launch Server"); <add> <add> //parse vm from job completion response to capture vm passwords on initial launch. <add> if (responseDoc != null){ <add> NodeList nodeList = responseDoc.getElementsByTagName("virtualmachine"); <add> if (nodeList.getLength() > 0) { <add> Node virtualMachine = nodeList.item(0); <add> vm = toVirtualMachine(virtualMachine); <add> if( vm != null ) { <add> return vm; <add> } <add> } <add> } <add> <add> if (vm == null){ <add> long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE*20); <add> while( System.currentTimeMillis() < timeout ) { <add> try { vm = getVirtualMachine(serverId); } <add> catch( Throwable ignore ) { } <add> if( vm != null ) { <add> return vm; <add> } <add> try { Thread.sleep(5000L); } <add> catch( InterruptedException ignore ) { } <add> } <add> } <ide> vm = getVirtualMachine(serverId); <ide> if( vm == null ) { <ide> throw new CloudException("No virtual machine provided: " + serverId);
JavaScript
mit
fc007b5481de19d631f39f64476537a845f2ea22
0
wulanrahayu/jsPDF-AutoTable,simonbengtsson/jsPDF-AutoTable,hikmahtiar6/jsPDF-AutoTable,simonbengtsson/jsPDF-AutoTable,Mathieuu/jsPDF-AutoTable,ChipCastleDotCom/jsPDF-AutoTable,venusdharan/jsPDF-AutoTable,someatoms/jsPDF-AutoTable,RobertoMalatesta/jsPDF-AutoTable,simonbengtsson/jsPDF-AutoTable,wulanrahayu/jsPDF-AutoTable,daniel-z/jsPDF-AutoTable,ChipCastleDotCom/jsPDF-AutoTable,venusdharan/jsPDF-AutoTable,defmacro-jam/jsPDF-AutoTable
/** * jsPDF AutoTable plugin * Copyright (c) 2014 Simon Bengtsson, https://github.com/someatoms/jsPDF-AutoTable * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ (function (API) { 'use strict'; var MIN_COLUMN_WIDTH = 25; var doc, cellPos, pageCount = 1; // See README.md for documentation of the options or the examples var defaultOptions = { padding: 5, fontSize: 10, lineHeight: 20, renderHeader: function (doc, pageNumber, settings) { }, renderFooter: function (doc, lastCellPos, pageNumber, settings) { }, renderHeaderCell: function (x, y, width, height, key, value, settings) { doc.setFillColor(52, 73, 94); // Asphalt doc.setTextColor(255, 255, 255); doc.setFontStyle('bold'); doc.rect(x, y, width, height, 'F'); y += settings.lineHeight / 2 + doc.internal.getLineHeight() / 2; doc.text('' + value, x + settings.padding, y); }, renderCell: function (x, y, width, height, key, value, row, settings) { doc.setFillColor(row % 2 === 0 ? 245 : 255); doc.setTextColor(50); doc.rect(x, y, width, height, 'F'); y += settings.lineHeight / 2 + doc.internal.getLineHeight() / 2 - 2.5; doc.text('' + value, x + settings.padding, y); }, margins: {horizontal: 40, top: 50, bottom: 40}, startY: false, avoidPageSplit: false, extendWidth: true }; // User and default options merged var settings; /** * Create a table from a set of rows and columns. * * @param {Object[]|String[]} columns Either as an array of objects or array of strings * @param {Object[][]|String[][]} data Either as an array of objects or array of strings * @param {Object} [options={}] Options that will override the default ones (above) */ API.autoTable = function (columns, data, options) { doc = this; var userFontSize = doc.internal.getFontSize(); initData({columns: columns, data: data}); initOptions(options || {}); cellPos = {x: settings.margins.horizontal, y: settings.startY === false ? settings.margins.top : settings.startY}; var tableHeight = settings.margins.bottom + settings.margins.top + settings.lineHeight * (data.length + 1) + 5 + settings.startY; if(settings.startY !== false && settings.avoidPageSplit && tableHeight > doc.internal.pageSize.height) { doc.addPage(); cellPos.y = settings.margins.top; } settings.renderHeader(doc, pageCount, settings); var columnWidths = calculateColumnWidths(data, columns); printHeader(columns, columnWidths); printRows(columns, data, columnWidths); settings.renderFooter(doc, cellPos, pageCount, settings); doc.setFontSize(userFontSize); return this; }; /** * Returns the position of the last drawn cell */ API.autoTableEndPos = function () { return cellPos; }; function initData(params) { // Transform from String[] to Object[] if (typeof params.columns[0] === 'string') { params.data.forEach(function (row, i) { var obj = {}; for (var j = 0; j < row.length; j++) { obj[j] = params.data[i][j]; } params.data[i] = obj; }); params.columns.forEach(function (title, i) { params.columns[i] = {title: title, key: i}; }); } } function initOptions(raw) { settings = defaultOptions; Object.keys(raw).forEach(function (key) { settings[key] = raw[key]; }); doc.setFontSize(settings.fontSize); } function calculateColumnWidths(rows, columns) { var widths = {}; // Optimal widths var totalWidth = 0; columns.forEach(function (header) { var widest = getStringWidth(header.title || ''); if(header.key === 'expenses') { console.log(widest); } rows.forEach(function (row) { if(!header.hasOwnProperty('key')) throw new Error("The key attribute is required in every header"); var w = getStringWidth(prop(row, header.key)); if (w > widest) { widest = w; } }); widths[header.key] = widest; totalWidth += widest; }); var paddingAndMargin = settings.padding * 2 * columns.length + settings.margins.horizontal * 2; var spaceDiff = doc.internal.pageSize.width - totalWidth - paddingAndMargin; var keys = Object.keys(widths); if (spaceDiff < 0) { // Shrink columns var shrinkableColumns = []; var shrinkableColumnWidths = 0; keys.forEach(function (key) { if (widths[key] > MIN_COLUMN_WIDTH) { shrinkableColumns.push(key); shrinkableColumnWidths += widths[key]; } }); shrinkableColumns.forEach(function (key) { widths[key] += spaceDiff * (widths[key] / shrinkableColumnWidths); }); } else if (spaceDiff > 0 && settings.extendWidth) { // Fill page horizontally keys.forEach(function (key) { widths[key] += spaceDiff / keys.length; }); } return widths; } function printHeader(headers, columnWidths) { if (!headers) return; // headers.forEach(function (header) { var width = columnWidths[header.key] + settings.padding * 2; var title = ellipsize(columnWidths[header.key] || '', header.title || ''); settings.renderHeaderCell(cellPos.x, cellPos.y, width, settings.lineHeight + 5, header.key, title, settings); cellPos.x += width; }); doc.setTextColor(70, 70, 70); doc.setFontStyle('normal'); cellPos.y += settings.lineHeight + 5; cellPos.x = settings.margins.horizontal; } function printRows(headers, rows, columnWidths) { for (var i = 0; i < rows.length; i++) { var row = rows[i]; headers.forEach(function (header) { var title = ellipsize(columnWidths[header.key] || '', prop(row, header.key)); var width = columnWidths[header.key] + settings.padding * 2; settings.renderCell(cellPos.x, cellPos.y, width, settings.lineHeight, header.key, title, i, settings); cellPos.x = cellPos.x + columnWidths[header.key] + settings.padding * 2; }); var newPage = (cellPos.y + settings.margins.bottom + settings.lineHeight * 2) >= doc.internal.pageSize.height; if (newPage) { settings.renderFooter(doc, cellPos, pageCount, settings); doc.addPage(); cellPos = {x: settings.margins.horizontal, y: settings.margins.top}; pageCount++; settings.renderHeader(doc, pageCount, settings); printHeader(headers, columnWidths); } else { cellPos.y += settings.lineHeight; cellPos.x = settings.margins.horizontal; } } } /** * Ellipsize the text to fit in the width * @param width * @param text */ function ellipsize(width, text) { var isBold = doc.internal.getFont().fontStyle === 'bold'; if (width + (isBold ? 5 : 0) >= getStringWidth(text)) { return text; } while (width < getStringWidth(text + "...")) { if (text.length < 2) { break; } text = text.substring(0, text.length - 1); } text += "..."; return text; } function prop(row, key) { return row.hasOwnProperty(key) ? '' + row[key] : ''; } function getStringWidth(txt) { return doc.getStringUnitWidth(txt) * doc.internal.getFontSize(); } })(jsPDF.API);
jspdf.plugin.autotable.js
/** * jsPDF AutoTable plugin * Copyright (c) 2014 Simon Bengtsson, https://github.com/someatoms/jsPDF-AutoTable * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license */ (function (API) { 'use strict'; var MIN_COLUMN_WIDTH = 25; var doc, cellPos, pageCount = 1; // See README.md for documentation of the options or the examples var defaultOptions = { padding: 5, fontSize: 10, lineHeight: 20, renderHeader: function (doc, pageNumber, settings) { }, renderFooter: function (doc, lastCellPos, pageNumber, settings) { }, renderHeaderCell: function (x, y, width, height, key, value, settings) { doc.setFillColor(52, 73, 94); // Asphalt doc.setTextColor(255, 255, 255); doc.setFontStyle('bold'); doc.rect(x, y, width, height, 'F'); y += settings.lineHeight / 2 + doc.internal.getLineHeight() / 2; doc.text('' + value, x + settings.padding, y); }, renderCell: function (x, y, width, height, key, value, row, settings) { doc.setFillColor(row % 2 === 0 ? 245 : 255); doc.setTextColor(50); doc.rect(x, y, width, height, 'F'); y += settings.lineHeight / 2 + doc.internal.getLineHeight() / 2 - 2.5; doc.text('' + value, x + settings.padding, y); }, margins: {horizontal: 40, top: 50, bottom: 40}, startY: false, avoidPageSplit: false, extendWidth: true }; // User and default options merged var settings; /** * Create a table from a set of rows and columns. * * @param {Object[]|String[]} columns Either as an array of objects or array of strings * @param {Object[][]|String[][]} data Either as an array of objects or array of strings * @param {Object} [options={}] Options that will override the default ones (above) */ API.autoTable = function (columns, data, options) { doc = this; var userFontSize = doc.internal.getFontSize(); initData({columns: columns, data: data}); initOptions(options || {}); cellPos = {x: settings.margins.horizontal, y: settings.startY === false ? settings.margins.top : settings.startY}; var tableHeight = settings.margins.bottom + settings.margins.top + settings.lineHeight * (data.length + 1) + 5 + settings.startY; if(settings.startY !== false && settings.avoidPageSplit && tableHeight > doc.internal.pageSize.height) { doc.addPage(); cellPos.y = settings.margins.top; } settings.renderHeader(doc, pageCount, settings); var columnWidths = calculateColumnWidths(data, columns); printHeader(columns, columnWidths); printRows(columns, data, columnWidths); settings.renderFooter(doc, cellPos, pageCount, settings); doc.setFontSize(userFontSize); return this; }; /** * Returns the position of the last drawn cell */ API.autoTableEndPos = function () { return cellPos; }; function initData(params) { // Transform from String[] to Object[] if (typeof params.columns[0] === 'string') { params.data.forEach(function (row, i) { var obj = {}; for (var j = 0; j < row.length; j++) { obj[j] = params.data[i][j]; } params.data[i] = obj; }); params.columns.forEach(function (title, i) { params.columns[i] = {title: title, key: i}; }); } } function initOptions(raw) { settings = defaultOptions; Object.keys(raw).forEach(function (key) { settings[key] = raw[key]; }); doc.setFontSize(settings.fontSize); } function calculateColumnWidths(rows, columns) { var widths = {}; // Optimal widths var totalWidth = 0; columns.forEach(function (header) { var widest = getStringWidth(header.title || ''); if(header.key === 'expenses') { console.log(widest); } rows.forEach(function (row) { var w = getStringWidth(row[header.key] || ''); if (w > widest) { widest = w; } }); widths[header.key] = widest; totalWidth += widest; }); var paddingAndMargin = settings.padding * 2 * columns.length + settings.margins.horizontal * 2; var spaceDiff = doc.internal.pageSize.width - totalWidth - paddingAndMargin; var keys = Object.keys(widths); if (spaceDiff < 0) { // Shrink columns var shrinkableColumns = []; var shrinkableColumnWidths = 0; keys.forEach(function (key) { if (widths[key] > MIN_COLUMN_WIDTH) { shrinkableColumns.push(key); shrinkableColumnWidths += widths[key]; } }); shrinkableColumns.forEach(function (key) { widths[key] += spaceDiff * (widths[key] / shrinkableColumnWidths); }); } else if (spaceDiff > 0 && settings.extendWidth) { // Fill page horizontally keys.forEach(function (key) { widths[key] += spaceDiff / keys.length; }); } return widths; } function printHeader(headers, columnWidths) { if (!headers) return; // headers.forEach(function (header) { var width = columnWidths[header.key] + settings.padding * 2; var title = ellipsize(columnWidths[header.key] || '', header.title); settings.renderHeaderCell(cellPos.x, cellPos.y, width, settings.lineHeight + 5, header.key, title, settings); cellPos.x += width; }); doc.setTextColor(70, 70, 70); doc.setFontStyle('normal'); cellPos.y += settings.lineHeight + 5; cellPos.x = settings.margins.horizontal; } function printRows(headers, rows, columnWidths) { for (var i = 0; i < rows.length; i++) { var row = rows[i]; headers.forEach(function (header) { var title = ellipsize(columnWidths[header.key] || '', row[header.key] || ''); var width = columnWidths[header.key] + settings.padding * 2; settings.renderCell(cellPos.x, cellPos.y, width, settings.lineHeight, header.key, title, i, settings); cellPos.x = cellPos.x + columnWidths[header.key] + settings.padding * 2; }); var newPage = (cellPos.y + settings.margins.bottom + settings.lineHeight * 2) >= doc.internal.pageSize.height; if (newPage) { settings.renderFooter(doc, cellPos, pageCount, settings); doc.addPage(); cellPos = {x: settings.margins.horizontal, y: settings.margins.top}; pageCount++; settings.renderHeader(doc, pageCount, settings); printHeader(headers, columnWidths); } else { cellPos.y += settings.lineHeight; cellPos.x = settings.margins.horizontal; } } } /** * Ellipsize the text to fit in the width * @param width * @param text */ function ellipsize(width, text) { var isBold = doc.internal.getFont().fontStyle === 'bold'; if (width + (isBold ? 5 : 0) >= getStringWidth(text)) { return text; } while (width < getStringWidth(text + "...")) { if (text.length < 2) { break; } text = text.substring(0, text.length - 1); } text += "..."; return text; } function getStringWidth(txt) { return doc.getStringUnitWidth(txt) * doc.internal.getFontSize(); } })(jsPDF.API);
Fixed display of falsy values
jspdf.plugin.autotable.js
Fixed display of falsy values
<ide><path>spdf.plugin.autotable.js <ide> console.log(widest); <ide> } <ide> rows.forEach(function (row) { <del> var w = getStringWidth(row[header.key] || ''); <add> if(!header.hasOwnProperty('key')) <add> throw new Error("The key attribute is required in every header"); <add> var w = getStringWidth(prop(row, header.key)); <ide> if (w > widest) { <ide> widest = w; <ide> } <ide> <ide> var paddingAndMargin = settings.padding * 2 * columns.length + settings.margins.horizontal * 2; <ide> var spaceDiff = doc.internal.pageSize.width - totalWidth - paddingAndMargin; <del> <del> <ide> <ide> var keys = Object.keys(widths); <ide> if (spaceDiff < 0) { <ide> if (!headers) return; // <ide> headers.forEach(function (header) { <ide> var width = columnWidths[header.key] + settings.padding * 2; <del> var title = ellipsize(columnWidths[header.key] || '', header.title); <add> var title = ellipsize(columnWidths[header.key] || '', header.title || ''); <ide> settings.renderHeaderCell(cellPos.x, cellPos.y, width, settings.lineHeight + 5, header.key, title, settings); <ide> cellPos.x += width; <ide> }); <ide> var row = rows[i]; <ide> <ide> headers.forEach(function (header) { <del> var title = ellipsize(columnWidths[header.key] || '', row[header.key] || ''); <add> var title = ellipsize(columnWidths[header.key] || '', prop(row, header.key)); <ide> var width = columnWidths[header.key] + settings.padding * 2; <ide> settings.renderCell(cellPos.x, cellPos.y, width, settings.lineHeight, header.key, title, i, settings); <ide> cellPos.x = cellPos.x + columnWidths[header.key] + settings.padding * 2; <ide> return text; <ide> } <ide> <add> function prop(row, key) { <add> return row.hasOwnProperty(key) ? '' + row[key] : ''; <add> } <add> <ide> function getStringWidth(txt) { <ide> return doc.getStringUnitWidth(txt) * doc.internal.getFontSize(); <ide> }
JavaScript
agpl-3.0
e5bec963c709a82f3dae3b9cce543a761790f510
0
luanlv/lila,luanlv/lila,arex1337/lila,arex1337/lila,luanlv/lila,arex1337/lila,luanlv/lila,arex1337/lila,arex1337/lila,luanlv/lila,arex1337/lila,luanlv/lila,luanlv/lila,arex1337/lila
// CONFIGURE ME! mainDb = Mongo('127.0.0.1:27017').getDB('lichess'); oauthDb = Mongo('127.0.0.1:27017').getDB('lichess'); studyDb = Mongo('127.0.0.1:27017').getDB('lichess'); puzzleDb = Mongo('127.0.0.1:27017').getDB('puzzler'); // CONFIG END if (typeof user == 'undefined') throw 'Usage: mongo lichess --eval \'user="username"\' script.js'; user = db.user4.findOne({ _id: user }); if (!user || user.enabled || !user.erasedAt) throw 'Erase with lichess CLI first.'; print(`\n\n Delete user ${user.username} and all references to their username!\n\n`); sleep(5000); const newGhostId = () => { const idChars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; const idLength = 8; let id = ''; for (let i = idLength; i > 0; --i) id += idChars[Math.floor(Math.random() * idChars.length)]; return `!${id}`; }; const scrub = (collName, inDb) => f => { print(`- ${collName}`); sleep(200); return f((inDb || mainDb)[collName]); }; const byId = doc => ({ _id: doc._id }); const deleteAllIn = (db, collName, field, value) => scrub(collName, db)(c => c.remove({ [field]: value || userId })); const deleteAll = (collName, field, value) => deleteAllIn(mainDb, collName, field, value); const setNewGhostId = (coll, doc, field) => coll.update(byId(doc), { $set: { [field]: randomId() } }); const replaceWithNewGhostIds = (collName, field, inDb) => scrub(collName, inDb)(c => c.find({ [field]: userId }, { _id: 1 }).forEach(doc => setNewGhostId(c, doc, field))); const userId = user._id; const tos = user.marks && (user.marks.engine || user.marks.boost || user.marks.troll || user.marks.rankban || user.marks.alt); // Let us scrub. deleteAll('activity', '_id', new RegExp(`^${userId}:`)); deleteAll('analysis_requester', '_id'); deleteAll('bookmark', 'u'); deleteAll('challenge', 'challenger.id'); deleteAll('challenge', 'destUser.id'); replaceWithNewGhostIds('clas_clas', 'created.by'); scrub('clas_clas')(c => c.updateMany({ teachers: userId }, { $pull: { teachers: userId } })); deleteAll('clas_student', 'userId'); deleteAll('coach', '_id'); deleteAll('coach_review', 'userId'); deleteAll('config', '_id'); deleteAll('coordinate_score', '_id'); deleteAll('crosstable2', '_id', new RegExp(`^${userId}/`)); replaceWithNewGhostIds('f_post', 'userId'); scrub('game5')(c => c.find({ us: userId }, { us: 1, wid: 1 }).forEach(doc => { const gameGhostId = newGhostId(); c.update(byId(doc), { $set: { [`us.${doc.us.indexOf(userId)}`]: gameGhostId, // replace player usernames ...(doc.wid == userId ? { wid: gameGhostId } : {}), // replace winner username }, }); }) ); deleteAll('history3', '_id'); deleteAll('image', 'createdBy'); if (!tos) deleteAll('irwin_report', '_id'); deleteAll('learn_progress', '_id'); deleteAll('matchup', '_id', new RegExp(`^${userId}/`)); /* We decided not to delete PMs out of legit interest of the correspondents and also to be able to comply with data requests from law enforcement const msgThreadIds = scrub('msg_thread')(c => { const ids = c.distinct('_id', { users: userId }); c.remove({ users: userId }); return ids; }); scrub('msg_msg')(c => msgThreadIds.length && c.remove({ tid: { $in: msgThreadIds } })); */ scrub('note')(c => { c.remove({ from: userId, mod: { $ne: true } }); c.remove({ to: userId, mod: { $ne: true } }); }); deleteAll('notify', 'notifies'); replaceWithNewGhostIds('oauth_client', 'author', oauthDb); deleteAllIn(oauthDb, 'oauth_access_token', 'user_id'); deleteAll('perf_stat', new RegExp(`^${userId}/`)); replaceWithNewGhostIds('plan_charge', 'userId'); deleteAll('plan_patron', '_id'); deleteAll('playban', '_id'); deleteAll('player_assessment', 'userId'); deleteAll('practice_progress', '_id'); deleteAll('pref', '_id'); deleteAll('push_device', 'userId'); scrub( 'puzzle2_puzzle', puzzleDb )(c => c.find({ userId: userId }, { users: 1 }).forEach(doc => c.update(byId(doc), { $set: { [`users.${doc.users.indexOf(userId)}`]: newGhostId(), }, }) ) ); deleteAllIn(puzzleDb, 'puzzle2_round', '_id', new RegExp(`^${userId}:`)); deleteAll('ranking', new RegExp(`^${userId}:`)); deleteAll('relation', 'u1'); deleteAll('relation', 'u2'); scrub('report2')(c => { c.find({ 'atoms.by': userId }, { atoms: 1 }).forEach(doc => { const reportGhostId = newGhostId(); const newAtoms = doc.atoms.map(a => ({ ...a, by: a.by == userId ? reportGhostId : a.by, })); c.update(byId(doc), { $set: { atoms: newAtoms } }); }); !tos && c.updateMany({ user: userId }, { $set: { user: newGhostId() } }); }); if (!tos) deleteAll('security', 'user'); deleteAll('seek', 'user.id'); deleteAll('shutup', '_id'); replaceWithNewGhostIds('simul', 'hostId'); scrub('simul')(c => c.find({ 'pairings.player.user': userId }, { pairings: 1 }).forEach(doc => { doc.pairings.forEach(p => { if (p.player.user == userId) p.player.user = newGhostId(); }); c.update(byId(doc), { $set: { pairings: doc.pairings } }); }) ); deleteAll('storm_day', '_id', new RegExp(`^${userId}:`)); deleteAll('streamer', '_id'); replaceWithNewGhostIds('study', 'ownerId', studyDb); const studyIds = scrub( 'study', studyDb )(c => { c.updateMany({ likers: userId }, { $pull: { likers: userId } }); const ids = c.distinct('_id', { uids: userId }); c.updateMany({ uids: userId }, { $pull: { uids: userId }, $unset: { [`members.${userId}`]: true } }); return ids; }); scrub( 'study_chapter_flat', studyDb )(c => c.find({ _id: { $in: studyIds }, ownerId: userId }, { _id: 1 }).forEach(doc => setNewGhostId(c, doc, 'ownerId')) ); deleteAllIn(studyDb, 'study_user_topic', '_id'); replaceWithNewGhostIds('swiss', 'winnerId'); const swissIds = scrub('swiss_player')(c => c.distinct('s', { u: userId })); if (swissIds.length) { // here we use a single ghost ID for all swiss players and pairings, // because the mapping of swiss player to swiss pairings must be preserved const swissGhostId = newGhostId(); scrub('swiss_player')(c => { c.find({ _id: { $in: swissIds.map(s => `${s}:${userId}`) } }).forEach(p => { c.remove({ _id: p._id }); p._id = `${p.s}:${swissGhostId}`; p.u = swissGhostId; c.insert(p); }); }); scrub('swiss_pairing')(c => c.updateMany({ s: { $in: swissIds }, p: userId }, { $set: { 'p.$': swissGhostId } })); } replaceWithNewGhostIds('team', 'createdBy'); scrub('team')(c => c.updateMany({ leaders: userId }, { $pull: { leaders: userId } })); deleteAll('team_request', 'user'); deleteAll('team_member', 'user'); replaceWithNewGhostIds('tournament2', 'createdBy'); replaceWithNewGhostIds('tournament2', 'winnerId'); const arenaIds = scrub('tournament_leaderboard')(c => c.distinct('t', { u: userId })); if (arenaIds.length) { // here we use a single ghost ID for all arena players and pairings, // because the mapping of arena player to arena pairings must be preserved const arenaGhostId = newGhostId(); scrub('tournament_player')(c => c.updateMany({ tid: { $in: arenaIds }, uid: userId }, { $set: { uid: arenaGhostId } }) ); scrub('tournament_pairing')(c => c.updateMany({ tid: { $in: arenaIds }, u: userId }, { $set: { 'u.$': arenaGhostId } }) ); deleteAll('tournament_leaderboard', 'u'); } deleteAll('trophy', 'user'); // Delete everything from the user document, with the following exceptions: // - username, as to prevent signing up with the same username again. Usernames must NOT be reused. // - email, which is only kept in case of TOS violation, to prevent sign up from the same email again. // - prevEmail and createdAt, to prevent mass-creation of accounts reusing the same email address. // - GDPR erasure date for book-keeping. scrub('user4')(c => c.update( { _id: userId }, { email: user.email, prevEmail: user.prevEmail, createdAt: user.createdAt, erasedAt: new Date(), } ) ); deleteAll('video_view', 'u');
bin/mongodb/user-gdpr-scrub.js
// CONFIGURE ME! mainDb = Mongo('127.0.0.1:27017').getDB('lichess'); oauthDb = Mongo('127.0.0.1:27017').getDB('lichess'); studyDb = Mongo('127.0.0.1:27017').getDB('lichess'); puzzleDb = Mongo('127.0.0.1:27017').getDB('puzzler'); // CONFIG END if (typeof user == 'undefined') throw 'Usage: mongo lichess --eval \'user="username"\' script.js'; user = db.user4.findOne({ _id: user }); if (!user || user.enabled || !user.erasedAt) throw 'Erase with lichess CLI first.'; print(`\n\n Delete user ${user.username} and all references to their username!\n\n`); sleep(5000); const newGhostId = () => { const idChars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; const idLength = 8; let id = ''; for (let i = idLength; i > 0; --i) id += idChars[Math.floor(Math.random() * idChars.length)]; return `!${id}`; }; const scrub = (collName, inDb) => f => { print(`- ${collName}`); sleep(200); return f((inDb || mainDb)[collName]); }; const byId = doc => ({ _id: doc._id }); const deleteAllIn = (db, collName, field, value) => scrub(collName, db)(c => c.remove({ [field]: value || userId })); const deleteAll = (collName, field, value) => deleteAllIn(mainDb, collName, field, value); const setNewGhostId = (coll, doc, field) => coll.update(byId(doc), { $set: { [field]: randomId() } }); const replaceWithNewGhostIds = (collName, field, inDb) => scrub(collName, inDb)(c => c.find({ [field]: userId }, { _id: 1 }).forEach(doc => setNewGhostId(c, doc, field))); const userId = user._id; const tos = user.marks && (user.marks.engine || user.marks.boost || user.marks.troll || user.marks.rankban || user.marks.alt); // Let us scrub. deleteAll('activity', '_id', new RegExp(`^${userId}:`)); deleteAll('analysis_requester', '_id'); deleteAll('bookmark', 'u'); deleteAll('challenge', 'challenger.id'); deleteAll('challenge', 'destUser.id'); replaceWithNewGhostIds('clas_clas', 'created.by'); scrub('clas_clas')(c => c.updateMany({ teachers: userId }, { $pull: { teachers: userId } })); deleteAll('clas_student', 'userId'); deleteAll('coach', '_id'); deleteAll('coach_review', 'userId'); deleteAll('config', '_id'); deleteAll('coordinate_score', '_id'); deleteAll('crosstable2', '_id', new RegExp(`^${userId}/`)); replaceWithNewGhostIds('f_post', 'userId'); scrub('game5')(c => c.find({ us: userId }, { us: 1, wid: 1 }).forEach(doc => { const gameGhostId = newGhostId(); c.update(byId(doc), { $set: { [`us.${doc.us.indexOf(userId)}`]: gameGhostId, // replace player usernames ...(doc.wid == userId ? { wid: gameGhostId } : {}), // replace winner username }, }); }) ); deleteAll('history3', '_id'); deleteAll('image', 'createdBy'); if (!tos) deleteAll('irwin_report', '_id'); deleteAll('learn_progress', '_id'); deleteAll('matchup', '_id', new RegExp(`^${userId}/`)); /* We decided not to delete PMs out of legit interest of the correspondents and also to be able to comply to data requests from law enforcement const msgThreadIds = scrub('msg_thread')(c => { const ids = c.distinct('_id', { users: userId }); c.remove({ users: userId }); return ids; }); scrub('msg_msg')(c => msgThreadIds.length && c.remove({ tid: { $in: msgThreadIds } })); */ scrub('note')(c => { c.remove({ from: userId, mod: { $ne: true } }); c.remove({ to: userId, mod: { $ne: true } }); }); deleteAll('notify', 'notifies'); replaceWithNewGhostIds('oauth_client', 'author', oauthDb); deleteAllIn(oauthDb, 'oauth_access_token', 'user_id'); deleteAll('perf_stat', new RegExp(`^${userId}/`)); replaceWithNewGhostIds('plan_charge', 'userId'); deleteAll('plan_patron', '_id'); deleteAll('playban', '_id'); deleteAll('player_assessment', 'userId'); deleteAll('practice_progress', '_id'); deleteAll('pref', '_id'); deleteAll('push_device', 'userId'); scrub( 'puzzle2_puzzle', puzzleDb )(c => c.find({ userId: userId }, { users: 1 }).forEach(doc => c.update(byId(doc), { $set: { [`users.${doc.users.indexOf(userId)}`]: newGhostId(), }, }) ) ); deleteAllIn(puzzleDb, 'puzzle2_round', '_id', new RegExp(`^${userId}:`)); deleteAll('ranking', new RegExp(`^${userId}:`)); deleteAll('relation', 'u1'); deleteAll('relation', 'u2'); scrub('report2')(c => { c.find({ 'atoms.by': userId }, { atoms: 1 }).forEach(doc => { const reportGhostId = newGhostId(); const newAtoms = doc.atoms.map(a => ({ ...a, by: a.by == userId ? reportGhostId : a.by, })); c.update(byId(doc), { $set: { atoms: newAtoms } }); }); !tos && c.updateMany({ user: userId }, { $set: { user: newGhostId() } }); }); if (!tos) deleteAll('security', 'user'); deleteAll('seek', 'user.id'); deleteAll('shutup', '_id'); replaceWithNewGhostIds('simul', 'hostId'); scrub('simul')(c => c.find({ 'pairings.player.user': userId }, { pairings: 1 }).forEach(doc => { doc.pairings.forEach(p => { if (p.player.user == userId) p.player.user = newGhostId(); }); c.update(byId(doc), { $set: { pairings: doc.pairings } }); }) ); deleteAll('storm_day', '_id', new RegExp(`^${userId}:`)); deleteAll('streamer', '_id'); replaceWithNewGhostIds('study', 'ownerId', studyDb); const studyIds = scrub( 'study', studyDb )(c => { c.updateMany({ likers: userId }, { $pull: { likers: userId } }); const ids = c.distinct('_id', { uids: userId }); c.updateMany({ uids: userId }, { $pull: { uids: userId }, $unset: { [`members.${userId}`]: true } }); return ids; }); scrub( 'study_chapter_flat', studyDb )(c => c.find({ _id: { $in: studyIds }, ownerId: userId }, { _id: 1 }).forEach(doc => setNewGhostId(c, doc, 'ownerId')) ); deleteAllIn(studyDb, 'study_user_topic', '_id'); replaceWithNewGhostIds('swiss', 'winnerId'); const swissIds = scrub('swiss_player')(c => c.distinct('s', { u: userId })); if (swissIds.length) { // here we use a single ghost ID for all swiss players and pairings, // because the mapping of swiss player to swiss pairings must be preserved const swissGhostId = newGhostId(); scrub('swiss_player')(c => { c.find({ _id: { $in: swissIds.map(s => `${s}:${userId}`) } }).forEach(p => { c.remove({ _id: p._id }); p._id = `${p.s}:${swissGhostId}`; p.u = swissGhostId; c.insert(p); }); }); scrub('swiss_pairing')(c => c.updateMany({ s: { $in: swissIds }, p: userId }, { $set: { 'p.$': swissGhostId } })); } replaceWithNewGhostIds('team', 'createdBy'); scrub('team')(c => c.updateMany({ leaders: userId }, { $pull: { leaders: userId } })); deleteAll('team_request', 'user'); deleteAll('team_member', 'user'); replaceWithNewGhostIds('tournament2', 'createdBy'); replaceWithNewGhostIds('tournament2', 'winnerId'); const arenaIds = scrub('tournament_leaderboard')(c => c.distinct('t', { u: userId })); if (arenaIds.length) { // here we use a single ghost ID for all arena players and pairings, // because the mapping of arena player to arena pairings must be preserved const arenaGhostId = newGhostId(); scrub('tournament_player')(c => c.updateMany({ tid: { $in: arenaIds }, uid: userId }, { $set: { uid: arenaGhostId } }) ); scrub('tournament_pairing')(c => c.updateMany({ tid: { $in: arenaIds }, u: userId }, { $set: { 'u.$': arenaGhostId } }) ); deleteAll('tournament_leaderboard', 'u'); } deleteAll('trophy', 'user'); deleteAll('video_view', 'u');
scrub the user document
bin/mongodb/user-gdpr-scrub.js
scrub the user document
<ide><path>in/mongodb/user-gdpr-scrub.js <ide> <ide> /* <ide> We decided not to delete PMs out of legit interest of the correspondents <del>and also to be able to comply to data requests from law enforcement <add>and also to be able to comply with data requests from law enforcement <ide> <ide> const msgThreadIds = scrub('msg_thread')(c => { <ide> const ids = c.distinct('_id', { users: userId }); <ide> <ide> deleteAll('trophy', 'user'); <ide> <add>// Delete everything from the user document, with the following exceptions: <add>// - username, as to prevent signing up with the same username again. Usernames must NOT be reused. <add>// - email, which is only kept in case of TOS violation, to prevent sign up from the same email again. <add>// - prevEmail and createdAt, to prevent mass-creation of accounts reusing the same email address. <add>// - GDPR erasure date for book-keeping. <add>scrub('user4')(c => <add> c.update( <add> { _id: userId }, <add> { <add> email: user.email, <add> prevEmail: user.prevEmail, <add> createdAt: user.createdAt, <add> erasedAt: new Date(), <add> } <add> ) <add>); <add> <ide> deleteAll('video_view', 'u');
Java
apache-2.0
94dcc045d40bbf30bea003a3e53110c500df3baf
0
jmsalcido/catapi-android
package org.otfusion.votecats.ui.activities; import android.content.Intent; import android.view.GestureDetector; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.squareup.otto.Subscribe; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import org.otfusion.votecats.R; import org.otfusion.votecats.common.model.Cat; import org.otfusion.votecats.events.CatLoadedEvent; import org.otfusion.votecats.events.FavoriteCatEvent; import org.otfusion.votecats.ui.gestures.GestureDoubleTap; import org.otfusion.votecats.util.UIUtils; import butterknife.Bind; public class MainActivity extends CatActivity { @Bind(R.id.cat_view) ImageView _catImageView; @Bind(R.id.load_cat_button) Button _loadCatButton; @Bind(R.id.favorite_cat_button) Button _favoriteCatButton; private Cat _currentCat; @Override protected int getContentLayoutId() { return R.layout.activity_main; } @Override protected void loadContent() { loadCat(); _loadCatButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { loadCat(); } }); _favoriteCatButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FavoriteCatEvent event = new FavoriteCatEvent(getBus(), _currentCat); event.executeEvent("button"); } }); final GestureDoubleTap<FavoriteCatEvent> doubleTapGesture = new GestureDoubleTap<>(); _catImageView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { doubleTapGesture.setEvent(new FavoriteCatEvent(getBus(), _currentCat)); GestureDetector gestureDetector = new GestureDetector(getApplicationContext(), doubleTapGesture); return gestureDetector.onTouchEvent(motionEvent); } }); } private void loadCat() { _loadCatButton.setEnabled(false); getCatService().getCatFromApi(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_main_goto_favorite) { Intent intent = new Intent(this, FavoriteActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } @Subscribe @SuppressWarnings("unused") // used by the bus public void handleCatLoadedEvent(CatLoadedEvent catLoadedEvent) { _currentCat = catLoadedEvent.getCat(); Picasso.with(getApplicationContext()).load(_currentCat.getImageUrl()).into(_catImageView, new Callback() { @Override public void onSuccess() { enableLoadButton(); } @Override public void onError() { enableLoadButton(); } private void enableLoadButton() { _loadCatButton.setEnabled(true); } }); } @Subscribe @SuppressWarnings("unused") // used by the bus public void handleFavoriteCatEvent(FavoriteCatEvent favoriteCatEvent) { Cat cat = favoriteCatEvent.getCat(); if (cat != null) { if (getCatService().isCatInFavorites(cat)) { UIUtils.showToast("That cat is already in your collection"); } else { getCatService().saveCatToFavorites(cat); loadCat(); UIUtils.showToast("Saving that right Meow!"); } } else { UIUtils.showToast("There is no cat there."); } } }
app/src/main/java/org/otfusion/votecats/ui/activities/MainActivity.java
package org.otfusion.votecats.ui.activities; import android.content.Intent; import android.view.GestureDetector; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.squareup.otto.Subscribe; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import org.otfusion.votecats.R; import org.otfusion.votecats.common.model.Cat; import org.otfusion.votecats.events.CatLoadedEvent; import org.otfusion.votecats.events.FavoriteCatEvent; import org.otfusion.votecats.ui.gestures.GestureDoubleTap; import org.otfusion.votecats.util.UIUtils; import butterknife.Bind; public class MainActivity extends CatActivity { @Bind(R.id.cat_view) ImageView _catImageView; @Bind(R.id.load_cat_button) Button _loadCatButton; @Bind(R.id.favorite_cat_button) Button _favoriteCatButton; private Cat _currentCat; @Override protected int getContentLayoutId() { return R.layout.activity_main; } @Override protected void loadContent() { _loadCatButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { _loadCatButton.setEnabled(false); getCatService().getCatFromApi(); } }); _favoriteCatButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FavoriteCatEvent event = new FavoriteCatEvent(getBus(), _currentCat); event.executeEvent("button"); } }); final GestureDoubleTap<FavoriteCatEvent> doubleTapGesture = new GestureDoubleTap<>(); _catImageView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { doubleTapGesture.setEvent(new FavoriteCatEvent(getBus(), _currentCat)); GestureDetector gestureDetector = new GestureDetector(getApplicationContext(), doubleTapGesture); return gestureDetector.onTouchEvent(motionEvent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_main_goto_favorite) { Intent intent = new Intent(this, FavoriteActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } @Subscribe @SuppressWarnings("unused") // used by the bus public void handleCatLoadedEvent(CatLoadedEvent catLoadedEvent) { _currentCat = catLoadedEvent.getCat(); Picasso.with(getApplicationContext()).load(_currentCat.getImageUrl()).into(_catImageView, new Callback() { @Override public void onSuccess() { enableLoadButton(); } @Override public void onError() { enableLoadButton(); } private void enableLoadButton() { _loadCatButton.setEnabled(true); } }); } @Subscribe @SuppressWarnings("unused") // used by the bus public void handleFavoriteCatEvent(FavoriteCatEvent favoriteCatEvent) { Cat cat = favoriteCatEvent.getCat(); if (cat != null) { if (getCatService().isCatInFavorites(cat)) { UIUtils.showToast("That cat is already in your collection"); } else { getCatService().saveCatToFavorites(cat); UIUtils.showToast("Saving that right Meow!"); } } else { UIUtils.showToast("There is no cat there."); } } }
id:#11 have image when hit back on the favorites activity description: just re-load a cat from the api.
app/src/main/java/org/otfusion/votecats/ui/activities/MainActivity.java
id:#11 have image when hit back on the favorites activity description: just re-load a cat from the api.
<ide><path>pp/src/main/java/org/otfusion/votecats/ui/activities/MainActivity.java <ide> <ide> @Override <ide> protected void loadContent() { <add> loadCat(); <ide> _loadCatButton.setOnClickListener(new View.OnClickListener() { <ide> @Override <ide> public void onClick(View view) { <del> _loadCatButton.setEnabled(false); <del> getCatService().getCatFromApi(); <add> loadCat(); <ide> } <ide> }); <ide> <ide> return gestureDetector.onTouchEvent(motionEvent); <ide> } <ide> }); <add> } <add> <add> private void loadCat() { <add> _loadCatButton.setEnabled(false); <add> getCatService().getCatFromApi(); <ide> } <ide> <ide> @Override <ide> UIUtils.showToast("That cat is already in your collection"); <ide> } else { <ide> getCatService().saveCatToFavorites(cat); <add> loadCat(); <ide> UIUtils.showToast("Saving that right Meow!"); <ide> } <ide> } else {
Java
apache-2.0
07cbcc410895093844903bd0e1b7488134844a8a
0
Aulust/async-http-client,stepancheg/async-http-client,bomgar/async-http-client,fengshao0907/async-http-client,nemoyixin/async-http-client,hgl888/async-http-client,typesafehub/async-http-client,elijah513/async-http-client,magiccao/async-http-client,thinker-fang/async-http-client,ooon/async-http-client,jxauchengchao/async-http-client,wyyl1/async-http-client,olksdr/async-http-client,afelisatti/async-http-client,ALEXGUOQ/async-http-client,liuyb02/async-http-client,drmaas/async-http-client,dotta/async-http-client,craigwblake/async-http-client-1,junjiemars/async-http-client,jroper/async-http-client,Aulust/async-http-client
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.asynchttpclient; import org.asynchttpclient.filter.IOExceptionFilter; import org.asynchttpclient.filter.RequestFilter; import org.asynchttpclient.filter.ResponseFilter; import org.asynchttpclient.util.AllowAllHostnameVerifier; import org.asynchttpclient.util.ProxyUtils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; /** * Configuration class to use with a {@link AsyncHttpClient}. System property can be also used to configure this * object default behavior by doing: * <p/> * -Dorg.asynchttpclient.AsyncHttpClientConfig.nameOfTheProperty * ex: * <p/> * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultMaxTotalConnections * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultMaxTotalConnections * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultMaxConnectionsPerHost * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultConnectionTimeoutInMS * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultIdleConnectionInPoolTimeoutInMS * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultRequestTimeoutInMS * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultRedirectsEnabled * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultMaxRedirects */ public class AsyncHttpClientConfig { protected final static String ASYNC_CLIENT = AsyncHttpClientConfig.class.getName() + "."; public final static String AHC_VERSION; static { InputStream is = null; Properties prop = new Properties(); try { is = AsyncHttpClientConfig.class.getResourceAsStream("version.properties"); prop.load(is); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException ignored) { } } } AHC_VERSION = prop.getProperty("ahc.version", "UNKNOWN"); } protected int maxTotalConnections; protected int maxConnectionPerHost; protected int connectionTimeOutInMs; protected int webSocketIdleTimeoutInMs; protected int idleConnectionInPoolTimeoutInMs; protected int idleConnectionTimeoutInMs; protected int requestTimeoutInMs; protected boolean redirectEnabled; protected int maxDefaultRedirects; protected boolean compressionEnabled; protected String userAgent; protected boolean allowPoolingConnection; protected ScheduledExecutorService reaper; protected ExecutorService applicationThreadPool; protected ProxyServer proxyServer; protected SSLContext sslContext; protected SSLEngineFactory sslEngineFactory; protected AsyncHttpProviderConfig<?, ?> providerConfig; protected ConnectionsPool<?, ?> connectionsPool; protected Realm realm; protected List<RequestFilter> requestFilters; protected List<ResponseFilter> responseFilters; protected List<IOExceptionFilter> ioExceptionFilters; protected int requestCompressionLevel; protected int maxRequestRetry; protected boolean allowSslConnectionPool; protected boolean useRawUrl; protected boolean removeQueryParamOnRedirect; protected HostnameVerifier hostnameVerifier; protected int ioThreadMultiplier; protected boolean strict302Handling; protected int maxConnectionLifeTimeInMs; protected boolean useRelativeURIsWithSSLProxies; protected boolean spdyEnabled; protected int spdyInitialWindowSize; protected int spdyMaxConcurrentStreams; protected AsyncHttpClientConfig() { } private AsyncHttpClientConfig(int maxTotalConnections, int maxConnectionPerHost, int connectionTimeOutInMs, int webSocketTimeoutInMs, int idleConnectionInPoolTimeoutInMs, int idleConnectionTimeoutInMs, int requestTimeoutInMs, int connectionMaxLifeTimeInMs, boolean redirectEnabled, int maxDefaultRedirects, boolean compressionEnabled, String userAgent, boolean keepAlive, ScheduledExecutorService reaper, ExecutorService applicationThreadPool, ProxyServer proxyServer, SSLContext sslContext, SSLEngineFactory sslEngineFactory, AsyncHttpProviderConfig<?, ?> providerConfig, ConnectionsPool<?, ?> connectionsPool, Realm realm, List<RequestFilter> requestFilters, List<ResponseFilter> responseFilters, List<IOExceptionFilter> ioExceptionFilters, int requestCompressionLevel, int maxRequestRetry, boolean allowSslConnectionCaching, boolean useRawUrl, boolean removeQueryParamOnRedirect, HostnameVerifier hostnameVerifier, int ioThreadMultiplier, boolean strict302Handling, boolean useRelativeURIsWithSSLProxies, boolean spdyEnabled, int spdyInitialWindowSize, int spdyMaxConcurrentStreams) { this.maxTotalConnections = maxTotalConnections; this.maxConnectionPerHost = maxConnectionPerHost; this.connectionTimeOutInMs = connectionTimeOutInMs; this.webSocketIdleTimeoutInMs = webSocketTimeoutInMs; this.idleConnectionInPoolTimeoutInMs = idleConnectionInPoolTimeoutInMs; this.idleConnectionTimeoutInMs = idleConnectionTimeoutInMs; this.requestTimeoutInMs = requestTimeoutInMs; this.maxConnectionLifeTimeInMs = connectionMaxLifeTimeInMs; this.redirectEnabled = redirectEnabled; this.maxDefaultRedirects = maxDefaultRedirects; this.compressionEnabled = compressionEnabled; this.userAgent = userAgent; this.allowPoolingConnection = keepAlive; this.sslContext = sslContext; this.sslEngineFactory = sslEngineFactory; this.providerConfig = providerConfig; this.connectionsPool = connectionsPool; this.realm = realm; this.requestFilters = requestFilters; this.responseFilters = responseFilters; this.ioExceptionFilters = ioExceptionFilters; this.requestCompressionLevel = requestCompressionLevel; this.maxRequestRetry = maxRequestRetry; this.reaper = reaper; this.allowSslConnectionPool = allowSslConnectionCaching; this.removeQueryParamOnRedirect = removeQueryParamOnRedirect; this.hostnameVerifier = hostnameVerifier; this.ioThreadMultiplier = ioThreadMultiplier; this.strict302Handling = strict302Handling; this.useRelativeURIsWithSSLProxies = useRelativeURIsWithSSLProxies; if (applicationThreadPool == null) { this.applicationThreadPool = Executors.newCachedThreadPool(); } else { this.applicationThreadPool = applicationThreadPool; } this.proxyServer = proxyServer; this.useRawUrl = useRawUrl; this.spdyEnabled = spdyEnabled; this.spdyInitialWindowSize = spdyInitialWindowSize; this.spdyMaxConcurrentStreams = spdyMaxConcurrentStreams; } /** * A {@link ScheduledExecutorService} used to expire idle connections. * * @return {@link ScheduledExecutorService} */ public ScheduledExecutorService reaper() { return reaper; } /** * Return the maximum number of connections an {@link AsyncHttpClient} can handle. * * @return the maximum number of connections an {@link AsyncHttpClient} can handle. */ public int getMaxTotalConnections() { return maxTotalConnections; } /** * Return the maximum number of connections per hosts an {@link AsyncHttpClient} can handle. * * @return the maximum number of connections per host an {@link AsyncHttpClient} can handle. */ public int getMaxConnectionPerHost() { return maxConnectionPerHost; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} can wait when connecting to a remote host * * @return the maximum time in millisecond an {@link AsyncHttpClient} can wait when connecting to a remote host */ public int getConnectionTimeoutInMs() { return connectionTimeOutInMs; } /** * Return the maximum time, in milliseconds, a {@link org.asynchttpclient.websocket.WebSocket} may be idle before being timed out. * @return the maximum time, in milliseconds, a {@link org.asynchttpclient.websocket.WebSocket} may be idle before being timed out. */ public int getWebSocketIdleTimeoutInMs() { return webSocketIdleTimeoutInMs; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} can stay idle. * * @return the maximum time in millisecond an {@link AsyncHttpClient} can stay idle. */ public int getIdleConnectionTimeoutInMs() { return idleConnectionTimeoutInMs; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} will keep connection * in pool. * * @return the maximum time in millisecond an {@link AsyncHttpClient} will keep connection * in pool. */ public int getIdleConnectionInPoolTimeoutInMs() { return idleConnectionInPoolTimeoutInMs; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} wait for a response * * @return the maximum time in millisecond an {@link AsyncHttpClient} wait for a response */ public int getRequestTimeoutInMs() { return requestTimeoutInMs; } /** * Is HTTP redirect enabled * * @return true if enabled. */ public boolean isRedirectEnabled() { return redirectEnabled; } /** * Get the maximum number of HTTP redirect * * @return the maximum number of HTTP redirect */ public int getMaxRedirects() { return maxDefaultRedirects; } /** * Is the {@link ConnectionsPool} support enabled. * * @return true if keep-alive is enabled */ public boolean getAllowPoolingConnection() { return allowPoolingConnection; } /** * Is the {@link ConnectionsPool} support enabled. * * @return true if keep-alive is enabled * @deprecated - Use {@link AsyncHttpClientConfig#getAllowPoolingConnection()} */ public boolean getKeepAlive() { return allowPoolingConnection; } /** * Return the USER_AGENT header value * * @return the USER_AGENT header value */ public String getUserAgent() { return userAgent; } /** * Is HTTP compression enabled. * * @return true if compression is enabled */ public boolean isCompressionEnabled() { return compressionEnabled; } /** * Return the {@link java.util.concurrent.ExecutorService} an {@link AsyncHttpClient} use for handling * asynchronous response. * * @return the {@link java.util.concurrent.ExecutorService} an {@link AsyncHttpClient} use for handling * asynchronous response. */ public ExecutorService executorService() { return applicationThreadPool; } /** * An instance of {@link ProxyServer} used by an {@link AsyncHttpClient} * * @return instance of {@link ProxyServer} */ public ProxyServer getProxyServer() { return proxyServer; } /** * Return an instance of {@link SSLContext} used for SSL connection. * * @return an instance of {@link SSLContext} used for SSL connection. */ public SSLContext getSSLContext() { return sslContext; } /** * Return an instance of {@link ConnectionsPool} * * @return an instance of {@link ConnectionsPool} */ public ConnectionsPool<?, ?> getConnectionsPool() { return connectionsPool; } /** * Return an instance of {@link SSLEngineFactory} used for SSL connection. * * @return an instance of {@link SSLEngineFactory} used for SSL connection. */ public SSLEngineFactory getSSLEngineFactory() { if (sslEngineFactory == null) { return new SSLEngineFactory() { public SSLEngine newSSLEngine() { if (sslContext != null) { SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(true); return sslEngine; } else { return null; } } }; } return sslEngineFactory; } /** * Return the {@link AsyncHttpProviderConfig} * * @return the {@link AsyncHttpProviderConfig} */ public AsyncHttpProviderConfig<?, ?> getAsyncHttpProviderConfig() { return providerConfig; } /** * Return the current {@link Realm}} * * @return the current {@link Realm}} */ public Realm getRealm() { return realm; } /** * Return the list of {@link RequestFilter} * * @return Unmodifiable list of {@link ResponseFilter} */ public List<RequestFilter> getRequestFilters() { return Collections.unmodifiableList(requestFilters); } /** * Return the list of {@link ResponseFilter} * * @return Unmodifiable list of {@link ResponseFilter} */ public List<ResponseFilter> getResponseFilters() { return Collections.unmodifiableList(responseFilters); } /** * Return the list of {@link java.io.IOException} * * @return Unmodifiable list of {@link java.io.IOException} */ public List<IOExceptionFilter> getIOExceptionFilters() { return Collections.unmodifiableList(ioExceptionFilters); } /** * Return the compression level, or -1 if no compression is used. * * @return the compression level, or -1 if no compression is use */ public int getRequestCompressionLevel() { return requestCompressionLevel; } /** * Return the number of time the library will retry when an {@link java.io.IOException} is throw by the remote server * * @return the number of time the library will retry when an {@link java.io.IOException} is throw by the remote server */ public int getMaxRequestRetry() { return maxRequestRetry; } /** * Return true is SSL connection polling is enabled. Default is true. * * @return true is enabled. */ public boolean isSslConnectionPoolEnabled() { return allowSslConnectionPool; } /** * @return the useRawUrl */ public boolean isUseRawUrl() { return useRawUrl; } /** * @return whether or not SPDY is enabled. */ public boolean isSpdyEnabled() { return spdyEnabled; } /** * @return the windows size new SPDY sessions should be initialized to. */ public int getSpdyInitialWindowSize() { return spdyInitialWindowSize; } /** * @return the maximum number of concurrent streams over one SPDY session. */ public int getSpdyMaxConcurrentStreams() { return spdyMaxConcurrentStreams; } /** * Return true if the query parameters will be stripped from the request when a redirect is requested. * * @return true if the query parameters will be stripped from the request when a redirect is requested. */ public boolean isRemoveQueryParamOnRedirect() { return removeQueryParamOnRedirect; } /** * Return true if one of the {@link java.util.concurrent.ExecutorService} has been shutdown. * * @return true if one of the {@link java.util.concurrent.ExecutorService} has been shutdown. */ public boolean isClosed() { return applicationThreadPool.isShutdown() || reaper.isShutdown(); } /** * Return the {@link HostnameVerifier} * * @return the {@link HostnameVerifier} */ public HostnameVerifier getHostnameVerifier() { return hostnameVerifier; } /** * @return number to multiply by availableProcessors() that will determine # of NioWorkers to use */ public int getIoThreadMultiplier() { return ioThreadMultiplier; } /** * <p> * In the case of a POST/Redirect/Get scenario where the server uses a 302 * for the redirect, should AHC respond to the redirect with a GET or * whatever the original method was. Unless configured otherwise, * for a 302, AHC, will use a GET for this case. * </p> * * @return <code>true</code> if string 302 handling is to be used, * otherwise <code>false</code>. * * @since 1.7.2 */ public boolean isStrict302Handling() { return strict302Handling; } /** * @return<code>true</code> if AHC should use relative URIs instead of absolute ones when talking with a SSL proxy, * otherwise <code>false</code>. * * @since 1.7.12 */ public boolean isUseRelativeURIsWithSSLProxies() { return useRelativeURIsWithSSLProxies; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} will keep connection in the pool, or -1 to keep connection while possible. * * @return the maximum time in millisecond an {@link AsyncHttpClient} will keep connection in the pool, or -1 to keep connection while possible. */ public int getMaxConnectionLifeTimeInMs() { return maxConnectionLifeTimeInMs; } /** * Builder for an {@link AsyncHttpClient} */ public static class Builder { private int defaultMaxTotalConnections = Integer.getInteger(ASYNC_CLIENT + "defaultMaxTotalConnections", -1); private int defaultMaxConnectionPerHost = Integer.getInteger(ASYNC_CLIENT + "defaultMaxConnectionsPerHost", -1); private int defaultConnectionTimeOutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultConnectionTimeoutInMS", 60 * 1000); private int defaultWebsocketIdleTimeoutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultWebsocketTimoutInMS", 15 * 60 * 1000); private int defaultIdleConnectionInPoolTimeoutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultIdleConnectionInPoolTimeoutInMS", 60 * 1000); private int defaultIdleConnectionTimeoutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultIdleConnectionTimeoutInMS", 60 * 1000); private int defaultRequestTimeoutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultRequestTimeoutInMS", 60 * 1000); private int defaultMaxConnectionLifeTimeInMs = Integer.getInteger(ASYNC_CLIENT + "defaultMaxConnectionLifeTimeInMs", -1); private boolean redirectEnabled = Boolean.getBoolean(ASYNC_CLIENT + "defaultRedirectsEnabled"); private int maxDefaultRedirects = Integer.getInteger(ASYNC_CLIENT + "defaultMaxRedirects", 5); private boolean compressionEnabled = Boolean.getBoolean(ASYNC_CLIENT + "compressionEnabled"); private String userAgent = System.getProperty(ASYNC_CLIENT + "userAgent", "AsyncHttpClient/" + AHC_VERSION); private boolean useProxyProperties = Boolean.getBoolean(ASYNC_CLIENT + "useProxyProperties"); private boolean allowPoolingConnection = true; private boolean useRelativeURIsWithSSLProxies = Boolean.getBoolean(ASYNC_CLIENT + "useRelativeURIsWithSSLProxies"); private ScheduledExecutorService reaper; private ExecutorService applicationThreadPool; private ProxyServer proxyServer = null; private SSLContext sslContext; private SSLEngineFactory sslEngineFactory; private AsyncHttpProviderConfig<?, ?> providerConfig; private ConnectionsPool<?, ?> connectionsPool; private Realm realm; private int requestCompressionLevel = -1; private int maxRequestRetry = 5; private final List<RequestFilter> requestFilters = new LinkedList<RequestFilter>(); private final List<ResponseFilter> responseFilters = new LinkedList<ResponseFilter>(); private final List<IOExceptionFilter> ioExceptionFilters = new LinkedList<IOExceptionFilter>(); private boolean allowSslConnectionPool = true; private boolean useRawUrl = false; private boolean removeQueryParamOnRedirect = true; private HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier(); private int ioThreadMultiplier = 2; private boolean strict302Handling; private boolean spdyEnabled; private int spdyInitialWindowSize = 10 * 1024 * 1024; private int spdyMaxConcurrentStreams = 100; public Builder() { } /** * Set the maximum number of connections an {@link AsyncHttpClient} can handle. * * @param defaultMaxTotalConnections the maximum number of connections an {@link AsyncHttpClient} can handle. * @return a {@link Builder} */ public Builder setMaximumConnectionsTotal(int defaultMaxTotalConnections) { this.defaultMaxTotalConnections = defaultMaxTotalConnections; return this; } /** * Set the maximum number of connections per hosts an {@link AsyncHttpClient} can handle. * * @param defaultMaxConnectionPerHost the maximum number of connections per host an {@link AsyncHttpClient} can handle. * @return a {@link Builder} */ public Builder setMaximumConnectionsPerHost(int defaultMaxConnectionPerHost) { this.defaultMaxConnectionPerHost = defaultMaxConnectionPerHost; return this; } /** * Set the maximum time in millisecond an {@link AsyncHttpClient} can wait when connecting to a remote host * * @param defaultConnectionTimeOutInMs the maximum time in millisecond an {@link AsyncHttpClient} can wait when connecting to a remote host * @return a {@link Builder} */ public Builder setConnectionTimeoutInMs(int defaultConnectionTimeOutInMs) { this.defaultConnectionTimeOutInMs = defaultConnectionTimeOutInMs; return this; } /** * Set the maximum time in millisecond an {@link org.asynchttpclient.websocket.WebSocket} can stay idle. * * @param defaultWebSocketIdleTimeoutInMs * the maximum time in millisecond an {@link org.asynchttpclient.websocket.WebSocket} can stay idle. * @return a {@link Builder} */ public Builder setWebSocketIdleTimeoutInMs(int defaultWebSocketIdleTimeoutInMs) { this.defaultWebsocketIdleTimeoutInMs = defaultWebSocketIdleTimeoutInMs; return this; } /** * Set the maximum time in millisecond an {@link AsyncHttpClient} can stay idle. * * @param defaultIdleConnectionTimeoutInMs * the maximum time in millisecond an {@link AsyncHttpClient} can stay idle. * @return a {@link Builder} */ public Builder setIdleConnectionTimeoutInMs(int defaultIdleConnectionTimeoutInMs) { this.defaultIdleConnectionTimeoutInMs = defaultIdleConnectionTimeoutInMs; return this; } /** * Set the maximum time in millisecond an {@link AsyncHttpClient} will keep connection * idle in pool. * * @param defaultIdleConnectionInPoolTimeoutInMs * the maximum time in millisecond an {@link AsyncHttpClient} will keep connection * idle in pool. * @return a {@link Builder} */ public Builder setIdleConnectionInPoolTimeoutInMs(int defaultIdleConnectionInPoolTimeoutInMs) { this.defaultIdleConnectionInPoolTimeoutInMs = defaultIdleConnectionInPoolTimeoutInMs; return this; } /** * Set the maximum time in millisecond an {@link AsyncHttpClient} wait for a response * * @param defaultRequestTimeoutInMs the maximum time in millisecond an {@link AsyncHttpClient} wait for a response * @return a {@link Builder} */ public Builder setRequestTimeoutInMs(int defaultRequestTimeoutInMs) { this.defaultRequestTimeoutInMs = defaultRequestTimeoutInMs; return this; } /** * Set to true to enable HTTP redirect * * @param redirectEnabled true if enabled. * @return a {@link Builder} */ public Builder setFollowRedirects(boolean redirectEnabled) { this.redirectEnabled = redirectEnabled; return this; } /** * Set the maximum number of HTTP redirect * * @param maxDefaultRedirects the maximum number of HTTP redirect * @return a {@link Builder} */ public Builder setMaximumNumberOfRedirects(int maxDefaultRedirects) { this.maxDefaultRedirects = maxDefaultRedirects; return this; } /** * Enable HTTP compression. * * @param compressionEnabled true if compression is enabled * @return a {@link Builder} */ public Builder setCompressionEnabled(boolean compressionEnabled) { this.compressionEnabled = compressionEnabled; return this; } /** * Set the USER_AGENT header value * * @param userAgent the USER_AGENT header value * @return a {@link Builder} */ public Builder setUserAgent(String userAgent) { this.userAgent = userAgent; return this; } /** * Set true if connection can be pooled by a {@link ConnectionsPool}. Default is true. * * @param allowPoolingConnection true if connection can be pooled by a {@link ConnectionsPool} * @return a {@link Builder} */ public Builder setAllowPoolingConnection(boolean allowPoolingConnection) { this.allowPoolingConnection = allowPoolingConnection; return this; } /** * Set true if connection can be pooled by a {@link ConnectionsPool}. Default is true. * * @param allowPoolingConnection true if connection can be pooled by a {@link ConnectionsPool} * @return a {@link Builder} * @deprecated - Use {@link AsyncHttpClientConfig.Builder#setAllowPoolingConnection(boolean)} */ public Builder setKeepAlive(boolean allowPoolingConnection) { this.allowPoolingConnection = allowPoolingConnection; return this; } /** * Set the{@link ScheduledExecutorService} used to expire idle connections. * * @param reaper the{@link ScheduledExecutorService} used to expire idle connections. * @return a {@link Builder} */ public Builder setScheduledExecutorService(ScheduledExecutorService reaper) { this.reaper = reaper; return this; } /** * Set the {@link java.util.concurrent.ExecutorService} an {@link AsyncHttpClient} use for handling * asynchronous response. * * @param applicationThreadPool the {@link java.util.concurrent.ExecutorService} an {@link AsyncHttpClient} use for handling * asynchronous response. * @return a {@link Builder} */ public Builder setExecutorService(ExecutorService applicationThreadPool) { this.applicationThreadPool = applicationThreadPool; return this; } /** * Set an instance of {@link ProxyServer} used by an {@link AsyncHttpClient} * * @param proxyServer instance of {@link ProxyServer} * @return a {@link Builder} */ public Builder setProxyServer(ProxyServer proxyServer) { this.proxyServer = proxyServer; return this; } /** * Set the {@link SSLEngineFactory} for secure connection. * * @param sslEngineFactory the {@link SSLEngineFactory} for secure connection * @return a {@link Builder} */ public Builder setSSLEngineFactory(SSLEngineFactory sslEngineFactory) { this.sslEngineFactory = sslEngineFactory; return this; } /** * Set the {@link SSLContext} for secure connection. * * @param sslContext the {@link SSLContext} for secure connection * @return a {@link Builder} */ public Builder setSSLContext(final SSLContext sslContext) { this.sslEngineFactory = new SSLEngineFactory() { public SSLEngine newSSLEngine() throws GeneralSecurityException { SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(true); return sslEngine; } }; this.sslContext = sslContext; return this; } /** * Set the {@link AsyncHttpProviderConfig} * * @param providerConfig the {@link AsyncHttpProviderConfig} * @return a {@link Builder} */ public Builder setAsyncHttpClientProviderConfig(AsyncHttpProviderConfig<?, ?> providerConfig) { this.providerConfig = providerConfig; return this; } /** * Set the {@link ConnectionsPool} * * @param connectionsPool the {@link ConnectionsPool} * @return a {@link Builder} */ public Builder setConnectionsPool(ConnectionsPool<?, ?> connectionsPool) { this.connectionsPool = connectionsPool; return this; } /** * Set the {@link Realm} that will be used for all requests. * * @param realm the {@link Realm} * @return a {@link Builder} */ public Builder setRealm(Realm realm) { this.realm = realm; return this; } /** * Add an {@link org.asynchttpclient.filter.RequestFilter} that will be invoked before {@link AsyncHttpClient#executeRequest(Request)} * * @param requestFilter {@link org.asynchttpclient.filter.RequestFilter} * @return this */ public Builder addRequestFilter(RequestFilter requestFilter) { requestFilters.add(requestFilter); return this; } /** * Remove an {@link org.asynchttpclient.filter.RequestFilter} that will be invoked before {@link AsyncHttpClient#executeRequest(Request)} * * @param requestFilter {@link org.asynchttpclient.filter.RequestFilter} * @return this */ public Builder removeRequestFilter(RequestFilter requestFilter) { requestFilters.remove(requestFilter); return this; } /** * Add an {@link org.asynchttpclient.filter.ResponseFilter} that will be invoked as soon as the response is * received, and before {@link AsyncHandler#onStatusReceived(HttpResponseStatus)}. * * @param responseFilter an {@link org.asynchttpclient.filter.ResponseFilter} * @return this */ public Builder addResponseFilter(ResponseFilter responseFilter) { responseFilters.add(responseFilter); return this; } /** * Remove an {@link org.asynchttpclient.filter.ResponseFilter} that will be invoked as soon as the response is * received, and before {@link AsyncHandler#onStatusReceived(HttpResponseStatus)}. * * @param responseFilter an {@link org.asynchttpclient.filter.ResponseFilter} * @return this */ public Builder removeResponseFilter(ResponseFilter responseFilter) { responseFilters.remove(responseFilter); return this; } /** * Add an {@link org.asynchttpclient.filter.IOExceptionFilter} that will be invoked when an {@link java.io.IOException} * occurs during the download/upload operations. * * @param ioExceptionFilter an {@link org.asynchttpclient.filter.ResponseFilter} * @return this */ public Builder addIOExceptionFilter(IOExceptionFilter ioExceptionFilter) { ioExceptionFilters.add(ioExceptionFilter); return this; } /** * Remove an {@link org.asynchttpclient.filter.IOExceptionFilter} tthat will be invoked when an {@link java.io.IOException} * occurs during the download/upload operations. * * @param ioExceptionFilter an {@link org.asynchttpclient.filter.ResponseFilter} * @return this */ public Builder removeIOExceptionFilter(IOExceptionFilter ioExceptionFilter) { ioExceptionFilters.remove(ioExceptionFilter); return this; } /** * Return the compression level, or -1 if no compression is used. * * @return the compression level, or -1 if no compression is use */ public int getRequestCompressionLevel() { return requestCompressionLevel; } /** * Set the compression level, or -1 if no compression is used. * * @param requestCompressionLevel compression level, or -1 if no compression is use * @return this */ public Builder setRequestCompressionLevel(int requestCompressionLevel) { this.requestCompressionLevel = requestCompressionLevel; return this; } /** * Set the number of times a request will be retried when an {@link java.io.IOException} occurs because of a Network exception. * * @param maxRequestRetry the number of times a request will be retried * @return this */ public Builder setMaxRequestRetry(int maxRequestRetry) { this.maxRequestRetry = maxRequestRetry; return this; } /** * Return true is if connections pooling is enabled. * * @param allowSslConnectionPool true if enabled * @return this */ public Builder setAllowSslConnectionPool(boolean allowSslConnectionPool) { this.allowSslConnectionPool = allowSslConnectionPool; return this; } /** * Allows use unescaped URLs in requests * useful for retrieving data from broken sites * * @param useRawUrl * @return this */ public Builder setUseRawUrl(boolean useRawUrl) { this.useRawUrl = useRawUrl; return this; } /** * Set to false if you don't want the query parameters removed when a redirect occurs. * * @param removeQueryParamOnRedirect * @return this */ public Builder setRemoveQueryParamsOnRedirect(boolean removeQueryParamOnRedirect) { this.removeQueryParamOnRedirect = removeQueryParamOnRedirect; return this; } /** * Sets whether AHC should use the default http.proxy* system properties * to obtain proxy information. * <p/> * If useProxyProperties is set to <code>true</code> but {@link #setProxyServer(ProxyServer)} was used * to explicitly set a proxy server, the latter is preferred. * <p/> * See http://download.oracle.com/javase/1.4.2/docs/guide/net/properties.html */ public Builder setUseProxyProperties(boolean useProxyProperties) { this.useProxyProperties = useProxyProperties; return this; } public Builder setIOThreadMultiplier(int multiplier) { this.ioThreadMultiplier = multiplier; return this; } /** * Set the {@link HostnameVerifier} * * @param hostnameVerifier {@link HostnameVerifier} * @return this */ public Builder setHostnameVerifier(HostnameVerifier hostnameVerifier) { this.hostnameVerifier = hostnameVerifier; return this; } /** * Configures this AHC instance to be strict in it's handling of 302 redirects * in a POST/Redirect/GET situation. * * @param strict302Handling strict handling * * @return this * * @since 1.7.2 */ public Builder setStrict302Handling(final boolean strict302Handling) { this.strict302Handling = strict302Handling; return this; } /** * Set the maximum time in millisecond connection can be added to the pool for further reuse * * @param maxConnectionLifeTimeInMs the maximum time in millisecond connection can be added to the pool for further reuse * @return a {@link Builder} */ public Builder setMaxConnectionLifeTimeInMs(int maxConnectionLifeTimeInMs) { this.defaultMaxConnectionLifeTimeInMs = maxConnectionLifeTimeInMs; return this; } /** * Configures this AHC instance to use relative URIs instead of absolute ones when talking with a SSL proxy. * * @param useRelativeURIsWithSSLProxies * @return this * * @since 1.7.2 */ public Builder setUseRelativeURIsWithSSLProxies(boolean useRelativeURIsWithSSLProxies) { this.useRelativeURIsWithSSLProxies = useRelativeURIsWithSSLProxies; return this; } /** * Enables SPDY support. Note that doing so, will currently disable WebSocket support * for this client instance. If not explicitly enabled, spdy will not be used. * * @param spdyEnabled configures spdy support. * * @return this * * @since 2.0 */ public Builder setSpdyEnabled(boolean spdyEnabled) { this.spdyEnabled = spdyEnabled; return this; } /** * Configures the initial window size for the SPDY session. * * @param spdyInitialWindowSize the initial window size. * * @return this * * @since 2.0 */ public Builder setSpdyInitialWindowSize(int spdyInitialWindowSize) { this.spdyInitialWindowSize = spdyInitialWindowSize; return this; } /** * Configures the maximum number of concurrent streams over a single * SPDY session. * * @param spdyMaxConcurrentStreams the maximum number of concurrent * streams over a single SPDY session. * * @return this * * @since 2.0 */ public Builder setSpdyMaxConcurrentStreams(int spdyMaxConcurrentStreams) { this.spdyMaxConcurrentStreams = spdyMaxConcurrentStreams; return this; } /** * Create a config builder with values taken from the given prototype configuration. * * @param prototype the configuration to use as a prototype. */ public Builder(AsyncHttpClientConfig prototype) { allowPoolingConnection = prototype.getAllowPoolingConnection(); providerConfig = prototype.getAsyncHttpProviderConfig(); connectionsPool = prototype.getConnectionsPool(); defaultConnectionTimeOutInMs = prototype.getConnectionTimeoutInMs(); defaultIdleConnectionInPoolTimeoutInMs = prototype.getIdleConnectionInPoolTimeoutInMs(); defaultIdleConnectionTimeoutInMs = prototype.getIdleConnectionTimeoutInMs(); defaultMaxConnectionPerHost = prototype.getMaxConnectionPerHost(); defaultMaxConnectionLifeTimeInMs = prototype.getMaxConnectionLifeTimeInMs(); maxDefaultRedirects = prototype.getMaxRedirects(); defaultMaxTotalConnections = prototype.getMaxTotalConnections(); proxyServer = prototype.getProxyServer(); realm = prototype.getRealm(); defaultRequestTimeoutInMs = prototype.getRequestTimeoutInMs(); sslContext = prototype.getSSLContext(); sslEngineFactory = prototype.getSSLEngineFactory(); userAgent = prototype.getUserAgent(); redirectEnabled = prototype.isRedirectEnabled(); compressionEnabled = prototype.isCompressionEnabled(); reaper = prototype.reaper(); applicationThreadPool = prototype.executorService(); requestFilters.clear(); responseFilters.clear(); ioExceptionFilters.clear(); requestFilters.addAll(prototype.getRequestFilters()); responseFilters.addAll(prototype.getResponseFilters()); ioExceptionFilters.addAll(prototype.getIOExceptionFilters()); requestCompressionLevel = prototype.getRequestCompressionLevel(); useRawUrl = prototype.isUseRawUrl(); ioThreadMultiplier = prototype.getIoThreadMultiplier(); maxRequestRetry = prototype.getMaxRequestRetry(); allowSslConnectionPool = prototype.getAllowPoolingConnection(); removeQueryParamOnRedirect = prototype.isRemoveQueryParamOnRedirect(); hostnameVerifier = prototype.getHostnameVerifier(); strict302Handling = prototype.isStrict302Handling(); useRelativeURIsWithSSLProxies = prototype.isUseRelativeURIsWithSSLProxies(); } /** * Build an {@link AsyncHttpClientConfig} * * @return an {@link AsyncHttpClientConfig} */ public AsyncHttpClientConfig build() { if (reaper == null) { reaper = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r, "AsyncHttpClient-Reaper"); t.setDaemon(true); return t; } }); } if (applicationThreadPool == null) { applicationThreadPool = Executors.newCachedThreadPool(new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r, "AsyncHttpClient-Callback"); t.setDaemon(true); return t; } }); } if (applicationThreadPool.isShutdown()) { throw new IllegalStateException("ExecutorServices closed"); } if (proxyServer == null && useProxyProperties) { proxyServer = ProxyUtils.createProxy(System.getProperties()); } return new AsyncHttpClientConfig(defaultMaxTotalConnections, defaultMaxConnectionPerHost, defaultConnectionTimeOutInMs, defaultWebsocketIdleTimeoutInMs, defaultIdleConnectionInPoolTimeoutInMs, defaultIdleConnectionTimeoutInMs, defaultRequestTimeoutInMs, defaultMaxConnectionLifeTimeInMs, redirectEnabled, maxDefaultRedirects, compressionEnabled, userAgent, allowPoolingConnection, reaper, applicationThreadPool, proxyServer, sslContext, sslEngineFactory, providerConfig, connectionsPool, realm, requestFilters, responseFilters, ioExceptionFilters, requestCompressionLevel, maxRequestRetry, allowSslConnectionPool, useRawUrl, removeQueryParamOnRedirect, hostnameVerifier, ioThreadMultiplier, strict302Handling, useRelativeURIsWithSSLProxies, spdyEnabled, spdyInitialWindowSize, spdyMaxConcurrentStreams); } } }
api/src/main/java/org/asynchttpclient/AsyncHttpClientConfig.java
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.asynchttpclient; import org.asynchttpclient.filter.IOExceptionFilter; import org.asynchttpclient.filter.RequestFilter; import org.asynchttpclient.filter.ResponseFilter; import org.asynchttpclient.util.AllowAllHostnameVerifier; import org.asynchttpclient.util.ProxyUtils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; /** * Configuration class to use with a {@link AsyncHttpClient}. System property can be also used to configure this * object default behavior by doing: * <p/> * -Dorg.asynchttpclient.AsyncHttpClientConfig.nameOfTheProperty * ex: * <p/> * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultMaxTotalConnections * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultMaxTotalConnections * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultMaxConnectionsPerHost * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultConnectionTimeoutInMS * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultIdleConnectionInPoolTimeoutInMS * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultRequestTimeoutInMS * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultRedirectsEnabled * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultMaxRedirects */ public class AsyncHttpClientConfig { protected final static String ASYNC_CLIENT = AsyncHttpClientConfig.class.getName() + "."; public final static String AHC_VERSION; static { InputStream is = null; Properties prop = new Properties(); try { is = AsyncHttpClientConfig.class.getResourceAsStream("version.properties"); prop.load(is); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException ignored) { } } } AHC_VERSION = prop.getProperty("ahc.version", "UNKNOWN"); } protected int maxTotalConnections; protected int maxConnectionPerHost; protected int connectionTimeOutInMs; protected int webSocketIdleTimeoutInMs; protected int idleConnectionInPoolTimeoutInMs; protected int idleConnectionTimeoutInMs; protected int requestTimeoutInMs; protected boolean redirectEnabled; protected int maxDefaultRedirects; protected boolean compressionEnabled; protected String userAgent; protected boolean allowPoolingConnection; protected ScheduledExecutorService reaper; protected ExecutorService applicationThreadPool; protected ProxyServer proxyServer; protected SSLContext sslContext; protected SSLEngineFactory sslEngineFactory; protected AsyncHttpProviderConfig<?, ?> providerConfig; protected ConnectionsPool<?, ?> connectionsPool; protected Realm realm; protected List<RequestFilter> requestFilters; protected List<ResponseFilter> responseFilters; protected List<IOExceptionFilter> ioExceptionFilters; protected int requestCompressionLevel; protected int maxRequestRetry; protected boolean allowSslConnectionPool; protected boolean useRawUrl; protected boolean removeQueryParamOnRedirect; protected HostnameVerifier hostnameVerifier; protected int ioThreadMultiplier; protected boolean strict302Handling; protected int maxConnectionLifeTimeInMs; protected boolean useRelativeURIsWithSSLProxies; protected boolean spdyEnabled; protected int spdyInitialWindowSize; protected int spdyMaxConcurrentStreams; protected AsyncHttpClientConfig() { } private AsyncHttpClientConfig(int maxTotalConnections, int maxConnectionPerHost, int connectionTimeOutInMs, int webSocketTimeoutInMs, int idleConnectionInPoolTimeoutInMs, int idleConnectionTimeoutInMs, int requestTimeoutInMs, int connectionMaxLifeTimeInMs, boolean redirectEnabled, int maxDefaultRedirects, boolean compressionEnabled, String userAgent, boolean keepAlive, ScheduledExecutorService reaper, ExecutorService applicationThreadPool, ProxyServer proxyServer, SSLContext sslContext, SSLEngineFactory sslEngineFactory, AsyncHttpProviderConfig<?, ?> providerConfig, ConnectionsPool<?, ?> connectionsPool, Realm realm, List<RequestFilter> requestFilters, List<ResponseFilter> responseFilters, List<IOExceptionFilter> ioExceptionFilters, int requestCompressionLevel, int maxRequestRetry, boolean allowSslConnectionCaching, boolean useRawUrl, boolean removeQueryParamOnRedirect, HostnameVerifier hostnameVerifier, int ioThreadMultiplier, boolean strict302Handling, boolean useRelativeURIsWithSSLProxies, boolean spdyEnabled, int spdyInitialWindowSize, int spdyMaxConcurrentStreams) { this.maxTotalConnections = maxTotalConnections; this.maxConnectionPerHost = maxConnectionPerHost; this.connectionTimeOutInMs = connectionTimeOutInMs; this.webSocketIdleTimeoutInMs = webSocketTimeoutInMs; this.idleConnectionInPoolTimeoutInMs = idleConnectionInPoolTimeoutInMs; this.idleConnectionTimeoutInMs = idleConnectionTimeoutInMs; this.requestTimeoutInMs = requestTimeoutInMs; this.maxConnectionLifeTimeInMs = connectionMaxLifeTimeInMs; this.redirectEnabled = redirectEnabled; this.maxDefaultRedirects = maxDefaultRedirects; this.compressionEnabled = compressionEnabled; this.userAgent = userAgent; this.allowPoolingConnection = keepAlive; this.sslContext = sslContext; this.sslEngineFactory = sslEngineFactory; this.providerConfig = providerConfig; this.connectionsPool = connectionsPool; this.realm = realm; this.requestFilters = requestFilters; this.responseFilters = responseFilters; this.ioExceptionFilters = ioExceptionFilters; this.requestCompressionLevel = requestCompressionLevel; this.maxRequestRetry = maxRequestRetry; this.reaper = reaper; this.allowSslConnectionPool = allowSslConnectionCaching; this.removeQueryParamOnRedirect = removeQueryParamOnRedirect; this.hostnameVerifier = hostnameVerifier; this.ioThreadMultiplier = ioThreadMultiplier; this.strict302Handling = strict302Handling; this.useRelativeURIsWithSSLProxies = useRelativeURIsWithSSLProxies; if (applicationThreadPool == null) { this.applicationThreadPool = Executors.newCachedThreadPool(); } else { this.applicationThreadPool = applicationThreadPool; } this.proxyServer = proxyServer; this.useRawUrl = useRawUrl; this.spdyEnabled = spdyEnabled; this.spdyInitialWindowSize = spdyInitialWindowSize; this.spdyMaxConcurrentStreams = spdyMaxConcurrentStreams; } /** * A {@link ScheduledExecutorService} used to expire idle connections. * * @return {@link ScheduledExecutorService} */ public ScheduledExecutorService reaper() { return reaper; } /** * Return the maximum number of connections an {@link AsyncHttpClient} can handle. * * @return the maximum number of connections an {@link AsyncHttpClient} can handle. */ public int getMaxTotalConnections() { return maxTotalConnections; } /** * Return the maximum number of connections per hosts an {@link AsyncHttpClient} can handle. * * @return the maximum number of connections per host an {@link AsyncHttpClient} can handle. */ public int getMaxConnectionPerHost() { return maxConnectionPerHost; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} can wait when connecting to a remote host * * @return the maximum time in millisecond an {@link AsyncHttpClient} can wait when connecting to a remote host */ public int getConnectionTimeoutInMs() { return connectionTimeOutInMs; } /** * Return the maximum time, in milliseconds, a {@link org.asynchttpclient.websocket.WebSocket} may be idle before being timed out. * @return the maximum time, in milliseconds, a {@link org.asynchttpclient.websocket.WebSocket} may be idle before being timed out. */ public int getWebSocketIdleTimeoutInMs() { return webSocketIdleTimeoutInMs; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} can stay idle. * * @return the maximum time in millisecond an {@link AsyncHttpClient} can stay idle. */ public int getIdleConnectionTimeoutInMs() { return idleConnectionTimeoutInMs; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} will keep connection * in pool. * * @return the maximum time in millisecond an {@link AsyncHttpClient} will keep connection * in pool. */ public int getIdleConnectionInPoolTimeoutInMs() { return idleConnectionInPoolTimeoutInMs; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} wait for a response * * @return the maximum time in millisecond an {@link AsyncHttpClient} wait for a response */ public int getRequestTimeoutInMs() { return requestTimeoutInMs; } /** * Is HTTP redirect enabled * * @return true if enabled. */ public boolean isRedirectEnabled() { return redirectEnabled; } /** * Get the maximum number of HTTP redirect * * @return the maximum number of HTTP redirect */ public int getMaxRedirects() { return maxDefaultRedirects; } /** * Is the {@link ConnectionsPool} support enabled. * * @return true if keep-alive is enabled */ public boolean getAllowPoolingConnection() { return allowPoolingConnection; } /** * Is the {@link ConnectionsPool} support enabled. * * @return true if keep-alive is enabled * @deprecated - Use {@link AsyncHttpClientConfig#getAllowPoolingConnection()} */ public boolean getKeepAlive() { return allowPoolingConnection; } /** * Return the USER_AGENT header value * * @return the USER_AGENT header value */ public String getUserAgent() { return userAgent; } /** * Is HTTP compression enabled. * * @return true if compression is enabled */ public boolean isCompressionEnabled() { return compressionEnabled; } /** * Return the {@link java.util.concurrent.ExecutorService} an {@link AsyncHttpClient} use for handling * asynchronous response. * * @return the {@link java.util.concurrent.ExecutorService} an {@link AsyncHttpClient} use for handling * asynchronous response. */ public ExecutorService executorService() { return applicationThreadPool; } /** * An instance of {@link ProxyServer} used by an {@link AsyncHttpClient} * * @return instance of {@link ProxyServer} */ public ProxyServer getProxyServer() { return proxyServer; } /** * Return an instance of {@link SSLContext} used for SSL connection. * * @return an instance of {@link SSLContext} used for SSL connection. */ public SSLContext getSSLContext() { return sslContext; } /** * Return an instance of {@link ConnectionsPool} * * @return an instance of {@link ConnectionsPool} */ public ConnectionsPool<?, ?> getConnectionsPool() { return connectionsPool; } /** * Return an instance of {@link SSLEngineFactory} used for SSL connection. * * @return an instance of {@link SSLEngineFactory} used for SSL connection. */ public SSLEngineFactory getSSLEngineFactory() { if (sslEngineFactory == null) { return new SSLEngineFactory() { public SSLEngine newSSLEngine() { if (sslContext != null) { SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(true); return sslEngine; } else { return null; } } }; } return sslEngineFactory; } /** * Return the {@link AsyncHttpProviderConfig} * * @return the {@link AsyncHttpProviderConfig} */ public AsyncHttpProviderConfig<?, ?> getAsyncHttpProviderConfig() { return providerConfig; } /** * Return the current {@link Realm}} * * @return the current {@link Realm}} */ public Realm getRealm() { return realm; } /** * Return the list of {@link RequestFilter} * * @return Unmodifiable list of {@link ResponseFilter} */ public List<RequestFilter> getRequestFilters() { return Collections.unmodifiableList(requestFilters); } /** * Return the list of {@link ResponseFilter} * * @return Unmodifiable list of {@link ResponseFilter} */ public List<ResponseFilter> getResponseFilters() { return Collections.unmodifiableList(responseFilters); } /** * Return the list of {@link java.io.IOException} * * @return Unmodifiable list of {@link java.io.IOException} */ public List<IOExceptionFilter> getIOExceptionFilters() { return Collections.unmodifiableList(ioExceptionFilters); } /** * Return the compression level, or -1 if no compression is used. * * @return the compression level, or -1 if no compression is use */ public int getRequestCompressionLevel() { return requestCompressionLevel; } /** * Return the number of time the library will retry when an {@link java.io.IOException} is throw by the remote server * * @return the number of time the library will retry when an {@link java.io.IOException} is throw by the remote server */ public int getMaxRequestRetry() { return maxRequestRetry; } /** * Return true is SSL connection polling is enabled. Default is true. * * @return true is enabled. */ public boolean isSslConnectionPoolEnabled() { return allowSslConnectionPool; } /** * @return the useRawUrl */ public boolean isUseRawUrl() { return useRawUrl; } /** * @return whether or not SPDY is enabled. */ public boolean isSpdyEnabled() { return spdyEnabled; } /** * @return the windows size new SPDY sessions should be initialized to. */ public int getSpdyInitialWindowSize() { return spdyInitialWindowSize; } /** * @return the maximum number of concurrent streams over one SPDY session. */ public int getSpdyMaxConcurrentStreams() { return spdyMaxConcurrentStreams; } /** * Return true if the query parameters will be stripped from the request when a redirect is requested. * * @return true if the query parameters will be stripped from the request when a redirect is requested. */ public boolean isRemoveQueryParamOnRedirect() { return removeQueryParamOnRedirect; } /** * Return true if one of the {@link java.util.concurrent.ExecutorService} has been shutdown. * * @return true if one of the {@link java.util.concurrent.ExecutorService} has been shutdown. */ public boolean isClosed() { return applicationThreadPool.isShutdown() || reaper.isShutdown(); } /** * Return the {@link HostnameVerifier} * * @return the {@link HostnameVerifier} */ public HostnameVerifier getHostnameVerifier() { return hostnameVerifier; } /** * @return number to multiply by availableProcessors() that will determine # of NioWorkers to use */ public int getIoThreadMultiplier() { return ioThreadMultiplier; } /** * <p> * In the case of a POST/Redirect/Get scenario where the server uses a 302 * for the redirect, should AHC respond to the redirect with a GET or * whatever the original method was. Unless configured otherwise, * for a 302, AHC, will use a GET for this case. * </p> * * @return <code>true</code> if string 302 handling is to be used, * otherwise <code>false</code>. * * @since 1.7.2 */ public boolean isStrict302Handling() { return strict302Handling; } /** * @return<code>true</code> if AHC should use relative URIs instead of absolute ones when talking with a SSL proxy, * otherwise <code>false</code>. * * @since 1.7.12 */ public boolean isUseRelativeURIsWithSSLProxies() { return useRelativeURIsWithSSLProxies; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} will keep connection in the pool, or -1 to keep connection while possible. * * @return the maximum time in millisecond an {@link AsyncHttpClient} will keep connection in the pool, or -1 to keep connection while possible. */ public int getMaxConnectionLifeTimeInMs() { return maxConnectionLifeTimeInMs; } /** * Builder for an {@link AsyncHttpClient} */ public static class Builder { private int defaultMaxTotalConnections = Integer.getInteger(ASYNC_CLIENT + "defaultMaxTotalConnections", -1); private int defaultMaxConnectionPerHost = Integer.getInteger(ASYNC_CLIENT + "defaultMaxConnectionsPerHost", -1); private int defaultConnectionTimeOutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultConnectionTimeoutInMS", 60 * 1000); private int defaultWebsocketIdleTimeoutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultWebsocketTimoutInMS", 15 * 60 * 1000); private int defaultIdleConnectionInPoolTimeoutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultIdleConnectionInPoolTimeoutInMS", 60 * 1000); private int defaultIdleConnectionTimeoutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultIdleConnectionTimeoutInMS", 60 * 1000); private int defaultRequestTimeoutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultRequestTimeoutInMS", 60 * 1000); private int defaultMaxConnectionLifeTimeInMs = Integer.getInteger(ASYNC_CLIENT + "defaultMaxConnectionLifeTimeInMs", -1); private boolean redirectEnabled = Boolean.getBoolean(ASYNC_CLIENT + "defaultRedirectsEnabled"); private int maxDefaultRedirects = Integer.getInteger(ASYNC_CLIENT + "defaultMaxRedirects", 5); private boolean compressionEnabled = Boolean.getBoolean(ASYNC_CLIENT + "compressionEnabled"); private String userAgent = System.getProperty(ASYNC_CLIENT + "userAgent", "AsyncHttpClient/" + AHC_VERSION); private boolean useProxyProperties = Boolean.getBoolean(ASYNC_CLIENT + "useProxyProperties"); private boolean allowPoolingConnection = true; private boolean useRelativeURIsWithSSLProxies = Boolean.getBoolean(ASYNC_CLIENT + "useRelativeURIsWithSSLProxies"); private ScheduledExecutorService reaper; private ExecutorService applicationThreadPool; private ProxyServer proxyServer = null; private SSLContext sslContext; private SSLEngineFactory sslEngineFactory; private AsyncHttpProviderConfig<?, ?> providerConfig; private ConnectionsPool<?, ?> connectionsPool; private Realm realm; private int requestCompressionLevel = -1; private int maxRequestRetry = 5; private final List<RequestFilter> requestFilters = new LinkedList<RequestFilter>(); private final List<ResponseFilter> responseFilters = new LinkedList<ResponseFilter>(); private final List<IOExceptionFilter> ioExceptionFilters = new LinkedList<IOExceptionFilter>(); private boolean allowSslConnectionPool = true; private boolean useRawUrl = false; private boolean removeQueryParamOnRedirect = true; private HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier(); private int ioThreadMultiplier = 2; private boolean strict302Handling; private boolean spdyEnabled; private int spdyInitialWindowSize = 10 * 1024 * 1024; private int spdyMaxConcurrentStreams = 100; public Builder() { } /** * Set the maximum number of connections an {@link AsyncHttpClient} can handle. * * @param defaultMaxTotalConnections the maximum number of connections an {@link AsyncHttpClient} can handle. * @return a {@link Builder} */ public Builder setMaximumConnectionsTotal(int defaultMaxTotalConnections) { this.defaultMaxTotalConnections = defaultMaxTotalConnections; return this; } /** * Set the maximum number of connections per hosts an {@link AsyncHttpClient} can handle. * * @param defaultMaxConnectionPerHost the maximum number of connections per host an {@link AsyncHttpClient} can handle. * @return a {@link Builder} */ public Builder setMaximumConnectionsPerHost(int defaultMaxConnectionPerHost) { this.defaultMaxConnectionPerHost = defaultMaxConnectionPerHost; return this; } /** * Set the maximum time in millisecond an {@link AsyncHttpClient} can wait when connecting to a remote host * * @param defaultConnectionTimeOutInMs the maximum time in millisecond an {@link AsyncHttpClient} can wait when connecting to a remote host * @return a {@link Builder} */ public Builder setConnectionTimeoutInMs(int defaultConnectionTimeOutInMs) { this.defaultConnectionTimeOutInMs = defaultConnectionTimeOutInMs; return this; } /** * Set the maximum time in millisecond an {@link org.asynchttpclient.websocket.WebSocket} can stay idle. * * @param defaultWebSocketIdleTimeoutInMs * the maximum time in millisecond an {@link org.asynchttpclient.websocket.WebSocket} can stay idle. * @return a {@link Builder} */ public Builder setWebSocketIdleTimeoutInMs(int defaultWebSocketIdleTimeoutInMs) { this.defaultWebsocketIdleTimeoutInMs = defaultWebSocketIdleTimeoutInMs; return this; } /** * Set the maximum time in millisecond an {@link AsyncHttpClient} can stay idle. * * @param defaultIdleConnectionTimeoutInMs * the maximum time in millisecond an {@link AsyncHttpClient} can stay idle. * @return a {@link Builder} */ public Builder setIdleConnectionTimeoutInMs(int defaultIdleConnectionTimeoutInMs) { this.defaultIdleConnectionTimeoutInMs = defaultIdleConnectionTimeoutInMs; return this; } /** * Set the maximum time in millisecond an {@link AsyncHttpClient} will keep connection * idle in pool. * * @param defaultIdleConnectionInPoolTimeoutInMs * the maximum time in millisecond an {@link AsyncHttpClient} will keep connection * idle in pool. * @return a {@link Builder} */ public Builder setIdleConnectionInPoolTimeoutInMs(int defaultIdleConnectionInPoolTimeoutInMs) { this.defaultIdleConnectionInPoolTimeoutInMs = defaultIdleConnectionInPoolTimeoutInMs; return this; } /** * Set the maximum time in millisecond an {@link AsyncHttpClient} wait for a response * * @param defaultRequestTimeoutInMs the maximum time in millisecond an {@link AsyncHttpClient} wait for a response * @return a {@link Builder} */ public Builder setRequestTimeoutInMs(int defaultRequestTimeoutInMs) { this.defaultRequestTimeoutInMs = defaultRequestTimeoutInMs; return this; } /** * Set to true to enable HTTP redirect * * @param redirectEnabled true if enabled. * @return a {@link Builder} */ public Builder setFollowRedirects(boolean redirectEnabled) { this.redirectEnabled = redirectEnabled; return this; } /** * Set the maximum number of HTTP redirect * * @param maxDefaultRedirects the maximum number of HTTP redirect * @return a {@link Builder} */ public Builder setMaximumNumberOfRedirects(int maxDefaultRedirects) { this.maxDefaultRedirects = maxDefaultRedirects; return this; } /** * Enable HTTP compression. * * @param compressionEnabled true if compression is enabled * @return a {@link Builder} */ public Builder setCompressionEnabled(boolean compressionEnabled) { this.compressionEnabled = compressionEnabled; return this; } /** * Set the USER_AGENT header value * * @param userAgent the USER_AGENT header value * @return a {@link Builder} */ public Builder setUserAgent(String userAgent) { this.userAgent = userAgent; return this; } /** * Set true if connection can be pooled by a {@link ConnectionsPool}. Default is true. * * @param allowPoolingConnection true if connection can be pooled by a {@link ConnectionsPool} * @return a {@link Builder} */ public Builder setAllowPoolingConnection(boolean allowPoolingConnection) { this.allowPoolingConnection = allowPoolingConnection; return this; } /** * Set true if connection can be pooled by a {@link ConnectionsPool}. Default is true. * * @param allowPoolingConnection true if connection can be pooled by a {@link ConnectionsPool} * @return a {@link Builder} * @deprecated - Use {@link AsyncHttpClientConfig.Builder#setAllowPoolingConnection(boolean)} */ public Builder setKeepAlive(boolean allowPoolingConnection) { this.allowPoolingConnection = allowPoolingConnection; return this; } /** * Set the{@link ScheduledExecutorService} used to expire idle connections. * * @param reaper the{@link ScheduledExecutorService} used to expire idle connections. * @return a {@link Builder} */ public Builder setScheduledExecutorService(ScheduledExecutorService reaper) { this.reaper = reaper; return this; } /** * Set the {@link java.util.concurrent.ExecutorService} an {@link AsyncHttpClient} use for handling * asynchronous response. * * @param applicationThreadPool the {@link java.util.concurrent.ExecutorService} an {@link AsyncHttpClient} use for handling * asynchronous response. * @return a {@link Builder} */ public Builder setExecutorService(ExecutorService applicationThreadPool) { this.applicationThreadPool = applicationThreadPool; return this; } /** * Set an instance of {@link ProxyServer} used by an {@link AsyncHttpClient} * * @param proxyServer instance of {@link ProxyServer} * @return a {@link Builder} */ public Builder setProxyServer(ProxyServer proxyServer) { this.proxyServer = proxyServer; return this; } /** * Set the {@link SSLEngineFactory} for secure connection. * * @param sslEngineFactory the {@link SSLEngineFactory} for secure connection * @return a {@link Builder} */ public Builder setSSLEngineFactory(SSLEngineFactory sslEngineFactory) { this.sslEngineFactory = sslEngineFactory; return this; } /** * Set the {@link SSLContext} for secure connection. * * @param sslContext the {@link SSLContext} for secure connection * @return a {@link Builder} */ public Builder setSSLContext(final SSLContext sslContext) { this.sslEngineFactory = new SSLEngineFactory() { public SSLEngine newSSLEngine() throws GeneralSecurityException { SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(true); return sslEngine; } }; this.sslContext = sslContext; return this; } /** * Set the {@link AsyncHttpProviderConfig} * * @param providerConfig the {@link AsyncHttpProviderConfig} * @return a {@link Builder} */ public Builder setAsyncHttpClientProviderConfig(AsyncHttpProviderConfig<?, ?> providerConfig) { this.providerConfig = providerConfig; return this; } /** * Set the {@link ConnectionsPool} * * @param connectionsPool the {@link ConnectionsPool} * @return a {@link Builder} */ public Builder setConnectionsPool(ConnectionsPool<?, ?> connectionsPool) { this.connectionsPool = connectionsPool; return this; } /** * Set the {@link Realm} that will be used for all requests. * * @param realm the {@link Realm} * @return a {@link Builder} */ public Builder setRealm(Realm realm) { this.realm = realm; return this; } /** * Add an {@link org.asynchttpclient.filter.RequestFilter} that will be invoked before {@link AsyncHttpClient#executeRequest(Request)} * * @param requestFilter {@link org.asynchttpclient.filter.RequestFilter} * @return this */ public Builder addRequestFilter(RequestFilter requestFilter) { requestFilters.add(requestFilter); return this; } /** * Remove an {@link org.asynchttpclient.filter.RequestFilter} that will be invoked before {@link AsyncHttpClient#executeRequest(Request)} * * @param requestFilter {@link org.asynchttpclient.filter.RequestFilter} * @return this */ public Builder removeRequestFilter(RequestFilter requestFilter) { requestFilters.remove(requestFilter); return this; } /** * Add an {@link org.asynchttpclient.filter.ResponseFilter} that will be invoked as soon as the response is * received, and before {@link AsyncHandler#onStatusReceived(HttpResponseStatus)}. * * @param responseFilter an {@link org.asynchttpclient.filter.ResponseFilter} * @return this */ public Builder addResponseFilter(ResponseFilter responseFilter) { responseFilters.add(responseFilter); return this; } /** * Remove an {@link org.asynchttpclient.filter.ResponseFilter} that will be invoked as soon as the response is * received, and before {@link AsyncHandler#onStatusReceived(HttpResponseStatus)}. * * @param responseFilter an {@link org.asynchttpclient.filter.ResponseFilter} * @return this */ public Builder removeResponseFilter(ResponseFilter responseFilter) { responseFilters.remove(responseFilter); return this; } /** * Add an {@link org.asynchttpclient.filter.IOExceptionFilter} that will be invoked when an {@link java.io.IOException} * occurs during the download/upload operations. * * @param ioExceptionFilter an {@link org.asynchttpclient.filter.ResponseFilter} * @return this */ public Builder addIOExceptionFilter(IOExceptionFilter ioExceptionFilter) { ioExceptionFilters.add(ioExceptionFilter); return this; } /** * Remove an {@link org.asynchttpclient.filter.IOExceptionFilter} tthat will be invoked when an {@link java.io.IOException} * occurs during the download/upload operations. * * @param ioExceptionFilter an {@link org.asynchttpclient.filter.ResponseFilter} * @return this */ public Builder removeIOExceptionFilter(IOExceptionFilter ioExceptionFilter) { ioExceptionFilters.remove(ioExceptionFilter); return this; } /** * Return the compression level, or -1 if no compression is used. * * @return the compression level, or -1 if no compression is use */ public int getRequestCompressionLevel() { return requestCompressionLevel; } /** * Set the compression level, or -1 if no compression is used. * * @param requestCompressionLevel compression level, or -1 if no compression is use * @return this */ public Builder setRequestCompressionLevel(int requestCompressionLevel) { this.requestCompressionLevel = requestCompressionLevel; return this; } /** * Set the number of times a request will be retried when an {@link java.io.IOException} occurs because of a Network exception. * * @param maxRequestRetry the number of times a request will be retried * @return this */ public Builder setMaxRequestRetry(int maxRequestRetry) { this.maxRequestRetry = maxRequestRetry; return this; } /** * Return true is if connections pooling is enabled. * * @param allowSslConnectionPool true if enabled * @return this */ public Builder setAllowSslConnectionPool(boolean allowSslConnectionPool) { this.allowSslConnectionPool = allowSslConnectionPool; return this; } /** * Allows use unescaped URLs in requests * useful for retrieving data from broken sites * * @param useRawUrl * @return this */ public Builder setUseRawUrl(boolean useRawUrl) { this.useRawUrl = useRawUrl; return this; } /** * Set to false if you don't want the query parameters removed when a redirect occurs. * * @param removeQueryParamOnRedirect * @return this */ public Builder setRemoveQueryParamsOnRedirect(boolean removeQueryParamOnRedirect) { this.removeQueryParamOnRedirect = removeQueryParamOnRedirect; return this; } /** * Sets whether AHC should use the default http.proxy* system properties * to obtain proxy information. * <p/> * If useProxyProperties is set to <code>true</code> but {@link #setProxyServer(ProxyServer)} was used * to explicitly set a proxy server, the latter is preferred. * <p/> * See http://download.oracle.com/javase/1.4.2/docs/guide/net/properties.html */ public Builder setUseProxyProperties(boolean useProxyProperties) { this.useProxyProperties = useProxyProperties; return this; } public Builder setIOThreadMultiplier(int multiplier) { this.ioThreadMultiplier = multiplier; return this; } /** * Set the {@link HostnameVerifier} * * @param hostnameVerifier {@link HostnameVerifier} * @return this */ public Builder setHostnameVerifier(HostnameVerifier hostnameVerifier) { this.hostnameVerifier = hostnameVerifier; return this; } /** * Configures this AHC instance to be strict in it's handling of 302 redirects * in a POST/Redirect/GET situation. * * @param strict302Handling strict handling * * @return this * * @since 1.7.2 */ public Builder setStrict302Handling(final boolean strict302Handling) { this.strict302Handling = strict302Handling; return this; } /** * Set the maximum time in millisecond connection can be added to the pool for further reuse * * @param maxConnectionLifeTimeInMs the maximum time in millisecond connection can be added to the pool for further reuse * @return a {@link Builder} */ public Builder setMaxConnectionLifeTimeInMs(int maxConnectionLifeTimeInMs) { this.defaultMaxConnectionLifeTimeInMs = maxConnectionLifeTimeInMs; return this; } /** * Configures this AHC instance to use relative URIs instead of absolute ones when talking with a SSL proxy. * * @param useRelativeURIsWithSSLProxies * @return this * * @since 1.7.2 */ public Builder setUseRelativeURIsWithSSLProxies(boolean useRelativeURIsWithSSLProxies) { this.useRelativeURIsWithSSLProxies = useRelativeURIsWithSSLProxies; return this; } /** * Enables SPDY support. Note that doing so, will currently disable WebSocket support * for this client instance. If not explicitly enabled, spdy will not be used. * * @param spdyEnabled configures spdy support. * * @return this * * @since 2.0 */ public Builder setSpdyEnabled(boolean spdyEnabled) { this.spdyEnabled = spdyEnabled; return this; } /** * Configures the initial window size for the SPDY session. * * @param spdyInitialWindowSize the initial window size. * * @return this * * @since 2.0 */ public Builder setSpdyInitialWindowSize(int spdyInitialWindowSize) { this.spdyInitialWindowSize = spdyInitialWindowSize; return this; } /** * Configures the maximum number of concurrent streams over a single * SPDY session. * * @param spdyMaxConcurrentStreams the maximum number of concurrent * streams over a single SPDY session. * * @return this * * @since 2.0 */ public Builder setSpdyMaxConcurrentStreams(int spdyMaxConcurrentStreams) { this.spdyMaxConcurrentStreams = spdyMaxConcurrentStreams; return this; } /** * Create a config builder with values taken from the given prototype configuration. * * @param prototype the configuration to use as a prototype. */ public Builder(AsyncHttpClientConfig prototype) { allowPoolingConnection = prototype.getAllowPoolingConnection(); providerConfig = prototype.getAsyncHttpProviderConfig(); connectionsPool = prototype.getConnectionsPool(); defaultConnectionTimeOutInMs = prototype.getConnectionTimeoutInMs(); defaultIdleConnectionInPoolTimeoutInMs = prototype.getIdleConnectionInPoolTimeoutInMs(); defaultIdleConnectionTimeoutInMs = prototype.getIdleConnectionTimeoutInMs(); defaultMaxConnectionPerHost = prototype.getMaxConnectionPerHost(); defaultMaxConnectionLifeTimeInMs = prototype.getMaxConnectionLifeTimeInMs(); maxDefaultRedirects = prototype.getMaxRedirects(); defaultMaxTotalConnections = prototype.getMaxTotalConnections(); proxyServer = prototype.getProxyServer(); realm = prototype.getRealm(); defaultRequestTimeoutInMs = prototype.getRequestTimeoutInMs(); sslContext = prototype.getSSLContext(); sslEngineFactory = prototype.getSSLEngineFactory(); userAgent = prototype.getUserAgent(); redirectEnabled = prototype.isRedirectEnabled(); compressionEnabled = prototype.isCompressionEnabled(); reaper = prototype.reaper(); applicationThreadPool = prototype.executorService(); requestFilters.clear(); responseFilters.clear(); ioExceptionFilters.clear(); requestFilters.addAll(prototype.getRequestFilters()); responseFilters.addAll(prototype.getResponseFilters()); ioExceptionFilters.addAll(prototype.getIOExceptionFilters()); requestCompressionLevel = prototype.getRequestCompressionLevel(); useRawUrl = prototype.isUseRawUrl(); ioThreadMultiplier = prototype.getIoThreadMultiplier(); maxRequestRetry = prototype.getMaxRequestRetry(); allowSslConnectionPool = prototype.getAllowPoolingConnection(); removeQueryParamOnRedirect = prototype.isRemoveQueryParamOnRedirect(); hostnameVerifier = prototype.getHostnameVerifier(); strict302Handling = prototype.isStrict302Handling(); useRelativeURIsWithSSLProxies = prototype.isUseRelativeURIsWithSSLProxies(); } /** * Build an {@link AsyncHttpClientConfig} * * @return an {@link AsyncHttpClientConfig} */ public AsyncHttpClientConfig build() { if (reaper == null) { reaper = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r, "AsyncHttpClient-Reaper"); t.setDaemon(true); return t; } }) } if (applicationThreadPool == null) { applicationThreadPool = Executors.newCachedThreadPool(new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r, "AsyncHttpClient-Callback"); t.setDaemon(true); return t; } }) } if (applicationThreadPool.isShutdown()) { throw new IllegalStateException("ExecutorServices closed"); } if (proxyServer == null && useProxyProperties) { proxyServer = ProxyUtils.createProxy(System.getProperties()); } return new AsyncHttpClientConfig(defaultMaxTotalConnections, defaultMaxConnectionPerHost, defaultConnectionTimeOutInMs, defaultWebsocketIdleTimeoutInMs, defaultIdleConnectionInPoolTimeoutInMs, defaultIdleConnectionTimeoutInMs, defaultRequestTimeoutInMs, defaultMaxConnectionLifeTimeInMs, redirectEnabled, maxDefaultRedirects, compressionEnabled, userAgent, allowPoolingConnection, reaper, applicationThreadPool, proxyServer, sslContext, sslEngineFactory, providerConfig, connectionsPool, realm, requestFilters, responseFilters, ioExceptionFilters, requestCompressionLevel, maxRequestRetry, allowSslConnectionPool, useRawUrl, removeQueryParamOnRedirect, hostnameVerifier, ioThreadMultiplier, strict302Handling, useRelativeURIsWithSSLProxies, spdyEnabled, spdyInitialWindowSize, spdyMaxConcurrentStreams); } } }
Fix build
api/src/main/java/org/asynchttpclient/AsyncHttpClientConfig.java
Fix build
<ide><path>pi/src/main/java/org/asynchttpclient/AsyncHttpClientConfig.java <ide> t.setDaemon(true); <ide> return t; <ide> } <del> }) <add> }); <ide> } <ide> <ide> if (applicationThreadPool == null) { <ide> t.setDaemon(true); <ide> return t; <ide> } <del> }) <add> }); <ide> } <ide> <ide> if (applicationThreadPool.isShutdown()) {
Java
mit
459c61b93a7cfea04cebc8fddd1bbcaf9bb7013b
0
bcgit/bc-java,bcgit/bc-java,bcgit/bc-java
package org.bouncycastle.util; /** * Utility methods for processing String objects containing IP addresses. */ public class IPAddress { /** * Validate the given IPv4 or IPv6 address. * * @param address the IP address as a String. * * @return true if a valid address, false otherwise */ public static boolean isValid( String address) { return isValidIPv4(address) || isValidIPv6(address); } /** * Validate the given IPv4 or IPv6 address and netmask. * * @param address the IP address as a String. * * @return true if a valid address with netmask, false otherwise */ public static boolean isValidWithNetMask( String address) { return isValidIPv4WithNetmask(address) || isValidIPv6WithNetmask(address); } /** * Validate the given IPv4 address. * * @param address the IP address as a String. * * @return true if a valid IPv4 address, false otherwise */ public static boolean isValidIPv4( String address) { if (address.length() == 0) { return false; } int octet; int octets = 0; String temp = address+"."; int pos; int start = 0; while (start < temp.length() && (pos = temp.indexOf('.', start)) > start) { if (octets == 4) { return false; } try { octet = Integer.parseInt(temp.substring(start, pos)); } catch (NumberFormatException ex) { return false; } if (octet < 0 || octet > 255) { return false; } start = pos + 1; octets++; } return octets == 4; } public static boolean isValidIPv4WithNetmask( String address) { int index = address.indexOf("/"); String mask = address.substring(index + 1); return (index > 0) && isValidIPv4(address.substring(0, index)) && (isValidIPv4(mask) || isMaskValue(mask, 32)); } public static boolean isValidIPv6WithNetmask( String address) { int index = address.indexOf("/"); String mask = address.substring(index + 1); return (index > 0) && (isValidIPv6(address.substring(0, index)) && (isValidIPv6(mask) || isMaskValue(mask, 128))); } private static boolean isMaskValue(String component, int size) { try { int value = Integer.parseInt(component); return value >= 0 && value <= size; } catch (NumberFormatException e) { return false; } } /** * Validate the given IPv6 address. * * @param address the IP address as a String. * * @return true if a valid IPv6 address, false otherwise */ public static boolean isValidIPv6( String address) { if (address.length() == 0) { return false; } int octet; int octets = 0; String temp = address + ":"; boolean doubleColonFound = false; int pos; int start = 0; while (start < temp.length() && (pos = temp.indexOf(':', start)) >= start) { if (octets == 8) { return false; } if (start != pos) { String value = temp.substring(start, pos); if (pos == (temp.length() - 1) && value.indexOf('.') > 0) { if (!isValidIPv4(value)) { return false; } octets++; // add an extra one as address covers 2 words. } else { try { octet = Integer.parseInt(temp.substring(start, pos), 16); } catch (NumberFormatException ex) { return false; } if (octet < 0 || octet > 0xffff) { return false; } } } else { if (pos != 1 && pos != temp.length() - 1 && doubleColonFound) { return false; } doubleColonFound = true; } start = pos + 1; octets++; } return octets == 8 || doubleColonFound; } }
core/src/main/java/org/bouncycastle/util/IPAddress.java
package org.bouncycastle.util; /** * Utility methods for processing String objects containing IP addresses. */ public class IPAddress { /** * Validate the given IPv4 or IPv6 address. * * @param address the IP address as a String. * * @return true if a valid address, false otherwise */ public static boolean isValid( String address) { return isValidIPv4(address) || isValidIPv6(address); } /** * Validate the given IPv4 or IPv6 address and netmask. * * @param address the IP address as a String. * * @return true if a valid address with netmask, false otherwise */ public static boolean isValidWithNetMask( String address) { return isValidIPv4WithNetmask(address) || isValidIPv6WithNetmask(address); } /** * Validate the given IPv4 address. * * @param address the IP address as a String. * * @return true if a valid IPv4 address, false otherwise */ public static boolean isValidIPv4( String address) { if (address.length() == 0) { return false; } int octet; int octets = 0; String temp = address+"."; int pos; int start = 0; while (start < temp.length() && (pos = temp.indexOf('.', start)) > start) { if (octets == 4) { return false; } try { octet = Integer.parseInt(temp.substring(start, pos)); } catch (NumberFormatException ex) { return false; } if (octet < 0 || octet > 255) { return false; } start = pos + 1; octets++; } return octets == 4; } public static boolean isValidIPv4WithNetmask( String address) { int index = address.indexOf("/"); String mask = address.substring(index + 1); return (index > 0) && isValidIPv4(address.substring(0, index)) && (isValidIPv4(mask) || isMaskValue(mask, 32)); } public static boolean isValidIPv6WithNetmask( String address) { int index = address.indexOf("/"); String mask = address.substring(index + 1); return (index > 0) && (isValidIPv6(address.substring(0, index)) && (isValidIPv6(mask) || isMaskValue(mask, 128))); } private static boolean isMaskValue(String component, int size) { try { int value = Integer.parseInt(component); return value >= 0 && value <= size; } catch (NumberFormatException e) { return false; } } /** * Validate the given IPv6 address. * * @param address the IP address as a String. * * @return true if a valid IPv4 address, false otherwise */ public static boolean isValidIPv6( String address) { if (address.length() == 0) { return false; } int octet; int octets = 0; String temp = address + ":"; boolean doubleColonFound = false; int pos; int start = 0; while (start < temp.length() && (pos = temp.indexOf(':', start)) >= start) { if (octets == 8) { return false; } if (start != pos) { String value = temp.substring(start, pos); if (pos == (temp.length() - 1) && value.indexOf('.') > 0) { if (!isValidIPv4(value)) { return false; } octets++; // add an extra one as address covers 2 words. } else { try { octet = Integer.parseInt(temp.substring(start, pos), 16); } catch (NumberFormatException ex) { return false; } if (octet < 0 || octet > 0xffff) { return false; } } } else { if (pos != 1 && pos != temp.length() - 1 && doubleColonFound) { return false; } doubleColonFound = true; } start = pos + 1; octets++; } return octets == 8 || doubleColonFound; } }
Fix javadoc
core/src/main/java/org/bouncycastle/util/IPAddress.java
Fix javadoc
<ide><path>ore/src/main/java/org/bouncycastle/util/IPAddress.java <ide> * <ide> * @param address the IP address as a String. <ide> * <del> * @return true if a valid IPv4 address, false otherwise <add> * @return true if a valid IPv6 address, false otherwise <ide> */ <ide> public static boolean isValidIPv6( <ide> String address)
Java
apache-2.0
f6c9f4e10b8be302232ff96e9fa3926e8b7f3f73
0
FHannes/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,allotria/intellij-community,semonte/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ibinti/intellij-community,FHannes/intellij-community,signed/intellij-community,vvv1559/intellij-community,allotria/intellij-community,semonte/intellij-community,apixandru/intellij-community,semonte/intellij-community,ibinti/intellij-community,semonte/intellij-community,FHannes/intellij-community,signed/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,signed/intellij-community,FHannes/intellij-community,FHannes/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,semonte/intellij-community,vvv1559/intellij-community,signed/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,asedunov/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,da1z/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,signed/intellij-community,ibinti/intellij-community,semonte/intellij-community,semonte/intellij-community,da1z/intellij-community,allotria/intellij-community,ibinti/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,signed/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,asedunov/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ibinti/intellij-community,allotria/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,asedunov/intellij-community,da1z/intellij-community,FHannes/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,semonte/intellij-community,semonte/intellij-community,da1z/intellij-community,signed/intellij-community,signed/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,apixandru/intellij-community,semonte/intellij-community,allotria/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,xfournet/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,apixandru/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,semonte/intellij-community,allotria/intellij-community,apixandru/intellij-community,xfournet/intellij-community,allotria/intellij-community,signed/intellij-community,da1z/intellij-community,semonte/intellij-community,FHannes/intellij-community,da1z/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ibinti/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,signed/intellij-community,suncycheng/intellij-community,allotria/intellij-community,da1z/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,signed/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,signed/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,asedunov/intellij-community
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInspection.ex; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInspection.InspectionEP; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.configurationStore.SchemeDataHolder; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.SchemeState; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.profile.codeInspection.BaseInspectionProfileManager; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.profile.codeInspection.ProjectInspectionProfileManager; import com.intellij.project.ProjectKt; import com.intellij.psi.PsiElement; import com.intellij.psi.search.scope.packageSet.NamedScope; import com.intellij.util.ArrayUtil; import com.intellij.util.Consumer; import com.intellij.util.graph.DFSTBuilder; import com.intellij.util.graph.GraphGenerator; import com.intellij.util.graph.InboundSemiGraph; import com.intellij.util.xmlb.annotations.Attribute; import com.intellij.util.xmlb.annotations.Tag; import com.intellij.util.xmlb.annotations.Transient; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.util.*; /** * @author max */ public class InspectionProfileImpl extends NewInspectionProfile { @NonNls static final String INSPECTION_TOOL_TAG = "inspection_tool"; @NonNls static final String CLASS_TAG = "class"; protected static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.ex.InspectionProfileImpl"); @NonNls private static final String VALID_VERSION = "1.0"; @NonNls private static final String VERSION_TAG = "version"; @NonNls private static final String USED_LEVELS = "used_levels"; @TestOnly public static boolean INIT_INSPECTIONS = false; protected final InspectionToolRegistrar myRegistrar; protected final Map<String, Element> myUninitializedSettings = new TreeMap<>(); protected Map<String, ToolsImpl> myTools = new THashMap<>(); protected volatile Set<String> myChangedToolNames; @Attribute("is_locked") protected boolean myLockedProfile; protected final InspectionProfileImpl myBaseProfile; private volatile String myToolShortName; private String[] myScopesOrder; private String myDescription; private volatile boolean myInitialized; private final Object myLock = new Object(); private SchemeDataHolder<? super InspectionProfileImpl> myDataHolder; public InspectionProfileImpl(@NotNull String profileName, @NotNull InspectionToolRegistrar registrar, @NotNull BaseInspectionProfileManager profileManager) { this(profileName, registrar, profileManager, InspectionProfileKt.getBASE_PROFILE(), null); } public InspectionProfileImpl(@NotNull String profileName) { this(profileName, InspectionToolRegistrar.getInstance(), (BaseInspectionProfileManager)InspectionProfileManager.getInstance(), null, null); } public InspectionProfileImpl(@NotNull String profileName, @NotNull InspectionToolRegistrar registrar, @Nullable InspectionProfileImpl baseProfile) { this(profileName, registrar, (BaseInspectionProfileManager)InspectionProfileManager.getInstance(), baseProfile, null); } public InspectionProfileImpl(@NotNull String profileName, @NotNull InspectionToolRegistrar registrar, @NotNull BaseInspectionProfileManager profileManager, @Nullable InspectionProfileImpl baseProfile, @Nullable SchemeDataHolder<? super InspectionProfileImpl> dataHolder) { super(profileName, profileManager); myRegistrar = registrar; myBaseProfile = baseProfile; myDataHolder = dataHolder; if (dataHolder != null) { schemeState = SchemeState.UNCHANGED; } } public InspectionProfileImpl(@NotNull String profileName, @NotNull InspectionToolRegistrar registrar, @NotNull BaseInspectionProfileManager profileManager, @Nullable SchemeDataHolder<? super InspectionProfileImpl> dataHolder) { this(profileName, registrar, profileManager, InspectionProfileKt.getBASE_PROFILE(), dataHolder); } private static boolean toolSettingsAreEqual(@NotNull String toolName, @NotNull InspectionProfileImpl profile1, @NotNull InspectionProfileImpl profile2) { final Tools toolList1 = profile1.myTools.get(toolName); final Tools toolList2 = profile2.myTools.get(toolName); return Comparing.equal(toolList1, toolList2); } @NotNull protected static InspectionToolWrapper copyToolSettings(@NotNull InspectionToolWrapper toolWrapper) { final InspectionToolWrapper inspectionTool = toolWrapper.createCopy(); if (toolWrapper.isInitialized()) { Element config = new Element("config"); toolWrapper.getTool().writeSettings(config); inspectionTool.getTool().readSettings(config); } return inspectionTool; } @Override public HighlightDisplayLevel getErrorLevel(@NotNull HighlightDisplayKey inspectionToolKey, PsiElement element) { Project project = element == null ? null : element.getProject(); final ToolsImpl tools = getTools(inspectionToolKey.toString(), project); HighlightDisplayLevel level = tools != null ? tools.getLevel(element) : HighlightDisplayLevel.WARNING; if (!getProfileManager().getOwnSeverityRegistrar().isSeverityValid(level.getSeverity().getName())) { level = HighlightDisplayLevel.WARNING; setErrorLevel(inspectionToolKey, level, project); } return level; } @Override public void readExternal(@NotNull Element element) { super.readExternal(element); final Element highlightElement = element.getChild(USED_LEVELS); if (highlightElement != null) { // from old profiles getProfileManager().getOwnSeverityRegistrar().readExternal(highlightElement); } String version = element.getAttributeValue(VERSION_TAG); if (version == null || !version.equals(VALID_VERSION)) { InspectionToolWrapper[] tools = getInspectionTools(null); for (Element toolElement : element.getChildren("inspection_tool")) { String toolClassName = toolElement.getAttributeValue(CLASS_TAG); String shortName = convertToShortName(toolClassName, tools); if (shortName == null) { continue; } toolElement.setAttribute(CLASS_TAG, shortName); myUninitializedSettings.put(shortName, toolElement.clone()); } } else { for (Element toolElement : element.getChildren(INSPECTION_TOOL_TAG)) { myUninitializedSettings.put(toolElement.getAttributeValue(CLASS_TAG), toolElement.clone()); } } } @Nullable private static String convertToShortName(@Nullable String displayName, InspectionToolWrapper[] tools) { if (displayName == null) return null; for (InspectionToolWrapper tool : tools) { if (displayName.equals(tool.getDisplayName())) { return tool.getShortName(); } } return null; } @NotNull public Set<HighlightSeverity> getUsedSeverities() { LOG.assertTrue(myInitialized); Set<HighlightSeverity> result = new THashSet<>(); for (Tools tools : myTools.values()) { for (ScopeToolState state : tools.getTools()) { result.add(state.getLevel().getSeverity()); } } return result; } @Override @NotNull public Element writeScheme() { return writeScheme(true); } @NotNull public Element writeScheme(boolean setSchemeStateToUnchanged) { if (myDataHolder != null) { return myDataHolder.read(); } Element element = super.writeScheme(); if (isProjectLevel()) { element.setAttribute("version", "1.0"); } if (isProjectLevel() && ProjectKt.isDirectoryBased(((ProjectInspectionProfileManager)getProfileManager()).getProject())) { return new Element("component").setAttribute("name", "InspectionProjectProfileManager").addContent(element); } if (setSchemeStateToUnchanged) { schemeState = SchemeState.UNCHANGED; } return element; } @Override public void writeExternal(@NotNull Element element) { // must be first - compatibility element.setAttribute(VERSION_TAG, VALID_VERSION); super.writeExternal(element); synchronized (myLock) { if (!myInitialized) { for (Element el : myUninitializedSettings.values()) { element.addContent(el.clone()); } return; } } Set<String> changedToolNames = getChangedToolNames(); if (changedToolNames == null) { return; } List<String> allToolNames = new ArrayList<>(myTools.keySet()); allToolNames.addAll(myUninitializedSettings.keySet()); allToolNames.sort(null); for (String toolName : allToolNames) { Element toolElement = myUninitializedSettings.get(toolName); if (toolElement != null) { element.addContent(toolElement.clone()); continue; } if (!myLockedProfile && !changedToolNames.contains(toolName)) { markSettingsMerged(toolName, element); continue; } ToolsImpl toolList = myTools.get(toolName); LOG.assertTrue(toolList != null); Element inspectionElement = new Element(INSPECTION_TOOL_TAG); inspectionElement.setAttribute(CLASS_TAG, toolName); try { toolList.writeExternal(inspectionElement); getPathMacroManager().collapsePaths(inspectionElement); } catch (WriteExternalException e) { LOG.error(e); continue; } if (!areSettingsMerged(toolName, inspectionElement)) { element.addContent(inspectionElement); } } } private void markSettingsMerged(@NotNull String toolName, @NotNull Element element) { //add marker if already merged but result is now default (-> empty node) String mergedName = InspectionElementsMergerBase.getMergedMarkerName(toolName); if (!myUninitializedSettings.containsKey(mergedName)) { InspectionElementsMergerBase merger = getMerger(toolName); if (merger != null && merger.markSettingsMerged(myUninitializedSettings)) { element.addContent(new Element(INSPECTION_TOOL_TAG).setAttribute(CLASS_TAG, mergedName)); } } } private boolean areSettingsMerged(String toolName, Element inspectionElement) { //skip merged settings as they could be restored from already provided data final InspectionElementsMergerBase merger = getMerger(toolName); return merger != null && merger.areSettingsMerged(myUninitializedSettings, inspectionElement); } public void collectDependentInspections(@NotNull InspectionToolWrapper toolWrapper, @NotNull Set<InspectionToolWrapper<?, ?>> dependentEntries, Project project) { String mainToolId = toolWrapper.getMainToolId(); if (mainToolId != null) { InspectionToolWrapper dependentEntryWrapper = getInspectionTool(mainToolId, project); if (dependentEntryWrapper == null) { LOG.error("Can't find main tool: '" + mainToolId+"' which was specified in "+toolWrapper); return; } if (!dependentEntries.add(dependentEntryWrapper)) { collectDependentInspections(dependentEntryWrapper, dependentEntries, project); } } } @Override @Nullable public InspectionToolWrapper getInspectionTool(@NotNull String shortName, @Nullable PsiElement element) { final Tools toolList = getTools(shortName, element == null ? null : element.getProject()); return toolList == null ? null : toolList.getInspectionTool(element); } @Nullable @Override public InspectionProfileEntry getUnwrappedTool(@NotNull String shortName, @NotNull PsiElement element) { InspectionToolWrapper tool = getInspectionTool(shortName, element); return tool == null ? null : tool.getTool(); } @Override public <T extends InspectionProfileEntry> T getUnwrappedTool(@NotNull Key<T> shortNameKey, @NotNull PsiElement element) { //noinspection unchecked return (T) getUnwrappedTool(shortNameKey.toString(), element); } public void modifyProfile(@NotNull Consumer<InspectionProfileModifiableModel> modelConsumer) { InspectionProfileModifiableModelKt.edit(this, it -> { modelConsumer.consume(it); return null; }); } @Override public <T extends InspectionProfileEntry> void modifyToolSettings(@NotNull final Key<T> shortNameKey, @NotNull final PsiElement psiElement, @NotNull final Consumer<T> toolConsumer) { modifyProfile(model -> { InspectionProfileEntry tool = model.getUnwrappedTool(shortNameKey.toString(), psiElement); //noinspection unchecked toolConsumer.consume((T) tool); }); } @Override @Nullable public InspectionToolWrapper getInspectionTool(@NotNull String shortName, Project project) { final ToolsImpl tools = getTools(shortName, project); return tools != null? tools.getTool() : null; } public InspectionToolWrapper getToolById(@NotNull String id, @NotNull PsiElement element) { initInspectionTools(element.getProject()); for (Tools toolList : myTools.values()) { final InspectionToolWrapper tool = toolList.getInspectionTool(element); if (id.equals(tool.getID())) return tool; } return null; } @Nullable public List<InspectionToolWrapper> findToolsById(@NotNull String id, @NotNull PsiElement element) { List<InspectionToolWrapper> result = null; initInspectionTools(element.getProject()); for (Tools toolList : myTools.values()) { final InspectionToolWrapper tool = toolList.getInspectionTool(element); if (id.equals(tool.getID())) { if (result == null) { result = new ArrayList<>(); } result.add(tool); } } return result; } @Nullable @Override public String getSingleTool() { return myToolShortName; } public void setSingleTool(@NotNull final String toolShortName) { myToolShortName = toolShortName; } @Override @NotNull public String getDisplayName() { return getName(); } public void scopesChanged() { if (!myInitialized) { return; } for (ToolsImpl tools : myTools.values()) { tools.scopesChanged(); } getProfileManager().fireProfileChanged(this); } @Transient public boolean isProfileLocked() { return myLockedProfile; } public void lockProfile(boolean isLocked) { myLockedProfile = isLocked; schemeState = SchemeState.POSSIBLY_CHANGED; } @Override @NotNull public InspectionToolWrapper[] getInspectionTools(@Nullable PsiElement element) { initInspectionTools(element == null ? null : element.getProject()); List<InspectionToolWrapper> result = new ArrayList<>(); for (Tools toolList : myTools.values()) { result.add(toolList.getInspectionTool(element)); } return result.toArray(new InspectionToolWrapper[result.size()]); } @Override @NotNull public List<Tools> getAllEnabledInspectionTools(Project project) { initInspectionTools(project); List<Tools> result = new ArrayList<>(); for (final ToolsImpl toolList : myTools.values()) { if (toolList.isEnabled()) { result.add(toolList); } } return result; } public void disableTool(@NotNull String toolShortName, @NotNull PsiElement element) { getTools(toolShortName, element.getProject()).disableTool(element); } public void disableToolByDefault(@NotNull Collection<String> toolShortNames, @Nullable Project project) { for (String toolId : toolShortNames) { getTools(toolId, project).setDefaultEnabled(false); } schemeState = SchemeState.POSSIBLY_CHANGED; } @NotNull public ScopeToolState getToolDefaultState(@NotNull String toolShortName, @Nullable Project project) { return getTools(toolShortName, project).getDefaultState(); } public void enableToolsByDefault(@NotNull List<String> toolShortNames, Project project) { for (final String shortName : toolShortNames) { getTools(shortName, project).setDefaultEnabled(true); } schemeState = SchemeState.POSSIBLY_CHANGED; } public boolean wasInitialized() { return myInitialized; } public void initInspectionTools(@Nullable Project project) { //noinspection TestOnlyProblems if (myInitialized || (ApplicationManager.getApplication().isUnitTestMode() && !INIT_INSPECTIONS)) { return; } synchronized (myLock) { if (!myInitialized) { initialize(project); } } } @NotNull protected List<InspectionToolWrapper> createTools(@Nullable Project project) { return myRegistrar.createTools(); } private void initialize(@Nullable Project project) { SchemeDataHolder<? super InspectionProfileImpl> dataHolder = myDataHolder; if (dataHolder != null) { myDataHolder = null; Element element = dataHolder.read(); if (element.getName().equals("component")) { element = element.getChild("profile"); } assert element != null; readExternal(element); } if (myBaseProfile != null) { myBaseProfile.initInspectionTools(project); } final List<InspectionToolWrapper> tools; try { tools = createTools(project); } catch (ProcessCanceledException ignored) { return; } final Map<String, List<String>> dependencies = new THashMap<>(); for (InspectionToolWrapper toolWrapper : tools) { addTool(project, toolWrapper, dependencies); } DFSTBuilder<String> builder = new DFSTBuilder<>(GraphGenerator.generate(new InboundSemiGraph<String>() { @Override public Collection<String> getNodes() { return dependencies.keySet(); } @Override public Iterator<String> getIn(String n) { return dependencies.get(n).iterator(); } })); if (builder.isAcyclic()) { myScopesOrder = ArrayUtil.toStringArray(builder.getSortedNodes()); } copyToolsConfigurations(project); myInitialized = true; if (dataHolder != null) { // should be only after set myInitialized dataHolder.updateDigest(this); } } protected void copyToolsConfigurations(@Nullable Project project) { } public void addTool(@Nullable Project project, @NotNull InspectionToolWrapper toolWrapper, @NotNull Map<String, List<String>> dependencies) { final String shortName = toolWrapper.getShortName(); HighlightDisplayKey key = HighlightDisplayKey.find(shortName); if (key == null) { final InspectionEP extension = toolWrapper.getExtension(); Computable<String> computable = extension == null ? new Computable.PredefinedValueComputable<>(toolWrapper.getDisplayName()) : extension::getDisplayName; if (toolWrapper instanceof LocalInspectionToolWrapper) { key = HighlightDisplayKey.register(shortName, computable, toolWrapper.getID(), ((LocalInspectionToolWrapper)toolWrapper).getAlternativeID()); } else { key = HighlightDisplayKey.register(shortName, computable); } } if (key == null) { LOG.error(shortName + " ; number of initialized tools: " + myTools.size()); return; } HighlightDisplayLevel baseLevel = myBaseProfile != null && myBaseProfile.getTools(shortName, project) != null ? myBaseProfile.getErrorLevel(key, project) : HighlightDisplayLevel.DO_NOT_SHOW; HighlightDisplayLevel defaultLevel = toolWrapper.getDefaultLevel(); HighlightDisplayLevel level = baseLevel.getSeverity().compareTo(defaultLevel.getSeverity()) > 0 ? baseLevel : defaultLevel; boolean enabled = myBaseProfile != null ? myBaseProfile.isToolEnabled(key) : toolWrapper.isEnabledByDefault(); final ToolsImpl toolsList = new ToolsImpl(toolWrapper, level, !myLockedProfile && enabled, enabled); final Element element = myUninitializedSettings.remove(shortName); try { if (element != null) { getPathMacroManager().expandPaths(element); toolsList.readExternal(element, getProfileManager(), dependencies); } else if (!myUninitializedSettings.containsKey(InspectionElementsMergerBase.getMergedMarkerName(shortName))) { final InspectionElementsMergerBase merger = getMerger(shortName); Element merged = merger == null ? null : merger.merge(myUninitializedSettings); if (merged != null) { getPathMacroManager().expandPaths(merged); toolsList.readExternal(merged, getProfileManager(), dependencies); } else if (isProfileLocked()) { // https://youtrack.jetbrains.com/issue/IDEA-158936 toolsList.setEnabled(false); if (toolsList.getNonDefaultTools() == null) { toolsList.getDefaultState().setEnabled(false); } } } } catch (InvalidDataException e) { LOG.error("Can't read settings for " + toolWrapper, e); } myTools.put(shortName, toolsList); } @Nullable private static InspectionElementsMergerBase getMerger(String shortName) { final InspectionElementsMerger merger = InspectionElementsMerger.getMerger(shortName); if (merger instanceof InspectionElementsMergerBase) { return (InspectionElementsMergerBase)merger; } return merger != null ? new InspectionElementsMergerBase() { @Override public String getMergedToolName() { return merger.getMergedToolName(); } @Override public String[] getSourceToolNames() { return merger.getSourceToolNames(); } } : null; } @Nullable @Transient public String[] getScopesOrder() { return myScopesOrder; } public void setScopesOrder(String[] scopesOrder) { myScopesOrder = scopesOrder; schemeState = SchemeState.POSSIBLY_CHANGED; } private HighlightDisplayLevel getErrorLevel(@NotNull HighlightDisplayKey key, @Nullable Project project) { final ToolsImpl tools = getTools(key.toString(), project); LOG.assertTrue(tools != null, "profile name: " + myName + " base profile: " + (myBaseProfile != null ? myBaseProfile.getName() : "-") + " key: " + key); return tools.getLevel(); } @NotNull @TestOnly public InspectionProfileModifiableModel getModifiableModel() { return new InspectionProfileModifiableModel(this); } public void cleanup(@NotNull Project project) { if (!myInitialized) { return; } for (ToolsImpl toolList : myTools.values()) { if (toolList.isEnabled()) { toolList.cleanupTools(project); } } } public void enableTool(@NotNull String toolShortName, Project project) { final ToolsImpl tools = getTools(toolShortName, project); tools.setEnabled(true); tools.getDefaultState().setEnabled(true); schemeState = SchemeState.POSSIBLY_CHANGED; } public void enableTool(@NotNull String inspectionTool, @NotNull NamedScope namedScope, Project project) { getTools(inspectionTool, project).enableTool(namedScope, project); schemeState = SchemeState.POSSIBLY_CHANGED; } public void enableTools(@NotNull List<String> inspectionTools, NamedScope namedScope, Project project) { for (String inspectionTool : inspectionTools) { enableTool(inspectionTool, namedScope, project); } } public void disableTools(@NotNull List<String> inspectionTools, NamedScope namedScope, @NotNull Project project) { for (String inspectionTool : inspectionTools) { getTools(inspectionTool, project).disableTool(namedScope, project); } schemeState = SchemeState.POSSIBLY_CHANGED; } public void disableTool(@NotNull String inspectionTool, @Nullable Project project) { ToolsImpl tools = getTools(inspectionTool, project); tools.setEnabled(false); if (tools.getNonDefaultTools() == null) { tools.getDefaultState().setEnabled(false); } schemeState = SchemeState.POSSIBLY_CHANGED; } public void setErrorLevel(@NotNull HighlightDisplayKey key, @NotNull HighlightDisplayLevel level, Project project) { getTools(key.toString(), project).setLevel(level); schemeState = SchemeState.POSSIBLY_CHANGED; } @Override public boolean isToolEnabled(@Nullable HighlightDisplayKey key, PsiElement element) { if (key == null) { return false; } final Tools toolState = getTools(key.toString(), element == null ? null : element.getProject()); return toolState != null && toolState.isEnabled(element); } @Override public boolean isToolEnabled(@Nullable HighlightDisplayKey key) { return isToolEnabled(key, null); } @Override public boolean isExecutable(Project project) { initInspectionTools(project); for (Tools tools : myTools.values()) { if (tools.isEnabled()) return true; } return false; } @Tag public String getDescription() { return myDescription; } public void setDescription(@Nullable String description) { myDescription = StringUtil.nullize(description); schemeState = SchemeState.POSSIBLY_CHANGED; } public void convert(@NotNull Element element, @NotNull Project project) { final Element scopes = element.getChild("scopes"); if (scopes == null) { return; } initInspectionTools(project); for (Element scopeElement : scopes.getChildren(SCOPE)) { final String profile = scopeElement.getAttributeValue(PROFILE); InspectionProfileImpl inspectionProfile = profile == null ? null : getProfileManager().getProfile(profile); NamedScope scope = inspectionProfile == null ? null : getProfileManager().getScopesManager().getScope(scopeElement.getAttributeValue(NAME)); if (scope == null) { continue; } for (InspectionToolWrapper toolWrapper : inspectionProfile.getInspectionTools(null)) { final HighlightDisplayKey key = HighlightDisplayKey.find(toolWrapper.getShortName()); try { InspectionToolWrapper toolWrapperCopy = copyToolSettings(toolWrapper); HighlightDisplayLevel errorLevel = inspectionProfile.getErrorLevel(key, null, project); getTools(toolWrapper.getShortName(), project) .addTool(scope, toolWrapperCopy, inspectionProfile.isToolEnabled(key), errorLevel); } catch (Exception e) { LOG.error(e); } } } reduceConvertedScopes(); } private void reduceConvertedScopes() { for (ToolsImpl tools : myTools.values()) { final ScopeToolState toolState = tools.getDefaultState(); final List<ScopeToolState> nonDefaultTools = tools.getNonDefaultTools(); if (nonDefaultTools != null) { boolean equal = true; boolean isEnabled = toolState.isEnabled(); for (ScopeToolState state : nonDefaultTools) { isEnabled |= state.isEnabled(); if (!state.equalTo(toolState)) { equal = false; } } tools.setEnabled(isEnabled); if (equal) { tools.removeAllScopes(); } } } } @NotNull public List<ScopeToolState> getAllTools(@Nullable Project project) { initInspectionTools(project); List<ScopeToolState> result = new ArrayList<>(); for (Tools tools : myTools.values()) { tools.collectTools(result); } return result; } @NotNull public List<ScopeToolState> getDefaultStates(@Nullable Project project) { initInspectionTools(project); List<ScopeToolState> result = new ArrayList<>(); for (Tools tools : myTools.values()) { result.add(tools.getDefaultState()); } return result; } @NotNull public List<ScopeToolState> getNonDefaultTools(@NotNull String shortName, Project project) { final List<ScopeToolState> result = new ArrayList<>(); final List<ScopeToolState> nonDefaultTools = getTools(shortName, project).getNonDefaultTools(); if (nonDefaultTools != null) { result.addAll(nonDefaultTools); } return result; } public boolean isToolEnabled(@NotNull HighlightDisplayKey key, NamedScope namedScope, Project project) { return getTools(key.toString(), project).isEnabled(namedScope,project); } public void removeScope(@NotNull String toolShortName, @NotNull String scopeName, Project project) { getTools(toolShortName, project).removeScope(scopeName); schemeState = SchemeState.POSSIBLY_CHANGED; } public void removeScopes(@NotNull List<String> shortNames, @NotNull String scopeName, Project project) { for (final String shortName : shortNames) { removeScope(shortName, scopeName, project); } } /** * @return null if it has no base profile */ @Nullable private Set<String> getChangedToolNames() { if (myBaseProfile == null) return null; if (myChangedToolNames == null) { synchronized (myLock) { if (myChangedToolNames == null) { initInspectionTools(null); Set<String> names = myTools.keySet(); Set<String> map = new THashSet<>(names.size()); for (String toolId : names) { if (!toolSettingsAreEqual(toolId, myBaseProfile, this)) { map.add(toolId); } } myChangedToolNames = map; return map; } } } return myChangedToolNames; } public void profileChanged() { myChangedToolNames = null; schemeState = SchemeState.POSSIBLY_CHANGED; } @NotNull @Transient public HighlightDisplayLevel getErrorLevel(@NotNull HighlightDisplayKey key, NamedScope scope, Project project) { final ToolsImpl tools = getTools(key.toString(), project); return tools != null ? tools.getLevel(scope, project) : HighlightDisplayLevel.WARNING; } public ScopeToolState addScope(@NotNull InspectionToolWrapper toolWrapper, NamedScope scope, @NotNull HighlightDisplayLevel level, boolean enabled, Project project) { return getTools(toolWrapper.getShortName(), project).prependTool(scope, toolWrapper, enabled, level); } public void setErrorLevel(@NotNull HighlightDisplayKey key, @NotNull HighlightDisplayLevel level, String scopeName, Project project) { getTools(key.toString(), project).setLevel(level, scopeName, project); schemeState = SchemeState.POSSIBLY_CHANGED; } public void setErrorLevel(@NotNull List<HighlightDisplayKey> keys, @NotNull HighlightDisplayLevel level, String scopeName, Project project) { for (HighlightDisplayKey key : keys) { setErrorLevel(key, level, scopeName, project); } } public ToolsImpl getTools(@NotNull String toolShortName, @Nullable Project project) { initInspectionTools(project); return myTools.get(toolShortName); } public void enableAllTools(Project project) { for (InspectionToolWrapper entry : getInspectionTools(null)) { enableTool(entry.getShortName(), project); } } }
platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileImpl.java
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInspection.ex; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInspection.InspectionEP; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.configurationStore.SchemeDataHolder; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.SchemeState; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.profile.codeInspection.BaseInspectionProfileManager; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.profile.codeInspection.ProjectInspectionProfileManager; import com.intellij.project.ProjectKt; import com.intellij.psi.PsiElement; import com.intellij.psi.search.scope.packageSet.NamedScope; import com.intellij.util.ArrayUtil; import com.intellij.util.Consumer; import com.intellij.util.graph.DFSTBuilder; import com.intellij.util.graph.GraphGenerator; import com.intellij.util.graph.InboundSemiGraph; import com.intellij.util.xmlb.annotations.Attribute; import com.intellij.util.xmlb.annotations.Tag; import com.intellij.util.xmlb.annotations.Transient; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.util.*; /** * @author max */ public class InspectionProfileImpl extends NewInspectionProfile { @NonNls static final String INSPECTION_TOOL_TAG = "inspection_tool"; @NonNls static final String CLASS_TAG = "class"; protected static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.ex.InspectionProfileImpl"); @NonNls private static final String VALID_VERSION = "1.0"; @NonNls private static final String VERSION_TAG = "version"; @NonNls private static final String USED_LEVELS = "used_levels"; @TestOnly public static boolean INIT_INSPECTIONS = false; protected final InspectionToolRegistrar myRegistrar; protected final Map<String, Element> myUninitializedSettings = new TreeMap<>(); protected Map<String, ToolsImpl> myTools = new THashMap<>(); protected volatile Set<String> myChangedToolNames; @Attribute("is_locked") protected boolean myLockedProfile; protected final InspectionProfileImpl myBaseProfile; private volatile String myToolShortName; private String[] myScopesOrder; private String myDescription; private volatile boolean myInitialized; private final Object myLock = new Object(); private SchemeDataHolder<? super InspectionProfileImpl> myDataHolder; public InspectionProfileImpl(@NotNull String profileName, @NotNull InspectionToolRegistrar registrar, @NotNull BaseInspectionProfileManager profileManager) { this(profileName, registrar, profileManager, InspectionProfileKt.getBASE_PROFILE(), null); } public InspectionProfileImpl(@NotNull String profileName) { this(profileName, InspectionToolRegistrar.getInstance(), (BaseInspectionProfileManager)InspectionProfileManager.getInstance(), null, null); } public InspectionProfileImpl(@NotNull String profileName, @NotNull InspectionToolRegistrar registrar, @Nullable InspectionProfileImpl baseProfile) { this(profileName, registrar, (BaseInspectionProfileManager)InspectionProfileManager.getInstance(), baseProfile, null); } public InspectionProfileImpl(@NotNull String profileName, @NotNull InspectionToolRegistrar registrar, @NotNull BaseInspectionProfileManager profileManager, @Nullable InspectionProfileImpl baseProfile, @Nullable SchemeDataHolder<? super InspectionProfileImpl> dataHolder) { super(profileName, profileManager); myRegistrar = registrar; myBaseProfile = baseProfile; myDataHolder = dataHolder; if (dataHolder != null) { schemeState = SchemeState.UNCHANGED; } } public InspectionProfileImpl(@NotNull String profileName, @NotNull InspectionToolRegistrar registrar, @NotNull BaseInspectionProfileManager profileManager, @Nullable SchemeDataHolder<? super InspectionProfileImpl> dataHolder) { this(profileName, registrar, profileManager, InspectionProfileKt.getBASE_PROFILE(), dataHolder); } private static boolean toolSettingsAreEqual(@NotNull String toolName, @NotNull InspectionProfileImpl profile1, @NotNull InspectionProfileImpl profile2) { final Tools toolList1 = profile1.myTools.get(toolName); final Tools toolList2 = profile2.myTools.get(toolName); return Comparing.equal(toolList1, toolList2); } @NotNull protected static InspectionToolWrapper copyToolSettings(@NotNull InspectionToolWrapper toolWrapper) { final InspectionToolWrapper inspectionTool = toolWrapper.createCopy(); if (toolWrapper.isInitialized()) { Element config = new Element("config"); toolWrapper.getTool().writeSettings(config); inspectionTool.getTool().readSettings(config); } return inspectionTool; } @Override public HighlightDisplayLevel getErrorLevel(@NotNull HighlightDisplayKey inspectionToolKey, PsiElement element) { Project project = element == null ? null : element.getProject(); final ToolsImpl tools = getTools(inspectionToolKey.toString(), project); HighlightDisplayLevel level = tools != null ? tools.getLevel(element) : HighlightDisplayLevel.WARNING; if (!getProfileManager().getOwnSeverityRegistrar().isSeverityValid(level.getSeverity().getName())) { level = HighlightDisplayLevel.WARNING; setErrorLevel(inspectionToolKey, level, project); } return level; } @Override public void readExternal(@NotNull Element element) { super.readExternal(element); final Element highlightElement = element.getChild(USED_LEVELS); if (highlightElement != null) { // from old profiles getProfileManager().getOwnSeverityRegistrar().readExternal(highlightElement); } String version = element.getAttributeValue(VERSION_TAG); if (version == null || !version.equals(VALID_VERSION)) { InspectionToolWrapper[] tools = getInspectionTools(null); for (Element toolElement : element.getChildren("inspection_tool")) { String toolClassName = toolElement.getAttributeValue(CLASS_TAG); String shortName = convertToShortName(toolClassName, tools); if (shortName == null) { continue; } toolElement.setAttribute(CLASS_TAG, shortName); myUninitializedSettings.put(shortName, toolElement.clone()); } } else { for (Element toolElement : element.getChildren(INSPECTION_TOOL_TAG)) { myUninitializedSettings.put(toolElement.getAttributeValue(CLASS_TAG), toolElement.clone()); } } } @Nullable private static String convertToShortName(@Nullable String displayName, InspectionToolWrapper[] tools) { if (displayName == null) return null; for (InspectionToolWrapper tool : tools) { if (displayName.equals(tool.getDisplayName())) { return tool.getShortName(); } } return null; } @NotNull public Set<HighlightSeverity> getUsedSeverities() { LOG.assertTrue(myInitialized); Set<HighlightSeverity> result = new THashSet<>(); for (Tools tools : myTools.values()) { for (ScopeToolState state : tools.getTools()) { result.add(state.getLevel().getSeverity()); } } return result; } @Override @NotNull public Element writeScheme() { return writeScheme(true); } @NotNull public Element writeScheme(boolean setSchemeStateToUnchanged) { if (myDataHolder != null) { return myDataHolder.read(); } Element element = super.writeScheme(); if (isProjectLevel()) { element.setAttribute("version", "1.0"); } if (isProjectLevel() && ProjectKt.isDirectoryBased(((ProjectInspectionProfileManager)getProfileManager()).getProject())) { return new Element("component").setAttribute("name", "InspectionProjectProfileManager").addContent(element); } if (setSchemeStateToUnchanged) { schemeState = SchemeState.UNCHANGED; } return element; } @Override public void writeExternal(@NotNull Element element) { // must be first - compatibility element.setAttribute(VERSION_TAG, VALID_VERSION); super.writeExternal(element); synchronized (myLock) { if (!myInitialized) { for (Element el : myUninitializedSettings.values()) { element.addContent(el.clone()); } return; } } Set<String> changedToolNames = getChangedToolNames(); if (changedToolNames == null) { return; } List<String> allToolNames = new ArrayList<>(myTools.keySet()); allToolNames.addAll(myUninitializedSettings.keySet()); allToolNames.sort(null); for (String toolName : allToolNames) { Element toolElement = myUninitializedSettings.get(toolName); if (toolElement != null) { element.addContent(toolElement.clone()); continue; } if (!myLockedProfile && !changedToolNames.contains(toolName)) { markSettingsMerged(toolName, element); continue; } ToolsImpl toolList = myTools.get(toolName); LOG.assertTrue(toolList != null); Element inspectionElement = new Element(INSPECTION_TOOL_TAG); inspectionElement.setAttribute(CLASS_TAG, toolName); try { toolList.writeExternal(inspectionElement); getPathMacroManager().collapsePaths(inspectionElement); } catch (WriteExternalException e) { LOG.error(e); continue; } if (!areSettingsMerged(toolName, inspectionElement)) { element.addContent(inspectionElement); } } } private void markSettingsMerged(@NotNull String toolName, @NotNull Element element) { //add marker if already merged but result is now default (-> empty node) String mergedName = InspectionElementsMergerBase.getMergedMarkerName(toolName); if (!myUninitializedSettings.containsKey(mergedName)) { InspectionElementsMergerBase merger = getMerger(toolName); if (merger != null && merger.markSettingsMerged(myUninitializedSettings)) { element.addContent(new Element(INSPECTION_TOOL_TAG).setAttribute(CLASS_TAG, mergedName)); } } } private boolean areSettingsMerged(String toolName, Element inspectionElement) { //skip merged settings as they could be restored from already provided data final InspectionElementsMergerBase merger = getMerger(toolName); return merger != null && merger.areSettingsMerged(myUninitializedSettings, inspectionElement); } public void collectDependentInspections(@NotNull InspectionToolWrapper toolWrapper, @NotNull Set<InspectionToolWrapper<?, ?>> dependentEntries, Project project) { String mainToolId = toolWrapper.getMainToolId(); if (mainToolId != null) { InspectionToolWrapper dependentEntryWrapper = getInspectionTool(mainToolId, project); if (dependentEntryWrapper == null) { LOG.error("Can't find main tool: '" + mainToolId+"' which was specified in "+toolWrapper); return; } if (!dependentEntries.add(dependentEntryWrapper)) { collectDependentInspections(dependentEntryWrapper, dependentEntries, project); } } } @Override @Nullable public InspectionToolWrapper getInspectionTool(@NotNull String shortName, @Nullable PsiElement element) { final Tools toolList = getTools(shortName, element == null ? null : element.getProject()); return toolList == null ? null : toolList.getInspectionTool(element); } @Nullable @Override public InspectionProfileEntry getUnwrappedTool(@NotNull String shortName, @NotNull PsiElement element) { InspectionToolWrapper tool = getInspectionTool(shortName, element); return tool == null ? null : tool.getTool(); } @Override public <T extends InspectionProfileEntry> T getUnwrappedTool(@NotNull Key<T> shortNameKey, @NotNull PsiElement element) { //noinspection unchecked return (T) getUnwrappedTool(shortNameKey.toString(), element); } public void modifyProfile(@NotNull Consumer<InspectionProfileModifiableModel> modelConsumer) { InspectionProfileModifiableModelKt.edit(this, it -> { modelConsumer.consume(it); return null; }); } @Override public <T extends InspectionProfileEntry> void modifyToolSettings(@NotNull final Key<T> shortNameKey, @NotNull final PsiElement psiElement, @NotNull final Consumer<T> toolConsumer) { modifyProfile(model -> { InspectionProfileEntry tool = model.getUnwrappedTool(shortNameKey.toString(), psiElement); //noinspection unchecked toolConsumer.consume((T) tool); }); } @Override @Nullable public InspectionToolWrapper getInspectionTool(@NotNull String shortName, Project project) { final ToolsImpl tools = getTools(shortName, project); return tools != null? tools.getTool() : null; } public InspectionToolWrapper getToolById(@NotNull String id, @NotNull PsiElement element) { initInspectionTools(element.getProject()); for (Tools toolList : myTools.values()) { final InspectionToolWrapper tool = toolList.getInspectionTool(element); if (id.equals(tool.getID())) return tool; } return null; } @Nullable public List<InspectionToolWrapper> findToolsById(@NotNull String id, @NotNull PsiElement element) { List<InspectionToolWrapper> result = null; initInspectionTools(element.getProject()); for (Tools toolList : myTools.values()) { final InspectionToolWrapper tool = toolList.getInspectionTool(element); if (id.equals(tool.getID())) { if (result == null) { result = new ArrayList<>(); } result.add(tool); } } return result; } @Nullable @Override public String getSingleTool() { return myToolShortName; } public void setSingleTool(@NotNull final String toolShortName) { myToolShortName = toolShortName; } @Override @NotNull public String getDisplayName() { return getName(); } public void scopesChanged() { if (!myInitialized) { return; } for (ToolsImpl tools : myTools.values()) { tools.scopesChanged(); } getProfileManager().fireProfileChanged(this); } @Transient public boolean isProfileLocked() { return myLockedProfile; } public void lockProfile(boolean isLocked) { myLockedProfile = isLocked; schemeState = SchemeState.POSSIBLY_CHANGED; } @Override @NotNull public InspectionToolWrapper[] getInspectionTools(@Nullable PsiElement element) { initInspectionTools(element == null ? null : element.getProject()); List<InspectionToolWrapper> result = new ArrayList<>(); for (Tools toolList : myTools.values()) { result.add(toolList.getInspectionTool(element)); } return result.toArray(new InspectionToolWrapper[result.size()]); } @Override @NotNull public List<Tools> getAllEnabledInspectionTools(Project project) { initInspectionTools(project); List<Tools> result = new ArrayList<>(); for (final ToolsImpl toolList : myTools.values()) { if (toolList.isEnabled()) { result.add(toolList); } } return result; } public void disableTool(@NotNull String toolId, @NotNull PsiElement element) { getTools(toolId, element.getProject()).disableTool(element); } public void disableToolByDefault(@NotNull Collection<String> toolIds, @Nullable Project project) { for (String toolId : toolIds) { getTools(toolId, project).setDefaultEnabled(false); } schemeState = SchemeState.POSSIBLY_CHANGED; } @NotNull public ScopeToolState getToolDefaultState(@NotNull String toolId, @Nullable Project project) { return getTools(toolId, project).getDefaultState(); } public void enableToolsByDefault(@NotNull List<String> toolIds, Project project) { for (final String toolId : toolIds) { getTools(toolId, project).setDefaultEnabled(true); } schemeState = SchemeState.POSSIBLY_CHANGED; } public boolean wasInitialized() { return myInitialized; } public void initInspectionTools(@Nullable Project project) { //noinspection TestOnlyProblems if (myInitialized || (ApplicationManager.getApplication().isUnitTestMode() && !INIT_INSPECTIONS)) { return; } synchronized (myLock) { if (!myInitialized) { initialize(project); } } } @NotNull protected List<InspectionToolWrapper> createTools(@Nullable Project project) { return myRegistrar.createTools(); } private void initialize(@Nullable Project project) { SchemeDataHolder<? super InspectionProfileImpl> dataHolder = myDataHolder; if (dataHolder != null) { myDataHolder = null; Element element = dataHolder.read(); if (element.getName().equals("component")) { element = element.getChild("profile"); } assert element != null; readExternal(element); } if (myBaseProfile != null) { myBaseProfile.initInspectionTools(project); } final List<InspectionToolWrapper> tools; try { tools = createTools(project); } catch (ProcessCanceledException ignored) { return; } final Map<String, List<String>> dependencies = new THashMap<>(); for (InspectionToolWrapper toolWrapper : tools) { addTool(project, toolWrapper, dependencies); } DFSTBuilder<String> builder = new DFSTBuilder<>(GraphGenerator.generate(new InboundSemiGraph<String>() { @Override public Collection<String> getNodes() { return dependencies.keySet(); } @Override public Iterator<String> getIn(String n) { return dependencies.get(n).iterator(); } })); if (builder.isAcyclic()) { myScopesOrder = ArrayUtil.toStringArray(builder.getSortedNodes()); } copyToolsConfigurations(project); myInitialized = true; if (dataHolder != null) { // should be only after set myInitialized dataHolder.updateDigest(this); } } protected void copyToolsConfigurations(@Nullable Project project) { } public void addTool(@Nullable Project project, @NotNull InspectionToolWrapper toolWrapper, @NotNull Map<String, List<String>> dependencies) { final String shortName = toolWrapper.getShortName(); HighlightDisplayKey key = HighlightDisplayKey.find(shortName); if (key == null) { final InspectionEP extension = toolWrapper.getExtension(); Computable<String> computable = extension == null ? new Computable.PredefinedValueComputable<>(toolWrapper.getDisplayName()) : extension::getDisplayName; if (toolWrapper instanceof LocalInspectionToolWrapper) { key = HighlightDisplayKey.register(shortName, computable, toolWrapper.getID(), ((LocalInspectionToolWrapper)toolWrapper).getAlternativeID()); } else { key = HighlightDisplayKey.register(shortName, computable); } } if (key == null) { LOG.error(shortName + " ; number of initialized tools: " + myTools.size()); return; } HighlightDisplayLevel baseLevel = myBaseProfile != null && myBaseProfile.getTools(shortName, project) != null ? myBaseProfile.getErrorLevel(key, project) : HighlightDisplayLevel.DO_NOT_SHOW; HighlightDisplayLevel defaultLevel = toolWrapper.getDefaultLevel(); HighlightDisplayLevel level = baseLevel.getSeverity().compareTo(defaultLevel.getSeverity()) > 0 ? baseLevel : defaultLevel; boolean enabled = myBaseProfile != null ? myBaseProfile.isToolEnabled(key) : toolWrapper.isEnabledByDefault(); final ToolsImpl toolsList = new ToolsImpl(toolWrapper, level, !myLockedProfile && enabled, enabled); final Element element = myUninitializedSettings.remove(shortName); try { if (element != null) { getPathMacroManager().expandPaths(element); toolsList.readExternal(element, getProfileManager(), dependencies); } else if (!myUninitializedSettings.containsKey(InspectionElementsMergerBase.getMergedMarkerName(shortName))) { final InspectionElementsMergerBase merger = getMerger(shortName); Element merged = merger == null ? null : merger.merge(myUninitializedSettings); if (merged != null) { getPathMacroManager().expandPaths(merged); toolsList.readExternal(merged, getProfileManager(), dependencies); } else if (isProfileLocked()) { // https://youtrack.jetbrains.com/issue/IDEA-158936 toolsList.setEnabled(false); if (toolsList.getNonDefaultTools() == null) { toolsList.getDefaultState().setEnabled(false); } } } } catch (InvalidDataException e) { LOG.error("Can't read settings for " + toolWrapper, e); } myTools.put(shortName, toolsList); } @Nullable private static InspectionElementsMergerBase getMerger(String shortName) { final InspectionElementsMerger merger = InspectionElementsMerger.getMerger(shortName); if (merger instanceof InspectionElementsMergerBase) { return (InspectionElementsMergerBase)merger; } return merger != null ? new InspectionElementsMergerBase() { @Override public String getMergedToolName() { return merger.getMergedToolName(); } @Override public String[] getSourceToolNames() { return merger.getSourceToolNames(); } } : null; } @Nullable @Transient public String[] getScopesOrder() { return myScopesOrder; } public void setScopesOrder(String[] scopesOrder) { myScopesOrder = scopesOrder; schemeState = SchemeState.POSSIBLY_CHANGED; } private HighlightDisplayLevel getErrorLevel(@NotNull HighlightDisplayKey key, @Nullable Project project) { final ToolsImpl tools = getTools(key.toString(), project); LOG.assertTrue(tools != null, "profile name: " + myName + " base profile: " + (myBaseProfile != null ? myBaseProfile.getName() : "-") + " key: " + key); return tools.getLevel(); } @NotNull @TestOnly public InspectionProfileModifiableModel getModifiableModel() { return new InspectionProfileModifiableModel(this); } public void cleanup(@NotNull Project project) { if (!myInitialized) { return; } for (ToolsImpl toolList : myTools.values()) { if (toolList.isEnabled()) { toolList.cleanupTools(project); } } } public void enableTool(@NotNull String toolId, Project project) { final ToolsImpl tools = getTools(toolId, project); tools.setEnabled(true); tools.getDefaultState().setEnabled(true); schemeState = SchemeState.POSSIBLY_CHANGED; } public void enableTool(@NotNull String inspectionTool, @NotNull NamedScope namedScope, Project project) { getTools(inspectionTool, project).enableTool(namedScope, project); schemeState = SchemeState.POSSIBLY_CHANGED; } public void enableTools(@NotNull List<String> inspectionTools, NamedScope namedScope, Project project) { for (String inspectionTool : inspectionTools) { enableTool(inspectionTool, namedScope, project); } } public void disableTools(@NotNull List<String> inspectionTools, NamedScope namedScope, @NotNull Project project) { for (String inspectionTool : inspectionTools) { getTools(inspectionTool, project).disableTool(namedScope, project); } schemeState = SchemeState.POSSIBLY_CHANGED; } public void disableTool(@NotNull String inspectionTool, @Nullable Project project) { ToolsImpl tools = getTools(inspectionTool, project); tools.setEnabled(false); if (tools.getNonDefaultTools() == null) { tools.getDefaultState().setEnabled(false); } schemeState = SchemeState.POSSIBLY_CHANGED; } public void setErrorLevel(@NotNull HighlightDisplayKey key, @NotNull HighlightDisplayLevel level, Project project) { getTools(key.toString(), project).setLevel(level); schemeState = SchemeState.POSSIBLY_CHANGED; } @Override public boolean isToolEnabled(@Nullable HighlightDisplayKey key, PsiElement element) { if (key == null) { return false; } final Tools toolState = getTools(key.toString(), element == null ? null : element.getProject()); return toolState != null && toolState.isEnabled(element); } @Override public boolean isToolEnabled(@Nullable HighlightDisplayKey key) { return isToolEnabled(key, null); } @Override public boolean isExecutable(Project project) { initInspectionTools(project); for (Tools tools : myTools.values()) { if (tools.isEnabled()) return true; } return false; } @Tag public String getDescription() { return myDescription; } public void setDescription(@Nullable String description) { myDescription = StringUtil.nullize(description); schemeState = SchemeState.POSSIBLY_CHANGED; } public void convert(@NotNull Element element, @NotNull Project project) { final Element scopes = element.getChild("scopes"); if (scopes == null) { return; } initInspectionTools(project); for (Element scopeElement : scopes.getChildren(SCOPE)) { final String profile = scopeElement.getAttributeValue(PROFILE); InspectionProfileImpl inspectionProfile = profile == null ? null : getProfileManager().getProfile(profile); NamedScope scope = inspectionProfile == null ? null : getProfileManager().getScopesManager().getScope(scopeElement.getAttributeValue(NAME)); if (scope == null) { continue; } for (InspectionToolWrapper toolWrapper : inspectionProfile.getInspectionTools(null)) { final HighlightDisplayKey key = HighlightDisplayKey.find(toolWrapper.getShortName()); try { InspectionToolWrapper toolWrapperCopy = copyToolSettings(toolWrapper); HighlightDisplayLevel errorLevel = inspectionProfile.getErrorLevel(key, null, project); getTools(toolWrapper.getShortName(), project) .addTool(scope, toolWrapperCopy, inspectionProfile.isToolEnabled(key), errorLevel); } catch (Exception e) { LOG.error(e); } } } reduceConvertedScopes(); } private void reduceConvertedScopes() { for (ToolsImpl tools : myTools.values()) { final ScopeToolState toolState = tools.getDefaultState(); final List<ScopeToolState> nonDefaultTools = tools.getNonDefaultTools(); if (nonDefaultTools != null) { boolean equal = true; boolean isEnabled = toolState.isEnabled(); for (ScopeToolState state : nonDefaultTools) { isEnabled |= state.isEnabled(); if (!state.equalTo(toolState)) { equal = false; } } tools.setEnabled(isEnabled); if (equal) { tools.removeAllScopes(); } } } } @NotNull public List<ScopeToolState> getAllTools(@Nullable Project project) { initInspectionTools(project); List<ScopeToolState> result = new ArrayList<>(); for (Tools tools : myTools.values()) { tools.collectTools(result); } return result; } @NotNull public List<ScopeToolState> getDefaultStates(@Nullable Project project) { initInspectionTools(project); List<ScopeToolState> result = new ArrayList<>(); for (Tools tools : myTools.values()) { result.add(tools.getDefaultState()); } return result; } @NotNull public List<ScopeToolState> getNonDefaultTools(@NotNull String shortName, Project project) { final List<ScopeToolState> result = new ArrayList<>(); final List<ScopeToolState> nonDefaultTools = getTools(shortName, project).getNonDefaultTools(); if (nonDefaultTools != null) { result.addAll(nonDefaultTools); } return result; } public boolean isToolEnabled(@NotNull HighlightDisplayKey key, NamedScope namedScope, Project project) { return getTools(key.toString(), project).isEnabled(namedScope,project); } public void removeScope(@NotNull String toolId, @NotNull String scopeName, Project project) { getTools(toolId, project).removeScope(scopeName); schemeState = SchemeState.POSSIBLY_CHANGED; } public void removeScopes(@NotNull List<String> toolIds, @NotNull String scopeName, Project project) { for (final String toolId : toolIds) { removeScope(toolId, scopeName, project); } } /** * @return null if it has no base profile */ @Nullable private Set<String> getChangedToolNames() { if (myBaseProfile == null) return null; if (myChangedToolNames == null) { synchronized (myLock) { if (myChangedToolNames == null) { initInspectionTools(null); Set<String> names = myTools.keySet(); Set<String> map = new THashSet<>(names.size()); for (String toolId : names) { if (!toolSettingsAreEqual(toolId, myBaseProfile, this)) { map.add(toolId); } } myChangedToolNames = map; return map; } } } return myChangedToolNames; } public void profileChanged() { myChangedToolNames = null; schemeState = SchemeState.POSSIBLY_CHANGED; } @NotNull @Transient public HighlightDisplayLevel getErrorLevel(@NotNull HighlightDisplayKey key, NamedScope scope, Project project) { final ToolsImpl tools = getTools(key.toString(), project); return tools != null ? tools.getLevel(scope, project) : HighlightDisplayLevel.WARNING; } public ScopeToolState addScope(@NotNull InspectionToolWrapper toolWrapper, NamedScope scope, @NotNull HighlightDisplayLevel level, boolean enabled, Project project) { return getTools(toolWrapper.getShortName(), project).prependTool(scope, toolWrapper, enabled, level); } public void setErrorLevel(@NotNull HighlightDisplayKey key, @NotNull HighlightDisplayLevel level, String scopeName, Project project) { getTools(key.toString(), project).setLevel(level, scopeName, project); schemeState = SchemeState.POSSIBLY_CHANGED; } public void setErrorLevel(@NotNull List<HighlightDisplayKey> keys, @NotNull HighlightDisplayLevel level, String scopeName, Project project) { for (HighlightDisplayKey key : keys) { setErrorLevel(key, level, scopeName, project); } } public ToolsImpl getTools(@NotNull String toolId, @Nullable Project project) { initInspectionTools(project); return myTools.get(toolId); } public void enableAllTools(Project project) { for (InspectionToolWrapper entry : getInspectionTools(null)) { enableTool(entry.getShortName(), project); } } }
inspections: use more clear names
platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileImpl.java
inspections: use more clear names
<ide><path>latform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileImpl.java <ide> return result; <ide> } <ide> <del> public void disableTool(@NotNull String toolId, @NotNull PsiElement element) { <del> getTools(toolId, element.getProject()).disableTool(element); <del> } <del> <del> public void disableToolByDefault(@NotNull Collection<String> toolIds, @Nullable Project project) { <del> for (String toolId : toolIds) { <add> public void disableTool(@NotNull String toolShortName, @NotNull PsiElement element) { <add> getTools(toolShortName, element.getProject()).disableTool(element); <add> } <add> <add> public void disableToolByDefault(@NotNull Collection<String> toolShortNames, @Nullable Project project) { <add> for (String toolId : toolShortNames) { <ide> getTools(toolId, project).setDefaultEnabled(false); <ide> } <ide> schemeState = SchemeState.POSSIBLY_CHANGED; <ide> } <ide> <ide> @NotNull <del> public ScopeToolState getToolDefaultState(@NotNull String toolId, @Nullable Project project) { <del> return getTools(toolId, project).getDefaultState(); <del> } <del> <del> public void enableToolsByDefault(@NotNull List<String> toolIds, Project project) { <del> for (final String toolId : toolIds) { <del> getTools(toolId, project).setDefaultEnabled(true); <add> public ScopeToolState getToolDefaultState(@NotNull String toolShortName, @Nullable Project project) { <add> return getTools(toolShortName, project).getDefaultState(); <add> } <add> <add> public void enableToolsByDefault(@NotNull List<String> toolShortNames, Project project) { <add> for (final String shortName : toolShortNames) { <add> getTools(shortName, project).setDefaultEnabled(true); <ide> } <ide> schemeState = SchemeState.POSSIBLY_CHANGED; <ide> } <ide> } <ide> } <ide> <del> public void enableTool(@NotNull String toolId, Project project) { <del> final ToolsImpl tools = getTools(toolId, project); <add> public void enableTool(@NotNull String toolShortName, Project project) { <add> final ToolsImpl tools = getTools(toolShortName, project); <ide> tools.setEnabled(true); <ide> tools.getDefaultState().setEnabled(true); <ide> schemeState = SchemeState.POSSIBLY_CHANGED; <ide> return getTools(key.toString(), project).isEnabled(namedScope,project); <ide> } <ide> <del> public void removeScope(@NotNull String toolId, @NotNull String scopeName, Project project) { <del> getTools(toolId, project).removeScope(scopeName); <del> schemeState = SchemeState.POSSIBLY_CHANGED; <del> } <del> <del> public void removeScopes(@NotNull List<String> toolIds, @NotNull String scopeName, Project project) { <del> for (final String toolId : toolIds) { <del> removeScope(toolId, scopeName, project); <add> public void removeScope(@NotNull String toolShortName, @NotNull String scopeName, Project project) { <add> getTools(toolShortName, project).removeScope(scopeName); <add> schemeState = SchemeState.POSSIBLY_CHANGED; <add> } <add> <add> public void removeScopes(@NotNull List<String> shortNames, @NotNull String scopeName, Project project) { <add> for (final String shortName : shortNames) { <add> removeScope(shortName, scopeName, project); <ide> } <ide> } <ide> <ide> } <ide> } <ide> <del> public ToolsImpl getTools(@NotNull String toolId, @Nullable Project project) { <add> public ToolsImpl getTools(@NotNull String toolShortName, @Nullable Project project) { <ide> initInspectionTools(project); <del> return myTools.get(toolId); <add> return myTools.get(toolShortName); <ide> } <ide> <ide> public void enableAllTools(Project project) {
Java
mit
error: pathspec 'src/com/algs/Quick.java' did not match any file(s) known to git
1214dc16106291d2c5ef9593cc04b392a6126023
1
AlbertKnag/algs-practice,AlbertKnag/algs-practice,AlbertKnag/algs-practice
package com.algs; public class Quick { public static void sort(Comparable[] a) { sort(a, 0, a.length - 1); } //让数组从a[lo] 到 a[hi]有序 private static void sort(Comparable[] a, int lo, int hi) { if (hi <= lo) return; int j = partition(a, lo, hi); sort(a, lo, j-1); sort(a, j+1, hi); } // 切分数组a[lo..hi] 最终让数组满足如下状态: a[lo..j-1] <= a[j] <= a[j+1..hi] // 并返回j private static int partition(Comparable[] a, int lo, int hi) { int i = lo; int j = hi + 1; Comparable v = a[lo]; while (true) { while (less(a[++i], v)) if (i == hi) break; while (less(v, a[--j])) if (j == lo) break; if (i >= j) break; exch(a, i, j); } // 把切分的元素放到j的位置上 exch(a, lo, j); return j; } // 判断v < w ? private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } // 交换 a[i]和 a[j] private static void exch(Object[] a, int i, int j) { Object swap = a[i]; a[i] = a[j]; a[j] = swap; } public static void show(Integer[] a){ for (int i = 0; i < a.length; i++) { System.out.print(a[i]+" "); } } public static void main(String[] args) { Integer[] a = {1,55,32,2,3,4}; sort(a); show(a); } }
src/com/algs/Quick.java
add quick sort
src/com/algs/Quick.java
add quick sort
<ide><path>rc/com/algs/Quick.java <add>package com.algs; <add> <add> <add>public class Quick { <add> <add> public static void sort(Comparable[] a) { <add> sort(a, 0, a.length - 1); <add> } <add> <add> //让数组从a[lo] 到 a[hi]有序 <add> private static void sort(Comparable[] a, int lo, int hi) { <add> if (hi <= lo) return; <add> int j = partition(a, lo, hi); <add> sort(a, lo, j-1); <add> sort(a, j+1, hi); <add> } <add> <add> // 切分数组a[lo..hi] 最终让数组满足如下状态: a[lo..j-1] <= a[j] <= a[j+1..hi] <add> // 并返回j <add> private static int partition(Comparable[] a, int lo, int hi) { <add> int i = lo; <add> int j = hi + 1; <add> Comparable v = a[lo]; <add> while (true) { <add> while (less(a[++i], v)) <add> if (i == hi) break; <add> while (less(v, a[--j])) <add> if (j == lo) break; <add> if (i >= j) break; <add> exch(a, i, j); <add> } <add> // 把切分的元素放到j的位置上 <add> exch(a, lo, j); <add> return j; <add> } <add> <add> // 判断v < w ? <add> private static boolean less(Comparable v, Comparable w) { <add> return v.compareTo(w) < 0; <add> } <add> <add> // 交换 a[i]和 a[j] <add> private static void exch(Object[] a, int i, int j) { <add> Object swap = a[i]; <add> a[i] = a[j]; <add> a[j] = swap; <add> } <add> <add> public static void show(Integer[] a){ <add> for (int i = 0; i < a.length; i++) { <add> System.out.print(a[i]+" "); <add> } <add> } <add> <add> public static void main(String[] args) { <add> Integer[] a = {1,55,32,2,3,4}; <add> sort(a); <add> show(a); <add> } <add> <add>}
Java
apache-2.0
eeb610d62765268d131f010d05f1d9e9640c3ac4
0
OpenCode4Workspace/Watson-Work-Services-Java-SDK
package org.opencode4workspace.tests; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.opencode4workspace.WWException; import org.opencode4workspace.builders.SpaceDeleteGraphQLMutation; import org.opencode4workspace.mocks.MockClient; public class DeleteSpaceTest { private static final String DELETE_SPACE_MUTATION = "mutation deleteSpace {deleteSpace (input: {id: \"58938f40e4b0f86a34bbf40f\"}) {successful}}"; private static final String DELETE_SPACE_RESPONSE = "{\"data\": {\"deleteSpace\": {\"successful\": true}}"; @Test public void deleteSpace() throws WWException { SpaceDeleteGraphQLMutation mutation = SpaceDeleteGraphQLMutation.buildDeleteSpaceMutationString("58938f40e4b0f86a34bbf40f"); assertEquals(DELETE_SPACE_MUTATION, mutation.returnQuery()); } public void parseDeleteSpaceResponse() throws WWException { MockClient client = new MockClient(DELETE_SPACE_RESPONSE); assertEquals(true, client.getData().getDeletionSuccessful()); } }
wws-api/src/test/java/org/opencode4workspace/tests/DeleteSpaceTest.java
package org.opencode4workspace.tests; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.opencode4workspace.WWException; import org.opencode4workspace.builders.SpaceDeleteGraphQLMutation; public class DeleteSpaceTest { private static final String DELETE_SPACE_MUTATION = "mutation deleteSpace {deleteSpace (input: {id: \"58938f40e4b0f86a34bbf40f\"}) {successful}}"; @Test public void deleteSpace() throws WWException { SpaceDeleteGraphQLMutation mutation = SpaceDeleteGraphQLMutation.buildDeleteSpaceMutationString("58938f40e4b0f86a34bbf40f"); assertEquals(DELETE_SPACE_MUTATION, mutation.returnQuery()); } }
deleteSpace mutation
wws-api/src/test/java/org/opencode4workspace/tests/DeleteSpaceTest.java
deleteSpace mutation
<ide><path>ws-api/src/test/java/org/opencode4workspace/tests/DeleteSpaceTest.java <ide> import org.junit.Test; <ide> import org.opencode4workspace.WWException; <ide> import org.opencode4workspace.builders.SpaceDeleteGraphQLMutation; <add>import org.opencode4workspace.mocks.MockClient; <ide> <ide> public class DeleteSpaceTest { <ide> private static final String DELETE_SPACE_MUTATION = "mutation deleteSpace {deleteSpace (input: {id: \"58938f40e4b0f86a34bbf40f\"}) {successful}}"; <add> private static final String DELETE_SPACE_RESPONSE = "{\"data\": {\"deleteSpace\": {\"successful\": true}}"; <ide> <ide> @Test <ide> public void deleteSpace() throws WWException { <ide> assertEquals(DELETE_SPACE_MUTATION, mutation.returnQuery()); <ide> } <ide> <add> public void parseDeleteSpaceResponse() throws WWException { <add> MockClient client = new MockClient(DELETE_SPACE_RESPONSE); <add> assertEquals(true, client.getData().getDeletionSuccessful()); <add> } <add> <ide> }
Java
mit
73514940d413d50191caca6dc226a1e641190242
0
cs2103aug2014-f10-2j/main
// @author A0112725N package com.epictodo.logic; import com.epictodo.controller.json.Storage; import com.epictodo.model.*; import com.epictodo.model.exception.InvalidDateException; import com.epictodo.model.exception.InvalidTimeException; import com.epictodo.util.TaskDueDateComparator; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; public class CRUDLogic { /* * Message Constants */ private static final String MSG_CANT_REMOVE_TASK = "can't remove task"; private static final String MSG_POSTFIX_AS_DONE = "\" as done"; private static final String MSG_FAILED_TO_MARK_TASK = "failed to mark task \""; public static final String MSG_NO_MORE_ACTIONS_TO_BE_REDONE = "no more actions to be redone"; public static final String MSG_NO_MORE_ACTIONS_TO_BE_UNDONE = "no more actions to be undone"; private static final String MSG_POSTFIX_IS_REMOVED = "\" is removed"; private static final String MSG_POSTFIX_IS_UPDATED = "\" is updated"; private static final String MSG_POSTFIX_MARKED_AS_DONE = "\" is marked as done"; private static final String MSG_POSTFIX_IS_ADDED = "\" is added"; private static final String MSG_PREFIX_TASK = "task \""; private static final String MSG_FAILED_IO_ERROR = "failed due to file io error"; private static final String MSG_INVALID_INPUT = "invalid input"; private static final String MSG_ILLEGAL_PRIORITY = "illegal priority"; private static final String MSG_KEYWORD_MUST_NOT_BE_NULL = "keyword must not be <null>"; private static final String MSG_EMPTY_LIST = "empty list"; private static final String MSG_THERES_NO_INCOMPLETE_TASK = "there's no incomplete task"; private static final String MSG_THERES_NO_TASKS = "there's no tasks"; /* * Constants */ private static final String STRING_LINE_BREAK = "\r\n"; private static final String PATH_DATA_FILE = "storage.txt"; private static final int CONFIG_PRIORITY_MIN = 1; private static final int CONFIG_PRIORITY_MAX = 3; /* * Private Attributes */ private long _nextUid; // to track the next available uid for new Task private ArrayList<Task> _items; // to store all tasks private ArrayList<Command> _undoList; // to store undoable commands private ArrayList<Command> _redoList; // to store undone items private ArrayList<Task> _workingList; // to store previously displayed list /* * Constructor */ public CRUDLogic() { _nextUid = 1; _items = new ArrayList<Task>(); _undoList = new ArrayList<Command>(); _redoList = new ArrayList<Command>(); _workingList = new ArrayList<Task>(); } /* * CRUD Methods */ /** * This method returns the whole list of Tasks regardless of their status * * @return the ArrayList containing all the tasks * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getAllTasks() { /* * the return should only deliver a duplicate of the objects */ ArrayList<Task> retList = new ArrayList<Task>(); for (int i = 0; i < _items.size(); i++) { retList.add(_items.get(i).copy()); } updateWorkingList(retList); // update the working list return retList; } /** * This method returns the whole list of incomplete tasks * * @return the ArrayList containing all the tasks * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getIncompleteTasks() { /* * the return should only deliver a duplicate of the objects */ ArrayList<Task> resultList = new ArrayList<Task>(); for (int i = 0; i < _items.size(); i++) { if (!_items.get(i).getIsDone()) resultList.add(_items.get(i).copy()); } updateWorkingList(resultList); // update the working list return resultList; } /** * This method returns tasks based on whether it has been marked as done * * @return the ArrayList containing selected tasks * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getTasksByName(String keyword) { ArrayList<Task> resultList = new ArrayList<Task>(); /* * Exception handling to make sure param is not null */ if (keyword == null) { throw new NullPointerException(MSG_KEYWORD_MUST_NOT_BE_NULL); } for (int i = 0; i < size(); i++) { if (_items.get(i).getTaskName().toLowerCase() .contains(keyword.trim().toLowerCase()) && !_items.get(i).getIsDone()) { resultList.add(_items.get(i).copy()); } } updateWorkingList(resultList); // update the working list return resultList; } /** * This method returns tasks based on whether it has been marked as done * * @param boolean when true = Marked as done * @return the ArrayList containing selected tasks * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getTasksByStatus(boolean done) throws ParseException, InvalidDateException, InvalidTimeException { ArrayList<Task> resultList = new ArrayList<Task>(); for (int i = 0; i < size(); i++) { if (_items.get(i).getIsDone() == done) { resultList.add(_items.get(i).copy()); } } updateWorkingList(resultList); // update the working list return resultList; } /** * This method returns a list of tasks based on the priority set * * @param p * the priority enum * @return the ArrayList containing the selected tasks * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getTasksByPriority(int p) throws IllegalArgumentException, ParseException, InvalidDateException, InvalidTimeException { ArrayList<Task> resultList = new ArrayList<Task>(); /* * Exception handling to make sure the priority is within valid range */ if (p < CONFIG_PRIORITY_MIN || p > CONFIG_PRIORITY_MAX) { throw new IllegalArgumentException(MSG_ILLEGAL_PRIORITY); } for (int i = 0; i < size(); i++) { if (_items.get(i).getPriority() == p && !_items.get(i).getIsDone()) { resultList.add(_items.get(i).copy()); } } updateWorkingList(resultList); // update the working list return resultList; } /** * This method returns a list of active tasks in chronological order of due * dates * * @return array list of tasks * @throws IllegalArgumentException * @throws ParseException * @throws InvalidDateException * @throws InvalidTimeException */ public ArrayList<Task> getTasksOrderedByDueDate() throws IllegalArgumentException, ParseException, InvalidDateException, InvalidTimeException { ArrayList<Task> resultList = new ArrayList<Task>(); ArrayList<Task> temp = new ArrayList<Task>(); for (int i = 0; i < size(); i++) { if (_items.get(i) instanceof FloatingTask) { // Add floating tasks to list first resultList.add(_items.get(i).copy()); } else { // Dump all other tasks into a temp list temp.add(_items.get(i).copy()); } } // sort the temp list Collections.sort(temp, new TaskDueDateComparator()); // add the ordered temp list to the final list resultList.addAll(temp); updateWorkingList(resultList); // update the working list return resultList; } /** * This method retrieves a list of tasks based on a specific due date * (starting date) * * @param compareDate * due date in the ddmmyy format * @return the list of tasks */ public ArrayList<Task> getTasksByDate(String compareDate) { ArrayList<Task> resultList = new ArrayList<Task>(); ArrayList<Task> incomplete = getIncompleteTasks(); for (int i = 0; i < incomplete.size(); i++) { Task t = incomplete.get(i); String taskDate = ""; if (t instanceof DeadlineTask) { taskDate = ((DeadlineTask) t).getDate(); } else if (t instanceof TimedTask) { taskDate = ((TimedTask) t).getStartDate(); } if (taskDate.equals(compareDate)) { resultList.add(t); } } updateWorkingList(resultList); // update the working list return resultList; } /** * This method retrieves the task item in the working list based on index * * @param index * @return the task object - <null> indicates not found */ public Task translateWorkingListId(String keyword) { try { int index = Integer.valueOf(keyword.trim()); return _workingList.get(index - 1); } catch (Exception ex) { return null; } } /* * Other CRUD Methods */ /** * This method adds a Task to the list * * @param t * the Task obj * @return The result in a String */ public String createTask(Task t) throws NullPointerException { if (t == null) { return MSG_INVALID_INPUT; } addToItems(t); /* * Create an undoable command object */ addCommand(Command.CommandType.ADD, t); try { saveToFile(); } catch (IOException ioe) { _items.remove(t); return MSG_FAILED_IO_ERROR; } return MSG_PREFIX_TASK + t.getTaskName() + MSG_POSTFIX_IS_ADDED; } /** * This method adds an Floating Task to the list * * @param ft * the FloatingTask obj * @return The result in a String */ public String createTask(FloatingTask ft) throws NullPointerException { return createTask(ft); } /** * This method adds an Deadline Task to the list * * @param dt * the DeadlineTask obj * @return The result in a String */ public String createTask(DeadlineTask dt) throws NullPointerException { return createTask(dt); } /** * This method adds an Floating Task to the list * * @param tt * the TimedTask obj * @return The result in a String */ public String createTask(TimedTask tt) throws NullPointerException { return createTask(tt); } /** * This method displays the content of all the tasks that matches the * keyword in names * * @param keyword * @return */ public String searchForTasks(String keyword) { return convertListToString(getTasksByName(keyword)); } public String markAsDone(Task t) { if (t == null) return MSG_INVALID_INPUT; Task found = getTaskByUid(t.getUid()); if (found != null) { int index = _items.indexOf(getTaskByUid(found.getUid())); try { found.setIsDone(true); addCommand(Command.CommandType.MARKDONE, found, index); saveToFile(); return MSG_PREFIX_TASK + t.getTaskName() + MSG_POSTFIX_MARKED_AS_DONE; } catch (IOException ioe) { found.setIsDone(false); return MSG_FAILED_TO_MARK_TASK + t.getTaskName() + MSG_POSTFIX_AS_DONE; } } else { return MSG_FAILED_TO_MARK_TASK + t.getTaskName() + MSG_POSTFIX_AS_DONE; } } /** * This method marks all expired tasks as done */ public void clearExpiredTask() { for (int i = 0; i < size(); i++) { Task t = _items.get(i); long dateTimeNow = System.currentTimeMillis() / 1000L; if (t instanceof TimedTask && !t.getIsDone() && ((TimedTask) t).getEndDateTime() < dateTimeNow) { t.setIsDone(true); } else if (t instanceof DeadlineTask && !t.getIsDone() && ((DeadlineTask) t).getEndDateTime() < dateTimeNow) { t.setIsDone(true); } } try { saveToFile(); } catch (IOException e) { e.printStackTrace(); } } /** * This method updates a task item by replacing it with an updated one * * @param target * @param replacement * @return the message indicating the successfulness of the operation */ public String updateTask(Task target, Task replacement) { int index = _items.indexOf(getTaskByUid(target.getUid())); if (index != -1) { _items.set(index, replacement); /* * create an undoable command */ addCommand(Command.CommandType.UPDATE, target, replacement); /* * save changes to storage */ try { saveToFile(); return MSG_PREFIX_TASK + target.getTaskName() + MSG_POSTFIX_IS_UPDATED; } catch (IOException e) { e.printStackTrace(); return MSG_FAILED_IO_ERROR; } } else { return MSG_INVALID_INPUT; } } /* * Undo and Redo methods */ /** * This method removes a Task by UID * * @param t * @return */ public String deleteTask(Task t) { if (t == null) return MSG_INVALID_INPUT; Task found = getTaskByUid(t.getUid()); int index = _items.indexOf(getTaskByUid(found.getUid())); if (found != null && _items.remove(found)) { try { /* * create an undoable command */ addCommand(Command.CommandType.DELETE, found, index); _workingList = new ArrayList<Task>(); saveToFile(); return MSG_PREFIX_TASK + t.getTaskName() + MSG_POSTFIX_IS_REMOVED; } catch (IOException ioe) { _items.remove(t); return MSG_FAILED_IO_ERROR; } } else { return MSG_CANT_REMOVE_TASK; } } /** * This method invokes the undo operation on the most recent undoable action * * @return The result in a string */ public String undoMostRecent() { String result = MSG_NO_MORE_ACTIONS_TO_BE_UNDONE; if (_undoList.size() > 0) { Command comm = _undoList.get(_undoList.size() - 1); result = comm.undo(); /* * to enable redo */ _redoList.add(_undoList.remove(_undoList.size() - 1)); } return result; } /** * This method invokes the redo operation on the most recent undoable action * * @return The result in a string */ public String redoMostRecent() { String result = MSG_NO_MORE_ACTIONS_TO_BE_REDONE; if (_redoList.size() > 0) { Command comm = _redoList.get(_redoList.size() - 1); result = comm.redo(); _undoList.add(_redoList.remove(_redoList.size() - 1)); } return result; } /* * Other Methods */ /** * This method returns the number of task obj in the list * * @return int the size of the list of tasks */ public int size() { return _items.size(); } /** * This method returns a string that represent all the tasks in the task * list in RAM * * @return */ public String displayAllTaskList() { String result = convertListToString(getAllTasks()); if (result.equals(MSG_EMPTY_LIST)) { return MSG_THERES_NO_TASKS; } else { return result; } } /** * This method returns a string that represent all incomplete tasks list in * RAM * * @return */ public String displayIncompleteTaskList() { String result = convertListToString(getIncompleteTasks()); if (result.equals(MSG_EMPTY_LIST)) { return MSG_THERES_NO_INCOMPLETE_TASK; } else { return result; } } /** * This method returns a string that represent all the tasks in a list * * @param li * @return */ public String convertListToString(ArrayList<Task> li) { String retStr = ""; if (li.size() > 0) { for (int i = 0; i < li.size(); i++) { retStr += String.valueOf(i + 1) + ". " + li.get(i) + STRING_LINE_BREAK; } } else { retStr = MSG_EMPTY_LIST; } return retStr; } /* * Storage handlers */ /** * This method loads all tasks from the text file */ public boolean loadFromFile() throws IOException { _items = Storage.loadDbFile(PATH_DATA_FILE); if (_items == null) { _items = new ArrayList<Task>(); } _nextUid = getMaxUid(); return true; } /** * This method saves all tasks to the text file */ public void saveToFile() throws IOException { String filename = PATH_DATA_FILE; Storage.saveToJson(filename, _items); } /* * Private Methods */ /** * This method assign UID to new Task and add it to the list * * @param t * : the task to add */ private void addToItems(Task t) { t.setUid(_nextUid); _items.add(t); _nextUid++; } /** * This method returns an actual reference to the task with a specific UID * in the item list * * @param uid * @return */ private Task getTaskByUid(long uid) { for (int i = 0; i < _items.size(); i++) { if (_items.get(i).getUid() == uid) { return _items.get(i); } } return null; } /** * This method retrieves the next UID available for newly added Task objects * * @return the UID */ private long getMaxUid() { long max = 0; if (_items != null) { for (int i = 0; i < _items.size(); i++) { if (_items.get(i).getUid() > max) { max = _items.get(i).getUid(); } } } return max + 1; } /** * This method creates an undoable command in the stack * * @param type * @param target */ private void addCommand(Command.CommandType type, Task target) { Command comm = new Command(_items, type, target); _undoList.add(comm); } /** * This method adds a undoable command object to the undo list without * supplying the index of object being affected * * @param type * @param target * @param replacement */ private void addCommand(Command.CommandType type, Task target, Task replacement) { Command comm = new Command(_items, type, target, replacement); _undoList.add(comm); } /** * This method adds a undoable command object to the undo list with index of * affected object supplied as param * * @param type * @param target * @param index */ private void addCommand(Command.CommandType type, Task target, int index) { Command comm = new Command(_items, type, target, index); _undoList.add(comm); } /** * This method updates the working list * * @param li * the previously displayed list */ private void updateWorkingList(ArrayList<Task> li) { _workingList = li; } public String searchDetail(Task task) { String details = ""; if (task != null) { details = task.getDetail(); } return details; } }
src/main/java/com/epictodo/logic/CRUDLogic.java
// @author A0112725N package com.epictodo.logic; import com.epictodo.controller.json.Storage; import com.epictodo.model.*; import com.epictodo.model.exception.InvalidDateException; import com.epictodo.model.exception.InvalidTimeException; import com.epictodo.util.TaskDueDateComparator; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; public class CRUDLogic { /* * Message Constants */ private static final String MSG_CANT_REMOVE_TASK = "can't remove task"; private static final String MSG_POSTFIX_AS_DONE = "\" as done"; private static final String MSG_FAILED_TO_MARK_TASK = "failed to mark task \""; public static final String MSG_NO_MORE_ACTIONS_TO_BE_REDONE = "no more actions to be redone"; public static final String MSG_NO_MORE_ACTIONS_TO_BE_UNDONE = "no more actions to be undone"; private static final String MSG_POSTFIX_IS_REMOVED = "\" is removed"; private static final String MSG_POSTFIX_IS_UPDATED = "\" is updated"; private static final String MSG_POSTFIX_MARKED_AS_DONE = "\" is marked as done"; private static final String MSG_POSTFIX_IS_ADDED = "\" is added"; private static final String MSG_PREFIX_TASK = "task \""; private static final String MSG_FAILED_IO_ERROR = "failed due to file io error"; private static final String MSG_INVALID_INPUT = "invalid input"; private static final String MSG_ILLEGAL_PRIORITY = "illegal priority"; private static final String MSG_KEYWORD_MUST_NOT_BE_NULL = "keyword must not be <null>"; private static final String MSG_EMPTY_LIST = "empty list"; /* * Constants */ private static final String STRING_LINE_BREAK = "\r\n"; private static final String PATH_DATA_FILE = "storage.txt"; private static final int CONFIG_PRIORITY_MIN = 1; private static final int CONFIG_PRIORITY_MAX = 3; /* * Private Attributes */ private long _nextUid; // to track the next available uid for new Task private ArrayList<Task> _items; // to store all tasks private ArrayList<Command> _undoList; // to store undoable commands private ArrayList<Command> _redoList; // to store undone items private ArrayList<Task> _workingList; // to store previously displayed list /* * Constructor */ public CRUDLogic() { _nextUid = 1; _items = new ArrayList<Task>(); _undoList = new ArrayList<Command>(); _redoList = new ArrayList<Command>(); _workingList = new ArrayList<Task>(); } /* * CRUD Methods */ /** * This method returns the whole list of Tasks regardless of their status * * @return the ArrayList containing all the tasks * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getAllTasks() { /* * the return should only deliver a duplicate of the objects */ ArrayList<Task> retList = new ArrayList<Task>(); for (int i = 0; i < _items.size(); i++) { retList.add(_items.get(i).copy()); } updateWorkingList(retList); // update the working list return retList; } /** * This method returns the whole list of incomplete tasks * * @return the ArrayList containing all the tasks * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getIncompleteTasks() { /* * the return should only deliver a duplicate of the objects */ ArrayList<Task> resultList = new ArrayList<Task>(); for (int i = 0; i < _items.size(); i++) { if (!_items.get(i).getIsDone()) resultList.add(_items.get(i).copy()); } updateWorkingList(resultList); // update the working list return resultList; } /** * This method returns tasks based on whether it has been marked as done * * @return the ArrayList containing selected tasks * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getTasksByName(String keyword) { ArrayList<Task> resultList = new ArrayList<Task>(); /* * Exception handling to make sure param is not null */ if (keyword == null) { throw new NullPointerException(MSG_KEYWORD_MUST_NOT_BE_NULL); } for (int i = 0; i < size(); i++) { if (_items.get(i).getTaskName().toLowerCase() .contains(keyword.trim().toLowerCase()) && !_items.get(i).getIsDone()) { resultList.add(_items.get(i).copy()); } } updateWorkingList(resultList); // update the working list return resultList; } /** * This method returns tasks based on whether it has been marked as done * * @param boolean when true = Marked as done * @return the ArrayList containing selected tasks * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getTasksByStatus(boolean done) throws ParseException, InvalidDateException, InvalidTimeException { ArrayList<Task> resultList = new ArrayList<Task>(); for (int i = 0; i < size(); i++) { if (_items.get(i).getIsDone() == done) { resultList.add(_items.get(i).copy()); } } updateWorkingList(resultList); // update the working list return resultList; } /** * This method returns a list of tasks based on the priority set * * @param p * the priority enum * @return the ArrayList containing the selected tasks * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getTasksByPriority(int p) throws IllegalArgumentException, ParseException, InvalidDateException, InvalidTimeException { ArrayList<Task> resultList = new ArrayList<Task>(); /* * Exception handling to make sure the priority is within valid range */ if (p < CONFIG_PRIORITY_MIN || p > CONFIG_PRIORITY_MAX) { throw new IllegalArgumentException(MSG_ILLEGAL_PRIORITY); } for (int i = 0; i < size(); i++) { if (_items.get(i).getPriority() == p && !_items.get(i).getIsDone()) { resultList.add(_items.get(i).copy()); } } updateWorkingList(resultList); // update the working list return resultList; } /** * This method returns a list of active tasks in chronological order of due * dates * * @return array list of tasks * @throws IllegalArgumentException * @throws ParseException * @throws InvalidDateException * @throws InvalidTimeException */ public ArrayList<Task> getTasksOrderedByDueDate() throws IllegalArgumentException, ParseException, InvalidDateException, InvalidTimeException { ArrayList<Task> resultList = new ArrayList<Task>(); ArrayList<Task> temp = new ArrayList<Task>(); for (int i = 0; i < size(); i++) { if (_items.get(i) instanceof FloatingTask) { // Add floating tasks to list first resultList.add(_items.get(i).copy()); } else { // Dump all other tasks into a temp list temp.add(_items.get(i).copy()); } } // sort the temp list Collections.sort(temp, new TaskDueDateComparator()); // add the ordered temp list to the final list resultList.addAll(temp); updateWorkingList(resultList); // update the working list return resultList; } /** * This method retrieves a list of tasks based on a specific due date * (starting date) * * @param compareDate * due date in the ddmmyy format * @return the list of tasks */ public ArrayList<Task> getTasksByDate(String compareDate) { ArrayList<Task> resultList = new ArrayList<Task>(); ArrayList<Task> incomplete = getIncompleteTasks(); for (int i = 0; i < incomplete.size(); i++) { Task t = incomplete.get(i); String taskDate = ""; if (t instanceof DeadlineTask) { taskDate = ((DeadlineTask) t).getDate(); } else if (t instanceof TimedTask) { taskDate = ((TimedTask) t).getStartDate(); } if (taskDate.equals(compareDate)) { resultList.add(t); } } updateWorkingList(resultList); // update the working list return resultList; } /** * This method retrieves the task item in the working list based on index * * @param index * @return the task object - <null> indicates not found */ public Task translateWorkingListId(String keyword) { try { int index = Integer.valueOf(keyword.trim()); return _workingList.get(index - 1); } catch (Exception ex) { return null; } } /* * Other CRUD Methods */ /** * This method adds a Task to the list * * @param t * the Task obj * @return The result in a String */ public String createTask(Task t) throws NullPointerException { if (t == null) { return MSG_INVALID_INPUT; } addToItems(t); /* * Create an undoable command object */ addCommand(Command.CommandType.ADD, t); try { saveToFile(); } catch (IOException ioe) { _items.remove(t); return MSG_FAILED_IO_ERROR; } return MSG_PREFIX_TASK + t.getTaskName() + MSG_POSTFIX_IS_ADDED; } /** * This method adds an Floating Task to the list * * @param ft * the FloatingTask obj * @return The result in a String */ public String createTask(FloatingTask ft) throws NullPointerException { return createTask(ft); } /** * This method adds an Deadline Task to the list * * @param dt * the DeadlineTask obj * @return The result in a String */ public String createTask(DeadlineTask dt) throws NullPointerException { return createTask(dt); } /** * This method adds an Floating Task to the list * * @param tt * the TimedTask obj * @return The result in a String */ public String createTask(TimedTask tt) throws NullPointerException { return createTask(tt); } /** * This method displays the content of all the tasks that matches the * keyword in names * * @param keyword * @return */ public String searchForTasks(String keyword) { return convertListToString(getTasksByName(keyword)); } public String markAsDone(Task t) { if (t == null) return MSG_INVALID_INPUT; Task found = getTaskByUid(t.getUid()); if (found != null) { int index = _items.indexOf(getTaskByUid(found.getUid())); try { found.setIsDone(true); addCommand(Command.CommandType.MARKDONE, found, index); saveToFile(); return MSG_PREFIX_TASK + t.getTaskName() + MSG_POSTFIX_MARKED_AS_DONE; } catch (IOException ioe) { found.setIsDone(false); return MSG_FAILED_TO_MARK_TASK + t.getTaskName() + MSG_POSTFIX_AS_DONE; } } else { return MSG_FAILED_TO_MARK_TASK + t.getTaskName() + MSG_POSTFIX_AS_DONE; } } /** * This method marks all expired tasks as done */ public void clearExpiredTask() { for (int i = 0; i < size(); i++) { Task t = _items.get(i); long dateTimeNow = System.currentTimeMillis() / 1000L; if (t instanceof TimedTask && !t.getIsDone() && ((TimedTask) t).getEndDateTime() < dateTimeNow) { t.setIsDone(true); } else if (t instanceof DeadlineTask && !t.getIsDone() && ((DeadlineTask) t).getEndDateTime() < dateTimeNow) { t.setIsDone(true); } } try { saveToFile(); } catch (IOException e) { e.printStackTrace(); } } /** * This method updates a task item by replacing it with an updated one * * @param target * @param replacement * @return the message indicating the successfulness of the operation */ public String updateTask(Task target, Task replacement) { int index = _items.indexOf(getTaskByUid(target.getUid())); if (index != -1) { _items.set(index, replacement); /* * create an undoable command */ addCommand(Command.CommandType.UPDATE, target, replacement); /* * save changes to storage */ try { saveToFile(); return MSG_PREFIX_TASK + target.getTaskName() + MSG_POSTFIX_IS_UPDATED; } catch (IOException e) { e.printStackTrace(); return MSG_FAILED_IO_ERROR; } } else { return MSG_INVALID_INPUT; } } /* * Undo and Redo methods */ /** * This method removes a Task by UID * * @param t * @return */ public String deleteTask(Task t) { if (t == null) return MSG_INVALID_INPUT; Task found = getTaskByUid(t.getUid()); int index = _items.indexOf(getTaskByUid(found.getUid())); if (found != null && _items.remove(found)) { try { /* * create an undoable command */ addCommand(Command.CommandType.DELETE, found, index); _workingList = new ArrayList<Task>(); saveToFile(); return MSG_PREFIX_TASK + t.getTaskName() + MSG_POSTFIX_IS_REMOVED; } catch (IOException ioe) { _items.remove(t); return MSG_FAILED_IO_ERROR; } } else { return MSG_CANT_REMOVE_TASK; } } /** * This method invokes the undo operation on the most recent undoable action * * @return The result in a string */ public String undoMostRecent() { String result = MSG_NO_MORE_ACTIONS_TO_BE_UNDONE; if (_undoList.size() > 0) { Command comm = _undoList.get(_undoList.size() - 1); result = comm.undo(); /* * to enable redo */ _redoList.add(_undoList.remove(_undoList.size() - 1)); } return result; } /** * This method invokes the redo operation on the most recent undoable action * * @return The result in a string */ public String redoMostRecent() { String result = MSG_NO_MORE_ACTIONS_TO_BE_REDONE; if (_redoList.size() > 0) { Command comm = _redoList.get(_redoList.size() - 1); result = comm.redo(); _undoList.add(_redoList.remove(_redoList.size() - 1)); } return result; } /* * Other Methods */ /** * This method returns the number of task obj in the list * * @return int the size of the list of tasks */ public int size() { return _items.size(); } /** * This method returns a string that represent all the tasks in the task * list in RAM * * @return */ public String displayAllTaskList() { return convertListToString(getAllTasks()); } /** * This method returns a string that represent all incomplete tasks list in * RAM * * @return */ public String displayIncompleteTaskList() { return convertListToString(getIncompleteTasks()); } /** * This method returns a string that represent all the tasks in a list * * @param li * @return */ public String convertListToString(ArrayList<Task> li) { String retStr = ""; if (li.size() > 0) { for (int i = 0; i < li.size(); i++) { retStr += String.valueOf(i + 1) + ". " + li.get(i) + STRING_LINE_BREAK; } } else { retStr = MSG_EMPTY_LIST; } return retStr; } /* * Storage handlers */ /** * This method loads all tasks from the text file */ public boolean loadFromFile() throws IOException { _items = Storage.loadDbFile(PATH_DATA_FILE); if (_items == null) { _items = new ArrayList<Task>(); } _nextUid = getMaxUid(); return true; } /** * This method saves all tasks to the text file */ public void saveToFile() throws IOException { String filename = PATH_DATA_FILE; Storage.saveToJson(filename, _items); } /* * Private Methods */ /** * This method assign UID to new Task and add it to the list * * @param t * : the task to add */ private void addToItems(Task t) { t.setUid(_nextUid); _items.add(t); _nextUid++; } /** * This method returns an actual reference to the task with a specific UID * in the item list * * @param uid * @return */ private Task getTaskByUid(long uid) { for (int i = 0; i < _items.size(); i++) { if (_items.get(i).getUid() == uid) { return _items.get(i); } } return null; } /** * This method retrieves the next UID available for newly added Task objects * * @return the UID */ private long getMaxUid() { long max = 0; if (_items != null) { for (int i = 0; i < _items.size(); i++) { if (_items.get(i).getUid() > max) { max = _items.get(i).getUid(); } } } return max + 1; } /** * This method creates an undoable command in the stack * * @param type * @param target */ private void addCommand(Command.CommandType type, Task target) { Command comm = new Command(_items, type, target); _undoList.add(comm); } /** * This method adds a undoable command object to the undo list without * supplying the index of object being affected * * @param type * @param target * @param replacement */ private void addCommand(Command.CommandType type, Task target, Task replacement) { Command comm = new Command(_items, type, target, replacement); _undoList.add(comm); } /** * This method adds a undoable command object to the undo list with index of * affected object supplied as param * * @param type * @param target * @param index */ private void addCommand(Command.CommandType type, Task target, int index) { Command comm = new Command(_items, type, target, index); _undoList.add(comm); } /** * This method updates the working list * * @param li * the previously displayed list */ private void updateWorkingList(ArrayList<Task> li) { _workingList = li; } public String searchDetail(Task task) { String details = ""; if (task != null) { details = task.getDetail(); } return details; } }
Refined display message for empty list
src/main/java/com/epictodo/logic/CRUDLogic.java
Refined display message for empty list
<ide><path>rc/main/java/com/epictodo/logic/CRUDLogic.java <ide> private static final String MSG_ILLEGAL_PRIORITY = "illegal priority"; <ide> private static final String MSG_KEYWORD_MUST_NOT_BE_NULL = "keyword must not be <null>"; <ide> private static final String MSG_EMPTY_LIST = "empty list"; <add> private static final String MSG_THERES_NO_INCOMPLETE_TASK = "there's no incomplete task"; <add> private static final String MSG_THERES_NO_TASKS = "there's no tasks"; <ide> <ide> /* <ide> * Constants <ide> * @return <ide> */ <ide> public String displayAllTaskList() { <del> return convertListToString(getAllTasks()); <add> String result = convertListToString(getAllTasks()); <add> if (result.equals(MSG_EMPTY_LIST)) { <add> return MSG_THERES_NO_TASKS; <add> } else { <add> return result; <add> } <ide> } <ide> <ide> /** <ide> * @return <ide> */ <ide> public String displayIncompleteTaskList() { <del> return convertListToString(getIncompleteTasks()); <add> String result = convertListToString(getIncompleteTasks()); <add> if (result.equals(MSG_EMPTY_LIST)) { <add> return MSG_THERES_NO_INCOMPLETE_TASK; <add> } else { <add> return result; <add> } <ide> } <ide> <ide> /**
Java
apache-2.0
859049e864dca07869203c14524c28f80e437348
0
AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.widget; import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP_PREFIX; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Build; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.FocusFinder; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import android.view.animation.AnimationUtils; import android.widget.EdgeEffect; import android.widget.FrameLayout; import android.widget.OverScroller; import android.widget.ScrollView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.core.view.AccessibilityDelegateCompat; import androidx.core.view.InputDeviceCompat; import androidx.core.view.NestedScrollingChild3; import androidx.core.view.NestedScrollingChildHelper; import androidx.core.view.NestedScrollingParent3; import androidx.core.view.NestedScrollingParentHelper; import androidx.core.view.ScrollingView; import androidx.core.view.ViewCompat; import androidx.core.view.accessibility.AccessibilityNodeInfoCompat; import androidx.core.view.accessibility.AccessibilityRecordCompat; import java.util.List; /** * NestedScrollView is just like {@link android.widget.ScrollView}, but it supports acting * as both a nested scrolling parent and child on both new and old versions of Android. * Nested scrolling is enabled by default. */ public class NestedScrollView extends FrameLayout implements NestedScrollingParent3, NestedScrollingChild3, ScrollingView { static final int ANIMATED_SCROLL_GAP = 250; static final float MAX_SCROLL_FACTOR = 0.5f; private static final String TAG = "NestedScrollView"; /** * Interface definition for a callback to be invoked when the scroll * X or Y positions of a view change. * * <p>This version of the interface works on all versions of Android, back to API v4.</p> * * @see #setOnScrollChangeListener(OnScrollChangeListener) */ public interface OnScrollChangeListener { /** * Called when the scroll position of a view changes. * * @param v The view whose scroll position has changed. * @param scrollX Current horizontal scroll origin. * @param scrollY Current vertical scroll origin. * @param oldScrollX Previous horizontal scroll origin. * @param oldScrollY Previous vertical scroll origin. */ void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); } private long mLastScroll; private final Rect mTempRect = new Rect(); private OverScroller mScroller; private EdgeEffect mEdgeGlowTop; private EdgeEffect mEdgeGlowBottom; /** * Position of the last motion event. */ private int mLastMotionY; /** * True when the layout has changed but the traversal has not come through yet. * Ideally the view hierarchy would keep track of this for us. */ private boolean mIsLayoutDirty = true; private boolean mIsLaidOut = false; /** * The child to give focus to in the event that a child has requested focus while the * layout is dirty. This prevents the scroll from being wrong if the child has not been * laid out before requesting focus. */ private View mChildToScrollTo = null; /** * True if the user is currently dragging this ScrollView around. This is * not the same as 'is being flinged', which can be checked by * mScroller.isFinished() (flinging begins when the user lifts his finger). */ private boolean mIsBeingDragged = false; /** * Determines speed during touch scrolling */ private VelocityTracker mVelocityTracker; /** * When set to true, the scroll view measure its child to make it fill the currently * visible area. */ private boolean mFillViewport; /** * Whether arrow scrolling is animated. */ private boolean mSmoothScrollingEnabled = true; private int mTouchSlop; private int mMinimumVelocity; private int mMaximumVelocity; /** * ID of the active pointer. This is used to retain consistency during * drags/flings if multiple pointers are used. */ private int mActivePointerId = INVALID_POINTER; /** * Used during scrolling to retrieve the new offset within the window. */ private final int[] mScrollOffset = new int[2]; private final int[] mScrollConsumed = new int[2]; private int mNestedYOffset; private int mLastScrollerY; /** * Sentinel value for no current active pointer. * Used by {@link #mActivePointerId}. */ private static final int INVALID_POINTER = -1; private SavedState mSavedState; private static final AccessibilityDelegate ACCESSIBILITY_DELEGATE = new AccessibilityDelegate(); private static final int[] SCROLLVIEW_STYLEABLE = new int[] { android.R.attr.fillViewport }; private final NestedScrollingParentHelper mParentHelper; private final NestedScrollingChildHelper mChildHelper; private float mVerticalScrollFactor; private OnScrollChangeListener mOnScrollChangeListener; public NestedScrollView(@NonNull Context context) { this(context, null); } public NestedScrollView(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public NestedScrollView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initScrollView(); final TypedArray a = context.obtainStyledAttributes( attrs, SCROLLVIEW_STYLEABLE, defStyleAttr, 0); setFillViewport(a.getBoolean(0, false)); a.recycle(); mParentHelper = new NestedScrollingParentHelper(this); mChildHelper = new NestedScrollingChildHelper(this); // ...because why else would you be using this widget? setNestedScrollingEnabled(true); ViewCompat.setAccessibilityDelegate(this, ACCESSIBILITY_DELEGATE); } // NestedScrollingChild3 @Override public void dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, @Nullable int[] offsetInWindow, int type, @NonNull int[] consumed) { mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow, type, consumed); } // NestedScrollingChild2 @Override public boolean startNestedScroll(int axes, int type) { return mChildHelper.startNestedScroll(axes, type); } @Override public void stopNestedScroll(int type) { mChildHelper.stopNestedScroll(type); } @Override public boolean hasNestedScrollingParent(int type) { return mChildHelper.hasNestedScrollingParent(type); } @Override public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow, int type) { return mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow, type); } @Override public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow, int type) { return mChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow, type); } // NestedScrollingChild @Override public void setNestedScrollingEnabled(boolean enabled) { mChildHelper.setNestedScrollingEnabled(enabled); } @Override public boolean isNestedScrollingEnabled() { return mChildHelper.isNestedScrollingEnabled(); } @Override public boolean startNestedScroll(int axes) { return startNestedScroll(axes, ViewCompat.TYPE_TOUCH); } @Override public void stopNestedScroll() { stopNestedScroll(ViewCompat.TYPE_TOUCH); } @Override public boolean hasNestedScrollingParent() { return hasNestedScrollingParent(ViewCompat.TYPE_TOUCH); } @Override public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { return mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow); } @Override public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { return dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow, ViewCompat.TYPE_TOUCH); } @Override public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { return mChildHelper.dispatchNestedFling(velocityX, velocityY, consumed); } @Override public boolean dispatchNestedPreFling(float velocityX, float velocityY) { return mChildHelper.dispatchNestedPreFling(velocityX, velocityY); } // NestedScrollingParent3 @Override public void onNestedScroll(@NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type, @NonNull int[] consumed) { onNestedScrollInternal(dyUnconsumed, type, consumed); } private void onNestedScrollInternal(int dyUnconsumed, int type, @Nullable int[] consumed) { final int oldScrollY = getScrollY(); scrollBy(0, dyUnconsumed); final int myConsumed = getScrollY() - oldScrollY; if (consumed != null) { consumed[1] += myConsumed; } final int myUnconsumed = dyUnconsumed - myConsumed; mChildHelper.dispatchNestedScroll(0, myConsumed, 0, myUnconsumed, null, type, consumed); } // NestedScrollingParent2 @Override public boolean onStartNestedScroll(@NonNull View child, @NonNull View target, int axes, int type) { return (axes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0; } @Override public void onNestedScrollAccepted(@NonNull View child, @NonNull View target, int axes, int type) { mParentHelper.onNestedScrollAccepted(child, target, axes, type); startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL, type); } @Override public void onStopNestedScroll(@NonNull View target, int type) { mParentHelper.onStopNestedScroll(target, type); stopNestedScroll(type); } @Override public void onNestedScroll(@NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) { onNestedScrollInternal(dyUnconsumed, type, null); } @Override public void onNestedPreScroll(@NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) { dispatchNestedPreScroll(dx, dy, consumed, null, type); } // NestedScrollingParent @Override public boolean onStartNestedScroll( @NonNull View child, @NonNull View target, int nestedScrollAxes) { return onStartNestedScroll(child, target, nestedScrollAxes, ViewCompat.TYPE_TOUCH); } @Override public void onNestedScrollAccepted( @NonNull View child, @NonNull View target, int nestedScrollAxes) { onNestedScrollAccepted(child, target, nestedScrollAxes, ViewCompat.TYPE_TOUCH); } @Override public void onStopNestedScroll(@NonNull View target) { onStopNestedScroll(target, ViewCompat.TYPE_TOUCH); } @Override public void onNestedScroll(@NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { onNestedScrollInternal(dyUnconsumed, ViewCompat.TYPE_TOUCH, null); } @Override public void onNestedPreScroll(@NonNull View target, int dx, int dy, @NonNull int[] consumed) { onNestedPreScroll(target, dx, dy, consumed, ViewCompat.TYPE_TOUCH); } @Override public boolean onNestedFling( @NonNull View target, float velocityX, float velocityY, boolean consumed) { if (!consumed) { dispatchNestedFling(0, velocityY, true); fling((int) velocityY); return true; } return false; } @Override public boolean onNestedPreFling(@NonNull View target, float velocityX, float velocityY) { return dispatchNestedPreFling(velocityX, velocityY); } @Override public int getNestedScrollAxes() { return mParentHelper.getNestedScrollAxes(); } // ScrollView import @Override public boolean shouldDelayChildPressedState() { return true; } @Override protected float getTopFadingEdgeStrength() { if (getChildCount() == 0) { return 0.0f; } final int length = getVerticalFadingEdgeLength(); final int scrollY = getScrollY(); if (scrollY < length) { return scrollY / (float) length; } return 1.0f; } @Override protected float getBottomFadingEdgeStrength() { if (getChildCount() == 0) { return 0.0f; } View child = getChildAt(0); final NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int length = getVerticalFadingEdgeLength(); final int bottomEdge = getHeight() - getPaddingBottom(); final int span = child.getBottom() + lp.bottomMargin - getScrollY() - bottomEdge; if (span < length) { return span / (float) length; } return 1.0f; } /** * @return The maximum amount this scroll view will scroll in response to * an arrow event. */ public int getMaxScrollAmount() { return (int) (MAX_SCROLL_FACTOR * getHeight()); } private void initScrollView() { mScroller = new OverScroller(getContext()); setFocusable(true); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setWillNotDraw(false); final ViewConfiguration configuration = ViewConfiguration.get(getContext()); mTouchSlop = configuration.getScaledTouchSlop(); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); } @Override public void addView(View child) { if (getChildCount() > 0) { throw new IllegalStateException("ScrollView can host only one direct child"); } super.addView(child); } @Override public void addView(View child, int index) { if (getChildCount() > 0) { throw new IllegalStateException("ScrollView can host only one direct child"); } super.addView(child, index); } @Override public void addView(View child, ViewGroup.LayoutParams params) { if (getChildCount() > 0) { throw new IllegalStateException("ScrollView can host only one direct child"); } super.addView(child, params); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if (getChildCount() > 0) { throw new IllegalStateException("ScrollView can host only one direct child"); } super.addView(child, index, params); } /** * Register a callback to be invoked when the scroll X or Y positions of * this view change. * <p>This version of the method works on all versions of Android, back to API v4.</p> * * @param l The listener to notify when the scroll X or Y position changes. * @see android.view.View#getScrollX() * @see android.view.View#getScrollY() */ public void setOnScrollChangeListener(@Nullable OnScrollChangeListener l) { mOnScrollChangeListener = l; } /** * @return Returns true this ScrollView can be scrolled */ private boolean canScroll() { if (getChildCount() > 0) { View child = getChildAt(0); final NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childSize = child.getHeight() + lp.topMargin + lp.bottomMargin; int parentSpace = getHeight() - getPaddingTop() - getPaddingBottom(); return childSize > parentSpace; } return false; } /** * Indicates whether this ScrollView's content is stretched to fill the viewport. * * @return True if the content fills the viewport, false otherwise. * * @attr name android:fillViewport */ public boolean isFillViewport() { return mFillViewport; } /** * Set whether this ScrollView should stretch its content height to fill the viewport or not. * * @param fillViewport True to stretch the content's height to the viewport's * boundaries, false otherwise. * * @attr name android:fillViewport */ public void setFillViewport(boolean fillViewport) { if (fillViewport != mFillViewport) { mFillViewport = fillViewport; requestLayout(); } } /** * @return Whether arrow scrolling will animate its transition. */ public boolean isSmoothScrollingEnabled() { return mSmoothScrollingEnabled; } /** * Set whether arrow scrolling will animate its transition. * @param smoothScrollingEnabled whether arrow scrolling will animate its transition */ public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) { mSmoothScrollingEnabled = smoothScrollingEnabled; } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); if (mOnScrollChangeListener != null) { mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (!mFillViewport) { return; } final int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (heightMode == MeasureSpec.UNSPECIFIED) { return; } if (getChildCount() > 0) { View child = getChildAt(0); final NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childSize = child.getMeasuredHeight(); int parentSpace = getMeasuredHeight() - getPaddingTop() - getPaddingBottom() - lp.topMargin - lp.bottomMargin; if (childSize < parentSpace) { int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin, lp.width); int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(parentSpace, MeasureSpec.EXACTLY); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } } @Override public boolean dispatchKeyEvent(KeyEvent event) { // Let the focused view and/or our descendants get the key first return super.dispatchKeyEvent(event) || executeKeyEvent(event); } /** * You can call this function yourself to have the scroll view perform * scrolling from a key event, just as if the event had been dispatched to * it by the view hierarchy. * * @param event The key event to execute. * @return Return true if the event was handled, else false. */ public boolean executeKeyEvent(@NonNull KeyEvent event) { mTempRect.setEmpty(); if (!canScroll()) { if (isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) { View currentFocused = findFocus(); if (currentFocused == this) currentFocused = null; View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, View.FOCUS_DOWN); return nextFocused != null && nextFocused != this && nextFocused.requestFocus(View.FOCUS_DOWN); } return false; } boolean handled = false; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_UP: if (!event.isAltPressed()) { handled = arrowScroll(View.FOCUS_UP); } else { handled = fullScroll(View.FOCUS_UP); } break; case KeyEvent.KEYCODE_DPAD_DOWN: if (!event.isAltPressed()) { handled = arrowScroll(View.FOCUS_DOWN); } else { handled = fullScroll(View.FOCUS_DOWN); } break; case KeyEvent.KEYCODE_SPACE: pageScroll(event.isShiftPressed() ? View.FOCUS_UP : View.FOCUS_DOWN); break; } } return handled; } private boolean inChild(int x, int y) { if (getChildCount() > 0) { final int scrollY = getScrollY(); final View child = getChildAt(0); return !(y < child.getTop() - scrollY || y >= child.getBottom() - scrollY || x < child.getLeft() || x >= child.getRight()); } return false; } private void initOrResetVelocityTracker() { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } else { mVelocityTracker.clear(); } } private void initVelocityTrackerIfNotExists() { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } } private void recycleVelocityTracker() { if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { if (disallowIntercept) { recycleVelocityTracker(); } super.requestDisallowInterceptTouchEvent(disallowIntercept); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { /* * This method JUST determines whether we want to intercept the motion. * If we return true, onMotionEvent will be called and we do the actual * scrolling there. */ /* * Shortcut the most recurring case: the user is in the dragging * state and he is moving his finger. We want to intercept this * motion. */ final int action = ev.getAction(); if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) { return true; } switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_MOVE: { /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. */ /* * Locally do absolute value. mLastMotionY is set to the y value * of the down event. */ final int activePointerId = mActivePointerId; if (activePointerId == INVALID_POINTER) { // If we don't have a valid id, the touch down wasn't on content. break; } final int pointerIndex = ev.findPointerIndex(activePointerId); if (pointerIndex == -1) { Log.e(TAG, "Invalid pointerId=" + activePointerId + " in onInterceptTouchEvent"); break; } final int y = (int) ev.getY(pointerIndex); final int yDiff = Math.abs(y - mLastMotionY); if (yDiff > mTouchSlop && (getNestedScrollAxes() & ViewCompat.SCROLL_AXIS_VERTICAL) == 0) { mIsBeingDragged = true; mLastMotionY = y; initVelocityTrackerIfNotExists(); mVelocityTracker.addMovement(ev); mNestedYOffset = 0; final ViewParent parent = getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } } break; } case MotionEvent.ACTION_DOWN: { final int y = (int) ev.getY(); if (!inChild((int) ev.getX(), y)) { mIsBeingDragged = false; recycleVelocityTracker(); break; } /* * Remember location of down touch. * ACTION_DOWN always refers to pointer index 0. */ mLastMotionY = y; mActivePointerId = ev.getPointerId(0); initOrResetVelocityTracker(); mVelocityTracker.addMovement(ev); /* * If being flinged and user touches the screen, initiate drag; * otherwise don't. mScroller.isFinished should be false when * being flinged. We need to call computeScrollOffset() first so that * isFinished() is correct. */ mScroller.computeScrollOffset(); mIsBeingDragged = !mScroller.isFinished(); startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_TOUCH); break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: /* Release the drag */ mIsBeingDragged = false; mActivePointerId = INVALID_POINTER; recycleVelocityTracker(); if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) { ViewCompat.postInvalidateOnAnimation(this); } stopNestedScroll(ViewCompat.TYPE_TOUCH); break; case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } /* * The only time we want to intercept motion events is if we are in the * drag mode. */ return mIsBeingDragged; } @Override public boolean onTouchEvent(MotionEvent ev) { initVelocityTrackerIfNotExists(); final int actionMasked = ev.getActionMasked(); if (actionMasked == MotionEvent.ACTION_DOWN) { mNestedYOffset = 0; } MotionEvent vtev = MotionEvent.obtain(ev); vtev.offsetLocation(0, mNestedYOffset); switch (actionMasked) { case MotionEvent.ACTION_DOWN: { if (getChildCount() == 0) { return false; } if ((mIsBeingDragged = !mScroller.isFinished())) { final ViewParent parent = getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } } /* * If being flinged and user touches, stop the fling. isFinished * will be false if being flinged. */ if (!mScroller.isFinished()) { abortAnimatedScroll(); } // Remember where the motion event started mLastMotionY = (int) ev.getY(); mActivePointerId = ev.getPointerId(0); startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_TOUCH); break; } case MotionEvent.ACTION_MOVE: final int activePointerIndex = ev.findPointerIndex(mActivePointerId); if (activePointerIndex == -1) { Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent"); break; } final int y = (int) ev.getY(activePointerIndex); int deltaY = mLastMotionY - y; if (dispatchNestedPreScroll(0, deltaY, mScrollConsumed, mScrollOffset, ViewCompat.TYPE_TOUCH)) { deltaY -= mScrollConsumed[1]; mNestedYOffset += mScrollOffset[1]; } if (!mIsBeingDragged && Math.abs(deltaY) > mTouchSlop) { final ViewParent parent = getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } mIsBeingDragged = true; if (deltaY > 0) { deltaY -= mTouchSlop; } else { deltaY += mTouchSlop; } } if (mIsBeingDragged) { // Scroll to follow the motion event mLastMotionY = y - mScrollOffset[1]; final int oldY = getScrollY(); final int range = getScrollRange(); final int overscrollMode = getOverScrollMode(); boolean canOverscroll = overscrollMode == View.OVER_SCROLL_ALWAYS || (overscrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); // Calling overScrollByCompat will call onOverScrolled, which // calls onScrollChanged if applicable. if (overScrollByCompat(0, deltaY, 0, getScrollY(), 0, range, 0, 0, true) && !hasNestedScrollingParent(ViewCompat.TYPE_TOUCH)) { // Break our velocity if we hit a scroll barrier. mVelocityTracker.clear(); } final int scrolledDeltaY = getScrollY() - oldY; final int unconsumedY = deltaY - scrolledDeltaY; mScrollConsumed[1] = 0; dispatchNestedScroll(0, scrolledDeltaY, 0, unconsumedY, mScrollOffset, ViewCompat.TYPE_TOUCH, mScrollConsumed); mLastMotionY -= mScrollOffset[1]; mNestedYOffset += mScrollOffset[1]; if (canOverscroll) { deltaY -= mScrollConsumed[1]; ensureGlows(); final int pulledToY = oldY + deltaY; if (pulledToY < 0) { EdgeEffectCompat.onPull(mEdgeGlowTop, (float) deltaY / getHeight(), ev.getX(activePointerIndex) / getWidth()); if (!mEdgeGlowBottom.isFinished()) { mEdgeGlowBottom.onRelease(); } } else if (pulledToY > range) { EdgeEffectCompat.onPull(mEdgeGlowBottom, (float) deltaY / getHeight(), 1.f - ev.getX(activePointerIndex) / getWidth()); if (!mEdgeGlowTop.isFinished()) { mEdgeGlowTop.onRelease(); } } if (mEdgeGlowTop != null && (!mEdgeGlowTop.isFinished() || !mEdgeGlowBottom.isFinished())) { ViewCompat.postInvalidateOnAnimation(this); } } } break; case MotionEvent.ACTION_UP: final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId); if ((Math.abs(initialVelocity) >= mMinimumVelocity)) { if (!dispatchNestedPreFling(0, -initialVelocity)) { dispatchNestedFling(0, -initialVelocity, true); fling(-initialVelocity); } } else if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) { ViewCompat.postInvalidateOnAnimation(this); } mActivePointerId = INVALID_POINTER; endDrag(); break; case MotionEvent.ACTION_CANCEL: if (mIsBeingDragged && getChildCount() > 0) { if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) { ViewCompat.postInvalidateOnAnimation(this); } } mActivePointerId = INVALID_POINTER; endDrag(); break; case MotionEvent.ACTION_POINTER_DOWN: { final int index = ev.getActionIndex(); mLastMotionY = (int) ev.getY(index); mActivePointerId = ev.getPointerId(index); break; } case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); mLastMotionY = (int) ev.getY(ev.findPointerIndex(mActivePointerId)); break; } if (mVelocityTracker != null) { mVelocityTracker.addMovement(vtev); } vtev.recycle(); return true; } private void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = ev.getActionIndex(); final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. // TODO: Make this decision more intelligent. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastMotionY = (int) ev.getY(newPointerIndex); mActivePointerId = ev.getPointerId(newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } @Override public boolean onGenericMotionEvent(MotionEvent event) { if ((event.getSource() & InputDeviceCompat.SOURCE_CLASS_POINTER) != 0) { switch (event.getAction()) { case MotionEvent.ACTION_SCROLL: { if (!mIsBeingDragged) { final float vscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL); if (vscroll != 0) { final int delta = (int) (vscroll * getVerticalScrollFactorCompat()); final int range = getScrollRange(); int oldScrollY = getScrollY(); int newScrollY = oldScrollY - delta; if (newScrollY < 0) { newScrollY = 0; } else if (newScrollY > range) { newScrollY = range; } if (newScrollY != oldScrollY) { super.scrollTo(getScrollX(), newScrollY); return true; } } } } } } return false; } private float getVerticalScrollFactorCompat() { if (mVerticalScrollFactor == 0) { TypedValue outValue = new TypedValue(); final Context context = getContext(); if (!context.getTheme().resolveAttribute( android.R.attr.listPreferredItemHeight, outValue, true)) { throw new IllegalStateException( "Expected theme to define listPreferredItemHeight."); } mVerticalScrollFactor = outValue.getDimension( context.getResources().getDisplayMetrics()); } return mVerticalScrollFactor; } @Override protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { super.scrollTo(scrollX, scrollY); } boolean overScrollByCompat(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) { final int overScrollMode = getOverScrollMode(); final boolean canScrollHorizontal = computeHorizontalScrollRange() > computeHorizontalScrollExtent(); final boolean canScrollVertical = computeVerticalScrollRange() > computeVerticalScrollExtent(); final boolean overScrollHorizontal = overScrollMode == View.OVER_SCROLL_ALWAYS || (overScrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); final boolean overScrollVertical = overScrollMode == View.OVER_SCROLL_ALWAYS || (overScrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); int newScrollX = scrollX + deltaX; if (!overScrollHorizontal) { maxOverScrollX = 0; } int newScrollY = scrollY + deltaY; if (!overScrollVertical) { maxOverScrollY = 0; } // Clamp values if at the limits and record final int left = -maxOverScrollX; final int right = maxOverScrollX + scrollRangeX; final int top = -maxOverScrollY; final int bottom = maxOverScrollY + scrollRangeY; boolean clampedX = false; if (newScrollX > right) { newScrollX = right; clampedX = true; } else if (newScrollX < left) { newScrollX = left; clampedX = true; } boolean clampedY = false; if (newScrollY > bottom) { newScrollY = bottom; clampedY = true; } else if (newScrollY < top) { newScrollY = top; clampedY = true; } if (clampedY && !hasNestedScrollingParent(ViewCompat.TYPE_NON_TOUCH)) { mScroller.springBack(newScrollX, newScrollY, 0, 0, 0, getScrollRange()); } onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); return clampedX || clampedY; } int getScrollRange() { int scrollRange = 0; if (getChildCount() > 0) { View child = getChildAt(0); NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childSize = child.getHeight() + lp.topMargin + lp.bottomMargin; int parentSpace = getHeight() - getPaddingTop() - getPaddingBottom(); scrollRange = Math.max(0, childSize - parentSpace); } return scrollRange; } /** * <p> * Finds the next focusable component that fits in the specified bounds. * </p> * * @param topFocus look for a candidate is the one at the top of the bounds * if topFocus is true, or at the bottom of the bounds if topFocus is * false * @param top the top offset of the bounds in which a focusable must be * found * @param bottom the bottom offset of the bounds in which a focusable must * be found * @return the next focusable component in the bounds or null if none can * be found */ private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) { List<View> focusables = getFocusables(View.FOCUS_FORWARD); View focusCandidate = null; /* * A fully contained focusable is one where its top is below the bound's * top, and its bottom is above the bound's bottom. A partially * contained focusable is one where some part of it is within the * bounds, but it also has some part that is not within bounds. A fully contained * focusable is preferred to a partially contained focusable. */ boolean foundFullyContainedFocusable = false; int count = focusables.size(); for (int i = 0; i < count; i++) { View view = focusables.get(i); int viewTop = view.getTop(); int viewBottom = view.getBottom(); if (top < viewBottom && viewTop < bottom) { /* * the focusable is in the target area, it is a candidate for * focusing */ final boolean viewIsFullyContained = (top < viewTop) && (viewBottom < bottom); if (focusCandidate == null) { /* No candidate, take this one */ focusCandidate = view; foundFullyContainedFocusable = viewIsFullyContained; } else { final boolean viewIsCloserToBoundary = (topFocus && viewTop < focusCandidate.getTop()) || (!topFocus && viewBottom > focusCandidate.getBottom()); if (foundFullyContainedFocusable) { if (viewIsFullyContained && viewIsCloserToBoundary) { /* * We're dealing with only fully contained views, so * it has to be closer to the boundary to beat our * candidate */ focusCandidate = view; } } else { if (viewIsFullyContained) { /* Any fully contained view beats a partially contained view */ focusCandidate = view; foundFullyContainedFocusable = true; } else if (viewIsCloserToBoundary) { /* * Partially contained view beats another partially * contained view if it's closer */ focusCandidate = view; } } } } } return focusCandidate; } /** * <p>Handles scrolling in response to a "page up/down" shortcut press. This * method will scroll the view by one page up or down and give the focus * to the topmost/bottommost component in the new visible area. If no * component is a good candidate for focus, this scrollview reclaims the * focus.</p> * * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} * to go one page up or * {@link android.view.View#FOCUS_DOWN} to go one page down * @return true if the key event is consumed by this method, false otherwise */ public boolean pageScroll(int direction) { boolean down = direction == View.FOCUS_DOWN; int height = getHeight(); if (down) { mTempRect.top = getScrollY() + height; int count = getChildCount(); if (count > 0) { View view = getChildAt(count - 1); NestedScrollView.LayoutParams lp = (LayoutParams) view.getLayoutParams(); int bottom = view.getBottom() + lp.bottomMargin + getPaddingBottom(); if (mTempRect.top + height > bottom) { mTempRect.top = bottom - height; } } } else { mTempRect.top = getScrollY() - height; if (mTempRect.top < 0) { mTempRect.top = 0; } } mTempRect.bottom = mTempRect.top + height; return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); } /** * <p>Handles scrolling in response to a "home/end" shortcut press. This * method will scroll the view to the top or bottom and give the focus * to the topmost/bottommost component in the new visible area. If no * component is a good candidate for focus, this scrollview reclaims the * focus.</p> * * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} * to go the top of the view or * {@link android.view.View#FOCUS_DOWN} to go the bottom * @return true if the key event is consumed by this method, false otherwise */ public boolean fullScroll(int direction) { boolean down = direction == View.FOCUS_DOWN; int height = getHeight(); mTempRect.top = 0; mTempRect.bottom = height; if (down) { int count = getChildCount(); if (count > 0) { View view = getChildAt(count - 1); NestedScrollView.LayoutParams lp = (LayoutParams) view.getLayoutParams(); mTempRect.bottom = view.getBottom() + lp.bottomMargin + getPaddingBottom(); mTempRect.top = mTempRect.bottom - height; } } return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); } /** * <p>Scrolls the view to make the area defined by <code>top</code> and * <code>bottom</code> visible. This method attempts to give the focus * to a component visible in this area. If no component can be focused in * the new visible area, the focus is reclaimed by this ScrollView.</p> * * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} * to go upward, {@link android.view.View#FOCUS_DOWN} to downward * @param top the top offset of the new area to be made visible * @param bottom the bottom offset of the new area to be made visible * @return true if the key event is consumed by this method, false otherwise */ private boolean scrollAndFocus(int direction, int top, int bottom) { boolean handled = true; int height = getHeight(); int containerTop = getScrollY(); int containerBottom = containerTop + height; boolean up = direction == View.FOCUS_UP; View newFocused = findFocusableViewInBounds(up, top, bottom); if (newFocused == null) { newFocused = this; } if (top >= containerTop && bottom <= containerBottom) { handled = false; } else { int delta = up ? (top - containerTop) : (bottom - containerBottom); doScrollY(delta); } if (newFocused != findFocus()) newFocused.requestFocus(direction); return handled; } /** * Handle scrolling in response to an up or down arrow click. * * @param direction The direction corresponding to the arrow key that was * pressed * @return True if we consumed the event, false otherwise */ public boolean arrowScroll(int direction) { View currentFocused = findFocus(); if (currentFocused == this) currentFocused = null; View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); final int maxJump = getMaxScrollAmount(); if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) { nextFocused.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(nextFocused, mTempRect); int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); doScrollY(scrollDelta); nextFocused.requestFocus(direction); } else { // no new focus int scrollDelta = maxJump; if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) { scrollDelta = getScrollY(); } else if (direction == View.FOCUS_DOWN) { if (getChildCount() > 0) { View child = getChildAt(0); NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); int daBottom = child.getBottom() + lp.bottomMargin; int screenBottom = getScrollY() + getHeight() - getPaddingBottom(); scrollDelta = Math.min(daBottom - screenBottom, maxJump); } } if (scrollDelta == 0) { return false; } doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta); } if (currentFocused != null && currentFocused.isFocused() && isOffScreen(currentFocused)) { // previously focused item still has focus and is off screen, give // it up (take it back to ourselves) // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are // sure to // get it) final int descendantFocusability = getDescendantFocusability(); // save setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); requestFocus(); setDescendantFocusability(descendantFocusability); // restore } return true; } /** * @return whether the descendant of this scroll view is scrolled off * screen. */ private boolean isOffScreen(View descendant) { return !isWithinDeltaOfScreen(descendant, 0, getHeight()); } /** * @return whether the descendant of this scroll view is within delta * pixels of being on the screen. */ private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) { descendant.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(descendant, mTempRect); return (mTempRect.bottom + delta) >= getScrollY() && (mTempRect.top - delta) <= (getScrollY() + height); } /** * Smooth scroll by a Y delta * * @param delta the number of pixels to scroll by on the Y axis */ private void doScrollY(int delta) { if (delta != 0) { if (mSmoothScrollingEnabled) { smoothScrollBy(0, delta); } else { scrollBy(0, delta); } } } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param dx the number of pixels to scroll by on the X axis * @param dy the number of pixels to scroll by on the Y axis */ public final void smoothScrollBy(int dx, int dy) { smoothScrollBy(dx, dy, false); } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param dx the number of pixels to scroll by on the X axis * @param dy the number of pixels to scroll by on the Y axis * @param withNestedScrolling whether to include nested scrolling operations. */ private void smoothScrollBy(int dx, int dy, boolean withNestedScrolling) { if (getChildCount() == 0) { // Nothing to do. return; } long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; if (duration > ANIMATED_SCROLL_GAP) { View child = getChildAt(0); NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childSize = child.getHeight() + lp.topMargin + lp.bottomMargin; int parentSpace = getHeight() - getPaddingTop() - getPaddingBottom(); final int scrollY = getScrollY(); final int maxY = Math.max(0, childSize - parentSpace); dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY; mScroller.startScroll(getScrollX(), scrollY, 0, dy); runAnimatedScroll(withNestedScrolling); } else { if (!mScroller.isFinished()) { abortAnimatedScroll(); } scrollBy(dx, dy); } mLastScroll = AnimationUtils.currentAnimationTimeMillis(); } /** * Like {@link #scrollTo}, but scroll smoothly instead of immediately. * * @param x the position where to scroll on the X axis * @param y the position where to scroll on the Y axis */ public final void smoothScrollTo(int x, int y) { smoothScrollTo(x, y, false); } /** * Like {@link #scrollTo}, but scroll smoothly instead of immediately. * * @param x the position where to scroll on the X axis * @param y the position where to scroll on the Y axis * @param withNestedScrolling whether to include nested scrolling operations. */ // This should be considered private, it is package private to avoid a synthetic ancestor. void smoothScrollTo(int x, int y, boolean withNestedScrolling) { smoothScrollBy(x - getScrollX(), y - getScrollY(), withNestedScrolling); } /** * <p>The scroll range of a scroll view is the overall height of all of its * children.</p> * @hide */ @RestrictTo(LIBRARY_GROUP_PREFIX) @Override public int computeVerticalScrollRange() { final int count = getChildCount(); final int parentSpace = getHeight() - getPaddingBottom() - getPaddingTop(); if (count == 0) { return parentSpace; } View child = getChildAt(0); NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); int scrollRange = child.getBottom() + lp.bottomMargin; final int scrollY = getScrollY(); final int overscrollBottom = Math.max(0, scrollRange - parentSpace); if (scrollY < 0) { scrollRange -= scrollY; } else if (scrollY > overscrollBottom) { scrollRange += scrollY - overscrollBottom; } return scrollRange; } /** @hide */ @RestrictTo(LIBRARY_GROUP_PREFIX) @Override public int computeVerticalScrollOffset() { return Math.max(0, super.computeVerticalScrollOffset()); } /** @hide */ @RestrictTo(LIBRARY_GROUP_PREFIX) @Override public int computeVerticalScrollExtent() { return super.computeVerticalScrollExtent(); } /** @hide */ @RestrictTo(LIBRARY_GROUP_PREFIX) @Override public int computeHorizontalScrollRange() { return super.computeHorizontalScrollRange(); } /** @hide */ @RestrictTo(LIBRARY_GROUP_PREFIX) @Override public int computeHorizontalScrollOffset() { return super.computeHorizontalScrollOffset(); } /** @hide */ @RestrictTo(LIBRARY_GROUP_PREFIX) @Override public int computeHorizontalScrollExtent() { return super.computeHorizontalScrollExtent(); } @Override protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { ViewGroup.LayoutParams lp = child.getLayoutParams(); int childWidthMeasureSpec; int childHeightMeasureSpec; childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, getPaddingLeft() + getPaddingRight(), lp.width); childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } @Override protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) { final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin + widthUsed, lp.width); final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } @Override public void computeScroll() { if (mScroller.isFinished()) { return; } mScroller.computeScrollOffset(); final int y = mScroller.getCurrY(); int unconsumed = y - mLastScrollerY; mLastScrollerY = y; // Nested Scrolling Pre Pass mScrollConsumed[1] = 0; dispatchNestedPreScroll(0, unconsumed, mScrollConsumed, null, ViewCompat.TYPE_NON_TOUCH); unconsumed -= mScrollConsumed[1]; final int range = getScrollRange(); if (unconsumed != 0) { // Internal Scroll final int oldScrollY = getScrollY(); overScrollByCompat(0, unconsumed, getScrollX(), oldScrollY, 0, range, 0, 0, false); final int scrolledByMe = getScrollY() - oldScrollY; unconsumed -= scrolledByMe; // Nested Scrolling Post Pass mScrollConsumed[1] = 0; dispatchNestedScroll(0, scrolledByMe, 0, unconsumed, mScrollOffset, ViewCompat.TYPE_NON_TOUCH, mScrollConsumed); unconsumed -= mScrollConsumed[1]; } if (unconsumed != 0) { final int mode = getOverScrollMode(); final boolean canOverscroll = mode == OVER_SCROLL_ALWAYS || (mode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); if (canOverscroll) { ensureGlows(); if (unconsumed < 0) { if (mEdgeGlowTop.isFinished()) { mEdgeGlowTop.onAbsorb((int) mScroller.getCurrVelocity()); } } else { if (mEdgeGlowBottom.isFinished()) { mEdgeGlowBottom.onAbsorb((int) mScroller.getCurrVelocity()); } } } abortAnimatedScroll(); } if (!mScroller.isFinished()) { ViewCompat.postInvalidateOnAnimation(this); } else { stopNestedScroll(ViewCompat.TYPE_NON_TOUCH); } } private void runAnimatedScroll(boolean participateInNestedScrolling) { if (participateInNestedScrolling) { startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_NON_TOUCH); } else { stopNestedScroll(ViewCompat.TYPE_NON_TOUCH); } mLastScrollerY = getScrollY(); ViewCompat.postInvalidateOnAnimation(this); } private void abortAnimatedScroll() { mScroller.abortAnimation(); stopNestedScroll(ViewCompat.TYPE_NON_TOUCH); } /** * Scrolls the view to the given child. * * @param child the View to scroll to */ private void scrollToChild(View child) { child.getDrawingRect(mTempRect); /* Offset from child's local coordinates to ScrollView coordinates */ offsetDescendantRectToMyCoords(child, mTempRect); int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); if (scrollDelta != 0) { scrollBy(0, scrollDelta); } } /** * If rect is off screen, scroll just enough to get it (or at least the * first screen size chunk of it) on screen. * * @param rect The rectangle. * @param immediate True to scroll immediately without animation * @return true if scrolling was performed */ private boolean scrollToChildRect(Rect rect, boolean immediate) { final int delta = computeScrollDeltaToGetChildRectOnScreen(rect); final boolean scroll = delta != 0; if (scroll) { if (immediate) { scrollBy(0, delta); } else { smoothScrollBy(0, delta); } } return scroll; } /** * Compute the amount to scroll in the Y direction in order to get * a rectangle completely on the screen (or, if taller than the screen, * at least the first screen size chunk of it). * * @param rect The rect. * @return The scroll delta. */ protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { if (getChildCount() == 0) return 0; int height = getHeight(); int screenTop = getScrollY(); int screenBottom = screenTop + height; int actualScreenBottom = screenBottom; int fadingEdge = getVerticalFadingEdgeLength(); // TODO: screenTop should be incremented by fadingEdge * getTopFadingEdgeStrength (but for // the target scroll distance). // leave room for top fading edge as long as rect isn't at very top if (rect.top > 0) { screenTop += fadingEdge; } // TODO: screenBottom should be decremented by fadingEdge * getBottomFadingEdgeStrength (but // for the target scroll distance). // leave room for bottom fading edge as long as rect isn't at very bottom View child = getChildAt(0); final NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (rect.bottom < child.getHeight() + lp.topMargin + lp.bottomMargin) { screenBottom -= fadingEdge; } int scrollYDelta = 0; if (rect.bottom > screenBottom && rect.top > screenTop) { // need to move down to get it in view: move down just enough so // that the entire rectangle is in view (or at least the first // screen size chunk). if (rect.height() > height) { // just enough to get screen size chunk on scrollYDelta += (rect.top - screenTop); } else { // get entire rect at bottom of screen scrollYDelta += (rect.bottom - screenBottom); } // make sure we aren't scrolling beyond the end of our content int bottom = child.getBottom() + lp.bottomMargin; int distanceToBottom = bottom - actualScreenBottom; scrollYDelta = Math.min(scrollYDelta, distanceToBottom); } else if (rect.top < screenTop && rect.bottom < screenBottom) { // need to move up to get it in view: move up just enough so that // entire rectangle is in view (or at least the first screen // size chunk of it). if (rect.height() > height) { // screen size chunk scrollYDelta -= (screenBottom - rect.bottom); } else { // entire rect at top scrollYDelta -= (screenTop - rect.top); } // make sure we aren't scrolling any further than the top our content scrollYDelta = Math.max(scrollYDelta, -getScrollY()); } return scrollYDelta; } @Override public void requestChildFocus(View child, View focused) { if (!mIsLayoutDirty) { scrollToChild(focused); } else { // The child may not be laid out yet, we can't compute the scroll yet mChildToScrollTo = focused; } super.requestChildFocus(child, focused); } /** * When looking for focus in children of a scroll view, need to be a little * more careful not to give focus to something that is scrolled off screen. * * This is more expensive than the default {@link android.view.ViewGroup} * implementation, otherwise this behavior might have been made the default. */ @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { // convert from forward / backward notation to up / down / left / right // (ugh). if (direction == View.FOCUS_FORWARD) { direction = View.FOCUS_DOWN; } else if (direction == View.FOCUS_BACKWARD) { direction = View.FOCUS_UP; } final View nextFocus = previouslyFocusedRect == null ? FocusFinder.getInstance().findNextFocus(this, null, direction) : FocusFinder.getInstance().findNextFocusFromRect( this, previouslyFocusedRect, direction); if (nextFocus == null) { return false; } if (isOffScreen(nextFocus)) { return false; } return nextFocus.requestFocus(direction, previouslyFocusedRect); } @Override public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { // offset into coordinate space of this scroll view rectangle.offset(child.getLeft() - child.getScrollX(), child.getTop() - child.getScrollY()); return scrollToChildRect(rectangle, immediate); } @Override public void requestLayout() { mIsLayoutDirty = true; super.requestLayout(); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); mIsLayoutDirty = false; // Give a child focus if it needs it if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { scrollToChild(mChildToScrollTo); } mChildToScrollTo = null; if (!mIsLaidOut) { // If there is a saved state, scroll to the position saved in that state. if (mSavedState != null) { scrollTo(getScrollX(), mSavedState.scrollPosition); mSavedState = null; } // mScrollY default value is "0" // Make sure current scrollY position falls into the scroll range. If it doesn't, // scroll such that it does. int childSize = 0; if (getChildCount() > 0) { View child = getChildAt(0); NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); childSize = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin; } int parentSpace = b - t - getPaddingTop() - getPaddingBottom(); int currentScrollY = getScrollY(); int newScrollY = clamp(currentScrollY, parentSpace, childSize); if (newScrollY != currentScrollY) { scrollTo(getScrollX(), newScrollY); } } // Calling this with the present values causes it to re-claim them scrollTo(getScrollX(), getScrollY()); mIsLaidOut = true; } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); mIsLaidOut = false; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); View currentFocused = findFocus(); if (null == currentFocused || this == currentFocused) { return; } // If the currently-focused view was visible on the screen when the // screen was at the old height, then scroll the screen to make that // view visible with the new screen height. if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) { currentFocused.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(currentFocused, mTempRect); int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); doScrollY(scrollDelta); } } /** * Return true if child is a descendant of parent, (or equal to the parent). */ private static boolean isViewDescendantOf(View child, View parent) { if (child == parent) { return true; } final ViewParent theParent = child.getParent(); return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); } /** * Fling the scroll view * * @param velocityY The initial velocity in the Y direction. Positive * numbers mean that the finger/cursor is moving down the screen, * which means we want to scroll towards the top. */ public void fling(int velocityY) { if (getChildCount() > 0) { mScroller.fling(getScrollX(), getScrollY(), // start 0, velocityY, // velocities 0, 0, // x Integer.MIN_VALUE, Integer.MAX_VALUE, // y 0, 0); // overscroll runAnimatedScroll(true); } } private void endDrag() { mIsBeingDragged = false; recycleVelocityTracker(); stopNestedScroll(ViewCompat.TYPE_TOUCH); if (mEdgeGlowTop != null) { mEdgeGlowTop.onRelease(); mEdgeGlowBottom.onRelease(); } } /** * {@inheritDoc} * * <p>This version also clamps the scrolling to the bounds of our child. */ @Override public void scrollTo(int x, int y) { // we rely on the fact the View.scrollBy calls scrollTo. if (getChildCount() > 0) { View child = getChildAt(0); final NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); int parentSpaceHorizontal = getWidth() - getPaddingLeft() - getPaddingRight(); int childSizeHorizontal = child.getWidth() + lp.leftMargin + lp.rightMargin; int parentSpaceVertical = getHeight() - getPaddingTop() - getPaddingBottom(); int childSizeVertical = child.getHeight() + lp.topMargin + lp.bottomMargin; x = clamp(x, parentSpaceHorizontal, childSizeHorizontal); y = clamp(y, parentSpaceVertical, childSizeVertical); if (x != getScrollX() || y != getScrollY()) { super.scrollTo(x, y); } } } private void ensureGlows() { if (getOverScrollMode() != View.OVER_SCROLL_NEVER) { if (mEdgeGlowTop == null) { Context context = getContext(); mEdgeGlowTop = new EdgeEffect(context); mEdgeGlowBottom = new EdgeEffect(context); } } else { mEdgeGlowTop = null; mEdgeGlowBottom = null; } } @Override public void draw(Canvas canvas) { super.draw(canvas); if (mEdgeGlowTop != null) { final int scrollY = getScrollY(); if (!mEdgeGlowTop.isFinished()) { final int restoreCount = canvas.save(); int width = getWidth(); int height = getHeight(); int xTranslation = 0; int yTranslation = Math.min(0, scrollY); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || getClipToPadding()) { width -= getPaddingLeft() + getPaddingRight(); xTranslation += getPaddingLeft(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && getClipToPadding()) { height -= getPaddingTop() + getPaddingBottom(); yTranslation += getPaddingTop(); } canvas.translate(xTranslation, yTranslation); mEdgeGlowTop.setSize(width, height); if (mEdgeGlowTop.draw(canvas)) { ViewCompat.postInvalidateOnAnimation(this); } canvas.restoreToCount(restoreCount); } if (!mEdgeGlowBottom.isFinished()) { final int restoreCount = canvas.save(); int width = getWidth(); int height = getHeight(); int xTranslation = 0; int yTranslation = Math.max(getScrollRange(), scrollY) + height; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || getClipToPadding()) { width -= getPaddingLeft() + getPaddingRight(); xTranslation += getPaddingLeft(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && getClipToPadding()) { height -= getPaddingTop() + getPaddingBottom(); yTranslation -= getPaddingBottom(); } canvas.translate(xTranslation - width, yTranslation); canvas.rotate(180, width, 0); mEdgeGlowBottom.setSize(width, height); if (mEdgeGlowBottom.draw(canvas)) { ViewCompat.postInvalidateOnAnimation(this); } canvas.restoreToCount(restoreCount); } } } private static int clamp(int n, int my, int child) { if (my >= child || n < 0) { /* my >= child is this case: * |--------------- me ---------------| * |------ child ------| * or * |--------------- me ---------------| * |------ child ------| * or * |--------------- me ---------------| * |------ child ------| * * n < 0 is this case: * |------ me ------| * |-------- child --------| * |-- mScrollX --| */ return 0; } if ((my + n) > child) { /* this case: * |------ me ------| * |------ child ------| * |-- mScrollX --| */ return child - my; } return n; } @Override protected void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); mSavedState = ss; requestLayout(); } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.scrollPosition = getScrollY(); return ss; } static class SavedState extends BaseSavedState { public int scrollPosition; SavedState(Parcelable superState) { super(superState); } SavedState(Parcel source) { super(source); scrollPosition = source.readInt(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(scrollPosition); } @NonNull @Override public String toString() { return "HorizontalScrollView.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " scrollPosition=" + scrollPosition + "}"; } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } static class AccessibilityDelegate extends AccessibilityDelegateCompat { @Override public boolean performAccessibilityAction(View host, int action, Bundle arguments) { if (super.performAccessibilityAction(host, action, arguments)) { return true; } final NestedScrollView nsvHost = (NestedScrollView) host; if (!nsvHost.isEnabled()) { return false; } switch (action) { case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: case android.R.id.accessibilityActionScrollDown: { final int viewportHeight = nsvHost.getHeight() - nsvHost.getPaddingBottom() - nsvHost.getPaddingTop(); final int targetScrollY = Math.min(nsvHost.getScrollY() + viewportHeight, nsvHost.getScrollRange()); if (targetScrollY != nsvHost.getScrollY()) { nsvHost.smoothScrollTo(0, targetScrollY, true); return true; } } return false; case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: case android.R.id.accessibilityActionScrollUp: { final int viewportHeight = nsvHost.getHeight() - nsvHost.getPaddingBottom() - nsvHost.getPaddingTop(); final int targetScrollY = Math.max(nsvHost.getScrollY() - viewportHeight, 0); if (targetScrollY != nsvHost.getScrollY()) { nsvHost.smoothScrollTo(0, targetScrollY, true); return true; } } return false; } return false; } @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { super.onInitializeAccessibilityNodeInfo(host, info); final NestedScrollView nsvHost = (NestedScrollView) host; info.setClassName(ScrollView.class.getName()); if (nsvHost.isEnabled()) { final int scrollRange = nsvHost.getScrollRange(); if (scrollRange > 0) { info.setScrollable(true); if (nsvHost.getScrollY() > 0) { info.addAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat .ACTION_SCROLL_BACKWARD); info.addAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat .ACTION_SCROLL_UP); } if (nsvHost.getScrollY() < scrollRange) { info.addAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat .ACTION_SCROLL_FORWARD); info.addAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat .ACTION_SCROLL_DOWN); } } } } @Override public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { super.onInitializeAccessibilityEvent(host, event); final NestedScrollView nsvHost = (NestedScrollView) host; event.setClassName(ScrollView.class.getName()); final boolean scrollable = nsvHost.getScrollRange() > 0; event.setScrollable(scrollable); event.setScrollX(nsvHost.getScrollX()); event.setScrollY(nsvHost.getScrollY()); AccessibilityRecordCompat.setMaxScrollX(event, nsvHost.getScrollX()); AccessibilityRecordCompat.setMaxScrollY(event, nsvHost.getScrollRange()); } } }
core/core/src/main/java/androidx/core/widget/NestedScrollView.java
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.widget; import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP_PREFIX; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Build; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.FocusFinder; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import android.view.animation.AnimationUtils; import android.widget.EdgeEffect; import android.widget.FrameLayout; import android.widget.OverScroller; import android.widget.ScrollView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.core.view.AccessibilityDelegateCompat; import androidx.core.view.InputDeviceCompat; import androidx.core.view.NestedScrollingChild3; import androidx.core.view.NestedScrollingChildHelper; import androidx.core.view.NestedScrollingParent3; import androidx.core.view.NestedScrollingParentHelper; import androidx.core.view.ScrollingView; import androidx.core.view.ViewCompat; import androidx.core.view.accessibility.AccessibilityNodeInfoCompat; import androidx.core.view.accessibility.AccessibilityRecordCompat; import java.util.List; /** * NestedScrollView is just like {@link android.widget.ScrollView}, but it supports acting * as both a nested scrolling parent and child on both new and old versions of Android. * Nested scrolling is enabled by default. */ public class NestedScrollView extends FrameLayout implements NestedScrollingParent3, NestedScrollingChild3, ScrollingView { static final int ANIMATED_SCROLL_GAP = 250; static final float MAX_SCROLL_FACTOR = 0.5f; private static final String TAG = "NestedScrollView"; /** * Interface definition for a callback to be invoked when the scroll * X or Y positions of a view change. * * <p>This version of the interface works on all versions of Android, back to API v4.</p> * * @see #setOnScrollChangeListener(OnScrollChangeListener) */ public interface OnScrollChangeListener { /** * Called when the scroll position of a view changes. * * @param v The view whose scroll position has changed. * @param scrollX Current horizontal scroll origin. * @param scrollY Current vertical scroll origin. * @param oldScrollX Previous horizontal scroll origin. * @param oldScrollY Previous vertical scroll origin. */ void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); } private long mLastScroll; private final Rect mTempRect = new Rect(); private OverScroller mScroller; private EdgeEffect mEdgeGlowTop; private EdgeEffect mEdgeGlowBottom; /** * Position of the last motion event. */ private int mLastMotionY; /** * True when the layout has changed but the traversal has not come through yet. * Ideally the view hierarchy would keep track of this for us. */ private boolean mIsLayoutDirty = true; private boolean mIsLaidOut = false; /** * The child to give focus to in the event that a child has requested focus while the * layout is dirty. This prevents the scroll from being wrong if the child has not been * laid out before requesting focus. */ private View mChildToScrollTo = null; /** * True if the user is currently dragging this ScrollView around. This is * not the same as 'is being flinged', which can be checked by * mScroller.isFinished() (flinging begins when the user lifts his finger). */ private boolean mIsBeingDragged = false; /** * Determines speed during touch scrolling */ private VelocityTracker mVelocityTracker; /** * When set to true, the scroll view measure its child to make it fill the currently * visible area. */ private boolean mFillViewport; /** * Whether arrow scrolling is animated. */ private boolean mSmoothScrollingEnabled = true; private int mTouchSlop; private int mMinimumVelocity; private int mMaximumVelocity; /** * ID of the active pointer. This is used to retain consistency during * drags/flings if multiple pointers are used. */ private int mActivePointerId = INVALID_POINTER; /** * Used during scrolling to retrieve the new offset within the window. */ private final int[] mScrollOffset = new int[2]; private final int[] mScrollConsumed = new int[2]; private int mNestedYOffset; private int mLastScrollerY; /** * Sentinel value for no current active pointer. * Used by {@link #mActivePointerId}. */ private static final int INVALID_POINTER = -1; private SavedState mSavedState; private static final AccessibilityDelegate ACCESSIBILITY_DELEGATE = new AccessibilityDelegate(); private static final int[] SCROLLVIEW_STYLEABLE = new int[] { android.R.attr.fillViewport }; private final NestedScrollingParentHelper mParentHelper; private final NestedScrollingChildHelper mChildHelper; private float mVerticalScrollFactor; private OnScrollChangeListener mOnScrollChangeListener; public NestedScrollView(@NonNull Context context) { this(context, null); } public NestedScrollView(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public NestedScrollView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initScrollView(); final TypedArray a = context.obtainStyledAttributes( attrs, SCROLLVIEW_STYLEABLE, defStyleAttr, 0); setFillViewport(a.getBoolean(0, false)); a.recycle(); mParentHelper = new NestedScrollingParentHelper(this); mChildHelper = new NestedScrollingChildHelper(this); // ...because why else would you be using this widget? setNestedScrollingEnabled(true); ViewCompat.setAccessibilityDelegate(this, ACCESSIBILITY_DELEGATE); } // NestedScrollingChild3 @Override public void dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, @Nullable int[] offsetInWindow, int type, @NonNull int[] consumed) { mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow, type, consumed); } // NestedScrollingChild2 @Override public boolean startNestedScroll(int axes, int type) { return mChildHelper.startNestedScroll(axes, type); } @Override public void stopNestedScroll(int type) { mChildHelper.stopNestedScroll(type); } @Override public boolean hasNestedScrollingParent(int type) { return mChildHelper.hasNestedScrollingParent(type); } @Override public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow, int type) { return mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow, type); } @Override public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow, int type) { return mChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow, type); } // NestedScrollingChild @Override public void setNestedScrollingEnabled(boolean enabled) { mChildHelper.setNestedScrollingEnabled(enabled); } @Override public boolean isNestedScrollingEnabled() { return mChildHelper.isNestedScrollingEnabled(); } @Override public boolean startNestedScroll(int axes) { return startNestedScroll(axes, ViewCompat.TYPE_TOUCH); } @Override public void stopNestedScroll() { stopNestedScroll(ViewCompat.TYPE_TOUCH); } @Override public boolean hasNestedScrollingParent() { return hasNestedScrollingParent(ViewCompat.TYPE_TOUCH); } @Override public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { return mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow); } @Override public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { return dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow, ViewCompat.TYPE_TOUCH); } @Override public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { return mChildHelper.dispatchNestedFling(velocityX, velocityY, consumed); } @Override public boolean dispatchNestedPreFling(float velocityX, float velocityY) { return mChildHelper.dispatchNestedPreFling(velocityX, velocityY); } // NestedScrollingParent3 @Override public void onNestedScroll(@NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type, @NonNull int[] consumed) { onNestedScrollInternal(dyUnconsumed, type, consumed); } private void onNestedScrollInternal(int dyUnconsumed, int type, @Nullable int[] consumed) { final int oldScrollY = getScrollY(); scrollBy(0, dyUnconsumed); final int myConsumed = getScrollY() - oldScrollY; if (consumed != null) { consumed[1] += myConsumed; } final int myUnconsumed = dyUnconsumed - myConsumed; mChildHelper.dispatchNestedScroll(0, myConsumed, 0, myUnconsumed, null, type, consumed); } // NestedScrollingParent2 @Override public boolean onStartNestedScroll(@NonNull View child, @NonNull View target, int axes, int type) { return (axes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0; } @Override public void onNestedScrollAccepted(@NonNull View child, @NonNull View target, int axes, int type) { mParentHelper.onNestedScrollAccepted(child, target, axes, type); startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL, type); } @Override public void onStopNestedScroll(@NonNull View target, int type) { mParentHelper.onStopNestedScroll(target, type); stopNestedScroll(type); } @Override public void onNestedScroll(@NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) { onNestedScrollInternal(dyUnconsumed, type, null); } @Override public void onNestedPreScroll(@NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) { dispatchNestedPreScroll(dx, dy, consumed, null, type); } // NestedScrollingParent @Override public boolean onStartNestedScroll( @NonNull View child, @NonNull View target, int nestedScrollAxes) { return onStartNestedScroll(child, target, nestedScrollAxes, ViewCompat.TYPE_TOUCH); } @Override public void onNestedScrollAccepted( @NonNull View child, @NonNull View target, int nestedScrollAxes) { onNestedScrollAccepted(child, target, nestedScrollAxes, ViewCompat.TYPE_TOUCH); } @Override public void onStopNestedScroll(@NonNull View target) { onStopNestedScroll(target, ViewCompat.TYPE_TOUCH); } @Override public void onNestedScroll(@NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { onNestedScrollInternal(dyUnconsumed, ViewCompat.TYPE_TOUCH, null); } @Override public void onNestedPreScroll(@NonNull View target, int dx, int dy, @NonNull int[] consumed) { onNestedPreScroll(target, dx, dy, consumed, ViewCompat.TYPE_TOUCH); } @Override public boolean onNestedFling( @NonNull View target, float velocityX, float velocityY, boolean consumed) { if (!consumed) { dispatchNestedFling(0, velocityY, true); fling((int) velocityY); return true; } return false; } @Override public boolean onNestedPreFling(@NonNull View target, float velocityX, float velocityY) { return dispatchNestedPreFling(velocityX, velocityY); } @Override public int getNestedScrollAxes() { return mParentHelper.getNestedScrollAxes(); } // ScrollView import @Override public boolean shouldDelayChildPressedState() { return true; } @Override protected float getTopFadingEdgeStrength() { if (getChildCount() == 0) { return 0.0f; } final int length = getVerticalFadingEdgeLength(); final int scrollY = getScrollY(); if (scrollY < length) { return scrollY / (float) length; } return 1.0f; } @Override protected float getBottomFadingEdgeStrength() { if (getChildCount() == 0) { return 0.0f; } View child = getChildAt(0); final NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int length = getVerticalFadingEdgeLength(); final int bottomEdge = getHeight() - getPaddingBottom(); final int span = child.getBottom() + lp.bottomMargin - getScrollY() - bottomEdge; if (span < length) { return span / (float) length; } return 1.0f; } /** * @return The maximum amount this scroll view will scroll in response to * an arrow event. */ public int getMaxScrollAmount() { return (int) (MAX_SCROLL_FACTOR * getHeight()); } private void initScrollView() { mScroller = new OverScroller(getContext()); setFocusable(true); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setWillNotDraw(false); final ViewConfiguration configuration = ViewConfiguration.get(getContext()); mTouchSlop = configuration.getScaledTouchSlop(); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); } @Override public void addView(View child) { if (getChildCount() > 0) { throw new IllegalStateException("ScrollView can host only one direct child"); } super.addView(child); } @Override public void addView(View child, int index) { if (getChildCount() > 0) { throw new IllegalStateException("ScrollView can host only one direct child"); } super.addView(child, index); } @Override public void addView(View child, ViewGroup.LayoutParams params) { if (getChildCount() > 0) { throw new IllegalStateException("ScrollView can host only one direct child"); } super.addView(child, params); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if (getChildCount() > 0) { throw new IllegalStateException("ScrollView can host only one direct child"); } super.addView(child, index, params); } /** * Register a callback to be invoked when the scroll X or Y positions of * this view change. * <p>This version of the method works on all versions of Android, back to API v4.</p> * * @param l The listener to notify when the scroll X or Y position changes. * @see android.view.View#getScrollX() * @see android.view.View#getScrollY() */ public void setOnScrollChangeListener(@Nullable OnScrollChangeListener l) { mOnScrollChangeListener = l; } /** * @return Returns true this ScrollView can be scrolled */ private boolean canScroll() { if (getChildCount() > 0) { View child = getChildAt(0); final NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childSize = child.getHeight() + lp.topMargin + lp.bottomMargin; int parentSpace = getHeight() - getPaddingTop() - getPaddingBottom(); return childSize > parentSpace; } return false; } /** * Indicates whether this ScrollView's content is stretched to fill the viewport. * * @return True if the content fills the viewport, false otherwise. * * @attr name android:fillViewport */ public boolean isFillViewport() { return mFillViewport; } /** * Set whether this ScrollView should stretch its content height to fill the viewport or not. * * @param fillViewport True to stretch the content's height to the viewport's * boundaries, false otherwise. * * @attr name android:fillViewport */ public void setFillViewport(boolean fillViewport) { if (fillViewport != mFillViewport) { mFillViewport = fillViewport; requestLayout(); } } /** * @return Whether arrow scrolling will animate its transition. */ public boolean isSmoothScrollingEnabled() { return mSmoothScrollingEnabled; } /** * Set whether arrow scrolling will animate its transition. * @param smoothScrollingEnabled whether arrow scrolling will animate its transition */ public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) { mSmoothScrollingEnabled = smoothScrollingEnabled; } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); if (mOnScrollChangeListener != null) { mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (!mFillViewport) { return; } final int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (heightMode == MeasureSpec.UNSPECIFIED) { return; } if (getChildCount() > 0) { View child = getChildAt(0); final NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childSize = child.getMeasuredHeight(); int parentSpace = getMeasuredHeight() - getPaddingTop() - getPaddingBottom() - lp.topMargin - lp.bottomMargin; if (childSize < parentSpace) { int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin, lp.width); int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(parentSpace, MeasureSpec.EXACTLY); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } } @Override public boolean dispatchKeyEvent(KeyEvent event) { // Let the focused view and/or our descendants get the key first return super.dispatchKeyEvent(event) || executeKeyEvent(event); } /** * You can call this function yourself to have the scroll view perform * scrolling from a key event, just as if the event had been dispatched to * it by the view hierarchy. * * @param event The key event to execute. * @return Return true if the event was handled, else false. */ public boolean executeKeyEvent(@NonNull KeyEvent event) { mTempRect.setEmpty(); if (!canScroll()) { if (isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) { View currentFocused = findFocus(); if (currentFocused == this) currentFocused = null; View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, View.FOCUS_DOWN); return nextFocused != null && nextFocused != this && nextFocused.requestFocus(View.FOCUS_DOWN); } return false; } boolean handled = false; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_UP: if (!event.isAltPressed()) { handled = arrowScroll(View.FOCUS_UP); } else { handled = fullScroll(View.FOCUS_UP); } break; case KeyEvent.KEYCODE_DPAD_DOWN: if (!event.isAltPressed()) { handled = arrowScroll(View.FOCUS_DOWN); } else { handled = fullScroll(View.FOCUS_DOWN); } break; case KeyEvent.KEYCODE_SPACE: pageScroll(event.isShiftPressed() ? View.FOCUS_UP : View.FOCUS_DOWN); break; } } return handled; } private boolean inChild(int x, int y) { if (getChildCount() > 0) { final int scrollY = getScrollY(); final View child = getChildAt(0); return !(y < child.getTop() - scrollY || y >= child.getBottom() - scrollY || x < child.getLeft() || x >= child.getRight()); } return false; } private void initOrResetVelocityTracker() { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } else { mVelocityTracker.clear(); } } private void initVelocityTrackerIfNotExists() { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } } private void recycleVelocityTracker() { if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { if (disallowIntercept) { recycleVelocityTracker(); } super.requestDisallowInterceptTouchEvent(disallowIntercept); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { /* * This method JUST determines whether we want to intercept the motion. * If we return true, onMotionEvent will be called and we do the actual * scrolling there. */ /* * Shortcut the most recurring case: the user is in the dragging * state and he is moving his finger. We want to intercept this * motion. */ final int action = ev.getAction(); if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) { return true; } switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_MOVE: { /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. */ /* * Locally do absolute value. mLastMotionY is set to the y value * of the down event. */ final int activePointerId = mActivePointerId; if (activePointerId == INVALID_POINTER) { // If we don't have a valid id, the touch down wasn't on content. break; } final int pointerIndex = ev.findPointerIndex(activePointerId); if (pointerIndex == -1) { Log.e(TAG, "Invalid pointerId=" + activePointerId + " in onInterceptTouchEvent"); break; } final int y = (int) ev.getY(pointerIndex); final int yDiff = Math.abs(y - mLastMotionY); if (yDiff > mTouchSlop && (getNestedScrollAxes() & ViewCompat.SCROLL_AXIS_VERTICAL) == 0) { mIsBeingDragged = true; mLastMotionY = y; initVelocityTrackerIfNotExists(); mVelocityTracker.addMovement(ev); mNestedYOffset = 0; final ViewParent parent = getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } } break; } case MotionEvent.ACTION_DOWN: { final int y = (int) ev.getY(); if (!inChild((int) ev.getX(), y)) { mIsBeingDragged = false; recycleVelocityTracker(); break; } /* * Remember location of down touch. * ACTION_DOWN always refers to pointer index 0. */ mLastMotionY = y; mActivePointerId = ev.getPointerId(0); initOrResetVelocityTracker(); mVelocityTracker.addMovement(ev); /* * If being flinged and user touches the screen, initiate drag; * otherwise don't. mScroller.isFinished should be false when * being flinged. We need to call computeScrollOffset() first so that * isFinished() is correct. */ mScroller.computeScrollOffset(); mIsBeingDragged = !mScroller.isFinished(); startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_TOUCH); break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: /* Release the drag */ mIsBeingDragged = false; mActivePointerId = INVALID_POINTER; recycleVelocityTracker(); if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) { ViewCompat.postInvalidateOnAnimation(this); } stopNestedScroll(ViewCompat.TYPE_TOUCH); break; case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } /* * The only time we want to intercept motion events is if we are in the * drag mode. */ return mIsBeingDragged; } @Override public boolean onTouchEvent(MotionEvent ev) { initVelocityTrackerIfNotExists(); final int actionMasked = ev.getActionMasked(); if (actionMasked == MotionEvent.ACTION_DOWN) { mNestedYOffset = 0; } MotionEvent vtev = MotionEvent.obtain(ev); vtev.offsetLocation(0, mNestedYOffset); switch (actionMasked) { case MotionEvent.ACTION_DOWN: { if (getChildCount() == 0) { return false; } if ((mIsBeingDragged = !mScroller.isFinished())) { final ViewParent parent = getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } } /* * If being flinged and user touches, stop the fling. isFinished * will be false if being flinged. */ if (!mScroller.isFinished()) { abortAnimatedScroll(); } // Remember where the motion event started mLastMotionY = (int) ev.getY(); mActivePointerId = ev.getPointerId(0); startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_TOUCH); break; } case MotionEvent.ACTION_MOVE: final int activePointerIndex = ev.findPointerIndex(mActivePointerId); if (activePointerIndex == -1) { Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent"); break; } final int y = (int) ev.getY(activePointerIndex); int deltaY = mLastMotionY - y; if (dispatchNestedPreScroll(0, deltaY, mScrollConsumed, mScrollOffset, ViewCompat.TYPE_TOUCH)) { deltaY -= mScrollConsumed[1]; mNestedYOffset += mScrollOffset[1]; } if (!mIsBeingDragged && Math.abs(deltaY) > mTouchSlop) { final ViewParent parent = getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } mIsBeingDragged = true; if (deltaY > 0) { deltaY -= mTouchSlop; } else { deltaY += mTouchSlop; } } if (mIsBeingDragged) { // Scroll to follow the motion event mLastMotionY = y - mScrollOffset[1]; final int oldY = getScrollY(); final int range = getScrollRange(); final int overscrollMode = getOverScrollMode(); boolean canOverscroll = overscrollMode == View.OVER_SCROLL_ALWAYS || (overscrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); // Calling overScrollByCompat will call onOverScrolled, which // calls onScrollChanged if applicable. if (overScrollByCompat(0, deltaY, 0, getScrollY(), 0, range, 0, 0, true) && !hasNestedScrollingParent(ViewCompat.TYPE_TOUCH)) { // Break our velocity if we hit a scroll barrier. mVelocityTracker.clear(); } final int scrolledDeltaY = getScrollY() - oldY; final int unconsumedY = deltaY - scrolledDeltaY; mScrollConsumed[1] = 0; dispatchNestedScroll(0, scrolledDeltaY, 0, unconsumedY, mScrollOffset, ViewCompat.TYPE_TOUCH, mScrollConsumed); mLastMotionY -= mScrollOffset[1]; mNestedYOffset += mScrollOffset[1]; if (canOverscroll) { deltaY -= mScrollConsumed[1]; ensureGlows(); final int pulledToY = oldY + deltaY; if (pulledToY < 0) { EdgeEffectCompat.onPull(mEdgeGlowTop, (float) deltaY / getHeight(), ev.getX(activePointerIndex) / getWidth()); if (!mEdgeGlowBottom.isFinished()) { mEdgeGlowBottom.onRelease(); } } else if (pulledToY > range) { EdgeEffectCompat.onPull(mEdgeGlowBottom, (float) deltaY / getHeight(), 1.f - ev.getX(activePointerIndex) / getWidth()); if (!mEdgeGlowTop.isFinished()) { mEdgeGlowTop.onRelease(); } } if (mEdgeGlowTop != null && (!mEdgeGlowTop.isFinished() || !mEdgeGlowBottom.isFinished())) { ViewCompat.postInvalidateOnAnimation(this); } } } break; case MotionEvent.ACTION_UP: final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId); if ((Math.abs(initialVelocity) >= mMinimumVelocity)) { if (!dispatchNestedPreFling(0, -initialVelocity)) { dispatchNestedFling(0, -initialVelocity, true); fling(-initialVelocity); } } else if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) { ViewCompat.postInvalidateOnAnimation(this); } mActivePointerId = INVALID_POINTER; endDrag(); break; case MotionEvent.ACTION_CANCEL: if (mIsBeingDragged && getChildCount() > 0) { if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) { ViewCompat.postInvalidateOnAnimation(this); } } mActivePointerId = INVALID_POINTER; endDrag(); break; case MotionEvent.ACTION_POINTER_DOWN: { final int index = ev.getActionIndex(); mLastMotionY = (int) ev.getY(index); mActivePointerId = ev.getPointerId(index); break; } case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); mLastMotionY = (int) ev.getY(ev.findPointerIndex(mActivePointerId)); break; } if (mVelocityTracker != null) { mVelocityTracker.addMovement(vtev); } vtev.recycle(); return true; } private void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = ev.getActionIndex(); final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. // TODO: Make this decision more intelligent. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastMotionY = (int) ev.getY(newPointerIndex); mActivePointerId = ev.getPointerId(newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } @Override public boolean onGenericMotionEvent(MotionEvent event) { if ((event.getSource() & InputDeviceCompat.SOURCE_CLASS_POINTER) != 0) { switch (event.getAction()) { case MotionEvent.ACTION_SCROLL: { if (!mIsBeingDragged) { final float vscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL); if (vscroll != 0) { final int delta = (int) (vscroll * getVerticalScrollFactorCompat()); final int range = getScrollRange(); int oldScrollY = getScrollY(); int newScrollY = oldScrollY - delta; if (newScrollY < 0) { newScrollY = 0; } else if (newScrollY > range) { newScrollY = range; } if (newScrollY != oldScrollY) { super.scrollTo(getScrollX(), newScrollY); return true; } } } } } } return false; } private float getVerticalScrollFactorCompat() { if (mVerticalScrollFactor == 0) { TypedValue outValue = new TypedValue(); final Context context = getContext(); if (!context.getTheme().resolveAttribute( android.R.attr.listPreferredItemHeight, outValue, true)) { throw new IllegalStateException( "Expected theme to define listPreferredItemHeight."); } mVerticalScrollFactor = outValue.getDimension( context.getResources().getDisplayMetrics()); } return mVerticalScrollFactor; } @Override protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { super.scrollTo(scrollX, scrollY); } boolean overScrollByCompat(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) { final int overScrollMode = getOverScrollMode(); final boolean canScrollHorizontal = computeHorizontalScrollRange() > computeHorizontalScrollExtent(); final boolean canScrollVertical = computeVerticalScrollRange() > computeVerticalScrollExtent(); final boolean overScrollHorizontal = overScrollMode == View.OVER_SCROLL_ALWAYS || (overScrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); final boolean overScrollVertical = overScrollMode == View.OVER_SCROLL_ALWAYS || (overScrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); int newScrollX = scrollX + deltaX; if (!overScrollHorizontal) { maxOverScrollX = 0; } int newScrollY = scrollY + deltaY; if (!overScrollVertical) { maxOverScrollY = 0; } // Clamp values if at the limits and record final int left = -maxOverScrollX; final int right = maxOverScrollX + scrollRangeX; final int top = -maxOverScrollY; final int bottom = maxOverScrollY + scrollRangeY; boolean clampedX = false; if (newScrollX > right) { newScrollX = right; clampedX = true; } else if (newScrollX < left) { newScrollX = left; clampedX = true; } boolean clampedY = false; if (newScrollY > bottom) { newScrollY = bottom; clampedY = true; } else if (newScrollY < top) { newScrollY = top; clampedY = true; } if (clampedY && !hasNestedScrollingParent(ViewCompat.TYPE_NON_TOUCH)) { mScroller.springBack(newScrollX, newScrollY, 0, 0, 0, getScrollRange()); } onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); return clampedX || clampedY; } int getScrollRange() { int scrollRange = 0; if (getChildCount() > 0) { View child = getChildAt(0); NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childSize = child.getHeight() + lp.topMargin + lp.bottomMargin; int parentSpace = getHeight() - getPaddingTop() - getPaddingBottom(); scrollRange = Math.max(0, childSize - parentSpace); } return scrollRange; } /** * <p> * Finds the next focusable component that fits in the specified bounds. * </p> * * @param topFocus look for a candidate is the one at the top of the bounds * if topFocus is true, or at the bottom of the bounds if topFocus is * false * @param top the top offset of the bounds in which a focusable must be * found * @param bottom the bottom offset of the bounds in which a focusable must * be found * @return the next focusable component in the bounds or null if none can * be found */ private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) { List<View> focusables = getFocusables(View.FOCUS_FORWARD); View focusCandidate = null; /* * A fully contained focusable is one where its top is below the bound's * top, and its bottom is above the bound's bottom. A partially * contained focusable is one where some part of it is within the * bounds, but it also has some part that is not within bounds. A fully contained * focusable is preferred to a partially contained focusable. */ boolean foundFullyContainedFocusable = false; int count = focusables.size(); for (int i = 0; i < count; i++) { View view = focusables.get(i); int viewTop = view.getTop(); int viewBottom = view.getBottom(); if (top < viewBottom && viewTop < bottom) { /* * the focusable is in the target area, it is a candidate for * focusing */ final boolean viewIsFullyContained = (top < viewTop) && (viewBottom < bottom); if (focusCandidate == null) { /* No candidate, take this one */ focusCandidate = view; foundFullyContainedFocusable = viewIsFullyContained; } else { final boolean viewIsCloserToBoundary = (topFocus && viewTop < focusCandidate.getTop()) || (!topFocus && viewBottom > focusCandidate.getBottom()); if (foundFullyContainedFocusable) { if (viewIsFullyContained && viewIsCloserToBoundary) { /* * We're dealing with only fully contained views, so * it has to be closer to the boundary to beat our * candidate */ focusCandidate = view; } } else { if (viewIsFullyContained) { /* Any fully contained view beats a partially contained view */ focusCandidate = view; foundFullyContainedFocusable = true; } else if (viewIsCloserToBoundary) { /* * Partially contained view beats another partially * contained view if it's closer */ focusCandidate = view; } } } } } return focusCandidate; } /** * <p>Handles scrolling in response to a "page up/down" shortcut press. This * method will scroll the view by one page up or down and give the focus * to the topmost/bottommost component in the new visible area. If no * component is a good candidate for focus, this scrollview reclaims the * focus.</p> * * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} * to go one page up or * {@link android.view.View#FOCUS_DOWN} to go one page down * @return true if the key event is consumed by this method, false otherwise */ public boolean pageScroll(int direction) { boolean down = direction == View.FOCUS_DOWN; int height = getHeight(); if (down) { mTempRect.top = getScrollY() + height; int count = getChildCount(); if (count > 0) { View view = getChildAt(count - 1); NestedScrollView.LayoutParams lp = (LayoutParams) view.getLayoutParams(); int bottom = view.getBottom() + lp.bottomMargin + getPaddingBottom(); if (mTempRect.top + height > bottom) { mTempRect.top = bottom - height; } } } else { mTempRect.top = getScrollY() - height; if (mTempRect.top < 0) { mTempRect.top = 0; } } mTempRect.bottom = mTempRect.top + height; return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); } /** * <p>Handles scrolling in response to a "home/end" shortcut press. This * method will scroll the view to the top or bottom and give the focus * to the topmost/bottommost component in the new visible area. If no * component is a good candidate for focus, this scrollview reclaims the * focus.</p> * * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} * to go the top of the view or * {@link android.view.View#FOCUS_DOWN} to go the bottom * @return true if the key event is consumed by this method, false otherwise */ public boolean fullScroll(int direction) { boolean down = direction == View.FOCUS_DOWN; int height = getHeight(); mTempRect.top = 0; mTempRect.bottom = height; if (down) { int count = getChildCount(); if (count > 0) { View view = getChildAt(count - 1); NestedScrollView.LayoutParams lp = (LayoutParams) view.getLayoutParams(); mTempRect.bottom = view.getBottom() + lp.bottomMargin + getPaddingBottom(); mTempRect.top = mTempRect.bottom - height; } } return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom); } /** * <p>Scrolls the view to make the area defined by <code>top</code> and * <code>bottom</code> visible. This method attempts to give the focus * to a component visible in this area. If no component can be focused in * the new visible area, the focus is reclaimed by this ScrollView.</p> * * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} * to go upward, {@link android.view.View#FOCUS_DOWN} to downward * @param top the top offset of the new area to be made visible * @param bottom the bottom offset of the new area to be made visible * @return true if the key event is consumed by this method, false otherwise */ private boolean scrollAndFocus(int direction, int top, int bottom) { boolean handled = true; int height = getHeight(); int containerTop = getScrollY(); int containerBottom = containerTop + height; boolean up = direction == View.FOCUS_UP; View newFocused = findFocusableViewInBounds(up, top, bottom); if (newFocused == null) { newFocused = this; } if (top >= containerTop && bottom <= containerBottom) { handled = false; } else { int delta = up ? (top - containerTop) : (bottom - containerBottom); doScrollY(delta); } if (newFocused != findFocus()) newFocused.requestFocus(direction); return handled; } /** * Handle scrolling in response to an up or down arrow click. * * @param direction The direction corresponding to the arrow key that was * pressed * @return True if we consumed the event, false otherwise */ public boolean arrowScroll(int direction) { View currentFocused = findFocus(); if (currentFocused == this) currentFocused = null; View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); final int maxJump = getMaxScrollAmount(); if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) { nextFocused.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(nextFocused, mTempRect); int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); doScrollY(scrollDelta); nextFocused.requestFocus(direction); } else { // no new focus int scrollDelta = maxJump; if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) { scrollDelta = getScrollY(); } else if (direction == View.FOCUS_DOWN) { if (getChildCount() > 0) { View child = getChildAt(0); NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); int daBottom = child.getBottom() + lp.bottomMargin; int screenBottom = getScrollY() + getHeight() - getPaddingBottom(); scrollDelta = Math.min(daBottom - screenBottom, maxJump); } } if (scrollDelta == 0) { return false; } doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta); } if (currentFocused != null && currentFocused.isFocused() && isOffScreen(currentFocused)) { // previously focused item still has focus and is off screen, give // it up (take it back to ourselves) // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are // sure to // get it) final int descendantFocusability = getDescendantFocusability(); // save setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); requestFocus(); setDescendantFocusability(descendantFocusability); // restore } return true; } /** * @return whether the descendant of this scroll view is scrolled off * screen. */ private boolean isOffScreen(View descendant) { return !isWithinDeltaOfScreen(descendant, 0, getHeight()); } /** * @return whether the descendant of this scroll view is within delta * pixels of being on the screen. */ private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) { descendant.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(descendant, mTempRect); return (mTempRect.bottom + delta) >= getScrollY() && (mTempRect.top - delta) <= (getScrollY() + height); } /** * Smooth scroll by a Y delta * * @param delta the number of pixels to scroll by on the Y axis */ private void doScrollY(int delta) { if (delta != 0) { if (mSmoothScrollingEnabled) { smoothScrollBy(0, delta); } else { scrollBy(0, delta); } } } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param dx the number of pixels to scroll by on the X axis * @param dy the number of pixels to scroll by on the Y axis */ public final void smoothScrollBy(int dx, int dy) { smoothScrollBy(dx, dy, false); } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param dx the number of pixels to scroll by on the X axis * @param dy the number of pixels to scroll by on the Y axis * @param withNestedScrolling whether to include nested scrolling operations. */ private void smoothScrollBy(int dx, int dy, boolean withNestedScrolling) { if (getChildCount() == 0) { // Nothing to do. return; } long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; if (duration > ANIMATED_SCROLL_GAP) { View child = getChildAt(0); NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childSize = child.getHeight() + lp.topMargin + lp.bottomMargin; int parentSpace = getHeight() - getPaddingTop() - getPaddingBottom(); final int scrollY = getScrollY(); final int maxY = Math.max(0, childSize - parentSpace); dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY; mScroller.startScroll(getScrollX(), scrollY, 0, dy); runAnimatedScroll(withNestedScrolling); } else { if (!mScroller.isFinished()) { abortAnimatedScroll(); } scrollBy(dx, dy); } mLastScroll = AnimationUtils.currentAnimationTimeMillis(); } /** * Like {@link #scrollTo}, but scroll smoothly instead of immediately. * * @param x the position where to scroll on the X axis * @param y the position where to scroll on the Y axis */ public final void smoothScrollTo(int x, int y) { smoothScrollTo(x, y, false); } /** * Like {@link #scrollTo}, but scroll smoothly instead of immediately. * * @param x the position where to scroll on the X axis * @param y the position where to scroll on the Y axis * @param withNestedScrolling whether to include nested scrolling operations. */ // This should be considered private, it is package private to avoid a synthetic ancestor. void smoothScrollTo(int x, int y, boolean withNestedScrolling) { smoothScrollBy(x - getScrollX(), y - getScrollY(), withNestedScrolling); } /** * <p>The scroll range of a scroll view is the overall height of all of its * children.</p> * @hide */ @RestrictTo(LIBRARY_GROUP_PREFIX) @Override public int computeVerticalScrollRange() { final int count = getChildCount(); final int parentSpace = getHeight() - getPaddingBottom() - getPaddingTop(); if (count == 0) { return parentSpace; } View child = getChildAt(0); NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); int scrollRange = child.getBottom() + lp.bottomMargin; final int scrollY = getScrollY(); final int overscrollBottom = Math.max(0, scrollRange - parentSpace); if (scrollY < 0) { scrollRange -= scrollY; } else if (scrollY > overscrollBottom) { scrollRange += scrollY - overscrollBottom; } return scrollRange; } /** @hide */ @RestrictTo(LIBRARY_GROUP_PREFIX) @Override public int computeVerticalScrollOffset() { return Math.max(0, super.computeVerticalScrollOffset()); } /** @hide */ @RestrictTo(LIBRARY_GROUP_PREFIX) @Override public int computeVerticalScrollExtent() { return super.computeVerticalScrollExtent(); } /** @hide */ @RestrictTo(LIBRARY_GROUP_PREFIX) @Override public int computeHorizontalScrollRange() { return super.computeHorizontalScrollRange(); } /** @hide */ @RestrictTo(LIBRARY_GROUP_PREFIX) @Override public int computeHorizontalScrollOffset() { return super.computeHorizontalScrollOffset(); } /** @hide */ @RestrictTo(LIBRARY_GROUP_PREFIX) @Override public int computeHorizontalScrollExtent() { return super.computeHorizontalScrollExtent(); } @Override protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { ViewGroup.LayoutParams lp = child.getLayoutParams(); int childWidthMeasureSpec; int childHeightMeasureSpec; childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, getPaddingLeft() + getPaddingRight(), lp.width); childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } @Override protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) { final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin + widthUsed, lp.width); final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } @Override public void computeScroll() { if (mScroller.isFinished()) { return; } mScroller.computeScrollOffset(); final int y = mScroller.getCurrY(); int unconsumed = y - mLastScrollerY; mLastScrollerY = y; // Nested Scrolling Pre Pass mScrollConsumed[1] = 0; dispatchNestedPreScroll(0, unconsumed, mScrollConsumed, null, ViewCompat.TYPE_NON_TOUCH); unconsumed -= mScrollConsumed[1]; final int range = getScrollRange(); if (unconsumed != 0) { // Internal Scroll final int oldScrollY = getScrollY(); overScrollByCompat(0, unconsumed, getScrollX(), oldScrollY, 0, range, 0, 0, false); final int scrolledByMe = getScrollY() - oldScrollY; unconsumed -= scrolledByMe; // Nested Scrolling Post Pass mScrollConsumed[1] = 0; dispatchNestedScroll(0, scrolledByMe, 0, unconsumed, mScrollOffset, ViewCompat.TYPE_NON_TOUCH, mScrollConsumed); unconsumed -= mScrollConsumed[1]; } if (unconsumed != 0) { final int mode = getOverScrollMode(); final boolean canOverscroll = mode == OVER_SCROLL_ALWAYS || (mode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); if (canOverscroll) { ensureGlows(); if (unconsumed < 0) { if (mEdgeGlowTop.isFinished()) { mEdgeGlowTop.onAbsorb((int) mScroller.getCurrVelocity()); } } else { if (mEdgeGlowBottom.isFinished()) { mEdgeGlowBottom.onAbsorb((int) mScroller.getCurrVelocity()); } } } abortAnimatedScroll(); } if (!mScroller.isFinished()) { ViewCompat.postInvalidateOnAnimation(this); } else { stopNestedScroll(ViewCompat.TYPE_NON_TOUCH); } } private void runAnimatedScroll(boolean participateInNestedScrolling) { if (participateInNestedScrolling) { startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_NON_TOUCH); } else { stopNestedScroll(ViewCompat.TYPE_NON_TOUCH); } mLastScrollerY = getScrollY(); ViewCompat.postInvalidateOnAnimation(this); } private void abortAnimatedScroll() { mScroller.abortAnimation(); stopNestedScroll(ViewCompat.TYPE_NON_TOUCH); } /** * Scrolls the view to the given child. * * @param child the View to scroll to */ private void scrollToChild(View child) { child.getDrawingRect(mTempRect); /* Offset from child's local coordinates to ScrollView coordinates */ offsetDescendantRectToMyCoords(child, mTempRect); int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); if (scrollDelta != 0) { scrollBy(0, scrollDelta); } } /** * If rect is off screen, scroll just enough to get it (or at least the * first screen size chunk of it) on screen. * * @param rect The rectangle. * @param immediate True to scroll immediately without animation * @return true if scrolling was performed */ private boolean scrollToChildRect(Rect rect, boolean immediate) { final int delta = computeScrollDeltaToGetChildRectOnScreen(rect); final boolean scroll = delta != 0; if (scroll) { if (immediate) { scrollBy(0, delta); } else { smoothScrollBy(0, delta); } } return scroll; } /** * Compute the amount to scroll in the Y direction in order to get * a rectangle completely on the screen (or, if taller than the screen, * at least the first screen size chunk of it). * * @param rect The rect. * @return The scroll delta. */ protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { if (getChildCount() == 0) return 0; int height = getHeight(); int screenTop = getScrollY(); int screenBottom = screenTop + height; int actualScreenBottom = screenBottom; int fadingEdge = getVerticalFadingEdgeLength(); // TODO: screenTop should be incremented by fadingEdge * getTopFadingEdgeStrength (but for // the target scroll distance). // leave room for top fading edge as long as rect isn't at very top if (rect.top > 0) { screenTop += fadingEdge; } // TODO: screenBottom should be decremented by fadingEdge * getBottomFadingEdgeStrength (but // for the target scroll distance). // leave room for bottom fading edge as long as rect isn't at very bottom View child = getChildAt(0); final NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (rect.bottom < child.getHeight() + lp.topMargin + lp.bottomMargin) { screenBottom -= fadingEdge; } int scrollYDelta = 0; if (rect.bottom > screenBottom && rect.top > screenTop) { // need to move down to get it in view: move down just enough so // that the entire rectangle is in view (or at least the first // screen size chunk). if (rect.height() > height) { // just enough to get screen size chunk on scrollYDelta += (rect.top - screenTop); } else { // get entire rect at bottom of screen scrollYDelta += (rect.bottom - screenBottom); } // make sure we aren't scrolling beyond the end of our content int bottom = child.getBottom() + lp.bottomMargin; int distanceToBottom = bottom - actualScreenBottom; scrollYDelta = Math.min(scrollYDelta, distanceToBottom); } else if (rect.top < screenTop && rect.bottom < screenBottom) { // need to move up to get it in view: move up just enough so that // entire rectangle is in view (or at least the first screen // size chunk of it). if (rect.height() > height) { // screen size chunk scrollYDelta -= (screenBottom - rect.bottom); } else { // entire rect at top scrollYDelta -= (screenTop - rect.top); } // make sure we aren't scrolling any further than the top our content scrollYDelta = Math.max(scrollYDelta, -getScrollY()); } return scrollYDelta; } @Override public void requestChildFocus(View child, View focused) { if (!mIsLayoutDirty) { scrollToChild(focused); } else { // The child may not be laid out yet, we can't compute the scroll yet mChildToScrollTo = focused; } super.requestChildFocus(child, focused); } /** * When looking for focus in children of a scroll view, need to be a little * more careful not to give focus to something that is scrolled off screen. * * This is more expensive than the default {@link android.view.ViewGroup} * implementation, otherwise this behavior might have been made the default. */ @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { // convert from forward / backward notation to up / down / left / right // (ugh). if (direction == View.FOCUS_FORWARD) { direction = View.FOCUS_DOWN; } else if (direction == View.FOCUS_BACKWARD) { direction = View.FOCUS_UP; } final View nextFocus = previouslyFocusedRect == null ? FocusFinder.getInstance().findNextFocus(this, null, direction) : FocusFinder.getInstance().findNextFocusFromRect( this, previouslyFocusedRect, direction); if (nextFocus == null) { return false; } if (isOffScreen(nextFocus)) { return false; } return nextFocus.requestFocus(direction, previouslyFocusedRect); } @Override public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { // offset into coordinate space of this scroll view rectangle.offset(child.getLeft() - child.getScrollX(), child.getTop() - child.getScrollY()); return scrollToChildRect(rectangle, immediate); } @Override public void requestLayout() { mIsLayoutDirty = true; super.requestLayout(); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); mIsLayoutDirty = false; // Give a child focus if it needs it if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { scrollToChild(mChildToScrollTo); } mChildToScrollTo = null; if (!mIsLaidOut) { // If there is a saved state, scroll to the position saved in that state. if (mSavedState != null) { scrollTo(getScrollX(), mSavedState.scrollPosition); mSavedState = null; } // mScrollY default value is "0" // Make sure current scrollY position falls into the scroll range. If it doesn't, // scroll such that it does. int childSize = 0; if (getChildCount() > 0) { View child = getChildAt(0); NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); childSize = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin; } int parentSpace = b - t - getPaddingTop() - getPaddingBottom(); int currentScrollY = getScrollY(); int newScrollY = clamp(currentScrollY, parentSpace, childSize); if (newScrollY != currentScrollY) { scrollTo(getScrollX(), newScrollY); } } // Calling this with the present values causes it to re-claim them scrollTo(getScrollX(), getScrollY()); mIsLaidOut = true; } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); mIsLaidOut = false; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); View currentFocused = findFocus(); if (null == currentFocused || this == currentFocused) { return; } // If the currently-focused view was visible on the screen when the // screen was at the old height, then scroll the screen to make that // view visible with the new screen height. if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) { currentFocused.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(currentFocused, mTempRect); int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); doScrollY(scrollDelta); } } /** * Return true if child is a descendant of parent, (or equal to the parent). */ private static boolean isViewDescendantOf(View child, View parent) { if (child == parent) { return true; } final ViewParent theParent = child.getParent(); return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); } /** * Fling the scroll view * * @param velocityY The initial velocity in the Y direction. Positive * numbers mean that the finger/cursor is moving down the screen, * which means we want to scroll towards the top. */ public void fling(int velocityY) { if (getChildCount() > 0) { mScroller.fling(getScrollX(), getScrollY(), // start 0, velocityY, // velocities 0, 0, // x Integer.MIN_VALUE, Integer.MAX_VALUE, // y 0, 0); // overscroll runAnimatedScroll(true); } } private void endDrag() { mIsBeingDragged = false; recycleVelocityTracker(); stopNestedScroll(ViewCompat.TYPE_TOUCH); if (mEdgeGlowTop != null) { mEdgeGlowTop.onRelease(); mEdgeGlowBottom.onRelease(); } } /** * {@inheritDoc} * * <p>This version also clamps the scrolling to the bounds of our child. */ @Override public void scrollTo(int x, int y) { // we rely on the fact the View.scrollBy calls scrollTo. if (getChildCount() > 0) { View child = getChildAt(0); final NestedScrollView.LayoutParams lp = (LayoutParams) child.getLayoutParams(); int parentSpaceHorizontal = getWidth() - getPaddingLeft() - getPaddingRight(); int childSizeHorizontal = child.getWidth() + lp.leftMargin + lp.rightMargin; int parentSpaceVertical = getHeight() - getPaddingTop() - getPaddingBottom(); int childSizeVertical = child.getHeight() + lp.topMargin + lp.bottomMargin; x = clamp(x, parentSpaceHorizontal, childSizeHorizontal); y = clamp(y, parentSpaceVertical, childSizeVertical); if (x != getScrollX() || y != getScrollY()) { super.scrollTo(x, y); } } } private void ensureGlows() { if (getOverScrollMode() != View.OVER_SCROLL_NEVER) { if (mEdgeGlowTop == null) { Context context = getContext(); mEdgeGlowTop = new EdgeEffect(context); mEdgeGlowBottom = new EdgeEffect(context); } } else { mEdgeGlowTop = null; mEdgeGlowBottom = null; } } @Override public void draw(Canvas canvas) { super.draw(canvas); if (mEdgeGlowTop != null) { final int scrollY = getScrollY(); if (!mEdgeGlowTop.isFinished()) { final int restoreCount = canvas.save(); int width = getWidth(); int height = getHeight(); int xTranslation = 0; int yTranslation = Math.min(0, scrollY); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || getClipToPadding()) { width -= getPaddingLeft() + getPaddingRight(); xTranslation += getPaddingLeft(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && getClipToPadding()) { height -= getPaddingTop() + getPaddingBottom(); yTranslation += getPaddingTop(); } canvas.translate(xTranslation, yTranslation); mEdgeGlowTop.setSize(width, height); if (mEdgeGlowTop.draw(canvas)) { ViewCompat.postInvalidateOnAnimation(this); } canvas.restoreToCount(restoreCount); } if (!mEdgeGlowBottom.isFinished()) { final int restoreCount = canvas.save(); int width = getWidth(); int height = getHeight(); int xTranslation = 0; int yTranslation = Math.max(getScrollRange(), scrollY) + height; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || getClipToPadding()) { width -= getPaddingLeft() + getPaddingRight(); xTranslation += getPaddingLeft(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && getClipToPadding()) { height -= getPaddingTop() + getPaddingBottom(); yTranslation -= getPaddingBottom(); } canvas.translate(xTranslation - width, yTranslation); canvas.rotate(180, width, 0); mEdgeGlowBottom.setSize(width, height); if (mEdgeGlowBottom.draw(canvas)) { ViewCompat.postInvalidateOnAnimation(this); } canvas.restoreToCount(restoreCount); } } } private static int clamp(int n, int my, int child) { if (my >= child || n < 0) { /* my >= child is this case: * |--------------- me ---------------| * |------ child ------| * or * |--------------- me ---------------| * |------ child ------| * or * |--------------- me ---------------| * |------ child ------| * * n < 0 is this case: * |------ me ------| * |-------- child --------| * |-- mScrollX --| */ return 0; } if ((my + n) > child) { /* this case: * |------ me ------| * |------ child ------| * |-- mScrollX --| */ return child - my; } return n; } @Override protected void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); mSavedState = ss; requestLayout(); } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.scrollPosition = getScrollY(); return ss; } static class SavedState extends BaseSavedState { public int scrollPosition; SavedState(Parcelable superState) { super(superState); } SavedState(Parcel source) { super(source); scrollPosition = source.readInt(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(scrollPosition); } @NonNull @Override public String toString() { return "HorizontalScrollView.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " scrollPosition=" + scrollPosition + "}"; } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } static class AccessibilityDelegate extends AccessibilityDelegateCompat { @Override public boolean performAccessibilityAction(View host, int action, Bundle arguments) { if (super.performAccessibilityAction(host, action, arguments)) { return true; } final NestedScrollView nsvHost = (NestedScrollView) host; if (!nsvHost.isEnabled()) { return false; } switch (action) { case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: { final int viewportHeight = nsvHost.getHeight() - nsvHost.getPaddingBottom() - nsvHost.getPaddingTop(); final int targetScrollY = Math.min(nsvHost.getScrollY() + viewportHeight, nsvHost.getScrollRange()); if (targetScrollY != nsvHost.getScrollY()) { nsvHost.smoothScrollTo(0, targetScrollY, true); return true; } } return false; case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: { final int viewportHeight = nsvHost.getHeight() - nsvHost.getPaddingBottom() - nsvHost.getPaddingTop(); final int targetScrollY = Math.max(nsvHost.getScrollY() - viewportHeight, 0); if (targetScrollY != nsvHost.getScrollY()) { nsvHost.smoothScrollTo(0, targetScrollY, true); return true; } } return false; } return false; } @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { super.onInitializeAccessibilityNodeInfo(host, info); final NestedScrollView nsvHost = (NestedScrollView) host; info.setClassName(ScrollView.class.getName()); if (nsvHost.isEnabled()) { final int scrollRange = nsvHost.getScrollRange(); if (scrollRange > 0) { info.setScrollable(true); if (nsvHost.getScrollY() > 0) { info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD); } if (nsvHost.getScrollY() < scrollRange) { info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD); } } } } @Override public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { super.onInitializeAccessibilityEvent(host, event); final NestedScrollView nsvHost = (NestedScrollView) host; event.setClassName(ScrollView.class.getName()); final boolean scrollable = nsvHost.getScrollRange() > 0; event.setScrollable(scrollable); event.setScrollX(nsvHost.getScrollX()); event.setScrollY(nsvHost.getScrollY()); AccessibilityRecordCompat.setMaxScrollX(event, nsvHost.getScrollX()); AccessibilityRecordCompat.setMaxScrollY(event, nsvHost.getScrollRange()); } } }
Add directional accessibility scroll actions to NestedScrollView Test: tested with twisted talkback and example app using NestedScrollView that scroll down has the same effect as scroll forward and scroll up has the same effect as scroll backward. Bug: 136277517 Change-Id: Ieb17f26f4266b6f92ee249cdec78fcfc835fd5ad
core/core/src/main/java/androidx/core/widget/NestedScrollView.java
Add directional accessibility scroll actions to NestedScrollView
<ide><path>ore/core/src/main/java/androidx/core/widget/NestedScrollView.java <ide> return false; <ide> } <ide> switch (action) { <del> case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: { <add> case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: <add> case android.R.id.accessibilityActionScrollDown: { <ide> final int viewportHeight = nsvHost.getHeight() - nsvHost.getPaddingBottom() <ide> - nsvHost.getPaddingTop(); <ide> final int targetScrollY = Math.min(nsvHost.getScrollY() + viewportHeight, <ide> } <ide> } <ide> return false; <del> case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: { <add> case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: <add> case android.R.id.accessibilityActionScrollUp: { <ide> final int viewportHeight = nsvHost.getHeight() - nsvHost.getPaddingBottom() <ide> - nsvHost.getPaddingTop(); <ide> final int targetScrollY = Math.max(nsvHost.getScrollY() - viewportHeight, 0); <ide> if (scrollRange > 0) { <ide> info.setScrollable(true); <ide> if (nsvHost.getScrollY() > 0) { <del> info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD); <add> info.addAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat <add> .ACTION_SCROLL_BACKWARD); <add> info.addAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat <add> .ACTION_SCROLL_UP); <ide> } <ide> if (nsvHost.getScrollY() < scrollRange) { <del> info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD); <add> info.addAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat <add> .ACTION_SCROLL_FORWARD); <add> info.addAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat <add> .ACTION_SCROLL_DOWN); <ide> } <ide> } <ide> }
Java
mit
1d87cea7d612e12c6e26e5c63945a35b29e4574a
0
Cloudhunter/OpenCCSensors,lyqyd/OpenCCSensors
package openccsensors.common.helper; import openccsensors.common.core.OCSLog; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import cpw.mods.fml.common.registry.LanguageRegistry; public class SensorHelper { public static String getType(String rawType) { String translated = LanguageRegistry.instance().getStringLocalization(rawType); return translated == "" ? rawType : translated; } public static String getRawType(TileEntity entity) { ItemStack stack = new ItemStack(entity.getBlockType(), 1, entity.getBlockMetadata()); String rawName = entity.getClass().getName().toLowerCase(); try { rawName = stack.getItemName().toLowerCase(); }catch(Exception e) { } String packageName = entity.getClass().getName().toLowerCase(); String[] packageLevels = packageName.split("\\."); if (!rawName.startsWith(packageLevels[0])) { rawName = packageLevels[0] + "." + rawName; } return rawName; } public static String getDisplayType(TileEntity entity) { ItemStack stack = new ItemStack(entity.getBlockType(), 1, entity.getBlockMetadata()); return InventoryHelper.getNameForItemStack(stack); } }
src/openccsensors/common/helper/SensorHelper.java
package openccsensors.common.helper; import openccsensors.common.core.OCSLog; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import cpw.mods.fml.common.registry.LanguageRegistry; public class SensorHelper { public static String getType(String rawType) { String translated = LanguageRegistry.instance().getStringLocalization( rawType, "en_OCS"); return translated == "" ? rawType : translated; } public static String getRawType(TileEntity entity) { String rawType = entity.getClass().getName(); Block b = entity.getBlockType(); if (b != null) { rawType = b.getBlockName(); } return rawType.toLowerCase().trim(); } public static String getDisplayType(TileEntity entity) { ItemStack stack = new ItemStack(entity.getBlockType()); return InventoryHelper.getNameForItemStack(stack); } }
trying to sort this item name shit!!!
src/openccsensors/common/helper/SensorHelper.java
trying to sort this item name shit!!!
<ide><path>rc/openccsensors/common/helper/SensorHelper.java <ide> public class SensorHelper { <ide> <ide> public static String getType(String rawType) { <del> String translated = LanguageRegistry.instance().getStringLocalization( <del> rawType, "en_OCS"); <add> String translated = LanguageRegistry.instance().getStringLocalization(rawType); <ide> return translated == "" ? rawType : translated; <ide> } <ide> <ide> public static String getRawType(TileEntity entity) { <del> String rawType = entity.getClass().getName(); <del> Block b = entity.getBlockType(); <del> if (b != null) { <del> rawType = b.getBlockName(); <add> ItemStack stack = new ItemStack(entity.getBlockType(), 1, entity.getBlockMetadata()); <add> <add> String rawName = entity.getClass().getName().toLowerCase(); <add> try { <add> rawName = stack.getItemName().toLowerCase(); <add> }catch(Exception e) { <ide> } <del> return rawType.toLowerCase().trim(); <add> String packageName = entity.getClass().getName().toLowerCase(); <add> String[] packageLevels = packageName.split("\\."); <add> if (!rawName.startsWith(packageLevels[0])) { <add> rawName = packageLevels[0] + "." + rawName; <add> } <add> <add> return rawName; <ide> } <ide> <ide> public static String getDisplayType(TileEntity entity) { <del> ItemStack stack = new ItemStack(entity.getBlockType()); <add> ItemStack stack = new ItemStack(entity.getBlockType(), 1, entity.getBlockMetadata()); <ide> return InventoryHelper.getNameForItemStack(stack); <ide> } <ide>
JavaScript
bsd-2-clause
05553f80304e0e5a23821a3a30a6092d838696f7
0
featurist/pogoscript,featurist/pogoscript,featurist/pogoscript
var _ = require('underscore'); var parseError = exports.parseError = function (term, message, expected) { expected = expected || []; var e = new Error(message); e.index = term.index; e.context = term.context; e.expected = expected; return e; }; var ExpressionPrototype = new function () { this.generateJavaScriptReturn = function (buffer, scope) { buffer.write('return '); this.generateJavaScript(buffer, scope); buffer.write(';'); }; this.generateJavaScriptStatement = function (buffer, scope) { this.generateJavaScript(buffer, scope); buffer.write(';'); }; this.definitions = function (scope) { return []; }; this.definitionName = function(scope) { } }; var addWalker = function () { var self = arguments[0]; var subtermNames = Array.prototype.splice.call(arguments, 1, arguments.length - 1); self.walk = function (visitor) { visitor(this); for (var n in subtermNames) { var subterm = this[subtermNames[n]]; if (_.isArray(subterm)) { for (var i in subterm) { subterm[i].walk(visitor); } } else { subterm.walk(visitor); } } }; }; var expressionTerm = function (name, constructor) { constructor.prototype = ExpressionPrototype; return exports[name] = function () { var args = arguments; var F = function () { return constructor.apply(this, args); } F.prototype = constructor.prototype; return new F(); }; }; var semanticFailure = expressionTerm('semanticFailure', function(terms, message) { this.isSemanticFailure = true; this.terms = terms; this.message = message; this.generateJavaScript = function(buffer, scope) { throw this; }; this.printError = function(sourceFile) { process.stdout.write(this.message + '\n'); process.stdout.write('\n'); sourceFile.printIndex(this.index); } }); exports.identifier = function (name) { return { identifier: name }; }; var integer = expressionTerm('integer', function (value) { this.integer = value; this.generateJavaScript = function (buffer, scope) { buffer.write(this.integer.toString()); }; }); var boolean = expressionTerm('boolean', function(value) { this.boolean = value; this.generateJavaScript = function (buffer, scope) { if (this.boolean) { buffer.write('true'); } else { buffer.write('false'); } }; }); var formatJavaScriptString = function(s) { return "'" + s.replace("'", "\\'") + "'"; }; expressionTerm('string', function(value) { this.isString = true; this.string = value; this.generateJavaScript = function(buffer, scope) { buffer.write(formatJavaScriptString(this.string)); }; }); expressionTerm('float', function (value) { this.float = value; this.generateJavaScript = function (buffer, scope) { buffer.write(this.float.toString()); }; }); var variable = expressionTerm('variable', function (name) { this.variable = name; this.isVariable = true; this.generateJavaScript = function (buffer, scope) { buffer.write(concatName(this.variable)); }; this.generateJavaScriptTarget = this.generateJavaScript; this.definitionName = function(scope) { return this.variable; }; addWalker(this); }); var parameter = expressionTerm('parameter', function (name) { this.parameter = name; this.isParameter = true; this.generateJavaScript = function (buffer, scope) { buffer.write(concatName(this.parameter)); }; }); var concatName = function (nameSegments) { var name = nameSegments[0]; for (var n = 1; n < nameSegments.length; n++) { var segment = nameSegments[n]; name += segment[0].toUpperCase() + segment.substring(1); } return name; }; var functionCall = expressionTerm('functionCall', function (fun, arguments) { this.function = fun; this.arguments = arguments; this.isFunctionCall = true; this.generateJavaScript = function (buffer, scope) { fun.generateJavaScript(buffer, scope); buffer.write('('); var first = true; _(this.arguments).each(function (arg) { if (!first) { buffer.write(','); } first = false; arg.generateJavaScript(buffer, scope); }); buffer.write(')'); }; }); var block = expressionTerm('block', function (parameters, body, dontReturnLastStatement) { this.body = body; this.isBlock = true; this.dontReturnLastStatement = dontReturnLastStatement; this.parameters = parameters; this.generateJavaScript = function (buffer, scope) { buffer.write('function('); var first = true; _(this.parameters).each(function (parameter) { if (!first) { buffer.write(','); } first = false; parameter.generateJavaScript(buffer, scope); }); buffer.write('){'); if (this.dontReturnLastStatement) { body.generateJavaScript(buffer, scope.subScope()); } else { body.generateJavaScriptReturn(buffer, scope.subScope()); } buffer.write('}'); }; }); var writeToBufferWithDelimiter = function (array, delimiter, buffer, scope, writer) { writer = writer || function (item, buffer) { item.generateJavaScript(buffer, scope); }; var first = true; _(array).each(function (item) { if (!first) { buffer.write(delimiter); } first = false; writer(item, buffer); }); }; var methodCall = expressionTerm('methodCall', function (object, name, arguments) { this.object = object; this.name = name; this.arguments = arguments; this.generateJavaScript = function (buffer, scope) { this.object.generateJavaScript(buffer, scope); buffer.write('.'); buffer.write(concatName(this.name)); buffer.write('('); writeToBufferWithDelimiter(this.arguments, ',', buffer, scope); buffer.write(')'); }; addWalker(this, 'object', 'arguments'); }); var indexer = expressionTerm('indexer', function (object, indexer) { this.object = object; this.indexer = indexer; this.isIndexer = true; this.generateJavaScript = function (buffer, scope) { this.object.generateJavaScript(buffer, scope); buffer.write('['); this.indexer.generateJavaScript(buffer, scope); buffer.write(']'); }; this.generateJavaScriptTarget = this.generateJavaScript; }); var fieldReference = expressionTerm('fieldReference', function (object, name) { this.object = object; this.name = name; this.isFieldReference = true; this.generateJavaScript = function (buffer, scope) { this.object.generateJavaScript(buffer, scope); buffer.write('.'); buffer.write(concatName(this.name)); }; this.generateJavaScriptTarget = this.generateJavaScript; }); var hasScope = function (s) { if (!s) { console.log('---------------- NO SCOPE! -----------------'); throw new Error('no scope'); } }; var Statements = function (statements) { this.statements = statements; this.generateStatements = function (statements, buffer, scope) { hasScope(scope); var namesDefined = _(this.statements).chain().reduce(function (list, statement) { var defs = statement.definitions(scope); return list.concat(defs); }, []).map(function (name) { return concatName(name); }).filter(function (name) { if (!scope.isDefined(name)) { scope.define(name); return true; } else { return false; } }).value(); if (namesDefined.length > 0) { buffer.write ('var '); writeToBufferWithDelimiter(namesDefined, ',', buffer, scope, function (item, b) { b.write(item); }); buffer.write(';'); } _(statements).each(function (statement) { statement.generateJavaScriptStatement(buffer, scope); }); }; this.generateJavaScript = function (buffer, scope) { this.generateStatements(this.statements, buffer, scope); }; this.generateJavaScriptReturn = function (buffer, scope) { if (this.statements.length > 0) { this.generateStatements(this.statements.slice(0, this.statements.length - 1), buffer, scope); this.statements[this.statements.length - 1].generateJavaScriptReturn(buffer, scope); } }; this.definitions = function(scope) { return _(statements).reduce(function (list, statement) { var defs = statement.definitions(scope); return list.concat(defs); }, []); }; this.generateJavaScriptStatement = this.generateJavaScript; }; expressionTerm('module', function (statements) { this.statements = statements; this.generateJavaScript = function (buffer, scope) { functionCall(subExpression(block([], this.statements, true))).generateJavaScript(buffer, new Scope()); }; }); var UniqueNames = function() { var unique = 1; this.generateName = function(name) { return 'gen' + unique++ + '_' + name; }; }; var Scope = exports.Scope = function (parentScope, uniqueNames) { var uniqueNames = uniqueNames || new UniqueNames(); var variables = {}; this.define = function (name) { variables[name] = true; }; this.generateVariable = function(name) { return uniqueNames.generateName(name); }; this.isDefined = function (name) { return variables[name] || (parentScope && parentScope.isDefined(name)); }; this.subScope = function () { return new Scope(this, uniqueNames); }; }; var statements = exports.statements = function (s) { return new Statements(s); }; var extractName = function (terminals) { return _(terminals).filter(function (terminal) { return terminal.identifier; }).map(function (identifier) { return identifier.identifier; }); }; var definition = expressionTerm('definition', function (target, source) { this.target = target; this.source = source; this.isDefinition = true; this.generateJavaScript = function (buffer, scope) { target.generateJavaScriptTarget(buffer, scope); buffer.write('='); source.generateJavaScript(buffer, scope); }; this.definitions = function (scope) { var defs = []; var t = target.definitionName(scope); if (t) { defs.push(t); } var s = this.source.definitions(scope); defs = defs.concat(s); return defs; }; addWalker(this, 'target', 'source'); }); expressionTerm('basicExpression', function(terminals) { var isVariableExpression; this.terminals = terminals; this.isVariableExpression = function () { return _.isUndefined(isVariableExpression)? (isVariableExpression = _(this.terminals).all(function (terminal) { return terminal.identifier; })): isVariableExpression; }; this.variable = function () { return variable(this.name()); }; this.name = function() { return extractName(this.terminals); }; this.parameters = function() { return _(this.terminals).filter(function (terminal) { return terminal.isParameter; }); }; this.methodCall = function(expression) { this.buildBlocks(); var name = this.name(); var hasName = name.length > 0; var args = this.arguments(); var hasArgs = args.length > 0 || this.isNoArgumentFunctionCall(); if (hasName && !hasArgs) { return fieldReference(expression, name); } if (hasName && hasArgs) { return methodCall(expression, name, args); } if (!hasName && hasArgs) { if (args.length == 1) { return indexer(expression, args[0]); } else { return semanticFailure(args.slice(1), 'index only requires one argument, these are not required') } } return semanticFailure([this], "basic expression with no name and no arguments, how'd that happen?"); }; this.expression = function () { this.buildBlocks(); var terminals = this.terminals; var name = this.name(); if (name.length == 0 && terminals.length > 1) { return functionCall(terminals[0], terminals.splice(1)); } var createMacro = macros.findMacro(name); if (createMacro) { return createMacro(this); } if (this.isVariableExpression()) { return this.variable(); } if (this.isTerminalExpression()) { return this.terminal(); } var isNoArgCall = this.isNoArgumentFunctionCall(); var arguments = this.arguments(); if (isNoArgCall && arguments.length > 0) { return semanticFailure([this], "this function has arguments and an exclaimation mark (implying no arguments)"); } return functionCall(variable(name), arguments); }; this.hashEntry = function() { this.buildBlocks(); var args = this.arguments(); var name = this.name(); if (name.length > 0 && args.length == 1) { return hashEntry(name, args[0]); } if (name.length > 0 && args.length == 0) { return hashEntry(name, boolean(true)); } if (name.length == 0 && args.length == 2 && args[0].isString) { return hashEntry([args[0].string], args[1]); } }; this.makeSourceWithParameters = function(source) { var params = this.parameters(); if (params.length > 0) { if (!source.isBlock) { return block(params, source); } else { source.parameters = params; return source; } } else { return source; } }; this.definitionTarget = function (source) { var name = this.name(); var arguments = this.arguments(); if (arguments.length > 0) { return semanticFailure(arguments, 'these arguments cannot be used in definitions'); } if (name.length > 0) { return definition(variable(this.name()), this.makeSourceWithParameters(source)); } else { return semanticFailure(this.terminals, 'no name for definition'); } }; this.hasNameAndNoArguments = function() { return (this.name().length > 0) && (this.arguments().length == 0); }; this.objectDefinitionTarget = function(expression, source) { if (this.hasNameAndNoArguments()) { return definition(fieldReference(expression, this.name()), this.makeSourceWithParameters(source)); } else if (this.isTerminalExpression()) { return definition(indexer(expression, this.terminal()), source); } else { throw parseError(this, "didn't expect expression here"); } }; this.isTerminalExpression = function () { return this.terminals.length == 1; }; this.terminal = function () { return this.terminals[0]; }; this.isNoArgumentFunctionCall = function() { return this.terminals[this.terminals.length - 1].noArgumentFunctionCallSuffix; }; this.arguments = function() { return _(this.terminals).filter(function (terminal) { return !terminal.identifier && !terminal.noArgumentFunctionCallSuffix && !terminal.isParameter; }); }; this.buildBlocks = function () { var parameters = []; _(this.terminals).each(function (terminal) { if (terminal.isParameter) { parameters.push(terminal); } else if (terminal.body) { terminal.parameters = parameters; parameters = []; } }); this.terminals = _(this.terminals).filter(function(terminal) { return !terminal.isParameter; }); }; }); var MacroDirectory = exports.MacroDirectory = function () { var nameTreeRoot = {}; this.addMacro = function(name, createMacro) { var nameTree = nameTreeRoot; _(name).each(function(nameSegment) { if (!nameTree[nameSegment]) { nameTree = nameTree[nameSegment] = {}; } else { nameTree = nameTree[nameSegment]; } }); nameTree['create macro'] = createMacro; }; this.findMacro = function(name) { var nameTree = nameTreeRoot; _(name).each(function(nameSegment) { if (nameTree) { nameTree = nameTree[nameSegment]; } }); if (nameTree) { return nameTree['create macro']; } }; }; var macros = exports.macros = new MacroDirectory(); var list = expressionTerm('list', function(items) { this.list = items; this.generateJavaScript = function (buffer, scope) { buffer.write('['); writeToBufferWithDelimiter(this.list, ',', buffer, scope); buffer.write(']'); }; }); var hash = expressionTerm('hash', function(entries) { this.isHash = true; this.entries = entries; this.generateJavaScript = function(buffer, scope) { buffer.write('{'); writeToBufferWithDelimiter(this.entries, ',', buffer, scope, function (item, b) { item.generateJavaScriptHashEntry(b, scope); }); buffer.write('}'); }; }); var isLegalJavaScriptIdentifier = function(id) { return /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(id); }; var hashEntry = expressionTerm('hashEntry', function(field, value) { this.field = field; this.value = value; this.generateJavaScriptHashEntry = function(buffer, scope) { var f = concatName(this.field); if (isLegalJavaScriptIdentifier(f)) { buffer.write(f); } else { buffer.write(formatJavaScriptString(f)); } buffer.write(':'); this.value.generateJavaScript(buffer, scope); }; }); var ifExpression = expressionTerm('ifExpression', function (condition, then, _else) { this.isIfExpression = true; this.condition = condition; this.then = then; this._else = _else; this.generateJavaScriptStatement = function (buffer, scope) { buffer.write('if('); this.condition.generateJavaScript(buffer, scope); buffer.write('){'); this.then.generateJavaScript(buffer, scope); buffer.write('}'); if (this._else) { buffer.write('else{'); this._else.generateJavaScript(buffer, scope); buffer.write('}'); } }; this.generateJavaScript = function (buffer, scope) { functionCall(subExpression(block([], statements([this]))), []).generateJavaScript(buffer, scope); }; this.generateJavaScriptReturn = function (buffer, scope) { buffer.write('if('); this.condition.generateJavaScript(buffer, scope); buffer.write('){'); this.then.generateJavaScriptReturn(buffer, scope); buffer.write('}'); if (this._else) { buffer.write('else{'); this._else.generateJavaScriptReturn(buffer, scope); buffer.write('}'); } }; }); var createIfExpression = function(expression) { var args = expression.arguments(); var _else = args[2]; var then = args[1]; return ifExpression(args[0], then.body, _else? _else.body: undefined); }; macros.addMacro(['if'], createIfExpression); macros.addMacro(['if', 'else'], createIfExpression); var newOperator = expressionTerm('newOperator', function(functionCall) { this.isNewOperator = true; this.functionCall = functionCall; this.generateJavaScript = function(buffer, scope) { buffer.write('new '); this.functionCall.generateJavaScript(buffer, scope); } }); macros.addMacro(['new'], function(basicExpression) { var args = basicExpression.arguments(); return newOperator(args[0]); }); var generatedVariable = expressionTerm('generatedVariable', function(name) { this.name = name; var genVar; this.generatedName = function(scope) { if (!genVar) { genVar = scope.generateVariable(concatName(this.name)); } return genVar; }; this.generateJavaScript = function(buffer, scope) { buffer.write(this.generatedName(scope)); }; this.generateJavaScriptTarget = this.generateJavaScript; this.definitionName = function(scope) { var n = this.generatedName(scope); return [n]; }; }); var postIncrement = expressionTerm('postIncrement', function(expr) { this.expression = expr; this.generateJavaScript = function(buffer, scope) { this.expression.generateJavaScript(buffer, scope); buffer.write('++'); }; }); var forEach = expressionTerm('forEach', function(collection, itemVariable, stmts) { var itemsVar = generatedVariable(['items']); var indexVar = generatedVariable(['i']); var s = [definition(variable(itemVariable), indexer(itemsVar, indexVar))]; s.push.apply(s, stmts.statements); var statementsWithItemAssignment = statements(s); var init = definition(indexVar, integer(0)); var test = operator('<', [indexVar, fieldReference(itemsVar, ['length'])]); var incr = postIncrement(indexVar); return statements([ definition(itemsVar, collection), forStatement(init, test, incr, statementsWithItemAssignment) ]); }); macros.addMacro(['for', 'each', 'in', 'do'], function(basicExpression) { var args = basicExpression.arguments(); var collection = args[0]; var block = args[1]; var itemVariable = block.parameters[0].parameter; return forEach(collection, itemVariable, block.body); }); var forStatement = expressionTerm('forStatement', function(init, test, incr, stmts) { this.isFor = true; this.initialization = init; this.test = test; this.increment = incr; this.statements = stmts; this.indexVariable = init.target; this.generateJavaScript = function(buffer, scope) { buffer.write('for('); this.initialization.generateJavaScript(buffer, scope); buffer.write(';'); this.test.generateJavaScript(buffer, scope); buffer.write(';'); this.increment.generateJavaScript(buffer, scope); buffer.write('){'); this.statements.generateJavaScript(buffer, scope); buffer.write('}'); }; this.generateJavaScriptStatement = this.generateJavaScript; this.generateJavaScriptReturn = this.generateJavaScript; this.definitions = function(scope) { var defs = []; var indexName = this.indexVariable.definitionName(scope); if (indexName) { defs.push(indexName); } return defs.concat(stmts.definitions(scope)); }; }); macros.addMacro(['for'], function(basicExpression) { var args = basicExpression.arguments(); var init = args[0].body.statements[0]; var test = args[1].body.statements[0]; var incr = args[2].body.statements[0]; return forStatement(init, test, incr, args[3].body); }); var whileStatement = expressionTerm('whileStatement', function(test, statements) { this.isWhile = true; this.test = test; this.statements = statements; this.generateJavaScript = function(buffer, scope) { buffer.write('while('); this.test.generateJavaScript(buffer, scope); buffer.write('){'); this.statements.generateJavaScript(buffer, scope); buffer.write('}'); }; this.generateJavaScriptReturn = this.generateJavaScript; this.generateJavaScriptStatement = this.generateJavaScript; }); macros.addMacro(['while'], function(basicExpression) { var args = basicExpression.arguments(); var test = args[0].body.statements[0]; var statements = args[1].body; return whileStatement(test, statements); }); var subExpression = expressionTerm('subExpression', function (expr) { this.expression = expr; this.generateJavaScript = function(buffer, scope) { buffer.write('('); this.expression.generateJavaScript(buffer, scope); buffer.write(')'); }; }); var operator = expressionTerm('operator', function (op, args) { this.operator = op; this.arguments = args; this.generateJavaScript = function(buffer, scope) { buffer.write('('); if (this.arguments.length == 1) { buffer.write(op); this.arguments[0].generateJavaScript(buffer, scope); } else { this.arguments[0].generateJavaScript(buffer, scope); buffer.write(op); this.arguments[1].generateJavaScript(buffer, scope); } buffer.write(')'); }; }); var createOperator = function(expr) { return operator(expr.name()[0], expr.arguments()); }; _.each(['+', '*', '/', '-', '>=', '==', '!=', '===', '!==', '<=', '<', '>'], function(op) { macros.addMacro([op], createOperator); }); macros.addMacro(['and'], function (expr) { return operator('&&', expr.arguments()); }); macros.addMacro(['or'], function (expr) { return operator('||', expr.arguments()); }); macros.addMacro(['not'], function (expr) { return operator('!', expr.arguments()); }); var returnStatement = expressionTerm('returnStatement', function(expr) { this.isReturn = true; this.expression = expr; this.generateJavaScriptStatement = function(buffer, scope) { this.expression.generateJavaScriptReturn(buffer, scope); }; this.generateJavaScriptReturn = this.generateJavaScriptStatement; }); macros.addMacro(['return'], function(expr) { return returnStatement(expr.arguments()[0]); });
src/lib/codeGenerator.js
var _ = require('underscore'); var parseError = exports.parseError = function (term, message, expected) { expected = expected || []; var e = new Error(message); e.index = term.index; e.context = term.context; e.expected = expected; return e; }; var ExpressionPrototype = new function () { this.generateJavaScriptReturn = function (buffer, scope) { buffer.write('return '); this.generateJavaScript(buffer, scope); buffer.write(';'); }; this.generateJavaScriptStatement = function (buffer, scope) { this.generateJavaScript(buffer, scope); buffer.write(';'); }; this.definitions = function (scope) { return []; }; this.definitionName = function(scope) { } }; var addWalker = function () { var self = arguments[0]; var subtermNames = Array.prototype.splice.call(arguments, 1, arguments.length - 1); self.walk = function (visitor) { visitor(this); for (var n in subtermNames) { var subterm = this[subtermNames[n]]; if (_.isArray(subterm)) { for (var i in subterm) { subterm[i].walk(visitor); } } else { subterm.walk(visitor); } } }; }; var expressionTerm = function (name, constructor) { constructor.prototype = ExpressionPrototype; return exports[name] = function () { var args = arguments; var F = function () { return constructor.apply(this, args); } F.prototype = constructor.prototype; return new F(); }; }; var semanticFailure = expressionTerm('semanticFailure', function(terms, message) { this.isSemanticFailure = true; this.terms = terms; this.message = message; this.generateJavaScript = function(buffer, scope) { throw this; }; this.printError = function(sourceFile) { process.stdout.write(this.message + '\n'); process.stdout.write('\n'); sourceFile.printIndex(this.index); } }); exports.identifier = function (name) { return { identifier: name }; }; var integer = expressionTerm('integer', function (value) { this.integer = value; this.generateJavaScript = function (buffer, scope) { buffer.write(this.integer.toString()); }; }); var boolean = expressionTerm('boolean', function(value) { this.boolean = value; }); var formatJavaScriptString = function(s) { return "'" + s.replace("'", "\\'") + "'"; }; expressionTerm('string', function(value) { this.isString = true; this.string = value; this.generateJavaScript = function(buffer, scope) { buffer.write(formatJavaScriptString(this.string)); }; }); expressionTerm('float', function (value) { this.float = value; this.generateJavaScript = function (buffer, scope) { buffer.write(this.float.toString()); }; }); var variable = expressionTerm('variable', function (name) { this.variable = name; this.isVariable = true; this.generateJavaScript = function (buffer, scope) { buffer.write(concatName(this.variable)); }; this.generateJavaScriptTarget = this.generateJavaScript; this.definitionName = function(scope) { return this.variable; }; addWalker(this); }); var parameter = expressionTerm('parameter', function (name) { this.parameter = name; this.isParameter = true; this.generateJavaScript = function (buffer, scope) { buffer.write(concatName(this.parameter)); }; }); var concatName = function (nameSegments) { var name = nameSegments[0]; for (var n = 1; n < nameSegments.length; n++) { var segment = nameSegments[n]; name += segment[0].toUpperCase() + segment.substring(1); } return name; }; var functionCall = expressionTerm('functionCall', function (fun, arguments) { this.function = fun; this.arguments = arguments; this.isFunctionCall = true; this.generateJavaScript = function (buffer, scope) { fun.generateJavaScript(buffer, scope); buffer.write('('); var first = true; _(this.arguments).each(function (arg) { if (!first) { buffer.write(','); } first = false; arg.generateJavaScript(buffer, scope); }); buffer.write(')'); }; }); var block = expressionTerm('block', function (parameters, body, dontReturnLastStatement) { this.body = body; this.isBlock = true; this.dontReturnLastStatement = dontReturnLastStatement; this.parameters = parameters; this.generateJavaScript = function (buffer, scope) { buffer.write('function('); var first = true; _(this.parameters).each(function (parameter) { if (!first) { buffer.write(','); } first = false; parameter.generateJavaScript(buffer, scope); }); buffer.write('){'); if (this.dontReturnLastStatement) { body.generateJavaScript(buffer, scope.subScope()); } else { body.generateJavaScriptReturn(buffer, scope.subScope()); } buffer.write('}'); }; }); var writeToBufferWithDelimiter = function (array, delimiter, buffer, scope, writer) { writer = writer || function (item, buffer) { item.generateJavaScript(buffer, scope); }; var first = true; _(array).each(function (item) { if (!first) { buffer.write(delimiter); } first = false; writer(item, buffer); }); }; var methodCall = expressionTerm('methodCall', function (object, name, arguments) { this.object = object; this.name = name; this.arguments = arguments; this.generateJavaScript = function (buffer, scope) { this.object.generateJavaScript(buffer, scope); buffer.write('.'); buffer.write(concatName(this.name)); buffer.write('('); writeToBufferWithDelimiter(this.arguments, ',', buffer, scope); buffer.write(')'); }; addWalker(this, 'object', 'arguments'); }); var indexer = expressionTerm('indexer', function (object, indexer) { this.object = object; this.indexer = indexer; this.isIndexer = true; this.generateJavaScript = function (buffer, scope) { this.object.generateJavaScript(buffer, scope); buffer.write('['); this.indexer.generateJavaScript(buffer, scope); buffer.write(']'); }; this.generateJavaScriptTarget = this.generateJavaScript; }); var fieldReference = expressionTerm('fieldReference', function (object, name) { this.object = object; this.name = name; this.isFieldReference = true; this.generateJavaScript = function (buffer, scope) { this.object.generateJavaScript(buffer, scope); buffer.write('.'); buffer.write(concatName(this.name)); }; this.generateJavaScriptTarget = this.generateJavaScript; }); var hasScope = function (s) { if (!s) { console.log('---------------- NO SCOPE! -----------------'); throw new Error('no scope'); } }; var Statements = function (statements) { this.statements = statements; this.generateStatements = function (statements, buffer, scope) { hasScope(scope); var namesDefined = _(this.statements).chain().reduce(function (list, statement) { var defs = statement.definitions(scope); return list.concat(defs); }, []).map(function (name) { return concatName(name); }).filter(function (name) { if (!scope.isDefined(name)) { scope.define(name); return true; } else { return false; } }).value(); if (namesDefined.length > 0) { buffer.write ('var '); writeToBufferWithDelimiter(namesDefined, ',', buffer, scope, function (item, b) { b.write(item); }); buffer.write(';'); } _(statements).each(function (statement) { statement.generateJavaScriptStatement(buffer, scope); }); }; this.generateJavaScript = function (buffer, scope) { this.generateStatements(this.statements, buffer, scope); }; this.generateJavaScriptReturn = function (buffer, scope) { if (this.statements.length > 0) { this.generateStatements(this.statements.slice(0, this.statements.length - 1), buffer, scope); this.statements[this.statements.length - 1].generateJavaScriptReturn(buffer, scope); } }; this.definitions = function(scope) { return _(statements).reduce(function (list, statement) { var defs = statement.definitions(scope); return list.concat(defs); }, []); }; this.generateJavaScriptStatement = this.generateJavaScript; }; expressionTerm('module', function (statements) { this.statements = statements; this.generateJavaScript = function (buffer, scope) { functionCall(subExpression(block([], this.statements, true))).generateJavaScript(buffer, new Scope()); }; }); var UniqueNames = function() { var unique = 1; this.generateName = function(name) { return 'gen' + unique++ + '_' + name; }; }; var Scope = exports.Scope = function (parentScope, uniqueNames) { var uniqueNames = uniqueNames || new UniqueNames(); var variables = {}; this.define = function (name) { variables[name] = true; }; this.generateVariable = function(name) { return uniqueNames.generateName(name); }; this.isDefined = function (name) { return variables[name] || (parentScope && parentScope.isDefined(name)); }; this.subScope = function () { return new Scope(this, uniqueNames); }; }; var statements = exports.statements = function (s) { return new Statements(s); }; var extractName = function (terminals) { return _(terminals).filter(function (terminal) { return terminal.identifier; }).map(function (identifier) { return identifier.identifier; }); }; var definition = expressionTerm('definition', function (target, source) { this.target = target; this.source = source; this.isDefinition = true; this.generateJavaScript = function (buffer, scope) { target.generateJavaScriptTarget(buffer, scope); buffer.write('='); source.generateJavaScript(buffer, scope); }; this.definitions = function (scope) { var defs = []; var t = target.definitionName(scope); if (t) { defs.push(t); } var s = this.source.definitions(scope); defs = defs.concat(s); return defs; }; addWalker(this, 'target', 'source'); }); expressionTerm('basicExpression', function(terminals) { var isVariableExpression; this.terminals = terminals; this.isVariableExpression = function () { return _.isUndefined(isVariableExpression)? (isVariableExpression = _(this.terminals).all(function (terminal) { return terminal.identifier; })): isVariableExpression; }; this.variable = function () { return variable(this.name()); }; this.name = function() { return extractName(this.terminals); }; this.parameters = function() { return _(this.terminals).filter(function (terminal) { return terminal.isParameter; }); }; this.methodCall = function(expression) { this.buildBlocks(); var name = this.name(); var hasName = name.length > 0; var args = this.arguments(); var hasArgs = args.length > 0 || this.isNoArgumentFunctionCall(); if (hasName && !hasArgs) { return fieldReference(expression, name); } if (hasName && hasArgs) { return methodCall(expression, name, args); } if (!hasName && hasArgs) { if (args.length == 1) { return indexer(expression, args[0]); } else { return semanticFailure(args.slice(1), 'index only requires one argument, these are not required') } } return semanticFailure([this], "basic expression with no name and no arguments, how'd that happen?"); }; this.expression = function () { this.buildBlocks(); var terminals = this.terminals; var name = this.name(); if (name.length == 0 && terminals.length > 1) { return functionCall(terminals[0], terminals.splice(1)); } var createMacro = macros.findMacro(name); if (createMacro) { return createMacro(this); } if (this.isVariableExpression()) { return this.variable(); } if (this.isTerminalExpression()) { return this.terminal(); } var isNoArgCall = this.isNoArgumentFunctionCall(); var arguments = this.arguments(); if (isNoArgCall && arguments.length > 0) { return semanticFailure([this], "this function has arguments and an exclaimation mark (implying no arguments)"); } return functionCall(variable(name), arguments); }; this.hashEntry = function() { this.buildBlocks(); var args = this.arguments(); var name = this.name(); if (name.length > 0 && args.length == 1) { return hashEntry(name, args[0]); } if (name.length > 0 && args.length == 0) { return hashEntry(name, boolean(true)); } if (name.length == 0 && args.length == 2 && args[0].isString) { return hashEntry([args[0].string], args[1]); } }; this.makeSourceWithParameters = function(source) { var params = this.parameters(); if (params.length > 0) { if (!source.isBlock) { return block(params, source); } else { source.parameters = params; return source; } } else { return source; } }; this.definitionTarget = function (source) { var name = this.name(); var arguments = this.arguments(); if (arguments.length > 0) { return semanticFailure(arguments, 'these arguments cannot be used in definitions'); } if (name.length > 0) { return definition(variable(this.name()), this.makeSourceWithParameters(source)); } else { return semanticFailure(this.terminals, 'no name for definition'); } }; this.hasNameAndNoArguments = function() { return (this.name().length > 0) && (this.arguments().length == 0); }; this.objectDefinitionTarget = function(expression, source) { if (this.hasNameAndNoArguments()) { return definition(fieldReference(expression, this.name()), this.makeSourceWithParameters(source)); } else if (this.isTerminalExpression()) { return definition(indexer(expression, this.terminal()), source); } else { throw parseError(this, "didn't expect expression here"); } }; this.isTerminalExpression = function () { return this.terminals.length == 1; }; this.terminal = function () { return this.terminals[0]; }; this.isNoArgumentFunctionCall = function() { return this.terminals[this.terminals.length - 1].noArgumentFunctionCallSuffix; }; this.arguments = function() { return _(this.terminals).filter(function (terminal) { return !terminal.identifier && !terminal.noArgumentFunctionCallSuffix && !terminal.isParameter; }); }; this.buildBlocks = function () { var parameters = []; _(this.terminals).each(function (terminal) { if (terminal.isParameter) { parameters.push(terminal); } else if (terminal.body) { terminal.parameters = parameters; parameters = []; } }); this.terminals = _(this.terminals).filter(function(terminal) { return !terminal.isParameter; }); }; }); var MacroDirectory = exports.MacroDirectory = function () { var nameTreeRoot = {}; this.addMacro = function(name, createMacro) { var nameTree = nameTreeRoot; _(name).each(function(nameSegment) { if (!nameTree[nameSegment]) { nameTree = nameTree[nameSegment] = {}; } else { nameTree = nameTree[nameSegment]; } }); nameTree['create macro'] = createMacro; }; this.findMacro = function(name) { var nameTree = nameTreeRoot; _(name).each(function(nameSegment) { if (nameTree) { nameTree = nameTree[nameSegment]; } }); if (nameTree) { return nameTree['create macro']; } }; }; var macros = exports.macros = new MacroDirectory(); var list = expressionTerm('list', function(items) { this.list = items; this.generateJavaScript = function (buffer, scope) { buffer.write('['); writeToBufferWithDelimiter(this.list, ',', buffer, scope); buffer.write(']'); }; }); var hash = expressionTerm('hash', function(entries) { this.isHash = true; this.entries = entries; this.generateJavaScript = function(buffer, scope) { buffer.write('{'); writeToBufferWithDelimiter(this.entries, ',', buffer, scope, function (item, b) { item.generateJavaScriptHashEntry(b, scope); }); buffer.write('}'); }; }); var isLegalJavaScriptIdentifier = function(id) { return /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(id); }; var hashEntry = expressionTerm('hashEntry', function(field, value) { this.field = field; this.value = value; this.generateJavaScriptHashEntry = function(buffer, scope) { var f = concatName(this.field); if (isLegalJavaScriptIdentifier(f)) { buffer.write(f); } else { buffer.write(formatJavaScriptString(f)); } buffer.write(':'); this.value.generateJavaScript(buffer, scope); }; }); var ifExpression = expressionTerm('ifExpression', function (condition, then, _else) { this.isIfExpression = true; this.condition = condition; this.then = then; this._else = _else; this.generateJavaScriptStatement = function (buffer, scope) { buffer.write('if('); this.condition.generateJavaScript(buffer, scope); buffer.write('){'); this.then.generateJavaScript(buffer, scope); buffer.write('}'); if (this._else) { buffer.write('else{'); this._else.generateJavaScript(buffer, scope); buffer.write('}'); } }; this.generateJavaScript = function (buffer, scope) { functionCall(subExpression(block([], statements([this]))), []).generateJavaScript(buffer, scope); }; this.generateJavaScriptReturn = function (buffer, scope) { buffer.write('if('); this.condition.generateJavaScript(buffer, scope); buffer.write('){'); this.then.generateJavaScriptReturn(buffer, scope); buffer.write('}'); if (this._else) { buffer.write('else{'); this._else.generateJavaScriptReturn(buffer, scope); buffer.write('}'); } }; }); var createIfExpression = function(expression) { var args = expression.arguments(); var _else = args[2]; var then = args[1]; return ifExpression(args[0], then.body, _else? _else.body: undefined); }; macros.addMacro(['if'], createIfExpression); macros.addMacro(['if', 'else'], createIfExpression); var newOperator = expressionTerm('newOperator', function(functionCall) { this.isNewOperator = true; this.functionCall = functionCall; this.generateJavaScript = function(buffer, scope) { buffer.write('new '); this.functionCall.generateJavaScript(buffer, scope); } }); macros.addMacro(['new'], function(basicExpression) { var args = basicExpression.arguments(); return newOperator(args[0]); }); var generatedVariable = expressionTerm('generatedVariable', function(name) { this.name = name; var genVar; this.generatedName = function(scope) { if (!genVar) { genVar = scope.generateVariable(concatName(this.name)); } return genVar; }; this.generateJavaScript = function(buffer, scope) { buffer.write(this.generatedName(scope)); }; this.generateJavaScriptTarget = this.generateJavaScript; this.definitionName = function(scope) { var n = this.generatedName(scope); return [n]; }; }); var postIncrement = expressionTerm('postIncrement', function(expr) { this.expression = expr; this.generateJavaScript = function(buffer, scope) { this.expression.generateJavaScript(buffer, scope); buffer.write('++'); }; }); var forEach = expressionTerm('forEach', function(collection, itemVariable, stmts) { var itemsVar = generatedVariable(['items']); var indexVar = generatedVariable(['i']); var s = [definition(variable(itemVariable), indexer(itemsVar, indexVar))]; s.push.apply(s, stmts.statements); var statementsWithItemAssignment = statements(s); var init = definition(indexVar, integer(0)); var test = operator('<', [indexVar, fieldReference(itemsVar, ['length'])]); var incr = postIncrement(indexVar); return statements([ definition(itemsVar, collection), forStatement(init, test, incr, statementsWithItemAssignment) ]); }); macros.addMacro(['for', 'each', 'in', 'do'], function(basicExpression) { var args = basicExpression.arguments(); var collection = args[0]; var block = args[1]; var itemVariable = block.parameters[0].parameter; return forEach(collection, itemVariable, block.body); }); var forStatement = expressionTerm('forStatement', function(init, test, incr, stmts) { this.isFor = true; this.initialization = init; this.test = test; this.increment = incr; this.statements = stmts; this.indexVariable = init.target; this.generateJavaScript = function(buffer, scope) { buffer.write('for('); this.initialization.generateJavaScript(buffer, scope); buffer.write(';'); this.test.generateJavaScript(buffer, scope); buffer.write(';'); this.increment.generateJavaScript(buffer, scope); buffer.write('){'); this.statements.generateJavaScript(buffer, scope); buffer.write('}'); }; this.generateJavaScriptStatement = this.generateJavaScript; this.generateJavaScriptReturn = this.generateJavaScript; this.definitions = function(scope) { var defs = []; var indexName = this.indexVariable.definitionName(scope); if (indexName) { defs.push(indexName); } return defs.concat(stmts.definitions(scope)); }; }); macros.addMacro(['for'], function(basicExpression) { var args = basicExpression.arguments(); var init = args[0].body.statements[0]; var test = args[1].body.statements[0]; var incr = args[2].body.statements[0]; return forStatement(init, test, incr, args[3].body); }); var whileStatement = expressionTerm('whileStatement', function(test, statements) { this.isWhile = true; this.test = test; this.statements = statements; this.generateJavaScript = function(buffer, scope) { buffer.write('while('); this.test.generateJavaScript(buffer, scope); buffer.write('){'); this.statements.generateJavaScript(buffer, scope); buffer.write('}'); }; this.generateJavaScriptReturn = this.generateJavaScript; this.generateJavaScriptStatement = this.generateJavaScript; }); macros.addMacro(['while'], function(basicExpression) { var args = basicExpression.arguments(); var test = args[0].body.statements[0]; var statements = args[1].body; return whileStatement(test, statements); }); var subExpression = expressionTerm('subExpression', function (expr) { this.expression = expr; this.generateJavaScript = function(buffer, scope) { buffer.write('('); this.expression.generateJavaScript(buffer, scope); buffer.write(')'); }; }); var operator = expressionTerm('operator', function (op, args) { this.operator = op; this.arguments = args; this.generateJavaScript = function(buffer, scope) { buffer.write('('); if (this.arguments.length == 1) { buffer.write(op); this.arguments[0].generateJavaScript(buffer, scope); } else { this.arguments[0].generateJavaScript(buffer, scope); buffer.write(op); this.arguments[1].generateJavaScript(buffer, scope); } buffer.write(')'); }; }); var createOperator = function(expr) { return operator(expr.name()[0], expr.arguments()); }; _.each(['+', '*', '/', '-', '>=', '==', '!=', '===', '!==', '<=', '<', '>'], function(op) { macros.addMacro([op], createOperator); }); macros.addMacro(['and'], function (expr) { return operator('&&', expr.arguments()); }); macros.addMacro(['or'], function (expr) { return operator('||', expr.arguments()); }); macros.addMacro(['not'], function (expr) { return operator('!', expr.arguments()); }); var returnStatement = expressionTerm('returnStatement', function(expr) { this.isReturn = true; this.expression = expr; this.generateJavaScriptStatement = function(buffer, scope) { this.expression.generateJavaScriptReturn(buffer, scope); }; this.generateJavaScriptReturn = this.generateJavaScriptStatement; }); macros.addMacro(['return'], function(expr) { return returnStatement(expr.arguments()[0]); });
generating booleans
src/lib/codeGenerator.js
generating booleans
<ide><path>rc/lib/codeGenerator.js <ide> <ide> var boolean = expressionTerm('boolean', function(value) { <ide> this.boolean = value; <add> this.generateJavaScript = function (buffer, scope) { <add> if (this.boolean) { <add> buffer.write('true'); <add> } else { <add> buffer.write('false'); <add> } <add> }; <ide> }); <ide> <ide> var formatJavaScriptString = function(s) {
Java
mpl-2.0
2724dca9fb607e76b6abdd956181feaa93263a1e
0
msteinhoff/hello-world
84550780-cb8e-11e5-a707-00264a111016
src/main/java/HelloWorld.java
844aa94f-cb8e-11e5-b94b-00264a111016
NO CHANGES
src/main/java/HelloWorld.java
NO CHANGES
<ide><path>rc/main/java/HelloWorld.java <del>844aa94f-cb8e-11e5-b94b-00264a111016 <add>84550780-cb8e-11e5-a707-00264a111016
Java
apache-2.0
77cfb080a0c88bed86fad8dfacef72fdaa792ba2
0
juankysoriano/material-painter
package com.novoda.materialpainter; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.ParcelFileDescriptor; import android.support.v7.app.ActionBarActivity; import android.support.v7.graphics.Palette; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.animation.OvershootInterpolator; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.novoda.materialpainter.view.PaletteView; import com.novoda.notils.caster.Views; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.IOException; public class PainterActivity extends ActionBarActivity { private static final int READ_REQUEST_CODE = 42; private static final int ANIMATION_START_DELAY = 300; private static final int ANIMATION_DURATION = 400; private static final float TENSION = 1.f; private TextView startingText; private PaletteView paletteView; private ImageButton selectImage; private ImageView imageView; private Toolbar toolbar; private int fabHideTranslationY; private int toolbarHideTranslationY; private boolean viewsVisible = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_painter); toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar); setSupportActionBar(toolbar); fabHideTranslationY = 2 * getResources().getDimensionPixelOffset(R.dimen.fab_min_size); toolbarHideTranslationY = -2 * getResources().getDimensionPixelOffset(R.dimen.toolbar_min_size); initViews(); setListeners(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent resultData) { if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) { Uri uri; if (resultData != null) { uri = resultData.getData(); showImage(uri); } } } private void initViews() { startingText = Views.findById(this, R.id.starting_text); paletteView = Views.findById(this, R.id.palette); imageView = Views.findById(this, R.id.show_image); selectImage = Views.findById(this, R.id.fab_select_image); } private void setListeners() { imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (viewsVisible) { hideViews(); } else { showViews(); } } }); selectImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { runTranslateAnimationWithEndAction(selectImage, fabHideTranslationY, performImageSearchRunnable); } }); } private Runnable performImageSearchRunnable = new Runnable() { @Override public void run() { performFileSearch(); } }; public void performFileSearch() { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); startActivityForResult(intent, READ_REQUEST_CODE); } private void showImage(Uri uri) { try { Bitmap image = parcelImage(uri); generatePalette(image); hideViews(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private Bitmap parcelImage(Uri uri) throws IOException { ParcelFileDescriptor parcelFileDescriptor; parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); imageView.setImageBitmap(image); parcelFileDescriptor.close(); return image; } private void generatePalette(Bitmap image) { Palette.generateAsync(image, new Palette.PaletteAsyncListener() { public void onGenerated(Palette palette) { if (palette != null) { paletteView.updateWith(palette); } } }); } private void showViews() { runTranslateAnimation(selectImage, 0); runTranslateAnimation(toolbar, 0); viewsVisible = true; } private void hideViews() { runTranslateAnimation(selectImage, fabHideTranslationY); runTranslateAnimation(toolbar, toolbarHideTranslationY); startingText.setVisibility(View.GONE); viewsVisible = false; } private void runTranslateAnimation(View view, int translateY) { view.animate() .translationY(translateY) .setInterpolator(new OvershootInterpolator(TENSION)) .setStartDelay(ANIMATION_START_DELAY) .setDuration(ANIMATION_DURATION) .start(); } private void runTranslateAnimationWithEndAction(View view, int translateY, Runnable runnable) { view.animate() .translationY(translateY) .setInterpolator(new OvershootInterpolator(TENSION)) .setStartDelay(ANIMATION_START_DELAY) .setDuration(ANIMATION_DURATION) .withEndAction(runnable) .start(); } }
app/src/main/java/com/novoda/materialpainter/PainterActivity.java
package com.novoda.materialpainter; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.ParcelFileDescriptor; import android.support.v7.app.ActionBarActivity; import android.support.v7.graphics.Palette; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.animation.OvershootInterpolator; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.novoda.materialpainter.view.PaletteView; import com.novoda.notils.caster.Views; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.IOException; public class PainterActivity extends ActionBarActivity { private static final int READ_REQUEST_CODE = 42; private TextView startingText; private PaletteView paletteView; private ImageButton selectImage; private ImageView imageView; private Toolbar toolbar; private boolean viewsVisible = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_painter); toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar); setSupportActionBar(toolbar); initViews(); setListeners(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent resultData) { if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) { Uri uri; if (resultData != null) { uri = resultData.getData(); showImage(uri); } } } private void initViews() { startingText = Views.findById(this, R.id.starting_text); paletteView = Views.findById(this, R.id.palette); imageView = Views.findById(this, R.id.show_image); selectImage = Views.findById(this, R.id.fab_select_image); } private void setListeners() { imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (viewsVisible) { hideViews(); } else { showViews(); } } }); selectImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { performFileSearch(); } }); } public void performFileSearch() { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); startActivityForResult(intent, READ_REQUEST_CODE); } private void showImage(Uri uri) { try { Bitmap image = parcelImage(uri); generatePalette(image); hideViews(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private Bitmap parcelImage(Uri uri) throws IOException { ParcelFileDescriptor parcelFileDescriptor; parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); imageView.setImageBitmap(image); parcelFileDescriptor.close(); return image; } private void generatePalette(Bitmap image) { Palette.generateAsync(image, new Palette.PaletteAsyncListener() { public void onGenerated(Palette palette) { if (palette != null) { paletteView.updateWith(palette); } } }); } private void showViews() { runTranslateAnimation(selectImage, 0); runTranslateAnimation(toolbar, 0); viewsVisible = true; } private void hideViews() { runTranslateAnimation(selectImage, 2 * getResources().getDimensionPixelOffset(R.dimen.fab_min_size)); runTranslateAnimation(toolbar, -2 * getResources().getDimensionPixelOffset(R.dimen.toolbar_min_size)); startingText.setVisibility(View.GONE); viewsVisible = false; } private void runTranslateAnimation(View view, int translateY) { view.animate() .translationY(translateY) .setInterpolator(new OvershootInterpolator(1.f)) .setStartDelay(300) .setDuration(400) .start(); } }
had to make that animation
app/src/main/java/com/novoda/materialpainter/PainterActivity.java
had to make that animation
<ide><path>pp/src/main/java/com/novoda/materialpainter/PainterActivity.java <ide> public class PainterActivity extends ActionBarActivity { <ide> <ide> private static final int READ_REQUEST_CODE = 42; <add> private static final int ANIMATION_START_DELAY = 300; <add> private static final int ANIMATION_DURATION = 400; <add> private static final float TENSION = 1.f; <ide> <ide> private TextView startingText; <ide> private PaletteView paletteView; <ide> private ImageButton selectImage; <ide> private ImageView imageView; <ide> private Toolbar toolbar; <add> <add> private int fabHideTranslationY; <add> private int toolbarHideTranslationY; <ide> <ide> private boolean viewsVisible = false; <ide> <ide> <ide> toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar); <ide> setSupportActionBar(toolbar); <add> <add> fabHideTranslationY = 2 * getResources().getDimensionPixelOffset(R.dimen.fab_min_size); <add> toolbarHideTranslationY = -2 * getResources().getDimensionPixelOffset(R.dimen.toolbar_min_size); <ide> <ide> initViews(); <ide> setListeners(); <ide> selectImage.setOnClickListener(new View.OnClickListener() { <ide> @Override <ide> public void onClick(View v) { <del> performFileSearch(); <add> runTranslateAnimationWithEndAction(selectImage, fabHideTranslationY, performImageSearchRunnable); <ide> } <ide> }); <ide> } <add> <add> private Runnable performImageSearchRunnable = <add> new Runnable() { <add> @Override <add> public void run() { <add> performFileSearch(); <add> } <add> }; <ide> <ide> public void performFileSearch() { <ide> Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); <ide> } <ide> <ide> private void hideViews() { <del> runTranslateAnimation(selectImage, 2 * getResources().getDimensionPixelOffset(R.dimen.fab_min_size)); <del> runTranslateAnimation(toolbar, -2 * getResources().getDimensionPixelOffset(R.dimen.toolbar_min_size)); <add> runTranslateAnimation(selectImage, fabHideTranslationY); <add> runTranslateAnimation(toolbar, toolbarHideTranslationY); <ide> startingText.setVisibility(View.GONE); <ide> viewsVisible = false; <ide> } <ide> private void runTranslateAnimation(View view, int translateY) { <ide> view.animate() <ide> .translationY(translateY) <del> .setInterpolator(new OvershootInterpolator(1.f)) <del> .setStartDelay(300) <del> .setDuration(400) <add> .setInterpolator(new OvershootInterpolator(TENSION)) <add> .setStartDelay(ANIMATION_START_DELAY) <add> .setDuration(ANIMATION_DURATION) <add> .start(); <add> <add> } <add> <add> private void runTranslateAnimationWithEndAction(View view, int translateY, Runnable runnable) { <add> view.animate() <add> .translationY(translateY) <add> .setInterpolator(new OvershootInterpolator(TENSION)) <add> .setStartDelay(ANIMATION_START_DELAY) <add> .setDuration(ANIMATION_DURATION) <add> .withEndAction(runnable) <ide> .start(); <ide> <ide> }
Java
apache-2.0
34b22e8315fbcd5f980e671c6676a2c19cf1c3c4
0
CMPUT301F15T05/cuddly-quack
package ca.ualberta.cs.swapmyride; import android.test.ActivityInstrumentationTestCase2; import android.test.ApplicationTestCase; /** * Created by carsonmclean on 9/10/15. */ public class OfflineTest extends ActivityInstrumentationTestCase2 { public OfflineTest() {super(MainMenu.class); } // Use Case 28: Add Vehicle Offline public void testAddItemOffline() { //TODO: find how to turn off data //android.turnOffData(); InventoryList inventoryList = new InventoryList(); Vehicle vehicle = new Vehicle(); //list should be empty assertTrue(inventoryList.getList().size() == 0); inventoryList.add(vehicle); //TODO: find how to turn on data //android.turnOnData(); //make sure an vehicle was added assertTrue(inventoryList.size() == 1); //make sure it is the correct vehicle assertTrue(inventoryList.getList().get(0) == vehicle); } // Use Case 29: Make Trades Offline public void testMakeTradesOffline() { //TODO: find how to turn off data //android.turnOffData(); //create users and their inventories User userOne = new User(); User userTwo = new User(); InventoryList userOneInventory = new InventoryList(); InventoryList userTwoInventory = new InventoryList(); //create items and add to inventories Vehicle vehicleOne = new Vehicle(); Vehicle vehicleTwo = new Vehicle(); userOneInventory.add(vehicleOne); //// TODO: Add picture back //vehicleOne.setPhoto(picture); vehicleOne.setName("Cadillac"); vehicleOne.setCategory(VehicleCategory.COUPE); vehicleOne.setQuality(VehicleQuality.GOOD); vehicleOne.setQuantity(1); vehicleOne.setComments("1995 Cadillac"); vehicleOne.setPublic(true); userTwoInventory.add(vehicleTwo); //TODO: Add photo back into test //vehicleTwo.setPhoto(picture); vehicleTwo.setName("Jeep"); vehicleTwo.setCategory(VehicleCategory.SUV); vehicleTwo.setQuality(VehicleQuality.OKAY); vehicleTwo.setQuantity(1); vehicleTwo.setComments("1994 Jeep"); vehicleTwo.setPublic(true); //add new trade, assert that it was created properly TradeList tradeList = new TradeList(); Trade trade = new Trade(userOne, userTwo); trade.addOwnerItem(vehicleOne); trade.addBorrowerItem(vehicleTwo); //TODO: find how to turn off data //android.turnOnData(); assertTrue(tradeList.getTrades().size() == 0); tradeList.add(trade); assertTrue(tradeList.getSize() == 1); assertTrue(tradeList.get(0) == trade); assertTrue(trade.getOwnerItems().get(0).equals(vehicleOne)); assertTrue(trade.getBorrowerItems().get(0).equals(vehicleTwo)); } // Use Case 30: Browse Friends Offline public void testBrowseFriendsOffline() { FriendsList friendsList = new FriendsList(); User userone = new User(); User usertwo = new User(); userone.setUserName("camclean"); usertwo.setUserName("ccdunn"); friendsList.addFriend(userone); friendsList.addFriend(usertwo); ////TODO: find how to turn off data //android.turnOffData(); // Storing the returned User class in variable found User found = friendsList.findUser(userone); // Check if found is equal to what findUser gets assertTrue(found.equals(userone)); //TODO: find how to turn on data //android.turnOnData(); } }
SwapMyRide/app/src/androidTest/java/ca/ualberta/cs/swapmyride/OfflineTest.java
package ca.ualberta.cs.swapmyride; import android.test.ActivityInstrumentationTestCase2; import android.test.ApplicationTestCase; /** * Created by carsonmclean on 9/10/15. */ public class OfflineTest extends ActivityInstrumentationTestCase2 { public OfflineTest() {super(MainMenu.class); } // Use Case 28: Add Vehicle Offline public void testAddItemOffline() { //TODO: find how to turn off data //android.turnOffData(); InventoryList inventoryList = new InventoryList(); Vehicle vehicle = new Vehicle(); //list should be empty assertTrue(inventoryList.getList().size() == 0); inventoryList.add(vehicle); //TODO: find how to turn on data //android.turnOnData(); //make sure an vehicle was added assertTrue(inventoryList.size() == 1); //make sure it is the correct vehicle assertTrue(inventoryList.getList().get(0) == vehicle); } // Use Case 29: Make Trades Offline public void testMakeTradesOffline() { //TODO: find how to turn off data //android.turnOffData(); //create users and their inventories User userOne = new User(); User userTwo = new User(); InventoryList userOneInventory = new InventoryList(); InventoryList userTwoInventory = new InventoryList(); //create items and add to inventories Vehicle vehicleOne = new Vehicle(); Vehicle vehicleTwo = new Vehicle(); userOneInventory.add(vehicleOne); //// TODO: Add picture back //vehicleOne.setPhoto(picture); vehicleOne.setName("Cadillac"); vehicleOne.setCategory(VehicleCategory.COUPE); vehicleOne.setQuality(VehicleQuality.GOOD); vehicleOne.setQuantity(1); vehicleOne.setComments("1995 Cadillac"); vehicleOne.setPublic(true); userTwoInventory.add(vehicleTwo); //TODO: Add photo back into test //vehicleTwo.setPhoto(picture); vehicleTwo.setName("Jeep"); vehicleTwo.setCategory(VehicleCategory.SUV); vehicleTwo.setQuality(VehicleQuality.OKAY); vehicleTwo.setQuantity(1); vehicleTwo.setComments("1994 Jeep"); vehicleTwo.setPublic(true); //add new trade, assert that it was created properly TradeList tradeList = new TradeList(); Trade trade = new Trade(userOne, userTwo); trade.addOwnerItem(vehicleOne); trade.addBorrowerItem(vehicleTwo); //TODO: find how to turn off data //android.turnOnData(); assertTrue(tradeList.getTrades() == null); tradeList.add(trade); assertTrue(tradeList.getSize() == 1); assertTrue(tradeList.get(0) == trade); assertTrue(trade.getOwnerItems().get(0).equals(vehicleOne)); assertTrue(trade.getBorrowerItems().get(0).equals(vehicleTwo)); } // Use Case 30: Browse Friends Offline public void testBrowseFriendsOffline() { FriendsList friendsList = new FriendsList(); User userone = new User(); User usertwo = new User(); userone.setUserName("camclean"); usertwo.setUserName("ccdunn"); friendsList.addFriend(userone); friendsList.addFriend(usertwo); ////TODO: find how to turn off data //android.turnOffData(); // Storing the returned User class in variable found User found = friendsList.findUser(userone); // Check if found is equal to what findUser gets assertTrue(found.equals(userone)); //TODO: find how to turn on data //android.turnOnData(); } }
this should be the last .size() == 0 change
SwapMyRide/app/src/androidTest/java/ca/ualberta/cs/swapmyride/OfflineTest.java
this should be the last .size() == 0 change
<ide><path>wapMyRide/app/src/androidTest/java/ca/ualberta/cs/swapmyride/OfflineTest.java <ide> //TODO: find how to turn off data <ide> //android.turnOnData(); <ide> <del> assertTrue(tradeList.getTrades() == null); <add> assertTrue(tradeList.getTrades().size() == 0); <ide> tradeList.add(trade); <ide> assertTrue(tradeList.getSize() == 1); <ide> assertTrue(tradeList.get(0) == trade);
Java
mit
88570b800a95f1495925cfdf33d64283af5db9c1
0
vtsukur/spring-rest-black-market,vtsukur/spring-rest-black-market,vtsukur/spring-rest-black-market
package org.vtsukur.spring.rest.market.domain.core.ad; import lombok.*; import org.springframework.hateoas.Identifiable; import org.vtsukur.spring.rest.market.domain.core.user.User; import javax.persistence.*; import java.math.BigDecimal; import java.math.BigInteger; import java.time.LocalDateTime; /** * @author volodymyr.tsukur */ @Entity @Data public class Ad implements Identifiable<Long> { @Id @GeneratedValue private Long id; @Column(nullable = false) @Enumerated(EnumType.STRING) private Type type; public enum Type { BUY, SELL } @Column(nullable = false) private BigInteger amount; @Column(nullable = false) @Enumerated(EnumType.STRING) private Currency currency; public enum Currency { USD, EUR } @Column(nullable = false) private BigDecimal rate; @ManyToOne @JoinColumn(nullable = false) private User user; private Location location; @Embeddable @Getter @Setter @NoArgsConstructor @AllArgsConstructor public static class Location { @Column(nullable = false) private String city; private String area; } private String comment; @Lob private LocalDateTime publishedAt; @Column(nullable = false) @Enumerated(EnumType.STRING) private Status status = Status.NEW; public enum Status { NEW, PUBLISHED, EXPIRED } public Ad publish() { if (status == Status.NEW) { publishedAt = LocalDateTime.now(); status = Status.PUBLISHED; } else { throw new InvalidAdStateTransitionException("Ad is already published"); } return this; } public Ad finish() { if (status == Status.PUBLISHED) { status = Status.EXPIRED; } else { throw new InvalidAdStateTransitionException( "Ad can be finished only when it is in the " + Status.PUBLISHED + " state"); } return this; } }
src/main/java/org/vtsukur/spring/rest/market/domain/core/ad/Ad.java
package org.vtsukur.spring.rest.market.domain.core.ad; import lombok.*; import org.springframework.hateoas.Identifiable; import org.vtsukur.spring.rest.market.domain.core.user.User; import javax.persistence.*; import java.math.BigDecimal; import java.math.BigInteger; import java.time.LocalDateTime; /** * @author volodymyr.tsukur */ @Entity @Data public class Ad implements Identifiable<Long> { @Id @GeneratedValue private Long id; @Column(nullable = false) @Enumerated(EnumType.STRING) private Type type; public enum Type { BUY, SELL } @Column(nullable = false) private BigInteger amount; @Column(nullable = false) @Enumerated(EnumType.STRING) private Currency currency; public enum Currency { USD, EUR } @Column(nullable = false) private BigDecimal rate; @ManyToOne @JoinColumn(nullable = false) private User user; private Location location; @Embeddable @Getter @Setter @NoArgsConstructor @AllArgsConstructor public static class Location { @Column(nullable = false) private String city; private String area; } private String comment; @Lob private LocalDateTime publishedAt; @Column(nullable = false) @Enumerated(EnumType.STRING) private Status status = Status.NEW; public enum Status { NEW, PUBLISHED, OUTDATED } public Ad publish() { if (status == Status.NEW) { publishedAt = LocalDateTime.now(); status = Status.PUBLISHED; } else { throw new InvalidAdStateTransitionException("Ad is already published"); } return this; } public Ad finish() { if (status == Status.PUBLISHED) { status = Status.OUTDATED; } else { throw new InvalidAdStateTransitionException( "Ad can be finished only when it is in the " + Status.PUBLISHED + " state"); } return this; } }
Renaming OUTDATED into EXPIRED.
src/main/java/org/vtsukur/spring/rest/market/domain/core/ad/Ad.java
Renaming OUTDATED into EXPIRED.
<ide><path>rc/main/java/org/vtsukur/spring/rest/market/domain/core/ad/Ad.java <ide> <ide> PUBLISHED, <ide> <del> OUTDATED <add> EXPIRED <ide> <ide> } <ide> <ide> <ide> public Ad finish() { <ide> if (status == Status.PUBLISHED) { <del> status = Status.OUTDATED; <add> status = Status.EXPIRED; <ide> } <ide> else { <ide> throw new InvalidAdStateTransitionException(
JavaScript
mit
22562694cefea0d8d53ba7e70f5f8682851cb225
0
watson/monster-drift
'use strict' var debug = require('debug')('monster-drift') delete process.env.DEBUG // hackrf doesn't like this flag var fs = require('fs') var devices = require('hackrf')() var signal = { f: fs.readFileSync('./recordings/car-f.raw'), b: fs.readFileSync('./recordings/car-b.raw'), l: fs.readFileSync('./recordings/car-r.raw'), r: fs.readFileSync('./recordings/car-l.raw'), fr: fs.readFileSync('./recordings/car-fl.raw'), fl: fs.readFileSync('./recordings/car-fr.raw'), br: fs.readFileSync('./recordings/car-bl.raw'), bl: fs.readFileSync('./recordings/car-br.raw') } signal.f.name = 'forward' signal.b.name = 'backward' signal.l.name = 'left' signal.r.name = 'right' signal.fr.name = 'forward/right' signal.fl.name = 'forward/left' signal.br.name = 'backward/right' signal.bl.name = 'backward/left' module.exports = MonsterDrift function MonsterDrift (opts) { if (!(this instanceof MonsterDrift)) return new MonsterDrift() if (!opts) opts = {} this._freq = opts.freq || 27e6 this._index = 0 this._stream = null this._device = devices.open(opts.id || 0) this._device.setTxGain(opts.gain || 40) // TX VGA (IF) gain, 0-47 dB in 1 dB steps this._device.setFrequency(this._freq) } MonsterDrift.prototype.uturn = function (cb) { var self = this this.forward() setTimeout(function () { self.right() setTimeout(function () { self.backwardLeft() setTimeout(function () { self.backward() if (cb) setTimeout(cb, 1000) }, 100) }, 125) }, 1000) } MonsterDrift.prototype.start = function () { var self = this debug('starting') this._device.startTx(function (buf, cb) { var i if (self._stream) { for (i = 0; i < buf.length; i++) { buf[i] = self._stream[self._index++] if (self._index === self._stream.length) self._index = 0 } } else { for (i = 0; i < buf.length; i++) buf[i] = 0 } cb() }) } MonsterDrift.prototype.stop = function (cb) { if (!this._stream) return debug('stopping') this._stream = null this._device.stopTx(function () { debug('stopped!') if (cb) cb() }) } MonsterDrift.prototype.close = function (cb) { var self = this this._device.stopTx(function () { self._device.close(cb) }) } MonsterDrift.prototype.left = function () { this._drive(signal.l) } MonsterDrift.prototype.right = function () { this._drive(signal.r) } MonsterDrift.prototype.forward = function () { this._drive(signal.f) } MonsterDrift.prototype.forwardRight = function () { this._drive(signal.fr) } MonsterDrift.prototype.forwardLeft = function () { this._drive(signal.fl) } MonsterDrift.prototype.backward = function () { this._drive(signal.b) } MonsterDrift.prototype.backwardRight = function () { this._drive(signal.br) } MonsterDrift.prototype.backwardLeft = function () { this._drive(signal.bl) } MonsterDrift.prototype._drive = function (s) { debug(s.name) if (this._stream === s) return else if (!this._stream) this.start() debug('new direction') this._index = 0 this._stream = s }
index.js
'use strict' var debug = require('debug')('monster-drift') delete process.env.DEBUG // hackrf doesn't like this flag var fs = require('fs') var devices = require('hackrf')() var signal = { f: fs.readFileSync('./recordings/car-f.raw'), b: fs.readFileSync('./recordings/car-b.raw'), l: fs.readFileSync('./recordings/car-r.raw'), r: fs.readFileSync('./recordings/car-l.raw'), fr: fs.readFileSync('./recordings/car-fl.raw'), fl: fs.readFileSync('./recordings/car-fr.raw'), br: fs.readFileSync('./recordings/car-bl.raw'), bl: fs.readFileSync('./recordings/car-br.raw') } signal.f.name = 'forward' signal.b.name = 'backward' signal.l.name = 'left' signal.r.name = 'right' signal.fr.name = 'forward/right' signal.fl.name = 'forward/left' signal.br.name = 'backward/right' signal.bl.name = 'backward/left' module.exports = MonsterDrift function MonsterDrift (opts) { if (!(this instanceof MonsterDrift)) return new MonsterDrift() if (!opts) opts = {} this._freq = opts.freq || 27e6 this._index = 0 this._stream = null this._device = devices.open(opts.id || 0) this._device.setTxGain(opts.gain || 40) // TX VGA (IF) gain, 0-47 dB in 1 dB steps this._device.setFrequency(this._freq) } MonsterDrift.prototype.uturn = function (cb) { var self = this this.forward() setTimeout(function () { self._drive(signal.r) setTimeout(function () { self.backwardLeft() setTimeout(function () { self.backward() setTimeout(cb, 1000) }, 100) }, 125) }, 1000) } MonsterDrift.prototype.start = function () { var self = this debug('starting') this._device.startTx(function (buf, cb) { var i if (self._stream) { for (i = 0; i < buf.length; i++) { buf[i] = self._stream[self._index++] if (self._index === self._stream.length) self._index = 0 } } else { for (i = 0; i < buf.length; i++) buf[i] = 0 } cb() }) } MonsterDrift.prototype.stop = function (cb) { if (!this._stream) return debug('stopping') this._stream = null this._device.stopTx(function () { debug('stopped!') if (cb) cb() }) } MonsterDrift.prototype.close = function (cb) { var self = this this._device.stopTx(function () { self._device.close(cb) }) } MonsterDrift.prototype.left = function () { this._drive(signal.l) } MonsterDrift.prototype.right = function () { this._drive(signal.r) } MonsterDrift.prototype.forward = function () { this._drive(signal.f) } MonsterDrift.prototype.forwardRight = function () { this._drive(signal.fr) } MonsterDrift.prototype.forwardLeft = function () { this._drive(signal.fl) } MonsterDrift.prototype.backward = function () { this._drive(signal.b) } MonsterDrift.prototype.backwardRight = function () { this._drive(signal.br) } MonsterDrift.prototype.backwardLeft = function () { this._drive(signal.bl) } MonsterDrift.prototype._drive = function (s) { debug(s.name) if (this._stream === s) return else if (!this._stream) this.start() debug('new direction') this._index = 0 this._stream = s }
Clean up uturn
index.js
Clean up uturn
<ide><path>ndex.js <ide> var self = this <ide> this.forward() <ide> setTimeout(function () { <del> self._drive(signal.r) <add> self.right() <ide> setTimeout(function () { <ide> self.backwardLeft() <ide> setTimeout(function () { <ide> self.backward() <del> setTimeout(cb, 1000) <add> if (cb) setTimeout(cb, 1000) <ide> }, 100) <ide> }, 125) <ide> }, 1000)
JavaScript
mit
059c150e1f8a4693029cd7cf5a1e556b13b06798
0
Terab/terab.github.io,Terab/terab.github.io
function GameManager(size, InputManager, Actuator, ScoreManager) { this.size = size; // Size of the grid this.inputManager = new InputManager; this.scoreManager = new ScoreManager; this.actuator = new Actuator; this.startTiles = 2; this.inputManager.on("move", this.move.bind(this)); this.inputManager.on("restart", this.restart.bind(this)); this.inputManager.on("keepPlaying", this.keepPlaying.bind(this)); this.setup(); } // Restart the game GameManager.prototype.restart = function () { this.actuator.continue(); this.setup(); }; // Keep playing after winning GameManager.prototype.keepPlaying = function () { this.keepPlaying = true; this.actuator.continue(); }; GameManager.prototype.isGameTerminated = function () { if (this.over || (this.won && !this.keepPlaying)) { return true; } else { return false; } }; // Set up the game GameManager.prototype.setup = function () { this.grid = new Grid(this.size); this.score = 0; this.over = false; this.won = false; this.keepPlaying = false; // Add the initial tiles this.addStartTiles(); // Update the actuator this.actuate(); }; // Set up the initial tiles to start the game with GameManager.prototype.addStartTiles = function () { for (var i = 0; i < this.startTiles; i++) { this.addRandomTile(); } }; // Adds a tile in a random position GameManager.prototype.addRandomTile = function () { if (this.grid.cellsAvailable()) { var value = Math.random() < 0.9 ? -2 : -4; var tile = new Tile(this.grid.randomAvailableCell(), value); this.grid.insertTile(tile); } }; // Sends the updated grid to the actuator GameManager.prototype.actuate = function () { if (this.scoreManager.get() < this.score) { this.scoreManager.set(this.score); } this.actuator.actuate(this.grid, { score: this.score, over: this.over, won: this.won, bestScore: this.scoreManager.get(), terminated: this.isGameTerminated() }); }; // Save all tile positions and remove merger info GameManager.prototype.prepareTiles = function () { this.grid.eachCell(function (x, y, tile) { if (tile) { tile.mergedFrom = null; tile.savePosition(); } }); }; // Move a tile and its representation GameManager.prototype.moveTile = function (tile, cell) { this.grid.cells[tile.x][tile.y] = null; this.grid.cells[cell.x][cell.y] = tile; tile.updatePosition(cell); }; // Move tiles on the grid in the specified direction GameManager.prototype.move = function (direction) { // 0: up, 1: right, 2:down, 3: left var self = this; if (this.isGameTerminated()) return; // Don't do anything if the game's over var cell, tile; var vector = this.getVector(direction); var traversals = this.buildTraversals(vector); var moved = false; // Save the current tile positions and remove merger information this.prepareTiles(); // Traverse the grid in the right direction and move tiles traversals.x.forEach(function (x) { traversals.y.forEach(function (y) { cell = { x: x, y: y }; tile = self.grid.cellContent(cell); if (tile) { var positions = self.findFarthestPosition(cell, vector); var next = self.grid.cellContent(positions.next); // Only one merger per row traversal? if (next && next.value === tile.value && !next.mergedFrom) { var merged = new Tile(positions.next, tile.value * 2); merged.mergedFrom = [tile, next]; self.grid.insertTile(merged); self.grid.removeTile(tile); // Converge the two tiles' positions tile.updatePosition(positions.next); // Update the score self.score += merged.value; // The mighty 2048 tile if (merged.value === 2048) self.won = true; } else { self.moveTile(tile, positions.farthest); } if (!self.positionsEqual(cell, tile)) { moved = true; // The tile moved from its original cell! } } }); }); if (moved) { this.addRandomTile(); if (!this.movesAvailable()) { this.over = true; // Game over! } this.actuate(); } }; // Get the vector representing the chosen direction GameManager.prototype.getVector = function (direction) { // Vectors representing tile movement var map = { 0: { x: 0, y: -1 }, // up 1: { x: 1, y: 0 }, // right 2: { x: 0, y: 1 }, // down 3: { x: -1, y: 0 } // left }; return map[direction]; }; // Build a list of positions to traverse in the right order GameManager.prototype.buildTraversals = function (vector) { var traversals = { x: [], y: [] }; for (var pos = 0; pos < this.size; pos++) { traversals.x.push(pos); traversals.y.push(pos); } // Always traverse from the farthest cell in the chosen direction if (vector.x === 1) traversals.x = traversals.x.reverse(); if (vector.y === 1) traversals.y = traversals.y.reverse(); return traversals; }; GameManager.prototype.findFarthestPosition = function (cell, vector) { var previous; // Progress towards the vector direction until an obstacle is found do { previous = cell; cell = { x: previous.x + vector.x, y: previous.y + vector.y }; } while (this.grid.withinBounds(cell) && this.grid.cellAvailable(cell)); return { farthest: previous, next: cell // Used to check if a merge is required }; }; GameManager.prototype.movesAvailable = function () { return this.grid.cellsAvailable() || this.tileMatchesAvailable(); }; // Check for available matches between tiles (more expensive check) GameManager.prototype.tileMatchesAvailable = function () { var self = this; var tile; for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { tile = this.grid.cellContent({ x: x, y: y }); if (tile) { for (var direction = 0; direction < 4; direction++) { var vector = self.getVector(direction); var cell = { x: x + vector.x, y: y + vector.y }; var other = self.grid.cellContent(cell); if (other && other.value === tile.value) { return true; // These two tiles can be merged } } } } } return false; }; GameManager.prototype.positionsEqual = function (first, second) { return first.x === second.x && first.y === second.y; };
js/game_manager.js
function GameManager(size, InputManager, Actuator, ScoreManager) { this.size = size; // Size of the grid this.inputManager = new InputManager; this.scoreManager = new ScoreManager; this.actuator = new Actuator; this.startTiles = 2; this.inputManager.on("move", this.move.bind(this)); this.inputManager.on("restart", this.restart.bind(this)); this.inputManager.on("keepPlaying", this.keepPlaying.bind(this)); this.setup(); } // Restart the game GameManager.prototype.restart = function () { this.actuator.continue(); this.setup(); }; // Keep playing after winning GameManager.prototype.keepPlaying = function () { this.keepPlaying = true; this.actuator.continue(); }; GameManager.prototype.isGameTerminated = function () { if (this.over || (this.won && !this.keepPlaying)) { return true; } else { return false; } }; // Set up the game GameManager.prototype.setup = function () { this.grid = new Grid(this.size); this.score = 0; this.over = false; this.won = false; this.keepPlaying = false; // Add the initial tiles this.addStartTiles(); // Update the actuator this.actuate(); }; // Set up the initial tiles to start the game with GameManager.prototype.addStartTiles = function () { for (var i = 0; i < this.startTiles; i++) { this.addRandomTile(); } }; // Adds a tile in a random position GameManager.prototype.addRandomTile = function () { if (this.grid.cellsAvailable()) { var value = Math.random() < 0.9 ? 1024 : 2048; var tile = new Tile(this.grid.randomAvailableCell(), value); this.grid.insertTile(tile); } }; // Sends the updated grid to the actuator GameManager.prototype.actuate = function () { if (this.scoreManager.get() < this.score) { this.scoreManager.set(this.score); } this.actuator.actuate(this.grid, { score: this.score, over: this.over, won: this.won, bestScore: this.scoreManager.get(), terminated: this.isGameTerminated() }); }; // Save all tile positions and remove merger info GameManager.prototype.prepareTiles = function () { this.grid.eachCell(function (x, y, tile) { if (tile) { tile.mergedFrom = null; tile.savePosition(); } }); }; // Move a tile and its representation GameManager.prototype.moveTile = function (tile, cell) { this.grid.cells[tile.x][tile.y] = null; this.grid.cells[cell.x][cell.y] = tile; tile.updatePosition(cell); }; // Move tiles on the grid in the specified direction GameManager.prototype.move = function (direction) { // 0: up, 1: right, 2:down, 3: left var self = this; if (this.isGameTerminated()) return; // Don't do anything if the game's over var cell, tile; var vector = this.getVector(direction); var traversals = this.buildTraversals(vector); var moved = false; // Save the current tile positions and remove merger information this.prepareTiles(); // Traverse the grid in the right direction and move tiles traversals.x.forEach(function (x) { traversals.y.forEach(function (y) { cell = { x: x, y: y }; tile = self.grid.cellContent(cell); if (tile) { var positions = self.findFarthestPosition(cell, vector); var next = self.grid.cellContent(positions.next); // Only one merger per row traversal? if (next && next.value === tile.value && !next.mergedFrom) { var merged = new Tile(positions.next, tile.value * 2); merged.mergedFrom = [tile, next]; self.grid.insertTile(merged); self.grid.removeTile(tile); // Converge the two tiles' positions tile.updatePosition(positions.next); // Update the score self.score += merged.value; // The mighty 2048 tile if (merged.value === 2048) self.won = true; } else { self.moveTile(tile, positions.farthest); } if (!self.positionsEqual(cell, tile)) { moved = true; // The tile moved from its original cell! } } }); }); if (moved) { this.addRandomTile(); if (!this.movesAvailable()) { this.over = true; // Game over! } this.actuate(); } }; // Get the vector representing the chosen direction GameManager.prototype.getVector = function (direction) { // Vectors representing tile movement var map = { 0: { x: 0, y: -1 }, // up 1: { x: 1, y: 0 }, // right 2: { x: 0, y: 1 }, // down 3: { x: -1, y: 0 } // left }; return map[direction]; }; // Build a list of positions to traverse in the right order GameManager.prototype.buildTraversals = function (vector) { var traversals = { x: [], y: [] }; for (var pos = 0; pos < this.size; pos++) { traversals.x.push(pos); traversals.y.push(pos); } // Always traverse from the farthest cell in the chosen direction if (vector.x === 1) traversals.x = traversals.x.reverse(); if (vector.y === 1) traversals.y = traversals.y.reverse(); return traversals; }; GameManager.prototype.findFarthestPosition = function (cell, vector) { var previous; // Progress towards the vector direction until an obstacle is found do { previous = cell; cell = { x: previous.x + vector.x, y: previous.y + vector.y }; } while (this.grid.withinBounds(cell) && this.grid.cellAvailable(cell)); return { farthest: previous, next: cell // Used to check if a merge is required }; }; GameManager.prototype.movesAvailable = function () { return this.grid.cellsAvailable() || this.tileMatchesAvailable(); }; // Check for available matches between tiles (more expensive check) GameManager.prototype.tileMatchesAvailable = function () { var self = this; var tile; for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { tile = this.grid.cellContent({ x: x, y: y }); if (tile) { for (var direction = 0; direction < 4; direction++) { var vector = self.getVector(direction); var cell = { x: x + vector.x, y: y + vector.y }; var other = self.grid.cellContent(cell); if (other && other.value === tile.value) { return true; // These two tiles can be merged } } } } } return false; }; GameManager.prototype.positionsEqual = function (first, second) { return first.x === second.x && first.y === second.y; };
negative are as awesome
js/game_manager.js
negative are as awesome
<ide><path>s/game_manager.js <ide> // Adds a tile in a random position <ide> GameManager.prototype.addRandomTile = function () { <ide> if (this.grid.cellsAvailable()) { <del> var value = Math.random() < 0.9 ? 1024 : 2048; <add> var value = Math.random() < 0.9 ? -2 : -4; <ide> var tile = new Tile(this.grid.randomAvailableCell(), value); <ide> <ide> this.grid.insertTile(tile);
Java
apache-2.0
c6037b988fbb28b96e4c3cf5688f3a2e7b9009b0
0
psakar/Resteasy,psakar/Resteasy,awhitford/Resteasy,awhitford/Resteasy,psakar/Resteasy,rankinc/Resteasy,rankinc/Resteasy,psakar/Resteasy,awhitford/Resteasy,rankinc/Resteasy,rankinc/Resteasy,awhitford/Resteasy,awhitford/Resteasy
package org.jboss.resteasy.plugins.server.netty; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferOutputStream; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.resteasy.specimpl.MultivaluedMapImpl; import org.jboss.resteasy.spi.HttpResponse; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.NewCookie; import java.io.IOException; import java.io.OutputStream; /** * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public class NettyHttpResponse implements HttpResponse { private int status = 200; private ChannelBuffer buffer; private ChannelBufferOutputStream os; private MultivaluedMap<String, Object> outputHeaders; private String message = null; public NettyHttpResponse() { outputHeaders = new MultivaluedMapImpl<String, Object>(); buffer = ChannelBuffers.dynamicBuffer(); os = new ChannelBufferOutputStream(buffer); } public ChannelBuffer getBuffer() { return buffer; } public String getMessage() { return message; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public MultivaluedMap<String, Object> getOutputHeaders() { return outputHeaders; } public OutputStream getOutputStream() throws IOException { return os; } public void addNewCookie(NewCookie cookie) { outputHeaders.add(HttpHeaders.SET_COOKIE, cookie); } public void sendError(int status) throws IOException { this.status = status; } public void sendError(int status, String message) throws IOException { this.status = status; this.message = message; } public boolean isCommitted() { return false; } public void reset() { outputHeaders.clear(); } }
jaxrs/server-adapters/resteasy-netty/src/main/java/org/jboss/resteasy/plugins/server/netty/NettyHttpResponse.java
package org.jboss.resteasy.plugins.server.netty; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferOutputStream; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.resteasy.specimpl.MultivaluedMapImpl; import org.jboss.resteasy.spi.HttpResponse; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.NewCookie; import java.io.IOException; import java.io.OutputStream; /** * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public class NettyHttpResponse implements HttpResponse { private int status = 200; private ChannelBuffer buffer; private ChannelBufferOutputStream os; private MultivaluedMap<String, Object> outputHeaders; private String message = null; public NettyHttpResponse() { outputHeaders = new MultivaluedMapImpl<String, Object>(); buffer = ChannelBuffers.dynamicBuffer(); os = new ChannelBufferOutputStream(buffer); } public ChannelBuffer getBuffer() { return buffer; } public String getMessage() { return message; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public MultivaluedMap<String, Object> getOutputHeaders() { return outputHeaders; } public OutputStream getOutputStream() throws IOException { return os; } public void addNewCookie(NewCookie cookie) { outputHeaders.add(HttpHeaders.SET_COOKIE, cookie); } public void sendError(int status) throws IOException { this.status = status; } public void sendError(int status, String message) throws IOException { this.status = status; this.message = message; } public boolean isCommitted() { return false; } public void reset() { outputHeaders.clear(); buffer.clear(); } }
Make sure reset does only rest the headers
jaxrs/server-adapters/resteasy-netty/src/main/java/org/jboss/resteasy/plugins/server/netty/NettyHttpResponse.java
Make sure reset does only rest the headers
<ide><path>axrs/server-adapters/resteasy-netty/src/main/java/org/jboss/resteasy/plugins/server/netty/NettyHttpResponse.java <ide> public void reset() <ide> { <ide> outputHeaders.clear(); <del> buffer.clear(); <ide> } <ide> <ide> }
Java
apache-2.0
366e7d680377fe87831d8c43b4449f86437f668b
0
nobdy/mybatis-plus,baomidou/mybatis-plus,baomidou/mybatis-plus
/** * Copyright (c) 2011-2020, hubin ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.baomidou.mybatisplus.spring; import com.baomidou.mybatisplus.entity.GlobalConfiguration; import com.baomidou.mybatisplus.toolkit.SystemClock; import org.apache.ibatis.binding.MapperRegistry; import org.apache.ibatis.builder.xml.XMLMapperBuilder; import org.apache.ibatis.builder.xml.XMLMapperEntityResolver; import org.apache.ibatis.executor.ErrorContext; import org.apache.ibatis.executor.keygen.SelectKeyGenerator; import org.apache.ibatis.io.Resources; import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.LogFactory; import org.apache.ibatis.parsing.XNode; import org.apache.ibatis.parsing.XPathParser; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.core.NestedIOException; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.util.ResourceUtils; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * <p> * 切莫用于生产环境(后果自负)<br> * Mybatis 映射文件热加载(发生变动后自动重新加载).<br> * 方便开发时使用,不用每次修改xml文件后都要去重启应用.<br> * </p> * * @author nieqiurong * @Date 2016-08-25 */ public class MybatisMapperRefresh implements Runnable { private static final Log logger = LogFactory.getLog(MybatisMapperRefresh.class); private SqlSessionFactory sqlSessionFactory; private Resource[] mapperLocations; private Long beforeTime = 0L; private Configuration configuration; /** * 是否开启刷新mapper */ private boolean enabled; /** * xml文件目录 */ private Set<String> fileSet; /** * 延迟加载时间 */ private int delaySeconds = 10; /** * 刷新间隔时间 */ private int sleepSeconds = 20; /** * 记录jar包存在的mapper */ private static Map<String, List<Resource>> jarMapper = new HashMap<String, List<Resource>>(); public MybatisMapperRefresh(Resource[] mapperLocations, SqlSessionFactory sqlSessionFactory, int delaySeconds, int sleepSeconds, boolean enabled) { this.mapperLocations = mapperLocations; this.sqlSessionFactory = sqlSessionFactory; this.delaySeconds = delaySeconds; this.enabled = enabled; this.sleepSeconds = sleepSeconds; this.configuration = sqlSessionFactory.getConfiguration(); this.run(); } public MybatisMapperRefresh(Resource[] mapperLocations, SqlSessionFactory sqlSessionFactory, boolean enabled) { this.mapperLocations = mapperLocations; this.sqlSessionFactory = sqlSessionFactory; this.enabled = enabled; this.configuration = sqlSessionFactory.getConfiguration(); this.run(); } public void run() { final GlobalConfiguration globalConfig = GlobalConfiguration.getGlobalConfig(configuration); /* * 启动 XML 热加载 */ if (enabled) { beforeTime = SystemClock.now(); final MybatisMapperRefresh runnable = this; new Thread(new Runnable() { public void run() { if (fileSet == null) { fileSet = new HashSet<String>(); for (Resource mapperLocation : mapperLocations) { try { if (ResourceUtils.isJarURL(mapperLocation.getURL())) { String key = new UrlResource(ResourceUtils.extractJarFileURL(mapperLocation.getURL())) .getFile().getPath(); fileSet.add(key); if (jarMapper.get(key) != null) { jarMapper.get(key).add(mapperLocation); } else { List<Resource> resourcesList = new ArrayList<Resource>(); resourcesList.add(mapperLocation); jarMapper.put(key, resourcesList); } } else { fileSet.add(mapperLocation.getFile().getPath()); } } catch (IOException ioException) { ioException.printStackTrace(); } } } try { Thread.sleep(delaySeconds * 1000); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); } while (true) { try { for (String filePath : fileSet) { File file = new File(filePath); if (file != null && file.isFile() && file.lastModified() > beforeTime) { globalConfig.setRefresh(true); List<Resource> removeList = jarMapper.get(filePath); if (removeList != null && !removeList.isEmpty()) {// 如果是jar包中的xml,将刷新jar包中存在的所有xml,后期再修改加载jar中修改过后的xml for (Resource resource : removeList) { runnable.refresh(resource); } } else { runnable.refresh(new FileSystemResource(file)); } } } if (globalConfig.isRefresh()) { beforeTime = SystemClock.now(); } globalConfig.setRefresh(true); } catch (Exception exception) { exception.printStackTrace(); } try { Thread.sleep(sleepSeconds * 1000); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); } } } }, "mybatis-plus MapperRefresh").start(); } } /** * 刷新mapper * * @throws Exception */ @SuppressWarnings("rawtypes") private void refresh(Resource resource) throws Exception { this.configuration = sqlSessionFactory.getConfiguration(); boolean isSupper = configuration.getClass().getSuperclass() == Configuration.class; try { Field loadedResourcesField = isSupper ? configuration.getClass().getSuperclass().getDeclaredField("loadedResources") : configuration.getClass().getDeclaredField("loadedResources"); loadedResourcesField.setAccessible(true); Set loadedResourcesSet = ((Set) loadedResourcesField.get(configuration)); XPathParser xPathParser = new XPathParser(resource.getInputStream(), true, configuration.getVariables(), new XMLMapperEntityResolver()); XNode context = xPathParser.evalNode("/mapper"); String namespace = context.getStringAttribute("namespace"); Field field = MapperRegistry.class.getDeclaredField("knownMappers"); field.setAccessible(true); Map mapConfig = (Map) field.get(configuration.getMapperRegistry()); mapConfig.remove(Resources.classForName(namespace)); loadedResourcesSet.remove(resource.toString()); configuration.getCacheNames().remove(namespace); cleanParameterMap(context.evalNodes("/mapper/parameterMap"), namespace); cleanResultMap(context.evalNodes("/mapper/resultMap"), namespace); cleanKeyGenerators(context.evalNodes("insert|update"), namespace); cleanSqlElement(context.evalNodes("/mapper/sql"), namespace); XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resource.getInputStream(), sqlSessionFactory.getConfiguration(), // 注入的sql先不进行处理了 resource.toString(), sqlSessionFactory.getConfiguration().getSqlFragments()); xmlMapperBuilder.parse(); logger.debug("refresh: '" + resource + "', success!"); } catch (Exception e) { throw new NestedIOException("Failed to parse mapping resource: '" + resource + "'", e); } finally { ErrorContext.instance().reset(); } } /** * 清理parameterMap * * @param list * @param namespace */ private void cleanParameterMap(List<XNode> list, String namespace) { for (XNode parameterMapNode : list) { String id = parameterMapNode.getStringAttribute("id"); configuration.getParameterMaps().remove(namespace + "." + id); } } /** * 清理resultMap * * @param list * @param namespace */ private void cleanResultMap(List<XNode> list, String namespace) { for (XNode resultMapNode : list) { String id = resultMapNode.getStringAttribute("id", resultMapNode.getValueBasedIdentifier()); configuration.getResultMapNames().remove(id); configuration.getResultMapNames().remove(namespace + "." + id); clearResultMap(resultMapNode, namespace); } } private void clearResultMap(XNode xNode, String namespace) { for (XNode resultChild : xNode.getChildren()) { if ("association".equals(resultChild.getName()) || "collection".equals(resultChild.getName()) || "case".equals(resultChild.getName())) { if (resultChild.getStringAttribute("select") == null) { configuration.getResultMapNames().remove( resultChild.getStringAttribute("id", resultChild.getValueBasedIdentifier())); configuration.getResultMapNames().remove( namespace + "." + resultChild.getStringAttribute("id", resultChild.getValueBasedIdentifier())); if (resultChild.getChildren() != null && !resultChild.getChildren().isEmpty()) { clearResultMap(resultChild, namespace); } } } } } /** * 清理selectKey * * @param list * @param namespace */ private void cleanKeyGenerators(List<XNode> list, String namespace) { for (XNode context : list) { String id = context.getStringAttribute("id"); configuration.getKeyGeneratorNames().remove(id + SelectKeyGenerator.SELECT_KEY_SUFFIX); configuration.getKeyGeneratorNames().remove(namespace + "." + id + SelectKeyGenerator.SELECT_KEY_SUFFIX); } } /** * 清理sql节点缓存 * * @param list * @param namespace */ private void cleanSqlElement(List<XNode> list, String namespace) { for (XNode context : list) { String id = context.getStringAttribute("id"); configuration.getSqlFragments().remove(id); configuration.getSqlFragments().remove(namespace + "." + id); } } }
mybatis-plus/src/main/java/com/baomidou/mybatisplus/spring/MybatisMapperRefresh.java
/** * Copyright (c) 2011-2020, hubin ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.baomidou.mybatisplus.spring; import com.baomidou.mybatisplus.entity.GlobalConfiguration; import com.baomidou.mybatisplus.toolkit.SystemClock; import org.apache.ibatis.binding.MapperRegistry; import org.apache.ibatis.builder.xml.XMLMapperBuilder; import org.apache.ibatis.builder.xml.XMLMapperEntityResolver; import org.apache.ibatis.executor.ErrorContext; import org.apache.ibatis.executor.keygen.SelectKeyGenerator; import org.apache.ibatis.io.Resources; import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.LogFactory; import org.apache.ibatis.parsing.XNode; import org.apache.ibatis.parsing.XPathParser; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.core.NestedIOException; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.util.ResourceUtils; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * <p> * 切莫用于生产环境(后果自负)<br> * Mybatis 映射文件热加载(发生变动后自动重新加载).<br> * 方便开发时使用,不用每次修改xml文件后都要去重启应用.<br> * </p> * * @author nieqiurong * @Date 2016-08-25 */ public class MybatisMapperRefresh implements Runnable { private static final Log logger = LogFactory.getLog(MybatisMapperRefresh.class); private SqlSessionFactory sqlSessionFactory; private Resource[] mapperLocations; private Long beforeTime = 0L; private Configuration configuration; /** * 是否开启刷新mapper */ private boolean enabled; /** * xml文件目录 */ private Set<String> fileSet; /** * 延迟加载时间 */ private int delaySeconds = 10; /** * 刷新间隔时间 */ private int sleepSeconds = 20; /** * 记录jar包存在的mapper */ private static Map<String, List<Resource>> jarMapper = new HashMap<String, List<Resource>>(); public MybatisMapperRefresh(Resource[] mapperLocations, SqlSessionFactory sqlSessionFactory, int delaySeconds, int sleepSeconds, boolean enabled) { this.mapperLocations = mapperLocations; this.sqlSessionFactory = sqlSessionFactory; this.delaySeconds = delaySeconds; this.enabled = enabled; this.sleepSeconds = sleepSeconds; this.configuration = sqlSessionFactory.getConfiguration(); this.run(); } public MybatisMapperRefresh(Resource[] mapperLocations, SqlSessionFactory sqlSessionFactory, boolean enabled) { this.mapperLocations = mapperLocations; this.sqlSessionFactory = sqlSessionFactory; this.enabled = enabled; this.configuration = sqlSessionFactory.getConfiguration(); this.run(); } public void run() { final GlobalConfiguration globalConfig = GlobalConfiguration.getGlobalConfig(configuration); /* * 启动 XML 热加载 */ if (enabled) { beforeTime = SystemClock.now(); final MybatisMapperRefresh runnable = this; new Thread(new Runnable() { public void run() { if (fileSet == null) { fileSet = new HashSet<String>(); for (Resource mapperLocation : mapperLocations) { try { if (ResourceUtils.isJarURL(mapperLocation.getURL())) { String key = new UrlResource(ResourceUtils.extractJarFileURL(mapperLocation.getURL())) .getFile().getPath(); fileSet.add(key); if (jarMapper.get(key) != null) { jarMapper.get(key).add(mapperLocation); } else { List<Resource> resourcesList = new ArrayList<Resource>(); resourcesList.add(mapperLocation); jarMapper.put(key, resourcesList); } } else { fileSet.add(mapperLocation.getFile().getPath()); } } catch (IOException ioException) { ioException.printStackTrace(); } } } try { Thread.sleep(delaySeconds * 1000); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); } while (true) { try { for (String filePath : fileSet) { File file = new File(filePath); if (file != null && file.isFile() && file.lastModified() > beforeTime) { globalConfig.setRefresh(true); List<Resource> removeList = jarMapper.get(filePath); if (removeList != null && !removeList.isEmpty()) {// 如果是jar包中的xml,将刷新jar包中存在的所有xml,后期再修改加载jar中修改过后的xml for (Resource resource : removeList) { runnable.refresh(resource); } } else { runnable.refresh(new FileSystemResource(file)); } } } if (globalConfig.isRefresh()) { beforeTime = SystemClock.now(); } globalConfig.setRefresh(true); } catch (Exception exception) { exception.printStackTrace(); } try { Thread.sleep(sleepSeconds * 1000); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); } } } }, "mybatis-plus MapperRefresh").start(); } } /** * 刷新mapper * * @throws Exception */ @SuppressWarnings("rawtypes") private void refresh(Resource resource) throws Exception { this.configuration = sqlSessionFactory.getConfiguration(); boolean isSupper = configuration.getClass().getSuperclass() == Configuration.class; try { Field loadedResourcesField = isSupper ? configuration.getClass().getSuperclass().getDeclaredField("loadedResources") : configuration.getClass().getDeclaredField("loadedResources"); loadedResourcesField.setAccessible(true); Set loadedResourcesSet = ((Set) loadedResourcesField.get(configuration)); XPathParser xPathParser = new XPathParser(resource.getInputStream(), true, configuration.getVariables(), new XMLMapperEntityResolver()); XNode context = xPathParser.evalNode("/mapper"); String namespace = context.getStringAttribute("namespace"); Field field = MapperRegistry.class.getDeclaredField("knownMappers"); field.setAccessible(true); Map mapConfig = (Map) field.get(configuration.getMapperRegistry()); mapConfig.remove(Resources.classForName(namespace)); loadedResourcesSet.remove(resource.toString()); configuration.getCacheNames().remove(namespace); cleanParameterMap(context.evalNodes("/mapper/parameterMap"), namespace); cleanResultMap(context.evalNodes("/mapper/resultMap"), namespace); cleanKeyGenerators(context.evalNodes("insert|update"), namespace); cleanSqlElement(context.evalNodes("/mapper/sql"), namespace); XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resource.getInputStream(), sqlSessionFactory.getConfiguration(), // 注入的sql先不进行处理了 resource.toString(), sqlSessionFactory.getConfiguration().getSqlFragments()); xmlMapperBuilder.parse(); logger.debug("refresh:" + resource + ",success!"); } catch (Exception e) { throw new NestedIOException("Failed to parse mapping resource: '" + resource + "'", e); } finally { ErrorContext.instance().reset(); } } /** * 清理parameterMap * * @param list * @param namespace */ private void cleanParameterMap(List<XNode> list, String namespace) { for (XNode parameterMapNode : list) { String id = parameterMapNode.getStringAttribute("id"); configuration.getParameterMaps().remove(namespace + "." + id); } } /** * 清理resultMap * * @param list * @param namespace */ private void cleanResultMap(List<XNode> list, String namespace) { for (XNode resultMapNode : list) { String id = resultMapNode.getStringAttribute("id", resultMapNode.getValueBasedIdentifier()); configuration.getResultMapNames().remove(id); configuration.getResultMapNames().remove(namespace + "." + id); clearResultMap(resultMapNode, namespace); } } private void clearResultMap(XNode xNode, String namespace) { for (XNode resultChild : xNode.getChildren()) { if ("association".equals(resultChild.getName()) || "collection".equals(resultChild.getName()) || "case".equals(resultChild.getName())) { if (resultChild.getStringAttribute("select") == null) { configuration.getResultMapNames().remove( resultChild.getStringAttribute("id", resultChild.getValueBasedIdentifier())); configuration.getResultMapNames().remove( namespace + "." + resultChild.getStringAttribute("id", resultChild.getValueBasedIdentifier())); if (resultChild.getChildren() != null && !resultChild.getChildren().isEmpty()) { clearResultMap(resultChild, namespace); } } } } } /** * 清理selectKey * * @param list * @param namespace */ private void cleanKeyGenerators(List<XNode> list, String namespace) { for (XNode context : list) { String id = context.getStringAttribute("id"); configuration.getKeyGeneratorNames().remove(id + SelectKeyGenerator.SELECT_KEY_SUFFIX); configuration.getKeyGeneratorNames().remove(namespace + "." + id + SelectKeyGenerator.SELECT_KEY_SUFFIX); } } /** * 清理sql节点缓存 * * @param list * @param namespace */ private void cleanSqlElement(List<XNode> list, String namespace) { for (XNode context : list) { String id = context.getStringAttribute("id"); configuration.getSqlFragments().remove(id); configuration.getSqlFragments().remove(namespace + "." + id); } } }
FORMAT
mybatis-plus/src/main/java/com/baomidou/mybatisplus/spring/MybatisMapperRefresh.java
FORMAT
<ide><path>ybatis-plus/src/main/java/com/baomidou/mybatisplus/spring/MybatisMapperRefresh.java <ide> sqlSessionFactory.getConfiguration(), // 注入的sql先不进行处理了 <ide> resource.toString(), sqlSessionFactory.getConfiguration().getSqlFragments()); <ide> xmlMapperBuilder.parse(); <del> logger.debug("refresh:" + resource + ",success!"); <add> logger.debug("refresh: '" + resource + "', success!"); <ide> } catch (Exception e) { <ide> throw new NestedIOException("Failed to parse mapping resource: '" + resource + "'", e); <ide> } finally {
Java
apache-2.0
61036390e21e35ed643a0ae65bc2b489e95a971e
0
iacdingping/elasticsearch,easonC/elasticsearch,wbowling/elasticsearch,socialrank/elasticsearch,Ansh90/elasticsearch,MjAbuz/elasticsearch,marcuswr/elasticsearch-dateline,btiernay/elasticsearch,pozhidaevak/elasticsearch,jimczi/elasticsearch,tkssharma/elasticsearch,alexbrasetvik/elasticsearch,loconsolutions/elasticsearch,mmaracic/elasticsearch,caengcjd/elasticsearch,masaruh/elasticsearch,btiernay/elasticsearch,andrewvc/elasticsearch,wangtuo/elasticsearch,iantruslove/elasticsearch,apepper/elasticsearch,mmaracic/elasticsearch,fooljohnny/elasticsearch,bawse/elasticsearch,iamjakob/elasticsearch,loconsolutions/elasticsearch,davidvgalbraith/elasticsearch,karthikjaps/elasticsearch,clintongormley/elasticsearch,khiraiwa/elasticsearch,jimhooker2002/elasticsearch,libosu/elasticsearch,dongjoon-hyun/elasticsearch,abhijitiitr/es,cnfire/elasticsearch-1,ulkas/elasticsearch,EasonYi/elasticsearch,Fsero/elasticsearch,springning/elasticsearch,dantuffery/elasticsearch,qwerty4030/elasticsearch,kingaj/elasticsearch,rhoml/elasticsearch,amit-shar/elasticsearch,masterweb121/elasticsearch,StefanGor/elasticsearch,xpandan/elasticsearch,iamjakob/elasticsearch,petabytedata/elasticsearch,rento19962/elasticsearch,slavau/elasticsearch,ThalaivaStars/OrgRepo1,janmejay/elasticsearch,AndreKR/elasticsearch,lightslife/elasticsearch,vrkansagara/elasticsearch,fforbeck/elasticsearch,F0lha/elasticsearch,vingupta3/elasticsearch,codebunt/elasticsearch,MaineC/elasticsearch,NBSW/elasticsearch,kimchy/elasticsearch,elasticdog/elasticsearch,alexkuk/elasticsearch,episerver/elasticsearch,MjAbuz/elasticsearch,likaiwalkman/elasticsearch,coding0011/elasticsearch,djschny/elasticsearch,lzo/elasticsearch-1,ulkas/elasticsearch,diendt/elasticsearch,pablocastro/elasticsearch,khiraiwa/elasticsearch,hanst/elasticsearch,masaruh/elasticsearch,achow/elasticsearch,likaiwalkman/elasticsearch,alexshadow007/elasticsearch,NBSW/elasticsearch,andrejserafim/elasticsearch,areek/elasticsearch,khiraiwa/elasticsearch,Siddartha07/elasticsearch,liweinan0423/elasticsearch,truemped/elasticsearch,dylan8902/elasticsearch,chrismwendt/elasticsearch,Shekharrajak/elasticsearch,lightslife/elasticsearch,Stacey-Gammon/elasticsearch,fekaputra/elasticsearch,MetSystem/elasticsearch,cwurm/elasticsearch,strapdata/elassandra5-rc,vorce/es-metrics,ricardocerq/elasticsearch,zhaocloud/elasticsearch,marcuswr/elasticsearch-dateline,HarishAtGitHub/elasticsearch,linglaiyao1314/elasticsearch,wbowling/elasticsearch,javachengwc/elasticsearch,acchen97/elasticsearch,koxa29/elasticsearch,slavau/elasticsearch,amaliujia/elasticsearch,petmit/elasticsearch,luiseduardohdbackup/elasticsearch,alexkuk/elasticsearch,aglne/elasticsearch,Helen-Zhao/elasticsearch,pritishppai/elasticsearch,combinatorist/elasticsearch,zkidkid/elasticsearch,djschny/elasticsearch,kalimatas/elasticsearch,jpountz/elasticsearch,szroland/elasticsearch,18098924759/elasticsearch,sscarduzio/elasticsearch,henakamaMSFT/elasticsearch,mohit/elasticsearch,spiegela/elasticsearch,hechunwen/elasticsearch,Fsero/elasticsearch,lmtwga/elasticsearch,vietlq/elasticsearch,YosuaMichael/elasticsearch,xuzha/elasticsearch,njlawton/elasticsearch,ZTE-PaaS/elasticsearch,markwalkom/elasticsearch,zhaocloud/elasticsearch,mjason3/elasticsearch,wenpos/elasticsearch,kingaj/elasticsearch,tebriel/elasticsearch,andrejserafim/elasticsearch,markllama/elasticsearch,tsohil/elasticsearch,NBSW/elasticsearch,StefanGor/elasticsearch,ivansun1010/elasticsearch,lydonchandra/elasticsearch,trangvh/elasticsearch,strapdata/elassandra,diendt/elasticsearch,mute/elasticsearch,wittyameta/elasticsearch,vietlq/elasticsearch,spiegela/elasticsearch,martinstuga/elasticsearch,libosu/elasticsearch,zkidkid/elasticsearch,F0lha/elasticsearch,xuzha/elasticsearch,zhaocloud/elasticsearch,elancom/elasticsearch,wayeast/elasticsearch,mjhennig/elasticsearch,vingupta3/elasticsearch,Charlesdong/elasticsearch,mgalushka/elasticsearch,mohsinh/elasticsearch,abhijitiitr/es,mgalushka/elasticsearch,jimczi/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,uboness/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,Shepard1212/elasticsearch,xingguang2013/elasticsearch,smflorentino/elasticsearch,alexkuk/elasticsearch,diendt/elasticsearch,zeroctu/elasticsearch,umeshdangat/elasticsearch,aparo/elasticsearch,queirozfcom/elasticsearch,lightslife/elasticsearch,mmaracic/elasticsearch,Stacey-Gammon/elasticsearch,obourgain/elasticsearch,glefloch/elasticsearch,nezirus/elasticsearch,kcompher/elasticsearch,tahaemin/elasticsearch,Liziyao/elasticsearch,Siddartha07/elasticsearch,codebunt/elasticsearch,mute/elasticsearch,episerver/elasticsearch,ThiagoGarciaAlves/elasticsearch,abibell/elasticsearch,hafkensite/elasticsearch,wangtuo/elasticsearch,hechunwen/elasticsearch,ricardocerq/elasticsearch,mkis-/elasticsearch,sauravmondallive/elasticsearch,truemped/elasticsearch,hydro2k/elasticsearch,vietlq/elasticsearch,sreeramjayan/elasticsearch,Clairebi/ElasticsearchClone,ckclark/elasticsearch,easonC/elasticsearch,franklanganke/elasticsearch,dpursehouse/elasticsearch,ulkas/elasticsearch,mbrukman/elasticsearch,Collaborne/elasticsearch,Stacey-Gammon/elasticsearch,AshishThakur/elasticsearch,Microsoft/elasticsearch,ESamir/elasticsearch,dongjoon-hyun/elasticsearch,overcome/elasticsearch,vorce/es-metrics,nilabhsagar/elasticsearch,camilojd/elasticsearch,iacdingping/elasticsearch,apepper/elasticsearch,Asimov4/elasticsearch,camilojd/elasticsearch,sauravmondallive/elasticsearch,pablocastro/elasticsearch,strapdata/elassandra5-rc,PhaedrusTheGreek/elasticsearch,Flipkart/elasticsearch,GlenRSmith/elasticsearch,luiseduardohdbackup/elasticsearch,pablocastro/elasticsearch,aglne/elasticsearch,nellicus/elasticsearch,glefloch/elasticsearch,onegambler/elasticsearch,trangvh/elasticsearch,masterweb121/elasticsearch,adrianbk/elasticsearch,clintongormley/elasticsearch,rajanm/elasticsearch,jimczi/elasticsearch,nomoa/elasticsearch,wayeast/elasticsearch,hafkensite/elasticsearch,gingerwizard/elasticsearch,infusionsoft/elasticsearch,fekaputra/elasticsearch,StefanGor/elasticsearch,SergVro/elasticsearch,mm0/elasticsearch,abhijitiitr/es,Charlesdong/elasticsearch,lightslife/elasticsearch,rlugojr/elasticsearch,javachengwc/elasticsearch,jeteve/elasticsearch,wayeast/elasticsearch,nilabhsagar/elasticsearch,girirajsharma/elasticsearch,chirilo/elasticsearch,kcompher/elasticsearch,karthikjaps/elasticsearch,mjason3/elasticsearch,lmtwga/elasticsearch,AleksKochev/elasticsearch,feiqitian/elasticsearch,socialrank/elasticsearch,Shepard1212/elasticsearch,beiske/elasticsearch,masterweb121/elasticsearch,schonfeld/elasticsearch,ZTE-PaaS/elasticsearch,coding0011/elasticsearch,vietlq/elasticsearch,sreeramjayan/elasticsearch,sdauletau/elasticsearch,kkirsche/elasticsearch,C-Bish/elasticsearch,ouyangkongtong/elasticsearch,fekaputra/elasticsearch,sauravmondallive/elasticsearch,Chhunlong/elasticsearch,VukDukic/elasticsearch,s1monw/elasticsearch,infusionsoft/elasticsearch,Kakakakakku/elasticsearch,snikch/elasticsearch,rmuir/elasticsearch,cwurm/elasticsearch,AshishThakur/elasticsearch,acchen97/elasticsearch,caengcjd/elasticsearch,smflorentino/elasticsearch,iamjakob/elasticsearch,fernandozhu/elasticsearch,wayeast/elasticsearch,onegambler/elasticsearch,strapdata/elassandra,boliza/elasticsearch,djschny/elasticsearch,lchennup/elasticsearch,alexksikes/elasticsearch,sdauletau/elasticsearch,trangvh/elasticsearch,fernandozhu/elasticsearch,andrestc/elasticsearch,wimvds/elasticsearch,schonfeld/elasticsearch,anti-social/elasticsearch,JackyMai/elasticsearch,LeoYao/elasticsearch,nrkkalyan/elasticsearch,uschindler/elasticsearch,truemped/elasticsearch,lks21c/elasticsearch,episerver/elasticsearch,sdauletau/elasticsearch,fred84/elasticsearch,Collaborne/elasticsearch,Shekharrajak/elasticsearch,GlenRSmith/elasticsearch,areek/elasticsearch,robin13/elasticsearch,Rygbee/elasticsearch,mikemccand/elasticsearch,queirozfcom/elasticsearch,anti-social/elasticsearch,MichaelLiZhou/elasticsearch,jbertouch/elasticsearch,zhiqinghuang/elasticsearch,markwalkom/elasticsearch,brandonkearby/elasticsearch,umeshdangat/elasticsearch,strapdata/elassandra5-rc,iantruslove/elasticsearch,elancom/elasticsearch,jchampion/elasticsearch,SergVro/elasticsearch,scottsom/elasticsearch,scottsom/elasticsearch,HonzaKral/elasticsearch,kalburgimanjunath/elasticsearch,NBSW/elasticsearch,milodky/elasticsearch,mkis-/elasticsearch,tcucchietti/elasticsearch,adrianbk/elasticsearch,milodky/elasticsearch,queirozfcom/elasticsearch,vorce/es-metrics,zeroctu/elasticsearch,wimvds/elasticsearch,vingupta3/elasticsearch,polyfractal/elasticsearch,kenshin233/elasticsearch,davidvgalbraith/elasticsearch,kimimj/elasticsearch,iacdingping/elasticsearch,cwurm/elasticsearch,ivansun1010/elasticsearch,lks21c/elasticsearch,btiernay/elasticsearch,jbertouch/elasticsearch,MetSystem/elasticsearch,nazarewk/elasticsearch,GlenRSmith/elasticsearch,iacdingping/elasticsearch,Liziyao/elasticsearch,uboness/elasticsearch,feiqitian/elasticsearch,hirdesh2008/elasticsearch,alexkuk/elasticsearch,himanshuag/elasticsearch,diendt/elasticsearch,fred84/elasticsearch,tkssharma/elasticsearch,pranavraman/elasticsearch,easonC/elasticsearch,glefloch/elasticsearch,dantuffery/elasticsearch,naveenhooda2000/elasticsearch,zeroctu/elasticsearch,easonC/elasticsearch,jprante/elasticsearch,xingguang2013/elasticsearch,jchampion/elasticsearch,tcucchietti/elasticsearch,Chhunlong/elasticsearch,scorpionvicky/elasticsearch,JSCooke/elasticsearch,henakamaMSFT/elasticsearch,MichaelLiZhou/elasticsearch,vrkansagara/elasticsearch,Siddartha07/elasticsearch,rento19962/elasticsearch,jeteve/elasticsearch,wbowling/elasticsearch,dantuffery/elasticsearch,mute/elasticsearch,infusionsoft/elasticsearch,henakamaMSFT/elasticsearch,nknize/elasticsearch,peschlowp/elasticsearch,zhiqinghuang/elasticsearch,nrkkalyan/elasticsearch,PhaedrusTheGreek/elasticsearch,mapr/elasticsearch,adrianbk/elasticsearch,himanshuag/elasticsearch,MaineC/elasticsearch,umeshdangat/elasticsearch,Brijeshrpatel9/elasticsearch,hanswang/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,infusionsoft/elasticsearch,ThiagoGarciaAlves/elasticsearch,Flipkart/elasticsearch,franklanganke/elasticsearch,Shekharrajak/elasticsearch,nknize/elasticsearch,18098924759/elasticsearch,milodky/elasticsearch,nellicus/elasticsearch,mm0/elasticsearch,awislowski/elasticsearch,sc0ttkclark/elasticsearch,iantruslove/elasticsearch,mjason3/elasticsearch,amaliujia/elasticsearch,mikemccand/elasticsearch,mgalushka/elasticsearch,achow/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,nilabhsagar/elasticsearch,sposam/elasticsearch,wangyuxue/elasticsearch,slavau/elasticsearch,jimhooker2002/elasticsearch,beiske/elasticsearch,Asimov4/elasticsearch,kkirsche/elasticsearch,LewayneNaidoo/elasticsearch,phani546/elasticsearch,fforbeck/elasticsearch,Helen-Zhao/elasticsearch,codebunt/elasticsearch,kaneshin/elasticsearch,strapdata/elassandra-test,ThalaivaStars/OrgRepo1,btiernay/elasticsearch,qwerty4030/elasticsearch,andrewvc/elasticsearch,uboness/elasticsearch,jeteve/elasticsearch,djschny/elasticsearch,huypx1292/elasticsearch,mgalushka/elasticsearch,hanst/elasticsearch,fubuki/elasticsearch,weipinghe/elasticsearch,dongjoon-hyun/elasticsearch,apepper/elasticsearch,golubev/elasticsearch,tkssharma/elasticsearch,queirozfcom/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,camilojd/elasticsearch,onegambler/elasticsearch,dongjoon-hyun/elasticsearch,hydro2k/elasticsearch,Clairebi/ElasticsearchClone,hanswang/elasticsearch,petabytedata/elasticsearch,dpursehouse/elasticsearch,bestwpw/elasticsearch,petabytedata/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,aparo/elasticsearch,slavau/elasticsearch,myelin/elasticsearch,zhiqinghuang/elasticsearch,wbowling/elasticsearch,Charlesdong/elasticsearch,davidvgalbraith/elasticsearch,ZTE-PaaS/elasticsearch,Kakakakakku/elasticsearch,kubum/elasticsearch,nilabhsagar/elasticsearch,jpountz/elasticsearch,mikemccand/elasticsearch,kubum/elasticsearch,lzo/elasticsearch-1,wenpos/elasticsearch,lydonchandra/elasticsearch,Brijeshrpatel9/elasticsearch,lydonchandra/elasticsearch,hafkensite/elasticsearch,Asimov4/elasticsearch,weipinghe/elasticsearch,pranavraman/elasticsearch,masaruh/elasticsearch,humandb/elasticsearch,bestwpw/elasticsearch,yuy168/elasticsearch,MaineC/elasticsearch,cnfire/elasticsearch-1,javachengwc/elasticsearch,drewr/elasticsearch,sjohnr/elasticsearch,JackyMai/elasticsearch,andrewvc/elasticsearch,cnfire/elasticsearch-1,fred84/elasticsearch,adrianbk/elasticsearch,sposam/elasticsearch,JervyShi/elasticsearch,kcompher/elasticsearch,kaneshin/elasticsearch,mjhennig/elasticsearch,snikch/elasticsearch,snikch/elasticsearch,Microsoft/elasticsearch,snikch/elasticsearch,marcuswr/elasticsearch-dateline,salyh/elasticsearch,truemped/elasticsearch,coding0011/elasticsearch,MetSystem/elasticsearch,kimimj/elasticsearch,achow/elasticsearch,LewayneNaidoo/elasticsearch,sarwarbhuiyan/elasticsearch,Helen-Zhao/elasticsearch,JervyShi/elasticsearch,jango2015/elasticsearch,huanzhong/elasticsearch,Fsero/elasticsearch,F0lha/elasticsearch,skearns64/elasticsearch,myelin/elasticsearch,mapr/elasticsearch,vorce/es-metrics,kalimatas/elasticsearch,thecocce/elasticsearch,salyh/elasticsearch,wuranbo/elasticsearch,tahaemin/elasticsearch,mjhennig/elasticsearch,sscarduzio/elasticsearch,clintongormley/elasticsearch,trangvh/elasticsearch,codebunt/elasticsearch,lydonchandra/elasticsearch,jchampion/elasticsearch,yynil/elasticsearch,alexbrasetvik/elasticsearch,Rygbee/elasticsearch,kunallimaye/elasticsearch,huanzhong/elasticsearch,njlawton/elasticsearch,jchampion/elasticsearch,xingguang2013/elasticsearch,gfyoung/elasticsearch,szroland/elasticsearch,i-am-Nathan/elasticsearch,abibell/elasticsearch,areek/elasticsearch,chrismwendt/elasticsearch,hirdesh2008/elasticsearch,ydsakyclguozi/elasticsearch,springning/elasticsearch,queirozfcom/elasticsearch,wuranbo/elasticsearch,feiqitian/elasticsearch,Widen/elasticsearch,queirozfcom/elasticsearch,rento19962/elasticsearch,ajhalani/elasticsearch,Widen/elasticsearch,jeteve/elasticsearch,markwalkom/elasticsearch,MisterAndersen/elasticsearch,abibell/elasticsearch,zeroctu/elasticsearch,yynil/elasticsearch,sarwarbhuiyan/elasticsearch,jchampion/elasticsearch,lzo/elasticsearch-1,ImpressTV/elasticsearch,areek/elasticsearch,Ansh90/elasticsearch,iacdingping/elasticsearch,Siddartha07/elasticsearch,vingupta3/elasticsearch,mbrukman/elasticsearch,boliza/elasticsearch,lmtwga/elasticsearch,yuy168/elasticsearch,sjohnr/elasticsearch,chirilo/elasticsearch,yuy168/elasticsearch,petabytedata/elasticsearch,smflorentino/elasticsearch,ouyangkongtong/elasticsearch,mohit/elasticsearch,vvcephei/elasticsearch,beiske/elasticsearch,tsohil/elasticsearch,HonzaKral/elasticsearch,beiske/elasticsearch,wangyuxue/elasticsearch,dylan8902/elasticsearch,Chhunlong/elasticsearch,MjAbuz/elasticsearch,sc0ttkclark/elasticsearch,yynil/elasticsearch,jsgao0/elasticsearch,sarwarbhuiyan/elasticsearch,diendt/elasticsearch,caengcjd/elasticsearch,hirdesh2008/elasticsearch,lchennup/elasticsearch,mcku/elasticsearch,amaliujia/elasticsearch,SergVro/elasticsearch,jsgao0/elasticsearch,weipinghe/elasticsearch,fforbeck/elasticsearch,skearns64/elasticsearch,codebunt/elasticsearch,mortonsykes/elasticsearch,vietlq/elasticsearch,vvcephei/elasticsearch,zeroctu/elasticsearch,uschindler/elasticsearch,mute/elasticsearch,xuzha/elasticsearch,jango2015/elasticsearch,mnylen/elasticsearch,18098924759/elasticsearch,a2lin/elasticsearch,jpountz/elasticsearch,rento19962/elasticsearch,mnylen/elasticsearch,kalburgimanjunath/elasticsearch,HarishAtGitHub/elasticsearch,qwerty4030/elasticsearch,AleksKochev/elasticsearch,diendt/elasticsearch,alexbrasetvik/elasticsearch,zhaocloud/elasticsearch,kenshin233/elasticsearch,IanvsPoplicola/elasticsearch,LewayneNaidoo/elasticsearch,mcku/elasticsearch,Siddartha07/elasticsearch,palecur/elasticsearch,rmuir/elasticsearch,aglne/elasticsearch,lchennup/elasticsearch,ImpressTV/elasticsearch,sdauletau/elasticsearch,sscarduzio/elasticsearch,Shekharrajak/elasticsearch,micpalmia/elasticsearch,maddin2016/elasticsearch,huypx1292/elasticsearch,sarwarbhuiyan/elasticsearch,yynil/elasticsearch,hanst/elasticsearch,Microsoft/elasticsearch,andrejserafim/elasticsearch,NBSW/elasticsearch,episerver/elasticsearch,a2lin/elasticsearch,Widen/elasticsearch,artnowo/elasticsearch,yynil/elasticsearch,fernandozhu/elasticsearch,avikurapati/elasticsearch,Widen/elasticsearch,schonfeld/elasticsearch,wittyameta/elasticsearch,mjhennig/elasticsearch,micpalmia/elasticsearch,golubev/elasticsearch,aparo/elasticsearch,MjAbuz/elasticsearch,hanswang/elasticsearch,lks21c/elasticsearch,kimchy/elasticsearch,franklanganke/elasticsearch,socialrank/elasticsearch,iantruslove/elasticsearch,socialrank/elasticsearch,myelin/elasticsearch,onegambler/elasticsearch,ajhalani/elasticsearch,fforbeck/elasticsearch,NBSW/elasticsearch,rento19962/elasticsearch,huanzhong/elasticsearch,drewr/elasticsearch,sscarduzio/elasticsearch,shreejay/elasticsearch,rlugojr/elasticsearch,Flipkart/elasticsearch,PhaedrusTheGreek/elasticsearch,pozhidaevak/elasticsearch,brandonkearby/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,socialrank/elasticsearch,rmuir/elasticsearch,ThiagoGarciaAlves/elasticsearch,elancom/elasticsearch,KimTaehee/elasticsearch,drewr/elasticsearch,abibell/elasticsearch,beiske/elasticsearch,acchen97/elasticsearch,beiske/elasticsearch,hydro2k/elasticsearch,schonfeld/elasticsearch,ricardocerq/elasticsearch,mrorii/elasticsearch,sposam/elasticsearch,umeshdangat/elasticsearch,ImpressTV/elasticsearch,kalburgimanjunath/elasticsearch,PhaedrusTheGreek/elasticsearch,loconsolutions/elasticsearch,pranavraman/elasticsearch,mgalushka/elasticsearch,hanst/elasticsearch,geidies/elasticsearch,nazarewk/elasticsearch,kenshin233/elasticsearch,LeoYao/elasticsearch,cnfire/elasticsearch-1,maddin2016/elasticsearch,kkirsche/elasticsearch,gingerwizard/elasticsearch,jbertouch/elasticsearch,phani546/elasticsearch,clintongormley/elasticsearch,springning/elasticsearch,karthikjaps/elasticsearch,dataduke/elasticsearch,weipinghe/elasticsearch,smflorentino/elasticsearch,combinatorist/elasticsearch,karthikjaps/elasticsearch,IanvsPoplicola/elasticsearch,clintongormley/elasticsearch,tcucchietti/elasticsearch,golubev/elasticsearch,peschlowp/elasticsearch,gfyoung/elasticsearch,micpalmia/elasticsearch,heng4fun/elasticsearch,smflorentino/elasticsearch,awislowski/elasticsearch,YosuaMichael/elasticsearch,clintongormley/elasticsearch,dataduke/elasticsearch,robin13/elasticsearch,chirilo/elasticsearch,gmarz/elasticsearch,adrianbk/elasticsearch,sjohnr/elasticsearch,pablocastro/elasticsearch,jw0201/elastic,anti-social/elasticsearch,phani546/elasticsearch,VukDukic/elasticsearch,martinstuga/elasticsearch,jango2015/elasticsearch,nilabhsagar/elasticsearch,easonC/elasticsearch,sreeramjayan/elasticsearch,achow/elasticsearch,fekaputra/elasticsearch,amaliujia/elasticsearch,geidies/elasticsearch,vorce/es-metrics,Widen/elasticsearch,javachengwc/elasticsearch,mnylen/elasticsearch,ydsakyclguozi/elasticsearch,loconsolutions/elasticsearch,loconsolutions/elasticsearch,smflorentino/elasticsearch,fekaputra/elasticsearch,humandb/elasticsearch,caengcjd/elasticsearch,jaynblue/elasticsearch,18098924759/elasticsearch,avikurapati/elasticsearch,chrismwendt/elasticsearch,chirilo/elasticsearch,elancom/elasticsearch,rajanm/elasticsearch,gfyoung/elasticsearch,ulkas/elasticsearch,wimvds/elasticsearch,iantruslove/elasticsearch,episerver/elasticsearch,a2lin/elasticsearch,wittyameta/elasticsearch,awislowski/elasticsearch,onegambler/elasticsearch,palecur/elasticsearch,anti-social/elasticsearch,geidies/elasticsearch,sreeramjayan/elasticsearch,markllama/elasticsearch,Uiho/elasticsearch,MichaelLiZhou/elasticsearch,hirdesh2008/elasticsearch,djschny/elasticsearch,yanjunh/elasticsearch,maddin2016/elasticsearch,bestwpw/elasticsearch,humandb/elasticsearch,hafkensite/elasticsearch,mrorii/elasticsearch,slavau/elasticsearch,djschny/elasticsearch,AleksKochev/elasticsearch,koxa29/elasticsearch,pritishppai/elasticsearch,PhaedrusTheGreek/elasticsearch,abhijitiitr/es,TonyChai24/ESSource,s1monw/elasticsearch,acchen97/elasticsearch,LewayneNaidoo/elasticsearch,feiqitian/elasticsearch,nrkkalyan/elasticsearch,Uiho/elasticsearch,strapdata/elassandra5-rc,btiernay/elasticsearch,hechunwen/elasticsearch,sdauletau/elasticsearch,bawse/elasticsearch,acchen97/elasticsearch,ivansun1010/elasticsearch,tsohil/elasticsearch,amit-shar/elasticsearch,iamjakob/elasticsearch,Siddartha07/elasticsearch,sposam/elasticsearch,Collaborne/elasticsearch,alexkuk/elasticsearch,shreejay/elasticsearch,andrestc/elasticsearch,JervyShi/elasticsearch,qwerty4030/elasticsearch,drewr/elasticsearch,jpountz/elasticsearch,njlawton/elasticsearch,pranavraman/elasticsearch,mrorii/elasticsearch,maddin2016/elasticsearch,F0lha/elasticsearch,springning/elasticsearch,thecocce/elasticsearch,kenshin233/elasticsearch,PhaedrusTheGreek/elasticsearch,mute/elasticsearch,kingaj/elasticsearch,gingerwizard/elasticsearch,Collaborne/elasticsearch,opendatasoft/elasticsearch,GlenRSmith/elasticsearch,dataduke/elasticsearch,ThiagoGarciaAlves/elasticsearch,markwalkom/elasticsearch,ulkas/elasticsearch,ImpressTV/elasticsearch,nomoa/elasticsearch,TonyChai24/ESSource,SergVro/elasticsearch,yongminxia/elasticsearch,yanjunh/elasticsearch,jprante/elasticsearch,fooljohnny/elasticsearch,dylan8902/elasticsearch,szroland/elasticsearch,obourgain/elasticsearch,raishiv/elasticsearch,brandonkearby/elasticsearch,alexbrasetvik/elasticsearch,Charlesdong/elasticsearch,geidies/elasticsearch,janmejay/elasticsearch,raishiv/elasticsearch,andrejserafim/elasticsearch,huypx1292/elasticsearch,hechunwen/elasticsearch,elancom/elasticsearch,brandonkearby/elasticsearch,artnowo/elasticsearch,nrkkalyan/elasticsearch,ThalaivaStars/OrgRepo1,shreejay/elasticsearch,gmarz/elasticsearch,TonyChai24/ESSource,EasonYi/elasticsearch,wimvds/elasticsearch,yynil/elasticsearch,vingupta3/elasticsearch,hydro2k/elasticsearch,khiraiwa/elasticsearch,jango2015/elasticsearch,pozhidaevak/elasticsearch,scorpionvicky/elasticsearch,YosuaMichael/elasticsearch,dataduke/elasticsearch,mnylen/elasticsearch,ckclark/elasticsearch,18098924759/elasticsearch,xpandan/elasticsearch,HarishAtGitHub/elasticsearch,yongminxia/elasticsearch,vvcephei/elasticsearch,mohit/elasticsearch,apepper/elasticsearch,kevinkluge/elasticsearch,tahaemin/elasticsearch,abibell/elasticsearch,kevinkluge/elasticsearch,peschlowp/elasticsearch,himanshuag/elasticsearch,karthikjaps/elasticsearch,weipinghe/elasticsearch,dylan8902/elasticsearch,ivansun1010/elasticsearch,kunallimaye/elasticsearch,xingguang2013/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,sc0ttkclark/elasticsearch,areek/elasticsearch,wittyameta/elasticsearch,yanjunh/elasticsearch,skearns64/elasticsearch,opendatasoft/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,Uiho/elasticsearch,masaruh/elasticsearch,JackyMai/elasticsearch,tebriel/elasticsearch,sreeramjayan/elasticsearch,kevinkluge/elasticsearch,rhoml/elasticsearch,petmit/elasticsearch,jw0201/elastic,Helen-Zhao/elasticsearch,ImpressTV/elasticsearch,kingaj/elasticsearch,alexksikes/elasticsearch,JervyShi/elasticsearch,opendatasoft/elasticsearch,F0lha/elasticsearch,myelin/elasticsearch,rento19962/elasticsearch,polyfractal/elasticsearch,tsohil/elasticsearch,KimTaehee/elasticsearch,zhiqinghuang/elasticsearch,cwurm/elasticsearch,peschlowp/elasticsearch,raishiv/elasticsearch,naveenhooda2000/elasticsearch,Ansh90/elasticsearch,ThalaivaStars/OrgRepo1,fooljohnny/elasticsearch,hanswang/elasticsearch,schonfeld/elasticsearch,nellicus/elasticsearch,mortonsykes/elasticsearch,rhoml/elasticsearch,ouyangkongtong/elasticsearch,ckclark/elasticsearch,markharwood/elasticsearch,xingguang2013/elasticsearch,jw0201/elastic,Stacey-Gammon/elasticsearch,HonzaKral/elasticsearch,bawse/elasticsearch,schonfeld/elasticsearch,i-am-Nathan/elasticsearch,wbowling/elasticsearch,overcome/elasticsearch,girirajsharma/elasticsearch,kimimj/elasticsearch,mnylen/elasticsearch,hechunwen/elasticsearch,markllama/elasticsearch,bestwpw/elasticsearch,likaiwalkman/elasticsearch,wenpos/elasticsearch,jprante/elasticsearch,davidvgalbraith/elasticsearch,YosuaMichael/elasticsearch,sjohnr/elasticsearch,jw0201/elastic,fubuki/elasticsearch,cnfire/elasticsearch-1,JSCooke/elasticsearch,weipinghe/elasticsearch,Flipkart/elasticsearch,ESamir/elasticsearch,Chhunlong/elasticsearch,Microsoft/elasticsearch,polyfractal/elasticsearch,socialrank/elasticsearch,Rygbee/elasticsearch,libosu/elasticsearch,knight1128/elasticsearch,kalburgimanjunath/elasticsearch,sposam/elasticsearch,C-Bish/elasticsearch,mikemccand/elasticsearch,areek/elasticsearch,andrestc/elasticsearch,combinatorist/elasticsearch,robin13/elasticsearch,alexbrasetvik/elasticsearch,Widen/elasticsearch,nezirus/elasticsearch,Collaborne/elasticsearch,fubuki/elasticsearch,humandb/elasticsearch,ricardocerq/elasticsearch,rmuir/elasticsearch,winstonewert/elasticsearch,aglne/elasticsearch,kcompher/elasticsearch,linglaiyao1314/elasticsearch,cnfire/elasticsearch-1,ulkas/elasticsearch,kunallimaye/elasticsearch,xuzha/elasticsearch,JervyShi/elasticsearch,SergVro/elasticsearch,wangyuxue/elasticsearch,janmejay/elasticsearch,avikurapati/elasticsearch,kimimj/elasticsearch,nrkkalyan/elasticsearch,vvcephei/elasticsearch,polyfractal/elasticsearch,knight1128/elasticsearch,zhiqinghuang/elasticsearch,nezirus/elasticsearch,Kakakakakku/elasticsearch,tebriel/elasticsearch,khiraiwa/elasticsearch,liweinan0423/elasticsearch,henakamaMSFT/elasticsearch,vrkansagara/elasticsearch,avikurapati/elasticsearch,girirajsharma/elasticsearch,vroyer/elassandra,alexshadow007/elasticsearch,lks21c/elasticsearch,mcku/elasticsearch,linglaiyao1314/elasticsearch,ajhalani/elasticsearch,tahaemin/elasticsearch,mrorii/elasticsearch,geidies/elasticsearch,cnfire/elasticsearch-1,Stacey-Gammon/elasticsearch,Helen-Zhao/elasticsearch,pablocastro/elasticsearch,mrorii/elasticsearch,naveenhooda2000/elasticsearch,kunallimaye/elasticsearch,vrkansagara/elasticsearch,strapdata/elassandra-test,overcome/elasticsearch,springning/elasticsearch,KimTaehee/elasticsearch,luiseduardohdbackup/elasticsearch,iacdingping/elasticsearch,mapr/elasticsearch,xpandan/elasticsearch,girirajsharma/elasticsearch,tsohil/elasticsearch,strapdata/elassandra-test,bestwpw/elasticsearch,yuy168/elasticsearch,lightslife/elasticsearch,AshishThakur/elasticsearch,caengcjd/elasticsearch,iacdingping/elasticsearch,kalburgimanjunath/elasticsearch,jimhooker2002/elasticsearch,easonC/elasticsearch,markllama/elasticsearch,ImpressTV/elasticsearch,lydonchandra/elasticsearch,himanshuag/elasticsearch,EasonYi/elasticsearch,janmejay/elasticsearch,Brijeshrpatel9/elasticsearch,HarishAtGitHub/elasticsearch,karthikjaps/elasticsearch,markharwood/elasticsearch,davidvgalbraith/elasticsearch,sarwarbhuiyan/elasticsearch,tkssharma/elasticsearch,strapdata/elassandra-test,yongminxia/elasticsearch,C-Bish/elasticsearch,drewr/elasticsearch,mapr/elasticsearch,lmtwga/elasticsearch,aglne/elasticsearch,andrestc/elasticsearch,onegambler/elasticsearch,adrianbk/elasticsearch,dantuffery/elasticsearch,koxa29/elasticsearch,aglne/elasticsearch,xuzha/elasticsearch,ydsakyclguozi/elasticsearch,mkis-/elasticsearch,petabytedata/elasticsearch,chrismwendt/elasticsearch,JSCooke/elasticsearch,kalimatas/elasticsearch,shreejay/elasticsearch,elasticdog/elasticsearch,TonyChai24/ESSource,Rygbee/elasticsearch,JSCooke/elasticsearch,GlenRSmith/elasticsearch,infusionsoft/elasticsearch,jaynblue/elasticsearch,lchennup/elasticsearch,Ansh90/elasticsearch,coding0011/elasticsearch,nknize/elasticsearch,Fsero/elasticsearch,kenshin233/elasticsearch,koxa29/elasticsearch,Asimov4/elasticsearch,huypx1292/elasticsearch,pritishppai/elasticsearch,obourgain/elasticsearch,mkis-/elasticsearch,mbrukman/elasticsearch,bestwpw/elasticsearch,Fsero/elasticsearch,kalburgimanjunath/elasticsearch,rmuir/elasticsearch,StefanGor/elasticsearch,franklanganke/elasticsearch,jaynblue/elasticsearch,iamjakob/elasticsearch,humandb/elasticsearch,mkis-/elasticsearch,kevinkluge/elasticsearch,Charlesdong/elasticsearch,AndreKR/elasticsearch,huanzhong/elasticsearch,xpandan/elasticsearch,naveenhooda2000/elasticsearch,Chhunlong/elasticsearch,artnowo/elasticsearch,rajanm/elasticsearch,jimhooker2002/elasticsearch,Liziyao/elasticsearch,HonzaKral/elasticsearch,vrkansagara/elasticsearch,YosuaMichael/elasticsearch,peschlowp/elasticsearch,ThiagoGarciaAlves/elasticsearch,micpalmia/elasticsearch,huypx1292/elasticsearch,kubum/elasticsearch,xingguang2013/elasticsearch,dylan8902/elasticsearch,schonfeld/elasticsearch,18098924759/elasticsearch,tsohil/elasticsearch,markwalkom/elasticsearch,ImpressTV/elasticsearch,overcome/elasticsearch,hydro2k/elasticsearch,tebriel/elasticsearch,tahaemin/elasticsearch,ESamir/elasticsearch,Uiho/elasticsearch,Clairebi/ElasticsearchClone,mbrukman/elasticsearch,elancom/elasticsearch,myelin/elasticsearch,truemped/elasticsearch,vroyer/elasticassandra,yuy168/elasticsearch,pablocastro/elasticsearch,MjAbuz/elasticsearch,Liziyao/elasticsearch,avikurapati/elasticsearch,pablocastro/elasticsearch,mm0/elasticsearch,vroyer/elassandra,nrkkalyan/elasticsearch,NBSW/elasticsearch,scottsom/elasticsearch,golubev/elasticsearch,jsgao0/elasticsearch,likaiwalkman/elasticsearch,pranavraman/elasticsearch,ajhalani/elasticsearch,alexshadow007/elasticsearch,lydonchandra/elasticsearch,kingaj/elasticsearch,jchampion/elasticsearch,hafkensite/elasticsearch,springning/elasticsearch,aparo/elasticsearch,areek/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,kubum/elasticsearch,AndreKR/elasticsearch,achow/elasticsearch,markwalkom/elasticsearch,mm0/elasticsearch,gfyoung/elasticsearch,abhijitiitr/es,artnowo/elasticsearch,MetSystem/elasticsearch,MisterAndersen/elasticsearch,fforbeck/elasticsearch,Fsero/elasticsearch,gmarz/elasticsearch,vrkansagara/elasticsearch,sneivandt/elasticsearch,milodky/elasticsearch,TonyChai24/ESSource,petabytedata/elasticsearch,Ansh90/elasticsearch,Clairebi/ElasticsearchClone,apepper/elasticsearch,Ansh90/elasticsearch,huanzhong/elasticsearch,ESamir/elasticsearch,aparo/elasticsearch,alexksikes/elasticsearch,EasonYi/elasticsearch,feiqitian/elasticsearch,pranavraman/elasticsearch,cwurm/elasticsearch,mikemccand/elasticsearch,golubev/elasticsearch,fernandozhu/elasticsearch,opendatasoft/elasticsearch,masterweb121/elasticsearch,strapdata/elassandra5-rc,AleksKochev/elasticsearch,janmejay/elasticsearch,achow/elasticsearch,dataduke/elasticsearch,libosu/elasticsearch,alexksikes/elasticsearch,amit-shar/elasticsearch,zhaocloud/elasticsearch,jprante/elasticsearch,salyh/elasticsearch,maddin2016/elasticsearch,jango2015/elasticsearch,jango2015/elasticsearch,camilojd/elasticsearch,fubuki/elasticsearch,mcku/elasticsearch,Uiho/elasticsearch,AndreKR/elasticsearch,luiseduardohdbackup/elasticsearch,hirdesh2008/elasticsearch,mjhennig/elasticsearch,mcku/elasticsearch,sc0ttkclark/elasticsearch,gingerwizard/elasticsearch,sneivandt/elasticsearch,knight1128/elasticsearch,huanzhong/elasticsearch,tsohil/elasticsearch,kunallimaye/elasticsearch,strapdata/elassandra-test,kevinkluge/elasticsearch,MaineC/elasticsearch,EasonYi/elasticsearch,szroland/elasticsearch,ivansun1010/elasticsearch,kimimj/elasticsearch,tkssharma/elasticsearch,lzo/elasticsearch-1,Widen/elasticsearch,MetSystem/elasticsearch,sreeramjayan/elasticsearch,hafkensite/elasticsearch,Collaborne/elasticsearch,fred84/elasticsearch,janmejay/elasticsearch,zeroctu/elasticsearch,glefloch/elasticsearch,lchennup/elasticsearch,yongminxia/elasticsearch,polyfractal/elasticsearch,phani546/elasticsearch,nomoa/elasticsearch,sarwarbhuiyan/elasticsearch,hirdesh2008/elasticsearch,iamjakob/elasticsearch,scottsom/elasticsearch,ydsakyclguozi/elasticsearch,truemped/elasticsearch,hanswang/elasticsearch,rhoml/elasticsearch,dataduke/elasticsearch,alexksikes/elasticsearch,salyh/elasticsearch,gmarz/elasticsearch,tahaemin/elasticsearch,petmit/elasticsearch,fred84/elasticsearch,nrkkalyan/elasticsearch,martinstuga/elasticsearch,humandb/elasticsearch,petabytedata/elasticsearch,mbrukman/elasticsearch,ZTE-PaaS/elasticsearch,masterweb121/elasticsearch,libosu/elasticsearch,sarwarbhuiyan/elasticsearch,winstonewert/elasticsearch,Siddartha07/elasticsearch,vingupta3/elasticsearch,jprante/elasticsearch,combinatorist/elasticsearch,scorpionvicky/elasticsearch,chirilo/elasticsearch,markllama/elasticsearch,IanvsPoplicola/elasticsearch,markharwood/elasticsearch,PhaedrusTheGreek/elasticsearch,HarishAtGitHub/elasticsearch,VukDukic/elasticsearch,fekaputra/elasticsearch,hechunwen/elasticsearch,AndreKR/elasticsearch,bawse/elasticsearch,hanswang/elasticsearch,mbrukman/elasticsearch,wbowling/elasticsearch,YosuaMichael/elasticsearch,lzo/elasticsearch-1,likaiwalkman/elasticsearch,rlugojr/elasticsearch,koxa29/elasticsearch,kcompher/elasticsearch,ouyangkongtong/elasticsearch,kaneshin/elasticsearch,kingaj/elasticsearch,wbowling/elasticsearch,AndreKR/elasticsearch,heng4fun/elasticsearch,kunallimaye/elasticsearch,Brijeshrpatel9/elasticsearch,yongminxia/elasticsearch,ckclark/elasticsearch,robin13/elasticsearch,kaneshin/elasticsearch,wuranbo/elasticsearch,kimimj/elasticsearch,sneivandt/elasticsearch,hydro2k/elasticsearch,xpandan/elasticsearch,MisterAndersen/elasticsearch,markharwood/elasticsearch,scorpionvicky/elasticsearch,jaynblue/elasticsearch,opendatasoft/elasticsearch,jsgao0/elasticsearch,Brijeshrpatel9/elasticsearch,nazarewk/elasticsearch,zkidkid/elasticsearch,raishiv/elasticsearch,pozhidaevak/elasticsearch,i-am-Nathan/elasticsearch,ydsakyclguozi/elasticsearch,ThiagoGarciaAlves/elasticsearch,gingerwizard/elasticsearch,nellicus/elasticsearch,sjohnr/elasticsearch,MisterAndersen/elasticsearch,Kakakakakku/elasticsearch,alexbrasetvik/elasticsearch,amit-shar/elasticsearch,socialrank/elasticsearch,yanjunh/elasticsearch,amaliujia/elasticsearch,martinstuga/elasticsearch,obourgain/elasticsearch,JervyShi/elasticsearch,ThalaivaStars/OrgRepo1,AleksKochev/elasticsearch,mgalushka/elasticsearch,amaliujia/elasticsearch,linglaiyao1314/elasticsearch,ouyangkongtong/elasticsearch,wimvds/elasticsearch,mmaracic/elasticsearch,EasonYi/elasticsearch,heng4fun/elasticsearch,lks21c/elasticsearch,milodky/elasticsearch,MaineC/elasticsearch,KimTaehee/elasticsearch,hydro2k/elasticsearch,rajanm/elasticsearch,StefanGor/elasticsearch,palecur/elasticsearch,andrejserafim/elasticsearch,yuy168/elasticsearch,zkidkid/elasticsearch,Clairebi/ElasticsearchClone,jimczi/elasticsearch,shreejay/elasticsearch,uschindler/elasticsearch,IanvsPoplicola/elasticsearch,nellicus/elasticsearch,18098924759/elasticsearch,spiegela/elasticsearch,micpalmia/elasticsearch,Asimov4/elasticsearch,rmuir/elasticsearch,dpursehouse/elasticsearch,kevinkluge/elasticsearch,scottsom/elasticsearch,jw0201/elastic,s1monw/elasticsearch,bawse/elasticsearch,dongjoon-hyun/elasticsearch,coding0011/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,kingaj/elasticsearch,anti-social/elasticsearch,fubuki/elasticsearch,wangtuo/elasticsearch,sc0ttkclark/elasticsearch,i-am-Nathan/elasticsearch,F0lha/elasticsearch,codebunt/elasticsearch,kcompher/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,himanshuag/elasticsearch,dylan8902/elasticsearch,mjhennig/elasticsearch,nezirus/elasticsearch,kkirsche/elasticsearch,snikch/elasticsearch,drewr/elasticsearch,kkirsche/elasticsearch,Collaborne/elasticsearch,strapdata/elassandra,sauravmondallive/elasticsearch,LewayneNaidoo/elasticsearch,martinstuga/elasticsearch,libosu/elasticsearch,milodky/elasticsearch,uschindler/elasticsearch,elancom/elasticsearch,C-Bish/elasticsearch,mm0/elasticsearch,xingguang2013/elasticsearch,sjohnr/elasticsearch,slavau/elasticsearch,IanvsPoplicola/elasticsearch,andrejserafim/elasticsearch,petmit/elasticsearch,Brijeshrpatel9/elasticsearch,fubuki/elasticsearch,huypx1292/elasticsearch,kalburgimanjunath/elasticsearch,luiseduardohdbackup/elasticsearch,Uiho/elasticsearch,mohit/elasticsearch,obourgain/elasticsearch,rento19962/elasticsearch,jsgao0/elasticsearch,infusionsoft/elasticsearch,skearns64/elasticsearch,caengcjd/elasticsearch,slavau/elasticsearch,phani546/elasticsearch,springning/elasticsearch,iantruslove/elasticsearch,btiernay/elasticsearch,markharwood/elasticsearch,ydsakyclguozi/elasticsearch,mjason3/elasticsearch,rajanm/elasticsearch,kenshin233/elasticsearch,wimvds/elasticsearch,tahaemin/elasticsearch,kimimj/elasticsearch,spiegela/elasticsearch,ESamir/elasticsearch,thecocce/elasticsearch,kalimatas/elasticsearch,mapr/elasticsearch,KimTaehee/elasticsearch,tcucchietti/elasticsearch,yongminxia/elasticsearch,liweinan0423/elasticsearch,ulkas/elasticsearch,VukDukic/elasticsearch,jeteve/elasticsearch,hanst/elasticsearch,LeoYao/elasticsearch,tkssharma/elasticsearch,gingerwizard/elasticsearch,knight1128/elasticsearch,JackyMai/elasticsearch,vroyer/elassandra,opendatasoft/elasticsearch,jbertouch/elasticsearch,iantruslove/elasticsearch,mm0/elasticsearch,javachengwc/elasticsearch,tcucchietti/elasticsearch,wayeast/elasticsearch,mortonsykes/elasticsearch,kalimatas/elasticsearch,lchennup/elasticsearch,rhoml/elasticsearch,wayeast/elasticsearch,bestwpw/elasticsearch,wangtuo/elasticsearch,uschindler/elasticsearch,mohsinh/elasticsearch,nomoa/elasticsearch,MichaelLiZhou/elasticsearch,polyfractal/elasticsearch,fekaputra/elasticsearch,brwe/elasticsearch,sc0ttkclark/elasticsearch,liweinan0423/elasticsearch,brwe/elasticsearch,achow/elasticsearch,zhiqinghuang/elasticsearch,franklanganke/elasticsearch,kaneshin/elasticsearch,alexshadow007/elasticsearch,knight1128/elasticsearch,ESamir/elasticsearch,fernandozhu/elasticsearch,ouyangkongtong/elasticsearch,lzo/elasticsearch-1,ajhalani/elasticsearch,brwe/elasticsearch,luiseduardohdbackup/elasticsearch,YosuaMichael/elasticsearch,Charlesdong/elasticsearch,drewr/elasticsearch,szroland/elasticsearch,kenshin233/elasticsearch,mohsinh/elasticsearch,Uiho/elasticsearch,ouyangkongtong/elasticsearch,combinatorist/elasticsearch,pritishppai/elasticsearch,kunallimaye/elasticsearch,gingerwizard/elasticsearch,jeteve/elasticsearch,linglaiyao1314/elasticsearch,strapdata/elassandra,anti-social/elasticsearch,thecocce/elasticsearch,phani546/elasticsearch,himanshuag/elasticsearch,aparo/elasticsearch,amit-shar/elasticsearch,Chhunlong/elasticsearch,kubum/elasticsearch,zhiqinghuang/elasticsearch,boliza/elasticsearch,dpursehouse/elasticsearch,Liziyao/elasticsearch,brandonkearby/elasticsearch,yongminxia/elasticsearch,Clairebi/ElasticsearchClone,camilojd/elasticsearch,mbrukman/elasticsearch,Flipkart/elasticsearch,jimhooker2002/elasticsearch,mohsinh/elasticsearch,mgalushka/elasticsearch,brwe/elasticsearch,nellicus/elasticsearch,Ansh90/elasticsearch,jbertouch/elasticsearch,overcome/elasticsearch,mm0/elasticsearch,lightslife/elasticsearch,lmenezes/elasticsearch,Rygbee/elasticsearch,markharwood/elasticsearch,kimchy/elasticsearch,Shepard1212/elasticsearch,MetSystem/elasticsearch,lightslife/elasticsearch,petmit/elasticsearch,vingupta3/elasticsearch,khiraiwa/elasticsearch,strapdata/elassandra-test,Shepard1212/elasticsearch,wimvds/elasticsearch,truemped/elasticsearch,Rygbee/elasticsearch,dantuffery/elasticsearch,sposam/elasticsearch,linglaiyao1314/elasticsearch,mute/elasticsearch,raishiv/elasticsearch,amit-shar/elasticsearch,scorpionvicky/elasticsearch,martinstuga/elasticsearch,wittyameta/elasticsearch,pozhidaevak/elasticsearch,brwe/elasticsearch,Fsero/elasticsearch,snikch/elasticsearch,mnylen/elasticsearch,spiegela/elasticsearch,wayeast/elasticsearch,Kakakakakku/elasticsearch,apepper/elasticsearch,Flipkart/elasticsearch,jbertouch/elasticsearch,robin13/elasticsearch,wuranbo/elasticsearch,boliza/elasticsearch,sneivandt/elasticsearch,lmtwga/elasticsearch,ckclark/elasticsearch,mmaracic/elasticsearch,javachengwc/elasticsearch,jpountz/elasticsearch,strapdata/elassandra-test,lydonchandra/elasticsearch,dpursehouse/elasticsearch,iamjakob/elasticsearch,heng4fun/elasticsearch,mmaracic/elasticsearch,mohit/elasticsearch,mcku/elasticsearch,mute/elasticsearch,jimhooker2002/elasticsearch,gmarz/elasticsearch,feiqitian/elasticsearch,wangtuo/elasticsearch,jaynblue/elasticsearch,abibell/elasticsearch,kcompher/elasticsearch,C-Bish/elasticsearch,winstonewert/elasticsearch,nomoa/elasticsearch,btiernay/elasticsearch,amit-shar/elasticsearch,VukDukic/elasticsearch,kaneshin/elasticsearch,masterweb121/elasticsearch,onegambler/elasticsearch,AshishThakur/elasticsearch,zhaocloud/elasticsearch,wuranbo/elasticsearch,Liziyao/elasticsearch,camilojd/elasticsearch,winstonewert/elasticsearch,lzo/elasticsearch-1,hanst/elasticsearch,tebriel/elasticsearch,hafkensite/elasticsearch,chirilo/elasticsearch,henakamaMSFT/elasticsearch,knight1128/elasticsearch,naveenhooda2000/elasticsearch,xuzha/elasticsearch,acchen97/elasticsearch,yuy168/elasticsearch,AshishThakur/elasticsearch,vroyer/elasticassandra,marcuswr/elasticsearch-dateline,MichaelLiZhou/elasticsearch,fooljohnny/elasticsearch,queirozfcom/elasticsearch,qwerty4030/elasticsearch,mohsinh/elasticsearch,HarishAtGitHub/elasticsearch,lmenezes/elasticsearch,kubum/elasticsearch,Charlesdong/elasticsearch,jimczi/elasticsearch,rajanm/elasticsearch,alexshadow007/elasticsearch,MjAbuz/elasticsearch,awislowski/elasticsearch,davidvgalbraith/elasticsearch,tkssharma/elasticsearch,JackyMai/elasticsearch,fooljohnny/elasticsearch,HarishAtGitHub/elasticsearch,geidies/elasticsearch,mnylen/elasticsearch,nellicus/elasticsearch,knight1128/elasticsearch,lmtwga/elasticsearch,abibell/elasticsearch,rlugojr/elasticsearch,Chhunlong/elasticsearch,Shekharrajak/elasticsearch,pritishppai/elasticsearch,rhoml/elasticsearch,Asimov4/elasticsearch,huanzhong/elasticsearch,sdauletau/elasticsearch,s1monw/elasticsearch,MichaelLiZhou/elasticsearch,apepper/elasticsearch,mortonsykes/elasticsearch,alexkuk/elasticsearch,linglaiyao1314/elasticsearch,girirajsharma/elasticsearch,mortonsykes/elasticsearch,vvcephei/elasticsearch,mjhennig/elasticsearch,sposam/elasticsearch,thecocce/elasticsearch,elasticdog/elasticsearch,masaruh/elasticsearch,palecur/elasticsearch,winstonewert/elasticsearch,palecur/elasticsearch,KimTaehee/elasticsearch,kevinkluge/elasticsearch,jeteve/elasticsearch,a2lin/elasticsearch,jw0201/elastic,karthikjaps/elasticsearch,Rygbee/elasticsearch,tebriel/elasticsearch,gfyoung/elasticsearch,ricardocerq/elasticsearch,nknize/elasticsearch,zeroctu/elasticsearch,vietlq/elasticsearch,overcome/elasticsearch,JSCooke/elasticsearch,acchen97/elasticsearch,s1monw/elasticsearch,weipinghe/elasticsearch,sneivandt/elasticsearch,AshishThakur/elasticsearch,wittyameta/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,trangvh/elasticsearch,mcku/elasticsearch,sc0ttkclark/elasticsearch,djschny/elasticsearch,Kakakakakku/elasticsearch,luiseduardohdbackup/elasticsearch,vroyer/elasticassandra,elasticdog/elasticsearch,franklanganke/elasticsearch,Shepard1212/elasticsearch,ZTE-PaaS/elasticsearch,LeoYao/elasticsearch,pranavraman/elasticsearch,strapdata/elassandra,Microsoft/elasticsearch,ThalaivaStars/OrgRepo1,skearns64/elasticsearch,salyh/elasticsearch,chrismwendt/elasticsearch,sauravmondallive/elasticsearch,humandb/elasticsearch,thecocce/elasticsearch,adrianbk/elasticsearch,pritishppai/elasticsearch,jpountz/elasticsearch,sscarduzio/elasticsearch,LeoYao/elasticsearch,likaiwalkman/elasticsearch,Brijeshrpatel9/elasticsearch,mrorii/elasticsearch,nazarewk/elasticsearch,hanswang/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,boliza/elasticsearch,hirdesh2008/elasticsearch,jango2015/elasticsearch,kubum/elasticsearch,Liziyao/elasticsearch,TonyChai24/ESSource,caengcjd/elasticsearch,umeshdangat/elasticsearch,vietlq/elasticsearch,MetSystem/elasticsearch,markllama/elasticsearch,LeoYao/elasticsearch,liweinan0423/elasticsearch,TonyChai24/ESSource,pritishppai/elasticsearch,jimhooker2002/elasticsearch,nezirus/elasticsearch,dataduke/elasticsearch,njlawton/elasticsearch,kkirsche/elasticsearch,MjAbuz/elasticsearch,KimTaehee/elasticsearch,zkidkid/elasticsearch,masterweb121/elasticsearch,infusionsoft/elasticsearch,heng4fun/elasticsearch,yanjunh/elasticsearch,sauravmondallive/elasticsearch,dylan8902/elasticsearch,a2lin/elasticsearch,uboness/elasticsearch,ckclark/elasticsearch,i-am-Nathan/elasticsearch,lchennup/elasticsearch,skearns64/elasticsearch,mapr/elasticsearch,LeoYao/elasticsearch,nknize/elasticsearch,likaiwalkman/elasticsearch,markllama/elasticsearch,wittyameta/elasticsearch,andrestc/elasticsearch,EasonYi/elasticsearch,koxa29/elasticsearch,ivansun1010/elasticsearch,xpandan/elasticsearch,jaynblue/elasticsearch,sdauletau/elasticsearch,Shekharrajak/elasticsearch,wenpos/elasticsearch,SergVro/elasticsearch,girirajsharma/elasticsearch,Shekharrajak/elasticsearch,mkis-/elasticsearch,rlugojr/elasticsearch,mjason3/elasticsearch,loconsolutions/elasticsearch,artnowo/elasticsearch,himanshuag/elasticsearch,andrestc/elasticsearch,MisterAndersen/elasticsearch,jsgao0/elasticsearch,marcuswr/elasticsearch-dateline,franklanganke/elasticsearch,fooljohnny/elasticsearch,ckclark/elasticsearch,golubev/elasticsearch,njlawton/elasticsearch,MichaelLiZhou/elasticsearch,andrestc/elasticsearch,vvcephei/elasticsearch,lmtwga/elasticsearch,szroland/elasticsearch,elasticdog/elasticsearch,awislowski/elasticsearch,glefloch/elasticsearch,nazarewk/elasticsearch,beiske/elasticsearch,wenpos/elasticsearch
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.test.hamcrest; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Query; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.ActionRequestBuilder; import org.elasticsearch.action.ShardOperationFailedException; import org.elasticsearch.action.count.CountResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.ShardSearchFailure; import org.elasticsearch.action.support.broadcast.BroadcastOperationResponse; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.suggest.Suggest; import org.hamcrest.Matcher; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.fail; /** * */ public class ElasticsearchAssertions { /* * assertions */ public static void assertHitCount(SearchResponse searchResponse, long expectedHitCount) { if (searchResponse.getHits().totalHits() != expectedHitCount) { String msg = "Hit count is " + searchResponse.getHits().totalHits() + " but " + expectedHitCount + " was expected. " + searchResponse.getFailedShards() + " shard failures:"; for (ShardSearchFailure failure : searchResponse.getShardFailures()) { msg += "\n " + failure.toString(); } fail(msg); } } public static void assertSearchHits(SearchResponse searchResponse, String... ids) { assertThat("Expected different hit count", searchResponse.getHits().hits().length, equalTo(ids.length)); Set<String> idsSet = new HashSet<String>(Arrays.asList(ids)); for (SearchHit hit : searchResponse.getHits()) { assertThat("Expected id: " + hit.getId() + " in the result but wasn't", idsSet.remove(hit.getId()), equalTo(true)); } assertThat("Expected ids: " + Arrays.toString(idsSet.toArray(new String[0])) + " in the result - result size differs", idsSet.size(), equalTo(0)); } public static void assertHitCount(CountResponse countResponse, long expectedHitCount) { if (countResponse.getCount() != expectedHitCount) { String msg = "Count is " + countResponse.getCount() + " but " + expectedHitCount + " was expected. " + countResponse.getFailedShards() + " shard failures:"; for (ShardOperationFailedException failure : countResponse.getShardFailures()) { msg += "\n " + failure.toString(); } fail(msg); } } public static void assertFirstHit(SearchResponse searchResponse, Matcher<SearchHit> matcher) { assertSearchHit(searchResponse, 1, matcher); } public static void assertSecondHit(SearchResponse searchResponse, Matcher<SearchHit> matcher) { assertSearchHit(searchResponse, 2, matcher); } public static void assertThirdHit(SearchResponse searchResponse, Matcher<SearchHit> matcher) { assertSearchHit(searchResponse, 3, matcher); } public static void assertSearchHit(SearchResponse searchResponse, int number, Matcher<SearchHit> matcher) { assert number > 0; assertThat("SearchHit number must be greater than 0", number, greaterThan(0)); assertThat(searchResponse.getHits().totalHits(), greaterThanOrEqualTo((long) number)); assertSearchHit(searchResponse.getHits().getAt(number - 1), matcher); } public static void assertNoFailures(SearchResponse searchResponse) { assertThat("Unexpectd ShardFailures: " + Arrays.toString(searchResponse.getShardFailures()), searchResponse.getShardFailures().length, equalTo(0)); } public static void assertNoFailures(BroadcastOperationResponse response) { assertThat("Unexpectd ShardFailures: " + Arrays.toString(response.getShardFailures()), response.getFailedShards(), equalTo(0)); } public static void assertSearchHit(SearchHit searchHit, Matcher<SearchHit> matcher) { assertThat(searchHit, matcher); } public static void assertHighlight(SearchResponse resp, int hit, String field, int fragment, Matcher<String> matcher) { assertNoFailures(resp); assertThat("not enough hits", resp.getHits().hits().length, greaterThan(hit)); assertThat(resp.getHits().hits()[hit].getHighlightFields().get(field), notNullValue()); assertThat(resp.getHits().hits()[hit].getHighlightFields().get(field).fragments().length, greaterThan(fragment)); assertThat(resp.getHits().hits()[hit].highlightFields().get(field).fragments()[fragment].string(), matcher); } public static void assertSuggestionSize(Suggest searchSuggest, int entry, int size, String key) { assertThat(searchSuggest, notNullValue()); assertThat(searchSuggest.size(), greaterThanOrEqualTo(1)); assertThat(searchSuggest.getSuggestion(key).getName(), equalTo(key)); assertThat(searchSuggest.getSuggestion(key).getEntries().size(), greaterThanOrEqualTo(entry)); assertThat(searchSuggest.getSuggestion(key).getEntries().get(entry).getOptions().size(), equalTo(size)); } public static void assertSuggestion(Suggest searchSuggest, int entry, int ord, String key, String text) { assertThat(searchSuggest, notNullValue()); assertThat(searchSuggest.size(), greaterThanOrEqualTo(1)); assertThat(searchSuggest.getSuggestion(key).getName(), equalTo(key)); assertThat(searchSuggest.getSuggestion(key).getEntries().size(), greaterThanOrEqualTo(entry)); assertThat(searchSuggest.getSuggestion(key).getEntries().get(entry).getOptions().size(), greaterThan(ord)); assertThat(searchSuggest.getSuggestion(key).getEntries().get(entry).getOptions().get(ord).getText().string(), equalTo(text)); } /* * matchers */ public static Matcher<SearchHit> hasId(final String id) { return new ElasticsearchMatchers.SearchHitHasIdMatcher(id); } public static Matcher<SearchHit> hasType(final String type) { return new ElasticsearchMatchers.SearchHitHasTypeMatcher(type); } public static Matcher<SearchHit> hasIndex(final String index) { return new ElasticsearchMatchers.SearchHitHasIndexMatcher(index); } public static <T extends Query> T assertBooleanSubQuery(Query query, Class<T> subqueryType, int i) { assertThat(query, instanceOf(BooleanQuery.class)); BooleanQuery q = (BooleanQuery) query; assertThat(q.getClauses().length, greaterThan(i)); assertThat(q.getClauses()[i].getQuery(), instanceOf(subqueryType)); return (T) q.getClauses()[i].getQuery(); } public static <E extends Throwable> void assertThrows(ActionRequestBuilder<?, ?, ?> builder, Class<E> exceptionClass) { assertThrows(builder.execute(), exceptionClass); } public static <E extends Throwable> void assertThrows(ActionFuture future, Class<E> exceptionClass) { boolean fail = false; try { future.actionGet(); fail = true; } catch (ElasticSearchException esException) { assertThat(esException.unwrapCause(), instanceOf(exceptionClass)); } catch (Throwable e) { assertThat(e, instanceOf(exceptionClass)); } // has to be outside catch clause to get a proper message if (fail) { throw new AssertionError("Expected a " + exceptionClass + " exception to be thrown"); } } }
src/test/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.test.hamcrest; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Query; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.ActionRequestBuilder; import org.elasticsearch.action.ShardOperationFailedException; import org.elasticsearch.action.count.CountResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.ShardSearchFailure; import org.elasticsearch.action.support.broadcast.BroadcastOperationResponse; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.suggest.Suggest; import org.hamcrest.Matcher; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.fail; /** * */ public class ElasticsearchAssertions { /* * assertions */ public static void assertHitCount(SearchResponse searchResponse, long expectedHitCount) { if (searchResponse.getHits().totalHits() != expectedHitCount) { String msg = "Hit count is " + searchResponse.getHits().totalHits() + " but " + expectedHitCount + " was expected. " + searchResponse.getFailedShards() + " shard failures:"; for (ShardSearchFailure failure : searchResponse.getShardFailures()) { msg += "\n " + failure.toString(); } fail(msg); } } public static void assertSearchHits(SearchResponse searchResponse, String... ids) { assertThat("Expected different hit count", searchResponse.getHits().hits().length, equalTo(ids.length)); Set<String> idsSet = new HashSet<String>(Arrays.asList(ids)); for (SearchHit hit : searchResponse.getHits()) { assertThat("Expected id: " + hit.getId() + " in the result but wasn't", idsSet.remove(hit.getId()), equalTo(true)); } assertThat("Expected ids: " + Arrays.toString(idsSet.toArray(new String[0])) + " in the result - result size differs", idsSet.size(), equalTo(0)); } public static void assertHitCount(CountResponse countResponse, long expectedHitCount) { assertThat(countResponse.getCount(), is(expectedHitCount)); if (countResponse.getCount() != expectedHitCount) { String msg = "Count is " + countResponse.getCount() + " but " + expectedHitCount + " was expected. " + countResponse.getFailedShards() + " shard failures:"; for (ShardOperationFailedException failure : countResponse.getShardFailures()) { msg += "\n " + failure.toString(); } fail(msg); } } public static void assertFirstHit(SearchResponse searchResponse, Matcher<SearchHit> matcher) { assertSearchHit(searchResponse, 1, matcher); } public static void assertSecondHit(SearchResponse searchResponse, Matcher<SearchHit> matcher) { assertSearchHit(searchResponse, 2, matcher); } public static void assertThirdHit(SearchResponse searchResponse, Matcher<SearchHit> matcher) { assertSearchHit(searchResponse, 3, matcher); } public static void assertSearchHit(SearchResponse searchResponse, int number, Matcher<SearchHit> matcher) { assert number > 0; assertThat("SearchHit number must be greater than 0", number, greaterThan(0)); assertThat(searchResponse.getHits().totalHits(), greaterThanOrEqualTo((long) number)); assertSearchHit(searchResponse.getHits().getAt(number - 1), matcher); } public static void assertNoFailures(SearchResponse searchResponse) { assertThat("Unexpectd ShardFailures: " + Arrays.toString(searchResponse.getShardFailures()), searchResponse.getShardFailures().length, equalTo(0)); } public static void assertNoFailures(BroadcastOperationResponse response) { assertThat("Unexpectd ShardFailures: " + Arrays.toString(response.getShardFailures()), response.getFailedShards(), equalTo(0)); } public static void assertSearchHit(SearchHit searchHit, Matcher<SearchHit> matcher) { assertThat(searchHit, matcher); } public static void assertHighlight(SearchResponse resp, int hit, String field, int fragment, Matcher<String> matcher) { assertNoFailures(resp); assertThat("not enough hits", resp.getHits().hits().length, greaterThan(hit)); assertThat(resp.getHits().hits()[hit].getHighlightFields().get(field), notNullValue()); assertThat(resp.getHits().hits()[hit].getHighlightFields().get(field).fragments().length, greaterThan(fragment)); assertThat(resp.getHits().hits()[hit].highlightFields().get(field).fragments()[fragment].string(), matcher); } public static void assertSuggestionSize(Suggest searchSuggest, int entry, int size, String key) { assertThat(searchSuggest, notNullValue()); assertThat(searchSuggest.size(), greaterThanOrEqualTo(1)); assertThat(searchSuggest.getSuggestion(key).getName(), equalTo(key)); assertThat(searchSuggest.getSuggestion(key).getEntries().size(), greaterThanOrEqualTo(entry)); assertThat(searchSuggest.getSuggestion(key).getEntries().get(entry).getOptions().size(), equalTo(size)); } public static void assertSuggestion(Suggest searchSuggest, int entry, int ord, String key, String text) { assertThat(searchSuggest, notNullValue()); assertThat(searchSuggest.size(), greaterThanOrEqualTo(1)); assertThat(searchSuggest.getSuggestion(key).getName(), equalTo(key)); assertThat(searchSuggest.getSuggestion(key).getEntries().size(), greaterThanOrEqualTo(entry)); assertThat(searchSuggest.getSuggestion(key).getEntries().get(entry).getOptions().size(), greaterThan(ord)); assertThat(searchSuggest.getSuggestion(key).getEntries().get(entry).getOptions().get(ord).getText().string(), equalTo(text)); } /* * matchers */ public static Matcher<SearchHit> hasId(final String id) { return new ElasticsearchMatchers.SearchHitHasIdMatcher(id); } public static Matcher<SearchHit> hasType(final String type) { return new ElasticsearchMatchers.SearchHitHasTypeMatcher(type); } public static Matcher<SearchHit> hasIndex(final String index) { return new ElasticsearchMatchers.SearchHitHasIndexMatcher(index); } public static <T extends Query> T assertBooleanSubQuery(Query query, Class<T> subqueryType, int i) { assertThat(query, instanceOf(BooleanQuery.class)); BooleanQuery q = (BooleanQuery) query; assertThat(q.getClauses().length, greaterThan(i)); assertThat(q.getClauses()[i].getQuery(), instanceOf(subqueryType)); return (T) q.getClauses()[i].getQuery(); } public static <E extends Throwable> void assertThrows(ActionRequestBuilder<?, ?, ?> builder, Class<E> exceptionClass) { assertThrows(builder.execute(), exceptionClass); } public static <E extends Throwable> void assertThrows(ActionFuture future, Class<E> exceptionClass) { boolean fail = false; try { future.actionGet(); fail = true; } catch (ElasticSearchException esException) { assertThat(esException.unwrapCause(), instanceOf(exceptionClass)); } catch (Throwable e) { assertThat(e, instanceOf(exceptionClass)); } // has to be outside catch clause to get a proper message if (fail) { throw new AssertionError("Expected a " + exceptionClass + " exception to be thrown"); } } }
removed a left over assert made redundant by last commit
src/test/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java
removed a left over assert made redundant by last commit
<ide><path>rc/test/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java <ide> } <ide> <ide> public static void assertHitCount(CountResponse countResponse, long expectedHitCount) { <del> assertThat(countResponse.getCount(), is(expectedHitCount)); <ide> if (countResponse.getCount() != expectedHitCount) { <ide> String msg = "Count is " + countResponse.getCount() + " but " + expectedHitCount + " was expected. " + <ide> countResponse.getFailedShards() + " shard failures:";
Java
apache-2.0
66ddaee764022e16b5576534df525cba02bc9669
0
cmballard07/wordcram,tectronics/wordcram,naren01/wordcram,cmballard07/wordcram,cmballard07/wordcram,naren01/wordcram,tectronics/wordcram,naren01/wordcram,allendaicool/wordcram,allendaicool/wordcram,allendaicool/wordcram,cmballard07/wordcram,naren01/wordcram,tectronics/wordcram
package wordcram; /* Copyright 2010 Daniel Bernier Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import processing.core.PApplet; import processing.core.PVector; public class SpiralWordNudger implements WordNudger { // Who knows? this seems to be good, but it seems to depend on the font -- // bigger fonts need a bigger thetaIncrement. private float thetaIncrement = (float) (Math.PI * 0.03); @Override public PVector nudgeFor(Word w, int attempt) { float rad = powerMap(0.6f, attempt, 0, 600, 1, 100); thetaIncrement = powerMap(1, attempt, 0, 600, 0.5f, 0.3f); float theta = thetaIncrement * attempt; float x = PApplet.cos(theta) * rad; float y = PApplet.sin(theta) * rad; return new PVector(x, y); } private float powerMap(float power, float v, float min1, float max1, float min2, float max2) { float val = PApplet.norm(v, min1, max1); val = PApplet.pow(val, power); return PApplet.lerp(min2, max2, val); } }
src/wordcram/SpiralWordNudger.java
package wordcram; /* Copyright 2010 Daniel Bernier Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import processing.core.PApplet; import processing.core.PVector; public class SpiralWordNudger implements WordNudger { // Who knows? this seems to be good, but it seems to depend on the font -- // bigger fonts need a bigger thetaIncrement. private float thetaIncrement = (float) (Math.PI * 0.03); @Override public PVector nudgeFor(Word w, int attempt) { float rad = powerMap(2, attempt, 0, 600, 1, 100); thetaIncrement = powerMap(1, attempt, 0, 600, 0.5f, 0.1f); float theta = thetaIncrement * attempt; float x = PApplet.cos(theta) * rad; float y = PApplet.sin(theta) * rad; return new PVector(x, y); } private float powerMap(float power, float v, float min1, float max1, float min2, float max2) { float val = PApplet.norm(v, min1, max1); val = PApplet.pow(val, power); return PApplet.lerp(min2, max2, val); } }
SpiralWordNudger, changed the numbers around so it's a better spiral
src/wordcram/SpiralWordNudger.java
SpiralWordNudger, changed the numbers around so it's a better spiral
<ide><path>rc/wordcram/SpiralWordNudger.java <ide> <ide> @Override <ide> public PVector nudgeFor(Word w, int attempt) { <del> float rad = powerMap(2, attempt, 0, 600, 1, 100); <add> float rad = powerMap(0.6f, attempt, 0, 600, 1, 100); <ide> <del> thetaIncrement = powerMap(1, attempt, 0, 600, 0.5f, 0.1f); <add> thetaIncrement = powerMap(1, attempt, 0, 600, 0.5f, 0.3f); <ide> float theta = thetaIncrement * attempt; <ide> float x = PApplet.cos(theta) * rad; <ide> float y = PApplet.sin(theta) * rad;
JavaScript
mit
0e36620f480123b0a1cb2e749fc2dce05ef19b3d
0
zubairq/gosharedata,zubairq/yazz,zubairq/yazz,zubairq/gosharedata
function(args) { /* is_app(true) component_type("VB") display_name("Data control") description("This will return the data control") base_component_id("database_control") load_once_from_file(true) visibility("PRIVATE") read_only(true) properties( [ { id: "text", name: "Text", type: "String" } , { id: "sourceControlName", name: "sourceControlName", type: "String" } , { id: "width", name: "Width", default: 150, type: "Number" } , { id: "limit", name: "Limit", type: "Number", default_expression: "(typeof $RETURNED_ROWS_LIMIT !== 'undefined')?eval('$RETURNED_ROWS_LIMIT'):100", } , { id: "height", name: "Height", default: 100, type: "Number" } , { id: "background_color", name: "Background color", type: "String" } , { id: "has_details_ui", name: "Has details UI?", type: "Boolean", default: true, hidden: true } , { id: "changed_event", name: "Changed event", type: "Event" } , { id: "is_container", name: "Is Container?", type: "Boolean", default: true, hidden: true } , { id: "hide_children", name: "Hide Children?", type: "Boolean", default: true, hidden: true } , { id: "design_mode_table", name: "Design Table", type: "String", default: "", hidden: true } , { id: "hide_children", name: "Hide Children?", type: "Boolean", default: false, hidden: true } , { id: "setData", snippet: `setData([{a: 1, b: "c"},{a: 2, b: "d"}])`, name: "setData", type: "Action" } , { id: "resetColumns", snippet: `resetColumns()`, name: "resetColumns", type: "Action" } , { id: "addColumn", name: "addColumn", type: "Action" } , { id: "source_type", name: "Data Source Type", type: "String", default: "postgres" } , { id: "sql", name: "SQL", type: "String", default: "SELECT * FROM pg_catalog.pg_tables;" } , { id: "user", name: "USER", type: "String", default_expression: "(typeof $POSTGRES_USER !== 'undefined')?eval('$POSTGRES_USER'):'postgres'" } , { id: "password", name: "Password", type: "String", password: true, default_expression: "(typeof $POSTGRES_PASSWORD !== 'undefined')?eval('$POSTGRES_PASSWORD'):'password'", } , { id: "database", name: "Database", type: "String", default_expression: "(typeof $POSTGRES_DATABASE !== 'undefined')?eval('$POSTGRES_DATABASE'):'postgres'", } , { id: "port", name: "Port", type: "Number", default_expression: "(typeof $POSTGRES_PORT !== 'undefined')?eval('$POSTGRES_PORT'):5432", } , { id: "host", name: "Host", type: "String", default_expression: "(typeof $POSTGRES_HOST !== 'undefined')?$POSTGRES_HOST:'localhost'", } , { id: "dataWindowColumns", name: "dataWindowColumns", type: "Array", hidden: true, default: [] } , { id: "data", name: "data", type: "Array", hidden: true, default: [], types: {table_data: true} } , { id: "dataWindowColumnsMax", name: "dataWindowColumnsMax", type: "Number", hidden: true, default: 0 } , { id: "selected_data_window_column_index", name: "selected_data_window_column_index", type: "Number", hidden: true, default: -1 } , { id: "selected_data_window_column", name: "selected_data_window_column", type: "String", hidden: true, default: "" } , { id: "layout", name: "Layout", type: "", hidden: false, type: "Select", default: "fitColumns", values: [ {display: "Fit Columns", value: "fitColumns"}, {display: "Fit Data", value: "fitData"}, {display: "Fit Data Fill", value: "fitDataFill"} ] } , { id: "allow_col_resize", name: "allow_col_resize", type: "Boolean", hidden: true, default: false } , { id: "allow_col_move", name: "allow_col_move", type: "Boolean", hidden: true, default: false } , { id: "allow_row_resize", name: "allow_row_resize", type: "Boolean", hidden: true, default: false } , { id: "columns", name: "columns", type: "Array", hidden: true, default: [] } , { id: "where_clause", name: "where_clause", type: "String", hidden: true, default: "" } , { id: "selected_column", name: "selected_column", type: "String", hidden: true, default: "" } , { id: "result", name: "result", type: "Array", default: [] } , { id: "executeSql", pre_snippet: `await `, snippet: `executeSql()`, name: "executeSql", type: "Action", help: `<div>Help text for <b>executeSql</b> function <div>The SQL is store in the "sql" property</div> </div>` } , { id: "is_container", name: "Is Container?", type: "Boolean", default: true, hidden: true } , { id: "test", pre_snippet: ` `, snippet: `test()`, name: "test", type: "Action" } ] )//properties logo_url("/driver_icons/data_control.png") */ Vue.component("database_control",{ props: ["meta","name","args","refresh","design_mode", "children"] , template: `<div v-bind:style='"width:100%;overflow-y:auto;height:100%;color:black;" v-bind:refresh='refresh'> <div v-bind:style='"height:100%;width:100%; border: 0px;color:black;padding: 10px;"' v-if='design_mode == "detail_editor"'> <div v-bind:style='"height:100%;width:100%; overflow: none;"'> <ul class="nav nav-pills" v-bind:style='"height:20%;width:100%; overflow: none;"'> <li class="nav-item" style="width:20%;"> <a v-bind:class='"nav-link " + ((designDetailTab == "connection")?"active":"")' v-on:click="designDetailTab = 'connection';" href="#"> Data source connection </a> </li> <li class="nav-item" style="width:20%;"> <a v-bind:class='"nav-link " + ((designDetailTab == "schema")?"active":"")' v-on:click="designDetailTab = 'schema';" href="#">Schema and tables</a> </li> <li class="nav-item" style="width:20%;"> <a v-bind:class='"nav-link " + ((designDetailTab == "columns")?"active":"")' v-on:click="designDetailTab = 'columns';" href="#">Columns</a> </li> <li class="nav-item" style="width:20%;"> <a v-bind:class='"nav-link " + ((designDetailTab == "where")?"active":"")' v-on:click="designDetailTab = 'where';" href="#">Where</a> </li> <li class="nav-item" style="width:20%;"> <a v-bind:class='"nav-link " + ((designDetailTab == "options")?"active":"")' v-on:click="designDetailTab = 'options';" href="#">Options</a> </li> </ul> <div v-if='designDetailTab == "connection"' > Connection :: {{dynamic}} :: <select @change='chooseSource($event)'> <option value="" selected='true'> </option> <option v-for='propVal in data_sources' v-bind:value="propVal.base_component_id" v-bind:selected2='(propVal.base_component_id == "postgres")'> {{propVal.display_name}} </option> </select> <div v-if='children && children[0]'> <slot v-bind:refresh='refresh'> </slot> <button class="btn btn-primary" v-on:click="connect"> Connect </button> </div> </div> <div v-if='designDetailTab == "schema"' > Database tables for schema &#34;{{args.database}}&#34; <div style="height:70%;width:100%; overflow-y: scroll;border: 1px solid lightgray;"> <div v-for='table in tables' v-on:click="args.sql = 'select * from ' + table; args.design_mode_table = table;getColumns();args.dataWindowColumns=[];" v-bind:style='"padding: 5px; " + ((args.design_mode_table == table)?"background-color:gray;color:white;":"background-color:white;color:gray;") '> {{table}} </div> </div> </div> <div v-if='designDetailTab == "columns"' > Columns for table &#34;{{args.design_mode_table}}&#34; <div> <div style="height:70%;width:30%; overflow-y: scroll;display:inline-block;vertical-align:top; border: 2px solid gray;"> <div v-for='column in args.columns' v-on:click="args.selected_column = column;" v-bind:style='"padding: 5px; " + ((args.selected_column == column)?"background-color:gray;color:white;":"background-color:white;color:gray;") '> {{column}} </div> </div> <div style="height:70%;width:15%; overflow-y: none;display:inline-block;vertical-align:top;"> <button class="btn btn-primary" :disabled="(args.selected_column && args.selected_column.length > 0)?false:true" v-on:click="var newId = args.dataWindowColumnsMax++;args.dataWindowColumns.push({id: newId, value: args.selected_column, name: args.selected_column});setSql();args.selected_data_window_column_index = newId;args.selected_data_window_column = args.dataWindowColumns[args.dataWindowColumns.length - 1];"> Add >> </button> <button class="btn btn-primary" style="margin-top:20px;" :disabled="(args.selected_data_window_column_index > -1)?false:true" v-on:click="args.dataWindowColumns.splice(args.selected_data_window_column_index,1);setSql(); args.selected_data_window_column_index = -1;args.selected_data_window_column='';"> << Remove </button> </div> <div style="height:30%;width:30%; overflow-y: none;display:inline-block;vertical-align:top; margin-left: 20px; border: 2px solid gray;"> <div style="height:100%;width:100%; overflow-y: scroll;vertical-align:top;"> <div v-for='(dwcolumn,index) in args.dataWindowColumns' v-on:click="args.selected_data_window_column = dwcolumn;args.selected_data_window_column_index = index;" v-bind:style='"padding: 5px; " + ((args.selected_data_window_column.id == dwcolumn.id)?"background-color:gray;color:white;":"background-color:white;color:gray;") '> {{dwcolumn.value}} </div> </div> <div class="btn-group"> <button class="btn btn-primary" :disabled="(args.selected_data_window_column_index > 0)?false:true" style="margin-top:20px; margin-left: 0px;" v-on:click="array_move(args.dataWindowColumns,args.selected_data_window_column_index,args.selected_data_window_column_index-1);args.selected_data_window_column_index --;"> Move Up </button> <button class="btn btn-primary" :disabled="((args.selected_data_window_column_index > -1) && (args.selected_data_window_column_index < (args.dataWindowColumns.length - 1)))?false:true" style="margin-top:20px; margin-left: 20px;" v-on:click="array_move(args.dataWindowColumns,args.selected_data_window_column_index,args.selected_data_window_column_index + 1);args.selected_data_window_column_index ++;"> Move Down </button> </div> <div style=" border: 1px solid lightgray;height:90%;width:100%; display:inline-block;margin-top:20px;overflow-y:scroll;"> <div v-if="args.selected_data_window_column" style="height:100%;width:100%; overflow-y: none; padding: 10px;"> <div class="form-group"> <label for="col_input_name">Title</label> <input type=text class="form-control" style="margin-bottom: 30px;" id=col_input_name name="col_input_name" required v-bind:value='args.selected_data_window_column.name' v-on:change="var qwe = document.getElementById('col_input_name').value;args.dataWindowColumns[args.selected_data_window_column_index].name=qwe;args.selected_data_window_column.name = qwe;" > </input> <label for="col_input_value">DB Col ID</label> <input type=text class="form-control" id=col_input_value style="margin-bottom: 30px;" name="col_input_value" required v-bind:value='args.selected_data_window_column.value' v-on:change="var qwe = document.getElementById('col_input_value').value;args.dataWindowColumns[args.selected_data_window_column_index].value=qwe;args.selected_data_window_column.value = qwe;" > </input> <div class="valid-feedback">Valid.</div> <div class="invalid-feedback">Please fill out this field.</div> <label for="col_input_width">Col Width px</label> <input type=text style="margin-bottom: 30px;" class="form-control" id=col_input_width name="col_input_width" v-bind:value='args.selected_data_window_column.width?args.selected_data_window_column.width:""' v-on:change="var qwe = document.getElementById('col_input_width').value;args.selected_data_window_column.width = qwe;args.dataWindowColumns[args.selected_data_window_column_index].width=qwe;" > </input> </div> </div> <div v-if="!args.selected_data_window_column" style="height:100%;width:100%; overflow-y: none;margin-top:0px;border: 1px solid lightgray;"> </div> </div> </div> </div> </div> <div v-if='designDetailTab == "where"' > <label for="col_input_width">Where Clause</label> <input type=text style="margin-bottom: 30px;" class="form-control" id=where_clause name="where_clause" v-bind:value='(args.where_clause && (args.where_clause.length > 0))?args.where_clause:""' v-on:change="args.where_clause = document.getElementById('where_clause').value;setSql()" > </input> </div> <div v-if='designDetailTab == "options"' > Options tab <form> <div class="form-group"> <div class="form-check"> <input type="checkbox" class="form-check-input" id="allow_col_resize" :checked='args.allow_col_resize' v-model='args.allow_col_resize'> <label class="form-check-label" for="allow_col_resize">Allow col resize</label> </div> <div class="form-check"> <input type="checkbox" class="form-check-input" id="allow_col_move" :checked='args.allow_col_move' v-model='args.allow_col_move'> <label class="form-check-label" for="allow_col_move">Allow col move</label> </div> <div class="form-check"> <input type="checkbox" class="form-check-input" id="allow_row_resize" :checked='args.allow_row_resize' v-model='args.allow_row_resize'> <label class="form-check-label" for="allow_row_resize">Allow row resize</label> </div> </form> </div> </div> </div> <div v-else> <div v-bind:style='"height:100%;width:100%; border: 0px;" + "background-color: "+ args["background_color"] + ";"' v-if='design_mode == false'> </div> <div v-bind:style='"height:100%;width:100%; border: 0px;" + "background-color:white;color:black;"' v-else> <b>SQL:</b> {{args.sql}} </div> </div> </div>` , data: function() { return { selected_index: null , columnDefinitions: [ ] , tables: [ ] , data_sources: [] , designDetailTab: "connection" , dynamic: "No dynamic" } } , watch: { // This would be called anytime the value of the input changes refresh: function(newValue, oldValue) { //console.log("refresh: " + this.args.text) if (isValidObject(this.args)) { this.getTables() //alert(JSON.stringify(this.tables,null,2)) } } } , mounted: async function() { registerComponent(this) let listLL = await findComponentsImplementing(["getSchema"]) //aaa //alert(JSON.stringify(listLL,null,2)) this.data_sources = listLL.values if (isValidObject(this.args)) { } if (this.design_mode == "never") { this.table = new Tabulator(this.$refs.exampletable, { width: this.args.width , height: this.args.height , tables: [] , data: this.args.data , layout: "fitColumns" , responsiveLayout: "hide" , tooltips: true , addRowPos: "top" , history: true , pagination: "local" , paginationSize: 7 , movableColumns: true , resizableColumns: this.args.allow_col_resize , resizableRows: this.args.allow_row_resize , movableColumns: this.args.allow_col_move , layout: this.args.layout , tableNames: [] , initialSort: [ ] , columns: this.columnDefinitions }); } if (this.design_mode) { await this.getTables() } if (!this.design_mode) { var results = await this.executeSql() //alert(JSON.stringify(results,null,2)) //await this.setData(results) } } , methods: { chooseSource: async function(event) { //debugger let mm = this let typeName = event.target.value await loadV2([typeName]) mm.args.sourceControlName = typeName + "_" + this.meta.getEditor().getNextComponentid() await this.meta.getEditor().addControl( { "leftX": 10, "topY": 10, "name": mm.args.sourceControlName, "base_component_id": typeName, parent_base_component_id: mm.args.base_component_id, parent_name: mm.args.name } ) debugger //await mm.meta.getEditor().updateComponentMethods() let newcontrol = mm.meta.lookupComponent(mm.args.sourceControlName) let retttq = newcontrol.getDynamic() mm.dynamic = retttq newcontrol.width = 300 newcontrol.height = 500 //let newcontrol = mm.meta.getEditor().form_runtime_info[mm.meta.getEditor().active_form].component_lookup_by_name["aaa"] //newcontrol.setText2("helo duck") //zzz } , test: function() { //debugger let mm = this //let newcontrol = mm.meta.getEditor().form_runtime_info[mm.meta.getEditor().active_form].component_lookup_by_name[newName] let newcontrol = mm.meta.getEditor().form_runtime_info[mm.meta.getEditor().active_form].component_lookup_by_name["aaa"] //mm.dynamic = newcontrol.getDynamic() newcontrol.setText2("helo duck") } , connect: async function() { //zzz //alert(1) debugger let mm = this let newcontrol = mm.meta.lookupComponent(mm.args.sourceControlName) let retttq = await newcontrol.executeSql() if (newcontrol.result && newcontrol.result.failed) { mm.dynamic = "Failed: " + JSON.stringify(newcontrol.result.failed.routine,null,2) } else { mm.dynamic = "Connected" } } , setSql: function() { var colSql = "*" if (this.args.dataWindowColumns.length > 0) { colSql = "" for (var coli=0; coli < this.args.dataWindowColumns.length; coli ++) { colSql += this.args.dataWindowColumns[coli].value if (coli< (this.args.dataWindowColumns.length - 1)) { colSql += "," } } } this.args.sql = "select " + colSql + " from " + this.args.design_mode_table if (this.args.where_clause && (this.args.where_clause.length > 0)) { this.args.sql += " where " + this.args.where_clause } } , changedFn: function() { if (isValidObject(this.args)) { } } , resetColumns: async function(data) { this.table.setColumns([]) } , addColumn: async function(colData) { this.table.addColumn(colData, true, "name"); } , runEventHandler: function() { this.$emit('send', { type: "subcomponent_event", control_name: this.args.name, sub_type: "changed", code: this.args.changed_event }) } , setData: async function(data) { this.args.data = data this.table.setData(data) var keysOfData = new Object() if ((this.columnDefinitions == null) || (this.columnDefinitions.length == 0)) { for (var rr = 0 ; rr < data.length; rr ++) { var dfg = Object.keys(data[rr]) for (var qq = 0 ; qq < dfg.length; qq ++) { keysOfData[dfg[qq]] = true } } } if (this.args.dataWindowColumns.length == 0) { var dfg2 = Object.keys(keysOfData) for (var qq2 = 0 ; qq2 < dfg2.length; qq2 ++) { this.addColumn({title:dfg2[qq2], field:dfg2[qq2]}) } } else { for (var coli = this.args.dataWindowColumns.length - 1; coli >= 0; coli --) { var colDefn = {title:this.args.dataWindowColumns[coli].name, field:this.args.dataWindowColumns[coli].value } if (this.args.dataWindowColumns[coli].width) { colDefn.width = parseInt(this.args.dataWindowColumns[coli].width) } this.addColumn(colDefn) } } } , array_move: function (arr, old_index, new_index) { if (new_index >= arr.length) { var k = new_index - arr.length + 1; while (k--) { arr.push(undefined); } } arr.splice(new_index, 0, arr.splice(old_index, 1)[0]); return arr; // for testing } , getTables: async function() { console.log("In getTables") if (this.design_mode) { var result = await callFunction( { driver_name: "postgres_server", method_name: "postgres_sql" } ,{ user: this.args.user, password: this.args.password, database: this.args.database, host: this.args.host, port: this.args.port, get_tables: true }) //alert("executeSql: " + JSON.stringify(result,null,2)) console.log(JSON.stringify(result,null,2)) if (result) { this.tables = [] //alert(JSON.stringify(result,null,2)) for (var i=0;i<result.length;i++) { this.tables.push(result[i].name) } } } } , getColumns: async function() { console.log("In getColumns") if (this.design_mode) { var result = await callFunction( { driver_name: "postgres_server", method_name: "postgres_sql" } ,{ user: this.args.user, password: this.args.password, database: this.args.database, host: this.args.host, port: this.args.port, get_columns: true, table: this.args.design_mode_table }) //alert("executeSql: " + JSON.stringify(result,null,2)) console.log(JSON.stringify(result,null,2)) if (result) { this.args.columns = [] //alert(JSON.stringify(result,null,2)) for (var i=0;i<result.length;i++) { this.args.columns.push(result[i].name) } } } } , executeSql: async function() { if (!this.design_mode) { var result = await callFunction( { driver_name: "postgres_server", method_name: "postgres_sql" } ,{ sql: this.args.sql, user: this.args.user, password: this.args.password, database: this.args.database, host: this.args.host, port: this.args.port, limit: this.args.limit }) //debugger //alert("executeSql: " + JSON.stringify(result,null,2)) console.log(JSON.stringify(result,null,2)) if (result) { this.args.result = result return result } } this.args.result = [] //this.changedFn() return {} } } }) }
public/visifile_drivers/controls/database.js
function(args) { /* is_app(true) component_type("VB") display_name("Data control") description("This will return the data control") base_component_id("database_control") load_once_from_file(true) visibility("PRIVATE") read_only(true) properties( [ { id: "text", name: "Text", type: "String" } , { id: "sourceControlName", name: "sourceControlName", type: "String" } , { id: "width", name: "Width", default: 150, type: "Number" } , { id: "limit", name: "Limit", type: "Number", default_expression: "(typeof $RETURNED_ROWS_LIMIT !== 'undefined')?eval('$RETURNED_ROWS_LIMIT'):100", } , { id: "height", name: "Height", default: 100, type: "Number" } , { id: "background_color", name: "Background color", type: "String" } , { id: "has_details_ui", name: "Has details UI?", type: "Boolean", default: true, hidden: true } , { id: "changed_event", name: "Changed event", type: "Event" } , { id: "is_container", name: "Is Container?", type: "Boolean", default: true, hidden: true } , { id: "hide_children", name: "Hide Children?", type: "Boolean", default: true, hidden: true } , { id: "design_mode_table", name: "Design Table", type: "String", default: "", hidden: true } , { id: "hide_children", name: "Hide Children?", type: "Boolean", default: false, hidden: true } , { id: "setData", snippet: `setData([{a: 1, b: "c"},{a: 2, b: "d"}])`, name: "setData", type: "Action" } , { id: "resetColumns", snippet: `resetColumns()`, name: "resetColumns", type: "Action" } , { id: "addColumn", name: "addColumn", type: "Action" } , { id: "source_type", name: "Data Source Type", type: "String", default: "postgres" } , { id: "sql", name: "SQL", type: "String", default: "SELECT * FROM pg_catalog.pg_tables;" } , { id: "user", name: "USER", type: "String", default_expression: "(typeof $POSTGRES_USER !== 'undefined')?eval('$POSTGRES_USER'):'postgres'" } , { id: "password", name: "Password", type: "String", password: true, default_expression: "(typeof $POSTGRES_PASSWORD !== 'undefined')?eval('$POSTGRES_PASSWORD'):'password'", } , { id: "database", name: "Database", type: "String", default_expression: "(typeof $POSTGRES_DATABASE !== 'undefined')?eval('$POSTGRES_DATABASE'):'postgres'", } , { id: "port", name: "Port", type: "Number", default_expression: "(typeof $POSTGRES_PORT !== 'undefined')?eval('$POSTGRES_PORT'):5432", } , { id: "host", name: "Host", type: "String", default_expression: "(typeof $POSTGRES_HOST !== 'undefined')?$POSTGRES_HOST:'localhost'", } , { id: "dataWindowColumns", name: "dataWindowColumns", type: "Array", hidden: true, default: [] } , { id: "data", name: "data", type: "Array", hidden: true, default: [], types: {table_data: true} } , { id: "dataWindowColumnsMax", name: "dataWindowColumnsMax", type: "Number", hidden: true, default: 0 } , { id: "selected_data_window_column_index", name: "selected_data_window_column_index", type: "Number", hidden: true, default: -1 } , { id: "selected_data_window_column", name: "selected_data_window_column", type: "String", hidden: true, default: "" } , { id: "layout", name: "Layout", type: "", hidden: false, type: "Select", default: "fitColumns", values: [ {display: "Fit Columns", value: "fitColumns"}, {display: "Fit Data", value: "fitData"}, {display: "Fit Data Fill", value: "fitDataFill"} ] } , { id: "allow_col_resize", name: "allow_col_resize", type: "Boolean", hidden: true, default: false } , { id: "allow_col_move", name: "allow_col_move", type: "Boolean", hidden: true, default: false } , { id: "allow_row_resize", name: "allow_row_resize", type: "Boolean", hidden: true, default: false } , { id: "columns", name: "columns", type: "Array", hidden: true, default: [] } , { id: "where_clause", name: "where_clause", type: "String", hidden: true, default: "" } , { id: "selected_column", name: "selected_column", type: "String", hidden: true, default: "" } , { id: "result", name: "result", type: "Array", default: [] } , { id: "executeSql", pre_snippet: `await `, snippet: `executeSql()`, name: "executeSql", type: "Action", help: `<div>Help text for <b>executeSql</b> function <div>The SQL is store in the "sql" property</div> </div>` } , { id: "is_container", name: "Is Container?", type: "Boolean", default: true, hidden: true } , { id: "test", pre_snippet: ` `, snippet: `test()`, name: "test", type: "Action" } ] )//properties logo_url("/driver_icons/data_control.png") */ Vue.component("database_control",{ props: ["meta","name","args","refresh","design_mode", "children"] , template: `<div v-bind:style='"width:100%;overflow-y:auto;height:100%;color:black;" v-bind:refresh='refresh'> <div v-bind:style='"height:100%;width:100%; border: 0px;color:black;padding: 10px;"' v-if='design_mode == "detail_editor"'> <div v-bind:style='"height:100%;width:100%; overflow: none;"'> <ul class="nav nav-pills" v-bind:style='"height:20%;width:100%; overflow: none;"'> <li class="nav-item" style="width:20%;"> <a v-bind:class='"nav-link " + ((designDetailTab == "connection")?"active":"")' v-on:click="designDetailTab = 'connection';" href="#"> Data source connection </a> </li> <li class="nav-item" style="width:20%;"> <a v-bind:class='"nav-link " + ((designDetailTab == "schema")?"active":"")' v-on:click="designDetailTab = 'schema';" href="#">Schema and tables</a> </li> <li class="nav-item" style="width:20%;"> <a v-bind:class='"nav-link " + ((designDetailTab == "columns")?"active":"")' v-on:click="designDetailTab = 'columns';" href="#">Columns</a> </li> <li class="nav-item" style="width:20%;"> <a v-bind:class='"nav-link " + ((designDetailTab == "where")?"active":"")' v-on:click="designDetailTab = 'where';" href="#">Where</a> </li> <li class="nav-item" style="width:20%;"> <a v-bind:class='"nav-link " + ((designDetailTab == "options")?"active":"")' v-on:click="designDetailTab = 'options';" href="#">Options</a> </li> </ul> <div v-if='designDetailTab == "connection"' > Connection :: {{dynamic}} :: <select @change='chooseSource($event)'> <option value="" selected='true'> </option> <option v-for='propVal in data_sources' v-bind:value="propVal.base_component_id" v-bind:selected2='(propVal.base_component_id == "postgres")'> {{propVal.display_name}} </option> </select> <div v-if='children && children[0]'> <slot v-bind:refresh='refresh'> </slot> <button class="btn btn-primary" v-on:click="connect"> Connect </button> </div> </div> <div v-if='designDetailTab == "schema"' > Database tables for schema &#34;{{args.database}}&#34; <div style="height:70%;width:100%; overflow-y: scroll;border: 1px solid lightgray;"> <div v-for='table in tables' v-on:click="args.sql = 'select * from ' + table; args.design_mode_table = table;getColumns();args.dataWindowColumns=[];" v-bind:style='"padding: 5px; " + ((args.design_mode_table == table)?"background-color:gray;color:white;":"background-color:white;color:gray;") '> {{table}} </div> </div> </div> <div v-if='designDetailTab == "columns"' > Columns for table &#34;{{args.design_mode_table}}&#34; <div> <div style="height:70%;width:30%; overflow-y: scroll;display:inline-block;vertical-align:top; border: 2px solid gray;"> <div v-for='column in args.columns' v-on:click="args.selected_column = column;" v-bind:style='"padding: 5px; " + ((args.selected_column == column)?"background-color:gray;color:white;":"background-color:white;color:gray;") '> {{column}} </div> </div> <div style="height:70%;width:15%; overflow-y: none;display:inline-block;vertical-align:top;"> <button class="btn btn-primary" :disabled="(args.selected_column && args.selected_column.length > 0)?false:true" v-on:click="var newId = args.dataWindowColumnsMax++;args.dataWindowColumns.push({id: newId, value: args.selected_column, name: args.selected_column});setSql();args.selected_data_window_column_index = newId;args.selected_data_window_column = args.dataWindowColumns[args.dataWindowColumns.length - 1];"> Add >> </button> <button class="btn btn-primary" style="margin-top:20px;" :disabled="(args.selected_data_window_column_index > -1)?false:true" v-on:click="args.dataWindowColumns.splice(args.selected_data_window_column_index,1);setSql(); args.selected_data_window_column_index = -1;args.selected_data_window_column='';"> << Remove </button> </div> <div style="height:30%;width:30%; overflow-y: none;display:inline-block;vertical-align:top; margin-left: 20px; border: 2px solid gray;"> <div style="height:100%;width:100%; overflow-y: scroll;vertical-align:top;"> <div v-for='(dwcolumn,index) in args.dataWindowColumns' v-on:click="args.selected_data_window_column = dwcolumn;args.selected_data_window_column_index = index;" v-bind:style='"padding: 5px; " + ((args.selected_data_window_column.id == dwcolumn.id)?"background-color:gray;color:white;":"background-color:white;color:gray;") '> {{dwcolumn.value}} </div> </div> <div class="btn-group"> <button class="btn btn-primary" :disabled="(args.selected_data_window_column_index > 0)?false:true" style="margin-top:20px; margin-left: 0px;" v-on:click="array_move(args.dataWindowColumns,args.selected_data_window_column_index,args.selected_data_window_column_index-1);args.selected_data_window_column_index --;"> Move Up </button> <button class="btn btn-primary" :disabled="((args.selected_data_window_column_index > -1) && (args.selected_data_window_column_index < (args.dataWindowColumns.length - 1)))?false:true" style="margin-top:20px; margin-left: 20px;" v-on:click="array_move(args.dataWindowColumns,args.selected_data_window_column_index,args.selected_data_window_column_index + 1);args.selected_data_window_column_index ++;"> Move Down </button> </div> <div style=" border: 1px solid lightgray;height:90%;width:100%; display:inline-block;margin-top:20px;overflow-y:scroll;"> <div v-if="args.selected_data_window_column" style="height:100%;width:100%; overflow-y: none; padding: 10px;"> <div class="form-group"> <label for="col_input_name">Title</label> <input type=text class="form-control" style="margin-bottom: 30px;" id=col_input_name name="col_input_name" required v-bind:value='args.selected_data_window_column.name' v-on:change="var qwe = document.getElementById('col_input_name').value;args.dataWindowColumns[args.selected_data_window_column_index].name=qwe;args.selected_data_window_column.name = qwe;" > </input> <label for="col_input_value">DB Col ID</label> <input type=text class="form-control" id=col_input_value style="margin-bottom: 30px;" name="col_input_value" required v-bind:value='args.selected_data_window_column.value' v-on:change="var qwe = document.getElementById('col_input_value').value;args.dataWindowColumns[args.selected_data_window_column_index].value=qwe;args.selected_data_window_column.value = qwe;" > </input> <div class="valid-feedback">Valid.</div> <div class="invalid-feedback">Please fill out this field.</div> <label for="col_input_width">Col Width px</label> <input type=text style="margin-bottom: 30px;" class="form-control" id=col_input_width name="col_input_width" v-bind:value='args.selected_data_window_column.width?args.selected_data_window_column.width:""' v-on:change="var qwe = document.getElementById('col_input_width').value;args.selected_data_window_column.width = qwe;args.dataWindowColumns[args.selected_data_window_column_index].width=qwe;" > </input> </div> </div> <div v-if="!args.selected_data_window_column" style="height:100%;width:100%; overflow-y: none;margin-top:0px;border: 1px solid lightgray;"> </div> </div> </div> </div> </div> <div v-if='designDetailTab == "where"' > <label for="col_input_width">Where Clause</label> <input type=text style="margin-bottom: 30px;" class="form-control" id=where_clause name="where_clause" v-bind:value='(args.where_clause && (args.where_clause.length > 0))?args.where_clause:""' v-on:change="args.where_clause = document.getElementById('where_clause').value;setSql()" > </input> </div> <div v-if='designDetailTab == "options"' > Options tab <form> <div class="form-group"> <div class="form-check"> <input type="checkbox" class="form-check-input" id="allow_col_resize" :checked='args.allow_col_resize' v-model='args.allow_col_resize'> <label class="form-check-label" for="allow_col_resize">Allow col resize</label> </div> <div class="form-check"> <input type="checkbox" class="form-check-input" id="allow_col_move" :checked='args.allow_col_move' v-model='args.allow_col_move'> <label class="form-check-label" for="allow_col_move">Allow col move</label> </div> <div class="form-check"> <input type="checkbox" class="form-check-input" id="allow_row_resize" :checked='args.allow_row_resize' v-model='args.allow_row_resize'> <label class="form-check-label" for="allow_row_resize">Allow row resize</label> </div> </form> </div> </div> </div> <div v-else> <div v-bind:style='"height:100%;width:100%; border: 0px;" + "background-color: "+ args["background_color"] + ";"' v-if='design_mode == false'> </div> <div v-bind:style='"height:100%;width:100%; border: 0px;" + "background-color:white;color:black;"' v-else> <b>SQL:</b> {{args.sql}} </div> </div> </div>` , data: function() { return { selected_index: null , columnDefinitions: [ ] , tables: [ ] , data_sources: [] , designDetailTab: "connection" , dynamic: "No dynamic" } } , watch: { // This would be called anytime the value of the input changes refresh: function(newValue, oldValue) { //console.log("refresh: " + this.args.text) if (isValidObject(this.args)) { this.getTables() //alert(JSON.stringify(this.tables,null,2)) } } } , mounted: async function() { registerComponent(this) let listLL = await findComponentsImplementing(["getSchema"]) //aaa //alert(JSON.stringify(listLL,null,2)) this.data_sources = listLL.values if (isValidObject(this.args)) { } if (this.design_mode == "never") { this.table = new Tabulator(this.$refs.exampletable, { width: this.args.width , height: this.args.height , tables: [] , data: this.args.data , layout: "fitColumns" , responsiveLayout: "hide" , tooltips: true , addRowPos: "top" , history: true , pagination: "local" , paginationSize: 7 , movableColumns: true , resizableColumns: this.args.allow_col_resize , resizableRows: this.args.allow_row_resize , movableColumns: this.args.allow_col_move , layout: this.args.layout , tableNames: [] , initialSort: [ ] , columns: this.columnDefinitions }); } if (this.design_mode) { await this.getTables() } if (!this.design_mode) { var results = await this.executeSql() //alert(JSON.stringify(results,null,2)) //await this.setData(results) } } , methods: { chooseSource: async function(event) { //debugger let mm = this let typeName = event.target.value await loadV2([typeName]) mm.args.sourceControlName = typeName + "_" + this.meta.getEditor().getNextComponentid() await this.meta.getEditor().addControl( { "leftX": 10, "topY": 10, "name": mm.args.sourceControlName, "base_component_id": typeName, parent_base_component_id: mm.args.base_component_id, parent_name: mm.args.name } ) debugger //await mm.meta.getEditor().updateComponentMethods() let newcontrol = mm.meta.lookupComponent(mm.args.sourceControlName) let retttq = newcontrol.getDynamic() mm.dynamic = retttq newcontrol.width = 300 newcontrol.height = 500 //let newcontrol = mm.meta.getEditor().form_runtime_info[mm.meta.getEditor().active_form].component_lookup_by_name["aaa"] //newcontrol.setText2("helo duck") //zzz } , test: function() { //debugger let mm = this //let newcontrol = mm.meta.getEditor().form_runtime_info[mm.meta.getEditor().active_form].component_lookup_by_name[newName] let newcontrol = mm.meta.getEditor().form_runtime_info[mm.meta.getEditor().active_form].component_lookup_by_name["aaa"] //mm.dynamic = newcontrol.getDynamic() newcontrol.setText2("helo duck") } , connect: async function() { //zzz //alert(1) debugger let mm = this let newcontrol = mm.meta.lookupComponent(mm.args.sourceControlName) let retttq = await newcontrol.executeSql() mm.dynamic = newcontrol.result } , setSql: function() { var colSql = "*" if (this.args.dataWindowColumns.length > 0) { colSql = "" for (var coli=0; coli < this.args.dataWindowColumns.length; coli ++) { colSql += this.args.dataWindowColumns[coli].value if (coli< (this.args.dataWindowColumns.length - 1)) { colSql += "," } } } this.args.sql = "select " + colSql + " from " + this.args.design_mode_table if (this.args.where_clause && (this.args.where_clause.length > 0)) { this.args.sql += " where " + this.args.where_clause } } , changedFn: function() { if (isValidObject(this.args)) { } } , resetColumns: async function(data) { this.table.setColumns([]) } , addColumn: async function(colData) { this.table.addColumn(colData, true, "name"); } , runEventHandler: function() { this.$emit('send', { type: "subcomponent_event", control_name: this.args.name, sub_type: "changed", code: this.args.changed_event }) } , setData: async function(data) { this.args.data = data this.table.setData(data) var keysOfData = new Object() if ((this.columnDefinitions == null) || (this.columnDefinitions.length == 0)) { for (var rr = 0 ; rr < data.length; rr ++) { var dfg = Object.keys(data[rr]) for (var qq = 0 ; qq < dfg.length; qq ++) { keysOfData[dfg[qq]] = true } } } if (this.args.dataWindowColumns.length == 0) { var dfg2 = Object.keys(keysOfData) for (var qq2 = 0 ; qq2 < dfg2.length; qq2 ++) { this.addColumn({title:dfg2[qq2], field:dfg2[qq2]}) } } else { for (var coli = this.args.dataWindowColumns.length - 1; coli >= 0; coli --) { var colDefn = {title:this.args.dataWindowColumns[coli].name, field:this.args.dataWindowColumns[coli].value } if (this.args.dataWindowColumns[coli].width) { colDefn.width = parseInt(this.args.dataWindowColumns[coli].width) } this.addColumn(colDefn) } } } , array_move: function (arr, old_index, new_index) { if (new_index >= arr.length) { var k = new_index - arr.length + 1; while (k--) { arr.push(undefined); } } arr.splice(new_index, 0, arr.splice(old_index, 1)[0]); return arr; // for testing } , getTables: async function() { console.log("In getTables") if (this.design_mode) { var result = await callFunction( { driver_name: "postgres_server", method_name: "postgres_sql" } ,{ user: this.args.user, password: this.args.password, database: this.args.database, host: this.args.host, port: this.args.port, get_tables: true }) //alert("executeSql: " + JSON.stringify(result,null,2)) console.log(JSON.stringify(result,null,2)) if (result) { this.tables = [] //alert(JSON.stringify(result,null,2)) for (var i=0;i<result.length;i++) { this.tables.push(result[i].name) } } } } , getColumns: async function() { console.log("In getColumns") if (this.design_mode) { var result = await callFunction( { driver_name: "postgres_server", method_name: "postgres_sql" } ,{ user: this.args.user, password: this.args.password, database: this.args.database, host: this.args.host, port: this.args.port, get_columns: true, table: this.args.design_mode_table }) //alert("executeSql: " + JSON.stringify(result,null,2)) console.log(JSON.stringify(result,null,2)) if (result) { this.args.columns = [] //alert(JSON.stringify(result,null,2)) for (var i=0;i<result.length;i++) { this.args.columns.push(result[i].name) } } } } , executeSql: async function() { if (!this.design_mode) { var result = await callFunction( { driver_name: "postgres_server", method_name: "postgres_sql" } ,{ sql: this.args.sql, user: this.args.user, password: this.args.password, database: this.args.database, host: this.args.host, port: this.args.port, limit: this.args.limit }) //debugger //alert("executeSql: " + JSON.stringify(result,null,2)) console.log(JSON.stringify(result,null,2)) if (result) { this.args.result = result return result } } this.args.result = [] //this.changedFn() return {} } } }) }
Made connection status clearer
public/visifile_drivers/controls/database.js
Made connection status clearer
<ide><path>ublic/visifile_drivers/controls/database.js <ide> let mm = this <ide> let newcontrol = mm.meta.lookupComponent(mm.args.sourceControlName) <ide> let retttq = await newcontrol.executeSql() <del> mm.dynamic = newcontrol.result <add> if (newcontrol.result && newcontrol.result.failed) { <add> mm.dynamic = "Failed: " + JSON.stringify(newcontrol.result.failed.routine,null,2) <add> } else { <add> mm.dynamic = "Connected" <add> } <add> <ide> <ide> } <ide> ,
Java
apache-2.0
3a60f6b817f70326012d662724594679f241a79f
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testFramework; import com.intellij.openapi.util.Pair; import com.intellij.util.ThrowableRunnable; import com.sun.management.OperatingSystemMXBean; import it.unimi.dsi.fastutil.longs.Long2LongMap; import it.unimi.dsi.fastutil.longs.Long2LongMaps; import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongMaps; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import one.util.streamex.StreamEx; import org.jetbrains.annotations.NotNull; import java.lang.management.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; public final class CpuUsageData { private static final ThreadMXBean ourThreadMXBean = ManagementFactory.getThreadMXBean(); private static final List<GarbageCollectorMXBean> ourGcBeans = ManagementFactory.getGarbageCollectorMXBeans(); private static final CompilationMXBean ourCompilationMXBean = ManagementFactory.getCompilationMXBean(); private static final OperatingSystemMXBean ourOSBean = (OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean(); public final long durationMs; private final FreeMemorySnapshot myMemStart; private final FreeMemorySnapshot myMemEnd; private final long myCompilationTime; private final long myProcessTime; private final List<Pair<Long, String>> myGcTimes = new ArrayList<>(); private final List<Pair<Long, String>> myThreadTimes = new ArrayList<>(); private CpuUsageData(long durationMs, Object2LongMap<GarbageCollectorMXBean> gcTimes, Long2LongMap threadTimes, long compilationTime, long processTime, FreeMemorySnapshot memStart, FreeMemorySnapshot memEnd) { this.durationMs = durationMs; myMemStart = memStart; myMemEnd = memEnd; myCompilationTime = compilationTime; myProcessTime = processTime; Object2LongMaps.fastForEach(gcTimes, entry -> myGcTimes.add(Pair.create(entry.getLongValue(), entry.getKey().getName()))); Long2LongMaps.fastForEach(threadTimes, entry -> { ThreadInfo info = ourThreadMXBean.getThreadInfo(entry.getLongKey()); myThreadTimes.add(Pair.create(toMillis(entry.getLongValue()), info == null ? "<unknown>" : info.getThreadName())); }); } public String getGcStats() { return printLongestNames(myGcTimes) + "; free " + myMemStart + " -> " + myMemEnd + " MB"; } String getProcessCpuStats() { long gcTotal = myGcTimes.stream().mapToLong(p -> p.first).sum(); return myCompilationTime + "ms (" +(myCompilationTime*100/(myProcessTime==0?1000000:myProcessTime))+"%) JITc"+ (gcTotal > 0 ? " and " + gcTotal + "ms ("+ (gcTotal*100/(myProcessTime==0?1000000:myProcessTime))+"%) GC": "") + " of " + myProcessTime + "ms total"; } public String getThreadStats() { return printLongestNames(myThreadTimes); } public long getMemDelta() { long usedBefore = myMemStart.total - myMemStart.free; long usedAfter = myMemEnd.total - myMemEnd.free; return usedAfter - usedBefore; } public String getSummary(String indent) { return indent + "GC: " + getGcStats() + "\n" + indent + "Threads: " + getThreadStats() + "\n" + indent + "Process: " + getProcessCpuStats(); } boolean hasAnyActivityBesides(Thread thread) { return myCompilationTime > 0 || myThreadTimes.stream().anyMatch(pair -> pair.first > 0 && !pair.second.equals(thread.getName())) || myGcTimes.stream().anyMatch(pair -> pair.first > 0); } @NotNull private static String printLongestNames(List<Pair<Long, String>> times) { String stats = StreamEx.of(times) .sortedBy(p -> -p.first) .filter(p -> p.first > 10).limit(10) .map(p -> "\"" + p.second + "\"" + " took " + p.first + "ms") .joining(", "); return stats.isEmpty() ? "insignificant" : stats; } private static long toMillis(long timeNs) { return timeNs / 1_000_000; } public static <E extends Throwable> CpuUsageData measureCpuUsage(ThrowableRunnable<E> runnable) throws E { FreeMemorySnapshot memStart = new FreeMemorySnapshot(); Object2LongMap<GarbageCollectorMXBean> gcTimes = new Object2LongOpenHashMap<>(); for (GarbageCollectorMXBean bean : ourGcBeans) { gcTimes.put(bean, bean.getCollectionTime()); } Long2LongMap threadTimes = new Long2LongOpenHashMap(); for (long id : ourThreadMXBean.getAllThreadIds()) { threadTimes.put(id, ourThreadMXBean.getThreadUserTime(id)); } long compStart = getTotalCompilationMillis(); long processStart = ourOSBean.getProcessCpuTime(); long start = System.nanoTime(); runnable.run(); long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); long processTime = TimeUnit.NANOSECONDS.toMillis(ourOSBean.getProcessCpuTime() - processStart); long compTime = getTotalCompilationMillis() - compStart; FreeMemorySnapshot memEnd = new FreeMemorySnapshot(); for (long id : ourThreadMXBean.getAllThreadIds()) { threadTimes.put(id, ourThreadMXBean.getThreadUserTime(id) - threadTimes.get(id)); } for (GarbageCollectorMXBean bean : ourGcBeans) { gcTimes.put(bean, bean.getCollectionTime() - gcTimes.getLong(bean)); } return new CpuUsageData(duration, gcTimes, threadTimes, compTime, processTime, memStart, memEnd); } static long getTotalCompilationMillis() { return ourCompilationMXBean.getTotalCompilationTime(); } private static class FreeMemorySnapshot { final long free = toMb(Runtime.getRuntime().freeMemory()); final long total = toMb(Runtime.getRuntime().totalMemory()); private static long toMb(long bytes) { return bytes / 1024 / 1024; } @Override public String toString() { return free + "/" + total; } } }
platform/testFramework/src/com/intellij/testFramework/CpuUsageData.java
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testFramework; import com.intellij.openapi.util.Pair; import com.intellij.util.ThrowableRunnable; import com.sun.management.OperatingSystemMXBean; import it.unimi.dsi.fastutil.longs.Long2LongMap; import it.unimi.dsi.fastutil.longs.Long2LongMaps; import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongMaps; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import one.util.streamex.StreamEx; import org.jetbrains.annotations.NotNull; import java.lang.management.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; public final class CpuUsageData { private static final ThreadMXBean ourThreadMXBean = ManagementFactory.getThreadMXBean(); private static final List<GarbageCollectorMXBean> ourGcBeans = ManagementFactory.getGarbageCollectorMXBeans(); private static final CompilationMXBean ourCompilationMXBean = ManagementFactory.getCompilationMXBean(); private static final OperatingSystemMXBean ourOSBean = (OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean(); public final long durationMs; private final FreeMemorySnapshot myMemStart; private final FreeMemorySnapshot myMemEnd; private final long myCompilationTime; private final long myProcessTime; private final List<Pair<Long, String>> myGcTimes = new ArrayList<>(); private final List<Pair<Long, String>> myThreadTimes = new ArrayList<>(); private CpuUsageData(long durationMs, Object2LongMap<GarbageCollectorMXBean> gcTimes, Long2LongMap threadTimes, long compilationTime, long processTime, FreeMemorySnapshot memStart, FreeMemorySnapshot memEnd) { this.durationMs = durationMs; myMemStart = memStart; myMemEnd = memEnd; myCompilationTime = compilationTime; myProcessTime = processTime; Object2LongMaps.fastForEach(gcTimes, entry -> { myGcTimes.add(Pair.create(entry.getLongValue(), entry.getKey().getName())); }); Long2LongMaps.fastForEach(threadTimes, entry -> { ThreadInfo info = ourThreadMXBean.getThreadInfo(entry.getLongKey()); myThreadTimes.add(Pair.create(toMillis(entry.getLongValue()), info == null ? "<unknown>" : info.getThreadName())); }); } public String getGcStats() { return printLongestNames(myGcTimes) + "; free " + myMemStart + " -> " + myMemEnd + " MB"; } String getProcessCpuStats() { long gcTotal = myGcTimes.stream().mapToLong(p -> p.first).sum(); return myCompilationTime + "ms JITc " + (gcTotal > 0 ? "and " + gcTotal + "ms GC " : "") + "of " + myProcessTime + "ms total"; } public String getThreadStats() { return printLongestNames(myThreadTimes); } public long getMemDelta() { long usedBefore = myMemStart.total - myMemStart.free; long usedAfter = myMemEnd.total - myMemEnd.free; return usedAfter - usedBefore; } public String getSummary(String indent) { return indent + "GC: " + getGcStats() + "\n" + indent + "Threads: " + getThreadStats() + "\n" + indent + "Process: " + getProcessCpuStats(); } boolean hasAnyActivityBesides(Thread thread) { return myCompilationTime > 0 || myThreadTimes.stream().anyMatch(pair -> pair.first > 0 && !pair.second.equals(thread.getName())) || myGcTimes.stream().anyMatch(pair -> pair.first > 0); } @NotNull private static String printLongestNames(List<Pair<Long, String>> times) { String stats = StreamEx.of(times) .sortedBy(p -> -p.first) .filter(p -> p.first > 10).limit(10) .map(p -> "\"" + p.second + "\"" + " took " + p.first + "ms") .joining(", "); return stats.isEmpty() ? "insignificant" : stats; } private static long toMillis(long timeNs) { return timeNs / 1_000_000; } public static <E extends Throwable> CpuUsageData measureCpuUsage(ThrowableRunnable<E> runnable) throws E { FreeMemorySnapshot memStart = new FreeMemorySnapshot(); Object2LongMap<GarbageCollectorMXBean> gcTimes = new Object2LongOpenHashMap<>(); for (GarbageCollectorMXBean bean : ourGcBeans) { gcTimes.put(bean, bean.getCollectionTime()); } Long2LongMap threadTimes = new Long2LongOpenHashMap(); for (long id : ourThreadMXBean.getAllThreadIds()) { threadTimes.put(id, ourThreadMXBean.getThreadUserTime(id)); } long compStart = getTotalCompilationMillis(); long processStart = ourOSBean.getProcessCpuTime(); long start = System.nanoTime(); runnable.run(); long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); long processTime = TimeUnit.NANOSECONDS.toMillis(ourOSBean.getProcessCpuTime() - processStart); long compTime = getTotalCompilationMillis() - compStart; FreeMemorySnapshot memEnd = new FreeMemorySnapshot(); for (long id : ourThreadMXBean.getAllThreadIds()) { threadTimes.put(id, ourThreadMXBean.getThreadUserTime(id) - threadTimes.get(id)); } for (GarbageCollectorMXBean bean : ourGcBeans) { gcTimes.put(bean, bean.getCollectionTime() - gcTimes.getLong(bean)); } return new CpuUsageData(duration, gcTimes, threadTimes, compTime, processTime, memStart, memEnd); } static long getTotalCompilationMillis() { return ourCompilationMXBean.getTotalCompilationTime(); } private static class FreeMemorySnapshot { final long free = toMb(Runtime.getRuntime().freeMemory()); final long total = toMb(Runtime.getRuntime().totalMemory()); private static long toMb(long bytes) { return bytes / 1024 / 1024; } @Override public String toString() { return free + "/" + total; } } }
print percentage of JIT/GC activities to easier understand how expensive they were GitOrigin-RevId: 1343ca780e0e38be7b1253681e15fcb79521c31b
platform/testFramework/src/com/intellij/testFramework/CpuUsageData.java
print percentage of JIT/GC activities to easier understand how expensive they were
<ide><path>latform/testFramework/src/com/intellij/testFramework/CpuUsageData.java <ide> myMemEnd = memEnd; <ide> myCompilationTime = compilationTime; <ide> myProcessTime = processTime; <del> Object2LongMaps.fastForEach(gcTimes, entry -> { <del> myGcTimes.add(Pair.create(entry.getLongValue(), entry.getKey().getName())); <del> }); <add> Object2LongMaps.fastForEach(gcTimes, entry -> myGcTimes.add(Pair.create(entry.getLongValue(), entry.getKey().getName()))); <ide> Long2LongMaps.fastForEach(threadTimes, entry -> { <ide> ThreadInfo info = ourThreadMXBean.getThreadInfo(entry.getLongKey()); <ide> myThreadTimes.add(Pair.create(toMillis(entry.getLongValue()), info == null ? "<unknown>" : info.getThreadName())); <ide> <ide> String getProcessCpuStats() { <ide> long gcTotal = myGcTimes.stream().mapToLong(p -> p.first).sum(); <del> return myCompilationTime + "ms JITc " + <del> (gcTotal > 0 ? "and " + gcTotal + "ms GC " : "") + <del> "of " + myProcessTime + "ms total"; <add> return myCompilationTime + "ms (" +(myCompilationTime*100/(myProcessTime==0?1000000:myProcessTime))+"%) JITc"+ <add> (gcTotal > 0 ? " and " + gcTotal + "ms ("+ (gcTotal*100/(myProcessTime==0?1000000:myProcessTime))+"%) GC": "") + <add> " of " + myProcessTime + "ms total"; <ide> } <ide> <ide> public String getThreadStats() {
Java
mit
efdd07445f0b962fbc873931590c067626b5fa52
0
rhomobile/rhostudio,rhomobile/rhostudio
package rhogenwizard.editors; import java.util.ArrayList; import java.util.List; import rhogenwizard.PlatformType; public enum Capabilities { eUnknown(null, null), eGps("gps", PlatformType.eUnknown), ePim("pim", PlatformType.eUnknown), eCamera("camera", PlatformType.eUnknown), eVibrate("vibrate", PlatformType.eUnknown), ePhone("phone", PlatformType.eUnknown), eBluetooth("bluetooth", PlatformType.eUnknown), eCalendar("calendar", PlatformType.eUnknown), eNoMotoDevice("non_motorola_device", PlatformType.eUnknown), eNativeBrowser("native_browser", PlatformType.eUnknown), eMotoBrowser("motorola_browser", PlatformType.eUnknown), eHardAccelerate("hardware_acceleration", PlatformType.eAndroid), eNetWorkState("network_state",PlatformType.eAndroid), eSDCard("sdcard",PlatformType.eAndroid); public final String publicId; public final PlatformType platformId; private Capabilities(final String publicName, final PlatformType platform) { platformId = platform; publicId = publicName; } public static String[] getPublicIds() { return getPublicIdsList().toArray(new String[0]); } public static List<String> getPublicIdsList() { List<String> list = new ArrayList<String>(); for (Capabilities pt : Capabilities.values()) { if (pt.publicId != null) { list.add(pt.publicId); } } return list; } public static List<String> getPublicIdsList(List<Capabilities> capabList) { List<String> list = new ArrayList<String>(); for (Capabilities pt : capabList) { if (pt.publicId != null) { list.add(pt.publicId); } } return list; } public static List<Capabilities> getCapabilitiesList(List<String> capabList) { List<Capabilities> list = new ArrayList<Capabilities>(); if (capabList != null) { for (String pt : capabList) { list.add(Capabilities.fromId(pt)); } } return list; } public static Capabilities fromId(String id) { for (Capabilities pt : Capabilities.values()) { if (id.equals(pt.publicId)) { return pt; } } return Capabilities.eUnknown; } @Override public String toString() { return publicId; } };
rhogen-wizard/src/rhogenwizard/editors/Capabilities.java
package rhogenwizard.editors; import java.util.ArrayList; import java.util.List; import rhogenwizard.PlatformType; public enum Capabilities { eUnknown(null, null), eGps("gps", PlatformType.eUnknown), ePim("pim", PlatformType.eUnknown), eCamera("camera", PlatformType.eUnknown), eVibrate("vibrate", PlatformType.eUnknown), ePhone("phone", PlatformType.eUnknown), eBluetooth("bluetooth", PlatformType.eUnknown), eCalendar("calendar", PlatformType.eUnknown), eNoMotoDevice("non_motorola_device", PlatformType.eUnknown), eNativeBrowser("native_browser", PlatformType.eUnknown), eMotoBrowser("motorola_browser", PlatformType.eUnknown), eHardAccelerate("hardware_acceleration", PlatformType.eAndroid); public final String publicId; public final PlatformType platformId; private Capabilities(final String publicName, final PlatformType platform) { platformId = platform; publicId = publicName; } public static String[] getPublicIds() { return getPublicIdsList().toArray(new String[0]); } public static List<String> getPublicIdsList() { List<String> list = new ArrayList<String>(); for (Capabilities pt : Capabilities.values()) { if (pt.publicId != null) { list.add(pt.publicId); } } return list; } public static List<String> getPublicIdsList(List<Capabilities> capabList) { List<String> list = new ArrayList<String>(); for (Capabilities pt : capabList) { if (pt.publicId != null) { list.add(pt.publicId); } } return list; } public static List<Capabilities> getCapabilitiesList(List<String> capabList) { List<Capabilities> list = new ArrayList<Capabilities>(); if (capabList != null) { for (String pt : capabList) { list.add(Capabilities.fromId(pt)); } } return list; } public static Capabilities fromId(String id) { for (Capabilities pt : Capabilities.values()) { if (id.equals(pt.publicId)) { return pt; } } return Capabilities.eUnknown; } @Override public String toString() { return publicId; } };
add network_state and sdcard capabilities
rhogen-wizard/src/rhogenwizard/editors/Capabilities.java
add network_state and sdcard capabilities
<ide><path>hogen-wizard/src/rhogenwizard/editors/Capabilities.java <ide> eNoMotoDevice("non_motorola_device", PlatformType.eUnknown), <ide> eNativeBrowser("native_browser", PlatformType.eUnknown), <ide> eMotoBrowser("motorola_browser", PlatformType.eUnknown), <del> eHardAccelerate("hardware_acceleration", PlatformType.eAndroid); <add> eHardAccelerate("hardware_acceleration", PlatformType.eAndroid), <add> eNetWorkState("network_state",PlatformType.eAndroid), <add> eSDCard("sdcard",PlatformType.eAndroid); <ide> <ide> public final String publicId; <ide> public final PlatformType platformId;
Java
apache-2.0
120bf498c215c56c877d03b94f231f0b6c7ba609
0
sakai-mirror/evaluation,sakai-mirror/evaluation
/********************************************************************************** * * Copyright (c) 2005, 2006 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.evaluation.logic.impl.scheduling; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.api.app.scheduler.DelayedInvocation; import org.sakaiproject.api.app.scheduler.ScheduledInvocationManager; import org.sakaiproject.evaluation.logic.EvalEmailsLogic; import org.sakaiproject.evaluation.logic.EvalEvaluationsLogic; import org.sakaiproject.evaluation.logic.EvalExternalLogic; import org.sakaiproject.evaluation.logic.EvalSettings; import org.sakaiproject.evaluation.logic.externals.EvalJobLogic; import org.sakaiproject.evaluation.logic.utils.EvalUtils; import org.sakaiproject.evaluation.model.EvalEvaluation; import org.sakaiproject.evaluation.model.constant.EvalConstants; import org.sakaiproject.time.api.TimeService; /** * Handle job scheduling related to EvalEvaluation state transitions.</br> * Dates that have not passed may be changed, which might then require * rescheduling a job to keep jobs and EvalEvaluation dates in sync. * * @author rwellis * */ public class EvalJobLogicImpl implements EvalJobLogic { private static Log log = LogFactory.getLog(EvalJobLogicImpl.class); //the component scheduled by the ScheduledInvocationManager private final String COMPONENT_ID = "org.sakaiproject.evaluation.logic.externals.EvalScheduledInvocation"; private final String SEPARATOR = "/"; private final String EVENT_EVAL_START = "evaluation.state.start"; private final String EVENT_EVAL_DUE = "evaluation.state.due"; private final String EVENT_EVAL_STOP = "evaluation.state.stop"; private final String EVENT_EVAL_VIEWABLE = "evaluation.state.viewable"; private final String EVENT_EMAIL_REMINDER = "evaluation.email.reminder"; //TODO jleasia: track events private EvalEmailsLogic emails; public void setEmails(EvalEmailsLogic emails) { this.emails = emails; } private EvalEvaluationsLogic evalEvaluationsLogic; public void setEvalEvaluationsLogic(EvalEvaluationsLogic evalEvaluationsLogic) { this.evalEvaluationsLogic = evalEvaluationsLogic; } private EvalExternalLogic externalLogic; public void setExternalLogic(EvalExternalLogic externalLogic) { this.externalLogic = externalLogic; } private ScheduledInvocationManager scheduledInvocationManager; public void setScheduledInvocationManager(ScheduledInvocationManager scheduledInvocationManager) { this.scheduledInvocationManager = scheduledInvocationManager; } private EvalSettings settings; public void setSettings(EvalSettings settings) { this.settings = settings; } private TimeService timeService; public void setTimeService(TimeService timeService) { this.timeService = timeService; } public void init() { log.debug("EvalJobLogicImpl.init()"); } public EvalJobLogicImpl() { } /** * Compare the date when a job will be invoked with the * EvalEvaluation date to see if the job needs to be rescheduled. * * @param eval the EvalEvaluation * @param jobType the type of job (refer to EvalConstants) * @param correctDate the date when the job should be invoked * */ private void checkInvocationDate(EvalEvaluation eval, String jobType, Date correctDate) { if(eval == null || jobType == null || correctDate == null) return; if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.checkInvocationDate(" + eval.getId() + "," + jobType + "," + correctDate); /* We don't reschedule reminders, because the active date won't change * once an evaluation becomes active, and therefore reminder dates also * remain fixed. We do add or remove reminders if the due date is moved * forward or backward. */ if(EvalConstants.JOB_TYPE_REMINDER.equals(jobType)) return; //get the delayed invocation, a pea with .Date Date String id = eval.getId().toString(); String opaqueContext = id + SEPARATOR + jobType; DelayedInvocation[] invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); //if there are none, return if(invocations.length == 0) { return; } else if(invocations.length == 1) { //we expect at most one delayed invocation matching componentId and opaqueContxt //if the dates differ if(invocations[0].date.compareTo(correctDate) != 0) { //remove the old invocation scheduledInvocationManager.deleteDelayedInvocation(invocations[0].uuid); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.checkInvocationDate remove the old invocation " + invocations[0].uuid + "," + invocations[0].contextId + "," + invocations[0].date); //and schedule a new invocation scheduledInvocationManager.createDelayedInvocation(timeService.newTime(correctDate.getTime()), COMPONENT_ID, opaqueContext); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.checkInvocationDate and schedule a new invocation " + correctDate + "," + COMPONENT_ID + "," + opaqueContext + ")"); //the due date was changed, so reminders might need to be added or removed if(EvalConstants.JOB_TYPE_DUE.equals(jobType)) { fixReminders(eval.getId()); } } } else { log.warn(this + ".checkInvocationDate: multiple delayed invocations of componentId '" + COMPONENT_ID + "', opaqueContext '" + opaqueContext +"'"); } } /** * Add or remove reminders if the due date is moved forward or back while in the active state * * @param evalId the EvalEvaluation id */ private void fixReminders(Long evaluationId) { //TODO refactor with scheduleReminders EvalEvaluation eval = evalEvaluationsLogic.getEvaluationById(evaluationId); String opaqueContext = evaluationId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_REMINDER; DelayedInvocation lastReminder = null; long start = 0; //if the due date is sooner, any reminders after the due date should be removed DelayedInvocation[] invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); lastReminder = invocations[0]; for(int i = 0; i < invocations.length; i++) { //remove reminders after the due date DelayedInvocation invocation = invocations[i]; Date runAt = invocation.date; if(runAt.after(eval.getDueDate())) { scheduledInvocationManager.deleteDelayedInvocation(invocation.uuid); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.fixReminders remove reminder after the due date " + invocation.uuid + "," + invocation.contextId + "," + invocation.date); } else { if(invocation.date.after(lastReminder.date)) { lastReminder = invocation; } } } //if the due date is later, it might be necessary to schedule more reminders if(lastReminder != null) { //start at the last reminder start = lastReminder.date.getTime(); } else { //start at the current time start = timeService.newTime().getTime(); } long due = eval.getDueDate().getTime(); long available = due - start; long interval = 1000 * 60 * 60 * 24 * eval.getReminderDays().intValue(); long numberOfReminders = available/interval; long runAt = start; //schedule more reminders for(int i = 0; i < numberOfReminders; i++) { if(runAt + interval < due) { runAt = runAt + interval; scheduledInvocationManager.createDelayedInvocation(timeService.newTime(runAt), COMPONENT_ID, opaqueContext); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.fixReminders schedule more reminders " + timeService.newTime(runAt) + "," + COMPONENT_ID + "," + opaqueContext + ")"); } } } /** * Remove all ScheduledInvocationCammand jobs for an EvalEvaluation * * @param evalId the EvalEvaluation id */ public void removeScheduledInvocations(Long evalId) { if(evalId == null) return; String userId = externalLogic.getCurrentUserId(); if(evalEvaluationsLogic.canRemoveEvaluation(userId, evalId)) { //TODO be selective based on the state of the EvalEvaluation when deleted String opaqueContext = null; DelayedInvocation[] invocations = null; opaqueContext = evalId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_ACTIVE; invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); for(int i = 0; i < invocations.length; i++) { scheduledInvocationManager.deleteDelayedInvocation(invocations[i].uuid); } opaqueContext = evalId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_DUE; invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); for(int i = 0; i < invocations.length; i++) { scheduledInvocationManager.deleteDelayedInvocation(invocations[i].uuid); } opaqueContext = evalId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_CLOSED; invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); for(int i = 0; i < invocations.length; i++) { scheduledInvocationManager.deleteDelayedInvocation(invocations[i].uuid); } opaqueContext = evalId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_REMINDER; invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); for(int i = 0; i < invocations.length; i++) { scheduledInvocationManager.deleteDelayedInvocation(invocations[i].uuid); } opaqueContext = evalId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_VIEWABLE; invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); for(int i = 0; i < invocations.length; i++) { scheduledInvocationManager.deleteDelayedInvocation(invocations[i].uuid); } opaqueContext = evalId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_VIEWABLE_INSTRUCTORS; invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); for(int i = 0; i < invocations.length; i++) { scheduledInvocationManager.deleteDelayedInvocation(invocations[i].uuid); } opaqueContext = evalId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_VIEWABLE_STUDENTS; invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); for(int i = 0; i < invocations.length; i++) { scheduledInvocationManager.deleteDelayedInvocation(invocations[i].uuid); } } } /* * (non-Javadoc) * @see org.sakaiproject.evaluation.logic.externals.EvalJobLogic#processNewEvaluation(org.sakaiproject.evaluation.model.EvalEvaluation) */ public void processNewEvaluation(EvalEvaluation eval) { if(eval == null) throw new NullPointerException("Notification of a new evaluation failed, because the evaluation was null."); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.processNewEvaluation(" + eval.getId() + ")"); String state = EvalUtils.getEvaluationState(eval); if(state == null) throw new NullPointerException("Notification of a new evaluation failed, because the evaluation state was null."); //send created email if instructor can add questions or opt-in or opt-out int instructorAdds = ((Integer)settings.get(EvalSettings.INSTRUCTOR_ADD_ITEMS_NUMBER)).intValue(); if(instructorAdds > 0 || !eval.getInstructorOpt().equals(EvalConstants.INSTRUCTOR_REQUIRED)) { /* Note: email cannot be sent at this point, because it precedes saveAssignGroup, * so we schedule email for ten minutes from now, also giving instructor ten minutes * to delete the evaluation and its notification */ long runAt = new Date().getTime() + (1000 * 60 * 10); scheduleJob(eval.getId(), new Date(runAt), EvalConstants.JOB_TYPE_CREATED); } scheduleJob(eval.getId(), eval.getStartDate(), EvalConstants.JOB_TYPE_ACTIVE); } /* * (non-Javadoc) * @see org.sakaiproject.evaluation.logic.externals.EvalJobLogic#processEvaluationChange(org.sakaiproject.evaluation.model.EvalEvaluation) */ public void processEvaluationChange(EvalEvaluation eval) { if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.processEvaluationChange(" + eval.getId() + ")"); //checks if(eval == null) return; String state = EvalUtils.getEvaluationState(eval); if(EvalConstants.EVALUATION_STATE_UNKNOWN.equals(state)) { if(log.isWarnEnabled()) log.warn(this + ".processEvaluationChange(Long "+ eval.getId().toString() + ") for " + eval.getTitle() + ". Evaluation in UNKNOWN state"); throw new RuntimeException("Evaluation '"+eval.getTitle()+"' in UNKNOWN state"); } try { if(EvalConstants.EVALUATION_STATE_INQUEUE.equals(eval.getState())) { //make sure active job invocation date matches EvalEvaluation start date checkInvocationDate(eval, EvalConstants.JOB_TYPE_ACTIVE, eval.getStartDate()); } else if(EvalConstants.EVALUATION_STATE_ACTIVE.equals(eval.getState())) { /* make sure due job invocation start date matches EvalEaluation due date * and moving the due date is reflected in reminders */ checkInvocationDate(eval, EvalConstants.JOB_TYPE_DUE, eval.getDueDate()); } else if (EvalConstants.EVALUATION_STATE_DUE.equals(eval.getState())) { //make sure closed job invocation start date matches EvalEvaluation stop date checkInvocationDate(eval, EvalConstants.JOB_TYPE_CLOSED, eval.getStopDate()); } else if (EvalConstants.EVALUATION_STATE_CLOSED.equals(eval.getState())) { //make sure view job invocation start date matches EvalEvaluation view date checkInvocationDate(eval, EvalConstants.JOB_TYPE_VIEWABLE, eval.getViewDate()); //make sure view by instructors job invocation start date matches EvalEvaluation instructor's date checkInvocationDate(eval, EvalConstants.JOB_TYPE_VIEWABLE_INSTRUCTORS, eval.getInstructorsDate()); //make sure view by students job invocation start date matches EvalEvaluation student's date checkInvocationDate(eval, EvalConstants.JOB_TYPE_VIEWABLE_STUDENTS, eval.getStudentsDate()); } } catch(Exception e) { e.printStackTrace(); if(log.isWarnEnabled()) log.warn(this + ".processEvaluationChange("+ eval.getId() + ") for '" + eval.getTitle() + "' " + e); throw new RuntimeException("Evaluation '" + eval.getTitle() + "' " + e); } } /** * Schedule a job using the ScheduledInvocationManager.</br> * "When" is specified by runDate, "what" by componentId, and "what to do" * by opaqueContext. OpaqueContext contains an EvalEvaluationId * and a jobType from EvalConstants, which is used to keep track of * pending jobs and reschedule or remove jobs when necessary. * *@param evaluationId the id of an EvalEvaluation *@param runDate the Date when the command should be invoked *@param jobType the type of job, from EvalConstants */ private void scheduleJob(Long evaluationId, Date runDate, String jobType) { if(evaluationId == null || runDate == null || jobType == null) { if(log.isErrorEnabled()) log.error(this + ".scheduleJob null parameter"); //TODO: throw exception return; } if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.scheduleJob(" + evaluationId + "," + runDate + "," + jobType + ")"); String opaqueContext = evaluationId.toString() + SEPARATOR + jobType; scheduledInvocationManager.createDelayedInvocation(timeService.newTime(runDate.getTime()), COMPONENT_ID, opaqueContext); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.scheduleJob scheduledInvocationManager.createDelayedInvocation(" + timeService.newTime(runDate.getTime()) + "," + COMPONENT_ID + "," + opaqueContext + ")"); } /** * Schedule reminders to be run under the ScheduledInvocationManager.</br> * The ScheduledInvocationManager has no concept of repeating an invocation, so a number * of reminders are pre-scheduled. * * @param evaluationId the EvalEvaluation id */ private void scheduleReminders(Long evaluationId) { EvalEvaluation eval = evalEvaluationsLogic.getEvaluationById(evaluationId); String opaqueContext = evaluationId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_REMINDER; //schedule reminders at selected intervals while the evaluation is available long start = eval.getStartDate().getTime(); long due = eval.getDueDate().getTime(); long available = due - start; long interval = 1000 * 60 * 60 * 24 * eval.getReminderDays().intValue(); if(interval != 0) { long numberOfReminders = available/interval; long runAt = eval.getStartDate().getTime(); for(int i = 0; i < numberOfReminders; i++) { if(runAt + interval < due) { runAt = runAt + interval; scheduledInvocationManager.createDelayedInvocation(timeService.newTime(runAt), COMPONENT_ID, opaqueContext); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.scheduleReminders(" + evaluationId + ") - scheduledInvocationManager.createDelayedInvocation( " + timeService.newTime(runAt) + "," + COMPONENT_ID + "," + opaqueContext); } } } } /* * (non-Javadoc) * @see org.sakaiproject.evaluation.logic.externals.EvalJobLogic#jobAction(java.lang.Long) */ public void jobAction(Long evaluationId, String jobType) { /* Note: If interactive response time is too slow waiting for * mail to be sent, sending mail could be done as another type * of job run by the scheduler in a separate thread. */ if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.jobAction(" + evaluationId + "," + jobType + ")"); try { EvalEvaluation eval = evalEvaluationsLogic.getEvaluationById(evaluationId); //fix EvalEvaluation state String state = evalEvaluationsLogic.getEvaluationState(evaluationId); if(log.isDebugEnabled()) log.debug("evaluation state " + state + " saved"); //TODO:simplify scheduleJob(JOB_TYPE_REMINDER) with Reminder job determining if another Reminder is needed //send email and/or schedule jobs if(EvalConstants.EVALUATION_STATE_INQUEUE.equals(state)) { sendCreatedEmail(evaluationId); } else if(EvalConstants.EVALUATION_STATE_ACTIVE.equals(state)) { externalLogic.registerEntityEvent(EVENT_EVAL_START, eval); sendAvailableEmail(evaluationId); scheduleJob(eval.getId(), eval.getDueDate(), EvalConstants.JOB_TYPE_DUE); scheduleReminders(eval.getId()); } else if(EvalConstants.EVALUATION_STATE_DUE.equals(state)) { externalLogic.registerEntityEvent(EVENT_EVAL_DUE, eval); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.jobAction scheduleJob(" + eval.getId() + "," + eval.getStopDate() + "," + EvalConstants.JOB_TYPE_CLOSED + ")"); scheduleJob(eval.getId(), eval.getStopDate(), EvalConstants.JOB_TYPE_CLOSED); } else if(EvalConstants.EVALUATION_STATE_CLOSED.equals(state)) { externalLogic.registerEntityEvent(EVENT_EVAL_STOP, eval); Date instructorViewDate = eval.getInstructorsDate(); Date studentViewDate = eval.getStudentsDate(); if(instructorViewDate == null && studentViewDate == null) //use same view date for all users scheduleJob(eval.getId(), eval.getViewDate(), EvalConstants.JOB_TYPE_VIEWABLE); else { //use separate view dates scheduleJob(eval.getId(), instructorViewDate, EvalConstants.JOB_TYPE_VIEWABLE_INSTRUCTORS); if(studentViewDate != null) scheduleJob(eval.getId(), studentViewDate, EvalConstants.JOB_TYPE_VIEWABLE_STUDENTS); } } else if(EvalConstants.EVALUATION_STATE_VIEWABLE.equals(state)) { externalLogic.registerEntityEvent(EVENT_EVAL_VIEWABLE, eval); //send results viewable notification to owner if private, or all if not sendViewableEmail(evaluationId, jobType, eval.getResultsPrivate()); } } catch(Exception e) { log.error("jobAction died horribly:" + e.getMessage(), e); throw new RuntimeException(e); // die horribly, as it should -AZ } } /** * Send email to evaluation participants that an evaluation * is available for taking by clicking the contained URL * * @param evalId the EvalEvaluation id */ public void sendAvailableEmail(Long evalId) { //For now, we always want to include the evaluatees in the evaluations boolean includeEvaluatees = true; String[] sentMessages = emails.sendEvalAvailableNotifications(evalId, includeEvaluatees); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.sendAvailableEmail(" + evalId + ")" + " sentMessages: " + sentMessages.toString()); } /** * Send email that an evaluation has been created</br> * not implemented * * @param evalId the EvalEvaluation id */ public void sendCreatedEmail(Long evalId) { boolean includeOwner = true; String[] sentMessages = emails.sendEvalCreatedNotifications(evalId, includeOwner); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.sendCreatedEmail(" + evalId + ")" + " sentMessages: " + sentMessages.toString()); } /** * Send a reminder that an evaluation is available * for taking to those who have not responded * * @param evalId the EvalEvaluation id */ public void sendReminderEmail(Long evalId) { EvalEvaluation eval = evalEvaluationsLogic.getEvaluationById(evalId); externalLogic.registerEntityEvent(EVENT_EMAIL_REMINDER, eval); String includeConstant = EvalConstants.EMAIL_INCLUDE_ALL; String[] sentMessages = emails.sendEvalReminderNotifications(evalId, includeConstant); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.sendReminderEmail(" + evalId + ")" + " sentMessages: " + sentMessages.toString()); } /** * Send email that the results of an evaluation may be viewed now.</br> * Notification may be sent to owner only, instructors and students together or * separately. * * @param evalId the EvalEvaluation id * @param the job type fom EvalConstants */ public void sendViewableEmail(Long evalId, String jobType, Boolean resultsPrivate) { boolean includeEvaluatees = true; boolean includeAdmins = true; //if results are private, only send notification to owner if(resultsPrivate.booleanValue()) { includeEvaluatees = false; includeAdmins = false; String[] sentMessages = emails.sendEvalResultsNotifications(evalId, includeEvaluatees, includeAdmins); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.sendViewableEmail(" + evalId + "," + jobType + ", resultsPrivate " + resultsPrivate + ")" + " sentMessages: " + sentMessages.toString()); } else { if(EvalConstants.JOB_TYPE_VIEWABLE.equals(jobType)) { String[] sentMessages = emails.sendEvalResultsNotifications(evalId, includeEvaluatees, includeAdmins); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.sendViewableEmail(" + evalId + "," + jobType + ", resultsPrivate " + resultsPrivate + ")" + " sentMessages: " + sentMessages.toString()); } else if(EvalConstants.JOB_TYPE_VIEWABLE_INSTRUCTORS.equals(jobType)) { includeEvaluatees = false; String[] sentMessages = emails.sendEvalResultsNotifications(evalId, includeEvaluatees, includeAdmins); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.sendViewableEmail(" + evalId + "," + jobType + ", resultsPrivate " + resultsPrivate + ")" + " sentMessages: " + sentMessages.toString()); } else if(EvalConstants.JOB_TYPE_VIEWABLE_STUDENTS.equals(jobType)) { includeAdmins = false; String[] sentMessages = emails.sendEvalResultsNotifications(evalId, includeEvaluatees, includeAdmins); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.sendViewableEmail(" + evalId + "," + jobType + ", resultsPrivate " + resultsPrivate + ")" + " sentMessages: " + sentMessages.toString()); } else { if(log.isWarnEnabled()) log.warn(this + ".sendViewableEmail: for evalId " + evalId + " unrecognized job type " + jobType); } } } }
impl/logic/src/java/org/sakaiproject/evaluation/logic/impl/scheduling/EvalJobLogicImpl.java
/********************************************************************************** * * Copyright (c) 2005, 2006 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.evaluation.logic.impl.scheduling; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.api.app.scheduler.DelayedInvocation; import org.sakaiproject.api.app.scheduler.ScheduledInvocationManager; import org.sakaiproject.evaluation.logic.EvalEmailsLogic; import org.sakaiproject.evaluation.logic.EvalEvaluationsLogic; import org.sakaiproject.evaluation.logic.EvalExternalLogic; import org.sakaiproject.evaluation.logic.EvalSettings; import org.sakaiproject.evaluation.logic.externals.EvalJobLogic; import org.sakaiproject.evaluation.logic.utils.EvalUtils; import org.sakaiproject.evaluation.model.EvalEvaluation; import org.sakaiproject.evaluation.model.constant.EvalConstants; import org.sakaiproject.time.api.TimeService; /** * Handle job scheduling related to EvalEvaluation state transitions.</br> * Dates that have not passed may be changed, which might then require * rescheduling a job to keep jobs and EvalEvaluation dates in sync. * * @author rwellis * */ public class EvalJobLogicImpl implements EvalJobLogic { private static Log log = LogFactory.getLog(EvalJobLogicImpl.class); //the component scheduled by the ScheduledInvocationManager private final String COMPONENT_ID = "org.sakaiproject.evaluation.logic.externals.EvalScheduledInvocation"; private final String SEPARATOR = "/"; private final String EVENT_EVAL_START = "evaluation.state.start"; private final String EVENT_EVAL_DUE = "evaluation.state.due"; private final String EVENT_EVAL_STOP = "evaluation.state.stop"; private final String EVENT_EVAL_VIEWABLE = "evaluation.state.viewable"; private final String EVENT_EMAIL_REMINDER = "evaluation.email.reminder"; //TODO jleasia: track events private EvalEmailsLogic emails; public void setEmails(EvalEmailsLogic emails) { this.emails = emails; } private EvalEvaluationsLogic evalEvaluationsLogic; public void setEvalEvaluationsLogic(EvalEvaluationsLogic evalEvaluationsLogic) { this.evalEvaluationsLogic = evalEvaluationsLogic; } private EvalExternalLogic externalLogic; public void setExternalLogic(EvalExternalLogic externalLogic) { this.externalLogic = externalLogic; } private ScheduledInvocationManager scheduledInvocationManager; public void setScheduledInvocationManager(ScheduledInvocationManager scheduledInvocationManager) { this.scheduledInvocationManager = scheduledInvocationManager; } private EvalSettings settings; public void setSettings(EvalSettings settings) { this.settings = settings; } private TimeService timeService; public void setTimeService(TimeService timeService) { this.timeService = timeService; } public void init() { log.debug("EvalJobLogicImpl.init()"); } public EvalJobLogicImpl() { } /** * Compare the date when a job will be invoked with the * EvalEvaluation date to see if the job needs to be rescheduled. * * @param eval the EvalEvaluation * @param jobType the type of job (refer to EvalConstants) * @param correctDate the date when the job should be invoked * */ private void checkInvocationDate(EvalEvaluation eval, String jobType, Date correctDate) { if(eval == null || jobType == null || correctDate == null) return; if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.checkInvocationDate(" + eval.getId() + "," + jobType + "," + correctDate); /* We don't reschedule reminders, because the active date won't change * once an evaluation becomes active, and therefore reminder dates also * remain fixed. We do add or remove reminders if the due date is moved * forward or backward. */ if(EvalConstants.JOB_TYPE_REMINDER.equals(jobType)) return; //get the delayed invocation, a pea with .Date Date String id = eval.getId().toString(); String opaqueContext = id + SEPARATOR + jobType; DelayedInvocation[] invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); //if there are none, return if(invocations.length == 0) { return; } else if(invocations.length == 1) { //we expect at most one delayed invocation matching componentId and opaqueContxt //if the dates differ if(invocations[0].date.compareTo(correctDate) != 0) { //remove the old invocation scheduledInvocationManager.deleteDelayedInvocation(invocations[0].uuid); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.checkInvocationDate remove the old invocation " + invocations[0].uuid + "," + invocations[0].contextId + "," + invocations[0].date); //and schedule a new invocation scheduledInvocationManager.createDelayedInvocation(timeService.newTime(correctDate.getTime()), COMPONENT_ID, opaqueContext); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.checkInvocationDate and schedule a new invocation " + correctDate + "," + COMPONENT_ID + "," + opaqueContext + ")"); //the due date was changed, so reminders might need to be added or removed if(EvalConstants.JOB_TYPE_DUE.equals(jobType)) { fixReminders(eval.getId()); } } } else { log.warn(this + ".checkInvocationDate: multiple delayed invocations of componentId '" + COMPONENT_ID + "', opaqueContext '" + opaqueContext +"'"); } } /** * Add or remove reminders if the due date is moved forward or back while in the active state * * @param evalId the EvalEvaluation id */ private void fixReminders(Long evaluationId) { //TODO refactor with scheduleReminders EvalEvaluation eval = evalEvaluationsLogic.getEvaluationById(evaluationId); String opaqueContext = evaluationId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_REMINDER; DelayedInvocation lastReminder = null; long start = 0; //if the due date is sooner, any reminders after the due date should be removed DelayedInvocation[] invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); lastReminder = invocations[0]; for(int i = 0; i < invocations.length; i++) { //remove reminders after the due date DelayedInvocation invocation = invocations[i]; Date runAt = invocation.date; if(runAt.after(eval.getDueDate())) { scheduledInvocationManager.deleteDelayedInvocation(invocation.uuid); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.fixReminders remove reminder after the due date " + invocation.uuid + "," + invocation.contextId + "," + invocation.date); } else { if(invocation.date.after(lastReminder.date)) { lastReminder = invocation; } } } //if the due date is later, it might be necessary to schedule more reminders if(lastReminder != null) { //start at the last reminder start = lastReminder.date.getTime(); } else { //start at the current time start = timeService.newTime().getTime(); } long due = eval.getDueDate().getTime(); long available = due - start; long interval = 1000 * 60 * 60 * 24 * eval.getReminderDays().intValue(); long numberOfReminders = available/interval; long runAt = start; //schedule more reminders for(int i = 0; i < numberOfReminders; i++) { if(runAt + interval < due) { runAt = runAt + interval; scheduledInvocationManager.createDelayedInvocation(timeService.newTime(runAt), COMPONENT_ID, opaqueContext); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.fixReminders schedule more reminders " + timeService.newTime(runAt) + "," + COMPONENT_ID + "," + opaqueContext + ")"); } } } /** * Remove all ScheduledInvocationCammand jobs for an EvalEvaluation * * @param evalId the EvalEvaluation id */ public void removeScheduledInvocations(Long evalId) { if(evalId == null) return; String userId = externalLogic.getCurrentUserId(); if(evalEvaluationsLogic.canRemoveEvaluation(userId, evalId)) { //TODO be selective based on the state of the EvalEvaluation when deleted String opaqueContext = null; DelayedInvocation[] invocations = null; opaqueContext = evalId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_ACTIVE; invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); for(int i = 0; i < invocations.length; i++) { scheduledInvocationManager.deleteDelayedInvocation(invocations[i].uuid); } opaqueContext = evalId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_DUE; invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); for(int i = 0; i < invocations.length; i++) { scheduledInvocationManager.deleteDelayedInvocation(invocations[i].uuid); } opaqueContext = evalId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_CLOSED; invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); for(int i = 0; i < invocations.length; i++) { scheduledInvocationManager.deleteDelayedInvocation(invocations[i].uuid); } opaqueContext = evalId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_REMINDER; invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); for(int i = 0; i < invocations.length; i++) { scheduledInvocationManager.deleteDelayedInvocation(invocations[i].uuid); } opaqueContext = evalId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_VIEWABLE; invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); for(int i = 0; i < invocations.length; i++) { scheduledInvocationManager.deleteDelayedInvocation(invocations[i].uuid); } opaqueContext = evalId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_VIEWABLE_INSTRUCTORS; invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); for(int i = 0; i < invocations.length; i++) { scheduledInvocationManager.deleteDelayedInvocation(invocations[i].uuid); } opaqueContext = evalId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_VIEWABLE_STUDENTS; invocations = scheduledInvocationManager.findDelayedInvocations(COMPONENT_ID, opaqueContext); for(int i = 0; i < invocations.length; i++) { scheduledInvocationManager.deleteDelayedInvocation(invocations[i].uuid); } } } /* * (non-Javadoc) * @see org.sakaiproject.evaluation.logic.externals.EvalJobLogic#processNewEvaluation(org.sakaiproject.evaluation.model.EvalEvaluation) */ public void processNewEvaluation(EvalEvaluation eval) { if(eval == null) throw new NullPointerException("Notification of a new evaluation failed, because the evaluation was null."); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.processNewEvaluation(" + eval.getId() + ")"); String state = EvalUtils.getEvaluationState(eval); if(state == null) throw new NullPointerException("Notification of a new evaluation failed, because the evaluation state was null."); //send created email if instructor can add questions or opt-in or opt-out int instructorAdds = ((Integer)settings.get(EvalSettings.INSTRUCTOR_ADD_ITEMS_NUMBER)).intValue(); if(instructorAdds > 0 || !eval.getInstructorOpt().equals(EvalConstants.INSTRUCTOR_REQUIRED)) { /* Note: email cannot be sent at this point, because it precedes saveAssignGroup, * so we schedule email for ten minutes from now, also giving instructor ten minutes * to delete the evaluation and its notification */ long runAt = new Date().getTime() + (1000 * 60 * 60 * 10); scheduleJob(eval.getId(), new Date(runAt), EvalConstants.JOB_TYPE_CREATED); } scheduleJob(eval.getId(), eval.getStartDate(), EvalConstants.JOB_TYPE_ACTIVE); } /* * (non-Javadoc) * @see org.sakaiproject.evaluation.logic.externals.EvalJobLogic#processEvaluationChange(org.sakaiproject.evaluation.model.EvalEvaluation) */ public void processEvaluationChange(EvalEvaluation eval) { if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.processEvaluationChange(" + eval.getId() + ")"); //checks if(eval == null) return; String state = EvalUtils.getEvaluationState(eval); if(EvalConstants.EVALUATION_STATE_UNKNOWN.equals(state)) { if(log.isWarnEnabled()) log.warn(this + ".processEvaluationChange(Long "+ eval.getId().toString() + ") for " + eval.getTitle() + ". Evaluation in UNKNOWN state"); throw new RuntimeException("Evaluation '"+eval.getTitle()+"' in UNKNOWN state"); } try { if(EvalConstants.EVALUATION_STATE_INQUEUE.equals(eval.getState())) { //make sure active job invocation date matches EvalEvaluation start date checkInvocationDate(eval, EvalConstants.JOB_TYPE_ACTIVE, eval.getStartDate()); } else if(EvalConstants.EVALUATION_STATE_ACTIVE.equals(eval.getState())) { /* make sure due job invocation start date matches EvalEaluation due date * and moving the due date is reflected in reminders */ checkInvocationDate(eval, EvalConstants.JOB_TYPE_DUE, eval.getDueDate()); } else if (EvalConstants.EVALUATION_STATE_DUE.equals(eval.getState())) { //make sure closed job invocation start date matches EvalEvaluation stop date checkInvocationDate(eval, EvalConstants.JOB_TYPE_CLOSED, eval.getStopDate()); } else if (EvalConstants.EVALUATION_STATE_CLOSED.equals(eval.getState())) { //make sure view job invocation start date matches EvalEvaluation view date checkInvocationDate(eval, EvalConstants.JOB_TYPE_VIEWABLE, eval.getViewDate()); //make sure view by instructors job invocation start date matches EvalEvaluation instructor's date checkInvocationDate(eval, EvalConstants.JOB_TYPE_VIEWABLE_INSTRUCTORS, eval.getInstructorsDate()); //make sure view by students job invocation start date matches EvalEvaluation student's date checkInvocationDate(eval, EvalConstants.JOB_TYPE_VIEWABLE_STUDENTS, eval.getStudentsDate()); } } catch(Exception e) { e.printStackTrace(); if(log.isWarnEnabled()) log.warn(this + ".processEvaluationChange("+ eval.getId() + ") for '" + eval.getTitle() + "' " + e); throw new RuntimeException("Evaluation '" + eval.getTitle() + "' " + e); } } /** * Schedule a job using the ScheduledInvocationManager.</br> * "When" is specified by runDate, "what" by componentId, and "what to do" * by opaqueContext. OpaqueContext contains an EvalEvaluationId * and a jobType from EvalConstants, which is used to keep track of * pending jobs and reschedule or remove jobs when necessary. * *@param evaluationId the id of an EvalEvaluation *@param runDate the Date when the command should be invoked *@param jobType the type of job, from EvalConstants */ private void scheduleJob(Long evaluationId, Date runDate, String jobType) { if(evaluationId == null || runDate == null || jobType == null) { if(log.isErrorEnabled()) log.error(this + ".scheduleJob null parameter"); //TODO: throw exception return; } if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.scheduleJob(" + evaluationId + "," + runDate + "," + jobType + ")"); String opaqueContext = evaluationId.toString() + SEPARATOR + jobType; scheduledInvocationManager.createDelayedInvocation(timeService.newTime(runDate.getTime()), COMPONENT_ID, opaqueContext); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.scheduleJob scheduledInvocationManager.createDelayedInvocation(" + timeService.newTime(runDate.getTime()) + "," + COMPONENT_ID + "," + opaqueContext + ")"); } /** * Schedule reminders to be run under the ScheduledInvocationManager.</br> * The ScheduledInvocationManager has no concept of repeating an invocation, so a number * of reminders are pre-scheduled. * * @param evaluationId the EvalEvaluation id */ private void scheduleReminders(Long evaluationId) { EvalEvaluation eval = evalEvaluationsLogic.getEvaluationById(evaluationId); String opaqueContext = evaluationId.toString() + SEPARATOR + EvalConstants.JOB_TYPE_REMINDER; //schedule reminders at selected intervals while the evaluation is available long start = eval.getStartDate().getTime(); long due = eval.getDueDate().getTime(); long available = due - start; long interval = 1000 * 60 * 60 * 24 * eval.getReminderDays().intValue(); if(interval != 0) { long numberOfReminders = available/interval; long runAt = eval.getStartDate().getTime(); for(int i = 0; i < numberOfReminders; i++) { if(runAt + interval < due) { runAt = runAt + interval; scheduledInvocationManager.createDelayedInvocation(timeService.newTime(runAt), COMPONENT_ID, opaqueContext); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.scheduleReminders(" + evaluationId + ") - scheduledInvocationManager.createDelayedInvocation( " + timeService.newTime(runAt) + "," + COMPONENT_ID + "," + opaqueContext); } } } } /* * (non-Javadoc) * @see org.sakaiproject.evaluation.logic.externals.EvalJobLogic#jobAction(java.lang.Long) */ public void jobAction(Long evaluationId, String jobType) { /* Note: If interactive response time is too slow waiting for * mail to be sent, sending mail could be done as another type * of job run by the scheduler in a separate thread. */ if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.jobAction(" + evaluationId + "," + jobType + ")"); try { EvalEvaluation eval = evalEvaluationsLogic.getEvaluationById(evaluationId); //fix EvalEvaluation state String state = evalEvaluationsLogic.getEvaluationState(evaluationId); if(log.isDebugEnabled()) log.debug("evaluation state " + state + " saved"); //TODO:simplify scheduleJob(JOB_TYPE_REMINDER) with Reminder job determining if another Reminder is needed //send email and/or schedule jobs if(EvalConstants.EVALUATION_STATE_INQUEUE.equals(state)) { sendCreatedEmail(evaluationId); } else if(EvalConstants.EVALUATION_STATE_ACTIVE.equals(state)) { externalLogic.registerEntityEvent(EVENT_EVAL_START, eval); sendAvailableEmail(evaluationId); scheduleJob(eval.getId(), eval.getDueDate(), EvalConstants.JOB_TYPE_DUE); scheduleReminders(eval.getId()); } else if(EvalConstants.EVALUATION_STATE_DUE.equals(state)) { externalLogic.registerEntityEvent(EVENT_EVAL_DUE, eval); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.jobAction scheduleJob(" + eval.getId() + "," + eval.getStopDate() + "," + EvalConstants.JOB_TYPE_CLOSED + ")"); scheduleJob(eval.getId(), eval.getStopDate(), EvalConstants.JOB_TYPE_CLOSED); } else if(EvalConstants.EVALUATION_STATE_CLOSED.equals(state)) { externalLogic.registerEntityEvent(EVENT_EVAL_STOP, eval); Date instructorViewDate = eval.getInstructorsDate(); Date studentViewDate = eval.getStudentsDate(); if(instructorViewDate == null && studentViewDate == null) //use same view date for all users scheduleJob(eval.getId(), eval.getViewDate(), EvalConstants.JOB_TYPE_VIEWABLE); else { //use separate view dates scheduleJob(eval.getId(), instructorViewDate, EvalConstants.JOB_TYPE_VIEWABLE_INSTRUCTORS); if(studentViewDate != null) scheduleJob(eval.getId(), studentViewDate, EvalConstants.JOB_TYPE_VIEWABLE_STUDENTS); } } else if(EvalConstants.EVALUATION_STATE_VIEWABLE.equals(state)) { externalLogic.registerEntityEvent(EVENT_EVAL_VIEWABLE, eval); //send results viewable notification to owner if private, or all if not sendViewableEmail(evaluationId, jobType, eval.getResultsPrivate()); } } catch(Exception e) { log.error("jobAction died horribly:" + e.getMessage(), e); throw new RuntimeException(e); // die horribly, as it should -AZ } } /** * Send email to evaluation participants that an evaluation * is available for taking by clicking the contained URL * * @param evalId the EvalEvaluation id */ public void sendAvailableEmail(Long evalId) { //For now, we always want to include the evaluatees in the evaluations boolean includeEvaluatees = true; String[] sentMessages = emails.sendEvalAvailableNotifications(evalId, includeEvaluatees); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.sendAvailableEmail(" + evalId + ")" + " sentMessages: " + sentMessages.toString()); } /** * Send email that an evaluation has been created</br> * not implemented * * @param evalId the EvalEvaluation id */ public void sendCreatedEmail(Long evalId) { boolean includeOwner = true; String[] sentMessages = emails.sendEvalCreatedNotifications(evalId, includeOwner); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.sendCreatedEmail(" + evalId + ")" + " sentMessages: " + sentMessages.toString()); } /** * Send a reminder that an evaluation is available * for taking to those who have not responded * * @param evalId the EvalEvaluation id */ public void sendReminderEmail(Long evalId) { EvalEvaluation eval = evalEvaluationsLogic.getEvaluationById(evalId); externalLogic.registerEntityEvent(EVENT_EMAIL_REMINDER, eval); String includeConstant = EvalConstants.EMAIL_INCLUDE_ALL; String[] sentMessages = emails.sendEvalReminderNotifications(evalId, includeConstant); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.sendReminderEmail(" + evalId + ")" + " sentMessages: " + sentMessages.toString()); } /** * Send email that the results of an evaluation may be viewed now.</br> * Notification may be sent to owner only, instructors and students together or * separately. * * @param evalId the EvalEvaluation id * @param the job type fom EvalConstants */ public void sendViewableEmail(Long evalId, String jobType, Boolean resultsPrivate) { boolean includeEvaluatees = true; boolean includeAdmins = true; //if results are private, only send notification to owner if(resultsPrivate.booleanValue()) { includeEvaluatees = false; includeAdmins = false; String[] sentMessages = emails.sendEvalResultsNotifications(evalId, includeEvaluatees, includeAdmins); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.sendViewableEmail(" + evalId + "," + jobType + ", resultsPrivate " + resultsPrivate + ")" + " sentMessages: " + sentMessages.toString()); } else { if(EvalConstants.JOB_TYPE_VIEWABLE.equals(jobType)) { String[] sentMessages = emails.sendEvalResultsNotifications(evalId, includeEvaluatees, includeAdmins); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.sendViewableEmail(" + evalId + "," + jobType + ", resultsPrivate " + resultsPrivate + ")" + " sentMessages: " + sentMessages.toString()); } else if(EvalConstants.JOB_TYPE_VIEWABLE_INSTRUCTORS.equals(jobType)) { includeEvaluatees = false; String[] sentMessages = emails.sendEvalResultsNotifications(evalId, includeEvaluatees, includeAdmins); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.sendViewableEmail(" + evalId + "," + jobType + ", resultsPrivate " + resultsPrivate + ")" + " sentMessages: " + sentMessages.toString()); } else if(EvalConstants.JOB_TYPE_VIEWABLE_STUDENTS.equals(jobType)) { includeAdmins = false; String[] sentMessages = emails.sendEvalResultsNotifications(evalId, includeEvaluatees, includeAdmins); if(log.isDebugEnabled()) log.debug("EvalJobLogicImpl.sendViewableEmail(" + evalId + "," + jobType + ", resultsPrivate " + resultsPrivate + ")" + " sentMessages: " + sentMessages.toString()); } else { if(log.isWarnEnabled()) log.warn(this + ".sendViewableEmail: for evalId " + evalId + " unrecognized job type " + jobType); } } } }
fix for EVALSYS-144 created email not sent 10 minutes after evaluation created git-svn-id: 6eed24e287f84bf0ab23ca377a3e397011128a6f@9753 fdecad78-55fc-0310-b1b2-d7d25cf747c9
impl/logic/src/java/org/sakaiproject/evaluation/logic/impl/scheduling/EvalJobLogicImpl.java
fix for EVALSYS-144 created email not sent 10 minutes after evaluation created
<ide><path>mpl/logic/src/java/org/sakaiproject/evaluation/logic/impl/scheduling/EvalJobLogicImpl.java <ide> * so we schedule email for ten minutes from now, also giving instructor ten minutes <ide> * to delete the evaluation and its notification <ide> */ <del> long runAt = new Date().getTime() + (1000 * 60 * 60 * 10); <add> long runAt = new Date().getTime() + (1000 * 60 * 10); <ide> scheduleJob(eval.getId(), new Date(runAt), EvalConstants.JOB_TYPE_CREATED); <ide> } <ide> scheduleJob(eval.getId(), eval.getStartDate(), EvalConstants.JOB_TYPE_ACTIVE);
JavaScript
mit
63c286a5e20693e701f4640a0f7d76632e0cd2a0
0
stevebrush/giftdibs-api
require('./shared/environment').applyEnvironment(); const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const db = require('./database'); db.connect(); const app = express(); app.set('port', process.env.PORT); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(cors({ allowedHeaders: ['Content-Type', 'Authorization'], credentials: true, methods: 'GET,POST,PATCH,DELETE,OPTIONS', optionsSuccessStatus: 200, origin: process.env.ALLOW_ORIGIN, preflightContinue: true })); app.options('*', cors()); const passport = require('passport'); passport.use(require('./strategies/jwt')); passport.use(require('./strategies/local')); app.use(passport.initialize()); app.use('/v1', require('./routes')); app.use(require('./middleware/404')); app.use(require('./middleware/format-schema-validation-error')); app.use(require('./middleware/format-schema-cast-error')); app.use(require('./middleware/error-handler')); module.exports = app;
src/app.js
require('./shared/environment').applyEnvironment(); const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const db = require('./database'); db.connect(); const app = express(); app.set('port', process.env.PORT); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(cors({ allowedHeaders: ['Content-Type', 'Authorization'], credentials: true, methods: 'GET,POST,PATCH,DELETE,OPTIONS', optionsSuccessStatus: 200, origin: process.env.ALLOW_ORIGIN })); app.options('*', cors()); const passport = require('passport'); passport.use(require('./strategies/jwt')); passport.use(require('./strategies/local')); app.use(passport.initialize()); app.use('/v1', require('./routes')); app.use(require('./middleware/404')); app.use(require('./middleware/format-schema-validation-error')); app.use(require('./middleware/format-schema-cast-error')); app.use(require('./middleware/error-handler')); module.exports = app;
Added preflight continue
src/app.js
Added preflight continue
<ide><path>rc/app.js <ide> credentials: true, <ide> methods: 'GET,POST,PATCH,DELETE,OPTIONS', <ide> optionsSuccessStatus: 200, <del> origin: process.env.ALLOW_ORIGIN <add> origin: process.env.ALLOW_ORIGIN, <add> preflightContinue: true <ide> })); <ide> app.options('*', cors()); <ide>