answer
stringlengths
17
10.2M
package java8.optional; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; public class OpTest { private static User testOptionalList() { List<String> names = Stream.of("1", "2", "3", "4").collect(Collectors.toList()); User user = new User(); Optional.ofNullable(user.getNames()).orElse(names).addAll(names); System.out.println(" user.setNames(Stream.of("A").collect(Collectors.toList())); Optional.ofNullable(user.getNames()).ifPresent(o -> o.addAll(names)); System.out.println(" return user; } public static void main(String[] args) { //test1(); System.out.println(testOptionalList()); ; } private static void test1() { //List<Integer> list = List.of(1, 2, 3, 4, 5); List<Integer> list = null; //System.out.println(Optional.ofNullable(list).orElse(List.of(0))); //System.out.println(Optional.ofNullable(list).orElseGet(() -> List.of(0))); //System.out.println(Optional.ofNullable(list).orElseThrow(RuntimeException::new)); //System.out.println(Optional.ofNullable(list).ifPresent(o->o.parallelStream().findAny().ifPresent(u->u.toString()))); //System.out.println(Optional.of(list).orElse(List.of(0))); //System.out.println(Optional.of(list).orElseGet(() -> List.of(0))); //System.out.println(Optional.of(list).orElseThrow(RuntimeException::new)); } static class User { private List<String> names; public List<String> getNames() { return names; } public void setNames(List<String> names) { this.names = names; } @Override public String toString() { return "User{" + "names=" + names + '}'; } } }
package com.jme3.asset; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import com.jme3.texture.Image; import com.jme3.texture.Image.Format; import java.io.IOException; import java.io.InputStream; /** * <code>AndroidImageInfo</code> is set in a jME3 image via the {@link Image#setEfficientData(java.lang.Object)} * method to retrieve a {@link Bitmap} when it is needed by the renderer. * User code may extend <code>AndroidImageInfo</code> and provide their own implementation of the * {@link AndroidImageInfo#loadBitmap()} method to acquire a bitmap by their own means. * * @author Kirill Vainer */ public class AndroidImageInfo { protected AssetInfo assetInfo; protected Bitmap bitmap; protected Format format; public AndroidImageInfo(AssetInfo assetInfo) { this.assetInfo = assetInfo; } public Bitmap getBitmap(){ if (bitmap == null || bitmap.isRecycled()){ try { loadBitmap(); } catch (IOException ex) { // If called first inside AssetManager, the error will propagate // correctly. Assuming that if the first calls succeeds // then subsequent calls will as well. throw new AssetLoadException("Failed to load image " + assetInfo.getKey(), ex); } } return bitmap; } public Format getFormat(){ return format; } /** * Loads the bitmap directly from the asset info, possibly updating * or creating the image object. */ protected void loadBitmap() throws IOException{ InputStream in = null; try { in = assetInfo.openStream(); bitmap = BitmapFactory.decodeStream(in); if (bitmap == null) { throw new IOException("Failed to load image: " + assetInfo.getKey().getName()); } } finally { if (in != null) { in.close(); } } switch (bitmap.getConfig()) { case ALPHA_8: format = Image.Format.Alpha8; break; case ARGB_4444: format = Image.Format.ARGB4444; break; case ARGB_8888: format = Image.Format.RGBA8; break; case RGB_565: format = Image.Format.RGB565; break; default: // This should still work as long // as renderer doesn't check format // but just loads bitmap directly. format = null; } TextureKey texKey = (TextureKey) assetInfo.getKey(); if (texKey.isFlipY()) { // Flip the image, then delete the old one. Matrix flipMat = new Matrix(); flipMat.preScale(1.0f, -1.0f); Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), flipMat, false); bitmap.recycle(); bitmap = newBitmap; if (bitmap == null) { throw new IOException("Failed to flip image: " + texKey); } } } }
// of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. import java.io.DataInput; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.filecache.DistributedCache; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapred.FileAlreadyExistsException; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import hadooptrunk.InputSampler; import hadooptrunk.MultipleOutputs; import hadooptrunk.TotalOrderPartitioner; import fi.tkk.ics.hadoop.bam.BAMInputFormat; import fi.tkk.ics.hadoop.bam.BAMRecordReader; import fi.tkk.ics.hadoop.bam.custom.samtools.BlockCompressedOutputStream; import fi.tkk.ics.hadoop.bam.custom.samtools.SAMRecord; public final class Summarize extends Configured implements Tool { public static void main(String[] args) throws Exception { System.exit(ToolRunner.run(new Configuration(), new Summarize(), args)); } private final List<Job> jobs = new ArrayList<Job>(); @Override public int run(String[] args) throws ClassNotFoundException, IOException, InterruptedException { if (args.length < 3) { System.err.println( "Usage: Summarize <output directory> <levels> "+ "file [file...]\n\n"+ "Levels should be a comma-separated list of positive integers. "+ "For each level,\noutputs a summary file describing the average "+ "number of alignments at various\npositions in the file. The "+ "level is the number of alignments that are\nsummarized into "+ "one."); return 2; } FileSystem fs = FileSystem.get(getConf()); Path outputDir = new Path(args[0]); if (fs.exists(outputDir) && !fs.getFileStatus(outputDir).isDir()) { System.err.printf( "ERROR: specified output directory '%s' is not a directory!\n", outputDir); return 2; } String[] levels = args[1].split(","); for (String l : levels) { try { int lvl = Integer.parseInt(l); if (lvl > 0) continue; System.err.printf( "ERROR: specified summary level '%d' is not positive!\n", lvl); } catch (NumberFormatException e) { System.err.printf( "ERROR: specified summary level '%s' is not an integer!\n", l); } return 2; } List<Path> files = new ArrayList<Path>(args.length - 2); for (String file : Arrays.asList(args).subList(2, args.length)) files.add(new Path(file)); if (new HashSet<Path>(files).size() < files.size()) { System.err.println("ERROR: duplicate file names specified!"); return 2; } for (Path file : files) if (!fs.isFile(file)) { System.err.printf("ERROR: file '%s' is not a file!\n", file); return 2; } for (Path file : files) submitJob(file, outputDir, levels); int ret = 0; for (Job job : jobs) if (!job.waitForCompletion(true)) ret = 1; return ret; } private void submitJob( Path inputFile, Path outputDir, String[] summaryLvls) throws ClassNotFoundException, IOException, InterruptedException { Configuration conf = new Configuration(getConf()); // Used by SummarizeOutputFormat to construct the output filename conf.set(SummarizeOutputFormat.INPUT_FILENAME_PROP, inputFile.getName()); conf.setStrings(SummarizeReducer.SUMMARY_LEVELS_PROP, summaryLvls); setSamplingConf(inputFile, conf); // As far as I can tell there's no non-deprecated way of getting this // info. int maxReduceTasks = new JobClient(new JobConf(conf)).getClusterStatus() .getMaxReduceTasks(); conf.setInt("mapred.reduce.tasks", Math.max(1, maxReduceTasks * 9 / 10)); Job job = new Job(conf); job.setJarByClass (Summarize.class); job.setMapperClass (Mapper.class); job.setReducerClass(SummarizeReducer.class); job.setMapOutputKeyClass (LongWritable.class); job.setMapOutputValueClass(Range.class); job.setOutputKeyClass (NullWritable.class); job.setOutputValueClass (RangeCount.class); job.setInputFormatClass (SummarizeInputFormat.class); job.setOutputFormatClass(SummarizeOutputFormat.class); FileInputFormat .setInputPaths(job, inputFile); FileOutputFormat.setOutputPath(job, outputDir); job.setPartitionerClass(TotalOrderPartitioner.class); sample(inputFile, job); for (String s : summaryLvls) MultipleOutputs.addNamedOutput( job, "summary" + s, SummarizeOutputFormat.class, NullWritable.class, Range.class); job.submit(); jobs.add(job); } private void setSamplingConf(Path inputFile, Configuration conf) throws IOException { Path inputDir = inputFile.getParent(); inputDir = inputDir.makeQualified(inputDir.getFileSystem(conf)); String name = inputFile.getName(); Path partition = new Path(inputDir, "_partitioning" + name); TotalOrderPartitioner.setPartitionFile(conf, partition); try { URI partitionURI = new URI( partition.toString() + "#_partitioning" + name); DistributedCache.addCacheFile(partitionURI, conf); DistributedCache.createSymlink(conf); } catch (URISyntaxException e) { assert false; } } private void sample(Path inputFile, Job job) throws ClassNotFoundException, IOException, InterruptedException { InputSampler.Sampler<LongWritable,Range> sampler = new InputSampler.SplitSampler<LongWritable,Range>(1 << 16, 10); InputSampler.<LongWritable,Range>writePartitionFile(job, sampler); } } final class SummarizeReducer extends Reducer<LongWritable,Range, NullWritable,RangeCount> { public static final String SUMMARY_LEVELS_PROP = "summarize.summary.levels"; private MultipleOutputs<NullWritable,RangeCount> mos; private final List<SummaryGroup> summaryGroups = new ArrayList<SummaryGroup>(); private final RangeCount summary = new RangeCount(); // This is a safe initial choice: it doesn't matter whether the first actual // reference ID we get matches this or not, since all summaryLists are empty // anyway. private int currentReferenceID = 0; @Override public void setup( Reducer<LongWritable,Range, NullWritable,RangeCount>.Context ctx) { mos = new MultipleOutputs<NullWritable,RangeCount>(ctx); for (String s : ctx.getConfiguration().getStrings(SUMMARY_LEVELS_PROP)) { int level = Integer.parseInt(s); summaryGroups.add(new SummaryGroup(level, "summary" + level)); } } @Override protected void reduce( LongWritable key, Iterable<Range> ranges, Reducer<LongWritable,Range, NullWritable,RangeCount>.Context context) throws IOException, InterruptedException { final int referenceID = (int)(key.get() >>> 32); // When the reference sequence changes we have to flush out everything // we've got and start from scratch again. if (referenceID != currentReferenceID) { currentReferenceID = referenceID; doAllSummaries(); } for (final Range range : ranges) { final int beg = range.beg.get(), end = range.end.get(); for (SummaryGroup group : summaryGroups) { group.sumBeg += beg; group.sumEnd += end; if (++group.count == group.level) doSummary(group); } } } @Override protected void cleanup( Reducer<LongWritable,Range, NullWritable,RangeCount>.Context context) throws IOException, InterruptedException { // Don't lose any remaining ones at the end. doAllSummaries(); mos.close(); } private void doAllSummaries() throws IOException, InterruptedException { for (SummaryGroup group : summaryGroups) if (group.count > 0) doSummary(group); } private void doSummary(SummaryGroup group) throws IOException, InterruptedException { summary.rid. set(currentReferenceID); summary.range.beg.set((int)(group.sumBeg / group.count)); summary.range.end.set((int)(group.sumEnd / group.count)); summary.count. set(group.count); mos.write(NullWritable.get(), summary, group.outName); group.reset(); } } final class Range implements Writable { public final IntWritable beg = new IntWritable(); public final IntWritable end = new IntWritable(); public void setFrom(SAMRecord record) { beg.set(record.getAlignmentStart()); end.set(record.getAlignmentEnd()); } public int getCentreOfMass() { return (int)(((long)beg.get() + end.get()) / 2); } @Override public void write(DataOutput out) throws IOException { beg.write(out); end.write(out); } @Override public void readFields(DataInput in) throws IOException { beg.readFields(in); end.readFields(in); } } final class RangeCount implements Comparable<RangeCount>, Writable { public final Range range = new Range(); public final IntWritable count = new IntWritable(); public final IntWritable rid = new IntWritable(); // This is what the TextOutputFormat will write. The format is // It might not be sorted by range.beg though! With the centre of mass // approach, it most likely won't be. @Override public String toString() { return rid + "\t" + range.beg + "\t" + range.end + "\t" + count; } // Comparisons only take into account the leftmost position. @Override public int compareTo(RangeCount o) { return Integer.valueOf(range.beg.get()).compareTo(o.range.beg.get()); } @Override public void write(DataOutput out) throws IOException { range.write(out); count.write(out); rid .write(out); } @Override public void readFields(DataInput in) throws IOException { range.readFields(in); count.readFields(in); rid .readFields(in); } } // We want the centre of mass to be used as (the low order bits of) the key // already at this point, because we want a total order so that we can // meaningfully look at consecutive ranges in the reducers. If we were to set // the final key in the mapper, the partitioner wouldn't use it. // And since getting the centre of mass requires calculating the Range as well, // we might as well get that here as well. final class SummarizeInputFormat extends FileInputFormat<LongWritable,Range> { private final BAMInputFormat bamIF = new BAMInputFormat(); @Override protected boolean isSplitable(JobContext job, Path path) { return bamIF.isSplitable(job, path); } @Override public List<InputSplit> getSplits(JobContext job) throws IOException { return bamIF.getSplits(job); } @Override public RecordReader<LongWritable,Range> createRecordReader(InputSplit split, TaskAttemptContext ctx) throws InterruptedException, IOException { final RecordReader<LongWritable,Range> rr = new SummarizeRecordReader(); rr.initialize(split, ctx); return rr; } } final class SummarizeRecordReader extends RecordReader<LongWritable,Range> { private final BAMRecordReader bamRR = new BAMRecordReader(); private final LongWritable key = new LongWritable(); private final Range range = new Range(); @Override public void initialize(InputSplit spl, TaskAttemptContext ctx) throws IOException { bamRR.initialize(spl, ctx); } @Override public void close() throws IOException { bamRR.close(); } @Override public float getProgress() { return bamRR.getProgress(); } @Override public LongWritable getCurrentKey () { return key; } @Override public Range getCurrentValue() { return range; } @Override public boolean nextKeyValue() { SAMRecord rec; do { if (!bamRR.nextKeyValue()) return false; rec = bamRR.getCurrentValue().get(); } while (rec.getReadUnmappedFlag()); range.setFrom(rec); key.set((long)rec.getReferenceIndex() << 32 | range.getCentreOfMass()); return true; } } final class SummarizeOutputFormat extends TextOutputFormat<NullWritable,RangeCount> { public static final String INPUT_FILENAME_PROP = "summarize.input.filename"; @Override public RecordWriter<NullWritable,RangeCount> getRecordWriter( TaskAttemptContext ctx) throws IOException { Path path = getDefaultWorkFile(ctx, ""); FileSystem fs = path.getFileSystem(ctx.getConfiguration()); return new TextOutputFormat.LineRecordWriter<NullWritable,RangeCount>( new DataOutputStream( new BlockCompressedOutputStream(fs.create(path)))); } @Override public Path getDefaultWorkFile( TaskAttemptContext context, String ext) throws IOException { Configuration conf = context.getConfiguration(); // From MultipleOutputs. If we had a later version of FileOutputFormat as // well, we'd use getOutputName(). String summaryName = conf.get("mapreduce.output.basename"); // A RecordWriter is created as soon as a reduce task is started, even // though MultipleOutputs eventually overrides it with its own. // To avoid creating a file called "inputfilename-null" when that // RecordWriter is initialized, make it a hidden file instead, like this. // We can't use a filename we'd use later, because TextOutputFormat would // throw later on, as the file would already exist. String inputName = summaryName == null ? ".unused_" : ""; inputName += conf.get(INPUT_FILENAME_PROP); String extension = ext.isEmpty() ? ext : "." + ext; int part = context.getTaskAttemptID().getTaskID().getId(); return new Path(super.getDefaultWorkFile(context, ext).getParent(), inputName + "-" + summaryName + "-" + String.format("%06d", part) + extension); } // Allow the output directory to exist, so that we can make multiple jobs // that write into it. @Override public void checkOutputSpecs(JobContext job) throws FileAlreadyExistsException, IOException {} } final class SummaryGroup { public int count; public final int level; public long sumBeg, sumEnd; public final String outName; public SummaryGroup(int lvl, String name) { level = lvl; outName = name; reset(); } public void reset() { sumBeg = sumEnd = 0; count = 0; } }
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TVMscreen implements ActionListener { JButton singleCashFlow = new JButton(); JButton annuity = new JButton(); JButton rates = new JButton(); JLabel TVMcalculator = new JLabel(); JPanel mainScreen = new JPanel(); JPanel top = new JPanel(); JPanel center = new JPanel(); JFrame window = new JFrame(); GridLayout layout0 = new GridLayout(1,3); BorderLayout layout1 = new BorderLayout(); //Addition of images for the graphics ImageIcon TVMlabel = new ImageIcon("Resources/tVm.png"); ImageIcon sCf = new ImageIcon("Resources/sCf.png"); //sCf is short for single cash flow ImageIcon Ac = new ImageIcon("Resources/Ac.png"); //Ac is short for annuity calculations ImageIcon ratesIcon = new ImageIcon("Resources/rates.png"); scfCalculations scf = new scfCalculations(); annuityCalculations aC = new annuityCalculations(); rateCalculations aprAndEar = new rateCalculations(); public TVMscreen() { TVMcalculator.setIcon(TVMlabel); singleCashFlow.setIcon(sCf); annuity.setIcon(Ac); rates.setIcon(ratesIcon); singleCashFlow.setContentAreaFilled(false); annuity.setContentAreaFilled(false); rates.setContentAreaFilled(false); //mainScreen.setBackground(Color.WHITE); center.setBackground(Color.WHITE); //singleCashFlow.setOpaque(false); mainScreen.setLayout(layout1); center.setLayout(layout0); mainScreen.add("North", top); mainScreen.add("Center", center); top.add(TVMcalculator); center.add(singleCashFlow); center.add(annuity); center.add(rates); window.setTitle("TVM Calculator"); window.setSize(1100,450); window.setContentPane(mainScreen); //window.setVisible(true); //window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setResizable(false); singleCashFlow.addActionListener(this); annuity.addActionListener(this); rates.addActionListener(this); } public static void main(String[] args) { TVMscreen graphic = new TVMscreen(); } public void show() { window.setVisible(true); } public void actionPerformed(ActionEvent event) { if (event.getSource() == singleCashFlow) { scf.show(); } else if (event.getSource() == annuity) { aC.show(); } else if (event.getSource() == rates) { aprAndEar.show(); } } }
package qa.qcri.aidr.predictui.util; /** * * @author Imran */ public class Config { //TODO: Replace with config file in text format public static final String STATUS_CODE_SUCCESS = "SUCCESS"; public static final String STATUS_CODE_FAILED = "FAILED"; //TODO : THIS PATH HAS TO BE UPDATED BASED ON aidr-tagger location //public static final String AIDR_TAGGER_CONFIG_URL = "/home/local/QCRI/mimran/aidr/tagger/config/config.txt"; public static final String AIDR_TAGGER_CONFIG_URL = "/home/mimran/aidr/aidr-tagger/config/config.txt"; // for aidr-prod server //public static final String AIDR_TAGGER_CONFIG_URL = "/home/koushik/aidr-tagger/config/config.txt"; // on local server //public static final String LOG_FILE_NAME = "aidr-tagger-logs.txt";// //For deleting stale tasks from Document entity/table public static final String TASK_EXPIRY_AGE_LIMIT = "6h"; public static final String TASK_BUFFER_SCAN_INTERVAL = "1h"; public static final int PUBLIC_LANDING_PAGE_TOP = 1; public static final int PUBLIC_LANDING_PAGE_BOTTOM = 2; public static final int CLASSIFIER_DESCRIPTION_PAGE = 3; public static final int CLASSIFIER_TUTORIAL_ONE = 4; public static final int CLASSIFIER_TUTORIAL_TWO = 5; public static final int CUSTOM_CURATOR = 6; public static final int CLASSIFIER_SKIN = 7; }
package aimax.osm.routing.mapagent; import aima.gui.applications.search.SearchFactory; import aima.gui.applications.search.map.MapAgentFrame; /** * Simple frame for running map agents in maps defined by OSM data. * @author Ruediger Lunde */ public class OsmAgentFrame extends MapAgentFrame { private static final long serialVersionUID = 1L; /** Creates a new frame. */ public OsmAgentFrame(OsmMapAdapter map) { setTitle("OMAS - the Osm Map Agent Simulator"); setSelectors(new String[]{ SCENARIO_SEL, AGENT_SEL, SEARCH_SEL, SEARCH_MODE_SEL, HEURISTIC_SEL}, new String[]{ "Select Scenario", "Select Agent", "Select Search Strategy", "Select Search Mode", "Select Heuristic"} ); setSelectorItems(SCENARIO_SEL, new String[] {"Use any way", "Travel by car", "Travel by bicycle"}, 0); setSelectorItems(AGENT_SEL, new String[] {"Offline Search", "Online Search (LRTA*)"}, 0); setSelectorItems(SEARCH_SEL, SearchFactory.getInstance().getSearchStrategyNames(), 5); setSelectorItems(SEARCH_MODE_SEL, SearchFactory.getInstance() .getSearchModeNames(), 1); // change the default! setSelectorItems(HEURISTIC_SEL, new String[] { "=0", "SLD" }, 1); } }
package beginner; import com.sandwich.koan.Koan; import static com.sandwich.koan.constant.KoanConstants.__; import static com.sandwich.util.Assert.assertEquals; public class AboutEquality { @Koan public void doubleEqualsTestsIfTwoObjectsAreTheSame() { Object object = new Object(); Object sameObject = object; assertEquals(object == sameObject, true); assertEquals(object == new Object(), false); } @Koan public void equalsMethodByDefaultTestsIfTwoObjectsAreTheSame() { Object object = new Object(); assertEquals(object.equals(object), true); assertEquals(object.equals(new Object()), false); } @Koan public void equalsMethodCanBeChangedBySubclassesToTestsIfTwoObjectsAreEqual() { Object object = new Integer(1); assertEquals(object.equals(object), true); assertEquals(object.equals(new Integer(1)), true); // Note: This means that for the class 'Object' there is no difference between 'equal' and 'same' // but for the class 'Integer' there is difference - see below } @Koan public void equalsMethodCanBeChangedBySubclassesToTestsIfTwoObjectsAreEqualExample() { Integer value1 = new Integer(4); Integer value2 = new Integer(2 + 2); assertEquals(value1.equals(value2), true); assertEquals(value1, value2); } @Koan public void objectsNeverEqualNull() { assertEquals(new Object().equals(null), false); } @Koan public void objectsEqualThemselves() { Object obj = new Object(); assertEquals(obj.equals(obj), true); } }
package software.sitb.react.amap; import android.os.AsyncTask; import android.util.Log; import android.util.SparseArray; import com.amap.api.location.AMapLocation; import com.amap.api.location.AMapLocationClient; import com.amap.api.location.AMapLocationClientOption; import com.amap.api.location.AMapLocationListener; import com.facebook.react.bridge.*; import software.sitb.react.commons.DefaultReactContextBaseJavaModule; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Sean sean.snow@live.com createAt 2017/4/6 */ public class AmapLocation extends DefaultReactContextBaseJavaModule { private static final String TAG = "AMAP"; private static final String EVENT = "amapWatchPosition"; private SparseArray<AMapLocationClient> watchIds = new SparseArray<>(); public AmapLocation(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "AmapLocation"; } @ReactMethod public void setApiKey(String key) { Log.d(TAG, "API KEY"); AMapLocationClient.setApiKey(key); } @ReactMethod public void getCurrentPosition(ReadableMap options) { AMapLocationClientOption option = getDefaultOption(); option.setOnceLocation(true); //client AMapLocationClient locationClient = new AMapLocationClient(this.reactContext); locationClient.setLocationOption(option); new WatchLocationGuardedAsyncTask(getReactApplicationContext(), locationClient) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @ReactMethod public void watchPosition(ReadableMap options, Integer watchId) { AMapLocationClientOption option = getDefaultOption(); //client AMapLocationClient locationClient = new AMapLocationClient(this.reactContext); locationClient.setLocationOption(option); new WatchLocationGuardedAsyncTask(getReactApplicationContext(), locationClient) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); watchIds.put(watchId, locationClient); } @ReactMethod public void clearWatch(Integer watchId) { AMapLocationClient client = watchIds.get(watchId); if (null != client) { client.stopLocation(); } } /** * * * @author hongming.wang * @since 2.8.0 */ private AMapLocationClientOption getDefaultOption() { AMapLocationClientOption mOption = new AMapLocationClientOption(); mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy); mOption.setGpsFirst(true);//gps mOption.setHttpTimeOut(30000); mOption.setInterval(2000); mOption.setNeedAddress(true);//true mOption.setOnceLocation(false);//false mOption.setOnceLocationLatest(false);//wififalse.true, AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);// HTTPHTTPSHTTP mOption.setSensorEnable(false);//false mOption.setWifiScan(true); //wifitruefalse mOption.setLocationCacheEnable(true); //true return mOption; } private class WatchLocationGuardedAsyncTask extends GuardedAsyncTask<Void, Void> { private AMapLocationClient locationClient; protected WatchLocationGuardedAsyncTask(ReactContext reactContext, AMapLocationClient locationClient) { super(reactContext); this.locationClient = locationClient; } @Override protected void doInBackgroundGuarded(Void... voids) { locationClient.setLocationListener(new AMapLocationListener() { @Override public void onLocationChanged(AMapLocation location) { if (null == location) { Log.e(TAG, ""); } else if (location.getErrorCode() == 0) { Log.d(TAG, "->" + location.toString()); WritableMap result = Arguments.createMap(); WritableMap coords = Arguments.createMap(); coords.putDouble("latitude", location.getLatitude()); coords.putDouble("longitude", location.getLongitude()); coords.putDouble("accuracy", location.getAccuracy()); result.putMap("coords", coords); result.putDouble("timestamp", location.getTime()); result.putBoolean("success", true); sendEvent(EVENT, result); } else { Log.e(TAG, "location Error, ErrCode:" + location.getErrorCode() + ", errInfo:" + location.getErrorInfo()); WritableMap result = Arguments.createMap(); result.putInt("code", location.getErrorCode()); result.putString("message", location.getErrorInfo()); result.putBoolean("success", false); sendEvent(EVENT, result); } } }); locationClient.startLocation(); } } }
package com.yahoo.squidb.data; import com.yahoo.squidb.sql.Field; import com.yahoo.squidb.sql.Property.StringProperty; import com.yahoo.squidb.sql.Query; import com.yahoo.squidb.sql.TableModelName; import com.yahoo.squidb.sql.TableStatement; import com.yahoo.squidb.test.DatabaseTestCase; import com.yahoo.squidb.test.Employee; import com.yahoo.squidb.test.SQLiteBindingProvider; import com.yahoo.squidb.test.TestDatabase; import com.yahoo.squidb.test.TestModel; import com.yahoo.squidb.test.TestViewModel; import com.yahoo.squidb.test.Thing; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public class SquidDatabaseTest extends DatabaseTestCase { private TestHookDatabase testHookDatabase; @Override protected void setupDatabase() { super.setupDatabase(); testHookDatabase = new TestHookDatabase(); testHookDatabase.getDatabase(); // init } @Override protected void tearDownDatabase() { super.tearDownDatabase(); testHookDatabase.clear(); } public void testRawQuery() { testHookDatabase.persist(new TestModel().setFirstName("Sam").setLastName("Bosley").setBirthday(testDate)); ICursor cursor = null; try { // Sanity check that there is only one row in the table assertEquals(1, testHookDatabase.countAll(TestModel.class)); // Test that raw query binds arguments correctly--if the argument // is bound as a String, the result will be empty cursor = testHookDatabase.rawQuery("select * from testModels where abs(_id) = ?", new Object[]{1}); assertEquals(1, cursor.getCount()); } finally { if (cursor != null) { cursor.close(); } } } public void testTryAddColumn() { StringProperty goodProperty = new StringProperty( new TableModelName(TestModel.class, TestModel.TABLE.getName()), "good_column"); testHookDatabase.tryAddColumn(goodProperty); // don't care about the result, just that it didn't throw final StringProperty badProperty = new StringProperty( new TableModelName(TestViewModel.class, TestViewModel.VIEW.getName()), "bad_column"); testThrowsException(new Runnable() { @Override public void run() { testHookDatabase.tryAddColumn(badProperty); } }, IllegalArgumentException.class); } public void testMigrationFailureCalledWhenOnUpgradeReturnsFalse() { testMigrationFailureCalled(true, false, false, false); } public void testMigrationFailureCalledWhenOnUpgradeThrowsException() { testMigrationFailureCalled(true, true, false, false); } public void testMigrationFailureCalledWhenOnDowngradeReturnsFalse() { testMigrationFailureCalled(false, false, false, false); } public void testMigrationFailureCalledWhenOnDowngradeThrowsException() { testMigrationFailureCalled(false, true, false, false); } private void testMigrationFailureCalled(boolean upgrade, boolean shouldThrow, boolean shouldRecreateDuringMigration, boolean shouldRecreateOnMigrationFailed) { testHookDatabase.shouldThrowDuringMigration = shouldThrow; testHookDatabase.shouldRecreateInMigration = shouldRecreateDuringMigration; testHookDatabase.shouldRecreateInOnMigrationFailed = shouldRecreateOnMigrationFailed; // set version manually ISQLiteDatabase db = testHookDatabase.getDatabase(); final int version = db.getVersion(); final int previousVersion = upgrade ? version - 1 : version + 1; db.setVersion(previousVersion); // close and reopen to trigger an upgrade/downgrade testHookDatabase.onTablesCreatedCalled = false; testHookDatabase.close(); RuntimeException caughtException = null; try { testHookDatabase.getDatabase(); } catch (RuntimeException e) { caughtException = e; } // If throwing or returning false from migration but not handling it, we expect getDatabase to also throw // since the DB will not be open after exiting the onMigrationFailed hook if (!shouldRecreateDuringMigration) { assertNotNull(caughtException); } else { assertNull(caughtException); } assertTrue(upgrade ? testHookDatabase.onUpgradeCalled : testHookDatabase.onDowngradeCalled); if (shouldRecreateDuringMigration || shouldRecreateOnMigrationFailed) { assertTrue(testHookDatabase.onTablesCreatedCalled); } else { assertTrue(testHookDatabase.onMigrationFailedCalled); assertEquals(previousVersion, testHookDatabase.migrationFailedOldVersion); assertEquals(version, testHookDatabase.migrationFailedNewVersion); } } /** * {@link SquidDatabase} does not automatically recreate the database when a migration fails. This is really to * test that {@link SquidDatabase#recreate()} can safely be called during onUpgrade or * onDowngrade as an exemplar for client developers. */ public void testRecreateOnUpgradeFailure() { testRecreateDuringMigrationOrFailureCallback(true, false); } public void testRecreateOnDowngradeFailure() { testRecreateDuringMigrationOrFailureCallback(false, false); } public void testRecreateDuringOnMigrationFailed() { testRecreateDuringMigrationOrFailureCallback(true, true); } private void testRecreateDuringMigrationOrFailureCallback(boolean upgrade, boolean recreateDuringMigration) { // insert some data to check for later testHookDatabase.persist(new Employee().setName("Alice")); testHookDatabase.persist(new Employee().setName("Bob")); testHookDatabase.persist(new Employee().setName("Cindy")); assertEquals(3, testHookDatabase.countAll(Employee.class)); testMigrationFailureCalled(upgrade, recreateDuringMigration, true, recreateDuringMigration); // verify the db was recreated with the appropriate version and no previous data ISQLiteDatabase db = testHookDatabase.getDatabase(); assertEquals(testHookDatabase.getVersion(), db.getVersion()); assertEquals(0, testHookDatabase.countAll(Employee.class)); } public void testExceptionDuringOpenCleansUp() { testHookDatabase.shouldThrowDuringMigration = true; testHookDatabase.shouldRecreateInMigration = true; testHookDatabase.shouldRecreateInOnMigrationFailed = false; testHookDatabase.shouldRethrowInOnMigrationFailed = true; testThrowsException(new Runnable() { @Override public void run() { // set version manually ISQLiteDatabase db = testHookDatabase.getDatabase(); final int version = db.getVersion(); final int previousVersion = version - 1; db.setVersion(previousVersion); // close and reopen to trigger an upgrade/downgrade testHookDatabase.onTablesCreatedCalled = false; testHookDatabase.close(); testHookDatabase.getDatabase(); } }, SquidDatabase.MigrationFailedException.class); assertFalse(testHookDatabase.inTransaction()); assertFalse(testHookDatabase.isOpen()); } public void testAcquireExclusiveLockFailsWhenInTransaction() { testThrowsException(new Runnable() { @Override public void run() { IllegalStateException caughtException = null; testHookDatabase.beginTransaction(); try { testHookDatabase.acquireExclusiveLock(); } catch (IllegalStateException e) { // Need to do this in the catch block rather than the finally block, because otherwise tearDown is // called before we have a chance to release the transaction lock testHookDatabase.endTransaction(); caughtException = e; } finally { if (caughtException == null) { // Sanity cleanup if catch block was never reached testHookDatabase.endTransaction(); } } if (caughtException != null) { throw caughtException; } } }, IllegalStateException.class); } public void testCustomMigrationException() { final TestDatabase database = new TestDatabase(); ISQLiteDatabase db = database.getDatabase(); // force a downgrade final int version = db.getVersion(); final int previousVersion = version + 1; db.setVersion(previousVersion); database.close(); // Expect an exception here because this DB does not cleanly re-open the DB in case of errors testThrowsException(new Runnable() { @Override public void run() { database.getDatabase(); } }, RuntimeException.class); try { assertTrue(database.caughtCustomMigrationException); } finally { database.clear(); // clean up since this is the only test using it } } public void testRetryOpenDatabase() { testHookDatabase.clear(); // init opens it, we need a new db final AtomicBoolean openFailedHandlerCalled = new AtomicBoolean(); testHookDatabase.shouldThrowDuringOpen = true; testHookDatabase.dbOpenFailedHandler = new DbOpenFailedHandler() { @Override public void dbOpenFailed(RuntimeException failure, int openFailureCount) { openFailedHandlerCalled.set(true); testHookDatabase.shouldThrowDuringOpen = false; testHookDatabase.getDatabase(); } }; testHookDatabase.getDatabase(); assertTrue(testHookDatabase.isOpen()); assertTrue(openFailedHandlerCalled.get()); assertEquals(1, testHookDatabase.dbOpenFailureCount); } public void testRecreateOnOpenFailed() { final AtomicBoolean openFailedHandlerCalled = new AtomicBoolean(); testHookDatabase.persist(new Employee().setName("Alice")); testHookDatabase.persist(new Employee().setName("Bob")); testHookDatabase.persist(new Employee().setName("Cindy")); assertEquals(3, testHookDatabase.countAll(Employee.class)); ISQLiteDatabase db = testHookDatabase.getDatabase(); db.setVersion(db.getVersion() + 1); testHookDatabase.close(); testHookDatabase.shouldThrowDuringMigration = true; testHookDatabase.shouldRethrowInOnMigrationFailed = true; testHookDatabase.dbOpenFailedHandler = new DbOpenFailedHandler() { @Override public void dbOpenFailed(RuntimeException failure, int openFailureCount) { openFailedHandlerCalled.set(true); testHookDatabase.shouldThrowDuringOpen = false; testHookDatabase.recreate(); } }; testHookDatabase.getDatabase(); assertTrue(testHookDatabase.isOpen()); assertTrue(openFailedHandlerCalled.get()); assertEquals(1, testHookDatabase.dbOpenFailureCount); assertEquals(0, testHookDatabase.countAll(Employee.class)); } public void testSuppressingDbOpenFailedThrowsRuntimeException() { testHookDatabase.clear(); final AtomicBoolean openFailedHandlerCalled = new AtomicBoolean(); testHookDatabase.shouldThrowDuringOpen = true; testHookDatabase.dbOpenFailedHandler = new DbOpenFailedHandler() { @Override public void dbOpenFailed(RuntimeException failure, int openFailureCount) { openFailedHandlerCalled.set(true); } }; testThrowsException(new Runnable() { @Override public void run() { testHookDatabase.getDatabase(); } }, RuntimeException.class); assertTrue(openFailedHandlerCalled.get()); assertFalse(testHookDatabase.isOpen()); } public void testRecursiveRetryDbOpen() { testRecursiveRetryDbOpen(1, true); testRecursiveRetryDbOpen(1, false); testRecursiveRetryDbOpen(2, true); testRecursiveRetryDbOpen(2, false); testRecursiveRetryDbOpen(3, true); testRecursiveRetryDbOpen(3, false); } private void testRecursiveRetryDbOpen(final int maxRetries, final boolean eventualRecovery) { testHookDatabase.clear(); testHookDatabase.shouldThrowDuringOpen = true; testHookDatabase.dbOpenFailedHandler = new DbOpenFailedHandler() { @Override public void dbOpenFailed(RuntimeException failure, int openFailureCount) { if (openFailureCount >= maxRetries) { testHookDatabase.shouldThrowDuringOpen = false; if (!eventualRecovery) { throw failure; } } testHookDatabase.getDatabase(); } }; if (eventualRecovery) { testHookDatabase.getDatabase(); } else { testThrowsException(new Runnable() { @Override public void run() { testHookDatabase.getDatabase(); } }, RuntimeException.class); } assertEquals(maxRetries, testHookDatabase.dbOpenFailureCount); assertEquals(eventualRecovery, testHookDatabase.isOpen()); } public void testDataChangeNotifiersDisabledDuringDbOpen() { testDataChangeNotifiersDisabledDuringDbOpen(true, true); testDataChangeNotifiersDisabledDuringDbOpen(true, false); testDataChangeNotifiersDisabledDuringDbOpen(false, true); testDataChangeNotifiersDisabledDuringDbOpen(false, false); } private void testDataChangeNotifiersDisabledDuringDbOpen(boolean startEnabled, final boolean openFailure) { final AtomicBoolean notifierCalled = new AtomicBoolean(); final AtomicBoolean failOnOpen = new AtomicBoolean(openFailure); SimpleDataChangedNotifier simpleNotifier = new SimpleDataChangedNotifier(Thing.TABLE) { @Override protected void onDataChanged() { notifierCalled.set(true); } }; TestDatabase testDb = new TestDatabase() { @Override public String getName() { return super.getName() + "2"; } @Override protected void onTablesCreated(ISQLiteDatabase db) { super.onTablesCreated(db); persist(new Thing().setFoo("foo").setBar(1)); if (failOnOpen.getAndSet(false)) { throw new RuntimeException("Failed to open db"); } } @Override protected void onDatabaseOpenFailed(RuntimeException failure, int openFailureCount) { getDatabase(); } }; testDb.setDataChangedNotificationsEnabled(startEnabled); testDb.registerDataChangedNotifier(simpleNotifier); testDb.getDatabase(); assertFalse(notifierCalled.get()); assertEquals(1, testDb.countAll(Thing.class)); assertEquals(startEnabled, testDb.areDataChangedNotificationsEnabled()); testDb.persist(new Thing().setFoo("foo2").setBar(2)); assertEquals(startEnabled, notifierCalled.get()); testDb.clear(); } public void testOnCloseHook() { final AtomicReference<ISQLitePreparedStatement> preparedStatementRef = new AtomicReference<>(); testHookDatabase.onCloseTester = new DbHookTester() { @Override void onHookImpl(ISQLiteDatabase db) { assertTrue(db.isOpen()); ISQLitePreparedStatement statement = preparedStatementRef.get(); assertNotNull(statement); statement.close(); preparedStatementRef.set(null); } }; preparedStatementRef.set(testHookDatabase.prepareStatement("SELECT COUNT(*) FROM testModels")); assertNotNull(preparedStatementRef.get()); assertEquals(0, preparedStatementRef.get().simpleQueryForLong()); testHookDatabase.close(); assertTrue(testHookDatabase.onCloseTester.wasCalled); assertNull(preparedStatementRef.get()); } /** * A {@link TestDatabase} that intentionally fails in onUpgrade and onDowngrade and provides means of testing * various other SquidDatabase hooks */ private static class TestHookDatabase extends TestDatabase { private boolean onMigrationFailedCalled = false; private boolean onUpgradeCalled = false; private boolean onDowngradeCalled = false; private boolean onTablesCreatedCalled = false; private int dbOpenFailureCount = 0; private int migrationFailedOldVersion = 0; private int migrationFailedNewVersion = 0; private boolean shouldThrowDuringOpen = false; private boolean shouldThrowDuringMigration = false; private boolean shouldRecreateInMigration = false; private boolean shouldRecreateInOnMigrationFailed = false; private boolean shouldRethrowInOnMigrationFailed = false; private DbOpenFailedHandler dbOpenFailedHandler = null; private DbHookTester onCloseTester = null; public TestHookDatabase() { super(); } @Override public String getName() { return "badDb"; } @Override protected int getVersion() { return super.getVersion() + 1; } @Override protected void onTablesCreated(ISQLiteDatabase db) { onTablesCreatedCalled = true; if (shouldThrowDuringOpen) { throw new RuntimeException("Simulating DB open failure"); } } @Override protected final boolean onUpgrade(ISQLiteDatabase db, int oldVersion, int newVersion) { onUpgradeCalled = true; if (shouldThrowDuringMigration) { throw new RuntimeException("My name is \"NO! NO! BAD DATABASE!\". What's yours?"); } else if (shouldRecreateInMigration) { recreate(); } return false; } @Override protected boolean onDowngrade(ISQLiteDatabase db, int oldVersion, int newVersion) { onDowngradeCalled = true; if (shouldThrowDuringMigration) { throw new RuntimeException("My name is \"NO! NO! BAD DATABASE!\". What's yours?"); } else if (shouldRecreateInMigration) { recreate(); } return false; } @Override protected void onMigrationFailed(MigrationFailedException failure) { onMigrationFailedCalled = true; migrationFailedOldVersion = failure.oldVersion; migrationFailedNewVersion = failure.newVersion; if (shouldRecreateInOnMigrationFailed) { recreate(); } else if (shouldRethrowInOnMigrationFailed) { throw failure; } } @Override protected void onDatabaseOpenFailed(RuntimeException failure, int openFailureCount) { dbOpenFailureCount = openFailureCount; if (dbOpenFailedHandler != null) { dbOpenFailedHandler.dbOpenFailed(failure, openFailureCount); } else { super.onDatabaseOpenFailed(failure, openFailureCount); } } @Override protected void onClose(ISQLiteDatabase db) { if (onCloseTester != null) { onCloseTester.onHook(db); } } } private interface DbOpenFailedHandler { void dbOpenFailed(RuntimeException failure, int openFailureCount); } // This class can be used to add customized behavior to the optional SquidDatabase overrideable hook methods // in the TestHookDatabase class. private static abstract class DbHookTester { boolean wasCalled = false; final void onHook(ISQLiteDatabase db) { wasCalled = true; onHookImpl(db); } abstract void onHookImpl(ISQLiteDatabase db); } public void testBasicInsertAndFetch() { TestModel model = insertBasicTestModel(); TestModel fetch = database.fetch(TestModel.class, model.getRowId(), TestModel.PROPERTIES); assertEquals("Sam", fetch.getFirstName()); assertEquals("Bosley", fetch.getLastName()); assertEquals(testDate, fetch.getBirthday().longValue()); } public void testPropertiesAreNullable() { TestModel model = insertBasicTestModel(); model.setFirstName(null); model.setLastName(null); assertNull(model.getFirstName()); assertNull(model.getLastName()); database.persist(model); TestModel fetch = database.fetch(TestModel.class, model.getRowId(), TestModel.PROPERTIES); assertNull(fetch.getFirstName()); assertNull(fetch.getLastName()); } public void testBooleanProperties() { TestModel model = insertBasicTestModel(); assertTrue(model.isHappy()); model.setIsHappy(false); assertFalse(model.isHappy()); database.persist(model); TestModel fetch = database.fetch(TestModel.class, model.getRowId(), TestModel.PROPERTIES); assertFalse(fetch.isHappy()); } public void testQueriesWithBooleanPropertiesWork() { insertBasicTestModel(); TestModel model; SquidCursor<TestModel> result = database.query(TestModel.class, Query.select(TestModel.PROPERTIES).where(TestModel.IS_HAPPY.isTrue())); try { assertEquals(1, result.getCount()); result.moveToFirst(); model = new TestModel(result); assertTrue(model.isHappy()); model.setIsHappy(false); database.persist(model); } finally { result.close(); } result = database.query(TestModel.class, Query.select(TestModel.PROPERTIES).where(TestModel.IS_HAPPY.isFalse())); try { assertEquals(1, result.getCount()); result.moveToFirst(); model = new TestModel(result); assertFalse(model.isHappy()); } finally { result.close(); } } public void testConflict() { insertBasicTestModel(); TestModel conflict = new TestModel(); conflict.setFirstName("Dave"); conflict.setLastName("Bosley"); boolean result = database.persistWithOnConflict(conflict, TableStatement.ConflictAlgorithm.IGNORE); assertFalse(result); TestModel shouldntExist = database.fetchByCriterion(TestModel.class, TestModel.FIRST_NAME.eq("Dave").and(TestModel.LAST_NAME.eq("Bosley")), TestModel.PROPERTIES); assertNull(shouldntExist); RuntimeException expected = null; try { conflict.clearValue(TestModel.ID); database.persistWithOnConflict(conflict, TableStatement.ConflictAlgorithm.FAIL); } catch (RuntimeException e) { expected = e; } assertNotNull(expected); } public void testFetchByQueryResetsLimitAndTable() { TestModel model1 = new TestModel().setFirstName("Sam1").setLastName("Bosley1"); TestModel model2 = new TestModel().setFirstName("Sam2").setLastName("Bosley2"); TestModel model3 = new TestModel().setFirstName("Sam3").setLastName("Bosley3"); database.persist(model1); database.persist(model2); database.persist(model3); Query query = Query.select().limit(2, 1); TestModel fetched = database.fetchByQuery(TestModel.class, query); assertEquals(model2.getRowId(), fetched.getRowId()); assertEquals(Field.field("2"), query.getLimit()); assertEquals(Field.field("1"), query.getOffset()); assertEquals(null, query.getTable()); } public void testEqCaseInsensitive() { insertBasicTestModel(); TestModel fetch = database.fetchByCriterion(TestModel.class, TestModel.LAST_NAME.eqCaseInsensitive("BOSLEY"), TestModel.PROPERTIES); assertNotNull(fetch); } public void testInsertRow() { TestModel model = insertBasicTestModel(); assertNotNull(database.fetch(TestModel.class, model.getRowId())); database.delete(TestModel.class, model.getRowId()); assertNull(database.fetch(TestModel.class, model.getRowId())); long modelId = model.getRowId(); database.insertRow(model); // Should reinsert the row with the same id assertEquals(modelId, model.getRowId()); assertNotNull(database.fetch(TestModel.class, model.getRowId())); assertEquals(1, database.countAll(TestModel.class)); } public void testDropView() { database.tryDropView(TestViewModel.VIEW); testThrowsRuntimeException(new Runnable() { @Override public void run() { database.query(TestViewModel.class, Query.select().from(TestViewModel.VIEW)); } }); } public void testDropTable() { database.tryDropTable(TestModel.TABLE); testThrowsRuntimeException(new Runnable() { @Override public void run() { database.query(TestModel.class, Query.select().from(TestModel.TABLE)); } }); } public void testTryExecSqlReturnsFalseForInvalidSql() { assertFalse(database.tryExecSql("CREATE TABLE")); } public void testExecSqlOrThrowThrowsForInvalidSql() { testThrowsRuntimeException(new Runnable() { @Override public void run() { database.execSqlOrThrow("CREATE TABLE"); } }); testThrowsRuntimeException(new Runnable() { @Override public void run() { database.execSqlOrThrow("CREATE TABLE", null); } }); } public void testUpdateAll() { database.persist(new TestModel().setFirstName("A").setLastName("A") .setBirthday(System.currentTimeMillis() - 1).setLuckyNumber(1)); database.persist(new TestModel().setFirstName("A").setLastName("B") .setBirthday(System.currentTimeMillis() - 1).setLuckyNumber(2)); database.updateAll(new TestModel().setLuckyNumber(5)); assertEquals(0, database.count(TestModel.class, TestModel.LUCKY_NUMBER.neq(5))); } public void testDeleteAll() { insertBasicTestModel("A", "B", System.currentTimeMillis() - 1); insertBasicTestModel("C", "D", System.currentTimeMillis()); assertEquals(2, database.countAll(TestModel.class)); database.deleteAll(TestModel.class); assertEquals(0, database.countAll(TestModel.class)); } public void testBlobs() { List<byte[]> randomBlobs = new ArrayList<>(); Random r = new Random(); randomBlobs.add(new byte[0]); // Test 0-length blob int numBlobs = 10; for (int i = 0; i < numBlobs; i++) { byte[] blob = new byte[i + 1]; r.nextBytes(blob); randomBlobs.add(blob); } Thing t = new Thing(); database.beginTransaction(); try { for (byte[] blob : randomBlobs) { t.setBlob(blob); database.createNew(t); } database.setTransactionSuccessful(); } finally { database.endTransaction(); } SquidCursor<Thing> cursor = database.query(Thing.class, Query.select(Thing.BLOB).orderBy(Thing.ID.asc())); try { assertEquals(randomBlobs.size(), cursor.getCount()); for (int i = 0; i < randomBlobs.size(); i++) { cursor.moveToPosition(i); byte[] blob = cursor.get(Thing.BLOB); assertTrue(Arrays.equals(randomBlobs.get(i), blob)); } } finally { cursor.close(); } } public void testConcurrentReadsWithWAL() { // Tests that concurrent reads can happen when using WAL, but only committed changes will be visible // on other threads insertBasicTestModel(); final Semaphore sema1 = new Semaphore(0); final Semaphore sema2 = new Semaphore(0); final AtomicInteger countBeforeCommit = new AtomicInteger(); final AtomicInteger countAfterCommit = new AtomicInteger(); Thread thread = new Thread(new Runnable() { @Override public void run() { try { sema2.acquire(); } catch (InterruptedException e) { fail(e.getMessage()); } countBeforeCommit.set(database.countAll(TestModel.class)); sema1.release(); try { sema2.acquire(); } catch (InterruptedException e) { fail(e.getMessage()); } countAfterCommit.set(database.countAll(TestModel.class)); } }); database.beginTransactionNonExclusive(); try { thread.start(); insertBasicTestModel("A", "B", System.currentTimeMillis() + 100); sema2.release(); try { sema1.acquire(); } catch (InterruptedException e) { fail(e.getMessage()); } database.setTransactionSuccessful(); } finally { database.endTransaction(); sema2.release(); } try { thread.join(); } catch (InterruptedException e) { fail(e.getMessage()); } assertEquals(1, countBeforeCommit.get()); assertEquals(2, countAfterCommit.get()); } public void testConcurrencyStressTest() { int numThreads = 20; final AtomicReference<Exception> exception = new AtomicReference<>(); List<Thread> workers = new ArrayList<>(); for (int i = 0; i < numThreads; i++) { Thread t = new Thread(new Runnable() { @Override public void run() { concurrencyStressTest(exception); } }); t.start(); workers.add(t); } for (Thread t : workers) { try { t.join(); } catch (Exception e) { exception.set(e); } } assertNull(exception.get()); } private void concurrencyStressTest(AtomicReference<Exception> exception) { try { Random r = new Random(); int numOperations = 100; Thing t = new Thing(); for (int i = 0; i < numOperations; i++) { int rand = r.nextInt(10); if (rand == 0) { database.close(); } else if (rand == 1) { database.clear(); } else if (rand == 2) { database.recreate(); } else if (rand == 3) { database.beginTransactionNonExclusive(); try { for (int j = 0; j < 20; j++) { t.setFoo(Integer.toString(j)) .setBar(-j); database.createNew(t); } database.setTransactionSuccessful(); } finally { database.endTransaction(); } } else { t.setFoo(Integer.toString(i)) .setBar(-i); database.createNew(t); } } } catch (Exception e) { exception.set(e); } } public void testSimpleQueries() { database.beginTransactionNonExclusive(); try { // the changes() function only works inside a transaction, because otherwise you may not get // the same connection to the sqlite database depending on what the connection pool feels like giving you. String sql = "SELECT CHANGES()"; insertBasicTestModel(); assertEquals(1, database.simpleQueryForLong(sql, null)); assertEquals("1", database.simpleQueryForString(sql, null)); database.setTransactionSuccessful(); } finally { database.endTransaction(); } } public void testCopyDatabase() { insertBasicTestModel(); // Make sure DB is open and populated File destinationDir = new File(SQLiteBindingProvider.getInstance().getWriteableTestDir()); File dbFile = new File(database.getDatabasePath()); File walFile = new File(database.getDatabasePath() + "-wal"); assertTrue(dbFile.exists()); assertTrue(walFile.exists()); File destinationDbFile = new File(destinationDir.getPath() + File.separator + database.getName()); File destinationWalFile = new File(destinationDir.getPath() + File.separator + database.getName() + "-wal"); destinationDbFile.delete(); destinationWalFile.delete(); assertFalse(destinationDbFile.exists()); assertFalse(destinationWalFile.exists()); assertTrue(database.copyDatabase(destinationDir)); assertTrue(destinationDbFile.exists()); assertTrue(destinationWalFile.exists()); assertTrue(filesAreEqual(dbFile, destinationDbFile)); assertTrue(filesAreEqual(walFile, destinationWalFile)); } private boolean filesAreEqual(File f1, File f2) { if (f1.length() != f2.length()) { return false; } try { FileInputStream f1in = new FileInputStream(f1); FileInputStream f2in = new FileInputStream(f2); int f1Bytes; int f2Bytes; byte[] f1Buffer; byte[] f2Buffer; int BUFFER_SIZE = 1024; f1Buffer = new byte[BUFFER_SIZE]; f2Buffer = new byte[BUFFER_SIZE]; while ((f1Bytes = f1in.read(f1Buffer)) != -1) { f2Bytes = f2in.read(f2Buffer); if (f1Bytes != f2Bytes) { return false; } if (!Arrays.equals(f1Buffer, f2Buffer)) { return false; } } return f2in.read(f2Buffer) == -1; } catch (IOException e) { throw new RuntimeException(e); } } }
package org.carrot2.labs.smartsprites; import static org.carrot2.labs.test.Assertions.assertThat; import static org.fest.assertions.Assertions.assertThat; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; import org.apache.commons.io.FileUtils; import org.carrot2.labs.smartsprites.SmartSpritesParameters.PngDepth; import org.carrot2.labs.smartsprites.message.Message; import org.carrot2.labs.smartsprites.message.Message.MessageLevel; import org.junit.*; /** * Test cases for {@link SpriteBuilder}. The test cases read/ write files to the * directories contained in the test/ directory. */ public class SpriteBuilderTest extends TestWithMemoryMessageSink { /** Builder under tests, initialized in {@link #buildSprites(SmartSpritesParameters)} */ private SpriteBuilder spriteBuilder; @Before public void setUpHeadlessMode() { System.setProperty("java.awt.headless", "true"); } @Test public void testNoSpriteDeclarations() throws FileNotFoundException, IOException { final File testDir = testDir("no-sprite-declarations"); buildSprites(testDir); assertThat(processedCss()).doesNotExist(); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); } @Test public void testNoSpriteReferences() throws FileNotFoundException, IOException { final File testDir = testDir("no-sprite-references"); buildSprites(testDir); assertThat(processedCss()).hasSameContentAs(expectedCss()); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); } @Test public void testTargetSpriteImageDirNotExists() throws FileNotFoundException, IOException { final File testDir = testDir("target-sprite-image-dir-not-exists"); buildSprites(testDir); assertThat(processedCss()).hasSameContentAs(expectedCss()); assertThat(new File(testDir, "img-sprite/sprite.png")).exists(); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); FileUtils.deleteDirectory(new File(testDir, "img-sprite")); } @Test public void testSimpleHorizontalSprite() throws FileNotFoundException, IOException { final File testDir = testDir("simple-horizontal-sprite"); buildSprites(testDir); assertThat(processedCss()).hasSameContentAs(expectedCss()); assertThat(new File(testDir, "img/sprite.png")).exists(); org.fest.assertions.Assertions.assertThat(sprite(testDir)).hasSize( new Dimension(17 + 15 + 48, 47)); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); } @Test public void testSimpleHorizontalSpriteImportant() throws FileNotFoundException, IOException { final File testDir = testDir("simple-horizontal-sprite-important"); buildSprites(testDir); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); assertThat(processedCss()).hasSameContentAs(expectedCss()); assertThat(new File(testDir, "img/sprite.png")).exists(); org.fest.assertions.Assertions.assertThat(sprite(testDir)).hasSize( new Dimension(17 + 15 + 48, 47)); } @Test @Ignore public void testMultipleCssFiles() throws FileNotFoundException, IOException { final File testDir = testDir("multiple-css-files"); buildSprites(testDir); assertThat(processedCss()).hasSameContentAs(expectedCss()); assertThat(css("css/style2-sprite.css")).hasSameContentAs( css("css/style2-expected.css")); assertThat(new File(testDir, "img/sprite.png")).exists(); org.fest.assertions.Assertions.assertThat(sprite(testDir)).hasSize( new Dimension(17 + 15 + 48, 47)); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); } @Test public void testLargeVerticalRepeat() throws FileNotFoundException, IOException { final File testDir = testDir("large-vertical-repeat"); buildSprites(testDir); assertThat(processedCss()).hasSameContentAs(expectedCss()); assertThat(new File(testDir, "img/sprite.png")).exists(); org.fest.assertions.Assertions.assertThat(sprite(testDir)).hasSize( new Dimension(17 + 15, 16 * 17 /* lcm(16, 17) */)); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); } @Test public void testMissingImages() throws FileNotFoundException, IOException { final File testDir = testDir("missing-images"); buildSprites(testDir); assertThat(processedCss()).hasSameContentAs(expectedCss()); assertThat(new File(testDir, "img/sprite.png")).exists(); org.fest.assertions.Assertions.assertThat(sprite(testDir)).hasSize( new Dimension(18, 17 + 6 + 5)); // The unsatisfied sprite references are not removed from the output // file, hence we have two warnings assertThat(messages).contains( new Message(Message.MessageLevel.WARN, Message.MessageType.CANNOT_NOT_LOAD_IMAGE, new File(testDir, "css/style.css").getCanonicalPath(), 15, new File(testDir, "img/logo.png").getCanonicalPath(), "Can't read input file!"), new Message(Message.MessageLevel.WARN, Message.MessageType.CANNOT_NOT_LOAD_IMAGE, new File(testDir, "css/style-expected.css").getCanonicalPath(), 15, new File(testDir, "img/logo.png").getCanonicalPath(), "Can't read input file!")); } @Test public void testUnsupportedSpriteProperties() throws FileNotFoundException, IOException { final File testDir = testDir("unsupported-sprite-properties"); buildSprites(testDir); assertThat(processedCss()).hasSameContentAs(expectedCss()); assertThat(new File(testDir, "img/sprite.png")).exists(); org.fest.assertions.Assertions.assertThat(sprite(testDir)).hasSize( new Dimension(48, 16 + 17 + 47)); final String styleCssPath = new File(testDir, "css/style.css").getCanonicalPath(); assertThat(messages).isEquivalentTo( Message.MessageLevel.WARN, new Message(Message.MessageLevel.WARN, Message.MessageType.UNSUPPORTED_PROPERTIES_FOUND, styleCssPath, 4, "sprites-layout"), new Message(Message.MessageLevel.WARN, Message.MessageType.UNSUPPORTED_PROPERTIES_FOUND, styleCssPath, 14, "sprites-margin-top"), new Message(Message.MessageLevel.WARN, Message.MessageType.UNSUPPORTED_PROPERTIES_FOUND, styleCssPath, 18, "sprites-alignment")); } @Test public void testOverridingCssProperties() throws FileNotFoundException, IOException { final File testDir = testDir("overriding-css-properties"); buildSprites(testDir); assertThat(processedCss()).hasSameContentAs(expectedCss()); assertThat(new File(testDir, "img/sprite.png")).exists(); org.fest.assertions.Assertions.assertThat(sprite(testDir)).hasSize( new Dimension(17 + 15 + 48, 47)); final String styleCssPath = new File(testDir, "css/style.css").getCanonicalPath(); assertThat(messages).isEquivalentTo( Message.MessageLevel.WARN, new Message(Message.MessageLevel.WARN, Message.MessageType.OVERRIDING_PROPERTY_FOUND, styleCssPath, 10, "background-image", 9), new Message(Message.MessageLevel.WARN, Message.MessageType.OVERRIDING_PROPERTY_FOUND, styleCssPath, 21, "background-position", 20)); } @Test public void testAbsoluteImageUrl() throws FileNotFoundException, IOException { final File testDir = testDir("absolute-image-url"); final File documentRootDir = testDir("absolute-image-url/absolute-path"); buildSprites(new SmartSpritesParameters(testDir, null, documentRootDir, MessageLevel.INFO, SmartSpritesParameters.DEFAULT_CSS_FILE_SUFFIX, SmartSpritesParameters.DEFAULT_CSS_INDENT, SmartSpritesParameters.DEFAULT_SPRITE_PNG_DEPTH, SmartSpritesParameters.DEFAULT_SPRITE_PNG_IE6, SmartSpritesParameters.DEFAULT_CSS_FILE_ENCODING)); assertThat(processedCss()).hasSameContentAs(expectedCss()); final File spriteFile = new File(documentRootDir, "img/sprite.png"); assertThat(spriteFile).exists(); org.fest.assertions.Assertions.assertThat(ImageIO.read(spriteFile)).hasSize( new Dimension(17, 17)); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); spriteFile.delete(); } @Test public void testNonDefaultOutputDir() throws FileNotFoundException, IOException { final File testDir = testDir("non-default-output-dir"); final File documentRootDir = testDir("non-default-output-dir/absolute-path"); final File outputDir = testDir("non-default-output-dir/output-dir"); outputDir.mkdirs(); buildSprites(new SmartSpritesParameters(testDir, outputDir, documentRootDir, MessageLevel.INFO, SmartSpritesParameters.DEFAULT_CSS_FILE_SUFFIX, SmartSpritesParameters.DEFAULT_CSS_INDENT, SmartSpritesParameters.DEFAULT_SPRITE_PNG_DEPTH, SmartSpritesParameters.DEFAULT_SPRITE_PNG_IE6, SmartSpritesParameters.DEFAULT_CSS_FILE_ENCODING)); assertThat(processedCss()).hasSameContentAs(expectedCss()); final File absoluteSpriteFile = new File(documentRootDir, "img/absolute.png"); assertThat(absoluteSpriteFile).exists(); org.fest.assertions.Assertions.assertThat(ImageIO.read(absoluteSpriteFile)) .hasSize(new Dimension(17, 17)); final File relativeSpriteFile = new File(outputDir, "img/relative.png"); assertThat(relativeSpriteFile).exists(); org.fest.assertions.Assertions.assertThat(ImageIO.read(relativeSpriteFile)) .hasSize(new Dimension(15, 16)); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); FileUtils.deleteDirectory(outputDir); FileUtils.deleteDirectory(absoluteSpriteFile.getParentFile()); } @Test public void testCssOutputDir() throws FileNotFoundException, IOException { final File testDir = testDir("css-output-dir"); final File rootDir = new File(testDir, "css/sprite").getCanonicalFile(); final File outputDir = testDir("css-output-dir/output-dir/css"); outputDir.mkdirs(); buildSprites(new SmartSpritesParameters(rootDir, outputDir, null, MessageLevel.INFO, SmartSpritesParameters.DEFAULT_CSS_FILE_SUFFIX, SmartSpritesParameters.DEFAULT_CSS_INDENT, SmartSpritesParameters.DEFAULT_SPRITE_PNG_DEPTH, SmartSpritesParameters.DEFAULT_SPRITE_PNG_IE6, SmartSpritesParameters.DEFAULT_CSS_FILE_ENCODING)); assertThat(processedCss(new File(rootDir, "style.css"))).hasSameContentAs( new File(rootDir, "style-expected.css")); final File relativeSpriteFile = new File(outputDir, "../img/relative.png"); assertThat(relativeSpriteFile).exists(); org.fest.assertions.Assertions.assertThat(ImageIO.read(relativeSpriteFile)) .hasSize(new Dimension(17 + 15, 17)); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); FileUtils.deleteDirectory(outputDir.getParentFile()); } /** * Currently multiple references to the same image generate multiple copies of the * image in the sprite, hence the test is ignored. */ @Test @Ignore public void testRepeatedImageReferences() throws FileNotFoundException, IOException { final File testDir = testDir("repeated-image-references"); buildSprites(testDir); assertThat(processedCss()).hasSameContentAs(expectedCss()); assertThat(new File(testDir, "img/sprite.png")).exists(); org.fest.assertions.Assertions.assertThat(sprite(testDir)).hasSize( new Dimension(17, 17)); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); } @Test public void testIndexedColor() throws FileNotFoundException, IOException { final File testDir = testDir("indexed-color"); buildSprites(testDir); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-bit-alpha.gif")).isIndexedColor().hasBitAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-bit-alpha.png")).isIndexedColor().hasBitAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-full-alpha.png")).isDirectColor().hasTrueAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-many-colors.png")).isDirectColor() .doesNotHaveAlpha(); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); } @Test public void testIndexedForcedDirectColor() throws FileNotFoundException, IOException { final File testDir = testDir("indexed-color"); buildSprites(new SmartSpritesParameters(testDir, null, null, MessageLevel.INFO, SmartSpritesParameters.DEFAULT_CSS_FILE_SUFFIX, SmartSpritesParameters.DEFAULT_CSS_INDENT, PngDepth.DIRECT, SmartSpritesParameters.DEFAULT_SPRITE_PNG_IE6, SmartSpritesParameters.DEFAULT_CSS_FILE_ENCODING)); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-bit-alpha.gif")).isIndexedColor().hasBitAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-bit-alpha.png")).isDirectColor().hasBitAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-full-alpha.png")).isDirectColor().hasTrueAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-many-colors.png")).isDirectColor() .doesNotHaveAlpha(); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); } @Test public void testIndexedForcedIndexedColor() throws FileNotFoundException, IOException { final File testDir = testDir("indexed-color"); buildSprites(new SmartSpritesParameters(testDir, null, null, MessageLevel.INFO, SmartSpritesParameters.DEFAULT_CSS_FILE_SUFFIX, SmartSpritesParameters.DEFAULT_CSS_INDENT, PngDepth.INDEXED, SmartSpritesParameters.DEFAULT_SPRITE_PNG_IE6, SmartSpritesParameters.DEFAULT_CSS_FILE_ENCODING)); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-bit-alpha.gif")).isIndexedColor().hasBitAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-bit-alpha.png")).isIndexedColor().hasBitAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-full-alpha.png")).isIndexedColor().hasBitAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-many-colors.png")).isIndexedColor() .doesNotHaveAlpha(); assertThat(messages).isEquivalentTo( Message.MessageLevel.WARN, new Message(Message.MessageLevel.WARN, Message.MessageType.ALPHA_CHANNEL_LOSS_IN_INDEXED_COLOR, null, 25, "full-alpha"), new Message(Message.MessageLevel.WARN, Message.MessageType.USING_WHITE_MATTE_COLOR_AS_DEFAULT, null, 25, "full-alpha"), new Message(Message.MessageLevel.WARN, Message.MessageType.TOO_MANY_COLORS_FOR_INDEXED_COLOR, null, 32, "many-colors", 293, 255)); } @Test public void testMatteColor() throws FileNotFoundException, IOException { final File testDir = testDir("matte-color"); buildSprites(testDir); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-bit-alpha.png")).isIndexedColor().hasBitAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-full-alpha-m1.png")).isDirectColor() .hasTrueAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-full-alpha-m2.png")).isDirectColor() .hasTrueAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-full-alpha-m3.png")).isDirectColor() .hasTrueAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-many-colors.png")).isDirectColor() .doesNotHaveAlpha(); assertThat(messages).isEquivalentTo( Message.MessageLevel.WARN, new Message(Message.MessageLevel.WARN, Message.MessageType.IGNORING_MATTE_COLOR_NO_SUPPORT, null, 12, "full-alpha-m1"), new Message(Message.MessageLevel.WARN, Message.MessageType.IGNORING_MATTE_COLOR_NO_SUPPORT, null, 19, "full-alpha-m2"), new Message(Message.MessageLevel.WARN, Message.MessageType.IGNORING_MATTE_COLOR_NO_SUPPORT, null, 26, "full-alpha-m3"), new Message(Message.MessageLevel.WARN, Message.MessageType.IGNORING_MATTE_COLOR_NO_PARTIAL_TRANSPARENCY, null, 33, "bit-alpha"), new Message(Message.MessageLevel.WARN, Message.MessageType.IGNORING_MATTE_COLOR_NO_SUPPORT, null, 40, "many-colors")); } @Test public void testMatteColorForcedIndex() throws FileNotFoundException, IOException { final File testDir = testDir("matte-color"); buildSprites(new SmartSpritesParameters(testDir, null, null, MessageLevel.INFO, SmartSpritesParameters.DEFAULT_CSS_FILE_SUFFIX, SmartSpritesParameters.DEFAULT_CSS_INDENT, PngDepth.INDEXED, SmartSpritesParameters.DEFAULT_SPRITE_PNG_IE6, SmartSpritesParameters.DEFAULT_CSS_FILE_ENCODING)); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-bit-alpha.png")).isIndexedColor().hasBitAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-full-alpha-m1.png")).isIndexedColor() .hasBitAlpha().isEqualTo(sprite(testDir, "img/sprite-full-alpha-m2.png")) .isNotEqualTo(sprite(testDir, "img/sprite-full-alpha-m3.png")); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-full-alpha-m2.png")).isIndexedColor() .hasBitAlpha().isEqualTo(sprite(testDir, "img/sprite-full-alpha-m1.png")) .isNotEqualTo(sprite(testDir, "img/sprite-full-alpha-m3.png")); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-full-alpha-m3.png")).isIndexedColor() .hasBitAlpha().isNotEqualTo(sprite(testDir, "img/sprite-full-alpha-m1.png")); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-many-colors.png")).isIndexedColor() .doesNotHaveAlpha(); assertThat(messages).isEquivalentTo( Message.MessageLevel.WARN, new Message(Message.MessageLevel.WARN, Message.MessageType.ALPHA_CHANNEL_LOSS_IN_INDEXED_COLOR, null, 12, "full-alpha-m1"), new Message(Message.MessageLevel.WARN, Message.MessageType.ALPHA_CHANNEL_LOSS_IN_INDEXED_COLOR, null, 19, "full-alpha-m2"), new Message(Message.MessageLevel.WARN, Message.MessageType.ALPHA_CHANNEL_LOSS_IN_INDEXED_COLOR, null, 26, "full-alpha-m3"), new Message(Message.MessageLevel.WARN, Message.MessageType.IGNORING_MATTE_COLOR_NO_PARTIAL_TRANSPARENCY, null, 33, "bit-alpha"), new Message(Message.MessageLevel.WARN, Message.MessageType.TOO_MANY_COLORS_FOR_INDEXED_COLOR, null, 40, "many-colors", 293, 255)); } @Test public void testIe6IndexedColor() throws FileNotFoundException, IOException { final File testDir = testDir("indexed-color-ie6"); buildSprites(new SmartSpritesParameters(testDir, null, null, MessageLevel.INFO, SmartSpritesParameters.DEFAULT_CSS_FILE_SUFFIX, SmartSpritesParameters.DEFAULT_CSS_INDENT, PngDepth.AUTO, true, SmartSpritesParameters.DEFAULT_CSS_FILE_ENCODING)); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-bit-alpha.gif")).isIndexedColor().hasBitAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-bit-alpha.png")).isIndexedColor().hasBitAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-full-alpha.png")).isDirectColor().hasTrueAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-full-alpha-ie6.png")).isIndexedColor() .hasBitAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-many-colors.png")).isDirectColor() .doesNotHaveAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-many-colors-bit-alpha-ie6.png")).isIndexedColor() .hasBitAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-many-colors-bit-alpha-no-ie6.png")) .isDirectColor().hasBitAlpha(); org.carrot2.labs.test.Assertions.assertThat( sprite(testDir, "img/sprite-many-colors-bit-alpha.png")).isDirectColor() .hasBitAlpha(); assertThat(processedCss()).hasSameContentAs(expectedCss()); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); assertThat(messages).isEquivalentTo( Message.MessageLevel.IE6NOTICE, new Message(Message.MessageLevel.IE6NOTICE, Message.MessageType.ALPHA_CHANNEL_LOSS_IN_INDEXED_COLOR, null, 27, "full-alpha"), new Message(Message.MessageLevel.IE6NOTICE, Message.MessageType.USING_WHITE_MATTE_COLOR_AS_DEFAULT, null, 27, "full-alpha"), new Message(Message.MessageLevel.IE6NOTICE, Message.MessageType.TOO_MANY_COLORS_FOR_INDEXED_COLOR, null, 41, "many-colors-bit-alpha", 293, 255)); } @Test public void testSpriteImageUidMd5() throws FileNotFoundException, IOException { final File testDir = testDir("sprite-image-uid-md5"); buildSprites(testDir); assertThat(processedCss()).hasSameContentAs(expectedCss()); assertThat(new File(testDir, "img/sprite.png")).exists(); org.fest.assertions.Assertions.assertThat(sprite(testDir)).hasSize( new Dimension(17 + 15, 17)); org.fest.assertions.Assertions.assertThat(sprite(testDir, "img/sprite2.png")) .hasSize(new Dimension(48, 47)); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); } @Test public void testSpriteImageUidMd5Ie6() throws FileNotFoundException, IOException { final File testDir = testDir("sprite-image-uid-md5-ie6"); buildSprites(new SmartSpritesParameters(testDir, null, null, MessageLevel.INFO, SmartSpritesParameters.DEFAULT_CSS_FILE_SUFFIX, SmartSpritesParameters.DEFAULT_CSS_INDENT, PngDepth.AUTO, true, SmartSpritesParameters.DEFAULT_CSS_FILE_ENCODING)); assertThat(processedCss()).hasSameContentAs(expectedCss()); assertThat(new File(testDir, "img/sprite.png")).exists(); assertThat(new File(testDir, "img/sprite-ie6.png")).exists(); org.fest.assertions.Assertions.assertThat(sprite(testDir)).hasSize( new Dimension(20, 20)); assertThat(messages).doesNotHaveMessagesOfLevel(MessageLevel.WARN); } @After public void cleanUp() { // Delete sprite CSS deleteFiles(new File(spriteBuilder.parameters.getRootDir(), "css") .listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.contains("-sprite"); } })); // Delete sprites deleteFiles(new File(spriteBuilder.parameters.getRootDir(), "img") .listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith("sprite"); } })); } private void deleteFiles(final File [] files) { if (files != null) { for (File file : files) { file.delete(); } } } private File testDir(String test) { final File testDir = new File("test/" + test); return testDir; } private BufferedImage sprite(final File testDir) throws IOException { return sprite(testDir, "img/sprite.png"); } private BufferedImage sprite(final File testDir, String imagePath) throws IOException { return ImageIO.read(new File(testDir, imagePath)); } private File expectedCss() { return css("css/style-expected.css"); } private File sourceCss() { return css("css/style.css"); } private File processedCss() { return processedCss(sourceCss()); } private File css(String cssPath) { return new File(spriteBuilder.parameters.getRootDir(), cssPath); } private File processedCss(File sourceCss) { return spriteBuilder.getProcessedCssFile(sourceCss); } private void buildSprites(File dir) throws IOException { buildSprites(new SmartSpritesParameters(dir)); } private void buildSprites(SmartSpritesParameters parameters) throws IOException { spriteBuilder = new SpriteBuilder(parameters, messageLog); spriteBuilder.buildSprites(); } }
package jp.nyatla.mimic.mbedjs.javaapi.driver; import jp.nyatla.mimic.mbedjs.*; import jp.nyatla.mimic.mbedjs.javaapi.*; import jp.nyatla.mimic.mbedjs.javaapi.driver.utils.DriverBaseClass; public class ATP3011 extends DriverBaseClass{ /** * 7bit I2C */ public final static int I2C_ADDRESS=(0x2E); public final static int AQTK_STARTUP_WAIT_MS = 80; public final static int AQTK_POLL_WAIT_MS = 10; private long _last_call_in_msec; private final I2C _i2c; private final int _addr; /** I2C*/ private final boolean _is_attached; /** * I2C * @param i_i2c * @param i_address * @throws MbedJsException */ public ATP3011(I2C i_i2c,int i_address) throws MbedJsException { this._is_attached=false; this._i2c=i_i2c; this._addr=i_address; this._initDevice(); } /** * Mcu * @param i_mcu * @param sda * @param scl * @param i_address * @throws MbedJsException */ public ATP3011(Mcu i_mcu, int sda, int scl, int i_address) throws MbedJsException { this._is_attached=true; this._i2c=new I2C(i_mcu, sda, scl); this._addr=i_address; this._i2c.frequency(10000); this._initDevice(); } private void _initDevice() { this._last_call_in_msec=System.currentTimeMillis(); } public void dispose() throws MbedJsException{ if(this._is_attached){ this._i2c.dispose(); } } public boolean isActive(int i_timeout_ms) throws MbedJsException { sleep_ms(ATP3011.AQTK_STARTUP_WAIT_MS); long start=System.currentTimeMillis(); do{ if (this._i2c.write(this._addr,new byte[]{0x00}, false) == 0) { this._last_call_in_msec=System.currentTimeMillis(); return true; } sleep_ms(ATP3011.AQTK_POLL_WAIT_MS); }while(System.currentTimeMillis()-start<i_timeout_ms); return false; } public void synthe(byte[] i_msg) throws MbedJsException { while(this.isBusy()){ this.sleep_ms(AQTK_POLL_WAIT_MS); } this.write(i_msg); this.write(new byte[]{'\r'}); } public void write(byte[] i_msg) throws MbedJsException { this._i2c.write(this._addr, i_msg, false); this._last_call_in_msec=System.currentTimeMillis(); } public boolean isBusy() throws MbedJsException { long now=System.currentTimeMillis(); if(now-this._last_call_in_msec<AQTK_POLL_WAIT_MS){ return true; } this._last_call_in_msec=now; //I2C I2C.ReadResult rr= this._i2c.read(_addr, 1, false); byte c = rr.data[0]; if (c != 0) { return false; } return c == '*' || c == 0xff; } public static void main(String[] args) throws MbedJsException { Mcu mcu = new Mcu("10.0.0.2"); ATP3011 talk = new ATP3011(mcu,PinName.P0_10 , PinName.P0_11,ATP3011.I2C_ADDRESS<<1); for(int n=1 ; ; n++) { String str = String.format("<NUMK VAL={0}>.", n); byte[] msg = new byte[32]; msg = str.getBytes(); talk.synthe(msg); } } }
package kg.apc.jmeter.gui; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import org.apache.jorphan.gui.NumberRenderer; /** * * @author Stephane Hoblingre */ public class CustomNumberRenderer extends NumberRenderer { private NumberFormat customFormatter = null; public CustomNumberRenderer() { super(); } public CustomNumberRenderer(String format) { super(format); } public CustomNumberRenderer(String format, char groupingSeparator) { super(); DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setGroupingSeparator(groupingSeparator); customFormatter = new DecimalFormat(format, symbols); } @Override public void setValue(Object value) { String str = ""; if(value != null) { if(customFormatter != null) { str = customFormatter.format(value); } else { str = formatter.format(value); } } setText(str); } }
package org.dmg.pmml; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.jpmml.model.ArrayUtil; import org.jpmml.model.annotations.Property; import org.jpmml.model.annotations.ValueConstructor; public class ComplexArray extends Array { public ComplexArray(){ } @ValueConstructor public ComplexArray(@Property("type") Array.Type type, @Property("value") Collection<?> value){ super(type, requireComplexValue(value)); } @Override public ComplexArray setN(@Property("n") Integer n){ return (ComplexArray)super.setN(n); } @Override public ComplexArray setType(@Property("type") Array.Type type){ return (ComplexArray)super.setType(type); } @Override public Collection<?> getValue(){ return (Collection<?>)super.getValue(); } public ComplexArray setValue(List<?> values){ return (ComplexArray)super.setValue(new ListValue(values)); } public ComplexArray setValue(Set<?> values){ return (ComplexArray)super.setValue(new SetValue(values)); } @Override public ComplexArray setValue(@Property("value") Object value){ return (ComplexArray)super.setValue(requireComplexValue(value)); } static public <V extends Collection<?> & ComplexValue> V requireComplexValue(Object value){ if(value == null){ return null; } // End if if((value instanceof Collection) && (value instanceof ComplexValue)){ return (V)value; } throw new IllegalArgumentException(); } class ListValue extends ArrayList<Object> implements ComplexValue { ListValue(Collection<?> values){ super(values); } @Override public Object toSimpleValue(){ return ArrayUtil.format(getType(), this); } } class SetValue extends LinkedHashSet<Object> implements ComplexValue { SetValue(Collection<?> values){ super(values); } @Override public Object toSimpleValue(){ return ArrayUtil.format(getType(), this); } } }
package som.vmobjects; import java.lang.reflect.Field; import java.util.Arrays; import java.util.HashMap; import java.util.Map.Entry; import som.compiler.MixinDefinition.SlotDefinition; import som.interpreter.objectstorage.ClassFactory; import som.interpreter.objectstorage.ObjectLayout; import som.interpreter.objectstorage.StorageLocation; import som.interpreter.objectstorage.StorageLocation.AbstractObjectStorageLocation; import som.interpreter.objectstorage.StorageLocation.GeneralizeStorageLocationException; import som.interpreter.objectstorage.StorageLocation.UninitalizedStorageLocationException; import som.vm.constants.Nil; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; import com.oracle.truffle.api.nodes.ExplodeLoop; public abstract class SObject extends SObjectWithClass { public static final int NUM_PRIMITIVE_FIELDS = 5; public static final int NUM_OBJECT_FIELDS = 5; public static final class SImmutableObject extends SObject { public SImmutableObject(final SClass instanceClass, final ClassFactory classGroup, final ObjectLayout layout) { super(instanceClass, classGroup, layout); field1 = field2 = field3 = field4 = field5 = Nil.nilObject; isValue = instanceClass.declaredAsValue(); } public SImmutableObject(final boolean incompleteDefinition, final boolean isKernelObj) { super(incompleteDefinition); assert isKernelObj; isValue = true; } /** * Copy constructor. */ private SImmutableObject(final SImmutableObject old) { super(old); this.primField1 = old.primField1; this.primField2 = old.primField2; this.primField3 = old.primField3; this.primField4 = old.primField4; this.primField5 = old.primField5; this.isValue = old.isValue; } @CompilationFinal protected long primField1; @CompilationFinal protected long primField2; @CompilationFinal protected long primField3; @CompilationFinal protected long primField4; @CompilationFinal protected long primField5; @CompilationFinal public Object field1; @CompilationFinal public Object field2; @CompilationFinal public Object field3; @CompilationFinal public Object field4; @CompilationFinal public Object field5; @CompilationFinal protected boolean isValue; @Override protected void resetFields() { field1 = field2 = field3 = field4 = field5 = null; primField1 = primField2 = primField3 = primField4 = primField5 = Long.MIN_VALUE; } @Override public boolean isValue() { return isValue; } @Override public SObject cloneBasics() { assert !isValue : "There should not be any need to clone a value"; return new SImmutableObject(this); } } public static final class SMutableObject extends SObject { @SuppressWarnings("unused") private long primField1; @SuppressWarnings("unused") private long primField2; @SuppressWarnings("unused") private long primField3; @SuppressWarnings("unused") private long primField4; @SuppressWarnings("unused") private long primField5; @SuppressWarnings("unused") private Object field1; @SuppressWarnings("unused") private Object field2; @SuppressWarnings("unused") private Object field3; @SuppressWarnings("unused") private Object field4; @SuppressWarnings("unused") private Object field5; // this field exists because HotSpot reorders fields, and we need to keep // the layouts in sync to avoid having to manage different offsets for // SMutableObject and SImmuableObject @SuppressWarnings("unused") private boolean isValueOfSImmutableObjectSync; public SMutableObject(final SClass instanceClass, final ClassFactory factory, final ObjectLayout layout) { super(instanceClass, factory, layout); field1 = field2 = field3 = field4 = field5 = Nil.nilObject; } public SMutableObject(final boolean incompleteDefinition) { super(incompleteDefinition); } protected SMutableObject(final SMutableObject old) { super(old); this.primField1 = old.primField1; this.primField2 = old.primField2; this.primField3 = old.primField3; this.primField4 = old.primField4; this.primField5 = old.primField5; } @Override protected void resetFields() { field1 = field2 = field3 = field4 = field5 = null; primField1 = primField2 = primField3 = primField4 = primField5 = Long.MIN_VALUE; } @Override public boolean isValue() { return false; } @Override public SObject cloneBasics() { return new SMutableObject(this); } } @SuppressWarnings("unused") @CompilationFinal private long[] extensionPrimFields; @SuppressWarnings("unused") @CompilationFinal private Object[] extensionObjFields; // we manage the layout entirely in the class, but need to keep a copy here // to know in case the layout changed that we can update the instances lazily @CompilationFinal private ObjectLayout objectLayout; private int primitiveUsedMap; public SObject(final SClass instanceClass, final ClassFactory factory, final ObjectLayout layout) { super(instanceClass, factory); assert factory.getInstanceLayout() == layout || layout.layoutForSameClasses(factory.getInstanceLayout()); setLayoutInitially(layout); } public SObject(final boolean incompleteDefinition) { assert incompleteDefinition; // used during bootstrap } /** Copy Constructor. */ protected SObject(final SObject old) { super(old); this.objectLayout = old.objectLayout; this.primitiveUsedMap = old.primitiveUsedMap; // TODO: these tests should be compilation constant based on the object layout, check whether this needs to be optimized // we copy the content here, because we know they are all values if (old.extensionPrimFields != emptyPrim) { assert old.extensionPrimFields != null : "should always be initialized"; this.extensionPrimFields = old.extensionPrimFields.clone(); } // do not want to copy the content for the obj extension array, because // transfer should handle each of them. if (old.extensionObjFields != emptyObject) { assert old.extensionObjFields != null : "should always be initialized"; this.extensionObjFields = new Object[old.extensionObjFields.length]; } } /** * @return new object of the same type, initialized with same primitive * values, object layout etc. Object fields are not cloned. No deep copying * either. This method is used for cloning transfer objects. */ public abstract SObject cloneBasics(); public boolean isPrimitiveSet(final int mask) { return (primitiveUsedMap & mask) != 0; } public void markPrimAsSet(final int mask) { primitiveUsedMap |= mask; } private void setLayoutInitially(final ObjectLayout layout) { CompilerAsserts.partialEvaluationConstant(layout); objectLayout = layout; extensionPrimFields = getExtendedPrimStorage(layout); extensionObjFields = getExtendedObjectStorage(layout); } public final ObjectLayout getObjectLayout() { // TODO: should I really remove it, or should I update the layout? // assert clazz.getLayoutForInstances() == objectLayout; return objectLayout; } public final long[] getExtendedPrimFields() { return extensionPrimFields; } public final Object[] getExtensionObjFields() { return extensionObjFields; } @Override public final void setClass(final SClass value) { CompilerAsserts.neverPartOfCompilation("Only meant to be used in object system initalization"); super.setClass(value); setLayoutInitially(value.getLayoutForInstances()); } private static final long[] emptyPrim = new long[0]; private long[] getExtendedPrimStorage(final ObjectLayout layout) { int numExtFields = layout.getNumberOfUsedExtendedPrimStorageLocations(); CompilerAsserts.partialEvaluationConstant(numExtFields); if (numExtFields == 0) { return emptyPrim; } else { return new long[numExtFields]; } } private static final Object[] emptyObject = new Object[0]; private Object[] getExtendedObjectStorage(final ObjectLayout layout) { int numExtFields = layout.getNumberOfUsedExtendedObjectStorageLocations(); CompilerAsserts.partialEvaluationConstant(numExtFields); if (numExtFields == 0) { return emptyObject; } Object[] storage = new Object[numExtFields]; Arrays.fill(storage, Nil.nilObject); return storage; } @ExplodeLoop private HashMap<SlotDefinition, Object> getAllFields() { assert objectLayout != null; HashMap<SlotDefinition, StorageLocation> locations = objectLayout.getStorageLocations(); HashMap<SlotDefinition, Object> fieldValues = new HashMap<>((int) (locations.size() / 0.75f)); for (Entry<SlotDefinition, StorageLocation> loc : locations.entrySet()) { if (loc.getValue().isSet(this)) { fieldValues.put(loc.getKey(), loc.getValue().read(this)); } else { fieldValues.put(loc.getKey(), null); } } return fieldValues; } protected abstract void resetFields(); @ExplodeLoop private void setAllFields(final HashMap<SlotDefinition, Object> fieldValues) { resetFields(); primitiveUsedMap = 0; for (Entry<SlotDefinition, Object> entry : fieldValues.entrySet()) { if (entry.getValue() != null) { setField(entry.getKey(), entry.getValue()); } else if (getLocation(entry.getKey()) instanceof AbstractObjectStorageLocation) { setField(entry.getKey(), Nil.nilObject); } } } public final boolean updateLayoutToMatchClass() { ObjectLayout layoutAtClass = clazz.getLayoutForInstances(); if (objectLayout != layoutAtClass) { setLayoutAndTransferFields(); return true; } else { return false; } } private synchronized void setLayoutAndTransferFields() { CompilerDirectives.transferToInterpreterAndInvalidate(); ObjectLayout layoutAtClass; synchronized (clazz) { layoutAtClass = clazz.getLayoutForInstances(); if (objectLayout == layoutAtClass) { return; } } HashMap<SlotDefinition, Object> fieldValues = getAllFields(); objectLayout = layoutAtClass; extensionPrimFields = getExtendedPrimStorage(layoutAtClass); extensionObjFields = getExtendedObjectStorage(layoutAtClass); setAllFields(fieldValues); } protected final void updateLayoutWithInitializedField(final SlotDefinition slot, final Class<?> type) { ObjectLayout layout = classGroup.updateInstanceLayoutWithInitializedField(slot, type); assert objectLayout != layout; setLayoutAndTransferFields(); } protected final void updateLayoutWithGeneralizedField(final SlotDefinition slot) { ObjectLayout layout = classGroup.updateInstanceLayoutWithGeneralizedField(slot); assert objectLayout != layout; setLayoutAndTransferFields(); } private static final long FIRST_OBJECT_FIELD_OFFSET = getFirstObjectFieldOffset(); private static final long FIRST_PRIM_FIELD_OFFSET = getFirstPrimFieldOffset(); private static final long OBJECT_FIELD_LENGTH = getObjectFieldLength(); private static final long PRIM_FIELD_LENGTH = getPrimFieldLength(); public static long getObjectFieldOffset(final int fieldIndex) { assert 0 <= fieldIndex && fieldIndex < NUM_OBJECT_FIELDS; return FIRST_OBJECT_FIELD_OFFSET + fieldIndex * OBJECT_FIELD_LENGTH; } public static long getPrimitiveFieldOffset(final int fieldIndex) { assert 0 <= fieldIndex && fieldIndex < NUM_PRIMITIVE_FIELDS; return FIRST_PRIM_FIELD_OFFSET + fieldIndex * PRIM_FIELD_LENGTH; } public static int getPrimitiveFieldMask(final int fieldIndex) { assert 0 <= fieldIndex && fieldIndex < 32; // this limits the number of object fields for the moment... return 1 << fieldIndex; } private StorageLocation getLocation(final SlotDefinition slot) { StorageLocation location = objectLayout.getStorageLocation(slot); assert location != null; return location; } public final Object getField(final SlotDefinition slot) { CompilerAsserts.neverPartOfCompilation("getField"); StorageLocation location = getLocation(slot); return location.read(this); } public final void setField(final SlotDefinition slot, final Object value) { CompilerAsserts.neverPartOfCompilation("setField"); StorageLocation location = getLocation(slot); try { location.write(this, value); } catch (UninitalizedStorageLocationException e) { updateLayoutWithInitializedField(slot, value.getClass()); setFieldAfterLayoutChange(slot, value); } catch (GeneralizeStorageLocationException e) { updateLayoutWithGeneralizedField(slot); setFieldAfterLayoutChange(slot, value); } } private void setFieldAfterLayoutChange(final SlotDefinition slot, final Object value) { CompilerAsserts.neverPartOfCompilation("SObject.setFieldAfterLayoutChange(..)"); StorageLocation location = getLocation(slot); try { location.write(this, value); } catch (GeneralizeStorageLocationException | UninitalizedStorageLocationException e) { throw new RuntimeException("This should not happen, we just prepared this field for the new value."); } } private static long getFirstObjectFieldOffset() { CompilerAsserts.neverPartOfCompilation("SObject.getFirstObjectFieldOffset()"); try { final Field firstField = SMutableObject.class.getDeclaredField("field1"); return StorageLocation.getFieldOffset(firstField); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } } private static long getFirstPrimFieldOffset() { CompilerAsserts.neverPartOfCompilation("SObject.getFirstPrimFieldOffset()"); try { final Field firstField = SMutableObject.class.getDeclaredField("primField1"); return StorageLocation.getFieldOffset(firstField); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } } private static long getObjectFieldLength() { CompilerAsserts.neverPartOfCompilation("getObjectFieldLength()"); try { long dist = getFieldDistance("field1", "field2"); // this can go wrong if the VM rearranges fields to fill holes in the // memory layout of the object structure assert dist == 4 || dist == 8 : "We expect these fields to be adjecent and either 32 or 64bit appart."; return dist; } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException(e); } } private static long getPrimFieldLength() { CompilerAsserts.neverPartOfCompilation("getPrimFieldLength()"); try { long dist = getFieldDistance("primField1", "primField2"); // this can go wrong if the VM rearranges fields to fill holes in the // memory layout of the object structure assert dist == 8 : "We expect these fields to be adjecent and 64bit appart."; return dist; } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException(e); } } private static long getFieldDistance(final String field1, final String field2) throws NoSuchFieldException, IllegalAccessException { final Field firstField = SMutableObject.class.getDeclaredField(field1); final Field secondField = SMutableObject.class.getDeclaredField(field2); return StorageLocation.getFieldOffset(secondField) - StorageLocation.getFieldOffset(firstField); } }
package amu.roboclub.ui.fragments; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import amu.roboclub.R; import amu.roboclub.models.Contribution; import amu.roboclub.ui.viewholder.ContributionHolder; import butterknife.BindView; import butterknife.ButterKnife; public class ContributionFragment extends Fragment { public ContributionFragment() { // Required empty public constructor } public static ContributionFragment newInstance() { return new ContributionFragment(); } @BindView(R.id.recyclerView) RecyclerView recyclerView; @Override public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_contribution, container, false); ButterKnife.bind(this, root); recyclerView.setItemAnimator(new DefaultItemAnimator()); LinearLayoutManager llm = new LinearLayoutManager(getContext()); llm.setReverseLayout(true); llm.setStackFromEnd(true); recyclerView.setLayoutManager(llm); final Snackbar snackbar = Snackbar.make(recyclerView, "Loading Contributors", Snackbar.LENGTH_INDEFINITE); snackbar.show(); DatabaseReference contributionReference = FirebaseDatabase.getInstance().getReference("contribution"); FirebaseRecyclerAdapter contributionAdapter = new FirebaseRecyclerAdapter<Contribution, ContributionHolder> (Contribution.class, R.layout.item_contribution, ContributionHolder.class, contributionReference) { @Override protected void populateViewHolder(ContributionHolder holder, Contribution contribution, int position) { if (snackbar.isShown()) snackbar.dismiss(); holder.contributor.setText(contribution.contributor); holder.purpose.setText(contribution.purpose); holder.remark.setText(contribution.remark); holder.amount.setText(contribution.amount); } }; recyclerView.setAdapter(contributionAdapter); return root; } }
package au.com.greentron.nfcconfiguration; import android.content.Intent; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.View; import android.widget.Button; import android.widget.TabHost; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Handler uiHandler; NfcAdapter.ReaderCallback readerCallback; TextView dataSensorType; TextView configSensorType; TextView configName; TextView configPAN_ID; TextView configChannel; Button editConfig; Toolbar actionBar; TabHost tabHost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // The action bar was replaced to allow editing, so this is necessary actionBar = (Toolbar) findViewById(R.id.action_toolbar); setSupportActionBar(actionBar); // Setup tabs tabHost = (TabHost) findViewById(R.id.tabhost); tabHost.setup(); // Data Tab TabHost.TabSpec spec = tabHost.newTabSpec("Data"); spec.setContent(R.id.datatab); spec.setIndicator("Data"); tabHost.addTab(spec); //Config Tab spec = tabHost.newTabSpec("Config"); spec.setContent(R.id.configtab); spec.setIndicator("Config"); tabHost.addTab(spec); // Help Tab spec = tabHost.newTabSpec("Help"); spec.setContent(R.id.helptab); spec.setIndicator("Help"); tabHost.addTab(spec); // Set tab label size for(int i=0; i<tabHost.getTabWidget().getChildCount(); i++) { TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title); tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20); } // By deafult, open help tab tabHost.setCurrentTab(2); // Handles to UI elements dataSensorType = (TextView) findViewById(R.id.datatab_sensor_type); configSensorType = (TextView) findViewById(R.id.configtab_sensor_type); configName = (TextView) findViewById(R.id.sensor_name); configPAN_ID = (TextView) findViewById(R.id.panid); configChannel = (TextView) findViewById(R.id.channel); editConfig = (Button) findViewById(R.id.enter_config_setup); // Receive result from TagRead output uiHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { TextView dataField = (TextView) findViewById(R.id.datatab_data); // If user is currently on help tab, direct them to data tab if (tabHost.getCurrentTab() == 2) { tabHost.setCurrentTab(0); } switch (msg.what) { case Constants.WORKER_EXIT_SUCCESS: Configuration config = (Configuration) msg.obj; dataSensorType.setText(String.valueOf(config.sensor_type)); configSensorType.setText(String.valueOf(config.sensor_type)); configName.setText(config.name); configPAN_ID.setText(String.valueOf(config.pan_id)); configChannel.setText(String.valueOf(config.channel)); dataField.setText("Got data:\n"); for (int i=0; i<config.data.length; i++) { dataField.append("Page "); dataField.append(String.valueOf(i)); dataField.append(": "); dataField.append(String.valueOf(config.data[i])); dataField.append("\n"); } editConfig.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(), EditConfig.class); startActivity(intent); } }); editConfig.setEnabled(true); break; case Constants.WORKER_FATAL_ERROR: dataField.setText("Got fatal error:\n"); dataField.append(msg.obj.toString()); dataField.append("\n"); break; } } }; // Set up NFC callback, handled by TagRead NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext()); readerCallback = new NfcAdapter.ReaderCallback() { @Override public void onTagDiscovered(Tag tag) { (new TagRead(uiHandler, tag)).start(); } }; int nfcflags = NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK | NfcAdapter.FLAG_READER_NFC_A; nfcAdapter.enableReaderMode(this, readerCallback, nfcflags, new Bundle()); } }
package ay3524.com.wallpapertime.ui; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.PowerManager; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import ay3524.com.wallpapertime.R; import ay3524.com.wallpapertime.utils.CircleTransform; import ay3524.com.wallpapertime.utils.Constants; import ay3524.com.wallpapertime.utils.SingleMediaScanner; /** * An activity representing a single Item detail screen. This * activity is only used narrow width devices. On tablet-size devices, * item details are presented side-by-side with a list of items * in a {@link ItemListActivity}. */ public class ItemDetailActivity extends AppCompatActivity { CollapsingToolbarLayout collapsingToolbarLayout; String image_title, user_image_url, tags, user_profile_pixabay_link, image_pixabay_link, user, web_format_url,preview_url; int id, download_count, view_count, like_count; TextView title, downloads, views, likes, user_name; ImageView userImage; private ProgressDialog pDialog; Button dwnld, set; String fileName; //private Window window; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item_detail); Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar); setSupportActionBar(toolbar); title = (TextView) findViewById(R.id.imageTitle); downloads = (TextView) findViewById(R.id.downloads); views = (TextView) findViewById(R.id.views); likes = (TextView) findViewById(R.id.likes); user_name = (TextView) findViewById(R.id.user_name); userImage = (ImageView) findViewById(R.id.userImage); if (getIntent().getExtras() != null) { id = getIntent().getIntExtra(Constants.IMAGE_ID, 0); download_count = getIntent().getIntExtra(Constants.DOWNLOADS, 0); view_count = getIntent().getIntExtra(Constants.VIEWS, 0); like_count = getIntent().getIntExtra(Constants.LIKES, 0); tags = getIntent().getStringExtra(Constants.TAGS); String[] tagsList = tags.split(","); image_title = tagsList[0]; image_pixabay_link = getIntent().getStringExtra(Constants.PIXABAY_PAGE_URL); user_image_url = getIntent().getStringExtra(Constants.USER_IMAGE_URL); user = getIntent().getStringExtra(Constants.USER); web_format_url = getIntent().getStringExtra(Constants.WEB_FORMAT_URL); preview_url = getIntent().getStringExtra(Constants.PREVIEW_URL); String splitted[] = preview_url.split("/"); fileName = splitted[splitted.length - 1]; //Toast.makeText(this, fileName, Toast.LENGTH_SHORT).show(); } title.setText(image_title); downloads.setText(String.valueOf(download_count)); views.setText(String.valueOf(view_count)); likes.setText(String.valueOf(like_count)); user_name.setText(user); dwnld = (Button) findViewById(R.id.dwnld); set = (Button) findViewById(R.id.set_as_wallpaper); Glide.with(this).load(user_image_url) .crossFade() .thumbnail(0.5f) .placeholder(R.mipmap.ic_launcher) .error(R.mipmap.ic_launcher) .bitmapTransform(new CircleTransform(this)) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(userImage); //window = getWindow(); collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own detail action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); // Show the Up button in the action bar. ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } final ImageView image = (ImageView) findViewById(R.id.image); Glide.with(getApplicationContext()).load(getIntent().getStringExtra(Constants.WEB_FORMAT_URL)).crossFade() .diskCacheStrategy(DiskCacheStrategy.ALL).into(image); pDialog = new ProgressDialog(ItemDetailActivity.this); pDialog.setMessage("Downloading Image. Please wait..."); pDialog.setIndeterminate(true); pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pDialog.setCancelable(true); dwnld.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!(new File(Environment.getExternalStorageDirectory().toString() + "/WallTime/" + fileName).exists())) { new DownloadFileFromURL(getApplicationContext()).execute(web_format_url); } else { Toast.makeText(ItemDetailActivity.this, "Image Already Downloaded", Toast.LENGTH_SHORT).show(); } } }); /*set.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { File file = new File(Environment.getExternalStorageDirectory().toString() + fileName); if(file.exists()){ File sd = Environment.getExternalStorageDirectory(); File image = new File(sd+fileName, fileName); BitmapFactory.Options bmOptions = new BitmapFactory.Options(); Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions); WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext()); try { wallpaperManager.setBitmap(bitmap); } catch (IOException e) { Toast.makeText(ItemDetailActivity.this, "IOException While Image Setting", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } }else{ new DownloadFileFromURL().execute(user_image_url); } } });*/ } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. For // more details, see the Navigation pattern on Android Design: // http://developer.android.com/design/patterns/navigation.html#up-vs-back Intent intent = new Intent(this, ItemListActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); navigateUpTo(intent); return true; } return super.onOptionsItemSelected(item); } public boolean dir_exists(String dir_path) { boolean ret = false; File dir = new File(dir_path); if (dir.exists() && dir.isDirectory()) ret = true; return ret; } class DownloadFileFromURL extends AsyncTask<String, Integer, String> { private Context context; private PowerManager.WakeLock mWakeLock; public DownloadFileFromURL(Context context) { this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); // take CPU lock to prevent CPU from going off if the user // presses the power button during download PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName()); mWakeLock.acquire(); pDialog.show(); } @Override protected String doInBackground(String... sUrl) { //File extStore = Environment.getExternalStorageDirectory(); InputStream input = null; OutputStream output = null; HttpURLConnection connection = null; try { URL url = new URL(sUrl[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); // expect HTTP 200 OK, so we don't mistakenly save error report // instead of the file if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage(); } // this will be useful to display download percentage // might be -1: server did not report the length int fileLength = connection.getContentLength(); // download the file input = connection.getInputStream(); String dir_path = Environment.getExternalStorageDirectory() + "/WallTime"; if (!dir_exists(dir_path)) { File directory = new File(dir_path); directory.mkdirs(); } output = new FileOutputStream(dir_path + "/" + fileName); byte data[] = new byte[4096]; long total = 0; int count; while ((count = input.read(data)) != -1) { // allow canceling with back button if (isCancelled()) { input.close(); return null; } total += count; // publishing the progress.... if (fileLength > 0) // only if total length is known publishProgress((int) (total * 100 / fileLength)); output.write(data, 0, count); } } catch (Exception e) { return e.toString(); } finally { try { if (output != null) output.close(); if (input != null) input.close(); } catch (IOException ignored) { } if (connection != null) connection.disconnect(); } return null; } /** * Updating progress bar */ protected void onProgressUpdate(Integer... progress) { super.onProgressUpdate(progress); // if we get here, length is known, now set indeterminate to false pDialog.setIndeterminate(false); pDialog.setMax(100); pDialog.setProgress(progress[0]); } @Override protected void onPostExecute(String result) { // dismiss the dialog after the file was downloaded mWakeLock.release(); pDialog.dismiss(); if (result != null) { Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show(); } else { Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show(); File folder = new File(Environment.getExternalStorageDirectory() + "/WallTime"); File allFiles[] = folder.listFiles(); for (File allFile : allFiles) { new SingleMediaScanner(ItemDetailActivity.this, allFile); } } } } }
package com.averi.worldscribe.activities; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.averi.worldscribe.ArticleTextField; import com.averi.worldscribe.Category; import com.averi.worldscribe.Membership; import com.averi.worldscribe.R; import com.averi.worldscribe.adapters.MembersAdapter; import com.averi.worldscribe.utilities.ExternalDeleter; import com.averi.worldscribe.utilities.ExternalWriter; import com.averi.worldscribe.utilities.IntentFields; import com.averi.worldscribe.views.ArticleSectionCollapser; import com.averi.worldscribe.views.BottomBar; import java.util.ArrayList; public class GroupActivity extends ArticleActivity { public static final int RESULT_NEW_MEMBER = 300; private RecyclerView membersList; private Button addMemberButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); membersList = (RecyclerView) findViewById(R.id.recyclerMembers); addMemberButton = (Button) findViewById(R.id.buttonAddMember); addMemberButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addMember(); } }); } @Override protected int getLayoutResourceID() { return R.layout.activity_group; } @Override protected ImageView getImageView() { return (ImageView) findViewById(R.id.imageGroup); } @Override protected BottomBar getBottomBar() { return (BottomBar) findViewById(R.id.bottomBar); } @Override protected RecyclerView getConnectionsRecycler() { return (RecyclerView) findViewById(R.id.recyclerConnections); } @Override protected Button getAddConnectionButton() { return (Button) findViewById(R.id.buttonAddConnection); } @Override protected RecyclerView getSnippetsRecycler() { return (RecyclerView) findViewById(R.id.recyclerSnippets); } @Override protected Button getAddSnippetButton() { return (Button) findViewById(R.id.buttonAddSnippet); } @Override protected ArrayList<ArticleTextField> getTextFields() { Resources resources = getResources(); ArrayList<ArticleTextField> textFields = new ArrayList<>(); textFields.add(new ArticleTextField(resources.getString(R.string.mandateText), (EditText) findViewById(R.id.editMandate), this, getWorldName(), Category.Group, getArticleName())); textFields.add(new ArticleTextField(resources.getString(R.string.historyHint), (EditText) findViewById(R.id.editHistory), this, getWorldName(), Category.Group, getArticleName())); return textFields; } @Override protected TextView getGeneralInfoHeader() { return (TextView) findViewById(R.id.textGeneralInfo); } @Override protected ViewGroup getGeneralInfoLayout() { return (LinearLayout) findViewById(R.id.linearGeneralInfo); } @Override protected TextView getConnectionsHeader() { return (TextView) findViewById(R.id.textConnections); } @Override protected ViewGroup getConnectionsLayout() { return (LinearLayout) findViewById(R.id.linearConnections); } @Override protected TextView getSnippetsHeader() { return (TextView) findViewById(R.id.textSnippets); } @Override protected ViewGroup getSnippetsLayout() { return (LinearLayout) findViewById(R.id.linearSnippets); } @Override protected void onResume() { super.onResume(); populateMembers(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case RESULT_NEW_MEMBER: if (resultCode == RESULT_OK) { Membership newMembership = new Membership(); newMembership.worldName = getWorldName(); newMembership.groupName = getArticleName(); newMembership.memberName = data.getStringExtra(IntentFields.ARTICLE_NAME); Intent editMembershipIntent = new Intent(this, EditMembershipActivity.class); editMembershipIntent.putExtra(IntentFields.MEMBERSHIP, newMembership); startActivity(editMembershipIntent); } } } @Override protected void addSectionCollapsers() { TextView membersHeader = (TextView) findViewById(R.id.textMembers); membersHeader.setOnClickListener(new ArticleSectionCollapser(this, membersHeader, (LinearLayout) findViewById(R.id.linearMembers))); super.addSectionCollapsers(); } private void populateMembers() { membersList.setLayoutManager(new LinearLayoutManager(this)); membersList.setAdapter(new MembersAdapter(this, getWorldName(), getArticleName())); } /** * Opens SelectArticleActivity so the user can select a new Member to add to this Group. */ private void addMember() { Intent selectGroupIntent = new Intent(this, SelectArticleActivity.class); MembersAdapter membersAdapter = (MembersAdapter) membersList.getAdapter(); selectGroupIntent.putExtra(IntentFields.WORLD_NAME, getWorldName()); selectGroupIntent.putExtra(IntentFields.CATEGORY, Category.Person); selectGroupIntent.putExtra(IntentFields.MAIN_ARTICLE_CATEGORY, Category.Group); selectGroupIntent.putExtra(IntentFields.MAIN_ARTICLE_NAME, getArticleName()); selectGroupIntent.putExtra(IntentFields.EXISTING_LINKS, membersAdapter.getLinkedArticleList()); startActivityForResult(selectGroupIntent, RESULT_NEW_MEMBER); } @Override protected void deleteArticle() { if (removeAllMembers()) { super.deleteArticle(); } else { Toast.makeText(this, getString(R.string.deleteArticleError), Toast.LENGTH_SHORT).show(); } } /** * Deletes all Memberships to this Group. * @return True if all Memberships were deleted successfully; false otherwise. */ private boolean removeAllMembers() { boolean membersWereRemoved = true; ArrayList<Membership> allMemberships = ( (MembersAdapter) membersList.getAdapter()).getMemberships(); Membership membership; int index = 0; while ((index < allMemberships.size()) && (membersWereRemoved)) { membership = allMemberships.get(index); membersWereRemoved = ExternalDeleter.deleteMembership(this, membership); index++; } return membersWereRemoved; } @Override protected boolean renameArticle(String newName) { boolean renameWasSuccessful = false; if (renameGroupInMemberships(newName)) { renameWasSuccessful = super.renameArticle(newName); } else { Toast.makeText(this, R.string.renameArticleError, Toast.LENGTH_SHORT).show(); } return renameWasSuccessful; } /** * <p> * Updates all Memberships to this Group to reflect a new Group name. * </p> * <p> * If one or more Memberships failed to be updated, an error message is displayed. * </p> * @param newName The new name for this Group. * @return True if all Memberships updated successfully; false otherwise. */ private boolean renameGroupInMemberships(String newName) { boolean membershipsWereUpdated = true; MembersAdapter adapter = (MembersAdapter) membersList.getAdapter(); ArrayList<Membership> memberships = adapter.getMemberships(); int index = 0; Membership membership; while ((index < memberships.size()) && (membershipsWereUpdated)) { membership = memberships.get(index); if (ExternalWriter.renameGroupInMembership(this, membership, newName)) { membership.groupName = newName; } else { membershipsWereUpdated = false; } index++; } return membershipsWereUpdated; } }
package com.averi.worldscribe.utilities; import android.content.Context; import android.net.Uri; import android.os.Environment; import com.averi.worldscribe.Category; import com.averi.worldscribe.R; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOError; import java.io.IOException; import java.io.PrintWriter; public final class ExternalWriter { public static final int IMAGE_BYTE_SIZE = 1024; // public static boolean createAppDirectory() { // boolean directoryExists = true; // File appDirectory = new File(Environment.getExternalStorageDirectory(), APP_DIRECTORY_NAME); // Log.d("WorldScribe", appDirectory.getAbsolutePath()); // if (externalStorageIsWritable()) { // if (!(appDirectory.exists())) { // directoryExists = appDirectory.mkdirs(); // return directoryExists; private static boolean externalStorageIsWritable() { String state = Environment.getExternalStorageState(); return (Environment.MEDIA_MOUNTED.equals(state)); } public static boolean createWorldDirectory(Context context, String worldName) { boolean directoryWasCreated = true; File worldDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + FileRetriever.APP_DIRECTORY_NAME + "/", worldName); directoryWasCreated = worldDirectory.mkdirs(); if (directoryWasCreated) { directoryWasCreated = createArticleTypeDirectories(context, worldDirectory); // If one or more subfolders couldn't be created, delete the World folder so that // subsequent attempts can start building the World folder again from scratch. if (!(directoryWasCreated)) { // Delete the World directory. } } return directoryWasCreated; } private static boolean createArticleTypeDirectories(Context context, File worldDirectory) { boolean directoriesWereCreated = true; for (Category category : Category.values()) { File articleFolder = new File(worldDirectory.getAbsolutePath(), category.pluralName(context)); if (!(articleFolder.mkdirs())) { directoriesWereCreated = false; } } return directoriesWereCreated; } /** * Create a directory for a new Article. * Note that this does not overwrite an existing directory, so make sure to check before calling * this method. * @param context The context calling this method. * @param worldName The name of the World where the Article belongs. * @param category The {@link Category} the Article belongs to. * @param articleName The name of the new Article. * @return True if the directory was created successfully; false otherwise. */ public static boolean createArticleDirectory(Context context, String worldName, Category category, String articleName) { Boolean successful = true; successful = ( (FileRetriever.getConnectionCategoryDirectory(context, worldName, category, articleName, Category.Person).mkdirs()) && (FileRetriever.getConnectionCategoryDirectory(context, worldName, category, articleName, Category.Group).mkdirs()) && (FileRetriever.getConnectionCategoryDirectory(context, worldName, category, articleName, Category.Place).mkdirs()) && (FileRetriever.getConnectionCategoryDirectory(context, worldName, category, articleName, Category.Item).mkdirs()) && (FileRetriever.getConnectionCategoryDirectory(context, worldName, category, articleName, Category.Concept).mkdirs()) && (FileRetriever.getSnippetsDirectory(context, worldName, category, articleName).mkdirs()) ); if (successful) { if (category == Category.Person) { successful = ((FileRetriever.getMembershipsDirectory( context, worldName, articleName).mkdirs()) && (FileRetriever.getResidencesDirectory( context, worldName, articleName).mkdirs())); } else if (category == Category.Group) { successful = FileRetriever.getMembersDirectory( context, worldName, articleName).mkdirs(); } else if (category == Category.Place) { successful = FileRetriever.getResidentsDirectory( context, worldName, articleName).mkdirs(); } } // TODO: If any of the folders failed to be created, delete all other folders created during // the process. return successful; } /** * Saves a String to a text file within an Article's directory. * @param context The Context calling this method. * @param worldName The name of the world the Article belongs to. * @param category The name of the Category the Article belongs to. * @param articleName The name of the Article whose directory will possess the text file. * @param fileName The name of the text file that will be written to, with the file extension * omitted. * @param contents The String that will be saved in a text file. * @return True if the String was saved successfully; false if an I/O error occurs. */ public static boolean writeStringToArticleFile(Context context, String worldName, Category category, String articleName, String fileName, String contents) { Boolean result = true; try { PrintWriter writer = new PrintWriter(FileRetriever.getArticleFile(context, worldName, category, articleName, fileName + ExternalReader.TEXT_FIELD_FILE_EXTENSION)); writer.println(contents); writer.close(); } catch (IOException error) { result = false; } return result; } /** * Saves an image to a specific Article's directory. * If the Article already has an image, it will be overwritten. * @param context The Context calling this method. * @param worldName The name of the world the Article belongs to. * @param category The name of the Category the Article belongs to. * @param articleName The name of the Article whose image will be saved. * @param imageUri The URI to the new image's original location. * @return True if the image was saved successfully; false otherwise. */ public static boolean saveArticleImage(Context context, String worldName, Category category, String articleName, Uri imageUri) { Boolean result = true; String sourceFilename= imageUri.getPath(); String destinationFilename = FileRetriever.getArticleFile(context, worldName, category, articleName, context.getString(R.string.imageFileName)).getAbsolutePath(); destinationFilename += ExternalReader.IMAGE_FILE_EXTENSION; BufferedInputStream bufferedInputStream = null; BufferedOutputStream bufferedOutputStream = null; try { bufferedInputStream = new BufferedInputStream(new FileInputStream(sourceFilename)); bufferedOutputStream = new BufferedOutputStream( new FileOutputStream(destinationFilename, false)); byte[] buf = new byte[IMAGE_BYTE_SIZE]; bufferedInputStream.read(buf); do { bufferedOutputStream.write(buf); } while (bufferedInputStream.read(buf) != -1); } catch (IOException e) { result = false; } finally { try { if (bufferedInputStream != null) bufferedInputStream.close(); if (bufferedOutputStream != null) bufferedOutputStream.close(); } catch (IOException e) { } } return result; } /** * Saves the relation between an Article and one of its connected Articles. * @param context The Context calling this method. * @param worldName The name of the world the Article belongs to. * @param category The name of the Category the Article belongs to. * @param articleName The name of the Article who possesses the specified Connection. * @param connectedArticleCategory * @param connectedArticleName * @param relation A description of how the specified Article is related to the connected * Article. * @return True if the relation was saved successfully; false an I/O error occurs. */ public static boolean saveConnectionRelation(Context context, String worldName, Category category, String articleName, Category connectedArticleCategory, String connectedArticleName, String relation) { Boolean successful = true; try { PrintWriter writer = new PrintWriter(FileRetriever.getConnectionRelationFile( context, worldName, category, articleName, connectedArticleCategory, connectedArticleName)); writer.println(relation); writer.close(); } catch (IOException error) { successful = false; } return successful; } /** * Saves a String as a Snippet's new contents. * @param context The Context calling this method. * @param worldName The name of the world the Article belongs to. * @param category The name of the Category the Article belongs to. * @param articleName The name of the Article who possesses the specified Snippet. * @param snippetName The name of the Snippet that will be written to. * @param contents The String that will be saved to the Snippet. * @return True if the String was saved successfully; false if an I/O error occurs. */ public static boolean writeSnippetContents(Context context, String worldName, Category category, String articleName, String snippetName, String contents) { Boolean result = true; try { PrintWriter writer = new PrintWriter(FileRetriever.getSnippetFile(context, worldName, category, articleName, snippetName)); writer.println(contents); writer.close(); } catch (IOException error) { result = false; } return result; } }
package com.chariotinstruments.markets; import java.util.ArrayList; public class CalcStochastics { private MarketDay marketDay; private ArrayList<MarketCandle> marketCandles; private double lowPrice; private double highPrice; private double curPrice; private ArrayList<Double> kListFast; private ArrayList<Double> kListSlow; public CalcStochastics(MarketDay marDay){ marketDay = marDay; marketCandles = marketDay.getMarketCandles(); kListFast = new ArrayList<Double>(); kListSlow = new ArrayList<Double>(); } public void startCalc(){ calcFastK(); calcSlowK(); } public StochasticHelper getLowHighCurrent(int startIndex, int stopIndex){ StochasticHelper stochHelper = new StochasticHelper(); stochHelper.setCurPrice(marketCandles.get(stopIndex).getClose()); double curLow = 0.0; double curHigh = 0.0; //seed stochHelper.setLowPrice(marketCandles.get(startIndex).getLow()); stochHelper.setHighPrice(marketCandles.get(startIndex).getHigh()); stochHelper.setCurPrice(marketCandles.get(stopIndex).getClose()); for (int i = startIndex + 1; i < stopIndex; i++){ //note that I'm not including the last value since it's the current price added in PhaseOneControl. curLow = marketCandles.get(i).getLow(); curHigh = marketCandles.get(i).getHigh(); if(curLow < stochHelper.getLowprice()){ stochHelper.setLowPrice(curLow); } if(curHigh > stochHelper.getHighPrice()){ stochHelper.setHighPrice(curHigh); } //test if(stopIndex == marketCandles.size()-1){ System.out.println("cur candle: " + curLow); System.out.println("Low: "+stochHelper.getLowprice()); } } return stochHelper; } public void calcFastK(){ double curFastK; for(int i = 15; i < marketCandles.size(); i++){ StochasticHelper stochHelper = new StochasticHelper(); stochHelper = getLowHighCurrent(i-15, i); curFastK = ((stochHelper.getCurPrice() - stochHelper.getLowprice()) / (stochHelper.getHighPrice() - stochHelper.getLowprice())) * 100; kListFast.add(curFastK); } System.out.println(kListFast.get(kListFast.size()-2)); } public void calcSlowK(){ double curSlowK; for(int i = 2; i < kListFast.size(); i++){ int j = i; curSlowK = 0.0; while(j >= i-2){ curSlowK += kListFast.get(j); j } curSlowK = curSlowK / 3; kListSlow.add(curSlowK); } } public class StochasticHelper{ private double highPrice; private double lowPrice; private double curPrice; public StochasticHelper(){ highPrice = 0.0; lowPrice = 0.0; curPrice = 0.0; } public void setHighPrice(double highIn){ highPrice = highIn; } public double getHighPrice(){ return highPrice; } public void setLowPrice(double lowIn){ lowPrice = lowIn; } public double getLowprice(){ return lowPrice; } public void setCurPrice(double curIn){ curPrice = curIn; } public double getCurPrice(){ return curPrice; } } }
package com.grarak.kerneladiutor.views; import android.content.Context; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.support.v7.app.AlertDialog; import android.support.v7.widget.AppCompatImageView; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.NativeExpressAdView; import com.grarak.kerneladiutor.R; import com.grarak.kerneladiutor.utils.Prefs; import com.grarak.kerneladiutor.utils.Utils; import com.grarak.kerneladiutor.utils.ViewUtils; import com.squareup.picasso.Picasso; import com.squareup.picasso.Target; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class AdNativeExpress extends LinearLayout { public static final String ADS_FETCH = "https://raw.githubusercontent.com/Grarak/KernelAdiutor/master/ads/ads.json"; private static final int MAX_WIDTH = 1200; private static final int MIN_HEIGHT = 132; private boolean mNativeLoaded; private boolean mNativeLoading; private boolean mNativeFailedLoading; private boolean mGHLoading; private boolean mGHLoaded; private View mProgress; private View mAdText; private FrameLayout mNativeAdLayout; private NativeExpressAdView mNativeExpressAdView; private AppCompatImageView mGHImage; public AdNativeExpress(Context context) { this(context, null); } public AdNativeExpress(Context context, AttributeSet attrs) { this(context, attrs, 0); } public AdNativeExpress(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); LayoutInflater.from(context).inflate(R.layout.ad_native_express_view, this); mNativeAdLayout = (FrameLayout) findViewById(R.id.ad_layout); mProgress = findViewById(R.id.progress); mAdText = findViewById(R.id.ad_text); mGHImage = (AppCompatImageView) findViewById(R.id.gh_image); findViewById(R.id.remove_ad).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ViewUtils.dialogDonate(v.getContext()).show(); } }); mNativeExpressAdView = new NativeExpressAdView(context); mNativeExpressAdView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); mNativeExpressAdView.setAdUnitId(getContext().getString(Utils.DARK_THEME ? R.string.native_express_id_dark : R.string.native_express_id_light)); mNativeExpressAdView.setAdListener(new AdListener() { @Override public void onAdFailedToLoad(int i) { super.onAdFailedToLoad(i); mNativeLoading = false; mNativeLoaded = false; mNativeFailedLoading = true; loadGHAd(); } @Override public void onAdLoaded() { super.onAdLoaded(); mNativeLoaded = true; mNativeLoading = false; mNativeFailedLoading = false; mProgress.setVisibility(GONE); mNativeAdLayout.addView(mNativeExpressAdView); } }); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); int width; if (mNativeLoading || (mNativeLoaded && !mNativeFailedLoading) || (!mNativeLoaded && mNativeFailedLoading) || (width = mNativeAdLayout.getWidth()) == 0) { return; } float deviceDensity = getResources().getDisplayMetrics().density; if (deviceDensity > 0) { loadNativeAd(width, deviceDensity); } } private void loadNativeAd(int width, float deviceDensity) { float adWidth = width / deviceDensity; if (adWidth > MAX_WIDTH) adWidth = MAX_WIDTH; mNativeExpressAdView.setAdSize(new AdSize((int) adWidth, MIN_HEIGHT)); mNativeLoading = true; mNativeExpressAdView.loadAd(new AdRequest.Builder().build()); } public void loadGHAd() { if (!mNativeFailedLoading || mGHLoading || mGHLoaded) { return; } mGHLoading = true; GHAds ghAds = GHAds.fromCache(getContext()); List<GHAds.GHAd> ghAdList; if (ghAds.readable() && (ghAdList = ghAds.getAllAds()) != null) { GHAds.GHAd ad = null; int min = -1; for (GHAds.GHAd ghAd : ghAdList) { int shown = Prefs.getInt(ghAd.getName() + "_shown", 0, getContext()); if (min < 0 || shown < min) { min = shown; ad = ghAd; } } final String name = ad.getName(); final String link = ad.getLink(); final int totalShown = min + 1; Picasso.with(getContext()).load(ad.getBanner()).into(new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { mGHImage.setVisibility(VISIBLE); mProgress.setVisibility(GONE); mAdText.setVisibility(GONE); mGHImage.setImageBitmap(bitmap); Prefs.saveInt(name + "_shown", totalShown, getContext()); mGHLoaded = true; mGHLoading = false; } @Override public void onBitmapFailed(Drawable errorDrawable) { mGHImage.setVisibility(GONE); mProgress.setVisibility(GONE); mAdText.setVisibility(VISIBLE); mGHLoaded = false; mGHLoading = false; } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { mGHImage.setVisibility(GONE); mProgress.setVisibility(VISIBLE); } }); mGHImage.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(getContext()).setTitle(R.string.warning) .setMessage(R.string.gh_ad) .setPositiveButton(R.string.open_ad_anyway, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Utils.launchUrl(link, getContext()); } }).show(); } }); } else { mGHImage.setVisibility(GONE); mProgress.setVisibility(GONE); mAdText.setVisibility(VISIBLE); } } public void resume() { mNativeExpressAdView.resume(); } public void pause() { mNativeExpressAdView.pause(); } public void destroy() { mNativeExpressAdView.destroy(); } public static class GHAds { private final String mJson; private JSONArray mAds; public GHAds(String json) { mJson = json; if (json == null || json.isEmpty()) return; try { mAds = new JSONArray(json); } catch (JSONException ignored) { } } private static GHAds fromCache(Context context) { return new GHAds(Utils.readFile(context.getFilesDir() + "/ghads.json", false)); } public void cache(Context context) { Utils.writeFile(context.getFilesDir() + "/ghads.json", mJson, false, false); } private List<GHAd> getAllAds() { List<GHAd> list = new ArrayList<>(); for (int i = 0; i < mAds.length(); i++) { try { list.add(new GHAd(mAds.getJSONObject(i))); } catch (JSONException ignored) { return null; } } return list; } public boolean readable() { return mAds != null; } private static class GHAd { private final JSONObject mAd; private GHAd(JSONObject ad) { mAd = ad; } private String getLink() { return getString("link"); } private String getBanner() { return getString("banner"); } private String getName() { return getString("name"); } private String getString(String key) { try { return mAd.getString(key); } catch (JSONException ignored) { return null; } } } } }
package tankattack; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.*; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.stage.Stage; /** * * @author Ruslan */ public class TankAttack extends Application { public static final double gameWidth = 600; public static final double gameHeight = 600; private static final int NUM_FRAMES_PER_SECOND = 60; private Stage currStage; private World currWorld; private Scene currScene; @Override public void start(Stage primaryStage) { initTankAttack(primaryStage); displayCurrentScene(); primaryStage.setTitle("TANK ATTACK"); primaryStage.show(); setupAndLaunchGameLoop(); } private void setupAndLaunchGameLoop() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } private void initTankAttack(Stage stage) { currStage = stage; currWorld = new FirstWorld(stage); currScene = currWorld.createScene(); } private void displayCurrentScene() { currStage.setScene(currScene); } public void tellStageToShowScene(Scene scene) { currStage.setScene(scene); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
package controllers; import javax.inject.Inject; import javax.xml.namespace.QName; import com.fasterxml.jackson.databind.JsonNode; import com.mysema.query.Tuple; import com.mysema.query.sql.SQLQuery; import com.mysema.query.sql.SQLSubQuery; import com.mysema.query.support.Expressions; import com.mysema.query.types.Expression; import com.mysema.query.types.QTuple; import com.mysema.query.types.expr.BooleanExpression; import com.mysema.query.types.expr.NumberExpression; import com.mysema.query.types.path.NumberPath; import com.mysema.query.types.path.StringPath; import com.mysema.query.types.template.BooleanTemplate; import nl.idgis.dav.model.Resource; import nl.idgis.dav.model.ResourceDescription; import nl.idgis.dav.model.ResourceProperties; import nl.idgis.dav.model.DefaultResource; import nl.idgis.dav.model.DefaultResourceDescription; import nl.idgis.dav.model.DefaultResourceProperties; import nl.idgis.publisher.database.QSourceDatasetVersion; import nl.idgis.publisher.database.QSourceDatasetVersionColumn; import nl.idgis.publisher.metadata.MetadataDocument; import nl.idgis.publisher.metadata.MetadataDocumentFactory; import nl.idgis.publisher.xml.exceptions.NotFound; import nl.idgis.publisher.xml.exceptions.QueryFailure; import play.Logger; import play.api.mvc.Handler; import play.api.mvc.RequestHeader; import play.libs.Json; import play.mvc.Controller; import play.mvc.Result; import util.MetadataConfig; import util.QueryDSL; import util.Security; import util.QueryDSL.Transaction; import static nl.idgis.publisher.database.QDataset.dataset; import static nl.idgis.publisher.database.QDatasetColumn.datasetColumn; import static nl.idgis.publisher.database.QSourceDataset.sourceDataset; import static nl.idgis.publisher.database.QSourceDatasetMetadata.sourceDatasetMetadata; import static nl.idgis.publisher.database.QSourceDatasetMetadataAttachment.sourceDatasetMetadataAttachment; import static nl.idgis.publisher.database.QSourceDatasetVersion.sourceDatasetVersion; import static nl.idgis.publisher.database.QSourceDatasetVersionColumn.sourceDatasetVersionColumn; import static nl.idgis.publisher.database.QPublishedServiceDataset.publishedServiceDataset; import static nl.idgis.publisher.database.QPublishedService.publishedService; import static nl.idgis.publisher.database.QEnvironment.environment; import static nl.idgis.publisher.database.QDatasetCopy.datasetCopy; import static nl.idgis.publisher.database.QDatasetView.datasetView; import java.io.IOException; import java.sql.Timestamp; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.stream.Collectors; public class DatasetMetadata extends AbstractMetadata { private final MetadataDocumentFactory mdf; private final Pattern urlPattern; private final DatasetQueryBuilder dqb; @Inject public DatasetMetadata(MetadataConfig config, QueryDSL q, DatasetQueryBuilder dqb, Security s) throws Exception { this(config, q, dqb, s, new MetadataDocumentFactory(), "/"); } public DatasetMetadata(MetadataConfig config, QueryDSL q, DatasetQueryBuilder dqb, Security s, MetadataDocumentFactory mdf, String prefix) { super(config, q, s, prefix); this.mdf = mdf; this.dqb = dqb; urlPattern = Pattern.compile(".*/(.*)(\\?.*)?$"); } @Override public DatasetMetadata withPrefix(String prefix) { return new DatasetMetadata(config, q, dqb, s, mdf, prefix); } @Override public Optional<Resource> resource(String name) { return getId(name).flatMap(id -> q.withTransaction(tx -> { Optional<Resource> optionalDataset = datasetResource(id, tx); if(optionalDataset.isPresent()) { return optionalDataset; } else { if(config.getIncludeSourceDatasetMetadata()) { return sourceDatasetResource(id, tx); } else { Optional<Resource> emptyOptional = Optional.empty(); return emptyOptional; } } })); } private Optional<Resource> sourceDatasetResource(String id, Transaction tx) { return Optional.ofNullable(dqb.fromSourceDataset(tx) .where(sourceDataset.metadataFileIdentification.eq(id) .and(sourceDataset.deleteTime.isNull())) .singleResult( sourceDataset.metadataIdentification, sourceDatasetMetadata.sourceDatasetId, sourceDatasetMetadata.document)) .map(datasetTuple -> tupleToDatasetResource( tx, datasetTuple, datasetTuple.get(sourceDatasetMetadata.sourceDatasetId), null, id, datasetTuple.get(sourceDataset.metadataIdentification))); } private Optional<Resource> datasetResource(String id, Transaction tx) throws Exception { return Optional.ofNullable(dqb.fromDataset(tx) .where(dataset.metadataFileIdentification.eq(id) .and(sourceDataset.deleteTime.isNull())) .singleResult( dataset.id, dataset.metadataIdentification, sourceDatasetMetadata.sourceDatasetId, sourceDatasetMetadata.document)) .map(datasetTuple -> tupleToDatasetResource( tx, datasetTuple, datasetTuple.get(sourceDatasetMetadata.sourceDatasetId), datasetTuple.get(dataset.id), id, datasetTuple.get(dataset.metadataIdentification))); } private List<Tuple> datasetColumnAliases(Transaction tx, Expression<?> datasetRel, NumberPath<Integer> datasetRelId, StringPath datasetRelName, int datasetId) { final QSourceDatasetVersionColumn sourceDatasetVersionColumnSub = new QSourceDatasetVersionColumn("source_dataset_version_column_sub"); final QSourceDatasetVersion sourceDatasetVersionSub = new QSourceDatasetVersion("source_dataset_version_sub"); return tx.query().from(datasetRel) .join(dataset).on(dataset.id.eq(datasetRelId)) .join(sourceDatasetVersionColumn).on(sourceDatasetVersionColumn.name.eq(datasetRelName)) .join(sourceDatasetVersion).on(sourceDatasetVersion.id.eq(sourceDatasetVersionColumn.sourceDatasetVersionId) .and(dataset.sourceDatasetId.eq(sourceDatasetVersion.sourceDatasetId))) .where(datasetRelId.eq(datasetId)) .where(new SQLSubQuery().from(sourceDatasetVersionColumnSub) .join(sourceDatasetVersionSub).on(sourceDatasetVersionSub.id.eq(sourceDatasetVersionColumnSub.sourceDatasetVersionId)) .where(sourceDatasetVersionColumnSub.name.eq(sourceDatasetVersionColumn.name)) .where(sourceDatasetVersionColumnSub.sourceDatasetVersionId.gt(sourceDatasetVersionColumn.sourceDatasetVersionId)) .where(sourceDatasetVersionSub.sourceDatasetId.eq(dataset.sourceDatasetId)) .notExists()) .where(sourceDatasetVersionColumn.alias.isNotNull()) .orderBy(sourceDatasetVersionColumn.index.desc()) .list(sourceDatasetVersionColumn.name, sourceDatasetVersionColumn.alias); } private Resource tupleToDatasetResource(Transaction tx, Tuple datasetTuple, int sourceDatasetId, Integer datasetId, String fileIdentifier, String datasetIdentifier) { final QSourceDatasetVersion sourceDatasetVersionSub = new QSourceDatasetVersion("source_dataset_version_sub"); try { MetadataDocument metadataDocument = mdf.parseDocument(datasetTuple.get(sourceDatasetMetadata.document)); metadataDocument.removeStylesheet(); stylesheet("datasets").ifPresent(metadataDocument::setStylesheet); metadataDocument.setDatasetIdentifier(datasetIdentifier); metadataDocument.setFileIdentifier(fileIdentifier); final String physicalName = tx.query().from(sourceDatasetVersion) .where(sourceDatasetVersion.sourceDatasetId.eq(sourceDatasetId) .and(sourceDatasetVersion.id.eq(new SQLSubQuery().from(sourceDatasetVersionSub) .where(sourceDatasetVersionSub.sourceDatasetId.eq(sourceDatasetId)) .unique(sourceDatasetVersionSub.id.max())))) .singleResult(sourceDatasetVersion.physicalName); try { final String existingAlternateTitle = metadataDocument.getDatasetAlternateTitle(); if(physicalName != null) { if(existingAlternateTitle.toLowerCase().trim().contains(physicalName.toLowerCase().trim()) || physicalName.toLowerCase().trim().contains(existingAlternateTitle.toLowerCase().trim())) { // do nothing } else { metadataDocument.setDatasetAlternateTitle(existingAlternateTitle + " " + physicalName); } } } catch(NotFound nf) { metadataDocument.addDatasetAlternateTitle(physicalName); } if(!s.isTrusted()) { metadataDocument.removeAdditionalPointOfContacts(); } Map<String, Integer> attachments = tx.query().from(sourceDatasetMetadataAttachment) .where(sourceDatasetMetadataAttachment.sourceDatasetId.eq(sourceDatasetId)) .list( sourceDatasetMetadataAttachment.id, sourceDatasetMetadataAttachment.identification) .stream() .collect(Collectors.toMap( t -> t.get(sourceDatasetMetadataAttachment.identification), t -> t.get(sourceDatasetMetadataAttachment.id))); for(String supplementalInformation : metadataDocument.getSupplementalInformation()) { int separator = supplementalInformation.indexOf("|"); if(separator != -1) { String type = supplementalInformation.substring(0, separator); String url = supplementalInformation.substring(separator + 1).trim().replace('\\', '/'); String fileName; Matcher urlMatcher = urlPattern.matcher(url); if(urlMatcher.find()) { fileName = urlMatcher.group(1); } else { fileName = "download"; } if(attachments.containsKey(supplementalInformation)) { String updatedSupplementalInformation = type + "|" + routes.Attachment.get(attachments.get(supplementalInformation).toString(), fileName) .absoluteURL(false, config.getHost()); metadataDocument.updateSupplementalInformation( supplementalInformation, updatedSupplementalInformation); } else { metadataDocument.removeSupplementalInformation(supplementalInformation); } } } List<String> browseGraphics = metadataDocument.getDatasetBrowseGraphics(); for(String browseGraphic : browseGraphics) { if(attachments.containsKey(browseGraphic)) { String url = browseGraphic.trim().replace('\\', '/'); String fileName; Matcher urlMatcher = urlPattern.matcher(url); if(urlMatcher.find()) { fileName = urlMatcher.group(1); } else { fileName = "preview"; } String updatedbrowseGraphic = routes.Attachment.get(attachments.get(browseGraphic).toString(), fileName) .absoluteURL(false, config.getHost()); metadataDocument.updateDatasetBrowseGraphic(browseGraphic, updatedbrowseGraphic); } } metadataDocument.removeServiceLinkage(); Consumer<List<Tuple>> columnAliasWriter = columnTuples -> { if(columnTuples.isEmpty()) { return; } StringBuilder textAlias = new StringBuilder("INHOUD ATTRIBUTENTABEL:"); for(Tuple columnTuple : columnTuples) { textAlias .append(" ") .append(columnTuple.get(sourceDatasetVersionColumn.name)) .append(": ") .append(columnTuple.get(sourceDatasetVersionColumn.alias)); } try { metadataDocument.addProcessStep(textAlias.toString()); } catch(NotFound nf) { throw new RuntimeException(nf); } }; if(datasetId == null) { columnAliasWriter.accept( tx.query().from(sourceDatasetVersionColumn) .where(sourceDatasetVersionColumn.sourceDatasetVersionId.eq( new SQLSubQuery().from(sourceDatasetVersion) .where(sourceDatasetVersion.sourceDatasetId.eq(sourceDatasetId)) .unique(sourceDatasetVersion.id.max()))) .where(sourceDatasetVersionColumn.alias.isNotNull()) .orderBy(sourceDatasetVersionColumn.index.desc()) .list(sourceDatasetVersionColumn.name, sourceDatasetVersionColumn.alias)); } else { final QSourceDatasetVersionColumn sourceDatasetVersionColumnSub = new QSourceDatasetVersionColumn("source_dataset_version_column_sub"); List<Tuple> datasetCopyAliases = datasetColumnAliases( tx, datasetCopy, datasetCopy.datasetId, datasetCopy.name, datasetId); if(datasetCopyAliases.isEmpty()) { columnAliasWriter.accept( datasetColumnAliases( tx, datasetView, datasetView.datasetId, datasetView.name, datasetId)); } else { columnAliasWriter.accept(datasetCopyAliases); } SQLQuery serviceQuery = tx.query().from(publishedService) .join(publishedServiceDataset).on(publishedServiceDataset.serviceId.eq(publishedService.serviceId)) .join(environment).on(environment.id.eq(publishedService.environmentId)); if(!s.isTrusted()) { // do not generate links to services with confidential content as these are inaccessible. serviceQuery.where(environment.confidential.isFalse()); } boolean sourceDatasetConfidential = tx.query().from(sourceDataset) .join(sourceDatasetVersion).on(sourceDatasetVersion.sourceDatasetId.eq(sourceDataset.id)) .where(sourceDatasetVersion.id.eq( new SQLSubQuery().from(sourceDatasetVersion) .where(sourceDatasetVersion.sourceDatasetId.eq(sourceDatasetId)) .unique(sourceDatasetVersion.id.max()))) .uniqueResult(sourceDatasetVersion.confidential); String datasetType = tx.query().from(dataset) .join(sourceDataset).on(sourceDataset.id.eq(dataset.sourceDatasetId)) .join(sourceDatasetVersion) .on(sourceDatasetVersion.sourceDatasetId.eq(sourceDataset.id)) .where(sourceDatasetVersion.id.eq(new SQLSubQuery() .from(sourceDatasetVersionSub) .where(sourceDatasetVersionSub.sourceDatasetId.eq(sourceDataset.id)) .unique(sourceDatasetVersionSub.id.max())) .and(dataset.id.eq(datasetId))) .uniqueResult(sourceDatasetVersion.type); if("RASTER".equals(datasetType) && config.getRasterUrlDisplay()) { if(sourceDatasetConfidential) { config.getDownloadUrlPrefixInternal().ifPresent(downloadUrlPrefix -> { try { metadataDocument.addServiceLinkage(downloadUrlPrefix + "raster/" + fileIdentifier, "download", null); } catch(NotFound nf) { throw new RuntimeException(nf); } }); } else { config.getDownloadUrlPrefixExternal().ifPresent(downloadUrlPrefix -> { try { metadataDocument.addServiceLinkage(downloadUrlPrefix + "raster/" + fileIdentifier, "download", null); } catch(NotFound nf) { throw new RuntimeException(nf); } }); } } List<Tuple> serviceTuples = serviceQuery.where(publishedServiceDataset.datasetId.eq(datasetId)) .list( publishedService.content, environment.identification, environment.confidential, environment.url, environment.wmsOnly, publishedServiceDataset.layerName); if(!serviceTuples.isEmpty()) { if("VECTOR".equals(datasetType)) { if(sourceDatasetConfidential) { config.getDownloadUrlPrefixInternal().ifPresent(downloadUrlPrefix -> { if(config.getDownloadUrlDisplay()) { try { metadataDocument.addServiceLinkage(downloadUrlPrefix + "vector/" + fileIdentifier, "download", null); } catch(NotFound nf) { throw new RuntimeException(nf); } } }); } else { config.getDownloadUrlPrefixExternal().ifPresent(downloadUrlPrefix -> { if(config.getDownloadUrlDisplay()) { try { metadataDocument.addServiceLinkage(downloadUrlPrefix + "vector/" + fileIdentifier, "download", null); } catch(NotFound nf) { throw new RuntimeException(nf); } } }); } } } boolean environmentConfidential = true; boolean environmentWmsOnly = false; int serviceTupleIndex = 0; for(int i = 0; i < serviceTuples.size(); i++) { boolean confidential = serviceTuples.get(i).get(environment.confidential); if(!confidential) { environmentConfidential = false; environmentWmsOnly = serviceTuples.get(i).get(environment.wmsOnly); serviceTupleIndex = i; if(!environmentWmsOnly) { break; } } } String lastWMSLinkage = null; String lastWFSLinkage = null; for(int i = 0; i < serviceTuples.size(); i++) { JsonNode serviceInfo = Json.parse(serviceTuples.get(i).get(publishedService.content)); String serviceName = serviceInfo.get("name").asText(); String scopedName = serviceTuples.get(i).get(publishedServiceDataset.layerName); if(config.getViewerUrlDisplay() && i == serviceTupleIndex) { if(environmentConfidential) { config.getViewerUrlSecurePrefix().ifPresent(viewerUrlPrefix -> { try { metadataDocument.addServiceLinkage(viewerUrlPrefix + "/layer/" + serviceName + "/" + scopedName, "website", null); } catch(NotFound nf) { throw new RuntimeException(nf); } }); } else if(environmentWmsOnly) { config.getViewerUrlWmsOnlyPrefix().ifPresent(viewerUrlPrefix -> { try { metadataDocument.addServiceLinkage(viewerUrlPrefix + "/layer/" + serviceName + "/" + scopedName, "website", null); } catch(NotFound nf) { throw new RuntimeException(nf); } }); } else { config.getViewerUrlPublicPrefix().ifPresent(viewerUrlPrefix -> { try { metadataDocument.addServiceLinkage(viewerUrlPrefix + "/layer/" + serviceName + "/" + scopedName, "website", null); } catch(NotFound nf) { throw new RuntimeException(nf); } }); } } String environmentUrl = serviceTuples.get(i).get(environment.url); // we only automatically generate browseGraphics // when none where provided by the source. if(browseGraphics.isEmpty()) { String linkage = getServiceLinkage(environmentUrl, serviceName, ServiceType.WMS); metadataDocument.addDatasetBrowseGraphic(linkage + config.getBrowseGraphicWmsRequest() + scopedName); } boolean wmsOnly = serviceInfo.get("wmsOnly") != null ? serviceInfo.get("wmsOnly").asBoolean() : false; for(ServiceType serviceType : ServiceType.values()) { String linkage = getServiceLinkage(environmentUrl, serviceName, serviceType); String protocol = serviceType.getProtocol(); for(String spatialSchema : metadataDocument.getSpatialSchema()) { if((!wmsOnly && "vector".equals(spatialSchema)) || "OGC:WMS".equals(protocol)) { // only add wms url when linkage hasn't been added already if("OGC:WMS".equals(protocol) && (lastWMSLinkage == null || !linkage.equals(lastWMSLinkage))) { lastWMSLinkage = linkage; metadataDocument.addServiceLinkage(linkage, protocol, scopedName); } // only add wfs url when linkage hasn't been added already if("OGC:WFS".equals(protocol) && (lastWFSLinkage == null || !linkage.equals(lastWFSLinkage))) { lastWFSLinkage = linkage; metadataDocument.addServiceLinkage(linkage, protocol, scopedName); } } } } } } return new DefaultResource("application/xml", metadataDocument.getContent()); } catch(Exception e) { throw new RuntimeException(e); } } @Override public Stream<ResourceDescription> descriptions() { if(config.getIncludeSourceDatasetMetadata()) { return q.withTransaction(tx -> Stream.concat( datasetDescriptions(tx), sourceDatasetDescriptions(tx))); } else { return q.withTransaction(this::datasetDescriptions); } } private Stream<ResourceDescription> sourceDatasetDescriptions(Transaction tx) { return dqb.fromNonPublishedSourceDataset(tx).list( sourceDataset.metadataFileIdentification, sourceDatasetVersion.metadataConfidential, sourceDatasetVersion.revision, sourceDatasetMetadata.document).stream() .map(tuple -> tupleToDatasetDescription(tuple, sourceDataset.metadataFileIdentification, false)); } private Stream<ResourceDescription> datasetDescriptions(Transaction tx) { return dqb.fromPublishedDataset(tx).list( dataset.metadataFileIdentification, sourceDatasetVersion.metadataConfidential, sourceDatasetVersion.revision, sourceDatasetMetadata.document).stream() .map(tuple -> tupleToDatasetDescription(tuple, dataset.metadataFileIdentification, true)); } private ResourceDescription tupleToDatasetDescription(Tuple tuple, Expression<String> identificationExpression, boolean published) { Timestamp createTime = null; MetadataDocument metadataDocument; try { metadataDocument = mdf.parseDocument(tuple.get(sourceDatasetMetadata.document)); String metadataRevisionDateString = metadataDocument.getMetaDataCreationDate(); LocalDate metadataRevisionDate = LocalDate.parse(metadataRevisionDateString, DateTimeFormatter.ISO_DATE); createTime = Timestamp.valueOf(LocalDateTime.of(metadataRevisionDate, LocalTime.MIN)); } catch (Exception e) { Logger.info(tuple.get(identificationExpression) + ": Either metadata document " + "doesn't exist, metadata revision date can't be found or date is not in " + "iso date format"); } boolean confidential = tuple.get(sourceDatasetVersion.metadataConfidential); return new DefaultResourceDescription( getName(tuple.get(identificationExpression)), new DefaultResourceProperties( false, createTime, resourceProperties(confidential, published))); } @Override public Optional<ResourceProperties> properties(String name) { return getId(name).flatMap(id -> q.withTransaction(tx -> { Optional<ResourceProperties> optionalProperties = datasetProperties(id, tx); if(optionalProperties.isPresent()) { return optionalProperties; } else { if(config.getIncludeSourceDatasetMetadata()) { return sourceDatasetProperties(id, tx); } else { Optional<ResourceProperties> emptyOptional = Optional.empty(); return emptyOptional; } } })); } private Optional<ResourceProperties> sourceDatasetProperties(String id, Transaction tx) { return tupleToDatasetProperties( dqb.fromSourceDataset(tx).where(sourceDataset.metadataFileIdentification.eq(id)), BooleanTemplate.FALSE); } private Optional<ResourceProperties> datasetProperties(String id, Transaction tx) { return tupleToDatasetProperties( dqb.fromDataset(tx).where(dataset.metadataFileIdentification.eq(id)), dqb.isPublishedDataset()); } private Optional<ResourceProperties> tupleToDatasetProperties(SQLQuery query, BooleanExpression isPublished) { final BooleanExpression isPublishedAliased = isPublished.as("is_published"); return Optional.ofNullable(query .singleResult(sourceDatasetVersion.revision, sourceDatasetVersion.metadataConfidential, isPublishedAliased)) .map(datasetTuple -> { Timestamp createTime = datasetTuple.get(sourceDatasetVersion.revision); boolean confidential = datasetTuple.get(sourceDatasetVersion.metadataConfidential); return new DefaultResourceProperties( false, createTime, resourceProperties(confidential, datasetTuple.get(isPublishedAliased))); }); } private Map<QName, String> resourceProperties(boolean confidential, boolean published) { Map<QName, String> properties = new HashMap<QName, String>(); properties.put(new QName("http://idgis.nl/geopublisher", "confidential"), "" + confidential); properties.put(new QName("http://idgis.nl/geopublisher", "published"), "" + published); return properties; } }
package com.longway.daemon.services; import android.annotation.TargetApi; import android.app.job.JobParameters; import android.app.job.JobService; import android.os.Build; import android.util.Log; @TargetApi(Build.VERSION_CODES.LOLLIPOP) public class JobScheduleService extends JobService { private static final String TAG = JobScheduleService.class.getSimpleName(); @Override public boolean onStartJob(JobParameters params) { Log.e(TAG, " onStartJob jobId:" + params.getJobId()); WhiteService.startService(this); return false; } @Override public boolean onStopJob(JobParameters params) { Log.e(TAG, "onStopJob jobId:" + params.getJobId()); return false; } }
package controllers; import javax.inject.Inject; import org.apache.commons.io.IOUtils; import com.fasterxml.jackson.databind.JsonNode; import com.mysema.query.Tuple; import com.mysema.query.sql.SQLQuery; import com.mysema.query.sql.SQLSubQuery; import com.mysema.query.types.Predicate; import com.mysema.query.types.QTuple; import com.typesafe.config.Config; import model.dav.Resource; import model.dav.ResourceDescription; import model.dav.ResourceProperties; import model.dav.DefaultResource; import model.dav.DefaultResourceDescription; import model.dav.DefaultResourceProperties; import nl.idgis.publisher.metadata.MetadataDocument; import nl.idgis.publisher.metadata.MetadataDocumentFactory; import play.Configuration; import play.api.mvc.Handler; import play.api.mvc.RequestHeader; import play.api.routing.Router; import play.libs.Json; import play.mvc.Controller; import play.mvc.Result; import router.dav.SimpleWebDAV; import util.InetFilter; import util.MetadataConfig; import util.QueryDSL; import util.QueryDSL.Transaction; import static nl.idgis.publisher.database.QDataset.dataset; import static nl.idgis.publisher.database.QConstants.constants; import static nl.idgis.publisher.database.QService.service; import static nl.idgis.publisher.database.QPublishedService.publishedService; import static nl.idgis.publisher.database.QEnvironment.environment; import static nl.idgis.publisher.database.QSourceDataset.sourceDataset; import static nl.idgis.publisher.database.QSourceDatasetMetadata.sourceDatasetMetadata; import static nl.idgis.publisher.database.QSourceDatasetVersion.sourceDatasetVersion; import static nl.idgis.publisher.database.QPublishedServiceKeyword.publishedServiceKeyword; import static nl.idgis.publisher.database.QPublishedServiceDataset.publishedServiceDataset; import java.sql.Timestamp; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import java.util.stream.Collectors; public class ServiceMetadata extends AbstractMetadata { private static final String ENDPOINT_CODE_LIST_VALUE = "WebServices"; private static final String ENDPOINT_CODE_LIST = "http://www.isotc211.org/2005/iso19119/resources/Codelist/gmxCodelists.xml#DCPList"; private static final String ENDPOINT_OPERATION_NAME = "GetCapabilitities"; private static final String BROWSE_GRAPHIC_BASE_URL = "?request=GetMap&service=WMS&SRS=EPSG:28992&CRS=EPSG:28992" + "&bbox=180000,459000,270000,540000&width=600&height=662&" + "format=image/png&styles="; private final static String stylesheet = webjar + "services/intern/metadata.xsl"; private final MetadataDocument template; @Inject public ServiceMetadata(InetFilter filter, MetadataConfig config, QueryDSL q) throws Exception { this(filter, config, q, getTemplate(), "/"); } private static MetadataDocument getTemplate() throws Exception { MetadataDocumentFactory mdf = new MetadataDocumentFactory(); return mdf.parseDocument( ServiceMetadata.class .getClassLoader() .getResourceAsStream("nl/idgis/publisher/metadata/service_metadata.xml")); } public ServiceMetadata(InetFilter filter, MetadataConfig config, QueryDSL q, MetadataDocument template, String prefix) { super(filter, config, q, prefix); this.template = template; } @Override public ServiceMetadata withPrefix(String prefix) { return new ServiceMetadata(filter, config, q, template, prefix); } private SQLQuery fromService(Transaction tx) { SQLQuery query = tx.query().from(service) .join(publishedService).on(publishedService.serviceId.eq(service.id)) .join(environment).on(environment.id.eq(publishedService.environmentId)); if(!isTrusted()) { query.where(environment.confidential.isFalse()); } return query; } @Override public Optional<Resource> resource(String name) { return getId(name).flatMap(id -> q.withTransaction(tx -> { Tuple serviceTuple = fromService(tx) .join(constants).on(constants.id.eq(service.constantsId)) .where(service.wmsMetadataFileIdentification.eq(id) .or(service.wfsMetadataFileIdentification.eq(id))) .singleResult( service.id, publishedService.content, publishedService.title, publishedService.alternateTitle, publishedService.abstractCol, constants.contact, constants.organization, constants.position, constants.addressType, constants.address, constants.city, constants.state, constants.zipcode, constants.country, constants.telephone, constants.fax, constants.email, service.wmsMetadataFileIdentification, service.wfsMetadataFileIdentification, environment.identification); if(serviceTuple == null) { return Optional.<Resource>empty(); } int serviceId = serviceTuple.get(service.id); List<String> keywords = tx.query().from(publishedServiceKeyword) .where(publishedServiceKeyword.serviceId.eq(serviceId)) .orderBy(publishedServiceKeyword.keyword.asc()) .list(publishedServiceKeyword.keyword); List<Tuple> serviceDatasetTuples = tx.query().from(publishedServiceDataset) .join(dataset).on(dataset.id.eq(publishedServiceDataset.datasetId)) .where(publishedServiceDataset.serviceId.eq(serviceId)) .orderBy(dataset.id.asc(), publishedServiceDataset.layerName.asc()) .list( dataset.id, dataset.metadataIdentification, dataset.metadataFileIdentification, publishedServiceDataset.layerName); MetadataDocument metadataDocument = template.clone(); metadataDocument.setFileIdentifier(id); metadataDocument.setServiceTitle(serviceTuple.get(publishedService.title)); metadataDocument.setServiceAlternateTitle(serviceTuple.get(publishedService.alternateTitle)); metadataDocument.setServiceAbstract(serviceTuple.get(publishedService.abstractCol)); metadataDocument.removeServiceKeywords(); metadataDocument.addServiceKeywords( keywords, "GEMET - Concepts, version 2.4", "2010-01-13", "http://www.isotc211.org/2005/resources/codeList.xml#CI_DateTypeCode", "publication"); String role = "pointOfContact"; metadataDocument.setServiceResponsiblePartyName(role, serviceTuple.get(constants.organization)); metadataDocument.setServiceResponsiblePartyEmail(role, serviceTuple.get(constants.email)); metadataDocument.setMetaDataPointOfContactName(role, serviceTuple.get(constants.organization)); metadataDocument.setMetaDataPointOfContactEmail(role, serviceTuple.get(constants.email)); Integer lastDatasetId = null; metadataDocument.removeOperatesOn(); for(Tuple serviceDatasetTuple : serviceDatasetTuples) { int datasetId = serviceDatasetTuple.get(dataset.id); // a service can operate on a dataset using multiple // layer names (i.e. we encounter it multiple times in this loop), // but it should reported only once here. if(lastDatasetId == null || datasetId != lastDatasetId) { lastDatasetId = datasetId; String uuid = serviceDatasetTuple.get(dataset.metadataIdentification); String fileIdentification = serviceDatasetTuple.get(dataset.metadataFileIdentification); String uuidref = config.getMetadataUrlPrefix() + "dataset/" + getName(fileIdentification); metadataDocument.addOperatesOn(uuid, uuidref); } } metadataDocument.removeServiceType(); metadataDocument.removeServiceEndpoint(); metadataDocument.removeBrowseGraphic(); metadataDocument.removeServiceLinkage(); metadataDocument.removeSVCoupledResource(); ServiceType serviceType; if(id.equals(serviceTuple.get(service.wmsMetadataFileIdentification))) { serviceType = ServiceType.WMS; } else { serviceType = ServiceType.WFS; } // we obtain the serviceName from the published service content // because we don't store it anywhere else at the moment. JsonNode serviceInfo = Json.parse(serviceTuple.get(publishedService.content)); String serviceName = serviceInfo.get("name").asText(); String environmentId = serviceTuple.get(environment.identification); String linkage = getServiceLinkage(environmentId, serviceName, serviceType); metadataDocument.addServiceType(serviceType.getName()); metadataDocument.addServiceEndpoint(ENDPOINT_OPERATION_NAME, ENDPOINT_CODE_LIST, ENDPOINT_CODE_LIST_VALUE, linkage); for(Tuple serviceDatasetTuple : serviceDatasetTuples) { String identifier = serviceDatasetTuple.get(dataset.metadataIdentification); String scopedName = serviceDatasetTuple.get(publishedServiceDataset.layerName); if(serviceType == ServiceType.WMS) { metadataDocument.addBrowseGraphic(linkage + BROWSE_GRAPHIC_BASE_URL + "&layers=" + scopedName); } metadataDocument.addServiceLinkage(linkage, serviceType.getProtocol(), scopedName); metadataDocument.addSVCoupledResource(serviceType.getOperationName(), identifier, scopedName); } metadataDocument.setStylesheet(stylesheet); return Optional.<Resource>of(new DefaultResource("application/xml", metadataDocument.getContent())); })); } @Override public Stream<ResourceDescription> descriptions() { return q.withTransaction(tx -> fromService(tx) .list( publishedService.createTime, service.wmsMetadataFileIdentification, service.wfsMetadataFileIdentification).stream() .flatMap(serviceTuple -> { Timestamp createTime = serviceTuple.get(publishedService.createTime); return Stream.of( serviceTuple.get(service.wmsMetadataFileIdentification), serviceTuple.get(service.wfsMetadataFileIdentification)) .map(id -> new DefaultResourceDescription(getName(id), new DefaultResourceProperties(false, createTime))); })); } @Override public Optional<ResourceProperties> properties(String name) { return getId(name).flatMap(id -> q.withTransaction(tx -> { Tuple serviceTuple = fromService(tx) .where(service.wmsMetadataFileIdentification.eq(id) .or(service.wfsMetadataFileIdentification.eq(id))) .singleResult(new QTuple(publishedService.createTime)); if(serviceTuple == null) { return Optional.<ResourceProperties>empty(); } else { return Optional.<ResourceProperties>of( new DefaultResourceProperties( false, serviceTuple.get(publishedService.createTime))); } })); } }
package com.mohammedsazid.android.listr; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentUris; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.CheckBox; import android.widget.TextView; import android.widget.Toast; import com.mohammedsazid.android.listr.data.ListDbContract; import com.mohammedsazid.android.listr.data.ListProvider; public class NotifyActivity extends AppCompatActivity { int id; String content; boolean checkedState; boolean priorityState; Cursor cursor = null; TextView tv; CheckBox priorityCb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notify); id = getIntent().getIntExtra("_id", -1); loadContent(); bindViews(); tv.setText(content); priorityCb.setChecked(priorityState); Uri notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_done) .setContentTitle("Listr") .setSound(notificationSoundUri) .setVibrate(new long[] {300, 100, 400, 100}) .setContentText(content); Intent resultIntent = new Intent(this, ChecklistItemEditorActivity.class); resultIntent.putExtra("_id", id); PendingIntent pendingIntent = PendingIntent.getActivity(this, id, resultIntent, PendingIntent.FLAG_CANCEL_CURRENT); builder.setContentIntent(pendingIntent); NotificationManager notifMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Notification notification = builder.build(); notification.flags |= Notification.FLAG_AUTO_CANCEL; notifMgr.notify(id, notification); } @Override public void onStop() { closeCursor(); super.onStop(); } private void bindViews() { tv = (TextView) findViewById(R.id.req_content); priorityCb = (CheckBox) findViewById(R.id.checklist_item_priority); } private void closeCursor() { if (cursor != null && !cursor.isClosed()) { cursor.close(); cursor = null; } } private void loadContent() { if (id > -1) { Uri uri = ContentUris.withAppendedId( ListProvider.CONTENT_URI.buildUpon().appendPath("items").build(), id); closeCursor(); cursor = this.getContentResolver().query( uri, new String[]{ ListDbContract.ChecklistItems._ID, ListDbContract.ChecklistItems.COLUMN_LABEL, ListDbContract.ChecklistItems.COLUMN_CHECKED_STATE, ListDbContract.ChecklistItems.COLUMN_PRIORITY, ListDbContract.ChecklistItems.COLUMN_LAST_MODIFIED, ListDbContract.ChecklistItems.COLUMN_NOTIFY_TIME }, null, null, null ); cursor.moveToFirst(); content = cursor.getString( cursor.getColumnIndex(ListDbContract.ChecklistItems.COLUMN_LABEL)); checkedState = cursor.getInt( cursor.getColumnIndex(ListDbContract.ChecklistItems.COLUMN_CHECKED_STATE)) != 0; priorityState = cursor.getInt( cursor.getColumnIndex(ListDbContract.ChecklistItems.COLUMN_PRIORITY)) != 0; } } public void checkItem(View view) { ContentValues values = new ContentValues(); values.put(ListDbContract.ChecklistItems.COLUMN_CHECKED_STATE, true); values.put(ListDbContract.ChecklistItems.COLUMN_LAST_MODIFIED, System.currentTimeMillis()); Uri uri = ContentUris.withAppendedId(ListProvider.CONTENT_URI.buildUpon().appendPath("items").build(), id); int count = getContentResolver().update(uri, values, null, null); if (count > 0) { Toast.makeText(this, "Item checked.", Toast.LENGTH_SHORT).show(); super.onBackPressed(); } } }
package com.zfdang.zsmth_android; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.zfdang.zsmth_android.models.Board; import com.zfdang.zsmth_android.models.ListBoardContent; import com.zfdang.zsmth_android.newsmth.SMTHHelper; import java.util.ArrayList; import java.util.List; import okhttp3.ResponseBody; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * A fragment representing a list of Items. * <p/> * Activities containing this fragment MUST implement the {@link OnBoardFragmentInteractionListener} * interface. */ public class FavoriteBoardFragment extends Fragment { private final String TAG = "FavoriteBoardFragment"; private static final String ARG_COLUMN_COUNT = "column-count"; private int mColumnCount = 1; private OnBoardFragmentInteractionListener mListener; private RecyclerView mRecylerView = null; private String mOriginalTitle = null; // list of favorite paths private List<String> mFavoritePaths = null; private List<String> mFavoritePathNames = null; public void pushFavoritePath(String path, String name) { if(mFavoritePaths == null) { mFavoritePaths = new ArrayList<String>(); } if(mFavoritePathNames == null) { mFavoritePathNames = new ArrayList<String>(); } mFavoritePaths.add(path); mFavoritePathNames.add(name.trim()); } public void popFavoritePath() { if(mFavoritePaths != null & mFavoritePaths.size() > 1){ this.mFavoritePaths.remove(this.mFavoritePaths.size()-1); this.mFavoritePathNames.remove(this.mFavoritePathNames.size()-1); } } public String getCurrentFavoritePath(){ if(mFavoritePaths != null & mFavoritePaths.size() > 0){ return this.mFavoritePaths.get(this.mFavoritePaths.size() - 1); } else { return ""; } } public boolean atFavoriteRoot() { return !(mFavoritePaths != null && mFavoritePaths.size() > 1); } /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public FavoriteBoardFragment() { } // TODO: Customize parameter initialization @SuppressWarnings("unused") public static FavoriteBoardFragment newInstance(int columnCount) { FavoriteBoardFragment fragment = new FavoriteBoardFragment(); Bundle args = new Bundle(); args.putInt(ARG_COLUMN_COUNT, columnCount); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT); } // set the initial favorite path chain mFavoritePaths = new ArrayList<String>(); mFavoritePathNames = new ArrayList<String>(); pushFavoritePath("", ""); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRecylerView = (RecyclerView) inflater.inflate(R.layout.fragment_favorite_board, container, false); // Set the adapter if (mRecylerView != null) { mRecylerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL)); Context context = mRecylerView.getContext(); if (mColumnCount <= 1) { mRecylerView.setLayoutManager(new LinearLayoutManager(context)); } else { mRecylerView.setLayoutManager(new GridLayoutManager(context, mColumnCount)); } mRecylerView.setAdapter(new BoardRecyclerViewAdapter(ListBoardContent.FAVORITE_BOARDS, mListener)); } if(ListBoardContent.FAVORITE_BOARDS.size() == 0) { // only load boards on the first time RefreshFavoriteBoards(); } return mRecylerView; } public void showLoadingHints() { MainActivity activity = (MainActivity)getActivity(); activity.showProgress("...", true); } public void clearLoadingHints () { // disable progress bar MainActivity activity = (MainActivity) getActivity(); activity.showProgress("", false); } public void RefreshFavoriteBoards() { showLoadingHints(); LoadFavoriteBoardsByPath(getCurrentFavoritePath()); } protected void LoadFavoriteBoardsByPath(final String path) { SMTHHelper helper = SMTHHelper.getInstance(); helper.wService.getFavoriteByPath(path) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.io()) .flatMap(new Func1<ResponseBody, Observable<Board>>() { @Override public Observable<Board> call(ResponseBody resp) { try { String response = SMTHHelper.DecodeResponseFromWWW(resp.bytes()); Log.d(TAG, response); List<Board> boards = SMTHHelper.ParseFavoriteBoardsFromWWW(response); return Observable.from(boards); } catch (Exception e) { Log.d(TAG, "Failed to load favorite {" + path + "}"); Log.d(TAG, e.toString()); return null; } } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<Board>() { @Override public void onStart() { super.onStart(); ListBoardContent.clearFavorites(); mRecylerView.getAdapter().notifyDataSetChanged(); } @Override public void onCompleted() { clearLoadingHints(); updateFavoriteTitle(); } @Override public void onError(Throwable e) { Log.d(TAG, e.toString()); } @Override public void onNext(Board board) { ListBoardContent.addFavoriteItem(board); mRecylerView.getAdapter().notifyItemInserted(ListBoardContent.FAVORITE_BOARDS.size()); Log.d(TAG, board.toString()); } }); } private void updateFavoriteTitle(){ if(mOriginalTitle == null) { mOriginalTitle = getActivity().getTitle().toString(); } if( mFavoritePathNames != null && mFavoritePathNames.size() > 1) { String path = ""; for(int i = 1; i < mFavoritePathNames.size(); i ++) { path += ">" + mFavoritePathNames.get(i); } getActivity().setTitle(mOriginalTitle + path); } else { getActivity().setTitle(mOriginalTitle); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnBoardFragmentInteractionListener) { mListener = (OnBoardFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnBoardFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } }
package de.mygrades.main.processor; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import java.util.ArrayList; import java.util.List; import de.greenrobot.dao.query.DeleteQuery; import de.greenrobot.event.EventBus; import de.mygrades.database.dao.Action; import de.mygrades.database.dao.ActionDao; import de.mygrades.database.dao.ActionParam; import de.mygrades.database.dao.ActionParamDao; import de.mygrades.database.dao.Rule; import de.mygrades.database.dao.TransformerMapping; import de.mygrades.database.dao.TransformerMappingDao; import de.mygrades.database.dao.University; import de.mygrades.database.dao.UniversityDao; import de.mygrades.main.events.UniversityEvent; import de.mygrades.util.Constants; import retrofit.RetrofitError; /** * UniversityProcessor is responsible for university resources. * It makes rest calls and required inserts / updates to the local database. */ public class UniversityProcessor extends BaseProcessor { private static final String TAG = UniversityProcessor.class.getSimpleName(); public UniversityProcessor(Context context) { super(context); } /** * Load all universities from the server and posts an UniversityEvent. * * @param publishedOnly - load only published universities or all */ public void getUniversities(boolean publishedOnly) { List<University> universities = new ArrayList<>(); // make synchronous rest call try { String updatedAtServerPublished = getUpdatedAtServerForUniversities(true); String updatedAtServerUnpublished = getUpdatedAtServerForUniversities(false); universities = restClient.getRestApi().getUniversities(publishedOnly, updatedAtServerPublished, updatedAtServerUnpublished); } catch (RetrofitError e) { Log.e(TAG, "RetrofitError: " + e.getMessage()); } universities = universities == null ? new ArrayList<University>() : universities; // insert into database daoSession.getUniversityDao().insertOrReplaceInTx(universities); // post university event UniversityEvent universityEvent = new UniversityEvent(); universityEvent.setUniversities(universities); EventBus.getDefault().post(universityEvent); } /** * Load all universities from the database and posts an UniversityEvent. * * @param publishedOnly - select only published universities or all */ public void getUniversitiesFromDatabase(boolean publishedOnly) { UniversityDao universityDao = daoSession.getUniversityDao(); List<University> universities = universityDao.queryBuilder() .where(UniversityDao.Properties.Published.eq(publishedOnly)) .orderAsc(UniversityDao.Properties.Name) .list(); // post university event UniversityEvent universityEvent = new UniversityEvent(); universityEvent.setUniversities(universities); EventBus.getDefault().post(universityEvent); } /** * Get a detailed university with all rules, actions etc by an university id. * * @param universityId - university id */ public void getDetailedUniversity(long universityId) { University university = null; try { String updatedAtServer = getUpdatedAtServerForUniversity(universityId); university = restClient.getRestApi().getUniversity(universityId, updatedAtServer); } catch (RetrofitError e) { Log.e(TAG, "RetrofitError: " + e.getMessage()); } // insert into database if (university != null) { final University finalUniversity = university; daoSession.runInTx(new Runnable() { @Override public void run() { daoSession.getUniversityDao().insertOrReplace(finalUniversity); for (Rule rule : finalUniversity.getRulesRaw()) { clearRule(rule); // delete actions and transformer mappings daoSession.getRuleDao().insertOrReplace(rule); for (Action action : rule.getActionsRaw()) { daoSession.getActionDao().insertOrReplace(action); for (ActionParam actionParam : action.getActionParamsRaw()) { daoSession.getActionParamDao().insertOrReplace(actionParam); } } for (TransformerMapping transformerMapping : rule.getTransformerMappingsRaw()) { daoSession.getTransformerMappingDao().insertOrReplace(transformerMapping); } } } }); } } /** * Deletes all ActionParams, Actions and TransformerMappings for a given rule from database. * * @param rule */ private void clearRule(Rule rule) { DeleteQuery deleteActionParams = daoSession.getActionParamDao().queryBuilder() .where(ActionParamDao.Properties.ActionId.eq(-1)) .buildDelete(); DeleteQuery deleteActions = daoSession.getActionDao().queryBuilder() .where(ActionDao.Properties.RuleId.eq(rule.getRuleId())) .buildDelete(); DeleteQuery deleteTransformerMappings = daoSession.getTransformerMappingDao().queryBuilder() .where(TransformerMappingDao.Properties.RuleId.eq(rule.getRuleId())) .buildDelete(); // delete actionParams for (Action action : rule.getActionsRaw()) { deleteActionParams.setParameter(0, action.getActionId()); deleteActionParams.executeDeleteWithoutDetachingEntities(); } // delete actions deleteActions.executeDeleteWithoutDetachingEntities(); // delete transformer mappings deleteTransformerMappings.executeDeleteWithoutDetachingEntities(); daoSession.clear(); } /** * Get the latest updated_at_server timestamp for all universities. * The selected university should be excluded from the query, because * it may be already updated multiple times. * * @param publishedOnly - get timestamp for published or unpublished universities * @return timestamp as string */ public String getUpdatedAtServerForUniversities(boolean publishedOnly) { // get selected university id to exclude it from query SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); long universityId = prefs.getLong(Constants.PREF_KEY_UNIVERSITY_ID, -1); University university = daoSession.getUniversityDao().queryBuilder() .orderDesc(UniversityDao.Properties.UpdatedAtServer) .where(UniversityDao.Properties.UniversityId.notEq(universityId)) .where(UniversityDao.Properties.Published.eq(publishedOnly)) .limit(1) .unique(); if (university != null) { return university.getUpdatedAtServer(); } return null; } /** * Get the updated_at_server timestamp for the selected university. * Return null, if the selected university has no rules attached (should only happen at first load). * * @param universityId - university id * @return timestamp as string */ private String getUpdatedAtServerForUniversity(long universityId) { University u = daoSession.getUniversityDao().queryBuilder().where(UniversityDao.Properties.UniversityId.eq(universityId)).unique(); if (u == null || u.getRules() == null || u.getRules().size() == 0) { return null; } return u.getUpdatedAtServer(); } }
package org.stepic.droid.view.activities; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import com.squareup.otto.Subscribe; import org.stepic.droid.R; import org.stepic.droid.base.FragmentActivityBase; import org.stepic.droid.concurrency.FromDbStepTask; import org.stepic.droid.concurrency.ToDbStepTask; import org.stepic.droid.events.steps.FailLoadStepEvent; import org.stepic.droid.events.steps.FromDbStepEvent; import org.stepic.droid.events.steps.UpdateStepEvent; import org.stepic.droid.events.steps.UpdateStepsState; import org.stepic.droid.events.steps.SuccessLoadStepEvent; import org.stepic.droid.model.Assignment; import org.stepic.droid.model.Lesson; import org.stepic.droid.model.Progress; import org.stepic.droid.model.Step; import org.stepic.droid.model.Unit; import org.stepic.droid.util.AppConstants; import org.stepic.droid.util.ProgressHelper; import org.stepic.droid.util.ProgressUtil; import org.stepic.droid.view.adapters.StepFragmentAdapter; import org.stepic.droid.web.AssignmentResponse; import org.stepic.droid.web.ProgressesResponse; import org.stepic.droid.web.StepResponse; import org.stepic.droid.web.ViewAssignment; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.BindString; import butterknife.ButterKnife; import retrofit.Callback; import retrofit.Response; import retrofit.Retrofit; public class StepsActivity extends FragmentActivityBase { // public final static String KEY_INDEX_CURRENT_FRAGMENT = "key_index"; public final static String KEY_COUNT_CURRENT_FRAGMENT = "key_count"; @Bind(R.id.toolbar) Toolbar mToolbar; @Bind(R.id.viewpager) ViewPager mViewPager; @Bind(R.id.tabs) TabLayout mTabLayout; @Bind(R.id.load_progressbar) ProgressBar mProgressBar; @BindString(R.string.not_available_lesson) String notAvailable; StepFragmentAdapter mStepAdapter; private List<Step> mStepList; private Unit mUnit; private Lesson mLesson; private boolean isLoaded; private volatile boolean isAssignmentsUpdated = false; private volatile boolean isProgressUpdated = false; private ToDbStepTask saveStepsTask; private FromDbStepTask getFromDbStepsTask; // private int lastSavedPosition; private int mCount; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_steps); if (savedInstanceState == null) { // lastSavedPosition = -1; mCount = -1; } else { mCount = savedInstanceState.getInt(KEY_COUNT_CURRENT_FRAGMENT); } overridePendingTransition(R.anim.slide_in_from_end, R.anim.slide_out_to_start); ButterKnife.bind(this); mUnit = (Unit) (getIntent().getExtras().get(AppConstants.KEY_UNIT_BUNDLE)); mLesson = (Lesson) (getIntent().getExtras().get(AppConstants.KEY_LESSON_BUNDLE)); mStepList = new ArrayList<>(); mStepAdapter = new StepFragmentAdapter(getSupportFragmentManager(), this, mStepList, mLesson, mUnit, mCount); mViewPager.setAdapter(mStepAdapter); setTitle(mLesson.getTitle()); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { pushState(position); } @Override public void onPageScrollStateChanged(int state) { } }); if (mLesson != null && mLesson.getSteps() != null && mLesson.getSteps().length != 0 && !isLoaded) updateSteps(); } private void pushState(int position) { if (mStepList.size() <= position) return; final Step step = mStepList.get(position); final int local = position; if (mStepResolver.isViewedStatePost(step) && !step.is_custom_passed()) { //try to push viewed state to the server AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { long stepId = step.getId(); protected Void doInBackground(Void... params) { long assignmentID = mDbManager.getAssignmentIdByStepId(stepId); Log.i("push", "push " + local); mShell.getScreenProvider().pushToViewedQueue(new ViewAssignment(assignmentID, stepId)); return null; } }; task.execute(); } } private void updateSteps() { ProgressHelper.activate(mProgressBar); getFromDbStepsTask = new FromDbStepTask(mLesson); getFromDbStepsTask.execute(); } @Subscribe public void onFromDbStepEvent(FromDbStepEvent e) { if (e.getLesson() != null && e.getLesson().getId() != mLesson.getId()) { bus.post(new FailLoadStepEvent()); return; } if (e.getStepList() != null && e.getStepList().size() != 0) { showSteps(e.getStepList()); } else { mShell.getApi().getSteps(mLesson.getSteps()).enqueue(new Callback<StepResponse>() { @Override public void onResponse(Response<StepResponse> response, Retrofit retrofit) { if (response.isSuccess()) { bus.post(new SuccessLoadStepEvent(response)); } else { bus.post(new FailLoadStepEvent()); } } @Override public void onFailure(Throwable t) { bus.post(new FailLoadStepEvent()); } }); } } @Subscribe public void onSuccessLoad(SuccessLoadStepEvent e) { //// FIXME: 10.10.15 check right lesson ?? is it need? StepResponse stepicResponse = e.getResponse().body(); final List<Step> steps = stepicResponse.getSteps(); if (steps.isEmpty()) { bus.post(new FailLoadStepEvent()); } else { // ToDbStepTask task = new ToDbStepTask(mLesson, steps); // task.execute(); mShell.getApi().getAssignments(mUnit.getAssignments()).enqueue(new Callback<AssignmentResponse>() { @Override public void onResponse(Response<AssignmentResponse> response, Retrofit retrofit) { if (response.isSuccess()) { final List<Assignment> assignments = response.body().getAssignments(); AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { for (Assignment item : assignments) { mDbManager.addAssignment(item); } return null; } }; task.execute(); final String[] progressIds = ProgressUtil.getAllProgresses(assignments); mShell.getApi().getProgresses(progressIds).enqueue(new Callback<ProgressesResponse>() { Unit localUnit = mUnit; @Override public void onResponse(final Response<ProgressesResponse> response, Retrofit retrofit) { if (response.isSuccess()) { AsyncTask<Void, Void, Void> task1 = new AsyncTask<Void, Void, Void>() { List<Progress> progresses; @Override protected Void doInBackground(Void... params) { progresses = response.body().getProgresses(); for (Progress item : progresses) { mDbManager.addProgress(item); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); bus.post(new UpdateStepsState(localUnit, steps)); } }; task1.execute(); } } @Override public void onFailure(Throwable t) { } }); } } @Override public void onFailure(Throwable t) { } }); } } @Subscribe public void onUpdateStepsState(final UpdateStepsState e) { if (e.getUnit().getId() != mUnit.getId()) return; final List<Step> localSteps = e.getSteps(); AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { for (Step item : localSteps) { item.setIs_custom_passed(mDbManager.isStepPassed(item.getId())); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if (mStepList != null && mStepAdapter != null && mTabLayout != null) { Log.i("update", "update ui"); showSteps(localSteps); } } }; task.execute(); } @Subscribe public void onUpdateOneStep(UpdateStepEvent e) { long stepId = e.getStepId(); Step step = null; if (mStepList != null) { for (Step item : mStepList) { if (item.getId() == stepId) { step = item; } } } if (step != null) { step.setIs_custom_passed(true); int pos = mViewPager.getCurrentItem(); for (int i = 0; i < mStepAdapter.getCount(); i++) { TabLayout.Tab tab = mTabLayout.getTabAt(i); tab.setIcon(mStepAdapter.getTabDrawable(i)); } } } // @Subscribe // public void onSuccessSaveToDb(SuccessToDbStepEvent e) { // if (e.getmLesson().getId() != mLesson.getId()) return; // FromDbStepTask stepTask = new FromDbStepTask(mLesson); // stepTask.execute(); private void showSteps(List<Step> steps) { mStepList.clear(); mStepList.addAll(steps); mStepAdapter.notifyDataSetChanged(); updateTabs(); mTabLayout.setVisibility(View.VISIBLE); ProgressHelper.dismiss(mProgressBar); isLoaded = true; pushState(mViewPager.getCurrentItem()); // if (lastSavedPosition >= 0) { // mViewPager.setCurrentItem(lastSavedPosition, false); } @Subscribe public void onFailLoad(FailLoadStepEvent e) { Toast.makeText(this, notAvailable, Toast.LENGTH_LONG).show(); isLoaded = false; ProgressHelper.dismiss(mProgressBar); } private void updateTabs() { mTabLayout.setupWithViewPager(mViewPager); for (int i = 0; i < mStepAdapter.getCount(); i++) { TabLayout.Tab tab = mTabLayout.getTabAt(i); tab.setIcon(mStepAdapter.getTabDrawable(i)); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // outState.putInt(KEY_INDEX_CURRENT_FRAGMENT, mViewPager.getCurrentItem()); outState.putInt(KEY_COUNT_CURRENT_FRAGMENT, mStepList.size()); } // @Override // protected void onRestoreInstanceState(Bundle savedInstanceState) { // super.onRestoreInstanceState(savedInstanceState); //// if (savedInstanceState != null) { //// lastSavedPosition = savedInstanceState.getInt(KEY_INDEX_CURRENT_FRAGMENT); @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } @Override public void finish() { super.finish(); overridePendingTransition(R.anim.slide_in_from_start, R.anim.slide_out_to_end); } }
package org.wikipedia.edit.preview; import android.annotation.SuppressLint; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.ScrollView; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.analytics.EditFunnel; import org.wikipedia.bridge.CommunicationBridge; import org.wikipedia.bridge.CommunicationBridge.CommunicationBridgeListener; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.dataclient.okhttp.OkHttpWebViewClient; import org.wikipedia.edit.EditSectionActivity; import org.wikipedia.edit.summaries.EditSummaryTag; import org.wikipedia.history.HistoryEntry; import org.wikipedia.page.LinkHandler; import org.wikipedia.page.PageActivity; import org.wikipedia.page.PageTitle; import org.wikipedia.page.PageViewModel; import org.wikipedia.util.ConfigurationCompat; import org.wikipedia.util.L10nUtil; import org.wikipedia.util.UriUtil; import org.wikipedia.views.ObservableWebView; import org.wikipedia.views.ViewAnimations; import java.util.ArrayList; import java.util.List; import java.util.Locale; import io.reactivex.disposables.CompositeDisposable; import static org.wikipedia.dataclient.RestService.PAGE_HTML_PREVIEW_ENDPOINT; import static org.wikipedia.util.DeviceUtil.hideSoftKeyboard; import static org.wikipedia.util.UriUtil.handleExternalLink; public class EditPreviewFragment extends Fragment implements CommunicationBridgeListener { private ObservableWebView webview; private ScrollView previewContainer; private EditSectionActivity parentActivity; private ViewGroup editSummaryTagsContainer; private String previewHTML; private PageViewModel model = new PageViewModel(); private CommunicationBridge bridge; private List<EditSummaryTag> summaryTags; private EditSummaryTag otherTag; private EditFunnel funnel; private CompositeDisposable disposables = new CompositeDisposable(); @Override @SuppressLint({"AddJavascriptInterface", "SetJavaScriptEnabled"}) public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View parent = inflater.inflate(R.layout.fragment_preview_edit, container, false); webview = parent.findViewById(R.id.edit_preview_webview); previewContainer = parent.findViewById(R.id.edit_preview_container); editSummaryTagsContainer = parent.findViewById(R.id.edit_summary_tags_container); bridge = new CommunicationBridge(this); webview.getSettings().setJavaScriptEnabled(true); webview.setWebViewClient(new OkHttpWebViewClient() { @NonNull @Override public PageViewModel getModel() { return model; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); parentActivity.showProgressBar(false); parentActivity.supportInvalidateOptionsMenu(); //Save the html received from the the wikitext to mobile-html transform, to use in the savedInstanceState view.evaluateJavascript( "(function() { return (document.documentElement.outerHTML); })();", html -> { previewHTML = html; }); } }); return parent; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); parentActivity = (EditSectionActivity)getActivity(); PageTitle pageTitle = parentActivity.getPageTitle(); model.setTitle(pageTitle); model.setTitleOriginal(pageTitle); model.setCurEntry(new HistoryEntry(pageTitle, HistoryEntry.SOURCE_INTERNAL_LINK)); funnel = WikipediaApp.getInstance().getFunnelManager().getEditFunnel(pageTitle); Resources oldResources = getResources(); AssetManager assets = oldResources.getAssets(); DisplayMetrics metrics = oldResources.getDisplayMetrics(); Locale oldLocale = ConfigurationCompat.getLocale(oldResources.getConfiguration()); Locale newLocale = new Locale(pageTitle.getWikiSite().languageCode()); Configuration config = new Configuration(oldResources.getConfiguration()); Resources tempResources = getResources(); boolean hasSameLocale = oldLocale.getLanguage().equals(newLocale.getLanguage()); if (!hasSameLocale && !newLocale.getLanguage().equals("test")) { L10nUtil.setDesiredLocale(config, newLocale); tempResources = new Resources(assets, metrics, config); } // build up summary tags... int[] summaryTagStrings = { R.string.edit_summary_tag_typo, R.string.edit_summary_tag_grammar, R.string.edit_summary_tag_links }; summaryTags = new ArrayList<>(); for (int i : summaryTagStrings) { final EditSummaryTag tag = new EditSummaryTag(getActivity()); tag.setText(tempResources.getString(i)); tag.setTag(i); tag.setOnClickListener((view) -> { funnel.logEditSummaryTap((Integer) view.getTag()); tag.setSelected(!tag.getSelected()); }); editSummaryTagsContainer.addView(tag); summaryTags.add(tag); } otherTag = new EditSummaryTag(getActivity()); otherTag.setText(tempResources.getString(R.string.edit_summary_tag_other)); editSummaryTagsContainer.addView(otherTag); otherTag.setOnClickListener((view) -> { funnel.logEditSummaryTap(R.string.edit_summary_tag_other); if (otherTag.getSelected()) { otherTag.setSelected(false); } else { parentActivity.showCustomSummary(); } }); /* Reset AssetManager to its original state, by creating a new Resources object with the original Locale (from above) */ if (!hasSameLocale) { config.setLocale(oldLocale); new Resources(assets, metrics, config); } if (savedInstanceState != null) { for (int i = 0; i < summaryTags.size(); i++) { summaryTags.get(i).setSelected(savedInstanceState.getBoolean("summaryTag" + i, false)); } if (savedInstanceState.containsKey("otherTag")) { otherTag.setSelected(true); otherTag.setText(savedInstanceState.getString("otherTag")); } previewHTML = savedInstanceState.getString("previewHTML"); boolean isActive = savedInstanceState.getBoolean("isActive"); previewContainer.setVisibility(isActive ? View.VISIBLE : View.GONE); if (isActive) { displayPreviewHtml(previewHTML); } } } private void displayPreviewHtml(String previewHTML) { webview.loadData(previewHTML, "text/html", "UTF-8"); setUpWebView(); } public void setCustomSummary(String summary) { otherTag.setText(summary.length() > 0 ? summary : getString(R.string.edit_summary_tag_other)); otherTag.setSelected(summary.length() > 0); } private boolean isWebViewSetup = false; /** * Fetches preview html from the modified wikitext text, and shows (fades in) the Preview fragment, * which includes edit summary tags. When the fade-in completes, the state of the * actionbar button(s) is updated, and the preview is shown. * @param title The PageTitle associated with the text being modified. * @param wikiText The text of the section to be shown in the Preview. */ public void showPreview(final PageTitle title, final String wikiText) { hideSoftKeyboard(requireActivity()); parentActivity.showProgressBar(true); String url = model.getTitle().getWikiSite().uri() + PAGE_HTML_PREVIEW_ENDPOINT + title.getConvertedText(); String postData; postData = "wikitext=" + UriUtil.encodeURL(wikiText); webview.postUrl(url, postData.getBytes()); setUpWebView(); } private void setUpWebView() { if (!isWebViewSetup) { isWebViewSetup = true; bridge.addListener("link_clicked", new LinkHandler(requireActivity()) { @Override public void onPageLinkClicked(@NonNull String href, @NonNull String linkText) { // TODO: also need to handle references, issues, disambig, ... in preview eventually } @Override public void onInternalLinkClicked(@NonNull final PageTitle title) { showLeavingEditDialogue(() -> startActivity(PageActivity.newIntentForCurrentTab(getContext(), new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK), title))); } @Override public void onExternalLinkClicked(@NonNull final Uri uri) { showLeavingEditDialogue(() -> handleExternalLink(getContext(), uri)); } @Override public void onSVGLinkClicked(@NonNull String href) { // ignore } /** * Shows the user a dialogue asking them if they really meant to leave the edit * workflow, and warning them that their changes have not yet been saved. * @param runnable The runnable that is run if the user chooses to leave. */ private void showLeavingEditDialogue(final Runnable runnable) { //Ask the user if they really meant to leave the edit workflow final AlertDialog leavingEditDialog = new AlertDialog.Builder(requireActivity()) .setMessage(R.string.dialog_message_leaving_edit) .setPositiveButton(R.string.dialog_message_leaving_edit_leave, (dialog, which) -> { //They meant to leave; close dialogue and run specified action dialog.dismiss(); runnable.run(); }) .setNegativeButton(R.string.dialog_message_leaving_edit_stay, null) .create(); leavingEditDialog.show(); } @Override public WikiSite getWikiSite() { return parentActivity.getPageTitle().getWikiSite(); } }); bridge.addListener("image_clicked", (messageType, messagePayload) -> { // TODO: do something when an image is clicked in Preview. }); bridge.addListener("mediaClicked", (messageType, messagePayload) -> { // TODO: do something when a video is clicked in Preview. }); bridge.addListener("reference_clicked", (messageType, messagePayload) -> { // TODO: do something when a reference is clicked in Preview. }); } ViewAnimations.fadeIn(previewContainer, () -> parentActivity.supportInvalidateOptionsMenu()); ViewAnimations.fadeOut(requireActivity().findViewById(R.id.edit_section_container)); } /** * Gets the overall edit summary, as specified by the user by clicking various tags, * and/or entering a custom summary. * @return Summary of the edit. If the user clicked more than one summary tag, * they will be separated by commas. */ public String getSummary() { StringBuilder summaryStr = new StringBuilder(); for (EditSummaryTag tag : summaryTags) { if (!tag.getSelected()) { continue; } if (summaryStr.length() > 0) { summaryStr.append(", "); } summaryStr.append(tag); } if (otherTag.getSelected()) { if (summaryStr.length() > 0) { summaryStr.append(", "); } summaryStr.append(otherTag); } return summaryStr.toString(); } @Override public void onDestroyView() { disposables.clear(); if (webview != null) { webview.clearAllListeners(); ((ViewGroup) webview.getParent()).removeView(webview); webview = null; } super.onDestroyView(); } public boolean handleBackPressed() { if (isActive()) { hide(); return true; } return false; } /** * Hides (fades out) the Preview fragment. * When fade-out completes, the state of the actionbar button(s) is updated. */ public void hide() { View editSectionContainer = requireActivity().findViewById(R.id.edit_section_container); ViewAnimations.crossFade(previewContainer, editSectionContainer, () -> parentActivity.supportInvalidateOptionsMenu()); } public boolean isActive() { return previewContainer.getVisibility() == View.VISIBLE; } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putString("previewHTML", previewHTML); outState.putBoolean("isActive", isActive()); for (int i = 0; i < summaryTags.size(); i++) { outState.putBoolean("summaryTag" + i, summaryTags.get(i).getSelected()); } if (otherTag.getSelected()) { outState.putString("otherTag", otherTag.toString()); } } @Override public WebView getWebView() { return webview; } }
package pl.kodujdlapolski.na4lapy.user; import android.support.annotation.NonNull; import org.joda.time.LocalDate; import org.joda.time.Years; import java.util.Collections; import java.util.List; import javax.inject.Inject; import pl.kodujdlapolski.na4lapy.model.Animal; import pl.kodujdlapolski.na4lapy.model.UserPreferences; import pl.kodujdlapolski.na4lapy.model.type.ActivityAnimal; import pl.kodujdlapolski.na4lapy.model.type.Gender; import pl.kodujdlapolski.na4lapy.model.type.Size; import pl.kodujdlapolski.na4lapy.model.type.Species; import pl.kodujdlapolski.na4lapy.preferences.PreferencesService; import static com.google.common.base.Preconditions.checkNotNull; public class UserServiceImpl implements UserService { private PreferencesService mPreferencesService; private UserPreferences mUserPreferences; @Inject public UserServiceImpl(PreferencesService preferencesService) { mPreferencesService = preferencesService; mUserPreferences = mPreferencesService.getUserPreferences(); } @Override public void saveCurrentUserPreferences(@NonNull UserPreferences userPreferences) { UserPreferences newUserPreferences = checkNotNull(userPreferences, "UserPreferences cannot be null"); mPreferencesService.setUserPreferences(newUserPreferences); mUserPreferences = userPreferences; } @Override @NonNull public UserPreferences loadCurrentUserPreferences() { UserPreferences userPreferences = mPreferencesService.getUserPreferences(); return userPreferences != null ? userPreferences : new UserPreferences(); } @Override public int getPreferencesComplianceLevel(Animal animal) { if (mUserPreferences == null) { return 0; } int result = 0; if ((mUserPreferences.isTypeDog() && Species.DOG.equals(animal.getSpecies())) || (mUserPreferences.isTypeCat() && Species.CAT.equals(animal.getSpecies())) || (mUserPreferences.isTypeOther() && Species.OTHER.equals(animal.getSpecies()))) { ++result; } else { return 0; } if ((mUserPreferences.isGenderMan() && mUserPreferences.isGenderWoman() && Gender.UNKNOWN.equals(animal.getGender())) || (mUserPreferences.isGenderMan() && Gender.MALE.equals(animal.getGender())) || (mUserPreferences.isGenderWoman() && Gender.FEMALE.equals(animal.getGender()))) { ++result; } if (animal.getBirthDate() != null) { int age = Years.yearsBetween(animal.getBirthDate(), LocalDate.now()).getYears(); if (age >= mUserPreferences.getAgeMin() && age <= mUserPreferences.getAgeMax()) { ++result; } } if ((mUserPreferences.isSizeSmall() && Size.SMALL.equals(animal.getSize())) || (mUserPreferences.isSizeMedium() && Size.MEDIUM.equals(animal.getSize())) || (mUserPreferences.isSizeLarge() && Size.LARGE.equals(animal.getSize()))) { ++result; } if ((mUserPreferences.isActivityLow() && mUserPreferences.isActivityHigh() && ActivityAnimal.UNKNOWN.equals(animal.getActivity())) || (mUserPreferences.isActivityLow() && ActivityAnimal.LOW.equals(animal.getActivity())) || (mUserPreferences.isActivityHigh() && ActivityAnimal.HIGH.equals(animal.getActivity()))) { ++result; } return result; } @Override public void login() { // TODO } @Override public void logout() { // TODO } @Override public String getUserFirstName() { // TODO return null; } @Override public String getUserPhotoUrl() { // TODO return null; } @Override public boolean isLogged() { return false; // TODO } @Override public void addToFavourite(Animal animal) { if (animal == null || animal.getId() == null) { return; } mPreferencesService.addToFavourite(animal.getId()); } @Override public void removeFromFavourite(Animal animal) { if (animal == null || animal.getId() == null) { return; } mPreferencesService.removeFromFavourite(animal.getId()); } @Override public boolean isFavourite(Animal animal) { List<Long> favourites = mPreferencesService.getFavouriteList(); if (favourites == null || favourites.isEmpty() || animal == null || animal.getId() == null) { return false; } for (Long l : favourites) { if (l.equals(animal.getId())) { return true; } } return false; } @Override public List<Animal> sortByUserPreferences(List<Animal> animals) { if (animals == null) { return null; } Collections.sort(animals, (previousAnimal, nextAnimal) -> { Integer previousAnimalComplianceLevel = getPreferencesComplianceLevel(previousAnimal); Integer nextAnimalComplianceLevel = getPreferencesComplianceLevel(nextAnimal); return nextAnimalComplianceLevel.compareTo(previousAnimalComplianceLevel); }); return animals; } }
package tk11.jphacks.titech.view.fragment; import android.app.Activity; import android.app.FragmentManager; import android.content.Context; import android.media.AudioManager; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.HorizontalScrollView; import android.widget.TextView; import com.daimajia.swipe.SwipeLayout; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Click; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.ViewById; import org.json.JSONArray; import io.skyway.Peer.Browser.Canvas; import io.skyway.Peer.Browser.MediaConstraints; import io.skyway.Peer.Browser.MediaStream; import io.skyway.Peer.Browser.Navigator; import io.skyway.Peer.CallOption; import io.skyway.Peer.MediaConnection; import io.skyway.Peer.OnCallback; import io.skyway.Peer.Peer; import io.skyway.Peer.PeerError; import io.skyway.Peer.PeerOption; import tk11.jphacks.titech.R; import tk11.jphacks.titech.controller.animation.RevealEffect; import tk11.jphacks.titech.view.view.ExtensionBrowserCanvas; @EFragment(R.layout.fragment_call) public class CallFragment extends BaseFragment { private static final String TAG = CallFragment.class.getSimpleName(); private Peer _peer; private MediaConnection _media; private MediaStream _msLocal; private MediaStream _msRemote; private Handler _handler; private String _id; private String[] _listPeerIds; private boolean _bCalling; @ViewById(R.id.extension_canvas) ExtensionBrowserCanvas extentionBrowserCanvas; @ViewById(R.id.svPrimary) ExtensionBrowserCanvas primaryCanvas; @ViewById(R.id.btnAction) Button btnAction; @ViewById(R.id.tvOwnId) TextView tvOwnId; @ViewById(R.id.sliding_layout) SwipeLayout slidingUpPanelLayout; @ViewById(R.id.button_container) HorizontalScrollView buttonContainer; @Click(R.id.red_filter_button) void clickRedFilter() { extentionBrowserCanvas.setStandardFilter(ExtensionBrowserCanvas.RED_FILTER); } @Click(R.id.white_filter_button) void clickWhiteFilter() { extentionBrowserCanvas.setStandardFilter(ExtensionBrowserCanvas.WHITE_FILTER); } @Click(R.id.frame_filter_button) void clickFrameFilter() { extentionBrowserCanvas.setFrameFilter(); } @Click(R.id.star_anim_filter_button) void clickStarAnimFilter() { extentionBrowserCanvas.setAnimationFilter(getActivity()); } @Click(R.id.reset_filter_button) void clickResetButton() { extentionBrowserCanvas.clearFilter(); } @Click(R.id.sliding_layout) void clickSlidingLayout() { } @AfterViews void onAfterViews() { Activity activity = getActivity(); RevealEffect.bindAnimation( (ViewGroup) activity.getWindow().getDecorView().findViewById(android.R.id.content), activity.getIntent(), activity.getApplicationContext(), activity.getWindow(), getResources() ); slidingUpPanelLayout.addDrag(SwipeLayout.DragEdge.Bottom, buttonContainer); slidingUpPanelLayout.setRightSwipeEnabled(false); slidingUpPanelLayout.setLeftSwipeEnabled(false); slidingUpPanelLayout.addSwipeListener(new SwipeLayout.SwipeListener() { @Override public void onClose(SwipeLayout layout) { //when the SurfaceView totally cover the BottomView. } @Override public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) { //you are swiping. } @Override public void onStartOpen(SwipeLayout layout) { } @Override public void onOpen(SwipeLayout layout) { //when the BottomView totally show. } @Override public void onStartClose(SwipeLayout layout) { } @Override public void onHandRelease(SwipeLayout layout, float xvel, float yvel) { //when user's hand released. } }); Window wnd = getActivity().getWindow(); wnd.addFlags(Window.FEATURE_NO_TITLE); _handler = new Handler(Looper.getMainLooper()); PeerOption options = new PeerOption(); options.key = "20acaf0d-4c8f-4d3b-bfa0-d320db8f283c"; options.domain = "tk11.titech.jphacks"; _peer = new Peer(getActivity(), options); setPeerCallback(_peer); Navigator.initialize(_peer); MediaConstraints constraints = new MediaConstraints(); _msLocal = Navigator.getUserMedia(constraints); extentionBrowserCanvas.addSrc(_msLocal, 0); _bCalling = false; btnAction.setEnabled(true); btnAction.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); if (!_bCalling) { listingPeers(); } else { closing(); } v.setEnabled(true); } }); } /** * Media connecting to remote peer. * @param strPeerId Remote peer. */ void calling(String strPeerId) { if (null == _peer) { return; } if (null != _media) { _media.close(); _media = null; } CallOption option = new CallOption(); _media = _peer.call(strPeerId, _msLocal, option); if (null != _media) { setMediaCallback(_media); _bCalling = true; } updateUI(); } private void setPeerCallback(Peer peer) { peer.on(Peer.PeerEventEnum.OPEN, new OnCallback() { @Override public void onCallback(Object object) { Log.d(TAG, "[On/Open]"); if (object instanceof String) { _id = (String) object; Log.d(TAG, "ID:" + _id); updateUI(); } } }); peer.on(Peer.PeerEventEnum.CALL, new OnCallback() { @Override public void onCallback(Object object) { Log.d(TAG, "[On/Call]"); if (!(object instanceof MediaConnection)) { return; } _media = (MediaConnection) object; _media.answer(_msLocal); setMediaCallback(_media); _bCalling = true; updateUI(); } }); // !!!: Event/Close peer.on(Peer.PeerEventEnum.CLOSE, new OnCallback() { @Override public void onCallback(Object object) { Log.d(TAG, "[On/Close]"); } }); // !!!: Event/Disconnected peer.on(Peer.PeerEventEnum.DISCONNECTED, new OnCallback() { @Override public void onCallback(Object object) { Log.d(TAG, "[On/Disconnected]"); } }); // !!!: Event/Error peer.on(Peer.PeerEventEnum.ERROR, new OnCallback() { @Override public void onCallback(Object object) { PeerError error = (PeerError) object; Log.d(TAG, "[On/Error]" + error); String strMessage = "" + error; String strLabel = getString(android.R.string.ok); } }); } //Unset peer callback void unsetPeerCallback(Peer peer) { peer.on(Peer.PeerEventEnum.OPEN, null); peer.on(Peer.PeerEventEnum.CONNECTION, null); peer.on(Peer.PeerEventEnum.CALL, null); peer.on(Peer.PeerEventEnum.CLOSE, null); peer.on(Peer.PeerEventEnum.DISCONNECTED, null); peer.on(Peer.PeerEventEnum.ERROR, null); } void setMediaCallback(MediaConnection media) { media.on(MediaConnection.MediaEventEnum.STREAM, new OnCallback() { @Override public void onCallback(Object object) { _msRemote = (MediaStream) object; primaryCanvas.addSrc(_msRemote, 0); } }); // !!!: MediaEvent/Close media.on(MediaConnection.MediaEventEnum.CLOSE, new OnCallback() { @Override public void onCallback(Object object) { if (null == _msRemote) { return; } primaryCanvas.removeSrc(_msRemote, 0); _msRemote = null; _media = null; _bCalling = false; updateUI(); } }); // !!!: MediaEvent/Error media.on(MediaConnection.MediaEventEnum.ERROR, new OnCallback() { @Override public void onCallback(Object object) { PeerError error = (PeerError) object; Log.d(TAG, "[On/MediaError]" + error); String strMessage = "" + error; String strLabel = getString(android.R.string.ok); } }); /////////////// END: Set SkyWay peer Media connection callback //////////////// } //Unset media connection event callback. void unsetMediaCallback(MediaConnection media) { media.on(MediaConnection.MediaEventEnum.STREAM, null); media.on(MediaConnection.MediaEventEnum.CLOSE, null); media.on(MediaConnection.MediaEventEnum.ERROR, null); } // Listing all peers void listingPeers() { if ((null == _peer) || (null == _id) || (0 == _id.length())) { return; } _peer.listAllPeers(new OnCallback() { @Override public void onCallback(Object object) { if (!(object instanceof JSONArray)) { return; } JSONArray peers = (JSONArray) object; StringBuilder sbItems = new StringBuilder(); for (int i = 0; peers.length() > i; i++) { String strValue = ""; try { strValue = peers.getString(i); } catch (Exception e) { e.printStackTrace(); } if (0 == _id.compareToIgnoreCase(strValue)) { continue; } if (0 < sbItems.length()) { sbItems.append(","); } sbItems.append(strValue); } String strItems = sbItems.toString(); _listPeerIds = strItems.split(","); if ((null != _listPeerIds) && (0 < _listPeerIds.length)) { selectingPeer(); } } }); } /** * Selecting peer */ void selectingPeer() { if (null == _handler) { return; } _handler.post(new Runnable() { @Override public void run() { FragmentManager mgr = getFragmentManager(); } }); } /** * Closing connection. */ void closing() { if (false == _bCalling) { return; } _bCalling = false; if (null != _media) { _media.close(); } } void updateUI() { _handler.post(new Runnable() { @Override public void run() { if (null != btnAction) { if (false == _bCalling) { btnAction.setText("Calling"); } else { btnAction.setText("Hang up"); } } if (null != tvOwnId) { if (null == _id) { tvOwnId.setText(""); } else { tvOwnId.setText(_id); } } } }); } /** * Destroy Peer object. */ private void destroyPeer() { closing(); if (null != _msRemote) { primaryCanvas.removeSrc(_msRemote, 0); _msRemote.close(); _msRemote = null; } if (null != _msLocal) { extentionBrowserCanvas.removeSrc(_msLocal, 0); _msLocal.close(); _msLocal = null; } if (null != _media) { if (_media.isOpen) { _media.close(); } unsetMediaCallback(_media); _media = null; } Navigator.terminate(); if (null != _peer) { unsetPeerCallback(_peer); if (false == _peer.isDisconnected) { _peer.disconnect(); } if (false == _peer.isDestroyed) { _peer.destroy(); } _peer = null; } } @Override public void onStart() { super.onStart(); // Disable Sleep and Screen Lock Window wnd = getActivity().getWindow(); wnd.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); wnd.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } @Override public void onResume() { super.onResume(); // Set volume control stream type to WebRTC audio. getActivity().setVolumeControlStream(AudioManager.STREAM_VOICE_CALL); } @Override public void onPause() { // Set default volume control stream type. getActivity().setVolumeControlStream(AudioManager.USE_DEFAULT_STREAM_TYPE); super.onPause(); } @Override public void onStop() { // Enable Sleep and Screen Lock Window wnd = getActivity().getWindow(); wnd.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); wnd.clearFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); super.onStop(); } @Override public void onDestroy() { destroyPeer(); _listPeerIds = null; _handler = null; super.onDestroy(); } }
package org.commcare.activities; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.commcare.dalvik.R; import org.commcare.utils.StringUtils; /** * Activity that is shown when a user tries to install more than 2 apps at a time, without having * either superuser privileges or a multiple apps seat enabled on the device. * * @author Aliza Stone (astone@dimagi.com), created 6/9/16. */ public class MultipleAppsLimitWarningActivity extends CommCareActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.multiple_apps_limit_view); boolean installAttemptCameFromAppManager = getIntent() .getBooleanExtra(AppManagerActivity.KEY_LAUNCH_FROM_MANAGER, false); setupUI(installAttemptCameFromAppManager); } private void setupUI(final boolean installAttemptCameFromManager) { Button toManagerButton = findViewById(R.id.back_to_manager_button); if (installAttemptCameFromManager) { toManagerButton.setText(R.string.back_to_manager); } else { toManagerButton.setText(R.string.go_to_manager); } toManagerButton.setOnClickListener(v -> onManagerButtonClicked(installAttemptCameFromManager)); TextView mulitpleAppLimitTextView = findViewById(R.id.mulitple_app_limit_textview); String text = StringUtils.getStringRobust(this, R.string.multiple_apps_limit_message, String.valueOf(CommCareSetupActivity.MAX_ALLOWED_APPS)); mulitpleAppLimitTextView.setText(text); } private void onManagerButtonClicked(boolean installAttemptCameFromManager) { if (installAttemptCameFromManager) { setResult(RESULT_OK); finish(); } else { Intent i = new Intent(MultipleAppsLimitWarningActivity.this, AppManagerActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); } } }
package fr.pizzeria.dao; import java.util.List; import fr.pizzeria.exception.*; public interface Dao<T, E> { List<T> findAllPizzas(); void save(T element) throws DaoException; void update(E code, T element) throws DaoException; void delete(E code) throws DaoException; }
package com.xqbase.baiji.io; import com.xqbase.baiji.util.ByteBufferInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; /** * A non-buffering version of {@link BinaryDecoder}. * <p/> * This implementation will not read-ahead from the provided InputStream * beyond the minimum required to service the API requests. * * @see Encoder * * @author Tony He */ public class DirectBinaryDecoder extends BinaryDecoder { private InputStream in; private ByteReader byteReader; // used for {@link readFloat} and {@link readDouble}. private final byte[] buf = new byte[8]; public DirectBinaryDecoder(InputStream in) { super(); } private DirectBinaryDecoder configure(InputStream in) { if (null == in) { throw new NullPointerException("InputStream cannot be null"); } this.in = in; this.byteReader = (in instanceof ByteBufferInputStream) ? new ReuseByteReader((ByteBufferInputStream) in) : new ByteReader(); return this; } private class ByteReader { public ByteBuffer read(ByteBuffer old, int length) throws IOException { ByteBuffer result; if (old != null && length <= old.capacity()) { result = old; result.clear(); } else { result = ByteBuffer.allocate(length); } doReadBytes(result.array(), result.position(), length); result.limit(length); return result; } } private class ReuseByteReader extends ByteReader { private final ByteBufferInputStream bbi; public ReuseByteReader(ByteBufferInputStream bbi) { this.bbi = bbi; } } @Override public boolean readBoolean() throws IOException { int n = in.read(); if (n < 0) { throw new EOFException(); } return n == 1; } @Override public int readInt() throws IOException { // adapt variable-length, zig-zag encoding int n = 0; int b; int shift = 0; do { b = in.read(); if (b >= 0) { n |= (b & 0x7F) << shift; if ((b & 0x80) == 0) { // no more data return (n >>> 1) ^ -(n & 1); // back to two's-complement } } else { throw new EOFException(); } shift += 7; } while (shift < 32); throw new EOFException(); } @Override public long readLong() throws IOException { // adapt variable-length, zig-zag encoding long n = 0L; int b; int shift = 0; do { b = in.read(); if (b >= 0) { n |= (b & 0x7FL) << shift; if ((b & 0x80) == 0) { // no more data return (n >>> 1) & -(n & 1); } } else { throw new EOFException(); } shift += 7; } while (shift < 64); throw new EOFException(); } @Override public float readFloat() throws IOException { doReadBytes(buf, 0, 4); int n = (((int) buf[0]) & 0xff) | ((((int) buf[1]) & 0xff) << 8) | ((((int) buf[2]) & 0xff) << 16) | ((((int) buf[3]) & 0xff) << 24); return Float.intBitsToFloat(n); } @Override public double readDouble() throws IOException { doReadBytes(buf, 0, 8); long n = (((long) buf[0]) & 0xff) | ((((long) buf[1]) & 0xff) << 8) | ((((long) buf[2]) & 0xff) << 16) | ((((long) buf[3]) & 0xff) << 24) | ((((long) buf[4]) & 0xff) << 32) | ((((long) buf[5]) & 0xff) << 40) | ((((long) buf[6]) & 0xff) << 48) | ((((long) buf[7]) & 0xff) << 56); return Double.longBitsToDouble(n); } @Override public ByteBuffer readBytes(ByteBuffer old) throws IOException { int length = readInt(); return byteReader.read(old, length); } @Override protected void doReadBytes(byte[] bytes, int start, int length) throws IOException { for (; ;) { int n = in.read(bytes, start, length); // n represents that actual read byte number if (n == length || length == 0) { return; } else if (n < 0) { throw new EOFException(); } start += n; length -= n; } } }
package com.socrata.balboa.server; import com.socrata.balboa.server.exceptions.InvalidRequestException; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; public class ServiceUtils { public static Date parseDate(String input) throws InvalidRequestException { DateFormat onlyDate = new SimpleDateFormat("yyyy-MM-dd"); DateFormat dateWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); onlyDate.setTimeZone(TimeZone.getTimeZone("UTC")); dateWithTime.setTimeZone(TimeZone.getTimeZone("UTC")); // First try to parse with the time component. try { return dateWithTime.parse(input); } catch (ParseException e) { } // Try to parse first without a time component. try { return onlyDate.parse(input); } catch (ParseException e) { } throw new InvalidRequestException("Unparsable date '" + input + "'."); } public static void validateRequired(Map<String, String> params, String[] required) throws InvalidRequestException { for (String param : required) { if (!params.containsKey(param)) { throw new InvalidRequestException("Parameter '" + param + "' is required."); } } } public static Map<String, String> getParameters(HttpServletRequest request) throws IOException { Map params = request.getParameterMap(); Map<String, String> results = new HashMap<String, String>(); for (Object k : params.keySet()) { String key = (String)k; String[] value = (String[])params.get(key); results.put(key, value[0]); } return results; } }
package org.intermine.bio.dataconversion; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.intermine.bio.io.gff3.GFF3Parser; import org.intermine.bio.io.gff3.GFF3Record; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.TypeUtil; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; import org.intermine.xml.full.ItemFactory; import org.intermine.xml.full.ItemHelper; import org.intermine.xml.full.Reference; /** * Class to read a GFF3 source data and produce a data representation * * @author Wenyan Ji * @author Richard Smith */ public class GFF3Converter { private static final Logger LOG = Logger.getLogger(GFF3Converter.class); private Reference orgRef; private ItemWriter writer; private String seqClsName, orgTaxonId; private Item organism, dataSet, dataSource, seqDataSource; private Model tgtModel; private int itemid = 0; private Map analyses = new HashMap(); private Map seqs = new HashMap(); private Map identifierMap = new HashMap(); private GFF3RecordHandler handler; private ItemFactory itemFactory; private GFF3SeqHandler sequenceHandler; private boolean dontCreateLocations; protected IdResolverFactory resolverFactory; /** * Constructor * @param writer ItemWriter * @param seqClsName The class of the coordinate system for this GFF3 file (generally * Chromosome) * @param orgTaxonId The taxon ID of the organism we are loading * @param dataSourceName name for dataSource * @param dataSetTitle title for dataSet * @param seqDataSourceName name of source for synonym on sequence (col 1), often different * to dataSourceName * @param tgtModel the model to create items in * @param handler object to perform optional additional operations per GFF3 line * @param sequenceHandler the GFF3SeqHandler use to create sequence Items * @throws ObjectStoreException if something goes wrong */ public GFF3Converter(ItemWriter writer, String seqClsName, String orgTaxonId, String dataSourceName, String dataSetTitle, String seqDataSourceName, Model tgtModel, GFF3RecordHandler handler, GFF3SeqHandler sequenceHandler) throws ObjectStoreException { this.writer = writer; this.seqClsName = seqClsName; this.orgTaxonId = orgTaxonId; this.tgtModel = tgtModel; this.handler = handler; this.sequenceHandler = sequenceHandler; this.itemFactory = new ItemFactory(tgtModel, "1_"); organism = getOrganism(); dataSource = createItem("DataSource"); dataSource.addAttribute(new Attribute("name", dataSourceName)); writer.store(ItemHelper.convert(dataSource)); dataSet = createItem("DataSet"); dataSet.addAttribute(new Attribute("title", dataSetTitle)); dataSet.setReference("dataSource", dataSource); writer.store(ItemHelper.convert(dataSet)); if (!seqDataSourceName.equals(dataSourceName)) { seqDataSource = createItem("DataSource"); seqDataSource.addAttribute(new Attribute("name", seqDataSourceName)); writer.store(ItemHelper.convert(seqDataSource)); } else { seqDataSource = dataSource; } if (sequenceHandler == null) { this.sequenceHandler = new GFF3SeqHandler(); } handler.setItemFactory(itemFactory); handler.setIdentifierMap(identifierMap); handler.setDataSource(dataSource); handler.setDataSet(dataSet); handler.setOrganism(organism); } /** * Parse a bufferedReader and process GFF3 record * @param bReader the Reader * @throws java.io.IOException if an error occurs reading GFF * @throws ObjectStoreException if an error occurs storing items */ public void parse(BufferedReader bReader) throws IOException, ObjectStoreException { GFF3Record record; long start, now, opCount; opCount = 0; start = System.currentTimeMillis(); for (Iterator i = GFF3Parser.parse(bReader); i.hasNext();) { record = (GFF3Record) i.next(); process(record); opCount++; if (opCount % 10000 == 0) { now = System.currentTimeMillis(); LOG.info("processed " + opCount + " lines --took " + (now - start) + " ms"); start = System.currentTimeMillis(); } } } /** * store all the items * @throws ObjectStoreException if an error occurs storing items */ public void store() throws ObjectStoreException { // TODO should probably not store if an empty file Iterator iter = handler.getFinalItems().iterator(); while (iter.hasNext()) { writer.store(ItemHelper.convert((Item) iter.next())); } handler.clearFinalItems(); } /** * process GFF3 record and give a xml presentation * @param record GFF3Record * @throws ObjectStoreException if an error occurs storing items */ public void process(GFF3Record record) throws ObjectStoreException { // get rid of previous record Items from handler handler.clear(); List names = record.getNames(); List parents = record.getParents(); Item seq = getSeq(record.getSequenceID()); String term = record.getType(); String className = TypeUtil.javaiseClassName(term); String fullClassName = tgtModel.getPackageName() + "." + className; ClassDescriptor cd = tgtModel.getClassDescriptorByName(fullClassName); if (cd == null) { throw new IllegalArgumentException("no class found in model for: " + className + " (original GFF record type: " + term + ") for " + "record: " + record); } Set<Item> synonymsToAdd = new HashSet(); Item feature; // need to look up item id for this feature as may have already been a parent reference if (record.getId() != null) { feature = createItem(className, getIdentifier(record.getId())); feature.addAttribute(new Attribute("primaryIdentifier", record.getId())); } else { feature = createItem(className); } handler.setFeature(feature); if (names != null) { if (cd.getFieldDescriptorByName("symbol") == null) { feature.addAttribute(new Attribute("name", (String) names.get(0))); for (Iterator i = names.iterator(); i.hasNext(); ) { String recordName = (String) i.next(); Item synonym = createItem("Synonym"); if (!recordName.equals(record.getId())) { synonym.setReference("subject", feature.getIdentifier()); synonym.setAttribute("value", recordName); synonym.setAttribute("type", "name"); synonym.addToCollection("dataSets", dataSet); synonymsToAdd.add(synonym); } } } else { feature.addAttribute(new Attribute("symbol", (String) names.get(0))); for (Iterator i = names.iterator(); i.hasNext(); ) { String recordName = (String) i.next(); if (!recordName.equals(record.getId())) { Item synonym = createItem("Synonym"); synonym.setReference("subject", feature.getIdentifier()); synonym.setAttribute("value", recordName); synonym.setAttribute("type", "symbol"); synonym.addToCollection("dataSets", dataSet); synonymsToAdd.add(synonym); } } } } feature.addReference(getOrgRef()); feature.setCollection("dataSets", new ArrayList(Collections.singleton(dataSet.getIdentifier()))); if (record.getParents() != null) { // if parents -> create a SimpleRelation Set seenParents = new HashSet(); for (Iterator i = parents.iterator(); i.hasNext();) { String parentName = (String) i.next(); // add check for duplicate parent IDs to cope with pseudoobscura GFF if (!seenParents.contains(parentName)) { Item simpleRelation = createItem("SimpleRelation"); simpleRelation.setReference("object", getIdentifier(parentName)); simpleRelation.setReference("subject", feature.getIdentifier()); handler.addParentRelation(simpleRelation); seenParents.add(parentName); } } } Item relation; if (!record.getType().equals("chromosome") && seq != null) { boolean makeLocation = record.getStart() >= 1 && record.getEnd() >= 1 && !dontCreateLocations && handler.createLocations(record); if (makeLocation) { relation = createItem("Location"); int start = record.getStart(); int end = record.getEnd(); if (record.getStart() < record.getEnd()) { relation.addAttribute(new Attribute("start", String.valueOf(start))); relation.addAttribute(new Attribute("end", String.valueOf(end))); } else { relation.addAttribute(new Attribute("start", String.valueOf(end))); relation.addAttribute(new Attribute("end", String.valueOf(start))); } if (record.getStrand() != null && record.getStrand().equals("+")) { relation.addAttribute(new Attribute("strand", "1")); } else if (record.getStrand() != null && record.getStrand().equals("-")) { relation.addAttribute(new Attribute("strand", "-1")); } else { relation.addAttribute(new Attribute("strand", "0")); } if (record.getPhase() != null) { relation.setAttribute("phase", record.getPhase()); } int length = Math.abs(end - start) + 1; feature.setAttribute("length", String.valueOf(length)); } else { relation = createItem("SimpleRelation"); } relation.setReference("object", seq.getIdentifier()); relation.setReference("subject", feature.getIdentifier()); relation.setCollection("dataSets", Arrays.asList(new String[] { dataSet.getIdentifier() })); handler.setLocation(relation); if (seqClsName.equals("Chromosome") && (cd.getFieldDescriptorByName("chromosome") != null)) { feature.setReference("chromosome", seq.getIdentifier()); if (makeLocation) { feature.setReference("chromosomeLocation", relation); } } } handler.addDataSet(dataSet); if (record.getScore() != null && !String.valueOf(record.getScore()).equals("")) { Item computationalResult = createItem("ComputationalResult"); computationalResult.setAttribute("type", "score"); computationalResult.setAttribute("score", String.valueOf(record.getScore())); Item computationalAnalysis = getComputationalAnalysis(record.getSource()); computationalResult.setReference("analysis", computationalAnalysis.getIdentifier()); handler.setAnalysis(computationalAnalysis); handler.setResult(computationalResult); handler.addEvidence(computationalResult); } String orgAbb = null; String tgtSeqIdentifier = null; if (record.getAttributes().get("Organism") != null) { orgAbb = (String) ((List) record.getAttributes().get("Organism")).get(0); } if (record.getAttributes().get(seqClsName) != null) { tgtSeqIdentifier = (String) ((List) record.getAttributes().get(seqClsName)).get(0); } String tgtLocation = record.getTarget(); if (orgAbb != null && tgtSeqIdentifier != null && tgtLocation != null) { handler.setCrossGenomeMatch(feature, orgAbb, tgtSeqIdentifier, seq, tgtLocation); } if (feature.hasAttribute("secondaryIdentifier")) { Item synonym = createItem("Synonym"); synonym.addReference(new Reference("subject", feature.getIdentifier())); String value = feature.getAttribute("secondaryIdentifier").getValue(); synonym.addAttribute(new Attribute("value", value)); synonym.addAttribute(new Attribute("type", "identifier")); synonym.addReference(new Reference("source", dataSource.getIdentifier())); synonymsToAdd.add(synonym); } if (feature.hasAttribute("primaryIdentifier")) { Item synonym = createItem("Synonym"); synonym.addReference(new Reference("subject", feature.getIdentifier())); String value = feature.getAttribute("primaryIdentifier").getValue(); synonym.addAttribute(new Attribute("value", value)); synonym.addAttribute(new Attribute("type", "identifier")); synonym.addReference(new Reference("source", dataSource.getIdentifier())); synonymsToAdd.add(synonym); } for (Item synonym : synonymsToAdd) { handler.addItem(synonym); } handler.process(record); if (handler.getDataSetReferenceList().getRefIds().size() > 0) { feature.addCollection(handler.getDataSetReferenceList()); } handler.clearDataSetReferenceList(); if (handler.getEvidenceReferenceList().getRefIds().size() > 0) { feature.addCollection(handler.getEvidenceReferenceList()); } handler.clearEvidenceReferenceList(); if (handler.getPublicationReferenceList().getRefIds().size() > 0) { feature.addCollection(handler.getPublicationReferenceList()); } handler.clearPublicationReferenceList(); try { Iterator iter = handler.getItems().iterator(); while (iter.hasNext()) { Item item = (Item) iter.next(); writer.store(ItemHelper.convert(item)); } } catch (ObjectStoreException e) { LOG.error("Problem writing item to the itemwriter"); throw e; } } private String getIdentifier(String id) { String identifier = (String) identifierMap.get(id); if (identifier == null) { identifier = createIdentifier(); identifierMap.put(id, identifier); } return identifier; } /** * Perform any necessary clean-up after post-conversion * @throws Exception if an error occurs */ public void close() throws Exception { // empty - overridden as necessary } /** * Return the DataSet Item created for this GFF3Converter from the data set title passed * to the constructor. * @return the DataSet item */ public Item getDataSet() { return dataSet; } /** * Return the DataSource Item created for this GFF3Converter from the data source name passed * to the constructor. * @return the DataSource item */ public Item getDataSource() { return dataSource; } /** * Return the organism Item created for this GFF3Converter from the organism abbreviation passed * to the constructor. * @return the organism item * @throws ObjectStoreException if the Organism item can't be stored */ public Item getOrganism() throws ObjectStoreException { if (organism == null) { organism = createItem("Organism"); organism.setAttribute("taxonId", orgTaxonId); writer.store(ItemHelper.convert(organism)); } return organism; } /** * Return the sequence class name that was passed to the constructor. * @return the class name */ public String getSeqClsName() { return seqClsName; } /** * Return the * @return the target Model */ public Model getTgtModel() { return tgtModel; } /** * @return organism reference * @throws ObjectStoreException if the Organism Item can't be stored */ private Reference getOrgRef() throws ObjectStoreException { if (orgRef == null) { orgRef = new Reference("organism", getOrganism().getIdentifier()); } return orgRef; } /** * @return ComputationalAnalysis item created/from map * @throws ObjectStoreException if the Item can't be stored */ private Item getComputationalAnalysis(String algorithm) throws ObjectStoreException { Item analysis = (Item) analyses.get(algorithm); if (analysis == null) { analysis = createItem("ComputationalAnalysis"); analysis.setAttribute("algorithm", algorithm); writer.store(ItemHelper.convert(analysis)); analyses.put(algorithm, analysis); } return analysis; } /** * @return return/create item of class seqClsName for given identifier * @throws ObjectStoreException if the Item can't be stored */ private Item getSeq(String id) throws ObjectStoreException { // the seqHandler may have changed the id used, e.g. if using an IdResolver String identifier = sequenceHandler.getSeqIdentifier(id); if (identifier == null) { return null; } if (identifier.startsWith("chr")) { identifier = identifier.substring(3); } Item seq = (Item) seqs.get(identifier); if (seq == null) { seq = sequenceHandler.makeSequenceItem(this, identifier); // sequence handler may choose not to create sequence if (seq != null) { seq.addReference(getOrgRef()); seq.addToCollection("dataSets", getDataSet()); writer.store(ItemHelper.convert(seq)); Item synonym = createItem("Synonym"); synonym.setReference("subject", seq.getIdentifier()); synonym.setAttribute("value", identifier); synonym.setAttribute("type", "identifier"); synonym.addToCollection("dataSets", getDataSet()); handler.addItem(synonym); seqs.put(identifier, seq); } } handler.setSequence(seq); return seq; } /** * Create an item with given className * @param className the new class name * @return the created item */ protected Item createItem(String className) { return createItem(className, createIdentifier()); } /** * Create an item with given className and item identifier * @param className the class of the new Item * @param identifier the identifier of the new Item * @return the created item */ Item createItem(String className, String identifier) { return itemFactory.makeItem(identifier, className, ""); } private String createIdentifier() { return "0_" + itemid++; } /** * Set the dontCreateLocations flag * @param dontCreateLocations if false, create Locations of features on chromosomes while * processing */ public void setDontCreateLocations(boolean dontCreateLocations) { this.dontCreateLocations = dontCreateLocations; } }
package com.psddev.dari.db; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.psddev.dari.util.UuidUtils; import org.joda.time.DateTime; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; class MetricDatabase { //private static final Logger LOGGER = LoggerFactory.getLogger(MetricDatabase.class); public static final String METRIC_TABLE = "Metric"; public static final String METRIC_ID_FIELD = "id"; public static final String METRIC_TYPE_FIELD = "typeId"; public static final String METRIC_SYMBOL_FIELD = "symbolId"; public static final String METRIC_DIMENSION_FIELD = "dimensionId"; public static final String METRIC_DIMENSION_TABLE = "MetricDimension"; public static final String METRIC_DIMENSION_VALUE_FIELD = "value"; public static final String METRIC_DATA_FIELD = "data"; public static final int AMOUNT_DECIMAL_PLACES = 6; public static final long AMOUNT_DECIMAL_SHIFT = (long) Math.pow(10, AMOUNT_DECIMAL_PLACES); public static final long DATE_DECIMAL_SHIFT = 60000L; public static final int CUMULATIVEAMOUNT_POSITION = 1; public static final int AMOUNT_POSITION = 2; public static final int DATE_BYTE_SIZE = 4; public static final int AMOUNT_BYTE_SIZE = 8; private static final int QUERY_TIMEOUT = 3; private static final int DIMENSION_CACHE_SIZE = 1000; private final String symbol; private final SqlDatabase db; private final UUID id; private final UUID typeId; private MetricQuery query; private static final transient Cache<String, UUID> dimensionCache = CacheBuilder.newBuilder().maximumSize(DIMENSION_CACHE_SIZE).build(); private MetricInterval eventDateProcessor; private Long eventDate; private boolean isImplicitEventDate; public MetricDatabase(SqlDatabase database, UUID id, UUID typeId, String symbol) { this.db = database; this.symbol = symbol; this.id = id; this.typeId = typeId; } public MetricDatabase(UUID id, UUID typeId, String symbol) { this(Database.Static.getFirst(SqlDatabase.class), id, typeId, symbol); } public MetricDatabase(State state, String symbol) { this(state.getId(), state.getTypeId(), symbol); } public void setEventDateProcessor(MetricInterval processor) { this.eventDateProcessor = processor; } public UUID getId() { return id; } public UUID getTypeId() { return typeId; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof MetricDatabase)) { return false; } if (getId().equals(((MetricDatabase) other).getId()) && getTypeId().equals(((MetricDatabase) other).getTypeId()) && getSymbolId() == ((MetricDatabase) other).getSymbolId() && getEventDate() == ((MetricDatabase) other).getEventDate()) { return true; } else { return false; } } public String toKeyString() { StringBuilder str = new StringBuilder(); str.append(getId()); str.append(":"); str.append(getTypeId()); str.append(":"); str.append(getSymbolId()); str.append(":"); str.append(getEventDate()); return str.toString(); } public MetricInterval getEventDateProcessor() { if (eventDateProcessor == null) { eventDateProcessor = new MetricInterval.Hourly(); } return eventDateProcessor; } public SqlDatabase getDatabase() { return db; } public int getSymbolId() { return getQuery().getSymbolId(); } private MetricQuery getQuery() { if (query == null) { query = new MetricQuery(db.getSymbolId(symbol), id, typeId); } return query; } // This method should strip the minutes and seconds off of a timestamp, or otherwise process it public void setEventDate(DateTime eventDate) { if (eventDate == null) { eventDate = new DateTime(); isImplicitEventDate = true; } else { if (eventDate.getMillis() > new DateTime().getMillis()) { throw new RuntimeException("Metric.eventDate may not be a date in the future."); } isImplicitEventDate = false; } this.eventDate = getEventDateProcessor().process(eventDate); } public void setEventDateMillis(Long timestampMillis) { setEventDate((timestampMillis == null ? null : new DateTime(timestampMillis))); } public long getEventDate() { if (eventDate == null) { setEventDateMillis(null); } return eventDate; } public void setQueryDateRange(DateTime startTimestamp, DateTime endTimestamp) { setQueryTimestampRange((startTimestamp == null ? null : startTimestamp.getMillis()), (endTimestamp == null ? null : endTimestamp.getMillis())); } public void setQueryTimestampRange(Long startTimestamp, Long endTimestamp) { getQuery().setDateRange(startTimestamp, endTimestamp); } public Double getMetric(String dimensionValue) throws SQLException { return Static.getMetricByIdAndDimension(getDatabase(), getId(), getTypeId(), getQuery().getSymbolId(), getDimensionId(dimensionValue), getQuery().getStartTimestamp(), getQuery().getEndTimestamp()); } public Double getMetricSum() throws SQLException { return Static.getMetricSumById(getDatabase(), getId(), getTypeId(), getQuery().getSymbolId(), getQuery().getStartTimestamp(), getQuery().getEndTimestamp()); } public Map<String, Double> getMetricValues() throws SQLException { return Static.getMetricDimensionsById(getDatabase(), getId(), getTypeId(), getQuery().getSymbolId(), getQuery().getStartTimestamp(), getQuery().getEndTimestamp()); } public Map<DateTime, Double> getMetricTimeline(String dimensionValue, MetricInterval metricInterval) throws SQLException { if (metricInterval == null) { metricInterval = getEventDateProcessor(); } return Static.getMetricTimelineByIdAndDimension(getDatabase(), getId(), getTypeId(), getQuery().getSymbolId(), getDimensionId(dimensionValue), getQuery().getStartTimestamp(), getQuery().getEndTimestamp(), metricInterval); } public Map<DateTime, Double> getMetricSumTimeline(MetricInterval metricInterval) throws SQLException { if (metricInterval == null) { metricInterval = getEventDateProcessor(); } return Static.getMetricSumTimelineById(getDatabase(), getId(), getTypeId(), getQuery().getSymbolId(), getQuery().getStartTimestamp(), getQuery().getEndTimestamp(), metricInterval); } public void incrementMetric(String dimensionValue, Double amount) throws SQLException { if (amount == 0) return; // This actually causes some problems if it's not here Static.doIncrementUpdateOrInsert(getDatabase(), getId(), getTypeId(), getQuery().getSymbolId(), getDimensionId(dimensionValue), amount, getEventDate(), isImplicitEventDate); } public void incrementMetricByDimensionId(UUID dimensionId, Double amount) throws SQLException { if (amount == 0) return; // This actually causes some problems if it's not here Static.doIncrementUpdateOrInsert(getDatabase(), getId(), getTypeId(), getQuery().getSymbolId(), dimensionId, amount, getEventDate(), isImplicitEventDate); } public void setMetric(String dimensionValue, Double amount) throws SQLException { // This only works if we're not tracking eventDate if (getEventDate() != 0) { throw new RuntimeException("MetricDatabase.setMetric() can only be used if EventDateProcessor is None"); } Static.doSetUpdateOrInsert(getDatabase(), getId(), getTypeId(), getQuery().getSymbolId(), getDimensionId(dimensionValue), amount, getEventDate()); } public void deleteMetric() throws SQLException { Static.doMetricDelete(getDatabase(), getId(), getTypeId(), getQuery().getSymbolId()); } public void reconstructCumulativeAmounts() throws SQLException { Static.doReconstructCumulativeAmounts(getDatabase(), getId(), getTypeId(), getQuery().getSymbolId(), null); } public static UUID getDimensionIdByValue(String dimensionValue) { if (dimensionValue == null || "".equals(dimensionValue)) { return UuidUtils.ZERO_UUID; } UUID dimensionId = dimensionCache.getIfPresent(dimensionValue); if (dimensionId == null) { try { SqlDatabase db = Database.Static.getFirst(SqlDatabase.class); dimensionId = Static.getDimensionIdByValue(db, dimensionValue); if (dimensionId == null) { dimensionId = UuidUtils.createSequentialUuid(); Static.doInsertDimensionValue(db, dimensionId, dimensionValue); } dimensionCache.put(dimensionValue, dimensionId); } catch (SQLException e) { throw new DatabaseException(Database.Static.getFirst(SqlDatabase.class), "Error in MetricDatabase.getDimensionIdByValue() : " + e.getLocalizedMessage()); } } return dimensionId; } public UUID getDimensionId(String dimensionValue) throws SQLException { if (dimensionValue == null || "".equals(dimensionValue)) { return UuidUtils.ZERO_UUID; } UUID dimensionId = dimensionCache.getIfPresent(dimensionValue); if (dimensionId == null) { dimensionId = Static.getDimensionIdByValue(db, dimensionValue); if (dimensionId == null) { dimensionId = UuidUtils.createSequentialUuid(); Static.doInsertDimensionValue(db, dimensionId, dimensionValue); } dimensionCache.put(dimensionValue, dimensionId); } return dimensionId; } static class UpdateFailedException extends Exception { private static final long serialVersionUID = 1L; } /** {@link MetricDatabase} utility methods. */ public static final class Static { private Static() { } // Methods that generate SQL statements private static String getDataSql(SqlDatabase db, UUID id, UUID typeId, int symbolId, UUID dimensionId, Long minEventDate, Long maxEventDate, boolean selectMinData, boolean doDecodeToBytes, String extraSelectSql, String extraGroupBySql) { StringBuilder sqlBuilder = new StringBuilder(); SqlVendor vendor = db.getVendor(); sqlBuilder.append("SELECT "); if (dimensionId == null) { vendor.appendIdentifier(sqlBuilder, METRIC_DIMENSION_FIELD); sqlBuilder.append(", "); } StringBuilder maxDataBuilder = new StringBuilder("MAX("); vendor.appendIdentifier(maxDataBuilder, METRIC_DATA_FIELD); maxDataBuilder.append(")"); if (doDecodeToBytes) { vendor.appendMetricDataBytes(sqlBuilder, maxDataBuilder.toString()); } else { sqlBuilder.append(maxDataBuilder); } sqlBuilder.append(" "); vendor.appendIdentifier(sqlBuilder, "maxData"); if (selectMinData) { sqlBuilder.append(", "); StringBuilder minDataBuilder = new StringBuilder("MIN("); vendor.appendIdentifier(minDataBuilder, METRIC_DATA_FIELD); minDataBuilder.append(")"); if (doDecodeToBytes) { vendor.appendMetricDataBytes(sqlBuilder, minDataBuilder.toString()); } else { sqlBuilder.append(minDataBuilder); } sqlBuilder.append(" "); vendor.appendIdentifier(sqlBuilder, "minData"); } if (extraSelectSql != null && ! "".equals(extraSelectSql)) { sqlBuilder.append(", "); sqlBuilder.append(extraSelectSql); } sqlBuilder.append(" FROM "); vendor.appendIdentifier(sqlBuilder, METRIC_TABLE); sqlBuilder.append(" WHERE "); vendor.appendIdentifier(sqlBuilder, METRIC_ID_FIELD); sqlBuilder.append(" = "); vendor.appendValue(sqlBuilder, id); sqlBuilder.append(" AND "); vendor.appendIdentifier(sqlBuilder, METRIC_SYMBOL_FIELD); sqlBuilder.append(" = "); vendor.appendValue(sqlBuilder, symbolId); sqlBuilder.append(" AND "); vendor.appendIdentifier(sqlBuilder, METRIC_TYPE_FIELD); sqlBuilder.append(" = "); vendor.appendValue(sqlBuilder, typeId); if (dimensionId != null) { sqlBuilder.append(" AND "); vendor.appendIdentifier(sqlBuilder, METRIC_DIMENSION_FIELD); sqlBuilder.append(" = "); vendor.appendValue(sqlBuilder, dimensionId); } if (maxEventDate != null) { sqlBuilder.append(" AND "); vendor.appendIdentifier(sqlBuilder, METRIC_DATA_FIELD); sqlBuilder.append(" < "); vendor.appendMetricEncodeTimestampSql(sqlBuilder, null, maxEventDate, '0'); } if (minEventDate != null) { sqlBuilder.append(" AND "); vendor.appendIdentifier(sqlBuilder, METRIC_DATA_FIELD); sqlBuilder.append(" >= "); vendor.appendMetricEncodeTimestampSql(sqlBuilder, null, minEventDate, '0'); } if (dimensionId == null) { sqlBuilder.append(" GROUP BY "); vendor.appendIdentifier(sqlBuilder, METRIC_DIMENSION_FIELD); if (extraGroupBySql != null && ! "".equals(extraGroupBySql)) { sqlBuilder.append(", "); sqlBuilder.append(extraGroupBySql); } } else if (extraGroupBySql != null && ! "".equals(extraGroupBySql)) { sqlBuilder.append(" GROUP BY "); sqlBuilder.append(extraGroupBySql); } return sqlBuilder.toString(); } private static String getAllDataSql(SqlDatabase db, UUID id, UUID typeId, int symbolId, UUID dimensionId, Long minEventDate, Long maxEventDate, boolean doDecodeToBytes) { StringBuilder sqlBuilder = new StringBuilder(); SqlVendor vendor = db.getVendor(); sqlBuilder.append("SELECT "); if (dimensionId == null) { vendor.appendIdentifier(sqlBuilder, METRIC_DIMENSION_FIELD); sqlBuilder.append(", "); } if (doDecodeToBytes) { vendor.appendMetricDataBytes(sqlBuilder, METRIC_DATA_FIELD); } else { sqlBuilder.append(METRIC_DATA_FIELD); } sqlBuilder.append(" FROM "); vendor.appendIdentifier(sqlBuilder, METRIC_TABLE); sqlBuilder.append(" WHERE "); vendor.appendIdentifier(sqlBuilder, METRIC_ID_FIELD); sqlBuilder.append(" = "); vendor.appendValue(sqlBuilder, id); sqlBuilder.append(" AND "); vendor.appendIdentifier(sqlBuilder, METRIC_SYMBOL_FIELD); sqlBuilder.append(" = "); vendor.appendValue(sqlBuilder, symbolId); sqlBuilder.append(" AND "); vendor.appendIdentifier(sqlBuilder, METRIC_TYPE_FIELD); sqlBuilder.append(" = "); vendor.appendValue(sqlBuilder, typeId); if (dimensionId != null) { sqlBuilder.append(" AND "); vendor.appendIdentifier(sqlBuilder, METRIC_DIMENSION_FIELD); sqlBuilder.append(" = "); vendor.appendValue(sqlBuilder, dimensionId); } if (maxEventDate != null) { sqlBuilder.append(" AND "); vendor.appendIdentifier(sqlBuilder, METRIC_DATA_FIELD); sqlBuilder.append(" < "); vendor.appendMetricEncodeTimestampSql(sqlBuilder, null, maxEventDate, '0'); } if (minEventDate != null) { sqlBuilder.append(" AND "); vendor.appendIdentifier(sqlBuilder, METRIC_DATA_FIELD); sqlBuilder.append(" >= "); vendor.appendMetricEncodeTimestampSql(sqlBuilder, null, minEventDate, '0'); } sqlBuilder.append(" ORDER BY "); if (dimensionId == null) { vendor.appendIdentifier(sqlBuilder, METRIC_DIMENSION_FIELD); sqlBuilder.append(", "); } vendor.appendIdentifier(sqlBuilder, METRIC_DATA_FIELD); return sqlBuilder.toString(); } private static String getSumSql(SqlDatabase db, UUID id, UUID typeId, int symbolId, Long minEventDate, Long maxEventDate) { StringBuilder sqlBuilder = new StringBuilder(); SqlVendor vendor = db.getVendor(); String innerSql = getDataSql(db, id, typeId, symbolId, null, minEventDate, maxEventDate, true, false, null, null); sqlBuilder.append("SELECT "); appendSelectCalculatedAmountSql(sqlBuilder, vendor, "minData", "maxData", true); sqlBuilder.append(" FROM ("); sqlBuilder.append(innerSql); sqlBuilder.append(") x"); return sqlBuilder.toString(); } private static String getDimensionsSql(SqlDatabase db, UUID id, UUID typeId, int symbolId, Long minEventDate, Long maxEventDate) { StringBuilder sqlBuilder = new StringBuilder(); SqlVendor vendor = db.getVendor(); String innerSql = getDataSql(db, id, typeId, symbolId, null, minEventDate, maxEventDate, true, false, null, null); sqlBuilder.append("SELECT "); StringBuilder dimValField = new StringBuilder(); vendor.appendIdentifier(dimValField, "d"); dimValField.append("."); vendor.appendIdentifier(dimValField, METRIC_DIMENSION_VALUE_FIELD); sqlBuilder.append(vendor.convertRawToStringSql(METRIC_DIMENSION_VALUE_FIELD)); sqlBuilder.append(", "); appendSelectCalculatedAmountSql(sqlBuilder, vendor, "minData", "maxData", true); sqlBuilder.append(" FROM ("); sqlBuilder.append(innerSql); sqlBuilder.append(") x "); sqlBuilder.append(" JOIN "); // This could be a left join if we want to include NULL dimension values in this query. vendor.appendIdentifier(sqlBuilder, METRIC_DIMENSION_TABLE); sqlBuilder.append(" "); vendor.appendIdentifier(sqlBuilder, "d"); sqlBuilder.append(" ON ("); vendor.appendIdentifier(sqlBuilder, "x"); sqlBuilder.append("."); vendor.appendIdentifier(sqlBuilder, METRIC_DIMENSION_FIELD); sqlBuilder.append(" = "); vendor.appendIdentifier(sqlBuilder, "d"); sqlBuilder.append("."); vendor.appendIdentifier(sqlBuilder, METRIC_DIMENSION_FIELD); sqlBuilder.append(")"); sqlBuilder.append(" GROUP BY "); vendor.appendIdentifier(sqlBuilder, "d"); sqlBuilder.append("."); vendor.appendIdentifier(sqlBuilder, METRIC_DIMENSION_VALUE_FIELD); return sqlBuilder.toString(); } private static String getTimelineSql(SqlDatabase db, UUID id, UUID typeId, int symbolId, UUID dimensionId, Long minEventDate, Long maxEventDate, MetricInterval metricInterval, boolean doDecodeToBytes) { SqlVendor vendor = db.getVendor(); StringBuilder extraSelectSqlBuilder = new StringBuilder("MIN("); vendor.appendMetricSelectTimestampSql(extraSelectSqlBuilder, METRIC_DATA_FIELD); extraSelectSqlBuilder.append(") * "); vendor.appendValue(extraSelectSqlBuilder, DATE_DECIMAL_SHIFT); extraSelectSqlBuilder.append(" "); vendor.appendIdentifier(extraSelectSqlBuilder, "eventDate"); StringBuilder extraGroupBySqlBuilder = new StringBuilder(); vendor.appendMetricDateFormatTimestampSql(extraGroupBySqlBuilder, METRIC_DATA_FIELD, metricInterval); StringBuilder sqlBuilder = new StringBuilder(); String innerSql = getDataSql(db, id, typeId, symbolId, dimensionId, minEventDate, maxEventDate, true, doDecodeToBytes, extraSelectSqlBuilder.toString(), extraGroupBySqlBuilder.toString()); sqlBuilder.append(innerSql); sqlBuilder.append(" ORDER BY "); if (dimensionId == null) { vendor.appendIdentifier(sqlBuilder, "dimensionId"); sqlBuilder.append(", "); } vendor.appendIdentifier(sqlBuilder, "eventDate"); return sqlBuilder.toString(); } private static String getSumTimelineSql(SqlDatabase db, UUID id, UUID typeId, int symbolId, Long minEventDate, Long maxEventDate, MetricInterval metricInterval) { StringBuilder sqlBuilder = new StringBuilder(); SqlVendor vendor = db.getVendor(); String innerSql = getTimelineSql(db, id, typeId, symbolId, null, minEventDate, maxEventDate, metricInterval, false); sqlBuilder.append("SELECT "); appendSelectCalculatedAmountSql(sqlBuilder, vendor, "minData", "maxData", true); sqlBuilder.append(", "); vendor.appendIdentifier(sqlBuilder, "eventDate"); sqlBuilder.append(" FROM ("); sqlBuilder.append(innerSql); sqlBuilder.append(") x"); sqlBuilder.append(" GROUP BY "); vendor.appendIdentifier(sqlBuilder, "eventDate"); sqlBuilder.append(" ORDER BY "); vendor.appendIdentifier(sqlBuilder, "eventDate"); return sqlBuilder.toString(); } private static String getUpdateSql(SqlDatabase db, List<Object> parameters, UUID id, UUID typeId, int symbolId, UUID dimensionId, double amount, long eventDate, boolean increment, boolean updateFuture) { StringBuilder updateBuilder = new StringBuilder("UPDATE "); SqlVendor vendor = db.getVendor(); vendor.appendIdentifier(updateBuilder, METRIC_TABLE); updateBuilder.append(" SET "); vendor.appendIdentifier(updateBuilder, METRIC_DATA_FIELD); updateBuilder.append(" = "); vendor.appendMetricUpdateDataSql(updateBuilder, METRIC_DATA_FIELD, parameters, amount, eventDate, increment, updateFuture); updateBuilder.append(" WHERE "); vendor.appendIdentifier(updateBuilder, METRIC_ID_FIELD); updateBuilder.append(" = "); vendor.appendBindValue(updateBuilder, id, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, METRIC_TYPE_FIELD); updateBuilder.append(" = "); vendor.appendBindValue(updateBuilder, typeId, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, METRIC_SYMBOL_FIELD); updateBuilder.append(" = "); vendor.appendBindValue(updateBuilder, symbolId, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, METRIC_DIMENSION_FIELD); updateBuilder.append(" = "); vendor.appendBindValue(updateBuilder, dimensionId, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, METRIC_DATA_FIELD); updateBuilder.append(" >= "); vendor.appendMetricEncodeTimestampSql(updateBuilder, parameters, eventDate, '0'); if (!updateFuture) { updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, METRIC_DATA_FIELD); updateBuilder.append(" <= "); vendor.appendMetricEncodeTimestampSql(updateBuilder, parameters, eventDate, 'F'); } return updateBuilder.toString(); } private static String getRepairTypeIdSql(SqlDatabase db, List<Object> parameters, UUID id, UUID typeId, UUID dimensionId, int symbolId, long eventDate) { StringBuilder updateBuilder = new StringBuilder("UPDATE "); SqlVendor vendor = db.getVendor(); vendor.appendIdentifier(updateBuilder, METRIC_TABLE); updateBuilder.append(" SET "); vendor.appendIdentifier(updateBuilder, METRIC_TYPE_FIELD); updateBuilder.append(" = "); vendor.appendBindValue(updateBuilder, typeId, parameters); updateBuilder.append(" WHERE "); vendor.appendIdentifier(updateBuilder, METRIC_ID_FIELD); updateBuilder.append(" = "); vendor.appendBindValue(updateBuilder, id, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, METRIC_SYMBOL_FIELD); updateBuilder.append(" = "); vendor.appendBindValue(updateBuilder, symbolId, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, METRIC_DIMENSION_FIELD); updateBuilder.append(" = "); vendor.appendBindValue(updateBuilder, dimensionId, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, METRIC_DATA_FIELD); updateBuilder.append(" >= "); vendor.appendMetricEncodeTimestampSql(updateBuilder, null, eventDate, '0'); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, METRIC_DATA_FIELD); updateBuilder.append(" <= "); vendor.appendMetricEncodeTimestampSql(updateBuilder, null, eventDate, 'F'); return updateBuilder.toString(); } private static String getFixDataRowSql(SqlDatabase db, List<Object> parameters, UUID id, UUID typeId, int symbolId, UUID dimensionId, long eventDate, double cumulativeAmount, double amount) { StringBuilder updateBuilder = new StringBuilder("UPDATE "); SqlVendor vendor = db.getVendor(); vendor.appendIdentifier(updateBuilder, METRIC_TABLE); updateBuilder.append(" SET "); vendor.appendIdentifier(updateBuilder, METRIC_DATA_FIELD); updateBuilder.append(" = "); vendor.appendMetricFixDataSql(updateBuilder, METRIC_DATA_FIELD, parameters, eventDate, cumulativeAmount, amount); updateBuilder.append(" WHERE "); vendor.appendIdentifier(updateBuilder, METRIC_ID_FIELD); updateBuilder.append(" = "); vendor.appendBindValue(updateBuilder, id, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, METRIC_TYPE_FIELD); updateBuilder.append(" = "); vendor.appendBindValue(updateBuilder, typeId, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, METRIC_SYMBOL_FIELD); updateBuilder.append(" = "); vendor.appendBindValue(updateBuilder, symbolId, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, METRIC_DIMENSION_FIELD); updateBuilder.append(" = "); vendor.appendBindValue(updateBuilder, dimensionId, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, METRIC_DATA_FIELD); updateBuilder.append(" >= "); vendor.appendMetricEncodeTimestampSql(updateBuilder, null, eventDate, '0'); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, METRIC_DATA_FIELD); updateBuilder.append(" <= "); vendor.appendMetricEncodeTimestampSql(updateBuilder, null, eventDate, 'F'); return updateBuilder.toString(); } private static String getMetricInsertSql(SqlDatabase db, List<Object> parameters, UUID id, UUID typeId, int symbolId, UUID dimensionId, double amount, double cumulativeAmount, long eventDate) { SqlVendor vendor = db.getVendor(); StringBuilder insertBuilder = new StringBuilder("INSERT INTO "); vendor.appendIdentifier(insertBuilder, METRIC_TABLE); insertBuilder.append(" ("); LinkedHashMap<String, Object> cols = new LinkedHashMap<String, Object>(); cols.put(METRIC_ID_FIELD, id); cols.put(METRIC_TYPE_FIELD, typeId); cols.put(METRIC_SYMBOL_FIELD, symbolId); cols.put(METRIC_DIMENSION_FIELD, dimensionId); for (Map.Entry<String, Object> entry : cols.entrySet()) { vendor.appendIdentifier(insertBuilder, entry.getKey()); insertBuilder.append(", "); } vendor.appendIdentifier(insertBuilder, METRIC_DATA_FIELD); insertBuilder.append(") VALUES ("); for (Map.Entry<String, Object> entry : cols.entrySet()) { vendor.appendBindValue(insertBuilder, entry.getValue(), parameters); insertBuilder.append(", "); } vendor.appendBindMetricBytes(insertBuilder, toBytes(eventDate, cumulativeAmount, amount), parameters); insertBuilder.append(")"); return insertBuilder.toString(); } private static String getDeleteMetricSql(SqlDatabase db, UUID id, UUID typeId, int symbolId) { SqlVendor vendor = db.getVendor(); StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("DELETE FROM "); vendor.appendIdentifier(sqlBuilder, METRIC_TABLE); sqlBuilder.append(" WHERE "); vendor.appendIdentifier(sqlBuilder, METRIC_SYMBOL_FIELD); sqlBuilder.append(" = "); vendor.appendValue(sqlBuilder, symbolId); sqlBuilder.append(" AND "); vendor.appendIdentifier(sqlBuilder, METRIC_ID_FIELD); sqlBuilder.append(" = "); vendor.appendValue(sqlBuilder, id); sqlBuilder.append(" AND "); vendor.appendIdentifier(sqlBuilder, METRIC_TYPE_FIELD); sqlBuilder.append(" = "); vendor.appendValue(sqlBuilder, typeId); return sqlBuilder.toString(); } private static String getDimensionIdByValueSql(SqlDatabase db, String dimensionValue) { SqlVendor vendor = db.getVendor(); StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("SELECT "); vendor.appendIdentifier(sqlBuilder, METRIC_DIMENSION_FIELD); sqlBuilder.append(" FROM "); vendor.appendIdentifier(sqlBuilder, METRIC_DIMENSION_TABLE); sqlBuilder.append(" WHERE "); vendor.appendIdentifier(sqlBuilder, METRIC_DIMENSION_VALUE_FIELD); sqlBuilder.append(" = "); vendor.appendValue(sqlBuilder, dimensionValue); return sqlBuilder.toString(); } private static String getInsertDimensionValueSql(SqlDatabase db, List<Object> parameters, UUID dimensionId, String dimensionValue) { SqlVendor vendor = db.getVendor(); StringBuilder insertBuilder = new StringBuilder("INSERT INTO "); vendor.appendIdentifier(insertBuilder, METRIC_DIMENSION_TABLE); insertBuilder.append(" ("); vendor.appendIdentifier(insertBuilder, METRIC_DIMENSION_FIELD); insertBuilder.append(", "); vendor.appendIdentifier(insertBuilder, METRIC_DIMENSION_VALUE_FIELD); insertBuilder.append(") VALUES ("); vendor.appendBindValue(insertBuilder, dimensionId, parameters); insertBuilder.append(", "); vendor.appendBindValue(insertBuilder, dimensionValue, parameters); insertBuilder.append(")"); return insertBuilder.toString(); } // Methods that generate complicated bits of SQL public static void appendSelectCalculatedAmountSql(StringBuilder str, SqlVendor vendor, String minDataColumnIdentifier, String maxDataColumnIdentifier, boolean includeSum) { str.append("ROUND("); if (includeSum) str.append("SUM"); str.append("("); vendor.appendMetricSelectAmountSql(str, maxDataColumnIdentifier, CUMULATIVEAMOUNT_POSITION); str.append(" - ("); vendor.appendMetricSelectAmountSql(str, minDataColumnIdentifier, CUMULATIVEAMOUNT_POSITION); str.append(" - "); vendor.appendMetricSelectAmountSql(str, minDataColumnIdentifier, AMOUNT_POSITION); str.append(") "); str.append(")"); str.append(" / "); vendor.appendValue(str, AMOUNT_DECIMAL_SHIFT); str.append(","); vendor.appendValue(str, AMOUNT_DECIMAL_PLACES); str.append(") "); } // methods that convert bytes into values and back again private static byte[] toBytes(long eventDate, double cumulativeAmount, double amount) { Long cumulativeAmountLong = (long) (cumulativeAmount * AMOUNT_DECIMAL_SHIFT); Long amountLong = (long) (amount * AMOUNT_DECIMAL_SHIFT); Integer eventDateInt = (int) (eventDate / DATE_DECIMAL_SHIFT); int size, offset = 0; byte[] bytes = new byte[DATE_BYTE_SIZE+AMOUNT_BYTE_SIZE+AMOUNT_BYTE_SIZE]; // first 4 bytes: timestamp size = DATE_BYTE_SIZE; for (int i = 0; i < size; ++i) { bytes[i+offset] = (byte) (eventDateInt >> (size - i - 1 << 3)); } offset += size; // second 8 bytes: cumulativeAmount size = AMOUNT_BYTE_SIZE; for (int i = 0; i < size; ++i) { bytes[i+offset] = (byte) (cumulativeAmountLong >> (size - i - 1 << 3)); } offset += size; // last 8 bytes: amount size = AMOUNT_BYTE_SIZE; for (int i = 0; i < 8; ++i) { bytes[i+offset] = (byte) (amountLong >> (size - i - 1 << 3)); } return bytes; } private static double amountFromBytes(byte[] bytes, int position) { long amountLong = 0; int offset = DATE_BYTE_SIZE + ((position-1)*AMOUNT_BYTE_SIZE); for (int i = 0; i < AMOUNT_BYTE_SIZE; ++i) { amountLong = (amountLong << 8) | (bytes[i+offset] & 0xff); } return (double) amountLong / AMOUNT_DECIMAL_SHIFT; } private static long timestampFromBytes(byte[] bytes) { long timestamp = 0; for (int i = 0; i < DATE_BYTE_SIZE; ++i) { timestamp = (timestamp << 8) | (bytes[i] & 0xff); } return timestamp * DATE_DECIMAL_SHIFT; } /* private static double minMaxDataToAmount(byte[] minData, byte[] maxData) { double amount; double maxCumAmt = amountFromBytes(maxData, CUMULATIVEAMOUNT_POSITION); double minCumAmt = amountFromBytes(minData, CUMULATIVEAMOUNT_POSITION); double minAmt = amountFromBytes(minData, AMOUNT_POSITION); amount = (maxCumAmt - (minCumAmt - minAmt)); return amount; } */ // methods that actually touch the database private static void doIncrementUpdateOrInsert(SqlDatabase db, UUID id, UUID typeId, int symbolId, UUID dimensionId, double incrementAmount, long eventDate, boolean isImplicitEventDate) throws SQLException { Connection connection = db.openConnection(); try { if (isImplicitEventDate) { // If they have not passed in an eventDate, we can assume a couple of things: // 1) The event date is the CURRENT date // 2) There is NOT any FUTURE data // 3) We CANNOT assume the row exists List<Object> updateParameters = new ArrayList<Object>(); // Try to do an update. This is the best case scenario, and does not require any reads. String updateSql = getUpdateSql(db, updateParameters, id, typeId, symbolId, dimensionId, incrementAmount, eventDate, true, false); int rowsAffected = SqlDatabase.Static.executeUpdateWithList(connection, updateSql, updateParameters); if (0 == rowsAffected) { // There is no data for the current date. Now we have to read // the previous cumulative amount so we can insert a new row. byte[] data = getDataByIdAndDimension(db, id, typeId, symbolId, dimensionId, null, null); double previousCumulativeAmount = 0.0d; if (data != null) { previousCumulativeAmount = amountFromBytes(data, CUMULATIVEAMOUNT_POSITION); } // Try to insert, if that fails then try the update again List<Object> insertParameters = new ArrayList<Object>(); String insertSql = getMetricInsertSql(db, insertParameters, id, typeId, symbolId, dimensionId, incrementAmount, previousCumulativeAmount+incrementAmount, eventDate); tryInsertThenUpdate(db, connection, insertSql, insertParameters, updateSql, updateParameters); } } else { // First, find the max eventDate. Under normal circumstances, this will either be null (INSERT), before our eventDate (INSERT) or equal to our eventDate (UPDATE). byte[] data = getDataByIdAndDimension(db, id, typeId, symbolId, dimensionId, null, null); if (data == null || timestampFromBytes(data) < eventDate) { // No data for this eventDate; insert. double previousCumulativeAmount = 0.0d; if (data != null) { previousCumulativeAmount = amountFromBytes(data, CUMULATIVEAMOUNT_POSITION); } List<Object> insertParameters = new ArrayList<Object>(); String insertSql = getMetricInsertSql(db, insertParameters, id, typeId, symbolId, dimensionId, incrementAmount, previousCumulativeAmount+incrementAmount, eventDate); List<Object> updateParameters = new ArrayList<Object>(); String updateSql = getUpdateSql(db, updateParameters, id, typeId, symbolId, dimensionId, incrementAmount, eventDate, true, false); tryInsertThenUpdate(db, connection, insertSql, insertParameters, updateSql, updateParameters); } else if (timestampFromBytes(data) == eventDate) { // There is data for this eventDate; update it. List<Object> updateParameters = new ArrayList<Object>(); String updateSql = getUpdateSql(db, updateParameters, id, typeId, symbolId, dimensionId, incrementAmount, eventDate, true, false); SqlDatabase.Static.executeUpdateWithList(connection, updateSql, updateParameters); } else { // if (timestampFromBytes(data) > eventDate) // The max(eventDate) in the table is greater than our // event date. If there exists a row in the past, UPDATE it // or if not, INSERT. Either way we will be updating future // data, so just INSERT with a value of 0 if necessary, then // UPDATE all rows. byte[] oldData = getDataByIdAndDimension(db, id, typeId, symbolId, dimensionId, null, eventDate); if (oldData == null || timestampFromBytes(oldData) < eventDate) { double previousCumulativeAmount = 0.0d; if (oldData != null) { previousCumulativeAmount = amountFromBytes(oldData, CUMULATIVEAMOUNT_POSITION); } List<Object> insertParameters = new ArrayList<Object>(); String insertSql = getMetricInsertSql(db, insertParameters, id, typeId, symbolId, dimensionId, 0, previousCumulativeAmount, eventDate); tryInsertThenUpdate(db, connection, insertSql, insertParameters, null, null); // the UPDATE is going to be executed regardless of whether this fails - it's only inserting 0 anyway. } // Now update all the future rows. List<Object> updateParameters = new ArrayList<Object>(); String updateSql = getUpdateSql(db, updateParameters, id, typeId, symbolId, dimensionId, incrementAmount, eventDate, true, true); SqlDatabase.Static.executeUpdateWithList( connection, updateSql, updateParameters); } } } catch (UpdateFailedException e) { // There is an existing row that has the wrong type ID (bad data). Repair it and try again. List<Object> repairParameters = new ArrayList<Object>(); String repairSql = getRepairTypeIdSql(db, repairParameters, id, typeId, dimensionId, symbolId, eventDate); SqlDatabase.Static.executeUpdateWithList(connection, repairSql, repairParameters); doIncrementUpdateOrInsert(db, id, typeId, symbolId, dimensionId, incrementAmount, eventDate, isImplicitEventDate); } finally { db.closeConnection(connection); } } // This is for the occasional race condition when we check for the existence of a row, it does not exist, then two threads try to insert at (almost) the same time. private static void tryInsertThenUpdate(SqlDatabase db, Connection connection, String insertSql, List<Object> insertParameters, String updateSql, List<Object> updateParameters) throws SQLException, UpdateFailedException { try { SqlDatabase.Static.executeUpdateWithList(connection, insertSql, insertParameters); } catch (SQLException ex) { if (db.getVendor().isDuplicateKeyException(ex)) { // Try the update again, maybe we lost a race condition. if (updateSql != null) { int rowsAffected = SqlDatabase.Static.executeUpdateWithList(connection, updateSql, updateParameters); if (0 == rowsAffected) { // The only practical way this query updated 0 rows is if there is an existing row with the wrong typeId. throw new UpdateFailedException(); } } } else { throw ex; } } } private static void doSetUpdateOrInsert(SqlDatabase db, UUID id, UUID typeId, int symbolId, UUID dimensionId, double amount, long eventDate) throws SQLException { Connection connection = db.openConnection(); if (eventDate != 0L) { throw new RuntimeException("MetricDatabase.Static.doSetUpdateOrInsert() can only be used if EventDatePrecision is NONE; eventDate is " + eventDate + ", should be 0L."); } try { List<Object> updateParameters = new ArrayList<Object>(); String updateSql = getUpdateSql(db, updateParameters, id, typeId, symbolId, dimensionId, amount, eventDate, false, false); int rowsAffected = SqlDatabase.Static.executeUpdateWithList(connection, updateSql, updateParameters); if (rowsAffected == 0) { List<Object> insertParameters = new ArrayList<Object>(); String insertSql = getMetricInsertSql(db, insertParameters, id, typeId, symbolId, dimensionId, amount, amount, eventDate); tryInsertThenUpdate(db, connection, insertSql, insertParameters, updateSql, updateParameters); } } catch (UpdateFailedException e) { // There is an existing row that has the wrong type ID (bad data). Repair it and try again. List<Object> repairParameters = new ArrayList<Object>(); String repairSql = getRepairTypeIdSql(db, repairParameters, id, typeId, dimensionId, symbolId, eventDate); SqlDatabase.Static.executeUpdateWithList(connection, repairSql, repairParameters); doSetUpdateOrInsert(db, id, typeId, symbolId, dimensionId, amount, eventDate); } finally { db.closeConnection(connection); } } static void doMetricDelete(SqlDatabase db, UUID id, UUID typeId, int symbolId) throws SQLException { Connection connection = db.openConnection(); List<Object> parameters = new ArrayList<Object>(); try { String sql = getDeleteMetricSql(db, id, typeId, symbolId); SqlDatabase.Static.executeUpdateWithList(connection, sql, parameters); } finally { db.closeConnection(connection); } } static void doInsertDimensionValue(SqlDatabase db, UUID dimensionId, String dimensionValue) throws SQLException { Connection connection = db.openConnection(); List<Object> parameters = new ArrayList<Object>(); try { String sql = getInsertDimensionValueSql(db, parameters, dimensionId, dimensionValue); SqlDatabase.Static.executeUpdateWithList(connection, sql, parameters); } finally { db.closeConnection(connection); } } static void doFixDataRow(SqlDatabase db, UUID id, UUID typeId, int symbolId, UUID dimensionId, long eventDate, double cumulativeAmount, double amount) throws SQLException { Connection connection = db.openConnection(); List<Object> parameters = new ArrayList<Object>(); try { String updateSql = getFixDataRowSql(db, parameters, id, typeId, symbolId, dimensionId, eventDate, cumulativeAmount, amount); SqlDatabase.Static.executeUpdateWithList(connection, updateSql, parameters); } finally { db.closeConnection(connection); } } static void doReconstructCumulativeAmounts(SqlDatabase db, UUID id, UUID typeId, int symbolId, Long minEventDate) throws SQLException { // for each row, ordered by date, keep a running total of amount and update it into cumulativeAmount String selectSql = getAllDataSql(db, id, typeId, symbolId, null, minEventDate, null, true); Connection connection = db.openConnection(); try { Statement statement = connection.createStatement(); ResultSet result = db.executeQueryBeforeTimeout(statement, selectSql, QUERY_TIMEOUT); UUID lastDimensionId = null; double correctCumAmt = 0, calcAmt = 0, amt = 0, cumAmt = 0, lastCorrectCumAmt = 0; long timestamp = 0; while (result.next()) { UUID dimensionId = UuidUtils.fromBytes(result.getBytes(1)); if (lastDimensionId == null || ! dimensionId.equals(lastDimensionId)) { // new dimension, reset the correctCumAmt. This depends // on getAllDataSql ordering by dimensionId, data. correctCumAmt = 0; lastCorrectCumAmt = 0; } lastDimensionId = dimensionId; byte[] data = result.getBytes(2); amt = amountFromBytes(data, AMOUNT_POSITION); cumAmt = amountFromBytes(data, CUMULATIVEAMOUNT_POSITION); timestamp = timestampFromBytes(data); // if this amount is not equal to this cumulative amount // minus the previous CORRECT cumulative amount, adjust // this cumulative amount UPWARDS OR DOWNWARDS to match it. calcAmt = cumAmt - lastCorrectCumAmt; if (calcAmt != amt) { correctCumAmt = lastCorrectCumAmt + amt; } else { correctCumAmt = cumAmt; } if (correctCumAmt != cumAmt) { doFixDataRow(db, id, typeId, symbolId, dimensionId, timestamp, correctCumAmt, amt); } lastCorrectCumAmt = correctCumAmt; } } finally { db.closeConnection(connection); } } // METRIC SELECT private static Double getMetricSumById(SqlDatabase db, UUID id, UUID typeId, int symbolId, Long minEventDate, Long maxEventDate) throws SQLException { String sql = getSumSql(db, id, typeId, symbolId, minEventDate, maxEventDate); Double amount = null; Connection connection = db.openReadConnection(); try { Statement statement = connection.createStatement(); ResultSet result = db.executeQueryBeforeTimeout(statement, sql, QUERY_TIMEOUT); if (result.next()) { amount = result.getDouble(1); } } finally { db.closeConnection(connection); } return amount; } private static Map<String, Double> getMetricDimensionsById(SqlDatabase db, UUID id, UUID typeId, int symbolId, Long minEventDate, Long maxEventDate) throws SQLException { String sql = getDimensionsSql(db, id, typeId, symbolId, minEventDate, maxEventDate); Map<String, Double> values = new HashMap<String, Double>(); Connection connection = db.openReadConnection(); try { Statement statement = connection.createStatement(); ResultSet result = db.executeQueryBeforeTimeout(statement, sql, QUERY_TIMEOUT); while (result.next()) { values.put(result.getString(1), result.getDouble(2)); } } finally { db.closeConnection(connection); } return values; } private static Double getMetricByIdAndDimension(SqlDatabase db, UUID id, UUID typeId, int symbolId, UUID dimensionId, Long minEventDate, Long maxEventDate) throws SQLException { if (minEventDate == null) { byte[] data = getDataByIdAndDimension(db, id, typeId, symbolId, dimensionId, minEventDate, maxEventDate); if (data == null) return null; return amountFromBytes(data, CUMULATIVEAMOUNT_POSITION); } else { List<byte[]> datas = getMinMaxDataByIdAndDimension(db, id, typeId, symbolId, dimensionId, minEventDate, maxEventDate); if (datas.size() == 0) return null; if (datas.get(0) == null) return null; double maxCumulativeAmount = amountFromBytes(datas.get(0), CUMULATIVEAMOUNT_POSITION); double minCumulativeAmount = amountFromBytes(datas.get(1), CUMULATIVEAMOUNT_POSITION); double minAmount = amountFromBytes(datas.get(1), AMOUNT_POSITION); return maxCumulativeAmount - (minCumulativeAmount - minAmount); } } private static Map<DateTime, Double> getMetricTimelineByIdAndDimension(SqlDatabase db, UUID id, UUID typeId, int symbolId, UUID dimensionId, Long minEventDate, Long maxEventDate, MetricInterval metricInterval) throws SQLException { String sql = getTimelineSql(db, id, typeId, symbolId, dimensionId, minEventDate, maxEventDate, metricInterval, true); Map<DateTime, Double> values = new LinkedHashMap<DateTime, Double>(); Connection connection = db.openReadConnection(); try { Statement statement = connection.createStatement(); ResultSet result = db.executeQueryBeforeTimeout(statement, sql, QUERY_TIMEOUT); while (result.next()) { byte[] maxData = result.getBytes(1); byte[] minData = result.getBytes(2); long timestamp = result.getLong(3); timestamp = metricInterval.process(new DateTime(timestamp)); double maxCumulativeAmount = amountFromBytes(maxData, CUMULATIVEAMOUNT_POSITION); double minCumulativeAmount = amountFromBytes(minData, CUMULATIVEAMOUNT_POSITION); double minAmount = amountFromBytes(minData, AMOUNT_POSITION); double intervalAmount = maxCumulativeAmount - (minCumulativeAmount - minAmount); values.put(new DateTime(timestamp), intervalAmount); } } finally { db.closeConnection(connection); } return values; } private static Map<DateTime, Double> getMetricSumTimelineById(SqlDatabase db, UUID id, UUID typeId, int symbolId, Long minEventDate, Long maxEventDate, MetricInterval metricInterval) throws SQLException { String sql = getSumTimelineSql(db, id, typeId, symbolId, minEventDate, maxEventDate, metricInterval); Map<DateTime, Double> values = new LinkedHashMap<DateTime, Double>(); Connection connection = db.openReadConnection(); try { Statement statement = connection.createStatement(); ResultSet result = db.executeQueryBeforeTimeout(statement, sql, QUERY_TIMEOUT); while (result.next()) { double intervalAmount = result.getLong(1); long timestamp = result.getLong(2); timestamp = metricInterval.process(new DateTime(timestamp)); values.put(new DateTime(timestamp), intervalAmount); } } finally { db.closeConnection(connection); } return values; } /* private static Long getMaxEventDateById(SqlDatabase db, UUID id, UUID typeId, int symbolId, Long minEventDate, Long maxEventDate) throws SQLException { byte[] data = getDataById(db, id, typeId, symbolId, minEventDate, maxEventDate); if (data == null) return null; return timestampFromBytes(data); } */ private static byte[] getDataByIdAndDimension(SqlDatabase db, UUID id, UUID typeId, int symbolId, UUID dimensionId, Long minEventDate, Long maxEventDate) throws SQLException { String sql = getDataSql(db, id, typeId, symbolId, dimensionId, minEventDate, maxEventDate, false, true, null, null); byte[] data = null; Connection connection = db.openReadConnection(); try { Statement statement = connection.createStatement(); ResultSet result = db.executeQueryBeforeTimeout(statement, sql, QUERY_TIMEOUT); if (result.next()) { data = result.getBytes(1); } } finally { db.closeConnection(connection); } return data; } private static List<byte[]> getMinMaxDataByIdAndDimension(SqlDatabase db, UUID id, UUID typeId, int symbolId, UUID dimensionId, Long minEventDate, Long maxEventDate) throws SQLException { List<byte[]> datas = new ArrayList<byte[]>(); String sql = getDataSql(db, id, typeId, symbolId, dimensionId, minEventDate, maxEventDate, true, true, null, null); Connection connection = db.openReadConnection(); try { Statement statement = connection.createStatement(); ResultSet result = db.executeQueryBeforeTimeout(statement, sql, QUERY_TIMEOUT); if (result.next()) { datas.add(result.getBytes(1)); datas.add(result.getBytes(2)); } } finally { db.closeConnection(connection); } return datas; } private static UUID getDimensionIdByValue(SqlDatabase db, String dimensionValue) throws SQLException { String sql = getDimensionIdByValueSql(db, dimensionValue); Connection connection = db.openReadConnection(); try { Statement statement = connection.createStatement(); ResultSet result = db.executeQueryBeforeTimeout(statement, sql, QUERY_TIMEOUT); if (result.next()) { return db.getVendor().getUuid(result, 1); } } finally { db.closeConnection(connection); } return null; } } // MODIFICATIONS @Record.FieldInternalNamePrefix("metrics.") public static class FieldData extends Modification<ObjectField> { private transient MetricInterval eventDateProcessor; private boolean metricValue; private String eventDateProcessorClassName; public boolean isMetricValue() { return metricValue; } public void setMetricValue(boolean metricValue) { this.metricValue = metricValue; } @SuppressWarnings("unchecked") public MetricInterval getEventDateProcessor() { if (eventDateProcessor == null) { if (eventDateProcessorClassName == null) { return null; } else { try { Class<MetricInterval> cls = (Class<MetricInterval>) Class.forName(eventDateProcessorClassName); eventDateProcessor = cls.newInstance(); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } return eventDateProcessor; } public void setEventDateProcessorClass(Class<? extends MetricInterval> eventDateProcessorClass) { this.eventDateProcessorClassName = eventDateProcessorClass.getName(); } } }
package example; // tag::user_guide[] import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assumptions.assumeTrue; import example.util.Calculator; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; public class ExampleTestCase { private final Calculator calculator = new Calculator(); @Test @Disabled("for demonstration purposes") void skippedTest() { // skipped ... } @Test void succeedingTest() { assertEquals(42, calculator.multiply(6, 7)); } @Test void abortedTest() { assumeTrue("abc".contains("Z")); // aborted ... } @Test void failingTest() { // The following throws an ArithmeticException: "/ by zero" calculator.divide(1, 0); } } // end::user_guide[]
package promotionSystem; import org.junit.Assert; import org.junit.Test; import static promotionSystem.builder.AlianzaBuilder.crearAlianza; public class PersonajeTest { Personaje personajeAtacante; Personaje personajeAtacado; public void crearPersonajes(){ personajeAtacante=new Personaje(); personajeAtacado=new Personaje(); } @Test public void siAtacaDisminuyeEnergiaPropiaYSaludDelRival(){ crearPersonajes(); personajeAtacado.setDefensa(0); personajeAtacante.atacar(personajeAtacado); Assert.assertTrue(personajeAtacado.getSalud()==90 && personajeAtacante.getEnergia()==90); } @Test public void siAtacaUnaVezElPersonajeAtacadoTodaviaSigueVivo(){ crearPersonajes(); personajeAtacante.atacar(personajeAtacado); Assert.assertTrue(personajeAtacado.estaVivo()); } @Test public void siElAtacadoTieneMenosVidaQueElAtaqueDelPersonajeAtacanteElPersonajeAtacadoMuere(){ crearPersonajes(); Assert.assertTrue(personajeAtacado.estaVivo()); personajeAtacado.setDefensa(0); personajeAtacado.setSalud(9); personajeAtacante.atacar(personajeAtacado); Assert.assertFalse(personajeAtacado.estaVivo()); } @Test public void siElAtacadoTieneIgualVidaQueElAtaqueDelPersonajeAtacanteElPersonajeAtacadoMuere(){ crearPersonajes(); Assert.assertTrue(personajeAtacado.estaVivo()); personajeAtacado.setDefensa(0); personajeAtacado.setSalud(10); personajeAtacante.atacar(personajeAtacado); Assert.assertFalse(personajeAtacado.estaVivo()); } @Test public void siTieneMenosSaludQueLaInicialYEsCuradoLaSaludVuelveAlMaximo(){ personajeAtacado=new Personaje(); personajeAtacado.setSalud(10); personajeAtacado.serCurado(); Assert.assertTrue(personajeAtacado.getSalud()==100); } @Test public void siTieneMenosEnergiaQueLaInicialYEsEnergizadoLaVuelveAlMaximo(){ personajeAtacante=new Personaje(); personajeAtacante.setEnergia(10); personajeAtacante.serEnergizado(); Assert.assertTrue(personajeAtacante.getEnergia()==100); } @Test public void siSeQuedoSinEnergiaNoPuedeAtacar(){ crearPersonajes(); personajeAtacante.setEnergia(0); personajeAtacante.atacar(personajeAtacado); Assert.assertTrue(personajeAtacado.getSalud()==100); } @Test public void siTieneVidaAlMaximoNoPuedeAumentarSuSaludAlSerCurado(){ personajeAtacado=new Personaje(); Assert.assertTrue(personajeAtacado.getSalud()==100); personajeAtacado.serCurado(); Assert.assertTrue(personajeAtacado.getSalud()==100); } @Test public void siTieneEnergiaAlMaximoNoPuedeAumentarSuEnergiaAlSerEnergizado(){ personajeAtacante=new Personaje(); Assert.assertTrue(personajeAtacante.getEnergia()==100); personajeAtacante.serEnergizado(); Assert.assertTrue(personajeAtacante.getEnergia()==100); } @Test public void siLaDefensaDelAtacadoEsMayorAlAtaqueDelAtacadoNoRecibeDano(){ crearPersonajes(); personajeAtacado.setDefensa(15); personajeAtacante.atacar(personajeAtacado); Assert.assertTrue(personajeAtacado.getSalud()==100); } //FIXME corregir nombre del metodo @Test public void siLaDefensaEsMenorQueElAtaqueLaSaludDisminuyePeroNoTanto(){ crearPersonajes(); personajeAtacado.setDefensa(5); personajeAtacante.atacar(personajeAtacado); Assert.assertTrue(personajeAtacado.getSalud()==95); } @Test public void debeDevolverLosPuntosDeAtaque(){ personajeAtacante=new Personaje(); Assert.assertTrue(personajeAtacante.obtenerPuntosDeAtaque()==10); } @Test public void debeDevolverLosPuntosDeDefensa(){ personajeAtacante=new Personaje(); Assert.assertTrue(personajeAtacante.obtenerPuntosDeDefensa()==2); } @Test public void debeDevolverLosPuntosDeMagia(){ personajeAtacante=new Personaje(); Assert.assertTrue(personajeAtacante.obtenerPuntosDeMagia()==5); } @Test public void debeAumentarExperiencia(){ personajeAtacante=new Personaje(); Assert.assertTrue(personajeAtacante.getExperiencia()==0); personajeAtacante.subirExperiencia(200); Assert.assertTrue(personajeAtacante.getExperiencia()==200); } @Test public void SiPoseeLaExperienciaSuficienteElPersonajeDebeAumentarNivel(){ personajeAtacante=new Personaje(); personajeAtacante.subirExperiencia(20); personajeAtacante.subirNivel(); Assert.assertTrue(personajeAtacante.getNivel()==1); } @Test public void SiNoPoseeLaExperienciaSuficienteElPersonajeDebeAumentarNivel(){ personajeAtacante=new Personaje(); personajeAtacante.subirExperiencia(9); personajeAtacante.subirNivel(); Assert.assertTrue(personajeAtacante.getNivel()==0); } @Test public void debeElegirElPrimerPersonajeComoVictima(){ Alianza alianzaEnemiga = crearAlianza(1); personajeAtacante = new Personaje(); Personaje victima = personajeAtacante.elegirVictima(alianzaEnemiga, 1); Assert.assertEquals(0, alianzaEnemiga.getPersonajes().indexOf(victima)); } }
package testharness; import userprofile.controller.LoginCntl; import userprofile.view.LoginUI; import foodmood.controller.NavigationCntl; /** * * @author HannahGarthwaite */ public class LoginTest { public LoginTest() { LoginCntl theLoginController = new LoginCntl(); if(theLoginController != null) { System.out.println("The Login Controller was created."); } String username = "correct"; char[] password = "password".toCharArray(); char[] incorrectPassword = "incorrect".toCharArray(); LoginUI theLoginView = new LoginUI(theLoginController); theLoginView.enterCredentialsFromSavedValues(username, incorrectPassword); System.out.println("Incorrect user credentials entered in LoginView"); //theLoginView.submitUserCredentials(); System.out.println("Incorrect user credentials sent for login"); theLoginView.enterCredentialsFromSavedValues(username, incorrectPassword); System.out.println("Correct user credentials entered in LoginView"); //theLoginView.submitUserCredentials(); System.out.println("Correct user credentials sent for login"); if(theLoginController.authenticateUserCredentials(username, password)){ System.out.println("The Login Controller successfully authenticated user."); }else{ System.out.println("The Login Controller failed to authenticate user."); } if(theLoginController.authenticateUserCredentials(username, incorrectPassword)){ System.out.println("The Login Controller successfully denied access."); }else{ System.out.println("The Login Controller incorrectly logged a user in."); } // theLoginController.login(); System.out.println("The Navigation Controller was created by Login Control."); NavigationTest theNavigationTest = new NavigationTest(); } }
package tests; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Arrays; import org.junit.Test; import logic.*; public class BoardLogicTests { @Test public void test_stateAfterDefaultInit() { BoardLogic logic = new BoardLogic(); FieldType[][] expectedState = getDefaultState(); assertEquals("y lengths are not the same", expectedState.length, logic.getBoardState().length); for (int i = 0; i < logic.getBoardSize(); i++) { assertEquals("Current state x length and expected state x length are not the same", logic.getBoardState()[i].length, expectedState[i].length); assertEquals("Current state xy value and expected state xy value are not the same", logic.getBoardState()[i][i], expectedState[i][i]); } } @Test public void test_stateAfterCustomInit() { try { BoardLogic logic = new BoardLogic(8); FieldType[][] expectedState = { {FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty}, {FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty}, {FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty}, {FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Player1,FieldType.Player2,FieldType.Empty,FieldType.Empty,FieldType.Empty}, {FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Player2,FieldType.Player1,FieldType.Empty,FieldType.Empty,FieldType.Empty}, {FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty}, {FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty}, {FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty} }; assertEquals("Length is not the same", expectedState.length, logic.getBoardState().length); for (int i = 0; i < logic.getBoardSize(); i++) { assertEquals("Current state x length and expected state x length are not the same", logic.getBoardState()[i].length, expectedState[i].length); for (int j = 0; j < logic.getBoardSize(); j++) { assertEquals("Current state xy value and expected state xy value are not the same", logic.getBoardState()[i][j], expectedState[i][j]); } } } catch (Exception e) { fail("Failed to init the logic with a valid number"); } } @Test public void test_scoreAfterInit() { BoardLogic logic = new BoardLogic(); assertEquals("Current score p1 value is not 2", 2, logic.getScore().p1()); assertEquals("Current score p2 value is not 2", 2, logic.getScore().p2()); } @Test public void test_validMove() { BoardLogic logic = new BoardLogic(); FieldPosition p = new FieldPosition(1,3); assertTrue("Move should be valid but result is false",logic.makeMove(FieldType.Player1, p)); } @Test public void test_invalidMove() { BoardLogic logic = new BoardLogic(); FieldPosition p = new FieldPosition(0,0); assertFalse("Move should be invalid but result is true",logic.makeMove(FieldType.Player1, p)); } @Test public void test_scoreAfterValidMove() { BoardLogic logic = new BoardLogic(); FieldPosition p = new FieldPosition(1,3); logic.makeMove(FieldType.Player1, p); assertEquals("Current score p1 value is not 4", logic.getScore().p1(), 4); assertEquals("Current score p2 value is not 1", logic.getScore().p2(), 1); } @Test public void test_scoreAfterInvalidMove() { BoardLogic logic = new BoardLogic(); FieldPosition p = new FieldPosition(0,0); logic.makeMove(FieldType.Player1, p); assertEquals("Current score p1 value is not 2", logic.getScore().p1(), 2); assertEquals("Current score p2 value is not 2", logic.getScore().p2(), 2); } @Test public void test_possibleMoveCountEmpty() { BoardLogic logic = new BoardLogic(); ArrayList<FieldPosition> moves = logic.getPossibleMoves(FieldType.Empty); assertEquals("Possible moves are not 0", 0, moves.size()); } @Test public void test_possibleMoveCountPlayer1() { BoardLogic logic = new BoardLogic(); ArrayList<FieldPosition> moves = logic.getPossibleMoves(FieldType.Player1); assertEquals("Move count is not 4", 4, moves.size()); } @Test public void test_possibleMovesPlayer1() { BoardLogic logic = new BoardLogic(); FieldPosition p1 = new FieldPosition(3,1); FieldPosition p2 = new FieldPosition(4,2); FieldPosition p3 = new FieldPosition(1,3); FieldPosition p4 = new FieldPosition(2,4); ArrayList<FieldPosition> expectedResult = new ArrayList<FieldPosition>(); expectedResult.addAll(Arrays.asList(p1, p2, p3, p4)); ArrayList<FieldPosition> moves = logic.getPossibleMoves(FieldType.Player1); assertEquals("not the same", expectedResult, moves); } @Test public void test_possibleMoveCountPlayer2() { BoardLogic logic = new BoardLogic(); ArrayList<FieldPosition> moves = logic.getPossibleMoves(FieldType.Player2); assertEquals("Move count is not 4", 4, moves.size()); } @Test public void test_possibleMovesPlayer2() { BoardLogic logic = new BoardLogic(); FieldPosition p1 = new FieldPosition(2,1); FieldPosition p2 = new FieldPosition(1,2); FieldPosition p3 = new FieldPosition(4,3); FieldPosition p4 = new FieldPosition(3,4); ArrayList<FieldPosition> expectedResult = new ArrayList<FieldPosition>(); expectedResult.addAll(Arrays.asList(p1, p2, p3, p4)); ArrayList<FieldPosition> moves = logic.getPossibleMoves(FieldType.Player2); assertEquals("not the same", expectedResult, moves); } @Test public void test_objectEqualityAfterCloning() { BoardLogic logic = new BoardLogic(); BoardLogic clone; try { clone = (BoardLogic) logic.clone(); assertEquals("Classes are not equal", logic.getClass(), clone.getClass()); assertNotEquals("Objects shouldn't reference to the same memory address", logic, clone); } catch (Exception e) { fail("Cloning should not throw an exception"); } } @Test public void test_sizeEqualityAfterCloning() { BoardLogic logic = new BoardLogic(); BoardLogic clone; try { clone = (BoardLogic) logic.clone(); assertEquals("Sizes are not equal", logic.getBoardSize(), clone.getBoardSize()); } catch (Exception e) { fail("Cloning should not throw an exception"); } } @Test public void test_stateEqualityAfterCloning() { BoardLogic logic = new BoardLogic(); BoardLogic clone; try { clone = (BoardLogic) logic.clone(); assertNotEquals("States shouldn't reference to the same memory address", logic.getBoardState(), clone.getBoardState()); int size = logic.getBoardSize(); for (int i = 0; i < size; i++) { assertNotEquals("Second dimension on index "+ i + " shouldn't reference to the same memory address", logic.getBoardState()[i], clone.getBoardState()[i]); for(int j = 0; j < size; j++) { assertEquals("State values are not equal", logic.getBoardState()[i][j], clone.getBoardState()[i][j]); } } } catch (Exception e) { fail("Cloning should not throw an exception"); } } @Test public void test_horizontalForwardMove() { BoardLogic logic = new BoardLogic(); FieldPosition p = new FieldPosition(1, 2); logic.makeMove(FieldType.Player2, p); FieldType[][] expected = getDefaultState(); expected[2][1] = FieldType.Player2; expected[2][2] = FieldType.Player2; FieldType[][] result = logic.getBoardState(); for (int i = 0; i < logic.getBoardSize(); i++) { for (int j = 0; j < logic.getBoardSize(); j++ ) { assertEquals("Current state xy value and expected state xy value are not the same", result[i][j], expected[i][j]); } } } @Test public void test_horizontalBackwardMove() { BoardLogic logic = new BoardLogic(); FieldPosition p = new FieldPosition(4, 2); logic.makeMove(FieldType.Player1, p); FieldType[][] expected = getDefaultState(); expected[2][3] = FieldType.Player1; expected[2][4] = FieldType.Player1; FieldType[][] result = logic.getBoardState(); for (int i = 0; i < logic.getBoardSize(); i++) { for (int j = 0; j < logic.getBoardSize(); j++ ) { assertEquals("Current state xy value and expected state xy value are not the same", result[i][j], expected[i][j]); } } } @Test public void test_verticalBackwardMove() { BoardLogic logic = new BoardLogic(); FieldPosition p = new FieldPosition(2, 4); logic.makeMove(FieldType.Player1, p); FieldType[][] expected = getDefaultState(); expected[3][2] = FieldType.Player1; expected[4][2] = FieldType.Player1; FieldType[][] result = logic.getBoardState(); for (int i = 0; i < logic.getBoardSize(); i++) { for (int j = 0; j < logic.getBoardSize(); j++ ) { assertEquals("Current state xy value and expected state xy value are not the same", result[i][j], expected[i][j]); } } } @Test public void test_verticalForwardMove() { BoardLogic logic = new BoardLogic(); FieldPosition p = new FieldPosition(3, 1); logic.makeMove(FieldType.Player1, p); FieldType[][] expected = getDefaultState(); expected[1][3] = FieldType.Player1; expected[2][3] = FieldType.Player1; FieldType[][] result = logic.getBoardState(); for (int i = 0; i < logic.getBoardSize(); i++) { for (int j = 0; j < logic.getBoardSize(); j++ ) { assertEquals("Current state xy value and expected state xy value are not the same", result[i][j], expected[i][j]); } } } @Test public void test_diagonalBackwardMoveUp() { BoardLogic logic = new BoardLogic(); FieldPosition p = new FieldPosition(3, 4); FieldType[][] expected = getDefaultState(); expected[4][3] = FieldType.Player2; expected[4][4] = FieldType.Player1; logic.makeMove(FieldType.Player2, p); p = new FieldPosition(4, 4); logic.makeMove(FieldType.Player1, p); FieldType[][] result = logic.getBoardState(); for (int i = 0; i < logic.getBoardSize(); i++) { for (int j = 0; j < logic.getBoardSize(); j++ ) { assertEquals("Current state xy value and expected state xy value are not the same", result[i][j], expected[i][j]); } } } @Test public void test_diagonalBackwardMoveDown() { FieldType[][] state = getDefaultState(); state[2][3] = FieldType.Player1; FieldType[][] expected = getDefaultState(); expected[1][4] = FieldType.Player2; LogicMock logic = new LogicMock(); logic.useStateForTest(state); logic.makeMove(FieldType.Player2, new FieldPosition(4,1)); FieldType[][] result = logic.getBoardState(); for (int i = 0; i < logic.getBoardSize(); i++) { for (int j = 0; j < logic.getBoardSize(); j++ ) { assertEquals("Current state xy value and expected state xy value are not the same", result[i][j], expected[i][j]); } } } @Test public void test_diagonalForwardMoveDown() { BoardLogic logic = new BoardLogic(); FieldPosition p = new FieldPosition(2, 1); logic.makeMove(FieldType.Player2, p); p = new FieldPosition(1, 1); logic.makeMove(FieldType.Player1, p); FieldType[][] expected = getDefaultState(); expected[1][1] = FieldType.Player1; expected[1][2] = FieldType.Player2; FieldType[][] result = logic.getBoardState(); for (int i = 0; i < logic.getBoardSize(); i++) { for (int j = 0; j < logic.getBoardSize(); j++ ) { assertEquals("Current state xy value and expected state xy value are not the same", result[i][j], expected[i][j]); } } } @Test public void test_diagonalForwardMoveUp() { FieldType[][] state = getDefaultState(); state[3][2] = FieldType.Player1; LogicMock logic = new LogicMock(); logic.useStateForTest(state); logic.makeMove(FieldType.Player2, new FieldPosition(1,4)); FieldType[][] expected = getDefaultState(); expected[4][1] = FieldType.Player2; FieldType[][] result = logic.getBoardState(); for (int i = 0; i < logic.getBoardSize(); i++) { for (int j = 0; j < logic.getBoardSize(); j++ ) { assertEquals("Current state xy value and expected state xy value are not the same", result[i][j], expected[i][j]); } } } @Test public void test_multipleMoves() { FieldType[][] state = getDefaultState(); state[2][2] = FieldType.Player1; state[2][3] = FieldType.Player1; state[2][4] = FieldType.Player1; state[3][2] = FieldType.Player2; state[3][3] = FieldType.Player2; state[3][4] = FieldType.Player2; LogicMock logic = new LogicMock(); logic.useStateForTest(state); FieldType[][] expected = getDefaultState(); expected[1][2] = FieldType.Player2; expected[2][2] = FieldType.Player2; expected[2][3] = FieldType.Player2; expected[2][4] = FieldType.Player1; expected[3][2] = FieldType.Player2; expected[3][3] = FieldType.Player2; expected[3][4] = FieldType.Player2; logic.makeMove(FieldType.Player2, new FieldPosition(2,1)); FieldType[][] result = logic.getBoardState(); for(int i = 0; i < logic.getBoardSize(); i++) { for(int j = 0; j < logic.getBoardSize(); j++) { assertTrue("Result is not as aspected", result[i][j] == expected[i][j]); } } } @Test public void test_stateImmutabillity() { BoardLogic logic = new BoardLogic(); FieldType[][] state = logic.getBoardState(); state[0][0] = FieldType.Player1; assertTrue("State is mutable from outside", logic.getBoardState()[0][0] == FieldType.Empty); } private FieldType[][] getDefaultState() { FieldType[][] state = { {FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty}, {FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty}, {FieldType.Empty,FieldType.Empty,FieldType.Player1,FieldType.Player2,FieldType.Empty,FieldType.Empty}, {FieldType.Empty,FieldType.Empty,FieldType.Player2,FieldType.Player1,FieldType.Empty,FieldType.Empty}, {FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty}, {FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty,FieldType.Empty} }; return state; } }
package theschoolproject; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.Serializable; import java.util.ArrayList; import java.util.Random; import resources.SettingsProperties; public class Room implements Serializable { int width = 17; int height = 13; int xNum; int yNum; public int numEnemies = UsefulSnippets.generateRandomNumber(3) + 2; public ArrayList<Entity> en_arry = new ArrayList(); int[] tiles = new int[width * height]; int[] spawnTiles = new int[width * height]; FloorTile[] tileArry = new FloorTile[width * height]; GameEngine world; SettingsProperties props = new SettingsProperties(); transient BufferedImage lvl; transient BufferedImage spawnMap; String lvlPath; String spawnMapPath; int drawCycle = 0; Random gen = new Random(); public Room(GameEngine ge, String levelImage, String spawnImage, int x, int y) { world = ge; for (int i = 0; i < tileArry.length; i++) { tileArry[i] = new FloorTile(1); } for (int l = 0; l < numEnemies; l++) { int spr = UsefulSnippets.generateRandomNumber(2); en_arry.add(new Enemy(world, world.spritePaths[spr])); } lvl = UsefulSnippets.loadImage(levelImage); spawnMap = UsefulSnippets.loadImage(spawnImage); lvlPath = levelImage; spawnMapPath = spawnImage; this.xNum = x; this.yNum = y; this.numEnemies = gen.nextInt(3) + 2; loadLevel(); } public final void loadLevel() { lvl.getRGB(0, 0, width, height, tiles, 0, width); spawnMap.getRGB(0, 0, width, height, spawnTiles, 0, width); for (int i = 0; i < lvl.getWidth(); i++) { for (int j = 0; j < lvl.getHeight(); j++) { if (tiles[i + j * width] == 0xFFFFFFFF) { tileArry[i + j * width].setTile(1); //Wall } if (tiles[i + j * width] == 0xFF000000) { tileArry[i + j * width].setTile(2); //Floor tileArry[i + j * width].metaElement = UsefulSnippets.generateRandomNumber(3); } if (tiles[i + j * width] == 0xFF532F00) { tileArry[i + j * width].setTile(3); //Door } if (tiles[i + j * width] == 0xFF0000ff) { tileArry[i + j * width].setTile(4); //Water } if (tiles[i + j * width] == 0xFF03a5ff) { tileArry[i + j * width].setTile(5); //Ice } if (tiles[i + j * width] == 0xFFfc1604) { tileArry[i + j * width].setTile(6); //Lava } if (tiles[i + j * width] == 0xFF073a08) { tileArry[i + j * width].setTile(7); //Moss } if (tiles[i + j * width] == 0xFF007f00) { tileArry[i + j * width].setTile(8); //Grass } if (tiles[i + j * width] == 0xFF6b3d00) { tileArry[i + j * width].setTile(9); //Rock } if (spawnTiles[i + j * width] == 0xFFff0096) { tileArry[i + j * width].isSpawn = true; //Spawn } } } // System.out.println(tileArry[5 + 5 * width].TILE_ID); for (int i = 1; i < lvl.getWidth() - 1; i++) { for (int j = 1; j < lvl.getHeight() - 1; j++) { if (tileArry[i + j * width].TILE_ID == 2) { //Sides if (tileArry[i + (j + 1) * width].TILE_ID == 4) { tileArry[i + j * width].metaElement = 1; tileArry[i + j * width].metaDir = 0; } if (tileArry[i + (j - 1) * width].TILE_ID == 4) { tileArry[i + j * width].metaElement = 1; tileArry[i + j * width].metaDir = 2; } if (tileArry[(i + 1) + j * width].TILE_ID == 4) { tileArry[i + j * width].metaElement = 1; tileArry[i + j * width].metaDir = 1; } if (tileArry[(i - 1) + j * width].TILE_ID == 4) { tileArry[i + j * width].metaElement = 1; tileArry[i + j * width].metaDir = 3; } //Corners if (tileArry[(i - 1) + j * width].TILE_ID == 4 && tileArry[(i) + (j + 1) * width].TILE_ID == 4) { tileArry[i + j * width].metaElement = 2; tileArry[i + j * width].metaDir = 0; } if (tileArry[(i + 1) + j * width].TILE_ID == 4 && tileArry[(i) + (j + 1) * width].TILE_ID == 4) { tileArry[i + j * width].metaElement = 2; tileArry[i + j * width].metaDir = 1; } if (tileArry[(i - 1) + j * width].TILE_ID == 4 && tileArry[(i) + (j - 1) * width].TILE_ID == 4) { tileArry[i + j * width].metaElement = 2; tileArry[i + j * width].metaDir = 2; } if (tileArry[(i + 1) + j * width].TILE_ID == 4 && tileArry[(i) + (j - 1) * width].TILE_ID == 4) { tileArry[i + j * width].metaElement = 2; tileArry[i + j * width].metaDir = 3; } //Opposites if (tileArry[(i - 1) + j * width].TILE_ID == 4 && tileArry[(i + 1) + j * width].TILE_ID == 4) { tileArry[i + j * width].metaElement = 3; tileArry[i + j * width].metaDir = 0; } if (tileArry[i + (j - 1) * width].TILE_ID == 4 && tileArry[i + (j + 1) * width].TILE_ID == 4) { tileArry[i + j * width].metaElement = 3; tileArry[i + j * width].metaDir = 1; } //3 Sides (dead end) if (tileArry[(i - 1) + j * width].TILE_ID == 4 && tileArry[i + (j + 1) * width].TILE_ID == 4 && tileArry[i + (j - 1) * width].TILE_ID == 4) { tileArry[i + j * width].metaElement = 4; tileArry[i + j * width].metaDir = 0; } if (tileArry[(i + 1) + j * width].TILE_ID == 4 && tileArry[(i) + (j + 1) * width].TILE_ID == 4 && tileArry[i + (j - 1) * width].TILE_ID == 4) { tileArry[i + j * width].metaElement = 4; tileArry[i + j * width].metaDir = 1; } if (tileArry[(i - 1) + j * width].TILE_ID == 4 && tileArry[(i) + (j - 1) * width].TILE_ID == 4 && tileArry[(i + 1) + j * width].TILE_ID == 4) { tileArry[i + j * width].metaElement = 4; tileArry[i + j * width].metaDir = 2; } if (tileArry[(i - 1) + j * width].TILE_ID == 4 && tileArry[(i) + (j + 1) * width].TILE_ID == 4 && tileArry[(i + 1) + j * width].TILE_ID == 4) { tileArry[i + j * width].metaElement = 4; tileArry[i + j * width].metaDir = 3; } //Lava //Sides if (tileArry[i + (j + 1) * width].TILE_ID == 6) { tileArry[i + j * width].metaElement = 2; tileArry[i + j * width].metaDir = 0; } if (tileArry[i + (j - 1) * width].TILE_ID == 6) { tileArry[i + j * width].metaElement = 2; tileArry[i + j * width].metaDir = 2; } if (tileArry[(i + 1) + j * width].TILE_ID == 6) { tileArry[i + j * width].metaElement = 2; tileArry[i + j * width].metaDir = 1; } if (tileArry[(i - 1) + j * width].TILE_ID == 6) { tileArry[i + j * width].metaElement = 2; tileArry[i + j * width].metaDir = 3; } //Corners if (tileArry[(i - 1) + j * width].TILE_ID == 6 && tileArry[(i) + (j + 1) * width].TILE_ID == 6) { tileArry[i + j * width].metaElement = 3; tileArry[i + j * width].metaDir = 0; } if (tileArry[(i + 1) + j * width].TILE_ID == 6 && tileArry[(i) + (j + 1) * width].TILE_ID == 6) { tileArry[i + j * width].metaElement = 3; tileArry[i + j * width].metaDir = 1; } if (tileArry[(i - 1) + j * width].TILE_ID == 6 && tileArry[(i) + (j - 1) * width].TILE_ID == 6) { tileArry[i + j * width].metaElement = 3; tileArry[i + j * width].metaDir = 2; } if (tileArry[(i + 1) + j * width].TILE_ID == 6 && tileArry[(i) + (j - 1) * width].TILE_ID == 6) { tileArry[i + j * width].metaElement = 3; tileArry[i + j * width].metaDir = 3; } } } } if (this.yNum == 0) { tileArry[7].TILE_ID = 1; tileArry[8].TILE_ID = 1; tileArry[9].TILE_ID = 1; } if (this.xNum == 0) { tileArry[85].TILE_ID = 1; tileArry[102].TILE_ID = 1; tileArry[119].TILE_ID = 1; } if (this.xNum == world.rooms[0].length - 1) { tileArry[101].TILE_ID = 1; tileArry[118].TILE_ID = 1; tileArry[135].TILE_ID = 1; } if (this.yNum == world.rooms.length - 1) { tileArry[211].TILE_ID = 1; tileArry[212].TILE_ID = 1; tileArry[213].TILE_ID = 1; } } public void draw(Graphics g) { //You are entering switch hell for (int i = 0; i < lvl.getWidth(); i++) { for (int j = 0; j < lvl.getHeight(); j++) { g.setColor(tileArry[i + j * width].getColor()); g.fill3DRect(i * 50, j * 50, 50, 50, true); switch (tileArry[i + j * width].TILE_ID) { case 0: g.drawImage(world.spritesTex[0][0], i * 50, j * 50, null); //Test tile break; case 1: g.drawImage(world.spritesTex[tileArry[i + j * width].metaElement][1], i * 50, j * 50, null); //Wall tile break; case 2: if (tileArry[i + j * width].metaDir == -1) { g.drawImage(world.spritesTex[tileArry[i + j * width].metaElement][2], i * 50, j * 50, null); } else { switch (tileArry[i + j * width].metaElement) { case 0: switch (tileArry[i + j * width].metaDir) { case 0: g.drawImage(world.spritesTex[9][4], i * 50, j * 50, null); break; case 1: g.drawImage(world.spritesTex[8][4], i * 50, j * 50, null); break; case 2: g.drawImage(world.spritesTex[6][4], i * 50, j * 50, null); break; case 3: g.drawImage(world.spritesTex[7][4], i * 50, j * 50, null); break; } break; case 1: switch (tileArry[i + j * width].metaDir) { case 0: g.drawImage(world.spritesTex[13][4], i * 50, j * 50, null); break; case 1: g.drawImage(world.spritesTex[12][4], i * 50, j * 50, null); break; case 2: g.drawImage(world.spritesTex[10][4], i * 50, j * 50, null); break; case 3: g.drawImage(world.spritesTex[11][4], i * 50, j * 50, null); break; } case 2: switch (tileArry[i + j * width].metaDir) { case 0: g.drawImage(world.spritesTex[9][6], i * 50, j * 50, null); break; case 1: g.drawImage(world.spritesTex[8][6], i * 50, j * 50, null); break; case 2: g.drawImage(world.spritesTex[6][6], i * 50, j * 50, null); break; case 3: g.drawImage(world.spritesTex[7][6], i * 50, j * 50, null); break; } break; case 3: switch (tileArry[i + j * width].metaDir) { case 0: g.drawImage(world.spritesTex[13][6], i * 50, j * 50, null); break; case 1: g.drawImage(world.spritesTex[12][6], i * 50, j * 50, null); break; case 2: g.drawImage(world.spritesTex[10][6], i * 50, j * 50, null); break; case 3: g.drawImage(world.spritesTex[11][6], i * 50, j * 50, null); break; } } break; } break; case 3: g.drawImage(world.spritesTex[tileArry[i + j * width].metaElement][3], i * 50, j * 50, null); //Door tile break; case 4: drawCycle++; if (drawCycle > 10) { tileArry[i + j * width].metaElement = UsefulSnippets.generateRandomNumber(3); drawCycle = 0; g.drawImage(world.spritesTex[tileArry[i + j * width].metaElement][4], i * 50, j * 50, null); } else { g.drawImage(world.spritesTex[tileArry[i + j * width].metaElement][4], i * 50, j * 50, null); } break; case 5: g.drawImage(world.spritesTex[tileArry[i + j * width].metaElement][5], i * 50, j * 50, null); break; case 6: drawCycle++; if (drawCycle > 10) { tileArry[i + j * width].metaElement = UsefulSnippets.generateRandomNumber(3); drawCycle = 0; g.drawImage(world.spritesTex[tileArry[i + j * width].metaElement][6], i * 50, j * 50, null); } else { g.drawImage(world.spritesTex[tileArry[i + j * width].metaElement][6], i * 50, j * 50, null); } break; case 7: g.drawImage(world.spritesTex[tileArry[i + j * width].metaElement][7], i * 50, j * 50, null); break; case 8: g.drawImage(world.spritesTex[tileArry[i + j * width].metaElement][7], i * 50, j * 50, null); break; case 9: g.drawImage(world.spritesTex[tileArry[(i + j * width) + 1].metaElement][tileArry[(i + j * width) + 1].TILE_ID], i * 50, j * 50, null); g.drawImage(world.spritesTex[0][9], i * 50, j * 50, null); break; case 10: g.drawImage(world.spritesTex[tileArry[(i + j * width) + 1].metaElement][tileArry[(i + j * width) + 1].TILE_ID], i * 50, j * 50, null); g.drawImage(world.spritesTex[0][10], i * 50, j * 50, null); break; } if (tileArry[i + j * width].isSpawn) { g.drawImage(world.spritesTex[0][10], i * 50, j * 50, null); } // if (SettingsProperties.debugModeG == true) { // g.setColor(Color.yellow); // g.fill3DRect((world.pl.tileLocX) * 50, (world.pl.tileLocY) * 50, 50, 50, true); // g.setColor(new Color(0, 255, 0, 7)); // g.fill3DRect((world.pl.tileLocX + 1) * 50, (world.pl.tileLocY) * 50, 50, 50, true); // g.fill3DRect((world.pl.tileLocX) * 50, (world.pl.tileLocY + 1) * 50, 50, 50, true); // g.fill3DRect((world.pl.tileLocX - 1) * 50, (world.pl.tileLocY) * 50, 50, 50, true); // g.fill3DRect((world.pl.tileLocX) * 50, (world.pl.tileLocY - 1) * 50, 50, 50, true); // g.setColor(new Color(255, 0, 0, 7)); // if (tileArry[(world.pl.tileLocX + 1) + (world.pl.tileLocY) * width].isSolid()) { // g.fill3DRect((world.pl.tileLocX + 1) * 50, (world.pl.tileLocY) * 50, 50, 50, true); // if (tileArry[(world.pl.tileLocX) + (world.pl.tileLocY + 1) * width].isSolid()) { // g.fill3DRect((world.pl.tileLocX) * 50, (world.pl.tileLocY + 1) * 50, 50, 50, true); // if (tileArry[(world.pl.tileLocX - 1) + (world.pl.tileLocY) * width].isSolid()) { // g.fill3DRect((world.pl.tileLocX - 1) * 50, (world.pl.tileLocY) * 50, 50, 50, true); // if (tileArry[(world.pl.tileLocX) + (world.pl.tileLocY - 1) * width].isSolid()) { // g.fill3DRect((world.pl.tileLocX) * 50, (world.pl.tileLocY - 1) * 50, 50, 50, true); // g.setColor(Color.white); } } } public void loadResources() { lvl = UsefulSnippets.loadImage(lvlPath); spawnMap = UsefulSnippets.loadImage(spawnMapPath); } }
// This file is part of OpenTSDB. // This program is free software: you can redistribute it and/or modify it // option) any later version. This program is distributed in the hope that it // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser package tsd.client; import java.util.ArrayList; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.DomEvent; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.Focusable; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.SuggestBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; final class MetricForm extends HorizontalPanel implements Focusable { public static interface MetricChangeHandler extends EventHandler { void onMetricChange(MetricForm widget); } private static final String TSDB_ID_CLASS = "[-_./a-zA-Z0-9]"; private static final String TSDB_ID_RE = "^" + TSDB_ID_CLASS + "*$"; private static final String TSDB_TAGVALUE_RE = "^(\\*?" // a `*' wildcard or nothing + "|" + TSDB_ID_CLASS + "+(\\|" + TSDB_ID_CLASS + "+)*)$"; // `foo|bar|...' private final EventsHandler events_handler; private MetricChangeHandler metric_change_handler; private final CheckBox downsample = new CheckBox("Downsample"); private final ListBox downsampler = new ListBox(); private final ValidatedTextBox interval = new ValidatedTextBox(); private final CheckBox rate = new CheckBox("Rate"); private final CheckBox rate_counter = new CheckBox("Rate Ctr"); private final TextBox counter_max = new TextBox(); private final TextBox counter_reset_value = new TextBox(); private final CheckBox x1y2 = new CheckBox("Right Axis"); private final ListBox aggregators = new ListBox(); private final ValidatedTextBox metric = new ValidatedTextBox(); private final FlexTable tagtable = new FlexTable(); public MetricForm(final EventsHandler handler) { events_handler = handler; setupDownsampleWidgets(); downsample.addClickHandler(handler); downsampler.addChangeHandler(handler); interval.addBlurHandler(handler); interval.addKeyPressHandler(handler); rate.addClickHandler(handler); rate_counter.addClickHandler(handler); counter_max.addBlurHandler(handler); counter_max.addKeyPressHandler(handler); counter_reset_value.addBlurHandler(handler); counter_reset_value.addKeyPressHandler(handler); x1y2.addClickHandler(handler); aggregators.addChangeHandler(handler); metric.addBlurHandler(handler); metric.addKeyPressHandler(handler); { final EventsHandler metric_handler = new EventsHandler() { protected <H extends EventHandler> void onEvent(final DomEvent<H> event) { if (metric_change_handler != null) { metric_change_handler.onMetricChange(MetricForm.this); } } }; metric.addBlurHandler(metric_handler); metric.addKeyPressHandler(metric_handler); } metric.setValidationRegexp(TSDB_ID_RE); assembleUi(); } public String getMetric() { return metric.getText(); } /** * Parses the metric and tags out of the given string. * @param metric A string of the form "metric" or "metric{tag=value,...}". * @return The name of the metric. */ private String parseWithMetric(final String metric) { // TODO: Try to reduce code duplication with Tags.parseWithMetric(). final int curly = metric.indexOf('{'); if (curly < 0) { clearTags(); return metric; } final int len = metric.length(); if (metric.charAt(len - 1) != '}') { // "foo{" clearTags(); return null; // Missing '}' at the end. } else if (curly == len - 2) { // "foo{}" clearTags(); return metric.substring(0, len - 2); } // substring the tags out of "foo{a=b,...,x=y}" and parse them. int i = 0; // Tag index. final int num_tags_before = getNumTags(); for (final String tag : metric.substring(curly + 1, len - 1).split(",")) { final String[] kv = tag.split("="); if (kv.length != 2 || kv[0].isEmpty() || kv[1].isEmpty()) { setTag(i, "", ""); continue; // Invalid tag. } if (i < num_tags_before) { setTag(i, kv[0], kv[1]); } else { addTag(kv[0], kv[1]); } i++; } // Leave an empty line at the end. if (i < num_tags_before) { setTag(i, "", ""); } else { addTag(); } // Remove extra tags. for (i++; i < num_tags_before; i++) { tagtable.removeRow(i + 1); } // Return the "foo" part of "foo{a=b,...,x=y}" return metric.substring(0, curly); } public void updateFromQueryString(final String m, final String o) { // TODO: Try to reduce code duplication with GraphHandler.parseQuery(). // m is of the following forms: // agg:[interval-agg:][rate[{counter[,max[,reset]]}:]metric[{tag=value,...}] // Where the parts in square brackets `[' .. `]' are optional. final String[] parts = m.split(":"); final int nparts = parts.length; int i = parts.length; if (i < 2 || i > 4) { return; // Malformed. } setSelectedItem(aggregators, parts[0]); i--; // Move to the last part (the metric name). metric.setText(parseWithMetric(parts[i])); metric_change_handler.onMetricChange(this); final boolean rate = parts[--i].startsWith("rate"); this.rate.setValue(rate, false); Object[] rate_options = parseRateOptions(rate, parts[i]); this.rate_counter.setValue((Boolean) rate_options[0], false); final long rate_counter_max = (Long) rate_options[1]; this.counter_max.setValue( rate_counter_max == Long.MAX_VALUE ? "" : Long.toString(rate_counter_max), false); this.counter_reset_value .setValue(Long.toString((Long) rate_options[2]), false); if (rate) { i } // downsampling function & interval. if (i > 0) { final int dash = parts[1].indexOf('-', 1); // 1st char can't be `-'. if (dash < 0) { disableDownsample(); return; // Invalid downsampling specifier. } downsample.setValue(true, false); downsampler.setEnabled(true); setSelectedItem(downsampler, parts[1].substring(dash + 1)); interval.setEnabled(true); interval.setText(parts[1].substring(0, dash)); } else { disableDownsample(); } x1y2.setValue(o.contains("axis x1y2"), false); } private void disableDownsample() { downsample.setValue(false, false); interval.setEnabled(false); downsampler.setEnabled(false); } public CheckBox x1y2() { return x1y2; } private void assembleUi() { setWidth("100%"); { // Left hand-side panel. final HorizontalPanel hbox = new HorizontalPanel(); final InlineLabel l = new InlineLabel(); l.setText("Metric:"); hbox.add(l); final SuggestBox suggest = RemoteOracle.newSuggestBox("metrics", metric); suggest.setLimit(40); hbox.add(suggest); hbox.setWidth("100%"); metric.setWidth("100%"); tagtable.setWidget(0, 0, hbox); tagtable.getFlexCellFormatter().setColSpan(0, 0, 3); addTag(); tagtable.setText(1, 0, "Tags"); add(tagtable); } { // Right hand-side panel. final VerticalPanel vbox = new VerticalPanel(); { final HorizontalPanel hbox = new HorizontalPanel(); hbox.add(rate); hbox.add(rate_counter); hbox.add(x1y2); vbox.add(hbox); } { final HorizontalPanel hbox = new HorizontalPanel(); final InlineLabel l = new InlineLabel("Rate Ctr Max:"); hbox.add(l); hbox.add(counter_max); vbox.add(hbox); } { final HorizontalPanel hbox = new HorizontalPanel(); final InlineLabel l = new InlineLabel("Rate Ctr Reset:"); hbox.add(l); hbox.add(counter_reset_value); vbox.add(hbox); } { final HorizontalPanel hbox = new HorizontalPanel(); final InlineLabel l = new InlineLabel(); l.setText("Aggregator:"); hbox.add(l); hbox.add(aggregators); vbox.add(hbox); } vbox.add(downsample); { final HorizontalPanel hbox = new HorizontalPanel(); hbox.add(downsampler); hbox.add(interval); vbox.add(hbox); } add(vbox); } } public void setMetricChangeHandler(final MetricChangeHandler handler) { metric_change_handler = handler; } public void setAggregators(final ArrayList<String> aggs) { for (final String agg : aggs) { aggregators.addItem(agg); downsampler.addItem(agg); } setSelectedItem(aggregators, "sum"); setSelectedItem(downsampler, "avg"); } public boolean buildQueryString(final StringBuilder url) { final String metric = getMetric(); if (metric.isEmpty()) { return false; } url.append("&m="); url.append(selectedValue(aggregators)); if (downsample.getValue()) { url.append(':').append(interval.getValue()) .append('-').append(selectedValue(downsampler)); } if (rate.getValue()) { url.append(":rate"); if (rate_counter.getValue()) { url.append('{').append("counter"); final String max = counter_max.getValue().trim(); final String reset = counter_reset_value.getValue().trim(); if (max.length() > 0 && reset.length() > 0) { url.append(',').append(max).append(',').append(reset); } else if (max.length() > 0 && reset.length() == 0) { url.append(',').append(max); } else if (max.length() == 0 && reset.length() > 0){ url.append(",,").append(reset); } url.append('}'); } } url.append(':').append(metric); { final int ntags = getNumTags(); url.append('{'); for (int tag = 0; tag < ntags; tag++) { final String tagname = getTagName(tag); final String tagvalue = getTagValue(tag); if (tagname.isEmpty() || tagvalue.isEmpty()) { continue; } url.append(tagname).append('=').append(tagvalue) .append(','); } final int last = url.length() - 1; if (url.charAt(last) == '{') { // There was no tag. url.setLength(last); // So remove the `{'. } else { // Need to replace the last `,' with a `}'. url.setCharAt(url.length() - 1, '}'); } } url.append("&o="); if (x1y2.getValue()) { url.append("axis x1y2"); } return true; } private int getNumTags() { return tagtable.getRowCount() - 1; } private String getTagName(final int i) { return ((SuggestBox) tagtable.getWidget(i + 1, 1)).getValue(); } private String getTagValue(final int i) { return ((SuggestBox) tagtable.getWidget(i + 1, 2)).getValue(); } private void setTagName(final int i, final String value) { ((SuggestBox) tagtable.getWidget(i + 1, 1)).setValue(value); } private void setTagValue(final int i, final String value) { ((SuggestBox) tagtable.getWidget(i + 1, 2)).setValue(value); } /** * Changes the name/value of an existing tag. * @param i The index of the tag to change. * @param name The new name of the tag. * @param value The new value of the tag. * Requires: {@code i < getNumTags()}. */ private void setTag(final int i, final String name, final String value) { setTagName(i, name); setTagValue(i, value); } private void addTag() { addTag(null, null); } private void addTag(final String default_tagname) { addTag(default_tagname, null); } private void addTag(final String default_tagname, final String default_value) { final int row = tagtable.getRowCount(); final ValidatedTextBox tagname = new ValidatedTextBox(); final SuggestBox suggesttagk = RemoteOracle.newSuggestBox("tagk", tagname); final ValidatedTextBox tagvalue = new ValidatedTextBox(); final SuggestBox suggesttagv = RemoteOracle.newSuggestBox("tagv", tagvalue); tagname.setValidationRegexp(TSDB_ID_RE); tagvalue.setValidationRegexp(TSDB_TAGVALUE_RE); tagname.setWidth("100%"); tagvalue.setWidth("100%"); tagname.addBlurHandler(recompact_tagtable); tagname.addBlurHandler(events_handler); tagname.addKeyPressHandler(events_handler); tagvalue.addBlurHandler(recompact_tagtable); tagvalue.addBlurHandler(events_handler); tagvalue.addKeyPressHandler(events_handler); tagtable.setWidget(row, 1, suggesttagk); tagtable.setWidget(row, 2, suggesttagv); if (row > 2) { final Button remove = new Button("x"); remove.addClickHandler(removetag); tagtable.setWidget(row - 1, 0, remove); } if (default_tagname != null) { tagname.setText(default_tagname); if (default_value == null) { tagvalue.setFocus(true); } } if (default_value != null) { tagvalue.setText(default_value); } } private void clearTags() { setTag(0, "", ""); for (int i = getNumTags() - 1; i > 1; i++) { tagtable.removeRow(i + 1); } } public void autoSuggestTag(final String tag) { // First try to see if the tag is already in the table. final int nrows = tagtable.getRowCount(); int unused_row = -1; for (int row = 1; row < nrows; row++) { final SuggestBox tagname = ((SuggestBox) tagtable.getWidget(row, 1)); final SuggestBox tagvalue = ((SuggestBox) tagtable.getWidget(row, 2)); final String thistag = tagname.getValue(); if (thistag.equals(tag)) { return; // This tag is already in the table. } if (thistag.isEmpty() && tagvalue.getValue().isEmpty()) { unused_row = row; break; } } if (unused_row >= 0) { ((SuggestBox) tagtable.getWidget(unused_row, 1)).setValue(tag); } else { addTag(tag); } } private final BlurHandler recompact_tagtable = new BlurHandler() { public void onBlur(final BlurEvent event) { int ntags = getNumTags(); // Is the first line empty? If yes, move everything up by 1 line. if (getTagName(0).isEmpty() && getTagValue(0).isEmpty()) { for (int tag = 1; tag < ntags; tag++) { final String tagname = getTagName(tag); final String tagvalue = getTagValue(tag); setTag(tag - 1, tagname, tagvalue); } setTag(ntags - 1, "", ""); } // Try to remove empty lines from the tag table (but never remove the // first line or last line, even if they're empty). Walk the table // from the end to make it easier to delete rows as we iterate. for (int tag = ntags - 1; tag >= 1; tag final String tagname = getTagName(tag); final String tagvalue = getTagValue(tag); if (tagname.isEmpty() && tagvalue.isEmpty()) { tagtable.removeRow(tag + 1); } } ntags = getNumTags(); // How many lines are left? // If the last line isn't empty, add another one. final String tagname = getTagName(ntags - 1); final String tagvalue = getTagValue(ntags - 1); if (!tagname.isEmpty() && !tagvalue.isEmpty()) { addTag(); } } }; private final ClickHandler removetag = new ClickHandler() { public void onClick(final ClickEvent event) { if (!(event.getSource() instanceof Button)) { return; } final Widget source = (Widget) event.getSource(); final int ntags = getNumTags(); for (int tag = 1; tag < ntags; tag++) { if (source == tagtable.getWidget(tag + 1, 0)) { tagtable.removeRow(tag + 1); events_handler.onClick(event); break; } } } }; private void setupDownsampleWidgets() { downsampler.setEnabled(false); interval.setEnabled(false); interval.setMaxLength(5); interval.setVisibleLength(5); interval.setValue("10m"); interval.setValidationRegexp("^[1-9][0-9]*[smhdwy]$"); downsample.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { final boolean checked = ((CheckBox) event.getSource()).getValue(); downsampler.setEnabled(checked); interval.setEnabled(checked); if (checked) { downsampler.setFocus(true); } } }); } private static String selectedValue(final ListBox list) { // They should add return list.getValue(list.getSelectedIndex()); // this to GWT... } /** * If the given item is in the list, mark it as selected. * @param list The list to manipulate. * @param item The item to select if present. */ private void setSelectedItem(final ListBox list, final String item) { final int nitems = list.getItemCount(); for (int i = 0; i < nitems; i++) { if (item.equals(list.getValue(i))) { list.setSelectedIndex(i); return; } } } static final public Object[] parseRateOptions(boolean rate, String spec) { if (!rate || spec.length() == 4) { return new Object[] { false, Long.MAX_VALUE, 0 }; } if (spec.length() < 6) { return new Object[] { false, Long.MAX_VALUE, 0 }; } String[] parts = spec.split(spec.substring(5, spec.length() - 1), ','); if (parts.length < 1 || parts.length > 3) { return new Object[] { false, Long.MAX_VALUE, 0 }; } try { return new Object[] { "counter".equals(parts[0]), parts.length >= 2 && parts[1].length() > 0 ? Long.parseLong(parts[1]) : Long.MAX_VALUE, parts.length >= 3 && parts[2].length() > 0 ? Long.parseLong(parts[2]) : 0 }; } catch (NumberFormatException e) { return new Object[] { false, Long.MAX_VALUE, 0 }; } } // Focusable interface // public int getTabIndex() { return metric.getTabIndex(); } public void setTabIndex(final int index) { metric.setTabIndex(index); } public void setAccessKey(final char key) { metric.setAccessKey(key); } public void setFocus(final boolean focused) { metric.setFocus(focused); } }
package net.sourceforge.pebble.util; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A collection of utility methods for manipulating strings. * * @author Simon Brown */ public final class StringUtils { private static final Pattern OPENING_B_TAG_PATTERN = Pattern.compile("&lt;b&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern CLOSING_B_TAG_PATTERN = Pattern.compile("&lt;/b&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern OPENING_STRONG_TAG_PATTERN = Pattern.compile("&lt;strong&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern CLOSING_STRONG_TAG_PATTERN = Pattern.compile("&lt;/strong&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern OPENING_I_TAG_PATTERN = Pattern.compile("&lt;i&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern CLOSING_I_TAG_PATTERN = Pattern.compile("&lt;/i&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern OPENING_EM_TAG_PATTERN = Pattern.compile("&lt;em&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern CLOSING_EM_TAG_PATTERN = Pattern.compile("&lt;/em&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern OPENING_BLOCKQUOTE_TAG_PATTERN = Pattern.compile("&lt;blockquote&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern CLOSING_BLOCKQUOTE_TAG_PATTERN = Pattern.compile("&lt;/blockquote&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern BR_TAG_PATTERN = Pattern.compile("&lt;br */*&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern OPENING_P_TAG_PATTERN = Pattern.compile("&lt;p&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern CLOSING_P_TAG_PATTERN = Pattern.compile("&lt;/p&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern OPENING_PRE_TAG_PATTERN = Pattern.compile("&lt;pre&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern CLOSING_PRE_TAG_PATTERN = Pattern.compile("&lt;/pre&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern OPENING_UL_TAG_PATTERN = Pattern.compile("&lt;ul&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern CLOSING_UL_TAG_PATTERN = Pattern.compile("&lt;/ul&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern OPENING_OL_TAG_PATTERN = Pattern.compile("&lt;ol&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern CLOSING_OL_TAG_PATTERN = Pattern.compile("&lt;/ol&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern OPENING_LI_TAG_PATTERN = Pattern.compile("&lt;li&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern CLOSING_LI_TAG_PATTERN = Pattern.compile("&lt;/li&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern CLOSING_A_TAG_PATTERN = Pattern.compile("&lt;/a&gt;", Pattern.CASE_INSENSITIVE); private static final Pattern OPENING_A_TAG_PATTERN = Pattern.compile("&lt;a href=.*?&gt;", Pattern.CASE_INSENSITIVE); /** * Filters out characters that have meaning within JSP and HTML, and * replaces them with "escaped" versions. * * @param s the String to filter * @return the filtered String */ public static String transformHTML(String s) { if (s == null) { return null; } StringBuffer buf = new StringBuffer(s.length()); // loop through every character and replace if necessary int length = s.length(); for (int i = 0; i < length; i++) { switch (s.charAt(i)) { case '<': buf.append("&lt;"); break; case '>': buf.append("&gt;"); break; case '&': buf.append("&amp;"); break; default : buf.append(s.charAt(i)); } } return buf.toString(); } /** * Transforms the given String into a subset of HTML displayable on a web * page. The subset includes &lt;b&gt;, &lt;i&gt;, &lt;p&gt;, &lt;br&gt;, * &lt;pre&gt; and &lt;a href&gt; (and their corresponding end tags). * * @param s the String to transform * @return the transformed String */ public static String transformToHTMLSubset(String s) { if (s == null) { return null; } s = replace(s, OPENING_B_TAG_PATTERN, "<b>"); s = replace(s, CLOSING_B_TAG_PATTERN, "</b>"); s = replace(s, OPENING_STRONG_TAG_PATTERN, "<strong>"); s = replace(s, CLOSING_STRONG_TAG_PATTERN, "</strong>"); s = replace(s, OPENING_I_TAG_PATTERN, "<i>"); s = replace(s, CLOSING_I_TAG_PATTERN, "</i>"); s = replace(s, OPENING_EM_TAG_PATTERN, "<em>"); s = replace(s, CLOSING_EM_TAG_PATTERN, "</em>"); s = replace(s, OPENING_BLOCKQUOTE_TAG_PATTERN, "<blockquote>"); s = replace(s, CLOSING_BLOCKQUOTE_TAG_PATTERN, "</blockquote>"); s = replace(s, BR_TAG_PATTERN, "<br />"); s = replace(s, OPENING_P_TAG_PATTERN, "<p>"); s = replace(s, CLOSING_P_TAG_PATTERN, "</p>"); s = replace(s, OPENING_PRE_TAG_PATTERN, "<pre>"); s = replace(s, CLOSING_PRE_TAG_PATTERN, "</pre>"); s = replace(s, OPENING_UL_TAG_PATTERN, "<ul>"); s = replace(s, CLOSING_UL_TAG_PATTERN, "</ul>"); s = replace(s, OPENING_OL_TAG_PATTERN, "<ol>"); s = replace(s, CLOSING_OL_TAG_PATTERN, "</ol>"); s = replace(s, OPENING_LI_TAG_PATTERN, "<li>"); s = replace(s, CLOSING_LI_TAG_PATTERN, "</li>"); // HTTP links s = replace(s, CLOSING_A_TAG_PATTERN, "</a>"); Matcher m = OPENING_A_TAG_PATTERN.matcher(s); while (m.find()) { int start = m.start(); int end = m.end(); String link = s.substring(start, end); link = "<" + link.substring(4, link.length() - 4) + ">"; s = s.substring(0, start) + link + s.substring(end, s.length()); m = OPENING_A_TAG_PATTERN.matcher(s); } // escaped angle brackets s = s.replaceAll("&amp;lt;", "&lt;"); s = s.replaceAll("&amp;gt;", "&gt;"); s = s.replaceAll("&amp; s = s.replaceAll("&amp;nbsp;", "&nbsp;"); return s; } private static String replace(String string, Pattern pattern, String replacement) { Matcher m = pattern.matcher(string); return m.replaceAll(replacement); } /** * Filters out newline characters. * * @param s the String to filter * @return the filtered String */ public static String filterNewlines(String s) { if (s == null) { return null; } StringBuffer buf = new StringBuffer(s.length()); // loop through every character and replace if necessary int length = s.length(); for (int i = 0; i < length; i++) { switch (s.charAt(i)) { case '\r': break; default : buf.append(s.charAt(i)); } } return buf.toString(); } /** * Filters out all HTML tags. * * @param s the String to filter * @return the filtered String */ public static String filterHTML(String s) { if (s == null) { return null; } s = s.replaceAll("&lt;", ""); s = s.replaceAll("&gt;", ""); s = s.replaceAll("&nbsp;", ""); return s.replaceAll("<.*?>", ""); } }
package com.RNFetchBlob; import android.app.DownloadManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.net.Uri; import android.util.Base64; import android.util.Log; import com.RNFetchBlob.Response.RNFetchBlobDefaultResp; import com.RNFetchBlob.Response.RNFetchBlobFileResp; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableMapKeySetIterator; import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.DeviceEventManagerModule; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLEncoder; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.util.HashMap; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.ConnectionPool; import okhttp3.Headers; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import okhttp3.FormBody; import okhttp3.internal.framed.Header; import okhttp3.internal.http.OkHeaders; public class RNFetchBlobReq extends BroadcastReceiver implements Runnable { enum RequestType { Form, SingleFile, AsIs, WithoutBody, Others }; enum ResponseType { KeepInMemory, FileStorage }; public static HashMap<String, Call> taskTable = new HashMap<>(); static HashMap<String, Boolean> progressReport = new HashMap<>(); static HashMap<String, Boolean> uploadProgressReport = new HashMap<>(); static ConnectionPool pool = new ConnectionPool(); MediaType contentType = RNFetchBlobConst.MIME_OCTET; ReactApplicationContext ctx; RNFetchBlobConfig options; String taskId; String method; String url; String rawRequestBody; String destPath; ReadableArray rawRequestBodyArray; ReadableMap headers; Callback callback; long contentLength; long downloadManagerId; RequestType requestType; ResponseType responseType; WritableMap respInfo; boolean timeout = false; public boolean reportProgress = false; public boolean reportUploadProgress = false; public RNFetchBlobReq(ReadableMap options, String taskId, String method, String url, ReadableMap headers, String body, ReadableArray arrayBody, final Callback callback) { this.method = method; this.options = new RNFetchBlobConfig(options); this.taskId = taskId; this.url = url; this.headers = headers; this.callback = callback; this.rawRequestBody = body; this.rawRequestBodyArray = arrayBody; if(this.options.fileCache || this.options.path != null) responseType = ResponseType.FileStorage; else responseType = ResponseType.KeepInMemory; if (body != null) requestType = RequestType.SingleFile; else if (arrayBody != null) requestType = RequestType.Form; else requestType = RequestType.WithoutBody; } public static void cancelTask(String taskId) { if(taskTable.containsKey(taskId)) { Call call = taskTable.get(taskId); call.cancel(); taskTable.remove(taskId); } } @Override public void run() { // use download manager instead of default HTTP implementation if (options.addAndroidDownloads != null && options.addAndroidDownloads.hasKey("useDownloadManager")) { if (options.addAndroidDownloads.getBoolean("useDownloadManager")) { Uri uri = Uri.parse(url); DownloadManager.Request req = new DownloadManager.Request(uri); req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); if (options.addAndroidDownloads.hasKey("title")) { req.setTitle(options.addAndroidDownloads.getString("title")); } if (options.addAndroidDownloads.hasKey("description")) { req.setDescription(options.addAndroidDownloads.getString("description")); } // set headers ReadableMapKeySetIterator it = headers.keySetIterator(); while (it.hasNextKey()) { String key = it.nextKey(); req.addRequestHeader(key, headers.getString(key)); } Context appCtx = RNFetchBlob.RCTContext.getApplicationContext(); DownloadManager dm = (DownloadManager) appCtx.getSystemService(Context.DOWNLOAD_SERVICE); downloadManagerId = dm.enqueue(req); appCtx.registerReceiver(this, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); return; } } // find cached result if `key` property exists String cacheKey = this.taskId; String ext = this.options.appendExt != "" ? "." + this.options.appendExt : ""; if (this.options.key != null) { cacheKey = RNFetchBlobUtils.getMD5(this.options.key); if (cacheKey == null) { cacheKey = this.taskId; } File file = new File(RNFetchBlobFS.getTmpPath(RNFetchBlob.RCTContext, cacheKey) + ext); if (file.exists()) { callback.invoke(null, file.getAbsolutePath()); return; } } if(this.options.path != null) this.destPath = this.options.path; else if(this.options.fileCache == true) this.destPath = RNFetchBlobFS.getTmpPath(RNFetchBlob.RCTContext, cacheKey) + ext; OkHttpClient.Builder clientBuilder; try { // use trusty SSL socket if (this.options.trusty) { clientBuilder = RNFetchBlobUtils.getUnsafeOkHttpClient(); } else { clientBuilder = new OkHttpClient.Builder(); } final Request.Builder builder = new Request.Builder(); try { builder.url(new URL(url)); } catch (MalformedURLException e) { e.printStackTrace(); } HashMap<String, String> mheaders = new HashMap<>(); // set headers if (headers != null) { ReadableMapKeySetIterator it = headers.keySetIterator(); while (it.hasNextKey()) { String key = it.nextKey(); String value = headers.getString(key); builder.header(key, value); mheaders.put(key,value); } } if(method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put")) { String cType = getHeaderIgnoreCases(mheaders, "Content-Type").toLowerCase(); if(cType == null) { builder.header("Content-Type", "application/octet-stream"); requestType = RequestType.SingleFile; } if(rawRequestBody != null) { if(rawRequestBody.startsWith(RNFetchBlobConst.FILE_PREFIX)) { requestType = RequestType.SingleFile; } else if (cType.toLowerCase().contains(";base64") || cType.toLowerCase().startsWith("application/octet")) { requestType = RequestType.SingleFile; } else { requestType = RequestType.AsIs; } } } else { requestType = RequestType.WithoutBody; } // set request body switch (requestType) { case SingleFile: builder.method(method, new RNFetchBlobBody( taskId, requestType, rawRequestBody, MediaType.parse(getHeaderIgnoreCases(mheaders, "content-type")) )); break; case AsIs: builder.method(method, new RNFetchBlobBody( taskId, requestType, rawRequestBody, MediaType.parse(getHeaderIgnoreCases(mheaders, "content-type")) )); break; case Form: builder.method(method, new RNFetchBlobBody( taskId, requestType, rawRequestBodyArray, MediaType.parse("multipart/form-data; boundary=RNFetchBlob-" + taskId) )); break; case WithoutBody: if(method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) { builder.method(method, RequestBody.create(null, new byte[0])); } else builder.method(method, null); break; } final Request req = builder.build(); // create response handler clientBuilder.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { try { Response originalResponse = chain.proceed(req); ResponseBody extended; switch (responseType) { case KeepInMemory: extended = new RNFetchBlobDefaultResp( RNFetchBlob.RCTContext, taskId, originalResponse.body()); break; case FileStorage: extended = new RNFetchBlobFileResp( RNFetchBlob.RCTContext, taskId, originalResponse.body(), destPath); break; default: extended = new RNFetchBlobDefaultResp( RNFetchBlob.RCTContext, taskId, originalResponse.body()); break; } return originalResponse.newBuilder().body(extended).build(); } catch(SocketTimeoutException ex) { timeout = true; } return chain.proceed(chain.request()); } }); if(options.timeout > 0) { clientBuilder.connectTimeout(options.timeout, TimeUnit.MILLISECONDS); clientBuilder.readTimeout(options.timeout, TimeUnit.MILLISECONDS); } else { clientBuilder.connectTimeout(-1, TimeUnit.MILLISECONDS); clientBuilder.readTimeout(-1, TimeUnit.MILLISECONDS); } clientBuilder.connectionPool(pool); clientBuilder.retryOnConnectionFailure(false); OkHttpClient client = clientBuilder.build(); Call call = client.newCall(req); taskTable.put(taskId, call); call.enqueue(new okhttp3.Callback() { @Override public void onFailure(Call call, IOException e) { if(respInfo == null) { respInfo = Arguments.createMap(); } // check if this error caused by timeout if(e.getClass().equals(SocketTimeoutException.class)) { respInfo.putBoolean("timeout", true); callback.invoke("request timed out.", respInfo, null); } else callback.invoke(e.getLocalizedMessage(), respInfo, null); removeTaskInfo(); } @Override public void onResponse(Call call, Response response) throws IOException { ReadableMap notifyConfig = options.addAndroidDownloads; respInfo = getResponseInfo(response); // Download manager settings if(notifyConfig != null ) { String title = "", desc = "", mime = "text/plain"; boolean scannable = false, notification = false; if(notifyConfig.hasKey("title")) title = options.addAndroidDownloads.getString("title"); if(notifyConfig.hasKey("description")) desc = notifyConfig.getString("description"); if(notifyConfig.hasKey("mime")) mime = notifyConfig.getString("mime"); if(notifyConfig.hasKey("mediaScannable")) scannable = notifyConfig.getBoolean("mediaScannable"); if(notifyConfig.hasKey("notification")) notification = notifyConfig.getBoolean("notification"); DownloadManager dm = (DownloadManager)RNFetchBlob.RCTContext.getSystemService(RNFetchBlob.RCTContext.DOWNLOAD_SERVICE); dm.addCompletedDownload(title, desc, scannable, mime, destPath, contentLength, notification); } done(response); } }); } catch (Exception error) { error.printStackTrace(); taskTable.remove(taskId); callback.invoke("RNFetchBlob request error: " + error.getMessage() + error.getCause(), this.respInfo); } } /** * Remove cached information of the HTTP task */ private void removeTaskInfo() { if(taskTable.containsKey(taskId)) taskTable.remove(taskId); if(uploadProgressReport.containsKey(taskId)) uploadProgressReport.remove(taskId); if(progressReport.containsKey(taskId)) progressReport.remove(taskId); } /** * Send response data back to javascript context. * @param resp OkHttp response object */ private void done(Response resp) { emitStateEvent(getResponseInfo(resp)); switch (responseType) { case KeepInMemory: try { // For XMLHttpRequest, automatic response data storing strategy, when response // header is not `application/json` or `text/plain`, write response data to // file system. if(isBlobResponse(resp) && options.auto == true) { String dest = RNFetchBlobFS.getTmpPath(ctx, taskId); InputStream ins = resp.body().byteStream(); FileOutputStream os = new FileOutputStream(new File(dest)); byte [] buffer = new byte[10240]; int read = ins.read(buffer); os.write(buffer,0,read); while(read > 0) { os.write(buffer,0,read); read = ins.read(buffer); } ins.close(); os.close(); WritableMap info = getResponseInfo(resp); callback.invoke(null, info, dest); } else { // we should check if the response data is a UTF8 string, because BASE64 // encoding will somehow break the UTF8 string format. In order to encode // UTF8 string correctly, we should do URL encoding before BASE64. String utf8Str; byte[] b = resp.body().bytes(); CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder(); try { encoder.encode(ByteBuffer.wrap(b).asCharBuffer()); // if the data can be encoded to UTF8 append URL encode b = URLEncoder.encode(new String(b), "UTF-8").getBytes(); } // This usually mean the data is binary data catch(CharacterCodingException e) { } finally { callback.invoke(null, getResponseInfo(resp), android.util.Base64.encodeToString(b, Base64.NO_WRAP)); } } } catch (IOException e) { callback.invoke("RNFetchBlob failed to encode response data to BASE64 string.", null); } break; case FileStorage: try{ resp.body().bytes(); } catch (Exception ignored) { } callback.invoke(null, getResponseInfo(resp), this.destPath); break; default: try { callback.invoke(null, getResponseInfo(resp), new String(resp.body().bytes(), "UTF-8")); } catch (IOException e) { callback.invoke("RNFetchBlob failed to encode response data to UTF8 string.", null); } break; } removeTaskInfo(); } public static boolean isReportProgress(String taskId) { if(!progressReport.containsKey(taskId)) return false; return progressReport.get(taskId); } public static boolean isReportUploadProgress(String taskId) { if(!uploadProgressReport.containsKey(taskId)) return false; return uploadProgressReport.get(taskId); } private WritableMap getResponseInfo(Response resp) { WritableMap info = Arguments.createMap(); info.putInt("status", resp.code()); info.putString("state", "2"); info.putString("taskId", this.taskId); info.putBoolean("timeout", timeout); WritableMap headers = Arguments.createMap(); for(int i =0;i< resp.headers().size();i++) { headers.putString(resp.headers().name(i), resp.headers().value(i)); } info.putMap("headers", headers); Headers h = resp.headers(); if(getHeaderIgnoreCases(h, "content-type").equalsIgnoreCase("text/")) { info.putString("respType", "text"); } else if(getHeaderIgnoreCases(h, "content-type").contains("application/json")) { info.putString("respType", "json"); } else if(getHeaderIgnoreCases(h, "content-type").length() < 1) { info.putString("respType", "blob"); } else { info.putString("respType", "text"); } return info; } private boolean isBlobResponse(Response resp) { Headers h = resp.headers(); boolean isText = !getHeaderIgnoreCases(h, "content-type").equalsIgnoreCase("text/"); boolean isJSON = !getHeaderIgnoreCases(h, "content-type").equalsIgnoreCase("application/json"); return !(isJSON || isText); } private String getHeaderIgnoreCases(Headers headers, String field) { String val = headers.get(field); if(val != null) return val; return headers.get(field.toLowerCase()) == null ? "" : headers.get(field.toLowerCase()); } private String getHeaderIgnoreCases(HashMap<String,String> headers, String field) { String val = headers.get(field); if(val != null) return val; return headers.get(field.toLowerCase()) == null ? "" : headers.get(field.toLowerCase()); } private void emitStateEvent(WritableMap args) { RNFetchBlob.RCTContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(RNFetchBlobConst.EVENT_HTTP_STATE, args); } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { Context appCtx = RNFetchBlob.RCTContext.getApplicationContext(); long id = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID); if (id == this.downloadManagerId) { DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(downloadManagerId); DownloadManager dm = (DownloadManager) appCtx.getSystemService(Context.DOWNLOAD_SERVICE); dm.query(query); Cursor c = dm.query(query); if (c.moveToFirst()) { String contentUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); Uri uri = Uri.parse(contentUri); Cursor cursor = appCtx.getContentResolver().query(uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null); if (cursor != null) { cursor.moveToFirst(); String filePath = cursor.getString(0); cursor.close(); this.callback.invoke(null, null, filePath); } else this.callback.invoke(null, null, null); } } } } }
package com.yahoo.document; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.Struct; import com.yahoo.document.datatypes.StructuredFieldValue; import com.yahoo.document.json.JsonWriter; import com.yahoo.document.serialization.DocumentReader; import com.yahoo.document.serialization.DocumentSerializer; import com.yahoo.document.serialization.DocumentSerializerFactory; import com.yahoo.document.serialization.DocumentWriter; import com.yahoo.document.serialization.FieldReader; import com.yahoo.document.serialization.FieldWriter; import com.yahoo.document.serialization.SerializationException; import com.yahoo.document.serialization.XmlSerializationHelper; import com.yahoo.document.serialization.XmlStream; import com.yahoo.io.GrowableByteBuffer; import com.yahoo.vespa.objects.BufferSerializer; import com.yahoo.vespa.objects.Ids; import com.yahoo.vespa.objects.Serializer; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.Map; /** * A document is an identifiable * set of value bindings of a {@link DocumentType document type}. * A document represents an instance of some entity of interest * in an application, like an article, a web document, a product, etc. * * Deprecation: Try to use document set and get methods only with FieldValue types, * not with primitive types. Support for direct access to primitive types will * be removed soon. * * @author bratseth * @author Einar M R Rosenvinge */ public class Document extends StructuredFieldValue { public static final int classId = registerClass(Ids.document + 3, Document.class); public static final short SERIALIZED_VERSION = 8; private DocumentId docId; private Struct header; private Struct body; private Long lastModified = null; /** * Create a document with the given document type and identifier. * @param docType DocumentType to use for creation * @param id The id for this document */ public Document(DocumentType docType, String id) { this(docType, new DocumentId(id)); } /** * Create a document with the given document type and identifier. * @param docType DocumentType to use for creation * @param id The id for this document */ public Document(DocumentType docType, DocumentId id) { super(docType); setNewType(docType); internalSetId(id, docType); } /** * Creates a document that is a shallow copy of another. * * @param doc The document to copy. */ public Document(Document doc) { this(doc.getDataType(), doc.getId()); header = doc.header; body = doc.body; lastModified = doc.lastModified; } /** * * @param reader The deserializer to use for creating this document */ public Document(DocumentReader reader) { super(null); reader.read(this); } public DocumentId getId() { return docId; } public void setId(DocumentId id) { internalSetId(id, getDataType()); } private void internalSetId(DocumentId id, DocumentType docType) { if (id != null && id.hasDocType() && docType != null && !id.getDocType().equals(docType.getName())) { throw new IllegalArgumentException("Trying to set a document id (type " + id.getDocType() + ") that doesn't match the document type (" + getDataType().getName() + ")."); } docId = id; } public Struct getHeader() { return header; } public Struct getBody() { return body; } @Override public void assign(Object o) { throw new IllegalArgumentException("Assign not implemented for " + getClass() + " objects"); } @Override public Document clone() { Document doc = (Document) super.clone(); doc.docId = docId.clone(); doc.header = header.clone(); doc.body = body.clone(); return doc; } private void setNewType(DocumentType type) { header = type.getHeaderType().createFieldValue(); body = type.getBodyType().createFieldValue(); } public void setDataType(DataType type) { if (docId != null && docId.hasDocType() && !docId.getDocType().equals(type.getName())) { throw new IllegalArgumentException("Trying to set a document type (" + type.getName() + ") that doesn't match the document id (" + docId + ")."); } super.setDataType(type); setNewType((DocumentType)type); } public int getSerializedSize() throws SerializationException { DocumentSerializer data = DocumentSerializerFactory.create42(new GrowableByteBuffer(64 * 1024, 2.0f)); data.write(this); return data.getBuf().position(); } /** * This is an approximation of serialized size. We just set it to 4096 as a definition of a medium document. * @return Approximate size of document (4096) */ public final int getApproxSize() { return 4096; } public void serialize(OutputStream out) throws SerializationException { DocumentSerializer writer = DocumentSerializerFactory.create42(new GrowableByteBuffer(64 * 1024, 2.0f)); writer.write(this); GrowableByteBuffer data = writer.getBuf(); byte[] array; if (data.hasArray()) { //just get the array array = data.array(); } else { //copy the bytebuffer into the array array = new byte[data.position()]; int endPos = data.position(); data.position(0); data.get(array); data.position(endPos); } try { out.write(array, 0, data.position()); } catch (IOException ioe) { throw new SerializationException(ioe); } } public static Document createDocument(DocumentReader buffer) { return new Document(buffer); } @Override public Field getField(String fieldName) { Field field = header.getField(fieldName); if (field == null) { field = body.getField(fieldName); } if (field == null) { for(DocumentType parent : getDataType().getInheritedTypes()) { field = parent.getField(fieldName); if (field != null) { break; } } } return field; } @Override public FieldValue getFieldValue(Field field) { if (field.isHeader()) { return header.getFieldValue(field); } else { return body.getFieldValue(field); } } @Override protected void doSetFieldValue(Field field, FieldValue value) { if (field.isHeader()) { header.setFieldValue(field, value); } else { body.setFieldValue(field, value); } } @Override public FieldValue removeFieldValue(Field field) { if (field.isHeader()) { return header.removeFieldValue(field); } else { return body.removeFieldValue(field); } } @Override public void clear() { header.clear(); body.clear(); } @Override public Iterator<Map.Entry<Field, FieldValue>> iterator() { return new Iterator<Map.Entry<Field, FieldValue>>() { private Iterator<Map.Entry<Field, FieldValue>> headerIt = header.iterator(); private Iterator<Map.Entry<Field, FieldValue>> bodyIt = body.iterator(); public boolean hasNext() { if (headerIt != null) { if (headerIt.hasNext()) { return true; } else { headerIt = null; } } return bodyIt.hasNext(); } public Map.Entry<Field, FieldValue> next() { return (headerIt == null ? bodyIt.next() : headerIt.next()); } public void remove() { if (headerIt == null) { bodyIt.remove(); } else { headerIt.remove(); } } }; } public String toString() { return "document '" + String.valueOf(docId) + "' of type '" + getDataType().getName() + "'"; } public String toXML(String indent) { XmlStream xml = new XmlStream(); xml.setIndent(indent); xml.beginTag("document"); printXml(xml); xml.endTag(); return xml.toString(); } /** * Get XML representation of the document root and its children, contained * within a &lt;document&gt;&lt;/document&gt; tag. * @return XML representation of document */ public String toXml() { return toXML(" "); } public void printXml(XmlStream xml) { XmlSerializationHelper.printDocumentXml(this, xml); } /** * Get JSON representation of the document root and its children contained in a JSON object * @return JSON representation of document */ public String toJson() { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); JsonWriter writer = new JsonWriter(buffer); writer.write(this); try { return buffer.toString("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** Returns true if the argument is a document which has the same set of values */ @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Document)) return false; Document other = (Document) o; return (super.equals(o) && docId.equals(other.docId) && header.equals(other.header) && body.equals(other.body)); } @Override public int hashCode() { return 31 * super.hashCode() + (docId != null ? docId.hashCode() : 0); } /** * Returns the last modified time of this Document, when stored in persistent storage. This is typically set by the * library that retrieves the Document from persistent storage. * * This variable doesn't really belong in document. It is used when retrieving docblocks of documents to be able to * see when documents was last modified in VDS, without having to add modified times separate in the API. * * NOTE: This is a transient field, and will not be serialized with a Document (will be null after deserialization). * * @return the last modified time of this Document (in milliseconds), or null if unset */ public Long getLastModified() { return lastModified; } /** * Sets the last modified time of this Document. This is typically set by the library that retrieves the * Document from persistent storage, and should not be set by arbitrary clients. NOTE: This is a * transient field, and will not be serialized with a Document (will be null after deserialization). * * @param lastModified the last modified time of this Document (in milliseconds) */ public void setLastModified(Long lastModified) { this.lastModified = lastModified; } public void onSerialize(Serializer data) throws SerializationException { serialize((DocumentWriter)data); } @SuppressWarnings("deprecation") public void serializeHeader(Serializer data) throws SerializationException { if (data instanceof DocumentWriter) { if (data instanceof com.yahoo.document.serialization.VespaDocumentSerializer42) { ((com.yahoo.document.serialization.VespaDocumentSerializer42)data).setHeaderOnly(true); } serialize((DocumentWriter)data); } else if (data instanceof BufferSerializer) { serialize(DocumentSerializerFactory.create42(((BufferSerializer) data).getBuf(), true)); } else { DocumentSerializer fw = DocumentSerializerFactory.create42(new GrowableByteBuffer(), true); serialize(fw); data.put(null, fw.getBuf().getByteBuffer()); } } public void serializeBody(Serializer data) throws SerializationException { if (getBody().getFieldCount() > 0) { if (data instanceof FieldWriter) { getBody().serialize(new Field("body", getBody().getDataType()), (FieldWriter) data); } else if (data instanceof BufferSerializer) { getBody().serialize(new Field("body", getBody().getDataType()), DocumentSerializerFactory.create42(((BufferSerializer) data).getBuf())); } else { DocumentSerializer fw = DocumentSerializerFactory.create42(new GrowableByteBuffer()); getBody().serialize(new Field("body", getBody().getDataType()), fw); data.put(null, fw.getBuf().getByteBuffer()); } } } @Override public DocumentType getDataType() { return (DocumentType)super.getDataType(); } @Override public int getFieldCount() { return header.getFieldCount() + body.getFieldCount(); } public void serialize(DocumentWriter writer) { writer.write(this); } public void deserialize(DocumentReader reader) { reader.read(this); } @Override public void serialize(Field field, FieldWriter writer) { writer.write(field, this); } /* (non-Javadoc) * @see com.yahoo.document.datatypes.FieldValue#deserialize(com.yahoo.document.Field, com.yahoo.document.serialization.FieldReader) */ @Override public void deserialize(Field field, FieldReader reader) { reader.read(field, this); } @Override public int compareTo(FieldValue fieldValue) { int comp = super.compareTo(fieldValue); if (comp != 0) { return comp; } //types are equal, this must be of this type Document otherValue = (Document) fieldValue; comp = getId().compareTo(otherValue.getId()); if (comp != 0) { return comp; } comp = header.compareTo(otherValue.header); if (comp != 0) { return comp; } comp = body.compareTo(otherValue.body); return comp; } }
package nu.validator.perftest; import java.io.CharArrayReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import nu.validator.htmlparser.common.XmlViolationPolicy; import nu.validator.htmlparser.dom.HtmlDocumentBuilder; import nu.validator.htmlparser.sax.HtmlParser; import nu.validator.saxtree.TreeBuilder; import nu.validator.xml.NullEntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; public class ParserPerfHarness { private final long endTime; private final XMLReader reader; private final char[] testData; /** * @param endTime * @param reader * @param testFile * @throws IOException */ public ParserPerfHarness(long endTime, XMLReader reader, char[] testData) throws IOException { this.endTime = endTime; this.reader = reader; this.testData = testData; } private static char[] loadFileIntoArray(File testFile) throws IOException { Reader in = new InputStreamReader(new FileInputStream(testFile), "utf-8"); StringBuilder sb = new StringBuilder(); int c = 0; while ((c = in.read()) != -1) { sb.append((char) c); } char[] rv = new char[sb.length()]; sb.getChars(0, sb.length(), rv, 0); return rv; } public long runLoop() throws SAXException, IOException { long times = 0; while (System.currentTimeMillis() < endTime) { InputSource inputSource = new InputSource(new CharArrayReader( testData)); inputSource.setEncoding("utf-8"); reader.parse(inputSource); times++; } return times; } /** * @param args * @throws IOException * @throws SAXException * @throws ParserConfigurationException */ public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException { long duration = Long.parseLong(args[0]) * 60000L; boolean html = "h".equals(args[1]); String path = args[2]; char[] testData = loadFileIntoArray(new File(path)); XMLReader reader = null; if (html) { HtmlParser parser = new HtmlParser(XmlViolationPolicy.ALLOW); parser.setContentHandler(new DefaultHandler()); parser.setStreamabilityViolationPolicy(XmlViolationPolicy.FATAL); reader = parser; } else { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); reader = factory.newSAXParser().getXMLReader(); reader.setContentHandler(new DefaultHandler()); reader.setEntityResolver(new NullEntityResolver()); } System.out.println("Warmup:"); System.out.println((new ParserPerfHarness(System.currentTimeMillis() + duration, reader, testData)).runLoop()); System.gc(); System.out.println("Real:"); System.out.println((new ParserPerfHarness(System.currentTimeMillis() + duration, reader, testData)).runLoop()); } }
package bzh.plealog.bioinfo.api.data.searchjob; import java.io.Serializable; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.TreeMap; import bzh.plealog.bioinfo.api.core.config.CoreSystemConfigurator; import bzh.plealog.bioinfo.api.data.feature.AnnotationDataModelConstants; import bzh.plealog.bioinfo.api.data.feature.AnnotationDataModelConstants.ANNOTATION_CATEGORY; import bzh.plealog.bioinfo.api.data.searchresult.SRCTerm; import bzh.plealog.bioinfo.api.data.searchresult.SRClassification; import bzh.plealog.bioinfo.api.data.searchresult.SRHit; import bzh.plealog.bioinfo.api.data.searchresult.SRHsp; import bzh.plealog.bioinfo.api.data.searchresult.SRHspScore; import bzh.plealog.bioinfo.api.data.searchresult.SRHspSequence; import bzh.plealog.bioinfo.api.data.searchresult.SRIteration; import bzh.plealog.bioinfo.api.data.searchresult.SROutput; import bzh.plealog.bioinfo.api.data.searchresult.SRRequestInfo; import bzh.plealog.bioinfo.api.data.sequence.BankSequenceInfo; import bzh.plealog.bioinfo.io.searchresult.csv.AnnotationDataModel; import bzh.plealog.bioinfo.io.searchresult.csv.ExtractAnnotation; /** * This class contains the summary of a BLAST result. Such a summary reports the * information related to the best hit of that result. * * Directly used for serialization. Modify with caution. * * @author Patrick G. Durand */ public class SRFileSummary implements Serializable { private static final long serialVersionUID = 7467266811057328060L; private int nHits; private String bestHitAccession; private String bestHitDescription; private String bestHitLength; private String bestHitEValue; private String bestHitIdentify; private String bestHitSimilarity; private String bestHitCoverage; private String bestHitScore; private String bestHitScoreBits; private String bestHitCoverageH; private String taxonomy; private String organism; private String queryLength; private String queryFrom; private String queryTo; private String queryFrame; private String queryGaps; private String bestHitFrom; private String bestHitTo; private String bestHitFrame; private String bestHitGaps; private String alignLength; private String nbHsps; private String queryId; private String queryDescription; private String execMsg; private String queryRID; private SROutput.FEATURES_CONTAINER featContainer; private boolean filtered; //complete classification (main Terms + FAKE ones (those internal to paths). private SRClassification classification; private transient String totalGaps; private transient String percentGaps; private transient String mistmatches; private transient String LCA; private transient String rankLCA; private transient String originJobName = NOT_APPLICABLE; private transient String originJobId = NOT_APPLICABLE; //mains terms only for View purpose private transient List<SRTermSummary> mainTermsForView; private transient boolean _initialized; public static final String UNKNOWN = "-"; public static final String NOT_APPLICABLE = "none"; public static final int HEADER_SIZE = 128; public static final DecimalFormat EVALUE_FORMATTER1 = new DecimalFormat("0. public static final DecimalFormat EVALUE_FORMATTER2 = new DecimalFormat(" public static final DecimalFormat PCT_FORMATTER = new DecimalFormat(" public static final DecimalFormat SCORE_FORMATTER = new DecimalFormat(" /** * Default constructor. */ public SRFileSummary() { reset(true); setBestHitAccession(NOT_APPLICABLE); setBestHitDescription(NOT_APPLICABLE); } public void reset(boolean updateQuery) { setBestHitAccession(NOT_APPLICABLE); setBestHitDescription(NOT_APPLICABLE); setBestHitEValue(UNKNOWN); setBestHitLength(UNKNOWN); setBestHitIdentify(UNKNOWN); setBestHitSimilarity(UNKNOWN); setBestHitCoverage(UNKNOWN); setBestHitScore(UNKNOWN); setBestHitScoreBits(UNKNOWN); setBestHitCoverageH(UNKNOWN); setBestHitFrom(UNKNOWN); setBestHitTo(UNKNOWN); setBestHitFrame(UNKNOWN); setBestHitGaps(UNKNOWN); setQueryFrom(UNKNOWN); setQueryTo(UNKNOWN); setQueryFrame(UNKNOWN); setQueryGaps(UNKNOWN); setAlignLength(UNKNOWN); setNbHsps(UNKNOWN); if (updateQuery) { setQueryId(UNKNOWN); setQueryDescription(UNKNOWN); setQueryLength(UNKNOWN); } setExecMsg(null); setTaxonomy(UNKNOWN); setOrganism(UNKNOWN); setFeatContainer(SROutput.FEATURES_CONTAINER.none); setFiltered(false); setNHits(0); setQueryRID(UNKNOWN); setTotalGaps(UNKNOWN); setPercentGaps(UNKNOWN); setMistmatches(UNKNOWN); setLCA(UNKNOWN); setRankLCA(UNKNOWN); setOriginJobName(NOT_APPLICABLE); } /** * Initializes this BFileSummary from a BOutput. */ public void initialize(SROutput output) { BankSequenceInfo si; SRIteration iterHits; SRHit hit; SRHsp hsp; SRHspScore scores; SRHspSequence seq; double eval; if (output.countIteration() == 0) { reset(false); return; } // init Query fields Object o = output.getRequestInfo().getValue(SRRequestInfo.QUERY_LENGTH_DESCRIPTOR_KEY); setQueryLength(o != null ? o.toString() : UNKNOWN); o = output.getRequestInfo().getValue(SRRequestInfo.QUERY_ID_DESCRIPTOR_KEY); setQueryId(o != null ? o.toString() : UNKNOWN); o = output.getRequestInfo().getValue(SRRequestInfo.QUERY_DEF_DESCRIPTOR_KEY); setQueryDescription(o != null ? o.toString() : UNKNOWN); //do we hat hits? iterHits = output.getIteration(0); if (iterHits.countHit() == 0) { reset(false); return; } //init best hit fields hit = iterHits.getHit(0); nHits = iterHits.countHit(); setBestHitAccession(hit.getHitAccession()); String definition = hit.getHitDef(); int idx = definition.indexOf("[["); if (idx != -1) { definition = definition.substring(0, idx); } if (definition.length() > HEADER_SIZE) definition = definition.substring(0, HEADER_SIZE); setBestHitDescription(definition); setBestHitLength(String.valueOf(hit.getHitLen())); hsp = hit.getHsp(0); scores = hsp.getScores(); eval = scores.getEvalue(); if (eval > 0 && eval < 0.1) setBestHitEValue(EVALUE_FORMATTER1.format(eval)); else setBestHitEValue(EVALUE_FORMATTER2.format(eval)); eval = scores.getScore(); if (eval > 0 && eval < 0.1) setBestHitScore(EVALUE_FORMATTER1.format(eval)); else setBestHitScore(EVALUE_FORMATTER2.format(eval)); setBestHitScoreBits(SCORE_FORMATTER.format(scores.getBitScore())); setBestHitIdentify(PCT_FORMATTER.format(scores.getIdentityP()) + "%"); setBestHitSimilarity(PCT_FORMATTER.format(scores.getPositiveP()) + "%"); setTotalGaps(String.valueOf(scores.getGaps())); setPercentGaps(PCT_FORMATTER.format(scores.getGapsP()) + "%"); setMistmatches(String.valueOf(scores.getMismatches())); setBestHitCoverage(PCT_FORMATTER.format(hit.getQueryGlobalCoverage()) + "%"); setBestHitCoverageH(PCT_FORMATTER.format(hit.getHitGlobalCoverage()) + "%"); seq = hsp.getHit(); setBestHitFrom(String.valueOf(seq.getFrom())); setBestHitTo(String.valueOf(seq.getTo())); setBestHitFrame(String.valueOf(seq.getFrame())); setBestHitGaps(String.valueOf(seq.getGaps())); seq = hsp.getQuery(); setQueryFrom(String.valueOf(seq.getFrom())); setQueryTo(String.valueOf(seq.getTo())); setQueryFrame(String.valueOf(seq.getFrame())); setQueryGaps(String.valueOf(seq.getGaps())); setAlignLength(String.valueOf(hsp.getScores().getAlignLen())); setNbHsps(String.valueOf(hit.countHsp())); setFeatContainer(output.checkFeatures()); si = hit.getSequenceInfo(); if (si != null) { if (si.getOrganism() != null) organism = si.getOrganism(); if (si.getTaxonomy() != null) taxonomy = si.getTaxonomy(); } // Get unique set of Bio Classification IDs if (output.getClassification()!=null) { SRClassification classification = CoreSystemConfigurator.getSRFactory().creationBClassification(); SRClassification refClassification; //classification data if any; get data for best hit only by default TreeMap<String, TreeMap<AnnotationDataModelConstants.ANNOTATION_CATEGORY, HashMap<String, AnnotationDataModel>>> annotatedHitsHashMap = new TreeMap<String, TreeMap<AnnotationDataModelConstants.ANNOTATION_CATEGORY, HashMap<String, AnnotationDataModel>>>(); TreeMap<AnnotationDataModelConstants.ANNOTATION_CATEGORY, TreeMap<String, AnnotationDataModel>> annotationDictionary = new TreeMap<AnnotationDataModelConstants.ANNOTATION_CATEGORY, TreeMap<String, AnnotationDataModel>>(); // Prepare Bio Classification (IPR, EC, GO and TAX) for all hits //this call populates annotatedHitsHashMap and annotationDictionary ExtractAnnotation.buildAnnotatedHitDataSet(output, 0, annotatedHitsHashMap, annotationDictionary); // Collect unique set of Bio Classification IDs of first hit only refClassification = ExtractAnnotation.buildClassificationDataSet(output.getClassification(), annotatedHitsHashMap, 0, 0, 0); //then discard FAKE terms (those making path of Terms associated to hits) Enumeration<String> ids = refClassification.getTermIDs(); String id; SRCTerm term; //prepare the view List of main Terms LinkedList<SRTermSummary>mapTerms = new LinkedList<>(); while(ids.hasMoreElements()) { id = ids.nextElement(); term = refClassification.getTerm(id); classification.addTerm(id, term); if ((term.getType().equals(SRCTerm.FAKE_TERM)|| term.getType().equals(ANNOTATION_CATEGORY.TAX.name()))==false) { mapTerms.add(new SRTermSummary(id, term)); } } setClassification(classification); //Java 8 style to sort a List by two fields mapTerms.sort(Comparator.comparing(SRTermSummary::getViewType).thenComparing(SRTermSummary::getID)); setClassificationForView(mapTerms); } _initialized = true; } /** * Sets the initial status of this BFileSummary. */ public void setInitialized(boolean initialized) { _initialized = initialized; } public boolean isInitialized() { return _initialized; } /** * Returns the accession of best hit. */ public String getBestHitAccession() { return bestHitAccession; } /** * Sets the accession of best hit. */ public void setBestHitAccession(String hitAccession) { bestHitAccession = hitAccession; } /** * Returns the description of best hit. */ public String getBestHitDescription() { return bestHitDescription; } /** * Sets the description of best hit. */ public void setBestHitDescription(String hitDescription) { bestHitDescription = hitDescription; } /** * Returns the e-value of best hit. */ public String getBestHitEValue() { return bestHitEValue; } /** * Sets the e-value of best hit. */ public void setBestHitEValue(String hitEValue) { bestHitEValue = hitEValue; } /** * Returns the length of best hit. */ public String getBestHitLength() { return bestHitLength; } /** * Sets the length of best hit. */ public void setBestHitLength(String hitLength) { bestHitLength = hitLength; } public String getBestHitCoverage() { return bestHitCoverage; } public void setBestHitCoverage(String bestHitCoverage) { this.bestHitCoverage = bestHitCoverage; } public String getBestHitIdentify() { return bestHitIdentify; } public void setBestHitIdentify(String bestHitIdentify) { this.bestHitIdentify = bestHitIdentify; } public String getBestHitSimilarity() { return bestHitSimilarity; } public void setBestHitSimilarity(String bestHitSimilarity) { this.bestHitSimilarity = bestHitSimilarity; } /** * Returns the number of hits. */ public int getNHits() { return nHits; } /** * Sets the number of hits. */ public void setNHits(int hits) { nHits = hits; } public String getBestHitScore() { return bestHitScore; } public void setBestHitScore(String bestHitScore) { this.bestHitScore = bestHitScore; } public String getBestHitScoreBits() { return bestHitScoreBits; } public void setBestHitScoreBits(String bestHitScoreBits) { this.bestHitScoreBits = bestHitScoreBits; } public String getBestHitCoverageH() { return bestHitCoverageH; } public void setBestHitCoverageH(String bestHitCoverageH) { this.bestHitCoverageH = bestHitCoverageH; } public String getTaxonomy() { return taxonomy; } public String getOrganism() { return organism; } public void setTaxonomy(String taxonomy) { this.taxonomy = taxonomy; } public void setOrganism(String organism) { this.organism = organism; } public String getQueryLength() { return queryLength; } public String getQueryFrom() { return queryFrom; } public String getQueryTo() { return queryTo; } public String getQueryFrame() { return queryFrame; } public String getBestHitFrom() { return bestHitFrom; } public String getBestHitTo() { return bestHitTo; } public String getBestHitFrame() { return bestHitFrame; } public void setQueryLength(String queryLength) { this.queryLength = queryLength; } public void setQueryFrom(String queryFrom) { this.queryFrom = queryFrom; } public void setQueryTo(String queryTo) { this.queryTo = queryTo; } public void setQueryFrame(String queryFrame) { this.queryFrame = queryFrame; } public void setBestHitFrom(String bestHitFrom) { this.bestHitFrom = bestHitFrom; } public void setBestHitTo(String bestHitTo) { this.bestHitTo = bestHitTo; } public void setBestHitFrame(String bestHitFrame) { this.bestHitFrame = bestHitFrame; } public String getQueryGaps() { return queryGaps; } public String getBestHitGaps() { return bestHitGaps; } public void setQueryGaps(String queryGaps) { this.queryGaps = queryGaps; } public void setBestHitGaps(String bestHitGaps) { this.bestHitGaps = bestHitGaps; } public String getAlignLength() { return alignLength; } public void setAlignLength(String alignLength) { this.alignLength = alignLength; } public String getNbHsps() { return nbHsps; } public void setNbHsps(String nbHsps) { this.nbHsps = nbHsps; } public String getQueryId() { return queryId; } public String getQueryDescription() { return queryDescription; } public String getExecMsg() { return execMsg; } public void setQueryId(String queryId) { this.queryId = queryId; } public void setQueryDescription(String queryDescription) { this.queryDescription = queryDescription; } public void setExecMsg(String execMsg) { this.execMsg = execMsg; } public SROutput.FEATURES_CONTAINER getFeatContainer() { return featContainer; } public void setFeatContainer(SROutput.FEATURES_CONTAINER featContainer) { this.featContainer = featContainer; } public boolean isFiltered() { return filtered; } public void setFiltered(boolean filtered) { this.filtered = filtered; } public String getQueryRID() { return queryRID; } public void setQueryRID(String queryRID) { this.queryRID = queryRID; } public String getTotalGaps() { return totalGaps; } public void setTotalGaps(String totalGaps) { this.totalGaps = totalGaps; } public String getPercentGaps() { return percentGaps; } public void setPercentGaps(String percentGaps) { this.percentGaps = percentGaps; } public String getMistmatches() { return mistmatches; } public void setMistmatches(String mistmatches) { this.mistmatches = mistmatches; } public String getLCA() { return LCA; } public void setLCA(String LCA) { this.LCA = LCA; } public String getRankLCA() { return rankLCA; } public void setRankLCA(String rankLCA) { this.rankLCA = rankLCA; } public String getOriginJobName() { return originJobName; } public void setOriginJobName(String originJobName) { this.originJobName = originJobName; } public String getOriginJobId() { return originJobId; } public void setOriginJobId(String originJobId) { this.originJobId = originJobId; } public void setClassification(SRClassification classification) { this.classification = classification; } public SRClassification getClassification() { return classification; } public void setClassificationForView(List<SRTermSummary> terms) { mainTermsForView = terms; } public List<SRTermSummary> getClassificationForView(){ return mainTermsForView; } /** * Returned a filtered list of SRTermSummary. * * @param types list of String representation of AnnotationDataModelConstants.ANNOTATION_CATEGORY values. * We use that design to enable sub-filtering of GO terms. Indeed, in addition to ANNOTATION_CATEGORY.GO, one * can use the following strings: GOC, GOP, GOF. In this parameter is null full list of SRTermSummary * is returned. * */ public List<SRTermSummary> getClassificationForView(List<String> types){ if (types==null || mainTermsForView==null) { return mainTermsForView; } ArrayList<SRTermSummary> newList; String type; newList = new ArrayList<>(); for(SRTermSummary term : mainTermsForView) { type = term.getViewType(); if (types.contains(type)) { newList.add(term); } } return newList; } public String toString() { StringBuffer szBuf; szBuf = new StringBuffer(); szBuf.append(" Nb hits: "); szBuf.append(getNHits()); szBuf.append("\n Accesion: "); szBuf.append(getBestHitAccession()); szBuf.append("\n Description: "); szBuf.append(getBestHitDescription()); szBuf.append("\n Length: "); szBuf.append(getBestHitLength()); szBuf.append("\n E-Value: "); szBuf.append(getBestHitEValue()); return szBuf.toString(); } }
package mmsort; import java.util.Comparator; public class MergeSort implements ISortAlgorithm { /** * * / 2 * @param array sort target / * @param from index of first element / * @param to index of last element (exclusive) / + 1 * @param workArray work area / * @param comparator comparator of array element / */ public static final <T> void mergeSort(final T[] array, final int from, final int to, final T[] workArray, final Comparator<? super T> comparator) { final int range = to - from; if (range <= 1) { return; } else if (range == 2) { if (comparator.compare(array[from + 1], array[from]) < 0) { T work = array[from]; array[from] = array[from + 1]; array[from + 1] = work; } return; } else if (range == 3) { if (comparator.compare(array[from + 1], array[from]) < 0) { T work = array[from]; array[from] = array[from + 1]; array[from + 1] = work; } if (comparator.compare(array[from + 2], array[from + 1]) < 0) { T work = array[from + 1]; array[from + 1] = array[from + 2]; array[from + 2] = work; if (comparator.compare(array[from + 1], array[from]) < 0) { work = array[from]; array[from] = array[from + 1]; array[from + 1] = work; } } return; } int mid = from + (to - from) / 2; mergeSort(array, from, mid, workArray, comparator); mergeSort(array, mid, to, workArray, comparator); int idx = from; int idx1 = from; int idx2 = mid; if (comparator.compare(array[mid - 1], array[mid]) < 0) return; if (mid - idx1 > 0) { System.arraycopy(array, idx1, workArray, idx1 - from, mid - idx1); } // (array) idx = idx1; while (idx1 < mid && idx2 < to) { final T value1 = workArray[idx1 - from]; final T value2 = array[idx2]; if (comparator.compare(value1, value2) <= 0) { // virtual code : (value2 < value1) == false array[idx] = value1; idx1++; } else { array[idx] = value2; idx2++; } idx++; } while (idx1 < mid) { array[idx] = workArray[idx1 - from]; idx++; idx1++; } // if (idx != idx2) // throw new RuntimeException("Position error"); } /** * Merge sort * * @param array sort target / * @param from index of first element / * @param to index of last element (exclusive) / + 1 * @param comparator comparator of array element / */ public static final <T> void mergeSort(T[] array, int from, int to, Comparator<? super T> comparator) { @SuppressWarnings("unchecked") final T[] workArray = (T[])new Object[(to - from) / 2]; mergeSort(array, from, to, workArray, comparator); } @Override public <T> void sort(final T[] array, final int from, final int to, final Comparator<? super T> comparator) { mergeSort(array, from, to, comparator); } @Override public boolean isStable() { return true; } @Override public String getName() { return "Merge Sort"; } }
package src.model; /** *Class which represents a review */ public class Recensione{ private int id; private int approvazione; private String testo; private int idGioco; private int idUtente; /** *Basic constructor */ public Recensione(){} /** *Constructor * *@param testo review's text *@param idGioco game's ID which review is about *@param idUtente user's ID who has written the review * */ public Recensione(String testo, int idGioco, int idUtente){ this.testo = testo; this.idGioco = idGioco; this.idUtente = idUtente; } /** *Full constructor * *@param id review's ID *@param approvazione number which specifies if the review is accepted or not *@param testo review's text *@param idGioco game's ID which review is about *@param idUtente user's ID who has written the review */ public Recensione(int id, int approvazione, String testo, int idGioco, int idUtente){ // Calling this() causes problems with interactions with db. this.id = id; this.approvazione = approvazione; this.testo = testo; this.idGioco = idGioco; this.idUtente = idUtente; } /** *Method used to get review's ID * *@return int number of ID */ public int getId(){ return this.id; } /** *Method used to get review's approval * *@return int id of approval */ public int getApprovazione(){ return this.approvazione; } /** *Method used to get review's text * *@return String review's text */ public String getTesto(){ return this.testo; } /** *Method used to get review's gameID * *@return int number of gameID */ public int getIdGioco(){ return this.idGioco; } /** *Method used to get review's userID * *@return int number of userID */ public int getIdUtente(){ return this.idUtente;} /** *Method used to set review's ID * *@param id new review's ID */ public void setId(int id){ this.id = id; } /** *Method used to set review's approval * *@param approvazione new review's approval */ public void setApprovazione(int approvazione){ this.approvazione = approvazione; } /** *Method used to set review's text * *@param testo new review's text */ public void setTesto(String testo){ this.testo = testo; } /** *Method used to set review's gameID * *@param idGioco new review's gameID */ public void setIdGioco(int idGioco){ this.idGioco = idGioco; } /** *Method used to set review's userID * *@param idUtente new review's userID */ public void setIdUtente(int idUtente){ this.idUtente = idUtente; } /** *Method used to get review's information * *@return String review's ID and text */ @Override public String toString(){ return this.getId() + " - " + this.getTesto(); } }
package com.dmdirc.ui.swing.dialogs.channelsetting; import com.dmdirc.Channel; import com.dmdirc.Topic; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.ui.swing.UIUtilities; import com.dmdirc.ui.swing.actions.NoNewlinesPasteAction; import com.dmdirc.ui.swing.components.SwingInputHandler; import com.dmdirc.ui.swing.components.TextAreaInputField; import com.dmdirc.ui.swing.components.TextLabel; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import net.miginfocom.swing.MigLayout; /** Topic panel. */ public final class TopicPane extends JPanel implements DocumentListener, ActionListener { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 2; /** Parent channel. */ private final Channel channel; /** Parent dialog. */ private final ChannelSettingsDialog parent; /** the maximum length allowed for a topic. */ private int topicLengthMax; /** label showing the number of characters left in a topic.*/ private JLabel topicLengthLabel; /** Topic text entry text area. */ private TextAreaInputField topicText; /** Topic who. */ private TextLabel topicWho; /** Topic history. */ private JComboBox topicHistory; /** * Creates a new instance of TopicModesPane. * * @param channel Parent channel * @param parent Parent dialog */ public TopicPane(final Channel channel, final ChannelSettingsDialog parent) { super(); this.setOpaque(UIUtilities.getTabbedPaneOpaque()); this.channel = channel; this.parent = parent; final Map<String, String> iSupport = channel.getServer().getParser().get005(); if (iSupport.containsKey("TOPICLEN")) { try { topicLengthMax = Integer.parseInt(iSupport.get("TOPICLEN")); } catch (NumberFormatException ex) { topicLengthMax = 0; Logger.userError(ErrorLevel.LOW, "IRCD doesnt supply topic length"); } } update(); } /** Updates the panel. */ public void update() { setVisible(false); removeAll(); initTopicsPanel(); layoutComponents(); topicText.getDocument().addDocumentListener(this); topicHistory.addActionListener(this); setVisible(true); } /** Initialises the topic panel. */ private void initTopicsPanel() { final List<Topic> topics = channel.getTopics(); Collections.reverse(topics); topicLengthLabel = new JLabel(); topicText = new TextAreaInputField(100, 4); topicHistory = new JComboBox(new DefaultComboBoxModel(topics.toArray())); topicHistory.setPrototypeDisplayValue("This is a substantial prototype value"); topicWho = new TextLabel(); if (topicHistory.getModel().getSize() == 0) { topicHistory.setEnabled(false); } topicText.setText(channel.getChannelInfo().getTopic()); topicText.setLineWrap(true); topicText.setWrapStyleWord(true); topicText.setRows(5); topicText.setColumns(30); new SwingInputHandler(topicText, channel.getFrame().getCommandParser(), channel.getFrame()).setTypes(false, false, true, false); topicText.getActionMap(). put("paste-from-clipboard", new NoNewlinesPasteAction()); topicText.getInputMap(). put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), new EnterAction()); topicText.getInputMap(). put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, UIUtilities.getCtrlDownMask()), new EnterAction()); UIUtilities.addUndoManager(topicText); topicChanged(); actionPerformed(null); } /** Lays out the components. */ private void layoutComponents() { setLayout(new MigLayout("wrap 1, fill, wmax 450")); add(topicHistory, "growx"); add(new JScrollPane(topicText), "grow"); add(topicLengthLabel, "pushx, growx"); add(topicWho, "growx"); } /** Processes the topic and changes it if necessary. */ protected void setChangedTopic() { if (!channel.getChannelInfo().getTopic().equals(topicText.getText())) { channel.setTopic(topicText.getText()); } } /** Handles the topic change. */ private void topicChanged() { if (topicLengthMax == 0) { topicLengthLabel.setForeground(Color.BLACK); topicLengthLabel.setText(topicText.getText().length() + " characters"); } else { final int charsLeft = topicLengthMax - topicText.getText().length(); if (charsLeft >= 0) { topicLengthLabel.setForeground(Color.BLACK); topicLengthLabel.setText(charsLeft + " of " + topicLengthMax + " available"); } else { topicLengthLabel.setForeground(Color.RED); topicLengthLabel.setText(0 + " of " + topicLengthMax + " available " + (-1 * charsLeft) + " too many characters"); } } } /** {@inheritDoc}. */ @Override public void insertUpdate(final DocumentEvent e) { topicChanged(); } /** {@inheritDoc}. */ @Override public void removeUpdate(final DocumentEvent e) { topicChanged(); } /** {@inheritDoc}. */ @Override public void changedUpdate(final DocumentEvent e) { //Ignore } /** * {@inheritDoc}. * * @param e Action event */ @Override public void actionPerformed(final ActionEvent e) { final Topic topic = (Topic) topicHistory.getSelectedItem(); if (topic == null) { topicWho.setText("No topic set."); } else { topicWho.setText("Set by " + topic.getClient() + "\n on " + new Date(1000 * topic.getTime())); topicText.setText(topic.getTopic()); } } /** Closes and saves the topic when enter is pressed. */ private class EnterAction extends AbstractAction { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** * {@inheritDoc} * * @param e Action event */ @Override public void actionPerformed(final ActionEvent e) { parent.save(); } } }
package model; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Optional; import org.eclipse.egit.github.core.Label; public class TurboLabel implements Listable { /* * Attributes, Getters & Setters */ public static final String EXCLUSIVE_DELIM = "."; public static final String NONEXCLUSIVE_DELIM = "-"; public String getValue() {return getName();} public void setValue(String value) {setName(value);} private String name = ""; public String getName() { return name; } public void setName(String value) { assert value != ""; assert value != null; name = value; } private String colour = ""; public final String getColour() {return colour;} public final void setColour(String value) {colour = value;} private String group = ""; public final String getGroup() {return group;} public final void setGroup(String value) {group = value;} private boolean isExclusive; // exclusive: "." non-exclusive: "-" public boolean isExclusive() {return isExclusive;} public void setExclusive(boolean isExclusive) { if (getGroup() != null) this.isExclusive = isExclusive; } /* * Constructors and Public Methods */ public TurboLabel(TurboLabel other){ this(other.toGhResource()); } public TurboLabel(){ setColour("000000"); } public TurboLabel(Label label) { assert label != null; String labelName = label.getName(); Optional<String[]> tokens = TurboLabel.parseName(labelName); if(!tokens.isPresent()){ setName(labelName); }else{ setGroup(tokens.get()[0]); setName(tokens.get()[1]); setExclusive(tokens.get()[2].equals(EXCLUSIVE_DELIM)); } setColour(label.getColor()); } public void copyValues(Object other){ if(other.getClass() == TurboLabel.class){ TurboLabel obj = (TurboLabel)other; setName(obj.getName()); setColour(obj.getColour()); setGroup(obj.getGroup()); setExclusive(obj.isExclusive); } } public Label toGhResource() { Label ghLabel = new Label(); ghLabel.setName(toGhName()); ghLabel.setColor(getColour()); return ghLabel; } public String getGroupDelimiter(){ String groupDelimiter = isExclusive ? EXCLUSIVE_DELIM : NONEXCLUSIVE_DELIM; return groupDelimiter; } public String toGhName() { String groupDelimiter = isExclusive ? EXCLUSIVE_DELIM : NONEXCLUSIVE_DELIM; String groupPrefix = (getGroup() == null || getGroup().isEmpty()) ? "" : getGroup() + groupDelimiter; String groupAppended = groupPrefix + getName(); return groupAppended; } public static List<Label> toGhLabels(List<TurboLabel> turboLabels) { List<Label> ghLabels = new ArrayList<Label>(); if (turboLabels == null) return ghLabels; for (TurboLabel turboLabel : turboLabels) { Label label = new Label(); label.setName(turboLabel.toGhName()); label.setColor(turboLabel.getColour()); ghLabels.add(label); } return ghLabels; } public String getStyle() { String colour = getColour(); int R = Integer.parseInt(colour.substring(0, 2), 16); int G = Integer.parseInt(colour.substring(2, 4), 16); int B = Integer.parseInt(colour.substring(4, 6), 16); double L = 0.2126 * R + 0.7152 * G + 0.0722 * B; boolean bright = L > 128; return "-fx-background-color: #" + getColour() + "; -fx-text-fill: " + (bright ? "black" : "white"); } /** * Returns an array in the format: * * { * label group, * label name, * separator * } * * May fail if the string is not in the format group.name or group-name. */ public static Optional<String[]> parseName(String name) { String[] result = new String[3]; int dotPos = name.indexOf(EXCLUSIVE_DELIM); int dashPos = name.indexOf(NONEXCLUSIVE_DELIM); int pos = -1; if(dotPos == -1){ pos = dashPos; }else if(dashPos == -1){ pos = dotPos; }else{ pos = Math.min(dashPos, dotPos); } if (pos == -1) { return Optional.empty(); } else { result[0] = name.substring(0, pos); result[1] = name.substring(pos+1); result[2] = name.substring(pos, pos+1); return Optional.of(result); } } public static HashMap<String, ArrayList<TurboLabel>> groupLabels(Collection<TurboLabel> labels, String ungroupedName) { HashMap<String, ArrayList<TurboLabel>> groups = new HashMap<>(); for (TurboLabel l : labels) { String groupName = l.getGroup() == null ? ungroupedName : l.getGroup(); if (groups.get(groupName) == null) { groups.put(groupName, new ArrayList<TurboLabel>()); } groups.get(groupName).add(l); } return groups; } /* * Overriden Methods */ @Override public String getListName() { return getName(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : toGhName().hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TurboLabel other = (TurboLabel) obj; if (name == null) { return other.name == null; } return this.toGhName().equals(other.toGhName()); } @Override public String toString() { return "TurboLabel [name=" + name + ", group=" + group + "]"; } /** * A convenient string representation of this object, for purposes of readable logs. * @return */ public String logString() { return toGhName(); } }
package org.apollo.fs.decoder; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.function.Predicate; import org.apollo.fs.IndexedFileSystem; import org.apollo.fs.decoder.MapFileDecoder.MapDefinition; import org.apollo.game.model.Position; import org.apollo.game.model.World; import org.apollo.game.model.area.Sector; import org.apollo.game.model.area.SectorRepository; import org.apollo.game.model.area.collision.CollisionMatrix; import org.apollo.game.model.def.ObjectDefinition; import org.apollo.game.model.entity.GameObject; import org.apollo.util.BufferUtil; import org.apollo.util.CompressionUtil; import com.google.common.collect.Iterables; /** * Parses static object definitions, which include map tiles and landscapes. * * @author Ryley */ public final class GameObjectDecoder { /** * A bit flag which denotes that a specified Position is blocked. */ private static final int FLAG_BLOCKED = 1; /** * A bit flag which denotes that a specified Position is a bridge. */ private static final int FLAG_BRIDGE = 2; /** * The sector repository. */ private static final SectorRepository REPOSITORY = World.getWorld().getSectorRepository(); /** * The {@link IndexedFileSystem}. */ private final IndexedFileSystem fs; /** * A {@link List} of decoded game objects. */ private final List<GameObject> objects = new ArrayList<>(); /** * Creates the decoder. * * @param fs The indexed file system. */ public GameObjectDecoder(IndexedFileSystem fs) { this.fs = fs; } /** * Decodes all static objects and places them in the returned array. * * @return The decoded objects. * @throws IOException If an I/O error occurs. */ public GameObject[] decode() throws IOException { Map<Integer, MapDefinition> definitions = MapFileDecoder.decode(fs); for (Entry<Integer, MapDefinition> entry : definitions.entrySet()) { MapDefinition def = entry.getValue(); int packed = def.getPacketCoordinates(); int x = (packed >> 8 & 0xFF) * 64; int y = (packed & 0xFF) * 64; ByteBuffer gameObjectData = fs.getFile(4, def.getObjectFile()); ByteBuffer gameObjectBuffer = ByteBuffer.wrap(CompressionUtil.degzip(gameObjectData)); parseGameObject(gameObjectBuffer, x, y); ByteBuffer terrainData = fs.getFile(4, def.getTerrainFile()); ByteBuffer terrainBuffer = ByteBuffer.wrap(CompressionUtil.degzip(terrainData)); parseTerrain(terrainBuffer, x, y); } return Iterables.toArray(objects, GameObject.class); } private void parseGameObject(ByteBuffer buffer, int x, int y) { for (int deltaId, id = -1; (deltaId = BufferUtil.readSmart(buffer)) != 0;) { id += deltaId; for (int deltaPos, pos = 0; (deltaPos = BufferUtil.readSmart(buffer)) != 0;) { pos += deltaPos - 1; int localY = pos & 0x3F; int localX = pos >> 6 & 0x3F; int height = pos >> 12; int attributes = buffer.get() & 0xFF; int type = attributes >> 2; int orientation = attributes & 0x3; Position position = new Position(x + localX, y + localY, height); gameObjectDecoded(id, orientation, type, position); } } } private void gameObjectDecoded(int id, int orientation, int type, Position position) { ObjectDefinition definition = ObjectDefinition.lookup(id); Sector sector = REPOSITORY.fromPosition(position); int x = position.getX(), y = position.getY(), height = position.getHeight(); // FIXME: For some reason the height is negative on some occasions if (height < 0) { return; } CollisionMatrix matrix = sector.getMatrix(height); boolean block = false; // Ground decoration, signs, water fountains, etc if (type == 22 && definition.isInteractive()) { block = true; } Predicate<Integer> walls = (value) -> value >= 0 && value < 4 || value == 9; Predicate<Integer> roofs = (value) -> value >= 12 && value < 22; // Walls and roofs that intercept may intercept a mob when moving if (walls.test(type) || roofs.test(type)) { block = true; } // General objects, trees, statues, etc if (type == 10 && definition.isSolid()) { block = true; } if (block) { for (int dx = 0; dx < definition.getWidth(); dx++) { for (int dy = 0; dy < definition.getLength(); dy++) { int localX = (x % Sector.SECTOR_SIZE) + dx, localY = (y % Sector.SECTOR_SIZE) + dy; if (localX > 7 || localY > 7) { int nextLocalX = localX > 7 ? x + localX - 7 : x + localX; int nextLocalY = localY > 7 ? y + localY - 7 : y - localY; Position nextPosition = new Position(nextLocalX, nextLocalY); Sector next = REPOSITORY.fromPosition(nextPosition); int nextX = (nextPosition.getX() % Sector.SECTOR_SIZE) + dx, nextY = (nextPosition.getY() % Sector.SECTOR_SIZE) + dy; if(nextX > 7) nextX -= 7; if(nextY > 7) nextY -= 7; next.getMatrix(height).block(nextX, nextY); continue; } matrix.block(localX, localY); } } } objects.add(new GameObject(id, position, type, orientation)); } private void parseTerrain(ByteBuffer buffer, int x, int y) { for (int height = 0; height < 4; height++) { for (int localX = 0; localX < 64; localX++) { for (int localY = 0; localY < 64; localY++) { Position position = new Position(x + localX, y + localY, height); int flags = 0; while (true) { int attributeId = buffer.get() & 0xFF; if (attributeId == 0) { terrainDecoded(flags, position); break; } else if (attributeId == 1) { buffer.get(); terrainDecoded(flags, position); break; } else if (attributeId <= 49) { buffer.get(); } else if (attributeId <= 81) { flags = attributeId - 49; } } } } } } private void terrainDecoded(int flags, Position position) { Sector sector = REPOSITORY.fromPosition(position); int x = position.getX(), y = position.getY(), height = position.getHeight(); // FIXME: For some reason the height is negative on some occasions if (height < 0) { return; } CollisionMatrix current = sector.getMatrix(height); boolean block = false; if ((flags & FLAG_BLOCKED) != 0) { block = true; } if ((flags & FLAG_BRIDGE) != 0) { if (--height >= 0) { block = true; } } if (block) { int localX = (x % Sector.SECTOR_SIZE), localY = (y % Sector.SECTOR_SIZE); current.block(localX, localY); } } }
package org.appwork.utils.swing.table; import java.awt.Color; import java.awt.Component; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.EventObject; import java.util.regex.Pattern; import javax.swing.AbstractCellEditor; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JPopupMenu; import javax.swing.JTable; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.text.JTextComponent; import org.appwork.utils.logging.Log; import org.appwork.utils.swing.EDTHelper; public abstract class ExtColumn<E> extends AbstractCellEditor implements TableCellEditor, TableCellRenderer { protected static Color background = null; protected static Color backgroundselected = null; protected static Color foreground = null; protected static Color foregroundselected = null; private static final long serialVersionUID = -2662459732650363059L; /** * If this colum is editable, this parameter says how many clicks are * required to start edit mode */ private int clickcount = 2; /** * The model this column belongs to */ private ExtTableModel<E> model; /** * The columns Title. */ private final String name; /** * A toggle to select the next sortingorder. ASC or DESC */ private boolean sortOrderToggle = true; /** * Sorting algorithms run in an own thread */ private Thread sortThread = null; private ExtDefaultRowSorter<E> rowSorter; private String id; /** * Create a new ExtColum. * * @param name * @param table * @param database */ public ExtColumn(final String name, final ExtTableModel<E> table) { this.name = name; this.model = table; this.id = this.getClass().getSuperclass().getSimpleName() + "." + this.getClass().getName() + "." + (this.model.getColumnCount() + 1); // sort function this.rowSorter = new ExtDefaultRowSorter<E>(); } /** * @param value * @param isSelected * @param hasFocus * @param row */ protected void adaptRowHighlighters(final E value, final JComponent comp, final boolean isSelected, final boolean hasFocus, final int row) { comp.setOpaque(false); // important for synthetica textcomponents if (comp instanceof JTextComponent) { comp.putClientProperty("Synthetica.opaque", Boolean.TRUE); } try { for (final ExtComponentRowHighlighter<E> rh : this.getModel().getExtComponentRowHighlighters()) { if (rh.highlight(this, comp, value, isSelected, hasFocus, row)) { break; } } } catch (final Throwable e) { Log.exception(e); } } /** * @return */ public JPopupMenu createHeaderPopup() { // TODO Auto-generated method stub return null; } protected void doSort(final Object obj) { if (this.sortThread != null) { return; } this.sortThread = new Thread("TableSorter " + this.getID()) { @Override public void run() { // get selections before sorting final ArrayList<E> selections = ExtColumn.this.model.getSelectedObjects(); try { // sort data ExtColumn.this.sortOrderToggle = !ExtColumn.this.sortOrderToggle; ExtColumn.this.getModel().sort(ExtColumn.this, ExtColumn.this.sortOrderToggle); } catch (final Exception e) { } // switch toggle ExtColumn.this.sortThread = null; // Do this in EDT new EDTHelper<Object>() { @Override public Object edtRun() { // inform model about structure change ExtColumn.this.model.fireTableStructureChanged(); // restore selection ExtColumn.this.model.setSelectedObjects(selections); return null; } }.start(); } }; this.sortThread.start(); } /** * @param popup */ public void extendControlButtonMenu(final JPopupMenu popup) { // TODO Auto-generated method stub } public abstract Object getCellEditorValue(); /** * @return the {@link ExtColumn#clickcount} * @see ExtColumn#clickcount */ public int getClickcount() { return this.clickcount; } /** * @return */ public int getDefaultWidth() { return 100; } @SuppressWarnings("unchecked") public JComponent getEditorComponent(final ExtTable<E> table, final E value, final boolean isSelected, final int row, final int column) { return (JComponent) table.getLafCellEditor(row, column).getTableCellEditorComponent(table, value, isSelected, row, column); } /** * override this if you want to show a icon in the table header * * @return */ public ImageIcon getHeaderIcon() { // TODO Auto-generated method stub return null; } /** * @param jTableHeader * @return */ public ExtTableHeaderRenderer getHeaderRenderer(final JTableHeader jTableHeader) { // TODO Auto-generated method stub return null; } /** * The storageID for this column. Override this if you have a selfdefined * column class which is used by several of your columns. * * @return */ public String getID() { return this.id; } /** * Should be overwritten when there should be a maximal width for this * column (e.g. for checkboxes) */ protected int getMaxWidth() { return -1; } /** * @return */ public int getMinWidth() { return 0; } /** * @return the {@link ExtColumn#model} * @see ExtColumn#model */ public ExtTableModel<E> getModel() { return this.model; } /** * @return the {@link ExtColumn#name} * @see ExtColumn#name */ public String getName() { return this.name; } @SuppressWarnings("unchecked") public JComponent getRendererComponent(final ExtTable<E> table, final E value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { return (JComponent) table.getLafCellRenderer(row, column).getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } /** * Returns null or a sorting comperator for this column * * @param sortToggle * @return */ public ExtDefaultRowSorter<E> getRowSorter(final boolean sortOrderToggle) { this.rowSorter.setSortOrderToggle(sortOrderToggle); return this.rowSorter; } @SuppressWarnings("unchecked") @Override final public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column) { @SuppressWarnings("unchecked") final JComponent ret = this.getEditorComponent((ExtTable<E>) table, (E) value, isSelected, row, column); ret.setEnabled(this.isEnabled((E) value)); this.adaptRowHighlighters((E) value, ret, isSelected, true, row); return ret; } @SuppressWarnings("unchecked") @Override final public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { @SuppressWarnings("unchecked") final JComponent ret = this.getRendererComponent((ExtTable<E>) table, (E) value, isSelected, hasFocus, row, column); ret.setEnabled(this.isEnabled((E) value)); this.adaptRowHighlighters((E) value, ret, isSelected, hasFocus, row); return ret; } @Override public boolean isCellEditable(final EventObject evt) { if (evt instanceof MouseEvent) { return ((MouseEvent) evt).getClickCount() >= this.clickcount && this.clickcount > 0; } return true; } /** * Returns if the cell is editable. Do NOT override this. Use * {@link #isEditable(Object)} instead * * @param rowIndex * @param columnIndex * @return */ public boolean isCellEditable(final int rowIndex, final int columnIndex) { final E obj = this.model.getValueAt(rowIndex, columnIndex); if (obj == null) { return false; } return this.isEditable(obj); } public boolean isDefaultVisible() { return true; } /** * returns true if the column is editable for the object obj * * @param obj * @return */ public abstract boolean isEditable(E obj); /** * returns if the cell defined by this column and the object is enabled or * disabled * * @param obj * @return */ abstract public boolean isEnabled(E obj); /** * returns if this column is allowed to be hidden * * @return */ public boolean isHidable() { return true; } /** * If you want to use only an icon in the table header, you can override * this and let the method return false. This only works if * {@link #getHeaderIcon()} returns an icon * * @return */ public boolean isPaintHeaderText() { return true; } /** * returns true if this column is sortable. if the call origin is an object, * the object is passed in obj parameter. if the caller origin is the column * header, obj is null * * @param obj * @return */ abstract public boolean isSortable(E obj); /** * @return the {@link ExtColumn#sortOrderToggle} * @see ExtColumn#sortOrderToggle */ protected boolean isSortOrderToggle() { return this.sortOrderToggle; } public boolean matchSearch(final E object, final Pattern pattern) { return false; } /** * @param clickcount * the {@link ExtColumn#clickcount} to set * @see ExtColumn#clickcount */ public void setClickcount(final int clickcount) { this.clickcount = Math.max(0, clickcount); } /** * @param model * the {@link ExtColumn#model} to set * @see ExtColumn#model */ public void setModel(final ExtTableModel<E> model) { this.model = model; this.id = this.getClass().getSuperclass().getSimpleName() + "." + this.getClass().getName() + "." + model.getColumnCount(); } /** * @param rowSorter * the {@link ExtColumn#rowSorter} to set * @see ExtColumn#rowSorter */ public void setRowSorter(final ExtDefaultRowSorter<E> rowSorter) { this.rowSorter = rowSorter; } /** * USe this method to catch changed values. * * @param value * the new value * @param object * the concerned object */ public abstract void setValue(Object value, E object); public void setValueAt(final Object value, final int rowIndex, final int columnIndex) { final E obj = this.model.getValueAt(rowIndex, columnIndex); if (obj == null) { return; } this.setValue(value, obj); } @Override public boolean shouldSelectCell(final EventObject anEvent) { return true; } }
package com.floreysoft.jmte.template; import static org.objectweb.asm.Opcodes.AASTORE; import static org.objectweb.asm.Opcodes.ACC_PROTECTED; import static org.objectweb.asm.Opcodes.ACC_PUBLIC; import static org.objectweb.asm.Opcodes.ACC_SUPER; import static org.objectweb.asm.Opcodes.ACONST_NULL; import static org.objectweb.asm.Opcodes.ALOAD; import static org.objectweb.asm.Opcodes.ANEWARRAY; import static org.objectweb.asm.Opcodes.ARETURN; import static org.objectweb.asm.Opcodes.ASTORE; import static org.objectweb.asm.Opcodes.ATHROW; import static org.objectweb.asm.Opcodes.BIPUSH; import static org.objectweb.asm.Opcodes.CHECKCAST; import static org.objectweb.asm.Opcodes.DUP; import static org.objectweb.asm.Opcodes.GETFIELD; import static org.objectweb.asm.Opcodes.GOTO; import static org.objectweb.asm.Opcodes.ICONST_0; import static org.objectweb.asm.Opcodes.ICONST_1; import static org.objectweb.asm.Opcodes.IFEQ; import static org.objectweb.asm.Opcodes.IFNE; import static org.objectweb.asm.Opcodes.INVOKEINTERFACE; import static org.objectweb.asm.Opcodes.INVOKESPECIAL; import static org.objectweb.asm.Opcodes.INVOKESTATIC; import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; import static org.objectweb.asm.Opcodes.NEW; import static org.objectweb.asm.Opcodes.POP; import static org.objectweb.asm.Opcodes.RETURN; import static org.objectweb.asm.Opcodes.V1_6; import java.io.StringWriter; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import com.floreysoft.jmte.Engine; import com.floreysoft.jmte.token.AnnotationToken; import com.floreysoft.jmte.token.ElseToken; import com.floreysoft.jmte.token.EndToken; import com.floreysoft.jmte.token.ForEachToken; import com.floreysoft.jmte.token.IfCmpToken; import com.floreysoft.jmte.token.IfToken; import com.floreysoft.jmte.token.InvalidToken; import com.floreysoft.jmte.token.PlainTextToken; import com.floreysoft.jmte.token.StringToken; import com.floreysoft.jmte.token.Token; import com.floreysoft.jmte.token.TokenStream; import com.floreysoft.jmte.util.UniqueNameGenerator; public class DynamicBytecodeCompiler implements TemplateCompiler { protected Class<?> loadClass(byte[] b) { return cloadLoader.defineClass(null, b); } @SuppressWarnings("rawtypes") private static class DelegatingClassLoader extends ClassLoader { private final ClassLoader parentClassLoader; public DelegatingClassLoader(ClassLoader parentClassLoader) { this.parentClassLoader = parentClassLoader; } public Class defineClass(String name, byte[] b) { return defineClass(name, b, 0, b.length); } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return parentClassLoader.loadClass(name); } }; private final static String COMPILED_TEMPLATE_NAME_PREFIX = "com/floreysoft/jmte/template/CompiledTemplate"; private final static int THIS = 0; private final static int CONTEXT = 1; private final static int BUFFER = 2; private final static int EXCEPTION = 3; private final static int HIGHEST = EXCEPTION; // all the compiled classes live as long as this class loader lives // this class loader lives as long as this compiler private final DelegatingClassLoader cloadLoader = new DelegatingClassLoader( DynamicBytecodeCompiler.class.getClassLoader()); private final UniqueNameGenerator<String, String> uniqueNameGenerator = new UniqueNameGenerator<String, String>( COMPILED_TEMPLATE_NAME_PREFIX); protected transient Set<String> usedVariables; protected final List<String> localVarStack = new LinkedList<String>(); protected transient ClassVisitor classVisitor; protected transient ClassWriter classWriter; protected final String superClassName = "com/floreysoft/jmte/template/AbstractCompiledTemplate"; protected transient String className; protected transient String typeDescriptor; protected transient StringWriter writer; protected transient MethodVisitor mv; protected transient Label startLabel = new Label(); protected transient Label endLabel = new Label(); protected transient TokenStream tokenStream; protected transient int tokenLocalVarIndex = HIGHEST + 1; protected transient Engine engine; private void initCompilation() { usedVariables = new TreeSet<String>(); localVarStack.clear(); className = uniqueNameGenerator.nextUniqueName(); typeDescriptor = "L" + className + ";"; classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES); // only for debugging // writer = new StringWriter(); // TraceClassVisitor traceClassVisitor = new TraceClassVisitor( // classWriter, new PrintWriter(writer)); // classVisitor = new CheckClassAdapter(traceClassVisitor); // classVisitor = traceClassVisitor; classVisitor = classWriter; } private void addUsedVariableIfNotLocal(String variableName) { if (!localVarStack.contains(variableName)) { usedVariables.add(variableName); } } private void foreach() { ForEachToken feToken = (ForEachToken) tokenStream.currentToken(); tokenStream.consume(); localVarStack.add(0, feToken.getVarName()); Label loopStart = new Label(); Label loopEnd = new Label(); Label tryEndLabel = new Label(); codeGenerateForeachBlockStart(feToken, loopStart, loopEnd, tryEndLabel); addUsedVariableIfNotLocal(feToken.getExpression()); Token contentToken; while ((contentToken = tokenStream.currentToken()) != null && !(contentToken instanceof EndToken)) { content(); } if (contentToken == null) { engine.getErrorHandler().error("missing-end", feToken); } else { tokenStream.consume(); } codeGenerateForeachBlockEnd(loopStart, loopEnd, tryEndLabel); localVarStack.remove(0); } private void condition() { IfToken ifToken = (IfToken) tokenStream.currentToken(); tokenStream.consume(); Label tryEndLabel = new Label(); Label finalLabel = new Label(); Label elseLabel = new Label(); codeGenerateIfBlockStart(ifToken, tryEndLabel, elseLabel); String variableName = ifToken.getExpression(); addUsedVariableIfNotLocal(variableName); Token contentToken; codeGenerateIfBranchStart(); while ((contentToken = tokenStream.currentToken()) != null && !(contentToken instanceof EndToken) && !(contentToken instanceof ElseToken)) { content(); } codeGenerateIfBranchEnd(finalLabel); codeGenerateElseBranchStart(elseLabel); if (contentToken instanceof ElseToken) { tokenStream.consume(); while ((contentToken = tokenStream.currentToken()) != null && !(contentToken instanceof EndToken)) { content(); } } codeGenerateElseBranchEnd(finalLabel); if (contentToken == null) { engine.getErrorHandler().error("missing-end", ifToken); } else { tokenStream.consume(); } codeGenerateIfBlockEnd(tryEndLabel, finalLabel); } private void content() { Token token = tokenStream.currentToken(); if (token instanceof PlainTextToken) { PlainTextToken plainTextToken = (PlainTextToken) token; tokenStream.consume(); String text = plainTextToken.getText(); codeGenerateText(text); } else if (token instanceof StringToken) { StringToken stringToken = (StringToken) token; tokenStream.consume(); String variableName = stringToken.getExpression(); addUsedVariableIfNotLocal(variableName); codeGenerateStringToken(stringToken); } else if (token instanceof ForEachToken) { foreach(); } else if (token instanceof IfToken) { condition(); } else if (token instanceof ElseToken) { tokenStream.consume(); engine.getErrorHandler().error("else-out-of-scope", token); } else if (token instanceof EndToken) { tokenStream.consume(); engine.getErrorHandler().error("unmatched-end", token, null); } else if (token instanceof InvalidToken) { tokenStream.consume(); engine.getErrorHandler().error("invalid-expression", token, null); } else if (token instanceof AnnotationToken) { tokenStream.consume(); codeGenerateAnnotationToken((AnnotationToken) token); } else { // what ever else there may be, we just ignore it tokenStream.consume(); } } public Template compile(String template, String sourceName, Engine engine) { try { this.engine = engine; initCompilation(); openCompilation(); tokenStream = new TokenStream(sourceName, template, engine .getExprStartToken(), engine.getExprEndToken()); tokenStream.nextToken(); while (tokenStream.currentToken() != null) { content(); } closeCompilation(); classWriter.visitEnd(); classVisitor.visitEnd(); // FIXME: Only for debugging // System.out.println(writer.toString()); byte[] byteArray = classWriter.toByteArray(); Class<?> myClass = loadClass(byteArray); try { AbstractCompiledTemplate compiledTemplate = (AbstractCompiledTemplate) myClass .newInstance(); compiledTemplate.setEngine(engine); compiledTemplate.setTemplate(template); compiledTemplate.setSourceName(sourceName); compiledTemplate.usedVariables = this.usedVariables; return compiledTemplate; } catch (InstantiationException e) { throw new RuntimeException("Internal error " + e); } catch (IllegalAccessException e) { throw new RuntimeException("Internal error " + e); } } finally { // free resources as soon as possible this.engine = null; this.tokenStream = null; } } private void createCtor() { // ctor no args // public SampleSimpleExpressionCompiledTemplate() MethodVisitor mv = classVisitor.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, THIS); mv.visitMethodInsn(INVOKESPECIAL, superClassName, "<init>", "()V"); mv.visitInsn(RETURN); // we can pass whatever we like as we have set // ClassWriter.COMPUTE_FRAMES to ClassWriter mv.visitMaxs(1, 1); mv.visitEnd(); } private void closeCompilation() { returnStringBuilder(); mv.visitLabel(endLabel); // we can pass whatever we like as we have set // ClassWriter.COMPUTE_FRAMES to ClassWriter mv.visitMaxs(1, 1); mv.visitEnd(); } // StringBuilder buffer = new StringBuilder(); private void createStringBuilder() { mv.visitTypeInsn(NEW, "java/lang/StringBuilder"); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V"); mv.visitVarInsn(ASTORE, BUFFER); } // return buffer.toString(); private void returnStringBuilder() { mv.visitVarInsn(ALOAD, BUFFER); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;"); mv.visitInsn(ARETURN); } private void pushConstant(String parameter) { if (parameter != null) { mv.visitLdcInsn(parameter); } else { mv.visitInsn(ACONST_NULL); } } private void openCompilation() { classVisitor.visit(V1_6, ACC_PUBLIC + ACC_SUPER, className, null, superClassName, null); createCtor(); mv = classVisitor.visitMethod(ACC_PROTECTED, "transformCompiled", "(Lcom/floreysoft/jmte/TemplateContext;)Ljava/lang/String;", null, null); mv.visitCode(); mv.visitLabel(startLabel); createStringBuilder(); } private void codeGenerateAnnotationToken(AnnotationToken annotationToken) { mv.visitVarInsn(ALOAD, BUFFER); mv.visitTypeInsn(NEW, "com/floreysoft/jmte/token/AnnotationToken"); mv.visitInsn(DUP); pushConstant(annotationToken.getReceiver()); pushConstant(annotationToken.getArguments()); mv.visitMethodInsn(INVOKESPECIAL, "com/floreysoft/jmte/token/AnnotationToken", "<init>", "(Ljava/lang/String;Ljava/lang/String;)V"); mv.visitVarInsn(ALOAD, CONTEXT); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/token/AnnotationToken", "evaluate", "(Lcom/floreysoft/jmte/TemplateContext;)Ljava/lang/Object;"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;"); mv.visitInsn(POP); } private void codeGenerateStringToken(StringToken stringToken) { mv.visitVarInsn(ALOAD, BUFFER); mv.visitTypeInsn(NEW, "com/floreysoft/jmte/token/StringToken"); mv.visitInsn(DUP); pushConstant(stringToken.getExpression()); pushList(stringToken.getSegments()); pushConstant(stringToken.getExpression()); pushConstant(stringToken.getDefaultValue()); pushConstant(stringToken.getPrefix()); pushConstant(stringToken.getSuffix()); pushConstant(stringToken.getRendererName()); pushConstant(stringToken.getParameters()); mv .visitMethodInsn( INVOKESPECIAL, "com/floreysoft/jmte/token/StringToken", "<init>", "(Ljava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); mv.visitVarInsn(ALOAD, CONTEXT); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/token/StringToken", "evaluate", "(Lcom/floreysoft/jmte/TemplateContext;)Ljava/lang/Object;"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;"); mv.visitInsn(POP); } private void codeGenerateText(String text) { mv.visitVarInsn(ALOAD, BUFFER); pushConstant(text); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;"); mv.visitInsn(POP); } private void codeGenerateElseBranchStart(Label elseLabel) { // } else { mv.visitLabel(elseLabel); } private void codeGenerateElseBranchEnd(Label finalLabel) { // end of else branch mv.visitJumpInsn(GOTO, finalLabel); } private void codeGenerateIfBranchStart() { // TODO Auto-generated method stub } private void codeGenerateIfBranchEnd(Label finalLabel) { // end of if branch mv.visitJumpInsn(GOTO, finalLabel); } private void codeGenerateIfBlockEnd(Label tryEndLabel, Label finalLabel) { tokenLocalVarIndex // try end block rethrowing exception mv.visitLabel(tryEndLabel); mv.visitVarInsn(ASTORE, EXCEPTION); codeGeneratePopContext(); mv.visitVarInsn(ALOAD, EXCEPTION); mv.visitInsn(ATHROW); // } finally { mv.visitLabel(finalLabel); // context.pop(); codeGeneratePopContext(); } private void codeGenerateIfToken(IfToken ifToken) { if (ifToken instanceof IfCmpToken) { // IfCmpToken token1 = new IfCmpToken(Arrays // .asList(new String[] { "address" }), "address", "Fillbert", // false); mv.visitTypeInsn(NEW, "com/floreysoft/jmte/token/IfCmpToken"); mv.visitInsn(DUP); pushList(ifToken.getSegments()); pushConstant(ifToken.getExpression()); pushConstant(((IfCmpToken) ifToken).getOperand()); mv.visitInsn(ifToken.isNegated() ? ICONST_1 : ICONST_0); mv.visitMethodInsn(INVOKESPECIAL, "com/floreysoft/jmte/token/IfCmpToken", "<init>", "(Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Z)V"); } else { // IfToken token1 = new IfToken(Arrays.asList(new String[] { "bean", // "trueCond" }), "bean.trueCond", true); mv.visitTypeInsn(NEW, "com/floreysoft/jmte/token/IfToken"); mv.visitInsn(DUP); pushList(ifToken.getSegments()); pushConstant(ifToken.getExpression()); mv.visitInsn(ifToken.isNegated() ? ICONST_1 : ICONST_0); mv.visitMethodInsn(INVOKESPECIAL, "com/floreysoft/jmte/token/IfToken", "<init>", "(Ljava/util/List;Ljava/lang/String;Z)V"); } mv.visitVarInsn(ASTORE, tokenLocalVarIndex); } private void pushList(List<String> list) { mv.visitIntInsn(BIPUSH, list.size()); mv.visitTypeInsn(ANEWARRAY, "java/lang/String"); for (int i = 0; i < list.size(); i++) { mv.visitInsn(DUP); mv.visitIntInsn(BIPUSH, i); mv.visitLdcInsn(list.get(i)); mv.visitInsn(AASTORE); } mv.visitMethodInsn(INVOKESTATIC, "java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;"); } private void codeGenerateIfBlockStart(IfToken ifToken, Label tryEndLabel, Label elseLabel) { Label tryStartLabel = new Label(); mv.visitTryCatchBlock(tryStartLabel, tryEndLabel, tryEndLabel, null); codeGenerateIfToken(ifToken); // context.push(token1); mv.visitVarInsn(ALOAD, CONTEXT); mv.visitVarInsn(ALOAD, tokenLocalVarIndex); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/TemplateContext", "push", "(Lcom/floreysoft/jmte/token/Token;)V"); // try { mv.visitLabel(tryStartLabel); // token1.evaluate(context) mv.visitVarInsn(ALOAD, tokenLocalVarIndex); mv.visitVarInsn(ALOAD, CONTEXT); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/token/IfToken", "evaluate", "(Lcom/floreysoft/jmte/TemplateContext;)Ljava/lang/Object;"); // (Boolean) mv.visitTypeInsn(CHECKCAST, "java/lang/Boolean"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z"); // if ((Boolean) token1.evaluate(context)) { // if the condition is 0 meaning false mv.visitJumpInsn(IFEQ, elseLabel); tokenLocalVarIndex++; } private void codeGeneratePopContext() { // context.pop(); mv.visitVarInsn(ALOAD, CONTEXT); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/TemplateContext", "pop", "()Lcom/floreysoft/jmte/token/Token;"); mv.visitInsn(POP); } private void codeGenerateForeachBlockEnd(Label loopStart, Label loopEnd, Label tryEndLabel) { this.tokenLocalVarIndex // if (!token1.isLast()) { // buffer.append(token1.getSeparator()); mv.visitVarInsn(ALOAD, this.tokenLocalVarIndex); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/token/ForEachToken", "isLast", "()Z"); mv.visitJumpInsn(IFNE, loopEnd); mv.visitVarInsn(ALOAD, BUFFER); mv.visitVarInsn(ALOAD, this.tokenLocalVarIndex); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/token/ForEachToken", "getSeparator", "()Ljava/lang/String;"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;"); mv.visitInsn(POP); // while (token1.iterator().hasNext()) { mv.visitLabel(loopEnd); mv.visitVarInsn(ALOAD, this.tokenLocalVarIndex); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/token/ForEachToken", "iterator", "()Ljava/util/Iterator;"); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Iterator", "hasNext", "()Z"); mv.visitJumpInsn(IFNE, loopStart); Label noExceptionFinallyLabel = new Label(); mv.visitJumpInsn(GOTO, noExceptionFinallyLabel); // exception occurred => first finally block, then throw exception mv.visitLabel(tryEndLabel); mv.visitVarInsn(ASTORE, EXCEPTION); codeGenerateExitScope(); codeGeneratePopContext(); mv.visitVarInsn(ALOAD, EXCEPTION); mv.visitInsn(ATHROW); // no exception occurred => execute finally block only mv.visitLabel(noExceptionFinallyLabel); codeGenerateExitScope(); codeGeneratePopContext(); } private void codeGenerateForeachToken(ForEachToken feToken) { // ForEachToken token1 = new ForEachToken(Arrays // .asList(new String[] { "list" }),"list", "item", "\n"); mv.visitTypeInsn(NEW, "com/floreysoft/jmte/token/ForEachToken"); mv.visitInsn(DUP); pushList(feToken.getSegments()); pushConstant(feToken.getExpression()); pushConstant(feToken.getVarName()); pushConstant(feToken.getSeparator()); mv .visitMethodInsn(INVOKESPECIAL, "com/floreysoft/jmte/token/ForEachToken", "<init>", "(Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); mv.visitVarInsn(ASTORE, this.tokenLocalVarIndex); // token1.setIterable((Iterable) token1.evaluate(context)); mv.visitVarInsn(ALOAD, this.tokenLocalVarIndex); mv.visitVarInsn(ALOAD, this.tokenLocalVarIndex); mv.visitVarInsn(ALOAD, CONTEXT); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/token/ForEachToken", "evaluate", "(Lcom/floreysoft/jmte/TemplateContext;)Ljava/lang/Object;"); mv.visitTypeInsn(CHECKCAST, "java/lang/Iterable"); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/token/ForEachToken", "setIterable", "(Ljava/lang/Iterable;)V"); } private void codeGenerateForeachBlockStart(ForEachToken feToken, Label loopStart, Label loopEnd, Label tryEndLabel) { Label tryStartLabel = new Label(); mv.visitTryCatchBlock(tryStartLabel, tryEndLabel, tryEndLabel, null); codeGenerateForeachToken(feToken); // context.model.enterScope(); mv.visitVarInsn(ALOAD, CONTEXT); mv.visitFieldInsn(GETFIELD, "com/floreysoft/jmte/TemplateContext", "model", "Lcom/floreysoft/jmte/ScopedMap;"); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/ScopedMap", "enterScope", "()V"); // context.push(token1); mv.visitVarInsn(ALOAD, CONTEXT); mv.visitVarInsn(ALOAD, this.tokenLocalVarIndex); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/TemplateContext", "push", "(Lcom/floreysoft/jmte/token/Token;)V"); // try { mv.visitLabel(tryStartLabel); // while (token1.iterator().hasNext()) { mv.visitJumpInsn(GOTO, loopEnd); mv.visitLabel(loopStart); // context.model.put(token1.getVarName(), token1.advance()); mv.visitVarInsn(ALOAD, CONTEXT); mv.visitFieldInsn(GETFIELD, "com/floreysoft/jmte/TemplateContext", "model", "Lcom/floreysoft/jmte/ScopedMap;"); mv.visitVarInsn(ALOAD, this.tokenLocalVarIndex); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/token/ForEachToken", "getVarName", "()Ljava/lang/String;"); mv.visitVarInsn(ALOAD, this.tokenLocalVarIndex); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/token/ForEachToken", "advance", "()Ljava/lang/Object;"); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/ScopedMap", "put", "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;"); mv.visitInsn(POP); // addSpecialVariables(token1, context.model); mv.visitVarInsn(ALOAD, THIS); mv.visitVarInsn(ALOAD, this.tokenLocalVarIndex); mv.visitVarInsn(ALOAD, CONTEXT); mv.visitFieldInsn(GETFIELD, "com/floreysoft/jmte/TemplateContext", "model", "Lcom/floreysoft/jmte/ScopedMap;"); mv.visitMethodInsn(INVOKEVIRTUAL, className, "addSpecialVariables", "(Lcom/floreysoft/jmte/token/ForEachToken;Ljava/util/Map;)V"); this.tokenLocalVarIndex++; } private void codeGenerateExitScope() { // context.model.exitScope(); mv.visitVarInsn(ALOAD, CONTEXT); mv.visitFieldInsn(GETFIELD, "com/floreysoft/jmte/TemplateContext", "model", "Lcom/floreysoft/jmte/ScopedMap;"); mv.visitMethodInsn(INVOKEVIRTUAL, "com/floreysoft/jmte/ScopedMap", "exitScope", "()V"); } }
package org.bdgp.OpenHiCAMM.Modules; import java.awt.Component; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.prefs.Preferences; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import mmcorej.CMMCore; import mmcorej.TaggedImage; import org.bdgp.OpenHiCAMM.Dao; import org.bdgp.OpenHiCAMM.ImageLog.ImageLogRecord; import org.bdgp.OpenHiCAMM.ImageLog.ImageLogRunner; import org.bdgp.OpenHiCAMM.Logger; import org.bdgp.OpenHiCAMM.OpenHiCAMM; import org.bdgp.OpenHiCAMM.Util; import org.bdgp.OpenHiCAMM.ValidationError; import org.bdgp.OpenHiCAMM.WorkflowRunner; import org.bdgp.OpenHiCAMM.DB.Acquisition; import org.bdgp.OpenHiCAMM.DB.Config; import org.bdgp.OpenHiCAMM.DB.Image; import org.bdgp.OpenHiCAMM.DB.ModuleConfig; import org.bdgp.OpenHiCAMM.DB.PoolSlide; import org.bdgp.OpenHiCAMM.DB.Slide; import org.bdgp.OpenHiCAMM.DB.SlidePosList; import org.bdgp.OpenHiCAMM.DB.Task; import org.bdgp.OpenHiCAMM.DB.Task.Status; import org.bdgp.OpenHiCAMM.DB.TaskConfig; import org.bdgp.OpenHiCAMM.DB.TaskDispatch; import org.bdgp.OpenHiCAMM.DB.WorkflowModule; import org.bdgp.OpenHiCAMM.Modules.Interfaces.Configuration; import org.bdgp.OpenHiCAMM.Modules.Interfaces.ImageLogger; import org.bdgp.OpenHiCAMM.Modules.Interfaces.Module; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.dialogs.AcqControlDlg; import org.micromanager.events.DisplayCreatedEvent; import org.micromanager.events.EventManager; import org.micromanager.MMOptions; import org.micromanager.MMStudio; import org.micromanager.acquisition.AcquisitionWrapperEngine; import org.micromanager.acquisition.MMAcquisition; import org.micromanager.api.Autofocus; import org.micromanager.api.ImageCache; import org.micromanager.api.ImageCacheListener; import org.micromanager.api.MultiStagePosition; import org.micromanager.api.PositionList; import org.micromanager.api.ScriptInterface; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMException; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.MMSerializationException; import com.google.common.eventbus.Subscribe; import static org.bdgp.OpenHiCAMM.Util.set; import static org.bdgp.OpenHiCAMM.Util.where; public class SlideImager implements Module, ImageLogger { private static final long DUMMY_SLEEP = 500; private static final boolean SANITY_CHECK = false; WorkflowRunner workflowRunner; WorkflowModule workflowModule; AcqControlDlg acqControlDlg; ScriptInterface script; AcquisitionWrapperEngine engine; @Override public void initialize(WorkflowRunner workflowRunner, WorkflowModule workflowModule) { this.workflowRunner = workflowRunner; this.workflowModule = workflowModule; OpenHiCAMM openhicamm = workflowRunner.getOpenHiCAMM(); this.script = openhicamm.getApp(); Preferences prefs = Preferences.userNodeForPackage(this.script.getClass()); MMOptions options = new MMOptions(); options.loadSettings(); if (this.script != null) { this.engine = MMStudio.getInstance().getAcquisitionEngine(); this.acqControlDlg = new AcqControlDlg(this.engine, prefs, this.script, options); } // set initial configs workflowRunner.getModuleConfig().insertOrUpdate( new ModuleConfig(this.workflowModule.getId(), "canImageSlides", "yes"), "id", "key"); } /** * Load the acquisition settings and get the position list from the DB * @param conf The module configuration * @param logger The logging module * @return the position list, or null if no position list was found */ public PositionList loadPositionList(Map<String,Config> conf, Logger logger) { Dao<Task> taskDao = this.workflowRunner.getTaskStatus(); // first try to load a position list from the posListId conf // otherwise, try loading from the posListModuleId conf PositionList positionList; if (conf.containsKey("posListModule")) { // get a sorted list of all the SlidePosList records for the posListModuleId module Config posListModuleConf = conf.get("posListModule"); Dao<SlidePosList> posListDao = workflowRunner.getWorkflowDb().table(SlidePosList.class); Integer slideId = new Integer(conf.get("slideId").getValue()); WorkflowModule posListModule = this.workflowRunner.getWorkflow().selectOneOrDie( where("name",posListModuleConf.getValue())); // get the list of slide position lists with valid task IDs or where task ID is null List<SlidePosList> posLists = new ArrayList<>(); for (SlidePosList posList : posListDao.select( where("slideId", slideId). and("moduleId", posListModule.getId()))) { if (posList.getTaskId() != null) { Task checkTask = taskDao.selectOne(where("id",posList.getTaskId())); if (checkTask == null) continue; } posLists.add(posList); } if (posLists.isEmpty()) { return null; } // Merge the list of PositionLists into a single positionList Collections.sort(posLists, (a,b)->a.getId()-b.getId()); positionList = posLists.get(0).getPositionList(); for (int i=1; i<posLists.size(); ++i) { SlidePosList spl = posLists.get(i); PositionList pl = spl.getPositionList(); for (int j=0; j<pl.getNumberOfPositions(); ++j) { MultiStagePosition msp = pl.getPosition(j); // sanitize the MSP label. This will be used as the directory name for each image String label = msp.getLabel().replaceAll("[ ():,]+", ".").replaceAll("[=]+", ""); msp.setLabel(label); positionList.addPosition(msp); } } // log the position list to the console try { logger.fine(String.format("%s: Read position list from module %s:%n%s", this.workflowModule.getName(), conf.get("posListModule"), positionList.serialize())); } catch (MMSerializationException e) {throw new RuntimeException(e);} // load the position list into the acquisition engine try { this.script.setPositionList(positionList); } catch (MMScriptException e) {throw new RuntimeException(e);} this.engine.setPositionList(positionList); } // otherwise, load a position list from a file else if (conf.containsKey("posListFile")) { Config posList = conf.get("posListFile"); logger.fine(String.format("%s: Loading position list from file: %s", this.workflowModule.getName(), Util.escape(posList.getValue()))); File posListFile = new File(posList.getValue()); if (!posListFile.exists()) { throw new RuntimeException("Cannot find position list file "+posListFile.getPath()); } try { positionList = new PositionList(); positionList.load(posListFile.getPath()); try { this.script.setPositionList(positionList); } catch (MMScriptException e) {throw new RuntimeException(e);} this.engine.setPositionList(positionList); } catch (MMException e) {throw new RuntimeException(e);} } else { throw new RuntimeException("No position list was given!"); } // Load the settings and position list from the settings files if (conf.containsKey("acqSettingsFile")) { Config acqSettings = conf.get("acqSettingsFile"); logger.fine(String.format("%s: Loading acquisition settings from file: %s", this.workflowModule.getName(), Util.escape(acqSettings.getValue()))); File acqSettingsFile = new File(acqSettings.getValue()); if (!acqSettingsFile.exists()) { throw new RuntimeException("Cannot find acquisition settings file "+acqSettingsFile.getPath()); } try { acqControlDlg.loadAcqSettingsFromFile(acqSettingsFile.getPath()); } catch (MMScriptException e) {throw new RuntimeException(e);} } return positionList; } @Subscribe public void showDisplay(DisplayCreatedEvent e) { e.getDisplayWindow().setVisible(true); } @Override public Status run(Task task, Map<String,Config> conf, Logger logger) { logger.fine(String.format("Running task: %s", task)); for (Config c : conf.values()) { logger.fine(String.format("Using configuration: %s", c)); } // get the list of parent tasks for this task List<Task> siblingTasks = this.workflowRunner.getTaskStatus().select(where("dispatchUUID",task.getDispatchUUID())); Set<Task> parentTaskSet = new HashSet<>(); for (Task siblingTask : siblingTasks) { for (TaskDispatch td : this.workflowRunner.getTaskDispatch().select(where("taskId",siblingTask.getId()))) { parentTaskSet.addAll(this.workflowRunner.getTaskStatus().select(where("id",td.getParentTaskId()))); } } List<Task> parentTasks = parentTaskSet.stream().collect(Collectors.toList()); // if this is the loadDynamicTaskRecords task, then we need to dynamically create the task records now Config loadDynamicTaskRecordsConf = conf.get("loadDynamicTaskRecords"); if (loadDynamicTaskRecordsConf != null && loadDynamicTaskRecordsConf.getValue().equals("yes")) { conf.put("dispatchUUID", new Config(task.getId(), "dispatchUUID", task.getDispatchUUID())); workflowRunner.createTaskRecords(this.workflowModule, parentTasks, conf, logger); return Status.SUCCESS; } Config imageLabelConf = conf.get("imageLabel"); if (imageLabelConf == null) throw new RuntimeException(String.format( "Could not find imageLabel conf for task %s!", task)); String imageLabel = imageLabelConf.getValue(); logger.fine(String.format("Using imageLabel: %s", imageLabel)); int[] indices = MDUtils.getIndices(imageLabel); if (indices == null || indices.length < 4) throw new RuntimeException(String.format( "Invalid indices parsed from imageLabel %s", imageLabel)); // If this is the acqusition task 0_0_0_0, start the acquisition engine if (indices[0] == 0 && indices[1] == 0 && indices[2] == 0 && indices[3] == 0) { // Make sure the acquisition control dialog was initialized if (this.acqControlDlg == null) { throw new RuntimeException("acqControlDlg is not initialized!"); } // load the position list and acquistion settings PositionList posList = this.loadPositionList(conf, logger); if (posList == null) { throw new RuntimeException("Could not load position list!"); } VerboseSummary verboseSummary = getVerboseSummary(); logger.info(String.format("Verbose summary:")); for (String line : verboseSummary.summary.split("\n")) workflowRunner.getLogger().info(String.format(" %s", line)); int totalImages = verboseSummary.channels * verboseSummary.slices * verboseSummary.frames * verboseSummary.positions; // Get Dao objects ready for use Dao<TaskConfig> taskConfigDao = workflowRunner.getWorkflowDb().table(TaskConfig.class); Dao<Acquisition> acqDao = workflowRunner.getWorkflowDb().table(Acquisition.class); Dao<Image> imageDao = workflowRunner.getWorkflowDb().table(Image.class); Dao<Slide> slideDao = workflowRunner.getWorkflowDb().table(Slide.class); Date startAcquisition = new Date(); // get the slide ID from the config if (!conf.containsKey("slideId")) throw new RuntimeException("No slideId found for image!"); Integer slideId = new Integer(conf.get("slideId").getValue()); logger.info(String.format("Using slideId: %d", slideId)); // get the slide's experiment ID Slide slide = slideId != null? slideDao.selectOne(where("id", slideId)) : null; String experimentId = slide != null? slide.getExperimentId() : null; // get the poolSlide record if it exists Dao<PoolSlide> poolSlideDao = this.workflowRunner.getWorkflowDb().table(PoolSlide.class); PoolSlide poolSlide = null; if (conf.containsKey("loadPoolSlideId")) { poolSlide = poolSlideDao.selectOneOrDie(where("id", new Integer(conf.get("loadPoolSlideId").getValue()))); } // set the acquisition name // Set rootDir and acqName String rootDir = workflowRunner.getWorkflowDir().getPath(); String acqName = String.format("acquisition_%s_%s%s%s", new SimpleDateFormat("yyyyMMddHHmmss").format(startAcquisition), this.workflowModule.getName(), poolSlide != null? String.format("_C%dS%02d", poolSlide.getCartridgePosition(), poolSlide.getSlidePosition()) : "", slide != null? String.format("_%s", slide.getName()) : "", experimentId != null? String.format("_%s", experimentId.replaceAll("[\\/ :]+","_")) : ""); CMMCore core = this.script.getMMCore(); logger.fine(String.format("This task is the acquisition task")); logger.info(String.format("Using rootDir: %s", rootDir)); logger.info(String.format("Requesting to use acqName: %s", acqName)); // Move stage to starting position and take some dummy pictures to adjust the camera if (conf.containsKey("dummyImageCount") && posList.getNumberOfPositions() > 0) { Integer dummyImageCount = new Integer(conf.get("dummyImageCount").getValue()); logger.info("Moving stage to starting position"); MultiStagePosition pos = posList.getPosition(0); SlideImager.moveStage(workflowModule.getName(), core, pos.getX(), pos.getY(), logger); // Acquire N dummy images to calibrate the camera for (int i=0; i<dummyImageCount; ++i) { // Take a picture but don't save it try { core.snapImage(); } catch (Exception e) {throw new RuntimeException(e);} logger.info(String.format("Acquired %d dummy images to calibrate the camera...", i+1)); // wait a second before taking the next one. try { Thread.sleep(DUMMY_SLEEP); } catch (InterruptedException e) {logger.info("Sleep thread was interrupted");} } } // build a map of imageLabel -> sibling task record Dao<Task> taskDao = this.workflowRunner.getTaskStatus(); Dao<TaskDispatch> taskDispatchDao = this.workflowRunner.getTaskDispatch(); List<TaskDispatch> tds = new ArrayList<>(); for (Task t : taskDao.select(where("moduleId", this.workflowModule.getId()))) { TaskConfig slideIdConf = this.workflowRunner.getTaskConfig().selectOne( where("id", t.getId()). and("key", "slideId"). and("value", slideId)); if (slideIdConf != null) { tds.addAll(taskDispatchDao.select(where("taskId", t.getId()))); } } Map<String,Task> tasks = new LinkedHashMap<String,Task>(); if (!tds.isEmpty()) { Collections.sort(tds, new Comparator<TaskDispatch>() { @Override public int compare(TaskDispatch a, TaskDispatch b) { return a.getTaskId() - b.getTaskId(); }}); for (TaskDispatch t : tds) { Task tt = taskDao.selectOneOrDie(where("id", t.getTaskId())); TaskConfig imageLabelConf2 = taskConfigDao.selectOneOrDie( where("id", tt.getId()). and("key", "imageLabel")); tasks.put(imageLabelConf2.getValue(), tt); } } else { List<Task> tts = taskDao.select(where("moduleId", this.workflowModule.getId())); Collections.sort(tts, new Comparator<Task>() { @Override public int compare(Task a, Task b) { return a.getId() - b.getId(); }}); for (Task tt : tts) { TaskConfig imageLabelConf2 = taskConfigDao.selectOneOrDie( where("id", tt.getId()). and("key", "imageLabel")); tasks.put(imageLabelConf2.getValue(), tt); } } // close all open acquisition windows for (String name : MMStudio.getInstance().getAcquisitionNames()) { try { MMStudio.getInstance().closeAcquisitionWindow(name); } catch (MMScriptException e) { /* do nothing */ } } // set the initial Z Position if (conf.containsKey("initialZPos")) { Double initialZPos = new Double(conf.get("initialZPos").getValue()); logger.info(String.format("Setting initial Z Position to: %.02f", initialZPos)); String focusDevice = core.getFocusDevice(); final double EPSILON = 1.0; try { Double currentPos = core.getPosition(focusDevice); while (Math.abs(currentPos-initialZPos) > EPSILON) { core.setPosition(focusDevice, initialZPos); core.waitForDevice(focusDevice); Thread.sleep(500); currentPos = core.getPosition(focusDevice); } } catch (Exception e1) {throw new RuntimeException(e1);} } // Start the acquisition engine. This runs asynchronously. try { EventManager.register(this); this.workflowRunner.getTaskConfig().insertOrUpdate( new TaskConfig(task.getId(), "startAcquisition", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(startAcquisition)), "id", "key"); logger.info(String.format("Now running the image acquisition sequence, please wait...")); String returnAcqName = acqControlDlg.runAcquisition(acqName, rootDir); if (returnAcqName == null) { throw new RuntimeException("acqControlDlg.runAcquisition returned null acquisition name"); } // get the prefix name and log it JSONObject summaryMetadata = this.engine.getSummaryMetadata(); String prefix; try { prefix = summaryMetadata.getString("Prefix"); } catch (JSONException e) { throw new RuntimeException(e); } logger.info(String.format("Acquisition was saved to root directory %s, prefix %s", Util.escape(rootDir), Util.escape(prefix))); // Write the acquisition record Acquisition acquisition = new Acquisition(returnAcqName, prefix, rootDir); acqDao.insertOrUpdate(acquisition,"prefix","directory"); acqDao.reload(acquisition); logger.info(String.format("Using acquisition record: %s", acquisition)); // add an image cache listener to eagerly kick off downstream processing after each image // is received. ImageCache acqImageCache = this.engine.getImageCache(); acqImageCache.addImageCacheListener(new ImageCacheListener() { @Override public void imageReceived(TaggedImage taggedImage) { // Log how many images have been acquired so far Set<String> taggedImages = new HashSet<String>(acqImageCache.imageKeys()); String label = MDUtils.getLabel(taggedImage.tags); // Get the task record that should be eagerly dispatched. Task dispatchTask = tasks.get(label); if (dispatchTask == null) throw new RuntimeException(String.format( "No SlideImager task was created for image with label %s!", label)); try { if (taggedImage.pix == null) throw new RuntimeException(String.format( "%s: taggedImage.pix is null!", label)); String positionName = null; try { positionName = MDUtils.getPositionName(taggedImage.tags); } catch (JSONException e) {} taggedImages.add(label); logger.info(String.format("Acquired image: %s [%d/%d images]", positionName != null? String.format("%s (%s)", positionName, label) : label, taggedImages.size(), totalImages)); int[] indices = MDUtils.getIndices(label); if (indices == null || indices.length < 4) throw new RuntimeException(String.format( "Bad image label from MDUtils.getIndices(): %s", label)); // Don't eagerly dispatch the acquisition thread. This thread must not be set to success // until the acquisition has finished, so the downstream processing for this task // must wait until the acquisition has finished. if (!(indices[0] == 0 && indices[1] == 0 && indices[2] == 0 && indices[3] == 0)) { // Make sure the position name of this image's metadata matches what we expected // from the Task configuration. TaskConfig positionNameConf = taskConfigDao.selectOneOrDie( where("id", dispatchTask.getId()).and("key", "positionName")); if (!positionName.equals(positionNameConf.getValue())) { throw new RuntimeException(String.format( "Position name mismatch! TaskConfig=%s, MDUtils.getPositionName=%s", positionNameConf, positionName)); } // Write the image record and kick off downstream processing. // create the image record Image image = new Image(slideId, acquisition, indices[0], indices[1], indices[2], indices[3]); imageDao.insertOrUpdate(image,"acquisitionId","channel","slice","frame","position"); logger.fine(String.format("Inserted/Updated image: %s", image)); imageDao.reload(image, "acquisitionId","channel","slice","frame","position"); // Store the Image ID as a Task Config variable TaskConfig imageId = new TaskConfig( dispatchTask.getId(), "imageId", new Integer(image.getId()).toString()); taskConfigDao.insertOrUpdate(imageId,"id","key"); conf.put("imageId", imageId); logger.fine(String.format("Inserted/Updated imageId config: %s", imageId)); // eagerly run the Slide Imager task in order to dispatch downstream processing logger.fine(String.format("Eagerly dispatching sibling task: %s", dispatchTask)); new Thread(new Runnable() { @Override public void run() { SlideImager.this.workflowRunner.run(dispatchTask, conf); }}).start(); } } catch (Throwable e) { dispatchTask.setStatus(Status.ERROR); taskDao.update(dispatchTask, "id"); throw new RuntimeException(e); } } @Override public void imagingFinished(String path) { } }); // wait until the current acquisition finishes while (acqControlDlg.isAcquisitionRunning()) { try { Thread.sleep(1000); } catch (InterruptedException e) { // if the thread is interrupted, abort the acquisition. if (this.engine != null && this.engine.isAcquisitionRunning()) { logger.warning("Aborting the acquisition..."); //this.engine.abortRequest(); this.engine.stop(true); return Status.ERROR; } } } // Get the ImageCache object for this acquisition MMAcquisition mmacquisition = acquisition.getAcquisition(acqDao); ImageCache imageCache = mmacquisition.getImageCache(); if (imageCache == null) throw new RuntimeException("MMAcquisition object was not initialized; imageCache is null!"); // Wait for the image cache to finish... while (!imageCache.isFinished()) { try { logger.info("Waiting for the ImageCache to finish..."); Thread.sleep(1000); } catch (InterruptedException e) { logger.warning("Thread was interrupted while waiting for the Image Cache to finish"); return Status.ERROR; } } if (!imageCache.isFinished()) throw new RuntimeException("ImageCache is not finished!"); Date endAcquisition = new Date(); this.workflowRunner.getTaskConfig().insertOrUpdate( new TaskConfig(task.getId(), "endAcquisition", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(endAcquisition)), "id", "key"); this.workflowRunner.getTaskConfig().insertOrUpdate( new TaskConfig(task.getId(), "acquisitionDuration", new Long(endAcquisition.getTime() - startAcquisition.getTime()).toString()), "id", "key"); // get the autofocus duration from the autofocus object Autofocus autofocus = this.script.getAutofocus(); if (new HashSet<String>(Arrays.asList(autofocus.getPropertyNames())).contains("autofocusDuration")) { try { this.workflowRunner.getTaskConfig().insertOrUpdate( new TaskConfig(task.getId(), "autofocusDuration", autofocus.getPropertyValue("autofocusDuration")), "id", "key"); } catch (MMException e) { throw new RuntimeException(e); } } // reset the autofocus settings back to defaults autofocus.applySettings(); // Get the set of taggedImage labels from the acquisition Set<String> taggedImages = imageCache.imageKeys(); logger.info(String.format("Found %d taggedImages: %s", taggedImages.size(), taggedImages.toString())); // Make sure the set of acquisition image labels matches what we expected. if (!taggedImages.equals(tasks.keySet())) { throw new RuntimeException(String.format( "Error: Unexpected image set from acquisition! acquisition image count is %d, expected %d!%n"+ "Verbose summary: %s%nFrom acquisition: %s%nFrom task config: %s", taggedImages.size(), tasks.size(), totalImages, taggedImages, tasks.keySet())); } // Add any missing Image record for e.g. the acquisition task. This is also important because // the ImageListener above is added *after* the acquisition is started, so there's a chance // we may have missed the first few imageReceived events. This race condition is currently // unavoidable due to the way that MMAcquisition is implemented. Any remaining SlideImager tasks // that weren't eagerly dispatched will be dispatched normally by the workflowRunner after this // task completes. for (String label : taggedImages) { // make sure none of the taggedImage.pix values are null int[] idx = MDUtils.getIndices(label); if (idx == null || idx.length < 4) throw new RuntimeException(String.format( "Bad image label from MDUtils.getIndices(): %s", label)); Task t = tasks.get(label); if (t == null) throw new RuntimeException(String.format( "Could not get task record for image with label %s!", label)); // The following sanity checks are very time-consuming and don't seem // to be necessary, so I've disabled them by default using the SANITY_CHECK flag. if (SANITY_CHECK) { TaggedImage taggedImage = imageCache.getImage(idx[0], idx[1], idx[2], idx[3]); if (taggedImage.pix == null) throw new RuntimeException(String.format( "%s: taggedImage.pix is null!", label)); // get the positionName String positionName; try { positionName = MDUtils.getPositionName(taggedImage.tags); } catch (JSONException e) {throw new RuntimeException(e);} // Make sure the position name of this image's metadata matches what we expected // from the Task configuration. TaskConfig positionNameConf = taskConfigDao.selectOneOrDie( where("id", t.getId()).and("key", "positionName")); if (!positionName.equals(positionNameConf.getValue())) { throw new RuntimeException(String.format( "Position name mismatch! TaskConfig=%s, MDUtils.getPositionName=%s", positionNameConf, positionName)); } } // Insert/Update image DB record Image image = new Image(slideId, acquisition, idx[0], idx[1], idx[2], idx[3]); imageDao.insertOrUpdate(image,"acquisitionId","channel","slice","frame","position"); logger.fine(String.format("Inserted image: %s", image)); imageDao.reload(image, "acquisitionId","channel","slice","frame","position"); // Store the Image ID as a Task Config variable TaskConfig imageId = new TaskConfig( t.getId(), "imageId", new Integer(image.getId()).toString()); taskConfigDao.insertOrUpdate(imageId,"id","key"); conf.put(imageId.getKey(), imageId); logger.fine(String.format("Inserted/Updated imageId config: %s", imageId)); } } finally { EventManager.unregister(this); } } return Status.SUCCESS; } @Override public String getTitle() { return this.getClass().getName(); } @Override public String getDescription() { return this.getClass().getName(); } @Override public Configuration configure() { return new Configuration() { SlideImagerDialog slideImagerDialog = new SlideImagerDialog(acqControlDlg, SlideImager.this.workflowRunner); @Override public Config[] retrieve() { List<Config> configs = new ArrayList<Config>(); if (slideImagerDialog.acqSettingsText.getText().length()>0) { configs.add(new Config(workflowModule.getId(), "acqSettingsFile", slideImagerDialog.acqSettingsText.getText())); } if (slideImagerDialog.posListText.getText().length()>0) { configs.add(new Config(workflowModule.getId(), "posListFile", slideImagerDialog.posListText.getText())); } if (slideImagerDialog.moduleName.getSelectedIndex()>0) { configs.add(new Config(workflowModule.getId(), "posListModule", slideImagerDialog.moduleName.getSelectedItem().toString())); } if (slideImagerDialog.dummyImageCount.getValue() != null) { configs.add(new Config(workflowModule.getId(), "dummyImageCount", slideImagerDialog.dummyImageCount.getValue().toString())); } if (((Double)slideImagerDialog.pixelSize.getValue()).doubleValue() != 0.0) { configs.add(new Config(workflowModule.getId(), "pixelSize", slideImagerDialog.pixelSize.getValue().toString())); } if (slideImagerDialog.invertXAxisYes.isSelected()) { configs.add(new Config(workflowModule.getId(), "invertXAxis", "yes")); } else if (slideImagerDialog.invertXAxisNo.isSelected()) { configs.add(new Config(workflowModule.getId(), "invertXAxis", "no")); } if (slideImagerDialog.invertYAxisYes.isSelected()) { configs.add(new Config(workflowModule.getId(), "invertYAxis", "yes")); } else if (slideImagerDialog.invertYAxisNo.isSelected()) { configs.add(new Config(workflowModule.getId(), "invertYAxis", "no")); } if (slideImagerDialog.setInitZPosYes.isSelected()) { configs.add(new Config(workflowModule.getId(), "initialZPos", slideImagerDialog.initialZPos.getValue().toString())); } return configs.toArray(new Config[0]); } @Override public Component display(Config[] configs) { Map<String,Config> conf = new HashMap<String,Config>(); for (Config config : configs) { conf.put(config.getKey(), config); } if (conf.containsKey("acqSettingsFile")) { Config acqDlgSettings = conf.get("acqSettingsFile"); slideImagerDialog.acqSettingsText.setText(acqDlgSettings.getValue()); } if (conf.containsKey("posListFile")) { Config posList = conf.get("posListFile"); slideImagerDialog.posListText.setText(posList.getValue()); } if (conf.containsKey("posListModule")) { Config posListModuleConf = conf.get("posListModule"); slideImagerDialog.moduleName.setSelectedItem(posListModuleConf.getValue()); } if (conf.containsKey("dummyImageCount")) { Config dummyImageCount = conf.get("dummyImageCount"); slideImagerDialog.dummyImageCount.setValue(new Integer(dummyImageCount.getValue())); } if (conf.containsKey("pixelSize")) { slideImagerDialog.pixelSize.setValue(new Double(conf.get("pixelSize").getValue())); } if (conf.containsKey("invertXAxis")) { if (conf.get("invertXAxis").getValue().equals("yes")) { slideImagerDialog.invertXAxisYes.setSelected(true); slideImagerDialog.invertXAxisNo.setSelected(false); } else if (conf.get("invertXAxis").getValue().equals("no")) { slideImagerDialog.invertXAxisYes.setSelected(false); slideImagerDialog.invertXAxisNo.setSelected(true); } } if (conf.containsKey("invertYAxis")) { if (conf.get("invertYAxis").getValue().equals("yes")) { slideImagerDialog.invertYAxisYes.setSelected(true); slideImagerDialog.invertYAxisNo.setSelected(false); } else if (conf.get("invertYAxis").getValue().equals("no")) { slideImagerDialog.invertYAxisYes.setSelected(false); slideImagerDialog.invertYAxisNo.setSelected(true); } } if (conf.containsKey("initialZPos")) { slideImagerDialog.setInitZPosYes.setSelected(true); slideImagerDialog.initialZPos.setValue(new Double(conf.get("initialZPos").getValue())); } else { slideImagerDialog.setInitZPosNo.setSelected(true); slideImagerDialog.initialZPos.setValue(new Double(0.0)); } return slideImagerDialog; } @Override public ValidationError[] validate() { List<ValidationError> errors = new ArrayList<ValidationError>(); File acqSettingsFile = new File(slideImagerDialog.acqSettingsText.getText()); if (!acqSettingsFile.exists()) { errors.add(new ValidationError(workflowModule.getName(), "Acquisition settings file "+acqSettingsFile.toString()+" not found.")); } if (slideImagerDialog.posListText.getText().length()>0) { File posListFile = new File(slideImagerDialog.posListText.getText()); if (!posListFile.exists()) { errors.add(new ValidationError(workflowModule.getName(), "Position list file "+posListFile.toString()+" not found.")); } } if (!((slideImagerDialog.posListText.getText().length()>0? 1: 0) + (slideImagerDialog.moduleName.getSelectedIndex()>0? 1: 0) == 1)) { errors.add(new ValidationError(workflowModule.getName(), "You must enter one of either a position list file, or a position list name.")); } if ((Double)slideImagerDialog.pixelSize.getValue() <= 0.0) { errors.add(new ValidationError(workflowModule.getName(), "Pixel size must be greater than zero.")); } return errors.toArray(new ValidationError[0]); } }; } @Override public List<Task> createTaskRecords(List<Task> parentTasks, Map<String,Config> config, Logger logger) { Dao<Slide> slideDao = workflowRunner.getWorkflowDb().table(Slide.class); Dao<ModuleConfig> moduleConfig = workflowRunner.getModuleConfig(); Dao<TaskConfig> taskConfigDao = workflowRunner.getTaskConfig(); // Load all the module configuration into a HashMap Map<String,Config> moduleConf = new HashMap<String,Config>(); for (ModuleConfig c : moduleConfig.select(where("id",this.workflowModule.getId()))) { moduleConf.put(c.getKey(), c); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Using module config: %s", this.workflowModule.getName(), c)); } // Create task records and connect to parent tasks // If no parent tasks were defined, then just create a single task instance. List<Task> tasks = new ArrayList<Task>(); for (Task parentTask : parentTasks.size()>0? parentTasks.toArray(new Task[]{}) : new Task[]{null}) { workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Connecting parent task %s", this.workflowModule.getName(), Util.escape(parentTask))); // get the parent task configuration Map<String,TaskConfig> parentTaskConf = new HashMap<String,TaskConfig>(); if (parentTask != null) { for (TaskConfig c : taskConfigDao.select(where("id",parentTask.getId()))) { parentTaskConf.put(c.getKey(), c); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Using task config: %s", this.workflowModule.getName(), c)); } } // Get the associated slide. Slide slide; if (parentTaskConf.containsKey("slideId")) { slide = slideDao.selectOneOrDie(where("id",new Integer(parentTaskConf.get("slideId").getValue()))); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Inherited slideId %s", this.workflowModule.getName(), parentTaskConf.get("slideId"))); } // if posListModule is set, use the most recent slide else if (moduleConf.containsKey("posListModule")) { List<Slide> slides = slideDao.select(); Collections.sort(slides, (a,b)->b.getId()-a.getId()); if (slides.size() > 0) { slide = slides.get(0); } else { throw new RuntimeException("No slides were found!"); } } // If no associated slide is registered, create a slide to represent this task else { String uuid = UUID.randomUUID().toString(); slide = new Slide(uuid); slideDao.insertOrUpdate(slide,"experimentId"); slideDao.reload(slide, "experimentId"); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created new slide: %s", this.workflowModule.getName(), slide.toString())); } config.put("slideId", new Config(this.workflowModule.getId(), "slideId", new Integer(slide.getId()).toString())); // Load the position list and set the acquisition settings. // If the position list is not yet loaded, then it will be determined at runtime. // We will add more task records when run() is called, since the position // list isn't ready yet. PositionList positionList = loadPositionList(config, workflowRunner.getLogger()); if (positionList == null) { Task task = new Task(this.workflowModule.getId(), Status.NEW); workflowRunner.getTaskStatus().insert(task); TaskConfig loadDynamicTaskRecordsConf = new TaskConfig( task.getId(), "loadDynamicTaskRecords", "yes"); taskConfigDao.insert(loadDynamicTaskRecordsConf); if (parentTask != null) { TaskDispatch dispatch = new TaskDispatch(task.getId(), parentTask.getId()); workflowRunner.getTaskDispatch().insert(dispatch); } continue; } // count the number of ROIs Set<String> rois = new HashSet<>(); for (MultiStagePosition msp : positionList.getPositions()) { if (msp.getProperty("ROI") != null) { rois.add(msp.getProperty("ROI")); } } // get the total images VerboseSummary verboseSummary = getVerboseSummary(); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Verbose summary:", this.workflowModule.getName())); for (String line : verboseSummary.summary.split("\n")) workflowRunner.getLogger().fine(String.format(" %s", line)); int totalImages = verboseSummary.channels * verboseSummary.slices * verboseSummary.frames * verboseSummary.positions; workflowRunner.getLogger().fine(String.format("%s: getTotalImages: Will create %d images", this.workflowModule.getName(), totalImages)); Config dispatchUUIDConf = config.get("dispatchUUID"); String dispatchUUID = dispatchUUIDConf != null? dispatchUUIDConf.getValue() : null; // Create the task records for (int c=0; c<verboseSummary.channels; ++c) { for (int s=0; s<verboseSummary.slices; ++s) { for (int f=0; f<verboseSummary.frames; ++f) { for (int p=0; p<verboseSummary.positions; ++p) { // Create task record Task task = new Task(this.workflowModule.getId(), Status.NEW); // setting the dispatch UUID is required for dynamically created // tasks to be picked up by the workflow runner task.setDispatchUUID(dispatchUUID); workflowRunner.getTaskStatus().insert(task); tasks.add(task); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task record: %s", this.workflowModule.getName(), task)); // Create taskConfig record for the image label TaskConfig imageLabel = new TaskConfig( task.getId(), "imageLabel", MDUtils.generateLabel(c, s, f, p)); taskConfigDao.insert(imageLabel); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task config: %s", this.workflowModule.getName(), imageLabel)); // Create taskConfig record for the MSP label (positionName) MultiStagePosition msp = positionList.getPosition(p); TaskConfig positionName = new TaskConfig( task.getId(), "positionName", msp.getLabel()); taskConfigDao.insert(positionName); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task config: %s", this.workflowModule.getName(), positionName)); // Store the MSP value as a JSON string try { PositionList mspPosList = new PositionList(); mspPosList.addPosition(msp); String mspJson = new JSONObject(mspPosList.serialize()). getJSONArray("POSITIONS").getJSONObject(0).toString(); TaskConfig mspConf = new TaskConfig( task.getId(), "MSP", mspJson); taskConfigDao.insert(mspConf); moduleConf.put("MSP", mspConf); workflowRunner.getLogger().fine(String.format( "Inserted MultiStagePosition config: %s", mspJson)); } catch (MMSerializationException e) {throw new RuntimeException(e);} catch (JSONException e) {throw new RuntimeException(e);} // Transfer MultiStagePosition property values to the task's configuration for (String propName : msp.getPropertyNames()) { String property = msp.getProperty(propName); TaskConfig prop = new TaskConfig( task.getId(), propName, property); taskConfigDao.insert(prop); moduleConf.put(property, prop); workflowRunner.getLogger().fine(String.format( "Inserted MultiStagePosition config: %s", prop)); } // create taskConfig record for the slide ID TaskConfig slideId = new TaskConfig( task.getId(), "slideId", new Integer(slide.getId()).toString()); taskConfigDao.insert(slideId); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task config: %s", this.workflowModule.getName(), slideId)); // add some task configs to the first imaging task to assist in calculating metrics if (c==0 && s==0 && f==0 && p==0) { TaskConfig positionsConf = new TaskConfig( task.getId(), "positions", new Integer(verboseSummary.positions).toString()); taskConfigDao.insert(positionsConf); TaskConfig roisConf = new TaskConfig( task.getId(), "ROIs", new Integer(rois.size()).toString()); taskConfigDao.insert(roisConf); TaskConfig verboseSummaryConf = new TaskConfig( task.getId(), "verboseSummary", verboseSummary.summary); taskConfigDao.insert(verboseSummaryConf); } // Create task dispatch record if (parentTask != null) { TaskDispatch dispatch = new TaskDispatch(task.getId(), parentTask.getId()); workflowRunner.getTaskDispatch().insert(dispatch); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task dispatch record: %s", this.workflowModule.getName(), dispatch)); } } } } } } return tasks; } public static class VerboseSummary { public String summary; public int frames; public int positions; public int slices; public int channels; public int totalImages; public String totalMemory; public String duration; public String[] order; } /** * Parse the verbose summary text returned by the AcqusitionWrapperEngine. * Sadly, this is the only way to get some needed information since the getNumSlices(), etc. * methods are private. * @return the VerboseSummary object */ public VerboseSummary getVerboseSummary() { String summary = this.engine.getVerboseSummary(); VerboseSummary verboseSummary = new VerboseSummary(); verboseSummary.summary = summary; Pattern pattern = Pattern.compile("^Number of time points: ([0-9]+)$", Pattern.MULTILINE); Matcher matcher = pattern.matcher(summary); if (!matcher.find()) throw new RuntimeException(String.format( "Could not parse frames field from summary:%n%s", summary)); verboseSummary.frames = new Integer(matcher.group(1)); pattern = Pattern.compile("^Number of positions: ([0-9]+)$", Pattern.MULTILINE); matcher = pattern.matcher(summary); if (!matcher.find()) throw new RuntimeException(String.format( "Could not parse positions field from summary:%n%s", summary)); verboseSummary.positions = new Integer(matcher.group(1)); pattern = Pattern.compile("^Number of slices: ([0-9]+)$", Pattern.MULTILINE); matcher = pattern.matcher(summary); if (!matcher.find()) throw new RuntimeException(String.format( "Could not parse slices field from summary:%n%s", summary)); verboseSummary.slices = new Integer(matcher.group(1)); pattern = Pattern.compile("^Number of channels: ([0-9]+)$", Pattern.MULTILINE); matcher = pattern.matcher(summary); if (!matcher.find()) throw new RuntimeException(String.format( "Could not parse channels field from summary:%n%s", summary)); verboseSummary.channels = new Integer(matcher.group(1)); pattern = Pattern.compile("^Total images: ([0-9]+)$", Pattern.MULTILINE); matcher = pattern.matcher(summary); if (!matcher.find()) throw new RuntimeException(String.format( "Could not parse total images field from summary:%n%s", summary)); verboseSummary.totalImages = new Integer(matcher.group(1)); pattern = Pattern.compile("^Total memory: ([^\\n]+)$", Pattern.MULTILINE); matcher = pattern.matcher(summary); if (!matcher.find()) throw new RuntimeException(String.format( "Could not parse total memory field from summary:%n%s", summary)); verboseSummary.totalMemory = matcher.group(1).trim(); pattern = Pattern.compile("^Duration: ([^\\n]+)$", Pattern.MULTILINE); matcher = pattern.matcher(summary); if (!matcher.find()) throw new RuntimeException(String.format( "Could not parse duration field from summary:%n%s", summary)); verboseSummary.duration = matcher.group(1).trim(); pattern = Pattern.compile("^Order: ([^\\n]+)$", Pattern.MULTILINE); matcher = pattern.matcher(summary); if (matcher.find()) { verboseSummary.order = matcher.group(1).trim().split(",\\s*"); } else { this.workflowRunner.getLogger().info(String.format( "Could not parse order field from summary:%n%s", summary)); } return verboseSummary; } @Override public TaskType getTaskType() { return Module.TaskType.SERIAL; } @Override public void cleanup(Task task, Map<String,Config> config, Logger logger) { } @Override public List<ImageLogRecord> logImages(Task task, Map<String,Config> config, Logger logger) { List<ImageLogRecord> imageLogRecords = new ArrayList<ImageLogRecord>(); // Add an image logger instance to the workflow runner for this module imageLogRecords.add(new ImageLogRecord(task.getName(workflowRunner.getWorkflow()), task.getName(workflowRunner.getWorkflow()), new FutureTask<ImageLogRunner>(new Callable<ImageLogRunner>() { @Override public ImageLogRunner call() throws Exception { // Get the Image record Config imageIdConf = config.get("imageId"); if (imageIdConf != null) { Integer imageId = new Integer(imageIdConf.getValue()); logger.info(String.format("Using image ID: %d", imageId)); Dao<Image> imageDao = workflowRunner.getWorkflowDb().table(Image.class); Image image = imageDao.selectOneOrDie(where("id",imageId)); logger.info(String.format("Using image: %s", image)); // Initialize the acquisition Dao<Acquisition> acqDao = workflowRunner.getWorkflowDb().table(Acquisition.class); Acquisition acquisition = acqDao.selectOneOrDie(where("id",image.getAcquisitionId())); logger.info(String.format("Using acquisition: %s", acquisition)); MMAcquisition mmacquisition = acquisition.getAcquisition(acqDao); // Get the image cache object ImageCache imageCache = mmacquisition.getImageCache(); if (imageCache == null) throw new RuntimeException("Acquisition was not initialized; imageCache is null!"); // Get the tagged image from the image cache TaggedImage taggedImage = image.getImage(imageCache); logger.info(String.format("Got taggedImage from ImageCache: %s", taggedImage)); ImageLogRunner imageLogRunner = new ImageLogRunner(task.getName(workflowRunner.getWorkflow())); imageLogRunner.addImage(taggedImage, "The image"); return imageLogRunner; } return null; } }))); return imageLogRecords; } @Override public void runInitialize() { } public synchronized static double[] moveStage(String moduleId, CMMCore core, double x, double y, Logger logger) { core.setTimeoutMs(10000); String xyStage = core.getXYStageDevice(); int move_tries = 0; final int MOVE_MAX_TRIES = 10; Throwable err = new RuntimeException("Unknown exception"); while (move_tries++ < MOVE_MAX_TRIES) { try { if (logger != null) logger.fine(String.format("%s: Moving stage to position: (%f,%f)", moduleId, x, y)); // get the stage coordinates // sometimes moving the stage throws, try at least 10 times double[] x_stage = new double[] {0.0}; double[] y_stage = new double[] {0.0}; int tries = 0; final int MAX_TRIES = 10; while(tries <= MAX_TRIES) { try { core.getXYPosition(xyStage, x_stage, y_stage); break; } catch (Throwable e) { if (tries >= MAX_TRIES) throw new RuntimeException(e); } Thread.sleep(500); ++tries; } if (logger != null) logger.fine(String.format("%s: Current stage position: (%f,%f)", moduleId, x_stage[0], y_stage[0])); // set the stage coordinates tries = 0; while(tries <= MAX_TRIES) { try { core.setXYPosition(xyStage, x, y); break; } catch (Throwable e) { if (tries >= MAX_TRIES) throw new RuntimeException(e); } Thread.sleep(500); ++tries; } // wait for the stage to finish moving final long MAX_WAIT = 10000000000L; // 10 seconds long startTime = System.nanoTime(); while (core.deviceBusy(xyStage)) { if (MAX_WAIT < System.nanoTime() - startTime) { // If it's taking too long to move the stage, // try re-sending the stage movement command. if (logger != null) logger.warning(String.format("%s: Stage is taking too long to move, re-sending stage move commands...", moduleId)); core.stop(xyStage); Thread.sleep(500); startTime = System.nanoTime(); core.setXYPosition(xyStage, x, y); } Thread.sleep(5); } // get the new stage coordinates double[] x_stage_new = new double[] {0.0}; double[] y_stage_new = new double[] {0.0}; tries = 0; while(tries <= MAX_TRIES) { try { core.getXYPosition(xyStage, x_stage_new, y_stage_new); break; } catch (Throwable e) { if (tries >= MAX_TRIES) throw new RuntimeException(e); } Thread.sleep(500); ++tries; } // make sure the stage moved to the correct coordinates if (logger != null) logger.fine(String.format("%s: New stage position: (%f,%f)", moduleId, x_stage_new[0], y_stage_new[0])); final double EPSILON = 1000; if (!(Math.abs(x_stage_new[0]-x) < EPSILON && Math.abs(y_stage_new[0]-y) < EPSILON)) { throw new RuntimeException(String.format("%s: Stage moved to wrong coordinates: (%.2f,%.2f)", moduleId, x_stage_new[0], y_stage_new[0])); } // return the new stage coordinates return new double[]{x_stage_new[0], y_stage_new[0]}; } catch (Throwable e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); if (logger != null) logger.severe(String.format("%s: Failed to move stage to position (%.2f,%.2f): %s", moduleId, x,y, sw.toString())); err = e; } } throw new RuntimeException(err); } public Status setTaskStatusOnResume(Task task) { TaskConfig loadDynamicTaskRecordsConf = this.workflowRunner.getTaskConfig().selectOne( where("id", task.getId()). and("key", "loadDynamicTaskRecords"). and("value","yes")); if (loadDynamicTaskRecordsConf != null) { return task.getStatus(); } TaskConfig imageLabelConf = this.workflowRunner.getTaskConfig().selectOne( where("id", task.getId()). and("key", "imageLabel")); if (imageLabelConf == null) throw new RuntimeException(String.format( "Could not find imageLabel conf for task %s!", task)); String imageLabel = imageLabelConf.getValue(); int[] indices = MDUtils.getIndices(imageLabel); if (indices == null || indices.length < 4) throw new RuntimeException(String.format( "Invalid indices parsed from imageLabel %s", imageLabel)); if (indices[0] == 0 && indices[1] == 0 && indices[2] == 0 && indices[3] == 0) { // get this slide ID TaskConfig slideIdConf = this.workflowRunner.getTaskConfig().selectOne( where("id", task.getId()). and("key", "slideId")); Integer slideId = slideIdConf != null? new Integer(slideIdConf.getValue()) : null; // if this task has a slide ID if (slideId != null) { // get all tasks with same slide ID as this one List<TaskConfig> sameSlideId = this.workflowRunner.getTaskConfig().select( where("key", "slideId"). and("value", slideId)); List<Task> tasks = new ArrayList<>(); for (TaskConfig tc : sameSlideId) { tasks.addAll(this.workflowRunner.getTaskStatus().select( where("id", tc.getId()). and("moduleId", task.getModuleId()))); } for (Task t : tasks) { if (t.getStatus() != Status.SUCCESS || this.workflowRunner.getTaskConfig().selectOne(where("id", t.getId()).and("key", "imageId")) == null) { for (Task t2 : tasks) { this.workflowRunner.getTaskStatus().update( set("status", Status.NEW). and("dispatchUUID", null), where("id", t2.getId())); } return Status.NEW; } } } else { // get all tasks without a defined slide ID List<Task> tasks = new ArrayList<>(); for (Task t : this.workflowRunner.getTaskStatus().select(where("moduleId", task.getModuleId()))) { TaskConfig tc = this.workflowRunner.getTaskConfig().selectOne( where("id", t.getId()). and("key", "slideId")); if (tc == null) tasks.add(t); } for (Task t : tasks) { if (t.getStatus() != Status.SUCCESS) { for (Task t2 : tasks) { this.workflowRunner.getTaskStatus().update( set("status", Status.NEW). and("dispatchUUID", null), where("id", t2.getId())); } return Status.NEW; } } } } return task.getDispatchUUID() == null? task.getStatus() : null; } }
package com.github.hydrazine.module.builtin; import java.io.File; import java.net.Proxy; import java.util.Scanner; import org.spacehq.mc.protocol.MinecraftProtocol; import org.spacehq.mc.protocol.data.game.values.MessageType; import org.spacehq.mc.protocol.packet.ingame.client.ClientChatPacket; import org.spacehq.mc.protocol.packet.ingame.server.ServerChatPacket; import org.spacehq.mc.protocol.packet.ingame.server.ServerJoinGamePacket; import org.spacehq.packetlib.Client; import org.spacehq.packetlib.event.session.PacketReceivedEvent; import org.spacehq.packetlib.event.session.SessionAdapter; import com.github.hydrazine.Hydrazine; import com.github.hydrazine.minecraft.Authenticator; import com.github.hydrazine.minecraft.ClientFactory; import com.github.hydrazine.minecraft.Credentials; import com.github.hydrazine.minecraft.Server; import com.github.hydrazine.module.Module; import com.github.hydrazine.module.ModuleSettings; import com.github.hydrazine.util.ConnectionHelper; /** * * @author xTACTIXzZ * * Connects a client to a server and reads the chat. * */ public class ChatReaderModule implements Module { // Create new file where the configuration will be stored (Same folder as jar file) private File configFile = new File(ClassLoader.getSystemClassLoader().getResource(".").getPath() + "." + this.getClass().getName()); // Configuration settings are stored in here private ModuleSettings settings = new ModuleSettings(configFile); @Override public String getName() { return "readchat"; } @Override public String getDescription() { return "This module connects to a server and passively reads the chat."; } @Override public void start() { // Load settings settings.load(); System.out.println(Hydrazine.infoPrefix + "Starting module \'" + getName() + "\'. Press CTRL + C to exit."); Scanner sc = new Scanner(System.in); Authenticator auth = new Authenticator(); ClientFactory factory = new ClientFactory(); Server server = new Server(Hydrazine.settings.getSetting("host"), Integer.parseInt(Hydrazine.settings.getSetting("port"))); // Server has offline mode enabled if(Hydrazine.settings.hasSetting("username") || Hydrazine.settings.hasSetting("genuser")) { String username = auth.getUsername(); MinecraftProtocol protocol = new MinecraftProtocol(username); Client client = ConnectionHelper.connect(factory, protocol, server); registerListeners(client); while(client.getSession().isConnected()) { try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } } sc.close(); stop(); } // Server has offline mode disabled else if(Hydrazine.settings.hasSetting("credentials")) { Credentials creds = auth.getCredentials(); Client client = null; // Check if auth proxy should be used if(Hydrazine.settings.hasSetting("authproxy")) { Proxy proxy = auth.getAuthProxy(); MinecraftProtocol protocol = auth.authenticate(creds, proxy); client = ConnectionHelper.connect(factory, protocol, server); } else { MinecraftProtocol protocol = auth.authenticate(creds); client = ConnectionHelper.connect(factory, protocol, server); } registerListeners(client); while(client.getSession().isConnected()) { try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } } sc.close(); stop(); } // User forgot to pass the options else { System.out.println(Hydrazine.errorPrefix + "No client option specified. You have to append one of those switches to the command: -u, -gu or -cr"); } } @Override public void stop() { System.out.println("Module stopped, bye!"); } @Override public void configure() { settings.setProperty("registerCommand", ModuleSettings.askUser("Enter register command: ")); settings.setProperty("loginCommand", ModuleSettings.askUser("Enter login command: ")); settings.setProperty("commandDelay", ModuleSettings.askUser("Enter the delay between the commands in milliseconds: ")); settings.setProperty("filterColorCodes", String.valueOf(ModuleSettings.askUserYesNo("Filter color codes?"))); // Create configuration file if not existing if(!configFile.exists()) { boolean success = settings.createConfigFile(); if(!success) { return; } } // Store configuration variables settings.store(); } /* * Register listeners */ private void registerListeners(Client client) { client.getSession().addListener(new SessionAdapter() { @Override public void packetReceived(PacketReceivedEvent event) { if(event.getPacket() instanceof ServerJoinGamePacket) { if(settings.containsKey("loginCommand") && settings.containsKey("registerCommand")) { if(!(settings.getProperty("loginCommand").isEmpty() && settings.getProperty("registerCommand").isEmpty())) { // Sleep because there may be a command cooldown try { Thread.sleep(Integer.parseInt(settings.getProperty("commandDelay"))); } catch (InterruptedException e) { e.printStackTrace(); } client.getSession().send(new ClientChatPacket(settings.getProperty("registerCommand"))); // Sleep because there may be a command cooldown try { Thread.sleep(Integer.parseInt(settings.getProperty("commandDelay"))); } catch (InterruptedException e) { e.printStackTrace(); } client.getSession().send(new ClientChatPacket(settings.getProperty("loginCommand"))); } } } else if(event.getPacket() instanceof ServerChatPacket) { ServerChatPacket packet = ((ServerChatPacket) event.getPacket()); // Check if message is a chat message if(packet.getType() != MessageType.NOTIFICATION) { if(settings.containsKey("filterColorCodes") && settings.getProperty("filterColorCodes").equals("true")) { String line = packet.getMessage().getFullText(); String builder = line; // Filter out color codes if(builder.contains("§")) { int count = builder.length() - builder.replace("§", "").length(); for(int i = 0; i < count; i++) { int index = builder.indexOf("§"); if(index > (-1)) // Check if index is invalid, happens sometimes. { String buf = builder.substring(index, index + 2); String repl = builder.replace(buf, ""); builder = repl; } } System.out.println(Hydrazine.inputPrefix + builder); } else { System.out.println(Hydrazine.inputPrefix + line); } } else { System.out.println(Hydrazine.inputPrefix + packet.getMessage().getFullText()); } } } } }); } }
package org.bdgp.OpenHiCAMM.Modules; import java.awt.Component; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.prefs.Preferences; import java.util.regex.Matcher; import java.util.regex.Pattern; import mmcorej.CMMCore; import mmcorej.TaggedImage; import org.bdgp.OpenHiCAMM.Dao; import org.bdgp.OpenHiCAMM.ImageLog.ImageLogRecord; import org.bdgp.OpenHiCAMM.ImageLog.ImageLogRunner; import org.bdgp.OpenHiCAMM.Logger; import org.bdgp.OpenHiCAMM.OpenHiCAMM; import org.bdgp.OpenHiCAMM.Util; import org.bdgp.OpenHiCAMM.ValidationError; import org.bdgp.OpenHiCAMM.WorkflowRunner; import org.bdgp.OpenHiCAMM.DB.Acquisition; import org.bdgp.OpenHiCAMM.DB.Config; import org.bdgp.OpenHiCAMM.DB.Image; import org.bdgp.OpenHiCAMM.DB.ModuleConfig; import org.bdgp.OpenHiCAMM.DB.Slide; import org.bdgp.OpenHiCAMM.DB.SlidePos; import org.bdgp.OpenHiCAMM.DB.SlidePosList; import org.bdgp.OpenHiCAMM.DB.Task; import org.bdgp.OpenHiCAMM.DB.Task.Status; import org.bdgp.OpenHiCAMM.DB.TaskConfig; import org.bdgp.OpenHiCAMM.DB.TaskDispatch; import org.bdgp.OpenHiCAMM.Modules.Interfaces.Configuration; import org.bdgp.OpenHiCAMM.Modules.Interfaces.ImageLogger; import org.bdgp.OpenHiCAMM.Modules.Interfaces.Module; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.dialogs.AcqControlDlg; import org.micromanager.events.DisplayCreatedEvent; import org.micromanager.events.EventManager; import org.micromanager.MMOptions; import org.micromanager.MMStudio; import org.micromanager.acquisition.AcquisitionWrapperEngine; import org.micromanager.acquisition.MMAcquisition; import org.micromanager.api.Autofocus; import org.micromanager.api.ImageCache; import org.micromanager.api.ImageCacheListener; import org.micromanager.api.MultiStagePosition; import org.micromanager.api.PositionList; import org.micromanager.api.ScriptInterface; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMException; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.MMSerializationException; import com.google.common.eventbus.Subscribe; import static org.bdgp.OpenHiCAMM.Util.where; public class SlideImager implements Module, ImageLogger { private static final long DUMMY_SLEEP = 500; WorkflowRunner workflowRunner; String moduleId; AcqControlDlg acqControlDlg; ScriptInterface script; AcquisitionWrapperEngine engine; @Override public void initialize(WorkflowRunner workflowRunner, String moduleId) { this.workflowRunner = workflowRunner; this.moduleId = moduleId; OpenHiCAMM openhicamm = workflowRunner.getOpenHiCAMM(); this.script = openhicamm.getApp(); Preferences prefs = Preferences.userNodeForPackage(this.script.getClass()); MMOptions options = new MMOptions(); options.loadSettings(); if (this.script != null) { this.engine = MMStudio.getInstance().getAcquisitionEngine(); this.acqControlDlg = new AcqControlDlg(this.engine, prefs, this.script, options); } } /** * Load the acquisition settings and get the position list from the DB * @param conf The module configuration * @param logger The logging module * @return the position list */ public PositionList loadPositionList(Map<String,Config> conf, Logger logger) { // first try to load a position list from the posListId conf // otherwise, try loading from the posListModuleId conf PositionList positionList; if (conf.containsKey("posListModuleId")) { // get a sorted list of all the SlidePosList records for the posListModuleId module Config posListModuleId = conf.get("posListModuleId"); Dao<SlidePosList> posListDao = workflowRunner.getInstanceDb().table(SlidePosList.class); Integer slideId = new Integer(conf.get("slideId").getValue()); List<SlidePosList> posLists = posListDao.select( where("slideId", slideId). and("moduleId", posListModuleId.getValue())); Collections.sort(posLists, new Comparator<SlidePosList>() { @Override public int compare(SlidePosList a, SlidePosList b) { return a.getId()-b.getId(); }}); if (posLists.isEmpty()) { throw new RuntimeException("Position list from module \""+posListModuleId.getValue()+"\" not found in database"); } // Merge the list of PositionLists into a single positionList positionList = posLists.get(0).getPositionList(); for (int i=1; i<posLists.size(); ++i) { SlidePosList spl = posLists.get(i); PositionList pl = spl.getPositionList(); for (int j=0; j<pl.getNumberOfPositions(); ++j) { MultiStagePosition msp = pl.getPosition(j); positionList.addPosition(msp); } } // log the position list to the console try { logger.info(String.format("%s: Read position list from module %s:%n%s", this.moduleId, conf.get("posListModuleId"), positionList.serialize())); } catch (MMSerializationException e) {throw new RuntimeException(e);} // load the position list into the acquisition engine try { this.script.setPositionList(positionList); } catch (MMScriptException e) {throw new RuntimeException(e);} this.engine.setPositionList(positionList); } // otherwise, load a position list from a file else if (conf.containsKey("posListFile")) { Config posList = conf.get("posListFile"); logger.info(String.format("%s: Loading position list from file: %s", this.moduleId, Util.escape(posList.getValue()))); File posListFile = new File(posList.getValue()); if (!posListFile.exists()) { throw new RuntimeException("Cannot find position list file "+posListFile.getPath()); } try { positionList = new PositionList(); positionList.load(posListFile.getPath()); try { this.script.setPositionList(positionList); } catch (MMScriptException e) {throw new RuntimeException(e);} this.engine.setPositionList(positionList); } catch (MMException e) {throw new RuntimeException(e);} } else { throw new RuntimeException("No position list was given!"); } // Load the settings and position list from the settings files if (conf.containsKey("acqSettingsFile")) { Config acqSettings = conf.get("acqSettingsFile"); logger.info(String.format("%s: Loading acquisition settings from file: %s", this.moduleId, Util.escape(acqSettings.getValue()))); File acqSettingsFile = new File(acqSettings.getValue()); if (!acqSettingsFile.exists()) { throw new RuntimeException("Cannot find acquisition settings file "+acqSettingsFile.getPath()); } try { acqControlDlg.loadAcqSettingsFromFile(acqSettingsFile.getPath()); } catch (MMScriptException e) {throw new RuntimeException(e);} } return positionList; } @Subscribe public void showDisplay(DisplayCreatedEvent e) { e.getDisplayWindow().setVisible(true); } @Override public Status run(Task task, final Map<String,Config> conf, final Logger logger) { logger.fine(String.format("Running task: %s", task)); for (Config c : conf.values()) { logger.fine(String.format("Using configuration: %s", c)); } Config imageLabelConf = conf.get("imageLabel"); if (imageLabelConf == null) throw new RuntimeException(String.format( "Could not find imageLabel conf for task %s!", task)); String imageLabel = imageLabelConf.getValue(); logger.fine(String.format("Using imageLabel: %s", imageLabel)); int[] indices = MDUtils.getIndices(imageLabel); if (indices.length < 4) throw new RuntimeException(String.format("Invalid indices parsed from imageLabel %s: %s", imageLabel, Arrays.toString(indices))); // If this is the acqusition task 0_0_0_0, start the acquisition engine if (indices[0] == 0 && indices[1] == 0 && indices[2] == 0 && indices[3] == 0) { // Make sure the acquisition control dialog was initialized if (this.acqControlDlg == null) { throw new RuntimeException("acqControlDlg is not initialized!"); } // load the position list and acquistion settings PositionList posList = this.loadPositionList(conf, logger); final VerboseSummary verboseSummary = getVerboseSummary(); logger.info(String.format("Verbose summary:%n%s%n", verboseSummary.summary)); final int totalImages = verboseSummary.channels * verboseSummary.slices * verboseSummary.frames * verboseSummary.positions; // Get Dao objects ready for use final Dao<TaskConfig> taskConfigDao = workflowRunner.getInstanceDb().table(TaskConfig.class); final Dao<Acquisition> acqDao = workflowRunner.getInstanceDb().table(Acquisition.class); final Dao<Image> imageDao = workflowRunner.getInstanceDb().table(Image.class); // Set rootDir and acqName String rootDir = new File( workflowRunner.getWorkflowDir(), workflowRunner.getInstance().getStorageLocation()).getPath(); String acqName = "images"; CMMCore core = this.script.getMMCore(); logger.fine(String.format("This task is the acquisition task")); logger.info(String.format("Using rootDir: %s", rootDir)); logger.info(String.format("Requesting to use acqName: %s", acqName)); // Move stage to starting position and take some dummy pictures to adjust the camera if (conf.containsKey("dummyImageCount") && posList.getNumberOfPositions() > 0) { Integer dummyImageCount = new Integer(conf.get("dummyImageCount").getValue()); logger.info("Moving stage to starting position"); MultiStagePosition pos = posList.getPosition(0); String xyStage = core.getXYStageDevice(); try { core.setXYPosition(xyStage, pos.getX(), pos.getY()); // wait for the stage to finish moving while (core.deviceBusy(xyStage)) {} } catch (Exception e) {throw new RuntimeException(e);} // Acquire N dummy images to calibrate the camera for (int i=0; i<dummyImageCount; ++i) { // Take a picture but don't save it try { core.snapImage(); } catch (Exception e) {throw new RuntimeException(e);} logger.info(String.format("Acquired %d dummy images to calibrate the camera...", i+1)); // wait a second before taking the next one. try { Thread.sleep(DUMMY_SLEEP); } catch (InterruptedException e) {logger.info("Sleep thread was interrupted");} } } // Set the autofocus device try { this.script.getAutofocusManager().selectDevice("BDGP"); Autofocus autofocus = this.script.getAutofocus(); // Only pass these settings to the autofocus object: Set<String> autoFocusKeys = new HashSet<String>(); autoFocusKeys.add("minAutoFocus"); autoFocusKeys.add("maxAutoFocus"); // Set the autofocus property values for (Map.Entry<String, Config> entry : conf.entrySet()) { if (autoFocusKeys.contains(entry.getKey())) { autofocus.setPropertyValue(entry.getKey(), entry.getValue().getValue()); } } // now apply the settings autofocus.applySettings(); } catch (MMException e) {throw new RuntimeException(e);} // build a map of imageLabel -> sibling task record Dao<Task> taskDao = this.workflowRunner.getTaskStatus(); Dao<TaskDispatch> taskDispatchDao = this.workflowRunner.getTaskDispatch(); TaskDispatch td = taskDispatchDao.selectOne(where("taskId", task.getId())); List<TaskDispatch> tds = td != null? taskDispatchDao.select(where("parentTaskId", td.getParentTaskId())) : null; final Map<String,Task> tasks = new TreeMap<String,Task>(); if (tds != null) { Collections.sort(tds, new Comparator<TaskDispatch>() { @Override public int compare(TaskDispatch a, TaskDispatch b) { return a.getTaskId() - b.getTaskId(); }}); for (TaskDispatch t : tds) { Task tt = taskDao.selectOneOrDie(where("id", t.getTaskId())); TaskConfig imageLabelConf2 = taskConfigDao.selectOneOrDie( where("id", new Integer(tt.getId()).toString()). and("key", "imageLabel")); tasks.put(imageLabelConf2.getValue(), tt); } } else { List<Task> tts = taskDao.select(where("moduleId", this.moduleId)); Collections.sort(tts, new Comparator<Task>() { @Override public int compare(Task a, Task b) { return a.getId() - b.getId(); }}); for (Task tt : tts) { TaskConfig imageLabelConf2 = taskConfigDao.selectOneOrDie( where("id", new Integer(tt.getId()).toString()). and("key", "imageLabel")); tasks.put(imageLabelConf2.getValue(), tt); } } // get the slide ID from the config if (!conf.containsKey("slideId")) throw new RuntimeException("No slideId found for image!"); final Integer slideId = new Integer(conf.get("slideId").getValue()); logger.info(String.format("Using slideId: %d", slideId)); // Start the acquisition engine. This runs asynchronously. try { EventManager.register(this); logger.info(String.format("Now running the image acquisition sequence, please wait...")); String returnAcqName = acqControlDlg.runAcquisition(acqName, rootDir); if (returnAcqName == null) { throw new RuntimeException("acqControlDlg.runAcquisition returned null acquisition name"); } // get the prefix name and log it JSONObject summaryMetadata = this.engine.getSummaryMetadata(); String prefix; try { prefix = summaryMetadata.getString("Prefix"); } catch (JSONException e) { throw new RuntimeException(e); } logger.info(String.format("Acquisition was saved to root directory %s, prefix %s", Util.escape(rootDir), Util.escape(prefix))); // Write the acquisition record final Acquisition acquisition = new Acquisition(returnAcqName, prefix, rootDir); acqDao.insertOrUpdate(acquisition,"name","directory"); acqDao.reload(acquisition); logger.info(String.format("Using acquisition record: %s", acquisition)); // add an image cache listener to eagerly kick off downstream processing after each image // is received. final ImageCache acqImageCache = this.engine.getImageCache(); acqImageCache.addImageCacheListener(new ImageCacheListener() { @Override public void imageReceived(final TaggedImage taggedImage) { // run the logic in a separate thread to avoid blocking the UI thread. new Thread(new Runnable() { @Override public void run() { // Log how many images have been acquired so far Set<String> taggedImages = new HashSet<String>(acqImageCache.imageKeys()); String label = MDUtils.getLabel(taggedImage.tags); taggedImages.add(label); logger.info(String.format("Acquired image: %s (%d/%d images)", MDUtils.getLabel(taggedImage.tags), taggedImages.size(), totalImages)); int[] indices = MDUtils.getIndices(label); if (indices.length < 4) throw new RuntimeException(String.format( "Bad image label from MDUtils.getIndices(): %s", label)); // Don't eagerly dispatch the acquisition thread. This thread must not be set to success // until the acquisition has finished, so the downstream processing for this task // must wait until the acquisition has finished. if (!(indices[0] == 0 && indices[1] == 0 && indices[2] == 0 && indices[3] == 0)) { // Write the image record and kick off downstream processing. // create the image record Image image = new Image(slideId, acquisition, indices[0], indices[1], indices[2], indices[3]); imageDao.insertOrUpdate(image,"acquisitionId","channel","slice","frame","position"); logger.fine(String.format("Inserted/Updated image: %s", image)); imageDao.reload(image, "acquisitionId","channel","slice","frame","position"); // Get the task record that should be eagerly dispatched. Task dispatchTask = tasks.get(label); if (dispatchTask == null) throw new RuntimeException(String.format( "No SlideImager task was created for image with label %s!", label)); // Store the Image ID as a Task Config variable TaskConfig imageId = new TaskConfig( new Integer(dispatchTask.getId()).toString(), "imageId", new Integer(image.getId()).toString()); taskConfigDao.insertOrUpdate(imageId,"id","key"); conf.put("imageId", imageId); logger.fine(String.format("Inserted/Updated imageId config: %s", imageId)); // eagerly run the Slide Imager task in order to dispatch downstream processing logger.fine(String.format("Eagerly dispatching sibling task: %s", dispatchTask)); SlideImager.this.workflowRunner.run(dispatchTask, conf); } }}).start(); } @Override public void imagingFinished(String path) { } }); // wait until the current acquisition finishes while (acqControlDlg.isAcquisitionRunning()) { try { Thread.sleep(1000); } catch (InterruptedException e) { // if the thread is interrupted, abort the acquisition. if (this.engine != null && this.engine.isAcquisitionRunning()) { logger.warning("Aborting the acquisition..."); //this.engine.abortRequest(); this.engine.stop(true); } } } // Get the ImageCache object for this acquisition MMAcquisition mmacquisition = acquisition.getAcquisition(acqDao); ImageCache imageCache = mmacquisition.getImageCache(); if (imageCache == null) throw new RuntimeException("MMAcquisition object was not initialized; imageCache is null!"); // Wait for the image cache to finish... while (!imageCache.isFinished()) { try { logger.info("Waiting for the ImageCache to finish..."); Thread.sleep(1000); } catch (InterruptedException e) { logger.warning("Thread was interrupted while waiting for the Image Cache to finish"); } } if (!imageCache.isFinished()) throw new RuntimeException("ImageCache is not finished!"); // Get the set of taggedImage labels from the acquisition Set<String> taggedImages = imageCache.imageKeys(); logger.info(String.format("Found %d taggedImages: %s", taggedImages.size(), taggedImages.toString())); // Make sure the set of acquisition image labels matches what we expected. if (!taggedImages.equals(tasks.keySet())) { throw new RuntimeException(String.format( "Error: Unexpected image set from acquisition! acquisition image count is %d, expected %d!%n"+ "From acquisition: %s%nFrom task config: %s", taggedImages.size(), totalImages, taggedImages, tasks.keySet())); } // Add any missing Image record for e.g. the acquisition task. This is also important because // the ImageListener above is added *after* the acquisition is started, so there's a chance // we may have missed the first few imageReceived events. This race condition is currently // unavoidable due to the way that MMAcquisition is implemented. Any remaining SlideImager tasks // that weren't eagerly dispatched will be dispatched normally by the workflowRunner after this // task completes. for (String label : taggedImages) { Task t = tasks.get(label); if (t == null) throw new RuntimeException(String.format( "Could not get task record for image with label %s!", label)); // Insert/Update image DB record int[] taggedImageKeys = MDUtils.getIndices(label); Image image = new Image(slideId, acquisition, taggedImageKeys[0], taggedImageKeys[1], taggedImageKeys[2], taggedImageKeys[3]); imageDao.insertOrUpdate(image,"acquisitionId","channel","slice","frame","position"); logger.fine(String.format("Inserted image: %s", image)); imageDao.reload(image, "acquisitionId","channel","slice","frame","position"); // Store the Image ID as a Task Config variable TaskConfig imageId = new TaskConfig( new Integer(t.getId()).toString(), "imageId", new Integer(image.getId()).toString()); taskConfigDao.insertOrUpdate(imageId,"id","key"); conf.put("imageId", imageId); logger.fine(String.format("Inserted/Updated imageId config: %s", imageId)); } } finally { EventManager.unregister(this); } } return Status.SUCCESS; } @Override public String getTitle() { return this.getClass().getName(); } @Override public String getDescription() { return this.getClass().getName(); } @Override public Configuration configure() { return new Configuration() { SlideImagerDialog slideImagerDialog = new SlideImagerDialog(acqControlDlg, SlideImager.this.workflowRunner); @Override public Config[] retrieve() { List<Config> configs = new ArrayList<Config>(); if (slideImagerDialog.acqSettingsText.getText().length()>0) { configs.add(new Config(moduleId, "acqSettingsFile", slideImagerDialog.acqSettingsText.getText())); } if (slideImagerDialog.posListText.getText().length()>0) { configs.add(new Config(moduleId, "posListFile", slideImagerDialog.posListText.getText())); } if (slideImagerDialog.moduleId.getSelectedIndex()>0) { configs.add(new Config(moduleId, "posListModuleId", slideImagerDialog.moduleId.getSelectedItem().toString())); } if (slideImagerDialog.dummyImageCount.getValue() != null) { configs.add(new Config(moduleId, "dummyImageCount", slideImagerDialog.dummyImageCount.getValue().toString())); } if (((Double)slideImagerDialog.minAutoFocus.getValue()).doubleValue() != 0.0) { configs.add(new Config(moduleId, "minAutoFocus", slideImagerDialog.minAutoFocus.getValue().toString())); } if (((Double)slideImagerDialog.maxAutoFocus.getValue()).doubleValue() != 0.0) { configs.add(new Config(moduleId, "maxAutoFocus", slideImagerDialog.maxAutoFocus.getValue().toString())); } return configs.toArray(new Config[0]); } @Override public Component display(Config[] configs) { Map<String,Config> conf = new HashMap<String,Config>(); for (Config config : configs) { conf.put(config.getKey(), config); } if (conf.containsKey("acqSettingsFile")) { Config acqDlgSettings = conf.get("acqSettingsFile"); slideImagerDialog.acqSettingsText.setText(acqDlgSettings.getValue()); } if (conf.containsKey("posListFile")) { Config posList = conf.get("posListFile"); slideImagerDialog.posListText.setText(posList.getValue()); } if (conf.containsKey("posListModuleId")) { Config posListModuleId = conf.get("posListModuleId"); slideImagerDialog.moduleId.setSelectedItem(posListModuleId.getValue()); } if (conf.containsKey("dummyImageCount")) { Config dummyImageCount = conf.get("dummyImageCount"); slideImagerDialog.dummyImageCount.setValue(new Integer(dummyImageCount.getValue())); } if (conf.containsKey("minAutoFocus")) { slideImagerDialog.minAutoFocus.setValue(new Double(conf.get("minAutoFocus").getValue())); } if (conf.containsKey("maxAutoFocus")) { slideImagerDialog.maxAutoFocus.setValue(new Double(conf.get("maxAutoFocus").getValue())); } return slideImagerDialog; } @Override public ValidationError[] validate() { List<ValidationError> errors = new ArrayList<ValidationError>(); File acqSettingsFile = new File(slideImagerDialog.acqSettingsText.getText()); if (!acqSettingsFile.exists()) { errors.add(new ValidationError(moduleId, "Acquisition settings file "+acqSettingsFile.toString()+" not found.")); } if (slideImagerDialog.posListText.getText().length()>0) { File posListFile = new File(slideImagerDialog.posListText.getText()); if (!posListFile.exists()) { errors.add(new ValidationError(moduleId, "Position list file "+posListFile.toString()+" not found.")); } } if (!((slideImagerDialog.posListText.getText().length()>0? 1: 0) + (slideImagerDialog.moduleId.getSelectedIndex()>0? 1: 0) == 1)) { errors.add(new ValidationError(moduleId, "You must enter one of either a position list file, or a position list name.")); } return errors.toArray(new ValidationError[0]); } }; } @Override public List<Task> createTaskRecords(List<Task> parentTasks) { Dao<Slide> slideDao = workflowRunner.getInstanceDb().table(Slide.class); Dao<SlidePosList> posListDao = workflowRunner.getInstanceDb().table(SlidePosList.class); Dao<SlidePos> posDao = workflowRunner.getInstanceDb().table(SlidePos.class); Dao<ModuleConfig> config = workflowRunner.getInstanceDb().table(ModuleConfig.class); Dao<TaskConfig> taskConfigDao = workflowRunner.getInstanceDb().table(TaskConfig.class); // Load all the module configuration into a HashMap Map<String,Config> conf = new HashMap<String,Config>(); for (ModuleConfig c : config.select(where("id",this.moduleId))) { conf.put(c.getKey(), c); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Using module config: %s", this.moduleId, c)); } // Create task records and connect to parent tasks // If no parent tasks were defined, then just create a single task instance. List<Task> tasks = new ArrayList<Task>(); for (Task parentTask : parentTasks.size()>0? parentTasks.toArray(new Task[0]) : new Task[] {null}) { workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Connecting parent task %s", this.moduleId, Util.escape(parentTask))); // get the parent task configuration Map<String,TaskConfig> parentTaskConf = new HashMap<String,TaskConfig>(); if (parentTask != null) { for (TaskConfig c : taskConfigDao.select(where("id",new Integer(parentTask.getId()).toString()))) { parentTaskConf.put(c.getKey(), c); workflowRunner.getLogger().info(String.format("%s: createTaskRecords: Using task config: %s", this.moduleId, c)); } } // Make sure this isn't a sentinel (dummy) task. The final slide loader task is only // used for putting the last slide back, and should have no child tasks. if (parentTask != null && (!parentTaskConf.containsKey("poolSlideId") || parentTaskConf.get("poolSlideId") == null)) { workflowRunner.getLogger().info(String.format( "%s: createTaskRecords: Task %d is a sentinel, not attaching child tasks", this.moduleId, parentTask.getId())); continue; } // Get the associated slide. Slide slide; if (parentTaskConf.containsKey("slideId")) { slide = slideDao.selectOneOrDie(where("id",new Integer(parentTaskConf.get("slideId").getValue()))); workflowRunner.getLogger().info(String.format("%s: createTaskRecords: Inherited slideId %s", this.moduleId, parentTaskConf.get("slideId"))); } // if posListModuleId is set, use the most recent slide else if (conf.containsKey("posListModuleId")) { List<Slide> slides = slideDao.select(); Collections.sort(slides, new Comparator<Slide>() { @Override public int compare(Slide a, Slide b) { return b.getId()-a.getId(); }}); if (slides.size() > 0) { slide = slides.get(0); } else { throw new RuntimeException("No slides were found!"); } } // If no associated slide is registered, create a slide to represent this task else { slide = new Slide(moduleId); slideDao.insertOrUpdate(slide,"experimentId"); slideDao.reload(slide, "experimentId"); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created new slide: %s", this.moduleId, slide.toString())); } conf.put("slideId", new Config(this.moduleId, "slideId", new Integer(slide.getId()).toString())); // get the position list for the slide SlidePosList posList = null; // first try to load a position list from the DB if (conf.containsKey("posListModuleId")) { // get a sorted list of all the SlidePosList records for the posListModuleId module Config posListModuleId = conf.get("posListModuleId"); List<SlidePosList> posLists = posListDao.select( where("slideId", slide.getId()). and("moduleId", posListModuleId.getValue())); Collections.sort(posLists, new Comparator<SlidePosList>() { @Override public int compare(SlidePosList a, SlidePosList b) { return a.getId()-b.getId(); }}); if (posLists.isEmpty()) { throw new RuntimeException("Position list from module \""+posListModuleId.getValue()+"\" not found in database"); } // Merge the list of PositionLists into a single positionList PositionList positionList = posLists.get(0).getPositionList(); for (int i=1; i<posLists.size(); ++i) { SlidePosList spl = posLists.get(i); PositionList pl = spl.getPositionList(); for (int j=0; j<pl.getNumberOfPositions(); ++j) { MultiStagePosition msp = pl.getPosition(j); positionList.addPosition(msp); } } posList = new SlidePosList(posLists.get(0).getModuleId(), posLists.get(0).getSlideId(), null, positionList); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Read position list from module %s", this.moduleId, conf.get("posListModuleId"))); } // otherwise, load a position list from a file else if (conf.containsKey("posListFile")) { Config posListConf = conf.get("posListFile"); File posListFile = new File(posListConf.getValue()); if (!posListFile.exists()) { throw new RuntimeException("Cannot find position list file "+posListFile.getPath()); } try { PositionList positionList = new PositionList(); positionList.load(posListFile.getPath()); posList = new SlidePosList(this.moduleId, slide.getId(), null, positionList); } catch (MMException e) {throw new RuntimeException(e);} workflowRunner.getLogger().info(String.format("%s: createTaskRecords: Read position list from file %s", this.moduleId, Util.escape(posListConf.getValue()))); // store the loaded position list in the DB posListDao.insertOrUpdate(posList,"moduleId","slideId"); posListDao.reload(posList,"moduleId","slideId"); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created/Updated posList: %s", this.moduleId, posList)); // delete any old record first posDao.delete(where("slidePosListId", posList.getId())); // then create new records MultiStagePosition[] msps = posList.getPositionList().getPositions(); for (int i=0; i<msps.length; ++i) { SlidePos slidePos = new SlidePos(posList.getId(), i); posDao.insert(slidePos); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Inserted slidePos at position %d: %s", this.moduleId, i, slidePos)); } } // Load the position list and set the acquisition settings loadPositionList(conf, workflowRunner.getLogger()); // get the total images VerboseSummary verboseSummary = getVerboseSummary(); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Verbose summary:%n%s%n", this.moduleId, verboseSummary.summary)); int totalImages = verboseSummary.channels * verboseSummary.slices * verboseSummary.frames * verboseSummary.positions; workflowRunner.getLogger().info(String.format("%s: getTotalImages: Will create %d images", this.moduleId, totalImages)); // Create the task records for (int c=0; c<verboseSummary.channels; ++c) { for (int s=0; s<verboseSummary.slices; ++s) { for (int f=0; f<verboseSummary.frames; ++f) { for (int p=0; p<verboseSummary.positions; ++p) { // Create task record Task task = new Task(moduleId, Status.NEW); workflowRunner.getTaskStatus().insert(task); tasks.add(task); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task record: %s", this.moduleId, task)); // Create taskConfig record to link task to position index in Position List TaskConfig imageLabel = new TaskConfig( new Integer(task.getId()).toString(), "imageLabel", MDUtils.generateLabel(c, s, f, p)); taskConfigDao.insert(imageLabel); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task config: %s", this.moduleId, imageLabel)); // create taskConfig record for the slide ID TaskConfig slideId = new TaskConfig( new Integer(task.getId()).toString(), "slideId", new Integer(slide.getId()).toString()); taskConfigDao.insert(slideId); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task config: %s", this.moduleId, slideId)); // Create task dispatch record if (parentTask != null) { TaskDispatch dispatch = new TaskDispatch(task.getId(), parentTask.getId()); workflowRunner.getTaskDispatch().insert(dispatch); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task dispatch record: %s", this.moduleId, dispatch)); } } } } } } return tasks; } public static class VerboseSummary { public String summary; public int frames; public int positions; public int slices; public int channels; public int totalImages; public String totalMemory; public String duration; public String[] order; } /** * Parse the verbose summary text returned by the AcqusitionWrapperEngine. * Sadly, this is the only way to get some needed information since the getNumSlices(), etc. * methods are private. * @return the VerboseSummary object */ public VerboseSummary getVerboseSummary() { String summary = this.engine.getVerboseSummary(); VerboseSummary verboseSummary = new VerboseSummary(); verboseSummary.summary = summary; Pattern pattern = Pattern.compile("^Number of time points: ([0-9]+)$", Pattern.MULTILINE); Matcher matcher = pattern.matcher(summary); if (!matcher.find()) throw new RuntimeException(String.format( "Could not parse frames field from summary:%n%s", summary)); verboseSummary.frames = new Integer(matcher.group(1)); pattern = Pattern.compile("^Number of positions: ([0-9]+)$", Pattern.MULTILINE); matcher = pattern.matcher(summary); if (!matcher.find()) throw new RuntimeException(String.format( "Could not parse positions field from summary:%n%s", summary)); verboseSummary.positions = new Integer(matcher.group(1)); pattern = Pattern.compile("^Number of slices: ([0-9]+)$", Pattern.MULTILINE); matcher = pattern.matcher(summary); if (!matcher.find()) throw new RuntimeException(String.format( "Could not parse slices field from summary:%n%s", summary)); verboseSummary.slices = new Integer(matcher.group(1)); pattern = Pattern.compile("^Number of channels: ([0-9]+)$", Pattern.MULTILINE); matcher = pattern.matcher(summary); if (!matcher.find()) throw new RuntimeException(String.format( "Could not parse channels field from summary:%n%s", summary)); verboseSummary.channels = new Integer(matcher.group(1)); pattern = Pattern.compile("^Total images: ([0-9]+)$", Pattern.MULTILINE); matcher = pattern.matcher(summary); if (!matcher.find()) throw new RuntimeException(String.format( "Could not parse total images field from summary:%n%s", summary)); verboseSummary.totalImages = new Integer(matcher.group(1)); pattern = Pattern.compile("^Total memory: ([^\\n]+)$", Pattern.MULTILINE); matcher = pattern.matcher(summary); if (!matcher.find()) throw new RuntimeException(String.format( "Could not parse total memory field from summary:%n%s", summary)); verboseSummary.totalMemory = matcher.group(1).trim(); pattern = Pattern.compile("^Duration: ([^\\n]+)$", Pattern.MULTILINE); matcher = pattern.matcher(summary); if (!matcher.find()) throw new RuntimeException(String.format( "Could not parse duration field from summary:%n%s", summary)); verboseSummary.duration = matcher.group(1).trim(); pattern = Pattern.compile("^Order: ([^\\n]+)$", Pattern.MULTILINE); matcher = pattern.matcher(summary); if (matcher.find()) { verboseSummary.order = matcher.group(1).trim().split(",\\s*"); } else { this.workflowRunner.getLogger().info(String.format( "Could not parse order field from summary:%n%s", summary)); } return verboseSummary; } @Override public TaskType getTaskType() { return Module.TaskType.SERIAL; } @Override public void cleanup(Task task) { } @Override public List<ImageLogRecord> logImages(final Task task, final Map<String,Config> config, final Logger logger) { List<ImageLogRecord> imageLogRecords = new ArrayList<ImageLogRecord>(); // Add an image logger instance to the workflow runner for this module imageLogRecords.add(new ImageLogRecord(task.getName(), task.getName(), new FutureTask<ImageLogRunner>(new Callable<ImageLogRunner>() { @Override public ImageLogRunner call() throws Exception { // Get the Image record Config imageIdConf = config.get("imageId"); if (imageIdConf != null) { Integer imageId = new Integer(imageIdConf.getValue()); logger.info(String.format("Using image ID: %d", imageId)); Dao<Image> imageDao = workflowRunner.getInstanceDb().table(Image.class); final Image image = imageDao.selectOneOrDie(where("id",imageId)); logger.info(String.format("Using image: %s", image)); // Initialize the acquisition Dao<Acquisition> acqDao = workflowRunner.getInstanceDb().table(Acquisition.class); Acquisition acquisition = acqDao.selectOneOrDie(where("id",image.getAcquisitionId())); logger.info(String.format("Using acquisition: %s", acquisition)); MMAcquisition mmacquisition = acquisition.getAcquisition(acqDao); // Get the image cache object ImageCache imageCache = mmacquisition.getImageCache(); if (imageCache == null) throw new RuntimeException("Acquisition was not initialized; imageCache is null!"); // Get the tagged image from the image cache TaggedImage taggedImage = image.getImage(imageCache); logger.info(String.format("Got taggedImage from ImageCache: %s", taggedImage)); ImageLogRunner imageLogRunner = new ImageLogRunner(task.getName()); imageLogRunner.addImage(taggedImage, "The image"); return imageLogRunner; } return null; } }))); return imageLogRecords; } @Override public void runIntialize() { } }
package com.mebigfatguy.fbcontrib.detect; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.bcel.Repository; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.CodeException; import org.apache.bcel.classfile.JavaClass; import com.mebigfatguy.fbcontrib.utils.OpcodeUtils; import com.mebigfatguy.fbcontrib.utils.ToString; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.ba.ClassContext; /** * looks for try/finally blocks that manage resources, without using try-with-resources */ public class UseTryWithResources extends BytecodeScanningDetector { enum State { SEEN_NOTHING, SEEN_IFNULL, SEEN_ALOAD }; private JavaClass autoCloseableClass; private BugReporter bugReporter; private OpcodeStack stack; private Map<Integer, TryBlock> finallyBlocks; private Map<Integer, Integer> regStoredPCs; private int lastGotoPC; private int lastNullCheckedReg; private State state; public UseTryWithResources(BugReporter bugReporter) { this.bugReporter = bugReporter; try { autoCloseableClass = Repository.lookupClass("java/lang/AutoCloseable"); } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } } @Override public void visitClassContext(ClassContext classContext) { try { int majorVersion = classContext.getJavaClass().getMajor(); if (majorVersion >= MAJOR_1_7) { stack = new OpcodeStack(); finallyBlocks = new HashMap<>(); regStoredPCs = new HashMap<>(); super.visitClassContext(classContext); } } finally { stack = null; finallyBlocks = null; regStoredPCs = null; } } @Override public void visitCode(Code obj) { if (prescreen(obj)) { stack.resetForMethodEntry(this); regStoredPCs.clear(); lastGotoPC = -1; state = State.SEEN_NOTHING; lastNullCheckedReg = -1; super.visitCode(obj); } } @Override public void sawOpcode(int seen) { try { int pc = getPC(); Iterator<TryBlock> it = finallyBlocks.values().iterator(); while (it.hasNext()) { TryBlock tb = it.next(); if (tb.getHandlerEndPC() < pc) { it.remove(); } } TryBlock tb = finallyBlocks.get(pc); if (tb != null) { if (lastGotoPC > -1) { tb.setHandlerEndPC(lastGotoPC); } } if (OpcodeUtils.isAStore(seen)) { regStoredPCs.put(Integer.valueOf(getRegisterOperand()), Integer.valueOf(pc)); } switch (state) { case SEEN_NOTHING: if ((seen == IFNULL) && (stack.getStackDepth() >= 1)) { OpcodeStack.Item itm = stack.getStackItem(0); lastNullCheckedReg = itm.getRegisterNumber(); state = lastNullCheckedReg >= 0 ? State.SEEN_IFNULL : State.SEEN_NOTHING; } else { lastNullCheckedReg = -1; } break; case SEEN_IFNULL: if (OpcodeUtils.isALoad(seen)) { if (lastNullCheckedReg == getRegisterOperand()) { state = State.SEEN_ALOAD; } else { state = State.SEEN_NOTHING; lastNullCheckedReg = -1; } } break; case SEEN_ALOAD: if ((seen == INVOKEVIRTUAL) || (seen == INVOKEINTERFACE)) { if ("close".equals(getNameConstantOperand()) && ("()V".equals(getSigConstantOperand()))) { JavaClass cls = Repository.lookupClass(getClassConstantOperand()); if (cls.implementationOf(autoCloseableClass)) { tb = findEnclosingFinally(pc); if (tb != null) { if (stack.getStackDepth() > 0) { OpcodeStack.Item itm = stack.getStackItem(0); int closeableReg = itm.getRegisterNumber(); if (closeableReg >= 0) { Integer storePC = regStoredPCs.get(closeableReg); if (storePC != null) { if (storePC <= tb.getStartPC()) { // save this location off } } } } } // wait to see if addSuppressedException is called } } } state = State.SEEN_NOTHING; lastNullCheckedReg = -1; break; } lastGotoPC = (((seen == GOTO) || (seen == GOTO_W)) && (getBranchOffset() > 0)) ? getBranchTarget() : -1; } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } finally { stack.sawOpcode(this, seen); } } private boolean prescreen(Code obj) { finallyBlocks.clear(); CodeException[] ces = obj.getExceptionTable(); if ((ces == null) || (ces.length == 0)) { return false; } boolean hasFinally = false; for (CodeException ce : ces) { if (ce.getCatchType() == 0) { finallyBlocks.put(Integer.valueOf(ce.getHandlerPC()), new TryBlock(ce.getStartPC(), ce.getEndPC(), ce.getHandlerPC())); hasFinally = true; } } return hasFinally; } private TryBlock findEnclosingFinally(int pc) { if (finallyBlocks.isEmpty()) { return null; } TryBlock deepest = null; for (TryBlock tb : finallyBlocks.values()) { int handlerPC = tb.getHandlerPC(); if ((deepest == null) || ((handlerPC <= pc) && (deepest.getHandlerPC() < handlerPC))) { deepest = tb; } } return deepest; } @Override public String toString() { return ToString.build(this); } static class TryBlock { private int startPC; private int endPC; private int handlerPC; private int handlerEndPC; public TryBlock(int startPC, int endPC, int handlerPC) { super(); this.startPC = startPC; this.endPC = endPC; this.handlerPC = handlerPC; this.handlerEndPC = Integer.MAX_VALUE; } public int getHandlerEndPC() { return handlerEndPC; } public void setHandlerEndPC(int handlerEndPC) { this.handlerEndPC = handlerEndPC; } public int getStartPC() { return startPC; } public int getEndPC() { return endPC; } public int getHandlerPC() { return handlerPC; } @Override public String toString() { return ToString.build(this); } } }
package com.qmetry.qaf.automation.testng.report; import static com.qmetry.qaf.automation.core.ConfigurationManager.getBundle; import static com.qmetry.qaf.automation.util.JSONUtil.getJsonObjectFromFile; import static com.qmetry.qaf.automation.util.JSONUtil.writeJsonObjectToFile; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import org.apache.commons.configuration.Configuration; import org.apache.commons.logging.Log; import org.apache.commons.logging.impl.LogFactoryImpl; import org.testng.ISuite; import org.testng.ISuiteResult; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.annotations.Test; import org.testng.xml.XmlTest; import com.qmetry.qaf.automation.core.CheckpointResultBean; import com.qmetry.qaf.automation.core.ConfigurationManager; import com.qmetry.qaf.automation.core.LoggingBean; import com.qmetry.qaf.automation.keys.ApplicationProperties; import com.qmetry.qaf.automation.step.client.TestNGScenario; import com.qmetry.qaf.automation.testng.RetryAnalyzer; import com.qmetry.qaf.automation.util.DateUtil; import com.qmetry.qaf.automation.util.FileUtil; import com.qmetry.qaf.automation.util.StringUtil; /** * com.qmetry.qaf.automation.testng.report.ReporterUtil.java * * @author chirag.jayswal */ public class ReporterUtil { private static final Log logger = LogFactoryImpl.getLog(ReporterUtil.class); public static void updateMetaInfo(ISuite suite) { createMetaInfo(suite, false); } public static void createMetaInfo(ISuite suite) { createMetaInfo(suite, true); } private static void createMetaInfo(ISuite suite, boolean listEntry) { List<XmlTest> tests = suite.getXmlSuite().getTests(); List<String> testNames = new ArrayList<String>(); for (XmlTest test : tests) { testNames.add(getTestName(test.getName())); } String dir = ApplicationProperties.JSON_REPORT_DIR.getStringVal(); Report report = new Report(); if (!getBundle().containsKey("suit.start.ts")) { dir = ApplicationProperties.JSON_REPORT_DIR .getStringVal(ApplicationProperties.JSON_REPORT_ROOT_DIR.getStringVal( "test-results") + "/" + DateUtil.getDate(0, "EdMMMyy_hhmma")); getBundle().setProperty(ApplicationProperties.JSON_REPORT_DIR.key, dir); FileUtil.checkCreateDir(ApplicationProperties.JSON_REPORT_ROOT_DIR .getStringVal("test-results")); FileUtil.checkCreateDir(dir); getBundle().setProperty("suit.start.ts", System.currentTimeMillis()); } else { report.setEndTime(System.currentTimeMillis()); } report.setName(suite.getName()); report.setTests(testNames); report.setDir(dir); int pass = 0, fail = 0, skip = 0, total = 0; Iterator<ISuiteResult> iter = suite.getResults().values().iterator(); while (iter.hasNext()) { ITestContext context = iter.next().getTestContext(); pass += getPassCnt(context); skip += getSkipCnt(context); fail += getFailCnt(context) + getFailWithPassPerCnt(context); total += getTotal(context); } report.setPass(pass); report.setFail(fail); report.setSkip(skip); report.setTotal((pass + fail + skip) > total ? pass + fail + skip : total); report.setStatus(fail > 0 ? "fail" : pass > 0 ? "pass" : "unstable"); report.setStartTime(getBundle().getLong("suit.start.ts", 0)); appendReportInfo(report); if (listEntry) { ReportEntry reportEntry = new ReportEntry(); reportEntry.setName(suite.getName()); reportEntry.setStartTime(getBundle().getLong("suit.start.ts", 0)); reportEntry.setDir(dir); appendMetaInfo(reportEntry); } } public static synchronized void updateOverview(ITestContext context, ITestResult result) { try { String file = ApplicationProperties.JSON_REPORT_DIR.getStringVal() + "/" + getTestName(context) + "/overview.json"; TestOverview overview = getJsonObjectFromFile(file, TestOverview.class); if (null == result) { Map<String, Object> runPrams = new HashMap<String, Object>( context.getCurrentXmlTest().getAllParameters()); Configuration env = getBundle().subset("env"); Iterator<?> iter = env.getKeys(); while (iter.hasNext()) { String key = (String) iter.next(); runPrams.put(key, env.getString(key)); } Map<String, Object> envInfo = new HashMap<String, Object>(); envInfo.put("isfw-build-info", getBundle().getObject("isfw.build.info")); envInfo.put("run-parameters", runPrams); envInfo.put("browser-desired-capabilities", getBundle().getObject("driver.desiredCapabilities")); envInfo.put("browser-actual-capabilities", getActualCapabilities()); overview.setEnvInfo(envInfo); Map<String, Object> executionEnvInfo = new HashMap<String, Object>(); executionEnvInfo.put("os.name", System.getProperty("os.name")); executionEnvInfo.put("os.version", System.getProperty("os.version")); executionEnvInfo.put("os.arch", System.getProperty("os.arch")); executionEnvInfo.put("java.version", System.getProperty("java.version")); executionEnvInfo.put("java.vendor", System.getProperty("java.vendor")); executionEnvInfo.put("java.arch", System.getProperty("sun.arch.data.model")); executionEnvInfo.put("user.name", System.getProperty("user.name")); try { executionEnvInfo.put("host", InetAddress.getLocalHost().getHostName()); } catch (Exception e) { // This code added for MAC to fetch hostname String hostname = execHostName("hostname"); executionEnvInfo.put("host", hostname); } envInfo.put("execution-env-info", executionEnvInfo); } int pass = getPassCnt(context); int fail = getFailCnt(context) + getFailWithPassPerCnt(context); int skip = getSkipCnt(context); int total = getTotal(context); overview.setTotal(total > (pass + fail + skip) ? total : pass + fail + skip); overview.setPass(pass); overview.setSkip(skip); overview.setFail(fail); if (null != result) { overview.getClasses().add(result.getTestClass().getName()); } if ((overview.getStartTime() > 0)) { overview.setEndTime(System.currentTimeMillis()); } else { overview.setStartTime(System.currentTimeMillis()); } writeJsonObjectToFile(file, overview); updateMetaInfo(context.getSuite()); } catch (Exception e) { logger.debug(e); } } private static Map<String, String> getActualCapabilities() { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) getBundle().getObject("driver.actualCapabilities"); Map<String, String> newMap = new HashMap<String, String>(); if (null != map) { for (String key : map.keySet()) { try { newMap.put(key, String.valueOf(map.get(key))); } catch (Exception e) { } } } return newMap; } /** * should be called on test method completion * * @param context * @param result */ public static void createMethodResult(ITestContext context, ITestResult result, List<LoggingBean> logs, List<CheckpointResultBean> checkpoints) { try { String dir = getClassDir(context, result); MethodResult methodResult = new MethodResult(); methodResult.setSeleniumLog(logs); methodResult.setCheckPoints(checkpoints); methodResult.setThrowable(result.getThrowable()); updateOverview(context, result); String fileName = getMethodName(result); String methodResultFile = dir + "/" + fileName; File f = new File(methodResultFile + ".json"); if (f.exists()) { // if file already exists then it will append some random // character as suffix fileName += StringUtil.getRandomString("aaaaaaaaaa"); // add updated file name as 'resultFileName' key in metaData methodResultFile = dir + "/" + fileName; updateClassMetaInfo(context, result, fileName); } else { updateClassMetaInfo(context, result, ""); } writeJsonObjectToFile(methodResultFile + ".json", methodResult); } catch (Exception e) { logger.warn(e.getMessage(), e); } } /** * should be called on test method completion * * @param context * @param result */ private static synchronized void updateClassMetaInfo(ITestContext context, ITestResult result, String methodfname) { String dir = getClassDir(context, result); String file = dir + "/meta-info.json"; FileUtil.checkCreateDir(dir); ClassInfo classInfo = getJsonObjectFromFile(file, ClassInfo.class); MethodInfo methodInfo = new MethodInfo(); methodInfo.setStartTime(result.getStartMillis()); methodInfo.setDuration(result.getEndMillis() - result.getStartMillis()); if (result.getStatus() == ITestResult.SUCCESS_PERCENTAGE_FAILURE) { // methodResult.setPassPer(result.getMethod().getCurrentInvocationCount()) } Map<String, Object> metadata; if (result.getMethod().isTest()) { methodInfo.setIndex(result.getMethod().getCurrentInvocationCount()); int retryCount = getBundle().getInt(RetryAnalyzer.RETRY_INVOCATION_COUNT, 0); if (retryCount > 0) { methodInfo.setRetryCount(retryCount); } methodInfo.setArgs(result.getParameters()); if (result.getMethod() instanceof TestNGScenario) { TestNGScenario scenario = (TestNGScenario) result.getMethod(); metadata = scenario.getMetaData(); metadata.put("description", scenario.getDescription()); metadata.put("groups", scenario.getGroups()); } else { String desc = ApplicationProperties.CURRENT_TEST_DESCRIPTION .getStringVal(result.getMethod().getDescription()); metadata = new HashMap<String, Object>(); metadata.put("groups", result.getMethod().getGroups()); metadata.put("description", desc); } metadata.put("name", getMethodName(result)); methodInfo.setMetaData(metadata); getBundle().clearProperty(ApplicationProperties.CURRENT_TEST_DESCRIPTION.key); Test test = result.getMethod().getConstructorOrMethod().getMethod() .getAnnotation(Test.class); if (((test.dependsOnMethods() != null) && (test.dependsOnMethods().length > 0)) || ((test.dependsOnGroups() != null) && (test.dependsOnGroups().length > 0))) { String[] depends = {"Methods: " + Arrays.toString(test.dependsOnMethods()), "Groups: " + Arrays.toString(test.dependsOnGroups())}; methodInfo.setDependsOn(depends); } methodInfo.setType("test"); } else { // config method String name = getMethodName(result); logger.debug("config method: " + name); metadata = new HashMap<String, Object>(); metadata.put("groups", result.getMethod().getGroups()); metadata.put("description", result.getMethod().getDescription()); metadata.put("name", name); methodInfo.setMetaData(metadata); methodInfo.setType("config"); } methodInfo.setResult(getResult(result.getStatus())); if (StringUtil.isNotBlank(methodfname)) { metadata.put("resultFileName", methodfname); } if (!classInfo.getMethods().contains(methodInfo)) { logger.debug("method: result: " + methodInfo.getResult() + " groups: " + methodInfo.getMetaData()); classInfo.getMethods().add(methodInfo); writeJsonObjectToFile(file, classInfo); } else { logger.warn("methodInfo already wrritten for " + methodInfo.getName()); } } private static String getMethodName(ITestResult result) { return result.getName(); } private static String getClassDir(ITestContext context, ITestResult result) { String testName = getTestName(context); return ApplicationProperties.JSON_REPORT_DIR.getStringVal() + "/" + testName + "/" + result.getTestClass().getName(); } private static void appendReportInfo(Report report) { String file = report.getDir() + "/meta-info.json"; writeJsonObjectToFile(file, report); } private static void appendMetaInfo(ReportEntry report) { String file = ApplicationProperties.JSON_REPORT_ROOT_DIR.getStringVal("test-results") + "/meta-info.json"; MetaInfo metaInfo = getJsonObjectFromFile(file, MetaInfo.class); metaInfo.getReports().remove(report); metaInfo.getReports().add(report); writeJsonObjectToFile(file, metaInfo); } private static String getResult(int res) { switch (res) { case ITestResult.SUCCESS : return "pass"; case ITestResult.FAILURE : return "fail"; case ITestResult.SKIP : return "skip"; case ITestResult.SUCCESS_PERCENTAGE_FAILURE : return "pass"; default : return ""; } } private static String getTestName(ITestContext context) { if (context == null) { context = (ITestContext) ConfigurationManager.getBundle() .getObject(ApplicationProperties.CURRENT_TEST_CONTEXT.key); } return getTestName(context.getName()); } private static int getPassCnt(ITestContext context) { if ((context != null) && (context.getPassedTests() != null)) { if (context.getPassedTests().getAllResults() != null) { return context.getPassedTests().getAllResults().size(); } return context.getPassedTests().size(); } return 0; } private static int getFailCnt(ITestContext context) { int failCnt = 0; if ((context != null) && (context.getFailedTests() != null)) { Collection<ITestNGMethod> allFailedTests = context.getFailedTests().getAllMethods(); // get unique failed test methods Set<ITestNGMethod> set = new HashSet<ITestNGMethod>(allFailedTests); if (ApplicationProperties.RETRY_CNT.getIntVal(0) > 0) set.removeAll(context.getPassedTests().getAllMethods()); Iterator<ITestNGMethod> iter = set.iterator(); while (iter.hasNext()) { ITestNGMethod m = iter.next(); // get failed invocations (remove duplicate because of retry) // for data driven, in case not data driven test invocations // will be 0 Set<Integer> invocationNumbers = new HashSet<Integer>(m.getFailedInvocationNumbers()); int invocatons = invocationNumbers.size(); failCnt += invocatons > 0 ? invocatons : 1; } } return failCnt; } private static int getFailWithPassPerCnt(ITestContext context) { if ((context != null) && (context.getFailedButWithinSuccessPercentageTests() != null)) { if (context.getFailedButWithinSuccessPercentageTests() .getAllResults() != null) { return context.getFailedButWithinSuccessPercentageTests().getAllResults() .size(); } return context.getFailedButWithinSuccessPercentageTests().size(); } return 0; } private static int getSkipCnt(ITestContext context) { if ((context != null) && (context.getSkippedTests() != null)) { if (context.getSkippedTests().getAllResults() != null) { return context.getSkippedTests().getAllResults().size(); } return context.getSkippedTests().size(); } return 0; } private static int getTotal(ITestContext context) { return (context == null) || (null == context.getAllTestMethods()) ? 0 : context.getAllTestMethods().length; } private static String getTestName(String testname) { return StringUtil.isBlank(testname) ? "" : testname.replaceAll("[^a-zA-Z0-9_]+", ""); } public static String execHostName(String execCommand) { InputStream stream; Scanner s; try { Process proc = Runtime.getRuntime().exec(execCommand); stream = proc.getInputStream(); if (stream != null) { s = new Scanner(stream); s.useDelimiter("\\A"); String val = s.hasNext() ? s.next() : ""; stream.close(); s.close(); return val; } } catch (IOException ioException) { ioException.printStackTrace(); } return ""; } }
package com.redhat.ceylon.compiler.typechecker.analyzer; import static com.redhat.ceylon.compiler.typechecker.model.Util.intersectionType; import static com.redhat.ceylon.compiler.typechecker.model.Util.isNamed; import static com.redhat.ceylon.compiler.typechecker.model.Util.isTypeUnknown; import static com.redhat.ceylon.compiler.typechecker.model.Util.producedType; import static com.redhat.ceylon.compiler.typechecker.model.Util.unionType; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.redhat.ceylon.compiler.typechecker.model.Annotation; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.Constructor; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Interface; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ProducedReference; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeAlias; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.Message; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.TypeArgumentList; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; /** * Bucket for some helper methods used by various * visitors. * * @author Gavin King * */ public class Util { static TypedDeclaration getTypedMember(TypeDeclaration d, String name, List<ProducedType> signature, boolean ellipsis, Unit unit) { Declaration member = d.getMember(name, unit, signature, ellipsis); if (member instanceof TypedDeclaration) { return (TypedDeclaration) member; } else { return null; } } static TypeDeclaration getTypeMember(TypeDeclaration d, String name, List<ProducedType> signature, boolean ellipsis, Unit unit) { Declaration member = d.getMember(name, unit, signature, ellipsis); if (member instanceof TypeDeclaration) { return (TypeDeclaration) member; } else if (member instanceof TypedDeclaration) { return anonymousType(name, member); } else { return null; } } static TypedDeclaration getTypedDeclaration(Scope scope, String name, List<ProducedType> signature, boolean ellipsis, Unit unit) { Declaration result = scope.getMemberOrParameter(unit, name, signature, ellipsis); if (result instanceof TypedDeclaration) { return (TypedDeclaration) result; } else { return null; } } static TypeDeclaration getTypeDeclaration(Scope scope, String name, List<ProducedType> signature, boolean ellipsis, Unit unit) { Declaration result = scope.getMemberOrParameter(unit, name, signature, ellipsis); if (result instanceof TypeDeclaration) { return (TypeDeclaration) result; } else if (result instanceof TypedDeclaration) { return anonymousType(name, result); } else { return null; } } static TypedDeclaration getPackageTypedDeclaration(String name, List<ProducedType> signature, boolean ellipsis, Unit unit) { Declaration result = unit.getPackage().getMember(name, signature, ellipsis); if (result instanceof TypedDeclaration) { return (TypedDeclaration) result; } else { return null; } } static TypeDeclaration getPackageTypeDeclaration(String name, List<ProducedType> signature, boolean ellipsis, Unit unit) { Declaration result = unit.getPackage().getMember(name, signature, ellipsis); if (result instanceof TypeDeclaration) { return (TypeDeclaration) result; } else if (result instanceof TypedDeclaration) { return anonymousType(name, result); } else { return null; } } public static TypeDeclaration anonymousType(String name, Declaration result) { ProducedType type = ((TypedDeclaration) result).getType(); if (type!=null) { TypeDeclaration typeDeclaration = type.getDeclaration(); if (typeDeclaration instanceof Class && typeDeclaration.isAnonymous() && isNamed(name,typeDeclaration)) { return typeDeclaration; } } return null; } static List<ProducedType> getTypeArguments(Tree.TypeArguments tas, List<TypeParameter> typeParameters, ProducedType qt) { if (tas instanceof Tree.TypeArgumentList) { List<ProducedType> typeArguments = new ArrayList<ProducedType>(typeParameters.size()); Map<TypeParameter, ProducedType> typeArgMap = new HashMap<TypeParameter, ProducedType>(); if (qt!=null) { typeArgMap.putAll(qt.getTypeArguments()); } if (tas instanceof Tree.TypeArgumentList) { TypeArgumentList tal = (Tree.TypeArgumentList) tas; List<Tree.Type> types = tal.getTypes(); for (int i=0; i<types.size(); i++) { ProducedType t = types.get(i).getTypeModel(); if (t==null) { typeArguments.add(null); } else { typeArguments.add(t); if (i<typeParameters.size()) { typeArgMap.put(typeParameters.get(i), t); } } } } else { List<ProducedType> types = tas.getTypeModels(); for (int i=0; i<types.size(); i++) { ProducedType t = types.get(i); if (t==null) { typeArguments.add(null); } else { typeArguments.add(t); if (i<typeParameters.size()) { typeArgMap.put(typeParameters.get(i), t); } } } } for (int i=typeArguments.size(); i<typeParameters.size(); i++) { TypeParameter tp = typeParameters.get(i); ProducedType dta = tp.getDefaultTypeArgument(); if (dta==null || //necessary to prevent stack overflow //default type argument dta.containsDeclaration(tp.getDeclaration())) { break; } else { ProducedType da = dta.substitute(typeArgMap); typeArguments.add(da); typeArgMap.put(tp, da); } } return typeArguments; } else { return Collections.<ProducedType>emptyList(); } } /*static List<ProducedType> getParameterTypes(Tree.ParameterTypes pts) { if (pts==null) return null; List<ProducedType> typeArguments = new ArrayList<ProducedType>(); for (Tree.SimpleType st: pts.getSimpleTypes()) { ProducedType t = st.getTypeModel(); if (t==null) { st.addError("could not resolve parameter type"); typeArguments.add(null); } else { typeArguments.add(t); } } return typeArguments; }*/ public static Tree.Statement getLastExecutableStatement(Tree.ClassBody that) { List<Tree.Statement> statements = that.getStatements(); Unit unit = that.getUnit(); for (int i=statements.size()-1; i>=0; i Tree.Statement s = statements.get(i); if (isExecutableStatement(unit, s) || s instanceof Tree.Constructor) { return s; } } return null; } static boolean isExecutableStatement(Unit unit, Tree.Statement s) { if (s instanceof Tree.SpecifierStatement) { //shortcut refinement statements with => aren't really "executable" Tree.SpecifierStatement ss = (Tree.SpecifierStatement) s; return !(ss.getSpecifierExpression() instanceof Tree.LazySpecifierExpression) || !ss.getRefinement(); } else if (s instanceof Tree.ExecutableStatement) { return true; } else { if (s instanceof Tree.AttributeDeclaration) { Tree.AttributeDeclaration ad = (Tree.AttributeDeclaration) s; Tree.SpecifierOrInitializerExpression sie = ad.getSpecifierOrInitializerExpression(); return sie!=null && !(sie instanceof Tree.LazySpecifierExpression); } /*else if (s instanceof Tree.MethodDeclaration) { if ( ((Tree.MethodDeclaration) s).getSpecifierExpression()!=null ) { return s; } }*/ else if (s instanceof Tree.ObjectDefinition) { Tree.ObjectDefinition o = (Tree.ObjectDefinition) s; if (o.getExtendedType()!=null) { ProducedType et = o.getExtendedType().getType().getTypeModel(); if (et!=null && !et.getDeclaration().equals(unit.getObjectDeclaration()) && !et.getDeclaration().equals(unit.getBasicDeclaration())) { return true; } } if (o.getClassBody()!=null) { if (getLastExecutableStatement(o.getClassBody())!=null) { return true; } } return false; } else { return false; } } } private static String message(ProducedType type, String problem, ProducedType otherType, Unit unit) { String unknownTypeError = type.getFirstUnknownTypeError(true); String typeName = type.getProducedTypeName(unit); String otherTypeName = otherType.getProducedTypeName(unit); if (otherTypeName.equals(typeName)) { typeName = type.getProducedTypeQualifiedName(); otherTypeName = otherType.getProducedTypeQualifiedName(); } return ": '" + typeName + "'" + problem + "'" + otherTypeName + "'" + (unknownTypeError != null ? ": " + unknownTypeError : ""); } private static String message(ProducedType type, String problem, Unit unit) { String typeName = type.getProducedTypeName(unit); return ": '" + typeName + "'" + problem; } static boolean checkCallable(ProducedType type, Node node, String message) { Unit unit = node.getUnit(); if (isTypeUnknown(type)) { addTypeUnknownError(node, type, message); return false; } else if (!unit.isCallableType(type)) { if (!hasError(node)) { String extra = message(type, " is not a subtype of 'Callable'", unit); if (node instanceof Tree.StaticMemberOrTypeExpression) { Tree.StaticMemberOrTypeExpression smte = (Tree.StaticMemberOrTypeExpression) node; Declaration d = smte.getDeclaration(); String name = d.getName(); if (d instanceof Interface) { extra = ": '" + name + "' is an interface"; } else if (d instanceof TypeAlias) { extra = ": '" + name + "' is a type alias"; } else if (d instanceof TypeParameter) { extra = ": '" + name + "' is a type parameter"; } else if (d instanceof Value) { extra = ": value '" + name + "' has type '" + type.getProducedTypeName(unit) + "' which is not a subtype of 'Callable'"; } } node.addError(message + extra); } return false; } else { return true; } } static ProducedType checkSupertype(ProducedType type, TypeDeclaration td, Node node, String message) { if (isTypeUnknown(type)) { addTypeUnknownError(node, type, message); return null; } else { ProducedType supertype = type.getSupertype(td); if (supertype==null) { node.addError(message + message(type, " is not a subtype of '" + td.getName() + "'", node.getUnit())); } return supertype; } } static void checkAssignable(ProducedType type, ProducedType supertype, Node node, String message) { if (isTypeUnknown(type)) { addTypeUnknownError(node, type, message); } else if (isTypeUnknown(supertype)) { addTypeUnknownError(node, supertype, message); } else if (!type.isSubtypeOf(supertype)) { node.addError(message + message(type, " is not assignable to ", supertype, node.getUnit())); } } static void checkAssignableWithWarning(ProducedType type, ProducedType supertype, Node node, String message) { if (isTypeUnknown(type)) { addTypeUnknownError(node, type, message); } else if (isTypeUnknown(supertype)) { addTypeUnknownError(node, supertype, message); } else if (!type.isSubtypeOf(supertype)) { node.addUnsupportedError(message + message(type, " is not assignable to ", supertype, node.getUnit())); } } static void checkAssignableToOneOf(ProducedType type, ProducedType supertype1, ProducedType supertype2, Node node, String message, int code) { if (isTypeUnknown(type)) { addTypeUnknownError(node, type, message); } else if (isTypeUnknown(supertype1)) { addTypeUnknownError(node, supertype1, message); } else if (isTypeUnknown(supertype2)) { addTypeUnknownError(node, supertype2, message); } else if (!type.isSubtypeOf(supertype1) && !type.isSubtypeOf(supertype2)) { node.addError(message + message(type, " is not assignable to ", supertype1, node.getUnit()), code); } } static void checkAssignable(ProducedType type, ProducedType supertype, Node node, String message, int code) { if (isTypeUnknown(type)) { addTypeUnknownError(node, type, message); } else if (isTypeUnknown(supertype)) { addTypeUnknownError(node, supertype, message); } else if (!type.isSubtypeOf(supertype)) { node.addError(message + message(type, " is not assignable to ", supertype, node.getUnit()), code); } } /*static void checkAssignable(ProducedType type, ProducedType supertype, TypeDeclaration td, Node node, String message) { if (isTypeUnknown(type) || isTypeUnknown(supertype)) { addTypeUnknownError(node, message); } else if (!type.isSubtypeOf(supertype)) { node.addError(message + message(type, " is not assignable to ", supertype, node.getUnit())); } }*/ static void checkIsExactly(ProducedType type, ProducedType supertype, Node node, String message) { if (isTypeUnknown(type)) { addTypeUnknownError(node, type, message); } else if (isTypeUnknown(supertype)) { addTypeUnknownError(node, supertype, message); } else if (!type.isExactly(supertype)) { node.addError(message + message(type, " is not exactly ", supertype, node.getUnit())); } } static void checkIsExactly(ProducedType type, ProducedType supertype, Node node, String message, int code) { if (isTypeUnknown(type)) { addTypeUnknownError(node, type, message); } else if (isTypeUnknown(supertype)) { addTypeUnknownError(node, supertype, message); } else if (!type.isExactly(supertype)) { node.addError(message + message(type, " is not exactly ", supertype, node.getUnit()), code); } } static void checkIsExactlyOneOf(ProducedType type, ProducedType supertype1, ProducedType supertype2, Node node, String message) { if (isTypeUnknown(type)) { addTypeUnknownError(node, type, message); } else if (isTypeUnknown(supertype1)) { addTypeUnknownError(node, supertype1, message); } else if (isTypeUnknown(supertype2)) { addTypeUnknownError(node, supertype2, message); } else if (!type.isExactly(supertype1) && !type.isExactly(supertype2)) { node.addError(message + message(type, " is not exactly ", supertype1, node.getUnit())); } } public static boolean hasErrorOrWarning(Node node) { return hasError(node, true); } public static boolean hasError(Node node) { return hasError(node, false); } static boolean hasError(Node node, final boolean includeWarnings) { // we use an exception to get out of the visitor // as fast as possible when an error is found // TODO: wtf?! because it's the common case that // a node has an error? that's just silly @SuppressWarnings("serial") class ErrorFoundException extends RuntimeException {} class ErrorVisitor extends Visitor { @Override public void handleException(Exception e, Node that) { if (e instanceof ErrorFoundException) { throw (ErrorFoundException) e; } super.handleException(e, that); } @Override public void visitAny(Node that) { if (that.getErrors().isEmpty()) { super.visitAny(that); } else if (includeWarnings) { throw new ErrorFoundException(); } else { // UsageWarning don't count as errors for (Message error: that.getErrors()) { if (!(error instanceof UsageWarning)) { // get out fast throw new ErrorFoundException(); } } // no real error, proceed super.visitAny(that); } } } ErrorVisitor ev = new ErrorVisitor(); try { node.visit(ev); return false; } catch (ErrorFoundException x) { return true; } } private static void addTypeUnknownError(Node node, ProducedType type, String message) { if (!hasError(node)) { node.addError(message + ": type cannot be determined" + getTypeUnknownError(type)); } } public static String getTypeUnknownError(ProducedType type) { if(type == null) return ""; String error = type.getFirstUnknownTypeError(); return error != null ? ": " + error : ""; } public static void buildAnnotations(Tree.AnnotationList al, List<Annotation> annotations) { if (al!=null) { Tree.AnonymousAnnotation aa = al.getAnonymousAnnotation(); if (aa!=null) { Annotation ann = new Annotation(); ann.setName("doc"); String text = aa.getStringLiteral().getText(); ann.addPositionalArgment(text); annotations.add(ann); } for (Tree.Annotation a: al.getAnnotations()) { Annotation ann = new Annotation(); Tree.BaseMemberExpression bma = (Tree.BaseMemberExpression) a.getPrimary(); String name = bma.getIdentifier().getText(); ann.setName(name); Tree.NamedArgumentList nal = a.getNamedArgumentList(); if (nal!=null) { for (Tree.NamedArgument na: nal.getNamedArguments()) { if (na instanceof Tree.SpecifiedArgument) { Tree.SpecifiedArgument sa = (Tree.SpecifiedArgument) na; Tree.SpecifierExpression sie = sa.getSpecifierExpression(); Tree.Expression e = sie.getExpression(); if (e!=null) { Tree.Term t = e.getTerm(); Parameter p = sa.getParameter(); if (p!=null) { String text = toString(t); if (text!=null) { ann.addNamedArgument(p.getName(), text); } } } } } } Tree.PositionalArgumentList pal = a.getPositionalArgumentList(); if (pal!=null) { for (Tree.PositionalArgument pa: pal.getPositionalArguments()) { if (pa instanceof Tree.ListedArgument) { Tree.ListedArgument la = (Tree.ListedArgument) pa; Tree.Term t = la.getExpression().getTerm(); String text = toString(t); if (text!=null) { ann.addPositionalArgment(text); } } } } annotations.add(ann); } } } private static String toString(Tree.Term t) { if (t instanceof Tree.Literal) { return ((Tree.Literal) t).getText(); } else if (t instanceof Tree.StaticMemberOrTypeExpression) { Tree.StaticMemberOrTypeExpression mte = (Tree.StaticMemberOrTypeExpression) t; String id = mte.getIdentifier().getText(); if (mte instanceof Tree.QualifiedMemberOrTypeExpression) { Tree.QualifiedMemberOrTypeExpression qmte = (Tree.QualifiedMemberOrTypeExpression) mte; Tree.Primary p = qmte.getPrimary(); if (p instanceof Tree.StaticMemberOrTypeExpression) { Tree.StaticMemberOrTypeExpression smte = (Tree.StaticMemberOrTypeExpression) p; return toString(smte) + '.' + id; } return null; } else { return id; } } else if (t instanceof Tree.TypeLiteral) { Tree.TypeLiteral tl = (Tree.TypeLiteral) t; Tree.StaticType type = tl.getType(); if (type!=null) { return toString(type); } return null; } else if (t instanceof Tree.MemberLiteral) { Tree.MemberLiteral ml = (Tree.MemberLiteral) t; Tree.Identifier id = ml.getIdentifier(); Tree.StaticType type = ml.getType(); if (type!=null) { String qualifier = toString(type); if (qualifier!=null && id!=null) { return qualifier + "." + id.getText(); } return null; } return id.getText(); } else if (t instanceof Tree.ModuleLiteral) { Tree.ModuleLiteral ml = (Tree.ModuleLiteral) t; return "module " + toString(ml.getImportPath()); } else if (t instanceof Tree.PackageLiteral) { Tree.PackageLiteral pl = (Tree.PackageLiteral) t; return "package " + toString(pl.getImportPath()); } else { return null; } } private static String toString(Tree.ImportPath importPath) { StringBuilder sb = new StringBuilder(); if (importPath.getIdentifiers() != null) { for (Tree.Identifier identifier : importPath.getIdentifiers()) { if (sb.length() != 0) { sb.append("."); } sb.append(identifier.getText()); } } return sb.toString(); } private static String toString(Tree.StaticType type) { // FIXME: we're discarding syntactic types and union/intersection types if (type instanceof Tree.BaseType){ Tree.BaseType bt = (Tree.BaseType) type; return bt.getIdentifier().getText(); } else if(type instanceof Tree.QualifiedType) { Tree.QualifiedType qt = (Tree.QualifiedType) type; String qualifier = toString(qt.getOuterType()); if(qualifier != null) { Tree.SimpleType st = (Tree.SimpleType) type; return qualifier + "." + st.getIdentifier().getText(); } return null; } return null; } static boolean inLanguageModule(Unit unit) { return unit.getPackage() .getQualifiedNameString() .startsWith(Module.LANGUAGE_MODULE_NAME); } static String typeDescription(TypeDeclaration td, Unit unit) { String name = td.getName(); if (td instanceof TypeParameter) { Declaration container = (Declaration) td.getContainer(); return "type parameter '" + name + "' of '" + container.getName(unit) + "'"; } else { return "type '" + name + "'"; } } static String typeNamesAsIntersection( List<ProducedType> upperBounds, Unit unit) { if (upperBounds.isEmpty()) { return "Anything"; } StringBuilder sb = new StringBuilder(); for (ProducedType st: upperBounds) { sb.append(st.getProducedTypeName(unit)).append(" & "); } if (sb.toString().endsWith(" & ")) { sb.setLength(sb.length()-3); } return sb.toString(); } public static Tree.Term eliminateParensAndWidening(Tree.Term term) { while (term instanceof Tree.OfOp || term instanceof Tree.Expression) { if (term instanceof Tree.OfOp) { term = ((Tree.OfOp) term).getTerm(); } else if (term instanceof Tree.Expression) { term = ((Tree.Expression) term).getTerm(); } } return term; } static boolean isAlwaysSatisfied(Tree.ConditionList cl) { if (cl==null) return false; for (Tree.Condition c: cl.getConditions()) { if (c instanceof Tree.BooleanCondition) { Tree.BooleanCondition bc = (Tree.BooleanCondition) c; Tree.Expression ex = bc.getExpression(); if (ex!=null) { Tree.Term t = ex.getTerm(); //TODO: eliminate parens //TODO: take into account conjunctions/disjunctions if (t instanceof Tree.BaseMemberExpression) { Tree.BaseMemberExpression bme = (Tree.BaseMemberExpression) t; Declaration d = bme.getDeclaration(); if (isBooleanTrue(d)) { continue; } } } } return false; } return true; } public static boolean isBooleanTrue(Declaration d) { return d!=null && d.getQualifiedNameString() .equals("ceylon.language::true"); } public static boolean isBooleanFalse(Declaration d) { return d!=null && d.getQualifiedNameString() .equals("ceylon.language::false"); } static boolean isNeverSatisfied(Tree.ConditionList cl) { if (cl==null) return false; for (Tree.Condition c: cl.getConditions()) { if (c instanceof Tree.BooleanCondition) { Tree.BooleanCondition bc = (Tree.BooleanCondition) c; Tree.Expression ex = bc.getExpression(); if (ex!=null) { Tree.Term t = ex.getTerm(); //TODO: eliminate parens //TODO: take into account conjunctions/disjunctions if (t instanceof Tree.BaseMemberExpression) { Tree.BaseMemberExpression bme = (Tree.BaseMemberExpression) t; Declaration d = bme.getDeclaration(); if (isBooleanFalse(d)) { return true; } } } } } return false; } static boolean isAtLeastOne(Tree.ForClause forClause) { Tree.ForIterator fi = forClause.getForIterator(); if (fi!=null) { Tree.SpecifierExpression se = fi.getSpecifierExpression(); if (se!=null) { Tree.Expression e = se.getExpression(); if (e!=null) { Unit unit = forClause.getUnit(); ProducedType at = unit.getAnythingDeclaration().getType(); ProducedType neit = unit.getNonemptyIterableType(at); ProducedType t = e.getTypeModel(); return t!=null && t.isSubtypeOf(neit); } } } return false; } static boolean declaredInPackage(Declaration dec, Unit unit) { return dec.getUnit().getPackage().equals(unit.getPackage()); } public static Tree.Term unwrapExpressionUntilTerm(Tree.Term term){ while (term instanceof Tree.Expression) { term = ((Tree.Expression)term).getTerm(); } return term; } public static boolean isIndirectInvocation(Tree.InvocationExpression that) { return isIndirectInvocation(that.getPrimary()); } private static boolean isIndirectInvocation(Tree.Primary primary) { Tree.Term p = unwrapExpressionUntilTerm(primary); if (p instanceof Tree.MemberOrTypeExpression) { Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) p; return isIndirectInvocation(mte); } else { return true; } } private static boolean isIndirectInvocation(Tree.MemberOrTypeExpression that) { ProducedReference prf = that.getTarget(); if (prf==null) { return true; } else { Declaration d = prf.getDeclaration(); if (!prf.isFunctional() || //type parameters are not really callable //even though they are Functional d instanceof TypeParameter) { return true; } if (that.getStaticMethodReference()) { if (d.isStaticallyImportable() || d instanceof Constructor) { Tree.QualifiedMemberOrTypeExpression qmte = (Tree.QualifiedMemberOrTypeExpression) that; return isIndirectInvocation(qmte.getPrimary()); } else { return true; } } return false; } } public static boolean isInstantiationExpression(Tree.Expression e) { Tree.Term term = e.getTerm(); if (term instanceof Tree.InvocationExpression) { Tree.InvocationExpression ie = (Tree.InvocationExpression) term; Tree.Primary p = ie.getPrimary(); if (p instanceof Tree.BaseTypeExpression || p instanceof Tree.QualifiedTypeExpression) { return true; } } return false; } public static boolean hasErrors(Tree.Declaration d) { class DeclarationErrorVisitor extends Visitor { boolean foundError; @Override public void visitAny(Node that) { super.visitAny(that); if (!that.getErrors().isEmpty()) { foundError = true; } } @Override public void visit(Tree.Body that) {} } DeclarationErrorVisitor dev = new DeclarationErrorVisitor(); d.visit(dev); return dev.foundError; } public static boolean hasErrors(Tree.TypedArgument d) { class ArgErrorVisitor extends Visitor { boolean foundError; @Override public void visitAny(Node that) { super.visitAny(that); if (!that.getErrors().isEmpty()) { foundError = true; } } @Override public void visit(Tree.Body that) {} } ArgErrorVisitor dev = new ArgErrorVisitor(); d.visit(dev); return dev.foundError; } public static boolean hasErrors(Tree.Body d) { class BodyErrorVisitor extends Visitor { boolean foundError; @Override public void visitAny(Node that) { super.visitAny(that); if (!that.getErrors().isEmpty()) { foundError = true; } } @Override public void visit(Tree.Declaration that) {} } BodyErrorVisitor bev = new BodyErrorVisitor(); d.visit(bev); return bev.foundError; } static String message(Declaration dec) { String qualifier; Scope container = dec.getContainer(); if (container instanceof Declaration) { String name = ((Declaration) container).getName(); qualifier = " in '" + name + "'"; } else { qualifier = ""; } return "'" + dec.getName() + "'" + qualifier; } public static Node getParameterTypeErrorNode(Tree.Parameter p) { if (p instanceof Tree.ParameterDeclaration) { Tree.ParameterDeclaration pd = (Tree.ParameterDeclaration) p; return pd.getTypedDeclaration().getType(); } else { return p; } } public static Node getTypeErrorNode(Node that) { if (that instanceof Tree.TypedDeclaration) { Tree.TypedDeclaration td = (Tree.TypedDeclaration) that; Tree.Type type = td.getType(); if (type!=null) { return type; } } if (that instanceof Tree.TypedArgument) { Tree.TypedArgument ta = (Tree.TypedArgument) that; Tree.Type type = ta.getType(); if (type!=null) { return type; } } if (that instanceof Tree.FunctionArgument) { Tree.FunctionArgument fa = (Tree.FunctionArgument) that; Tree.Type type = fa.getType(); if (type!=null && type.getToken()!=null) { return type; } } return that; } static void checkIsExactlyForInterop(Unit unit, boolean isCeylon, ProducedType parameterType, ProducedType refinedParameterType, Node node, String message) { if (isCeylon) { // it must be a Ceylon method checkIsExactly(parameterType, refinedParameterType, node, message, 9200); } else { // we're refining a Java method ProducedType refinedDefiniteType = unit.getDefiniteType(refinedParameterType); checkIsExactlyOneOf(parameterType, refinedParameterType, refinedDefiniteType, node, message); } } public static ProducedType getTupleType(List<Tree.PositionalArgument> es, Unit unit, boolean requireSequential) { ProducedType result = unit.getType(unit.getEmptyDeclaration()); ProducedType ut = unit.getNothingDeclaration().getType(); for (int i=es.size()-1; i>=0; i Tree.PositionalArgument a = es.get(i); ProducedType t = a.getTypeModel(); if (t!=null) { ProducedType et = t; //unit.denotableType(t); if (a instanceof Tree.SpreadArgument) { /*if (requireSequential) { checkSpreadArgumentSequential((Tree.SpreadArgument) a, et); }*/ ut = unit.getIteratedType(et); result = spreadType(et, unit, requireSequential); } else if (a instanceof Tree.Comprehension) { ut = et; Tree.Comprehension c = (Tree.Comprehension) a; Tree.InitialComprehensionClause icc = c.getInitialComprehensionClause(); result = icc.getPossiblyEmpty() ? unit.getSequentialType(et) : unit.getSequenceType(et); if (!requireSequential) { ProducedType it = producedType(unit.getIterableDeclaration(), et, icc.getFirstTypeModel()); result = intersectionType(result, it, unit); } } else { ut = unionType(ut, et, unit); result = producedType(unit.getTupleDeclaration(), ut, et, result); } } } return result; } public static ProducedType spreadType(ProducedType et, Unit unit, boolean requireSequential) { if (et==null) return null; if (requireSequential) { if (unit.isSequentialType(et)) { //if (et.getDeclaration() instanceof TypeParameter) { return et; /*} else { // if it's already a subtype of Sequential, erase // out extraneous information, like that it is a // String, just keeping information about what // kind of tuple it is List<ProducedType> elementTypes = unit.getTupleElementTypes(et); boolean variadic = unit.isTupleLengthUnbounded(et); boolean atLeastOne = unit.isTupleVariantAtLeastOne(et); int minimumLength = unit.getTupleMinimumLength(et); if (variadic) { ProducedType spt = elementTypes.get(elementTypes.size()-1); elementTypes.set(elementTypes.size()-1, unit.getIteratedType(spt)); } return unit.getTupleType(elementTypes, variadic, atLeastOne, minimumLength); }*/ } else { // transform any Iterable into a Sequence without // losing the information that it is nonempty, in // the case that we know that for sure ProducedType it = unit.getIteratedType(et); ProducedType st = unit.isNonemptyIterableType(et) ? unit.getSequenceType(it) : unit.getSequentialType(it); // unless this is a tuple constructor, remember // the original Iterable type arguments, to // account for the possibility that the argument // to Absent is a type parameter //return intersectionType(et.getSupertype(unit.getIterableDeclaration()), st, unit); // for now, just return the sequential type: return st; } } else { return et; } } static boolean isSelfReference(Tree.Primary that) { return that instanceof Tree.This || that instanceof Tree.Outer; } static boolean isEffectivelyBaseMemberExpression(Tree.Term term) { return term instanceof Tree.BaseMemberExpression || term instanceof Tree.QualifiedMemberExpression && isSelfReference(((Tree.QualifiedMemberExpression) term) .getPrimary()); } }
package org.jitsi.android.gui.chat; import java.util.*; import android.app.*; import android.content.*; import android.graphics.drawable.*; import android.os.*; import android.text.*; import android.text.ClipboardManager; import android.text.method.*; import android.view.*; import android.widget.*; import android.widget.LinearLayout.*; import net.java.sip.communicator.service.contactlist.*; import net.java.sip.communicator.service.globaldisplaydetails.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.service.protocol.globalstatus.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.util.Logger; import org.jitsi.*; import org.jitsi.android.*; import org.jitsi.android.gui.*; import org.jitsi.android.gui.contactlist.*; import org.jitsi.android.gui.util.*; import org.jitsi.service.osgi.*; /** * The <tt>ChatFragment</tt> is responsible for chat interface. * * @author Yana Stamcheva * @author Pawel Domas */ public class ChatFragment extends OSGiFragment { /** * The logger */ private static final Logger logger = Logger.getLogger(ChatFragment.class); /** * The session adapter for the contained <tt>ChatSession</tt>. */ private ChatListAdapter chatListAdapter; /** * The corresponding <tt>ChatSession</tt>. */ private ChatSession chatSession; /** * The chat list view representing the chat. */ private ListView chatListView; /** * The chat typing view. */ private LinearLayout typingView; /** * The task that loads history. */ private LoadHistoryTask loadHistoryTask; /** * Indicates that this fragment is visible to the user. * This is important, because of PagerAdapter being used on phone layouts, * which doesn't properly call onResume() when switched page fragment is * displayed. */ private boolean visibleToUser = false; /** * The chat controller used to handle operations like editing and sending * messages used by this fragment. */ private ChatController chatController; /** * Returns the corresponding <tt>ChatSession</tt>. * * @return the corresponding <tt>ChatSession</tt> */ public ChatSession getChatSession() { return chatSession; } /** * Returns the underlying chat list view. * * @return the underlying chat list view */ public ListView getChatListView() { return chatListView; } /** * Returns the underlying chat list view. * * @return the underlying chat list view */ public ChatListAdapter getChatListAdapter() { return chatListAdapter; } /** * {@inheritDoc} */ @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View content = inflater.inflate( R.layout.chat_conversation, container, false); chatListAdapter = new ChatListAdapter(); chatListView = (ListView) content.findViewById(R.id.chatListView); // Registers for chat message context menu registerForContextMenu(chatListView); typingView = (LinearLayout) content.findViewById(R.id.typingView); chatListView.setAdapter(chatListAdapter); chatListView.setSelector(R.drawable.contact_list_selector); // Chat intent handling Bundle arguments = getArguments(); String chatId = arguments.getString(ChatSessionManager.CHAT_IDENTIFIER); if(chatId == null) throw new IllegalArgumentException(); chatSession = ChatSessionManager.getActiveChat(chatId); return content; } /** * {@inheritDoc} */ @Override public void onAttach(Activity activity) { super.onAttach(activity); this.chatController = new ChatController(activity, this); } /** * This method must be called by parent <tt>Activity</tt> or * <tt>Fragment</tt> in order to register the chat controller. * * @param isVisible <tt>true</tt> if the fragment is now visible to * the user. * @see ChatController */ public void setVisibleToUser(boolean isVisible) { logger.debug("View visible to user: " + hashCode()+" "+isVisible); this.visibleToUser = isVisible; checkInitController(); } /** * Checks for <tt>ChatController</tt> initialization. To init the controller * fragment must be visible and it's View must be created. * * If fragment is no longer visible the controller will be uninitialized. */ private void checkInitController() { if(visibleToUser && chatListView != null) { logger.debug("Init controller: "+hashCode()); chatController.onShow(); } else if(!visibleToUser) { chatController.onHide(); } else { logger.debug("Skipping controller init... " + hashCode()); } } /** * Initializes the chat list adapter. */ private void initAdapter() { loadHistoryTask = new LoadHistoryTask(); loadHistoryTask.execute(); } @Override public void onResume() { super.onResume(); initAdapter(); // If added to the pager adapter for the first time it is required // to check again, because it's marked visible when the Views // are not created yet checkInitController(); chatSession.addMessageListener(chatListAdapter); chatSession.addContactStatusListener(chatListAdapter); chatSession.addTypingListener(chatListAdapter); } @Override public void onPause() { chatSession.removeMessageListener(chatListAdapter); chatSession.removeContactStatusListener(chatListAdapter); chatSession.removeTypingListener(chatListAdapter); /* * Indicates that this fragment is no longer visible, * because of this call parent <tt>Activities don't have to call it * in onPause(). */ setVisibleToUser(false); super.onPause(); } /** * {@inheritDoc} */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v,menuInfo); // Creates chat message context menu getActivity().getMenuInflater().inflate(R.menu.chat_msg_ctx_menu, menu); } /** * {@inheritDoc} */ @Override public boolean onContextItemSelected(MenuItem item) { if(item.getItemId() == R.id.copy_to_clipboard) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); // Gets clicked message ChatMessage clickedMsg = chatListAdapter.getMessage(info.position); // Copy message content to clipboard ClipboardManager clipboardManager = (ClipboardManager) getActivity() .getSystemService(Context.CLIPBOARD_SERVICE); clipboardManager.setText(clickedMsg.getContentForClipboard()); return true; } return super.onContextItemSelected(item); } /** * Creates new parametrized instance of <tt>CallContactFragment</tt>. * * @param chatId optional phone number that will be filled. * @return new parametrized instance of <tt>CallContactFragment</tt>. */ public static ChatFragment newInstance(String chatId) { if (logger.isDebugEnabled()) logger.debug("CHAT FRAGMENT NEW INSTANCE: " + chatId); ChatFragment chatFragment = new ChatFragment(); Bundle args = new Bundle(); args.putString(ChatSessionManager.CHAT_IDENTIFIER, chatId); chatFragment.setArguments(args); return chatFragment; } public void onDetach() { if (logger.isDebugEnabled()) logger.debug("DETACH CHAT FRAGMENT: " + this); super.onDetach(); chatListAdapter = null; if (loadHistoryTask != null) { loadHistoryTask.cancel(true); loadHistoryTask = null; } } class ChatListAdapter extends BaseAdapter implements ChatSession.ChatSessionListener, ContactPresenceStatusListener, TypingNotificationsListener { /** * The list of chat message displays. */ private final List<MessageDisplay> messages = new ArrayList<MessageDisplay>(); /** * The type of the incoming message view. */ final int INCOMING_MESSAGE_VIEW = 0; /** * The type of the outgoing message view. */ final int OUTGOING_MESSAGE_VIEW = 1; /** * The type of the system message view. */ final int SYSTEM_MESSAGE_VIEW = 2; /** * The type of the error message view. */ final int ERROR_MESSAGE_VIEW = 3; /** * HTML image getter. */ private final Html.ImageGetter imageGetter = new HtmlImageGetter(); /** * Passes the message to the contained <code>ChatConversationPanel</code> * for processing and appends it at the end of the conversationPanel * document. * */ public void addMessage( ChatMessage newMessage, boolean update) { synchronized (messages) { int lastMsgIdx = getLastMessageIdx(newMessage); ChatMessage lastMsg = lastMsgIdx != -1 ? chatListAdapter.getMessage(lastMsgIdx) : null; if(lastMsg == null || !lastMsg.isConsecutiveMessage(newMessage)) { messages.add(new MessageDisplay(newMessage)); } else { // Merge the message and update the object in the list messages.get(lastMsgIdx) .update(lastMsg.mergeMessage(newMessage)); } } if(update) dataChanged(); } /** * Finds index of the message that will handle <tt>newMessage</tt> * merging process(usually just the last one). If the * <tt>newMessage</tt> is a correction message, then the last message * of the same type will be returned. * * @param newMessage the next message to be merged into the adapter. * * @return index of the message that will handle <tt>newMessage</tt> * merging process. If <tt>newMessage</tt> is a correction message, * then the last message of the same type will be returned. */ private int getLastMessageIdx(ChatMessage newMessage) { // If it's not a correction message then jus return the last one if(newMessage.getCorrectedMessageUID() == null) return chatListAdapter.getCount()-1; // Search for the same type int msgType = newMessage.getMessageType(); for(int i=getCount()-1; i>= 0; i { ChatMessage candidate = getMessage(i); if(candidate.getMessageType() == msgType) { return i; } } return -1; } /** * {@inheritDoc} */ public int getCount() { synchronized (messages) { return messages.size(); } } /** * {@inheritDoc} */ public Object getItem(int position) { synchronized (messages) { if (logger.isDebugEnabled()) logger.debug("OBTAIN CHAT ITEM ON POSITION: " + position); return messages.get(position); } } ChatMessage getMessage(int pos) { return ((MessageDisplay) getItem(pos)).msg; } MessageDisplay getMessageDisplay(int pos) { return (MessageDisplay) getItem(pos); } /** * {@inheritDoc} */ public long getItemId(int pos) { return pos; } public int getViewTypeCount() { return 4; } public int getItemViewType(int position) { ChatMessage message = getMessage(position); int messageType = message.getMessageType(); if (messageType == ChatMessage.INCOMING_MESSAGE) return INCOMING_MESSAGE_VIEW; else if (messageType == ChatMessage.OUTGOING_MESSAGE) return OUTGOING_MESSAGE_VIEW; else if (messageType == ChatMessage.SYSTEM_MESSAGE) return SYSTEM_MESSAGE_VIEW; else if(messageType == ChatMessage.ERROR_MESSAGE) return ERROR_MESSAGE_VIEW; return 0; } /** * {@inheritDoc} */ public View getView(int position, View convertView, ViewGroup parent) { // Keeps reference to avoid future findViewById() MessageViewHolder messageViewHolder; if (convertView == null) { LayoutInflater inflater = getActivity().getLayoutInflater(); messageViewHolder = new MessageViewHolder(); int viewType = getItemViewType(position); messageViewHolder.viewType = viewType; if (viewType == INCOMING_MESSAGE_VIEW) { convertView = inflater.inflate( R.layout.chat_incoming_row, parent, false); messageViewHolder.avatarView = (ImageView) convertView.findViewById( R.id.incomingAvatarIcon); messageViewHolder.statusView = (ImageView) convertView.findViewById( R.id.incomingStatusIcon); messageViewHolder.messageView = (TextView) convertView.findViewById( R.id.incomingMessageView); messageViewHolder.timeView = (TextView) convertView.findViewById( R.id.incomingTimeView); messageViewHolder.typingView = (ImageView) convertView.findViewById( R.id.typingImageView); } else if(viewType == OUTGOING_MESSAGE_VIEW) { convertView = inflater.inflate( R.layout.chat_outgoing_row, parent, false); messageViewHolder.avatarView = (ImageView) convertView.findViewById( R.id.outgoingAvatarIcon); messageViewHolder.statusView = (ImageView) convertView.findViewById( R.id.outgoingStatusIcon); messageViewHolder.messageView = (TextView) convertView.findViewById( R.id.outgoingMessageView); messageViewHolder.timeView = (TextView) convertView.findViewById( R.id.outgoingTimeView); } else { // System or error view convertView = inflater.inflate( viewType == SYSTEM_MESSAGE_VIEW ? R.layout.chat_system_row : R.layout.chat_error_row, parent, false); messageViewHolder.messageView = (TextView) convertView.findViewById( R.id.messageView); } convertView.setTag(messageViewHolder); } else { messageViewHolder = (MessageViewHolder) convertView.getTag(); } MessageDisplay message = getMessageDisplay(position); if (message != null) { if(messageViewHolder.viewType == INCOMING_MESSAGE_VIEW || messageViewHolder.viewType == OUTGOING_MESSAGE_VIEW) { Drawable avatar = null; Drawable status = null; if (messageViewHolder.viewType == INCOMING_MESSAGE_VIEW) { avatar = ContactListAdapter.getAvatarDrawable( chatSession.getMetaContact()); status = ContactListAdapter.getStatusDrawable( chatSession.getMetaContact()); } else if (messageViewHolder.viewType == OUTGOING_MESSAGE_VIEW) { avatar = getLocalAvatarDrawable(); status = getLocalStatusDrawable(); } setAvatar(messageViewHolder.avatarView, avatar); setStatus(messageViewHolder.statusView, status); messageViewHolder.timeView.setText(message.getDateStr()); } messageViewHolder.messageView.setText(message.getBody()); // Html links are handled only for system messages, which is // currently used for displaying OTR authentication dialog. // Otherwise settings movement method prevent form firing // on item clicked events. int currentMsgType = message.msg.getMessageType(); if(messageViewHolder.msgType != currentMsgType) { MovementMethod movementMethod = null; if(currentMsgType == ChatMessage.SYSTEM_MESSAGE) { movementMethod = LinkMovementMethod.getInstance(); } messageViewHolder .messageView .setMovementMethod(movementMethod); } } return convertView; } private void dataChanged() { runOnUiThread(new Runnable() { public void run() { notifyDataSetChanged(); } }); } @Override public void messageDelivered(final MessageDeliveredEvent evt) { final Contact contact = evt.getDestinationContact(); final MetaContact metaContact = AndroidGUIActivator.getContactListService() .findMetaContactByContact(contact); if (logger.isTraceEnabled()) logger.trace("MESSAGE DELIVERED to contact: " + contact.getAddress()); if (metaContact != null && chatSession.getMetaContact().equals(metaContact)) { final ChatMessageImpl msg = ChatMessageImpl.getMsgForEvent(evt); if (logger.isTraceEnabled()) logger.trace( "MESSAGE DELIVERED: process message to chat for contact: " + contact.getAddress() + " MESSAGE: " + msg.getMessage()); addMessage(msg, true); } } @Override public void messageDeliveryFailed(MessageDeliveryFailedEvent arg0) { // Do nothing, handled in ChatSession } @Override public void messageReceived(final MessageReceivedEvent evt) { if (logger.isTraceEnabled()) logger.trace("MESSAGE RECEIVED from contact: " + evt.getSourceContact().getAddress()); final Contact protocolContact = evt.getSourceContact(); final MetaContact metaContact = AndroidGUIActivator.getContactListService() .findMetaContactByContact(protocolContact); if(metaContact != null && chatSession.getMetaContact().equals(metaContact)) { final ChatMessageImpl msg = ChatMessageImpl.getMsgForEvent(evt); addMessage(msg, true); } else { if (logger.isTraceEnabled()) logger.trace("MetaContact not found for protocol contact: " + protocolContact + "."); } } @Override public void messageAdded(ChatMessage msg) { addMessage(msg, true); } /** * Indicates a contact has changed its status. */ @Override public void contactPresenceStatusChanged( ContactPresenceStatusChangeEvent evt) { Contact sourceContact = evt.getSourceContact(); if (logger.isDebugEnabled()) logger.debug("Contact presence status changed: " + sourceContact.getAddress()); if (!chatSession.getMetaContact().containsContact(sourceContact)) return; new UpdateStatusTask().execute(); } @Override public void typingNotificationDeliveryFailed( TypingNotificationEvent evt) { } @Override public void typingNotificationReceived(TypingNotificationEvent evt) { if (logger.isDebugEnabled()) logger.debug("Typing notification received: " + evt.getSourceContact().getAddress()); TypingNotificationHandler .handleTypingNotificationReceived(evt, ChatFragment.this); } /** * Removes all messages from the adapter */ public void removeAllMessages() { messages.clear(); } /** * Class used to cache processed message contents. Prevents from * re-processing on each View display. */ class MessageDisplay { /** * Displayed <tt>ChatMessage</tt> */ private ChatMessage msg; /** * Date string cache */ private String dateStr; /** * Message body cache */ private Spanned body; /** * Creates new instance of <tt>MessageDisplay</tt> that will be used * for displaying given <tt>ChatMessage</tt>. * * @param msg the <tt>ChatMessage</tt> that will be displayed by * this instance. */ MessageDisplay(ChatMessage msg) { this.msg = msg; } /** * Returns formatted date string for the <tt>ChatMessage</tt>. * @return formatted date string for the <tt>ChatMessage</tt>. */ public String getDateStr() { if(dateStr == null) { dateStr = GuiUtils.formatTime(msg.getDate()); } return dateStr; } /** * Returns <tt>Spanned</tt> message body processed for HTML tags. * @return <tt>Spanned</tt> message body. */ public Spanned getBody() { if(body == null) { body = Html.fromHtml(msg.getMessage(), imageGetter, null); } return body; } /** * Updates this display instance with new message causing display * contents to be invalidated. * @param chatMessage new message content */ public void update(ChatMessage chatMessage) { dateStr = null; body = null; msg = chatMessage; } } } static class MessageViewHolder { ImageView avatarView; ImageView statusView; ImageView typeIndicator; TextView messageView; TextView timeView; ImageView typingView; int viewType; int position; int msgType; } /** * Loads the history in an asynchronous thread and then adds the history * messages to the user interface. */ private class LoadHistoryTask extends AsyncTask<Void, Void, Collection<ChatMessage>> { @Override protected Collection<ChatMessage> doInBackground(Void... params) { return chatSession.getHistory(); } @Override protected void onPostExecute(Collection<ChatMessage> result) { super.onPostExecute(result); chatListAdapter.removeAllMessages(); Iterator<ChatMessage> iterator = result.iterator(); while (iterator.hasNext()) { chatListAdapter.addMessage(iterator.next(), false); } chatListAdapter.dataChanged(); } } /** * Updates the status user interface. */ private class UpdateStatusTask extends AsyncTask<Void, Void, Void> { protected Void doInBackground(Void... params) { return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); for (int i = 0; i <= chatListView.getLastVisiblePosition(); i++) { RelativeLayout chatRowView = (RelativeLayout) chatListView.getChildAt( i - chatListView.getFirstVisiblePosition()); if (chatRowView != null && chatListAdapter.getItemViewType(i) == chatListAdapter.INCOMING_MESSAGE_VIEW) { Drawable status = ContactListAdapter .getStatusDrawable( chatSession.getMetaContact()); ImageView statusView = (ImageView) chatRowView .findViewById(R.id.incomingStatusIcon); setStatus(statusView, status); } } } } /** * Returns the local user avatar drawable. * * @return the local user avatar drawable */ private static Drawable getLocalAvatarDrawable() { GlobalDisplayDetailsService displayDetailsService = AndroidGUIActivator.getGlobalDisplayDetailsService(); byte[] avatarImage = displayDetailsService.getGlobalDisplayAvatar(); if (avatarImage != null) return AndroidImageUtil.drawableFromBytes(avatarImage); return null; } /** * Returns the local user status drawable. * * @return the local user status drawable */ private static Drawable getLocalStatusDrawable() { GlobalStatusService globalStatusService = AndroidGUIActivator.getGlobalStatusService(); byte[] statusImage = StatusUtil.getContactStatusIcon( globalStatusService.getGlobalPresenceStatus()); return AndroidImageUtil.drawableFromBytes(statusImage); } /** * Sets the avatar icon for the given avatar view. * * @param avatarView the avatar image view * @param avatarDrawable the avatar drawable to set */ public void setAvatar( ImageView avatarView, Drawable avatarDrawable) { if (avatarDrawable == null) { avatarDrawable = JitsiApplication.getAppResources() .getDrawable(R.drawable.avatar); } avatarView.setImageDrawable(avatarDrawable); } /** * Sets the status of the given view. * * @param statusView the status icon view * @param statusDrawable the status drawable */ public void setStatus( ImageView statusView, Drawable statusDrawable) { statusView.setImageDrawable(statusDrawable); } /** * Sets the appropriate typing notification interface. * * @param typingState the typing state that should be represented in the * view */ public void setTypingState(int typingState) { if (typingView == null) return; TextView typingTextView = (TextView) typingView.findViewById(R.id.typingTextView); ImageView typingImgView = (ImageView) typingView.findViewById(R.id.typingImageView); boolean setVisible = false; if (typingState == OperationSetTypingNotifications.STATE_TYPING) { Drawable typingDrawable = typingImgView.getDrawable(); if (!(typingDrawable instanceof AnimationDrawable)) { typingImgView.setImageResource(R.drawable.typing_drawable); typingDrawable = typingImgView.getDrawable(); } if(!((AnimationDrawable) typingDrawable).isRunning()) { AnimationDrawable animatedDrawable = (AnimationDrawable) typingDrawable; animatedDrawable.setOneShot(false); animatedDrawable.start(); } typingTextView.setText(chatSession.getShortDisplayName() + " " + getResources() .getString(R.string.service_gui_CONTACT_TYPING)); setVisible = true; } else if (typingState == OperationSetTypingNotifications.STATE_PAUSED) { typingImgView.setImageResource(R.drawable.typing1); typingTextView.setText( chatSession.getShortDisplayName() + " " + getResources() .getString(R.string.service_gui_CONTACT_PAUSED_TYPING)); setVisible = true; } if (setVisible) { typingImgView.getLayoutParams().height = LayoutParams.WRAP_CONTENT; typingImgView.setPadding(7, 0, 7, 7); typingView.setVisibility(View.VISIBLE); } else typingView.setVisibility(View.INVISIBLE); } }
package echowand.service.result; import echowand.common.EOJ; import echowand.common.EPC; import echowand.common.ESV; import echowand.net.CommonFrame; import echowand.net.Frame; import echowand.net.InternalSubnet; import echowand.net.Property; import echowand.net.StandardPayload; import echowand.service.CaptureResultObserver; import echowand.util.Selector; import java.util.LinkedList; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author ymakino */ public class CaptureResultTest { public static InternalSubnet subnet; public CaptureResult result; public short nextTID = 0; public CaptureResultTest() { } @BeforeClass public static void setUpClass() { subnet = new InternalSubnet("CaptureResultTest"); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { CaptureResultObserver observer = new CaptureResultObserver(); result = new CaptureResult(observer); } @After public void tearDown() { } private Frame newFrame() { Frame frame = new Frame(subnet.getLocalNode(), subnet.getLocalNode(), new CommonFrame()); frame.getCommonFrame().setTID(nextTID++); return frame; } private Frame newFrame(ESV esv, Property... properties) { Frame frame = new Frame(subnet.getLocalNode(), subnet.getLocalNode(), new CommonFrame()); frame.getCommonFrame().setTID(nextTID++); StandardPayload payload = new StandardPayload(); payload.setSEOJ(new EOJ("0ef001")); payload.setDEOJ(new EOJ("0ef001")); payload.setESV(esv); for (Property property : properties) { payload.addFirstProperty(property); } frame.getCommonFrame().setEDATA(payload); return frame; } /** * Test of stopCapture method, of class CaptureResult. */ @Test public void testStopCapture() { int count1 = result.countFrames(); result.stopCapture(); result.addReceivedFrame(newFrame()); result.addSentFrame(newFrame()); assertEquals(count1, result.countFrames()); } /** * Test of isDone method, of class CaptureResult. */ @Test public void testIsDone() { assertFalse(result.isDone()); result.stopCapture(); assertTrue(result.isDone()); } /** * Test of addSentFrame method, of class CaptureResult. */ @Test public void testAddSentFrame_Frame() { int count1 = result.countFrames(); int count2 = result.countReceivedFrames(); int count3 = result.countSentFrames(); Frame frame = newFrame(); assertTrue(result.addSentFrame(frame)); assertTrue(result.addSentFrame(frame)); assertTrue(result.addSentFrame(frame)); assertTrue(result.addSentFrame(frame)); assertEquals(count1 + 4, result.countFrames()); assertEquals(count2, result.countReceivedFrames()); assertEquals(count3 + 4, result.countSentFrames()); } /** * Test of addSentFrame method, of class CaptureResult. */ @Test public void testAddSentFrame_ResultFrame() { int count1 = result.countFrames(); int count2 = result.countReceivedFrames(); int count3 = result.countSentFrames(); Frame frame = newFrame(ESV.Get, new Property(EPC.x80)); ResultFrame resultFrame1 = new ResultFrame(frame, 10); ResultFrame resultFrame2 = new ResultFrame(frame, 10); assertTrue(result.addSentFrame(resultFrame1)); assertTrue(result.addSentFrame(resultFrame2)); assertFalse(result.addSentFrame(resultFrame1)); assertFalse(result.addSentFrame(resultFrame2)); assertEquals(count1 + 2, result.countFrames()); assertEquals(count2, result.countReceivedFrames()); assertEquals(count3 + 2, result.countSentFrames()); } /** * Test of addReceivedFrame method, of class CaptureResult. */ @Test public void testAddReceivedFrame_ResultFrame() { int count1 = result.countFrames(); int count2 = result.countReceivedFrames(); int count3 = result.countSentFrames(); Frame frame = newFrame(ESV.Get, new Property(EPC.x80)); ResultFrame resultFrame1 = new ResultFrame(frame, 10); ResultFrame resultFrame2 = new ResultFrame(frame, 10); assertTrue(result.addReceivedFrame(resultFrame1)); assertTrue(result.addReceivedFrame(resultFrame2)); assertFalse(result.addReceivedFrame(resultFrame1)); assertFalse(result.addReceivedFrame(resultFrame2)); assertEquals(count1 + 2, result.countFrames()); assertEquals(count2 + 2, result.countReceivedFrames()); assertEquals(count3, result.countSentFrames()); } /** * Test of addReceivedFrame method, of class CaptureResult. */ @Test public void testAddReceivedFrame_Frame() { int count1 = result.countFrames(); int count2 = result.countReceivedFrames(); int count3 = result.countSentFrames(); Frame frame = newFrame(); assertTrue(result.addReceivedFrame(frame)); assertTrue(result.addReceivedFrame(frame)); assertTrue(result.addReceivedFrame(frame)); assertTrue(result.addReceivedFrame(frame)); assertEquals(count1 + 4, result.countFrames()); assertEquals(count2 + 4, result.countReceivedFrames()); assertEquals(count3, result.countSentFrames()); } /** * Test of countFrames method, of class CaptureResult. */ @Test public void testCountFrames() { int count1 = result.countFrames(); assertTrue(result.addReceivedFrame(newFrame())); assertEquals(count1 + 1, result.countFrames()); assertTrue(result.addSentFrame(newFrame())); assertEquals(count1 + 2, result.countFrames()); } /** * Test of countSentFrames method, of class CaptureResult. */ @Test public void testCountSentFrames() { int count1 = result.countFrames(); assertTrue(result.addReceivedFrame(newFrame())); assertEquals(count1, result.countSentFrames()); assertTrue(result.addSentFrame(newFrame())); assertEquals(count1 + 1, result.countSentFrames()); } /** * Test of countReceivedFrames method, of class CaptureResult. */ @Test public void testCountReceivedFrames() { int count1 = result.countFrames(); assertTrue(result.addReceivedFrame(newFrame())); assertEquals(count1 + 1, result.countReceivedFrames()); assertTrue(result.addSentFrame(newFrame())); assertEquals(count1 + 1, result.countReceivedFrames()); } /** * Test of getFrame method, of class CaptureResult. */ @Test public void testGetFrame() { Frame frame1 = newFrame(); Frame frame2 = newFrame(); result.addReceivedFrame(frame1); result.addSentFrame(frame2); assertEquals(frame1, result.getFrame(0).frame); assertEquals(frame2, result.getFrame(1).frame); } /** * Test of getSentFrame method, of class CaptureResult. */ @Test public void testGetSentFrame() { Frame frame1 = newFrame(); Frame frame2 = newFrame(); result.addReceivedFrame(frame1); result.addSentFrame(frame2); assertEquals(frame2, result.getSentFrame(0).frame); } /** * Test of getReceivedFrame method, of class CaptureResult. */ @Test public void testGetReceivedFrame() { Frame frame1 = newFrame(); Frame frame2 = newFrame(); result.addSentFrame(frame1); result.addReceivedFrame(frame2); assertEquals(frame2, result.getReceivedFrame(0).frame); } /** * Test of getFrameList method, of class CaptureResult. */ @Test public void testGetFrameList() { assertTrue(result.getFrameList().isEmpty()); Frame frame1 = newFrame(); Frame frame2 = newFrame(); result.addSentFrame(frame1); result.addReceivedFrame(frame2); List<ResultFrame> resultFrameList = result.getFrameList(); assertEquals(2, resultFrameList.size()); assertEquals(frame1, resultFrameList.get(0).frame); assertEquals(frame2, resultFrameList.get(1).frame); } /** * Test of getSentFrameList method, of class CaptureResult. */ @Test public void testGetSentFrameList() { assertTrue(result.getSentFrameList().isEmpty()); Frame frame1 = newFrame(); Frame frame2 = newFrame(); result.addSentFrame(frame1); result.addReceivedFrame(frame2); List<ResultFrame> resultFrameList = result.getSentFrameList(); assertEquals(1, resultFrameList.size()); assertEquals(frame1, resultFrameList.get(0).frame); } /** * Test of getReceivedFrameList method, of class CaptureResult. */ @Test public void testGetReceivedFrameList() { assertTrue(result.getSentFrameList().isEmpty()); Frame frame1 = newFrame(); Frame frame2 = newFrame(); result.addSentFrame(frame1); result.addReceivedFrame(frame2); List<ResultFrame> resultFrameList = result.getReceivedFrameList(); assertEquals(1, resultFrameList.size()); assertEquals(frame2, resultFrameList.get(0).frame); } /** * Test of removeFrames method, of class CaptureResult. */ @Test public void testRemoveFrames() { Frame frame1 = newFrame(); Frame frame2 = newFrame(); Frame frame3 = newFrame(); Frame frame4 = newFrame(); final LinkedList<ResultFrame> matchFrames = new LinkedList<ResultFrame>(); Selector<ResultFrame> selector = new Selector<ResultFrame>() { @Override public boolean match(ResultFrame target) { return matchFrames.contains(target); } }; result.addSentFrame(frame1); result.addReceivedFrame(frame2); result.addSentFrame(frame3); result.addReceivedFrame(frame4); result.removeFrames(selector); assertEquals(4, result.countFrames()); assertEquals(2, result.countSentFrames()); assertEquals(2, result.countReceivedFrames()); matchFrames.addAll(result.getFrameList().subList(1, 3)); matchFrames.add(new ResultFrame(newFrame(), 10)); result.removeFrames(selector); assertEquals(2, result.countFrames()); assertEquals(1, result.countSentFrames()); assertEquals(1, result.countReceivedFrames()); } /** * Test of removeFrame method, of class CaptureResult. */ @Test public void testRemoveFrame_ResultFrame() { Frame frame1 = newFrame(); Frame frame2 = newFrame(); Frame frame3 = newFrame(); Frame frame4 = newFrame(); result.addSentFrame(frame1); result.addReceivedFrame(frame2); result.addSentFrame(frame3); result.addReceivedFrame(frame4); assertEquals(4, result.countFrames()); assertEquals(2, result.countSentFrames()); assertEquals(2, result.countReceivedFrames()); List<ResultFrame> frameList = result.getFrameList(); assertTrue(result.removeFrame(frameList.get(0))); assertEquals(3, result.countFrames()); assertEquals(1, result.countSentFrames()); assertEquals(2, result.countReceivedFrames()); assertFalse(result.removeFrame(frameList.get(0))); assertEquals(3, result.countFrames()); assertEquals(1, result.countSentFrames()); assertEquals(2, result.countReceivedFrames()); assertTrue(result.removeFrame(frameList.get(1))); assertEquals(2, result.countFrames()); assertEquals(1, result.countSentFrames()); assertEquals(1, result.countReceivedFrames()); } /** * Test of removeFrame method, of class CaptureResult. */ @Test public void testRemoveFrame_int() { Frame frame1 = newFrame(); Frame frame2 = newFrame(); Frame frame3 = newFrame(); Frame frame4 = newFrame(); result.addSentFrame(frame1); result.addReceivedFrame(frame2); result.addSentFrame(frame3); result.addReceivedFrame(frame4); assertEquals(4, result.countFrames()); assertEquals(2, result.countSentFrames()); assertEquals(2, result.countReceivedFrames()); List<ResultFrame> frameList = result.getFrameList(); result.removeFrame(0); assertEquals(3, result.countFrames()); assertEquals(1, result.countSentFrames()); assertEquals(2, result.countReceivedFrames()); result.removeFrame(2); assertEquals(2, result.countFrames()); assertEquals(1, result.countSentFrames()); assertEquals(1, result.countReceivedFrames()); } /** * Test of removeSentFrame method, of class CaptureResult. */ @Test public void testRemoveSentFrame() { Frame frame1 = newFrame(); Frame frame2 = newFrame(); Frame frame3 = newFrame(); Frame frame4 = newFrame(); result.addSentFrame(frame1); result.addReceivedFrame(frame2); result.addSentFrame(frame3); result.addReceivedFrame(frame4); result.removeSentFrame(1); assertEquals(3, result.countFrames()); assertEquals(1, result.countSentFrames()); assertEquals(2, result.countReceivedFrames()); assertEquals(frame1, result.getSentFrame(0).frame); result.removeSentFrame(0); assertEquals(2, result.countFrames()); assertEquals(0, result.countSentFrames()); assertEquals(2, result.countReceivedFrames()); } /** * Test of removeReceivedFrame method, of class CaptureResult. */ @Test public void testRemoveReceivedFrame() { Frame frame1 = newFrame(); Frame frame2 = newFrame(); Frame frame3 = newFrame(); Frame frame4 = newFrame(); result.addSentFrame(frame1); result.addReceivedFrame(frame2); result.addSentFrame(frame3); result.addReceivedFrame(frame4); result.removeReceivedFrame(1); assertEquals(3, result.countFrames()); assertEquals(2, result.countSentFrames()); assertEquals(1, result.countReceivedFrames()); assertEquals(frame1, result.getSentFrame(0).frame); result.removeReceivedFrame(0); assertEquals(2, result.countFrames()); assertEquals(2, result.countSentFrames()); assertEquals(0, result.countReceivedFrames()); } /** * Test of truncateSentFrames method, of class CaptureResult. */ @Test public void testTruncateSentFrames() { assertEquals(0, result.truncateSentFrames(1)); Frame frame1 = newFrame(); Frame frame2 = newFrame(); Frame frame3 = newFrame(); Frame frame4 = newFrame(); result.addSentFrame(frame1); result.addSentFrame(frame2); result.addSentFrame(frame3); result.addSentFrame(frame4); assertEquals(2, result.truncateSentFrames(2)); assertEquals(2, result.countSentFrames()); assertEquals(frame3, result.getSentFrame(0).frame); assertEquals(frame4, result.getSentFrame(1).frame); assertEquals(2, result.truncateSentFrames(1000)); assertEquals(0, result.countSentFrames()); } /** * Test of removeAllSentFrames method, of class CaptureResult. */ @Test public void testRemoveAllSentFrames() { assertEquals(0, result.removeAllSentFrames()); Frame frame1 = newFrame(); Frame frame2 = newFrame(); Frame frame3 = newFrame(); Frame frame4 = newFrame(); result.addSentFrame(frame1); result.addReceivedFrame(frame2); result.addSentFrame(frame3); result.addReceivedFrame(frame4); assertEquals(2, result.removeAllSentFrames()); assertEquals(0, result.countSentFrames()); assertEquals(2, result.countReceivedFrames()); assertEquals(2, result.countFrames()); } /** * Test of truncateReceivedFrames method, of class CaptureResult. */ @Test public void testTruncateReceivedFrames() { assertEquals(0, result.truncateReceivedFrames(1)); Frame frame1 = newFrame(); Frame frame2 = newFrame(); Frame frame3 = newFrame(); Frame frame4 = newFrame(); result.addReceivedFrame(frame1); result.addReceivedFrame(frame2); result.addReceivedFrame(frame3); result.addReceivedFrame(frame4); assertEquals(2, result.truncateReceivedFrames(2)); assertEquals(2, result.countReceivedFrames()); assertEquals(frame3, result.getReceivedFrame(0).frame); assertEquals(frame4, result.getReceivedFrame(1).frame); assertEquals(2, result.truncateReceivedFrames(1000)); assertEquals(0, result.countReceivedFrames()); } /** * Test of removeAllReceivedFrames method, of class CaptureResult. */ @Test public void testRemoveAllReceivedFrames() { assertEquals(0, result.removeAllReceivedFrames()); Frame frame1 = newFrame(); Frame frame2 = newFrame(); Frame frame3 = newFrame(); Frame frame4 = newFrame(); result.addSentFrame(frame1); result.addReceivedFrame(frame2); result.addSentFrame(frame3); result.addReceivedFrame(frame4); assertEquals(2, result.removeAllReceivedFrames()); assertEquals(2, result.countSentFrames()); assertEquals(0, result.countReceivedFrames()); assertEquals(2, result.countFrames()); } /** * Test of truncateFrames method, of class CaptureResult. */ @Test public void testTruncateFrames() { assertEquals(0, result.truncateReceivedFrames(1)); Frame frame1 = newFrame(); Frame frame2 = newFrame(); Frame frame3 = newFrame(); Frame frame4 = newFrame(); result.addSentFrame(frame1); result.addReceivedFrame(frame2); result.addSentFrame(frame3); result.addReceivedFrame(frame4); assertEquals(2, result.truncateFrames(2)); assertEquals(2, result.countFrames()); assertEquals(1, result.countSentFrames()); assertEquals(1, result.countReceivedFrames()); assertEquals(frame3, result.getFrame(0).frame); assertEquals(frame4, result.getFrame(1).frame); assertEquals(2, result.truncateFrames(1000)); assertEquals(0, result.countReceivedFrames()); } /** * Test of removeAllFrames method, of class CaptureResult. */ @Test public void testRemoveAllFrames() { assertEquals(0, result.removeAllFrames()); Frame frame1 = newFrame(); Frame frame2 = newFrame(); Frame frame3 = newFrame(); Frame frame4 = newFrame(); result.addSentFrame(frame1); result.addReceivedFrame(frame2); result.addSentFrame(frame3); result.addReceivedFrame(frame4); assertEquals(4, result.removeAllFrames()); assertEquals(0, result.countSentFrames()); assertEquals(0, result.countReceivedFrames()); assertEquals(0, result.countFrames()); } }
/* * $Id: PdfBoxTokenStream.java,v 1.7 2015-02-03 23:34:43 thib_gc Exp $ */ package org.lockss.pdf.pdfbox; import java.io.IOException; import java.util.*; import org.apache.pdfbox.pdmodel.PDResources; import org.apache.pdfbox.pdmodel.common.PDStream; import org.apache.pdfbox.pdmodel.font.PDFont; import org.lockss.pdf.*; /** * <p> * A {@link PdfTokenStream} implementation based on PDFBox 1.6.0. * </p> * <p> * This class acts as an adapter for the {@link PDStream} class, but * the origin of the wrapped instance comes from {@link #getPdStream()} * </p> * @author Thib Guicherd-Callin * @since 1.56 * @see PdfBoxDocumentFactory */ public abstract class PdfBoxTokenStream implements PdfTokenStream { /** * <p> * The parent {@link PdfBoxPage} instance. * </p> * @since 1.56 */ protected PdfBoxPage pdfBoxPage; /** * <p> * This constructor is accessible to classes in this package and * subclasses. * </p> * @param pdfBoxPage The parent {@link PdfBoxPage} instance. * @since 1.56 */ protected PdfBoxTokenStream(PdfBoxPage pdfBoxPage) { this.pdfBoxPage = pdfBoxPage; } @Override public PdfPage getPage() { return pdfBoxPage; } @Override public PdfTokenFactory getTokenFactory() throws PdfException { return getPage().getDocument().getTokenFactory(); } @Override public List<PdfToken> getTokens() throws PdfException { try { PDStream pdStream = getPdStream(); if (pdStream == null) { return new ArrayList<PdfToken>(); // Blank page with null stream } List<PdfToken> tokens = PdfBoxTokens.convertList(pdStream.getStream().getStreamTokens()); decodeStringsWithFontContext(tokens); return tokens; } catch (IOException ioe) { throw new PdfException(ioe); } } /** * <p> * Decodes strings using font contexts, in place in the given list. * </p> * * @param tokens * A list of tokens. * @param currentFont * The current font in the surrounding context of the list of tokens. * @throws PdfException * if a referenced font cannot be found. * @since 1.62 */ protected void decodeStringsWithFontContext(List<PdfToken> tokens) throws PdfException { decodeStringsWithFontContext(tokens, null); } /** * <p> * Decodes strings using font contexts, in place in the given list, using a * current font at the beginning. * </p> * * @param tokens * A list of tokens. * @param currentFont * The current font in the surrounding context of the list of tokens. * @throws PdfException * if a referenced font cannot be found. * @since 1.62 */ protected void decodeStringsWithFontContext(List<PdfToken> tokens, PDFont currentFont) throws PdfException { PdfTokenFactory factory = getTokenFactory(); for (int i = 0 ; i < tokens.size() ; ++i) { PdfToken token = tokens.get(i); if (token.isOperator() && PdfOpcodes.SET_TEXT_FONT.equals(token.getOperator())) { if (i == 0 || i == 1) { continue; // Malformed; ignore } PdfToken fontName = tokens.get(i - 2); PdfToken fontSize = tokens.get(i - 1); if (!fontName.isName() || !(fontSize.isFloat() || fontSize.isInteger())) { continue; // Malformed; ignore } PDResources streamResources = getStreamResources(); if (streamResources == null) { throw new PdfException("Current context has no PDResources instance"); } currentFont = (PDFont)streamResources.getFonts().get(fontName.getName()); if (currentFont == null) { throw new PdfException(String.format("Font '%s' not found", fontName.getName())); } } else if (token.isString()) { if (currentFont == null) { throw new PdfException(String.format("No font set at index %d", i)); } // See PDFBox 1.8.2, PDFStreamEngine, lines 387-514 StringBuilder sb = new StringBuilder(); byte[] bytes = PdfBoxTokens.asCOSString(token).getBytes(); int codeLength = 1; for (int j = 0; j < bytes.length; j += codeLength) { codeLength = 1; String str; try { str = currentFont.encode(bytes, j, codeLength); if (str == null && j + 1 < bytes.length) { codeLength++; str = currentFont.encode(bytes, j, codeLength); } } catch (IOException ioe) { throw new PdfException(String.format("Error decoding string at index %d", i), ioe); } if (str != null) { sb.append(str); } } tokens.set(i, factory.makeString(sb.toString())); } else if (token.isArray()) { List<PdfToken> array = token.getArray(); try { decodeStringsWithFontContext(array, currentFont); } catch (PdfException pdfe) { throw new PdfException(String.format("Error processing list at index %d", i), pdfe); } tokens.set(i, factory.makeArray(array)); } } } /** * <p> * Retrieves the {@link PDStream} instance underpinning this PDF token stream. * </p> * * @return The {@link PDStream} instance this instance represents. * @since 1.56 */ protected abstract PDStream getPdStream(); /** * <p> * Retrieves a {@link PDResources} instance suitable for the context of this * token stream. * </p> * * @return The {@link PDResources} instance for this token stream. * @since 1.64 */ protected abstract PDResources getStreamResources(); /** * <p> * Convenience method to create a new {@link PDStream} instance. * </p> * * @return A new {@link PDStream} instance based on this document. * @since 1.56 */ protected PDStream makeNewPdStream() { return new PDStream(pdfBoxPage.pdfBoxDocument.pdDocument); } }
package org.mozilla.javascript; public class ScriptRuntimeES6 { public static Scriptable requireObjectCoercible(Context cx, Scriptable val, IdFunctionObject idFuncObj) { if (val == null || Undefined.isUndefined(val)) { throw ScriptRuntime.typeError2("msg.called.null.or.undefined", idFuncObj.getTag(), idFuncObj.getFunctionName()); } return val; } }
package de.danoeh.antennapod.service.download; 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.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URL; import java.net.UnknownHostException; import org.apache.commons.io.IOUtils; import org.apache.http.HttpConnection; import org.apache.http.HttpStatus; import android.util.Log; import de.danoeh.antennapod.AppConfig; import de.danoeh.antennapod.R; import de.danoeh.antennapod.asynctask.DownloadStatus; import de.danoeh.antennapod.util.DownloadError; import de.danoeh.antennapod.util.StorageUtils; public class HttpDownloader extends Downloader { private static final String TAG = "HttpDownloader"; private static final int MAX_REDIRECTS = 5; private static final int BUFFER_SIZE = 8 * 1024; private static final int CONNECTION_TIMEOUT = 5000; public HttpDownloader(DownloadService downloadService, DownloadStatus status) { super(downloadService, status); } /** * This method is called by establishConnection(String). Don't call it * directly. * */ private HttpURLConnection establishConnection(String location, int redirectCount) throws MalformedURLException, IOException { URL url = new URL(location); HttpURLConnection connection = null; int responseCode = -1; connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(CONNECTION_TIMEOUT); // try with 'follow redirect' connection.setInstanceFollowRedirects(true); try { responseCode = connection.getResponseCode(); } catch (IOException e) { if (AppConfig.DEBUG) Log.d(TAG, "Failed to establish connection with 'follow redirects. Disabling 'follow redirects'"); connection.disconnect(); connection.setInstanceFollowRedirects(false); responseCode = connection.getResponseCode(); } if (AppConfig.DEBUG) Log.d(TAG, "Response Code: " + responseCode); switch (responseCode) { case HttpStatus.SC_TEMPORARY_REDIRECT: if (redirectCount < MAX_REDIRECTS) { final String redirect = connection.getHeaderField("Location"); if (redirect != null) { return establishConnection(redirect, redirectCount + 1); } } case HttpStatus.SC_OK: return connection; default: onFail(DownloadError.ERROR_HTTP_DATA_ERROR, String.valueOf(responseCode)); return null; } } /** * Establish connection to resource. This method will also try to handle * different response codes / redirect issues. * * @return the HttpURLConnection object if the connection could be opened, * null otherwise. * @throws MalformedURLException * , IOException * */ private HttpURLConnection establishConnection(String location) throws MalformedURLException, IOException { return establishConnection(location, 0); } @Override protected void download() { HttpURLConnection connection = null; OutputStream out = null; try { connection = establishConnection(status.getFeedFile() .getDownload_url()); if (connection != null) { if (AppConfig.DEBUG) { Log.d(TAG, "Connected to resource"); } if (StorageUtils.externalStorageMounted()) { File destination = new File(status.getFeedFile() .getFile_url()); if (!destination.exists()) { InputStream in = new BufferedInputStream( connection.getInputStream()); out = new BufferedOutputStream(new FileOutputStream( destination)); byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; status.setStatusMsg(R.string.download_running); if (AppConfig.DEBUG) Log.d(TAG, "Getting size of download"); status.setSize(connection.getContentLength()); if (AppConfig.DEBUG) Log.d(TAG, "Size is " + status.getSize()); if (status.getSize() == -1) { status.setSize(DownloadStatus.SIZE_UNKNOWN); } long freeSpace = StorageUtils.getFreeSpaceAvailable(); if (AppConfig.DEBUG) Log.d(TAG, "Free space is " + freeSpace); if (status.getSize() == DownloadStatus.SIZE_UNKNOWN || status.getSize() <= freeSpace) { if (AppConfig.DEBUG) Log.d(TAG, "Starting download"); while (!cancelled && (count = in.read(buffer)) != -1) { out.write(buffer, 0, count); status.setSoFar(status.getSoFar() + count); status.setProgressPercent((int) (((double) status .getSoFar() / (double) status.getSize()) * 100)); } if (cancelled) { onCancelled(); } else { onSuccess(); } } else { onFail(DownloadError.ERROR_NOT_ENOUGH_SPACE, null); } } else { onFail(DownloadError.ERROR_FILE_EXISTS, null); } } else { onFail(DownloadError.ERROR_DEVICE_NOT_FOUND, null); } } } catch (MalformedURLException e) { e.printStackTrace(); onFail(DownloadError.ERROR_MALFORMED_URL, e.getMessage()); } catch (SocketTimeoutException e) { e.printStackTrace(); onFail(DownloadError.ERROR_CONNECTION_ERROR, e.getMessage()); } catch (UnknownHostException e) { e.printStackTrace(); onFail(DownloadError.ERROR_UNKNOWN_HOST, e.getMessage()); } catch (IOException e) { e.printStackTrace(); onFail(DownloadError.ERROR_IO_ERROR, e.getMessage()); } catch (NullPointerException e) { // might be thrown by connection.getInputStream() e.printStackTrace(); onFail(DownloadError.ERROR_CONNECTION_ERROR, status.getFeedFile() .getDownload_url()); } finally { IOUtils.close(connection); IOUtils.closeQuietly(out); } } private void onSuccess() { if (AppConfig.DEBUG) Log.d(TAG, "Download was successful"); status.setSuccessful(true); status.setDone(true); } private void onFail(int reason, String reasonDetailed) { if (AppConfig.DEBUG) { Log.d(TAG, "Download failed"); } status.setReason(reason); status.setReasonDetailed(reasonDetailed); status.setDone(true); status.setSuccessful(false); } private void onCancelled() { if (AppConfig.DEBUG) Log.d(TAG, "Download was cancelled"); status.setReason(DownloadError.ERROR_DOWNLOAD_CANCELLED); status.setDone(true); status.setSuccessful(false); status.setCancelled(true); } }
package org.nschmidt.ldparteditor.data; import java.lang.reflect.InvocationTargetException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.TreeMap; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.widgets.Event; import org.lwjgl.opengl.GL11; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector4f; import org.nschmidt.csg.CSG; import org.nschmidt.csg.CSGCircle; import org.nschmidt.csg.CSGCone; import org.nschmidt.csg.CSGCube; import org.nschmidt.csg.CSGCylinder; import org.nschmidt.csg.CSGQuad; import org.nschmidt.csg.CSGSphere; import org.nschmidt.csg.Plane; import org.nschmidt.csg.Polygon; import org.nschmidt.ldparteditor.composites.Composite3D; import org.nschmidt.ldparteditor.enums.MyLanguage; import org.nschmidt.ldparteditor.enums.View; import org.nschmidt.ldparteditor.helpers.composite3d.PerspectiveCalculator; import org.nschmidt.ldparteditor.helpers.math.HashBiMap; import org.nschmidt.ldparteditor.helpers.math.MathHelper; import org.nschmidt.ldparteditor.helpers.math.PowerRay; import org.nschmidt.ldparteditor.i18n.I18n; import org.nschmidt.ldparteditor.shells.editor3d.Editor3DWindow; import org.nschmidt.ldparteditor.text.DatParser; /** * @author nils * */ public final class GDataCSG extends GData { final byte type; private final static HashMap<String, CSG> linkedCSG = new HashMap<String, CSG>(); private final static HashBiMap<Integer, GDataCSG> idToGDataCSG = new HashBiMap<Integer, GDataCSG>(); private final static HashMap<DatFile, HashSet<GData3>> selectedTrianglesMap = new HashMap<DatFile, HashSet<GData3>>(); private final static HashMap<DatFile, HashSet<GDataCSG>> selectedBodyMap = new HashMap<DatFile, HashSet<GDataCSG>>(); private static boolean deleteAndRecompile = true; private final static HashSet<GDataCSG> registeredData = new HashSet<GDataCSG>(); private final static HashSet<GDataCSG> parsedData = new HashSet<GDataCSG>(); private static int quality = 16; private int global_quality = 16; private double global_epsilon = 1e-6; private final String ref1; private final String ref2; private final String ref3; final GData1 parent; private CSG compiledCSG = null; private CSG dataCSG = null; private final GColour colour; final Matrix4f matrix; public static void forceRecompile() { registeredData.add(null); Plane.EPSILON = 1e-3; } public static void fullReset() { quality = 16; registeredData.clear(); linkedCSG.clear(); parsedData.clear(); idToGDataCSG.clear(); Plane.EPSILON = 1e-3; } public static void resetCSG() { quality = 16; HashSet<GDataCSG> ref = new HashSet<GDataCSG>(registeredData); ref.removeAll(parsedData); deleteAndRecompile = !ref.isEmpty(); if (deleteAndRecompile) { registeredData.clear(); registeredData.add(null); linkedCSG.clear(); idToGDataCSG.clear(); } parsedData.clear(); } public byte getCSGtype() { return type; } public GDataCSG(final int colourNumber, float r, float g, float b, float a, GDataCSG c) { this(c.type, c.colourReplace(new GColour(colourNumber, r, g, b, a).toString()), c.parent); } public GDataCSG(Matrix4f m, GDataCSG c) { this(c.type, c.transform(m), c.parent); } // CASE 1 0 !LPE [CSG TAG] [ID] [COLOUR] [MATRIX] 17 // CASE 2 0 !LPE [CSG TAG] [ID] [ID2] [ID3] 6 // CASE 3 0 !LPE [CSG TAG] [ID] 4 public GDataCSG(byte type, String csgLine, GData1 parent) { this.parent = parent; registeredData.add(this); String[] data_segments = csgLine.trim().split("\\s+"); //$NON-NLS-1$ this.type = type; this.text = csgLine; switch (type) { case CSG.COMPILE: if (data_segments.length == 4) { ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$ } else { ref1 = null; } ref2 = null; ref3 = null; colour = null; matrix = null; break; case CSG.QUAD: case CSG.CIRCLE: case CSG.ELLIPSOID: case CSG.CUBOID: case CSG.CYLINDER: case CSG.CONE: if (data_segments.length == 17) { ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$ GColour c = DatParser.validateColour(data_segments[4], .5f, .5f, .5f, 1f); if (c != null) { colour = c.clone(); } else { colour = View.getLDConfigColour(16); } matrix = MathHelper.matrixFromStrings(data_segments[5], data_segments[6], data_segments[7], data_segments[8], data_segments[11], data_segments[14], data_segments[9], data_segments[12], data_segments[15], data_segments[10], data_segments[13], data_segments[16]); } else { colour = null; matrix = null; ref1 = null; } ref2 = null; ref3 = null; break; case CSG.DIFFERENCE: case CSG.INTERSECTION: case CSG.UNION: if (data_segments.length == 6) { ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$ ref2 = data_segments[4] + "#>" + parent.shortName; //$NON-NLS-1$ ref3 = data_segments[5] + "#>" + parent.shortName; //$NON-NLS-1$ } else { ref1 = null; ref2 = null; ref3 = null; } colour = null; matrix = null; break; case CSG.QUALITY: if (data_segments.length == 4) { try { int q = Integer.parseInt(data_segments[3]); if (q > 0 && q < 49) { global_quality = q; } } catch (NumberFormatException e) { } ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$ } else { ref1 = null; } ref2 = null; ref3 = null; colour = null; matrix = null; break; case CSG.EPSILON: if (data_segments.length == 4) { try { double q = Double.parseDouble(data_segments[3]); if (q > 0d) { global_epsilon = q; } } catch (NumberFormatException e) { } ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$ } else { ref1 = null; } ref2 = null; ref3 = null; colour = null; matrix = null; break; default: ref1 = null; ref2 = null; ref3 = null; colour = null; matrix = null; break; } } private void drawAndParse(Composite3D c3d) { parsedData.add(this); final boolean modified = c3d.getManipulator().isModified(); if (deleteAndRecompile || modified) { final Matrix4f m; if (modified) { m = c3d.getManipulator().getTempTransformationCSG4f(); } else { m = View.ID; } registeredData.remove(null); try { compiledCSG = null; registeredData.add(this); if (ref1 != null) { switch (type) { case CSG.QUAD: case CSG.CIRCLE: case CSG.ELLIPSOID: case CSG.CUBOID: case CSG.CYLINDER: case CSG.CONE: if (matrix != null) { switch (type) { case CSG.QUAD: CSGQuad quad = new CSGQuad(); idToGDataCSG.put(quad.ID, this); CSG csgQuad = quad.toCSG(colour).transformed(matrix); if (isSelected(c3d)) csgQuad = csgQuad.transformed(m); dataCSG = csgQuad; linkedCSG.put(ref1, csgQuad); break; case CSG.CIRCLE: CSGCircle circle = new CSGCircle(quality); idToGDataCSG.put(circle.ID, this); CSG csgCircle = circle.toCSG(colour).transformed(matrix); if (isSelected(c3d)) csgCircle = csgCircle.transformed(m); dataCSG = csgCircle; linkedCSG.put(ref1, csgCircle); break; case CSG.ELLIPSOID: CSGSphere sphere = new CSGSphere(quality, quality / 2); idToGDataCSG.put(sphere.ID, this); CSG csgSphere = sphere.toCSG(colour).transformed(matrix); if (isSelected(c3d)) csgSphere = csgSphere.transformed(m); dataCSG = csgSphere; linkedCSG.put(ref1, csgSphere); break; case CSG.CUBOID: CSGCube cube = new CSGCube(); idToGDataCSG.put(cube.ID, this); CSG csgCube = cube.toCSG(colour).transformed(matrix); if (isSelected(c3d)) csgCube = csgCube.transformed(m); dataCSG = csgCube; linkedCSG.put(ref1, csgCube); break; case CSG.CYLINDER: CSGCylinder cylinder = new CSGCylinder(quality); idToGDataCSG.put(cylinder.ID, this); CSG csgCylinder = cylinder.toCSG(colour).transformed(matrix); if (isSelected(c3d)) csgCylinder = csgCylinder.transformed(m); dataCSG = csgCylinder; linkedCSG.put(ref1, csgCylinder); break; case CSG.CONE: CSGCone cone = new CSGCone(quality); idToGDataCSG.put(cone.ID, this); CSG csgCone = cone.toCSG(colour).transformed(matrix); if (isSelected(c3d)) csgCone = csgCone.transformed(m); dataCSG = csgCone; linkedCSG.put(ref1, csgCone); break; default: break; } } break; case CSG.COMPILE: if (linkedCSG.containsKey(ref1)) { compiledCSG = linkedCSG.get(ref1); compiledCSG.compile(); } else { compiledCSG = null; } break; case CSG.DIFFERENCE: if (linkedCSG.containsKey(ref1) && linkedCSG.containsKey(ref2)) { linkedCSG.put(ref3, linkedCSG.get(ref1).difference(linkedCSG.get(ref2))); } break; case CSG.INTERSECTION: if (linkedCSG.containsKey(ref1) && linkedCSG.containsKey(ref2)) { linkedCSG.put(ref3, linkedCSG.get(ref1).intersect(linkedCSG.get(ref2))); } break; case CSG.UNION: if (linkedCSG.containsKey(ref1) && linkedCSG.containsKey(ref2)) { linkedCSG.put(ref3, linkedCSG.get(ref1).union(linkedCSG.get(ref2))); } break; case CSG.QUALITY: quality = global_quality; break; case CSG.EPSILON: Plane.EPSILON = global_epsilon; break; default: break; } } } catch (StackOverflowError e) { registeredData.clear(); linkedCSG.clear(); parsedData.clear(); deleteAndRecompile = false; registeredData.add(null); Plane.EPSILON = Plane.EPSILON * 10d; } catch (Exception e) { } } if (compiledCSG != null) { if (c3d.getRenderMode() != 5) { compiledCSG.draw(c3d); } else { compiledCSG.draw_textured(c3d); } } } @Override public void draw(Composite3D c3d) { drawAndParse(c3d); } @Override public void drawRandomColours(Composite3D c3d) { drawAndParse(c3d); } @Override public void drawBFC(Composite3D c3d) { drawAndParse(c3d); } @Override public void drawBFCuncertified(Composite3D c3d) { drawAndParse(c3d); } @Override public void drawBFC_backOnly(Composite3D c3d) { drawAndParse(c3d); } @Override public void drawBFC_Colour(Composite3D c3d) { drawAndParse(c3d); } @Override public void drawBFC_Textured(Composite3D c3d) { drawAndParse(c3d); } @Override public void drawWhileAddCondlines(Composite3D c3d) { drawAndParse(c3d); } @Override public int type() { return 8; } @Override String getNiceString() { return text; } @Override public String inlinedString(final byte bfc, final GColour colour) { switch (type) { case CSG.COMPILE: if (compiledCSG != null) { final StringBuilder sb = new StringBuilder(); try { new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(false, false, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { Editor3DWindow.getWindow().getShell().getDisplay().readAndDispatch(); Object[] messageArguments = {getNiceString()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.DATFILE_Inlined); sb.append(formatter.format(messageArguments) + "<br>"); //$NON-NLS-1$ HashMap<GData3, Integer> result = compiledCSG.getResult(); for (GData3 g3 : result.keySet()) { StringBuilder lineBuilder3 = new StringBuilder(); lineBuilder3.append("3 "); //$NON-NLS-1$ if (g3.colourNumber == -1) { lineBuilder3.append("0x2"); //$NON-NLS-1$ lineBuilder3.append(MathHelper.toHex((int) (255f * g3.r)).toUpperCase()); lineBuilder3.append(MathHelper.toHex((int) (255f * g3.g)).toUpperCase()); lineBuilder3.append(MathHelper.toHex((int) (255f * g3.b)).toUpperCase()); } else { lineBuilder3.append(g3.colourNumber); } Vector4f g3_v1 = new Vector4f(g3.x1, g3.y1, g3.z1, 1f); Vector4f g3_v2 = new Vector4f(g3.x2, g3.y2, g3.z2, 1f); Vector4f g3_v3 = new Vector4f(g3.x3, g3.y3, g3.z3, 1f); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v1.x / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v1.y / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v1.z / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v2.x / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v2.y / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v2.z / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v3.x / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v3.y / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v3.z / 1000f)); sb.append(lineBuilder3.toString() + "<br>"); //$NON-NLS-1$ } } }); } catch (InvocationTargetException consumed) { consumed.printStackTrace(); } catch (InterruptedException consumed) { consumed.printStackTrace(); } return sb.toString(); } else { return getNiceString(); } default: return getNiceString(); } } private String floatToString(float flt) { String result; if (flt == (int) flt) { result = String.format("%d", (int) flt); //$NON-NLS-1$ } else { result = String.format("%s", flt); //$NON-NLS-1$ if (result.equals("0.0"))result = "0"; //$NON-NLS-1$ //$NON-NLS-2$ } if (result.startsWith("-0.")) return "-" + result.substring(2); //$NON-NLS-1$ //$NON-NLS-2$ if (result.startsWith("0.")) return result.substring(1); //$NON-NLS-1$ return result; } @Override public String transformAndColourReplace(String colour2, Matrix matrix) { boolean notChoosen = true; String t = null; switch (type) { case CSG.QUAD: if (notChoosen) { t = " CSG_QUAD "; //$NON-NLS-1$ notChoosen = false; } case CSG.CIRCLE: if (notChoosen) { t = " CSG_CIRCLE "; //$NON-NLS-1$ notChoosen = false; } case CSG.ELLIPSOID: if (notChoosen) { t = " CSG_ELLIPSOID "; //$NON-NLS-1$ notChoosen = false; } case CSG.CUBOID: if (notChoosen) { t = " CSG_CUBOID "; //$NON-NLS-1$ notChoosen = false; } case CSG.CYLINDER: if (notChoosen) { t = " CSG_CYLINDER "; //$NON-NLS-1$ notChoosen = false; } case CSG.CONE: if (notChoosen) { t = " CSG_CONE "; //$NON-NLS-1$ notChoosen = false; } StringBuilder colourBuilder = new StringBuilder(); if (colour == null) { colourBuilder.append(16); } else if (colour.getColourNumber() == -1) { colourBuilder.append("0x2"); //$NON-NLS-1$ colourBuilder.append(MathHelper.toHex((int) (255f * colour.getR())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * colour.getG())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * colour.getB())).toUpperCase()); } else { colourBuilder.append(colour.getColourNumber()); } Matrix4f newMatrix = new Matrix4f(this.matrix); Matrix4f newMatrix2 = new Matrix4f(matrix.getMatrix4f()); Matrix4f.transpose(newMatrix, newMatrix); newMatrix.m30 = newMatrix.m03; newMatrix.m31 = newMatrix.m13; newMatrix.m32 = newMatrix.m23; newMatrix.m03 = 0f; newMatrix.m13 = 0f; newMatrix.m23 = 0f; Matrix4f.mul(newMatrix2, newMatrix, newMatrix); String col = colourBuilder.toString(); if (col.equals(colour2)) col = "16"; //$NON-NLS-1$ String tag = ref1.substring(0, ref1.lastIndexOf("#>")); //$NON-NLS-1$ return "0 !LPE" + t + tag + " " + col + " " + MathHelper.matrixToString(newMatrix); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ default: return text; } } public String transform(Matrix4f m) { boolean notChoosen = true; String t = null; switch (type) { case CSG.QUAD: if (notChoosen) { t = " CSG_QUAD "; //$NON-NLS-1$ notChoosen = false; } case CSG.CIRCLE: if (notChoosen) { t = " CSG_CIRCLE "; //$NON-NLS-1$ notChoosen = false; } case CSG.ELLIPSOID: if (notChoosen) { t = " CSG_ELLIPSOID "; //$NON-NLS-1$ notChoosen = false; } case CSG.CUBOID: if (notChoosen) { t = " CSG_CUBOID "; //$NON-NLS-1$ notChoosen = false; } case CSG.CYLINDER: if (notChoosen) { t = " CSG_CYLINDER "; //$NON-NLS-1$ notChoosen = false; } case CSG.CONE: if (notChoosen) { t = " CSG_CONE "; //$NON-NLS-1$ notChoosen = false; } StringBuilder colourBuilder = new StringBuilder(); if (colour == null) { colourBuilder.append(16); } else if (colour.getColourNumber() == -1) { colourBuilder.append("0x2"); //$NON-NLS-1$ colourBuilder.append(MathHelper.toHex((int) (255f * colour.getR())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * colour.getG())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * colour.getB())).toUpperCase()); } else { colourBuilder.append(colour.getColourNumber()); } Matrix4f newMatrix = new Matrix4f(); newMatrix.m30 = m.m03 * 1000f; newMatrix.m31 = m.m13 * 1000f; newMatrix.m32 = m.m23 * 1000f; newMatrix.m20 = m.m02; newMatrix.m21 = m.m12; newMatrix.m22 = m.m22; Matrix4f newMatrix2 = new Matrix4f(this.matrix); Matrix4f.mul(newMatrix, newMatrix2, newMatrix); Matrix4f.transpose(newMatrix, newMatrix); newMatrix.m30 = newMatrix.m03; newMatrix.m31 = newMatrix.m13; newMatrix.m32 = newMatrix.m23; newMatrix.m03 = 0f; newMatrix.m13 = 0f; newMatrix.m23 = 0f; String tag = ref1.substring(0, ref1.lastIndexOf("#>")); //$NON-NLS-1$ return "0 !LPE" + t + tag + " " + colourBuilder.toString() + " " + MathHelper.matrixToString(newMatrix); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ default: return text; } } public String colourReplace(String colour2) { boolean notChoosen = true; String t = null; switch (type) { case CSG.QUAD: if (notChoosen) { t = " CSG_QUAD "; //$NON-NLS-1$ notChoosen = false; } case CSG.CIRCLE: if (notChoosen) { t = " CSG_CIRCLE "; //$NON-NLS-1$ notChoosen = false; } case CSG.ELLIPSOID: if (notChoosen) { t = " CSG_ELLIPSOID "; //$NON-NLS-1$ notChoosen = false; } case CSG.CUBOID: if (notChoosen) { t = " CSG_CUBOID "; //$NON-NLS-1$ notChoosen = false; } case CSG.CYLINDER: if (notChoosen) { t = " CSG_CYLINDER "; //$NON-NLS-1$ notChoosen = false; } case CSG.CONE: if (notChoosen) { t = " CSG_CONE "; //$NON-NLS-1$ notChoosen = false; } Matrix4f newMatrix = new Matrix4f(this.matrix); Matrix4f.transpose(newMatrix, newMatrix); newMatrix.m30 = newMatrix.m03; newMatrix.m31 = newMatrix.m13; newMatrix.m32 = newMatrix.m23; newMatrix.m03 = 0f; newMatrix.m13 = 0f; newMatrix.m23 = 0f; String col = colour2; String tag = ref1.substring(0, ref1.lastIndexOf("#>")); //$NON-NLS-1$ return "0 !LPE" + t + tag + " " + col + " " + MathHelper.matrixToString(newMatrix); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ default: return text; } } @Override public void getBFCorientationMap(HashMap<GData, Byte> map) {} @Override public void getBFCorientationMapNOCERTIFY(HashMap<GData, Byte> map) {} @Override public void getBFCorientationMapNOCLIP(HashMap<GData, Byte> map) {} @Override public void getVertexNormalMap(TreeMap<Vertex, float[]> vertexLinkedToNormalCACHE, HashMap<GData, float[]> dataLinkedToNormalCACHE, VM00Base vm) {} @Override public void getVertexNormalMapNOCERTIFY(TreeMap<Vertex, float[]> vertexLinkedToNormalCACHE, HashMap<GData, float[]> dataLinkedToNormalCACHE, VM00Base vm) {} @Override public void getVertexNormalMapNOCLIP(TreeMap<Vertex, float[]> vertexLinkedToNormalCACHE, HashMap<GData, float[]> dataLinkedToNormalCACHE, VM00Base vm) {} public static boolean hasSelectionCSG(DatFile df) { final HashSet<GData3> selectedTriangles = selectedTrianglesMap.get(df); if (selectedTriangles == null) { selectedTrianglesMap.put(df, new HashSet<GData3>()); return false; } return !selectedTriangles.isEmpty(); } public boolean isSelected(Composite3D c3d) { final HashSet<GDataCSG> map = selectedBodyMap.get(c3d.getLockableDatFileReference()); if (map == null) { return false; } return map.contains(this); } public static void drawSelectionCSG(Composite3D c3d, final boolean modifiedManipulator) { final HashSet<GData3> selectedTriangles = selectedTrianglesMap.get(c3d.getLockableDatFileReference()); if (selectedTriangles == null) { selectedTrianglesMap.put(c3d.getLockableDatFileReference(), new HashSet<GData3>()); return; } if (!selectedTriangles.isEmpty()) { GL11.glColor3f(View.vertex_selected_Colour_r[0], View.vertex_selected_Colour_g[0], View.vertex_selected_Colour_b[0]); GL11.glBegin(GL11.GL_LINES); for (GData3 tri : selectedTriangles) { GL11.glVertex3f(tri.x1, tri.y1, tri.z1); GL11.glVertex3f(tri.x2, tri.y2, tri.z2); GL11.glVertex3f(tri.x2, tri.y2, tri.z2); GL11.glVertex3f(tri.x3, tri.y3, tri.z3); GL11.glVertex3f(tri.x3, tri.y3, tri.z3); GL11.glVertex3f(tri.x1, tri.y1, tri.z1); } GL11.glEnd(); } } public static void selectCSG(Composite3D c3d, Event event) { final HashSet<GData3> selectedTriangles = selectedTrianglesMap.get(c3d.getLockableDatFileReference()); if (selectedTriangles == null) { selectedTrianglesMap.put(c3d.getLockableDatFileReference(), new HashSet<GData3>()); return; } if (!c3d.getKeys().isCtrlPressed()) { selectedTriangles.clear(); } Integer selectedBodyID = selectCSG_helper(c3d, event); if (selectedBodyID != null) { for (CSG csg : linkedCSG.values()) { for(Entry<GData3, Integer> pair : csg.getResult().entrySet()) { if (selectedBodyID.equals(pair.getValue())) { selectedTriangles.add(pair.getKey()); } } } } } private static Integer selectCSG_helper(Composite3D c3d, Event event) { final PowerRay powerRay = new PowerRay(); final HashBiMap<Integer, GData> dpl = c3d.getLockableDatFileReference().getDrawPerLine_NOCLONE(); PerspectiveCalculator perspective = c3d.getPerspectiveCalculator(); Matrix4f viewport_rotation = c3d.getRotation(); Vector4f zAxis4f = new Vector4f(0, 0, -1f, 1f); Matrix4f ovr_inverse2 = Matrix4f.invert(viewport_rotation, null); Matrix4f.transform(ovr_inverse2, zAxis4f, zAxis4f); Vector4f rayDirection = (Vector4f) new Vector4f(zAxis4f.x, zAxis4f.y, zAxis4f.z, 0f).normalise(); rayDirection.w = 1f; Vertex[] triQuadVerts = new Vertex[3]; Vector4f orig = perspective.get3DCoordinatesFromScreen(event.x, event.y); Vector4f point = new Vector4f(orig); double minDist = Double.MAX_VALUE; final double[] dist = new double[1]; Integer result = null; GDataCSG resultObj = null; for (CSG csg : linkedCSG.values()) { for(Entry<GData3, Integer> pair : csg.getResult().entrySet()) { final GData3 triangle = pair.getKey(); triQuadVerts[0] = new Vertex(triangle.x1, triangle.y1, triangle.z1); triQuadVerts[1] = new Vertex(triangle.x2, triangle.y2, triangle.z2); triQuadVerts[2] = new Vertex(triangle.x3, triangle.y3, triangle.z3); if (powerRay.TRIANGLE_INTERSECT(orig, rayDirection, triQuadVerts[0], triQuadVerts[1], triQuadVerts[2], point, dist)) { if (dist[0] < minDist) { Integer result2 = pair.getValue(); if (result2 != null) { for (GDataCSG c : registeredData) { if (dpl.containsValue(c) && idToGDataCSG.containsKey(result2)) { if (c.ref1 != null && c.ref2 == null && c.ref3 == null && c.type != CSG.COMPILE) { minDist = dist[0]; result = result2; resultObj = idToGDataCSG.getValue(result2); break; } } } } } } } } selectedBodyMap.putIfAbsent(c3d.getLockableDatFileReference(), new HashSet<GDataCSG>()); if (!c3d.getKeys().isCtrlPressed()) { selectedBodyMap.get(c3d.getLockableDatFileReference()).clear(); } selectedBodyMap.get(c3d.getLockableDatFileReference()).add(resultObj); return result; } public static HashSet<GDataCSG> getSelection(DatFile df) { return selectedBodyMap.get(df); } public static void rebuildSelection(DatFile df) { // FIXME Needs implementation for issue #161 final Composite3D c3d = df.getLastSelectedComposite(); if (c3d == null || df.getLastSelectedComposite().isDisposed()) return; final HashSet<GData3> selectedTriangles = selectedTrianglesMap.get(df); final HashSet<GDataCSG> selectedBodies = selectedBodyMap.get(df); if (selectedTriangles == null) { selectedTrianglesMap.put(df, new HashSet<GData3>()); return; } selectedTriangles.clear(); for (GDataCSG c : selectedBodies) { for (Polygon p : c.dataCSG.getPolygons()) { Matrix4f id = new Matrix4f(); Matrix4f.setIdentity(id); GData1 g1 = new GData1(-1, .5f, .5f, .5f, 1f, id, View.ACCURATE_ID, new ArrayList<String>(), null, null, 1, false, id, View.ACCURATE_ID, null, View.DUMMY_REFERENCE, true, false, new HashSet<String>(), View.DUMMY_REFERENCE); selectedTriangles.addAll(p.toLDrawTriangles(g1).keySet()); } } } }
package de.hotware.blockbreaker.android; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.Random; import org.andengine.engine.camera.Camera; import org.andengine.engine.camera.hud.HUD; import org.andengine.engine.handler.timer.ITimerCallback; import org.andengine.engine.handler.timer.TimerHandler; import org.andengine.engine.options.EngineOptions; import org.andengine.engine.options.EngineOptions.ScreenOrientation; import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.andengine.entity.scene.Scene; import org.andengine.entity.scene.background.SpriteBackground; import org.andengine.entity.sprite.Sprite; import org.andengine.entity.text.Text; import org.andengine.entity.util.FPSCounter; import org.andengine.entity.util.FPSLogger; import org.andengine.opengl.font.Font; import org.andengine.opengl.font.FontFactory; import org.andengine.opengl.font.FontManager; import org.andengine.opengl.texture.TextureManager; import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.andengine.opengl.texture.region.TextureRegion; import org.andengine.opengl.texture.region.TiledTextureRegion; import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.input.sensor.orientation.IOrientationListener; import org.andengine.input.sensor.orientation.OrientationData; import org.andengine.ui.activity.BaseGameActivity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.AssetManager; import android.graphics.Color; import android.preference.PreferenceManager; import android.view.Gravity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.FrameLayout; import de.hotware.blockbreaker.android.view.LevelSceneHandler; import de.hotware.blockbreaker.android.view.UIConstants; import de.hotware.blockbreaker.model.generator.LevelGenerator; import de.hotware.blockbreaker.model.listeners.IGameEndListener; import de.hotware.blockbreaker.model.listeners.IGameEndListener.GameEndEvent.GameEndType; import de.hotware.blockbreaker.model.Level; import de.hotware.blockbreaker.util.misc.StreamUtil; public class BlockBreakerActivity extends BaseGameActivity implements IOrientationListener { //// Constants //// static final String DEFAULT_LEVEL_PATH = "levels/default.lev"; static final boolean USE_MENU_WORKAROUND = Integer.valueOf(android.os.Build.VERSION.SDK) < 7; static final String HIGHSCORE_NUM_KEY = "high_score_num_key"; static final String HIGHSCORE_PLAYER_KEY = "high_score_player_key"; //// Fields //// static final Random sRandomSeedObject = new Random(); boolean mUseOrientSensor = false; boolean mTimeAttackMode = false; int mNumberOfTurns = 16; BitmapTextureAtlas mBlockBitmapTextureAtlas; TiledTextureRegion mBlockTiledTextureRegion; BitmapTextureAtlas mArrowBitmapTextureAtlas; TiledTextureRegion mArrowTiledTextureRegion; BitmapTextureAtlas mSceneBackgroundBitmapTextureAtlas; TextureRegion mSceneBackgroundTextureRegion; Properties mStringProperties; Camera mCamera; Scene mLevelScene; Font mMiscFont; Font mSceneUIFont; Text mSeedText; LevelSceneHandler mLevelSceneHandler; Level mBackupLevel; Level mLevel; //currently not used String mLevelPath = DEFAULT_LEVEL_PATH; boolean mIsAsset = true; //not used end private IGameTypeHandler mGameTypeHandler; //// Overridden Methods //// @Override public void onStart() { super.onStart(); boolean oldTimeAttackMode = this.mTimeAttackMode; this.getPrefs(); if(oldTimeAttackMode ^ this.mTimeAttackMode || this.mGameTypeHandler == null) { if(this.mGameTypeHandler != null) { this.mGameTypeHandler.cleanUp(); } this.mGameTypeHandler = this.mTimeAttackMode ? new TimeAttackGameHandler() : new DefaultGameHandler(); if(this.mLevel != null) { this.mLevel.setGameEndListener(this.mGameTypeHandler); this.mGameTypeHandler.start(); } } } /** * sets the EngineOptions to the needs of the game */ @Override public EngineOptions onCreateEngineOptions() { this.mCamera = new Camera(0, 0, UIConstants.LEVEL_WIDTH, UIConstants.LEVEL_HEIGHT); EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(UIConstants.LEVEL_WIDTH, UIConstants.LEVEL_HEIGHT), this.mCamera); return engineOptions; } /** * Load all the textures we need */ @Override public void onCreateResources(OnCreateResourcesCallback pCallback) { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); //TODO: Language choosing this.mStringProperties = new Properties(); AssetManager assetManager = this.getResources().getAssets(); InputStream is = null; boolean fail = false; try { is = assetManager.open(UIConstants.DEFAULT_PROPERTIES_PATH); this.mStringProperties.load(is); } catch (IOException e) { fail = true; this.showFailDialog(e.getMessage()); } finally { StreamUtil.closeQuietly(is); } if(fail) { this.finish(); } TextureManager textureManager = this.mEngine.getTextureManager(); //loading block textures this.mBlockBitmapTextureAtlas = new BitmapTextureAtlas(textureManager, 276, 46, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mBlockTiledTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBlockBitmapTextureAtlas, this, "blocks_tiled.png", 0,0, 6,1); this.mEngine.getTextureManager().loadTexture(this.mBlockBitmapTextureAtlas); //loading arrow sprites this.mArrowBitmapTextureAtlas = new BitmapTextureAtlas(textureManager, 512, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mArrowTiledTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mArrowBitmapTextureAtlas, this, "arrow_tiled.png", 0,0, 4,1); this.mEngine.getTextureManager().loadTexture(this.mArrowBitmapTextureAtlas); //Loading Background this.mSceneBackgroundBitmapTextureAtlas = new BitmapTextureAtlas(textureManager, 960, 640, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mSceneBackgroundTextureRegion = (TextureRegion) BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mSceneBackgroundBitmapTextureAtlas, this, "background.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mSceneBackgroundBitmapTextureAtlas); FontManager fontManager = this.mEngine.getFontManager(); //loading fps font BitmapTextureAtlas fpsFontTexture = new BitmapTextureAtlas(textureManager, 256, 256, TextureOptions.BILINEAR); this.mEngine.getTextureManager().loadTexture(fpsFontTexture); FontFactory.setAssetBasePath("font/"); this.mMiscFont = FontFactory.createFromAsset(fontManager, fpsFontTexture, assetManager, "Droid.ttf", 12, true, Color.BLACK); this.mEngine.getFontManager().loadFont(this.mMiscFont); //loading scene font BitmapTextureAtlas sceneFontTexture = new BitmapTextureAtlas(textureManager, 256, 256, TextureOptions.BILINEAR); this.mEngine.getTextureManager().loadTexture(sceneFontTexture); this.mSceneUIFont = FontFactory.createFromAsset(fontManager, sceneFontTexture, assetManager, "Plok.ttf", 18, true, Color.BLACK); this.mEngine.getFontManager().loadFont(this.mSceneUIFont); pCallback.onCreateResourcesFinished(); } /** * initialization of the Activity is done here. */ @Override public void onCreateScene(OnCreateSceneCallback pCallback) { this.mEngine.registerUpdateHandler(new FPSLogger()); pCallback.onCreateSceneFinished(new Scene()); } @Override public void onPopulateScene(Scene pScene, OnPopulateSceneCallback pCallback) { this.loadFirstLevel(); this.initLevel(); this.mCamera.getHUD().attachChild(this.mSeedText); //TODO: setting scene only for testing purposes!!! this.mEngine.setScene(this.mLevelScene); pCallback.onPopulateSceneFinished(); this.mGameTypeHandler.start(); } @Override public void onResumeGame() { super.onResumeGame(); if(this.mUseOrientSensor) { this.enableOrientationSensor(this); } else { this.disableOrientationSensor(); } this.mGameTypeHandler.onEnterFocus(); } @Override public void onPauseGame() { super.onPauseGame(); this.disableOrientationSensor(); this.mGameTypeHandler.onLeaveFocus(); } /** * Listener method for Changes of the devices Orientation. * sets the Levels Gravity to the overwhelming Gravity */ @Override public void onOrientationChanged(OrientationData pOrientData) { if(this.mUseOrientSensor) { if(this.mLevel != null) { float pitch = pOrientData.getPitch(); float roll = pOrientData.getRoll(); if(roll == 0 && pitch == 0) { this.mLevel.setGravity(Level.Gravity.NORTH); } else if(Math.max(Math.abs(pitch), Math.abs(roll)) == Math.abs(pitch)) { if(-pitch < 0) { this.mLevel.setGravity(Level.Gravity.SOUTH); } else { this.mLevel.setGravity(Level.Gravity.NORTH); } } else { if(roll < 0) { this.mLevel.setGravity(Level.Gravity.EAST); } else { this.mLevel.setGravity(Level.Gravity.WEST); } } } } } /** * creates the menu defined in the corresponding xml file */ @Override public boolean onCreateOptionsMenu(Menu menu) { if(this.mStringProperties != null) { menu.add(Menu.NONE, UIConstants.MENU_MENU_ID, Menu.NONE, this.mStringProperties.getProperty(UIConstants.MENU_PROPERTY_KEY)); menu.add(Menu.NONE, UIConstants.FROM_SEED_MENU_ID, Menu.NONE, this.mStringProperties.getProperty(UIConstants.FROM_SEED_PROPERTY_KEY)); menu.add(Menu.NONE, UIConstants.RESTART_MENU_ID, Menu.NONE, this.mStringProperties.getProperty(UIConstants.RESTART_PROPERTY_KEY)); menu.add(Menu.NONE, UIConstants.NEXT_MENU_ID, Menu.NONE, this.mStringProperties.getProperty(UIConstants.NEXT_PROPERTY_KEY)); return true; } return false; } /** * shows the Activities Menu */ @Override public boolean onOptionsItemSelected(MenuItem item) { //TODO use AndEngines Menu System! switch(item.getItemId()) { case UIConstants.MENU_MENU_ID: { if(this.mGameTypeHandler.requestLeaveToMenu()) { Intent settingsActivity = new Intent(getBaseContext(), BlockBreakerPreferencesActivity.class); this.startActivity(settingsActivity); } return true; } case UIConstants.FROM_SEED_MENU_ID: { if(!this.mTimeAttackMode) { this.showInputSeedDialog(); } return true; } case UIConstants.RESTART_MENU_ID: { this.mGameTypeHandler.requestRestart(); return true; } case UIConstants.NEXT_MENU_ID: { this.mGameTypeHandler.requestNextLevel(); return true; } default: { return super.onOptionsItemSelected(item); } } } /** * Fix for older SDK versions which don't have onBackPressed() */ @Override public boolean onKeyDown(int pKeyCode, KeyEvent pEvent) { if(USE_MENU_WORKAROUND && pKeyCode == KeyEvent.KEYCODE_BACK && pEvent.getRepeatCount() == 0) { this.onBackPressed(); } return super.onKeyDown(pKeyCode, pEvent); } /** * If the user presses the back button he is asked if he wants to quit */ @Override public void onBackPressed() { this.showCancelDialog(); } @Override public void onOrientationAccuracyChanged(OrientationData pOrientationData) { } //// Private/Package Methods //// void updateLevel(String pLevelPath, boolean pIsAsset) throws Exception { this.mSeedText.setText(""); this.mLevelPath = pLevelPath; this.mIsAsset = pIsAsset; this.loadLevelFromAsset(); this.mLevel = this.mBackupLevel.copy(); this.mLevel.start(); this.mLevel.setGameEndListener(this.mGameTypeHandler); this.mLevelSceneHandler.updateLevel(this.mLevel); } void loadLevelFromAsset() throws Exception{ throw new Exception("not Implemented!"); } void restartLevel() { this.mLevel = this.mBackupLevel.copy(); this.mLevel.start(); this.mLevel.setGameEndListener(this.mGameTypeHandler); this.mLevelSceneHandler.updateLevel(this.mLevel); } void randomLevel() { long seed = sRandomSeedObject.nextLong(); this.randomLevelFromSeed(seed); } void randomLevelFromSeed(long pSeed) { this.mSeedText.setText("Seed: " + Long.toString(pSeed)); this.mBackupLevel = LevelGenerator.createRandomLevelFromSeed(pSeed, this.mNumberOfTurns); this.mLevel = this.mBackupLevel.copy(); this.mLevel.start(); this.mLevel.setGameEndListener(this.mGameTypeHandler); this.mLevelSceneHandler.updateLevel(this.mLevel); } private void initLevel() { final Scene scene = new Scene(); this.mLevelScene = scene; this.mLevel = this.mBackupLevel.copy(); this.mLevel.start(); this.mLevel.setGameEndListener(this.mGameTypeHandler); VertexBufferObjectManager vboManager = this.mEngine.getVertexBufferObjectManager(); this.mLevelSceneHandler = new LevelSceneHandler(scene, vboManager); this.mLevelSceneHandler.initLevelScene(BlockBreakerActivity.this.mLevel, this.mSceneUIFont, this.mBlockTiledTextureRegion, this.mArrowTiledTextureRegion, this.mStringProperties); final HUD hud = new HUD(); final FPSCounter counter = new FPSCounter(); this.mEngine.registerUpdateHandler(counter); final int maxLength = "FPS: XXXXXXX".length(); final Text fps = new Text(1, 1, this.mMiscFont, "FPS:", maxLength, vboManager); hud.attachChild(fps); this.mCamera.setHUD(hud); scene.registerUpdateHandler(new TimerHandler(1/20F, true, new ITimerCallback() { @Override public void onTimePassed(TimerHandler arg0) { String fpsString = Float.toString(counter.getFPS()); int length = fpsString.length(); fps.setText("FPS: " + fpsString.substring(0, length >= 5 ? 5 : length)); } } )); scene.setBackground(new SpriteBackground(new Sprite(0,0,UIConstants.LEVEL_WIDTH, UIConstants.LEVEL_HEIGHT, BlockBreakerActivity.this.mSceneBackgroundTextureRegion, vboManager))); } void showEndDialog(final GameEndType pResult) { String resString; switch(pResult) { case WIN: { resString = this.mStringProperties.getProperty(UIConstants.WIN_GAME_PROPERTY_KEY); break; } case LOSE: { resString = this.mStringProperties.getProperty(UIConstants.LOSE_GAME_PROPERTY_KEY); break; } default: { resString = "WTF?"; break; } } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(resString + " " + this.mStringProperties.getProperty(UIConstants.RESTART_QUESTION_PROPERTY_KEY)) .setCancelable(true) .setPositiveButton(this.mStringProperties.getProperty(UIConstants.YES_PROPERTY_KEY), new DialogInterface.OnClickListener() { public void onClick(DialogInterface pDialog, int pId) { pDialog.dismiss(); BlockBreakerActivity.this.restartLevel(); } }) .setNegativeButton(this.mStringProperties.getProperty(UIConstants.NO_PROPERTY_KEY), new DialogInterface.OnClickListener() { public void onClick(DialogInterface pDialog, int pId) { pDialog.dismiss(); //TODO: Testing purposes! BlockBreakerActivity.this.randomLevel(); } }); builder.create().show(); } void showCancelDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(this.mStringProperties.getProperty(UIConstants.EXIT_GAME_QUESTION_PROPERTY_KEY)) .setCancelable(true) .setPositiveButton(this.mStringProperties.getProperty(UIConstants.YES_PROPERTY_KEY), new DialogInterface.OnClickListener() { public void onClick(DialogInterface pDialog, int pId) { pDialog.dismiss(); BlockBreakerActivity.this.finish(); } }) .setNegativeButton(this.mStringProperties.getProperty(UIConstants.NO_PROPERTY_KEY), new DialogInterface.OnClickListener() { public void onClick(DialogInterface pDialog, int pId) { pDialog.dismiss(); } }); builder.create().show(); } void showFailDialog(String pMessage) { //Don't use Properties here because this is used for failures in property loading as well AlertDialog.Builder builder = new AlertDialog.Builder(BlockBreakerActivity.this); builder.setMessage(pMessage + "\nQuitting!") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface pDialog, int pId) { BlockBreakerActivity.this.finish(); } }); builder.create().show(); } void showInputSeedDialog() { this.showInputSeedDialog( this.mStringProperties.getProperty(UIConstants.INPUT_SEED_QUESTION_PROPERTY_KEY)); } void showInputSeedDialog(String pText) { FrameLayout fl = new FrameLayout(this); final EditText input = new EditText(this); input.setGravity(Gravity.CENTER); fl.addView(input, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(pText) .setView(fl) .setCancelable(true) .setPositiveButton(this.mStringProperties.getProperty(UIConstants.OK_PROPERTY_KEY), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface pDialog, int pId) { try { long seed = Long.parseLong(input.getText().toString()); BlockBreakerActivity.this.randomLevelFromSeed(seed); pDialog.dismiss(); } catch (NumberFormatException e) { BlockBreakerActivity.this.showInputSeedDialog( BlockBreakerActivity.this.mStringProperties.getProperty( UIConstants.WRONG_SEED_INPUT_PROPERTY_KEY)); } } }) .setNegativeButton(this.mStringProperties.getProperty(UIConstants.CANCEL_PROPERTY_KEY), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface pDialog, int pId) { pDialog.dismiss(); } } ); builder.create().show(); } /** * loads the first randomly generated Level and initializes the SeedText */ private void loadFirstLevel() { long seed = sRandomSeedObject.nextLong(); this.mBackupLevel = LevelGenerator.createRandomLevelFromSeed(seed, this.mNumberOfTurns); int maxLength = "Seed: ".length() + Long.toString(Long.MAX_VALUE).length() + 1; this.mSeedText = new Text(1, UIConstants.LEVEL_HEIGHT - 15, this.mMiscFont, "Seed: " + seed, maxLength, this.mEngine.getVertexBufferObjectManager()); } private void getPrefs() { // Get the xml/preferences.xml preferences // Don't save this in a constant, because it will only be used in code here SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); this.mUseOrientSensor = prefs.getBoolean("orient_sens_pref", false); this.mTimeAttackMode = prefs.getBoolean("time_attack_pref", false); this.mNumberOfTurns = Integer.parseInt(prefs.getString("number_of_turns_pref", "16")); } //// Inner Classes & Interfaces //// interface IGameTypeHandler extends IGameEndListener { public void onLeaveFocus(); public void onEnterFocus(); public void requestNextLevel(); public boolean requestLeaveToMenu(); public void requestRestart(); public void start(); public void cleanUp(); } class DefaultGameHandler implements IGameTypeHandler { @Override public void onGameEnd(final GameEndEvent pEvt) { BlockBreakerActivity.this.runOnUiThread(new Runnable() { public void run() { BlockBreakerActivity.this.showEndDialog(pEvt.getType()); } }); } @Override public void onLeaveFocus() { //nothing to do here } @Override public void onEnterFocus() { //nothing to do here } @Override public boolean requestLeaveToMenu() { return true; } @Override public void requestRestart() { BlockBreakerActivity.this.restartLevel(); } @Override public void requestNextLevel() { BlockBreakerActivity.this.randomLevel(); } @Override public void start() { //nothing to do here } @Override public void cleanUp() { BlockBreakerActivity.this.randomLevel(); } } //TODO: Implement all this stuff class TimeAttackGameHandler implements IGameTypeHandler { @Override public void onGameEnd(GameEndEvent pEvt) { } @Override public void onEnterFocus() { } @Override public void onLeaveFocus() { } public boolean requestLeaveToMenu() { return true; } @Override public void requestRestart() { } @Override public void requestNextLevel() { } @Override public void start() { } @Override public void cleanUp() { } } }
package org.objectweb.asm.util; import org.objectweb.asm.Constants; import org.objectweb.asm.ClassReader; import org.objectweb.asm.CodeVisitor; import java.io.PrintWriter; /** * A {@link PrintClassVisitor PrintClassVisitor} that prints the ASM code that * generates the classes it visits. This class visitor can be used to quickly * write ASM code to generate some given bytecode: * <ul> * <li>write the Java source code equivalent to the bytecode you want to * generate;</li> * <li>compile it with <tt>javac</tt>;</li> * <li>make a {@link DumpClassVisitor DumpClassVisitor} visit this compiled * class (see the {@link #main main} method);</li> * <li>edit the generated source code, if necessary.</li> * </ul> * The source code printed when visiting the <tt>Hello</tt> class is the * following: * <p> * <blockquote> * <pre> * import org.objectweb.asm.*; * import java.io.FileOutputStream; * * public class Dump implements Constants { * * public static void main (String[] args) throws Exception { * * ClassWriter cw = new ClassWriter(false); * CodeVisitor cv; * * cw.visit(ACC_PUBLIC + ACC_SUPER, "Hello", "java/lang/Object", null, "Hello.java"); * * { * cv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null); * cv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); * cv.visitLdcInsn("hello"); * cv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); * cv.visitInsn(RETURN); * cv.visitMaxs(2, 1); * } * { * cv = cw.visitMethod(ACC_PUBLIC, "&lt;init&gt;", "()V", null); * cv.visitVarInsn(ALOAD, 0); * cv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "&lt;init&gt;", "()V"); * cv.visitInsn(RETURN); * cv.visitMaxs(1, 1); * } * cw.visitEnd(); * * FileOutputStream os = new FileOutputStream("Dumped.class"); * os.write(cw.toByteArray()); * os.close(); * } * } * </pre> * </blockquote> * where <tt>Hello</tt> is defined by: * <p> * <blockquote> * <pre> * public class Hello { * * public static void main (String[] args) { * System.out.println("hello"); * } * } * </pre> * </blockquote> */ public class DumpClassVisitor extends PrintClassVisitor { /** * Prints the ASM source code to generate the given class to the standard * output. * <p> * Usage: DumpClassVisitor &lt;fully qualified class name&gt; * * @param args the command line arguments. * * @throws Exception if the class cannot be found, or if an IO exception * occurs. */ public static void main (final String[] args) throws Exception { if (args.length == 0) { System.err.println("Prints the ASM code to generate the given class."); System.err.println("Usage: DumpClassVisitor <fully qualified class name>"); System.exit(-1); } ClassReader cr = new ClassReader(args[0]); cr.accept(new DumpClassVisitor(new PrintWriter(System.out)), true); } /** * Constructs a new {@link DumpClassVisitor DumpClassVisitor} object. * * @param pw the print writer to be used to print the class. */ public DumpClassVisitor (final PrintWriter pw) { super(pw); } public void visit ( final int access, final String name, final String superName, final String[] interfaces, final String sourceFile) { text.add("import org.objectweb.asm.*;\n"); text.add("import java.io.FileOutputStream;\n\n"); text.add("public class Dump implements Constants {\n\n"); text.add("public static void main (String[] args) throws Exception {\n\n"); text.add("ClassWriter cw = new ClassWriter(false);\n"); text.add("CodeVisitor cv;\n\n"); buf.setLength(0); buf.append("cw.visit("); appendAccess(access | 262144); buf.append(", "); appendConstant(buf, name); buf.append(", "); appendConstant(buf, superName); buf.append(", "); if (interfaces != null && interfaces.length > 0) { buf.append("new String[] {"); for (int i = 0; i < interfaces.length; ++i) { buf.append(i == 0 ? " " : ", "); appendConstant(buf, interfaces[i]); } buf.append(" }"); } else { buf.append("null"); } buf.append(", "); appendConstant(buf, sourceFile); buf.append(");\n\n"); text.add(buf.toString()); } public void visitInnerClass ( final String name, final String outerName, final String innerName, final int access) { buf.setLength(0); buf.append("cw.visitInnerClass("); appendConstant(buf, name); buf.append(", "); appendConstant(buf, outerName); buf.append(", "); appendConstant(buf, innerName); buf.append(", "); appendAccess(access); buf.append(");\n\n"); text.add(buf.toString()); } public void visitField ( final int access, final String name, final String desc, final Object value) { buf.setLength(0); buf.append("cw.visitField("); appendAccess(access); buf.append(", "); appendConstant(buf, name); buf.append(", "); appendConstant(buf, desc); buf.append(", "); appendConstant(buf, value); buf.append(");\n\n"); text.add(buf.toString()); } public CodeVisitor visitMethod ( final int access, final String name, final String desc, final String[] exceptions) { buf.setLength(0); buf.append("{\n").append("cv = cw.visitMethod("); appendAccess(access); buf.append(", "); appendConstant(buf, name); buf.append(", "); appendConstant(buf, desc); buf.append(", "); if (exceptions != null && exceptions.length > 0) { buf.append("new String[] {"); for (int i = 0; i < exceptions.length; ++i) { buf.append(i == 0 ? " " : ", "); appendConstant(buf, exceptions[i]); } buf.append(" });"); } else { buf.append("null);"); } buf.append("\n"); text.add(buf.toString()); PrintCodeVisitor pcv = new DumpCodeVisitor(); text.add(pcv.getText()); text.add("}\n"); return pcv; } public void visitEnd () { text.add("cw.visitEnd();\n\n"); text.add("FileOutputStream os = new FileOutputStream(\"Dumped.class\");\n"); text.add("os.write(cw.toByteArray());\n"); text.add("os.close();\n"); text.add("}\n"); text.add("}\n"); super.visitEnd(); } /** * Appends a string representation of the given access modifiers to {@link * #buf buf}. * * @param access some access modifiers. */ void appendAccess (final int access) { boolean first = true; if ((access & Constants.ACC_PUBLIC) != 0) { buf.append("ACC_PUBLIC"); first = false; } if ((access & Constants.ACC_PRIVATE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_PRIVATE"); first = false; } if ((access & Constants.ACC_PROTECTED) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_PROTECTED"); first = false; } if ((access & Constants.ACC_FINAL) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_FINAL"); first = false; } if ((access & Constants.ACC_STATIC) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_STATIC"); first = false; } if ((access & Constants.ACC_SYNCHRONIZED) != 0) { if (!first) { buf.append(" + "); } if ((access & 262144) != 0) { buf.append("ACC_SUPER"); } else { buf.append("ACC_SYNCHRONIZED"); } first = false; } if ((access & Constants.ACC_VOLATILE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_VOLATILE"); first = false; } if ((access & Constants.ACC_TRANSIENT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_TRANSIENT"); first = false; } if ((access & Constants.ACC_NATIVE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_NATIVE"); first = false; } if ((access & Constants.ACC_ABSTRACT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_ABSTRACT"); first = false; } if ((access & Constants.ACC_STRICT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_STRICT"); first = false; } if ((access & Constants.ACC_SYNTHETIC) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_SYNTHETIC"); first = false; } if ((access & Constants.ACC_DEPRECATED) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_DEPRECATED"); first = false; } if (first) { buf.append("0"); } } /** * Appends a string representation of the given constant to the given buffer. * * @param buf a string buffer. * @param cst an {@link java.lang.Integer Integer}, {@link java.lang.Float * Float}, {@link java.lang.Long Long}, {@link java.lang.Double Double} * or {@link String String} object. May be <tt>null</tt>. */ static void appendConstant (final StringBuffer buf, final Object cst) { if (cst == null) { buf.append("null"); } else if (cst instanceof String) { String s = (String)cst; buf.append("\""); for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); if (c == '\n') { buf.append("\\n"); } else if (c == '\\') { buf.append("\\\\"); } else if (c == '"') { buf.append("\\\""); } else { buf.append(c); } } buf.append("\""); } else if (cst instanceof Integer) { buf.append("new Integer(") .append(cst) .append(")"); } else if (cst instanceof Float) { buf.append("new Float(") .append(cst) .append("F)"); } else if (cst instanceof Long) { buf.append("new Long(") .append(cst) .append("L)"); } else if (cst instanceof Double) { buf.append("new Double(") .append(cst) .append(")"); } } }
package org.opencms.xml; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.types.CmsResourceTypeXmlContent; import org.opencms.file.types.I_CmsResourceType; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.relations.CmsRelation; import org.opencms.relations.CmsRelationFilter; import org.opencms.relations.CmsRelationType; import org.opencms.util.CmsStringUtil; import org.opencms.xml.content.CmsDefaultXmlContentHandler; import org.opencms.xml.content.CmsXmlContent; import org.opencms.xml.content.CmsXmlContentFactory; import org.opencms.xml.content.I_CmsXmlContentHandler; import org.opencms.xml.types.CmsXmlLocaleValue; import org.opencms.xml.types.CmsXmlNestedContentDefinition; import org.opencms.xml.types.CmsXmlStringValue; import org.opencms.xml.types.I_CmsXmlContentValue; import org.opencms.xml.types.I_CmsXmlSchemaType; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.QName; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Describes the structure definition of an XML content object.<p> * * @author Alexander Kandzior * * @version $Revision: 1.5 $ * * @since 6.0.0 */ public class CmsXmlContentDefinition implements Cloneable { /** * Enumeration of possible sequence types in a content definition. */ public enum SequenceType { /** A <code>xsd:choice</code> where the choice elements can appear more than once in a mix. */ MULTIPLE_CHOICE, /** A simple <code>xsd:sequence</code>. */ SEQUENCE, /** A <code>xsd:choice</code> where only one choice element can be selected. */ SINGLE_CHOICE } /** Constant for the XML schema attribute "mapto". */ public static final String XSD_ATTRIBUTE_DEFAULT = "default"; /** Constant for the XML schema attribute "elementFormDefault". */ public static final String XSD_ATTRIBUTE_ELEMENT_FORM_DEFAULT = "elementFormDefault"; /** Constant for the XML schema attribute "maxOccurs". */ public static final String XSD_ATTRIBUTE_MAX_OCCURS = "maxOccurs"; /** Constant for the XML schema attribute "minOccurs". */ public static final String XSD_ATTRIBUTE_MIN_OCCURS = "minOccurs"; /** Constant for the XML schema attribute "name". */ public static final String XSD_ATTRIBUTE_NAME = "name"; /** Constant for the XML schema attribute "schemaLocation". */ public static final String XSD_ATTRIBUTE_SCHEMA_LOCATION = "schemaLocation"; /** Constant for the XML schema attribute "type". */ public static final String XSD_ATTRIBUTE_TYPE = "type"; /** Constant for the XML schema attribute "use". */ public static final String XSD_ATTRIBUTE_USE = "use"; /** Constant for the XML schema attribute value "language". */ public static final String XSD_ATTRIBUTE_VALUE_LANGUAGE = "language"; /** Constant for the XML schema attribute value "1". */ public static final String XSD_ATTRIBUTE_VALUE_ONE = "1"; /** Constant for the XML schema attribute value "optional". */ public static final String XSD_ATTRIBUTE_VALUE_OPTIONAL = "optional"; /** Constant for the XML schema attribute value "qualified". */ public static final String XSD_ATTRIBUTE_VALUE_QUALIFIED = "qualified"; /** Constant for the XML schema attribute value "required". */ public static final String XSD_ATTRIBUTE_VALUE_REQUIRED = "required"; /** Constant for the XML schema attribute value "unbounded". */ public static final String XSD_ATTRIBUTE_VALUE_UNBOUNDED = "unbounded"; /** Constant for the XML schema attribute value "0". */ public static final String XSD_ATTRIBUTE_VALUE_ZERO = "0"; /** The opencms default type definition include. */ public static final String XSD_INCLUDE_OPENCMS = CmsXmlEntityResolver.OPENCMS_SCHEME + "opencms-xmlcontent.xsd"; /** The schema definition namespace. */ public static final Namespace XSD_NAMESPACE = Namespace.get("xsd", "http: /** Constant for the "annotation" node in the XML schema namespace. */ public static final QName XSD_NODE_ANNOTATION = QName.get("annotation", XSD_NAMESPACE); /** Constant for the "appinfo" node in the XML schema namespace. */ public static final QName XSD_NODE_APPINFO = QName.get("appinfo", XSD_NAMESPACE); /** Constant for the "attribute" node in the XML schema namespace. */ public static final QName XSD_NODE_ATTRIBUTE = QName.get("attribute", XSD_NAMESPACE); /** Constant for the "choice" node in the XML schema namespace. */ public static final QName XSD_NODE_CHOICE = QName.get("choice", XSD_NAMESPACE); /** Constant for the "complexType" node in the XML schema namespace. */ public static final QName XSD_NODE_COMPLEXTYPE = QName.get("complexType", XSD_NAMESPACE); /** Constant for the "element" node in the XML schema namespace. */ public static final QName XSD_NODE_ELEMENT = QName.get("element", XSD_NAMESPACE); /** Constant for the "include" node in the XML schema namespace. */ public static final QName XSD_NODE_INCLUDE = QName.get("include", XSD_NAMESPACE); /** Constant for the "schema" node in the XML schema namespace. */ public static final QName XSD_NODE_SCHEMA = QName.get("schema", XSD_NAMESPACE); /** Constant for the "sequence" node in the XML schema namespace. */ public static final QName XSD_NODE_SEQUENCE = QName.get("sequence", XSD_NAMESPACE); /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsXmlContentDefinition.class); /** Null schema type value, required for map lookups. */ private static final I_CmsXmlSchemaType NULL_SCHEMA_TYPE = new CmsXmlStringValue("NULL", "0", "0"); /** Max occurs value for xsd:choice definitions. */ private int m_choiceMaxOccurs; /** The XML content handler. */ private I_CmsXmlContentHandler m_contentHandler; /** The Map of configured types indexed by the element xpath. */ private Map<String, I_CmsXmlSchemaType> m_elementTypes; /** The set of included additional XML content definitions. */ private Set<CmsXmlContentDefinition> m_includes; /** The inner element name of the content definition (type sequence). */ private String m_innerName; /** The outer element name of the content definition (language sequence). */ private String m_outerName; /** The XML document from which the schema was unmarshalled. */ private Document m_schemaDocument; /** The location from which the XML schema was read (XML system id). */ private String m_schemaLocation; /** Indicates the sequence type of this content definition. */ private SequenceType m_sequenceType; /** The main type name of this XML content definition. */ private String m_typeName; /** The Map of configured types. */ private Map<String, I_CmsXmlSchemaType> m_types; /** The type sequence. */ private List<I_CmsXmlSchemaType> m_typeSequence; /** * Creates a new XML content definition.<p> * * @param innerName the inner element name to use for the content definiton * @param schemaLocation the location from which the XML schema was read (system id) */ public CmsXmlContentDefinition(String innerName, String schemaLocation) { this(innerName + "s", innerName, schemaLocation); } /** * Creates a new XML content definition.<p> * * @param outerName the outer element name to use for the content definition * @param innerName the inner element name to use for the content definition * @param schemaLocation the location from which the XML schema was read (system id) */ public CmsXmlContentDefinition(String outerName, String innerName, String schemaLocation) { m_outerName = outerName; m_innerName = innerName; setInnerName(innerName); m_typeSequence = new ArrayList<I_CmsXmlSchemaType>(); m_types = new HashMap<String, I_CmsXmlSchemaType>(); m_includes = new HashSet<CmsXmlContentDefinition>(); m_schemaLocation = schemaLocation; m_contentHandler = new CmsDefaultXmlContentHandler(); m_sequenceType = SequenceType.SEQUENCE; m_elementTypes = new HashMap<String, I_CmsXmlSchemaType>(); } /** * Required empty constructor for clone operation.<p> */ protected CmsXmlContentDefinition() { // noop, required for clone operation } /** * Factory method that returns a XML content definition instance for a given resource.<p> * * @param cms the cms-object * @param resource the resource * * @return the XML content definition * * @throws CmsException if something goes wrong */ public static CmsXmlContentDefinition getContentDefinitionForResource(CmsObject cms, CmsResource resource) throws CmsException { CmsXmlContentDefinition contentDef = null; I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(resource.getTypeId()); String schema = resType.getConfiguration().get(CmsResourceTypeXmlContent.CONFIGURATION_SCHEMA); if (schema != null) { try { // this wont in most cases read the file content contentDef = unmarshal(cms, schema); } catch (CmsException e) { // this should never happen, unless the configured schema is different than the schema in the xml if (!LOG.isDebugEnabled()) { LOG.warn(e); } LOG.debug(e.getLocalizedMessage(), e); } } if (contentDef == null) { // could still be empty since it is not mandatory to configure the resource type // try through the xsd relation List<CmsRelation> relations = cms.getRelationsForResource( resource, CmsRelationFilter.TARGETS.filterType(CmsRelationType.XSD)); if ((relations != null) && !relations.isEmpty()) { CmsXmlEntityResolver entityResolver = new CmsXmlEntityResolver(cms); String xsd = cms.getSitePath(relations.get(0).getTarget(cms, CmsResourceFilter.ALL)); contentDef = entityResolver.getCachedContentDefinition(xsd); } } if (contentDef == null) { // could still be empty if the xml content has not been saved with a version newer than 7.9.0 // so, to unmarshall is the only possibility left CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, cms.readFile(resource)); contentDef = content.getContentDefinition(); } return contentDef; } /** * Returns a content handler instance for the given resource.<p> * * @param cms the cms-object * @param resource the resource * * @return the content handler * * @throws CmsException if something goes wrong */ public static I_CmsXmlContentHandler getContentHandlerForResource(CmsObject cms, CmsResource resource) throws CmsException { return getContentDefinitionForResource(cms, resource).getContentHandler(); } /** * Factory method to unmarshal (read) a XML content definition instance from a byte array * that contains XML data.<p> * * @param xmlData the XML data in a byte array * @param schemaLocation the location from which the XML schema was read (system id) * @param resolver the XML entity resolver to use * * @return a XML content definition instance unmarshalled from the byte array * * @throws CmsXmlException if something goes wrong */ public static CmsXmlContentDefinition unmarshal(byte[] xmlData, String schemaLocation, EntityResolver resolver) throws CmsXmlException { CmsXmlContentDefinition result = getCachedContentDefinition(schemaLocation, resolver); if (result == null) { // content definition was not found in the cache, unmarshal the XML document result = unmarshalInternal(CmsXmlUtils.unmarshalHelper(xmlData, resolver), schemaLocation, resolver); } return result; } /** * Factory method to unmarshal (read) a XML content definition instance from the OpenCms VFS resource name.<p> * * @param cms the current users CmsObject * @param resourcename the resource name to unmarshal the XML content definition from * * @return a XML content definition instance unmarshalled from the VFS resource * * @throws CmsXmlException if something goes wrong */ public static CmsXmlContentDefinition unmarshal(CmsObject cms, String resourcename) throws CmsXmlException { CmsXmlEntityResolver resolver = new CmsXmlEntityResolver(cms); String schemaLocation = CmsXmlEntityResolver.OPENCMS_SCHEME.concat(resourcename.substring(1)); CmsXmlContentDefinition result = getCachedContentDefinition(schemaLocation, resolver); if (result == null) { // content definition was not found in the cache, unmarshal the XML document InputSource source = resolver.resolveEntity(null, schemaLocation); result = unmarshalInternal(CmsXmlUtils.unmarshalHelper(source, resolver), schemaLocation, resolver); } return result; } /** * Factory method to unmarshal (read) a XML content definition instance from a XML document.<p> * * This method does additional validation to ensure the document has the required * XML structure for a OpenCms content definition schema.<p> * * @param document the XML document to generate a XML content definition from * @param schemaLocation the location from which the XML schema was read (system id) * * @return a XML content definition instance unmarshalled from the XML document * * @throws CmsXmlException if something goes wrong */ public static CmsXmlContentDefinition unmarshal(Document document, String schemaLocation) throws CmsXmlException { EntityResolver resolver = document.getEntityResolver(); CmsXmlContentDefinition result = getCachedContentDefinition(schemaLocation, resolver); if (result == null) { // content definition was not found in the cache, unmarshal the XML document result = unmarshalInternal(document, schemaLocation, resolver); } return result; } /** * Factory method to unmarshal (read) a XML content definition instance from a XML InputSource.<p> * * @param source the XML InputSource to use * @param schemaLocation the location from which the XML schema was read (system id) * @param resolver the XML entity resolver to use * * @return a XML content definition instance unmarshalled from the InputSource * * @throws CmsXmlException if something goes wrong */ public static CmsXmlContentDefinition unmarshal(InputSource source, String schemaLocation, EntityResolver resolver) throws CmsXmlException { CmsXmlContentDefinition result = getCachedContentDefinition(schemaLocation, resolver); if (result == null) { // content definition was not found in the cache, unmarshal the XML document result = unmarshalInternal(CmsXmlUtils.unmarshalHelper(source, resolver), schemaLocation, resolver); } return result; } /** * Factory method to unmarshal (read) a XML content definition instance from a given XML schema location.<p> * * The XML content definition data to unmarshal will be read from the provided schema location using * an XML InputSource.<p> * * @param schemaLocation the location from which to read the XML schema (system id) * @param resolver the XML entity resolver to use * * @return a XML content definition instance unmarshalled from the InputSource * * @throws CmsXmlException if something goes wrong * @throws SAXException if the XML schema location could not be converted to an XML InputSource * @throws IOException if the XML schema location could not be converted to an XML InputSource */ public static CmsXmlContentDefinition unmarshal(String schemaLocation, EntityResolver resolver) throws CmsXmlException, SAXException, IOException { CmsXmlContentDefinition result = getCachedContentDefinition(schemaLocation, resolver); if (result == null) { // content definition was not found in the cache, unmarshal the XML document InputSource source = resolver.resolveEntity(null, schemaLocation); result = unmarshalInternal(CmsXmlUtils.unmarshalHelper(source, resolver), schemaLocation, resolver); } return result; } /** * Factory method to unmarshal (read) a XML content definition instance from a String * that contains XML data.<p> * * @param xmlData the XML data in a String * @param schemaLocation the location from which the XML schema was read (system id) * @param resolver the XML entity resolver to use * * @return a XML content definition instance unmarshalled from the byte array * * @throws CmsXmlException if something goes wrong */ public static CmsXmlContentDefinition unmarshal(String xmlData, String schemaLocation, EntityResolver resolver) throws CmsXmlException { CmsXmlContentDefinition result = getCachedContentDefinition(schemaLocation, resolver); if (result == null) { // content definition was not found in the cache, unmarshal the XML document result = unmarshalInternal(CmsXmlUtils.unmarshalHelper(xmlData, resolver), schemaLocation, resolver); } return result; } /** * Creates the name of the type attribute from the given content name.<p> * * @param name the name to use * * @return the name of the type attribute */ protected static String createTypeName(String name) { StringBuffer result = new StringBuffer(32); result.append("OpenCms"); result.append(name.substring(0, 1).toUpperCase()); if (name.length() > 1) { result.append(name.substring(1)); } return result.toString(); } /** * Validates if a given attribute exists at the given element with an (optional) specified value.<p> * * If the required value is not <code>null</code>, the attribute must have exactly this * value set.<p> * * If no value is required, some simple validation is performed on the attribute value, * like a check that the value does not have leading or trailing white spaces.<p> * * @param element the element to validate * @param attributeName the attribute to check for * @param requiredValue the required value of the attribute, or <code>null</code> if any value is allowed * * @return the value of the attribute * * @throws CmsXmlException if the element does not have the required attribute set, or if the validation fails */ protected static String validateAttribute(Element element, String attributeName, String requiredValue) throws CmsXmlException { Attribute attribute = element.attribute(attributeName); if (attribute == null) { throw new CmsXmlException(Messages.get().container( Messages.ERR_EL_MISSING_ATTRIBUTE_2, element.getUniquePath(), attributeName)); } String value = attribute.getValue(); if (requiredValue == null) { if (CmsStringUtil.isEmptyOrWhitespaceOnly(value) || !value.equals(value.trim())) { throw new CmsXmlException(Messages.get().container( Messages.ERR_EL_BAD_ATTRIBUTE_WS_3, element.getUniquePath(), attributeName, value)); } } else { if (!requiredValue.equals(value)) { throw new CmsXmlException(Messages.get().container( Messages.ERR_EL_BAD_ATTRIBUTE_VALUE_4, new Object[] {element.getUniquePath(), attributeName, requiredValue, value})); } } return value; } /** * Validates if a given element has exactly the required attributes set.<p> * * @param element the element to validate * @param requiredAttributes the list of required attributes * @param optionalAttributes the list of optional attributes * * @throws CmsXmlException if the validation fails */ protected static void validateAttributesExists( Element element, String[] requiredAttributes, String[] optionalAttributes) throws CmsXmlException { if (element.attributeCount() < requiredAttributes.length) { throw new CmsXmlException(Messages.get().container( Messages.ERR_EL_ATTRIBUTE_TOOFEW_3, element.getUniquePath(), new Integer(requiredAttributes.length), new Integer(element.attributeCount()))); } if (element.attributeCount() > (requiredAttributes.length + optionalAttributes.length)) { throw new CmsXmlException(Messages.get().container( Messages.ERR_EL_ATTRIBUTE_TOOMANY_3, element.getUniquePath(), new Integer(requiredAttributes.length + optionalAttributes.length), new Integer(element.attributeCount()))); } for (int i = 0; i < requiredAttributes.length; i++) { String attributeName = requiredAttributes[i]; if (element.attribute(attributeName) == null) { throw new CmsXmlException(Messages.get().container( Messages.ERR_EL_MISSING_ATTRIBUTE_2, element.getUniquePath(), attributeName)); } } List<String> rA = Arrays.asList(requiredAttributes); List<String> oA = Arrays.asList(optionalAttributes); for (int i = 0; i < element.attributes().size(); i++) { String attributeName = element.attribute(i).getName(); if (!rA.contains(attributeName) && !oA.contains(attributeName)) { throw new CmsXmlException(Messages.get().container( Messages.ERR_EL_INVALID_ATTRIBUTE_2, element.getUniquePath(), attributeName)); } } } /** * Validates the given element as a complex type sequence.<p> * * @param element the element to validate * @param includes the XML schema includes * * @return a data structure containing the validated complex type sequence data * * @throws CmsXmlException if the validation fails */ protected static CmsXmlComplexTypeSequence validateComplexTypeSequence( Element element, Set<CmsXmlContentDefinition> includes) throws CmsXmlException { validateAttributesExists(element, new String[] {XSD_ATTRIBUTE_NAME}, new String[0]); String name = validateAttribute(element, XSD_ATTRIBUTE_NAME, null); // now check the type definition list List<Element> mainElements = CmsXmlGenericWrapper.elements(element); if ((mainElements.size() != 1) && (mainElements.size() != 2)) { throw new CmsXmlException(Messages.get().container( Messages.ERR_TS_SUBELEMENT_COUNT_2, element.getUniquePath(), new Integer(mainElements.size()))); } boolean hasLanguageAttribute = false; if (mainElements.size() == 2) { // two elements in the master list: the second must be the "language" attribute definition Element typeAttribute = mainElements.get(1); if (!XSD_NODE_ATTRIBUTE.equals(typeAttribute.getQName())) { throw new CmsXmlException(Messages.get().container( Messages.ERR_CD_ELEMENT_NAME_3, typeAttribute.getUniquePath(), XSD_NODE_ATTRIBUTE.getQualifiedName(), typeAttribute.getQName().getQualifiedName())); } validateAttribute(typeAttribute, XSD_ATTRIBUTE_NAME, XSD_ATTRIBUTE_VALUE_LANGUAGE); validateAttribute(typeAttribute, XSD_ATTRIBUTE_TYPE, CmsXmlLocaleValue.TYPE_NAME); try { validateAttribute(typeAttribute, XSD_ATTRIBUTE_USE, XSD_ATTRIBUTE_VALUE_REQUIRED); } catch (CmsXmlException e) { validateAttribute(typeAttribute, XSD_ATTRIBUTE_USE, XSD_ATTRIBUTE_VALUE_OPTIONAL); } // no error: then the language attribute is valid hasLanguageAttribute = true; } // the type of the sequence SequenceType sequenceType; int choiceMaxOccurs = 0; // check the main element type sequence Element typeSequenceElement = mainElements.get(0); if (!XSD_NODE_SEQUENCE.equals(typeSequenceElement.getQName())) { if (!XSD_NODE_CHOICE.equals(typeSequenceElement.getQName())) { throw new CmsXmlException(Messages.get().container( Messages.ERR_CD_ELEMENT_NAME_4, new Object[] { typeSequenceElement.getUniquePath(), XSD_NODE_SEQUENCE.getQualifiedName(), XSD_NODE_CHOICE.getQualifiedName(), typeSequenceElement.getQName().getQualifiedName()})); } else { // this is a xsd:choice, check if this is single or multiple choice String minOccursStr = typeSequenceElement.attributeValue(XSD_ATTRIBUTE_MIN_OCCURS); int minOccurs = 1; if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(minOccursStr)) { try { minOccurs = Integer.parseInt(minOccursStr.trim()); } catch (NumberFormatException e) { throw new CmsXmlException(Messages.get().container( Messages.ERR_EL_BAD_ATTRIBUTE_3, element.getUniquePath(), XSD_ATTRIBUTE_MIN_OCCURS, minOccursStr == null ? "1" : minOccursStr)); } } String maxOccursStr = typeSequenceElement.attributeValue(XSD_ATTRIBUTE_MAX_OCCURS); choiceMaxOccurs = 1; if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(maxOccursStr)) { if (CmsXmlContentDefinition.XSD_ATTRIBUTE_VALUE_UNBOUNDED.equals(maxOccursStr.trim())) { choiceMaxOccurs = Integer.MAX_VALUE; } else { try { choiceMaxOccurs = Integer.parseInt(maxOccursStr.trim()); } catch (NumberFormatException e) { throw new CmsXmlException(Messages.get().container( Messages.ERR_EL_BAD_ATTRIBUTE_3, element.getUniquePath(), XSD_ATTRIBUTE_MAX_OCCURS, maxOccursStr)); } } } if ((minOccurs == 0) && (choiceMaxOccurs == 1)) { // minOccurs 0 and maxOccurs 1, this is a single choice sequence sequenceType = SequenceType.SINGLE_CHOICE; } else { // this is a multiple choice sequence if (minOccurs > choiceMaxOccurs) { throw new CmsXmlException(Messages.get().container( Messages.ERR_EL_BAD_ATTRIBUTE_3, element.getUniquePath(), XSD_ATTRIBUTE_MIN_OCCURS, minOccursStr == null ? "1" : minOccursStr)); } sequenceType = SequenceType.MULTIPLE_CHOICE; } } } else { // this is a simple sequence sequenceType = SequenceType.SEQUENCE; } // check the type definition sequence List<Element> typeSequenceElements = CmsXmlGenericWrapper.elements(typeSequenceElement); if (typeSequenceElements.size() < 1) { throw new CmsXmlException(Messages.get().container( Messages.ERR_TS_SUBELEMENT_TOOFEW_3, typeSequenceElement.getUniquePath(), new Integer(1), new Integer(typeSequenceElements.size()))); } // now add all type definitions from the schema List<I_CmsXmlSchemaType> sequence = new ArrayList<I_CmsXmlSchemaType>(); if (hasLanguageAttribute) { // only generate types for sequence node with language attribute CmsXmlContentTypeManager typeManager = OpenCms.getXmlContentTypeManager(); Iterator<Element> i = typeSequenceElements.iterator(); while (i.hasNext()) { Element typeElement = i.next(); if (sequenceType != SequenceType.SEQUENCE) { // in case of xsd:choice, need to make sure "minOccurs" for all type elements is 0 String minOccursStr = typeElement.attributeValue(XSD_ATTRIBUTE_MIN_OCCURS); int minOccurs = 1; if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(minOccursStr)) { try { minOccurs = Integer.parseInt(minOccursStr.trim()); } catch (NumberFormatException e) { // ignore } } // minOccurs must be "0" if (minOccurs != 0) { throw new CmsXmlException(Messages.get().container( Messages.ERR_EL_BAD_ATTRIBUTE_3, typeElement.getUniquePath(), XSD_ATTRIBUTE_MIN_OCCURS, minOccursStr == null ? "1" : minOccursStr)); } } // create the type with the type manager I_CmsXmlSchemaType type = typeManager.getContentType(typeElement, includes); if (sequenceType == SequenceType.MULTIPLE_CHOICE) { // if this is a multiple choice sequence, // all elements must have "minOccurs" 0 or 1 and "maxOccurs" of 1 if ((type.getMinOccurs() < 0) || (type.getMinOccurs() > 1) || (type.getMaxOccurs() != 1)) { throw new CmsXmlException(Messages.get().container( Messages.ERR_EL_BAD_ATTRIBUTE_3, typeElement.getUniquePath(), XSD_ATTRIBUTE_MAX_OCCURS, typeElement.attributeValue(XSD_ATTRIBUTE_MAX_OCCURS))); } } sequence.add(type); } } else { // generate a nested content definition for the main type sequence Element e = typeSequenceElements.get(0); String typeName = validateAttribute(e, XSD_ATTRIBUTE_NAME, null); String minOccurs = validateAttribute(e, XSD_ATTRIBUTE_MIN_OCCURS, XSD_ATTRIBUTE_VALUE_ZERO); String maxOccurs = validateAttribute(e, XSD_ATTRIBUTE_MAX_OCCURS, XSD_ATTRIBUTE_VALUE_UNBOUNDED); validateAttribute(e, XSD_ATTRIBUTE_TYPE, createTypeName(typeName)); CmsXmlNestedContentDefinition cd = new CmsXmlNestedContentDefinition(null, typeName, minOccurs, maxOccurs); sequence.add(cd); } // return a data structure with the collected values return new CmsXmlComplexTypeSequence(name, sequence, hasLanguageAttribute, sequenceType, choiceMaxOccurs); } /** * Looks up the given XML content definition system id in the internal content definition cache.<p> * * @param schemaLocation the system id of the XML content definition to look up * @param resolver the XML entity resolver to use (contains the cache) * * @return the XML content definition found, or null if no definition is cached for the given system id */ private static CmsXmlContentDefinition getCachedContentDefinition(String schemaLocation, EntityResolver resolver) { if (resolver instanceof CmsXmlEntityResolver) { // check for a cached version of this content definition CmsXmlEntityResolver cmsResolver = (CmsXmlEntityResolver)resolver; return cmsResolver.getCachedContentDefinition(schemaLocation); } return null; } /** * Internal method to unmarshal (read) a XML content definition instance from a XML document.<p> * * It is assumed that the XML content definition cache has already been tested and the document * has not been found in the cache. After the XML content definition has been successfully created, * it is placed in the cache.<p> * * @param document the XML document to generate a XML content definition from * @param schemaLocation the location from which the XML schema was read (system id) * @param resolver the XML entity resolver used by the given XML document * * @return a XML content definition instance unmarshalled from the XML document * * @throws CmsXmlException if something goes wrong */ private static CmsXmlContentDefinition unmarshalInternal( Document document, String schemaLocation, EntityResolver resolver) throws CmsXmlException { // analyze the document and generate the XML content type definition Element root = document.getRootElement(); if (!XSD_NODE_SCHEMA.equals(root.getQName())) { // schema node is required throw new CmsXmlException(Messages.get().container(Messages.ERR_CD_NO_SCHEMA_NODE_0)); } List<Element> includes = CmsXmlGenericWrapper.elements(root, XSD_NODE_INCLUDE); if (includes.size() < 1) { // one include is required throw new CmsXmlException(Messages.get().container(Messages.ERR_CD_ONE_INCLUDE_REQUIRED_0)); } Element include = includes.get(0); String target = validateAttribute(include, XSD_ATTRIBUTE_SCHEMA_LOCATION, null); if (!XSD_INCLUDE_OPENCMS.equals(target)) { // the first include must point to the default OpenCms standard schema include throw new CmsXmlException(Messages.get().container( Messages.ERR_CD_FIRST_INCLUDE_2, XSD_INCLUDE_OPENCMS, target)); } boolean recursive = false; Set<CmsXmlContentDefinition> nestedDefinitions = new HashSet<CmsXmlContentDefinition>(); if (includes.size() > 1) { // resolve additional, nested include calls for (int i = 1; i < includes.size(); i++) { Element inc = includes.get(i); String schemaLoc = validateAttribute(inc, XSD_ATTRIBUTE_SCHEMA_LOCATION, null); if (!(schemaLoc.equals(schemaLocation))) { InputSource source = null; try { source = resolver.resolveEntity(null, schemaLoc); } catch (Exception e) { throw new CmsXmlException(Messages.get().container(Messages.ERR_CD_BAD_INCLUDE_1, schemaLoc)); } CmsXmlContentDefinition xmlContentDefinition = unmarshal(source, schemaLoc, resolver); nestedDefinitions.add(xmlContentDefinition); } else { // recursion recursive = true; } } } List<Element> elements = CmsXmlGenericWrapper.elements(root, XSD_NODE_ELEMENT); if (elements.size() != 1) { // only one root element is allowed throw new CmsXmlException(Messages.get().container( Messages.ERR_CD_ROOT_ELEMENT_COUNT_1, XSD_INCLUDE_OPENCMS, new Integer(elements.size()))); } // collect the data from the root element node Element main = elements.get(0); String name = validateAttribute(main, XSD_ATTRIBUTE_NAME, null); // now process the complex types List<Element> complexTypes = CmsXmlGenericWrapper.elements(root, XSD_NODE_COMPLEXTYPE); if (complexTypes.size() != 2) { // exactly two complex types are required throw new CmsXmlException(Messages.get().container( Messages.ERR_CD_COMPLEX_TYPE_COUNT_1, new Integer(complexTypes.size()))); } // get the outer element sequence, this must be the first element CmsXmlComplexTypeSequence outerSequence = validateComplexTypeSequence(complexTypes.get(0), nestedDefinitions); CmsXmlNestedContentDefinition outer = (CmsXmlNestedContentDefinition)outerSequence.getSequence().get(0); // make sure the inner and outer element names are as required String outerTypeName = createTypeName(name); String innerTypeName = createTypeName(outer.getName()); validateAttribute(complexTypes.get(0), XSD_ATTRIBUTE_NAME, outerTypeName); validateAttribute(complexTypes.get(1), XSD_ATTRIBUTE_NAME, innerTypeName); validateAttribute(main, XSD_ATTRIBUTE_TYPE, outerTypeName); // generate the result XML content definition CmsXmlContentDefinition result = new CmsXmlContentDefinition(name, null, schemaLocation); // set the nested definitions result.m_includes = nestedDefinitions; // set the schema document result.m_schemaDocument = document; // the inner name is the element name set in the outer sequence result.setInnerName(outer.getName()); if (recursive) { nestedDefinitions.add(result); } // get the inner element sequence, this must be the second element CmsXmlComplexTypeSequence innerSequence = validateComplexTypeSequence(complexTypes.get(1), nestedDefinitions); // add the types from the main sequence node Iterator<I_CmsXmlSchemaType> it = innerSequence.getSequence().iterator(); while (it.hasNext()) { result.addType(it.next()); } // store if this content definition contains a xsd:choice sequence result.m_sequenceType = innerSequence.getSequenceType(); result.m_choiceMaxOccurs = innerSequence.getChoiceMaxOccurs(); // resolve the XML content handler information List<Element> annotations = CmsXmlGenericWrapper.elements(root, XSD_NODE_ANNOTATION); I_CmsXmlContentHandler contentHandler = null; Element appInfoElement = null; if (annotations.size() > 0) { List<Element> appinfos = CmsXmlGenericWrapper.elements(annotations.get(0), XSD_NODE_APPINFO); if (appinfos.size() > 0) { // the first appinfo node contains the specific XML content data appInfoElement = appinfos.get(0); // check for a special content handler in the appinfo node Element handlerElement = appInfoElement.element("handler"); if (handlerElement != null) { String className = handlerElement.attributeValue("class"); if (className != null) { contentHandler = OpenCms.getXmlContentTypeManager().getContentHandler(className, schemaLocation); } } } } if (contentHandler == null) { // if no content handler is defined, the default handler is used contentHandler = OpenCms.getXmlContentTypeManager().getContentHandler( CmsDefaultXmlContentHandler.class.getName(), name); } // analyze the app info node with the selected XML content handler contentHandler.initialize(appInfoElement, result); result.m_contentHandler = contentHandler; result.freeze(); if (resolver instanceof CmsXmlEntityResolver) { // put the generated content definition in the cache ((CmsXmlEntityResolver)resolver).cacheContentDefinition(schemaLocation, result); } return result; } /** * Adds the missing default XML according to this content definition to the given document element.<p> * * In case the root element already contains sub nodes, only missing sub nodes are added.<p> * * @param cms the current users OpenCms context * @param document the document where the XML is added in (required for default XML generation) * @param root the root node to add the missing XML for * @param locale the locale to add the XML for * * @return the given root element with the missing content added */ public Element addDefaultXml(CmsObject cms, I_CmsXmlDocument document, Element root, Locale locale) { Iterator<I_CmsXmlSchemaType> i = m_typeSequence.iterator(); int currentPos = 0; List<Element> allElements = CmsXmlGenericWrapper.elements(root); while (i.hasNext()) { I_CmsXmlSchemaType type = i.next(); // check how many elements of this type already exist in the XML String elementName = type.getName(); List<Element> elements = CmsXmlGenericWrapper.elements(root, elementName); currentPos += elements.size(); for (int j = elements.size(); j < type.getMinOccurs(); j++) { // append the missing elements Element typeElement = type.generateXml(cms, document, root, locale); // need to check for default value again because the of appinfo "mappings" node I_CmsXmlContentValue value = type.createValue(document, typeElement, locale); String defaultValue = document.getContentDefinition().getContentHandler().getDefault(cms, value, locale); if (defaultValue != null) { // only if there is a default value available use it to overwrite the initial default value.setStringValue(cms, defaultValue); } // re-sort elements as they have been appended to the end of the XML root, not at the correct position typeElement.detach(); allElements.add(currentPos, typeElement); currentPos++; } } return root; } /** * Adds a nested (included) XML content definition.<p> * * @param nestedSchema the nested (included) XML content definition to add */ public void addInclude(CmsXmlContentDefinition nestedSchema) { m_includes.add(nestedSchema); } /** * Adds the given content type.<p> * * @param type the content type to add * * @throws CmsXmlException in case an unregistered type is added */ public void addType(I_CmsXmlSchemaType type) throws CmsXmlException { // check if the type to add actually exists in the type manager CmsXmlContentTypeManager typeManager = OpenCms.getXmlContentTypeManager(); if (type.isSimpleType() && (typeManager.getContentType(type.getTypeName()) == null)) { throw new CmsXmlException(Messages.get().container(Messages.ERR_UNREGISTERED_TYPE_1, type.getTypeName())); } // add the type to the internal type sequence and lookup table m_typeSequence.add(type); m_types.put(type.getName(), type); // store reference to the content definition in the type type.setContentDefinition(this); } /** * Creates a clone of this XML content definition.<p> * * @return a clone of this XML content definition */ @Override public Object clone() { CmsXmlContentDefinition result = new CmsXmlContentDefinition(); result.m_innerName = m_innerName; result.m_schemaLocation = m_schemaLocation; result.m_typeSequence = m_typeSequence; result.m_types = m_types; result.m_contentHandler = m_contentHandler; result.m_typeName = m_typeName; result.m_includes = m_includes; result.m_sequenceType = m_sequenceType; result.m_choiceMaxOccurs = m_choiceMaxOccurs; result.m_elementTypes = m_elementTypes; return result; } /** * Generates the default XML content for this content definition, and append it to the given root element.<p> * * Please note: The default values for the annotations are read from the content definition of the given * document. For a nested content definitions, this means that all defaults are set in the annotations of the * "outer" or "main" content definition.<p> * * @param cms the current users OpenCms context * @param document the OpenCms XML document the XML is created for * @param root the node of the document where to append the generated XML to * @param locale the locale to create the default element in the document with * * @return the default XML content for this content definition, and append it to the given root element */ public Element createDefaultXml(CmsObject cms, I_CmsXmlDocument document, Element root, Locale locale) { Iterator<I_CmsXmlSchemaType> i = m_typeSequence.iterator(); while (i.hasNext()) { I_CmsXmlSchemaType type = i.next(); for (int j = 0; j < type.getMinOccurs(); j++) { Element typeElement = type.generateXml(cms, document, root, locale); // need to check for default value again because of the appinfo "mappings" node I_CmsXmlContentValue value = type.createValue(document, typeElement, locale); String defaultValue = document.getContentDefinition().getContentHandler().getDefault(cms, value, locale); if (defaultValue != null) { // only if there is a default value available use it to overwrite the initial default value.setStringValue(cms, defaultValue); } } } return root; } /** * Generates a valid XML document according to the XML schema of this content definition.<p> * * @param cms the current users OpenCms context * @param document the OpenCms XML document the XML is created for * @param locale the locale to create the default element in the document with * * @return a valid XML document according to the XML schema of this content definition */ public Document createDocument(CmsObject cms, I_CmsXmlDocument document, Locale locale) { Document doc = DocumentHelper.createDocument(); Element root = doc.addElement(getOuterName()); root.add(I_CmsXmlSchemaType.XSI_NAMESPACE); root.addAttribute(I_CmsXmlSchemaType.XSI_NAMESPACE_ATTRIBUTE_NO_SCHEMA_LOCATION, getSchemaLocation()); createLocale(cms, document, root, locale); return doc; } /** * Generates a valid locale (language) element for the XML schema of this content definition.<p> * * @param cms the current users OpenCms context * @param document the OpenCms XML document the XML is created for * @param root the root node of the document where to append the locale to * @param locale the locale to create the default element in the document with * * @return a valid XML element for the locale according to the XML schema of this content definition */ public Element createLocale(CmsObject cms, I_CmsXmlDocument document, Element root, Locale locale) { // add an element with a "locale" attribute to the given root node Element element = root.addElement(getInnerName()); element.addAttribute(XSD_ATTRIBUTE_VALUE_LANGUAGE, locale.toString()); // now generate the default XML for the element return createDefaultXml(cms, document, element, locale); } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof CmsXmlContentDefinition)) { return false; } CmsXmlContentDefinition other = (CmsXmlContentDefinition)obj; if (!getInnerName().equals(other.getInnerName())) { return false; } if (!getOuterName().equals(other.getOuterName())) { return false; } return m_typeSequence.equals(other.m_typeSequence); } /** * Freezes this content definition, making all internal data structures * unmodifiable.<p> * * This is required to prevent modification of a cached content definition.<p> */ public void freeze() { m_types = Collections.unmodifiableMap(m_types); m_typeSequence = Collections.unmodifiableList(m_typeSequence); } /** * Returns the maxOccurs value for the choice in case this is a <code>xsd:choice</code> content definition.<p> * * This content definition is a <code>xsd:choice</code> sequence if the returned value is larger then 0.<p> * * @return the maxOccurs value for the choice in case this is a <code>xsd:choice</code> content definition */ public int getChoiceMaxOccurs() { return m_choiceMaxOccurs; } /** * Returns the selected XML content handler for this XML content definition.<p> * * If no specific XML content handler was provided in the "appinfo" node of the * XML schema, the default XML content handler <code>{@link CmsDefaultXmlContentHandler}</code> is used.<p> * * @return the contentHandler */ public I_CmsXmlContentHandler getContentHandler() { return m_contentHandler; } /** * Returns the set of nested (included) XML content definitions.<p> * * @return the set of nested (included) XML content definitions */ public Set<CmsXmlContentDefinition> getIncludes() { return m_includes; } /** * Returns the inner element name of this content definition.<p> * * @return the inner element name of this content definition */ public String getInnerName() { return m_innerName; } /** * Returns the outer element name of this content definition.<p> * * @return the outer element name of this content definition */ public String getOuterName() { return m_outerName; } /** * Generates an XML schema for the content definition.<p> * * @return the generated XML schema */ public Document getSchema() { Document result; if (m_schemaDocument == null) { result = DocumentHelper.createDocument(); Element root = result.addElement(XSD_NODE_SCHEMA); root.addAttribute(XSD_ATTRIBUTE_ELEMENT_FORM_DEFAULT, XSD_ATTRIBUTE_VALUE_QUALIFIED); Element include = root.addElement(XSD_NODE_INCLUDE); include.addAttribute(XSD_ATTRIBUTE_SCHEMA_LOCATION, XSD_INCLUDE_OPENCMS); if (m_includes.size() > 0) { Iterator<CmsXmlContentDefinition> i = m_includes.iterator(); while (i.hasNext()) { CmsXmlContentDefinition definition = i.next(); root.addElement(XSD_NODE_INCLUDE).addAttribute( XSD_ATTRIBUTE_SCHEMA_LOCATION, definition.m_schemaLocation); } } String outerTypeName = createTypeName(getOuterName()); String innerTypeName = createTypeName(getInnerName()); Element content = root.addElement(XSD_NODE_ELEMENT); content.addAttribute(XSD_ATTRIBUTE_NAME, getOuterName()); content.addAttribute(XSD_ATTRIBUTE_TYPE, outerTypeName); Element list = root.addElement(XSD_NODE_COMPLEXTYPE); list.addAttribute(XSD_ATTRIBUTE_NAME, outerTypeName); Element listSequence = list.addElement(XSD_NODE_SEQUENCE); Element listElement = listSequence.addElement(XSD_NODE_ELEMENT); listElement.addAttribute(XSD_ATTRIBUTE_NAME, getInnerName()); listElement.addAttribute(XSD_ATTRIBUTE_TYPE, innerTypeName); listElement.addAttribute(XSD_ATTRIBUTE_MIN_OCCURS, XSD_ATTRIBUTE_VALUE_ZERO); listElement.addAttribute(XSD_ATTRIBUTE_MAX_OCCURS, XSD_ATTRIBUTE_VALUE_UNBOUNDED); Element main = root.addElement(XSD_NODE_COMPLEXTYPE); main.addAttribute(XSD_ATTRIBUTE_NAME, innerTypeName); Element mainSequence; if (m_sequenceType == SequenceType.SEQUENCE) { mainSequence = main.addElement(XSD_NODE_SEQUENCE); } else { mainSequence = main.addElement(XSD_NODE_CHOICE); if (getChoiceMaxOccurs() > 1) { mainSequence.addAttribute(XSD_ATTRIBUTE_MAX_OCCURS, String.valueOf(getChoiceMaxOccurs())); } else { mainSequence.addAttribute(XSD_ATTRIBUTE_MIN_OCCURS, XSD_ATTRIBUTE_VALUE_ZERO); mainSequence.addAttribute(XSD_ATTRIBUTE_MAX_OCCURS, XSD_ATTRIBUTE_VALUE_ONE); } } Iterator<I_CmsXmlSchemaType> i = m_typeSequence.iterator(); while (i.hasNext()) { I_CmsXmlSchemaType schemaType = i.next(); schemaType.appendXmlSchema(mainSequence); } Element language = main.addElement(XSD_NODE_ATTRIBUTE); language.addAttribute(XSD_ATTRIBUTE_NAME, XSD_ATTRIBUTE_VALUE_LANGUAGE); language.addAttribute(XSD_ATTRIBUTE_TYPE, CmsXmlLocaleValue.TYPE_NAME); language.addAttribute(XSD_ATTRIBUTE_USE, XSD_ATTRIBUTE_VALUE_OPTIONAL); } else { result = (Document)m_schemaDocument.clone(); } return result; } /** * Returns the location from which the XML schema was read (XML system id).<p> * * @return the location from which the XML schema was read (XML system id) */ public String getSchemaLocation() { return m_schemaLocation; } /** * Returns the schema type for the given element name, or <code>null</code> if no * node is defined with this name.<p> * * @param elementPath the element xpath to look up the type for * @return the type for the given element name, or <code>null</code> if no * node is defined with this name */ public I_CmsXmlSchemaType getSchemaType(String elementPath) { String path = CmsXmlUtils.removeXpath(elementPath); I_CmsXmlSchemaType result = m_elementTypes.get(path); if (result == null) { result = getSchemaTypeRecusive(path); if (result != null) { m_elementTypes.put(path, result); } else { m_elementTypes.put(path, NULL_SCHEMA_TYPE); } } else if (result == NULL_SCHEMA_TYPE) { result = null; } return result; } /** * Returns the internal set of schema type names.<p> * * @return the internal set of schema type names */ public Set<String> getSchemaTypes() { return m_types.keySet(); } /** * Returns the sequence type of this content definition.<p> * * @return the sequence type of this content definition */ public SequenceType getSequenceType() { return m_sequenceType; } /** * Returns the main type name of this XML content definition.<p> * * @return the main type name of this XML content definition */ public String getTypeName() { return m_typeName; } /** * Returns the type sequence, contains instances of {@link I_CmsXmlSchemaType}.<p> * * @return the type sequence, contains instances of {@link I_CmsXmlSchemaType} */ public List<I_CmsXmlSchemaType> getTypeSequence() { return m_typeSequence; } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return getInnerName().hashCode(); } /** * Sets the inner element name to use for the content definition.<p> * * @param innerName the inner element name to set */ protected void setInnerName(String innerName) { m_innerName = innerName; if (m_innerName != null) { m_typeName = createTypeName(innerName); } } /** * Sets the outer element name to use for the content definition.<p> * * @param outerName the outer element name to set */ protected void setOuterName(String outerName) { m_outerName = outerName; } /** * Calculates the schema type for the given element name by recursing into the schema structure.<p> * * @param elementPath the element xpath to look up the type for * @return the type for the given element name, or <code>null</code> if no * node is defined with this name */ private I_CmsXmlSchemaType getSchemaTypeRecusive(String elementPath) { String path = CmsXmlUtils.getFirstXpathElement(elementPath); I_CmsXmlSchemaType type = m_types.get(path); if (type == null) { // no node with the given path defined in schema return null; } // check if recursion is required to get value from a nested schema if (type.isSimpleType() || !CmsXmlUtils.isDeepXpath(elementPath)) { // no recursion required return type; } // recursion required since the path is an xpath and the type must be a nested content definition CmsXmlNestedContentDefinition nestedDefinition = (CmsXmlNestedContentDefinition)type; path = CmsXmlUtils.removeFirstXpathElement(elementPath); return nestedDefinition.getNestedContentDefinition().getSchemaType(path); } }
package org.pentaho.di.core.config; import java.beans.Introspector; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.commons.digester.Digester; import org.apache.commons.digester.SetNextRule; import org.apache.commons.digester.SetPropertiesRule; import org.pentaho.di.core.annotations.Inject; import org.xml.sax.Attributes; /** * The gateway for all configuration operations. * * <h3>Configuration Managers Property Injection:</h3> * This class reads "<property>" elements from kettle-config.xml and attemps to * inject the value of such fields into the corresponding * <code>ConfigManager</code> implementation, following the rules established * the * * @Inject annotation. * * @see org.pentaho.core.annotations.Inject * * @author Alex Silva * */ public class KettleConfig { private static final String KETTLE_CONFIG = "kettle-config/config"; private static final String KETTLE_CONFIG_PROPERTY = KETTLE_CONFIG + "/property"; private static final String KETTLE_CONFIG_CLASS = KETTLE_CONFIG + "/config-class"; private static KettleConfig config; private Map<String, ConfigManager<?>> configs = new HashMap<String, ConfigManager<?>>(); private KettleConfig() { Digester digester = createDigester(); try { digester.parse(Thread.currentThread().getContextClassLoader().getResource( getClass().getPackage().getName().replace('.', '/') + "/kettle-config.xml")); } catch (Exception e) { e.printStackTrace(); } } public static KettleConfig getInstance() { if (config == null) { synchronized (KettleConfig.class) { config = new KettleConfig(); } } return config; } public ConfigManager<?> getManager(String name) { return configs.get(name); } /** * Returns all loaders defined in kettle-config.xml. * * @return */ public Collection<ConfigManager<?>> getManagers() { return configs.values(); } private Digester createDigester() { Digester digester = new Digester(); digester.addObjectCreate(KETTLE_CONFIG, TempConfig.class); digester.addBeanPropertySetter(KETTLE_CONFIG_CLASS, "clazz"); digester.addSetProperties(KETTLE_CONFIG, "id", "id"); digester.addRule(KETTLE_CONFIG_PROPERTY, new SetPropertiesRule() { @Override @SuppressWarnings("deprecation") public void begin(Attributes attrs) throws Exception { ((TempConfig) digester.peek()).parms.put(attrs.getValue("name"), attrs.getValue("value")); } }); digester.addRule(KETTLE_CONFIG, new SetNextRule("") { @SuppressWarnings("unchecked") public void end(String nameSpace, String name) throws Exception { TempConfig cfg = (TempConfig) digester.peek(); // do the conversion here. Class<? extends ConfigManager> cfclass = Class.forName(cfg.clazz).asSubclass( ConfigManager.class); ConfigManager parms = cfclass.newInstance(); // method injection inject(cfclass.getMethods(), cfg, parms); // field injection inject(cfclass.getDeclaredFields(), cfg, parms); KettleConfig.this.configs.put(cfg.id, parms); } }); return digester; } private <E extends AccessibleObject> void inject(E[] elems, TempConfig cfg, ConfigManager<?> parms) throws IllegalAccessException, InvocationTargetException { for (AccessibleObject elem : elems) { Inject inj = elem.getAnnotation(Inject.class); if (inj != null) { // try to inject property from map. elem.setAccessible(true); String property = inj.property(); // Can't think of any other way if (elem instanceof Method) { Method meth = (Method) elem; // find out what we are going to inject 1st property = property.equals("") ? Introspector.decapitalize(meth.getName().substring(3)) : property; meth.invoke(parms, cfg.parms.get(property)); } else if (elem instanceof Field) { Field field = (Field) elem; field.set(parms, cfg.parms.get(property.equals("") ? field.getName() : property)); } } } } public static class TempConfig { private String clazz; private String id; private Map<String, String> parms = new HashMap<String, String>(); public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public String getId() { return id; } public void setId(String id) { this.id = id; } } }
package org.seqcode.deepseq.events; import org.seqcode.deepseq.experiments.ControlledExperiment; import org.seqcode.deepseq.experiments.ExperimentCondition; import org.seqcode.deepseq.experiments.ExperimentManager; import org.seqcode.genome.location.AnnotationLoader; import org.seqcode.genome.location.Gene; import org.seqcode.genome.location.Point; import org.seqcode.genome.location.Region; import org.seqcode.genome.sequence.SequenceGenerator; /** * BindingEvent: a class representing a potential binding event and associated read counts and * significance P-values across experimental conditions and replicates. * * BindingEvents are associated with a particular configuration of binding components, since the read counts per event can depend on * other proximal binding events. Therefore, and depending on what configuration the binding event comes from, multiple binding events * may share the same coordinate without having the same read counts associated per experiment. While this may seem strange, defining * events in this way reduces redundant records while representing all discovered configurations. * The conditions that shared the exact configuration that led to the creation of this binding event are represented in foundInCond. * * @author mahony * */ public class BindingEvent implements Comparable<BindingEvent>{ protected static ExperimentManager experiments=null; protected static EventsConfig config=null; protected static ExperimentCondition sortingCondition = null; protected static ExperimentCondition sortingConditionB = null; protected static final int numSingleCondCols = 4; //Number of columns in the output file for each single-condition protected static final int numInterCondCols = 3; //Number of columns in the output file for each inter-condition protected Point point; protected Region containingReg; protected boolean [] foundInCond; //The binding event was discovered in these conditions [indexed by condition] protected double [] condSigHits; //Signal counts by condition (not scaled) [indexed by condition] protected double [] condCtrlHits; //Control counts by condition (not scaled) [indexed by condition] protected double [] condSigVCtrlFold; //Signal vs Control fold by condition [indexed by condition] protected double [] condSigVCtrlP; //Signal vs Control P-value by condition [indexed by condition] protected double [] repSigHits; //Signal counts by replicate (not scaled) [indexed by replicate] protected double [] repCtrlHits; //Control counts by replicate (not scaled) [indexed by replicate] protected double [] repSigVCtrlFold; //Signal vs Control fold by replicate [indexed by replicate] protected double [] repSigVCtrlP; //Signal vs Control P-value by replicate [indexed by replicate] protected double [][] interCondScMean; //Signal vs signal scaled mean (logCPM from EdgeR), inter-condition [indexed by condition & condition] protected double [][] interCondFold; //Signal vs signal fold difference (logFold from EdgeR), inter-condition [indexed by condition & condition] protected double [][] interCondP; //Signal vs signal P, inter-condition [indexed by condition & condition] protected double [][] interRepP; //Signal vs signal P, inter-replicate [indexed by replicate & replicate] protected double [] LLd; //Log-likelihood loss test statistic resulting from eliminating component [indexed by condition] protected double [] LLp; //P-value for LL [indexed by condition] protected double [] motifScores; //LL score for motif match at binding event protected float [][] repEventTagBases=null; //Tag counts per base by replicate (only used in permanganate ChIP-seq) protected float [][] repBubbleTagBases=null; //Bubble tag counts per base by replicate (only used in permanganate ChIP-seq) protected float [] eventBases=null; //Base composition by replicate (only used in permanganate ChIP-seq) protected float [] bubbleBases=null; //Bubble base composition by replicate (only used in permanganate ChIP-seq) protected String sequences[]; //Sequences at binding event protected Gene nearestGene=null; protected int distToGene=0; public BindingEvent(Point p, Region potentialReg){ point=p; containingReg=potentialReg; int numC = experiments.getConditions().size(); int numR = experiments.getReplicates().size(); foundInCond = new boolean[numC]; condSigHits = new double [numC]; condCtrlHits = new double [numC]; condSigVCtrlFold = new double [numC]; condSigVCtrlP = new double [numC]; interCondScMean = new double [numC][numC]; interCondFold = new double [numC][numC]; interCondP = new double [numC][numC]; repSigHits = new double [numR]; repCtrlHits = new double [numR]; repSigVCtrlFold = new double [numR]; repSigVCtrlP = new double [numR]; interRepP = new double [numR][numR]; LLd = new double [numC]; LLp = new double [numC]; motifScores = new double[numC]; sequences = new String[numC]; for(int c=0; c<numC; c++){ foundInCond[c]=false; condSigHits[c]=0; condCtrlHits[c]=0; condSigVCtrlP[c]=1; condSigVCtrlFold[c]=1; motifScores[c]=0; sequences[c]=" for(int d=0; d<numC; d++){ interCondScMean[c][d]=0; interCondFold[c][d]=1; interCondP[c][d]=1; } } for(int r=0; r<numR; r++){ repSigHits[r]=0; repCtrlHits[r]=0; repSigVCtrlP[r]=1; repSigVCtrlFold[r]=1; } } //Getters public boolean isFoundInCondition(ExperimentCondition c){return foundInCond[experiments.getConditionIndex(c)];} public boolean isFoundInCondition(int conditionIndex){return foundInCond[conditionIndex];} public double getCondSigHits(ExperimentCondition c){return(condSigHits[experiments.getConditionIndex(c)]);} public double getCondCtrlHits(ExperimentCondition c){return(condCtrlHits[experiments.getConditionIndex(c)]);} public double getCondSigVCtrlP(ExperimentCondition c){return(condSigVCtrlP[experiments.getConditionIndex(c)]);} public double getCondSigVCtrlFold(ExperimentCondition c){return(condSigVCtrlFold[experiments.getConditionIndex(c)]);} public double getRepSigHits(ControlledExperiment r){return(repSigHits[r.getIndex()]);} public double getRepCtrlHits(ControlledExperiment r){return(repCtrlHits[r.getIndex()]);} public double getRepSigVCtrlP(ControlledExperiment r){return(repSigVCtrlP[r.getIndex()]);} public double getRepSigVCtrlFold(ControlledExperiment r){return(repSigVCtrlFold[r.getIndex()]);} public double getInterCondScMean(ExperimentCondition c1, ExperimentCondition c2){return(interCondScMean[experiments.getConditionIndex(c1)][experiments.getConditionIndex(c2)]);} public double getInterCondFold(ExperimentCondition c1, ExperimentCondition c2){return(interCondFold[experiments.getConditionIndex(c1)][experiments.getConditionIndex(c2)]);} public double getInterCondP(ExperimentCondition c1, ExperimentCondition c2){return(interCondP[experiments.getConditionIndex(c1)][experiments.getConditionIndex(c2)]);} public double getInterRepP(ControlledExperiment r1, ControlledExperiment r2){return interRepP[r1.getIndex()][r2.getIndex()];} public static int getNumSingleCondCols(){return numSingleCondCols;} public static int getNumInterCondCols(){return numInterCondCols;} public double getLLd(ExperimentCondition c1){return(LLd[experiments.getConditionIndex(c1)]);} public double getLLp(ExperimentCondition c1){return(LLp[experiments.getConditionIndex(c1)]);} public double getMotifScore(ExperimentCondition c1){return(motifScores[experiments.getConditionIndex(c1)]);} public String getSequence(ExperimentCondition c1){return sequences[experiments.getConditionIndex(c1)];} public String getFoundInConditionsString(){ String foundStr=""; for(ExperimentCondition c : experiments.getConditions()){ String found = foundInCond[c.getIndex()] ? "1" : "0"; if(foundStr.length()>0) foundStr=foundStr+","+found; else foundStr=found; } return foundStr; } public double getCondSigHitsFromReps(ExperimentCondition c){ double hits=0; for(ControlledExperiment rep : c.getReplicates()) hits+=repSigHits[rep.getIndex()]; return hits; } public double getCondCtrlHitsScaledFromReps(ExperimentCondition c){ double hits=0; for(ControlledExperiment rep : c.getReplicates()) hits+=repCtrlHits[rep.getIndex()]*rep.getControlScaling(); return hits; } public double getCondTotalSigHitsFromReps(ExperimentCondition c){ double total=0; for(ControlledExperiment rep : c.getReplicates()) total+=rep.getSignal().getHitCount(); return total; } public double getCondTotalCtrlHitsScaledFromReps(ExperimentCondition c){ double total=0; for(ControlledExperiment rep : c.getReplicates()) total+=rep.getControl().getHitCount()*rep.getControlScaling(); return total; } //Setters public void setIsFoundInCondition(ExperimentCondition c, boolean found){foundInCond[experiments.getConditionIndex(c)] = found;} public void setIsFoundInCondition(int c, boolean found){foundInCond[c] = found;} public void setCondSigHits(ExperimentCondition c, double x){condSigHits[experiments.getConditionIndex(c)]=x;} public void setCondCtrlHits(ExperimentCondition c, double x){condCtrlHits[experiments.getConditionIndex(c)]=x;} public void setCondSigVCtrlFold(ExperimentCondition c, double x){condSigVCtrlFold[experiments.getConditionIndex(c)]=x;} public void setCondSigVCtrlP(ExperimentCondition c, double x){condSigVCtrlP[experiments.getConditionIndex(c)]=x;} public void setLLd(ExperimentCondition c, double l){LLd[experiments.getConditionIndex(c)]=l;} public void setLLp(ExperimentCondition c, double p){LLp[experiments.getConditionIndex(c)]=p;} public void setRepSigHits(ControlledExperiment r, double x){repSigHits[r.getIndex()]=x;} public void setRepCtrlHits(ControlledExperiment r, double x){repCtrlHits[r.getIndex()]=x;} public void setRepSigVCtrlFold(ControlledExperiment r, double x){repSigVCtrlFold[r.getIndex()]=x;} public void setRepSigVCtrlP(ControlledExperiment r, double x){repSigVCtrlP[r.getIndex()]=x;} public void setInterCondScMean(ExperimentCondition c1, ExperimentCondition c2, double x){interCondScMean[experiments.getConditionIndex(c1)][experiments.getConditionIndex(c2)]=x;} public void setInterCondFold(ExperimentCondition c1, ExperimentCondition c2, double x){interCondFold[experiments.getConditionIndex(c1)][experiments.getConditionIndex(c2)]=x;} public void setInterCondP(ExperimentCondition c1, ExperimentCondition c2, double x){interCondP[experiments.getConditionIndex(c1)][experiments.getConditionIndex(c2)]=x;} public void setInterRepP(ControlledExperiment r1, ControlledExperiment r2, double x){interRepP[r1.getIndex()][r2.getIndex()]=x;} public void setMotifScore(ExperimentCondition c1, double s){motifScores[experiments.getConditionIndex(c1)] = s;} public void setSequence(ExperimentCondition c1, String seq){sequences[experiments.getConditionIndex(c1)]=seq;} /** * Rank according to increasing p-value (score) for the sorting condition, then by signal count for the sorting condition */ public int compareBySigCtrlPvalue(BindingEvent p) { if(this.getCondSigVCtrlP(sortingCondition)<p.getCondSigVCtrlP(sortingCondition)){return(-1);} else if(this.getCondSigVCtrlP(sortingCondition)>p.getCondSigVCtrlP(sortingCondition)){return(1);} else{ if(this.getCondSigHits(sortingCondition)>p.getCondSigHits(sortingCondition)){return(-1);} else if(this.getCondSigHits(sortingCondition)<p.getCondSigHits(sortingCondition)){return(1);} }return(0); } /** * Rank according to increasing p-value (score) for the pair of sorting conditions, then by signal count for the sorting condition */ public int compareByInterCondPvalue(BindingEvent p) { if(this.getInterCondP(sortingCondition, sortingConditionB) < p.getInterCondP(sortingCondition, sortingConditionB)){return(-1);} else if(this.getInterCondP(sortingCondition, sortingConditionB) > p.getInterCondP(sortingCondition, sortingConditionB)){return(1);} else{ if(this.getCondSigHits(sortingCondition)>p.getCondSigHits(sortingCondition)){return(-1);} else if(this.getCondSigHits(sortingCondition)<p.getCondSigHits(sortingCondition)){return(1);} }return(0); } /** * Rank according to increasing LL p-value for the sorting condition, then by signal count for the sorting condition */ public int compareByLLPvalue(BindingEvent p) { if(this.getLLp(sortingCondition)<p.getLLp(sortingCondition)){return(-1);} else if(this.getLLp(sortingCondition)>p.getLLp(sortingCondition)){return(1);} else{ if(this.getCondSigHits(sortingCondition)>p.getCondSigHits(sortingCondition)){return(-1);} else if(this.getCondSigHits(sortingCondition)<p.getCondSigHits(sortingCondition)){return(1);} }return(0); } /** * Rank according to location * @param f * @return */ public int compareByLocation(BindingEvent f) { return getPoint().compareTo(f.getPoint()); } //Comparable default method public int compareTo(BindingEvent f) { return compareByLocation(f); } public Point getPoint(){return(point);} public Region getContainingRegion(){return(containingReg);} /** * Returns a string suitable for use as the header of a table whose rows are * the output of BindingEvent.toString(). */ public static String fullHeadString(){ String head="### MultiGPS output\n"; head = head + "#Condition\tName\tIndex\tTotalSigCount\tSignalFraction\n"; //Add some basic information on the experiments for(ExperimentCondition c : experiments.getConditions()){ head = head + "#Condition\t"+c.getName()+"\t"+c.getIndex()+"\t"+c.getTotalSignalCount()+"\t"+String.format("%.3f",c.getTotalSignalVsNoiseFrac())+"\n"; } head = head + "#Replicate\tParentCond\tName\tIndex\tSigCount\tCtrlCount\tSigCtrlScaling\tSignalFraction\n"; for(ExperimentCondition c : experiments.getConditions()){ for(ControlledExperiment r : c.getReplicates()){ if(r.getControl()==null) head = head + "#Replicate\t"+c.getName()+"\t"+r.getName()+"\t"+r.getIndex()+"\t"+r.getSignal().getHitCount()+"\t0\t1\t"+String.format("%.2f",r.getSignalVsNoiseFraction())+"\n"; else head = head + "#Replicate\t"+c.getName()+"\t"+r.getName()+"\t"+r.getIndex()+"\t"+r.getSignal().getHitCount()+"\t"+r.getControl().getHitCount()+"\t"+String.format("%.2f",r.getControlScaling())+"\t"+String.format("%.3f",r.getSignalVsNoiseFraction())+"\n"; } } head = head + "#\n#Point"; for(ExperimentCondition c : experiments.getConditions()) head = head +"\t"+c.getName()+"_Sig"+"\t"+c.getName()+"_Ctrl"+"\t"+c.getName()+"_log2Fold"+"\t"+c.getName()+"_log2P"; for(ExperimentCondition c : experiments.getConditions()) for(ExperimentCondition c2 : experiments.getConditions()){ if(c!=c2){ head = head +"\t"+c.getName()+"_vs_"+c2.getName()+"_log2CPM"+"\t"+c.getName()+"_vs_"+c2.getName()+"_log2Fold"+"\t"+c.getName()+"_vs_"+c2.getName()+"_log2P"; } } head = head+"\tActiveConds"; if(config.isAddingAnnotations()) head = head +"\tnearestGene\tdistToGene"; //head = head +"\n"; return head; } /** * Print info on each condition and inter-condition */ public String toString() { //String gene = nearestGene == null ? "NONE" : nearestGene.getName(); String out = point.getLocationString(); for(ExperimentCondition c : experiments.getConditions()){ double logP = Math.log(getCondSigVCtrlP(c))/config.LOG2; double logF = Math.log(getCondSigVCtrlFold(c))/config.LOG2; out = out+"\t"+String.format("%.1f", getCondSigHits(c))+"\t"+String.format("%.1f", getCondCtrlHits(c))+"\t"+String.format("%.3f", logF)+"\t"+String.format("%.3f", logP); }for(ExperimentCondition c : experiments.getConditions()) for(ExperimentCondition c2 : experiments.getConditions()){ if(c!=c2){ double logP = Math.log(getInterCondP(c, c2))/config.LOG2; out = out+"\t"+String.format("%.2f", getInterCondScMean(c, c2))+"\t"+String.format("%.3f", getInterCondFold(c,c2))+"\t"+String.format("%.3f",logP); } } out = out+"\t"+this.getFoundInConditionsString(); if(config.isAddingAnnotations()) if(nearestGene==null) out = out + "\tNONE\t"+config.getMaxAnnotDistance(); else out = out + "\t"+nearestGene.getName()+"\t"+distToGene; //out = out+"\n"; return out; } /** * Returns a string suitable for use as the header of a table whose rows are * the output of BindingEvent.getRepCountString(). */ public static String repCountHeadString(){ String head = "Point"; for(ControlledExperiment r : experiments.getReplicates()) head = head +"\t"+r.getName(); return head; } /** * Print info on each replicate's & condition's unnormalized counts */ public String getRepCountString() { String out = point.getLocationString(); for(ControlledExperiment r : experiments.getReplicates()) out = out+"\t"+String.format("%.0f", getRepSigHits(r)); return out; } /** * Returns a string suitable for use as the header of a table whose rows are * the output of BindingEvent.getConditionString(). * (i.e. single condition files) */ public static String conditionHeadString(ExperimentCondition c){ String head="### MultiGPS output\n"; head = head + "#Condition\tName\tIndex\tTotalSigCount\tSignalFraction\n"; head = head + "#Condition\t"+c.getName()+"\t"+c.getIndex()+"\t"+c.getTotalSignalCount()+"\t"+String.format("%.3f",c.getTotalSignalVsNoiseFrac())+"\n"; head = head + "#Replicate\tParentCond\tName\tIndex\tSigCount\tCtrlCount\tCtrlScaling\tSignalFraction\n"; for(ControlledExperiment r : c.getReplicates()){ if(r.getControl()==null) head = head + "#Replicate\t"+c.getName()+"\t"+r.getName()+"\t"+r.getIndex()+"\t"+r.getSignal().getHitCount()+"\t0\t1\t"+String.format("%.3f",r.getSignalVsNoiseFraction())+"\n"; else head = head + "#Replicate\t"+c.getName()+"\t"+r.getName()+"\t"+r.getIndex()+"\t"+r.getSignal().getHitCount()+"\t"+r.getControl().getHitCount()+"\t"+String.format("%.3f",r.getControlScaling())+"\t"+String.format("%.3f",r.getSignalVsNoiseFraction())+"\n"; } head = head + "#\n#Point"; head = head +"\t"+c.getName()+"_Sig"+"\t"+c.getName()+"_Ctrl"+"\t"+c.getName()+"_log2Fold"+"\t"+c.getName()+"_log2P"; for(ExperimentCondition c2 : experiments.getConditions()){ if(c!=c2){ head = head +"\t"+c.getName()+"_vs_"+c2.getName()+"_log2CPM"+"\t"+c.getName()+"_vs_"+c2.getName()+"_log2Fold"+"\t"+c.getName()+"_vs_"+c2.getName()+"_log2P"; } } if(config.isAddingSequences()); head = head +"\tSequence\tMotifScore"; if(config.isAddingAnnotations()) head = head +"\tnearestGene\tdistToGene"; return head; } /** * Returns a string suitable for use as the header of a BED file whose rows are * the output of BindingEvent.getConditionBED(). * (i.e. single condition BED files) */ public static String conditionBEDHeadString(ExperimentCondition c){ String head="track name=multiGPS-"+c.getName()+" description="+"multiGPS events "+c.getName(); return head; } /** * Returns a string suitable for use as the header of a BED file whose rows are * the output of BindingEvent.getConditionBED(). * (i.e. single condition BED files) */ public static String diffConditionBEDHeadString(ExperimentCondition c1, ExperimentCondition c2){ String head="track name=multiGPS-"+c1.getName()+"-gt-"+c2.getName()+" description="+"multiGPS diff events "+c1.getName()+" > "+c2.getName(); return head; } /** * Returns a single-line string suitable for use as the header of a table of differential binding events */ public static String conditionShortHeadString(ExperimentCondition c){ String head = "#Point"; head = head +"\t"+c.getName()+"_Sig"+"\t"+c.getName()+"_Ctrl"+"\t"+c.getName()+"_log2Fold"+"\t"+c.getName()+"_log2P"; for(ExperimentCondition c2 : experiments.getConditions()){ if(c!=c2){ head = head +"\t"+c.getName()+"_vs_"+c2.getName()+"_log2CPM"+"\t"+c.getName()+"_vs_"+c2.getName()+"_log2Fold"+"\t"+c.getName()+"_vs_"+c2.getName()+"_log2P"; } } if(config.isAddingSequences()); head = head +"\tSequence\tMotifScore"; if(config.isAddingAnnotations()) head = head +"\tnearestGene\tdistToGene"; return head; } /** * Print info on a single condition and associated inter-condition tests */ public String getConditionString(ExperimentCondition c) { //String gene = nearestGene == null ? "NONE" : nearestGene.getName(); String out = point.getLocationString(); double logP = Math.log(getCondSigVCtrlP(c))/config.LOG2; double logF = Math.log(getCondSigVCtrlFold(c))/config.LOG2; //if(logP!=0.0) // logP*=-1; out = out+"\t"+String.format("%.1f", getCondSigHits(c))+"\t"+String.format("%.1f", getCondCtrlHits(c))+"\t"+String.format("%.3f", logF)+"\t"+String.format("%.3f", logP); for(ExperimentCondition c2 : experiments.getConditions()){ if(c!=c2){ double logPC = Math.log(getInterCondP(c, c2))/config.LOG2; out = out+"\t"+String.format("%.2f", getInterCondScMean(c, c2))+"\t"+String.format("%.3f", getInterCondFold(c, c2))+"\t"+String.format("%.3f",logPC); } } if(config.isAddingSequences()); out = out+"\t"+this.getSequence(c)+"\t"+String.format("%.2f", this.getMotifScore(c)); if(config.isAddingAnnotations()) if(nearestGene==null) out = out + "\tNONE\t"+config.getMaxAnnotDistance(); else out = out + "\t"+nearestGene.getName()+"\t"+distToGene; //out = out+"\n"; return out; } /** * Output in BED format */ public String getConditionBED(ExperimentCondition c){ if (point != null) { double logP = Math.log(getCondSigVCtrlP(c))/config.LOG2; //BED score ranges from 0 to 1000 // score = 10 * -logP int score = (int)(Math.max(0, Math.min(-10*logP, 1000))); //Note that BED is 0-start and end-noninclusive, so we always shift the // multiGPS binding event location back by one. return new String("chr"+point.getChrom()+"\t"+(point.getLocation()-1)+"\t"+point.getLocation()+"\tmultiGPS\t"+score); } return null; } /** * Returns the sequence window (length=win) centered on the point */ public String toSequence(int win){ String seq; SequenceGenerator seqgen = new SequenceGenerator(); Region peakWin=null; int start = point.getLocation()-((int)(win/2)); if(start<1){start=1;} int end = point.getLocation()+((int)win/2)-1; if(end>point.getGenome().getChromLength(point.getChrom())){end =point.getGenome().getChromLength(point.getChrom());} peakWin = new Region(point.getGenome(), point.getChrom(), start, end); String seqName = new String(">"+peakWin.getLocationString()+"\t"+peakWin.getWidth()+"\t"+point.getLocation()); String sq = seqgen.execute(peakWin); seq = seqName +"\n"+ sq+"\n"; return seq; } /** * Find the closest genes to the enriched features * @param enriched */ public void addClosestGenes(){ distToGene = config.getMaxAnnotDistance(); for(AnnotationLoader loader : config.getGeneAnnotations()){ if (config.getAnnotOverlapOnly()) { for(Gene gene : loader.getGenes(point)){ if(gene.contains(point)){ nearestGene = gene; distToGene = gene.distance(point); } } if (nearestGene != null) { distToGene = nearestGene.distance(point); } } else { for(Gene gene : loader.getGenes(point)){ int distance = point.getLocation() - gene.getFivePrime(); if (gene.getStrand()=='-') distance = -distance; if (Math.abs(distance) < Math.abs(distToGene)) { nearestGene = gene; distToGene = distance; } } } } } public static void setExperimentManager(ExperimentManager e){experiments = e; sortingCondition = experiments.getConditions().get(0);} public static void setConfig(EventsConfig c){config = c;} public static void setSortingCond(ExperimentCondition c){sortingCondition = c;} public static void setSortingCondB(ExperimentCondition c){sortingConditionB = c;} /** * Only used if performing analysis on permanganate ChIP-seq experiments * @param rep * @param eventTags * @param bubbleTags */ public void setRepPCScounts(ControlledExperiment rep, float[] eventTags, float[] eventB, float[] bubbleTags, float[] bubbleB){ //Initialize if(repEventTagBases==null){ int numR = experiments.getReplicates().size(); repEventTagBases = new float[numR][4]; repBubbleTagBases = new float[numR][4]; eventBases = new float[4]; bubbleBases = new float[4]; } repEventTagBases[rep.getIndex()]=eventTags; repBubbleTagBases[rep.getIndex()]=bubbleTags; eventBases=eventB; bubbleBases=bubbleB; //Force normalized: float totET=0, totBT=0, totEB=0, totBB=0; for(int b=0; b<4; b++){ totET+=repEventTagBases[rep.getIndex()][b]; totBT+=repBubbleTagBases[rep.getIndex()][b]; totEB+=eventBases[b]; totBB+=bubbleBases[b]; } for(int b=0; b<4; b++){ if(totET>0){repEventTagBases[rep.getIndex()][b]/=totET;} if(totBT>0){repBubbleTagBases[rep.getIndex()][b]/=totBT;} if(totEB>0){eventBases[b]/=totEB;} if(totBB>0){bubbleBases[b]/=totBB;} } } //More accessors public float[] getRepEventTagBases(ControlledExperiment rep){return repEventTagBases[rep.getIndex()];} public float[] getRepBubbleTagBases(ControlledExperiment rep){return repBubbleTagBases[rep.getIndex()];} public float[] getEventBases(){ return eventBases;} public float[] getBubbleBases(){ return bubbleBases;} }
package org.subethamail.core.admin.i; import java.io.Serializable; import java.net.URL; import javax.mail.internet.InternetAddress; /** * Some random information about the site. * * @author Jeff Schnitzer */ @SuppressWarnings("serial") public class SiteStatus implements Serializable { String defaultCharset; int listCount; int personCount; int mailCount; /** Some site config params */ URL defaultSiteUrl; InternetAddress postmasterEmail; String fallbackHost; protected SiteStatus() { } public SiteStatus(String encoding, int listCount, int personCount, int mailCount, URL defaultSiteUrl, InternetAddress postmasterEmail, String fallback) { this.defaultCharset = encoding; this.listCount = listCount; this.personCount = personCount; this.mailCount = mailCount; this.defaultSiteUrl = defaultSiteUrl; this.postmasterEmail = postmasterEmail; this.fallbackHost = fallback; } public String getDefaultCharset() { return this.defaultCharset; } public int getListCount() { return this.listCount; } public int getPersonCount() { return this.personCount; } public int getMailCount() { return this.mailCount; } public URL getDefaultSiteUrl() { return this.defaultSiteUrl; } public InternetAddress getPostmasterEmail() { return this.postmasterEmail; } public String getFallbackHost() { return this.fallbackHost; } }
package edu.iu.grid.oim.model.db; import java.io.IOException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import javax.security.auth.x500.X500Principal; import org.bouncycastle.asn1.x500.RDN; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.cms.CMSException; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.util.encoders.Base64; import org.apache.commons.lang.StringEscapeUtils; import org.apache.log4j.Logger; import edu.iu.grid.oim.lib.Authorization; import edu.iu.grid.oim.lib.Footprints; import edu.iu.grid.oim.lib.StaticConfig; import edu.iu.grid.oim.lib.Footprints.FPTicket; import edu.iu.grid.oim.lib.StringArray; import edu.iu.grid.oim.model.CertificateRequestStatus; import edu.iu.grid.oim.model.UserContext; import edu.iu.grid.oim.model.UserContext.MessageType; import edu.iu.grid.oim.model.cert.CertificateManager; import edu.iu.grid.oim.model.cert.ICertificateSigner; import edu.iu.grid.oim.model.cert.ICertificateSigner.Certificate; import edu.iu.grid.oim.model.cert.ICertificateSigner.CertificateProviderException; import edu.iu.grid.oim.model.cert.ICertificateSigner.IHostCertificatesCallBack; import edu.iu.grid.oim.model.db.CertificateRequestModelBase.LogDetail; import edu.iu.grid.oim.model.db.record.CertificateRequestHostRecord; import edu.iu.grid.oim.model.db.record.ContactRecord; import edu.iu.grid.oim.model.db.record.GridAdminRecord; import edu.iu.grid.oim.model.db.record.VORecord; import edu.iu.grid.oim.model.exceptions.CertificateRequestException; public class CertificateRequestHostModel extends CertificateRequestModelBase<CertificateRequestHostRecord> { static Logger log = Logger.getLogger(CertificateRequestHostModel.class); public CertificateRequestHostModel(UserContext _context) { super(_context, "certificate_request_host"); } //NO-AC public CertificateRequestHostRecord get(int id) throws SQLException { CertificateRequestHostRecord rec = null; ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); if (stmt.execute("SELECT * FROM "+table_name+ " WHERE id = " + id)) { rs = stmt.getResultSet(); if(rs.next()) { rec = new CertificateRequestHostRecord(rs); } } stmt.close(); conn.close(); return rec; } //return requests that I have submitted public ArrayList<CertificateRequestHostRecord> getISubmitted(Integer id) throws SQLException { ArrayList<CertificateRequestHostRecord> ret = new ArrayList<CertificateRequestHostRecord>(); ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); stmt.execute("SELECT * FROM "+table_name + " WHERE requester_contact_id = " + id); rs = stmt.getResultSet(); while(rs.next()) { ret.add(new CertificateRequestHostRecord(rs)); } stmt.close(); conn.close(); return ret; } //return requests that I am GA public ArrayList<CertificateRequestHostRecord> getIApprove(Integer id) throws SQLException { ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>(); //list all domains that user is gridadmin of StringBuffer cond = new StringBuffer(); GridAdminModel model = new GridAdminModel(context); try { for(GridAdminRecord grec : model.getGridAdminsByContactID(id)) { if(cond.length() != 0) { cond.append(" OR "); } cond.append("cns LIKE '%"+StringEscapeUtils.escapeSql(grec.domain)+"</String>%'"); } } catch (SQLException e1) { log.error("Failed to lookup GridAdmin domains", e1); } if(cond.length() != 0) { ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); stmt.execute("SELECT * FROM "+table_name + " WHERE "+cond.toString() + " AND status in ('REQUESTED','RENEW_REQUESTED','REVOKE_REQUESTED')"); rs = stmt.getResultSet(); while(rs.next()) { recs.add(new CertificateRequestHostRecord(rs)); } stmt.close(); conn.close(); } return recs; } /* //NO-AC //return pem encoded pkcs7s public String getPkcs7(CertificateRequestHostRecord rec) throws CertificateRequestException { StringArray pkcs7s = new StringArray(rec.cert_pkcs7); if(pkcs7s.length() > idx) { return pkcs7s.get(idx); } else { throw new CertificateRequestException("Index is larger than the number of CSR requested"); } } */ //NO-AC //issue all requested certs and store it back to DB //you can monitor request status by checking returned Certificate[] public void startissue(final CertificateRequestHostRecord rec) throws CertificateRequestException { // mark the request as "issuing.." try { rec.status = CertificateRequestStatus.ISSUING; context.setComment("Starting to issue certificates."); super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to update certificate request status for request:" + rec.id); throw new CertificateRequestException("Failed to update certificate request status"); }; //reconstruct cert array from db final StringArray csrs = new StringArray(rec.csrs); final StringArray serial_ids = new StringArray(rec.cert_serial_ids); final StringArray pkcs7s = new StringArray(rec.cert_pkcs7); final StringArray certificates = new StringArray(rec.cert_certificate); final StringArray intermediates = new StringArray(rec.cert_intermediate); final ICertificateSigner.Certificate[] certs = new ICertificateSigner.Certificate[csrs.length()]; for(int c = 0; c < csrs.length(); ++c) { certs[c] = new ICertificateSigner.Certificate(); certs[c].csr = csrs.get(c); certs[c].serial = serial_ids.get(c); certs[c].certificate = certificates.get(c); certs[c].intermediate = intermediates.get(c); certs[c].pkcs7 = pkcs7s.get(c); } new Thread(new Runnable() { public void failed(String message, Throwable e) { log.error(message, e); rec.status = CertificateRequestStatus.FAILED; rec.status_note = message + " :: " + e.getMessage(); try { context.setComment(message + " :: " + e.getMessage()); CertificateRequestHostModel.super.update(get(rec.id), rec); } catch (SQLException e1) { log.error("Failed to update request status while processing failed condition :" + message, e1); } //update ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ticket.description = "Failed to issue certificate.\n\n"; ticket.description += message+"\n\n"; ticket.description += e.getMessage()+"\n\n"; ticket.description += "The alert has been sent to GOC alert for furthre actions on this issue."; ticket.ccs.add(StaticConfig.conf.getProperty("certrequest.fail.assignee")); ticket.nextaction = "GOC developer to investigate"; fp.update(ticket, rec.goc_ticket_id); } //should we use Quartz instead? public void run() { CertificateManager cm = new CertificateManager(); try { cm.signHostCertificates(certs, new IHostCertificatesCallBack() { @Override public void certificateSigned(Certificate cert, int idx) { log.info("host cert issued by digicert: serial_id:" + cert.serial); log.info("pkcs7:" + cert.pkcs7); //pull some information from the cert for validation purpose java.security.cert.Certificate[] chain; try { chain = CertificateManager.parsePKCS7(cert.pkcs7); X509Certificate c0 = (X509Certificate)chain[0]; Date cert_notafter = c0.getNotAfter(); Date cert_notbefore = c0.getNotBefore(); //do a bit of validation Calendar today = Calendar.getInstance(); if(Math.abs(today.getTimeInMillis() - cert_notbefore.getTime()) > 1000*3600*24) { log.warn("Host certificate issued for request "+rec.id+"(idx:"+idx+") has cert_notbefore set too distance from current timestamp"); } long dayrange = (cert_notafter.getTime() - cert_notbefore.getTime()) / (1000*3600*24); if(dayrange < 390 || dayrange > 405) { log.warn("Host certificate issued for request "+rec.id+ "(idx:"+idx+") has valid range of "+dayrange+" days (too far from 395 days)"); } //make sure dn starts with correct base X500Principal dn = c0.getSubjectX500Principal(); String apache_dn = CertificateManager.X500Principal_to_ApacheDN(dn); String host_dn_base = StaticConfig.conf.getProperty("digicert.host_dn_base"); if(!apache_dn.startsWith(host_dn_base)) { log.warn("Host certificate issued for request " + rec.id + "(idx:"+idx+") has DN:"+apache_dn+" which doesn't have an expected DN base: "+host_dn_base); } } catch (CertificateException e1) { log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1); } catch (CMSException e1) { log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1); } catch (IOException e1) { log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1); } //update status note try { rec.status_note = "Certificate idx:"+idx+" has been issued. Serial Number: " + cert.serial; context.setComment(rec.status_note); CertificateRequestHostModel.super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to update certificate update while monitoring issue progress:" + rec.id); } } @Override public void certificateRequested() { //update certs db contents try { for(int c = 0; c < certs.length; ++c) { Certificate cert = certs[c]; serial_ids.set(c, cert.serial); } rec.cert_serial_ids = serial_ids.toXML(); context.setComment("Certificate requests has been sent."); CertificateRequestHostModel.super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to update certificate update while monitoring issue progress:" + rec.id); } } }); //update records int idx = 0; StringArray cert_certificates = new StringArray(rec.cert_certificate); StringArray cert_intermediates = new StringArray(rec.cert_intermediate); StringArray cert_pkcs7s = new StringArray(rec.cert_pkcs7); StringArray cert_serial_ids = new StringArray(rec.cert_serial_ids); for(ICertificateSigner.Certificate cert : certs) { cert_certificates.set(idx, cert.certificate); rec.cert_certificate = cert_certificates.toXML(); cert_intermediates.set(idx, cert.intermediate); rec.cert_intermediate = cert_intermediates.toXML(); cert_pkcs7s.set(idx, cert.pkcs7); rec.cert_pkcs7 = cert_pkcs7s.toXML(); cert_serial_ids.set(idx, cert.serial); rec.cert_serial_ids = cert_serial_ids.toXML(); ++idx; } //update status try { rec.status = CertificateRequestStatus.ISSUED; context.setComment("All ceritificates has been issued."); CertificateRequestHostModel.super.update(get(rec.id), rec); } catch (SQLException e) { throw new CertificateRequestException("Failed to update status for certificate request: " + rec.id); } //update ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has issued certificate. Resolving this ticket."; } else { ticket.description = "Someone with IP address: " + context.getRemoteAddr() + " has issued certificate. Resolving this ticket."; } ticket.status = "Resolved"; fp.update(ticket, rec.goc_ticket_id); } catch (ICertificateSigner.CertificateProviderException e) { failed("Failed to sign certificate -- CertificateProviderException ", e); } catch(Exception e) { failed("Failed to sign certificate -- unhandled", e); } } }).start(); } //NO-AC //return true if success public void approve(CertificateRequestHostRecord rec) throws CertificateRequestException { //get number of certificate requested for this request String [] cns = rec.getCNs(); int count = cns.length; //check quota CertificateQuotaModel quota = new CertificateQuotaModel(context); if(!quota.canApproveHostCert(count)) { throw new CertificateRequestException("You will exceed your host certificate quota."); } rec.status = CertificateRequestStatus.APPROVED; try { //context.setComment("Certificate Approved"); super.update(get(rec.id), rec); quota.incrementHostCertApproval(count); } catch (SQLException e) { log.error("Failed to approve host certificate request: " + rec.id); throw new CertificateRequestException("Failed to update certificate request record"); } //update ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ticket.description = "Dear " + rec.requester_name + ",\n\n"; ticket.description += "Your host certificate request has been approved. \n\n"; ticket.description += "To retrieve your certificate please visit " + getTicketUrl(rec.id) + " and click on Issue Certificate button.\n\n"; if(StaticConfig.isDebug()) { ticket.description += "Or if you are using the command-line: osg-cert-retrieve -T -i "+rec.id+"\n\n"; } else { ticket.description += "Or if you are using the command-line: osg-cert-retrieve -i "+rec.id+"\n\n"; } ticket.nextaction = "Requester to download certificate"; Calendar nad = Calendar.getInstance(); nad.add(Calendar.DATE, 7); ticket.nad = nad.getTime(); fp.update(ticket, rec.goc_ticket_id); } //NO-AC (for authenticated user) //return request record if successful, otherwise null public CertificateRequestHostRecord requestAsUser( String[] csrs, ContactRecord requester, String request_comment, String[] request_ccs, Integer approver_vo_id) throws CertificateRequestException { CertificateRequestHostRecord rec = new CertificateRequestHostRecord(); //Date current = new Date(); rec.requester_contact_id = requester.id; rec.requester_name = requester.name; rec.approver_vo_id = approver_vo_id; //rec.requester_email = requester.primary_email; //rec.requester_phone = requester.primary_phone; Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ticket.name = requester.name; ticket.email = requester.primary_email; ticket.phone = requester.primary_phone; ticket.title = "Host Certificate Request by " + requester.name + "(OIM user)"; ticket.metadata.put("SUBMITTER_NAME", requester.name); if(request_ccs != null) { for(String cc : request_ccs) { ticket.ccs.add(cc); } } return request(csrs, rec, ticket, request_comment); } //NO-AC (for guest user) //return request record if successful, otherwise null public CertificateRequestHostRecord requestAsGuest( String[] csrs, String requester_name, String requester_email, String requester_phone, String request_comment, String[] request_ccs, Integer approver_vo_id) throws CertificateRequestException { CertificateRequestHostRecord rec = new CertificateRequestHostRecord(); //Date current = new Date(); rec.approver_vo_id = approver_vo_id; rec.requester_name = requester_name; //rec.requester_email = requester_email; //rec.requester_phone = requester_phone; Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ticket.name = requester_name; ticket.email = requester_email; ticket.phone = requester_phone; ticket.title = "Host Certificate Request by " + requester_name + "(Guest)"; ticket.metadata.put("SUBMITTER_NAME", requester_name); if(request_ccs != null) { for(String cc : request_ccs) { ticket.ccs.add(cc); } } return request(csrs, rec, ticket, request_comment); } private String getTicketUrl(Integer request_id) { String base; //this is not an exactly correct assumption, but it should be good enough if(StaticConfig.isDebug()) { base = "https://oim-itb.grid.iu.edu/oim/"; } else { base = "https://oim.grid.iu.edu/oim/"; } return base + "certificatehost?id=" + request_id; } //NO-AC //return request record if successful, otherwise null (guest interface) private CertificateRequestHostRecord request( String[] csrs, CertificateRequestHostRecord rec, FPTicket ticket, String request_comment) throws CertificateRequestException { //log.debug("request"); Date current = new Date(); rec.request_time = new Timestamp(current.getTime()); rec.status = CertificateRequestStatus.REQUESTED; if(request_comment != null) { rec.status_note = request_comment; context.setComment(request_comment); } //log.debug("request init"); //store CSRs / CNs to record StringArray csrs_sa = new StringArray(csrs.length); StringArray cns_sa = new StringArray(csrs.length); int idx = 0; for(String csr_string : csrs) { log.debug("processing csr: " + csr_string); String cn; try { PKCS10CertificationRequest csr = parseCSR(csr_string); cn = pullCNFromCSR(csr); //we need to do CN validation here - so that I don't have to do it on both rest/web interfaces if(!cn.matches("^([-0-9a-zA-Z\\.]*/)?[-0-9a-zA-Z\\.]*$")) { //OSGPKI-255 throw new CertificateRequestException("CN structure is invalid, or contains invalid characters."); } cns_sa.set(idx, cn); } catch (IOException e) { log.error("Failed to base64 decode CSR", e); throw new CertificateRequestException("Failed to base64 decode CSR:"+csr_string, e); } catch (NullPointerException e) { log.error("(probably) couldn't find CN inside the CSR:"+csr_string, e); throw new CertificateRequestException("Failed to base64 decode CSR", e); } csrs_sa.set(idx++, csr_string); } rec.csrs = csrs_sa.toXML(); rec.cns = cns_sa.toXML(); StringArray ar = new StringArray(csrs.length); rec.cert_certificate = ar.toXML(); rec.cert_intermediate = ar.toXML(); rec.cert_pkcs7 = ar.toXML(); rec.cert_serial_ids = ar.toXML(); try { ArrayList<ContactRecord> gas = findGridAdmin(rec.getCSRs(), rec.approver_vo_id); //find if submitter is ga boolean submitter_is_ga = false; for(ContactRecord ga : gas) { if(ga.id.equals(rec.requester_contact_id)) { submitter_is_ga = true; break; } } //now submit - after this, we are commited. Integer request_id = super.insert(rec); if(submitter_is_ga) { ticket.description = "Host certificate request has been submitted by GridAdmin.\n\n"; //don't cc anyone. } else { ticket.description = "Dear GridAdmin; "; for(ContactRecord ga : gas) { ticket.description += ga.name + ", "; ticket.ccs.add(ga.primary_email); } ticket.description += "\n\n"; ticket.description += "Host certificate request has been submitted. "; ticket.description += "Please determine this request's authenticity, and approve / disapprove at " + getTicketUrl(request_id) + "\n\n"; } Authorization auth = context.getAuthorization(); ticket.description += "Requester IP:" + context.getRemoteAddr() + "\n"; if(auth.isUser()) { ContactRecord user = auth.getContact(); //ticket.description += "OIM User Name:" + user.name + "\n"; ticket.description += "Submitter is OIM authenticated with DN:" + auth.getUserDN() + "\n"; } if(request_comment != null) { ticket.description += "Requester Comment: "+request_comment; } ticket.assignees.add(StaticConfig.conf.getProperty("certrequest.host.assignee")); ticket.nextaction = "GridAdmin to verify requester"; Calendar nad = Calendar.getInstance(); nad.add(Calendar.DATE, 7); ticket.nad = nad.getTime(); //set metadata ticket.metadata.put("SUBMITTED_VIA", "OIM/CertManager(host)"); if(auth.isUser()) { ticket.metadata.put("SUBMITTER_DN", auth.getUserDN()); } //all ready to submit request Footprints fp = new Footprints(context); log.debug("opening footprints ticket"); String ticket_id = fp.open(ticket); log.debug("update request record with goc ticket id"); rec.goc_ticket_id = ticket_id; context.setComment("Opened GOC Ticket " + ticket_id); super.update(get(request_id), rec); } catch (SQLException e) { throw new CertificateRequestException("Failed to insert host certificate request record", e); } return rec; } public PKCS10CertificationRequest parseCSR(String csr_string) throws IOException { PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(csr_string)); return csr; } public String pullCNFromCSR(PKCS10CertificationRequest csr) throws CertificateRequestException { //pull CN from pkcs10 X500Name name; RDN[] cn_rdn; try { name = csr.getSubject(); cn_rdn = name.getRDNs(BCStyle.CN); } catch(Exception e) { throw new CertificateRequestException("Failed to decode CSR", e); } if(cn_rdn.length != 1) { throw new CertificateRequestException("Please specify exactly one CN containing the hostname. You have provided DN: " + name.toString()); } String cn = cn_rdn[0].getFirst().getValue().toString(); //wtf? log.debug("cn found: " + cn); return cn; } //find gridadmin who should process the request - identify domain from csrs //if there are more than 1 vos group, then user must specify whic hone via approver_vo_id (it could be null for gridadmin with only 1 vo group) //null if none, or there are more than 1 public ArrayList<ContactRecord> findGridAdmin(String[] csrs, Integer approver_vo_id) throws CertificateRequestException { GridAdminModel gamodel = new GridAdminModel(context); String gridadmin_domain = null; int idx = 0; if(csrs.length == 0) { throw new CertificateRequestException("No CSR"); } for(String csr_string : csrs) { //parse CSR and pull CN String cn; try { PKCS10CertificationRequest csr = parseCSR(csr_string); cn = pullCNFromCSR(csr); } catch (IOException e) { log.error("Failed to base64 decode CSR", e); throw new CertificateRequestException("Failed to base64 decode CSR:"+csr_string, e); } catch (NullPointerException e) { log.error("(probably) couldn't find CN inside the CSR:"+csr_string, e); throw new CertificateRequestException("Failed to base64 decode CSR", e); } catch(Exception e) { throw new CertificateRequestException("Failed to decode CSR", e); } //lookup registered gridadmin domain String domain = null; try { domain = gamodel.getDomainByFQDN(cn); } catch (SQLException e) { throw new CertificateRequestException("Failed to lookup GridAdmin to approve host:" + cn, e); } if(domain == null) { throw new CertificateRequestException("The hostname you have provided in the CSR/CN=" + cn + " does not match any domain OIM is currently configured to issue certificates for.\n\nPlease double check the CN you have specified. If you'd like to be a GridAdmin for this domain, please open GOC Ticket at https://ticket.grid.iu.edu "); } //make sure same set of gridadmin approves all host if(gridadmin_domain == null) { gridadmin_domain = domain; } else { if(!gridadmin_domain.equals(domain)) { throw new CertificateRequestException("All host certificates must be approved by the same set of gridadmins. Different for " + cn); } } } try { HashMap<VORecord, ArrayList<GridAdminRecord>> groups = gamodel.getByDomainGroupedByVO(gridadmin_domain); if(groups.size() == 0) { throw new CertificateRequestException("No gridadmin exists for domain: " + gridadmin_domain); } if(groups.size() == 1 && approver_vo_id == null) { //just return the first group for(VORecord vo : groups.keySet()) { ArrayList<GridAdminRecord> gas = groups.get(vo); return GAsToContacts(gas); } } //use a group user specified - must match String vonames = ""; for(VORecord vo : groups.keySet()) { vonames += vo.name + ", "; //just in case we might need to report error message later if(vo.id.equals(approver_vo_id)) { //found a match.. return the list ArrayList<GridAdminRecord> gas = groups.get(vo); return GAsToContacts(gas); } } //oops.. didn't find specified vo.. throw new CertificateRequestException("Couldn't find GridAdmin group under specified VO. Please use one of following VOs:" + vonames); } catch (SQLException e) { throw new CertificateRequestException("Failed to lookup gridadmin contacts for domain:" + gridadmin_domain, e); } } public ArrayList<ContactRecord> GAsToContacts(ArrayList<GridAdminRecord> gas) throws SQLException { //convert contact_id to contact record ArrayList<ContactRecord> contacts = new ArrayList<ContactRecord>(); ContactModel cmodel = new ContactModel(context); for(GridAdminRecord ga : gas) { contacts.add(cmodel.get(ga.contact_id)); } return contacts; } /* //go directly from ISSUED > ISSUEING public void renew(final CertificateRequestHostRecord rec) throws CertificateRequestException { String [] csrs = rec.getCSRs(); //check quota CertificateQuotaModel quota = new CertificateQuotaModel(context); if(!quota.canApproveHostCert(csrs.length)) { throw new CertificateRequestException("You will exceed your host certificate quota."); } //notification -- just make a note on an existing ticket - we don't need to create new goc ticket - there is nobody we need to inform - Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " is renewing host certificates.\n\n"; ticket.description += "> " + context.getComment(); } else { throw new CertificateRequestException("guest can't renew"); } ticket.status = "Engineering";//reopen ticket temporarily fp.update(ticket, rec.goc_ticket_id); //clear previously issued cert //rec.cert_certificate = null; //rec.cert_intermediate = null; //rec.cert_pkcs7 = null; //rec.cert_serial_ids = null; //start issuing immediately startissue(rec); //increment quota try { quota.incrementHostCertApproval(csrs.length); } catch (SQLException e) { log.error("Failed to incremenet quota while renewing request id:"+rec.id); } context.message(MessageType.SUCCESS, "Successfully renewed certificates. Please download & install your certificates."); } */ /* //NO-AC //return host rec if success public CertificateRequestHostRecord requestRenew(CertificateRequestHostRecord rec) throws CertificateRequestException { //lookup gridadmin first ArrayList<ContactRecord> gas = findGridAdmin(rec.getCSRs(), rec.approver_vo_id); rec.status = CertificateRequestStatus.RENEW_REQUESTED; //clear all previously issued cert (we are going to reuse the CSR) StringArray csrs = new StringArray(rec.csrs); StringArray ar = new StringArray(csrs.length()); rec.cert_certificate = ar.toXML(); rec.cert_intermediate = ar.toXML(); rec.cert_pkcs7 = ar.toXML(); rec.cert_serial_ids = ar.toXML(); try { super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to request host certificate request renewal: " + rec.id); throw new CertificateRequestException("Failed to update request status", e); } Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has requested renewal for this certificate request."; } else { ticket.description = "Guest user with IP:" + context.getRemoteAddr() + " has requested renewal of this certificate request."; } ticket.description += "\n\n> " + context.getComment(); ticket.description += "\n\nPlease approve / disapprove this request at " + getTicketUrl(rec.id); ticket.nextaction = "GridAdmin to verify and approve/reject"; //nad will be set to 7 days from today by default ticket.status = "Engineering"; //I need to reopen resolved ticket. //Update CC gridadmin (it might have been changed since last time request was made) VOContactModel model = new VOContactModel(context); ContactModel cmodel = new ContactModel(context); for(ContactRecord ga : gas) { ticket.ccs.add(ga.primary_email); } //reopen now fp.update(ticket, rec.goc_ticket_id); return rec; } */ //NO-AC public void requestRevoke(CertificateRequestHostRecord rec) throws CertificateRequestException { rec.status = CertificateRequestStatus.REVOCATION_REQUESTED; try { super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to request revocation of host certificate: " + rec.id); throw new CertificateRequestException("Failed to update request status", e); } Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has requested revocation of this certificate request."; } else { ticket.description = "Guest user with IP:" + context.getRemoteAddr() + " has requested revocation of this certificate request."; } ticket.description += "\n\nPlease approve / disapprove this request at " + getTicketUrl(rec.id); ticket.nextaction = "Grid Admin to process request."; //nad will be set to 7 days from today by default ticket.status = "Engineering"; //I need to reopen resolved ticket. fp.update(ticket, rec.goc_ticket_id); } //NO-AC //return true if success public void cancel(CertificateRequestHostRecord rec) throws CertificateRequestException { try { if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) || rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) { rec.status = CertificateRequestStatus.ISSUED; } else { rec.status = CertificateRequestStatus.CANCELED; } super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to cancel host certificate request:" + rec.id); throw new CertificateRequestException("Failed to cancel request status", e); } Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has canceled this request.\n\n"; } else { //Guest can still cancel by providing the password used to submit the request. } ticket.description += "\n\n> " + context.getComment(); ticket.status = "Resolved"; fp.update(ticket, rec.goc_ticket_id); } public void reject(CertificateRequestHostRecord rec) throws CertificateRequestException { if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED)|| rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) { rec.status = CertificateRequestStatus.ISSUED; } else { //all others rec.status = CertificateRequestStatus.REJECTED; } try { //context.setComment("Certificate Approved"); super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to reject host certificate request:" + rec.id); throw new CertificateRequestException("Failed to reject request status", e); } Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has rejected this certificate request.\n\n"; } else { throw new CertificateRequestException("Guest shouldn't be rejecting request"); } ticket.description += "> " + context.getComment(); ticket.status = "Resolved"; fp.update(ticket, rec.goc_ticket_id); } //NO-AC public void revoke(CertificateRequestHostRecord rec) throws CertificateRequestException { //revoke CertificateManager cm = new CertificateManager(); try { String[] cert_serial_ids = rec.getSerialIDs(); for(String cert_serial_id : cert_serial_ids) { log.info("Revoking certificate with serial ID: " + cert_serial_id); cm.revokeHostCertificate(cert_serial_id); } } catch (CertificateProviderException e1) { log.error("Failed to revoke host certificate", e1); throw new CertificateRequestException("Failed to revoke host certificate", e1); } rec.status = CertificateRequestStatus.REVOKED; try { //context.setComment("Certificate Approved"); super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to update host certificate status: " + rec.id); throw new CertificateRequestException("Failed to update host certificate status", e); } Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has revoked this certificate."; } else { throw new CertificateRequestException("Guest should'nt be revoking certificate"); } ticket.description += "> " + context.getComment(); ticket.status = "Resolved"; fp.update(ticket, rec.goc_ticket_id); } //determines if user should be able to view request details, logs, and download certificate (pkcs12 is session specific) public boolean canView(CertificateRequestHostRecord rec) { return true; /* if(auth.isGuest()) { //right now, guest can't view any certificate requests } else if(auth.isUser()) { //super ra can see all requests if(auth.allows("admin_all_user_cert_requests")) return true; //is user the requester? ContactRecord contact = auth.getContact(); if(rec.requester_id.equals(contact.id)) return true; //ra or sponsor for specified vo can view it VOContactModel model = new VOContactModel(context); ContactModel cmodel = new ContactModel(context); ArrayList<VOContactRecord> crecs; try { crecs = model.getByVOID(rec.vo_id); for(VOContactRecord crec : crecs) { ContactRecord contactrec = cmodel.get(crec.contact_id); if(crec.contact_type_id.equals(11) && crec.contact_rank_id.equals(1)) { //primary if(contactrec.id.equals(contact.id)) return true; } if(crec.contact_type_id.equals(11) && crec.contact_rank_id.equals(3)) { //sponsor if(contactrec.id.equals(contact.id)) return true; } } } catch (SQLException e1) { log.error("Failed to lookup RA/sponsor information", e1); } } return false; */ } //true if user can approve request public boolean canApprove(CertificateRequestHostRecord rec) { if(!canView(rec)) return false; if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) || rec.status.equals(CertificateRequestStatus.REQUESTED)) { //^RA doesn't *approve* REVOKE_REQUESTED - RA just click on REVOKE button if(auth.isUser()) { //grid admin can appove it ContactRecord user = auth.getContact(); try { ArrayList<ContactRecord> gas = findGridAdmin(rec.getCSRs(), rec.approver_vo_id); for(ContactRecord ga : gas) { if(ga.id.equals(user.id)) { return true; } } } catch (CertificateRequestException e) { log.error("Failed to lookup gridadmin for " + rec.id + " while processing canApprove()", e); } } } return false; } public LogDetail getLastApproveLog(ArrayList<LogDetail> logs) { for(LogDetail log : logs) { if(log.status.equals("APPROVED")) { return log; } } return null; } /* //true if user can approve request public boolean canRenew(CertificateRequestHostRecord rec, ArrayList<LogDetail> logs) { if(!canView(rec)) return false; //only issued request can be renewed if(!rec.status.equals(CertificateRequestStatus.ISSUED)) return false; //logged in? if(!auth.isUser()) return false; //original requester or gridadmin? ContactRecord contact = auth.getContact(); if(!rec.requester_contact_id.equals(contact.id) && !canApprove(rec)) return false; //approved within 5 years? LogDetail last = getLastApproveLog(logs); if(last == null) return false; //never approved Calendar five_years_ago = Calendar.getInstance(); five_years_ago.add(Calendar.YEAR, -5); if(last.time.before(five_years_ago.getTime())) return false; //TODO -- will expire in less than 6 month? (can I gurantee that all certificates has the same expiration date?) //Calendar six_month_future = Calendar.getInstance(); //six_month_future.add(Calendar.MONTH, 6); //if(rec.cert_notafter.after(six_month_future.getTime())) return false; //all good return true; } */ public boolean canReject(CertificateRequestHostRecord rec) { return canApprove(rec); //same rule as approval } public boolean canCancel(CertificateRequestHostRecord rec) { if(!canView(rec)) return false; if( rec.status.equals(CertificateRequestStatus.REQUESTED) || rec.status.equals(CertificateRequestStatus.APPROVED) || //if renew_requesterd > approved cert is canceled, it should really go back to "issued", but currently it doesn't. //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) || rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) { if(auth.isUser()) { //requester can cancel one's own request if(rec.requester_contact_id != null) {//could be null if guest submitted it ContactRecord contact = auth.getContact(); if(rec.requester_contact_id.equals(contact.id)) return true; } //grid admin can cancel it ContactRecord user = auth.getContact(); try { ArrayList<ContactRecord> gas = findGridAdmin(rec.getCSRs(), rec.approver_vo_id); for(ContactRecord ga : gas) { if(ga.id.equals(user.id)) { return true; } } } catch (CertificateRequestException e) { log.error("Failed to lookup gridadmin for " + rec.id + " while processing canCancel()", e); } } } return false; } //why can't we just issue certificate after it's been approved? because we might have to create pkcs12 public boolean canIssue(CertificateRequestHostRecord rec) { if(!canView(rec)) return false; if( rec.status.equals(CertificateRequestStatus.APPROVED)) { if(rec.requester_contact_id == null) { //anyone can issue guest request return true; } else { if(auth.isUser()) { ContactRecord contact = auth.getContact(); //requester can issue if(rec.requester_contact_id.equals(contact.id)) return true; } } } return false; } /* public boolean canRequestRenew(CertificateRequestHostRecord rec) { if(!canView(rec)) return false; if( rec.status.equals(CertificateRequestStatus.ISSUED)) { if(auth.isUser()) { return true; } } return false; } */ public boolean canRequestRevoke(CertificateRequestHostRecord rec) { if(!canView(rec)) return false; if(rec.status.equals(CertificateRequestStatus.ISSUED)) { if(auth.isUser() && canRevoke(rec)) { //if user can directly revoke it, no need to request it return false; } //all else, allow return true; } return false; } public boolean canRevoke(CertificateRequestHostRecord rec) { if(!canView(rec)) return false; if( rec.status.equals(CertificateRequestStatus.ISSUED) || rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) { if(auth.isUser()) { /* if(auth.allows("revoke_all_certificate")) { return true; } */ //requester oneself can revoke it if(rec.requester_contact_id != null) {//could be null if guest submitted it ContactRecord contact = auth.getContact(); if(rec.requester_contact_id.equals(contact.id)) return true; } //grid admin can revoke it ContactRecord user = auth.getContact(); try { ArrayList<ContactRecord> gas = findGridAdmin(rec.getCSRs(), rec.approver_vo_id); for(ContactRecord ga : gas) { if(ga.id.equals(user.id)) { return true; } } } catch (CertificateRequestException e) { log.error("Failed to lookup gridadmin for " + rec.id + " while processing canRevoke()", e); } } } return false; } //NO AC public CertificateRequestHostRecord getBySerialID(String serial_id) throws SQLException { CertificateRequestHostRecord rec = null; ResultSet rs = null; Connection conn = connectOIM(); PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM "+table_name+ " WHERE cert_serial_ids like ?"); pstmt.setString(1, "%>"+serial_id+"<%"); if (pstmt.executeQuery() != null) { rs = pstmt.getResultSet(); if(rs.next()) { rec = new CertificateRequestHostRecord(rs); } } pstmt.close(); conn.close(); return rec; } //pass null to not filter public ArrayList<CertificateRequestHostRecord> search(String cns_contains, String status, Date request_after, Date request_before) throws SQLException { ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>(); ResultSet rs = null; Connection conn = connectOIM(); String sql = "SELECT * FROM "+table_name+" WHERE 1 = 1"; if(cns_contains != null) { sql += " AND cns like \"%"+StringEscapeUtils.escapeSql(cns_contains)+"%\""; } if(status != null) { sql += " AND status = \""+status+"\""; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if(request_after != null) { sql += " AND request_time >= \""+sdf.format(request_after) + "\""; } if(request_before != null) { sql += " AND request_time <= \""+sdf.format(request_before) + "\""; } PreparedStatement stmt = conn.prepareStatement(sql); rs = stmt.executeQuery(); while(rs.next()) { recs.add(new CertificateRequestHostRecord(rs)); } stmt.close(); conn.close(); return recs; } //prevent low level access - please use model specific actions @Override public Integer insert(CertificateRequestHostRecord rec) throws SQLException { throw new UnsupportedOperationException("Please use model specific actions instead (request, approve, reject, etc..)"); } @Override public void update(CertificateRequestHostRecord oldrec, CertificateRequestHostRecord newrec) throws SQLException { throw new UnsupportedOperationException("Please use model specific actions insetead (request, approve, reject, etc..)"); } @Override public void remove(CertificateRequestHostRecord rec) throws SQLException { throw new UnsupportedOperationException("disallowing remove cert request.."); } @Override CertificateRequestHostRecord createRecord() throws SQLException { // TODO Auto-generated method stub return null; } }
/* * $Id: FuncSchedService.java,v 1.6 2004-10-26 18:50:25 tlipkis Exp $ */ package org.lockss.scheduler; import java.util.*; import java.io.*; import org.lockss.daemon.*; import org.lockss.util.*; import org.lockss.test.*; import org.lockss.plugin.*; /** * Test class for org.lockss.scheduler.SchedService */ public class FuncSchedService extends LockssTestCase { static Logger log = Logger.getLogger("FuncSchedService"); public static Class testedClasses[] = { org.lockss.scheduler.SchedService.class, org.lockss.scheduler.TaskRunner.class, }; private MockLockssDaemon theDaemon; private SchedService svc; public void setUp() throws Exception { super.setUp(); theDaemon = getMockLockssDaemon(); svc = theDaemon.getSchedService(); svc.startService(); } public void tearDown() throws Exception { svc.stopService(); super.tearDown(); } void waitUntilDone() throws Exception { Interrupter intr = null; try { intr = interruptMeIn(TIMEOUT_SHOULDNT); while (!svc.isIdle()) { TimerUtil.guaranteedSleep(100); } intr.cancel(); } finally { if (intr.did()) { fail("Hasher timed out"); } } } BackgroundTask btask(long start, long end, double loadFactor, TaskCallback cb) { return new BackgroundTask(Deadline.in(start), Deadline.in(end), loadFactor, cb); } public void testOneBack() throws Exception { final List rec = new ArrayList(); TaskCallback cb = new TaskCallback() { public void taskEvent(SchedulableTask task, Schedule.EventType event) { rec.add(new BERec(Deadline.in(0), (BackgroundTask)task, event)); }}; // Scheduling may legitimately fail if machine is slow or busy. // Successively try more distant times in the future until it succeeds. long future = 10; for (int ix = 1; ix <= 10; ix++) { BackgroundTask task = btask(future, future + 100, .1, cb); if (svc.scheduleTask(task)) { log.debug("scheduled with future = " + future); waitUntilDone(); List exp = ListUtil.list(new BERec(task, Schedule.EventType.START), new BERec(task, Schedule.EventType.FINISH)); assertEquals(exp, rec); return; } future = 2 * future; } fail("Couldn't schedule background task within " + StringUtil.timeIntervalToString(future)); } // Background event record class BERec { Deadline when; BackgroundTask task; Schedule.EventType event; BERec(Deadline when, BackgroundTask task, Schedule.EventType event) { this.when = when; this.task = task; this.event = event; } BERec(long when, BackgroundTask task, Schedule.EventType event) { this.when = Deadline.at(when); this.task = task; this.event = event; } BERec(BackgroundTask task, Schedule.EventType event) { this.when = Deadline.EXPIRED; this.task = task; this.event = event; } public boolean equals(Object obj) { if (obj instanceof BERec) { BERec o = (BERec)obj; return (!TimeBase.isSimulated() || when.equals(o.when)) && task.equals(o.task) && event == o.event; } return false; } public String toString() { return "[BERec: " + event + ", " + when + ", " + task + "]"; } } }
package edu.mit.mobile.android.content; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.app.Application; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.util.Log; import edu.mit.mobile.android.content.column.DBColumn; import edu.mit.mobile.android.content.dbhelper.SearchDBHelper; import edu.mit.mobile.android.content.m2m.M2MDBHelper; public abstract class SimpleContentProvider extends ContentProvider { private static final String TAG = SimpleContentProvider.class.getSimpleName(); // /////////////////// public API constants /** * Suffix that turns a dir path into an item path. The # represents the item ID number. */ public static final String PATH_ITEM_ID_SUFFIX = "/ /** * This is the starting value for the automatically-generated URI mapper entries. You can freely * use any numbers below this without any risk of conflict. */ public static final int URI_MATCHER_CODE_START = 0x100000; // /////////////////////// private fields private final String mAuthority; protected String mDBName; protected final int mDBVersion; private final DBHelperMapper mDBHelperMapper; private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH); private DatabaseOpenHelper mDatabaseHelper; private final List<DBHelper> mDBHelpers = new ArrayList<DBHelper>(); private final HashMap<String, Class<? extends ContentItem>> mContentItemTypeMap = new HashMap<String, Class<? extends ContentItem>>(); private int mMatcherID = URI_MATCHER_CODE_START; private static final String ERR_NO_HANDLER = "uri not handled by provider"; // /////////////////////////////// public methods /** * The database name for this provider is generated based on the provider's class name. If you * have multiple providers in your {@link Application}, you should ensure that these class names * are unique or specify your own dbName with * {@link #SimpleContentProvider(String, String, int)}. * * @param authority * the full authority string for this provider * @param dbVersion * the version of the database schema associated with this provider. * <strong>NOTE:</strong> This number must be increased each time the database schema * (in this instance, your {@link ContentItem} fields) changes in order for the * tables to be recreated. At the moment, there <strong>WILL BE DATA LOSS</strong> * when this number increases, so please make sure to that the data is backed up * first. */ public SimpleContentProvider(String authority, int dbVersion) { this(authority, null, dbVersion); } /** * @param authority * the full authority string for this provider * @param dbName * the name of the database. This must be unique throughout your {@link Application}. * @param dbVersion * the version of the database schema associated with this provider. * <strong>NOTE:</strong> This number must be increased each time the database schema * (in this instance, your {@link ContentItem} fields) changes in order for the * tables to be recreated. At the moment, there <strong>WILL BE DATA LOSS</strong> * when this number increases, so please make sure to that the data is backed up * first. */ public SimpleContentProvider(String authority, String dbName, int dbVersion) { super(); mAuthority = authority; mDBHelperMapper = new DBHelperMapper(); mDBName = dbName; mDBVersion = dbVersion; } /** * Registers a DBHelper with the content provider. You must call this in the constructor of any * subclasses. * * @param dbHelper * @deprecated no longer needed; helpers will be implicitly added when calling * {@link #addDirAndItemUri(DBHelper, String)} and friends. * @see SimpleContentProvider#registerDBHelper(DBHelper) */ @Deprecated public void addDBHelper(DBHelper dbHelper) { mDBHelpers.add(dbHelper); } /** * Registers a {@link DBHelper} with the provider. This is only needed when you don't call * {@link #addDirAndItemUri(DBHelper, String)} and friends, as they will implicitly register for * you. This can be called multiple times without issue. * * @param dbHelper * the helper you wish to have registered with this provider */ public void registerDBHelper(DBHelper dbHelper) { if (!mDBHelpers.contains(dbHelper)) { mDBHelpers.add(dbHelper); } } /** * Adds an entry for a directory of a given type. This should be called in the constructor of * any subclasses. * * @param dbHelper * the DBHelper to associate with the given path. * @param path * a complete path on top of the content provider's authority. * @param type * the complete MIME type for the item's directory. * @param verb * one or more of {@link DBHelperMapper#VERB_ALL}, {@link DBHelperMapper#VERB_INSERT} * , {@link DBHelperMapper#VERB_QUERY}, {@link DBHelperMapper#VERB_UPDATE}, * {@link DBHelperMapper#VERB_DELETE} joined bitwise. */ public void addDirUri(DBHelper dbHelper, String path, String type, int verb) { registerDBHelper(dbHelper); mDBHelperMapper.addDirMapping(mMatcherID, dbHelper, verb, type); MATCHER.addURI(mAuthority, path, mMatcherID); if (dbHelper instanceof ContentItemRegisterable) { registerContentItemType(type, ((ContentItemRegisterable) dbHelper).getContentItem(false)); } mMatcherID++; } /** * Adds an entry for a directory of a given type. This should be called in the constructor of * any subclasses. * * Defaults to handle all method types. * * @param dbHelper * the DBHelper to associate with the given path. * @param path * a complete path on top of the content provider's authority. * * @param type * the complete MIME type for the item's directory. */ public void addDirUri(DBHelper dbHelper, String path) { addDirUri(dbHelper, path, dbHelper.getDirType(mAuthority, path), DBHelperMapper.VERB_ALL); } /** * Adds an entry for a directory of a given type. This should be called in the constructor of * any subclasses. * * Defaults to handle all method types. * * @param dbHelper * the DBHelper to associate with the given path. * @param path * a complete path on top of the content provider's authority. * * @param type * the complete MIME type for the item's directory. */ public void addDirUri(DBHelper dbHelper, String path, String type) { addDirUri(dbHelper, path, type, DBHelperMapper.VERB_ALL); } /** * Adds dir and item entries for the given helper at the given path. The types are generated * using {@link DBHelper#getDirType(String, String)} and * {@link DBHelper#getItemType(String, String)} passing path in for the suffix. * * @param dbHelper * @param path * a complete path on top of the content provider's authority. */ public void addDirAndItemUri(DBHelper dbHelper, String path) { addDirAndItemUri(dbHelper, path, dbHelper.getDirType(mAuthority, path), dbHelper.getItemType(mAuthority, path)); } /** * Adds both dir and item entries for the given * * @param dbHelper * @param path * the path that will be used for the item's dir. For the item, it will be suffixed * with {@value #PATH_ITEM_ID_SUFFIX}. * @param dirType * The complete MIME type for the item's directory. * @param itemType * The complete MIME type for the item. */ public void addDirAndItemUri(DBHelper dbHelper, String path, String dirType, String itemType) { addDirUri(dbHelper, path, dirType, DBHelperMapper.VERB_ALL); addItemUri(dbHelper, path + PATH_ITEM_ID_SUFFIX, itemType, DBHelperMapper.VERB_ALL); } /** * Functionally equivalent to {@link #addDirAndItemUri(DBHelper, String)} with a path of * parentPath/#/childPath * * @param helper * the helper that will handle this request. Usually, this is an {@link M2MDBHelper}. * @param parentPath * the path of the parent. This should not end in an "#" as it will be added for you * @param childPath * the path of the child within an item of the parent. */ public void addChildDirAndItemUri(DBHelper helper, String parentPath, String childPath) { final String path = parentPath + "/#/" + childPath; addDirAndItemUri(helper, path); // XXX this is a hack. There should be a better solution for this if (helper instanceof ForeignKeyDBHelper || helper instanceof M2MDBHelper) { final String path_all = parentPath + "/_all/" + childPath; addDirAndItemUri(helper, path_all, helper.getDirType(mAuthority, path), helper.getItemType(mAuthority, path)); } } /** * Adds an entry for an item of a given type. This should be called in the constructor of any * subclasses. * * @param dbHelper * the DBHelper to associate with the given path. * @param path * a complete path on top of the content provider's authority. <strong>This must end * in <code>{@value #PATH_ITEM_ID_SUFFIX}</code></strong> * @param type * The complete MIME type for this item. * @param verb * one or more of {@link DBHelperMapper#VERB_ALL}, {@link DBHelperMapper#VERB_INSERT} * , {@link DBHelperMapper#VERB_QUERY}, {@link DBHelperMapper#VERB_UPDATE}, * {@link DBHelperMapper#VERB_DELETE} joined bitwise. */ public void addItemUri(DBHelper dbHelper, String path, String type, int verb) { registerDBHelper(dbHelper); mDBHelperMapper.addItemMapping(mMatcherID, dbHelper, verb, type); MATCHER.addURI(mAuthority, path, mMatcherID); if (dbHelper instanceof ContentItemRegisterable) { registerContentItemType(type, ((ContentItemRegisterable) dbHelper).getContentItem(true)); } mMatcherID++; } /** * Adds an entry for an item of a given type. This should be called in the constructor of any * subclasses. * * Defaults to handle all method types. * * @param dbHelper * the DBHelper to associate with the given path. * @param path * a complete path on top of the content provider's authority. <strong>This must end * in <code>{@value #PATH_ITEM_ID_SUFFIX}</code></strong> */ public void addItemUri(DBHelper dbHelper, String path, String type) { addItemUri(dbHelper, path, type, DBHelperMapper.VERB_ALL); } * {@link SearchManager#SUGGEST_URI_PATH_QUERY}{@code /*}. Can be null. */ public void addSearchUri(SearchDBHelper searchHelper, String path) { addDirUri(searchHelper, getSearchPath(path), SearchManager.SUGGEST_MIME_TYPE, DBHelperMapper.VERB_QUERY); /** * Constructs a full search path based on the given path. Equivalent to {@code path/} * {@link SearchManager#SUGGEST_URI_PATH_QUERY} * * @param path * the path to suffix the whole query. can be null, which will simply output * {@link SearchManager#SUGGEST_URI_PATH_QUERY}. * @return the full search path */ public static String getSearchPath(String path) { return (path != null ? path + "/" : "") + SearchManager.SUGGEST_URI_PATH_QUERY; } @Override public boolean onCreate() { if (mDBName == null) { mDBName = generateDBName(); } mDatabaseHelper = createDatabaseOpenHelper(); return true; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase(); final int match = MATCHER.match(uri); if (UriMatcher.NO_MATCH == match) { throw new IllegalArgumentException(ERR_NO_HANDLER + ": " + uri); } if (!mDBHelperMapper.canDelete(match)) { throw new IllegalArgumentException("delete note supported"); } final int count = mDBHelperMapper.delete(match, this, db, uri, selection, selectionArgs); getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public String getType(Uri uri) { final int match = MATCHER.match(uri); if (UriMatcher.NO_MATCH == match) { throw new IllegalArgumentException(ERR_NO_HANDLER + ": " + uri); } return mDBHelperMapper.getType(match); } /** * This has been moved to {@link ProviderUtils#toDirType(String, String)} * * @deprecated */ @Deprecated public String getDirType(String suffix) { return ProviderUtils.toDirType(mAuthority, suffix); } /** * This has been moved to {@link ProviderUtils#toItemType(String, String)} * * @deprecated */ @Deprecated public String getItemType(String suffix) { return ProviderUtils.toItemType(mAuthority, suffix); } /** * Registers a {@link ContentItem} to be associated with the given type. This can later be * retrieved using {@link #getContentItem(Uri)}. * * @param type * MIME type for the given {@link ContentItem} * @param itemClass * the class of the associated {@link ContentItem} */ public void registerContentItemType(String type, Class<? extends ContentItem> itemClass) { if (BuildConfig.DEBUG) { Log.d(TAG, "registered " + itemClass + " for type " + type); } mContentItemTypeMap.put(type, itemClass); } /** * Retrieves the class of the {@link ContentItem} previously associated using * {@link #registerContentItemType(String, Class)} * * @param type * the {@link ContentItem}'s MIME type * @return the class of the {@link ContentItem} or null if there's no mapping */ public Class<? extends ContentItem> getContentItem(String type) { return mContentItemTypeMap.get(type); } /** * Gets the class of the {@link ContentItem} that was previously associated with the MIME type * of the URI using {@link #registerContentItemType(String, Class)}. * * @param uri * a URI which has MIME types registered with this provider * @return the class of the {@link ContentItem} or null if there's no mapping */ public Class<? extends ContentItem> getContentItem(Uri uri) { final String type = getType(uri); if (type == null) { return null; } return mContentItemTypeMap.get(type); } /** * * @return the UriMatcher that's used to route the URIs of this handler */ protected static UriMatcher getMatcher() { return MATCHER; } @Override public Uri insert(Uri uri, ContentValues values) { final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase(); final int match = MATCHER.match(uri); if (UriMatcher.NO_MATCH == match) { throw new IllegalArgumentException(ERR_NO_HANDLER + ": " + uri); } if (!mDBHelperMapper.canInsert(match)) { throw new IllegalArgumentException("insert not supported"); } final Uri newUri = mDBHelperMapper.insert(match, this, db, uri, values); if (newUri != null) { getContext().getContentResolver().notifyChange(uri, null); } return newUri; } @Override public int bulkInsert(Uri uri, ContentValues[] values) { final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase(); final int match = MATCHER.match(uri); if (UriMatcher.NO_MATCH == match) { throw new IllegalArgumentException(ERR_NO_HANDLER + ": " + uri); } if (!mDBHelperMapper.canInsert(match)) { throw new IllegalArgumentException("insert not supported"); } int numSuccessfulAdds = 0; db.beginTransaction(); try { for (final ContentValues cv : values) { final Uri newUri = mDBHelperMapper.insert(match, this, db, uri, cv); if (newUri != null) { numSuccessfulAdds++; } } db.setTransactionSuccessful(); if (numSuccessfulAdds > 0) { getContext().getContentResolver().notifyChange(uri, null); } } finally { db.endTransaction(); } return numSuccessfulAdds; } @Override public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase(); ContentProviderResult[] res; db.beginTransaction(); try { res = super.applyBatch(operations); db.setTransactionSuccessful(); } finally { db.endTransaction(); } return res; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { final SQLiteDatabase db = mDatabaseHelper.getReadableDatabase(); final int match = MATCHER.match(uri); if (UriMatcher.NO_MATCH == match) { throw new IllegalArgumentException(ERR_NO_HANDLER + ": " + uri); } if (!mDBHelperMapper.canQuery(match)) { throw new IllegalArgumentException("query not supported"); } final Cursor c = mDBHelperMapper.query(match, this, db, uri, projection, selection, selectionArgs, sortOrder); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase(); final int match = MATCHER.match(uri); if (UriMatcher.NO_MATCH == match) { throw new IllegalArgumentException(ERR_NO_HANDLER + ": " + uri); } if (!mDBHelperMapper.canUpdate(match)) { throw new IllegalArgumentException("update not supported"); } final int changed = mDBHelperMapper.update(match, this, db, uri, values, selection, selectionArgs); if (changed != 0) { getContext().getContentResolver().notifyChange(uri, null); } return changed; } // ///////////////////// private methods /** * Generates a name for the database from the content provider. * * @return a valid name, based on the classname. */ protected String generateDBName() { return SQLGenUtils.toValidName(getClass()); } /** * Instantiate a new {@link DatabaseOpenHelper} for this provider. * * @return */ protected DatabaseOpenHelper createDatabaseOpenHelper() { return new DatabaseOpenHelper(getContext(), mDBName, mDBVersion); } // //////////////////// internal classes /** * A basic database helper that will go through all the provider's registered database helpers * and call creation/upgrades. This also turns on foreign keys if support is available. * * @author <a href="mailto:spomeroy@mit.edu">Steve Pomeroy</a> * */ protected class DatabaseOpenHelper extends SQLiteOpenHelper { public DatabaseOpenHelper(Context context, String name, int version) { super(context, name, null, version); } @Override public void onCreate(SQLiteDatabase db) { for (final DBHelper dbHelper : mDBHelpers) { dbHelper.createTables(db); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { for (final DBHelper dbHelper : mDBHelpers) { dbHelper.upgradeTables(db, oldVersion, newVersion); } } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); if (AndroidVersions.SQLITE_SUPPORTS_FOREIGN_KEYS) { db.execSQL("PRAGMA foreign_keys = ON;"); } } } }
package edu.ucsb.cs56.drawings.sswong.advanced; import java.awt.Graphics2D; import java.awt.Shape; // general class for shapes import java.awt.Color; // class for Colors import java.awt.Stroke; import java.awt.BasicStroke; import edu.ucsb.cs56.drawings.utilities.ShapeTransforms; import edu.ucsb.cs56.drawings.utilities.GeneralPathWrapper; /** * A class with static methods for drawing various pictures * * @author Simon Wong * @version for UCSB CS56, W16 */ public class AllMyDrawings { /** Draw a picture with a few trees */ public static void drawPicture1(Graphics2D g2) { // labeling the drawing g2.drawString("Some trees by Simon Wong",20,20); // draw three trees Tree t1 = new Tree(20,50,100,25,50); Tree t2 = new Tree(250,75,75,20,30); Tree t3 = new Tree(200,220,50,40,25); // rotated 45 degrees around center Shape t4 = ShapeTransforms.rotatedCopyOf(t2, Math.PI/4.0); g2.setColor(Color.GREEN); g2.draw(t1); g2.setColor(Color.BLUE); g2.draw(t2); g2.setColor(Color.RED); g2.draw(t3); g2.setColor(Color.BLACK); g2.draw(t4); // Make a black tree that's half the size of t4, // and moved over 150 pixels in x direction Shape t5 = ShapeTransforms.scaledCopyOfLL(t4,0.5,0.5); t5 = ShapeTransforms.translatedCopyOf(t5,150,0); g2.setColor(Color.BLACK); g2.draw(t5); // Here's a tree that's 4x as big (2x the original) // and moved over 150 more pixels to right. t5 = ShapeTransforms.scaledCopyOfLL(t5,4,4); t5 = ShapeTransforms.translatedCopyOf(t5,150,0); // We'll draw this with a thicker stroke Stroke thick = new BasicStroke (4.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL); // #002FA7 is "International Klein Blue" according to Wikipedia // In HTML we use #, but in Java (and C/C++) its 0x Stroke orig=g2.getStroke(); g2.setStroke(thick); g2.setColor(new Color(0x002FA7)); g2.draw(t5); } /** Draw a picture with some trees with fruits */ public static void drawPicture2(Graphics2D g2) { // labeling the drawing g2.drawString("Some trees with fruits by Simon Wong",20,20); // draw three trees with fruits TreeWithFruits twf1 = new TreeWithFruits(20,50,100,25,50); TreeWithFruits twf2 = new TreeWithFruits(250,75,75,20,30); TreeWithFruits twf3 = new TreeWithFruits(200,220,50,40,25); g2.setColor(Color.GREEN); g2.draw(twf1); g2.setColor(Color.BLACK); g2.draw(twf2); g2.setColor(Color.PINK); g2.draw(twf3); // Make an orange tree that's half the size of twf3, // and moved over 150 pixels in x direction Shape twf4 = ShapeTransforms.scaledCopyOfLL(twf3,0.5,0.5); twf4 = ShapeTransforms.translatedCopyOf(twf4,150,0); g2.setColor(Color.ORANGE); g2.draw(twf4); // Here's a tree that's 4x as big (2x the original) // and moved over 150 more pixels to right. twf4 = ShapeTransforms.scaledCopyOfLL(twf4,4,4); twf4 = ShapeTransforms.translatedCopyOf(twf4,150,0); // We'll draw this with a thicker stroke Stroke thick = new BasicStroke (4.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL); // #002FA7 is "International Klein Blue" according to Wikipedia // In HTML we use #, but in Java (and C/C++) its 0x Stroke orig=g2.getStroke(); g2.setStroke(thick); g2.setColor(new Color(0x002FA7)); g2.draw(twf4); // draw a 180 rotated twf4 Shape twf5 = ShapeTransforms.rotatedCopyOf(twf4, Math.PI/2.0); g2.draw(twf5); } /** Draw a picture with some trees, some with fruit */ public static void drawPicture3(Graphics2D g2) { // label the drawing g2.drawString("Some green trees by Simon Wong", 20,20); // Draw some trees. Tree t1 = new Tree(50,50,50,12.5,25); Tree t2 = new TreeWithFruits(250,50,50,12.5,25); Tree t3 = new Tree(450,50,50,12.5,25); Tree t4 = new TreeWithFruits(50,200,50,12.5,25); Tree t5 = new Tree(250,200,50,12.5,25); Tree t6 = new TreeWithFruits(450,200,50,12.5,25); g2.setColor(Color.GREEN); g2.draw(t1); g2.draw(t2); g2.draw(t3); g2.draw(t4); g2.draw(t5); g2.draw(t6); } }
package es.uniovi.imovil.fcrtrainer; import java.io.IOException; import java.util.ArrayList; import java.util.Locale; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; public class ProtocolExerciseFragment extends BaseExerciseFragment { //Problemas al cargar de la BD las preguntas. //Esqueleto mnimo, pero sin probar la funcionalidad por no cargarse bien la BD. private static final String DB_NAME = "protocolFCR.sqlite"; private static final int DB_VERSION = 1; private ArrayList<Test> testList=null; private View mRootView; private TextView question; private int i=0; Test test; RadioGroup rg; RadioButton rb1; RadioButton rb2; RadioButton rb3; Button bCheck; Button bSolution; int rbSelected; private boolean changeColor=false; public static ProtocolExerciseFragment newInstance() { ProtocolExerciseFragment fragment = new ProtocolExerciseFragment(); return fragment; } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView=inflater.inflate(R.layout.fragment_protocol, container, false); DataBaseHelper db = new DataBaseHelper(this.getActivity(), DB_NAME, null, DB_VERSION); rb1 = (RadioButton) mRootView.findViewById(R.id.rb1); rb2 = (RadioButton) mRootView.findViewById(R.id.rb2); rb3 = (RadioButton) mRootView.findViewById(R.id.rb3); rg = (RadioGroup) mRootView.findViewById(R.id.rg1); question = (TextView) mRootView.findViewById(R.id.exerciseQuestion); bCheck = (Button) mRootView.findViewById(R.id.checkbutton); bSolution = (Button) mRootView.findViewById(R.id.seesolution); try { db.createDataBase(); db.openDataBase(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Cargar la bd con las preguntas y respuestas en un array-list. testList=db.loadData(); //Lanzar el entrenamiento. //seeDB(); training(); //Raccionar a eventos del RadioGroup rb1.setOnClickListener(new RadioButton.OnClickListener(){ @Override public void onClick(View v) { rbSelected=1; } }); rb2.setOnClickListener(new RadioButton.OnClickListener(){ @Override public void onClick(View v) { rbSelected=2; } }); rb3.setOnClickListener(new RadioButton.OnClickListener(){ @Override public void onClick(View v) { rbSelected=3; } }); //Eventos del botn de comprobar la solucin. bCheck.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { changeColor=false; switch(rbSelected) { case 1: if (rb1.getText().equals(test.getResponse())) showAnimationAnswer(true); else showAnimationAnswer(false); rb1.setChecked(false); reset(); training(); return; case 2: if (rb2.getText().equals(test.getResponse())) showAnimationAnswer(true); else showAnimationAnswer(false); if (!changeColor) rb2.setTextColor(0xff000000); rb2.setChecked(false); reset(); training(); return; case 3: if (rb3.getText().equals(test.getResponse())) showAnimationAnswer(true); else showAnimationAnswer(false); rb3.setChecked(false); reset(); training(); return; default: reset(); training(); return; } } private void reset() { // TODO Auto-generated method stub rbSelected=0; i++; if (!changeColor) { rb1.setTextColor(0xff000000); rb2.setTextColor(0xff000000); rb3.setTextColor(0xff000000); } } }); //Botn de mostrar solucin. bSolution.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showSolution(); } }); return mRootView; } private void training() { if (i<testList.size()) //Completar todas las preguntas de la Base de Datos. { test = testList.get(i); //Mostrar pregunta y opciones. question.setText(test.getQuestion()); rb1.setText(test.getOption1()); rb2.setText(test.getOption2()); rb3.setText(test.getOption3()); //Final de entrenamiento. } else //Reiniciar { i=0; training(); } } public void showSolution() { // Mostrar la solucin buena en rojo. changeColor=true; if (rb1.getText().equals(test.getResponse())) { rb1.setTextColor(0xff00ff00); } if (rb2.getText().equals(test.getResponse())) { rb2.setTextColor(0xff00ff00); } if (rb3.getText().equals(test.getResponse())) { rb3.setTextColor(0xff00ff00); } } }
package fi.cie.chiru.servicefusionar.serviceApi; import util.Log; import android.annotation.SuppressLint; import fi.cie.chiru.servicefusionar.Finnkino.Auditorium; import fi.cie.chiru.servicefusionar.Finnkino.FinnkinoXmlParser; import fi.cie.chiru.servicefusionar.Finnkino.LogInScreen; import fi.cie.chiru.servicefusionar.Finnkino.MoviePayment; import fi.cie.chiru.servicefusionar.Finnkino.MovieTicket; import fi.cie.chiru.servicefusionar.Finnkino.SeatNumber; import fi.cie.chiru.servicefusionar.Finnkino.FinnkinoXmlParser.Movie; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class MovieManager { private static final String LOG_TAG = "MovieManager"; private ServiceManager serviceManager; private boolean movieInfoDownloaded; private int maxMovies = 10; private String selectedMovie; private InfoBubble infobubble; private LogInScreen loginscreen; private Auditorium auditorium; private MoviePayment moviePayment; private List<MovieTicket> tickets = null; public IdCard ic; public CreditCard cc; public MovieManager(ServiceManager serviceManager) { movieInfoDownloaded = false; String URL = "http: new XmlDownloader() { protected void onPostExecute(String xmlData) { if (xmlData != null) { movieInfoDownloaded = true; FinnkinoXmlParser parser = new FinnkinoXmlParser(); fillMovieInfo(parser.parse(xmlData)); } else Log.e(LOG_TAG, "Couldn't download xml data!"); } }.execute(URL); loginscreen = new LogInScreen(serviceManager); auditorium = new Auditorium(serviceManager); moviePayment = new MoviePayment(serviceManager); this.serviceManager = serviceManager; } public void showMovieInfo(String requesterName) { if(!movieInfoDownloaded) return; infobubble.visible(); } public void login(String movieTitle) { serviceManager.getSetup().camera.setUIMode(true); selectedMovie = movieTitle; //if more auditoriums than Plaza1 is added later the auditorium number can be parsed from movieTitle serviceManager.setVisibilityToAllApplications(false); infobubble.visible(); if(serviceManager.getMusicManager().getInfoBubble() != null && serviceManager.getMusicManager().getInfoBubble().isVisible()) serviceManager.getMusicManager().getInfoBubble().visible(); //auditorium.createAuditoriumScreen("Sali1"); loginscreen.createLogInScreen(movieTitle); moviePayment.setMovieName(movieTitle); if(ic==null) ic = new IdCard(serviceManager); } public void seatSelection() { auditorium.createAuditoriumScreen("Sali1"); } public void payment(List<SeatNumber> seats) { moviePayment.paySelectedSeats(seats); if(cc==null) cc = new CreditCard(serviceManager); } public void createTickets(List<SeatNumber> seats) { if(tickets ==null) tickets = new ArrayList<MovieTicket>(); for(int i=0; i<seats.size(); i++) { MovieTicket ticket = new MovieTicket(serviceManager, selectedMovie, seats.get(i)); tickets.add(ticket); } } public void removeTickets() { if(tickets == null) return; for(int i=0; i<tickets.size(); i++) { tickets.get(i).removeTicket(); } tickets = null; } public InfoBubble getInfoBubble() { return infobubble; } @SuppressLint("SimpleDateFormat") private void fillMovieInfo(List<Movie> movielist) { if (!movieInfoDownloaded || movielist == null) return; int longestTitle = getLongestMovieTitlteLen(movielist); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); String currentTime = sdf.format(new Date()); List<String> movieInfo = new ArrayList<String>(); for(int i = 0; i < movielist.size(); i++) { String movieInfoString = new String(); String time = new String(); String movieTitle = new String(); String auditorium = new String(); time = movielist.get(i).time.split("[T]")[1]; time = time.substring(0,5); if (currentTime.compareTo(time) > 0) continue; movieTitle = movielist.get(i).title; auditorium = movielist.get(i).auditorium; movieInfoString = time + " " + movieTitle + fillWhiteSpace(longestTitle - movieTitle.length()) + " " + auditorium; Log.d(LOG_TAG, movieInfoString); if (movieInfo.size() < maxMovies) movieInfo.add(movieInfoString); else break; } infobubble = new InfoBubble(serviceManager); if(infobubble.setInfoBubbleApplication("MovieInfobubble")) infobubble.populateItems(movieInfo, "MovieManager"); } private String fillWhiteSpace(int number) { String whitespace = new String(); for(int j=0; j<number; j++) whitespace += " "; return whitespace; } private int getLongestMovieTitlteLen(List<Movie> movie) { if (movie == null) { return 0; } int len = 0; for(int k=0; k<movie.size(); k++) { if(movie.get(k).title.length() > len) len = movie.get(k).title.length(); } return len; } }
package org.apache.jmeter.functions; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.Serializable; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.apache.jmeter.engine.util.CompoundVariable; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.samplers.Sampler; import org.apache.jmeter.threads.JMeterVariables; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; /** * StringFromFile Function to read a String from a text file. * * Parameters: * - file name * - variable name (optional - defaults to StringFromFile_) * * Returns: * - the next line from the file - or **ERR** if an error occurs * - value is also saved in the variable for later re-use. * * Ensure that different variable names are used for each call to the function * * * Notes: * - JMeter instantiates a copy of each function for every reference in a * Sampler or elsewhere; each instance will open its own copy of the the file * - the file name is resolved at file (re-)open time * - the output variable name is resolved every time the function is invoked * * @author sebb AT apache DOT org * * @version $Revision$ Updated on: $Date$ */ public class StringFromFile extends AbstractFunction implements Serializable { private static Logger log = LoggingManager.getLoggerForClass(); private static final List desc = new LinkedList(); private static final String KEY = "_StringFromFile";//$NON-NLS-1$ // Function name (only 1 _) private static final String ERR_IND = "**ERR**";//$NON-NLS-1$ static { desc.add(JMeterUtils.getResString("string_from_file_file_name"));//$NON-NLS-1$ desc.add(JMeterUtils.getResString("function_name_param"));//$NON-NLS-1$ } private String myValue = ERR_IND; private String myName = "StringFromFile_";//$NON-NLS-1$ - Name to store the value in private Object[] values; private BufferedReader myBread; // Buffered reader private FileReader fis; // keep this round to close it private boolean firstTime = false; // should we try to open the file? private boolean reopenFile = true; // Set from parameter list one day ... private String fileName; // needed for error messages public StringFromFile() { if (log.isDebugEnabled()) { log.debug("++++++++ Construct "+this); } } protected void finalize() throws Throwable{ if (log.isDebugEnabled()) { log.debug(" } } public Object clone() { StringFromFile newReader = new StringFromFile(); if (log.isDebugEnabled()) { // Skip expensive paramter creation .. log.debug(this +"::StringFromFile.clone()", new Throwable("debug"));//$NON-NLS-1$ } return newReader; } /* * Warning: the file will generally be left open at the end of a test run. * This is because functions don't have any way to find out when a test has * ended ... */ private void closeFile(){ String tn = Thread.currentThread().getName(); log.info(tn + " closing file " + fileName);//$NON-NLS-1$ try { myBread.close(); fis.close(); } catch (IOException e) { log.error("closeFile() error: " + e.toString());//$NON-NLS-1$ } } private void openFile() { String tn = Thread.currentThread().getName(); fileName = ((CompoundVariable) values[0]).execute(); log.info(tn + " opening file " + fileName);//$NON-NLS-1$ try { fis = new FileReader(fileName); myBread = new BufferedReader(fis); } catch (Exception e) { log.error("openFile() error: " + e.toString());//$NON-NLS-1$ myBread=null; } } /* (non-Javadoc) * @see org.apache.jmeter.functions.Function#execute(SampleResult, Sampler) */ public synchronized String execute( SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { JMeterVariables vars = getVariables(); if (values.length >= 2) { myName = ((CompoundVariable) values[1]).execute(); } myValue = ERR_IND; /* * To avoid re-opening the file repeatedly after an error, * only try to open it in the first execute() call * (It may be re=opened at EOF, but that will cause at most * one failure.) */ if (firstTime) { openFile(); firstTime=false; } if (null != myBread) { // Did we open the file? try { String line = myBread.readLine(); if (line == null && reopenFile) { // EOF, re-open file log.info("Reached EOF on " + fileName);//$NON-NLS-1$ closeFile(); openFile(); if (myBread != null) { line = myBread.readLine(); } else { line = ERR_IND; } } myValue = line; } catch (Exception e) { String tn = Thread.currentThread().getName(); log.error(tn + " error reading file " + e.toString());//$NON-NLS-1$ } } vars.put(myName, myValue); log.debug(this +"::StringFromFile.execute() name:" + myName + " value:" + myValue);//$NON-NLS-1$ return myValue; } /* (non-Javadoc) * Parameters: * - file name * - variable name (optional) * * @see org.apache.jmeter.functions.Function#setParameters(Collection) */ public void setParameters(Collection parameters) throws InvalidVariableException { log.debug(this +"::StringFromFile.setParameters()");//$NON-NLS-1$ values = parameters.toArray(); if ((values.length > 2) || (values.length < 1)) { throw new InvalidVariableException("Wrong number of parameters");//$NON-NLS-1$ } StringBuffer sb = new StringBuffer(40); sb.append("setParameters(");//$NON-NLS-1$ for (int i = 0; i< values.length;i++){ if (i > 0) sb.append(","); sb.append(((CompoundVariable) values[i]).getRawParameters()); } sb.append(")");//$NON-NLS-1$ log.info(sb.toString()); //N.B. seteParameters is called before the test proper is started, // and thus variables are not interpreted at this point // So defer the file open until later to allow variable file names to be used. firstTime = true; } /* (non-Javadoc) * @see org.apache.jmeter.functions.Function#getReferenceKey() */ public String getReferenceKey() { return KEY; } /* (non-Javadoc) * @see org.apache.jmeter.functions.Function#getArgumentDesc() */ public List getArgumentDesc() { return desc; } }
package gov.nih.nci.calab.ui.core; import gov.nih.nci.calab.dto.characterization.CharacterizationBean; import gov.nih.nci.calab.dto.characterization.CharacterizationSummaryBean; import gov.nih.nci.calab.dto.characterization.DatumBean; import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean; import gov.nih.nci.calab.dto.characterization.invitro.CytotoxicityBean; import gov.nih.nci.calab.dto.characterization.physical.MorphologyBean; import gov.nih.nci.calab.dto.characterization.physical.ShapeBean; import gov.nih.nci.calab.dto.characterization.physical.SolubilityBean; import gov.nih.nci.calab.dto.characterization.physical.SurfaceBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.common.ProtocolFileBean; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.dto.particle.ParticleBean; import gov.nih.nci.calab.exception.CaNanoLabSecurityException; import gov.nih.nci.calab.exception.FileException; import gov.nih.nci.calab.exception.ParticleCharacterizationException; import gov.nih.nci.calab.service.common.FileService; import gov.nih.nci.calab.service.particle.NanoparticleCharacterizationService; import gov.nih.nci.calab.service.particle.NanoparticleService; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.PropertyReader; import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.ui.particle.InitParticleSetup; import gov.nih.nci.calab.ui.protocol.InitProtocolSetup; import gov.nih.nci.calab.ui.security.InitSecuritySetup; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; /** * This action serves as the base action for all characterization related action * classes. It includes common operations such as download, updateManufacturers. * * @author pansu */ /* * CVS $Id: BaseCharacterizationAction.java,v 1.73 2007/08/02 21:41:47 zengje * Exp $ */ public abstract class BaseCharacterizationAction extends AbstractDispatchAction { protected CharacterizationBean prepareCreate(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { HttpSession session = request.getSession(); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // validate that characterization file/derived data can't be empty for (DerivedBioAssayDataBean derivedDataFileBean : charBean .getDerivedBioAssayDataList()) { if (derivedDataFileBean.getType().length() == 0 && derivedDataFileBean.getCategories().length == 0 && derivedDataFileBean.getDisplayName().length() == 0 && derivedDataFileBean.getDatumList().size() == 0) { throw new ParticleCharacterizationException( "has an empty section for characterization file/derived data. Please remove it prior to saving."); } } for (DerivedBioAssayDataBean derivedDataFileBean : charBean .getDerivedBioAssayDataList()) { Map<String, Integer> uniqueDatumMap = new HashMap<String, Integer>(); for (DatumBean datumBean : derivedDataFileBean.getDatumList()) { // validate that neither name nor value can be empty if (datumBean.getName().length() == 0 || datumBean.getValue().length() == 0) { throw new ParticleCharacterizationException( "Derived data name and value can't be empty."); } if (datumBean.getStatisticsType().equalsIgnoreCase("boolean")) { if (!datumBean.getValue().equalsIgnoreCase("true") && !datumBean.getValue().equalsIgnoreCase("false") && !datumBean.getValue().equalsIgnoreCase("yes") && !datumBean.getValue().equalsIgnoreCase("no")) { throw new ParticleCharacterizationException( "The datum value for boolean type should be 'True'/'False' or 'Yes'/'No'."); } } else { if (!StringUtils.isDouble(datumBean.getValue()) && !StringUtils.isInteger(datumBean.getValue())) { throw new ParticleCharacterizationException( "The datum value should be a number."); } } // validate derived data has unique name, statistics type and // category String uniqueStr = datumBean.getName() + ":" + datumBean.getStatisticsType() + ":" + datumBean.getCategory(); if (uniqueDatumMap.get(uniqueStr) != null) { throw new ParticleCharacterizationException( "no two derived data can have the same name, statistics type and category."); } else { uniqueDatumMap.put(uniqueStr, 1); } } } // set createdBy and createdDate for the characterization UserBean user = (UserBean) session.getAttribute("user"); Date date = new Date(); charBean.setCreatedBy(user.getLoginName()); charBean.setCreatedDate(date); ParticleBean particle = (ParticleBean) theForm.get("particle"); charBean.setParticle(particle); return charBean; } protected ActionForward postCreate(HttpServletRequest request, DynaValidatorForm theForm, ActionMapping mapping) throws Exception { ParticleBean particle = (ParticleBean) theForm.get("particle"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // save new lookup up types in the database definition tables. NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); service.addNewCharacterizationDataDropdowns(charBean, charBean .getName()); request.getSession().setAttribute("newCharacterizationCreated", "true"); request.getSession().setAttribute("newCharacterizationSourceCreated", "true"); request.getSession().setAttribute("newInstrumentCreated", "true"); request.getSession().setAttribute("newCharacterizationFileTypeCreated", "true"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); request.setAttribute("theParticle", particle); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.addCharacterization", charBean.getName()); msgs.add("message", msg); saveMessages(request, msgs); return mapping.findForward("success"); } protected CharacterizationBean[] prepareCopy(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); ParticleBean particle = (ParticleBean) theForm.get("particle"); String[] otherParticles = (String[]) theForm.get("otherParticles"); Boolean copyData = (Boolean) theForm.get("copyData"); CharacterizationBean[] charBeans = new CharacterizationBean[otherParticles.length]; NanoparticleService service = new NanoparticleService(); int i = 0; for (String particleName : otherParticles) { CharacterizationBean newCharBean = charBean.copy(copyData .booleanValue()); // overwrite particle and particle type; newCharBean.getParticle().setSampleName(particleName); ParticleBean otherParticle = service.getParticleBy(particleName); newCharBean.getParticle().setSampleType( otherParticle.getSampleType()); // reset view title String timeStamp = StringUtils.convertDateToString(new Date(), "MMddyyHHmmssSSS"); String autoTitle = CaNanoLabConstants.AUTO_COPY_CHARACTERIZATION_VIEW_TITLE_PREFIX + timeStamp; newCharBean.setViewTitle(autoTitle); List<DerivedBioAssayDataBean> dataList = newCharBean .getDerivedBioAssayDataList(); // replace particleName in path and uri with new particleName for (DerivedBioAssayDataBean derivedBioAssayData : dataList) { String origUri = derivedBioAssayData.getUri(); if (origUri != null) derivedBioAssayData.setUri(origUri.replace(particle .getSampleName(), particleName)); } charBeans[i] = newCharBean; i++; } return charBeans; } /** * clear session data from the input form * * @param session * @param theForm * @param mapping * @throws Exception */ protected void clearMap(HttpSession session, DynaValidatorForm theForm) throws Exception { // reset achar and otherParticles theForm.set("otherParticles", new String[0]); theForm.set("copyData", false); theForm.set("achar", new CharacterizationBean()); theForm.set("morphology", new MorphologyBean()); theForm.set("shape", new ShapeBean()); theForm.set("surface", new SurfaceBean()); theForm.set("solubility", new SolubilityBean()); theForm.set("cytotoxicity", new CytotoxicityBean()); cleanSessionAttributes(session); } /** * Prepopulate data for the input form * * @param request * @param theForm * @throws Exception */ protected void initSetup(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { HttpSession session = request.getSession(); clearMap(session, theForm); UserBean user = (UserBean) request.getSession().getAttribute("user"); InitParticleSetup.getInstance() .setAllCharacterizationDropdowns(session); // set up particle String particleId = request.getParameter("particleId"); if (particleId != null) { NanoparticleService particleService = new NanoparticleService(); ParticleBean particle = particleService.getParticleInfo(particleId, user); theForm.set("particle", particle); request.setAttribute("theParticle", particle); // set up other particles from the same source SortedSet<String> allOtherParticleNames = particleService .getOtherParticles(particle.getSampleSource(), particle .getSampleName(), user); session .setAttribute("allOtherParticleNames", allOtherParticleNames); InitParticleSetup.getInstance().setSideParticleMenu(request, particleId); } else { throw new ParticleCharacterizationException( "Particle ID is required."); } InitSessionSetup.getInstance().setApplicationOwner(session); InitParticleSetup.getInstance().setAllInstruments(session); InitParticleSetup.getInstance().setAllDerivedDataFileTypes(session); InitParticleSetup.getInstance().setAllPhysicalDropdowns(session); InitParticleSetup.getInstance().setAllInvitroDropdowns(session); // set characterization String submitType = (String) request.getParameter("submitType"); String characterizationId = request.getParameter("characterizationId"); if (characterizationId != null) { NanoparticleCharacterizationService charService = new NanoparticleCharacterizationService(); CharacterizationBean charBean = charService .getCharacterizationBy(characterizationId); if (charBean == null) { throw new ParticleCharacterizationException( "This characterization no longer exists in the database. Please log in again to refresh."); } theForm.set("achar", charBean); } CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); if (achar != null && submitType != null) { achar.setName(submitType); InitParticleSetup.getInstance() .setAllCharacterizationMeasureUnitsTypes(session, submitType); InitParticleSetup.getInstance().setDerivedDatumNames(session, achar.getName()); InitProtocolSetup.getInstance().setProtocolFilesByCharName(session, achar.getName()); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); // set up characterization files visibility, and whether file is an // image for (DerivedBioAssayDataBean fileBean : achar .getDerivedBioAssayDataList()) { boolean accessStatus = userService.checkReadPermission(user, fileBean.getId()); if (accessStatus) { List<String> accessibleGroups = userService .getAccessibleGroups(fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups .toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); fileBean.setHidden(false); } else { fileBean.setHidden(true); } boolean imageStatus = false; if (fileBean.getName() != null) { imageStatus = StringUtils.isImgFileExt(fileBean.getName()); fileBean.setImage(imageStatus); } } // set up protocol file visibility ProtocolFileBean protocolFileBean = achar.getProtocolFileBean(); if (protocolFileBean != null) { boolean status = false; if (protocolFileBean.getId() != null) { status = userService.checkReadPermission(user, protocolFileBean.getId()); } if (status) { protocolFileBean.setHidden(false); } else { protocolFileBean.setHidden(true); } } } } /** * Clean the session attribture * * @param sessioin * @throws Exception */ protected void cleanSessionAttributes(HttpSession session) throws Exception { for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) { String element = (String) e.nextElement(); if (element.startsWith(CaNanoLabConstants.CHARACTERIZATION_FILE)) { session.removeAttribute(element); } } } /** * Set up the input form for adding new characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); return mapping.getInputForward(); } public ActionForward input(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; // update editable dropdowns CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); ShapeBean shape = (ShapeBean) theForm.get("shape"); MorphologyBean morphology = (MorphologyBean) theForm.get("morphology"); CytotoxicityBean cyto = (CytotoxicityBean) theForm.get("cytotoxicity"); SolubilityBean solubility = (SolubilityBean) theForm.get("solubility"); HttpSession session = request.getSession(); updateAllCharEditables(session, achar); updateShapeEditable(session, shape); updateMorphologyEditable(session, morphology); updateCytotoxicityEditable(session, cyto); updateSolubilityEditable(session, solubility); // updateSurfaceEditable(session, surface); return mapping.findForward("setup"); } /** * Set up the form for updating existing characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // set characterizations with additional information if (charBean instanceof ShapeBean) { theForm.set("shape", charBean); } else if (charBean instanceof MorphologyBean) { theForm.set("morphology", charBean); } else if (charBean instanceof SolubilityBean) { theForm.set("solubility", charBean); } else if (charBean instanceof SurfaceBean) { theForm.set("surface", charBean); } else if (charBean instanceof SolubilityBean) { theForm.set("solubility", charBean); } else if (charBean instanceof CytotoxicityBean) { theForm.set("cytotoxicity", charBean); } return mapping.findForward("setup"); } public ActionForward detailView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); String particleId = request.getParameter("particleId"); String characterizationId = request.getParameter("characterizationId"); String submitType = request.getParameter("submitType"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); String printLinkURL = "/caNanoLab/" + charBean.getActionName() + ".do?page=0&dispatch=printDetailView&particleId=" + particleId + "&characterizationId=" + characterizationId + "&submitType=" + submitType; request.setAttribute("printLinkURL", printLinkURL); return mapping.findForward("detailView"); } public ActionForward exportDetail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); CharacterizationBean charBean = (CharacterizationBean) theForm.get("achar"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); //response.setContentType("application/vnd.ms-execel"); response.setContentType("application/octet-stream"); response.setHeader("cache-control", "Private"); response.setHeader("Content-disposition", "attachment;filename=" + charBean.getActionName() + "_" + charBean.getViewTitle() + ".xls"); UserBean user = (UserBean) request.getSession().getAttribute("user"); java.io.OutputStream out = response.getOutputStream(); service.exportDetailService(theForm, out, user); return null; } public ActionForward exportSummary(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); CharacterizationBean charBean = (CharacterizationBean) theForm.get("achar"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); //response.setContentType("application/vnd.ms-execel"); response.setContentType("application/octet-stream"); response.setHeader("cache-control", "Private"); response.setHeader("Content-disposition", "attachment;filename=" + charBean.getActionName() + ".xls"); UserBean user = (UserBean) request.getSession().getAttribute("user"); java.io.OutputStream out = response.getOutputStream(); String submitType = request.getParameter("submitType"); ParticleBean particle = (ParticleBean) theForm.get("particle"); List<CharacterizationSummaryBean> summaryBeans = service .getParticleCharacterizationSummaryByName(submitType, particle.getSampleId()); SortedSet<String> datumLabels = service.setDataLabelsAndFileVisibility(user, summaryBeans); service.exportSummaryService(datumLabels, summaryBeans, submitType, theForm, out, user); return null; } public ActionForward printDetailView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); return mapping.findForward("detailPrintView"); } private void setSummaryView(ActionForm form, HttpServletRequest request) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); String submitType = request.getParameter("submitType"); ParticleBean particle = (ParticleBean) theForm.get("particle"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); List<CharacterizationSummaryBean> charSummaryBeans = service .getParticleCharacterizationSummaryByName(submitType, particle .getSampleId()); if (charSummaryBeans == null) { throw new Exception( "There are no such characterizations in the database."); } // set data labels and file visibility, and whether file is an image UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); UserBean user = (UserBean) request.getSession().getAttribute("user"); List<CharacterizationBean> charBeans = new ArrayList<CharacterizationBean>(); SortedSet<String> datumLabels = new TreeSet<String>(); for (CharacterizationSummaryBean summaryBean : charSummaryBeans) { if (!charBeans.contains(summaryBean.getCharBean())) { charBeans.add(summaryBean.getCharBean()); } Map<String, String> datumMap = summaryBean.getDatumMap(); if (datumMap != null && !datumMap.isEmpty()) { datumLabels.addAll(datumMap.keySet()); } DerivedBioAssayDataBean fileBean = summaryBean.getCharFile(); if (fileBean != null) { boolean accessStatus = userService.checkReadPermission(user, fileBean.getId()); if (accessStatus) { List<String> accessibleGroups = userService .getAccessibleGroups(fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups .toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); fileBean.setHidden(false); } else { fileBean.setHidden(true); } boolean imageStatus = false; if (fileBean.getName() != null) { imageStatus = StringUtils.isImgFileExt(fileBean.getName()); } fileBean.setImage(imageStatus); } } request.setAttribute("summaryViewBeans", charSummaryBeans); request.setAttribute("summaryViewCharBeans", charBeans); request.setAttribute("datumLabels", datumLabels); } public ActionForward summaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setSummaryView(form, request); DynaValidatorForm theForm = (DynaValidatorForm) form; ParticleBean particle = (ParticleBean) theForm.get("particle"); String submitType = request.getParameter("submitType"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); String printLinkURL = "/caNanoLab/" + charBean.getActionName() + ".do?page=0&dispatch=printSummaryView&particleId=" + particle.getSampleId() + "&submitType=" + submitType; String printAllLinkURL = "/caNanoLab/" + charBean.getActionName() + ".do?page=0&dispatch=printFullSummaryView&particleId=" + particle.getSampleId() + "&submitType=" + submitType; request.setAttribute("printLinkURL", printLinkURL); request.setAttribute("printAllLinkURL", printAllLinkURL); return mapping.findForward("summaryView"); } public ActionForward printSummaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setSummaryView(form, request); return mapping.findForward("summaryPrintView"); } public ActionForward printFullSummaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setSummaryView(form, request); return mapping.findForward("summaryPrintAllView"); } /** * Load file action for characterization file loading. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward loadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; ParticleBean particle = (ParticleBean) theForm.get("particle"); request.setAttribute("loadFileForward", mapping.findForward("setup") .getPath()); CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); int fileNum = Integer.parseInt(request.getParameter("fileNumber")); DerivedBioAssayDataBean derivedBioAssayDataBean = achar .getDerivedBioAssayDataList().get(fileNum); derivedBioAssayDataBean.setParticleName(particle.getSampleName()); derivedBioAssayDataBean.setCharacterizationName(achar.getName()); request.setAttribute("file", derivedBioAssayDataBean); return mapping.findForward("loadFile"); } /** * Download action to handle characterization file download and viewing * * @param * @return */ public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileId = request.getParameter("fileId"); UserBean user = (UserBean) request.getSession().getAttribute("user"); FileService service = new FileService(); LabFileBean fileBean = service.getFile(fileId, user); String fileRoot = PropertyReader.getProperty( CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); File dFile = new File(fileRoot + File.separator + fileBean.getUri()); if (dFile.exists()) { response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=" + fileBean.getName()); response.setHeader("cache-control", "Private"); java.io.InputStream in = new FileInputStream(dFile); java.io.OutputStream out = response.getOutputStream(); byte[] bytes = new byte[32768]; int numRead = 0; while ((numRead = in.read(bytes)) > 0) { out.write(bytes, 0, numRead); } out.close(); } else { throw new FileException( "File to download doesn't exist on the server"); } return null; } public ActionForward addFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); List<DerivedBioAssayDataBean> origTables = achar .getDerivedBioAssayDataList(); int origNum = (origTables == null) ? 0 : origTables.size(); List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>(); for (int i = 0; i < origNum; i++) { tables.add(origTables.get(i)); } // add a new one tables.add(new DerivedBioAssayDataBean()); achar.setDerivedBioAssayDataList(tables); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward removeFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); List<DerivedBioAssayDataBean> origTables = achar .getDerivedBioAssayDataList(); int origNum = (origTables == null) ? 0 : origTables.size(); List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>(); for (int i = 0; i < origNum; i++) { tables.add(origTables.get(i)); } // remove the one at the index if (origNum > 0) { tables.remove(fileInd); } achar.setDerivedBioAssayDataList(tables); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward addData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar .getDerivedBioAssayDataList().get(fileInd); List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList(); int origNum = (origDataList == null) ? 0 : origDataList.size(); List<DatumBean> dataList = new ArrayList<DatumBean>(); for (int i = 0; i < origNum; i++) { DatumBean dataPoint = (DatumBean) origDataList.get(i); dataList.add(dataPoint); } dataList.add(new DatumBean()); derivedBioAssayDataBean.setDatumList(dataList); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward removeData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); String dataIndexStr = (String) request.getParameter("childCompInd"); int dataInd = Integer.parseInt(dataIndexStr); DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar .getDerivedBioAssayDataList().get(fileInd); List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList(); int origNum = (origDataList == null) ? 0 : origDataList.size(); List<DatumBean> dataList = new ArrayList<DatumBean>(); for (int i = 0; i < origNum; i++) { DatumBean dataPoint = (DatumBean) origDataList.get(i); dataList.add(dataPoint); } if (origNum > 0) dataList.remove(dataInd); derivedBioAssayDataBean.setDatumList(dataList); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); // return mapping.getInputForward(); this gives an // IndexOutOfBoundException in the jsp page } /** * Pepopulate data for the form * * @param request * @param theForm * @throws Exception */ public ActionForward deleteConfirmed(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); ParticleBean particle = (ParticleBean) theForm.get("particle"); String charId = request.getParameter("characterizationId"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); service.deleteCharacterizations(new String[] { charId }); // signal the session that characterization has been changed request.getSession().setAttribute("newCharacterizationCreated", "true"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.delete.characterization"); msgs.add("message", msg); saveMessages(request, msgs); return mapping.findForward("success"); } // add edited option to all editable dropdowns private void updateAllCharEditables(HttpSession session, CharacterizationBean achar) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, achar.getCharacterizationSource(), "characterizationSources"); InitSessionSetup.getInstance().updateEditableDropdown(session, achar.getInstrumentConfigBean().getInstrumentBean().getType(), "allInstrumentTypes"); InitSessionSetup.getInstance().updateEditableDropdown( session, achar.getInstrumentConfigBean().getInstrumentBean() .getManufacturer(), "allManufacturers"); for (DerivedBioAssayDataBean derivedBioAssayDataBean : achar .getDerivedBioAssayDataList()) { InitSessionSetup.getInstance().updateEditableDropdown(session, derivedBioAssayDataBean.getType(), "allDerivedDataFileTypes"); if (derivedBioAssayDataBean != null) { for (String category : derivedBioAssayDataBean.getCategories()) { InitSessionSetup.getInstance().updateEditableDropdown( session, category, "derivedDataCategories"); } for (DatumBean datum : derivedBioAssayDataBean.getDatumList()) { InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getName(), "datumNames"); InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getStatisticsType(), "charMeasureTypes"); InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getUnit(), "charMeasureUnits"); } } } } // add edited option to all editable dropdowns private void updateShapeEditable(HttpSession session, ShapeBean shape) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, shape.getType(), "allShapeTypes"); } private void updateMorphologyEditable(HttpSession session, MorphologyBean morphology) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, morphology.getType(), "allMorphologyTypes"); } private void updateCytotoxicityEditable(HttpSession session, CytotoxicityBean cyto) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, cyto.getCellLine(), "allCellLines"); } private void updateSolubilityEditable(HttpSession session, SolubilityBean solubility) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, solubility.getSolvent(), "allSolventTypes"); } // private void updateSurfaceEditable(HttpSession session, // SurfaceBean surface) throws Exception { public boolean loginRequired() { return true; } public boolean canUserExecute(UserBean user) throws CaNanoLabSecurityException { return InitSecuritySetup.getInstance().userHasCreatePrivilege(user, CaNanoLabConstants.CSM_PG_PARTICLE); } }
package io.core9.server.undertow; import io.core9.plugin.server.HostManager; import io.core9.plugin.server.VirtualHost; import io.core9.plugin.server.handler.Binding; import io.core9.plugin.server.handler.Middleware; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.util.SameThreadExecutor; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MiddlewareHandler implements HttpHandler { private static final List<Binding> BINDINGS = new ArrayList<Binding>(); private static final Map<VirtualHost,List<Binding>> VHOST_BINDINGS = new HashMap<>(); private Map<String,VirtualHost> hosts; public void setHostManager(HostManager hostManager) { this.hosts = hostManager.getVirtualHostsByHostname(); } public void addMiddleware(String pattern, Middleware middleware) { BINDINGS.add(createBinding(pattern, middleware)); } public void addMiddleware(VirtualHost vhost, String pattern, Middleware middleware) { if(!VHOST_BINDINGS.containsKey(vhost)) { VHOST_BINDINGS.put(vhost, new ArrayList<Binding>()); } VHOST_BINDINGS.get(vhost).add(createBinding(pattern, middleware)); } public void deregister(String pattern) { for(Binding binding : BINDINGS) { if(binding.getPath().equals(pattern)) { BINDINGS.remove(binding); } } } public void deregister(VirtualHost vhost, String pattern) { List<Binding> bindings = VHOST_BINDINGS.get(vhost); if(bindings != null) { for(Binding binding : bindings) { if(binding.getPath().equals(pattern)) { bindings.remove(binding); } } } } @Override public void handleRequest(HttpServerExchange exchange) throws Exception { if(exchange.isInIoThread()) { exchange.dispatch(this); return; } VirtualHost vhost = hosts.get(exchange.getHostAndPort()); RequestImpl req = new RequestImpl(vhost, exchange); for(Binding binding : VHOST_BINDINGS.get(req.getVirtualHost())) { binding.handle(req); } for(Binding binding : BINDINGS) { binding.handle(req); } req.getResponse().end(); } public static Binding createBinding(String pattern, Middleware middleware) { Matcher m = Pattern.compile(":([A-Za-z][A-Za-z0-9_-]*)").matcher(pattern); StringBuffer sb = new StringBuffer(); Set<String> groups = new HashSet<>(); while (m.find()) { String group = m.group().substring(1); if (groups.contains(group)) { throw new IllegalArgumentException("Cannot use identifier " + group + " more than once in pattern string"); } m.appendReplacement(sb, "(?<$1>[^\\/]+)"); groups.add(group); } m.appendTail(sb); String regex = sb.toString(); return new Binding(pattern, Pattern.compile(regex), groups, middleware); } }
package it.unimi.dsi.sux4j.mph; import it.unimi.dsi.Util; import it.unimi.dsi.fastutil.io.BinIO; import it.unimi.dsi.fastutil.longs.AbstractLongList; import it.unimi.dsi.io.FastBufferedReader; import it.unimi.dsi.io.FileLinesCollection; import it.unimi.dsi.io.LineIterator; import it.unimi.dsi.lang.MutableString; import it.unimi.dsi.logging.ProgressLogger; import it.unimi.dsi.bits.BitVector; import it.unimi.dsi.bits.Fast; import it.unimi.dsi.bits.HuTuckerTransformationStrategy; import it.unimi.dsi.bits.LongArrayBitVector; import it.unimi.dsi.bits.TransformationStrategies; import it.unimi.dsi.bits.TransformationStrategy; import java.io.IOException; import java.io.InputStreamReader; import java.io.Serializable; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import org.apache.log4j.Logger; import com.martiansoftware.jsap.FlaggedOption; import com.martiansoftware.jsap.JSAP; import com.martiansoftware.jsap.JSAPException; import com.martiansoftware.jsap.JSAPResult; import com.martiansoftware.jsap.Parameter; import com.martiansoftware.jsap.SimpleJSAP; import com.martiansoftware.jsap.Switch; import com.martiansoftware.jsap.UnflaggedOption; import com.martiansoftware.jsap.stringparsers.ForNameStringParser; /** A minimal perfect monotone hash implementation based on fixed-size bucketing. * * * @author Sebastiano Vigna * @since 0.1 */ public class LcpMinimalPerfectMonotoneHash<T> extends AbstractHash<T> implements Serializable { public static final long serialVersionUID = 1L; private static final Logger LOGGER = Util.getLogger( LcpMinimalPerfectMonotoneHash.class ); @SuppressWarnings("unused") private static final boolean DEBUG = false; /** The number of elements. */ final protected int n; /** The size of a bucket. */ final protected int bucketSize; /** {@link Fast#ceilLog2(int)} of {@link #bucketSize}. */ final protected int log2BucketSize; /** The mask for {@link #log2BucketSize} bits. */ final protected int bucketSizeMask; /** A function mapping each element to the offset inside its bucket (lowest {@link #log2BucketSize} bits) and * to the length of the longest common prefix of its bucket (remaining bits). */ final protected MWHCFunction<BitVector> offsetLcpLength; /** A function mapping each longest common prefix to its bucket. */ final protected MWHCFunction<BitVector> lcp2Bucket; /** The transformation strategy. */ final protected TransformationStrategy<? super T> transform; @SuppressWarnings("unchecked") public long getLong( final Object o ) { final BitVector bitVector = transform.toBitVector( (T)o ); final long value = offsetLcpLength.getLong( bitVector ); final long prefix = value >>> log2BucketSize; if ( prefix > bitVector.length() ) return -1; return lcp2Bucket.getLong( bitVector.subVector( 0, prefix ) ) * bucketSize + ( value & bucketSizeMask ); } @SuppressWarnings("unchecked") public long getByBitVector( final BitVector bitVector ) { final long value = offsetLcpLength.getLong( bitVector ); if ( value > bitVector.length() ) return -1; return lcp2Bucket.getLong( bitVector.subVector( 0, value >>> log2BucketSize ) ) * bucketSize + ( value & bucketSizeMask ); } @SuppressWarnings("unused") // TODO: move it to the first for loop when javac has been fixed public LcpMinimalPerfectMonotoneHash( final Iterable<? extends T> iterable, final TransformationStrategy<? super T> transform ) { final ProgressLogger pl = new ProgressLogger( LOGGER ); // First of all we compute the size, either by size(), if possible, or simply by iterating. if ( iterable instanceof Collection ) n = ((Collection<? extends T>)iterable).size(); else { int c = 0; // Do not add a suppression annotation--it breaks javac for( T o: iterable ) c++; n = c; } this.transform = transform; Iterator<? extends T> iterator = iterable.iterator(); if ( ! iterator.hasNext() ) { bucketSize = bucketSizeMask = log2BucketSize = 0; lcp2Bucket = null; offsetLcpLength = null; return; } int t = (int)Math.ceil( 1 + HypergraphSorter.GAMMA * Math.log( 2 ) + Math.log( n ) - Math.log( 1 + Math.log( n ) ) ); log2BucketSize = Fast.ceilLog2( t ); bucketSize = 1 << log2BucketSize; bucketSizeMask = bucketSize - 1; final int numBuckets = ( n + bucketSize - 1 ) / bucketSize; LongArrayBitVector prev = LongArrayBitVector.getInstance(); BitVector curr = null; int prefix, currLcp = 0; final BitVector[] lcp = new BitVector[ numBuckets ]; int maxLcp = 0; long maxLength = 0; pl.expectedUpdates = n; pl.start( "Scanning collection..." ); for( int b = 0; b < numBuckets; b++ ) { prev.replace( transform.toBitVector( iterator.next() ) ); pl.lightUpdate(); maxLength = Math.max( maxLength, prev.length() ); currLcp = (int)prev.length(); final int currBucketSize = Math.min( bucketSize, n - b * bucketSize ); for( int i = 0; i < currBucketSize - 1; i++ ) { curr = transform.toBitVector( iterator.next() ); pl.lightUpdate(); final int cmp = prev.compareTo( curr ); if ( cmp > 0 ) throw new IllegalArgumentException( "The list is not sorted at position " + ( b * bucketSize + i ) ); if ( cmp == 0 ) throw new IllegalArgumentException( "The list contains duplicates at position " + ( b * bucketSize + i ) ); currLcp = (int)Math.min( curr.longestCommonPrefixLength( prev ), currLcp ); prev.replace( curr ); maxLength = Math.max( maxLength, prev.length() ); } lcp[ b ] = prev.subVector( 0, currLcp ).copy(); maxLcp = Math.max( maxLcp, currLcp ); } pl.done(); // Build function assigning each lcp to its bucket. lcp2Bucket = new MWHCFunction<BitVector>( Arrays.asList( lcp ), TransformationStrategies.identity(), null, Fast.ceilLog2( numBuckets ) ); if ( DEBUG ) { int p = 0; for( BitVector v: lcp ) System.err.println( v + " " + v.length() ); for( BitVector v: Arrays.asList( lcp ) ) { final long value = lcp2Bucket.getLong( v ); if ( p++ != value ) { System.err.println( "p: " + (p-1) + " value: " + value + " key:" + v ); throw new AssertionError(); } } } // Build function assigning the lcp length and the bucketing data to each element. offsetLcpLength = new MWHCFunction<BitVector>( TransformationStrategies.wrap( iterable, transform ), TransformationStrategies.identity(), new AbstractLongList() { public long getLong( int index ) { return lcp[ index / bucketSize ].length() << log2BucketSize | index % bucketSize; } public int size() { return n; } }, log2BucketSize + Fast.ceilLog2( maxLcp ) ); if ( DEBUG ) { int p = 0; for( T key: iterable ) { final long value = offsetLcpLength.getLong( key ); if ( p++ != lcp2Bucket.getLong( transform.toBitVector( key ).subVector( 0, value >>> log2BucketSize ) ) * bucketSize + ( value & bucketSizeMask ) ) { System.err.println( "p: " + ( p - 1 ) + " Key: " + key + " bucket size: " + bucketSize + " lcp " + transform.toBitVector( key ).subVector( 0, value >>> log2BucketSize ) + " lcp length: " + ( value >>> log2BucketSize ) + " bucket " + lcp2Bucket.getLong( transform.toBitVector( key ).subVector( 0, value >>> log2BucketSize ) ) + " offset: " + ( value & bucketSizeMask ) ); throw new AssertionError(); } } } final int lnLnN = (int)Math.ceil( Math.log( 1 + Math.log( n ) ) ); LOGGER.debug( "Bucket size: " + bucketSize ); LOGGER.debug( "Forecast bit cost per element: " + ( HypergraphSorter.GAMMA + Fast.log2( bucketSize ) + Fast.log2( Math.E ) + Fast.ceilLog2( maxLength - lnLnN ) ) ); LOGGER.debug( "Empirical bit cost per element: " + ( HypergraphSorter.GAMMA + log2BucketSize + Fast.ceilLog2( maxLcp ) + Fast.ceilLog2( numBuckets ) / (double)bucketSize + (double)transform.numBits() / n ) ); LOGGER.debug( "Actual bit cost per element: " + (double)numBits() / n ); } /** Returns the number of terms hashed. * * @return the number of terms hashed. */ public int size() { return n; } /** Returns the number of bits used by this structure. * * @return the number of bits used by this structure. */ public long numBits() { return offsetLcpLength.numBits() + lcp2Bucket.numBits() + transform.numBits(); } public boolean hasTerms() { return false; } public static void main( final String[] arg ) throws NoSuchMethodException, IOException, JSAPException { final SimpleJSAP jsap = new SimpleJSAP( MinimalPerfectHash.class.getName(), "Builds a minimal perfect monotone hash function reading a newline-separated list of strings.", new Parameter[] { new FlaggedOption( "bufferSize", JSAP.INTSIZE_PARSER, "64Ki", JSAP.NOT_REQUIRED, 'b', "buffer-size", "The size of the I/O buffer used to read strings." ), new FlaggedOption( "encoding", ForNameStringParser.getParser( Charset.class ), "UTF-8", JSAP.NOT_REQUIRED, 'e', "encoding", "The string file encoding." ), new Switch( "huTucker", 'h', "hu-tucker", "Use Hu-Tucker coding to increase entropy (only available for offline construction)." ), new Switch( "iso", 'i', "iso", "Use ISO-8859-1 bit encoding." ), new Switch( "zipped", 'z', "zipped", "The string list is compressed in gzip format." ), new FlaggedOption( "stringFile", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'o', "offline", "Read strings from this file (without loading them into core memory) instead of standard input." ), new UnflaggedOption( "function", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename for the serialised minimal perfect hash function." ) }); JSAPResult jsapResult = jsap.parse( arg ); if ( jsap.messagePrinted() ) return; final int bufferSize = jsapResult.getInt( "bufferSize" ); final String functionName = jsapResult.getString( "function" ); final String stringFile = jsapResult.getString( "stringFile" ); final Charset encoding = (Charset)jsapResult.getObject( "encoding" ); final boolean zipped = jsapResult.getBoolean( "zipped" ); final boolean iso = jsapResult.getBoolean( "iso" ); final boolean huTucker = jsapResult.getBoolean( "huTucker" ); if ( huTucker && stringFile == null ) throw new IllegalArgumentException( "Hu-Tucker coding requires offline construction" ); final LcpMinimalPerfectMonotoneHash<CharSequence> lcpMinimalPerfectMonotoneHash; final TransformationStrategy<CharSequence> transformationStrategy = iso? TransformationStrategies.prefixFreeIso() : TransformationStrategies.prefixFreeUtf16(); if ( stringFile == null ) { ArrayList<MutableString> stringList = new ArrayList<MutableString>(); final ProgressLogger pl = new ProgressLogger( LOGGER ); pl.itemsName = "strings"; final LineIterator stringIterator = new LineIterator( new FastBufferedReader( new InputStreamReader( System.in, encoding ), bufferSize ), pl ); pl.start( "Reading strings..." ); while( stringIterator.hasNext() ) stringList.add( stringIterator.next().copy() ); pl.done(); LOGGER.info( "Building minimal perfect monotone hash function..." ); lcpMinimalPerfectMonotoneHash = new LcpMinimalPerfectMonotoneHash<CharSequence>( stringList, transformationStrategy ); } else { LOGGER.info( "Building minimal perfect monotone hash function..." ); FileLinesCollection flc = new FileLinesCollection( stringFile, encoding.name(), zipped ); lcpMinimalPerfectMonotoneHash = new LcpMinimalPerfectMonotoneHash<CharSequence>( flc, huTucker ? new HuTuckerTransformationStrategy( flc, true ) : transformationStrategy ); } LOGGER.info( "Writing to file..." ); BinIO.storeObject( lcpMinimalPerfectMonotoneHash, functionName ); LOGGER.info( "Completed." ); } }
package org.xins.client; import java.io.IOException; import java.util.Map; /** * Interface for API function calling functionality. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ public interface FunctionCaller { CallResult call(String functionName, Map parameters) throws IllegalArgumentException, IOException, InvalidCallResultException; }
package org.xins.common.text; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Pattern; import org.xins.common.MandatoryArgumentChecker; /** * Simple pattern parser. * * <h3>Format</h3> * * <p>A simple pattern is a text string that may contain letters, digits, * underscores, hyphens, dots and the wildcard characters <code>'*'</code> * (asterisk) and <code>'?'</code> (question mark). * * <p>The location of an asterisk indicates any number of characters is * allowed. The location of a question mark indicates exactly one character is * expected. * * <p>To allow matching of simple patterns, a simple pattern is first compiled * into a Perl 5 regular expression. Every asterisk is converted to * <code>".*"</code>, while every question mark is converted to * <code>"."</code>. * * <h3>Examples</h3> * * <p>Examples of conversions from a simple pattern to a Perl 4 regular * expression: * * <table> * <tr><th>Simple pattern</th><th>Perl 5 regex equivalent</th></tr> * <tr><td></td> <td></td> </tr> * <tr><td>*</td> <td>.*</td> </tr> * <tr><td>?</td> <td>.</td> </tr> * <tr><td>_Get*</td> <td>_Get.*</td> </tr> * <tr><td>_Get*i?n</td> <td>_Get.*i.n</td> </tr> * <tr><td>*on</td> <td>.*on</td> </tr> * <tr><td>_Get*,_Dis*</td> <td>_Get.*|_Dis.*</td> </tr> * </table> * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * @author Peter Troon (<a href="mailto:peter.troon@nl.wanadoo.com">peter.troon@nl.wanadoo.com</a>) * * @since XINS 1.0.0 */ public class SimplePatternParser extends Object { // Class fields // Class functions // Constructors /** * Creates a new <code>SimplePatternParser</code> object. */ public SimplePatternParser() { // empty } // Fields // Methods public Perl5Pattern parseSimplePattern(String simplePattern) throws IllegalArgumentException, ParseException { MandatoryArgumentChecker.check("simplePattern", simplePattern); simplePattern = convertToPerl5RegularExpression(simplePattern); Perl5Pattern perl5pattern = null; Perl5Compiler perl5compiler = new Perl5Compiler(); boolean parseError = false; try { Pattern pattern = perl5compiler.compile(simplePattern); if (pattern instanceof Perl5Pattern) { perl5pattern = (Perl5Pattern) pattern; } else { parseError = true; } } catch (MalformedPatternException mpe) { parseError = true; } if (parseError) { throw new ParseException("An error occurred while parsing the pattern '" + simplePattern + "'."); } return perl5pattern; } /** * Converts the pattern to a Perl 5 Regular Expression. This means that * every asterisk is replaced by a dot and an asterisk, every question mark * is replaced by a dot, an accent circunflex is prepended to the pattern * and a dollar sign is appended to the pattern. * * @param pattern * the pattern to be converted, may not be <code>null</code>. * * @return * the converted pattern, not <code>null</code>. * * @throws NullPointerException * if <code>pattern == null</code>. * * @throws ParseException * if provided simplePattern is invalid or could not be parsed. */ private String convertToPerl5RegularExpression(String pattern) throws NullPointerException, ParseException { // Short-circuit if the pattern is empty int length = pattern.length(); if (length < 1) { return ""; } // Convert to char array and construct buffer char[] contents = pattern.toCharArray(); FastStringBuffer buffer = new FastStringBuffer(length * 2); // Loop through all characters char prevChar = (char) 0; for (int i= 0; i < length; i++) { char currChar = contents[i]; if (currChar >= 'a' && currChar <= 'z') { buffer.append(currChar); } else if (currChar >= 'A' && currChar <= 'Z') { buffer.append(currChar); } else if (currChar >= '0' && currChar <= '9') { buffer.append(currChar); } else if (currChar == '_') { buffer.append(currChar); } else if (currChar == '-') { buffer.append(currChar); } else if (currChar == '.') { buffer.append("\\."); } else if ((currChar == '*' || currChar == '?') && (prevChar == '*' || prevChar == '?')) { final String DETAIL = "The pattern \"" + pattern + "\" is invalid since it contains two subsequent wildcard characters ('" + prevChar + "' and '" + currChar + "') at positions " + (i - 1) + " and " + i + '.'; throw new ParseException(DETAIL); } else if (currChar == '*') { buffer.append(".*"); } else if (currChar == '?') { buffer.append('.'); } else if (currChar == ',') { buffer.append('|'); } else { throw new ParseException("The pattern \"" + pattern + "\" is invalid. The character '" + currChar + "' is not allowed."); } prevChar = currChar; } return buffer.toString(); } }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.jdbc.depot.operator; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Collection; import com.samskivert.jdbc.depot.ConstructedQuery; import com.samskivert.jdbc.depot.PersistentRecord; import com.samskivert.jdbc.depot.expression.ColumnExp; import com.samskivert.jdbc.depot.expression.SQLExpression; import com.samskivert.jdbc.depot.operator.SQLOperator.BinaryOperator; /** * A convenient container for implementations of conditional operators. Classes that value brevity * over disambiguation will import Conditionals.* and construct queries with Equals() and In(); * classes that feel otherwise will use Conditionals.Equals() and Conditionals.In(). */ public abstract class Conditionals { /** The SQL 'is null' operator. */ public static class IsNull implements SQLOperator { public IsNull (String pColumn) { this(new ColumnExp(null, pColumn)); } public IsNull (Class<? extends PersistentRecord> pClass, String pColumn) { this(new ColumnExp(pClass, pColumn)); } public IsNull (ColumnExp column) { _column = column; } // from SQLExpression public void appendExpression (ConstructedQuery query, StringBuilder builder) { _column.appendExpression(query, builder); builder.append(" is null"); } // from SQLExpression public int bindArguments (PreparedStatement pstmt, int argIdx) throws SQLException { return argIdx; } protected ColumnExp _column; } /** The SQL '=' operator. */ public static class Equals extends BinaryOperator { public Equals (String pColumn, Comparable value) { super(new ColumnExp(pColumn), value); } public Equals (SQLExpression column, Comparable value) { super(column, value); } public Equals (SQLExpression column, SQLExpression value) { super(column, value); } @Override protected String operator() { return "="; } } /** The SQL '<' operator. */ public static class LessThan extends BinaryOperator { public LessThan (String pColumn, Comparable value) { super(new ColumnExp(pColumn), value); } public LessThan (SQLExpression column, Comparable value) { super(column, value); } public LessThan (SQLExpression column, SQLExpression value) { super(column, value); } @Override protected String operator() { return "<"; } } /** The SQL '>' operator. */ public static class GreaterThan extends BinaryOperator { public GreaterThan (String pColumn, Comparable value) { super(new ColumnExp(pColumn), value); } public GreaterThan (SQLExpression column, Comparable value) { super(column, value); } public GreaterThan (SQLExpression column, SQLExpression value) { super(column, value); } @Override protected String operator() { return ">"; } } /** The SQL 'in (...)' operator. */ public static class In implements SQLOperator { public In (String pColumn, Comparable... values) { this(new ColumnExp(null, pColumn), values); } public In (String pColumn, Collection<? extends Comparable> values) { this(new ColumnExp(null, pColumn), values.toArray(new Comparable[values.size()])); } public In (Class<? extends PersistentRecord> pClass, String pColumn, Comparable... values) { this(new ColumnExp(pClass, pColumn), values); } public In (Class<? extends PersistentRecord> pClass, String pColumn, Collection<? extends Comparable> values) { this(new ColumnExp(pClass, pColumn), values.toArray(new Comparable[values.size()])); } public In (ColumnExp column, Comparable... values) { if (values.length == 0) { throw new IllegalArgumentException("In() condition needs at least one value."); } _column = column; _values = values; } // from SQLExpression public void appendExpression (ConstructedQuery query, StringBuilder builder) { _column.appendExpression(query, builder); builder.append(" in ("); for (int ii = 0; ii < _values.length; ii ++) { if (ii > 0) { builder.append(", "); } builder.append("?"); } builder.append(")"); } // from SQLExpression public int bindArguments (PreparedStatement pstmt, int argIdx) throws SQLException { for (int ii = 0; ii < _values.length; ii++) { pstmt.setObject(argIdx ++, _values[ii]); } return argIdx; } protected ColumnExp _column; protected Comparable[] _values; } /** The MySQL 'match (...) against (...)' operator. */ public static class Match implements SQLOperator { public enum Mode { DEFAULT, BOOLEAN, NATURAL_LANGUAGE }; public Match (String query, Mode mode, boolean queryExpansion, String... pColumns) { _query = query; _mode = mode; _queryExpansion = queryExpansion; _columns = new ColumnExp[pColumns.length]; for (int ii = 0; ii < pColumns.length; ii++) { _columns[ii] = new ColumnExp(null, pColumns[ii]); } } public Match (String query, Mode mode, boolean queryExpansion, ColumnExp... columns) { _query = query; _queryExpansion = queryExpansion; _mode = mode; _columns = columns; } // from SQLExpression public void appendExpression (ConstructedQuery query, StringBuilder builder) { builder.append("match("); int idx = 0; for (ColumnExp column : _columns) { if (idx++ > 0) { builder.append(", "); } column.appendExpression(query, builder); } builder.append(") against (?"); switch (_mode) { case BOOLEAN: builder.append(" in boolean mode"); break; case NATURAL_LANGUAGE: builder.append(" in natural language mode"); break; } if (_queryExpansion) { builder.append(" with query expansion"); } builder.append(")"); } // from SQLExpression public int bindArguments (PreparedStatement pstmt, int argIdx) throws SQLException { pstmt.setString(argIdx++, _query); return argIdx; } protected String _query; protected Mode _mode; protected boolean _queryExpansion; protected ColumnExp[] _columns; } /** The SQL ' like ' operator. */ public static class Like extends BinaryOperator { public Like (String pColumn, Comparable value) { super(new ColumnExp(pColumn), value); } public Like (SQLExpression column, Comparable value) { super(column, value); } public Like (SQLExpression column, SQLExpression value) { super(column, value); } @Override protected String operator() { return " like "; } } }
package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.PDUStringException; import org.jsmpp.SMPPConstant; import org.jsmpp.bean.AlertNotification; import org.jsmpp.bean.Command; import org.jsmpp.bean.DeliverSm; import org.jsmpp.extra.ProcessRequestException; import org.jsmpp.extra.SessionState; import org.jsmpp.session.ResponseHandler; import org.jsmpp.util.DefaultDecomposer; import org.jsmpp.util.PDUDecomposer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is bound_tx state implementation of {@link SMPPSessionState}. * Response to receiver related transaction. * * @author uudashr * @version 1.0 * @since 2.0 * */ class SMPPSessionBoundRX extends SMPPSessionBound implements SMPPSessionState { private static final Logger logger = LoggerFactory.getLogger(SMPPSessionBoundRX.class); private static final PDUDecomposer pduDecomposer = new DefaultDecomposer(); public SessionState getSessionState() { return SessionState.BOUND_RX; } public void processDeliverSm(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { processDeliverSm0(pduHeader, pdu, responseHandler); } public void processSubmitSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processSubmitMultiResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processQuerySmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processCancelSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processReplaceSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { responseHandler.sendNegativeResponse(pduHeader.getCommandId(), SMPPConstant.STAT_ESME_RINVBNDSTS, pduHeader .getSequenceNumber()); } public void processAlertNotification(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) { processAlertNotification0(pduHeader, pdu, responseHandler); } static void processAlertNotification0(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) { try { AlertNotification alertNotification = pduDecomposer.alertNotification(pdu); responseHandler.processAlertNotification(alertNotification); } catch (PDUStringException e) { logger.error("Failed decomposing alert_notification", e); // there is no response for alert notification } } static void processDeliverSm0(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException { try { DeliverSm deliverSm = pduDecomposer.deliverSm(pdu); responseHandler.processDeliverSm(deliverSm); responseHandler.sendDeliverSmResp(pduHeader.getSequenceNumber()); } catch (PDUStringException e) { logger.error("Failed decomposing deliver_sm", e); responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e .getErrorCode(), pduHeader.getSequenceNumber()); } catch (ProcessRequestException e) { logger.error("Failed processing deliver_sm", e); responseHandler.sendNegativeResponse(pduHeader.getCommandId(), e .getErrorCode(), pduHeader.getSequenceNumber()); } } }
package org.apache.jcs.engine.memory.lru; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jcs.engine.CacheConstants; import org.apache.jcs.engine.CacheElement; import org.apache.jcs.engine.behavior.ICacheElement; import org.apache.jcs.engine.behavior.ICompositeCacheAttributes; import org.apache.jcs.engine.behavior.IElementAttributes; import org.apache.jcs.engine.control.CompositeCache; import org.apache.jcs.engine.memory.MemoryCache; import org.apache.jcs.engine.memory.MemoryElementDescriptor; import org.apache.jcs.engine.memory.shrinking.ShrinkerThread; /** * A fast reference management system. The least recently used items move to * the end of the list and get spooled to disk if the cache hub is configured * to use a disk cache. Most of the cache bottelnecks are in IO. There are no * io bottlenecks here, it's all about processing power. Even though there are * only a few adjustments necessary to maintain the double linked list, we * might want to find a more efficient memory manager for large cache regions. * The LRUMemoryCache is most efficeint when the first element is selected. The * smaller the region, the better the chance that this will be the case. < .04 * ms per put, p3 866, 1/10 of that per get * *@author <a href="mailto:asmuts@yahoo.com">Aaron Smuts</a> *@author <a href="mailto:jtaylor@apache.org">James Taylor</a> *@created May 13, 2002 *@version $Id$ */ public class LRUMemoryCache implements MemoryCache, Serializable { private final static Log log = LogFactory.getLog( LRUMemoryCache.class ); String cacheName; /** * Map where items are stored by key */ protected Map map = new Hashtable(); // LRU double linked list head/tail nodes private MemoryElementDescriptor first; private MemoryElementDescriptor last; private int max; /** * Region Elemental Attributes, used as a default. */ public IElementAttributes attr; /** * Cache Attributes */ public ICompositeCacheAttributes cattr; /** * The cache region this store is associated with */ CompositeCache cache; // status private int status = CacheConstants.STATUS_ERROR; // make configurable private int chunkSize = 2; /** * The background memory shrinker */ private ShrinkerThread shrinker; /** * Constructor for the LRUMemoryCache object */ public LRUMemoryCache() { status = CacheConstants.STATUS_ERROR; } /** * For post reflection creation initialization * *@param hub */ public synchronized void initialize( CompositeCache hub ) { this.cacheName = hub.getCacheName(); this.cattr = hub.getCacheAttributes(); this.max = this.cattr.getMaxObjects(); this.cache = hub; status = CacheConstants.STATUS_ALIVE; log.info( "initialized LRUMemoryCache for " + cacheName ); if ( cattr.getUseMemoryShrinker() && shrinker == null ) { shrinker = new ShrinkerThread( this ); shrinker.setPriority( shrinker.MIN_PRIORITY ); shrinker.start(); } } /** * Puts an item to the cache. * *@param ce Description of the Parameter *@exception IOException */ public void update( ICacheElement ce ) throws IOException { // Asynchronisly create a MemoryElement ce.getElementAttributes().setLastAccessTimeNow(); addFirst( ce ); MemoryElementDescriptor old = ( MemoryElementDescriptor ) map.put( ce.getKey(), first ); // If the node was the same as an existing node, remove it. if ( first.equals( old ) ) { removeNode( old ); } int size = map.size(); // If the element limit is reached, we need to spool if ( size < this.cattr.getMaxObjects() ) { return; } else { log.debug( "In memory limit reached, spooling" ); // Write the last 'chunkSize' items to disk. int chunkSizeCorrected = Math.min( size, chunkSize ); if ( log.isDebugEnabled() ) { log.debug( "About to spool to disk cache, map size: " + size + ", max objects: " + this.cattr.getMaxObjects() + ", items to spool: " + chunkSizeCorrected ); } // The spool will put them in a disk event queue, so there is no // need to pre-queue the queuing. This would be a bit wasteful // and wouldn't save much time in this synchronous call. MemoryElementDescriptor node; for ( int i = 0; i < chunkSizeCorrected; i++ ) { synchronized ( this ) { cache.spoolToDisk( last.ce ); map.remove( last.ce.getKey() ); removeNode( last ); } } if ( log.isDebugEnabled() ) { log.debug( "After spool map size: " + size ); } } } /** * Get an item from the cache without affecting its last access time or * position. * *@param key Identifies item to find *@return Element mathinh key if found, or null *@exception IOException */ public ICacheElement getQuiet( Serializable key ) throws IOException { ICacheElement ce = null; MemoryElementDescriptor me = (MemoryElementDescriptor) map.get(key); if ( me != null ) { if ( log.isDebugEnabled() ) { log.debug(cacheName + ": LRUMemoryCache quiet hit for " + key); } ce = me.ce; } else if ( log.isDebugEnabled() ) { log.debug( cacheName + ": LRUMemoryCache quiet miss for " + key ); } return ce; } /** * Get an item from the cache * *@param key Identifies item to find *@return ICacheElement if found, else null *@exception IOException */ public ICacheElement get( Serializable key ) throws IOException { ICacheElement ce = null; if ( log.isDebugEnabled() ) { log.debug( "getting item for key: " + key ); } MemoryElementDescriptor me = (MemoryElementDescriptor) map.get(key); if ( me != null ) { if ( log.isDebugEnabled() ) { log.debug( cacheName + ": LRUMemoryCache hit for " + key ); } ce = me.ce; ce.getElementAttributes().setLastAccessTimeNow(); makeFirst( me ); } else { log.debug( cacheName + ": LRUMemoryCache miss for " + key ); } return ce; } /** * Removes an item from the cache. This method handles hierarchical * removal. If the key is a String and ends with the * CacheConstants.NAME_COMPONENT_DELIMITER, then all items with keys * starting with the argument String will be removed. * *@param key *@return *@exception IOException */ public boolean remove( Serializable key ) throws IOException { if ( log.isDebugEnabled() ) { log.debug( "removing item for key: " + key ); } boolean removed = false; // handle partial removal if ( key instanceof String && ( ( String ) key ) .endsWith( CacheConstants.NAME_COMPONENT_DELIMITER ) ) { // remove all keys of the same name hierarchy. synchronized ( map ) { for ( Iterator itr = map.entrySet().iterator(); itr.hasNext(); ) { Map.Entry entry = ( Map.Entry ) itr.next(); Object k = entry.getKey(); if ( k instanceof String && ( ( String ) k ).startsWith( key.toString() ) ) { itr.remove(); removeNode( ( MemoryElementDescriptor ) entry.getValue() ); removed = true; } } } } else { // remove single item. MemoryElementDescriptor ce = ( MemoryElementDescriptor ) map.remove( key ); if ( ce != null ) { removeNode( ce ); removed = true; } } return removed; } /** * Removes all cached items from the cache. * *@exception IOException */ public void removeAll() throws IOException { map = new HashMap(); } /** * Prepares for shutdown. * *@exception IOException */ public void dispose() throws IOException { } /** * Returns the current cache size. * *@return The size value */ public int getSize() { return this.map.size(); } /** * Returns the cache status. * *@return The status value */ public int getStatus() { return this.status; } /** * Returns the cache name. * *@return The cacheName value */ public String getCacheName() { return this.cattr.getCacheName(); } /** * Gets the iterator attribute of the LRUMemoryCache object * *@return The iterator value */ public Iterator getIterator() { return map.entrySet().iterator(); } /** * Get an Array of the keys for all elements in the memory cache * *@return An Object[] */ public Object[] getKeyArray() { // need a better locking strategy here. synchronized ( this ) { // may need to lock to map here? return map.keySet().toArray(); } } // /** // * Get an Array of the keys for elements in the specified range of // * the memory cache. If the end position is greater than the size of the // * Map, the method will return an array of the remaining elements after // * the start position. If the start element is greater than the size of // * Map, a error will be thrown. // * // *@return An Object[] // */ // int size = getSize(); // if ( start >= size ) { // int stop = Math.min( size, end ); // int count = 0; // // need a better locking strategy here. // synchronized ( this ) // Object[] result = new Object[stop-start]; // Iterator e = this.map.keySet().iterator(); // for (int i=0; e.hasNext(); i++) // if ( i >= start && i < stop ) { // result[count] = e.next(); // count++; // if ( i >= stop ) { // continue; // return result; /** * Puts an item to the cache. * *@param ce Description of the Parameter *@exception IOException */ public void waterfal( ICacheElement ce ) throws IOException { this.cache.spoolToDisk( ce ); } /** * Returns the CacheAttributes. * *@return The CacheAttributes value */ public ICompositeCacheAttributes getCacheAttributes() { return this.cattr; } /** * Sets the CacheAttributes. * *@param cattr The new CacheAttributes value */ public void setCacheAttributes( ICompositeCacheAttributes cattr ) { this.cattr = cattr; } /** * Gets the cache hub / region taht the MemoryCache is used by * *@return The cache value */ public CompositeCache getCompositeCache() { return this.cache; } /** * Removes the specified node from the link list. * *@param me Description of the Parameter */ private synchronized void removeNode( MemoryElementDescriptor me ) { if ( log.isDebugEnabled() ) { log.debug( "removing node " + me.ce.getKey() ); } if ( me.next == null ) { if ( me.prev == null ) { // Make sure it really is the only node before setting head and // tail to null. It is possible that we will be passed a node // which has already been removed from the list, in which case // we should ignore it if ( me == first && me == last ) { first = last = null; } } else { // last but not the first. last = me.prev; last.next = null; me.prev = null; } } else if ( me.prev == null ) { // first but not the last. first = me.next; first.prev = null; me.next = null; } else { // neither the first nor the last. me.prev.next = me.next; me.next.prev = me.prev; me.prev = me.next = null; } } /** * Adds a new node to the end of the link list. Currently not used. * *@param ce The feature to be added to the Last */ private void addLast( CacheElement ce ) { MemoryElementDescriptor me = new MemoryElementDescriptor( ce ); if ( first == null ) { // empty list. first = me; } else { last.next = me; me.prev = last; } last = me; return; } /** * Adds a new node to the start of the link list. * *@param ce The feature to be added to the First */ private synchronized void addFirst( ICacheElement ce ) { MemoryElementDescriptor me = new MemoryElementDescriptor( ce ); if ( last == null ) { // empty list. last = me; } else { first.prev = me; me.next = first; } first = me; return; } /** * Moves an existing node to the start of the link list. * *@param ce Description of the Parameter */ public void makeFirst( ICacheElement ce ) { makeFirst( new MemoryElementDescriptor( ce ) ); } /** * Moves an existing node to the start of the link list. * *@param me Description of the Parameter */ public synchronized void makeFirst( MemoryElementDescriptor me ) { if ( me.prev == null ) { // already the first node. return; } me.prev.next = me.next; if ( me.next == null ) { // last but not the first. last = me.prev; last.next = null; } else { // neither the last nor the first. me.next.prev = me.prev; } first.prev = me; me.next = first; me.prev = null; first = me; } /** * Dump the cache map for debugging. */ public void dumpMap() { log.debug( "dumpingMap" ); for ( Iterator itr = map.entrySet().iterator(); itr.hasNext(); ) { //for ( Iterator itr = memCache.getIterator(); itr.hasNext();) { Map.Entry e = ( Map.Entry ) itr.next(); MemoryElementDescriptor me = ( MemoryElementDescriptor ) e.getValue(); log.debug( "dumpMap> key=" + e.getKey() + ", val=" + me.ce.getVal() ); } } /** * Dump the cache entries from first to list for debugging. */ public void dumpCacheEntries() { log.debug( "dumpingCacheEntries" ); for ( MemoryElementDescriptor me = first; me != null; me = me.next ) { log.debug( "dumpCacheEntries> key=" + me.ce.getKey() + ", val=" + me.ce.getVal() ); } } }
package cgeo.geocaching.utils; import cgeo.geocaching.connector.gc.GCConstants; import junit.framework.TestCase; public class CryptUtilsTest extends TestCase { public static void testROT13() { assertEquals("", CryptUtils.rot13("")); assertEquals("", CryptUtils.rot13((String) null)); assertEquals("Pnpur uvag", CryptUtils.rot13("Cache hint")); assertEquals("123", CryptUtils.rot13("123")); } public static void testConvertToGcBase31() { assertEquals(1186660, GCConstants.gccodeToGCId("GC1PKK9")); assertEquals(4660, GCConstants.gccodeToGCId("GC1234")); assertEquals(61731, GCConstants.gccodeToGCId("GCF123")); } public static void testIssue1902() throws Exception { assertEquals("ƖƖlƖƖƖƖ", CryptUtils.rot13("ƖƖyƖƖƖƖ")); } }
package radlab.rain.workload.rubis; import java.util.Arrays; import java.util.Calendar; import java.util.concurrent.atomic.AtomicInteger; //import java.util.concurrent.Semaphore; import java.util.Date; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.HttpStatus; import radlab.rain.util.HttpTransport; import radlab.rain.workload.rubis.model.RubisCategory; import radlab.rain.workload.rubis.model.RubisComment; import radlab.rain.workload.rubis.model.RubisItem; import radlab.rain.workload.rubis.model.RubisRegion; import radlab.rain.workload.rubis.model.RubisUser; import radlab.rain.workload.rubis.util.DiscreteDistribution; /** * Collection of RUBiS utilities. * * @author Marco Guazzone (marco.guazzone@gmail.com) */ public final class RubisUtility { public static final int ANONYMOUS_USER_ID = -1; public static final int INVALID_CATEGORY_ID = -1; public static final int INVALID_REGION_ID = -1; public static final int INVALID_ITEM_ID = -1; public static final int INVALID_OPERATION_ID = -1; public static final int MILLISECS_PER_DAY = 1000*60*60*24; private static final char[] ALNUM_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; ///< The set of alphanumeric characters private static final String[] COMMENTS = {"This is a very bad comment. Stay away from this seller!!", "This is a comment below average. I don't recommend this user!!", "This is a neutral comment. It is neither a good or a bad seller!!", "This is a comment above average. You can trust this seller even if it is not the best deal!!", "This is an excellent comment. You can make really great deals with this seller!!"}; ///< Descriptions associated to comment ratings private static final int[] COMMENT_RATINGS = {-5, // Bad -3, // Below average 0, // Neutral 3, // Average 5 /* Excellent */ }; ///< Possible comment ratings private static final int MIN_USER_ID = 1; ///< Mininum value for user IDs private static final int MIN_ITEM_ID = 1; ///< Mininum value for item IDs private static final int MIN_REGION_ID = 1; ///< Mininum value for region IDs private static final int MIN_CATEGORY_ID = 1; ///< Mininum value for category IDs private static AtomicInteger _userId; private static AtomicInteger _itemId; // private static Semaphore _userLock = new Semaphore(1, true); // private static Semaphore _itemLock = new Semaphore(1, true); private Random _rng = null; private RubisConfiguration _conf = null; private DiscreteDistribution _catDistr = null; ///< Probability distribution for generating random categories private Pattern _pageRegex = Pattern.compile("^.*?[&?]page=(\\d+).*?(?:[&?]page=(\\d+).*?)?$"); private static int nextUserId() { return _userId.incrementAndGet(); } private static int lastUserId() { return _userId.get(); } private static int nextItemId() { return _itemId.incrementAndGet(); } private static int lastItemId() { return _itemId.get(); } // private static void lockUsers() throws InterruptedException // _userLock.acquire(); // private static void unlockUsers() // _userLock.release(); // private static void lockItems() throws InterruptedException // _itemLock.acquire(); // private static void unlockItems() // _itemLock.release(); private static synchronized void initUserId(int numPreloadUsers) { _userId = new AtomicInteger(MIN_USER_ID+numPreloadUsers-1); } private static synchronized void initItemId(int numPreloadItems) { _itemId = new AtomicInteger(MIN_ITEM_ID+numPreloadItems-1); } public RubisUtility() { } public RubisUtility(Random rng, RubisConfiguration conf) { this._rng = rng; this._conf = conf; initUserId(this._conf.getNumOfPreloadedUsers()); initItemId(this._conf.getTotalActiveItems()+this._conf.getNumOfOldItems()); int nc = this._conf.getCategories().size(); if (nc > 0) { double[] catProbs = new double[nc]; for (int i = 0; i < nc; ++i) { catProbs[i] = this._conf.getNumOfItemsPerCategory(i) / ((double) this._conf.getTotalActiveItems()); } this._catDistr = new DiscreteDistribution(catProbs); } } public void setRandomGenerator(Random rng) { this._rng = rng; } public Random getRandomGenerator() { return this._rng; } public void setConfiguration(RubisConfiguration conf) { this._conf = conf; initUserId(this._conf.getNumOfPreloadedUsers()); } public RubisConfiguration getConfiguration() { return this._conf; } public boolean isAnonymousUser(RubisUser user) { return this.isAnonymousUser(user.id); } public boolean isAnonymousUser(int userId) { return ANONYMOUS_USER_ID == userId; } public boolean isLoggedUser(RubisUser user) { return !this.isLoggedUser(user.id); } public boolean isLoggedUser(int userId) { return !this.isAnonymousUser(userId); } public boolean isValidUser(RubisUser user) { return null != user && MIN_USER_ID <= user.id; } public boolean isValidItem(RubisItem item) { return null != item && MIN_ITEM_ID <= item.id; } public boolean isValidCategory(RubisCategory category) { return null != category && MIN_CATEGORY_ID <= category.id; } public boolean isValidRegion(RubisRegion region) { return null != region && MIN_REGION_ID <= region.id; } public boolean checkHttpResponse(HttpTransport httpTransport, String response) { if (response.length() == 0 || HttpStatus.SC_OK != httpTransport.getStatusCode() || -1 != response.indexOf("ERROR")) { return false; } return true; } /** * Creates a new RUBiS user object. * * @return an instance of RubisUser. */ public RubisUser newUser() { return this.getUser(nextUserId()); } /** * Generate a random RUBiS user among the ones already preloaded. * * @return an instance of RubisUser. */ public RubisUser generateUser() { // Only generate a user among the ones that have been already preloaded in the DB int userId = this._rng.nextInt(this._conf.getNumOfPreloadedUsers()-MIN_USER_ID)+MIN_USER_ID; return this.getUser(userId); } /** * Get the RUBiS user associated to the given identifier. * * @param id The user identifier. * @return an instance of RubisUser. */ public RubisUser getUser(int id) { RubisUser user = new RubisUser(); user.id = id; user.firstname = "Great" + user.id; user.lastname = "User" + user.id; user.nickname = "user" + user.id; user.email = user.firstname + "." + user.lastname + "@rubis.com"; user.password = "password" + user.id; user.region = this.generateRegion().id; Calendar cal = Calendar.getInstance(); user.creationDate = cal.getTime(); return user; } /** * Creates a new RUBiS item. * * @return an instance of RubisItem. */ public RubisItem newItem(int loggedUserId) { return this.getItem(nextItemId(), loggedUserId); } /** * Generate a random RUBiS item among the ones already preloaded. * * @return an instance of RubisItem. */ public RubisItem generateItem(int loggedUserId) { // Only generate an item among the active and old ones int itemId = this._rng.nextInt(this._conf.getTotalActiveItems()+this._conf.getNumOfOldItems()-MIN_ITEM_ID)+MIN_ITEM_ID; return this.getItem(itemId, loggedUserId); } /** * Get the RUBiS item associated to the given identifier. * * @param id The item identifier. * @return an instance of RubisItem. */ public RubisItem getItem(int id, int loggedUserId) { RubisItem item = new RubisItem(); item.id = id; item.name = "RUBiS automatically generated item #" + item.id; item.description = this.generateText(1, this._conf.getMaxItemDescriptionLength()); item.initialPrice = this._rng.nextInt((int) Math.round(this._conf.getMaxItemInitialPrice()))+1; if (this._rng.nextInt(this._conf.getTotalActiveItems()) < (this._conf.getPercentageOfUniqueItems()*this._conf.getTotalActiveItems()/100.0)) { item.quantity = 1; } else { item.quantity = this._rng.nextInt(this._conf.getMaxItemQuantity())+1; } if (this._rng.nextInt(this._conf.getTotalActiveItems()) < (this._conf.getPercentageOfItemsReserve()*this._conf.getTotalActiveItems()/100.0)) { item.reservePrice = this._rng.nextInt((int) Math.round(this._conf.getMaxItemBaseReservePrice()))+item.initialPrice; } else { item.reservePrice = 0; } if (this._rng.nextInt(this._conf.getTotalActiveItems()) < (this._conf.getPercentageOfItemsBuyNow()*this._conf.getTotalActiveItems()/100.0)) { item.buyNow = this._rng.nextInt((int) Math.round(this._conf.getMaxItemBaseBuyNowPrice()))+item.initialPrice+item.reservePrice; } else { item.buyNow = 0; } item.nbOfBids = 0; item.maxBid = 0; Calendar cal = Calendar.getInstance(); item.startDate = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, this._rng.nextInt(this._conf.getMaxItemDuration())+1); item.endDate = cal.getTime(); item.seller = loggedUserId; item.category = this.generateCategory().id; return item; } public RubisCategory generateCategory() { // return this.getCategory(this._rng.nextInt(this._conf.getCategories().size()-MIN_CATEGORY_ID)+MIN_CATEGORY_ID); return this.getCategory(this._catDistr.nextInt(this._rng)+MIN_CATEGORY_ID); } public RubisCategory getCategory(int id) { RubisCategory category = new RubisCategory(); category.id = id; category.name = this._conf.getCategories().get(category.id-MIN_CATEGORY_ID); return category; } public RubisRegion generateRegion() { return this.getRegion(this._rng.nextInt(this._conf.getRegions().size()-MIN_REGION_ID)+MIN_REGION_ID); } public RubisRegion getRegion(int id) { RubisRegion region = new RubisRegion(); region.id = id; region.name = this._conf.getRegions().get(region.id+MIN_REGION_ID); return region; } public RubisComment generateComment(int fromUserId, int toUserId, int itemId) { return getComment(fromUserId, toUserId, itemId, COMMENT_RATINGS[this._rng.nextInt(COMMENT_RATINGS.length)]); } public RubisComment getComment(int fromUserId, int toUserId, int itemId, int rating) { RubisComment comment = new RubisComment(); comment.fromUserId = fromUserId; comment.toUserId = toUserId; comment.itemId = itemId; int rateIdx = Arrays.binarySearch(COMMENT_RATINGS, rating); comment.rating = COMMENT_RATINGS[rateIdx]; comment.comment = this.generateText(1, this._conf.getMaxCommentLength()-COMMENTS[rateIdx].length()-System.lineSeparator().length()) + System.lineSeparator() + COMMENTS[rateIdx]; Calendar cal = Calendar.getInstance(); comment.date = cal.getTime(); return comment; } /** * Parses the given HTML text to find an item identifier. * * @param html The HTML string where to look for the item identifier. * @return The found item identifier, or INVALID_ITEM_ID if * no item identifier is found. If more than one item is found, returns the * one picked at random. * * This method is based on the edu.rice.rubis.client.UserSession#extractItemIdFromHTML. */ public int findItemIdInHtml(String html) { if (html == null) { return INVALID_ITEM_ID; } // Count number of itemId int count = 0; int keyIdx = html.indexOf("itemId="); while (keyIdx != -1) { ++count; keyIdx = html.indexOf("itemId=", keyIdx + 7); // 7 equals to "itemId=" } if (count == 0) { return INVALID_ITEM_ID; } // Choose randomly an item count = this._rng.nextInt(count) + 1; keyIdx = -7; while (count > 0) { keyIdx = html.indexOf("itemId=", keyIdx + 7); // 7 equals to itemId= --count; } int lastIdx = minIndex(Integer.MAX_VALUE, html.indexOf('\"', keyIdx + 7)); lastIdx = minIndex(lastIdx, html.indexOf('?', keyIdx + 7)); lastIdx = minIndex(lastIdx, html.indexOf('&', keyIdx + 7)); lastIdx = minIndex(lastIdx, html.indexOf('>', keyIdx + 7)); String str = html.substring(keyIdx + 7, lastIdx); return Integer.parseInt(str); } /** * Parses the given HTML text to find the value of the given parameter. * * @param html The HTML string where to look for the parameter. * @param paramName The name of the parameter to look for. * @return The value of the parameter as a string, or null if * no parameter is found. * * This method is based on the edu.rice.rubis.client.UserSession#extractIntFromHTML * and edu.rice.rubis.client.UserSession#extractFloatFromHTML. */ public String findParamInHtml(String html, String paramName) { if (html == null) { return null; } // Look for the parameter // int paramIdx = html.indexOf(paramName); // if (paramIdx == -1) // return null; // int lastIdx = minIndex(Integer.MAX_VALUE, html.indexOf('=', paramIdx + paramName.length())); // lastIdx = minIndex(lastIdx, html.indexOf('\"', paramIdx + paramName.length())); // lastIdx = minIndex(lastIdx, html.indexOf('?', paramIdx + paramName.length())); // lastIdx = minIndex(lastIdx, html.indexOf('&', paramIdx + paramName.length())); // lastIdx = minIndex(lastIdx, html.indexOf('>', paramIdx + paramName.length())); // return html.substring(paramIdx + paramName.length(), lastIdx); Pattern p = Pattern.compile("^.*?[&?]" + paramName + "=([^\"?&]*).+$"); Matcher m = p.matcher(html); if (m.matches()) { return m.group(1); } return null; } /** * Parses the given HTML text to find the value of the given form parameter. * * @param html The HTML string where to look for the form parameter. * @param paramName The name of the form parameter to look for. * @return The value of the form parameter as a string, or null if * no parameter is found. * * This method is based on the edu.rice.rubis.client.UserSession#extractIntFromHTML * and edu.rice.rubis.client.UserSession#extractFloatFromHTML. */ public String findFormParamInHtml(String html, String paramName) { if (html == null) { return null; } // Look for the parameter // String key = "name=" + paramName + " value="; // int keyIdx = html.indexOf(key); // if (keyIdx == -1) // return null; // int lastIdx = minIndex(Integer.MAX_VALUE, html.indexOf('=', keyIdx + key.length())); // lastIdx = minIndex(lastIdx, html.indexOf('\"', keyIdx + key.length())); // lastIdx = minIndex(lastIdx, html.indexOf('?', keyIdx + key.length())); // lastIdx = minIndex(lastIdx, html.indexOf('&', keyIdx + key.length())); // lastIdx = minIndex(lastIdx, html.indexOf('>', keyIdx + key.length())); // return html.substring(keyIdx + key.length(), lastIdx); Pattern p = Pattern.compile("^.*?<(?i:input)\\s+(?:.+\\s)?(?i:name)=" + paramName + "\\s+(?:.+\\s)?(?i:value)=([^\"?&>]+).+$"); Matcher m = p.matcher(html); if (m.matches()) { return m.group(1); } return null; } /** * Parses the given HTML text to find the page value. * * @param html The HTML string where to look for the item identifier. * @return The page value. * * This method is based on the edu.rice.rubis.client.UserSession#extractPageFromHTML */ public int findPageInHtml(String html) { if (html == null) { return 0; } // int firstPageIdx = html.indexOf("&page="); // if (firstPageIdx == -1) // return 0; // int secondPageIdx = html.indexOf("&page=", firstPageIdx + 6); // 6 equals to &page= // int chosenIdx = 0; // if (secondPageIdx == -1) // chosenIdx = firstPageIdx; // First or last page => go to next or previous page // else // // Choose randomly a page (previous or next) // if (this._rng.nextInt(100000) < 50000) // chosenIdx = firstPageIdx; // else // chosenIdx = secondPageIdx; // int lastIdx = minIndex(Integer.MAX_VALUE, html.indexOf('\"', chosenIdx + 6)); // lastIdx = minIndex(lastIdx, html.indexOf('?', chosenIdx + 6)); // lastIdx = minIndex(lastIdx, html.indexOf('&', chosenIdx + 6)); // lastIdx = minIndex(lastIdx, html.indexOf('>', chosenIdx + 6)); // String str = html.substring(chosenIdx + 6, lastIdx); // return Integer.parseInt(str); ////Pattern p = Pattern.compile("^.*?[&?]page=([^\"?&]*).*(?:[&?]page=([^\"?&]*).*)?$"); //Pattern p = Pattern.compile("^.*?[&?]page=(\\d+).*?(?:[&?]page=(\\d+).*?)?$"); Matcher m = _pageRegex.matcher(html); if (m.matches()) { if (m.groupCount() == 2 && m.group(2) != null) { // Choose randomly a page (previous or next) if (this._rng.nextInt(100000) < 50000) { return Integer.parseInt(m.group(1)); } return Integer.parseInt(m.group(2)); } // First or last page => go to next or previous page return (m.group(1) != null) ? Integer.parseInt(m.group(1)) : 0; } return 0; } /** * Get the number of days between the two input dates. * * @param from The first date * @param to The second date * @return The number of days between from and to. * A negative number means that the second date is earlier then the first * date. */ public int getDaysBetween(Date from, Date to) { Calendar cal = Calendar.getInstance(); cal.setTime(from); long fromTs = cal.getTimeInMillis(); cal.setTime(to); long toTs = cal.getTimeInMillis(); //long diffTs = Math.abs(toTs-fromTs); long diffTs = toTs-fromTs; return Math.round(diffTs/MILLISECS_PER_DAY); } public Date addDays(Date date, int n) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, n); return cal.getTime(); } /** * Internal method that returns the min between ix1 and ix2 if ix2 is not * equal to -1. * * @param ix1 The first index * @param ix2 The second index to compare with ix1 * @return ix2 if (ix2 < ix1 and ix2!=-1) else ix1 */ private static int minIndex(int ix1, int ix2) { if (ix2 == -1) { return ix1; } if (ix1 <= ix2) { return ix1; } return ix2; } /** * Generates a random text. * * @param minLen The minimum length of the text. * @param maxLen The maximum length of the text. * @return The generated text. */ private String generateText(int minLen, int maxLen) { int len = minLen+this._rng.nextInt(maxLen-minLen+1); StringBuilder buf = new StringBuilder(len); int left = len; while (left > 0) { if (buf.length() > 0) { buf.append(' '); --left; } String word = this.generateWord(1, left < this._conf.getMaxWordLength() ? left : this._conf.getMaxWordLength()); buf.append(word); left -= word.length(); } return buf.toString(); } /** * Generates a random word. * * @param minLen The minimum length of the word. * @param maxLen The maximum length of the word. * @return The generated word. */ private String generateWord(int minLen, int maxLen) { if (minLen > maxLen) { return ""; } int len = minLen+this._rng.nextInt(maxLen-minLen+1); char[] buf = new char[len]; for (int i = 0; i < len; ++i) { int j = this._rng.nextInt(ALNUM_CHARS.length); buf[i] = ALNUM_CHARS[j]; } return new String(buf); } }
package org.orbeon.oxf.processor.converter; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.orbeon.oxf.pipeline.api.ExternalContext; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.pipeline.api.ExternalContext.Response; import org.orbeon.oxf.portlet.PortletExternalContext; import org.orbeon.oxf.processor.ProcessorImpl; import org.orbeon.oxf.processor.ProcessorInputOutputInfo; import org.orbeon.oxf.processor.ProcessorOutput; import org.orbeon.oxf.xml.XMLUtils; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * <!-- XHTMLRewrite --> * XHTML specific Java impl of oxf-rewrite.xsl. Uses GOF state pattern + SAX to get the job done. * The state machine ad hoc and relies a bit on the simplicity of the transformation that we are * perfoming. * * Wrt the transformation, here is the comment from oxf-rewrite.xsl : * This stylesheet rewrites HTML or XHTML for servlets and portlets. URLs are parsed, so it must * be made certain that the URLs are well-formed. Absolute URLs are not modified. Relative or * absolute paths are supported, as well as the special case of a URL starting with a query string * (e.g. "?name=value"). This last syntax is supported by most Web browsers. * * A. For portlets, it does the following: * 1. Rewrite form/@action to WSRP action URL encoding * 2. Rewrite a/@href and link/@href to WSRP render encoding * 3. Rewrite img/@src, input[@type='image']/@src and script/@src to WSRP resource URL encoding * 4. If no form/@method is supplied, force an HTTP POST * 5. Escape any wsrp_rewrite occurence in text not within a script or * SCRIPT element to wsrp_rewritewsrp_rewrite. WSRP 1.0 does not appear to * specify a particular escape sequence, but we use this one in PresentationServer Portal. The * escaped sequence is recognized by the PresentationServer Portlet and restored to the * original sequence, so it is possible to include the string wsrp_rewrite within documents. * 6. Occurrences of wsrp_rewrite found within script or SCRIPT elements, as well as occurrences * within attributes, are left untouched. This allows them to be recognized by the * PresentationServer Portlet and rewritten. * * Known issues for portlets: * * o The input document should not contain; * o elements and attribute containing wsrp_rewrite * o namespace URIs containing wsrp_rewrite * o processing instructions containing wsrp_rewrite * * B. For servlets, it resrites the URLs to be absolute paths, and prepends the context path. * * @author d */ public class XHTMLRewrite extends ProcessorImpl { /** * <!-- REWRITE_IN --> * Name of the input that receives the content that is to be rewritten. * @author d */ private static final String REWRITE_IN = "rewrite-in"; /** * <!-- FORMATTING_URI --> * What you think. * @author d */ static final String FORMATTING_URI = "http://orbeon.org/oxf/xml/formatting"; /** * <!-- ACTION_ATT --> * What you think. * @author d */ static final String ACTION_ATT = "action"; /** * <!-- METHOD_ATT --> * What you think. * @author d */ static final String METHOD_ATT = "method"; /** * <!-- HREF_ATT --> * What you think. * @author d */ static final String HREF_ATT = "href"; /** * <!-- SRC_ATT --> * What you think. * @author d */ static final String SRC_ATT = "src"; /** * <!-- BACKGROUND_ATT --> * What you think. * @author d */ static final String BACKGROUND_ATT = "background"; /** * <!-- State --> * Base state. Simply forwards data to the destination content handler and returns itself. * That is unless the ( element ) depth becomes negative after an end element event. In this * case the previous state is returned. This means btw that we are really only considering * state changes on start and end element events. * @author d */ protected static abstract class State { /** * <!-- contentHandler --> * The destination of the rewrite transformation. * @author d */ protected final ContentHandler contentHandler; /** * <!-- State --> * What you think. * @author d */ protected final State previous; /** * <!-- response --> * Performs the URL rewrites. * @author d */ protected final Response response; /** * <!-- isPortlet --> * A sub-state, if you will. Didn't implement this as a sub-class of State as it doesn't * change during the course of a transformation. * @see XHTMLRewrite * @author d */ protected final boolean isPortlet; /** * <!-- haveScriptAncestor --> * Could have been another State. However since the value is determined in one state and * then used by a 'descendent' state doing so would have meant that descendent would have * to walk it's ancestors to get the value. So, since making this a field instead of * a separate State sub-class was easier to implement and is faster a field was used. * @see XHTMLRewrite * @author d */ protected final boolean haveScriptAncestor; /** * <!-- depth --> * At the moment are state transitions only happen on start element and end element events. * Therefore we track element depth and by default when the depth becomes negative we switch * to the previous state. * @author d */ protected int depth = 0; /** * <!-- State --> * @param stt The previous state. * @param cntntHndlr The destination for the rewrite transformation. * @param rspns Used to perform URL rewrites. * @param isPrtlt Whether or not the context is a portlet context. * @param scrptAncstr Whether content ( SAX events ) processed by this state are a * descendent of a script element. * @see #previous * @see #contentHandler * @see #response * @see #isPortlet * @see #haveScriptAncestor * @author d */ State( final State stt, final ContentHandler cntntHndlr, final Response rspns , final boolean isPrtlt, final boolean scrptAncstr ) { previous = stt; contentHandler = cntntHndlr; response = rspns; isPortlet = isPrtlt; haveScriptAncestor = scrptAncstr; } /** * <!-- characters --> * @see State * @author d */ State characters( final char[] ch, final int strt, final int len ) throws SAXException { contentHandler.characters( ch, strt, len ); return this; } /** * <!-- endDocument --> * @see State * @author d */ State endDocument() throws SAXException { contentHandler.endDocument(); return this; } /** * <!-- endElement --> * @see State * @author d */ State endElement( final String ns, final String lnam, final String qnam ) throws SAXException { depth final State ret; if ( depth >= 0 || previous == null ) { contentHandler.endElement( ns, lnam, qnam ); ret = this; } else { ret = previous.endElement( ns, lnam, qnam ); } return ret; } /** * <!-- endPrefixMapping--> * @see State * @author d */ State endPrefixMapping( final String pfx ) throws SAXException { contentHandler.endPrefixMapping( pfx ); return this; } /** * <!-- ignorableWhitespace --> * @see State * @author d */ State ignorableWhitespace( final char[] ch, final int strt, final int len ) throws SAXException { contentHandler.ignorableWhitespace( ch, strt, len ); return this; } /** * <!-- processingInstructions --> * @see State * @author d */ State processingInstruction( final String trgt, final String dat ) throws SAXException { contentHandler.processingInstruction( trgt, dat ); return this; } /** * <!-- setDocumentLocator --> * @see State * @author d */ State setDocumentLocator( final Locator lctr ) { contentHandler.setDocumentLocator( lctr ); return this; } /** * <!-- skippedEntity --> * @see State * @author d */ State skippedEntity( final String nam ) throws SAXException { contentHandler.skippedEntity( nam ); return this; } /** * <!-- startDocument --> * @see State * @author d */ State startDocument() throws SAXException { contentHandler.startDocument(); return this; } /** * <!-- startElement --> * @see State * @author d */ State startElement ( final String ns, final String lnam, final String qnam, final Attributes atts ) throws SAXException { depth++; contentHandler.startElement( ns, lnam, qnam, atts ); return this; } /** * <!-- startPrefixMapping --> * @see State * @author d */ State startPrefixMapping( final String pfx, final String uri ) throws SAXException { contentHandler.startPrefixMapping( pfx, uri ); return this; } } /** * <!-- RootFilter --> * Ignores everything before start element. On startElement switches to RewriteState. * So if this is used as the initial state then the result is that the prologue and epilogue * are ignored while the root element is passed to the next state. * @author d */ static class RootFilter extends State { /** * <!-- RootFilter --> * Simple calls super(...) * @see State#State(State, ContentHandler, Response, boolean, boolean) * @author d */ RootFilter( final State stt, final ContentHandler cntntHnder, final Response rspns , final boolean isPrtlt, final boolean scrptAncstr ) { super( stt, cntntHnder, rspns, isPrtlt, scrptAncstr ); } /** * <!-- startElement --> * @return new RewriteState( ... ) * @see RewriteState * @author d */ State startElement ( final String ns, final String lnam, final String qnam, final Attributes atts ) throws SAXException { final State ret = new RewriteState ( this, contentHandler, response, isPortlet, haveScriptAncestor ); return ret.startElement( ns, lnam, qnam, atts ); } /** * <!-- characters --> * @return this. Does nothing else. */ State characters( final char[] ch, final int strt, final int len ) throws SAXException { return this; } /** * <!-- ignorableWhitespace --> * @return this. Does nothing else. */ State ignorableWhitespace( final char[] ch, final int strt, final int len ) throws SAXException { return this; } /** * <!-- processingInstruction --> * @return this. Does nothing else. */ State processingInstruction( final String trgt, final String dat ) throws SAXException { return this; } } /** * <!-- RewriteState --> * The rewrite state. Essentially this corresponds to the default mode of oxf-rewrite.xsl. * Basically this : * <ul> * <li>Rewrites attribs in start element event when need be. * <li>Accumulates text from characters events so that proper char content rewriting can * happen. * <li>On an event that indicates the end of potentially rewritable text, e.g. start element, * rewrites and forwards the accumlated characters. * <li>When explicit no write is indicated, e.g. we see attrib no-rewrite=true, then * transition to the NoRewriteState. * </ul> * @author dsmall */ static class RewriteState extends State { /** * <!-- WSRP_REWRITE_REPLACMENT_CHARS --> * Chars useD to replace "wsrp_rewrite" in text. * @see XHTMLRewrite * @see RewriteState * @see #flushCharacters() * @author d */ private static final char[] WSRP_REWRITE_REPLACMENT_CHARS = new char[] { 'w', 's', 'r', 'p', '_', 'r', 'e', 'w', 'r', 'i', 't', 'e', 'w', 's', 'r', 'p', '_', 'r' , 'e', 'w', 'r', 'i', 't', 'e', }; /** * <!-- wsrprewriteMatcher --> * Used to find wsrp_rewrite in char data. * @see RewriteState * @author d */ private final Matcher wsrprewriteMatcher; /** * <!-- charactersBuf --> * Used to accumlate characters from characters event. Lazily init'd in characters. * Btw we use CharacterBuffer instead of StringBuffer because : * <ul> * <li>We want something that works in JDK 1.4.</li> * <li> * We don't want the performance penalty of StringBuffer's synchronization in JDK 1.5. * <li> * </ul> * * Btw if we didn't care about 1.4 we could use StringBuilder instead. * * @see RewriteState * @see #characters(char[], int, int) * @see #flushCharacters() * @author d */ private java.nio.CharBuffer charactersBuf; /** * <!-- RewriteState --> * Calls super( ... ) and initializes wsrprewriteMatcher with "wsrp_rewrite" * @author d * @see State#State(State, ContentHandler, Response, boolean, boolean) */ RewriteState( final State stt, final ContentHandler cntntHndlr, final Response rspns , final boolean isPrtlt, final boolean scrptAncstr ) { super( stt, cntntHndlr, rspns, isPrtlt, scrptAncstr ); final Pattern ptrn = Pattern.compile( "wsrp_rewrite" ); wsrprewriteMatcher = ptrn.matcher( "" ); } private State handleEltWithResource ( final String elt, final String resAtt, final String ns, final String lnam , final String qnam, final Attributes atts ) throws SAXException { State ret = null; done : if ( elt.equals( lnam ) ) { final String res = atts.getValue( "", resAtt ); if ( res == null ) break done; ret = this; final AttributesImpl newAtts = XMLUtils.getAttribsFromDefaultNamespace( atts ); final String newHref = response.rewriteResourceURL( res, false ); newAtts.addAttribute( "", resAtt, resAtt, "", newHref ); contentHandler.startElement( ns, lnam, qnam, newAtts ); } return ret; } private State handleA ( final String ns, final String lnam, final String qnam, final Attributes atts ) throws SAXException { State ret = null; done : if ( "a".equals( lnam ) ) { final String href = atts.getValue( "", HREF_ATT ); if ( href == null ) break done; ret = this; final AttributesImpl newAtts = XMLUtils.getAttribsFromDefaultNamespace( atts ); final String url_typ = atts.getValue( FORMATTING_URI, "url-type" ); final String newHref; if ( url_typ == null || "render".equals( url_typ ) ) { newHref = response.rewriteRenderURL( href ); } else if ( "action".equals( url_typ ) ) { newHref = response.rewriteActionURL( href ); } else if ( "resource".equals( url_typ ) ) { newHref = response.rewriteResourceURL( href, false ); } else { newHref = null; } if ( newHref != null ) { newAtts.addAttribute( "", HREF_ATT, HREF_ATT, "", newHref ); } contentHandler.startElement( ns, lnam, qnam, newAtts ); } return ret; } private State handleArea ( final String ns, final String lnam, final String qnam, final Attributes atts ) throws SAXException { State ret = null; done : if ( "area".equals( lnam ) ) { final String href = atts.getValue( "", HREF_ATT ); if ( href == null ) break done; ret = this; final AttributesImpl newAtts = XMLUtils.getAttribsFromDefaultNamespace( atts ); final String newHref = response.rewriteActionURL( href ); newAtts.addAttribute( "", HREF_ATT, HREF_ATT, "", newHref ); contentHandler.startElement( ns, lnam, qnam, newAtts ); } return ret; } private State handleScript ( final String ns, final String lnam, final String qnam, final Attributes atts ) throws SAXException { final State stt = handleEltWithResource( "script", SRC_ATT, ns, lnam, qnam, atts ); final State ret; if ( stt == null ) { ret = null; } else { ret = new RewriteState( this, contentHandler, response, isPortlet, true ); } return ret; } private State handleInput ( final String ns, final String lnam, final String qnam, final Attributes atts ) throws SAXException { final State ret; final String typ = atts.getValue( "", "type" ); if ( "image".equals( typ ) ) { ret = handleEltWithResource( "input", SRC_ATT, ns, lnam, qnam, atts ); } else { ret = null; } return ret; } * <xsl:if test="not(@method) and $container-type/* = 'portlet'"> * <xsl:attribute name="method">post</xsl:attribute> * </xsl:if> * <xsl:choose> * <xsl:when test="@portlet:is-portlet-form = 'true'"> * <xsl:apply-templates mode="norewrite"/> * </xsl:when> * <xsl:otherwise> * <xsl:apply-templates/> * </xsl:otherwise> * </xsl:choose> * </xsl:copy> * </xsl:template> * </pre> * * If match is satisfied then modified event is sent to destination contentHandler. * @return null match is not satisfied, * new NoRewriteState( this, contentHandler, response, isPortlet * , haveScriptAncestor ) if is-portlet-form='true', and this * otherwise. * @throws SAXException if destination contentHandler throws SAXException * @see XHTMLRewrite * @author d */ private State handleForm ( final String ns, final String lnam, final String qnam, final Attributes atts ) throws SAXException { final State ret; if ( "form".equals( lnam ) ) { final AttributesImpl newAtts = XMLUtils.getAttribsFromDefaultNamespace( atts ); final String actn = atts.getValue( "", ACTION_ATT ); final String newActn; if ( actn == null ) { newActn = response.rewriteActionURL( "" ); } else { newActn = response.rewriteActionURL( actn ); } newAtts.addAttribute( "", ACTION_ATT, ACTION_ATT, "", newActn ); if ( atts.getValue( "", METHOD_ATT ) == null && isPortlet ) { newAtts.addAttribute( "", METHOD_ATT, METHOD_ATT, "", "post" ); } final String isPrtltFrm = atts.getValue( "http://orbeon.org/oxf/xml/portlet", "is-portlet-form" ); if ( "true".equals( isPrtltFrm ) ) { ret = new NoRewriteState ( this, contentHandler, response, isPortlet, haveScriptAncestor ); } else { ret = this; } contentHandler.startElement( ns, lnam, qnam, newAtts ); } else { ret = null; } return ret; } /** * <!-- flushCharacters --> * If we have accumlated character data rewrite it and forward it. Implements : * <pre> * <xsl:template match="text()"> * <xsl:value-of * select="replace(current(), 'wsrp_rewrite', 'wsrp_rewritewsrp_rewrite')"/> * <xsl:apply-templates/> * </xsl:template> * </pre> * If there no character data has been accumulated do nothing. Also clears buffer. * @see XHTMLRewrite * @see RewriteState * @author d */ private void flushCharacters() throws SAXException { final int bfLen = charactersBuf == null ? 0 : charactersBuf.position(); if ( bfLen > 0 ) { charactersBuf.flip(); char[] chs = charactersBuf.array(); final int chsStrt = charactersBuf.arrayOffset(); wsrprewriteMatcher.reset( charactersBuf ); int last = 0; while ( wsrprewriteMatcher.find() ) { final int strt = wsrprewriteMatcher.start(); final int len = strt - last; contentHandler.characters( chs, chsStrt + strt, len ); contentHandler.characters ( WSRP_REWRITE_REPLACMENT_CHARS, 0, WSRP_REWRITE_REPLACMENT_CHARS.length ); last = wsrprewriteMatcher.end(); } if ( last < bfLen ) { final int len = bfLen - last; contentHandler.characters( chs, chsStrt + last, len ); } charactersBuf.clear(); } } /** * <!-- characters --> * If haveScriptAncestor then just forward data to destination contentHandler. Otherwise * store that data in the buffer and do not forward. Also manages init'ing and growing * charactersBuf as need be. * @see #charactersBuf * @see XHTMLRewrite * @see RewriteState * @author d */ public State characters( final char[] ch, final int strt, final int len ) throws SAXException { if ( haveScriptAncestor ) { contentHandler.characters( ch, strt, len ); } else { final int bufLen = charactersBuf == null ? 0 : charactersBuf.position(); final int cpcty = bufLen + ( len * 2 ); if ( charactersBuf == null || charactersBuf.remaining() < cpcty ) { final java.nio.CharBuffer newBuf = java.nio.CharBuffer.allocate( cpcty ); if ( charactersBuf != null ) { charactersBuf.flip(); newBuf.put( charactersBuf ); } charactersBuf = newBuf; } charactersBuf.put( ch, strt, len ); } return this; } /** * <!-- endElement --> * Just calls flushCharacters and super.endElement( ... ) * @see State#endElement(String, String, String) * @author dsmall d */ public State endElement( final String ns, final String lnam, final String qnam ) throws SAXException { flushCharacters(); return super.endElement( ns, lnam, qnam ); } /** * <!-- ignorableWhitespace --> * Just calls flushCharacters and super.endElement( ... ) * @see State#ignorableWhitespace(char[], int, int) * @author dsmall d */ public State ignorableWhitespace( final char[] ch, final int strt, final int len ) throws SAXException { flushCharacters(); return super.ignorableWhitespace(ch, strt, len); } /** * <!-- processingInstruction --> * Just calls flushCharacters and super.endElement( ... ) * @see State#processingInstruction(String, String) * @author dsmall d */ public State processingInstruction( final String trgt, final String dat ) throws SAXException { flushCharacters(); return super.processingInstruction( trgt, dat ); } /** * <!-- skippedEntity --> * Just calls flushCharacters and super.endElement( ... ) * @see State#skippedEntity(String) * @author dsmall d */ public State skippedEntity( final String nam ) throws SAXException { flushCharacters(); return super.skippedEntity( nam ); } public State startElement ( final String ns, final String lnam, final String qnam, final Attributes atts ) throws SAXException { flushCharacters(); final String no_urlrewrite = atts.getValue( FORMATTING_URI, "url-norewrite" ); depth++; State ret = this; if ( "true".equals( no_urlrewrite ) ) { final AttributesImpl newAtts = XMLUtils.getAttribsFromDefaultNamespace( atts ); contentHandler.startElement( ns, lnam, qnam, newAtts ); ret = new NoRewriteState ( this, contentHandler, response, isPortlet, haveScriptAncestor ); } else if ( "http: done : { ret = handleA( ns, lnam, qnam, atts ); if ( ret != null ) break done; ret = handleForm( ns, lnam, qnam, atts ); if ( ret != null ) break done; ret = handleArea( ns, lnam, qnam, atts ); if ( ret != null ) break done; ret = handleEltWithResource( "link", HREF_ATT, ns, lnam, qnam, atts ); if ( ret != null ) break done; ret = handleEltWithResource( "img", SRC_ATT, ns, lnam, qnam, atts ); if ( ret != null ) break done; ret = handleInput( ns, lnam, qnam, atts ); if ( ret != null ) break done; ret = handleScript( ns, lnam, qnam, atts ); if ( ret != null ) break done; ret = handleEltWithResource( "td", BACKGROUND_ATT, ns, lnam, qnam, atts ); if ( ret != null ) break done; ret = handleEltWithResource( "body", BACKGROUND_ATT, ns, lnam, qnam, atts ); if ( ret != null ) break done; ret = this; contentHandler.startElement( ns, lnam, qnam, atts ); } } else if ( FORMATTING_URI.equals( ns ) && "rewrite".equals( lnam ) ) { final String typ = atts.getValue( "", "type" ); final String url = atts.getValue( "", "url" ); if ( url != null ) { final String newURL; if ( "action".equals( typ ) ) { newURL = response.rewriteActionURL( url ); } else if ( "render".equals( typ ) ) { newURL = response.rewriteRenderURL( url ); } else { newURL = response.rewriteResourceURL( url, false ); } final char[] chs = newURL.toCharArray(); contentHandler.characters( chs, 0, chs.length ); } } else { ret = this; contentHandler.startElement( ns, lnam, qnam, atts ); } return ret; } } /** * <!-- NoRewriteState --> * Essentially this corresponds to the norewrite mode of oxf-rewrite.xsl. i.e. Just forwards * events to the destination content handler until we finish the initial element ( depth < 0 ) * or until it encounters @url-norewrite='false'. In the first case transitions to the previous * state and in the second case it transitions to * new RewriteState( this, contentHandler, response, isPortlet, haveScriptAncestor ). * @author dsmall */ static class NoRewriteState extends State { NoRewriteState( final State stt, final ContentHandler cntntHndlr, final Response rspns , final boolean isPrtlt, final boolean scrptAncstr ) { super( stt, cntntHndlr, rspns, isPrtlt, scrptAncstr ); } /** * <!-- startElement --> * @see NoRewriteState * @author d */ public State startElement ( final String ns, final String lnam, final String qnam, final Attributes atts ) throws SAXException { final String no_urlrewrite = atts .getValue( FORMATTING_URI, "url-norewrite" ); final Attributes newAtts = XMLUtils.getAttribsFromDefaultNamespace( atts ); contentHandler.startElement( ns, lnam, qnam, newAtts ); depth++; final State ret; if ( "false".equals( no_urlrewrite ) ) { ret = new RewriteState ( this, contentHandler, response, isPortlet, haveScriptAncestor ); } else { ret = this; } return ret; } } /** * <!-- StatefullHandler --> * Driver for our state machine. Just forwards SAX events to a State which in turn returns the * next State. The initial state is RootFilter * @see XHTMLRewrite * @see State * @see RootFilter * @author d */ static final class StatefullHandler implements ContentHandler { /** * <!-- state --> * The current state. * @see State * @see StatefullHandler * @author d */ private State state; /** * <!-- StatefullHandler --> * @see StatefullHandler * @author d */ StatefullHandler( final ContentHandler dst, final Response rspns, final boolean isPrtlt ) { state = new RootFilter( null, dst, rspns, isPrtlt, false ); } /** * <!-- characters --> * @see StatefullHandler * @author d */ public void characters( final char[] ch, final int strt, final int len ) throws SAXException { state = state.characters( ch, strt, len ); } /** * <!-- endDocument --> * @see StatefullHandler * @author d */ public void endDocument() throws SAXException { state = state.endDocument(); } /** * <!-- endElement --> * @see StatefullHandler * @author d */ public void endElement( final String ns, final String lnam, final String qnam ) throws SAXException { state = state.endElement( ns, lnam, qnam ); } /** * <!-- endPrefixMapping --> * @see StatefullHandler * @author d */ public void endPrefixMapping( final String pfx ) throws SAXException { state = state.endPrefixMapping(pfx); } /** * <!-- ignorableWhitespace --> * @see StatefullHandler * @author d */ public void ignorableWhitespace( final char[] ch, final int strt, final int len ) throws SAXException { state = state.ignorableWhitespace( ch, strt, len ); } /** * <!-- processingInstruction --> * @see StatefullHandler * @author d */ public void processingInstruction( final String trgt, final String dat ) throws SAXException { state = state.processingInstruction( trgt, dat ); } /** * <!-- setDocumentLocator --> * @see StatefullHandler * @author d */ public void setDocumentLocator( final Locator loc ) { state = state.setDocumentLocator( loc ); } /** * <!-- skippedEntity --> * @see StatefullHandler * @author d */ public void skippedEntity( final String nam ) throws SAXException { state = state.skippedEntity( nam ); } /** * <!-- startDocument --> * @see StatefullHandler * @author d */ public void startDocument() throws SAXException { state = state.startDocument(); } /** * <!-- startElement --> * @see StatefullHandler * @author d */ public void startElement ( final String ns, final String lnam, final String qnam, final Attributes atts ) throws SAXException { state = state.startElement( ns, lnam, qnam, atts ); } /** * <!-- startPrefixMapping --> * @see StatefullHandler * @author d */ public void startPrefixMapping( final String pfx, final String uri ) throws SAXException { state = state.startPrefixMapping( pfx, uri ); } } /** * <!-- RewriteOutput --> * @see #readImpl(PipelineContext, ContentHandler) * @author dsmall */ private final class RewriteOutput extends ProcessorImpl.CacheableTransformerOutputImpl { /** * <!-- RewriteOutput --> * Just calls super( ... ) * @author d */ private RewriteOutput( final Class cls, final String nam ) { super( cls, nam ); } /** * <!-- readImpl --> * Creates a StatefullHandler and uses that to translate the events from the input, * rewrite-in, and then send them to the contentHandler ( the output ). * @see XHTMLRewrite * @see StatefullHandler * @author d */ public void readImpl( final PipelineContext ctxt, final ContentHandler cntntHndlr ) { final ExternalContext extrnlCtxt = ( ExternalContext )ctxt.getAttribute( PipelineContext.EXTERNAL_CONTEXT ); final Response rspns = extrnlCtxt.getResponse(); // Do the conversion final boolean isPrtlt = extrnlCtxt instanceof PortletExternalContext; final StatefullHandler stFlHndlr= new StatefullHandler( cntntHndlr, rspns, isPrtlt ); readInputAsSAX( ctxt, REWRITE_IN, stFlHndlr ); } } /** * <!-- XHTMLRewrite --> * Just declares input 'rewrite-in' and output 'rewrite-out'. * @author d */ public XHTMLRewrite() { final ProcessorInputOutputInfo in = new ProcessorInputOutputInfo( REWRITE_IN ); addInputInfo( in ); final ProcessorInputOutputInfo out = new ProcessorInputOutputInfo( "rewrite-out" ); addOutputInfo( out ); } /** * <!-- createOutput --> * @return new RewriteOutput( cls, nam ) after adding it with addOutput. * @author d */ public ProcessorOutput createOutput( final String nam ) { final Class cls = getClass(); final ProcessorOutput ret = new RewriteOutput( cls, nam ); addOutput( nam, ret ); return ret; } }
package application.controllers; import application.fxobjects.cell.Cell; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import javafx.event.EventHandler; import javafx.scene.Node; import javafx.scene.input.MouseEvent; /** * Class responsible for the handling of mouse events */ public class GraphMouseHandling { MainController mainController; //final DragContext dragContext = new DragContext(); EventHandler<MouseEvent> onMousePressedEventHandler = event -> { Cell node = (Cell) event.getSource(); core.Node clicked = mainController.getGraphController().getGraph() .getModel().getLevelMaps().get(0).get(node.getCellId()); String info = ""; info += "Genome ID: " + clicked.getId() + "\n"; info += clicked.getGenomes().size() + " Genomes in Node: \n" + clicked.getGenomesAsString() + "\n"; info += "Seq: \n" + clicked.getSequence() + "\n"; mainController.modifyNodeInfo(info); }; EventHandler<MouseEvent> onMouseEnteredEventHandler = event -> { }; EventHandler<MouseEvent> onMouseExitedEventHandler = event -> { }; /** * Class constructor. * * @param m the mainController. */ @SuppressFBWarnings("URF_UNREAD_FIELD") public GraphMouseHandling(MainController m) { this.mainController = m; } /** * Assign mouse events handlers to a given Node. * * @param node Node to get mouse handlers assigned. */ public void setMouseHandling(final Node node) { node.setOnMousePressed(onMousePressedEventHandler); node.setOnMouseEntered(onMouseEnteredEventHandler); node.setOnMouseExited(onMouseExitedEventHandler); } /** * Used for dragging of nodes. * Unused at this point of time. */ @SuppressFBWarnings({"SIC_INNER_SHOULD_BE_STATIC", "UUF_UNUSED_FIELD"}) static class DragContext { double x; double y; } }
package archimulator.incubator.noc.startup; import archimulator.incubator.noc.Experiment; import archimulator.incubator.noc.routers.FlitState; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.QuoteMode; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Analyze. * * @author Min Cai */ public class Analyze { private static List<CSVField> fields = new ArrayList<>(); static { fields.add(new CSVField("Traffic", CSVFields::getTraffic)); fields.add(new CSVField("Data_Packet_Injection_Rate_(packets/cycle/node)", CSVFields::getDataPacketInjectionRate)); fields.add(new CSVField("Routing_Algorithm", CSVFields::getRouting)); fields.add(new CSVField("Selection_Policy", CSVFields::getSelection)); fields.add(new CSVField("Routing+Selection", CSVFields::getRoutingAndSelection)); fields.add(new CSVField("Ant_Packet_Injection_Rate_(packets/cycle/node)", CSVFields::getAntPacketInjectionRate)); fields.add(new CSVField("Alpha", CSVFields::getAcoSelectionAlpha)); fields.add(new CSVField("Reinforcement_Factor", CSVFields::getReinforcementFactor)); fields.add(new CSVField("Routing+Selection/Alpha/Reinforcement_Factor", CSVFields::getRoutingAndSelectionAndAcoSelectionAlphaAndReinforcementFactor)); fields.add(new CSVField("Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", CSVFields::getRoutingAndSelectionAndAntPacketInjectionRateAndAcoSelectionAlphaAndReinforcementFactor)); fields.add(new CSVField("Simulation_Time", CSVFields::getSimulationTime)); fields.add(new CSVField("Total_Cycles", CSVFields::getTotalCycles)); fields.add(new CSVField("Packets_Transmitted", CSVFields::getNumPacketsTransmitted)); fields.add(new CSVField("Throughput_(packets/cycle/node)", CSVFields::getThroughput)); fields.add(new CSVField("Average_Packet_Delay_(cycles)", CSVFields::getAveragePacketDelay)); fields.add(new CSVField("Average_Packet_Hops", CSVFields::getAveragePacketHops)); fields.add(new CSVField("Payload_Packets_Transmitted", CSVFields::getNumPayloadPacketsTransmitted)); fields.add(new CSVField("Payload_Throughput_(packets/cycle/node)", CSVFields::getPayloadThroughput)); fields.add(new CSVField("Average_Payload_Packet_Delay_(cycles)", CSVFields::getAveragePayloadPacketDelay)); fields.add(new CSVField("Average_Payload_Packet_Hops", CSVFields::getAveragePayloadPacketHops)); for (FlitState state : FlitState.values()) { fields.add(new CSVField(String.format("Average_Flit_per_State_Delay::%s", state), e -> CSVFields.getAverageFlitPerStateDelay(e, state))); fields.add(new CSVField(String.format("Max_Flit_per_State_Delay::%s", state), e -> CSVFields.getMaxFlitPerStateDelay(e, state))); } } public static void main(String[] args) { analyzeTrafficsAndDataPacketInjectionRates(); analyzeAntPacketInjectionRates(); analyzeAcoSelectionAlphasAndReinforcementFactors(); } public static void analyzeTrafficsAndDataPacketInjectionRates() { for (String traffic : Common.trafficsAndDataPacketInjectionRates.keySet()) { Common.trafficsAndDataPacketInjectionRates.get(traffic).forEach(Experiment::loadStats); toCsv(String.format("results/trafficsAndDataPacketInjectionRates/t_%s.csv", traffic), Common.trafficsAndDataPacketInjectionRates.get(traffic), fields); generatePlot( String.format("results/trafficsAndDataPacketInjectionRates/t_%s.csv", traffic), String.format("results/trafficsAndDataPacketInjectionRates/t_%s_throughput.pdf", traffic), "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Throughput_(packets/cycle/node)" ); generatePlot( String.format("results/trafficsAndDataPacketInjectionRates/t_%s.csv", traffic), String.format("results/trafficsAndDataPacketInjectionRates/t_%s_average_packet_delay.pdf", traffic), "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Average_Packet_Delay_(cycles)" ); generatePlot( String.format("results/trafficsAndDataPacketInjectionRates/t_%s.csv", traffic), String.format("results/trafficsAndDataPacketInjectionRates/t_%s_average_packet_hops.pdf", traffic), "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Average_Packet_Hops" ); generatePlot( String.format("results/trafficsAndDataPacketInjectionRates/t_%s.csv", traffic), String.format("results/trafficsAndDataPacketInjectionRates/t_%s_payload_throughput.pdf", traffic), "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Payload_Throughput_(packets/cycle/node)" ); generatePlot( String.format("results/trafficsAndDataPacketInjectionRates/t_%s.csv", traffic), String.format("results/trafficsAndDataPacketInjectionRates/t_%s_average_payload_packet_delay.pdf", traffic), "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Average_Payload_Packet_Delay_(cycles)" ); generatePlot( String.format("results/trafficsAndDataPacketInjectionRates/t_%s.csv", traffic), String.format("results/trafficsAndDataPacketInjectionRates/t_%s_average_payload_packet_hops.pdf", traffic), "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Average_Payload_Packet_Hops" ); } } public static void analyzeAntPacketInjectionRates() { Common.antPacketInjectionRates.forEach(Experiment::loadStats); toCsv("results/antPacketInjectionRates/t_transpose.csv", Common.antPacketInjectionRates, fields); generatePlot( "results/antPacketInjectionRates/t_transpose.csv", "results/antPacketInjectionRates/t_transpose_throughput.pdf", "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Throughput_(packets/cycle/node)" ); generatePlot( "results/antPacketInjectionRates/t_transpose.csv", "results/antPacketInjectionRates/t_transpose_average_packet_delay.pdf", "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Average_Packet_Delay_(cycles)" ); generatePlot( "results/antPacketInjectionRates/t_transpose.csv", "results/antPacketInjectionRates/t_transpose_average_packet_hops.pdf", "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Average_Packet_Hops" ); generatePlot( "results/antPacketInjectionRates/t_transpose.csv", "results/antPacketInjectionRates/t_transpose_payload_throughput.pdf", "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Payload_Throughput_(packets/cycle/node)" ); generatePlot( "results/antPacketInjectionRates/t_transpose.csv", "results/antPacketInjectionRates/t_transpose_average_payload_packet_delay.pdf", "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Average_Payload_Packet_Delay_(cycles)" ); generatePlot( "results/antPacketInjectionRates/t_transpose.csv", "results/antPacketInjectionRates/t_transpose_average_payload_packet_hops.pdf", "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Average_Payload_Packet_Hops" ); } public static void analyzeAcoSelectionAlphasAndReinforcementFactors() { Common.acoSelectionAlphasAndReinforcementFactors.forEach(Experiment::loadStats); toCsv("results/acoSelectionAlphasAndReinforcementFactors/t_transpose.csv", Common.acoSelectionAlphasAndReinforcementFactors, fields); generatePlot( "results/acoSelectionAlphasAndReinforcementFactors/t_transpose.csv", "results/acoSelectionAlphasAndReinforcementFactors/t_transpose_throughput.pdf", "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Throughput_(packets/cycle/node)" ); generatePlot( "results/acoSelectionAlphasAndReinforcementFactors/t_transpose.csv", "results/acoSelectionAlphasAndReinforcementFactors/t_transpose_average_packet_delay.pdf", "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Average_Packet_Delay_(cycles)" ); generatePlot( "results/acoSelectionAlphasAndReinforcementFactors/t_transpose.csv", "results/acoSelectionAlphasAndReinforcementFactors/t_transpose_average_packet_hops.pdf", "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Average_Packet_Hops" ); generatePlot( "results/acoSelectionAlphasAndReinforcementFactors/t_transpose.csv", "results/acoSelectionAlphasAndReinforcementFactors/t_transpose_payload_throughput.pdf", "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Payload_Throughput_(packets/cycle/node)" ); generatePlot( "results/acoSelectionAlphasAndReinforcementFactors/t_transpose.csv", "results/acoSelectionAlphasAndReinforcementFactors/t_transpose_average_payload_packet_delay.pdf", "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Average_Payload_Packet_Delay_(cycles)" ); generatePlot( "results/acoSelectionAlphasAndReinforcementFactors/t_transpose.csv", "results/acoSelectionAlphasAndReinforcementFactors/t_transpose_average_payload_packet_hops.pdf", "Data_Packet_Injection_Rate_(packets/cycle/node)", "Routing+Selection/Ant_Packet_Injection_Rate/Alpha/Reinforcement_Factor", "Average_Payload_Packet_Hops" ); } public static void toCsv(String outputCSVFileName, List<Experiment> results, List<CSVField> fields) { File resultDirFile = new File(outputCSVFileName).getParentFile(); if (!resultDirFile.exists()) { if (!resultDirFile.mkdirs()) { throw new RuntimeException(); } } CSVFormat format = CSVFormat.RFC4180.withHeader().withDelimiter(',').withQuoteMode(QuoteMode.ALL).withQuote('"'); try { FileWriter writer = new FileWriter(outputCSVFileName); CSVPrinter printer = new CSVPrinter(writer, format); printer.printRecord(fields); for (Experiment experiment : results) { List<String> experimentData = new ArrayList<>(); for (CSVField field : fields) { experimentData.add(field.getFunc().apply(experiment)); } printer.printRecord(experimentData); } printer.close(); } catch (IOException e) { throw new RuntimeException(e); } } public static void generatePlot(String csvFileName, String plotFileName, String x, String hue, String y) { try { ProcessBuilder pb = new ProcessBuilder( "tools/plots/plots.sh", "--csv_file_name", csvFileName, "--plot_file_name", plotFileName, "--x", x, "--hue", hue, "--y", y ).inheritIO(); pb.start().waitFor(); } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } } }
package at.ac.tuwien.kr.alpha.solver; import at.ac.tuwien.kr.alpha.common.AnswerSet; import at.ac.tuwien.kr.alpha.common.NoGood; import at.ac.tuwien.kr.alpha.grounder.Grounder; import at.ac.tuwien.kr.alpha.solver.heuristics.*; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.function.Consumer; import static at.ac.tuwien.kr.alpha.solver.ThriceTruth.FALSE; import static at.ac.tuwien.kr.alpha.solver.ThriceTruth.MBT; public class DefaultSolver extends AbstractSolver { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSolver.class); private final NoGoodStore<ThriceTruth> store; private final ChoiceStack choiceStack; private final Assignment assignment; private final GroundConflictNoGoodLearner learner; private final BranchingHeuristic branchingHeuristic; private final BranchingHeuristic fallbackBranchingHeuristic; private final ChoiceManager choiceManager; private boolean initialize = true; private boolean didChange; private int decisionCounter; public DefaultSolver(Grounder grounder, Random random, String branchingHeuristicName, boolean debugInternalChecks) { super(grounder); this.assignment = new BasicAssignment(grounder); this.store = new BasicNoGoodStore(assignment, grounder); if (debugInternalChecks) { store.enableInternalChecks(); } this.choiceStack = new ChoiceStack(grounder); this.learner = new GroundConflictNoGoodLearner(assignment); this.choiceManager = new ChoiceManager(assignment); this.branchingHeuristic = BranchingHeuristicFactory.getInstance(branchingHeuristicName, assignment, choiceManager, random); this.fallbackBranchingHeuristic = new NaiveHeuristic(choiceManager); } @Override protected boolean tryAdvance(Consumer<? super AnswerSet> action) { // Initially, get NoGoods from grounder. if (initialize) { if (!obtainNoGoodsFromGrounder()) { // NoGoods are unsatisfiable. LOGGER.info("{} decisions done.", decisionCounter); return false; } initialize = false; } else { // We already found one Answer-Set and are requested to find another one. // Create enumeration NoGood to avoid finding the same Answer-Set twice. if (!isSearchSpaceExhausted()) { NoGood enumerationNoGood = createEnumerationNoGood(); // Backjump instead of backtrack, enumerationNoGood will invert lass guess. doBackjump(assignment.getDecisionLevel() - 1); LOGGER.debug("Adding enumeration NoGood: {}", enumerationNoGood); if (store.add(grounder.registerOutsideNoGood(enumerationNoGood), enumerationNoGood) != null) { throw new RuntimeException("Adding enumeration NoGood causes conflicts. Should not happen."); } } else { LOGGER.info("{} decisions done.", decisionCounter); return false; } } int nextChoice; boolean afterAllAtomsAssigned = false; // Try all assignments until grounder reports no more NoGoods and all of them are satisfied while (true) { didChange |= store.propagate(); LOGGER.debug("Assignment after propagation is: {}", assignment); if (store.getViolatedNoGood() != null) { // Learn from conflict. NoGood violatedNoGood = store.getViolatedNoGood(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("NoGood violated ({}) by wrong choices ({} violated): {}", grounder.noGoodToString(violatedNoGood), choiceStack); } LOGGER.debug("Violating assignment is: {}", assignment); branchingHeuristic.violatedNoGood(violatedNoGood); if (!afterAllAtomsAssigned) { if (!learnBackjumpAddFromConflict()) { // NoGoods are unsatisfiable. LOGGER.info("{} decisions done.", decisionCounter); return false; } } else { // Will not learn from violated NoGood, do simple backtrack. LOGGER.debug("NoGood was violated after all unassigned atoms were assigned to false; will not learn from it; skipping."); doBacktrack(); afterAllAtomsAssigned = false; if (isSearchSpaceExhausted()) { LOGGER.info("{} decisions done.", decisionCounter); return false; } } } else if (!propagationFixpointReached()) { // Ask the grounder for new NoGoods, then propagate (again). LOGGER.trace("Doing propagation step."); updateGrounderAssignment(); if (!obtainNoGoodsFromGrounder()) { // NoGoods are unsatisfiable. LOGGER.info("{} decisions done.", decisionCounter); return false; } } else if ((nextChoice = computeChoice()) != 0) { LOGGER.debug("Doing choice."); doChoice(nextChoice); } else if (!allAtomsAssigned()) { LOGGER.debug("Closing unassigned known atoms (assigning FALSE)."); assignUnassignedToFalse(); afterAllAtomsAssigned = true; } else if (assignment.getMBTCount() == 0) { AnswerSet as = translate(assignment.getTrueAssignments()); LOGGER.debug("Answer-Set found: {}", as); LOGGER.debug("Choices of Answer-Set were: {}", choiceStack); action.accept(as); LOGGER.info("{} decisions done.", decisionCounter); return true; } else { LOGGER.debug("Backtracking from wrong choices ({} MBTs): {}", assignment.getMBTCount(), choiceStack); doBacktrack(); afterAllAtomsAssigned = false; if (isSearchSpaceExhausted()) { LOGGER.info("{} decisions done.", decisionCounter); return false; } } } } private NoGood createEnumerationNoGood() { int[] enumerationLiterals = new int[choiceStack.size()]; int enumerationPos = 0; for (Integer integer : choiceStack) { enumerationLiterals[enumerationPos++] = integer; } return new NoGood(enumerationLiterals, -1); } /** * Analyzes the conflict and either learns a new NoGood (causing backjumping and addition to the NoGood store), * or backtracks the guess causing the conflict. * @return false iff the analysis result shows that the set of NoGoods is unsatisfiable. */ private boolean learnBackjumpAddFromConflict() { LOGGER.debug("Analyzing conflict."); GroundConflictNoGoodLearner.ConflictAnalysisResult analysisResult = learner.analyzeConflictingNoGood(store.getViolatedNoGood()); if (analysisResult.isUnsatisfiable) { // Halt if unsatisfiable. return false; } branchingHeuristic.analyzedConflict(analysisResult); if (analysisResult.learnedNoGood == null) { LOGGER.debug("Conflict results from wrong guess, backjumping and removing guess."); LOGGER.debug("Backjumping to decision level: {}", analysisResult.backjumpLevel); doBackjump(analysisResult.backjumpLevel); store.backtrack(); LOGGER.debug("Backtrack: Removing last choice because of conflict, setting decision level to {}.", assignment.getDecisionLevel()); choiceStack.remove(); choiceManager.backtrack(); LOGGER.debug("Backtrack: choice stack size: {}, choice stack: {}", choiceStack.size(), choiceStack); if (!store.propagate()) { throw new RuntimeException("Nothing to propagate after backtracking from conflict-causing guess. Should not happen."); } } else { NoGood learnedNoGood = analysisResult.learnedNoGood; LOGGER.debug("Learned NoGood is: {}", learnedNoGood); int backjumpingDecisionLevel = analysisResult.backjumpLevel; LOGGER.debug("Computed backjumping level: {}", backjumpingDecisionLevel); doBackjump(backjumpingDecisionLevel); int learnedNoGoodId = grounder.registerOutsideNoGood(learnedNoGood); NoGoodStore.ConflictCause conflictCause = store.add(learnedNoGoodId, learnedNoGood); if (conflictCause != null) { throw new RuntimeException("Learned NoGood is violated after backjumping, should not happen."); } } return true; } private void doBackjump(int backjumpingDecisionLevel) { LOGGER.debug("Backjumping to decisionLevel: {}.", backjumpingDecisionLevel); if (backjumpingDecisionLevel < 0) { throw new RuntimeException("Backjumping decision level less than 0, should not happen."); } // Remove everything above the backjumpingDecisionLevel, but keep the backjumpingDecisionLevel unchanged. while (assignment.getDecisionLevel() > backjumpingDecisionLevel) { store.backtrack(); choiceStack.remove(); choiceManager.backtrack(); } } private void assignUnassignedToFalse() { for (Integer atom : unassignedAtoms) { assignment.assign(atom, FALSE, null); } } private List<Integer> unassignedAtoms; private boolean allAtomsAssigned() { unassignedAtoms = grounder.getUnassignedAtoms(assignment); return unassignedAtoms.isEmpty(); } private void doBacktrack() { boolean repeatBacktrack; // Iterative implementation of recursive backtracking. do { repeatBacktrack = false; if (isSearchSpaceExhausted()) { return; } int lastGuessedAtom = choiceStack.peekAtom(); boolean lastGuessedValue = choiceStack.peekValue(); Assignment.Entry lastChoiceEntry = assignment.get(lastGuessedAtom); store.backtrack(); LOGGER.debug("Backtrack: Removing last choice, setting decision level to {}.", assignment.getDecisionLevel()); boolean backtrackedAlready = choiceStack.peekBacktracked(); choiceStack.remove(); choiceManager.backtrack(); LOGGER.debug("Backtrack: choice stack size: {}, choice stack: {}", choiceStack.size(), choiceStack); if (!backtrackedAlready) { // Chronological backtracking: guess inverse now. // Guess FALSE if the previous guess was for TRUE and the atom was not already MBT at that time. if (lastGuessedValue && MBT.equals(assignment.getTruth(lastGuessedAtom))) { LOGGER.debug("Backtrack: inverting last guess not possible, atom was MBT before guessing TRUE."); LOGGER.debug("Recursive backtracking."); repeatBacktrack = true; continue; } // If choice was assigned at lower decision level (due to added NoGoods), no inverted guess should be done. if (lastChoiceEntry.getImpliedBy() != null) { LOGGER.debug("Last choice now is implied by: {}.", lastChoiceEntry.getImpliedBy()); if (lastChoiceEntry.getDecisionLevel() == assignment.getDecisionLevel() + 1) { throw new RuntimeException("Choice was assigned but not at a lower decision level. This should not happen."); } LOGGER.debug("Choice was assigned at a lower decision level"); LOGGER.debug("Recursive backtracking."); repeatBacktrack = true; continue; } decisionCounter++; boolean newGuess = !lastGuessedValue; assignment.guess(lastGuessedAtom, newGuess); LOGGER.debug("Backtrack: setting decision level to {}.", assignment.getDecisionLevel()); LOGGER.debug("Backtrack: inverting last guess. Now: {}={}@{}", grounder.atomToString(lastGuessedAtom), newGuess, assignment.getDecisionLevel()); choiceStack.pushBacktrack(lastGuessedAtom, newGuess); choiceManager.nextDecisionLevel(); LOGGER.debug("Backtrack: choice stack size: {}, choice stack: {}", choiceStack.size(), choiceStack); LOGGER.debug("Backtrack: {} choices so far.", decisionCounter); } else { LOGGER.debug("Recursive backtracking."); repeatBacktrack = true; } } while (repeatBacktrack); } private void updateGrounderAssignment() { grounder.updateAssignment(assignment.getNewAssignmentsIterator()); } /** * Obtains new NoGoods from grounder and adds them to the NoGoodStore and the heuristics. * @return false iff the set of NoGoods is detected to be unsatisfiable. */ private boolean obtainNoGoodsFromGrounder() { Map<Integer, NoGood> obtained = grounder.getNoGoods(); LOGGER.debug("Obtained NoGoods from grounder: {}", obtained); if (!obtained.isEmpty()) { // Record to detect propagation fixpoint, checking if new NoGoods were reported would be better here. didChange = true; } if (!addAllNoGoodsAndTreatContradictions(obtained)) { return false; } branchingHeuristic.newNoGoods(obtained.values()); // Record choice atoms. final Pair<Map<Integer, Integer>, Map<Integer, Integer>> choiceAtoms = grounder.getChoiceAtoms(); choiceManager.addChoiceInformation(choiceAtoms); return true; } /** * Adds all NoGoods in the given map to the NoGoodStore and treats eventual contradictions. * If the set of NoGoods is unsatisfiable, this method returns false. * @param obtained * @return false iff the new set of NoGoods is detected to be unsatisfiable. */ private boolean addAllNoGoodsAndTreatContradictions(Map<Integer, NoGood> obtained) { LinkedList<Map.Entry<Integer, NoGood>> noGoodsToAdd = new LinkedList<>(obtained.entrySet()); while (!noGoodsToAdd.isEmpty()) { Map.Entry<Integer, NoGood> noGoodEntry = noGoodsToAdd.poll(); NoGoodStore.ConflictCause conflictCause = store.add(noGoodEntry.getKey(), noGoodEntry.getValue()); if (conflictCause == null) { // There is no conflict, all is fine. Just skip conflict treatment and carry on. continue; } LOGGER.debug("Adding obtained NoGoods from grounder violates current assignment: learning, backjumping, and adding again."); if (conflictCause.violatedGuess != null) { LOGGER.debug("Added NoGood {} violates guess {}.", noGoodEntry.getKey(), conflictCause.violatedGuess); LOGGER.debug("Backjumping to decision level: {}", conflictCause.violatedGuess.getDecisionLevel()); doBackjump(conflictCause.violatedGuess.getDecisionLevel()); store.backtrack(); LOGGER.debug("Backtrack: Removing last choice because of conflict with newly added NoGoods, setting decision level to {}.", assignment.getDecisionLevel()); choiceStack.remove(); choiceManager.backtrack(); LOGGER.debug("Backtrack: choice stack size: {}, choice stack: {}", choiceStack.size(), choiceStack); } else { LOGGER.debug("Violated NoGood is {}. Analyzing the conflict.", conflictCause.violatedNoGood); GroundConflictNoGoodLearner.ConflictAnalysisResult conflictAnalysisResult = null; conflictAnalysisResult = learner.analyzeConflictingNoGood(conflictCause.violatedNoGood); if (conflictAnalysisResult.isUnsatisfiable) { // Halt if unsatisfiable. return false; } LOGGER.debug("Backjumping to decision level: {}", conflictAnalysisResult.backjumpLevel); doBackjump(conflictAnalysisResult.backjumpLevel); if (conflictAnalysisResult.clearLastGuessAfterBackjump) { store.backtrack(); LOGGER.debug("Backtrack: Removing last choice because of conflict with newly added NoGoods, setting decision level to {}.", assignment.getDecisionLevel()); choiceStack.remove(); choiceManager.backtrack(); LOGGER.debug("Backtrack: choice stack size: {}, choice stack: {}", choiceStack.size(), choiceStack); } // If NoGood was learned, add it to the store. // Note that the learned NoGood may cause further conflicts, since propagation on lower decision levels is lazy, hence backtracking once might not be enough to remove the real conflict cause. if (conflictAnalysisResult.learnedNoGood != null) { noGoodsToAdd.addFirst(new AbstractMap.SimpleEntry<>(grounder.registerOutsideNoGood(conflictAnalysisResult.learnedNoGood), conflictAnalysisResult.learnedNoGood)); } } if (store.add(noGoodEntry.getKey(), noGoodEntry.getValue()) != null) { throw new RuntimeException("Re-adding of former conflicting NoGood still causes conflicts. This should not happen."); } } return true; } private boolean isSearchSpaceExhausted() { return assignment.getDecisionLevel() == 0; } private boolean propagationFixpointReached() { // Check if anything changed: didChange is updated in places of change. boolean changeCopy = didChange; didChange = false; return !changeCopy; } private void doChoice(int nextChoice) { decisionCounter++; boolean sign = branchingHeuristic.chooseSign(nextChoice); assignment.guess(nextChoice, sign); choiceStack.push(nextChoice, sign); choiceManager.nextDecisionLevel(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Choice: guessing {}={}@{}", grounder.atomToString(nextChoice), sign, assignment.getDecisionLevel()); LOGGER.debug("Choice: stack size: {}, choice stack: {}", choiceStack.size(), choiceStack); LOGGER.debug("Choice: {} choices so far.", decisionCounter); } } private int computeChoice() { // Update ChoiceManager. Iterator<Assignment.Entry> it = assignment.getNewAssignmentsIterator2(); while (it.hasNext()) { choiceManager.updateAssignment(it.next().getAtom()); } // Run Heuristics. int heuristicChoice = branchingHeuristic.chooseAtom(); if (heuristicChoice != 0) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Atom chosen by branching heuristic: {}", grounder.atomToString(heuristicChoice)); } return heuristicChoice; } // TODO: remove fallback as soon as we are sure that BerkMin will always choose an atom LOGGER.debug("Falling back to NaiveHeuristics."); return fallbackBranchingHeuristic.chooseAtom(); } }
package bammerbom.ultimatecore.bukkit; import bammerbom.ultimatecore.bukkit.api.UEconomy; import bammerbom.ultimatecore.bukkit.api.UServer; import bammerbom.ultimatecore.bukkit.commands.CmdHeal; import bammerbom.ultimatecore.bukkit.commands.CmdRules; import bammerbom.ultimatecore.bukkit.listeners.*; import bammerbom.ultimatecore.bukkit.resources.classes.ErrorLogger; import bammerbom.ultimatecore.bukkit.resources.classes.MetaItemStack; import bammerbom.ultimatecore.bukkit.resources.databases.ItemDatabase; import bammerbom.ultimatecore.bukkit.resources.utils.BossbarUtil; import bammerbom.ultimatecore.bukkit.resources.utils.ItemUtil; import bammerbom.ultimatecore.bukkit.resources.utils.PerformanceUtil; import bammerbom.ultimatecore.bukkit.resources.utils.UuidUtil; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; public class UltimateCore extends JavaPlugin { public static File file; private static UltimateCore instance = null; static { r.prestart(); try { r.log("Prestarted Succesfully."); } catch (Exception ex) { ex.printStackTrace(); } } public UltimateCore() { instance = this; } public static UltimateCore getInstance() { return instance; } public static File getPluginFile() { return file; } @Override public void onEnable() { try { Long time = System.currentTimeMillis(); file = getFile(); UltimateFileLoader.Enable(); r.enableMES(); UltimateFileLoader.addConfig(); r.setColors(); UuidUtil.loadPlayers(); UltimateCommands.load(); UltimateSigns.start(); PerformanceUtil.getTps(); BossbarUtil.enable(); ItemDatabase.enable(); if (Bukkit.getPluginManager().isPluginEnabled("Vault")) { UEconomy.start(); } r.start(); UServer.start(); CmdHeal.start(); CmdRules.start(); MetaItemStack.start(); ItemUtil.start(); String c = Bukkit.getServer().getVersion().split("\\(MC: ")[1].split("\\)")[0]; Integer v = Integer.parseInt(c.replace(".", "")); if (v < 18) { Bukkit.getConsoleSender().sendMessage(" "); r.log(ChatColor.DARK_RED + "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); r.log(ChatColor.YELLOW + "Warning! Version " + c + " of craftbukkit is not supported!"); r.log(ChatColor.YELLOW + "Use UltimateCore at your own risk!"); r.log(ChatColor.DARK_RED + "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); Bukkit.getConsoleSender().sendMessage(" "); } UltimateConverter.convert(); r.runUpdater(); r.runMetrics(); PluginManager pm = Bukkit.getPluginManager(); GlobalPlayerListener.start(); pm.registerEvents(new GlobalWorldListener(), this); AfkListener.start(); AutomessageListener.start(); AutosaveListener.start(); BloodListener.start(); ChatListener.start(); DeathmessagesListener.start(); DynmapListener.start(); ExplosionListener.start(); JoinLeaveListener.start(); MotdListener.start(); PluginStealListener.start(); RespawnListener.start(); SignListener.start(); TabListener.start(); TreeListener.start(); UnknownCommandListener.start(); WeatherListener.start(); Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new UltimateTick(), 20L, 20L); time = System.currentTimeMillis() - time; r.log(ChatColor.GREEN + "Enabled Ultimate Core! (" + time + "ms)"); } catch (Exception ex) { ErrorLogger.log(ex, "Failed to enable UltimateCore"); } UltimateWorldLoader.startWorldLoading(); test(); } @Override public void onDisable() { try { Long time = System.currentTimeMillis(); r.removeUC(); ItemDatabase.disable(); BossbarUtil.disable(); DynmapListener.stop(); time = System.currentTimeMillis() - time; r.log(ChatColor.GREEN + "Disabled Ultimate Core! (" + time + "ms)"); } catch (Exception ex) { ErrorLogger.log(ex, "Failed to disable UltimateCore"); } } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { try { UltimateCommands.onCmd(sender, cmd, label, args); } catch (Exception ex) { ErrorLogger.log(ex, "Failed to execute command: /" + label + " " + r.getFinalArg(args, 0)); } return true; } public void test() { } }
package ch.openech.frontend.e10; import org.minimalj.frontend.action.Action; import org.minimalj.frontend.form.Form; import org.minimalj.frontend.form.element.ObjectFormElement; import org.minimalj.model.Keys; import org.minimalj.model.properties.PropertyInterface; import org.minimalj.util.mock.Mocking; import ch.openech.datagenerator.DataGenerator; import ch.openech.model.common.Address; public class AddressFormElement extends ObjectFormElement<Address> implements Mocking { private final boolean swiss; private final boolean person; private final boolean organisation; public AddressFormElement(Address key, boolean editable) { this(Keys.getProperty(key), editable, false, false, false); } public AddressFormElement(PropertyInterface property, boolean editable) { this(property, editable, false, false, false); } public AddressFormElement(Address key, boolean swiss, boolean person, boolean organisation) { this(Keys.getProperty(key), swiss, person, organisation); } public AddressFormElement(PropertyInterface property, boolean swiss, boolean person, boolean organisation) { this(property, true, swiss, person, organisation); } public AddressFormElement(PropertyInterface property, boolean editable, boolean swiss, boolean person, boolean organisation) { super(property, editable); this.swiss = swiss; this.person = person; this.organisation = organisation; } public Form<Address> createEditFrame() { return new AddressPanel(swiss, person, organisation); } @Override public void mock() { setValue(DataGenerator.address(true, true, false)); } @Override public Form<Address> createForm() { return new AddressPanel(swiss, person, organisation); } @Override protected Action[] getActions() { return new Action[] { getEditorAction() }; } @Override public void show(Address address) { boolean removeable = !getProperty().isFinal(); if (isEditable() && removeable) { add(address, new RemoveObjectAction()); } else { add(address); } } }
package sbmlplugin.pane; import ij.gui.GenericDialog; import java.util.Arrays; import org.sbml.libsbml.BoundaryCondition; import org.sbml.libsbml.Model; import org.sbml.libsbml.Parameter; import org.sbml.libsbml.SpatialParameterPlugin; import org.sbml.libsbml.libsbmlConstants; /** * Spatial SBML Plugin for ImageJ * @author Kaito Ii <ii@fun.bio.keio.ac.jp> * @author Akira Funahashi <funa@bio.keio.ac.jp> * Date Created: Jan 21, 2016 */ public class BoundaryConditionDialog { private Parameter parameter; private GenericDialog gd; private final String[] bool = {"true","false"}; private Model model; public BoundaryConditionDialog(Model model){ this.model = model; } public Parameter showDialog(){ gd = new GenericDialog("Add Boundary Condition"); gd.setResizable(true); gd.pack(); gd.addStringField("id:", ""); gd.addNumericField("value:", 0, 1); gd.addRadioButtonGroup("constant:", bool, 1, 2, "true"); gd.addChoice("species:", SBMLProcessUtil.listIdToStringArray(model.getListOfSpecies()), null); gd.addChoice("type:", SBMLProcessUtil.boundType, null); gd.addChoice("boundary:", getAllBoundAsString(), null); gd.showDialog(); if(gd.wasCanceled()) return null; parameter = model.createParameter(); setParameterData(); return parameter; } public Parameter showDialog(Parameter parameter){ this.parameter = parameter; SpatialParameterPlugin sp = (SpatialParameterPlugin) parameter.getPlugin("spatial"); BoundaryCondition bc = sp.getBoundaryCondition(); gd = new GenericDialog("Edit Parameter"); gd.setResizable(true); gd.pack(); gd.addStringField("id:", parameter.getId()); gd.addNumericField("value:", parameter.getValue(), 1); gd.addRadioButtonGroup("constant:", bool, 1, 2, String.valueOf(parameter.getConstant())); gd.addChoice("species:", SBMLProcessUtil.listIdToStringArray(model.getListOfSpecies()), bc.getVariable()); gd.addChoice("type:", SBMLProcessUtil.boundType, SBMLProcessUtil.boundaryIndexToString(bc.getType())); gd.addChoice("boundary:", getAllBoundAsString(), bc.isSetCoordinateBoundary() ? bc.getCoordinateBoundary(): bc.getBoundaryDomainType()); gd.showDialog(); if(gd.wasCanceled()) return null; setParameterData(); return parameter; } private void setParameterData(){ String str = gd.getNextString(); if (str.indexOf(' ')!=-1) str = str.replace(' ', '_'); parameter.setId(str); parameter.setValue(gd.getNextNumber()); parameter.setConstant(Boolean.getBoolean(gd.getNextRadioButton())); SpatialParameterPlugin sp = (SpatialParameterPlugin) parameter.getPlugin("spatial"); BoundaryCondition bc = sp.isSetBoundaryCondition() ? sp.getBoundaryCondition() : sp.createBoundaryCondition(); bc.setVariable(gd.getNextChoice()); bc.setType(gd.getNextChoice()); String bound = gd.getNextChoice(); if(Arrays.asList(SBMLProcessUtil.bounds).contains(bound)) bc.setCoordinateBoundary(bound); else bc.setBoundaryDomainType(bound); System.out.println(bc.toSBML()); } private String[] getAllBoundAsString(){ String[] bound = SBMLProcessUtil.bounds; String[] compartment = SBMLProcessUtil.listIdToStringArray(model.getListOfCompartments()); String[] str = new String[bound.length + compartment.length]; System.arraycopy(bound, 0, str, 0, bound.length); System.arraycopy(compartment, 0, str, bound.length, compartment.length); return str; } }
package com.amee.platform.search; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.NumericRangeQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.util.NumericUtils; import org.apache.lucene.util.Version; import java.beans.PropertyEditorSupport; public class QueryParserEditor extends PropertyEditorSupport { private String field; private Analyzer analyzer; private boolean doubleValue; public QueryParserEditor(String field) { setField(field); setAnalyzer(SearchService.STANDARD_ANALYZER); setDoubleValue(false); } public QueryParserEditor(String field, Analyzer analyzer) { setField(field); setAnalyzer(analyzer); setDoubleValue(false); } public QueryParserEditor(String field, Analyzer analyzer, boolean doubleValue) { setField(field); setAnalyzer(analyzer); setDoubleValue(doubleValue); } /** * A factory method to return a tag specific implementation of QueryParserEditor. Uses SearchService.TAG_ANALYZER * and a custom implementation of getModifiedText to replace commas with spaces (to avoid confusing Lucene). * * @param field * @return */ public static QueryParserEditor getTagQueryParserEditor(String field) { return new QueryParserEditor(field, SearchService.TAG_ANALYZER) { public String getModifiedText(String text) { return text.replace(',', ' '); } }; } @Override public void setAsText(String text) { if (text != null) { try { QueryParser parser = getQueryParser(); setValue(parser.parse(getModifiedText(text))); } catch (ParseException e) { throw new IllegalArgumentException("Cannot parse query (" + e.getMessage() + ").", e); } } else { setValue(null); } } private QueryParser getQueryParser() { return new QueryParser(Version.LUCENE_30, getField(), getAnalyzer()) { // TODO: is getField meant to resolve to this.getField or super.getField? // Added super as this is how java was resolving the unqualified method call. // See: http://findbugs.sourceforge.net/bugDescriptions.html#IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD protected Query newTermQuery(Term term) { if (isDoubleValue()) { try { return new TermQuery(new Term(super.getField(), NumericUtils.doubleToPrefixCoded(Double.parseDouble(term.text())))); } catch (NumberFormatException e) { throw new IllegalArgumentException("Cannot parse query (" + e.getMessage() + ").", e); } } else { return super.newTermQuery(term); } } // TODO: is getField meant to resolve to this.getField or super.getField? // Added super as this is how java was resolving the unqualified method call. // See: http://findbugs.sourceforge.net/bugDescriptions.html#IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD protected Query newRangeQuery(String field, String part1, String part2, boolean inclusive) { if (isDoubleValue()) { try { final NumericRangeQuery query = NumericRangeQuery.newDoubleRange( super.getField(), Double.parseDouble(part1), Double.parseDouble(part2), inclusive, inclusive); query.setRewriteMethod(super.getMultiTermRewriteMethod()); return query; } catch (NumberFormatException e) { throw new IllegalArgumentException("Cannot parse query (" + e.getMessage() + ").", e); } } else { return super.newRangeQuery(field, part1, part2, inclusive); } } }; } /** * Extension point to allow the text to be modified before it is parsed by the QueryParser. The default * implementation simply returns the text unmodified. * * @param text to be modified * @return text following modification. */ public String getModifiedText(String text) { return text; } public String getField() { return field; } public void setField(String field) { this.field = field; } public Analyzer getAnalyzer() { return analyzer; } public void setAnalyzer(Analyzer analyzer) { this.analyzer = analyzer; } public boolean isDoubleValue() { return doubleValue; } public void setDoubleValue(boolean doubleValue) { this.doubleValue = doubleValue; } }
package com.apm4all.tracy.backend; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.camel.Body; import org.apache.camel.Header; import org.apache.camel.Headers; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.filters.Filters; import org.elasticsearch.search.aggregations.bucket.filters.Filters.Bucket; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogram; import org.elasticsearch.search.aggregations.metrics.stats.Stats; import org.elasticsearch.search.aggregations.metrics.percentiles.Percentile; import org.elasticsearch.search.aggregations.metrics.percentiles.Percentiles; import com.apm4all.tracy.apimodel.LatencyHistogram; import com.apm4all.tracy.apimodel.SingleApdexTimechart; import com.apm4all.tracy.apimodel.TaskConfig; import com.apm4all.tracy.apimodel.TaskMeasurement; import com.apm4all.tracy.apimodel.VitalsTimechart; import com.apm4all.tracy.util.LatencyHistogramRows; import com.apm4all.tracy.util.LatencyHistogramRows.LatencyHistogramRow; import com.apm4all.tracy.util.TimeFrame; public class EsQueryProcessor { public static final String APPLICATION = "application"; public static final String TASK = "task"; public static final String TASK_CONFIG = "taskConfig"; public static final String TIME_FRAME = "timeFrame"; public static final String EARLIEST = "earliest"; public static final String LATEST = "latest"; public static final String SNAP = "snap"; public static final String TASK_MEASUREMENT = "taskMeasurement"; public void initMeasurement(@Headers Map<String, Object> headers, @Header(APPLICATION) String application, @Header(TASK) String task, @Header(TASK_CONFIG) TaskConfig taskConfig, @Header(EARLIEST) String earliest, @Header(LATEST) String latest, @Header(SNAP) String snap) { // FIXME: A valid config must be supplied at this point if (taskConfig == null) { taskConfig = new TaskConfig(); headers.put(TASK_CONFIG, taskConfig); } // Get earliest, latest and snap if provided headers.put(TIME_FRAME, new TimeFrame(earliest, latest, snap, taskConfig)); // Setup RetrievedTaskMeasurement TaskMeasurement taskMeasurement = new RetrievedTaskMeasurement(taskConfig.getApplication(), taskConfig.getTask()); headers.put(TASK_MEASUREMENT, taskMeasurement); SingleApdexTimechart singleApdexTimechart = taskMeasurement.getSingleApdexTimechart(); singleApdexTimechart.setApplication(application); singleApdexTimechart.setTask(task); singleApdexTimechart.setRttF(taskConfig.getMeasurement().getRttFrustrated()); singleApdexTimechart.setRttT(taskConfig.getMeasurement().getRttTolerating()); singleApdexTimechart.setRttUnit(taskConfig.getMeasurement().getRttUnit()); } public XContentBuilder buildOverviewSearchRequest( @Header(TASK_CONFIG) TaskConfig taskConfig, @Header(TIME_FRAME) TimeFrame timeFrame) throws IOException { // "bool" Restrict results by time range and match criteria long earliest = timeFrame.getEarliest(); long latest = timeFrame.getLatest(); int rttTolerating = taskConfig.getMeasurement().getRttTolerating(); int rttFrustrated = taskConfig.getMeasurement().getRttFrustrated(); String taskDefiningFilter = taskConfig.getDefiningFilter(); BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery() // TODO: For improved performance, filtering should be done at index level as well to avoid accessing unnecessary indexes .must(QueryBuilders.rangeQuery("@timestamp").gt(earliest).lt(latest)) .must(QueryBuilders.queryStringQuery(taskDefiningFilter)); // "aggs" date histogram aggregation @SuppressWarnings("rawtypes") AggregationBuilder aggregationBuilder = AggregationBuilders .dateHistogram("timeBuckets") .field("@timestamp") .interval(DateHistogram.Interval.MINUTE) // min_doc_count does not seem to work with DateHistogram. .minDocCount(0) .subAggregation( AggregationBuilders .filters("counters") .filter("invocations", FilterBuilders.queryFilter(QueryBuilders.simpleQueryStringQuery(taskDefiningFilter))) .filter("success", FilterBuilders.rangeFilter("status").lt(500)) .filter("errors", FilterBuilders.rangeFilter("status").gte(500)) .filter("satisfied", FilterBuilders.andFilter( FilterBuilders.rangeFilter("status").lt(500), FilterBuilders.rangeFilter("msecElapsed").lt(rttTolerating))) .filter("tolerating", FilterBuilders.andFilter( FilterBuilders.rangeFilter("status").lt(500), FilterBuilders.rangeFilter("msecElapsed").gt(rttTolerating).lt(rttFrustrated))) .filter("frustrated", FilterBuilders.andFilter( FilterBuilders.rangeFilter("status").lt(500), FilterBuilders.rangeFilter("msecElapsed").gt(rttFrustrated))) ); XContentBuilder contentBuilder = XContentFactory.jsonBuilder().startObject().field("query"); queryBuilder.toXContent(contentBuilder, null); contentBuilder.startObject("aggs"); aggregationBuilder.toXContent(contentBuilder, null); contentBuilder.endObject(); contentBuilder.field("size", 0); contentBuilder.endObject(); return contentBuilder; } private Double round(double number, int digits) { BigDecimal bd = new BigDecimal(number); bd = bd.setScale(digits, RoundingMode.HALF_UP); return bd.doubleValue(); } private Double calculateApdexScore(long invocations, long satisfied, long tolerating) { Double apdexScore; if(invocations == 0) { throw new ArithmeticException("Division by zero!"); } apdexScore = (double) (((double)satisfied + ((double)tolerating/2)) / (double)invocations); System.out.println("apdex: " + apdexScore + ", invocations " + invocations + ", satisfied " + satisfied + ", tolerating " + tolerating); return round(apdexScore, 2); } public TaskMeasurement handleOverviewSearchResponse( @Header(TASK_CONFIG) TaskConfig taskConfig, @Header(TIME_FRAME) TimeFrame timeFrame, @Header(TASK_MEASUREMENT) TaskMeasurement taskMeasurement, @Body SearchResponse searchResponse) { DateHistogram agg = searchResponse.getAggregations().get("timeBuckets"); // TODO: Iterate through each time bucket List<Long> apdexTimeSequence = new ArrayList<Long>(); List<Long> vitalsTimeSequence = new ArrayList<Long>(); List<Integer> vitalsCount = new ArrayList<Integer>(); List<Integer> vitalsErrors = new ArrayList<Integer>(); List<Double> apdexScores = new ArrayList<Double>(); for (long time=timeFrame.getEarliest() ; time < timeFrame.getLatest() ; time = time+timeFrame.getSnap()) { DateHistogram.Bucket histogramBucket = agg.getBucketByKey(time); long invocations = 0; long errors = 0; if (histogramBucket != null) { // If ES response contains this time bucket, populate from ES Filters f = histogramBucket.getAggregations().get("counters"); long satisfied = f.getBucketByKey("satisfied").getDocCount(); long tolerating = f.getBucketByKey("tolerating").getDocCount(); invocations = f.getBucketByKey("invocations").getDocCount(); errors = f.getBucketByKey("errors").getDocCount(); try { Double apdexScore = calculateApdexScore(invocations, satisfied, tolerating); apdexTimeSequence.add(time); apdexScores.add(apdexScore); System.out.println("+++ TIME: " + time + ", apdex: " + apdexScore + ", invocations " + invocations + ", satisfied " + satisfied + ", tolerating " + tolerating); } catch (ArithmeticException e) { } } else { // When handling response need to fill-in for empty (not returned) buckets // min_doc_count does not seem to work with DateHistogram. System.out.println("--- TIME: " + time); } vitalsTimeSequence.add(time); vitalsErrors.add((int) errors); vitalsCount.add((int) invocations); } for (DateHistogram.Bucket entry : agg.getBuckets()) { String key = entry.getKey(); // Key Number nkey = entry.getKeyAsNumber(); Filters f = entry.getAggregations().get("counters"); for (Filters.Bucket bucket : f.getBuckets()) { System.out.println( "key [" + key + "], " + "epoch [" + nkey.longValue() + "], " + bucket.getKey() + " [" + bucket.getDocCount() + "]"); } } // Populate SingleApdexTimechart: timeSequence, apdexScores SingleApdexTimechart singleApdexTimechart = taskMeasurement.getSingleApdexTimechart(); singleApdexTimechart.setTimeSequence(apdexTimeSequence); singleApdexTimechart.setApdexScores(apdexScores); // Populate VitalsTimeChart: timeSequence, count, errors (skip p95 and max) VitalsTimechart vitalsTimeChart = taskMeasurement.getVitalsTimechart(); vitalsTimeChart.setTimeSequence(vitalsTimeSequence); vitalsTimeChart.setCount(vitalsCount); vitalsTimeChart.setErrors(vitalsErrors); return taskMeasurement; } public XContentBuilder buildSuccessStatsSearchRequest( @Header(TASK_CONFIG) TaskConfig taskConfig, @Header(TIME_FRAME) TimeFrame timeFrame) throws IOException { // "bool" Restrict results by time range and match criteria long earliest = timeFrame.getEarliest(); long latest = timeFrame.getLatest(); int rttTolerating = taskConfig.getMeasurement().getRttTolerating(); int rttFrustrated = taskConfig.getMeasurement().getRttFrustrated(); String taskDefiningFilter = taskConfig.getDefiningFilter(); BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery() // TODO: For improved performance, filtering should be done at index level as well to avoid accessing unnecessary indexes .must(QueryBuilders.rangeQuery("@timestamp").gt(earliest).lt(latest)) .must(QueryBuilders.queryStringQuery(taskDefiningFilter)); // "aggs" date histogram aggregation @SuppressWarnings("rawtypes") AggregationBuilder aggregationBuilder = AggregationBuilders .dateHistogram("timeBuckets") .field("@timestamp") .interval(DateHistogram.Interval.MINUTE) // min_doc_count does not seem to work with DateHistogram. .minDocCount(0) .subAggregation( AggregationBuilders .filters("counters") .filter("success", FilterBuilders.rangeFilter("status").lt(500)) .subAggregation(AggregationBuilders .percentiles("percentiles") .field("msecElapsed") .percentiles(50.0, 95.0, 99.0)) .subAggregation(AggregationBuilders .stats("stats") .field("msecElapsed")) .subAggregation(AggregationBuilders .filters("latencyHistogram") .filter("0-100", FilterBuilders.rangeFilter("msecElapsed").gt(0).lte(100)) .filter("100-200", FilterBuilders.rangeFilter("msecElapsed").gt(100).lte(200)) .filter("200-300", FilterBuilders.rangeFilter("msecElapsed").gt(200).lte(300)) .filter("300-400", FilterBuilders.rangeFilter("msecElapsed").gt(300).lte(400)) .filter("400-500", FilterBuilders.rangeFilter("msecElapsed").gt(400).lte(500)) .filter("500-600", FilterBuilders.rangeFilter("msecElapsed").gt(600).lte(600)) .filter("600-700", FilterBuilders.rangeFilter("msecElapsed").gt(600).lte(700)) .filter("700-800", FilterBuilders.rangeFilter("msecElapsed").gt(700).lte(800)) .filter(">800", FilterBuilders.rangeFilter("msecElapsed").gt(800)) )); // TODO: Populate latencyHistogramFilters // LatencyHistogramRows latencyHistogramRows = new LatencyHistogramRows( // taskConfig.getMeasurement().getRttTolerating(), // taskConfig.getMeasurement().getRttFrustrated()); // for (LatencyHistogramRow row : latencyHistogramRows.asList()) { // Sort by latency descending // // TODO: create filter using // if (row.getUpperLimit != null) { // .filter(row.getLabel()), FilterBuilders.rangeFilter("msecElapsed").gt(row.getLowerLimit()).lte(row.getUpperLimit())); // else { // .filter(row.getLabel()), FilterBuilders.rangeFilter("msecElapsed").gt(row.getLowerLimit())); // row. // System.out.println("latencyHistogram [" + row.getLabel() // 0-100 // + "], value [" + latencyHistogram.getBucketByKey(row.getLabel()).getDocCount() + "]"); XContentBuilder contentBuilder = XContentFactory.jsonBuilder().startObject().field("query"); queryBuilder.toXContent(contentBuilder, null); contentBuilder.startObject("aggs"); aggregationBuilder.toXContent(contentBuilder, null); contentBuilder.endObject(); contentBuilder.field("size", 0); contentBuilder.endObject(); // System.out.println(contentBuilder.string()); return contentBuilder; } public TaskMeasurement handleSucessStatsSearchResponse( @Header(TASK_CONFIG) TaskConfig taskConfig, @Header(TIME_FRAME) TimeFrame timeFrame, @Header(TASK_MEASUREMENT) TaskMeasurement taskMeasurement, @Body SearchResponse searchResponse) { // Vitals data ArrayList<Double> p95 = new ArrayList<Double>(); ArrayList<Double> max = new ArrayList<Double>(); // LatencyHistogram data ArrayList<String> bins = new ArrayList<String>(); ArrayList<String> rttZone = new ArrayList<String>(); ArrayList<Integer> count = new ArrayList<Integer>(); LatencyHistogramRows latencyHistogramRows = new LatencyHistogramRows( taskConfig.getMeasurement().getRttTolerating(), taskConfig.getMeasurement().getRttFrustrated()); for (LatencyHistogramRow row : latencyHistogramRows.asList()) { bins.add(row.getLabel()); rttZone.add(row.getRttZone()); count.add(0); } DateHistogram agg = searchResponse.getAggregations().get("timeBuckets"); for (long time=timeFrame.getEarliest() ; time < timeFrame.getLatest() ; time = time+timeFrame.getSnap()) { DateHistogram.Bucket histogramBucket = agg.getBucketByKey(time); if (histogramBucket != null) { // If ES response contains this time bucket, populate from ES Filters counters = histogramBucket.getAggregations().get("counters"); Bucket satisfiedBucket = counters.getBucketByKey("success"); Stats stats = satisfiedBucket.getAggregations().get("stats"); // Populate Max System.out.println("Max [" + stats.getMax() + "]"); max.add(round(stats.getMax(),0)); Percentiles percentiles = satisfiedBucket.getAggregations().get("percentiles"); for (Percentile entry : percentiles) { double percent = entry.getPercent(); // Percent if (percent == 95.0) { // Populate p95 double value = entry.getValue(); // Value System.out.println("percent [" + percent + "], value [" + value + "]"); p95.add(round(value,0)); } } Filters latencyHistogram = satisfiedBucket.getAggregations().get("latencyHistogram"); // Populate latencyHistogram int i = 0; for (LatencyHistogramRow row : latencyHistogramRows.asList()) { // Sort by latency descending // latency histogram count int binCount = count.get(i); binCount = (int) (Integer.valueOf(binCount) + latencyHistogram.getBucketByKey(row.getLabel()).getDocCount()); count.set(i, binCount); i++; System.out.println("latencyHistogram [" + row.getLabel() // 0-100 + "], value [" + latencyHistogram.getBucketByKey(row.getLabel()).getDocCount() + "]"); } } else { p95.add(null); max.add(null); } } // Add VitalsTimechart data VitalsTimechart vitalsTimechart = taskMeasurement.getVitalsTimechart(); vitalsTimechart.setMax(max); vitalsTimechart.setP95(p95); // Add LatencyHistogram data LatencyHistogram latencyHistogram = taskMeasurement.getLatencyHistogram(); latencyHistogram.setBins(bins); latencyHistogram.setCount(count); latencyHistogram.setRttZone(rttZone); return taskMeasurement; } }