answer
stringlengths
17
10.2M
package edu.umn.cs.spatialHadoop.mapReduce; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Vector; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapred.FileSplit; import org.apache.hadoop.mapred.InputSplit; public class PairOfFileSplits extends PairWritable<FileSplit> implements InputSplit { public PairOfFileSplits() { first = new FileSplit(new Path("/"), 0, 0, new String[] {}); second = new FileSplit(new Path("/"), 0, 0, new String[] {}); } public PairOfFileSplits(FileSplit first, FileSplit second) { super(first, second); } public long getLength() throws IOException { return first.getLength() + second.getLength(); } public String[] getLocations() throws IOException { Map<String, Integer> locationFrequency = new HashMap<String, Integer>(); Vector<String> locations = new Vector<String>(); for (String location : first.getLocations()) { if (!locations.contains(location)) locations.add(location); if (locationFrequency.containsKey(location)) { locationFrequency.put(location, locationFrequency.get(location) + 1); } else { locationFrequency.put(location, 1); } } for (String location : second.getLocations()) { if (!locations.contains(location)) locations.add(location); if (locationFrequency.containsKey(location)) { locationFrequency.put(location, locationFrequency.get(location) + 1); } else { locationFrequency.put(location, 1); } } // Order by frequency to move location with may frequencies to the front for (int i = 0; i < locations.size(); i++) { for (int j = 0; j < locations.size() - i - 1; j++) { if (locationFrequency.get(locations.elementAt(j)) < locationFrequency.get(locations.elementAt(j+1))) { String temp = locations.elementAt(j); locations.set(j, locations.elementAt(j+1)); locations.set(j+1, temp); } } } return locations.toArray(new String[locations.size()]); } }
package edu.jhu.thrax.hadoop.tools; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.reduce.IntSumReducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.NullWritable; import edu.jhu.thrax.ThraxConfig; import edu.jhu.thrax.util.ConfFileParser; import edu.jhu.thrax.hadoop.datatypes.RuleWritable; import edu.jhu.thrax.hadoop.features.Feature; import edu.jhu.thrax.hadoop.features.MapReduceFeature; import edu.jhu.thrax.hadoop.features.FeatureFactory; import edu.jhu.thrax.hadoop.output.OutputMapper; import edu.jhu.thrax.hadoop.output.OutputReducer; import java.util.Map; public class OutputTool extends Configured implements Tool { public int run(String [] argv) throws Exception { if (argv.length < 1) { System.err.println("usage: OutputTool <conf file>"); return 1; } String confFile = argv[0]; Map<String,String> options = ConfFileParser.parse(confFile); Configuration conf = getConf(); for (String opt : options.keySet()) { conf.set("thrax." + opt, options.get(opt)); } String workDir = conf.get("thrax.work-dir"); if (workDir == null) { System.err.println("Set work-dir key in conf file " + confFile + "!"); return 1; } if (!workDir.endsWith(Path.SEPARATOR)) { workDir += Path.SEPARATOR; conf.set("thrax.work-dir", workDir); } Job job = new Job(conf, "thrax-collect"); job.setJarByClass(OutputMapper.class); job.setMapperClass(OutputMapper.class); job.setReducerClass(OutputReducer.class); job.setInputFormatClass(SequenceFileInputFormat.class); job.setMapOutputKeyClass(RuleWritable.class); job.setMapOutputValueClass(NullWritable.class); job.setOutputKeyClass(RuleWritable.class); job.setOutputValueClass(NullWritable.class); for (String feature : conf.get("thrax.features", "").split("\\s+")) { if (FeatureFactory.get(feature) instanceof MapReduceFeature) { FileInputFormat.addInputPath(job, new Path(workDir + feature)); } } if (FileInputFormat.getInputPaths(job).length == 0) FileInputFormat.addInputPath(job, new Path(workDir + "rules")); FileOutputFormat.setOutputPath(job, new Path(workDir + "final")); job.submit(); return 0; } public static void main(String [] argv) throws Exception { int exitCode = ToolRunner.run(null, new OutputTool(), argv); return; } }
package edu.yalestc.yalepublic.Events; import android.app.Activity; import android.app.usage.UsageEvents; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.concurrent.ExecutionException; import edu.yalestc.yalepublic.Cache.CalendarCache; import edu.yalestc.yalepublic.R; public class EventsAdapterForLists extends BaseAdapter { protected int mYear; //month here is in the standard format protected int mMonth; //for inflating layouts and displaymetrics and checking for cached DisplayMetrics display; protected Activity mActivity; protected int height; protected int width; //for quicker parsing of events. Is passed in from MonthFragment. See EventsParseForDateWithinCategory for more information //if allTheEvents is null, it means that we are using cached information! protected EventsParseForDateWithinCategory allTheEvents; //workaround for now. There is a discrepancy between how EventsParseForDateWithinCategory and db work... protected int mCategoryNo; //for ovals next to time protected int[] mColors; protected int[] mColorsFrom; private BaseAdapter mAdapter; //if we want to have a class that inherits, does not manage everything for us, but still //gives access to all those functions protected EventsAdapterForLists(Activity activity) { mActivity = activity; display = mActivity.getResources().getDisplayMetrics(); height = display.heightPixels; width = display.widthPixels; } protected EventsAdapterForLists(Activity activity, int year, int month, int category, int[] colors, int colorsFrom[]) { mActivity = activity; allTheEvents = null; mCategoryNo = category; update(year, month); mColors = colors; mColorsFrom = colorsFrom; display = mActivity.getResources().getDisplayMetrics(); height = display.heightPixels; width = display.widthPixels; } protected void setCallbackAdapter(BaseAdapter adapter) { mAdapter = adapter; } @Override public int getCount() { return 0; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { return null; } //called from EventsJSONReader after new data has been downloaded and is ready to be parsed. public void updateEvents(String rawData) { //allTheEvents is null as of the constructor, so need to check if it is the first time that //we need to parse any data. if (allTheEvents != null) { //the parser accepts the calendar-formatted date! allTheEvents.setNewEvents(rawData, mMonth - 1, mYear); } else { //the constructor by default takes in data to parse, so no need to call setNewEvents allTheEvents = new EventsParseForDateWithinCategory(rawData, mMonth - 1, mYear, mActivity, mCategoryNo); } mAdapter.notifyDataSetChanged(); } //set the new month and year, then pull the data from internet if needed. The AsyncTask //then calls updateEvents once it is done, so there is no need to call it at all. public void update(int year, int month) { updateMonthYear(year, month); if (!CalendarCache.isCached(mActivity, mMonth, mYear)) { pullDataFromInternet(); } } //sets new values to mMonth and mYear public void updateMonthYear(int year, int month) { mYear = year; //because calendar operates on 0 - 11 mMonth = month + 1; } protected void pullDataFromInternet() { String dateSearched = DateFormater.calendarDateToJSONQuery(mYear, mMonth - 1); EventsJSONReader newData = new EventsJSONReader("http://calendar.yale.edu/feeds/feed/opa/json/" + dateSearched + "/30days", mActivity); newData.setAdapter(this); Log.i("EventsCalendarEventList", "Pulling uncached data using query http://calendar.yale.edu/feeds/feed/opa/json/" + dateSearched + "/30days"); newData.execute(); } //make the little blob next to events name etc. protected GradientDrawable createBlob(int color, int colorFrom) { int[] colors = new int[]{colorFrom, color}; GradientDrawable blob = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors); blob.setShape(GradientDrawable.OVAL); blob.setSize(40, 40); blob.setGradientType(GradientDrawable.RADIAL_GRADIENT); blob.setGradientRadius(30); blob.setGradientCenter((float) 0.5, (float) 0.0); return blob; } protected View createNewEventElement(String[] information, GradientDrawable circle) { RelativeLayout eventListElement = (RelativeLayout) LayoutInflater.from(mActivity).inflate(R.layout.calendar_list_element, null); eventListElement.setMinimumHeight((int) (height * 0.104)); ((ImageView) eventListElement.getChildAt(0)).setImageDrawable(circle); //set the size of the time element ((TextView) eventListElement.getChildAt((1))).setMinWidth(width / 5); //set the time of the event ((TextView) eventListElement.getChildAt(1)).setText(information[1]); //set the title of the event ((TextView) eventListElement.getChildAt(2)).setText(information[0]); //set the palce of the event ((TextView) eventListElement.getChildAt(3)).setText(information[3]); eventListElement.setBackgroundColor(Color.parseColor("#dbdbdd")); return eventListElement; } protected View recycleView(RelativeLayout convertView, String[] information, GradientDrawable circle) { ((ImageView) convertView.getChildAt(0)).setImageDrawable(circle); //set the time of the event ((TextView) convertView.getChildAt(1)).setText(information[1]); //set the title of the event ((TextView) convertView.getChildAt(2)).setText(information[0]); //set the place of the event ((TextView) convertView.getChildAt(3)).setText(information[3]); return convertView; } }
package edu.kit.mindstormer.movement; import edu.kit.mindstormer.Constants; import edu.kit.mindstormer.sensor.Sensor; import lejos.hardware.BrickFinder; import lejos.hardware.motor.EV3LargeRegulatedMotor; import lejos.hardware.motor.EV3MediumRegulatedMotor; import lejos.robotics.RegulatedMotor; import lejos.utility.Delay; public final class Movement { protected final static RegulatedMotor leftMotor = new EV3LargeRegulatedMotor( BrickFinder.getDefault().getPort("D")); protected final static RegulatedMotor rightMotor = new EV3LargeRegulatedMotor( BrickFinder.getDefault().getPort("A")); protected final static RegulatedMotor sensorMotor = new EV3MediumRegulatedMotor( BrickFinder.getDefault().getPort("B")); protected final static MotorListener motorListener = new MotorListener(); private Movement() { }; public static void init() { leftMotor.setAcceleration(Constants.ACCELERATION); rightMotor.setAcceleration(Constants.ACCELERATION); leftMotor.addListener(motorListener); rightMotor.addListener(motorListener); sensorMotor.addListener(motorListener); leftMotor.synchronizeWith(new RegulatedMotor[] { rightMotor }); sensorMotor.setSpeed(Constants.SENSOR_MOTOR_SPEED); } public static void moveLeft(float centimeterPerSecond) { leftMotor.setSpeed(cmPerSecondToSpeed(centimeterPerSecond)); setMode(Wheel.LEFT, centimeterPerSecond); } public static void moveRight(float centimeterPerSecond) { rightMotor.setSpeed(cmPerSecondToSpeed(centimeterPerSecond)); setMode(Wheel.RIGHT, centimeterPerSecond); } public static void move(float centimeterPerSecond) { leftMotor.startSynchronization(); moveLeft(centimeterPerSecond); moveRight(centimeterPerSecond); leftMotor.endSynchronization(); } public static void moveLeft(int angle, float centimeterPerSecond) { leftMotor.setSpeed(cmPerSecondToSpeed(centimeterPerSecond)); leftMotor.rotate(angle, true); } public static void moveRight(int angle, float centimeterPerSecond) { rightMotor.setSpeed(cmPerSecondToSpeed(centimeterPerSecond)); rightMotor.rotate(angle, true); } public static void move(int leftCentimeterPerSecond, float rightCentimeterPerSecond) { leftMotor.startSynchronization(); moveLeft(leftCentimeterPerSecond); moveRight(rightCentimeterPerSecond); leftMotor.endSynchronization(); } public static void stop() { leftMotor.startSynchronization(); stopRight(); stopLeft(); leftMotor.endSynchronization(); } public static void stopLeft() { leftMotor.stop(); } public static void stopRight() { rightMotor.stop(); } private static float setMode(Wheel wheel, float leftCentimeterPerSecond) { if (leftCentimeterPerSecond > 0) { setMode(wheel, Mode.FORWARD); } else if (leftCentimeterPerSecond < 0) { setMode(wheel, Mode.BACKWARD); } else { setMode(wheel, Mode.STOP); } return Math.abs(leftCentimeterPerSecond); } private static void setMode(Wheel wheel, Mode mode) { RegulatedMotor selectedWheel = (wheel == Wheel.LEFT) ? leftMotor : rightMotor; if (Mode.FORWARD == mode) { selectedWheel.forward(); } else if (Mode.BACKWARD == mode) { selectedWheel.backward(); } else if (Mode.STOP == mode) { selectedWheel.stop(); } } public static void rotate(float angle, float centimeterPerSecond) { int motorAngle = getMotorAngleForRotation(angle, true); leftMotor.startSynchronization(); moveLeft(motorAngle, cmPerSecondToSpeed(centimeterPerSecond) / 2); moveRight(-motorAngle, cmPerSecondToSpeed(centimeterPerSecond) / 2); leftMotor.endSynchronization(); } public static void rotateLeft(float angle, float centimeterPerSecond) { int motorAngle = getMotorAngleForRotation(angle, false); moveLeft(motorAngle, centimeterPerSecond); } public static void rotateRight(float angle, float centimeterPerSecond) { int motorAngle = getMotorAngleForRotation(angle, false); moveRight(motorAngle, centimeterPerSecond); } private static int getMotorAngleForRotation(float angle, boolean bothWheels) { return Math.round(Constants.VEHICLE_ANGLE_TO_MOTOR_ANGLE * angle * (bothWheels ? 0.5f : 1)); } private static int getMotorAngleForDistance(float distance) { return Math.round(Constants.CM_TO_MOTOR_ANGLE * distance); } private static int cmPerSecondToSpeed(float centimeterPerSecond) { return Math.round(Constants.CM_TO_MOTOR_ANGLE * centimeterPerSecond); } public static void moveDistance(float distance, float centimeterPerSecond) { int motorAngle = getMotorAngleForDistance(distance); leftMotor.startSynchronization(); moveLeft(motorAngle, centimeterPerSecond); moveRight(motorAngle, centimeterPerSecond); leftMotor.endSynchronization(); } public static void rotateSensorMotor(int angle) { sensorMotor.rotate(Math.round(Constants.SENSOR_ANGLE_TO_MOTOR_ANGLE * angle), true); } public static void moveParallel(float centimeterPerSecond, float distance) { float sampleDistance = Constants.DEFAULT_SAMPLE_DISTANCE; alignParallel(centimeterPerSecond, sampleDistance); float sample = Sensor.sampleDistance(); float alignmentError = distance - sample; if (Math.abs(alignmentError) > Constants.MAX_ALIGNMENT_ERROR) { rotate(90, 14); State.waitForMotors(true, true); moveDistance(alignmentError, centimeterPerSecond); State.waitForMotors(true, true); rotate(-90, 14); State.waitForMotors(true, true); } } public static void alignParallel(float centimeterPerSecond) { alignParallel(centimeterPerSecond, Constants.DEFAULT_SAMPLE_DISTANCE); } public static void alignParallel(float centimeterPerSecond, float sampleDistance) { float sample = Sensor.sampleDistance(); if (sample > 30f) { return; } moveDistance(sampleDistance, centimeterPerSecond); while (!State.stopped(true, true)) {} stop(); float sampleDifference = (sample - Sensor.sampleDistance()); Delay.msDelay(10); rotate((centimeterPerSecond > 0 ? 1.f : -1.f) * (float) Math.toDegrees(Math.atan(sampleDifference / sampleDistance)), 14); while (!State.stopped(true, true)) {} } public static enum Mode { FORWARD, BACKWARD, STOP; } private static enum Wheel { LEFT, RIGHT; } }
package edu.mit.streamjit.test.apps.fft5; import com.jeffreybosboom.serviceproviderprocessor.ServiceProvider; import edu.mit.streamjit.api.CompiledStream; import edu.mit.streamjit.api.Filter; import edu.mit.streamjit.api.Input; import edu.mit.streamjit.api.Output; import edu.mit.streamjit.api.Pipeline; import edu.mit.streamjit.api.StatefulFilter; import edu.mit.streamjit.api.StreamCompiler; import edu.mit.streamjit.impl.compiler.CompilerStreamCompiler; import edu.mit.streamjit.test.SuppliedBenchmark; import edu.mit.streamjit.test.Benchmark; import edu.mit.streamjit.test.Datasets; import edu.mit.streamjit.impl.concurrent.ConcurrentStreamCompiler; import edu.mit.streamjit.impl.distributed.DistributedStreamCompiler; import edu.mit.streamjit.impl.interp.DebugStreamCompiler; import edu.mit.streamjit.test.Benchmarker; /** * Rewritten StreamIt's asplos06 benchmarks. Refer * STREAMIT_HOME/apps/benchmarks/asplos06/fft/streamit/FFT5.str for original * implementations. Each StreamIt's language constructs (i.e., pipeline, filter * and splitjoin) are rewritten as classes in StreamJit. * * @author Sumanan sumanan@mit.edu * @since Mar 14, 2013 */ public class FFT5 { public static void main(String[] args) throws InterruptedException { Benchmarker.runBenchmark(new FFT5Benchmark(), new CompilerStreamCompiler()); } @ServiceProvider(Benchmark.class) public static final class FFT5Benchmark extends SuppliedBenchmark { public FFT5Benchmark() { super("FFT5", FFT5Kernel.class, Datasets.nCopies(1000, 0.0f)); } } /** * This represents "void->void pipeline FFT5()". FIXME: actual pipeline is * void->void. Need to support void input, filereading, and file writing. */ public static class FFT5Kernel extends Pipeline<Float, Float> { public FFT5Kernel() { int N = 256; // add FileReader<float>("../input/FFT5.in"); add(new FFTReorder(N)); for (int j = 2; j <= N; j *= 2) { add(new CombineDFT(j)); } // add FileWriter<float>("FFT5.out"); } } private static class CombineDFT extends Filter<Float, Float> { float wn_r, wn_i; int n; CombineDFT(int n) { super(2 * n, 2 * n, 2 * n); this.n = n; init(); } private void init() { wn_r = (float) Math.cos(2 * 3.141592654 / n); wn_i = (float) Math.sin(2 * 3.141592654 / n); } public void work() { int i; float w_r = 1; float w_i = 0; float[] results = new float[2 * n]; for (i = 0; i < n; i += 2) { // this is a temporary work-around since there seems to be // a bug in field prop that does not propagate nWay into the // array references. --BFT 9/10/02 // int tempN = nWay; // Fixed --jasperln // removed nWay, just using n --sitij 9/26/03 float y0_r = peek(i); float y0_i = peek(i + 1); float y1_r = peek(n + i); float y1_i = peek(n + i + 1); float y1w_r = y1_r * w_r - y1_i * w_i; float y1w_i = y1_r * w_i + y1_i * w_r; results[i] = y0_r + y1w_r; results[i + 1] = y0_i + y1w_i; results[n + i] = y0_r - y1w_r; results[n + i + 1] = y0_i - y1w_i; float w_r_next = w_r * wn_r - w_i * wn_i; float w_i_next = w_r * wn_i + w_i * wn_r; w_r = w_r_next; w_i = w_i_next; } for (i = 0; i < 2 * n; i++) { pop(); push(results[i]); } } } private static class FFTReorderSimple extends Filter<Float, Float> { int totalData; int n; FFTReorderSimple(int n) { super(2 * n, 2 * n, 2 * n); this.n = n; init(); } private void init() { totalData = 2 * n; } public void work() { int i; for (i = 0; i < totalData; i += 4) { push(peek(i)); push(peek(i + 1)); } for (i = 2; i < totalData; i += 4) { push(peek(i)); push(peek(i + 1)); } for (i = 0; i < n; i++) { pop(); pop(); } } } private static class FFTReorder extends Pipeline<Float, Float> { FFTReorder(int n) { for (int i = 1; i < (n / 2); i *= 2) add(new FFTReorderSimple(n / i)); } } private static class FFTTestSource extends StatefulFilter<Float, Float> { float max = 1000.0f; float current = 0.0f; int N; FFTTestSource(int N) { super(1, 2 * N); this.N = N; } public void work() { int i; // FIXME: Actual pop is 0. As StreamJit doesn't support void input, // it receives input and just pops out it. pop(); // As current implementation has no support to fire the // streamgraph with void element, we offer the graph with // random values and just pop out here. if (current > max) current = 0.0f; for (i = 0; i < 2 * (N); i++) push(current++); } } private static class FloatPrinter extends Filter<Float, Void> { FloatPrinter() { super(1, 0); } public void work() { System.out.println(pop()); } } }
package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.Servo; /** * This class rotates the motor in the direction of the target, based on the * relative location of the target as determined by TargetLocator * * @author (Mark Macerato, Team 3167) * @version (March 2, 2014) */ class Motor { private double acceptableRange = 0.05; //The distance to the left or right of the target in inches that is acceptable private Servo motor = new Servo(1, 1); //The Servo that controls the rotating motor that aligns with the target private TargetLocator targetLocator = new TargetLocator(); //Will locate the target public void trackTheTarget() { //Rotates the motor aligning with the target. If the camera is too far to the left, it roates the motor right, and vice versa if (targetLocator.findTarget() > acceptableRange) { //if the target is too far to the right motor.set(1.0); dirverStation.print("Turning right...", 1); } else if (targetLocator.findTarget() < -acceptableRange) { //if the target is too far to the left motor.set(0.0); dirverStation.print("Turning left...", 1); } else if (targetLocator.findTarget() < acceptableRange && targetLocator.findTarget() > -acceptableRange) { //If the camera is aligned motor.set(motor.get()); dirverStation.print("Aligned!", 1); } else if(targetLocator.findTarget() == 0.0) { //If nothing is found dirverStation.print("No target", 1); } } }
package openblocks.common.tileentity; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.BlockCrops; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemDye; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; import net.minecraftforge.common.FakePlayer; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.liquids.ILiquidTank; import net.minecraftforge.liquids.ITankContainer; import net.minecraftforge.liquids.LiquidContainerRegistry; import net.minecraftforge.liquids.LiquidStack; import net.minecraftforge.liquids.LiquidTank; import openblocks.OpenBlocks; import openblocks.common.GenericInventory; import openblocks.common.api.IAwareTile; import openblocks.common.api.ISurfaceAttachment; import openblocks.utils.BlockUtils; import openblocks.utils.InventoryUtils; public class TileEntitySprinkler extends OpenTileEntity implements IAwareTile, ISurfaceAttachment, ITankContainer, IInventory { private LiquidStack water = new LiquidStack(Block.waterStill, 1); private ItemStack bonemeal = new ItemStack(Item.dyePowder, 1, 15); private LiquidTank tank = new LiquidTank(LiquidContainerRegistry.BUCKET_VOLUME); private GenericInventory inventory = new GenericInventory("sprinkler", true, 9); private boolean hasBonemeal = false; private void attemptFertilize() { if (worldObj == null || worldObj.isRemote) return; if (worldObj.rand.nextDouble() < 1.0 / (hasBonemeal ? OpenBlocks.Config.sprinklerBonemealFertizizeChance : OpenBlocks.Config.sprinklerFertilizeChance)) { Random random = worldObj.rand; int x = (random.nextInt(OpenBlocks.Config.sprinklerEffectiveRange) + 1) * (random.nextBoolean() ? 1 : -1) + xCoord; int z = (random.nextInt(OpenBlocks.Config.sprinklerEffectiveRange) + 1) * (random.nextBoolean() ? 1 : -1) + zCoord; /* What? Okay think about this. * i = -1 y = yCoord - 1 * i = 0 y = yCoord - 1 * i = 1 y = yCoord * * Is this the intended operation? I've changed it for now -NC */ for (int i = -1; i <= 1; i++) { int y = yCoord + i; for (int a = 0; a < 10; a++) { try { // Mikee, why do we try to apply it 10 times? Is it likely to fail? -NC if (ItemDye.applyBonemeal(bonemeal.copy(), worldObj, x, y, z, new FakePlayer(worldObj, "sprinkler"))) { break; } }catch(Exception e) { // do nothing, because who gives a fuck really } } } } } private void sprayParticles() { if (worldObj == null || !worldObj.isRemote) return; for (int i = 0; i < 6; i++) { float offset = (i - 2.5f) / 5f; ForgeDirection rotation = getRotation(); OpenBlocks.proxy.spawnLiquidSpray(worldObj, water, xCoord + 0.5 + (offset * 0.6 * rotation.offsetX), yCoord, zCoord + 0.5 + (offset * 0.6 * rotation.offsetZ), rotation, getSprayPitch(), 2 * offset); } } public void updateEntity() { super.updateEntity(); if (!worldObj.isRemote) { if (tank.getLiquid() == null || tank.getLiquid().amount == 0) { TileEntity below = worldObj.getBlockTileEntity(xCoord, yCoord - 1, zCoord); if (below instanceof ITankContainer) { ITankContainer belowTank = (ITankContainer)below; LiquidStack drained = belowTank.drain(ForgeDirection.UP, tank.getCapacity(), false); if (drained != null && drained.isLiquidEqual(water)) { drained = belowTank.drain(ForgeDirection.UP, tank.getCapacity(), true); if (drained != null) { tank.fill(drained, true); } } } } // every 60 ticks drain from the tank // if there's nothing to drain, disable it if (worldObj.getTotalWorldTime() % 1200 == 0) { hasBonemeal = InventoryUtils.consumeInventoryItem(inventory, bonemeal); } if (worldObj.getTotalWorldTime() % 60 == 0) { setEnabled(tank.drain(1, true) != null); sync(); } // if it's enabled.. } // simplified this action because only one of these will execute // depending on worldObj.isRemote if (isEnabled()) { attemptFertilize(); sprayParticles(); } } private void setEnabled(boolean b) { setFlag1(b); } private boolean isEnabled() { return getFlag1(); } @Override public int getSizeInventory() { return inventory.getSizeInventory(); } @Override public ItemStack getStackInSlot(int i) { return inventory.getStackInSlot(i); } @Override public ItemStack decrStackSize(int i, int j) { return inventory.decrStackSize(i, j); } @Override public ItemStack getStackInSlotOnClosing(int i) { return inventory.getStackInSlotOnClosing(i); } @Override public void setInventorySlotContents(int i, ItemStack itemstack) { inventory.setInventorySlotContents(i, itemstack); } @Override public String getInvName() { return inventory.getInvName(); } @Override public boolean isInvNameLocalized() { return inventory.isInvNameLocalized(); } @Override public int getInventoryStackLimit() { return inventory.getInventoryStackLimit(); } @Override public boolean isUseableByPlayer(EntityPlayer entityplayer) { return inventory.isUseableByPlayer(entityplayer); } @Override public void openChest() { // TODO Auto-generated method stub } @Override public void closeChest() { // TODO Auto-generated method stub } @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) { return inventory.isItemValidForSlot(i, itemstack); } @Override public int fill(ForgeDirection from, LiquidStack resource, boolean doFill) { if (resource != null && resource.isLiquidEqual(water)) { return tank.fill(resource, doFill); } return 0; } @Override public int fill(int tankIndex, LiquidStack resource, boolean doFill) { return fill(ForgeDirection.UNKNOWN, resource, doFill); } @Override public LiquidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { return null; } @Override public LiquidStack drain(int tankIndex, int maxDrain, boolean doDrain) { return null; } @Override public ILiquidTank[] getTanks(ForgeDirection direction) { return new ILiquidTank[] { tank }; } @Override public ILiquidTank getTank(ForgeDirection direction, LiquidStack type) { return tank; } @Override public ForgeDirection getSurfaceDirection() { return ForgeDirection.DOWN; } @Override public void onBlockBroken() { // TODO Auto-generated method stub } @Override public void onBlockAdded() { // TODO Auto-generated method stub } @Override public boolean onBlockActivated(EntityPlayer player, int side, float hitX, float hitY, float hitZ) { if (player.isSneaking()) { return false; } if (!worldObj.isRemote) { openGui(player, OpenBlocks.Gui.Sprinkler); } return true; } @Override public void onNeighbourChanged(int blockId) { // TODO Auto-generated method stub } @Override public void onBlockPlacedBy(EntityPlayer player, ForgeDirection side, ItemStack stack, float hitX, float hitY, float hitZ) { setRotation(BlockUtils.get2dOrientation(player)); sync(); } @Override public boolean onBlockEventReceived(int eventId, int eventParam) { // TODO Auto-generated method stub return false; } public float getSprayPitch() { return (float)(getSprayAngle() * Math.PI); } public float getSprayAngle() { if (isEnabled()) { float angle = (float)(MathHelper.sin(worldObj.getTotalWorldTime() * 0.02f) * Math.PI * 0.035f); return (float)(angle); } return 0; } public void writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); inventory.writeToNBT(tag); } public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); inventory.readFromNBT(tag); if (tag.hasKey("rotation")) { byte ordinal = tag.getByte("rotation"); setRotation(ForgeDirection.getOrientation(ordinal)); sync(); } } }
package eu.visualize.ini.convnet; import java.awt.Color; import java.awt.Cursor; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.PolarityEvent; import net.sf.jaer.eventprocessing.EventFilter2D; import net.sf.jaer.graphics.AEFrameChipRenderer; import net.sf.jaer.graphics.FrameAnnotater; import net.sf.jaer.graphics.ImageDisplay; /** * Computes CNN from DAVIS APS frames. * * @author tobi */ @Description("Computes CNN from DAVIS APS frames") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class DavisDeepLearnCnnProcessor extends EventFilter2D implements PropertyChangeListener, FrameAnnotater { protected DeepLearnCnnNetwork apsDvsNet = new DeepLearnCnnNetwork(); //, dvsNet = new DeepLearnCnnNetwork(); private String lastApsDvsNetXMLFilename = getString("lastAPSNetXMLFilename", "LCRN_cnn.xml"); // private String lastDVSNetXMLFilename = getString("lastDVSNetXMLFilename", "LCRN_cnn.xml"); // private ApsFrameExtractor frameExtractor = new ApsFrameExtractor(chip); private boolean showActivations = getBoolean("showActivations", false); private boolean showOutputAsBarChart = getBoolean("showOutputAsBarChart", true); private float uniformWeight = getFloat("uniformWeight", 0); private float uniformBias = getFloat("uniformBias", 0); protected boolean measurePerformance = getBoolean("measurePerformance", false); protected boolean processAPSFrames = getBoolean("processAPSFrames", true); // protected boolean processAPSDVSTogetherInAPSNet = true; // getBoolean("processAPSDVSTogetherInAPSNet", true); private boolean processDVSTimeSlices = getBoolean("processDVSTimeSlices", true); protected boolean addedPropertyChangeListener = false; // must do lazy add of us as listener to chip because renderer is not there yet when this is constructed private int dvsMinEvents = getInt("dvsMinEvents", 10000); private JFrame imageDisplayFrame = null; public ImageDisplay inputImageDisplay; protected DvsSubsamplerToFrame dvsSubsampler = null; private int dvsColorScale = getInt("dvsColorScale", 200); // 1/dvsColorScale is amount each event color the timeslice in subsampled timeslice input private boolean softMaxOutput = getBoolean("softMaxOutput", false); protected int lastProcessedEventTimestamp = 0; public DavisDeepLearnCnnProcessor(AEChip chip) { super(chip); String deb = "3. Debug", disp = "1. Display", anal = "2. Analysis"; setPropertyTooltip("loadApsDvsNetworkFromXML", "Load an XML file containing a CNN exported from DeepLearnToolbox by cnntoxml.m that proceses both APS and DVS frames"); // setPropertyTooltip("loadDVSTimesliceNetworkFromXML", "For the DVS time slices, load an XML file containing a CNN exported from DeepLearnToolbox by cnntoxml.m"); // setPropertyTooltip(deb, "setNetworkToUniformValues", "sets previously-loaded net to uniform values for debugging"); setPropertyTooltip(disp, "showOutputAsBarChart", "displays activity of output units as bar chart, where height indicates activation"); setPropertyTooltip(disp, "showKernels", "draw all the network kernels (once) in a new JFrame"); setPropertyTooltip(disp, "showActivations", "draws the network activations in a separate JFrame"); setPropertyTooltip(disp, "hideSubsamplingLayers", "hides layers that are subsampling conv layers"); setPropertyTooltip(disp, "hideConvLayers", "hides conv layers"); setPropertyTooltip(disp, "normalizeActivationDisplayGlobally", "normalizes the activations of layers globally across features"); setPropertyTooltip(disp, "normalizeKernelDisplayWeightsGlobally", "normalizes the weights globally across layer"); setPropertyTooltip(disp, "softMaxOutput", "normalizes the final outputs using softmax; use for ReLu final layer to display output in 0-1 range"); setPropertyTooltip(deb, "inputClampedTo1", "clamps network input image to fixed value (1) for debugging"); setPropertyTooltip(deb, "inputClampedToIncreasingIntegers", "clamps network input image to idx of matrix, increasing integers, for debugging"); setPropertyTooltip(deb, "printActivations", "prints out activations of CNN layers for debugging; by default shows input and output; combine with hideConvLayers and hideSubsamplingLayers to show more layers"); setPropertyTooltip(deb, "printWeights", "prints out weights of APS net layers for debugging"); setPropertyTooltip(anal, "measurePerformance", "Measures and logs time in ms to process each frame along with estimated operations count (MAC=2OPS)"); setPropertyTooltip(anal, "processAPSFrames", "sends APS frames to convnet"); setPropertyTooltip(anal, "processDVSTimeSlices", "sends DVS time slices to convnet"); setPropertyTooltip(anal, "processAPSDVSTogetherInAPSNet", "sends APS frames and DVS time slices to single convnet"); setPropertyTooltip(anal, "dvsColorScale", "1/dvsColorScale is the amount by which each DVS event is added to time slice 2D gray-level histogram"); setPropertyTooltip(anal, "dvsMinEvents", "minimum number of events to run net on DVS timeslice"); initFilter(); } synchronized public void doLoadApsDvsNetworkFromXML() { JFileChooser c = new JFileChooser(lastApsDvsNetXMLFilename); FileFilter filt = new FileNameExtensionFilter("XML File", "xml"); c.addChoosableFileFilter(filt); c.setFileFilter(filt); c.setSelectedFile(new File(lastApsDvsNetXMLFilename)); int ret = c.showOpenDialog(chip.getAeViewer()); if (ret != JFileChooser.APPROVE_OPTION) { return; } lastApsDvsNetXMLFilename = c.getSelectedFile().toString(); putString("lastAPSNetXMLFilename", lastApsDvsNetXMLFilename); try { apsDvsNet.loadFromXMLFile(c.getSelectedFile()); dvsSubsampler = new DvsSubsamplerToFrame(apsDvsNet.inputLayer.dimx, apsDvsNet.inputLayer.dimy, getDvsColorScale()); } catch (Exception ex) { Logger.getLogger(DavisDeepLearnCnnProcessor.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(chip.getAeViewer().getFilterFrame(), "Couldn't load net from this file, caught exception " + ex + ". See console for logging.", "Bad network file", JOptionPane.WARNING_MESSAGE); } } // public void doLoadDVSTimesliceNetworkFromXML() { // JFileChooser c = new JFileChooser(lastDVSNetXMLFilename); // FileFilter filt = new FileNameExtensionFilter("XML File", "xml"); // c.addChoosableFileFilter(filt); // c.setSelectedFile(new File(lastDVSNetXMLFilename)); // int ret = c.showOpenDialog(chip.getAeViewer()); // if (ret != JFileChooser.APPROVE_OPTION) { // return; // lastDVSNetXMLFilename = c.getSelectedFile().toString(); // putString("lastDVSNetXMLFilename", lastDVSNetXMLFilename); // dvsNet.loadFromXMLFile(c.getSelectedFile()); // dvsSubsampler = new DvsSubsamplerToFrame(dvsNet.inputLayer.dimx, dvsNet.inputLayer.dimy, getDvsColorScale()); // debug only // public void doSetNetworkToUniformValues() { // if (apsDvsNet != null) { // apsDvsNet.setNetworkToUniformValues(uniformWeight, uniformBias); public void doShowKernels() { if (apsDvsNet != null) { if (!apsDvsNet.networkRanOnce) { JOptionPane.showMessageDialog(chip.getAeViewer().getFilterFrame(), "Network must run at least once to correctly plot kernels (internal variables for indexing are computed at runtime)"); return; } final DeepLearnCnnNetwork ref = apsDvsNet; Runnable runnable = new Runnable() { @Override public void run() { try { setCursor(new Cursor(Cursor.WAIT_CURSOR)); JFrame frame = apsDvsNet.drawKernels(); frame.setTitle("APS net kernel weights"); } finally { setCursor(Cursor.getDefaultCursor()); } } }; SwingUtilities.invokeLater(runnable); } } @Override synchronized public EventPacket<?> filterPacket(EventPacket<?> in) { if (!addedPropertyChangeListener) { ((AEFrameChipRenderer) chip.getRenderer()).getSupport().addPropertyChangeListener(AEFrameChipRenderer.EVENT_NEW_FRAME_AVAILBLE, this); addedPropertyChangeListener = true; } // frameExtractor.filterPacket(in); // extracts frames with nornalization (brightness, contrast) and sends to apsDvsNet on each frame in PropertyChangeListener // send DVS timeslice to convnet if ((apsDvsNet != null)) { final int sizeX = chip.getSizeX(); final int sizeY = chip.getSizeY(); for (BasicEvent e : in) { lastProcessedEventTimestamp = e.getTimestamp(); PolarityEvent p = (PolarityEvent) e; if (dvsSubsampler != null) { dvsSubsampler.addEvent(p, sizeX, sizeY); } if (dvsSubsampler != null && dvsSubsampler.getAccumulatedEventCount() > dvsMinEvents) { long startTime = 0; if (measurePerformance) { startTime = System.nanoTime(); } if (processDVSTimeSlices) { apsDvsNet.processDvsTimeslice(dvsSubsampler); // generates PropertyChange EVENT_MADE_DECISION if (dvsSubsampler != null) { dvsSubsampler.clear(); } if (measurePerformance) { long dt = System.nanoTime() - startTime; float ms = 1e-6f * dt; log.info(String.format("DVS slice processing time: %.1fms; %s", ms, apsDvsNet.getPerformanceString())); } } } } } return in; } @Override public void resetFilter() { if (dvsSubsampler != null) { dvsSubsampler.clear(); } } @Override public void initFilter() { // if apsDvsNet was loaded before, load it now if (lastApsDvsNetXMLFilename != null) { File f = new File(lastApsDvsNetXMLFilename); if (f.exists() && f.isFile()) { try { apsDvsNet.loadFromXMLFile(f); apsDvsNet.setSoftMaxOutput(softMaxOutput); // must set manually since net doesn't know option kept here. dvsSubsampler = new DvsSubsamplerToFrame(apsDvsNet.inputLayer.dimx, apsDvsNet.inputLayer.dimy, getDvsColorScale()); } catch (IOException ex) { Logger.getLogger(DavisDeepLearnCnnProcessor.class.getName()).log(Level.SEVERE, null, ex); } } } // if (lastDVSNetXMLFilename != null) { // File f = new File(lastDVSNetXMLFilename); // if (f.exists() && f.isFile()) { // dvsNet.loadFromXMLFile(f); // dvsSubsampler = new DvsSubsamplerToFrame(dvsNet.inputLayer.dimx, dvsNet.inputLayer.dimy, getDvsColorScale()); } @Override synchronized public void propertyChange(PropertyChangeEvent evt) { // new activationsFrame is available, process it if (isFilterEnabled() && (apsDvsNet != null) && (processAPSFrames)) { // float[] frame = frameExtractor.getNewFrame(); // if (frame == null || frame.length == 0 || frameExtractor.getWidth() == 0) { // return; long startTime = 0; if (measurePerformance) { startTime = System.nanoTime(); } float[] outputs = apsDvsNet.processDownsampledFrame((AEFrameChipRenderer) (chip.getRenderer())); if (measurePerformance) { long dt = System.nanoTime() - startTime; float ms = 1e-6f * dt; float fps = 1e3f / ms; log.info(String.format("Frame processing time: %.1fms (%.1f FPS); %s", ms, fps, apsDvsNet.getPerformanceString())); } } } @Override public void annotate(GLAutoDrawable drawable ) { GL2 gl = drawable.getGL().getGL2(); if (showActivations) { if (apsDvsNet != null) { apsDvsNet.drawActivations(); } // if (dvsNet != null && processDVSTimeSlices) { // dvsNet.drawActivations(); } if (showOutputAsBarChart) { final float lineWidth = 2; if (apsDvsNet.outputLayer != null) { apsDvsNet.outputLayer.annotateHistogram(gl, chip.getSizeX(), chip.getSizeY(), lineWidth, Color.RED); } // if (dvsNet.outputLayer != null && processDVSTimeSlices) { // dvsNet.outputLayer.annotateHistogram(gl, chip.getSizeX(), chip.getSizeY(), lineWidth, Color.YELLOW); } } /** * @return the showActivations */ public boolean isShowActivations() { return showActivations; } /** * @param showActivations the showActivations to set */ public void setShowActivations(boolean showActivations) { this.showActivations = showActivations; } /** * @return the showOutputAsBarChart */ public boolean isShowOutputAsBarChart() { return showOutputAsBarChart; } /** * @param showOutputAsBarChart the showOutputAsBarChart to set */ public void setShowOutputAsBarChart(boolean showOutputAsBarChart) { this.showOutputAsBarChart = showOutputAsBarChart; putBoolean("showOutputAsBarChart", showOutputAsBarChart); } private void checkDisplayFrame() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } // /** // * @return the uniformWeight // */ // public float getUniformWeight() { // return uniformWeight; // /** // * @param uniformWeight the uniformWeight to set // */ // public void setUniformWeight(float uniformWeight) { // this.uniformWeight = uniformWeight; // putFloat("uniformWeight", uniformWeight); // /** // * @return the uniformBias // */ // public float getUniformBias() { // return uniformBias; // /** // * @param uniformBias the uniformBias to set // */ // public void setUniformBias(float uniformBias) { // this.uniformBias = uniformBias; // putFloat("uniformBias", uniformBias); // apsDvsNet computation debug methods public boolean isInputClampedTo1() { return apsDvsNet == null ? false : apsDvsNet.isInputClampedTo1(); } public void setInputClampedTo1(boolean inputClampedTo1) { if (apsDvsNet != null) { apsDvsNet.setInputClampedTo1(inputClampedTo1); } } public boolean isInputClampedToIncreasingIntegers() { return apsDvsNet == null ? false : apsDvsNet.isInputClampedToIncreasingIntegers(); } public void setInputClampedToIncreasingIntegers(boolean inputClampedTo1) { if (apsDvsNet != null) { apsDvsNet.setInputClampedToIncreasingIntegers(inputClampedTo1); } } /** * @return the measurePerformance */ public boolean isMeasurePerformance() { return measurePerformance; } /** * @param measurePerformance the measurePerformance to set */ public void setMeasurePerformance(boolean measurePerformance) { this.measurePerformance = measurePerformance; putBoolean("measurePerformance", measurePerformance); } public boolean isHideSubsamplingLayers() { return apsDvsNet.isHideSubsamplingLayers(); } public void setHideSubsamplingLayers(boolean hideSubsamplingLayers) { apsDvsNet.setHideSubsamplingLayers(hideSubsamplingLayers); // dvsNet.setHideSubsamplingLayers(hideSubsamplingLayers); } public boolean isHideConvLayers() { return apsDvsNet.isHideConvLayers(); } public void setHideConvLayers(boolean hideConvLayers) { apsDvsNet.setHideConvLayers(hideConvLayers); // dvsNet.setHideConvLayers(hideConvLayers); } /** * @return the processDVSTimeSlices */ public boolean isProcessDVSTimeSlices() { return processDVSTimeSlices; } /** * @param processDVSTimeSlices the processDVSTimeSlices to set */ public void setProcessDVSTimeSlices(boolean processDVSTimeSlices) { boolean old = this.processDVSTimeSlices; this.processDVSTimeSlices = processDVSTimeSlices; putBoolean("processDVSTimeSlices", processDVSTimeSlices); getSupport().firePropertyChange("processDVSTimeSlices", old, processDVSTimeSlices); } /** * @return the processAPSFrames */ public boolean isProcessAPSFrames() { return processAPSFrames; } /** * @param processAPSFrames the processAPSFrames to set */ public void setProcessAPSFrames(boolean processAPSFrames) { boolean old = this.processAPSFrames; this.processAPSFrames = processAPSFrames; putBoolean("processAPSFrames", processAPSFrames); getSupport().firePropertyChange("processAPSFrames", old, processAPSFrames); } /** * @return the dvsColorScale */ public int getDvsColorScale() { return dvsColorScale; } /** * @param dvsColorScale the dvsColorScale to set */ synchronized public void setDvsColorScale(int dvsColorScale) { if (dvsColorScale < 1) { dvsColorScale = 1; } this.dvsColorScale = dvsColorScale; putInt("dvsColorScale", dvsColorScale); if (dvsSubsampler != null) { dvsSubsampler.setColorScale(dvsColorScale); } } /** * @return the dvsMinEvents */ public int getDvsMinEvents() { return dvsMinEvents; } /** * @param dvsMinEvents the dvsMinEvents to set */ public void setDvsMinEvents(int dvsMinEvents) { this.dvsMinEvents = dvsMinEvents; putInt("dvsMinEvents", dvsMinEvents); } public boolean isNormalizeKernelDisplayWeightsGlobally() { if (apsDvsNet == null) { return false; } else { return apsDvsNet.isNormalizeKernelDisplayWeightsGlobally(); } } public void setNormalizeKernelDisplayWeightsGlobally(boolean normalizeKernelDisplayWeightsGlobally) { if (apsDvsNet != null) { apsDvsNet.setNormalizeKernelDisplayWeightsGlobally(normalizeKernelDisplayWeightsGlobally); } // if (dvsNet != null) { // dvsNet.setNormalizeKernelDisplayWeightsGlobally(normalizeKernelDisplayWeightsGlobally); } public boolean isNormalizeActivationDisplayGlobally() { if (apsDvsNet == null) { return false; } return apsDvsNet.isNormalizeActivationDisplayGlobally(); } public void setNormalizeActivationDisplayGlobally(boolean normalizeActivationDisplayGlobally) { if (apsDvsNet != null) { apsDvsNet.setNormalizeActivationDisplayGlobally(normalizeActivationDisplayGlobally); } // if (dvsNet != null) { // dvsNet.setNormalizeActivationDisplayGlobally(normalizeActivationDisplayGlobally); } public boolean isPrintActivations() { if (apsDvsNet == null) { return false; } return apsDvsNet.isPrintActivations(); } public void setPrintActivations(boolean printActivations) { if (apsDvsNet == null) { return; } apsDvsNet.setPrintActivations(printActivations); } public boolean isPrintWeights() { if (apsDvsNet == null) { return false; } return apsDvsNet.isPrintWeights(); } public void setPrintWeights(boolean printWeights) { if (apsDvsNet == null) { return; } apsDvsNet.setPrintWeights(printWeights); } // /** // * @return the processAPSDVSTogetherInAPSNet // */ // public boolean isProcessAPSDVSTogetherInAPSNet() { // return processAPSDVSTogetherInAPSNet; // /** // * @param processAPSDVSTogetherInAPSNet the processAPSDVSTogetherInAPSNet to // * set // */ // public void setProcessAPSDVSTogetherInAPSNet(boolean processAPSDVSTogetherInAPSNet) { // this.processAPSDVSTogetherInAPSNet = processAPSDVSTogetherInAPSNet; // putBoolean("processAPSDVSTogetherInAPSNet", processAPSDVSTogetherInAPSNet); // if (processAPSDVSTogetherInAPSNet) { // setProcessAPSFrames(false); // setProcessDVSTimeSlices(false); public boolean isSoftMaxOutput() { if (apsDvsNet == null) { return softMaxOutput; } return apsDvsNet.isSoftMaxOutput(); } public void setSoftMaxOutput(boolean softMaxOutput) { this.softMaxOutput = softMaxOutput; putBoolean("softMaxOutput", softMaxOutput); if (apsDvsNet == null) { return; } apsDvsNet.setSoftMaxOutput(softMaxOutput); } }
package org.apache.cocoon.components.cron; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.Map; import java.util.Properties; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.avalon.framework.CascadingRuntimeException; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.parameters.Parameters; import org.apache.avalon.framework.service.ServiceException; import org.apache.cocoon.components.cron.ConfigurableCronJob; import org.apache.cocoon.components.cron.ServiceableCronJob; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.excalibur.source.Source; import org.apache.excalibur.source.SourceResolver; import org.joda.time.DateTime; public class DequeueCronJob extends ServiceableCronJob implements Configurable, ConfigurableCronJob { private static final String PARAMETER_QUEUE_PATH = "queue-path"; private static final String PROCESSOR_STATUS_FILE = "processor-status.xml"; private static final long PROCESSOR_STATUS_FILE_STALE = 60000; private static final String inDirName = "in"; private static final String processingDirName = "in-progress"; private static final String outDirName = "out"; private static final String errorDirName = "error"; private File queuePath; /** * Copy job file to outDir, also, zip contents of processingDir into * "{currentJob-name}.zip" into outDir. * The zip contains a directory {currentJob-name}, all other files are in * that directory. * * @param processingDir * @param outDir * @param currentJob */ private void finishUpJob(File processingDir, File outDir, File currentJob) throws IOException { final String basename = FilenameUtils.getBaseName(currentJob.getName()); final String zipFileName = String.format("%s.zip", basename); File zipFile = new File(outDir, zipFileName); final String zipFolder = basename + "/"; FileUtils.copyFileToDirectory(currentJob, outDir); try { // create byte buffer byte[] buffer = new byte[1024]; FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); // add a directory to the new ZIP first zos.putNextEntry(new ZipEntry(zipFolder)); File[] files = processingDir.listFiles(); for (File file : files) { FileInputStream fis = new FileInputStream(file); // begin writing a new ZIP entry, positions the stream to the start of the entry data zos.putNextEntry(new ZipEntry(zipFolder + file.getName())); int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); // close the InputStream fis.close(); } // close the ZipOutputStream zos.close(); } catch (IOException ioe) { this.getLogger().info("Error creating zip file" + ioe); } } /** * The object that runs a task. */ private static class TaskRunner implements Callable { private final Task task; private final SourceResolver resolver; private final org.apache.avalon.framework.logger.Logger logger; private final File outputFile; public TaskRunner(Task t, SourceResolver resolver, org.apache.avalon.framework.logger.Logger logger, File outputFile) { this.task = t; this.resolver = resolver; this.logger = logger; this.outputFile = outputFile; } @Override public Object call() throws Exception { // this.logger.info("Processing task " + task.id + " called."); OutputStream os = new FileOutputStream(outputFile); processPipeline(task.uri, resolver, logger, os); os.close(); return null; } } /** * An enum denoting the status of a Processor this class). */ public enum ProcessorStatus { ALIVE, DEAD, NONE } /** * Process a job: add all tasks to ExecutorService, invokeAll tasks and wait * until all tasks have finished. While waiting, update * processor-status.xml. * * @param inDir Where all output files are stored. * @param currentJob The current job file. */ private void processCurrentJob(File inDir, File currentJob) throws ServiceException { this.getLogger().info("Processing job " + currentJob.getAbsoluteFile()); JobConfig jobConfig = readJobConfig(currentJob); int totalTasks = jobConfig.tasks.length; int completedTasks = 0; DateTime jobStartedAt = new DateTime(); writeProcessorStatus(jobConfig.name, jobStartedAt, totalTasks, completedTasks); int availableProcessors = Runtime.getRuntime().availableProcessors(); int maxConcurrent = jobConfig.maxConcurrent; int maxThreads = 1; // default nr of threads if (maxConcurrent <= 0) { // If negative, add to availableProcessors, but of course, // use at least one thread. maxThreads = availableProcessors + maxConcurrent; if (maxThreads < 1) { maxThreads = 1; } } else { // Use specified maximum, but only if it is no more than what's // available. maxThreads = maxConcurrent; if (maxConcurrent > availableProcessors) { maxThreads = availableProcessors; } } ExecutorService threadPool = Executors.newFixedThreadPool(maxThreads); this.getLogger().info("Using " + maxThreads + " processors to execute " + totalTasks + " tasks."); CompletionService<TaskRunner> jobExecutor = new ExecutorCompletionService<TaskRunner>(threadPool); SourceResolver resolver = (SourceResolver) this.manager.lookup(SourceResolver.ROLE); int submittedTasks = 0; for (Task t : jobConfig.tasks) { File outputFile = new File(inDir, String.format("task-%s.xml", t.id)); Callable taskRunner = new TaskRunner(t, resolver, this.getLogger(), outputFile); jobExecutor.submit(taskRunner); submittedTasks++; } this.getLogger().info("Submitted " + submittedTasks + " tasks."); boolean interrupted = false; threadPool.shutdown(); while (!threadPool.isTerminated()) { Future<TaskRunner> f = null; TaskRunner t = null; try { f = jobExecutor.take(); t = f.get(); } catch (ExecutionException eex) { if (null != t) { this.getLogger().info("Received ExecutionException for task " + t.task.id + ", ignoring, continuing with other tasks."); } } catch (InterruptedException iex) { this.getLogger().info("Received InterruptedException, quitting executing tasks."); interrupted = true; break; } catch (CascadingRuntimeException ex) { this.getLogger().info("Received CascadingRuntimeException, ignoring, continuing with other tasks."); } completedTasks++; this.getLogger().info("Processing tasks: completedTasks=" + completedTasks + ", totalTasks=" + totalTasks + "."); writeProcessorStatus(jobConfig.name, jobStartedAt, totalTasks, completedTasks); } if (interrupted) { threadPool.shutdownNow(); } this.manager.release(resolver); } /** * Read job description file into JobConfig object using XStream. * * @param currentJob * @return JobConfig */ private JobConfig readJobConfig(File currentJob) { // <job name="test-job" created="20140613T11:45:00" max-concurrent="3"> // <tasks> // <task id="task-1"> // </task> // </job> XStream xstream = new XStream(new DomDriver()); xstream.alias("job", JobConfig.class); xstream.useAttributeFor(JobConfig.class, "name"); xstream.useAttributeFor(JobConfig.class, "created"); xstream.useAttributeFor(JobConfig.class, "maxConcurrent"); xstream.aliasField("max-concurrent", JobConfig.class, "maxConcurrent"); xstream.alias("task", Task.class); xstream.useAttributeFor(Task.class, "id"); JobConfig jobConfig = (JobConfig) xstream.fromXML(currentJob); return jobConfig; } @SuppressWarnings("rawtypes") @Override public void setup(Parameters params, Map objects) { return; } /** * We're done, delete status file. */ private synchronized void deleteProcessorStatus() { File pStatusFile = new File(this.queuePath, PROCESSOR_STATUS_FILE); pStatusFile.delete(); } /** * Update status file. * * @param jobName * @param started * @param totalTasks * @param completedTasks * @param currentTaskStartedAt */ private synchronized void writeProcessorStatus(String jobName, DateTime started, int totalTasks, int completedTasks) { File pStatusFile = new File(this.queuePath, PROCESSOR_STATUS_FILE); String status = String.format("<processor id=\"%s\" job-name=\"%s\" started=\"%s\" tasks=\"%d\" tasks-completed=\"%d\"/>", Thread.currentThread().getId(), jobName, started.toString(), totalTasks, completedTasks); try { FileUtils.writeStringToFile(pStatusFile, status, "UTF-8"); } catch (IOException ex) { Logger.getLogger(DequeueCronJob.class.getName()).log(Level.SEVERE, null, ex); } } /** * Return File object for parent/path, creating it if necessary. * * @param parent * @param path * @return Resulting File object. */ private File getOrCreateDirectory(File parent, String path) { File dir = new File(parent, path); if (!dir.exists()) { dir.mkdirs(); } return dir; } /** * Move file from one File object to another File object, deleting an * already existing file if necessary. * * @param fromFile * @param toFile * @throws IOException */ private void moveFileTo(File fromFile, File toFile) throws IOException { if (toFile.isFile()) { FileUtils.forceDelete(toFile); } if (!fromFile.renameTo(toFile)) { if (this.getLogger().isErrorEnabled()) { this.getLogger().error(String.format("Could not move file \"%s\" to \"%s\"", fromFile.getAbsolutePath(), toFile.getAbsoluteFile())); } } } /** * Get oldest job (file named "job-*.xml") in dir, using lastModified * timestamp and picking first File if there is more than one file with the * same lastModified. * * @param dir * @return */ protected File getOldestJobFile(File dir) { if (dir == null || !dir.isDirectory()) { return null; } File[] files = dir.listFiles((FileFilter) new WildcardFileFilter("job-*.xml")); if (files.length == 0) { return null; } Arrays.sort(files, new Comparator<File>() { public int compare(File file1, File file2) { return Long.valueOf(file1.lastModified()).compareTo(file2.lastModified()); } }); return files[0]; } /** * Get path to queue folder. * * @param config * @throws ConfigurationException */ @Override public void configure(final Configuration config) throws ConfigurationException { String actualQueuesDirName = config.getChild(PARAMETER_QUEUE_PATH).getValue(); queuePath = new File(actualQueuesDirName); } /** * Process the URL in one Task. All errors are caught, if one task goes bad * continue processing the others. * * @param url URL to fetch * @param manager Cocoon servicemanager (so cocoon: protocol is allowed.) * @param logger For logging stuff * @param os Where the output ends up. */ private static void processPipeline(String url, SourceResolver resolver, org.apache.avalon.framework.logger.Logger logger, OutputStream os) throws IOException { Source src = null; InputStream is = null; try { src = resolver.resolveURI(url); is = src.getInputStream(); IOUtils.copy(is, os); } catch (IOException e) { throw new CascadingRuntimeException(String.format("Error processing pipeline \"%s\"", url), e); } finally { try { if (null != is) { is.close(); } } catch (IOException e) { throw new CascadingRuntimeException("DequeueCronJob raised an exception closing input stream on " + url + ".", e); } finally { if (null != src) { // logger.info(String.format("Releasing source: %s", src)); resolver.release(src); src = null; } } } } /** * Check if there's a job in the processingDir. If yes then abstain if * Processor = ALIVE, remove it otherwise. If No then move oldest job to * processingDir, process that job. */ private void processQueue() throws IOException { /* Create subdirs if necessary. */ File queueDir = getOrCreateDirectory(this.queuePath, ""); File inDir = getOrCreateDirectory(queueDir, inDirName); File processingDir = getOrCreateDirectory(queueDir, processingDirName); File outDir = getOrCreateDirectory(queueDir, outDirName); File errorDir = getOrCreateDirectory(queueDir, errorDirName); // Get status of Processor DequeueCronJob.ProcessorStatus pStatus = processorStatus(); File currentJobFile = getOldestJobFile(processingDir); this.getLogger().info(String.format("Processor: %s, queueDir=%s, current job: %s", pStatus, queueDir, currentJobFile)); // A job is already being processed if (null != currentJobFile) { /* * A job is processed by a live Processor -> quit now. */ if (pStatus.equals(DequeueCronJob.ProcessorStatus.ALIVE)) { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug(String.format("Active job \"%s\" in queue \"%s\", stopping", currentJobFile, queueDir)); } } else { /* * A job was processed, but the Processor is dead. * Move job tot error-folder. Clean processing folder. */ this.getLogger().warn(String.format("Stale job \"%s\" in queue \"%s\", cancelling job and stopping", currentJobFile, queueDir)); moveFileTo(currentJobFile, new File(errorDir, currentJobFile.getName())); FileUtils.cleanDirectory(processingDir); } } else { // No job being processed. File jobFile = getOldestJobFile(inDir); if (jobFile != null) { String jobFileName = jobFile.getName(); File currentJob = new File(processingDir, jobFileName); try { FileUtils.cleanDirectory(processingDir); writeProcessorStatus(jobFileName, new DateTime(), 0, 0); if (this.getLogger().isDebugEnabled()) { this.getLogger().debug(String.format("Processing job \"%s\" in queue \"%s\"", jobFileName, queueDir)); } moveFileTo(jobFile, currentJob); this.getLogger().debug(String.format("Moved job \"%s\" to \"%s\"", jobFile, currentJob)); processCurrentJob(processingDir, currentJob); finishUpJob(processingDir, outDir, currentJob); } catch (Exception e) { // Catch IOException AND catch ClassCast exception etc. if (this.getLogger().isErrorEnabled()) { this.getLogger().error("Error processing job \"" + jobFileName + "\"", e); } moveFileTo(currentJob, new File(errorDir, jobFileName)); String stackTrace = ExceptionUtils.getFullStackTrace(e); FileUtils.writeStringToFile(new File(errorDir, FilenameUtils.removeExtension(jobFileName) + ".txt"), stackTrace, "UTF-8"); } finally { FileUtils.cleanDirectory(processingDir); deleteProcessorStatus(); } } else { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("No job, stopping"); } } } } /** * Return NONE (No processor), ALIVE (Processor still active) or DEAD * (Processor hasn't updated status file for too long). * * @return ProcessorStatus: NONE, ALIVE or DEAD. */ private synchronized ProcessorStatus processorStatus() { File statusFile = new File(this.queuePath, PROCESSOR_STATUS_FILE); if (!statusFile.exists()) { return DequeueCronJob.ProcessorStatus.NONE; } else { long lastModified = statusFile.lastModified(); if (System.currentTimeMillis() - lastModified > PROCESSOR_STATUS_FILE_STALE) { return DequeueCronJob.ProcessorStatus.DEAD; } else { return DequeueCronJob.ProcessorStatus.ALIVE; } } } /** * Main entrypoint for CronJob. * * @param name */ @Override public void execute(String name) { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("CronJob " + name + " launched at " + new Date()); } try { processQueue(); } catch (IOException e) { throw new CascadingRuntimeException("CronJob " + name + " raised an exception.", e); } } /** * Classes used by XStream for loading the job-*.xml config files into. */ private class Task { private String id; private String uri; public Task() { } } private class JobConfig { // <job id="71qyqha7a-91ajauq" name="job-name" description="task" // created="date" max-concurrent="n">tasks...</job> private String id; private String name; private String description; private DateTime created; private Integer maxConcurrent; private Task[] tasks; public JobConfig() { } } }
package org.apache.xml.security.encryption; import java.util.Iterator; import java.util.List; import java.util.LinkedList; import org.w3c.dom.Element; /** * <code>ReferenceList</code> is an element that contains pointers from a key * value of an <code>EncryptedKey</code> to items encrypted by that key value * (<code>EncryptedData</code> or <code>EncryptedKey</code> elements). * <p> * It is defined as follows: * <xmp> * <element name='ReferenceList'> * <complexType> * <choice minOccurs='1' maxOccurs='unbounded'> * <element name='DataReference' type='xenc:ReferenceType'/> * <element name='KeyReference' type='xenc:ReferenceType'/> * </choice> * </complexType> * </element> * </xmp> * * @author Axl Mattheus * @see Reference. */ public class ReferenceList { public static final int DATA_REFERENCE = 0x00000001; public static final int KEY_REFERENCE = 0x00000002; private Class sentry; private List references; /** * Returns an instance of <code>ReferenceList</code>, initialized with the * appropriate parameters. * * @param type the type of references this <code>ReferenceList</code> will * hold. */ public ReferenceList (int type) { if (type == DATA_REFERENCE) { sentry = DataReference.class; } else if (type == KEY_REFERENCE) { sentry = KeyReference.class; } else { throw new IllegalArgumentException(); } references = new LinkedList(); } public void add(Reference reference) { if (!reference.getClass().equals(sentry)) { throw new IllegalArgumentException(); } else { references.add(reference); } } /** * Removes a reference from the <code>ReferenceList</code>. * * @param reference the reference to remove. */ public void remove(Reference reference) { if (!reference.getClass().equals(sentry)) { throw new IllegalArgumentException(); } else { references.remove(reference); } } /** * Returns the size of the <code>ReferenceList</code>. * * @return the size of the <code>ReferenceList</code>. */ public int size() { return (references.size()); } /** * Indicates if the <code>ReferenceList</code> is empty. * * @return <code><b>true</b></code> if the <code>ReferenceList</code> is * empty, else <code><b>false</b></code>. */ public boolean isEmpty() { return (references.isEmpty()); } /** * Returns an <code>Iterator</code> over all the <code>Reference</code>s * contatined in this <code>ReferenceList</code>. * * @return Iterator. */ public Iterator getReferences() { return (references.iterator()); } /** * <code>DataReference</code> factory method. Returns a * <code>DataReference</code>. */ public static Reference newDataReference(String uri) { return (new DataReference(uri)); } /** * <code>KeyReference</code> factory method. Returns a * <code>KeyReference</code>. */ public static Reference newKeyReference(String uri) { return (new KeyReference(uri)); } /** * <code>ReferenceImpl</code> is an implementation of * <code>Reference</code>. * * @see Reference. */ private static class ReferenceImpl implements Reference { private String uri; private List referenceInformation; ReferenceImpl(String _uri) { this.uri = _uri; referenceInformation = new LinkedList(); } public String getURI() { return (uri); } public Iterator getElementRetrievalInformation() { return (referenceInformation.iterator()); } public void setURI(String _uri) { this.uri = _uri; } public void removeElementRetrievalInformation(Element node) { referenceInformation.remove(node); } public void addElementRetrievalInformation(Element node) { referenceInformation.add(node); } } private static class DataReference extends ReferenceImpl { DataReference(String uri) { super(uri); } } private static class KeyReference extends ReferenceImpl { KeyReference(String uri) { super (uri); } } }
package org.apdplat.evaluation.impl; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import org.apdplat.evaluation.Evaluation; import org.apdplat.evaluation.EvaluationResult; import org.apdplat.evaluation.Segmenter; import org.wltea.analyzer.core.IKSegmenter; import org.wltea.analyzer.core.Lexeme; /** * IKAnalyzer * @author */ public class IKAnalyzerEvaluation extends Evaluation{ @Override public List<EvaluationResult> run() throws Exception { List<EvaluationResult> list = new ArrayList<>(); System.out.println(" IKAnalyzer "); list.add(run(true)); Evaluation.generateReport(list, "IKAnalyzer.txt"); System.out.println(" IKAnalyzer "); list.add(run(false)); Evaluation.generateReport(list, "IKAnalyzer.txt"); return list; } private EvaluationResult run(final boolean useSmart) throws Exception{ String des = ""; if(useSmart){ des = ""; } String resultText = "temp/result-text-"+des+".txt"; float rate = segFile(testText, resultText, new Segmenter(){ @Override public String seg(String text) { return segText(text, useSmart); } }); EvaluationResult result = evaluate(resultText, standardText); result.setAnalyzer("IKAnalyzer "+des); result.setSegSpeed(rate); return result; } private String segText(String text, boolean useSmart) { StringBuilder result = new StringBuilder(); IKSegmenter ik = new IKSegmenter(new StringReader(text), useSmart); try { Lexeme word = null; while((word=ik.next())!=null) { result.append(word.getLexemeText()).append(" "); } } catch (IOException ex) { throw new RuntimeException(ex); } return result.toString(); } @Override public List<String> seg(String text) { List<String> list = new ArrayList<>(); list.add(segText(text, true)); list.add(segText(text, false)); return list; } public static void main(String[] args) throws Exception{ new IKAnalyzerEvaluation().run(); } }
package org.appwork.swing.exttable.columns; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.regex.Pattern; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JTextField; import javax.swing.border.Border; import org.appwork.app.gui.MigPanel; import org.appwork.swing.exttable.ExtColumn; import org.appwork.swing.exttable.ExtDefaultRowSorter; import org.appwork.swing.exttable.ExtTableModel; import org.appwork.utils.swing.renderer.RenderLabel; import org.appwork.utils.swing.renderer.RendererMigPanel; public abstract class ExtTextColumn<E> extends ExtColumn<E> implements ActionListener, FocusListener { private static final long serialVersionUID = 2114805529462086691L; protected RenderLabel rendererField; protected JTextField editorField; private final Border defaultBorder = BorderFactory.createEmptyBorder(0, 5, 0, 5); private Color rendererForeground; private Color editorForeground; private Font rendererFont; private Font editorFont; protected MigPanel editor; protected RenderLabel rendererIcon; protected MigPanel renderer; private RenderLabel editorIconLabel; protected boolean noset = false; /** * @param string */ public ExtTextColumn(final String name) { this(name, null); } public ExtTextColumn(final String name, final ExtTableModel<E> table) { super(name, table); this.editorField = new JTextField(); this.editorField.addFocusListener(this); this.editorField.setBorder(null); this.rendererIcon = new RenderLabel() { private static final long serialVersionUID = 1L; @Override public void setIcon(final Icon icon) { this.setVisible(icon != null); if (icon != getIcon()) { super.setIcon(icon); } } }; this.editorField.addKeyListener(new KeyListener() { public void keyPressed(final KeyEvent e) { } public void keyReleased(final KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { ExtTextColumn.this.noset = true; try { ExtTextColumn.this.stopCellEditing(); } finally { ExtTextColumn.this.noset = false; } } } public void keyTyped(final KeyEvent e) { } }); this.rendererIcon.setOpaque(false); this.editorIconLabel = new RenderLabel() { private static final long serialVersionUID = 1L; @Override public void setIcon(final Icon icon) { this.setVisible(icon != null); super.setIcon(icon); } }; this.editorIconLabel.setOpaque(false); this.rendererField = new RenderLabel() { private static final long serialVersionUID = 1L; public void setText(String text) { if (text != getText()) { super.setText(text); } } @Override public void setIcon(final Icon icon) { ExtTextColumn.this.rendererIcon.setIcon(icon); } }; this.editorField.setOpaque(false); this.editorField.putClientProperty("Synthetica.opaque", Boolean.FALSE); this.rendererForeground = this.rendererField.getForeground(); this.editorForeground = this.editorField.getForeground(); this.rendererFont = this.rendererField.getFont(); this.editorFont = this.editorField.getFont(); this.editor = new MigPanel("ins 0", "[]5[grow,fill]", "[grow,fill]"); this.renderer = new RendererMigPanel("ins 0", "[]0[grow,fill]", "[grow,fill]"); this.layoutEditor(this.editor, this.editorIconLabel, this.editorField); this.layoutRenderer(this.renderer, this.rendererIcon, this.rendererField); this.setRowSorter(new ExtDefaultRowSorter<E>() { @Override public int compare(final E o1, final E o2) { String o1s = ExtTextColumn.this.getStringValue(o1); String o2s = ExtTextColumn.this.getStringValue(o2); if (o1s == null) { o1s = ""; } if (o2s == null) { o2s = ""; } if (this.getSortOrderIdentifier() != ExtColumn.SORT_ASC) { return o1s.compareTo(o2s); } else { return o2s.compareTo(o1s); } } }); } public void actionPerformed(final ActionEvent e) { this.editorField.removeActionListener(this); this.fireEditingStopped(); } protected void configureCurrentlyEditingComponent(E value, boolean isSelected, int row, int column) { this.editorIconLabel.setIcon(this.getIcon(value)); } @Override public void configureEditorComponent(final E value, final boolean isSelected, final int row, final int column) { this.editorField.removeActionListener(this); String str = this.getStringValue(value); if (str == null) { // under substance, setting setText(null) somehow sets the label // opaque. str = ""; } this.editorField.setText(str); this.editorField.addActionListener(this); this.editorIconLabel.setIcon(this.getIcon(value)); } @Override public void configureRendererComponent(final E value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { String str = this.getStringValue(value); if (str == null) { // under substance, setting setText(null) somehow sets the label // opaque. str = ""; } this.rendererField.setText(str); this.rendererIcon.setIcon(this.getIcon(value)); } @Override public void focusGained(final FocusEvent e) { this.editorField.selectAll(); } @Override public void focusLost(final FocusEvent e) { // TODO Auto-generated method stub System.out.println(2); } @Override public Object getCellEditorValue() { return this.editorField.getText(); } /** * @return */ @Override public JComponent getEditorComponent(final E value, final boolean isSelected, final int row, final int column) { return this.editor; } /* * @param value * * @return */ protected Icon getIcon(final E value) { return null; } /** * @return */ @Override public JComponent getRendererComponent(final E value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { return this.renderer; } public abstract String getStringValue(E value); @Override protected String getTooltipText(final E obj) { return this.getStringValue(obj); } @Override public boolean isEditable(final E obj) { return false; } @Override public boolean isEnabled(final E obj) { return true; } @Override public boolean isSortable(final E obj) { return true; } /** * @param editor2 * @param editorIconLabel2 * @param editorField2 */ protected void layoutEditor(final MigPanel editor, final RenderLabel editorIconLabel, final JTextField editorField) { editor.add(editorIconLabel, "hidemode 2"); editor.add(editorField); } /** * @param rendererField * @param rendererIco * @param renderer2 */ protected void layoutRenderer(final MigPanel renderer, final RenderLabel rendererIcon, final RenderLabel rendererField) { renderer.add(rendererIcon, "hidemode 2"); renderer.add(rendererField); } @Override public boolean matchSearch(final E object, final Pattern pattern) { return pattern.matcher(this.getStringValue(object)).matches(); } @Override public void resetEditor() { editor.setEnabled(true); this.editorField.setFont(this.editorFont); this.editorField.setForeground(this.editorForeground); this.editorField.setOpaque(false); this.editorField.setBackground(null); this.editor.setOpaque(false); this.editorIconLabel.setIcon(null); } @Override public void resetRenderer() { renderer.setEnabled(true); this.rendererField.setBorder(this.defaultBorder); this.rendererField.setOpaque(false); this.rendererField.setBackground(null); this.rendererField.setFont(this.rendererFont); this.rendererField.setForeground(this.rendererForeground); this.renderer.setOpaque(false); this.rendererIcon.setIcon(null); } // /** // * @param value // */ // protected void prepareLabel(final E value) { // /** // * @param label2 // */ // protected void prepareLabelForHelpText(final JLabel label) { // label.setForeground(Color.lightGray); // /** // * Should be overwritten to prepare the component for the TableCellEditor // * (e.g. setting tooltips) // */ // protected void prepareTableCellEditorComponent(final JTextField text) { // protected void prepareTextfieldForHelpText(final JTextField tf) { // tf.setForeground(Color.lightGray); /** * Override to save value after editing * * @param value * @param object */ protected void setStringValue(final String value, final E object) { } @Override public void setValue(final Object value, final E object) { if (!this.noset) { this.setStringValue((String) value, object); } } }
package io.sento; public final class SentoFactory { public static Binding<Object> createBinding(final Class<?> clazz) { throw new UnsupportedOperationException("This class will never be used in runtime. The real implementation will be generated by sento plugin."); } }
package org.bitbucket.ardimaster.guarddogs; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Wolf; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List; import java.util.Random; public class EventListener implements Listener { protected GuardDogs plugin; public EventListener(GuardDogs plugin) { this.plugin = plugin; } @EventHandler public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { if (!(event.getRightClicked() instanceof Wolf)) { return; } Wolf wolf = (Wolf) event.getRightClicked(); Player player = event.getPlayer(); if (player.getItemInHand().getType().equals(Material.PUMPKIN_SEEDS)) { if (!wolf.isTamed()) { player.sendMessage(ChatColor.RED + "You can't make this dog your guard dog as it isn't tamed!"); return; } if (!wolf.getOwner().equals(player)) { player.sendMessage(ChatColor.RED + "You can't make this dog your guard dog as it isn't yours!"); return; } if (plugin.createGuard(wolf)) { player.getInventory().removeItem(new ItemStack(Material.PUMPKIN_SEEDS, 1)); player.sendMessage(ChatColor.DARK_GREEN + "Guard dog" + ChatColor.GREEN + " ready for action"); wolf.setSitting(true); } else { player.sendMessage(ChatColor.RED + "This is already your guard dog!"); } } else if (player.getItemInHand().getType().equals(Material.STICK)) { if (!wolf.isTamed() || !wolf.getOwner().equals(player)) { player.sendMessage(ChatColor.RED + "This isn't your dog. Thus, it can't be your guard dog. " + "Thus, you can't disable it."); return; } if (plugin.removeGuard(wolf, player)) { player.sendMessage(ChatColor.DARK_GREEN + "Guard dog " + ChatColor.AQUA + "disabled."); } else { player.sendMessage(ChatColor.RED + "This isn't a guard dog, it's just a normal dog!"); } } } @EventHandler public void onEntityDeath(EntityDeathEvent event){ if (event.getEntity() instanceof Wolf) { Wolf wolf = (Wolf) event.getEntity(); plugin.deadGuard(wolf); } LivingEntity deadEntity = event.getEntity(); if (plugin.guardTargets.containsValue(deadEntity)) { for (Wolf wolf : plugin.guards) { if (plugin.guardTargets.get(wolf).equals(deadEntity)) { wolf.setSitting(true); // TODO: Teleport guard back to its original location } } } } // TODO: Move to syncRepeatedTask running every 5 Ticks and extend. @EventHandler public void onPlayerMove(PlayerMoveEvent event) { Player player = event.getPlayer(); LivingEntity playerEntity = player; ArrayList<LivingEntity> near = new ArrayList<>(); Random rand = new Random(); double radius = 15d; for (Wolf wolf : plugin.guards) { if (!wolf.isSitting()) { continue; } List<LivingEntity> all = wolf.getLocation().getWorld().getLivingEntities(); for (LivingEntity e : all) { if (e.getLocation().distance(wolf.getLocation()) <= radius) { if (wolf.getOwner().equals(player) && e.equals(playerEntity)) { continue; } if (e instanceof Wolf) { if (plugin.guards.contains(e)) { continue; } } near.add(e); } } LivingEntity target = near.get(rand.nextInt(near.size())); plugin.guardTargets.put(wolf, target); wolf.setSitting(false); wolf.damage(0d, target); } } }
package org.bouncycastle.mail.smime; import java.io.IOException; import java.io.OutputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.cert.CertStore; import java.security.cert.CertStoreException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.activation.CommandMap; import javax.activation.MailcapCommandMap; import javax.mail.MessagingException; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.cms.CMSException; import org.bouncycastle.cms.CMSSignedDataStreamGenerator; import com.sun.mail.util.CRLFOutputStream; /** * general class for generating a pkcs7-signature message. * <p> * A simple example of usage. * * <pre> * CertStore certs... * SMIMESignedGenerator fact = new SMIMESignedGenerator(); * * fact.addSigner(privKey, cert, SMIMESignedGenerator.DIGEST_SHA1); * fact.addCertificatesAndCRLs(certs); * * MimeMultipart smime = fact.generate(content, "BC"); * </pre> * <p> * Note: if you are using this class with AS2 or some other protocol * that does not use "7bit" as the default content transfer encoding you * will need to use the constructor that allows you to specify the default * content transfer encoding, such as "binary". * </p> */ public class SMIMESignedGenerator extends SMIMEGenerator { static final String CERTIFICATE_MANAGEMENT_CONTENT = "application/pkcs7-mime; name=smime.p7c; smime-type=certs-only"; private static final String DETACHED_SIGNATURE_TYPE = "application/pkcs7-signature; name=smime.p7s; smime-type=signed-data"; private static final String ENCAPSULATED_SIGNED_CONTENT_TYPE = "application/pkcs7-mime; name=smime.p7m; smime-type=signed-data"; public static final String DIGEST_SHA1 = "1.3.14.3.2.26"; public static final String DIGEST_MD5 = "1.2.840.113549.2.5"; public static final String DIGEST_SHA224 = NISTObjectIdentifiers.id_sha224.getId(); public static final String DIGEST_SHA256 = NISTObjectIdentifiers.id_sha256.getId(); public static final String DIGEST_SHA384 = NISTObjectIdentifiers.id_sha384.getId(); public static final String DIGEST_SHA512 = NISTObjectIdentifiers.id_sha512.getId(); public static final String ENCRYPTION_RSA = "1.2.840.113549.1.1.1"; public static final String ENCRYPTION_DSA = "1.2.840.10040.4.3"; private final String _defaultContentTransferEncoding; private List _certStores = new ArrayList(); private List _signers = new ArrayList(); static { MailcapCommandMap mc = (MailcapCommandMap)CommandMap.getDefaultCommandMap(); mc.addMailcap("application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature"); mc.addMailcap("application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime"); mc.addMailcap("application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature"); mc.addMailcap("application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime"); mc.addMailcap("multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed"); CommandMap.setDefaultCommandMap(mc); } /** * base constructor - default content transfer encoding 7bit */ public SMIMESignedGenerator() { _defaultContentTransferEncoding = "7bit"; } /** * base constructor - default content transfer encoding explicitly set * * @param defaultContentTransferEncoding new default to use. */ public SMIMESignedGenerator( String defaultContentTransferEncoding) { _defaultContentTransferEncoding = defaultContentTransferEncoding; } /** * add a signer - no attributes other than the default ones will be * provided here. */ public void addSigner( PrivateKey key, X509Certificate cert, String digestOID) throws IllegalArgumentException { _signers.add(new Signer(key, cert, digestOID, null, null)); } /** * add a signer with extra signed/unsigned attributes. */ public void addSigner( PrivateKey key, X509Certificate cert, String digestOID, AttributeTable signedAttr, AttributeTable unsignedAttr) throws IllegalArgumentException { _signers.add(new Signer(key, cert, digestOID, signedAttr, unsignedAttr)); } /** * add the certificates and CRLs contained in the given CertStore * to the pool that will be included in the encoded signature block. * <p> * Note: this assumes the CertStore will support null in the get * methods. */ public void addCertificatesAndCRLs( CertStore certStore) throws CertStoreException, SMIMEException { _certStores.add(certStore); } private void addHashHeader( StringBuffer header, List signers) { int count = 0; // build the hash header Iterator it = signers.iterator(); Set micAlgs = new HashSet(); while (it.hasNext()) { Signer signer = (Signer)it.next(); if (signer.getDigestOID().equals(DIGEST_SHA1)) { micAlgs.add("sha1"); } else if (signer.getDigestOID().equals(DIGEST_MD5)) { micAlgs.add("md5"); } else if (signer.getDigestOID().equals(DIGEST_SHA224)) { micAlgs.add("sha224"); } else if (signer.getDigestOID().equals(DIGEST_SHA256)) { micAlgs.add("sha256"); } else if (signer.getDigestOID().equals(DIGEST_SHA384)) { micAlgs.add("sha384"); } else if (signer.getDigestOID().equals(DIGEST_SHA512)) { micAlgs.add("sha512"); } else { header.append("unknown"); } } it = micAlgs.iterator(); while (it.hasNext()) { String alg = (String)it.next(); if (count == 0) { if (micAlgs.size() != 1) { header.append("; micalg=\""); } else { header.append("; micalg="); } } else { header.append(","); } header.append(alg); count++; } if (count != 0) { if (micAlgs.size() != 1) { header.append("\""); } } } /** * at this point we expect our body part to be well defined. */ private MimeMultipart make( MimeBodyPart content, String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, SMIMEException { try { MimeBodyPart sig = new MimeBodyPart(); sig.setContent(new ContentSigner(content, false, sigProvider), DETACHED_SIGNATURE_TYPE); sig.addHeader("Content-Type", DETACHED_SIGNATURE_TYPE); sig.addHeader("Content-Disposition", "attachment; filename=\"smime.p7s\""); sig.addHeader("Content-Description", "S/MIME Cryptographic Signature"); sig.addHeader("Content-Transfer-Encoding", encoding); // build the multipart header StringBuffer header = new StringBuffer( "signed; protocol=\"application/pkcs7-signature\""); addHashHeader(header, _signers); MimeMultipart mm = new MimeMultipart(header.toString()); mm.addBodyPart(content); mm.addBodyPart(sig); return mm; } catch (MessagingException e) { throw new SMIMEException("exception putting multi-part together.", e); } } /** * at this point we expect our body part to be well defined - generate with data in the signature */ private MimeBodyPart makeEncapsulated( MimeBodyPart content, String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, SMIMEException { try { MimeBodyPart sig = new MimeBodyPart(); sig.setContent(new ContentSigner(content, true, sigProvider), ENCAPSULATED_SIGNED_CONTENT_TYPE); sig.addHeader("Content-Type", ENCAPSULATED_SIGNED_CONTENT_TYPE); sig.addHeader("Content-Disposition", "attachment; filename=\"smime.p7m\""); sig.addHeader("Content-Description", "S/MIME Cryptographic Signed Data"); sig.addHeader("Content-Transfer-Encoding", encoding); return sig; } catch (MessagingException e) { throw new SMIMEException("exception putting body part together.", e); } } /** * generate a signed object that contains an SMIME Signed Multipart * object using the given provider. */ public MimeMultipart generate( MimeBodyPart content, String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, SMIMEException { return make(makeContentBodyPart(content), sigProvider); } /** * generate a signed object that contains an SMIME Signed Multipart * object using the given provider from the given MimeMessage */ public MimeMultipart generate( MimeMessage message, String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, SMIMEException { try { message.saveChanges(); // make sure we're up to date. } catch (MessagingException e) { throw new SMIMEException("unable to save message", e); } return make(makeContentBodyPart(message), sigProvider); } /** * generate a signed message with encapsulated content * <p> * Note: doing this is strongly <b>not</b> recommended as it means a * recipient of the message will have to be able to read the signature to read the * message. */ public MimeBodyPart generateEncapsulated( MimeBodyPart content, String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, SMIMEException { return makeEncapsulated(makeContentBodyPart(content), sigProvider); } /** * generate a signed object that contains an SMIME Signed Multipart * object using the given provider from the given MimeMessage. * <p> * Note: doing this is strongly <b>not</b> recommended as it means a * recipient of the message will have to be able to read the signature to read the * message. */ public MimeBodyPart generateEncapsulated( MimeMessage message, String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, SMIMEException { try { message.saveChanges(); // make sure we're up to date. } catch (MessagingException e) { throw new SMIMEException("unable to save message", e); } return makeEncapsulated(makeContentBodyPart(message), sigProvider); } /** * Creates a certificate management message which is like a signed message with no content * or signers but that still carries certificates and CRLs. * * @return a MimeBodyPart containing the certs and CRLs. */ public MimeBodyPart generateCertificateManagement( String provider) throws SMIMEException, NoSuchProviderException { try { MimeBodyPart sig = new MimeBodyPart(); sig.setContent(new ContentSigner(null, true, provider), CERTIFICATE_MANAGEMENT_CONTENT); sig.addHeader("Content-Type", CERTIFICATE_MANAGEMENT_CONTENT); sig.addHeader("Content-Disposition", "attachment; filename=\"smime.p7c\""); sig.addHeader("Content-Description", "S/MIME Certificate Management Message"); sig.addHeader("Content-Transfer-Encoding", encoding); return sig; } catch (MessagingException e) { throw new SMIMEException("exception putting body part together.", e); } } private class Signer { final PrivateKey key; final X509Certificate cert; final String digestOID; final AttributeTable signedAttr; final AttributeTable unsignedAttr; Signer( PrivateKey key, X509Certificate cert, String digestOID, AttributeTable signedAttr, AttributeTable unsignedAttr) { this.key = key; this.cert = cert; this.digestOID = digestOID; this.signedAttr = signedAttr; this.unsignedAttr = unsignedAttr; } public X509Certificate getCert() { return cert; } public String getDigestOID() { return digestOID; } public PrivateKey getKey() { return key; } public AttributeTable getSignedAttr() { return signedAttr; } public AttributeTable getUnsignedAttr() { return unsignedAttr; } } private class ContentSigner implements SMIMEStreamingProcessor { private final MimeBodyPart _content; private final boolean _encapsulate; private final String _provider; ContentSigner( MimeBodyPart content, boolean encapsulate, String provider) { _content = content; _encapsulate = encapsulate; _provider = provider; } protected CMSSignedDataStreamGenerator getGenerator() throws CMSException, CertStoreException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); Iterator it = _certStores.iterator(); while (it.hasNext()) { gen.addCertificatesAndCRLs((CertStore)it.next()); } it = _signers.iterator(); while (it.hasNext()) { Signer signer = (Signer)it.next(); gen.addSigner(signer.getKey(), signer.getCert(), signer.getDigestOID(), signer.getSignedAttr(), signer.getUnsignedAttr(), _provider); } return gen; } public void write(OutputStream out) throws IOException { try { CMSSignedDataStreamGenerator gen = getGenerator(); OutputStream signingStream = gen.open(out, _encapsulate); if (_content != null) { if (!_encapsulate) { if (SMIMEUtil.isCanonicalisationRequired(_content, _defaultContentTransferEncoding)) { signingStream = new CRLFOutputStream(signingStream); } } _content.writeTo(signingStream); } signingStream.close(); } catch (MessagingException e) { throw new IOException(e.toString()); } catch (NoSuchAlgorithmException e) { throw new IOException(e.toString()); } catch (NoSuchProviderException e) { throw new IOException(e.toString()); } catch (CMSException e) { throw new IOException(e.toString()); } catch (InvalidKeyException e) { throw new IOException(e.toString()); } catch (CertStoreException e) { throw new IOException(e.toString()); } } } }
package org.exist.xquery.functions.xmldb; import org.apache.log4j.Logger; import org.exist.EXistException; import org.exist.dom.DocumentSet; import org.exist.dom.NodeSet; import org.exist.dom.QName; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.update.Modification; import org.exist.xquery.value.FunctionParameterSequenceType; import org.exist.xquery.value.IntegerValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.Type; /** * Implments the xmldb:defragment() function. * * */ public class XMLDBDefragment extends BasicFunction { private static final Logger logger = Logger.getLogger(XMLDBDefragment.class); public final static FunctionSignature signatures[] = { new FunctionSignature( new QName("defragment", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX), "Start a defragmentation run on each document which has a node in $nodes. " + "Fragmentation may occur if nodes are inserted into a document using XQuery update " + "extensions. " + "The second argument specifies the minimum number of fragmented pages which should " + "be in a document before it is considered for defragmentation. " + "Please note that defragmenting a document changes its internal structure, so any " + "references to this document will become invalid, in particular, variables pointing to " + "some nodes in the document.", new SequenceType[] { new FunctionParameterSequenceType("nodes", Type.NODE, Cardinality.ONE_OR_MORE, "The sequence of nodes from the documents to defragment"), new FunctionParameterSequenceType("integer", Type.INTEGER, Cardinality.EXACTLY_ONE, "The minimum number of fragmented pages required before defragmenting") }, new SequenceType(Type.ITEM, Cardinality.EMPTY)), new FunctionSignature( new QName("defragment", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX), "Start a defragmentation run on each document which has a node in $nodes. " + "Fragmentation may occur if nodes are inserted into a document using XQuery update " + "extensions. " + "Please note that defragmenting a document changes its internal structure, so any " + "references to this document will become invalid, in particular, variables pointing to " + "some nodes in the document.", new SequenceType[] { new FunctionParameterSequenceType("nodes", Type.NODE, Cardinality.ONE_OR_MORE, "The sequence of nodes from the documents to defragment"), }, new SequenceType(Type.ITEM, Cardinality.EMPTY)) }; public XMLDBDefragment(XQueryContext context, FunctionSignature signature) { super(context, signature); } /* (non-Javadoc) * @see org.exist.xquery.Expression#eval(org.exist.dom.DocumentSet, org.exist.xquery.value.Sequence, org.exist.xquery.value.Item) */ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { // Get nodes NodeSet nodes = args[0].toNodeSet(); DocumentSet docs = nodes.getDocumentSet(); try { if (args.length > 1) { // Use supplied parameter int splitCount = ((IntegerValue)args[1].itemAt(0)).getInt(); Modification.checkFragmentation(context, docs, splitCount); } else { // Use conf.xml configured value or -1 if not existent Modification.checkFragmentation(context, docs); } } catch (EXistException e) { logger.error("An error occurred while defragmenting documents: " + e.getMessage()); throw new XPathException("An error occurred while defragmenting documents: " + e.getMessage(), e); } return Sequence.EMPTY_SEQUENCE; } }
package org.gridlab.gridsphere.tools; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import java.io.*; import java.util.Enumeration; import java.util.List; import java.util.Vector; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; public class DeployGridSphereTCK extends Task { private String warPath = null; private String buildDir = null; private String catalina = null; private List portlets = new Vector(); private List portletapps = new Vector(); private class WARFilenameFilter implements FilenameFilter { public boolean accept(File dir, String name) { if (name.endsWith(".war")) return true; return false; } } public void setWarDir(String warDir) { this.warPath = warDir; //System.out.println("Setting configdir to: "+this.configDir); } public void setBuildDir(String buildDir) { this.buildDir = buildDir; } public void setServer(String serverDir) { this.catalina = serverDir; } /** * Tool to transform Sun TCK portlet WAR's to GridSphere JSR model */ public void execute() throws BuildException { System.out.println("GridSphere tool to deploy Sun TCK portlet WAR files as "); System.out.println(" GridSphere JSR portlet applications and create a test layout descriptor"); try { loadWars(warPath); createLayout(); deployPortlets(); } catch (IOException e) { System.err.println("Error converting WARS:"); e.printStackTrace(); } } private void deployPortlets() throws IOException { String portletsDir = catalina + File.separator + "webapps" + File.separator + "gridsphere" + File.separator + "WEB-INF" + File.separator + "CustomPortal" + File.separator + "portlets" + File.separator; File tmp = null; for (int i = 0; i < portletapps.size(); i++) { tmp = new File(portletsDir + portletapps.get(i)); tmp.createNewFile(); } } private void createLayout() throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("guest-layout-tck.xml"))); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<page-layout theme=\"xp\" title=\"GridSphere Portal\">"); out.println("<portlet-header/>"); out.print("<portlet-tabbed-pane selected=\"0\" style=\"menu\">\n" + " <portlet-tab label=\"gridsphere\">\n" + " <title lang=\"en\">GridSphere</title>"); System.err.println("Number of portlets: " + portlets.size()); for (int i = 0; i < portlets.size(); i++) { System.err.println((String) portlets.get(i)); out.println("<portlet-frame>"); out.println("<portlet-class>" + (String) portlets.get(i) + "</portlet-class>"); out.println("</portlet-frame>"); } out.println("</portlet-tab></portlet-tabbed-pane></page-layout"); out.close(); } private void loadWars(String warPath) throws IOException { File warDir = new File(warPath); if (!warDir.isDirectory()) { throw new IOException("Specified TCK directory not valid: " + warPath); } String[] warFiles = warDir.list(new WARFilenameFilter()); byte[] buffer = new byte[1024]; int bytesRead; // loop thru all WARs for (int i = 0; i < warFiles.length; i++) { //System.err.println(warPath + File.separator + warFiles[i].toString()); String war = warFiles[i].substring(0, warFiles[i].indexOf(".war")); portletapps.add(war); JarFile jarFile = new JarFile(warPath + File.separator + warFiles[i]); JarOutputStream tempJar = new JarOutputStream(new FileOutputStream(System.getProperty("java.io.tmpdir") + File.separator + warFiles[i].toString())); addGridSphereJSRDescriptor(tempJar); addGridSphereTagLibs(tempJar); addLogProps(tempJar); // loop thru all jars Enumeration files = jarFile.entries(); while (files.hasMoreElements()) { JarEntry entry = (JarEntry) files.nextElement(); //System.err.println("\t\t" + entry.getName()); if (entry.getName().equals("WEB-INF/web.xml")) { InputStream entryStream = jarFile.getInputStream(entry); modifyWebXML(entryStream, tempJar, warFiles[i]); break; } if (entry.getName().equals("WEB-INF/portlet.xml")) { InputStream entryStream = jarFile.getInputStream(entry); collectPortletNames(war, entryStream); } tempJar.putNextEntry(entry); InputStream entryStream = jarFile.getInputStream(entry); // Read the entry and write it to the temp jar. while ((bytesRead = entryStream.read(buffer)) != -1) { tempJar.write(buffer, 0, bytesRead); } } tempJar.close(); jarFile.close(); } } public synchronized void modifyWebXML(InputStream webxmlStream, JarOutputStream tempJar, String warname) throws IOException { BufferedReader bis = new BufferedReader(new InputStreamReader(webxmlStream)); String line = null; String war = warname.substring(0, warname.indexOf(".war")); JarEntry entry = new JarEntry("WEB-INF" + File.separator + "web.xml"); tempJar.putNextEntry(entry); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("tmp.xml"))); boolean hasServletEntry = false; boolean domapping = false; while ((line = bis.readLine()) != null) { if (line.endsWith("<servlet-mapping>") && (!hasServletEntry)) { out.println(" <servlet>"); out.println(" <servlet-name>PortletServlet</servlet-name>"); out.println(" <servlet-class>org.gridlab.gridsphere.provider.portlet.jsr.PortletServlet</servlet-class>"); out.println(" </servlet>"); out.println(line); domapping = true; hasServletEntry = true; } else if (line.endsWith("<session-config>") && (!hasServletEntry)) { out.println(" <servlet>"); out.println(" <servlet-name>PortletServlet</servlet-name>"); out.println(" <servlet-class>org.gridlab.gridsphere.provider.portlet.jsr.PortletServlet</servlet-class>"); out.println(" </servlet>"); out.println(" <servlet-mapping>"); out.println(" <servlet-name>PortletServlet</servlet-name>"); out.println(" <url-pattern>/jsr/" + war + "</url-pattern>"); out.println(" </servlet-mapping>"); out.println(line); hasServletEntry = true; } else if ((line.endsWith("</web-app>")) && (!hasServletEntry)) { out.println(" <servlet>"); out.println(" <servlet-name>PortletServlet</servlet-name>"); out.println(" <servlet-class>org.gridlab.gridsphere.provider.portlet.jsr.PortletServlet</servlet-class>"); out.println(" </servlet>"); out.println(" <servlet-mapping>"); out.println(" <servlet-name>PortletServlet</servlet-name>"); out.println(" <url-pattern>/jsr/" + war + "</url-pattern>"); out.println(" </servlet-mapping>"); out.println("</web-app>"); } else if ((domapping) && (line.endsWith("<session-config>") || (line.endsWith("<web-app>")))) { out.println(" <servlet-mapping>"); out.println(" <servlet-name>PortletServlet</servlet-name>"); out.println(" <url-pattern>/jsr/" + war + "</url-pattern>"); out.println(" </servlet-mapping>"); out.println(line); hasServletEntry = true; } else { out.println(line); } } out.close(); bis.close(); // Open the given file. FileInputStream file = new FileInputStream("tmp.xml"); byte[] buffer = new byte[1024]; int bytesRead; try { // Read the file and write it to the jar. while ((bytesRead = file.read(buffer)) != -1) { tempJar.write(buffer, 0, bytesRead); } System.out.println(entry.getName() + " added."); } finally { file.close(); } } public void addGridSphereJSRDescriptor(JarOutputStream tempJar) throws IOException { String fileName = "config" + File.separator + "template" + File.separator + "gridsphere-portlet-jsr.xml"; byte[] buffer = new byte[1024]; int bytesRead; // Open the given file. FileInputStream file = new FileInputStream(fileName); try { // Create a jar entry and add it to the temp jar. JarEntry entry = new JarEntry("WEB-INF" + File.separator + "gridsphere-portlet.xml"); tempJar.putNextEntry(entry); // Read the file and write it to the jar. while ((bytesRead = file.read(buffer)) != -1) { tempJar.write(buffer, 0, bytesRead); } System.out.println(entry.getName() + " added."); } finally { file.close(); } } public void addLogProps(JarOutputStream tempJar) throws IOException { String fileName = "config" + File.separator + "log4j.properties"; byte[] buffer = new byte[1024]; int bytesRead; // Open the given file. FileInputStream file = new FileInputStream(fileName); try { // Create a jar entry and add it to the temp jar. JarEntry entry = new JarEntry("WEB-INF" + File.separator + "classes" + File.separator + "log4j.properties"); tempJar.putNextEntry(entry); // Read the file and write it to the jar. while ((bytesRead = file.read(buffer)) != -1) { tempJar.write(buffer, 0, bytesRead); } System.out.println(entry.getName() + " added."); } finally { file.close(); } } public void addGridSphereTagLibs(JarOutputStream tempJar) throws IOException { String fileName = buildDir + File.separator + "lib" + File.separator + "gridsphere-ui-tags-2.1.jar"; byte[] buffer = new byte[1024]; int bytesRead; // Open the given file. FileInputStream file = new FileInputStream(fileName); try { // Create a jar entry and add it to the temp jar. JarEntry entry = new JarEntry("WEB-INF" + File.separator + "lib" + File.separator + "gridsphere-ui-tags-2.1.jar"); tempJar.putNextEntry(entry); // Read the file and write it to the jar. while ((bytesRead = file.read(buffer)) != -1) { tempJar.write(buffer, 0, bytesRead); } System.out.println(entry.getName() + " added."); } finally { file.close(); } } public void collectPortletNames(String war, InputStream portletxmlStream) throws IOException { BufferedReader bis = new BufferedReader(new InputStreamReader(portletxmlStream)); String line = null; String portlet = ""; while ((line = bis.readLine()) != null) { //System.err.println("portlet= " + line); if (line.indexOf("<portlet-name>") > 0) { int d = line.indexOf("<portlet-name>"); String p = line.substring(d + "<portlet-name>".length()); int e = p.indexOf("</portlet-name>"); portlet = p.substring(0, e); portlets.add(war + "#" + portlet); } } bis.close(); } }
package org.irmacard.cardemu.selfenrol.mno; import android.os.AsyncTask; import android.util.Log; import net.sf.scuba.smartcards.CardServiceException; import org.irmacard.credentials.Attributes; import org.irmacard.credentials.idemix.IdemixCredentials; import org.irmacard.credentials.idemix.info.IdemixKeyStore; import org.irmacard.credentials.info.CredentialDescription; import org.irmacard.credentials.info.DescriptionStore; import org.irmacard.idemix.IdemixService; import org.jmrtd.BACKey; import org.jmrtd.PassportService; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.security.Security; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class MNOEnrollImpl implements MNOEnrol { // private SubscriberDatabase subscribers; private SimpleDateFormat shortDate; private String TAG = "MNOImpl"; public MNOEnrollImpl (SubscriberDatabase subscribers) { // this.subscribers = subscribers; this.shortDate = new SimpleDateFormat ("yyMMdd"); } public MNOEnrolResult enroll(String subscriberID, SubscriberInfo subscriberInfo, byte[] pin, PassportService passportService, IdemixService idemixService) { MNOEnrolResult result = MNOEnrolResult.SUCCESS; //SubscriberInfo subscriberInfo = null; // subscriberInfo = subscribers.getSubscriber (subscriberID); if (subscriberInfo == null) { result = MNOEnrolResult.UNKNOWN_SUBSCRIBER; Log.d(TAG,"MNO Impl, did not find a matching subscriber"); } if (result != MNOEnrolResult.SUCCESS) return result; result = checkPassport (subscriberInfo, passportService); //result = checkPassport(subscriberID,passportService); if (result != MNOEnrolResult.SUCCESS) return result; result = issueMNOCredential (subscriberInfo, pin, idemixService); if (result != MNOEnrolResult.SUCCESS) return result; return result; } //TEST FUNCTION WHICH retieves data again from it's own db. private MNOEnrolResult checkPassport (String subscriberId, PassportService passportService) { MNOEnrolResult result = MNOEnrolResult.SUCCESS; SubscriberInfo subscriberInfo = new MockupSubscriberDatabase().getSubscriber(subscriberId); String passportNumber = subscriberInfo.passportNumber; String dateOfBirth = shortDate.format (subscriberInfo.dateOfBirth); String expiryDate = shortDate.format(subscriberInfo.passportExpiryDate); BACKey bacKey = new BACKey (passportNumber, dateOfBirth, expiryDate); try { passportService.sendSelectApplet (false); passportService.doBAC (bacKey); } catch (CardServiceException e) { /* BAC failed */ e.printStackTrace(); result = MNOEnrolResult.PASSPORT_CHECK_FAILED; } return result; } private MNOEnrolResult checkPassport (SubscriberInfo subscriberInfo, PassportService passportService) { MNOEnrolResult result = MNOEnrolResult.SUCCESS; String passportNumber = subscriberInfo.passportNumber; String dateOfBirth = shortDate.format (subscriberInfo.dateOfBirth); String expiryDate = shortDate.format(subscriberInfo.passportExpiryDate); BACKey bacKey = new BACKey (passportNumber, dateOfBirth, expiryDate); try { // Spongycastle provides the MAC ISO9797Alg3Mac, which JMRTD uses // in the doBAC method below (at DESedeSecureMessagingWrapper.java, // line 115) // TODO examine if Android's BouncyCastle version causes other problems; // perhaps we should use SpongyCastle over all projects. Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider()); passportService.sendSelectApplet(false); passportService.doBAC (bacKey); } catch (CardServiceException e) { /* BAC failed */ e.printStackTrace(); result = MNOEnrolResult.PASSPORT_CHECK_FAILED; } return result; } private MNOEnrolResult issueMNOCredential (SubscriberInfo subscriberInfo, byte[] pin, IdemixService idemixService) { MNOEnrolResult result = MNOEnrolResult.SUCCESS; Attributes attributes = new Attributes(); attributes.add ("docNr", subscriberInfo.passportNumber.getBytes()); String issuer = "KPN"; String credential = "kpnSelfEnrolDocNr"; CredentialDescription cd = null; try { Date expiryDate = new Date (); Calendar c = Calendar.getInstance(); c.setTime (expiryDate); c.add (Calendar.DATE, 1); expiryDate = c.getTime(); cd = DescriptionStore.getInstance ().getCredentialDescriptionByName (issuer, credential); IdemixCredentials ic = new IdemixCredentials (idemixService); ic.connect(); idemixService.sendPin (pin); ic.issue (cd, IdemixKeyStore.getInstance().getSecretKey(cd), attributes, expiryDate); } catch (Exception e) { Log.e(TAG, e.toString()); e.printStackTrace(); result = MNOEnrolResult.ISSUANCE_FAILED; } return result; } }
package foam.nanos.crunch; import foam.core.FObject; import foam.core.X; import foam.dao.ArraySink; import foam.dao.DAO; import foam.mlang.predicate.Predicate; import foam.nanos.auth.Subject; import foam.nanos.auth.User; import foam.nanos.logger.Logger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Queue; import static foam.mlang.MLang.*; public class ServerCrunchService implements CrunchService { public List getGrantPath(X x, String rootId) { Logger logger = (Logger) x.get("logger"); DAO prerequisiteDAO = (DAO) x.get("prerequisiteCapabilityJunctionDAO"); DAO capabilityDAO = (DAO) x.get("capabilityDAO"); // Lookup for indices of previously observed capabilities List<String> alreadyListed = new ArrayList<String>(); // List of capabilities required to grant the desired capability. // Throughout the traversial algorithm this list starts with parents of // prerequisites appearing earlier in the list. Before returning, this // list is reversed so that the caller receives capabilities in order of // expected completion (i.e. pre-order traversial) List grantPath = new ArrayList<>(); Queue<String> nextSources = new ArrayDeque<String>(); nextSources.add(rootId); // Doing this instead of "this" could prevent unexpected behaviour // in the incident CrunchService's getJunction method is decorated CrunchService crunchService = (CrunchService) x.get("crunchService"); while ( nextSources.size() > 0 ) { String sourceCapabilityId = nextSources.poll(); UserCapabilityJunction ucj = crunchService.getJunction(x, sourceCapabilityId); if ( ucj != null && ucj.getStatus() == CapabilityJunctionStatus.GRANTED ) { continue; } if ( alreadyListed.contains(sourceCapabilityId) ) continue; // Add capability to grant path, and remember index in case it's replaced Capability cap = (Capability) capabilityDAO.find(sourceCapabilityId); alreadyListed.add(sourceCapabilityId); if ( cap instanceof MinMaxCapability && ! rootId.equals(sourceCapabilityId) ) { grantPath.add(this.getGrantPath(x, sourceCapabilityId)); continue; } grantPath.add(cap); // Enqueue prerequisites for adding to grant path List prereqs = ( (ArraySink) prerequisiteDAO .where(AND( EQ(CapabilityCapabilityJunction.SOURCE_ID, sourceCapabilityId), NOT(IN(CapabilityCapabilityJunction.TARGET_ID, alreadyListed)) )) .select(new ArraySink()) ).getArray(); for ( int i = prereqs.size() - 1; i >= 0; i CapabilityCapabilityJunction prereq = (CapabilityCapabilityJunction) prereqs.get(i); nextSources.add(prereq.getTargetId()); } } Collections.reverse(grantPath); return grantPath; } public UserCapabilityJunction getJunction(X x, String capabilityId) { Subject subject = (Subject) x.get("subject"); return this.getJunctionForSubject(x, capabilityId, subject); } public UserCapabilityJunction getJunctionForSubject( X x, String capabilityId, Subject subject ) { User user = subject.getUser(); User realUser = subject.getRealUser(); Predicate acjPredicate = INSTANCE_OF(AgentCapabilityJunction.class); Predicate targetPredicate = EQ(UserCapabilityJunction.TARGET_ID, capabilityId); try { DAO userCapabilityJunctionDAO = (DAO) x.get("userCapabilityJunctionDAO"); Predicate associationPredicate = OR( AND( NOT(acjPredicate), ( user != realUser ) ? OR( EQ(UserCapabilityJunction.SOURCE_ID, realUser.getId()), EQ(UserCapabilityJunction.SOURCE_ID, user.getId()) ) : EQ(UserCapabilityJunction.SOURCE_ID, realUser.getId()) ), AND( acjPredicate, EQ(UserCapabilityJunction.SOURCE_ID, realUser.getId()), EQ(AgentCapabilityJunction.EFFECTIVE_USER, user.getId()) ) ); UserCapabilityJunction ucj = (UserCapabilityJunction) userCapabilityJunctionDAO.find(AND(associationPredicate,targetPredicate)); if ( ucj != null ) { return ucj; } } catch ( Exception e ) { Logger logger = (Logger) x.get("logger"); logger.error("getJunction", capabilityId, e); } return null; } public void updateJunction(X x, String capabilityId, FObject data) { Subject subject = (Subject) x.get("subject"); UserCapabilityJunction ucj = this.getJunction(x, capabilityId); if ( ucj == null ) { // Need Capability to associate UCJ correctly DAO capabilityDAO = (DAO) x.get("capabilityDAO"); Capability cap = (Capability) capabilityDAO.find(capabilityId); if ( cap == null ) { throw new RuntimeException(String.format( "Capability with id '%s' not found", capabilityId )); } AssociatedEntity associatedEntity = cap.getAssociatedEntity(); boolean isAssociation = associatedEntity == AssociatedEntity.ACTING_USER; User associatedUser = associatedEntity == AssociatedEntity.USER ? subject.getUser() : subject.getRealUser() ; ucj = isAssociation ? new AgentCapabilityJunction.Builder(x) .setSourceId(associatedUser.getId()) .setTargetId(capabilityId) .setEffectiveUser(subject.getUser().getId()) .build() : new UserCapabilityJunction.Builder(x) .setSourceId(associatedUser.getId()) .setTargetId(capabilityId) .build() ; } if ( data != null ) { ucj.setData(data); } DAO userCapabilityJunctionDAO = (DAO) x.get("userCapabilityJunctionDAO"); userCapabilityJunctionDAO.put(ucj); } }
package org.kwstudios.play.ragemode.gameLogic; import java.util.HashMap; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.kwstudios.play.ragemode.scoreboard.ScoreBoard; import org.kwstudios.play.ragemode.scoreboard.ScoreBoardHolder; import org.kwstudios.play.ragemode.toolbox.ConstantHolder; public class RageScores { private static HashMap<String, PlayerPoints> playerpoints = new HashMap<String, PlayerPoints>(); // private static TableList<String, String> playergame = new // instead private static int totalPoints = 0; public static void addPointsToPlayer(Player killer, Player victim, String killCause) { if (!killer.getUniqueId().toString().equals(victim.getUniqueId().toString())) { PlayerPoints killerPoints; PlayerPoints victimPoints; switch (killCause.toLowerCase()) { case "ragebow": int bowPoints = ConstantHolder.POINTS_FOR_BOW_KILL; totalPoints = addPoints(killer, PlayerList.getPlayersGame(killer), bowPoints, true); addPoints(victim, PlayerList.getPlayersGame(victim), 0, false); killerPoints = playerpoints.get(killer.getUniqueId().toString()); int oldDirectArrowKills = killerPoints.getDirectArrowKills(); int newDirectArrowKills = oldDirectArrowKills++; killerPoints.setDirectArrowKills(newDirectArrowKills); victimPoints = playerpoints.get(victim.getUniqueId().toString()); int oldDirectArrowDeaths = victimPoints.getDirectArrowDeaths(); int newDirectArrowDeaths = oldDirectArrowDeaths++; victimPoints.setDirectArrowDeaths(newDirectArrowDeaths); killer.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_AQUA + "You killed " + ChatColor.GOLD.toString() + ChatColor.BOLD.toString() + victim.getName() + ChatColor.RESET.toString() + ChatColor.DARK_AQUA + " with a direct arrow hit. " + ChatColor.GOLD.toString() + ChatColor.BOLD.toString() + "+" + bowPoints); victim.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_AQUA + "You were killed by " + ChatColor.BOLD.toString() + ChatColor.GOLD.toString() + killer.getName()); killer.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_AQUA + "You now have " + ChatColor.BOLD.toString() + ChatColor.GOLD.toString() + totalPoints + ChatColor.RESET.toString() + ChatColor.DARK_AQUA.toString() + " points."); break; case "combataxe": int axePoints = ConstantHolder.POINTS_FOR_AXE_KILL; int axeMinusPoints = ConstantHolder.MINUS_POINTS_FOR_AXE_DEATH; totalPoints = addPoints(killer, PlayerList.getPlayersGame(killer), axePoints, true); addPoints(victim, PlayerList.getPlayersGame(victim), axeMinusPoints, false); killerPoints = playerpoints.get(killer.getUniqueId().toString()); int oldAxeKills = killerPoints.getAxeKills(); int newAxeKills = oldAxeKills++; killerPoints.setAxeKills(newAxeKills); victimPoints = playerpoints.get(victim.getUniqueId().toString()); int oldAxeDeaths = victimPoints.getAxeDeaths(); int newAxeDeaths = oldAxeDeaths++; victimPoints.setAxeDeaths(newAxeDeaths); killer.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_AQUA + "You killed " + ChatColor.GOLD.toString() + ChatColor.BOLD.toString() + victim.getName() + ChatColor.RESET.toString() + ChatColor.DARK_AQUA + " with your CombatAxe. " + ChatColor.GOLD.toString() + ChatColor.BOLD.toString() + "+" + axePoints); victim.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_AQUA + "You were killed by " + ChatColor.BOLD.toString() + ChatColor.GOLD.toString() + killer.getName() + ChatColor.BOLD.toString() + ChatColor.DARK_RED.toString() + axeMinusPoints); killer.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_AQUA + "You now have " + ChatColor.BOLD.toString() + ChatColor.GOLD.toString() + totalPoints + ChatColor.RESET.toString() + ChatColor.DARK_AQUA.toString() + " points."); break; case "rageknife": int knifePoints = ConstantHolder.POINTS_FOR_KNIFE_KILL; totalPoints = addPoints(killer, PlayerList.getPlayersGame(killer), knifePoints, true); addPoints(victim, PlayerList.getPlayersGame(victim), 0, false); killerPoints = playerpoints.get(killer.getUniqueId().toString()); int oldKnifeKills = killerPoints.getKnifeKills(); int newKnifeKills = oldKnifeKills++; killerPoints.setAxeKills(newKnifeKills); victimPoints = playerpoints.get(victim.getUniqueId().toString()); int oldKnifeDeaths = victimPoints.getKnifeDeaths(); int newKnifeDeaths = oldKnifeDeaths++; victimPoints.setAxeDeaths(newKnifeDeaths); killer.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_AQUA + "You killed " + ChatColor.GOLD.toString() + ChatColor.BOLD.toString() + victim.getName() + ChatColor.RESET.toString() + ChatColor.DARK_AQUA + " with your RageKnife. " + ChatColor.GOLD.toString() + ChatColor.BOLD.toString() + "+" + knifePoints); victim.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_AQUA + "You were killed by " + ChatColor.BOLD.toString() + ChatColor.GOLD.toString() + killer.getName()); killer.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_AQUA + "You now have " + ChatColor.BOLD.toString() + ChatColor.GOLD.toString() + totalPoints + ChatColor.RESET.toString() + ChatColor.DARK_AQUA.toString() + " points."); break; case "explosion": int explosionPoints = ConstantHolder.POINTS_FOR_EXPLOSION_KILL; totalPoints = addPoints(killer, PlayerList.getPlayersGame(killer), explosionPoints, true); addPoints(victim, PlayerList.getPlayersGame(victim), 0, false); killerPoints = playerpoints.get(killer.getUniqueId().toString()); int oldExplosionKills = killerPoints.getExplosionKills(); int newExplosionKills = oldExplosionKills++; killerPoints.setAxeKills(newExplosionKills); victimPoints = playerpoints.get(victim.getUniqueId().toString()); int oldExplosionDeaths = victimPoints.getExplosionDeaths(); int newExplosionDeaths = oldExplosionDeaths++; victimPoints.setAxeDeaths(newExplosionDeaths); killer.sendMessage( ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_AQUA + "You killed " + ChatColor.GOLD.toString() + ChatColor.BOLD.toString() + victim.getName() + ChatColor.RESET.toString() + ChatColor.DARK_AQUA + " by causing heavy explosions with your RageBow. " + ChatColor.GOLD.toString() + ChatColor.BOLD.toString() + "+" + explosionPoints); victim.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_AQUA + "You were killed by " + ChatColor.BOLD.toString() + ChatColor.GOLD.toString() + killer.getName()); killer.sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_AQUA + "You now have " + ChatColor.BOLD.toString() + ChatColor.GOLD.toString() + totalPoints + ChatColor.RESET.toString() + ChatColor.DARK_AQUA.toString() + " points."); break; default: break; } ScoreBoard board = ScoreBoard.allScoreBoards.get(PlayerList.getPlayersGame(killer)); updateScoreBoard(killer, board); updateScoreBoard(victim, board); } else { killer.sendMessage( ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_AQUA + "You killed yourself you silly idiot."); } // TabGuiUpdater.updateTabGui(PlayerList.getPlayersGame(killer)); // TabAPI.updateTabGuiListOverlayForGame(PlayerList.getPlayersGame(killer)); } private static void updateScoreBoard(Player player, ScoreBoard scoreBoard) { PlayerPoints points = playerpoints.get(player.getUniqueId().toString()); ScoreBoardHolder holder = scoreBoard.getScoreboards().get(player); String oldKD = holder.getOldKdLine(); String newKD = ChatColor.YELLOW + Integer.toString(points.getKills()) + " / " + Integer.toString(points.getDeaths()) + " " + ConstantHolder.SCOREBOARD_DEFAULT_KD; holder.setOldKdLine(newKD); scoreBoard.updateLine(player, oldKD, newKD, 0); String oldPoints = holder.getOldPointsLine(); String newPoints = ChatColor.YELLOW + Integer.toString(points.getPoints()) + " " + ConstantHolder.SCOREBOARD_DEFAULT_POINTS; holder.setOldPointsLine(newPoints); scoreBoard.updateLine(player, oldPoints, newPoints, 1); } public static void removePointsForPlayers(String[] playerUUIDs) { for (String playerUUID : playerUUIDs) { if (playerpoints.containsKey(playerUUID)) { playerpoints.remove(playerUUID); } } } public static PlayerPoints getPlayerPoints(String playerUUID) { if (playerpoints.containsKey(playerUUID)) { return playerpoints.get(playerUUID); } else { return null; } } private static int addPoints(Player player, String gameName, int points, boolean killer) { // returns // total // points String playerUUID = player.getUniqueId().toString(); if (playerpoints.containsKey(playerUUID)) { PlayerPoints pointsHolder = playerpoints.get(playerUUID); int oldPoints = pointsHolder.getPoints(); int oldKills = pointsHolder.getKills(); int oldDeaths = pointsHolder.getDeaths(); playerpoints.remove(playerUUID); int totalPoints = oldPoints + points; ; int totalKills = oldKills; int totalDeaths = oldDeaths; if (killer) { totalKills++; } else { totalDeaths++; } pointsHolder.setPoints(totalPoints); pointsHolder.setKills(totalKills); pointsHolder.setDeaths(totalDeaths); playerpoints.put(playerUUID, pointsHolder); return totalPoints; } else { int totalKills = 0; int totalDeaths = 0; if (killer) { totalKills = 1; } else { totalDeaths = 1; } PlayerPoints pointsHolder = new PlayerPoints(playerUUID); pointsHolder.setPoints(points); pointsHolder.setKills(totalKills); pointsHolder.setDeaths(totalDeaths); playerpoints.put(playerUUID, pointsHolder); return points; } } public static void calculateWinner(String game, String[] players) { String highest = UUID.randomUUID().toString(); int highestPoints = -200000000; int i = 0; int imax = players.length; while (i < imax) { if (playerpoints.containsKey(players[i])) { // Bukkit.broadcastMessage(Bukkit.getPlayer(UUID.fromString(players[i])).getName() // + " " + Integer.toString(i) + " " + // playerpoints.get(players[i]).getPoints() + " " + // Integer.toString(highestPoints)); if (playerpoints.get(players[i]).getPoints() > highestPoints) { highest = players[i]; highestPoints = playerpoints.get(players[i]).getPoints(); } } i++; } i = 0; while (i < imax) { if (players[i].equals(highest)) { Bukkit.getPlayer(UUID.fromString(highest)) .sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.LIGHT_PURPLE + "You won the game " + ChatColor.GOLD + game + ChatColor.LIGHT_PURPLE + "."); } else { Bukkit.getPlayer(UUID.fromString(players[i])) .sendMessage(ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_GREEN + Bukkit.getPlayer(UUID.fromString(highest)).getName() + ChatColor.LIGHT_PURPLE + " won the game " + ChatColor.GOLD + game + ChatColor.LIGHT_PURPLE + "."); } i++; } } // TODO Statistics for games and for the server globally. (Maybe also for // each map separately) (Total Axe kills, total bow kills,..., best axe // killer, best total killer,..., best victim,... }
// ZAP: 2011/08/30 Support for scanner levels // ZAP: 2012/01/02 Separate param and attack // ZAP: 2012/03/03 Added getLevel(boolean incDefault) // ZAP: 2102/03/15 Changed the type of the parameter "sb" of the method matchBodyPattern to // StringBuilder. // ZAP: 2012/04/25 Added @Override annotation to all appropriate methods. // ZAP: 2012/08/07 Renamed Level to AlertThreshold and added support for AttackStrength // ZAP: 2012/08/31 Enabled control of AttackStrength // ZAP: 2012/10/03 Issue 388 Added enabling support for technologies // ZAP: 2013/01/19 Issue 460 Add support for a scan progress dialog // ZAP: 2013/01/25 Removed the "(non-Javadoc)" comments. // ZAP: 2013/02/19 Issue 528 Scan progress dialog can show negative progress times package org.parosproxy.paros.core.scanner; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.configuration.Configuration; import org.apache.commons.httpclient.HttpException; import org.apache.log4j.Logger; import org.parosproxy.paros.control.Control; import org.parosproxy.paros.extension.encoder.Encoder; import org.parosproxy.paros.network.HttpHeader; import org.parosproxy.paros.network.HttpMessage; import org.zaproxy.zap.extension.anticsrf.AntiCsrfToken; import org.zaproxy.zap.extension.anticsrf.ExtensionAntiCSRF; import org.zaproxy.zap.model.Tech; import org.zaproxy.zap.model.TechSet; abstract public class AbstractPlugin implements Plugin, Comparable<Object> { /** * Default pattern used in pattern check for most plugins. */ protected static final int PATTERN_PARAM = Pattern.CASE_INSENSITIVE | Pattern.MULTILINE; /** * CRLF string. */ protected static final String CRLF = "\r\n"; private HostProcess parent = null; private HttpMessage msg = null; // private boolean enabled = false; private Logger log = Logger.getLogger(this.getClass()); private Configuration config = null; // ZAP Added delayInMs private int delayInMs; private ExtensionAntiCSRF extAntiCSRF = null; private Encoder encoder = new Encoder(); private AlertThreshold defaultAttackThreshold = AlertThreshold.MEDIUM; private static final AlertThreshold[] alertThresholdsSupported = new AlertThreshold[] { AlertThreshold.MEDIUM }; private AttackStrength defaultAttackStrength = AttackStrength.MEDIUM; private static final AttackStrength[] attackStrengthsSupported = new AttackStrength[] { AttackStrength.MEDIUM }; private TechSet techSet = null; private Date started = null; private Date finished = null; public AbstractPlugin() { } @Override abstract public int getId(); @Override abstract public String getName(); @Override public String getCodeName() { String result = getClass().getName(); int pos = getClass().getName().lastIndexOf("."); if (pos > -1) { result = result.substring(pos+1); } return result; } @Override abstract public String[] getDependency(); @Override abstract public String getDescription(); @Override abstract public int getCategory(); @Override abstract public String getSolution(); @Override abstract public String getReference(); @Override public void init(HttpMessage msg, HostProcess parent) { this.msg = msg.cloneAll(); this.parent = parent; init(); } abstract public void init(); /** * Obtain a new HttpMessage with the same request as the base. The response is empty. * This is used by plugin to build/craft a new message to send/receive. It does not affect * the base message. * @return A new HttpMessage with cloned request. Response is empty. */ protected HttpMessage getNewMsg() { return msg.cloneRequest(); } /** * Get the base reference HttpMessage for this check. Both request and response is present. * It should not be modified during when the plugin runs. * @return The base HttpMessage with request/response. */ protected HttpMessage getBaseMsg() { return msg; } protected void sendAndReceive(HttpMessage msg) throws HttpException, IOException { sendAndReceive(msg, true); } protected void sendAndReceive(HttpMessage msg, boolean isFollowRedirect) throws HttpException, IOException { sendAndReceive(msg, isFollowRedirect, true); } protected void sendAndReceive(HttpMessage msg, boolean isFollowRedirect, boolean handleAntiCSRF) throws HttpException, IOException { if (parent.handleAntiCsrfTokens() && handleAntiCSRF) { if (extAntiCSRF == null) { extAntiCSRF = (ExtensionAntiCSRF) Control.getSingleton().getExtensionLoader().getExtension(ExtensionAntiCSRF.NAME); } List<AntiCsrfToken> tokens = extAntiCSRF.getTokens(msg); AntiCsrfToken antiCsrfToken = null; if (tokens.size() > 0) { antiCsrfToken = tokens.get(0); } if (antiCsrfToken != null) { regenerateAntiCsrfToken(msg, antiCsrfToken); } } // always get the fresh copy msg.getRequestHeader().setHeader(HttpHeader.IF_MODIFIED_SINCE, null); msg.getRequestHeader().setHeader(HttpHeader.IF_NONE_MATCH, null); msg.getRequestHeader().setContentLength(msg.getRequestBody().length()); if (this.getDelayInMs() > 0) { try { Thread.sleep(this.getDelayInMs()); } catch (InterruptedException e) { // Ignore } } parent.getHttpSender().sendAndReceive(msg, isFollowRedirect); // ZAP: Notify parent parent.notifyNewMessage(msg); return; } private void regenerateAntiCsrfToken(HttpMessage msg, AntiCsrfToken antiCsrfToken) { if (antiCsrfToken == null) { return; } String tokenValue = null; try { HttpMessage tokenMsg = antiCsrfToken.getMsg().cloneAll(); // Ensure we dont loop sendAndReceive(tokenMsg, true, false); tokenValue = extAntiCSRF.getTokenValue(tokenMsg, antiCsrfToken.getName()); } catch (Exception e) { log.error(e.getMessage(), e); } if (tokenValue != null) { // Replace token value - only supported in the body right now log.debug("regenerateAntiCsrfToken replacing " + antiCsrfToken.getValue() + " with " + encoder.getURLEncode(tokenValue)); String replaced = msg.getRequestBody().toString(); replaced = replaced.replace(encoder.getURLEncode(antiCsrfToken.getValue()), encoder.getURLEncode(tokenValue)); msg.setRequestBody(replaced); extAntiCSRF.registerAntiCsrfToken(new AntiCsrfToken(msg, antiCsrfToken.getName(), tokenValue)); } } @Override public void run() { try { if (!isStop()) { this.started = new Date(); scan(); } } catch (Exception e) { getLog().warn(e.getMessage()); } notifyPluginCompleted(getParent()); this.finished = new Date(); } /** * The core scan method to be implmented by subclass. */ @Override abstract public void scan(); /** * Generate an alert when a security issue (risk/info) is found. Default name, description, * solution of this Plugin will be used. * @param risk * @param reliability * @param uri * @param param * @param otherInfo * @param msg */ protected void bingo(int risk, int reliability, String uri, String param, String attack, String otherInfo, HttpMessage msg) { bingo(risk, reliability, this.getName(), this.getDescription(), uri, param, attack, otherInfo, this.getSolution(), msg); } /** * Generate an alert when a security issue (risk/info) is found. Custome alert name, * description and solution will be used. * * @param risk * @param reliability * @param name * @param description * @param uri * @param param * @param otherInfo * @param solution * @param msg */ protected void bingo(int risk, int reliability, String name, String description, String uri, String param, String attack, String otherInfo, String solution, HttpMessage msg) { log.debug("New alert pluginid=" + + this.getId() + " " + name + " uri=" + uri); Alert alert = new Alert(this.getId(), risk, reliability, name); if (uri == null || uri.equals("")) { uri = msg.getRequestHeader().getURI().toString(); } if (param == null) { param = ""; } alert.setDetail(description, uri, param, attack, otherInfo, solution, this.getReference(), msg); parent.alertFound(alert); } /** * Check i * @param msg * @return */ protected boolean isFileExist(HttpMessage msg) { return parent.getAnalyser().isFileExist(msg); } /** * Check if this test should be stopped. It should be checked periodically in Plugin * (eg when in loops) so the HostProcess can stop this Plugin cleanly. * @return */ protected boolean isStop() { return parent.isStop(); } /** * @return Returns if this test is enabled. */ @Override public boolean isEnabled() { return getProperty("enabled").equals("1"); } @Override public boolean isVisible() { return true; } /** * Enable this test */ @Override public void setEnabled(boolean enabled) { if (enabled) { setProperty("enabled", "1"); } else { setProperty("enabled", "0"); } } @Override public AlertThreshold getAlertThreshold() { return this.getAlertThreshold(false); } @Override public AlertThreshold getAlertThreshold(boolean incDefault) { AlertThreshold level = null; try { level = AlertThreshold.valueOf(getProperty("level")); //log.debug("getAlertThreshold from configs: " + level.name()); } catch (Exception e) { // Ignore } if (level == null) { if (this.isEnabled()) { if (incDefault) { level = AlertThreshold.DEFAULT; } else { level = defaultAttackThreshold; } //log.debug("getAlertThreshold default: " + level.name()); } else { level = AlertThreshold.OFF; //log.debug("getAlertThreshold not enabled: " + level.name()); } } else if (level.equals(AlertThreshold.DEFAULT)) { if (incDefault) { level = AlertThreshold.DEFAULT; } else { level = defaultAttackThreshold; } //log.debug("getAlertThreshold default: " + level.name()); } return level; } @Override public void setAlertThreshold(AlertThreshold level) { setProperty("level", level.name()); } @Override public void setDefaultAlertThreshold(AlertThreshold level) { this.defaultAttackThreshold = level; } /** * Override this if you plugin supports other levels. */ @Override public AlertThreshold[] getAlertThresholdsSupported() { return alertThresholdsSupported; } @Override public AttackStrength getAttackStrength(boolean incDefault) { AttackStrength level = null; try { level = AttackStrength.valueOf(getProperty("strength")); //log.debug("getAttackStrength from configs: " + level.name()); } catch (Exception e) { // Ignore } if (level == null) { if (incDefault) { level = AttackStrength.DEFAULT; } else { level = this.defaultAttackStrength; } //log.debug("getAttackStrength default: " + level.name()); } else if (level.equals(AttackStrength.DEFAULT)) { if (incDefault) { level = AttackStrength.DEFAULT; } else { level = this.defaultAttackStrength; } //log.debug("getAttackStrength default: " + level.name()); } return level; } @Override public AttackStrength getAttackStrength() { return this.getAttackStrength(false); } @Override public void setAttackStrength (AttackStrength level) { setProperty("strength", level.name()); } @Override public void setDefaultAttackStrength(AttackStrength strength) { this.defaultAttackStrength = strength; } /** * Override this if you plugin supports other levels. */ @Override public AttackStrength[] getAttackStrengthsSupported() { return attackStrengthsSupported; } /** * Compare if 2 plugin is the same. */ @Override public int compareTo(Object obj) { int result = -1; if (obj instanceof AbstractPlugin) { AbstractPlugin test = (AbstractPlugin) obj; if (getId() < test.getId()) { result = -1; } else if (getId() > test.getId()) { result = 1; } else { result = 0; } } return result; } @Override public boolean equals(Object obj) { if (compareTo(obj) == 0) { return true; } return false; } /** * Check if the given pattern can be found in the header. * @param msg * @param header name. * @param pattern * @return true if the pattern can be found. */ protected boolean matchHeaderPattern(HttpMessage msg, String header, Pattern pattern) { if (msg.getResponseHeader().isEmpty()) { return false; } String val = msg.getResponseHeader().getHeader(header); if (val == null) { return false; } Matcher matcher = pattern.matcher(val); return matcher.find(); } /** * Check if the given pattern can be found in the msg body. If the supplied * StringBuilder is not null, append the result to the StringBuilder. * @param msg * @param pattern * @param sb * @return true if the pattern can be found. */ protected boolean matchBodyPattern(HttpMessage msg, Pattern pattern, StringBuilder sb) { // ZAP: Changed the type of the parameter "sb" to StringBuilder. Matcher matcher = pattern.matcher(msg.getResponseBody().toString()); boolean result = matcher.find(); if (result) { if (sb != null) { sb.append(matcher.group()); } } return result; } /** * Write a progress update message. Currently this just display in System.out * @param msg */ protected void writeProgress(String msg) { //System.out.println(msg); } /** * Get the parent HostProcess. * @return */ protected HostProcess getParent() { return parent; } @Override abstract public void notifyPluginCompleted(HostProcess parent); /** * Replace body by stripping of pattern string. The URLencoded and URLdecoded * pattern will also be stripped off. * This is mainly used for stripping off a testing string in HTTP response * for comparison against the original response. * Reference: TestInjectionSQL * @param body * @param pattern * @return */ protected String stripOff(String body, String pattern) { String urlEncodePattern = getURLEncode(pattern); String urlDecodePattern = getURLDecode(pattern); String htmlEncodePattern1 = getHTMLEncode(pattern); String htmlEncodePattern2 = getHTMLEncode(urlEncodePattern); String htmlEncodePattern3 = getHTMLEncode(urlDecodePattern); String result = body.replaceAll("\\Q" + pattern + "\\E", "").replaceAll("\\Q" + urlEncodePattern + "\\E", "").replaceAll("\\Q" + urlDecodePattern + "\\E", ""); result = result.replaceAll("\\Q" + htmlEncodePattern1 + "\\E", "").replaceAll("\\Q" + htmlEncodePattern2 + "\\E", "").replaceAll("\\Q" + htmlEncodePattern3 + "\\E", ""); return result; } public static String getURLEncode(String msg) { String result = ""; try { result = URLEncoder.encode(msg, "UTF8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } public static String getURLDecode(String msg) { String result = ""; try { result = URLDecoder.decode(msg, "UTF8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } public static String getHTMLEncode(String msg) { String result = msg.replaceAll("<", "& result = result.replaceAll(">", "& return result; } protected Kb getKb() { return getParent().getKb(); } protected Logger getLog() { return log; } public String getProperty(String key) { return config.getString("plugins." + "p" + getId() + "." + key); } public void setProperty(String key, String value) { config.setProperty("plugins." + "p" + getId() + "." + key, value); } @Override public void setConfig(Configuration config) { this.config = config; } @Override public Configuration getConfig() { return config; } /** * Check and create necessary parameter in config file if not already present. * */ @Override public void createParamIfNotExist() { if (getProperty("enabled") == null) { setProperty("enabled", "1"); } } // ZAP Added isDepreciated @Override public boolean isDepreciated() { return false; } @Override public int getDelayInMs() { return delayInMs; } @Override public void setDelayInMs(int delayInMs) { this.delayInMs = delayInMs; } @Override public boolean inScope(Tech tech) { return this.techSet == null || this.techSet.includes(tech); } @Override public void setTechSet(TechSet ts) { this.techSet = ts; } @Override public Date getTimeStarted() { return this.started; } @Override public Date getTimeFinished() { return this.finished; } @Override public void setTimeStarted() { this.started = new Date(); this.finished = null; } @Override public void setTimeFinished() { this.finished = new Date(); } }
package org.pentaho.di.trans.steps.excelinput; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; import jxl.BooleanCell; import jxl.Cell; import jxl.CellType; import jxl.DateCell; import jxl.LabelCell; import jxl.NumberCell; import jxl.Sheet; import jxl.Workbook; import jxl.WorkbookSettings; import org.apache.commons.vfs.FileObject; import org.pentaho.di.core.Const; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.RowSet; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.fileinput.FileInputList; import org.pentaho.di.core.playlist.FilePlayListAll; import org.pentaho.di.core.playlist.FilePlayListReplay; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.ValueDataUtil; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.di.trans.step.errorhandling.CompositeFileErrorHandler; import org.pentaho.di.trans.step.errorhandling.FileErrorHandler; import org.pentaho.di.trans.step.errorhandling.FileErrorHandlerContentLineNumber; import org.pentaho.di.trans.step.errorhandling.FileErrorHandlerMissingFiles; /** * This class reads data from one or more Microsoft Excel files. * * @author Matt * @since 19-NOV-2003 */ public class ExcelInput extends BaseStep implements StepInterface { private ExcelInputMeta meta; private ExcelInputData data; public ExcelInput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } private Object[] fillRow(int startcolumn, ExcelInputRow excelInputRow) throws KettleException { Object[] r = new Object[data.outputRowMeta.size()]; // Keep track whether or not we handled an error for this line yet. boolean errorHandled = false; // Set values in the row... for (int i = startcolumn; i < excelInputRow.cells.length && i - startcolumn < r.length; i++) { Cell cell = excelInputRow.cells[i]; int rowcolumn = i - startcolumn; ValueMetaInterface targetMeta = data.outputRowMeta.getValueMeta(rowcolumn); ValueMetaInterface sourceMeta = null; try { checkType(cell, targetMeta); } catch (KettleException ex) { if (!meta.isErrorIgnored()) throw ex; logBasic("Warning processing [" + targetMeta + "] from Excel file [" + data.filename + "] : " + ex.getMessage()); if (!errorHandled) { data.errorHandler.handleLineError(excelInputRow.rownr, excelInputRow.sheetName); errorHandled = true; } if (meta.isErrorLineSkipped()) { return null; } } CellType cellType = cell.getType(); if (CellType.BOOLEAN.equals(cellType) || CellType.BOOLEAN_FORMULA.equals(cellType)) { r[rowcolumn] = Boolean.valueOf( ((BooleanCell)cell).getValue() ); sourceMeta = data.valueMetaBoolean; } else { if (CellType.DATE.equals(cellType) || CellType.DATE_FORMULA.equals(cellType) ) { Date date = ((DateCell) cell).getDate(); long time = date.getTime(); int offset = TimeZone.getDefault().getOffset(time); r[rowcolumn] = new Date(time - offset); sourceMeta = data.valueMetaDate; } else { if (CellType.LABEL.equals(cellType) || CellType.STRING_FORMULA.equals(cellType)) { String string = ((LabelCell) cell).getString(); switch (meta.getField()[rowcolumn].getTrimType()) { case ExcelInputMeta.TYPE_TRIM_LEFT: string = ValueDataUtil.leftTrim(string); break; case ExcelInputMeta.TYPE_TRIM_RIGHT: string = ValueDataUtil.rightTrim(string); break; case ExcelInputMeta.TYPE_TRIM_BOTH: string = ValueDataUtil.trim(string); break; default: break; } r[rowcolumn] = string; sourceMeta = data.valueMetaString; } else { if (CellType.NUMBER.equals(cellType) || CellType.NUMBER_FORMULA.equals(cellType)) { r[rowcolumn] = new Double( ((NumberCell)cell).getValue() ); sourceMeta = data.valueMetaNumber; } else { if (log.isDetailed()) logDetailed("Unknown type : " + cell.getType().toString() + " : [" + cell.getContents() + "]"); r[rowcolumn] = null; } } } } ExcelInputField field = meta.getField()[rowcolumn]; // Change to the appropriate type if needed... try { // Null stays null folks. if (sourceMeta!=null && sourceMeta.getType() != targetMeta.getType() && r[rowcolumn]!=null) { ValueMetaInterface sourceMetaCopy = sourceMeta.clone(); sourceMetaCopy.setConversionMask(field.getFormat()); sourceMetaCopy.setGroupingSymbol(field.getGroupSymbol()); sourceMetaCopy.setDecimalSymbol(field.getDecimalSymbol()); sourceMetaCopy.setCurrencySymbol(field.getCurrencySymbol()); switch (targetMeta.getType()) { // Use case: we find a numeric value: convert it using the supplied format to the desired data type... case ValueMetaInterface.TYPE_NUMBER: case ValueMetaInterface.TYPE_INTEGER: switch (field.getType()) { case ValueMetaInterface.TYPE_DATE: // number to string conversion (20070522.00 --> "20070522") ValueMetaInterface valueMetaNumber = new ValueMeta("num", ValueMetaInterface.TYPE_NUMBER); valueMetaNumber.setConversionMask(" Object string = sourceMetaCopy.convertData(valueMetaNumber, r[rowcolumn]); // String to date with mask... r[rowcolumn] = targetMeta.convertData(sourceMetaCopy, string); break; default: r[rowcolumn] = targetMeta.convertData(sourceMeta, r[rowcolumn]); break; } break; default: r[rowcolumn] = targetMeta.convertData(sourceMeta, r[rowcolumn]); } } } catch (KettleException ex) { if (!meta.isErrorIgnored()) throw ex; logBasic("Warning processing [" + targetMeta + "] from Excel file [" + data.filename + "] : " + ex.toString()); if (!errorHandled) // check if we didn't log an error already for this one. { data.errorHandler.handleLineError(excelInputRow.rownr, excelInputRow.sheetName); errorHandled=true; } if (meta.isErrorLineSkipped()) { return null; } else { r[rowcolumn] = null; } } } int rowIndex = meta.getField().length; // Do we need to include the filename? if (!Const.isEmpty(meta.getFileField())) { r[rowIndex] = data.filename; rowIndex++; } // Do we need to include the sheetname? if (!Const.isEmpty(meta.getSheetField())) { r[rowIndex] = excelInputRow.sheetName; rowIndex++; } // Do we need to include the sheet rownumber? if (!Const.isEmpty(meta.getSheetRowNumberField())) { r[rowIndex] = new Long(data.rownr); rowIndex++; } // Do we need to include the rownumber? if (!Const.isEmpty(meta.getRowNumberField())) { r[rowIndex] = new Long(linesWritten + 1); rowIndex++; } return r; } private void checkType(Cell cell, ValueMetaInterface v) throws KettleException { if (!meta.isStrictTypes()) return; CellType cellType = cell.getType(); if (cellType.equals(CellType.BOOLEAN)) { if (!(v.getType() == ValueMetaInterface.TYPE_STRING || v.getType() == ValueMetaInterface.TYPE_NONE || v.getType() == ValueMetaInterface.TYPE_BOOLEAN)) throw new KettleException("Invalid type Boolean, expected " + v.getTypeDesc()); } else if (cellType.equals(CellType.DATE)) { if (!(v.getType() == ValueMetaInterface.TYPE_STRING || v.getType() == ValueMetaInterface.TYPE_NONE || v.getType() == ValueMetaInterface.TYPE_DATE)) throw new KettleException("Invalid type Date: " + cell.getContents() + ", expected " + v.getTypeDesc()); } else if (cellType.equals(CellType.LABEL)) { if (v.getType() == ValueMetaInterface.TYPE_BOOLEAN || v.getType() == ValueMetaInterface.TYPE_DATE || v.getType() == ValueMetaInterface.TYPE_INTEGER || v.getType() == ValueMetaInterface.TYPE_NUMBER) throw new KettleException("Invalid type Label: " + cell.getContents() + ", expected " + v.getTypeDesc()); } else if (cellType.equals(CellType.EMPTY)) { } else if (cellType.equals(CellType.NUMBER)) { if (!(v.getType() == ValueMetaInterface.TYPE_STRING || v.getType() == ValueMetaInterface.TYPE_NONE || v.getType() == ValueMetaInterface.TYPE_INTEGER || v.getType() == ValueMetaInterface.TYPE_BIGNUMBER || v.getType() == ValueMetaInterface.TYPE_NUMBER)) throw new KettleException("Invalid type Number: " + cell.getContents() + ", expected " + v.getTypeDesc()); } else { throw new KettleException("Unsupported type " + cellType + " with value: " + cell.getContents()); } } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (ExcelInputMeta) smi; data = (ExcelInputData) sdi; if (first) { first = false; data.outputRowMeta = new RowMeta(); // start from scratch! meta.getFields(data.outputRowMeta, getStepname(), null, null, this); if (meta.isAcceptingFilenames()) { // Read the files from the specified input stream... data.files.getFiles().clear(); int idx = -1; RowSet rowSet = findInputRowSet(meta.getAcceptingStepName()); Object[] fileRow = getRowFrom(rowSet); while (fileRow!=null) { if (idx<0) { idx = rowSet.getRowMeta().indexOfValue(meta.getAcceptingField()); if (idx<0) { logError("The filename field ["+meta.getAcceptingField()+"] could not be found in the input rows."); setErrors(1); stopAll(); return false; } } String fileValue = rowSet.getRowMeta().getString(fileRow, idx); try { data.files.addFile(KettleVFS.getFileObject(fileValue)); } catch(IOException e) { throw new KettleException("Unexpected error creating file object for "+fileValue, e); } // Grab another row fileRow = getRowFrom(rowSet); } } handleMissingFiles(); } // See if we're not done processing... // We are done processing if the filenr >= number of files. if (data.filenr >= data.files.nrOfFiles()) { if (log.isDetailed()) logDetailed("No more files to be processed! (" + data.filenr + " files done)"); setOutputDone(); // signal end to receiver(s) return false; // end of data or error. } if (meta.getRowLimit() > 0 && data.rownr > meta.getRowLimit()) { // The close of the openFile is in dispose() if (log.isDetailed()) logDetailed("Row limit of [" + meta.getRowLimit() + "] reached: stop processing."); setOutputDone(); // signal end to receiver(s) return false; // end of data or error. } Object[] r = getRowFromWorkbooks(); if (r != null) { // OK, see if we need to repeat values. if (data.previousRow != null) { for (int i = 0; i < meta.getField().length; i++) { ValueMetaInterface valueMeta = data.outputRowMeta.getValueMeta(i); Object valueData = r[i]; if (valueMeta.isNull(valueData) && meta.getField()[i].isRepeated()) { // Take the value from the previous row. r[i] = data.previousRow[i]; } } } // Remember this row for the next time around! data.previousRow = data.outputRowMeta.cloneRow(r); // Send out the good news: we found a row of data! putRow(data.outputRowMeta, r); return true; } else { // This row is ignored / eaten // We continue though. return true; } } private void handleMissingFiles() throws KettleException { List<FileObject> nonExistantFiles = data.files.getNonExistantFiles(); if (nonExistantFiles.size() != 0) { String message = FileInputList.getRequiredFilesDescription(nonExistantFiles); log.logBasic("Required files", "WARNING: Missing " + message); if (meta.isErrorIgnored()) for (FileObject fileObject : nonExistantFiles) { data.errorHandler.handleNonExistantFile( fileObject ); } else throw new KettleException("Following required files are missing: " + message); } List<FileObject> nonAccessibleFiles = data.files.getNonAccessibleFiles(); if (nonAccessibleFiles.size() != 0) { String message = FileInputList.getRequiredFilesDescription(nonAccessibleFiles); log.logBasic("Required files", "WARNING: Not accessible " + message); if (meta.isErrorIgnored()) for (FileObject fileObject : nonAccessibleFiles) { data.errorHandler.handleNonAccessibleFile(fileObject); } else throw new KettleException("Following required files are not accessible: " + message); } } public Object[] getRowFromWorkbooks() { // This procedure outputs a single Excel data row on the destination // rowsets... Object[] retval = null; try { // First, see if a file has been opened? if (data.workbook == null) { // Open a new openFile.. data.file = data.files.getFile(data.filenr); data.filename = KettleVFS.getFilename( data.file ); ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, data.file, getTransMeta().getName(), toString()); resultFile.setComment("File was read by an Excel input step"); addResultFile(resultFile); if (log.isDetailed()) logDetailed("Opening openFile #" + data.filenr + " : " + data.filename); WorkbookSettings ws = new WorkbookSettings(); if (!Const.isEmpty(meta.getEncoding())) { ws.setEncoding(meta.getEncoding()); } data.workbook = Workbook.getWorkbook(data.file.getContent().getInputStream(), ws); data.errorHandler.handleFile(data.file); // Start at the first sheet again... data.sheetnr = 0; // See if we have sheet names to retrieve, otherwise we'll have to get all sheets... if (meta.readAllSheets()) { data.sheetNames = data.workbook.getSheetNames(); data.startColumn = new int[data.sheetNames.length]; data.startRow = new int[data.sheetNames.length]; for (int i=0;i<data.sheetNames.length;i++) { data.startColumn[i] = data.defaultStartColumn; data.startRow[i] = data.defaultStartRow; } } } boolean nextsheet = false; // What sheet were we handling? if (log.isDebug()) logDetailed("Get sheet #" + data.filenr + "." + data.sheetnr); String sheetName = data.sheetNames[data.sheetnr]; Sheet sheet = data.workbook.getSheet(sheetName); if (sheet != null) { // at what row do we continue reading? if (data.rownr < 0) { data.rownr = data.startRow[data.sheetnr]; // Add an extra row if we have a header row to skip... if (meta.startsWithHeader()) { data.rownr++; } } // Start at the specified column data.colnr = data.startColumn[data.sheetnr]; // Build a new row and fill in the data from the sheet... try { Cell line[] = sheet.getRow(data.rownr); // Already increase cursor 1 row int lineNr = ++data.rownr; // Excel starts counting at 0 if (!data.filePlayList.isProcessingNeeded(data.file, lineNr, sheetName)) { retval = null; // placeholder, was already null } else { if (log.isRowLevel()) logRowlevel("Get line #" + lineNr + " from sheet #" + data.filenr + "." + data.sheetnr); if (log.isRowLevel()) logRowlevel("Read line with " + line.length + " cells"); ExcelInputRow excelInputRow = new ExcelInputRow(sheet.getName(), lineNr, line); Object[] r = fillRow(data.colnr, excelInputRow); if (log.isRowLevel()) logRowlevel("Converted line to row #" + lineNr + " : " + data.outputRowMeta.getString(r)); boolean isEmpty = isLineEmpty(line); if (!isEmpty || !meta.ignoreEmptyRows()) { // Put the row retval = r; } else { if (data.rownr>sheet.getRows()) { nextsheet=true; } } if (isEmpty && meta.stopOnEmpty()) { nextsheet = true; } } } catch (ArrayIndexOutOfBoundsException e) { if (log.isRowLevel()) logRowlevel("Out of index error: move to next sheet!"); // We tried to read below the last line in the sheet. // Go to the next sheet... nextsheet = true; } } else { nextsheet = true; } if (nextsheet) { // Go to the next sheet data.sheetnr++; // Reset the start-row: data.rownr = -1; // no previous row yet, don't take it from the previous sheet! // (that whould be plain wrong!) data.previousRow = null; // Perhaps it was the last sheet? if (data.sheetnr >= data.sheetNames.length) { jumpToNextFile(); } } } catch (Exception e) { logError("Error processing row from Excel file [" + data.filename + "] : " + e.toString()); setErrors(1); stopAll(); return null; } return retval; } private boolean isLineEmpty(Cell[] line) { if (line.length == 0) return true; boolean isEmpty = true; for (int i=0;i<line.length && isEmpty;i++) { if ( !Const.isEmpty(line[i].getContents()) ) isEmpty=false; } return isEmpty; } private void jumpToNextFile() throws KettleException { data.sheetnr = 0; // Reset the start-row: data.rownr = -1; // no previous row yet, don't take it from the previous sheet! (that // whould be plain wrong!) data.previousRow = null; // Close the openFile! data.workbook.close(); data.workbook = null; // marker to open again. data.errorHandler.close(); // advance to the next file! data.filenr++; } private void initErrorHandling() { List<FileErrorHandler> errorHandlers = new ArrayList<FileErrorHandler>(2); if (meta.getLineNumberFilesDestinationDirectory() != null) errorHandlers.add(new FileErrorHandlerContentLineNumber(getTrans().getCurrentDate(), meta.getLineNumberFilesDestinationDirectory(), meta.getLineNumberFilesExtension(), "Latin1", this)); if (meta.getErrorFilesDestinationDirectory() != null) errorHandlers.add(new FileErrorHandlerMissingFiles(getTrans().getCurrentDate(), meta.getErrorFilesDestinationDirectory(), meta.getErrorFilesExtension(), "Latin1", this)); data.errorHandler = new CompositeFileErrorHandler(errorHandlers); } private void initReplayFactory() { Date replayDate = getTrans().getReplayDate(); if (replayDate == null) data.filePlayList = FilePlayListAll.INSTANCE; else data.filePlayList = new FilePlayListReplay(replayDate, meta.getLineNumberFilesDestinationDirectory(), meta.getLineNumberFilesExtension(), meta.getErrorFilesDestinationDirectory(), meta .getErrorFilesExtension(), "Latin1"); } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta = (ExcelInputMeta) smi; data = (ExcelInputData) sdi; if (super.init(smi, sdi)) { initErrorHandling(); initReplayFactory(); data.files = meta.getFileList(this); if (data.files.nrOfFiles() == 0 && data.files.nrOfMissingFiles() == 0 && !meta.isAcceptingFilenames()) { logError("No file(s) specified! Stop processing."); return false; } if (meta.getEmptyFields().size() > 0) { // Determine the maximum filename length... data.maxfilelength = -1; for (FileObject file : data.files.getFiles()) { String name = KettleVFS.getFilename(file); if (name.length() > data.maxfilelength) data.maxfilelength = name.length(); } // Determine the maximum sheet name length... data.maxsheetlength = -1; if (!meta.readAllSheets()) { data.sheetNames = new String[meta.getSheetName().length]; data.startColumn = new int[meta.getSheetName().length]; data.startRow = new int[meta.getSheetName().length]; for (int i = 0; i < meta.getSheetName().length; i++) { data.sheetNames[i] = meta.getSheetName()[i]; data.startColumn[i] = meta.getStartColumn()[i]; data.startRow[i] = meta.getStartRow()[i]; if (meta.getSheetName()[i].length() > data.maxsheetlength) { data.maxsheetlength = meta.getSheetName()[i].length(); } } } else { // Allocated at open file time: we want ALL sheets. if (meta.getStartRow().length==1) { data.defaultStartRow = meta.getStartRow()[0]; } else { data.defaultStartRow = 0; } if (meta.getStartColumn().length==1) { data.defaultStartColumn = meta.getStartColumn()[0]; } else { data.defaultStartColumn = 0; } } return true; } else { logError("No input fields defined!"); } } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta = (ExcelInputMeta) smi; data = (ExcelInputData) sdi; if (data.workbook != null) data.workbook.close(); try { data.errorHandler.close(); } catch (KettleException e) { if (log.isDebug()) { logDebug("Could not close errorHandler: "+e.toString()); logDebug(Const.getStackTracker(e)); } } super.dispose(smi, sdi); } // Run is were the action happens! public void run() { try { logBasic(Messages.getString("System.Log.StartingToRun")); //$NON-NLS-1$ while (processRow(meta, data) && !isStopped()); } catch(Throwable t) { logError(Messages.getString("System.Log.UnexpectedError")+" : "); //$NON-NLS-1$ //$NON-NLS-2$ logError(Const.getStackTracker(t)); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }
package gov.nih.nci.caintegrator.application.zip; import java.io.File; import java.util.List; import org.apache.log4j.Logger; /** * @author Prashant Shah - NCICB/SAIC * * A wrapper class around the ZipFiles Class. Also provides the zip status value for the AJAX code */ @SuppressWarnings("unused") public class ZipManager extends Thread { // Total number of bytes to zip for all series private long totalBytesToZip = 0; // Total number of bytes zipped up to this point private long bytesZippedSoFar = 0; // Bytes zipped in the current zip file (there can be multiple zip files for large data sets) private long bytesZippedInCurrentZipFile = 0; // Name of first zip file created for the data private String destinationFile; // For a large data set, this number keeps track of which zip file is // being zipped. 0 is the first file private int sequenceNumber = 0; // Set to true if resulting zip files should be broken up // so that they don't become too large private boolean breakIntoMultipleFileIfLarge = true; // Maximum size for a single zip file (4GB) // Only applies if breakIntoMultipleFileIfLarge is true private static final long MAX_ZIP_FILE_SIZE = 4000000000L; // List of items to be zipped private List<ZipItem> items; private static Logger logger = Logger.getLogger(ZipManager.class); private static boolean finished = true; /** * Compute the percentage of series that have * been processed. Used by the progress bar * * @return */ public Integer getPercentProcessed() { if (totalBytesToZip != 0) { return new Double(bytesZippedSoFar * 100 /totalBytesToZip).intValue(); } else return 0; } /** * * @param items */ public void setItems(List<ZipItem> items) { this.items = items; } /** * * @param target */ public void setTarget(String target) { this.destinationFile = target; } /** * Actually does the zipping of the files * */ public List<String> zip() throws Exception { logger.info("Starting to zip: " + destinationFile); long startTime = System.currentTimeMillis(); AbstractFileZipper zipit = FileZipperFactory.getInstance(); // Initialize zipper try { zipit.startNewFile(destinationFile, sequenceNumber); // Loop through zip items for(ZipItem zipItem : items) { zipit.zip(zipItem.getDirectoryInZip(), zipItem.getFilePath()); } zipit.closeFile(); } catch (Exception e) { logger.error("Destination file "+destinationFile+" cannot be created ",e); throw e; } long endTime = System.currentTimeMillis(); logger.info(" Total zipping time for file "+destinationFile+" ( "+totalBytesToZip+"bytes) was "+(endTime-startTime)+" ms."); return zipit.getListOfZipFiles(); } public void run() { finished = false; try { zip(); } catch(Exception e) { logger.error("Unable to complete zipping of file "+destinationFile, e); } finished = true; } /** * Process a file for zipping. * */ private void zipFile(AbstractFileZipper zipit, String projectName, String taskName, String fileName,String filePath, Long fileSize) throws Exception { // Build the path inside of the zip file based on values passed in String path = projectName + File.separator + taskName + File.separator + fileName; // Possibly start a new zip file instead of // adding to the current one if(breakIntoMultipleFileIfLarge) { // Determine the file size // Only do this if there has been a sufficient amount // of data added to the zip file. long zipFileSize = 0; if(bytesZippedInCurrentZipFile > MAX_ZIP_FILE_SIZE) { zipFileSize = zipit.getFileSize(); long sizeWithThisFileIncluded = zipFileSize + fileSize; // See if the zip file would go over the limit if the // current file is added if(sizeWithThisFileIncluded > MAX_ZIP_FILE_SIZE) { // Close the streams and finalize the zip file zipit.closeFile(); // Start a new zip file, increasing the sequence number zipit.startNewFile(destinationFile, ++sequenceNumber); // Reset the counter bytesZippedInCurrentZipFile = 0; } } } zipit.zip(path, filePath); bytesZippedSoFar += fileSize; bytesZippedInCurrentZipFile += fileSize; } /** * Setter for breakIntoMultipleFileIfLarge * * @param flag */ public void setBreakIntoMultipleFileIfLarge(boolean flag) { breakIntoMultipleFileIfLarge = flag; } public static boolean isFinished() { return finished; } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc1073.robot15.subsystems; import org.usfirst.frc1073.robot15.Robot; import org.usfirst.frc1073.robot15.RobotMap; import org.usfirst.frc1073.robot15.commands.*; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class dashboard extends Subsystem { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS // Put methods for controlling this subsystem // here. Call these from Commands. public void initDefaultCommand() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND setDefaultCommand(new SendToDashboard()); } // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND private int CubicRel(boolean cubic, boolean fieldRel) { if(!cubic && !fieldRel) { return 0; } else if(cubic && !fieldRel) { return 1; } else if(!cubic && fieldRel) { return 2; } else if(cubic && fieldRel) { return 3; } return -1; } public void sendData() { SmartDashboard.putInt("Driving Mode", CubicRel(Robot.driveTrain.isCubicDrive(), Robot.driveTrain.isFieldRelative())); } // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); }
package io.core9.plugin.server.vertx; import io.core9.plugin.server.Cookie; import io.core9.plugin.server.request.Response; import io.core9.plugin.template.TemplateEngine; import io.netty.handler.codec.http.ServerCookieEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.vertx.java.core.Handler; import org.vertx.java.core.MultiMap; import org.vertx.java.core.buffer.Buffer; import org.vertx.java.core.http.HttpServerResponse; import org.vertx.java.core.json.JsonArray; import org.vertx.java.core.json.JsonObject; public class ResponseImpl implements Response, HttpServerResponse { // the original request private final HttpServerResponse response; private static TemplateEngine<String> templateEngine; private String template; private Map<String, Object> values; private boolean ended = false; private List<CookieImpl> cookies; public static void setTemplateEngine(TemplateEngine<String> engine) { templateEngine = engine; } @Override public String getTemplate() { return template; } @Override public ResponseImpl setTemplate(String template) { this.template = template; return this; } @Override public Map<String, Object> getValues() { return values; } @Override public void addValues(Map<String, Object> values) { this.values.putAll(values); } @Override public void addValue(String key, Object value) { this.values.put(key, value); } public ResponseImpl(HttpServerResponse response) { this.response = response; values = new HashMap<String, Object>(); } @Override public HttpServerResponse setWriteQueueMaxSize(int maxSize) { response.setWriteQueueMaxSize(maxSize); return this; } @Override public boolean writeQueueFull() { return response.writeQueueFull(); } @Override public HttpServerResponse drainHandler(Handler<Void> handler) { response.drainHandler(handler); return this; } @Override public HttpServerResponse exceptionHandler(Handler<Throwable> handler) { response.exceptionHandler(handler); return this; } @Override public String getStatusMessage() { return response.getStatusMessage(); } @Override public ResponseImpl setStatusMessage(String statusMessage) { response.setStatusMessage(statusMessage); return this; } @Override public HttpServerResponse setChunked(boolean chunked) { response.setChunked(chunked); return this; } @Override public boolean isChunked() { return response.isChunked(); } @Override public MultiMap headers() { return response.headers(); } @Override public ResponseImpl putHeader(String name, String value) { try { response.putHeader(name, value); } catch (Exception e) { // TODO: handle exception System.out.println("java.lang.IllegalStateException: Response has already been written" + this.getClass().getCanonicalName() + " : putHeader"); } return this; } @Override public HttpServerResponse putHeader(String name, Iterable<String> values) { response.putHeader(name, values); return this; } @Override public MultiMap trailers() { return response.trailers(); } @Override public HttpServerResponse putTrailer(String name, String value) { response.putTrailer(name, value); return this; } @Override public HttpServerResponse putTrailer(String name, Iterable<String> values) { response.putTrailer(name, values); return this; } @Override public HttpServerResponse closeHandler(Handler<Void> handler) { response.closeHandler(handler); return this; } @Override public HttpServerResponse write(Buffer chunk) { response.write(chunk); return this; } @Override public HttpServerResponse write(String chunk, String enc) { response.write(chunk, enc); return this; } @Override public HttpServerResponse write(String chunk) { response.write(chunk); return this; } @Override public void end(String chunk) { processHeaders(); response.end(chunk); this.ended = true; } @Override public void end(String chunk, String enc) { processHeaders(); response.end(chunk, enc); this.ended = true; } @Override public void end(Buffer chunk) { processHeaders(); response.end(chunk); this.ended = true; } @Override public void end() { if (!this.ended) { processHeaders(); if(this.template != null) { String result = ""; try { result = processTemplate(); } catch (Exception e) { result = e.getMessage(); } response.end(result); } else if (template == null && values.size() > 0) { sendJsonMap(values); } else { response.end(); } } this.ended = true; } @Override public ResponseImpl sendFile(String filename) { processHeaders(); response.sendFile(filename); this.ended = true; return this; } @Override public HttpServerResponse sendFile(String filename, String notFoundFile) { processHeaders(); response.sendFile(filename, notFoundFile); this.ended = true; return this; } @Override public void close() { response.close(); } @Override public int getStatusCode() { return response.getStatusCode(); } @Override public ResponseImpl setStatusCode(int statusCode) { response.setStatusCode(statusCode); return this; } @Override public ResponseImpl sendBinary(byte[] bin) { processHeaders(); response.end(new Buffer(bin)); this.ended = true; return this; } @SuppressWarnings("unchecked") @Override public void sendJsonArray(List<? extends Object> list) { processHeaders(); response.headers().add("Content-Type", "application/json"); response.end(new JsonArray((List<Object>) list).encodePrettily()); this.ended = true; } @Override public void sendJsonArray(Set<? extends Object> list) { processHeaders(); response.headers().add("Content-Type", "application/json"); response.end(new JsonArray(list.toArray()).encodePrettily()); this.ended = true; } @Override public void sendJsonMap(Map<String, Object> map) { processHeaders(); response.headers().add("Content-Type", "application/json"); response.end(new JsonObject(map).toString()); this.ended = true; } @Override public void sendRedirect(int status, String url) { processHeaders(); response.setStatusCode(status); response.headers().add("Content-Type", "plain/text"); response.headers().add("Location", url); response.end(); this.ended = true; } @Override public Response addCookie(Cookie cookie) { CookieImpl c = (CookieImpl) cookie; if (cookies == null) { cookies = new ArrayList<>(); } cookies.add(c); return this; } /** * Process the headers */ private void processHeaders() { if (this.cookies != null) { List<io.netty.handler.codec.http.Cookie> nettyCookies = new ArrayList<io.netty.handler.codec.http.Cookie>(); for (CookieImpl cookie : this.cookies) { nettyCookies.add((io.netty.handler.codec.http.Cookie) cookie); } response.putHeader("set-cookie", ServerCookieEncoder.encode(nettyCookies)); } } private String processTemplate() throws Exception { String contentType = response.headers().get("Content-Type"); if(contentType == null) { // Default to text/html content type response.headers().add("Content-Type", "text/html"); } return templateEngine.render(template, values); } }
package functionalTests.filetransfer; import java.io.File; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.objectweb.proactive.ProActive; import org.objectweb.proactive.core.config.ProActiveConfiguration; import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor; import org.objectweb.proactive.core.descriptor.data.VirtualNode; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.core.xml.VariableContract; import org.objectweb.proactive.core.xml.VariableContractType; import org.objectweb.proactive.filetransfer.FileVector; import functionalTests.FunctionalTest; import static junit.framework.Assert.assertTrue; /** * Tests that both schems work using the ProActive FileTransfer API */ public class TestDeployRetrieve extends FunctionalTest { static final long serialVersionUID = 1; private static Logger logger = ProActiveLogger.getLogger("functionalTests"); private static String XML_LOCATION = TestAPI.class.getResource( "/functionalTests/filetransfer/TestDeployRetrieve.xml").getPath(); ProActiveDescriptor pad; File fileTest = new File("/tmp/ProActiveTestFile.dat"); File fileRetrieved = new File("/tmp/ProActiveTestFileRetrieved.dat"); File fileDeployed = new File("/tmp/ProActiveTestFileDeployed.dat"); File fileRetrieved2 = new File("/tmp/ProActiveTestFileRetrieved2.dat"); File fileDeployed2 = new File("/tmp/ProActiveTestFileDeployed2.dat"); static int testblocksize = org.objectweb.proactive.core.filetransfer.FileBlock.DEFAULT_BLOCK_SIZE; static int testflyingblocks = org.objectweb.proactive.core.filetransfer.FileTransferService.DEFAULT_MAX_SIMULTANEOUS_BLOCKS; static int filesize = 2; //Descriptor variables String jvmProcess = "localJVM"; String hostName = "localhost"; @Before public void initTest() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Creating " + filesize + "Mb random test file in /tmp"); } //creates a new 2MB test file TestAPI.createRandomContentFile(fileTest.getAbsolutePath(), filesize); try { hostName = java.net.InetAddress.getLocalHost().getHostName(); } catch (Exception e) { hostName = "localhost"; } } @After public void endTest() throws Exception { if (pad != null) { pad.killall(false); } cleanIfNecessary(this.fileTest); cleanIfNecessary(this.fileDeployed); cleanIfNecessary(this.fileDeployed2); cleanIfNecessary(this.fileRetrieved2); cleanIfNecessary(this.fileRetrieved); } @Ignore @Test public void action() throws Exception { long fileTestSum = TestAPI.checkSum(fileTest); if (logger.isDebugEnabled()) { logger.debug("Loading descriptor from: " + XML_LOCATION); } // We save the current state of the schema validation and set it to false for this example String validatingProperyOld = ProActiveConfiguration.getInstance() .getProperty("schema.validation"); System.setProperty("schema.validation", "false"); VariableContract vc = new VariableContract(); vc.setVariableFromProgram("JVM_PROCESS", jvmProcess, VariableContractType.DescriptorDefaultVariable); vc.setVariableFromProgram("HOST_NAME", hostName, VariableContractType.DescriptorDefaultVariable); pad = ProActive.getProactiveDescriptor(XML_LOCATION, vc); // we restore the old state of the schema validation System.setProperty("schema.validation", validatingProperyOld); VirtualNode testVNode = pad.getVirtualNode("test"); testVNode.getVirtualNodeInternal() .setFileTransferParams(testblocksize, testflyingblocks); long initDeployment = System.currentTimeMillis(); testVNode.activate(); if (logger.isDebugEnabled()) { logger.debug("Getting the Node."); } Node[] node = testVNode.getNodes(); long finitDeployment = System.currentTimeMillis(); assertTrue(node.length > 0); if (logger.isDebugEnabled()) { logger.debug("Deployed " + node.length + " node from VirtualNode " + testVNode.getName() + " in " + (finitDeployment - initDeployment) + "[ms]"); } //Checking correc FileTransferDeploy if (logger.isDebugEnabled()) { logger.debug( "Checking the integrity of the test file transfer at deployment time."); } long fileDeployedSum = TestAPI.checkSum(fileDeployed); assertTrue(fileTestSum == fileDeployedSum); //Checking correct FileTransferRetrieve if (logger.isDebugEnabled()) { logger.debug("Retrieving test files"); } long initRetrieve = System.currentTimeMillis(); FileVector fileVector = testVNode.getVirtualNodeInternal() .fileTransferRetrieve(); //async fileVector.waitForAll(); //sync here long finitRetrieve = System.currentTimeMillis(); if (logger.isDebugEnabled()) { logger.debug("Retrieved " + fileVector.size() + " files from VirtualNode " + testVNode.getName() + " in " + (finitRetrieve - initRetrieve) + "[ms]"); } assertTrue(fileVector.size() == 2); fileRetrieved = new File(fileRetrieved.getAbsoluteFile() + "-" + node[0].getNodeInformation().getName()); fileRetrieved2 = new File(fileRetrieved2.getAbsoluteFile() + "-" + node[0].getNodeInformation().getName()); long fileRetrievedSum = TestAPI.checkSum(fileRetrieved); if (logger.isDebugEnabled()) { logger.debug("CheckSum TestFile =" + fileTestSum); logger.debug("CheckSum RetrieveFile=" + fileRetrievedSum); logger.debug("CheckSum Deploy=" + fileDeployedSum); } assertTrue(fileTestSum == fileRetrievedSum); } /** * Cleans test files */ private void cleanIfNecessary(File f) { if (f.exists()) { if (logger.isDebugEnabled()) { logger.debug("Deleting old randomly generated file:" + f.getName()); } f.delete(); } } /** * @param args */ public static void main(String[] args) { if (args.length == 4) { filesize = Integer.parseInt(args[0]); testblocksize = Integer.parseInt(args[1]); testflyingblocks = Integer.parseInt(args[2]); XML_LOCATION = args[3]; } else if (args.length != 0) { System.out.println( "Use with arguments: filesize[mb] fileblocksize[bytes] maxflyingblocks xmldescriptorpath"); } TestDeployRetrieve test = new TestDeployRetrieve(); test.jvmProcess = "remoteJVM"; try { System.out.println("InitTest"); test.initTest(); System.out.println("Action"); test.action(); System.out.println("endTest"); test.endTest(); System.out.println("The end"); } catch (Exception e) { e.printStackTrace(); } } }
package pitt.search.semanticvectors.vectors; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import java.util.logging.Logger; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.util.OpenBitSet; /** * Binary implementation of Vector. * * @author cohen */ public class BinaryVector extends Vector { public static final Logger logger = Logger.getLogger(BinaryVector.class.getCanonicalName()); private static final int DEBUG_PRINT_LENGTH = 64; private final int dimension; /** * Elemental representation for binary vectors. */ private OpenBitSet bitSet; private boolean isSparse; /** * Representation of voting record for superposition. Each OpenBitSet object contains one bit * of the count for the vote in each dimension. The count for any given dimension is derived from * all of the bits in that dimension across the OpenBitSets in the voting record. * * The precision of the voting record (in number of decimal places) is defined upon initialization. * By default, if the first weight added is an integer, rounding occurs to the nearest integer. * Otherwise, rounding occurs to the second binary place. */ private ArrayList<OpenBitSet> votingRecord; int decimalPlaces = 0; /** Accumulated sum of the weights with which vectors have been added into the voting record */ int totalNumberOfVotes = 0; // TODO(widdows) Understand and comment this. int minimum = 0; // Used only for temporary internal storage. private OpenBitSet tempSet; public BinaryVector(int dimension) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { throw new IllegalArgumentException("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } this.dimension = dimension; this.bitSet = new OpenBitSet(dimension); this.isSparse = true; } /** * Returns a new copy of this vector, in dense format. */ @SuppressWarnings("unchecked") public BinaryVector copy() { BinaryVector copy = new BinaryVector(dimension); copy.bitSet = (OpenBitSet) bitSet.clone(); if (!isSparse) copy.votingRecord = (ArrayList<OpenBitSet>) votingRecord.clone(); return copy; } public String toString() { StringBuilder debugString = new StringBuilder("BinaryVector."); if (isSparse) { debugString.append(" Elemental. First " + DEBUG_PRINT_LENGTH + " values are:\n"); for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.getBit(x) + " "); debugString.append("\nCardinality " + bitSet.cardinality()+"\n"); } else { debugString.append(" Semantic. First " + DEBUG_PRINT_LENGTH + " values are:\n"); // output voting record for first DEBUG_PRINT_LENGTH dimension debugString.append("\nVOTING RECORD: \n"); for (int y =0; y < votingRecord.size(); y++) { for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(votingRecord.get(y).getBit(x) + " "); debugString.append("\n"); } // TODO - output count from first DEBUG_PRINT_LENGTH dimension debugString.append("\nNORMALIZED: "); this.normalize(); for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.getBit(x) + " "); debugString.append("\n"); // Calculate actual values for first 20 dimension double[] actualvals = new double[DEBUG_PRINT_LENGTH]; debugString.append("COUNTS : "); for (int x =0; x < votingRecord.size(); x++) { for (int y = 0; y < DEBUG_PRINT_LENGTH; y++) { if (votingRecord.get(x).fastGet(y)) actualvals[y] += Math.pow(2, x); } } for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) { debugString.append((int) ((minimum + actualvals[x]) / Math.pow(10, decimalPlaces)) + " "); } debugString.append("\nCardinality " + bitSet.cardinality()+"\n"); debugString.append("Votes " + totalNumberOfVotes+"\n"); debugString.append("Minimum " + minimum + "\n"); } return debugString.toString(); } @Override public int getDimension() { return dimension; } public BinaryVector createZeroVector(int dimension) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { logger.severe("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } return new BinaryVector(dimension); } @Override public boolean isZeroVector() { if (isSparse) { return bitSet.cardinality() == 0; } else { return (votingRecord == null) || (votingRecord.size() == 0); } } @Override /** * Generates a basic elemental vector with a given number of 1's and otherwise 0's. * For binary vectors, the numnber of 1's and 0's must be the same, half the dimension. * * @return representation of basic binary vector. */ public BinaryVector generateRandomVector(int dimension, int numEntries, Random random) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { throw new IllegalArgumentException("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } // Check for balance between 1's and 0's if (numEntries != dimension / 2) { logger.severe("Attempting to create binary vector with unequal number of zeros and ones." + " Unlikely to produce meaningful results. Therefore, seedlength has been set to " + " dimension/2, as recommended for binary vectors"); numEntries = dimension / 2; } BinaryVector randomVector = new BinaryVector(dimension); randomVector.bitSet = new OpenBitSet(dimension); int testPlace = dimension - 1, entryCount = 0; // Iterate across dimension of bitSet, changing 0 to 1 if random(1) > 0.5 // until dimension/2 1's added. while (entryCount < numEntries) { testPlace = random.nextInt(dimension); if (!randomVector.bitSet.fastGet(testPlace)) { randomVector.bitSet.fastSet(testPlace); entryCount++; } } return randomVector; } @Override /** * Measures overlap of two vectors using 1 - normalized Hamming distance * * Causes this and other vector to be converted to dense representation. */ public double measureOverlap(Vector other) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (isZeroVector()) return 0; BinaryVector binaryOther = (BinaryVector) other; if (binaryOther.isZeroVector()) return 0; // Calculate hamming distance in place using cardinality and XOR, then return bitset to // original state. this.bitSet.xor(binaryOther.bitSet); double hammingDistance = this.bitSet.cardinality(); this.bitSet.xor(binaryOther.bitSet); return 1 - (hammingDistance / (double) dimension); } @Override /** * Adds the other vector to this one. If this vector was an elemental vector, the * "semantic vector" components (i.e. the voting record and temporary bitset) will be * initialized. * * Note that the precision of the voting record (in decimal places) is decided at this point: * if the initialization weight is an integer, rounding will occur to the nearest integer. * If not, rounding will occur to the second decimal place. * * This is an attempt to save space, as voting records can be prohibitively expansive * if not contained. */ public void superpose(Vector other, double weight, int[] permutation) { IncompatibleVectorsException.checkVectorsCompatible(this, other); BinaryVector binaryOther = (BinaryVector) other; if (isSparse) { if (Math.round(weight) != weight) { decimalPlaces = 2; } elementalToSemantic(); } if (permutation != null) { // Rather than permuting individual dimensions, we permute 64 bit groups at a time. // This should be considerably quicker, and dimension/64 should allow for sufficient // permutations if (permutation.length != dimension / 64) { throw new IllegalArgumentException("Binary vector of dimension " + dimension + " must have permutation of length " + dimension / 64 + " not " + permutation.length); } //TODO permute in place and reverse, to avoid creating a new BinaryVector here BinaryVector temp = binaryOther.copy(); temp.permute(permutation); superposeBitSet(temp.bitSet, weight); } else { superposeBitSet(binaryOther.bitSet, weight); } } /** * This method is the first of two required to facilitate superposition. The underlying representation * (i.e. the voting record) is an ArrayList of OpenBitSet, each with dimension "dimension", which can * be thought of as an expanding 2D array of bits. Each column keeps count (in binary) for the respective * dimension, and columns are incremented in parallel by sweeping a bitset across the rows. In any dimension * in which the BitSet to be added contains a "1", the effect will be that 1's are changed to 0's until a * new 1 is added (e.g. the column '110' would become '001' and so forth). * * The first method deals with floating point issues, and accelerates superposition by decomposing * the task into segments. * * @param incomingBitSet * @param weight */ protected void superposeBitSet(OpenBitSet incomingBitSet, double weight) { // If fractional weights are used, encode all weights as integers (1000 x double value). weight = (int) Math.round(weight * Math.pow(10, decimalPlaces)); if (weight == 0) return; // Keep track of number (or cumulative weight) of votes. totalNumberOfVotes += weight; // Decompose superposition task such that addition of some power of 2 (e.g. 64) is accomplished // by beginning the process at the relevant row (e.g. 7) instead of starting multiple (e.g. 64) // superposition processes at the first row. int logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2))); if (logFloorOfWeight < votingRecord.size() - 1) { while (logFloorOfWeight > 0) { superposeBitSetFromRowFloor(incomingBitSet, logFloorOfWeight); weight = weight - (int) Math.pow(2,logFloorOfWeight); logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2))); } } // Add remaining component of weight incrementally. for (int x = 0; x < weight; x++) superposeBitSetFromRowFloor(incomingBitSet, 0); } /** * Performs superposition from a particular row by sweeping a bitset across the voting record * such that for any column in which the incoming bitset contains a '1', 1's are changed * to 0's until a new 1 can be added, facilitating incrementation of the * binary number represented in this column. * * @param incomingBitSet the bitset to be added * @param rowfloor the index of the place in the voting record to start the sweep at */ protected void superposeBitSetFromRowFloor(OpenBitSet incomingBitSet, int rowfloor) { // Attempt to save space when minimum value across all columns > 0 // by decrementing across the board and raising the minimum where possible. int max = getMaximumSharedWeight(); if (max > 0) { decrement(max); } // Handle overflow: if any column that will be incremented // contains all 1's, add a new row to the voting record. tempSet.xor(tempSet); tempSet.xor(incomingBitSet); for (int x = rowfloor; x < votingRecord.size() && tempSet.cardinality() > 0; x++) { tempSet.and(votingRecord.get(x)); } if (tempSet.cardinality() > 0) { votingRecord.add(new OpenBitSet(dimension)); } // Sweep copy of bitset to be added across rows of voting record. // If a new '1' is added, this position in the copy is changed to zero // and will not affect future rows. // The xor step will transform 1's to 0's or vice versa for // dimension in which the temporary bitset contains a '1'. votingRecord.get(rowfloor).xor(incomingBitSet); tempSet.xor(tempSet); tempSet.xor(incomingBitSet); for (int x = rowfloor + 1; x < votingRecord.size(); x++) { tempSet.andNot(votingRecord.get(x-1)); //if 1 already added, eliminate dimension from tempSet votingRecord.get(x).xor(tempSet); votingRecord.get(x).trimTrailingZeros(); //attempt to save in sparsely populated rows } } /** * Reverses a string - simplifies the decoding of the binary vector for the 'exact' method * although it wouldn't be difficult to reverse the counter instead */ public static String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } return new StringBuffer(str).reverse().toString(); } /** * Returns a bitset with a "1" in the position of every dimension * that exactly matches the target number. */ private OpenBitSet exact(int target) { if (target == 0) { tempSet.set(0, dimension); tempSet.xor(votingRecord.get(0)); for (int x = 1; x < votingRecord.size(); x++) tempSet.andNot(votingRecord.get(x)); return tempSet; } String inbinary = reverse(Integer.toBinaryString(target)); tempSet.xor(tempSet); tempSet.xor(votingRecord.get(inbinary.indexOf("1"))); for (int q =0; q < votingRecord.size(); q++) { if (q < inbinary.length()) if (inbinary.charAt(q) == '1') tempSet.and(votingRecord.get(q)); else tempSet.andNot(votingRecord.get(q)); } // TODO(widdows): Figure out if there's a good reason for returning a member variable. // Seems redundant to do this. return tempSet; } /** * This method is used determine which dimension will receive 1 and which 0 when the voting * process is concluded. It produces an OpenBitSet in which * "1" is assigned to all dimension with a count > 50% of the total number of votes (i.e. more 1's than 0's added) * "0" is assigned to all dimension with a count < 50% of the total number of votes (i.e. more 0's than 1's added) * "0" or "1" are assigned to all dimension with a count = 50% of the total number of votes (i.e. equal 1's and 0's added) * * @return an OpenBitSet representing the superposition of all vectors added up to this point */ protected OpenBitSet concludeVote() { if (votingRecord.size() == 0) return new OpenBitSet(dimension); else return concludeVote(totalNumberOfVotes); } protected OpenBitSet concludeVote(int target) { int target2 = (int) Math.ceil((double) target / (double) 2); target2 = target2 - minimum; // Unlikely other than in testing: minimum more than half the votes if (target2 < 0) { OpenBitSet ans = new OpenBitSet(dimension); ans.set(0, dimension); return ans; } //Voting record insufficient to hold half the votes (unlikely unless unbalanced vectors used), so return zero vector // if (votingRecord.size() < 1+ Math.log(target2)/Math.log(2)) // return new OpenBitSet(dimension); boolean even = (target % 2 == 0); OpenBitSet result = concludeVote(target2, votingRecord.size() - 1); if (even) { tempSet = exact(target2); boolean switcher = true; // 50% chance of being true with split vote. for (int q = 0; q < dimension; q++) { if (tempSet.fastGet(q)) { switcher = !switcher; if (switcher) tempSet.fastClear(q); } } result.andNot(tempSet); } return result; } protected OpenBitSet concludeVote(int target, int row_ceiling) { /** logger.info("Entering conclude vote, target " + target + " row_ceiling " + row_ceiling + "voting record " + votingRecord.size() + " minimum "+ minimum + " index "+ Math.log(target)/Math.log(2) + " vector\n" + toString()); **/ if (target == 0) { OpenBitSet atLeastZero = new OpenBitSet(dimension); atLeastZero.set(0, dimension); return atLeastZero; } double rowfloor = Math.log(target)/Math.log(2); int row_floor = (int) Math.floor(rowfloor); //for 0 index int remainder = target - (int) Math.pow(2,row_floor); //System.out.println(target+"\t"+rowfloor+"\t"+row_floor+"\t"+remainder); if (row_ceiling == 0 && target == 1) { return votingRecord.get(0); } if (remainder == 0) { // Simple case - the number we're looking for is 2^n, so anything with a "1" in row n or above is true. OpenBitSet definitePositives = new OpenBitSet(dimension); for (int q = row_floor; q <= row_ceiling; q++) definitePositives.or(votingRecord.get(q)); return definitePositives; } else { // Simple part of complex case: first get anything with a "1" in a row above n (all true). OpenBitSet definitePositives = new OpenBitSet(dimension); for (int q = row_floor+1; q <= row_ceiling; q++) definitePositives.or(votingRecord.get(q)); // Complex part of complex case: get those that have a "1" in the row of n. OpenBitSet possiblePositives = (OpenBitSet) votingRecord.get(row_floor).clone(); OpenBitSet definitePositives2 = concludeVote(remainder, row_floor-1); possiblePositives.and(definitePositives2); definitePositives.or(possiblePositives); return definitePositives; } } /** * Decrement every dimension. Assumes at least one count in each dimension * i.e: no underflow check currently - will wreak havoc with zero counts */ public void decrement() { tempSet.set(0, dimension); for (int q = 0; q < votingRecord.size(); q++) { votingRecord.get(q).xor(tempSet); tempSet.and(votingRecord.get(q)); } } /** * Decrement every dimension by the number passed as a parameter. Again at least one count in each dimension * i.e: no underflow check currently - will wreak havoc with zero counts */ public void decrement(int weight) { if (weight == 0) return; minimum+= weight; int logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2))); if (logfloor < votingRecord.size() - 1) { while (logfloor > 0) { selected_decrement(logfloor); weight = weight - (int) Math.pow(2,logfloor); logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2))); } } for (int x = 0; x < weight; x++) { decrement(); } } public void selected_decrement(int floor) { tempSet.set(0, dimension); for (int q = floor; q < votingRecord.size(); q++) { votingRecord.get(q).xor(tempSet); tempSet.and(votingRecord.get(q)); } } /** * Returns the highest value shared by all dimensions. */ public int getMaximumSharedWeight() { int thismaximum = 0; tempSet.xor(tempSet); // Reset tempset to zeros. for (int x = votingRecord.size() - 1; x >= 0; x tempSet.or(votingRecord.get(x)); if (tempSet.cardinality() == dimension) { thismaximum += (int) Math.pow(2, x); tempSet.xor(tempSet); } } return thismaximum; } @Override /** * Normalizes the vector, converting sparse to dense representations in the process. */ public void normalize() { if (isSparse) elementalToSemantic(); this.bitSet = concludeVote(); } @Override /** * Writes vector out to object output stream. Converts to dense format if necessary. */ public void writeToLuceneStream(IndexOutput outputStream) { if (isSparse) { elementalToSemantic(); } long[] bitArray = bitSet.getBits(); for (int i = 0; i < bitArray.length; i++) { try { outputStream.writeLong(bitArray[i]); } catch (IOException e) { logger.severe("Couldn't write binary vector to lucene output stream."); e.printStackTrace(); } } } @Override /** * Reads a (dense) version of a vector from a Lucene input stream. */ public void readFromLuceneStream(IndexInput inputStream) { long bitArray[] = new long[(dimension / 64)]; for (int i = 0; i < dimension / 64; ++i) { try { bitArray[i] = inputStream.readLong(); } catch (IOException e) { logger.severe("Couldn't read binary vector from lucene output stream."); e.printStackTrace(); } } this.bitSet = new OpenBitSet(bitArray, bitArray.length); this.isSparse = true; } @Override /** * Writes vector to a string of the form 010 etc. (no delimiters). * * No terminating newline or delimiter. */ public String writeToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < dimension; ++i) { builder.append(Integer.toString(bitSet.getBit(i))); } return builder.toString(); } /** * Writes vector to a string of the form 010 etc. (no delimiters). * * No terminating newline or delimiter. */ public String writeLongToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < (bitSet.getBits().length); ++i) { builder.append(Long.toString(bitSet.getBits()[i])+"|"); } return builder.toString(); } @Override /** * Writes vector from a string of the form 01001 etc. */ public void readFromString(String input) { if (input.length() != dimension) { throw new IllegalArgumentException("Found " + (input.length()) + " possible coordinates: " + "expected " + dimension); } for (int i = 0; i < dimension; ++i) { if (input.charAt(i) == '1') bitSet.fastSet(i); } } /** * Automatically translate elemental vector (no storage capacity) into * semantic vector (storage capacity initialized, this will occupy RAM) */ protected void elementalToSemantic() { if (!isSparse) { logger.warning("Tryied to transform an elemental vector which is not in fact elemental." + "This may be a programming error."); return; } this.votingRecord = new ArrayList<OpenBitSet>(); this.tempSet = new OpenBitSet(dimension); this.isSparse = false; } /** * Permute the long[] array underlying the OpenBitSet binary representation */ public void permute(int[] permutation) { if (permutation.length != getDimension() / 64) { throw new IllegalArgumentException("Binary vector of dimension " + getDimension() + " must have permutation of length " + getDimension() / 64 + " not " + permutation.length); } //TODO permute in place without creating additional long[] (if proves problematic at scale) long[] coordinates = bitSet.getBits(); long[] new_coordinates = new long[coordinates.length]; for (int i = 0; i < coordinates.length; ++i) { int positionToAdd = i; positionToAdd = permutation[positionToAdd]; new_coordinates[i] = coordinates[positionToAdd]; } bitSet.setBits(new_coordinates); } // Available for testing and copying. protected BinaryVector(OpenBitSet inSet) { this.dimension = (int) inSet.size(); this.bitSet = inSet; } // Available for testing protected int bitLength() { return bitSet.getBits().length; } // Monitor growth of voting record. protected int numRows() { return votingRecord.size(); } }
package pitt.search.semanticvectors.vectors; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import java.util.logging.Logger; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.util.OpenBitSet; import pitt.search.semanticvectors.FlagConfig; import pitt.search.semanticvectors.hashing.Bobcat; /** * Binary implementation of Vector. * * Uses an "elemental" representation which is a single bit string (Lucene OpenBitSet). * * Superposes on this a "semantic" representation which contains the weights with which different * vectors have been added (superposed) onto this one. Calling {@link #superpose} causes the * voting record to be updated, but for performance the votes are not tallied back into the * elemental bit set representation until {@link #normalize} or one of the writing functions * is called. * * @author Trevor Cohen */ public class BinaryVector implements Vector { public static final Logger logger = Logger.getLogger(BinaryVector.class.getCanonicalName()); // TODO: Determing proper interface for default constants. /** * Number of decimal places to consider in weighted superpositions of binary vectors. * Higher precision requires additional memory during training. */ public static final int BINARY_VECTOR_DECIMAL_PLACES = 2; public static final boolean BINARY_BINDING_WITH_PERMUTE = false; private static final int DEBUG_PRINT_LENGTH = 64; private Random random; private final int dimension; /** * Elemental representation for binary vectors. */ protected OpenBitSet bitSet; private boolean isSparse; /** * Representation of voting record for superposition. Each OpenBitSet object contains one bit * of the count for the vote in each dimension. The count for any given dimension is derived from * all of the bits in that dimension across the OpenBitSets in the voting record. * * The precision of the voting record (in number of decimal places) is defined upon initialization. * By default, if the first weight added is an integer, rounding occurs to the nearest integer. * Otherwise, rounding occurs to the second binary place. */ private ArrayList<OpenBitSet> votingRecord; int decimalPlaces = 0; /** Accumulated sum of the weights with which vectors have been added into the voting record */ int totalNumberOfVotes = 0; // TODO(widdows) Understand and comment this. int minimum = 0; // Used only for temporary internal storage. private OpenBitSet tempSet; public BinaryVector(int dimension) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { throw new IllegalArgumentException("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } this.dimension = dimension; this.bitSet = new OpenBitSet(dimension); this.isSparse = true; this.random = new Random(); } /** * Returns a new copy of this vector, in dense format. */ @SuppressWarnings("unchecked") public BinaryVector copy() { BinaryVector copy = new BinaryVector(dimension); copy.bitSet = (OpenBitSet) bitSet.clone(); if (!isSparse) copy.votingRecord = (ArrayList<OpenBitSet>) votingRecord.clone(); return copy; } public String toString() { StringBuilder debugString = new StringBuilder("BinaryVector."); if (isSparse) { debugString.append(" Elemental. First " + DEBUG_PRINT_LENGTH + " values are:\n"); for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.getBit(x) + " "); debugString.append("\nCardinality " + bitSet.cardinality()+"\n"); } else { debugString.append(" Semantic. First " + DEBUG_PRINT_LENGTH + " values are:\n"); // output voting record for first DEBUG_PRINT_LENGTH dimension debugString.append("\nVOTING RECORD: \n"); for (int y =0; y < votingRecord.size(); y++) { for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(votingRecord.get(y).getBit(x) + " "); debugString.append("\n"); } // TODO - output count from first DEBUG_PRINT_LENGTH dimension debugString.append("\nNORMALIZED: "); this.normalize(); for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.getBit(x) + " "); debugString.append("\n"); // Calculate actual values for first 20 dimension double[] actualvals = new double[DEBUG_PRINT_LENGTH]; debugString.append("COUNTS : "); for (int x =0; x < votingRecord.size(); x++) { for (int y = 0; y < DEBUG_PRINT_LENGTH; y++) { if (votingRecord.get(x).fastGet(y)) actualvals[y] += Math.pow(2, x); } } for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) { debugString.append((int) ((minimum + actualvals[x]) / Math.pow(10, decimalPlaces)) + " "); } debugString.append("\nCardinality " + bitSet.cardinality()+"\n"); debugString.append("Votes " + totalNumberOfVotes+"\n"); debugString.append("Minimum " + minimum + "\n"); } return debugString.toString(); } @Override public int getDimension() { return dimension; } public BinaryVector createZeroVector(int dimension) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { logger.severe("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } return new BinaryVector(dimension); } @Override public boolean isZeroVector() { if (isSparse) { return bitSet.cardinality() == 0; } else { return (votingRecord == null) || (votingRecord.size() == 0); } } @Override /** * Generates a basic elemental vector with a given number of 1's and otherwise 0's. * For binary vectors, the numnber of 1's and 0's must be the same, half the dimension. * * @return representation of basic binary vector. */ public BinaryVector generateRandomVector(int dimension, int numEntries, Random random) { // Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks if (dimension % 64 != 0) { throw new IllegalArgumentException("Dimension should be a multiple of 64: " + dimension + " will lead to trouble!"); } // Check for balance between 1's and 0's if (numEntries != dimension / 2) { logger.severe("Attempting to create binary vector with unequal number of zeros and ones." + " Unlikely to produce meaningful results. Therefore, seedlength has been set to " + " dimension/2, as recommended for binary vectors"); numEntries = dimension / 2; } BinaryVector randomVector = new BinaryVector(dimension); randomVector.bitSet = new OpenBitSet(dimension); int testPlace = dimension - 1, entryCount = 0; // Iterate across dimension of bitSet, changing 0 to 1 if random(1) > 0.5 // until dimension/2 1's added. while (entryCount < numEntries) { testPlace = random.nextInt(dimension); if (!randomVector.bitSet.fastGet(testPlace)) { randomVector.bitSet.fastSet(testPlace); entryCount++; } } return randomVector; } @Override /** * Measures overlap of two vectors using 1 - normalized Hamming distance * * Causes this and other vector to be converted to dense representation. */ public double measureOverlap(Vector other) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (isZeroVector()) return 0; BinaryVector binaryOther = (BinaryVector) other; if (binaryOther.isZeroVector()) return 0; // Calculate hamming distance in place using cardinality and XOR, then return bitset to // original state. double hammingDistance = OpenBitSet.xorCount(binaryOther.bitSet, this.bitSet); return 2*(0.5 - (hammingDistance / (double) dimension)); } @Override /** * Adds the other vector to this one. If this vector was an elemental vector, the * "semantic vector" components (i.e. the voting record and temporary bitset) will be * initialized. * * Note that the precision of the voting record (in decimal places) is decided at this point: * if the initialization weight is an integer, rounding will occur to the nearest integer. * If not, rounding will occur to the second decimal place. * * This is an attempt to save space, as voting records can be prohibitively expansive * if not contained. */ public void superpose(Vector other, double weight, int[] permutation) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (weight == 0d) return; if (other.isZeroVector()) return; BinaryVector binaryOther = (BinaryVector) other; if (isSparse) { if (Math.round(weight) != weight) { decimalPlaces = BINARY_VECTOR_DECIMAL_PLACES; } elementalToSemantic(); } if (permutation != null) { // Rather than permuting individual dimensions, we permute 64 bit groups at a time. // This should be considerably quicker, and dimension/64 should allow for sufficient // permutations if (permutation.length != dimension / 64) { throw new IllegalArgumentException("Binary vector of dimension " + dimension + " must have permutation of length " + dimension / 64 + " not " + permutation.length); } //TODO permute in place and reverse, to avoid creating a new BinaryVector here BinaryVector temp = binaryOther.copy(); temp.permute(permutation); superposeBitSet(temp.bitSet, weight); } else { superposeBitSet(binaryOther.bitSet, weight); } } /** * This method is the first of two required to facilitate superposition. The underlying representation * (i.e. the voting record) is an ArrayList of OpenBitSet, each with dimension "dimension", which can * be thought of as an expanding 2D array of bits. Each column keeps count (in binary) for the respective * dimension, and columns are incremented in parallel by sweeping a bitset across the rows. In any dimension * in which the BitSet to be added contains a "1", the effect will be that 1's are changed to 0's until a * new 1 is added (e.g. the column '110' would become '001' and so forth). * * The first method deals with floating point issues, and accelerates superposition by decomposing * the task into segments. * * @param incomingBitSet * @param weight */ protected void superposeBitSet(OpenBitSet incomingBitSet, double weight) { // If fractional weights are used, encode all weights as integers (1000 x double value). weight = (int) Math.round(weight * Math.pow(10, decimalPlaces)); if (weight == 0) return; // Keep track of number (or cumulative weight) of votes. totalNumberOfVotes += weight; // Decompose superposition task such that addition of some power of 2 (e.g. 64) is accomplished // by beginning the process at the relevant row (e.g. 7) instead of starting multiple (e.g. 64) // superposition processes at the first row. int logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2))); if (logFloorOfWeight < votingRecord.size() - 1) { while (logFloorOfWeight > 0) { superposeBitSetFromRowFloor(incomingBitSet, logFloorOfWeight); weight = weight - (int) Math.pow(2,logFloorOfWeight); logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2))); } } // Add remaining component of weight incrementally. for (int x = 0; x < weight; x++) superposeBitSetFromRowFloor(incomingBitSet, 0); } /** * Performs superposition from a particular row by sweeping a bitset across the voting record * such that for any column in which the incoming bitset contains a '1', 1's are changed * to 0's until a new 1 can be added, facilitating incrementation of the * binary number represented in this column. * * @param incomingBitSet the bitset to be added * @param rowfloor the index of the place in the voting record to start the sweep at */ protected void superposeBitSetFromRowFloor(OpenBitSet incomingBitSet, int rowfloor) { // Attempt to save space when minimum value across all columns > 0 // by decrementing across the board and raising the minimum where possible. int max = getMaximumSharedWeight(); if (max > 0) { decrement(max); } // Handle overflow: if any column that will be incremented // contains all 1's, add a new row to the voting record. tempSet.xor(tempSet); tempSet.xor(incomingBitSet); for (int x = rowfloor; x < votingRecord.size() && tempSet.cardinality() > 0; x++) { tempSet.and(votingRecord.get(x)); } if (tempSet.cardinality() > 0) { votingRecord.add(new OpenBitSet(dimension)); } // Sweep copy of bitset to be added across rows of voting record. // If a new '1' is added, this position in the copy is changed to zero // and will not affect future rows. // The xor step will transform 1's to 0's or vice versa for // dimension in which the temporary bitset contains a '1'. votingRecord.get(rowfloor).xor(incomingBitSet); tempSet.xor(tempSet); tempSet.xor(incomingBitSet); for (int x = rowfloor + 1; x < votingRecord.size(); x++) { tempSet.andNot(votingRecord.get(x-1)); //if 1 already added, eliminate dimension from tempSet votingRecord.get(x).xor(tempSet); votingRecord.get(x).trimTrailingZeros(); //attempt to save in sparsely populated rows } } /** * Reverses a string - simplifies the decoding of the binary vector for the 'exact' method * although it wouldn't be difficult to reverse the counter instead */ public static String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } return new StringBuffer(str).reverse().toString(); } /** * Sets {@link #tempSet} to be a bitset with a "1" in the position of every dimension * in the {@link #votingRecord} that exactly matches the target number. */ private void setTempSetToExactMatches(int target) { if (target == 0) { tempSet.set(0, dimension); tempSet.xor(votingRecord.get(0)); for (int x = 1; x < votingRecord.size(); x++) tempSet.andNot(votingRecord.get(x)); } String inbinary = reverse(Integer.toBinaryString(target)); tempSet.xor(tempSet); tempSet.xor(votingRecord.get(inbinary.indexOf("1"))); for (int q =0; q < votingRecord.size(); q++) { if (q < inbinary.length()) if (inbinary.charAt(q) == '1') tempSet.and(votingRecord.get(q)); else tempSet.andNot(votingRecord.get(q)); } } /** * This method is used determine which dimension will receive 1 and which 0 when the voting * process is concluded. It produces an OpenBitSet in which * "1" is assigned to all dimension with a count > 50% of the total number of votes (i.e. more 1's than 0's added) * "0" is assigned to all dimension with a count < 50% of the total number of votes (i.e. more 0's than 1's added) * "0" or "1" are assigned to all dimension with a count = 50% of the total number of votes (i.e. equal 1's and 0's added) * * @return an OpenBitSet representing the superposition of all vectors added up to this point */ protected OpenBitSet concludeVote() { if (votingRecord.size() == 0 || votingRecord.size() == 1 && votingRecord.get(0).cardinality() ==0) return new OpenBitSet(dimension); else return concludeVote(totalNumberOfVotes); } protected OpenBitSet concludeVote(int target) { int target2 = (int) Math.ceil((double) target / (double) 2); target2 = target2 - minimum; // Unlikely other than in testing: minimum more than half the votes if (target2 < 0) { OpenBitSet ans = new OpenBitSet(dimension); ans.set(0, dimension); return ans; } boolean even = (target % 2 == 0); OpenBitSet result = concludeVote(target2, votingRecord.size() - 1); if (even) { setTempSetToExactMatches(target2); boolean switcher = true; // 50% chance of being true with split vote. for (int q = 0; q < dimension; q++) { if (tempSet.fastGet(q)) { switcher = !switcher; if (switcher) tempSet.fastClear(q); } } result.andNot(tempSet); } return result; } protected OpenBitSet concludeVote(int target, int row_ceiling) { /** logger.info("Entering conclude vote, target " + target + " row_ceiling " + row_ceiling + "voting record " + votingRecord.size() + " minimum "+ minimum + " index "+ Math.log(target)/Math.log(2) + " vector\n" + toString()); **/ if (target == 0) { OpenBitSet atLeastZero = new OpenBitSet(dimension); atLeastZero.set(0, dimension); return atLeastZero; } double rowfloor = Math.log(target)/Math.log(2); int row_floor = (int) Math.floor(rowfloor); //for 0 index int remainder = target - (int) Math.pow(2,row_floor); //System.out.println(target+"\t"+rowfloor+"\t"+row_floor+"\t"+remainder); if (row_ceiling == 0 && target == 1) { return votingRecord.get(0); } if (remainder == 0) { // Simple case - the number we're looking for is 2^n, so anything with a "1" in row n or above is true. OpenBitSet definitePositives = new OpenBitSet(dimension); for (int q = row_floor; q <= row_ceiling; q++) definitePositives.or(votingRecord.get(q)); return definitePositives; } else { // Simple part of complex case: first get anything with a "1" in a row above n (all true). OpenBitSet definitePositives = new OpenBitSet(dimension); for (int q = row_floor+1; q <= row_ceiling; q++) definitePositives.or(votingRecord.get(q)); // Complex part of complex case: get those that have a "1" in the row of n. OpenBitSet possiblePositives = (OpenBitSet) votingRecord.get(row_floor).clone(); OpenBitSet definitePositives2 = concludeVote(remainder, row_floor-1); possiblePositives.and(definitePositives2); definitePositives.or(possiblePositives); return definitePositives; } } /** * Decrement every dimension. Assumes at least one count in each dimension * i.e: no underflow check currently - will wreak havoc with zero counts */ public void decrement() { tempSet.set(0, dimension); for (int q = 0; q < votingRecord.size(); q++) { votingRecord.get(q).xor(tempSet); tempSet.and(votingRecord.get(q)); } } /** * Decrement every dimension by the number passed as a parameter. Again at least one count in each dimension * i.e: no underflow check currently - will wreak havoc with zero counts */ public void decrement(int weight) { if (weight == 0) return; minimum+= weight; int logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2))); if (logfloor < votingRecord.size() - 1) { while (logfloor > 0) { selectedDecrement(logfloor); weight = weight - (int) Math.pow(2,logfloor); logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2))); } } for (int x = 0; x < weight; x++) { decrement(); } } public void selectedDecrement(int floor) { tempSet.set(0, dimension); for (int q = floor; q < votingRecord.size(); q++) { votingRecord.get(q).xor(tempSet); tempSet.and(votingRecord.get(q)); } } /** * Returns the highest value shared by all dimensions. */ protected int getMaximumSharedWeight() { int thismaximum = 0; tempSet.xor(tempSet); // Reset tempset to zeros. for (int x = votingRecord.size() - 1; x >= 0; x tempSet.or(votingRecord.get(x)); if (tempSet.cardinality() == dimension) { thismaximum += (int) Math.pow(2, x); tempSet.xor(tempSet); } } return thismaximum; } @Override /** * Implements binding using permutations and XOR. */ public void bind(Vector other, int direction) { IncompatibleVectorsException.checkVectorsCompatible(this, other); BinaryVector binaryOther = (BinaryVector) other.copy(); if (direction > 0) { //as per Kanerva 2009: bind(A,B) = perm+(A) XOR B = C //this also functions as the left inverse: left inverse (A,C) = perm+(A) XOR C = B this.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, 1)); //perm+(A) this.bitSet.xor(binaryOther.bitSet); //perm+(A) XOR B } else { //as per Kanerva 2009: right inverse(C,B) = perm-(C XOR B) = perm-(perm+(A)) = A this.bitSet.xor(binaryOther.bitSet); //C XOR B this.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, -1)); //perm-(C XOR B) = A } } @Override /** * Implements inverse of binding using permutations and XOR. */ public void release(Vector other, int direction) { if (!BINARY_BINDING_WITH_PERMUTE) bind(other); else bind (other, direction); } @Override /** * Implements binding using exclusive OR. */ public void bind(Vector other) { IncompatibleVectorsException.checkVectorsCompatible(this, other); if (!BINARY_BINDING_WITH_PERMUTE) { BinaryVector binaryOther = (BinaryVector) other; this.bitSet.xor(binaryOther.bitSet); } else { bind(other, 1); } } @Override /** * Implements inverse binding using exclusive OR. */ public void release(Vector other) { if (!BINARY_BINDING_WITH_PERMUTE) bind(other); else bind(other, -1); } @Override /** * Normalizes the vector, converting sparse to dense representations in the process. This approach deviates from the "majority rule" * approach that is standard in the Binary Spatter Code(). Rather, the probability of assigning a one in a particular dimension * is a function of the probability of encountering the number of votes in the voting record in this dimension. * * This will be slower than normalizeBSC() below, but discards less information with positive effects on accuracy in preliminary experiments * * As a simple example to illustrate why this would be the case, consider the superposition of vectors for the terms "jazz","jazz" and "rock" * With the BSC normalization, the vector produced is identical to "jazz" (as jazz wins the vote in each case). With probabilistic normalization, * the vector produced is somewhat similar to both "jazz" and "rock", with a similarity that is proportional to the weights assigned to the * superposition, e.g. 0.624000:jazz; 0.246000:rock * */ public void normalize() { if (votingRecord == null) return; if (votingRecord.size() == 1) { this.bitSet = votingRecord.get(0); return; } //clear bitset; this.bitSet.xor(this.bitSet); //Ensure that the same set of superposed vectors will always produce the same result random.setSeed(Bobcat.asLong("##universal_superposition_seed##")); //Determine value above the universal minimum for each dimension of the voting record int[] counts = new int[dimension]; int max = totalNumberOfVotes; for (int x =0 ; x < votingRecord.size(); x++) for (int y =0 ; y < dimension; y++) { if (votingRecord.get(x).fastGet(y)) counts[y] += Math.pow(2, x); } for (int w =0; w < dimension; w++) { //determine total number of votes double votes = minimum+counts[w]; //calculate standard deviations above/below the mean of max/2 double z = (votes - (max/2)) / (Math.sqrt(max)/2); //find proportion of data points anticipated within z standard deviations of the mean (assuming approximately normal distribution) double proportion = erf(z/Math.sqrt(2)); //convert into a value between 0 and 1 (i.e. centered on 0.5 rather than centered on 0) proportion = (1+proportion) /2; //probabilistic normalization if ((random.nextDouble()) <= proportion) this.bitSet.fastSet(w); } //housekeeping votingRecord = new ArrayList<OpenBitSet>(); votingRecord.add((OpenBitSet) bitSet.clone()); totalNumberOfVotes = 1; tempSet = new OpenBitSet(dimension); minimum = 0; } // approximation of error function, equation 7.1.27 from //in Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables, //9th printing. New York: Dover, pp. 299-300, 1972. // error of approximation <= 5*10^-4 public double erf(double z) { //erf(-x) == -erf(x) double sign = Math.signum(z); z = Math.abs(z); double a1 = 0.278393, a2 = 0.230389, a3 = 0.000972, a4 = 0.078108; double sumterm = 1 + a1*z + a2*Math.pow(z,2) + a3*Math.pow(z,3) + a4*Math.pow(z,4); return sign * ( 1-1/(Math.pow(sumterm, 4))); } /** * Faster normalization according to the Binary Spatter Code's "majority" rule */ public void normalizeBSC() { if (!isSparse) this.bitSet = concludeVote(); votingRecord = new ArrayList<OpenBitSet>(); votingRecord.add((OpenBitSet) bitSet.clone()); totalNumberOfVotes = 1; tempSet = new OpenBitSet(dimension); minimum = 0; } /** * Counts votes without normalizing vector (i.e. voting record is not altered). Used in SemanticVectorCollider. */ public void tallyVotes() { if (!isSparse) this.bitSet = concludeVote(); } @Override /** * Writes vector out to object output stream. Converts to dense format if necessary. */ public void writeToLuceneStream(IndexOutput outputStream) { if (isSparse) { elementalToSemantic(); } long[] bitArray = bitSet.getBits(); for (int i = 0; i < bitArray.length; i++) { try { outputStream.writeLong(bitArray[i]); } catch (IOException e) { logger.severe("Couldn't write binary vector to lucene output stream."); e.printStackTrace(); } } } @Override /** * Reads a (dense) version of a vector from a Lucene input stream. */ public void readFromLuceneStream(IndexInput inputStream) { long bitArray[] = new long[(dimension / 64)]; for (int i = 0; i < dimension / 64; ++i) { try { bitArray[i] = inputStream.readLong(); } catch (IOException e) { logger.severe("Couldn't read binary vector from lucene output stream."); e.printStackTrace(); } } this.bitSet = new OpenBitSet(bitArray, bitArray.length); this.isSparse = true; } @Override /** * Writes vector to a string of the form 010 etc. (no delimiters). * * No terminating newline or delimiter. */ public String writeToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < dimension; ++i) { builder.append(Integer.toString(bitSet.getBit(i))); } return builder.toString(); } /** * Writes vector to a string of the form 010 etc. (no delimiters). * * No terminating newline or delimiter. */ public String writeLongToString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < (bitSet.getBits().length); ++i) { builder.append(Long.toString(bitSet.getBits()[i])+"|"); } return builder.toString(); } @Override /** * Writes vector from a string of the form 01001 etc. */ public void readFromString(String input) { if (input.length() != dimension) { throw new IllegalArgumentException("Found " + (input.length()) + " possible coordinates: " + "expected " + dimension); } for (int i = 0; i < dimension; ++i) { if (input.charAt(i) == '1') bitSet.fastSet(i); } } /** * Automatically translate elemental vector (no storage capacity) into * semantic vector (storage capacity initialized, this will occupy RAM) */ protected void elementalToSemantic() { if (!isSparse) { logger.warning("Tried to transform an elemental vector which is not in fact elemental." + "This may be a programming error."); return; } votingRecord = new ArrayList<OpenBitSet>(); votingRecord.add((OpenBitSet) bitSet.clone()); tempSet = new OpenBitSet(dimension); isSparse = false; } /** * Permute the long[] array underlying the OpenBitSet binary representation */ public void permute(int[] permutation) { if (permutation.length != getDimension() / 64) { throw new IllegalArgumentException("Binary vector of dimension " + getDimension() + " must have permutation of length " + getDimension() / 64 + " not " + permutation.length); } //TODO permute in place without creating additional long[] (if proves problematic at scale) long[] coordinates = bitSet.getBits(); long[] newCoordinates = new long[coordinates.length]; for (int i = 0; i < coordinates.length; ++i) { int positionToAdd = i; positionToAdd = permutation[positionToAdd]; newCoordinates[i] = coordinates[positionToAdd]; } bitSet.setBits(newCoordinates); } // Available for testing and copying. protected BinaryVector(OpenBitSet inSet) { this.dimension = (int) inSet.size(); this.bitSet = inSet; } // Available for testing protected int bitLength() { return bitSet.getBits().length; } // Monitor growth of voting record. protected int numRows() { if (isSparse) return 0; return votingRecord.size(); } }
package ginger.connexus.activity; import ginger.connexus.R; import ginger.connexus.util.AccountUtils; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.content.IntentSender; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.MenuItem; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.location.LocationClient; public class BaseActivity extends FragmentActivity implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener { public static final int MEDIA_TYPE_IMAGE = 1; public static final int MEDIA_TYPE_VIDEO = 2; private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100; private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200; /* * Define a request code to send to Google Play services This code is * returned in Activity.onActivityResult */ private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000; private boolean mConnected = false; private LocationClient mLocationClient; public Uri fileUri; protected void startLocationClient() { // Connect the client. mLocationClient.connect(); } protected void stopLocationClient() { // Disconnecting the client invalidates it. mLocationClient.disconnect(); } protected Location getLocation() { return mConnected ? mLocationClient.getLastLocation() : null; } /** Create a file Uri for saving an image or video */ private static Uri getOutputMediaFileUri(int type) { return Uri.fromFile(getOutputMediaFile(type)); } /** Create a File for saving an image or video */ @SuppressLint("SimpleDateFormat") private static File getOutputMediaFile(int type) { // To be safe, you should check that the SDCard is mounted // using Environment.getExternalStorageState() before doing this. File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Connexus"); // This location works best if you want the created images to be shared // between applications and persist after your app has been uninstalled. // Create the storage directory if it does not exist if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("Connexus", "failed to create directory"); return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile; if (type == MEDIA_TYPE_IMAGE) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); } else if (type == MEDIA_TYPE_VIDEO) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4"); } else { return null; } return mediaFile; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!AccountUtils.isAuthenticated(this)) { AccountUtils.startAuthenticationFlow(this, getIntent()); finish(); } /* * Create a new location client, using the enclosing class to handle * callbacks. */ mLocationClient = new LocationClient(this, this, this); } @Override protected void onStop() { stopLocationClient(); super.onStop(); } @Override public void onConnected(Bundle dataBundle) { mConnected = true; } @Override public void onDisconnected() { mConnected = false; } /* * Called by Location Services if the attempt to Location Services fails. */ @Override public void onConnectionFailed(ConnectionResult connectionResult) { /* * Google Play services can resolve some errors it detects. If the error * has a resolution, try sending an Intent to start a Google Play * services activity that can resolve error. */ if (connectionResult.hasResolution()) { try { // Start an Activity that tries to resolve the error connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST); /* * Thrown if Google Play services canceled the original * PendingIntent */ } catch (IntentSender.SendIntentException e) { // Log the error e.printStackTrace(); } } else { /* * If no resolution is available, display a dialog to the user with * the error. */ // Get the error code int errorCode = connectionResult.getErrorCode(); // Get the error dialog from Google Play services Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(errorCode, this, CONNECTION_FAILURE_RESOLUTION_REQUEST); // If Google Play services can provide an error dialog if (errorDialog != null) { // Create a new DialogFragment for the error dialog ErrorDialogFragment errorFragment = new ErrorDialogFragment(); // Set the dialog in the DialogFragment errorFragment.setDialog(errorDialog); // Show the error dialog in the DialogFragment errorFragment.show(getSupportFragmentManager(), "Location Updates"); } } } // Define a DialogFragment that displays the error dialog public static class ErrorDialogFragment extends DialogFragment { // Global field to contain the error dialog private Dialog mDialog; // Default constructor. Sets the dialog field to null public ErrorDialogFragment() { super(); mDialog = null; } // Set the dialog to display public void setDialog(Dialog dialog) { mDialog = dialog; } // Return a Dialog to the DialogFragment. @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return mDialog; } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.logout: AccountUtils.signOut(this); AccountUtils.startAuthenticationFlow(this, getIntent()); return true; case R.id.takepic: // create Intent to take a picture and return control to the // calling application Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // fileUri is public. Use this handle to access the saved image // from other classes. fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a // file to // save the // image intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the // image file // name // start the image capture Intent startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); return true; default: return super.onOptionsItemSelected(item); } } /* * Handle results returned to the FragmentActivity by Google Play services */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Decide what to do based on the original request code if (requestCode == CONNECTION_FAILURE_RESOLUTION_REQUEST) { // If the result code is Activity.RESULT_OK, try to connect again if (resultCode == Activity.RESULT_OK) { // Try the request again return; } } if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if (resultCode == RESULT_OK) { // Image captured and saved to fileUri specified in the Intent Toast.makeText(this, "Image saved", Toast.LENGTH_LONG).show(); } else if (resultCode == RESULT_CANCELED) { // User cancelled the image capture Toast.makeText(this, "Canceled", Toast.LENGTH_LONG).show(); } else { // Image capture failed, advise user Toast.makeText(this, "Image capture failed", Toast.LENGTH_LONG).show(); } } if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) { if (resultCode == RESULT_OK) { // Video captured and saved to fileUri specified in the Intent Toast.makeText(this, "Video saved", Toast.LENGTH_LONG).show(); } else if (resultCode == RESULT_CANCELED) { // User cancelled the video capture Toast.makeText(this, "Canceled", Toast.LENGTH_LONG).show(); } else { // Video capture failed, advise user Toast.makeText(this, "Video capture failed", Toast.LENGTH_LONG).show(); } } } }
package br.ufrj.cos.redes.fileAccess; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.Collections; import java.util.List; import br.ufrj.cos.redes.constant.Constants; public class RandomFileChunkRetriever implements FileChunkRetriever { private RandomAccessFile fileReader; private long fileLength; private int chunkCounter; private long chunkLength; private List<Integer> chunkSeqNumList; public RandomFileChunkRetriever(File file, long chunkLength) throws FileNotFoundException { fileReader = new RandomAccessFile(file, "r"); fileLength = file.length(); chunkCounter = 0; this.chunkLength = chunkLength; chunkSeqNumList = new ArrayList<Integer>(); for (int i = Constants.INITIAL_CHUNK_SEQ_NUM; i < Constants.INITIAL_CHUNK_SEQ_NUM + (int) Math.ceil((double) fileLength / (double) chunkLength); i++) { chunkSeqNumList.add(new Integer(i)); } Collections.shuffle(chunkSeqNumList); } @Override public boolean getNextChunk(Chunk chunk) throws IOException { if (chunk.getBytes().length != chunkLength) { throw new IllegalArgumentException("The byte array passed to this methos must have length = " + chunkLength); } int chunkSeqNum = chunkSeqNumList.get(chunkCounter++); chunk.setSeqNum(chunkSeqNum); fileReader.seek(chunkSeqNum * chunkLength); chunk.setActualChunkLength(fileReader.read(chunk.getBytes())); fileReader.seek(0); return true; } @Override public boolean hasNext() { return chunkCounter < chunkSeqNumList.size(); } @Override public long getTotalFileSize() { return this.fileLength; } }
// 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.util; import java.util.AbstractSet; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * A hashmap that maintains a count for each key. * * This implementation should change so that we extend AbstractMap, do our * own hashing, and can use our own Entry class. */ public class CountHashMap<K> extends HashMap<K, int[]> { public interface Entry<K> extends Map.Entry<K, int[]> { /** * Get the value of the entry as an int. */ public int getCount (); /** * Set the value of this entry as an int. * @return the old count */ public int setCount (int count); } /** * Increment the value associated with the specified key, return * the new value. */ public int incrementCount (K key, int amount) { int[] val = get(key); if (val == null) { put(key, val = new int[1]); } val[0] += amount; return val[0]; /* Alternate implementation, less hashing on the first increment * but more garbage created every other time. * (this whole method would be more optimal if this class were * rewritten) * int[] newVal = new int[] { amount }; int[] oldVal = put(key, newVal); if (oldVal != null) { newVal[0] += oldVal[0]; return oldVal[0]; } return 0; */ } /** * Get the count associated with the specified key. */ public int getCount (K key) { int[] val = get(key); return (val == null) ? 0 : val[0]; } /** * Set the count for the specified key. * * @return the old count. */ public int setCount (K key, int count) { int[] val = get(key); if (val == null) { put(key, new int[] { count }); return 0; // old value } int oldVal = val[0]; val[0] = count; return oldVal; } /** * Get the total count for all keys in the map. */ public int getTotalCount () { int count = 0; for (Iterator<int[]> itr = values().iterator(); itr.hasNext(); ) { count += itr.next()[0]; } return count; } /** * Compress the count map- remove entries for which the value is 0. */ public void compress () { for (Iterator<int[]> itr = values().iterator(); itr.hasNext(); ) { if (itr.next()[0] == 0) { itr.remove(); } } } @SuppressWarnings("unchecked") // documentation inherited public Set<Map.Entry<K, int[]>> entrySet () { // a giant mess of hoop-jumpery so that we can convert each Map.Entry // returned by the iterator to be a CountEntryImpl return new CountEntrySet(super.entrySet()); } protected static class CountEntryImpl<K> implements Entry<K> { public CountEntryImpl (Map.Entry<K, int[]> entry) { _entry = entry; } public boolean equals (Object o) { return _entry.equals(o); } public K getKey () { return _entry.getKey(); } public int[] getValue () { return _entry.getValue(); } public int hashCode () { return _entry.hashCode(); } public int[] setValue (int[] value) { return _entry.setValue(value); } public int getCount () { return getValue()[0]; } public int setCount (int count) { int[] val = getValue(); int oldVal = val[0]; val[0] = count; return oldVal; } protected Map.Entry<K, int[]> _entry; } protected class CountEntrySet<K> extends AbstractSet<Entry<K>> { public CountEntrySet (Set<Map.Entry<K,int[]>> superset) { _superset = superset; } public Iterator<Entry<K>> iterator () { final Iterator<Map.Entry<K, int[]>> itr = _superset.iterator(); return new Iterator<Entry<K>>() { public boolean hasNext () { return itr.hasNext(); } public Entry<K> next () { return new CountEntryImpl<K>(itr.next()); } public void remove () { itr.remove(); } }; } public boolean contains (Object o) { return _superset.contains(o); } public boolean remove (Object o) { return _superset.remove(o); } public int size () { return CountHashMap.this.size(); } public void clear () { CountHashMap.this.clear(); } protected Set<Map.Entry<K,int[]>> _superset; } }
package com.android.email.mail.transport; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.params.HttpParams; import com.android.email.mail.store.TrustManagerFactory; public class TrustedSocketFactory implements SocketFactory { private SSLSocketFactory mSocketFactory; private org.apache.http.conn.ssl.SSLSocketFactory mSchemeSocketFactory; public TrustedSocketFactory(String host, boolean secure) throws NoSuchAlgorithmException, KeyManagementException{ SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(host, secure) }, new SecureRandom()); mSocketFactory = sslContext.getSocketFactory(); mSchemeSocketFactory = org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory(); mSchemeSocketFactory.setHostnameVerifier( org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { return mSchemeSocketFactory.connectSocket(sock, host, port, localAddress, localPort, params); } public Socket createSocket() throws IOException { return mSocketFactory.createSocket(); } public boolean isSecure(Socket sock) throws IllegalArgumentException { return mSchemeSocketFactory.isSecure(sock); } }
// Inner class for a Namespace node. package org.jaxen.dom; import org.jaxen.pattern.Pattern; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Extension DOM2 node type for a Namespace Declaration. * * <p>This class implements the DOM2 {@link Node} interface to * allow Namespace declarations to be included in the result * set of an XPath selectNodes operation, even though DOM2 does * not model Namespace declarations as separate nodes.</p> * * <p>While all of the methods are implemented with reasonable * defaults, there will be some unexpected surprises, so users are * advised to test for NamespaceNodes and filter them out from the * result sets as early as possible:</p> * * <ol> * * <li>The {@link #getNodeType} method returns {@link #NAMESPACE_NODE}, * which is not one of the usual DOM2 node types. Generic code may * fall unexpectedly out of switch statements, for example.</li> * * <li>The {@link #getOwnerDocument} method returns the owner document * of the parent node, but that owner document will know nothing about * the Namespace node.</p> * * <li>The {@link #isSupported} method always returns false.</li> * * </ol> * * <p>All attempts to modify a NamespaceNode will fail with a {@link * DOMException} ({@link * DOMException#NO_MODIFICATION_ALLOWED_ERR}).</p> * * <p>This class has only protected constructors, so that it can be * instantiated only by {@link DocumentNavigator}.</p> * * @author David Megginson * @see DocumentNavigator */ public class NamespaceNode implements Node { // Constants. /** * Constant: this is a NamespaceNode. * * @see #getNodeType */ public final static short NAMESPACE_NODE = Pattern.NAMESPACE_NODE; // Protected Constructors. /** * Constructor. * * @param parent the DOM node to which the Namespace is attached * @param name the namespace prefix * @param value the Namespace URI */ public NamespaceNode (Node parent, String name, String value) { this.parent = parent; this.name = name; this.value = value; } /** * Constructor. * * @param parent the DOM node to which the Namespace is attached * @param attribute the DOM attribute object containing the * namespace declaration */ NamespaceNode (Node parent, Node attribute) { String name = attribute.getNodeName(); if (name.equals("xmlns")) { this.name = ""; } else { this.name = name.substring(6); // the part after "xmlns:" } this.parent = parent; this.value = attribute.getNodeValue(); } // Implementation of org.w3c.dom.Node. /** * Get the Namespace prefix. * * @return the Namespace prefix, or "" for the default Namespace. */ public String getNodeName () { return name; } /** * Get the Namespace URI. * * @return the Namespace URI */ public String getNodeValue () { return value; } /** * Change the Namespace URI (always fails). * * @param value the new URI * @throws DOMException always thrown */ public void setNodeValue (String value) throws DOMException { disallowModification(); } /** * Get the node type. * * @return Always {@link #NAMESPACE_NODE}. */ public short getNodeType () { return NAMESPACE_NODE; } /** * Get the parent node. * * <p>This method returns the element that was queried for Namespaces * in effect, <em>not</em> necessarily the actual element containing * the Namespace declaration.</p> * * @return the parent node (not null) */ public Node getParentNode () { return parent; } /** * Get the list of child nodes. * * @return an empty node list */ public NodeList getChildNodes () { return new EmptyNodeList(); } /** * Get the first child node. * * @return null */ public Node getFirstChild () { return null; } /** * Get the last child node. * * @return null */ public Node getLastChild () { return null; } /** * Get the previous sibling node. * * @return null */ public Node getPreviousSibling () { return null; } /** * Get the next sibling node. * * @return null */ public Node getNextSibling () { return null; } /** * Get the attribute nodes. * * @return null */ public NamedNodeMap getAttributes () { return null; } /** * Get the owner document. * * @return the owner document <em>of the parent node</em> */ public Document getOwnerDocument () { // FIXME: this could cause confusion return (parent == null ? null : parent.getOwnerDocument()); } /** * Insert a new child node (always fails). * * @throws DOMException always thrown * @see Node#insertBefore */ public Node insertBefore (Node newChild, Node refChild) throws DOMException { disallowModification(); return null; } /** * Replace a child node (always fails). * * @throws DOMException always thrown * @see Node#replaceChild */ public Node replaceChild (Node newChild, Node oldChild) throws DOMException { disallowModification(); return null; } /** * Remove a child node (always fails). * * @throws DOMException always thrown * @see Node#removeChild */ public Node removeChild (Node oldChild) throws DOMException { disallowModification(); return null; } /** * Append a new child node (always fails). * * @throws DOMException always thrown * @see Node#appendChild */ public Node appendChild (Node newChild) throws DOMException { disallowModification(); return null; } /** * Test for child nodes. * * @return false */ public boolean hasChildNodes () { return false; } /** * Create a copy of this node. * * @param deep Make a deep copy (no effect, since Namespace nodes * don't have children). * @return a new copy of this Namespace node */ public Node cloneNode (boolean deep) { return new NamespaceNode(parent, name, value); } /** * Normalize the text descendants of this node. * * <p>This method has no effect, since Namespace nodes have no * descendants.</p> */ public void normalize () { // no op } /** * Test if a DOM2 feature is supported. * * @param feature the feature name * @param version the feature version * @return false */ public boolean isSupported (String feature, String version) { return false; } /** * Get the Namespace URI for this node. * * <p>Namespace declarations are not themselves * Namespace-qualified.</p> * * @return null */ public String getNamespaceURI () { return null; } /** * Get the Namespace prefix for this node. * * <p>Namespace declarations are not themselves * Namespace-qualified.</p> * * @return null */ public String getPrefix () { return null; } /** * Change the Namespace prefix for this node (always fails). * * @param prefix the new prefix * @throws DOMException always thrown */ public void setPrefix (String prefix) throws DOMException { disallowModification(); } /** * Get the local name for this node. * * @return null */ public String getLocalName () { return name; } /** * Test if this node has attributes. * * @return false */ public boolean hasAttributes () { return false; } /** * Throw a NO_MODIFICATION_ALLOWED_ERR DOMException. * * @throws DOMException always thrown */ private void disallowModification () throws DOMException { throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "Namespace node may not be modified"); } // Override default methods from java.lang.Object. /** * Generate a hash code for a Namespace node. * * <p>The hash code is the sum of the hash codes of the parent node, * name, and value.</p> * * @return a hash code for this node */ public int hashCode () { return hashCode(parent) + hashCode(name) + hashCode(value); } /** * Test for equivalence with another object. * * <p>Two Namespace nodes are considered equivalent if their parents, * names, and values are equal.</p> * * @param o The object to test for equality. * @return true if the object is equivalent to this node, false * otherwise. */ public boolean equals (Object o) { if (o == this) return true; else if (o == null) return false; else if (o instanceof NamespaceNode) { NamespaceNode ns = (NamespaceNode)o; return (equals(parent, ns.getParentNode()) && equals(name, ns.getNodeName()) && equals(value, ns.getNodeValue())); } else { return false; } } /** * Helper method for generating a hash code. * * @param o the object for generating a hash code (possibly null) * @return the object's hash code, or 0 if the object is null * @see java.lang.Object#hashCode */ private int hashCode (Object o) { return (o == null ? 0 : o.hashCode()); } /** * Helper method for comparing two objects. * * @param a the first object to compare (possibly null) * @param b the second object to compare (possibly null) * @return true if the objects are equivalent or are both null * @see java.lang.Object#equals */ private boolean equals (Object a, Object b) { return ((a == null && b == null) || (a != null && a.equals(b))); } // Internal state. private Node parent; private String name; private String value; // Inner class: empty node list. /** * A node list with no members. * * <p>This class is necessary for the {@link Node#getChildNodes} * method, which must return an empty node list rather than * null when there are no children.</p> */ class EmptyNodeList implements NodeList { /** * @see NodeList#getLength */ public int getLength () { return 0; } /** * @see NodeList#item */ public Node item(int index) { return null; } } } // end of Namespace.java
package com.ecyrd.jspwiki.providers; import java.util.Properties; import java.util.Collection; import java.util.Date; import java.util.ArrayList; import java.util.List; import java.util.Iterator; import java.io.IOException; import java.io.InputStream; import org.apache.log4j.Logger; import com.opensymphony.module.oscache.base.Cache; import com.opensymphony.module.oscache.base.NeedsRefreshException; import com.ecyrd.jspwiki.*; import com.ecyrd.jspwiki.util.ClassUtil; import com.ecyrd.jspwiki.attachment.Attachment; import com.ecyrd.jspwiki.attachment.AttachmentManager; /** * Provides a caching attachment provider. This class rests on top of a * real provider class and provides a cache to speed things up. Only the * Attachment objects are cached; the actual attachment contents are * fetched always from the provider. * * @author Janne Jalkanen * @since 2.1.64. */ // FIXME: Do we need to clear the cache entry if we get an NRE and the attachment is not there? // FIXME: We probably clear the cache a bit too aggressively in places. // FIXME: Does not yet react well to external cache changes. Should really use custom // EntryRefreshPolicy for that. public class CachingAttachmentProvider implements WikiAttachmentProvider { private static final Logger log = Logger.getLogger(CachingAttachmentProvider.class); private WikiAttachmentProvider m_provider; /** * The cache contains Collection objects which contain Attachment objects. * The key is the parent wiki page name (String). */ private Cache m_cache; private long m_cacheMisses = 0; private long m_cacheHits = 0; private boolean m_gotall = false; // FIXME: Make settable. private int m_refreshPeriod = 60*10; // 10 minutes at the moment public void initialize( WikiEngine engine, Properties properties ) throws NoRequiredPropertyException, IOException { log.debug("Initing CachingAttachmentProvider"); // Construct an unlimited cache. m_cache = new Cache( true, false ); // Find and initialize real provider. String classname = WikiEngine.getRequiredProperty( properties, AttachmentManager.PROP_PROVIDER ); try { Class providerclass = ClassUtil.findClass( "com.ecyrd.jspwiki.providers", classname ); m_provider = (WikiAttachmentProvider)providerclass.newInstance(); log.debug("Initializing real provider class "+m_provider); m_provider.initialize( engine, properties ); } catch( ClassNotFoundException e ) { log.error("Unable to locate provider class "+classname,e); throw new IllegalArgumentException("no provider class"); } catch( InstantiationException e ) { log.error("Unable to create provider class "+classname,e); throw new IllegalArgumentException("faulty provider class"); } catch( IllegalAccessException e ) { log.error("Illegal access to provider class "+classname,e); throw new IllegalArgumentException("illegal provider class"); } } public void putAttachmentData( Attachment att, InputStream data ) throws ProviderException, IOException { m_provider.putAttachmentData( att, data ); m_cache.flushEntry( att.getParentName() ); } public InputStream getAttachmentData( Attachment att ) throws ProviderException, IOException { return m_provider.getAttachmentData( att ); } public Collection listAttachments( WikiPage page ) throws ProviderException { log.debug("Listing attachments for "+page); try { Collection c = (Collection)m_cache.getFromCache( page.getName(), m_refreshPeriod ); if( c != null ) { log.debug("LIST from cache, "+page.getName()+", size="+c.size()); m_cacheHits++; return c; } log.debug("list NOT in cache, "+page.getName()); c = refresh( page ); } catch( NeedsRefreshException nre ) { try { Collection c = refresh( page ); return c; } catch( ProviderException ex ) { log.warn("Provider failed, returning cached content"); return (Collection)nre.getCacheContent(); } } return new ArrayList(); } public Collection findAttachments( QueryItem[] query ) { return m_provider.findAttachments( query ); } public List listAllChanged( Date timestamp ) throws ProviderException { // FIXME: Should cache return m_provider.listAllChanged( timestamp ); } /** * Simply goes through the collection and attempts to locate the * given attachment of that name. * * @return null, if no such attachment was in this collection. */ private Attachment findAttachmentFromCollection( Collection c, String name ) { for( Iterator i = c.iterator(); i.hasNext(); ) { Attachment att = (Attachment) i.next(); if( name.equals( att.getFileName() ) ) { return att; } } return null; } /** * Refreshes the cache content and updates counters. * * @return The newly fetched object from the provider. */ private final Collection refresh( WikiPage page ) throws ProviderException { m_cacheMisses++; Collection c = m_provider.listAttachments( page ); m_cache.putInCache( page.getName(), c ); return c; } public Attachment getAttachmentInfo( WikiPage page, String name, int version ) throws ProviderException { if( log.isDebugEnabled() ) { log.debug("Getting attachments for "+page+", name="+name+", version="+version); } // We don't cache previous versions if( version != WikiProvider.LATEST_VERSION ) { log.debug("...we don't cache old versions"); return m_provider.getAttachmentInfo( page, name, version ); } try { Collection c = (Collection)m_cache.getFromCache( page.getName(), m_refreshPeriod ); if( c == null ) { log.debug("...wasn't in the cache"); c = refresh( page ); if( c == null ) return null; // No such attachment } else { log.debug("...FOUND in the cache"); m_cacheHits++; } return findAttachmentFromCollection( c, name ); } catch( NeedsRefreshException nre ) { log.debug("...needs refresh"); Collection c = null; try { c = refresh( page ); } catch( ProviderException ex ) { log.warn("Provider failed, returning cached content"); c = (Collection)nre.getCacheContent(); } if( c != null ) { return findAttachmentFromCollection( c, name ); } } return null; } /** * Returns version history. Each element should be * an Attachment. */ public List getVersionHistory( Attachment att ) { return m_provider.getVersionHistory( att ); } public void deleteVersion( Attachment att ) throws ProviderException { // This isn't strictly speaking correct, but it does not really matter m_cache.putInCache( att.getParentName(), null ); m_provider.deleteVersion( att ); } public void deleteAttachment( Attachment att ) throws ProviderException { m_cache.putInCache( att.getParentName(), null ); m_provider.deleteAttachment( att ); } public synchronized String getProviderInfo() { int cachedPages = 0; long totalSize = 0; return("Real provider: "+m_provider.getClass().getName()+ "<br />Cache misses: "+m_cacheMisses+ "<br />Cache hits: "+m_cacheHits); } public WikiAttachmentProvider getRealProvider() { return m_provider; } }
package org.concord.otrunk.view; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Toolkit; import java.awt.event.AWTEventListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Hashtable; import java.util.Vector; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.WindowConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.TreePath; import org.concord.applesupport.AppleApplicationAdapter; import org.concord.applesupport.AppleApplicationUtil; import org.concord.framework.otrunk.OTChangeEvent; import org.concord.framework.otrunk.OTChangeListener; import org.concord.framework.otrunk.OTID; import org.concord.framework.otrunk.OTObject; import org.concord.framework.otrunk.OTObjectList; import org.concord.framework.otrunk.OTrunk; import org.concord.framework.otrunk.view.OTExternalAppService; import org.concord.framework.otrunk.view.OTFrameManager; import org.concord.framework.otrunk.view.OTJComponentServiceFactory; import org.concord.framework.otrunk.view.OTUserListService; import org.concord.framework.otrunk.view.OTViewContainer; import org.concord.framework.otrunk.view.OTViewContainerChangeEvent; import org.concord.framework.otrunk.view.OTViewContainerListener; import org.concord.framework.otrunk.view.OTViewContext; import org.concord.framework.otrunk.view.OTViewFactory; import org.concord.framework.text.UserMessageHandler; import org.concord.framework.util.SimpleTreeNode; import org.concord.otrunk.OTMLToXHTMLConverter; import org.concord.otrunk.OTSystem; import org.concord.otrunk.OTrunkImpl; import org.concord.otrunk.OTrunkServiceEntry; import org.concord.otrunk.datamodel.OTDataObject; import org.concord.otrunk.overlay.OTOverlayGroup; import org.concord.otrunk.user.OTUserObject; import org.concord.otrunk.xml.ExporterJDOM; import org.concord.otrunk.xml.XMLDatabase; import org.concord.otrunk.xml.XMLDatabaseChangeEvent; import org.concord.otrunk.xml.XMLDatabaseChangeListener; import org.concord.swing.CustomDialog; import org.concord.swing.MemoryMonitorPanel; import org.concord.swing.MostRecentFileDialog; import org.concord.swing.StreamRecord; import org.concord.swing.StreamRecordView; import org.concord.swing.util.Util; import org.concord.view.SimpleTreeModel; import org.concord.view.SwingUserMessageHandler; /** * OTViewer Class name and description * * Date created: Dec 14, 2004 * * @author scott * */ public class OTViewer extends JFrame implements TreeSelectionListener, OTViewContainerListener, AppleApplicationAdapter { /** * first version of this class */ private static final long serialVersionUID = 1L; public final static String TITLE_PROP = "otrunk.view.frame_title"; public final static String HIDE_TREE_PROP = "otrunk.view.hide_tree"; public final static String SHOW_CONSOLE_PROP = "otrunk.view.show_console"; public final static String DEMO_ONLY_PROP = "otrunk.view.demo"; public final static String OTML_URL_PROP = "otrunk.otmlurl"; public final static String HTTP_PUT = "PUT"; public final static String HTTP_POST = "POST"; final static String DEFAULT_BASE_FRAME_TITLE = "OTrunk Viewer"; private static OTViewFactory otViewFactory; OTFrameManagerImpl frameManager; JSplitPane splitPane; OTViewContainerPanel bodyPanel; SimpleTreeModel folderTreeModel; SimpleTreeModel dataTreeModel; JTree folderTreeArea; JTree dataTreeArea; /** * Dialog used for instruction panel that shows when the program starts * Prompts "new" or "open" portfolio */ private JDialog commDialog; JFrame consoleFrame; JMenuBar menuBar; private JPanel statusPanel; String baseFrameTitle; String startupMessage = ""; //FIXME Is it being used at all? Hashtable otContainers = new Hashtable(); //FIXME Is it being used at all? boolean showTree = false; private boolean useScrollPane; boolean justStarted = false; protected int userMode = OTConfig.NO_USER_MODE; File currentAuthoredFile = null; URL currentURL = null; URL remoteURL; OTUserSession userSession; private static OTrunkImpl otrunk; XMLDatabase xmlDB; private OTSystem userSystem; private ArrayList services = new ArrayList(); private OTChangeListener systemChangeListener; /** * This is true if the user was asked about saving user data after they * initiated a close of the current view. */ private boolean askedAboutSavingUserData = false; /** * This is true if the user was asked about saving the user data, and said * yes */ private boolean needToSaveUserData = false; /** * This is true if the SailOTViewer created this OTViewer */ private boolean launchedBySailOTViewer = false; private boolean sailSaveEnabled = true; // Temp, to close the window AbstractAction exitAction; AbstractAction saveAsAction; private AbstractAction saveUserDataAsAction; private AbstractAction saveUserDataAction; private AbstractAction debugAction; private AbstractAction showConsoleAction; private AbstractAction newUserDataAction; private AbstractAction loadUserDataAction; private AbstractAction loadAction; private AbstractAction reloadWindowAction; private AbstractAction saveAction; private AbstractAction saveRemoteAsAction; private AbstractAction exportImageAction; private AbstractAction exportHiResImageAction; private AbstractAction exportToHtmlAction; public static void setOTViewFactory(OTViewFactory factory) { otViewFactory = factory; } public OTViewer() { super(); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.out.println("Error setting native LAF: " + e); } this.showTree = true; AppleApplicationUtil.registerWithMacOSX(this); baseFrameTitle = DEFAULT_BASE_FRAME_TITLE; try { // this overrides the default base frame title String title = System.getProperty(TITLE_PROP, null); if (title != null) { baseFrameTitle = title; } } catch (Throwable t) { // do nothing, just use the default title } setTitle(baseFrameTitle); // If "otrunk.view.demo" is true, closing frame will just dispose // the frame, not exit. if (!Boolean.getBoolean(DEMO_ONLY_PROP)){ setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { exitAction.actionPerformed(null); } }); } consoleFrame = new JFrame("Console"); StreamRecord record = new StreamRecord(50000); StreamRecordView view = new StreamRecordView(record); consoleFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); System.setOut((PrintStream) view.addOutputStream(System.out, "Console")); System.setErr((PrintStream) view.addOutputStream(System.err, System.out)); consoleFrame.getContentPane().add(view); consoleFrame.setSize(800, 600); if (OTConfig.getBooleanProp(SHOW_CONSOLE_PROP, false)) { consoleFrame.setVisible(true); } commDialog = new JDialog(this, true); // for debugging // add a breakpoint below, run in debugging mode, and then hit Meta-B // the object you're currently focused on will be passed in here and you // can // start exploring the data structures, etc. KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); KeyEventDispatcher deleteDispatcher = new KeyEventDispatcher(){ public boolean dispatchKeyEvent(KeyEvent e) { if ((e.getID() == java.awt.event.KeyEvent.KEY_RELEASED) && ((e.getModifiersEx() & java.awt.event.InputEvent.META_DOWN_MASK) != 0) && (e.getKeyCode() == java.awt.event.KeyEvent.VK_B)) { Object o = e.getSource(); System.out.println(o.toString()); return true; } return false; } }; focusManager.addKeyEventDispatcher(deleteDispatcher); // If the mouse click is a right click event and alt is pressed // or on a Mac the ctrl and option keys are down // then this code will print out the toString method of the // object which the mouse is over to the console. AWTEventListener awtEventListener = new AWTEventListener(){ public void eventDispatched(AWTEvent event) { if(!(event instanceof MouseEvent)){ return; } MouseEvent mEvent = (MouseEvent) event; if (mEvent.getID() == MouseEvent.MOUSE_CLICKED && (mEvent.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) != 0) { System.out.println(event.getSource().toString()); } } }; Toolkit.getDefaultToolkit().addAWTEventListener(awtEventListener, AWTEvent.MOUSE_EVENT_MASK); } /** * this needs to be called before initialized. * * @param serviceInterface * @param service */ public void addService(Class serviceInterface, Object service) { OTrunkServiceEntry entry = new OTrunkServiceEntry(service, serviceInterface); services.add(entry); } public void setUserMode(int mode) { userMode = mode; } public int getUserMode() { return userMode; } public void updateTreePane() { Dimension minimumSize = new Dimension(100, 50); folderTreeArea = new JTree(folderTreeModel); // we are just disabling this however if we want to // use this tree for authoring, or for managing student // created objects this will need to be some form of option folderTreeArea.setEditable(false); folderTreeArea.addTreeSelectionListener(this); JComponent leftComponent = null; JScrollPane folderTreeScrollPane = new JScrollPane(folderTreeArea); if (System.getProperty(OTConfig.DEBUG_PROP, "").equals("true")) { // ViewFactory.getComponent(root); dataTreeArea = new JTree(dataTreeModel); dataTreeArea.setEditable(false); dataTreeArea.addTreeSelectionListener(this); JScrollPane dataTreeScrollPane = new JScrollPane(dataTreeArea); JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.add("Folders", folderTreeScrollPane); tabbedPane.add("Resources", dataTreeScrollPane); // Provide minimum sizes for the two components in the split pane folderTreeScrollPane.setMinimumSize(minimumSize); dataTreeScrollPane.setMinimumSize(minimumSize); tabbedPane.setMinimumSize(minimumSize); leftComponent = tabbedPane; } else { leftComponent = folderTreeScrollPane; } if (splitPane == null) { splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, bodyPanel); } else { splitPane.setLeftComponent(leftComponent); } splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(200); } public void initArgs(String[] args) { URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args); if (authorOTMLURL == null && System.getProperty(OTML_URL_PROP, null) != null) { try { authorOTMLURL = new URL(System.getProperty(OTML_URL_PROP, null)); } catch (MalformedURLException e) { e.printStackTrace(); } } if (authorOTMLURL == null) { authorOTMLURL = OTViewer.class.getResource("no-arguments-page.otml"); } if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) { currentAuthoredFile = new File(authorOTMLURL.getPath()); } String urlStr = authorOTMLURL.toString(); initWithWizard(urlStr); } /** * @param args * @return */ public String getURL(String[] args) { URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args); if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) { try { URI authorOTMLURI = new URI(authorOTMLURL.toString()); currentAuthoredFile = new File(authorOTMLURI); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return authorOTMLURL.toString(); } public void init(String url) { updateRemoteURL(url); createActions(); updateMenuBar(); setJMenuBar(menuBar); frameManager = new OTFrameManagerImpl(); bodyPanel = new OTViewContainerPanel(frameManager); bodyPanel.addViewContainerListener(this); if (showTree) { dataTreeModel = new SimpleTreeModel(); folderTreeModel = new SimpleTreeModel(); updateTreePane(); getContentPane().add(splitPane); } else { getContentPane().add(bodyPanel); } if (OTConfig.isShowStatus() || (getUserMode() == OTConfig.SINGLE_USER_MODE && ! isSailSaveEnabled())) { statusPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 3, 1)); if (OTConfig.isShowStatus()) { final JLabel saveStateLabel = new JLabel("File saved"); statusPanel.add(saveStateLabel); statusPanel.add(Box.createHorizontalStrut(20)); statusPanel.add(new MemoryMonitorPanel()); statusPanel.add(Box.createHorizontalStrut(5)); // It takes a while for xmlDM to be initialized... Thread waitForDB = new Thread() { public void run() { while (xmlDB == null) { try { sleep(1000); } catch (Exception e) { } } xmlDB.addXMLDatabaseChangeListener(new XMLDatabaseChangeListener() { public void stateChanged(XMLDatabaseChangeEvent e) { if (xmlDB.isDirty()) { saveStateLabel.setText("Unsaved changes"); } else { saveStateLabel.setText("File saved"); } statusPanel.repaint(); } }); } }; waitForDB.start(); } if (getUserMode() == OTConfig.SINGLE_USER_MODE && ! isSailSaveEnabled()) { JLabel readOnlyLabel = new JLabel("User Data Will Not Be Saved!"); statusPanel.setBackground(Color.RED); statusPanel.add(readOnlyLabel); statusPanel.add(Box.createHorizontalStrut(5)); } getContentPane().add(statusPanel, BorderLayout.SOUTH); } SwingUtilities.invokeLater(new Runnable() { public void run() { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); if (screenSize.width < 1000 || screenSize.height < 700) { setVisible(true); int state = getExtendedState(); // Set the maximized bits state |= Frame.MAXIMIZED_BOTH; // Maximize the frame setExtendedState(state); } else { int cornerX = 50; int cornerY = 50; int sizeX = 800; int sizeY = 500; // OTViewService viewService = otViewFactory. setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY); setVisible(true); } } }); if (url == null) { return; } try { initializeURL(new URL(url)); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (Exception e) { // FIXME: this should popup a dialog System.err.println("Can't load url"); e.printStackTrace(); return; } } public void initializeURL(URL url) throws Exception { loadURL(url); OTMainFrame mainFrame = (OTMainFrame) otrunk.getService(OTMainFrame.class); if (OTConfig.getBooleanProp(HIDE_TREE_PROP, false) || !mainFrame.getShowLeftPanel()) { splitPane.getLeftComponent().setVisible(false); } useScrollPane = true; if (mainFrame.getFrame() != null) { if (mainFrame.getFrame().isResourceSet("width") && mainFrame.getFrame().isResourceSet("height")) { int cornerX = mainFrame.getFrame().getPositionX(); int cornerY = mainFrame.getFrame().getPositionY(); int sizeX = mainFrame.getFrame().getWidth(); int sizeY = mainFrame.getFrame().getHeight(); // See if title is set for main frame (only if name is // still default, so that jnlp prop will still // overrides this) if (baseFrameTitle == DEFAULT_BASE_FRAME_TITLE && mainFrame.getFrame().isResourceSet("title")){ System.out.println("change"); baseFrameTitle = mainFrame.getFrame().getTitle(); setTitle(baseFrameTitle); } setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY); repaint(); } useScrollPane = mainFrame.getFrame().getUseScrollPane(); } bodyPanel.setUseScrollPane(useScrollPane); setupBodyPanel(); } public void initWithWizard(String url) { justStarted = true; init(url); if (userMode == OTConfig.SINGLE_USER_MODE) { SwingUtilities.invokeLater(new Runnable() { public void run() { instructionPanel(); } }); } } public void loadUserDataFile(File file) { try { OTMLUserSession xmlUserSession = new OTMLUserSession(file, null); loadUserSession(xmlUserSession); } catch (Exception e) { e.printStackTrace(); } } /** * This method just sets the viewers userSession without loading it. * This is useful if a user needs to select the data they want to use * when the load method is called. Currently this is used by the "wizard" in * the ot viewer. * * @param userSession */ public void setUserSession(OTUserSession userSession) { this.userSession = userSession; userSession.setOTrunk(otrunk); } /** * This method loads in a user session, and reloads the window. * * @param userSession * @throws Exception */ public void loadUserSession(OTUserSession userSession) throws Exception { this.userSession = userSession; otrunk.registerUserSession(userSession); reloadWindow(); } public void updateOverlayGroupListeners() { OTObjectList overlays = userSystem.getOverlays(); for(int i=0; i<overlays.size(); i++){ OTObject item = overlays.get(i); if(item instanceof OTOverlayGroup){ ((OTOverlayGroup) item).addOTChangeListener(systemChangeListener); } } } public void reloadOverlays() { try { otrunk.reloadOverlays(userSession); updateOverlayGroupListeners(); reloadWindow(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void loadFile(File file) { currentAuthoredFile = file; try { initializeURL(currentAuthoredFile.toURL()); } catch (Exception e) { e.printStackTrace(); } } public void loadURL(URL url) throws Exception { XMLDatabase systemDB = null; try { // try loading in the system object if there is one String systemOtmlUrlStr = OTConfig.getStringProp(OTConfig.SYSTEM_OTML_PROP); if(systemOtmlUrlStr != null){ URL systemOtmlUrl = new URL(systemOtmlUrlStr); systemDB = new XMLDatabase(systemOtmlUrl, System.out); // don't track the resource info on the system db. systemDB.loadObjects(); } } catch (Exception e){ e.printStackTrace(); systemDB = null; } try { xmlDB = new XMLDatabase(url, System.out); // Only track the resource info when there isn't a user. Currently // all classroom uses // of OTViewer has NO_USER_MODE turned off, so using this setting // safe to test // the resource tracking without affecting real users. if (userMode == OTConfig.NO_USER_MODE) { xmlDB.setTrackResourceInfo(true); } xmlDB.loadObjects(); } catch (org.jdom.input.JDOMParseException e) { String xmlWarningTitle = "XML Decoding error"; String xmlWarningMessage = "There appears to a problem parsing the XML of this document. \n" + "Please show this error message to one of the workshop leaders. \n\n" + e.getMessage(); JOptionPane.showMessageDialog(null, xmlWarningMessage, xmlWarningTitle, JOptionPane.ERROR_MESSAGE); throw e; } addService(UserMessageHandler.class, new SwingUserMessageHandler(this)); otrunk = new OTrunkImpl(systemDB, xmlDB, services); OTViewFactory myViewFactory = (OTViewFactory) otrunk.getService(OTViewFactory.class); if (myViewFactory != null) { otViewFactory = myViewFactory; } OTViewContext factoryContext = otViewFactory.getViewContext(); factoryContext.addViewService(OTrunk.class, otrunk); factoryContext.addViewService(OTFrameManager.class, frameManager); factoryContext.addViewService(OTJComponentServiceFactory.class, new OTJComponentServiceFactoryImpl()); factoryContext.addViewService(OTExternalAppService.class, new OTExternalAppServiceImpl()); factoryContext.addViewService(OTUserListService.class, new OTUserListService() { public Vector getUserList() { return otrunk.getUsers(); } }); currentURL = url; } // This method was refactored out of loadURL private void setupBodyPanel() throws Exception { bodyPanel.setTopLevelContainer(true); bodyPanel.setOTViewFactory(otViewFactory); // set the current mode from the viewservice to the main bodyPanel // bodyPanel.setViewMode(otViewFactory.getDefaultMode()); // set the viewFactory of the frame manager frameManager.setViewFactory(otViewFactory); xmlDB.setDirty(false); reloadWindow(); } public OTObject getAuthoredRoot() throws Exception { String rootLocalId = OTConfig.getStringProp(OTConfig.ROOT_OBJECT_PROP); if(rootLocalId != null){ OTID rootID = xmlDB.getOTIDFromLocalID(rootLocalId); return otrunk.getOTObject(rootID); } return otrunk.getRoot(); } public OTObject getRoot() throws Exception { switch (userMode) { case OTConfig.NO_USER_MODE: return getAuthoredRoot(); case OTConfig.SINGLE_USER_MODE: if (userSession == null) { return null; } OTObject otRoot = getAuthoredRoot(); return otrunk.getUserRuntimeObject(otRoot, getCurrentUser()); } return null; } public void reloadWindow() throws Exception { OTObject root = getRoot(); boolean overrideShowTree = false; if (userMode == OTConfig.SINGLE_USER_MODE) { if (root == null) { // FIXME This is an error // the newAnonUserData should have been called before this // method is // called // no user file has been started yet overrideShowTree = true; } else { OTObject realRoot = otrunk.getRealRoot(); if (realRoot instanceof OTSystem) { OTSystem localUserSystem = (OTSystem) otrunk.getUserRuntimeObject(realRoot, getCurrentUser()); // FIXME there should be a better way than this because we // have to handle // multiple users. if (localUserSystem != userSystem) { userSystem = localUserSystem; systemChangeListener = new OTChangeListener() { public void stateChanged(OTChangeEvent e) { if ("overlays".equals(e.getProperty())) { reloadOverlays(); } } }; updateOverlayGroupListeners(); userSystem.addOTChangeListener(systemChangeListener); } } } } if (showTree && !overrideShowTree) { OTDataObject rootDataObject = xmlDB.getRoot(); dataTreeModel.setRoot(new OTDataObjectNode("root", rootDataObject, otrunk)); folderTreeModel.setRoot(new OTFolderNode(root)); } bodyPanel.setCurrentObject(root); if (showTree && !overrideShowTree) { folderTreeModel.fireTreeStructureChanged(new TreePath( (SimpleTreeNode) folderTreeModel.getRoot())); dataTreeModel.fireTreeStructureChanged(new TreePath( (SimpleTreeNode) dataTreeModel.getRoot())); } Frame frame = (Frame) SwingUtilities.getRoot(this); switch (userMode) { case OTConfig.NO_USER_MODE: if (remoteURL != null) { frame.setTitle(baseFrameTitle + ": " + remoteURL.toString()); } else { frame.setTitle(baseFrameTitle + ": " + currentURL.toString()); } break; case OTConfig.SINGLE_USER_MODE: String userSessionLabel = null; if (userSession != null) { userSessionLabel = userSession.getLabel(); } if(userSessionLabel != null){ frame.setTitle(baseFrameTitle + ": " + userSessionLabel); } else { frame.setTitle(baseFrameTitle); } break; } if(userSession == null){ saveUserDataAction.setEnabled(false); saveUserDataAsAction.setEnabled(false); } else { saveUserDataAction.setEnabled(userSession.allowSave()); saveUserDataAsAction.setEnabled(userSession.allowSaveAs()); } } public void reload() throws Exception { initializeURL(currentURL); } public OTUserSession getUserSession() { return userSession; } public OTUserObject getCurrentUser() { if(userSession == null){ return null; } return userSession.getUserObject(); } public static void main(String[] args) { System.setProperty("apple.laf.useScreenMenuBar", "true"); OTViewer viewer = new OTViewer(); if (OTConfig.getBooleanProp(OTConfig.SINGLE_USER_PROP, false)) { viewer.setUserMode(OTConfig.SINGLE_USER_MODE); } else if (OTConfig.getBooleanProp(OTConfig.NO_USER_PROP, false)) { viewer.setUserMode(OTConfig.NO_USER_MODE); } viewer.initArgs(args); } class ExitAction extends AbstractAction { /** * nothing to serialize here. */ private static final long serialVersionUID = 1L; public ExitAction() { super("Exit"); } public void actionPerformed(ActionEvent e) { // If this suceeds then the VM will exit so // the window will get disposed exit(); } } /* * (non-Javadoc) * * @see org.concord.otrunk.view.OTViewContainerListener#currentObjectChanged(org.concord.framework.otrunk.view.OTViewContainer) */ public void currentObjectChanged(OTViewContainerChangeEvent evt) { final OTViewContainer myContainer = (OTViewContainer) evt.getSource(); // TODO Auto-generated method stub SwingUtilities.invokeLater(new Runnable() { public void run() { OTObject currentObject = myContainer.getCurrentObject(); if (folderTreeArea != null) { OTFolderNode node = (OTFolderNode) folderTreeArea.getLastSelectedPathComponent(); if (node == null) return; if (node.getPfObject() != currentObject) { folderTreeArea.setSelectionPath(null); } } } }); } /* * (non-Javadoc) * * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent) */ public void valueChanged(TreeSelectionEvent event) { if (event.getSource() == folderTreeArea) { OTFolderNode node = (OTFolderNode) folderTreeArea.getLastSelectedPathComponent(); if (node == null) return; OTObject pfObject = node.getPfObject(); bodyPanel.setCurrentObject(pfObject); if (splitPane.getRightComponent() != bodyPanel) { splitPane.setRightComponent(bodyPanel); } } else if (event.getSource() == dataTreeArea) { SimpleTreeNode node = (SimpleTreeNode) dataTreeArea.getLastSelectedPathComponent(); Object resourceValue = null; if (node != null) { resourceValue = node.getObject(); if (resourceValue == null) { resourceValue = "null resource value"; } } else { resourceValue = "no selected data object"; } JComponent nodeView = null; if (resourceValue instanceof OTDataObject) { nodeView = new OTDataObjectView((OTDataObject) resourceValue); } else { nodeView = new JTextArea(resourceValue.toString()); } JScrollPane scrollPane = new JScrollPane(nodeView); splitPane.setRightComponent(scrollPane); } } private void updateRemoteURL(String defaultURL) { String remote = System.getProperty(OTConfig.REMOTE_URL_PROP, null); try { if (remote == null) { if (defaultURL != null && defaultURL.startsWith("http:")) { remoteURL = new URL(defaultURL); } } else { remoteURL = new URL(remote); } } catch (Exception e) { remoteURL = null; System.err.println("Remote URL is invalid."); e.printStackTrace(); } } public void createActions() { newUserDataAction = new AbstractAction("New") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { createNewUser(); } }; loadUserDataAction = new AbstractAction("Open...") { /** * nothing to serialize here. Just the parent class. */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { openUserData(true); } }; exportToHtmlAction = new AbstractAction("Export to html...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent arg0) { File fileToSave = getReportFile(); OTMLToXHTMLConverter otxc = new OTMLToXHTMLConverter(otViewFactory, bodyPanel.getViewContainer()); otxc.setXHTMLParams(fileToSave, 800, 600); (new Thread(otxc)).start(); } }; // Isn't it enabled by default? exportToHtmlAction.setEnabled(true); saveUserDataAction = new AbstractAction("Save") { /** * Nothing to serialize here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { userSession.save(); // the save operation might change the label used by the session setTitle(baseFrameTitle + ": " + userSession.getLabel()); } }; saveUserDataAsAction = new AbstractAction("Save As...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { if(userSession instanceof OTMLUserSession){ ((OTMLUserSession)userSession).setDialogParent(SwingUtilities.getRoot(OTViewer.this)); } userSession.saveAs(); } }; loadAction = new AbstractAction("Open Authored Content...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.openotml"); mrfd.setFilenameFilter("otml"); int retval = mrfd.showOpenDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); } if (file != null && file.exists()) { System.out.println("load file name: " + file); // if they open an authored file then they are overriding // the remoteURL, // at least for now. This makes the title bar update // correctly, and // fixes a lockup that happens when they have opened a local // file and then // try to save it again. remoteURL = null; loadFile(file); exportToHtmlAction.setEnabled(true); } } }; loadAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); saveAction = new AbstractAction("Save Authored Content...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { if (OTConfig.isRemoteSaveData() && remoteURL != null) { try { if (OTConfig.isRestEnabled()) { try { otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_PUT); setTitle(remoteURL.toString()); } catch (Exception e) { otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_POST); setTitle(remoteURL.toString()); } } else { otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_POST); setTitle(remoteURL.toString()); } } catch (Exception e) { JOptionPane.showMessageDialog( (Frame) SwingUtilities.getRoot(OTViewer.this), "There was an error saving. Check your URL and try again.", "Error Saving", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } else { if (currentAuthoredFile == null) { saveAsAction.actionPerformed(arg0); return; } if (checkForReplace(currentAuthoredFile)) { try { ExporterJDOM.export(currentAuthoredFile, xmlDB.getRoot(), xmlDB); xmlDB.setDirty(false); } catch (Exception e) { e.printStackTrace(); } } } // end if (remoteUrl == null) } }; saveAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); saveAsAction = new AbstractAction("Save Authored Content As...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.saveotml"); mrfd.setFilenameFilter("otml"); if (currentAuthoredFile != null) { mrfd.setCurrentDirectory(currentAuthoredFile.getParentFile()); mrfd.setSelectedFile(currentAuthoredFile); } int retval = mrfd.showSaveDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); String fileName = file.getPath(); if (!fileName.toLowerCase().endsWith(".otml")) { file = new File(file.getAbsolutePath() + ".otml"); } if (checkForReplace(file)) { try { ExporterJDOM.export(file, xmlDB.getRoot(), xmlDB); currentAuthoredFile = file; currentURL = file.toURL(); xmlDB.setDirty(false); } catch (Exception e) { e.printStackTrace(); } } frame.setTitle(fileName); remoteURL = null; updateMenuBar(); } } }; saveRemoteAsAction = new AbstractAction("Save Remotely As...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { // Pop up a dialog asking for a URL // Post the otml to the url JPanel panel = new JPanel(); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); panel.setLayout(new BorderLayout()); JLabel prompt = new JLabel("Please enter the URL to which you would like to save:"); prompt.setBorder(new EmptyBorder(0, 0, 10, 0)); JTextField textField = new JTextField(); if (remoteURL == null) { textField.setText("http: } else { textField.setText(remoteURL.toString()); } JPanel checkboxPanel = new JPanel(); JCheckBox restCheckbox = new JCheckBox("REST Enabled?"); restCheckbox.setSelected(OTConfig.isRestEnabled()); checkboxPanel.setBorder(new EmptyBorder(5, 5, 0, 0)); checkboxPanel.add(restCheckbox); panel.add(prompt, BorderLayout.NORTH); panel.add(textField, BorderLayout.CENTER); panel.add(checkboxPanel, BorderLayout.SOUTH); int returnVal = CustomDialog.showOKCancelDialog( (Frame) SwingUtilities.getRoot(OTViewer.this), // parent panel, // custom content "Save URL", // title false, // resizeable true // modal ); if (returnVal == 0) { try { remoteURL = new URL(textField.getText()); // WARNING this will cause a security exception if we // are running in a applet or jnlp which // has a security sandbox. System.setProperty(OTConfig.REST_ENABLED_PROP, Boolean.toString(restCheckbox.isSelected())); otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_POST); setTitle(remoteURL.toString()); updateMenuBar(); } catch (Exception e) { System.err.println("Bad URL. Not saving."); JOptionPane.showMessageDialog( (Frame) SwingUtilities.getRoot(OTViewer.this), "There was an error saving. Check your URL and try again.", "Error Saving", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } else { // CANCELLED } } }; exportImageAction = new AbstractAction("Export Image...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { // this introduces a dependency on concord Swing project // instead there needs to be a way to added these actions // through // the xml Component currentComp = bodyPanel.getCurrentComponent(); Util.makeScreenShot(currentComp); } }; exportHiResImageAction = new AbstractAction("Export Hi Res Image...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { Component currentComp = bodyPanel.getCurrentComponent(); Util.makeScreenShot(currentComp, 2, 2); } }; debugAction = new AbstractAction("Debug Mode") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (((JCheckBoxMenuItem) source).isSelected()) { System.setProperty(OTConfig.DEBUG_PROP, "true"); } else { System.setProperty(OTConfig.DEBUG_PROP, "false"); } try { reloadWindow(); } catch (Exception exp) { exp.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { public void run() { updateMenuBar(); } }); exportToHtmlAction.setEnabled(true); } }; showConsoleAction = new AbstractAction("Show Console") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { if (consoleFrame != null) { consoleFrame.setVisible(true); } } }; reloadWindowAction = new AbstractAction("Reload window") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { reload(); } catch (Exception e1) { e1.printStackTrace(); } } }; reloadWindowAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); exitAction = new ExitAction(); } /** * @return Returns the menuBar. */ public JMenuBar updateMenuBar() { JMenu fileMenu = null; if (menuBar == null) { menuBar = new JMenuBar(); fileMenu = new JMenu("File"); menuBar.add(fileMenu); } else { fileMenu = menuBar.getMenu(0); fileMenu.removeAll(); } if (OTConfig.isAuthorMode()) { userMode = OTConfig.NO_USER_MODE; } if (userMode == OTConfig.SINGLE_USER_MODE) { fileMenu.setEnabled(!justStarted); // we add new and load ("open") menu items only if this is NOT launched // by sail or if otrunk.view.destructive_menu is set to true if (!isLaunchedBySailOTViewer() || (OTConfig.isShowDestructiveMenuItems())){ fileMenu.add(newUserDataAction); fileMenu.add(loadUserDataAction); } fileMenu.add(saveUserDataAction); fileMenu.add(saveUserDataAsAction); } if (OTConfig.isDebug()) { if (userMode == OTConfig.SINGLE_USER_MODE) { loadAction.putValue(Action.NAME, "Open Authored Content..."); saveAction.putValue(Action.NAME, "Save Authored Content"); saveAsAction.putValue(Action.NAME, "Save Authored Content As..."); saveRemoteAsAction.putValue(Action.NAME, "Save Authored Content Remotely As..."); } else { loadAction.putValue(Action.NAME, "Open..."); saveAction.putValue(Action.NAME, "Save"); saveAsAction.putValue(Action.NAME, "Save As..."); saveRemoteAsAction.putValue(Action.NAME, "Save Remotely As..."); } fileMenu.add(loadAction); fileMenu.add(saveAction); fileMenu.add(saveAsAction); fileMenu.add(saveRemoteAsAction); } if (OTConfig.isAuthorMode() && !OTConfig.isDebug()) { if (userMode == OTConfig.SINGLE_USER_MODE) { loadAction.putValue(Action.NAME, "Open Authored Content..."); saveAction.putValue(Action.NAME, "Save Authored Content"); saveAsAction.putValue(Action.NAME, "Save Authored Content As..."); } else { loadAction.putValue(Action.NAME, "Open..."); saveAction.putValue(Action.NAME, "Save"); saveAsAction.putValue(Action.NAME, "Save As..."); } fileMenu.add(loadAction); fileMenu.add(saveAction); fileMenu.add(saveAsAction); } if (OTConfig.getBooleanProp("otrunk.view.export_image", false)) { fileMenu.add(exportImageAction); fileMenu.add(exportHiResImageAction); } fileMenu.add(exportToHtmlAction); fileMenu.add(showConsoleAction); if (OTConfig.isAuthorMode() || OTConfig.isDebug()) { fileMenu.add(reloadWindowAction); } JCheckBoxMenuItem debugItem = new JCheckBoxMenuItem(debugAction); debugItem.setSelected(OTConfig.isDebug()); fileMenu.add(debugItem); fileMenu.add(exitAction); return menuBar; } boolean checkForReplace(File file) { if (file == null){ return false; } if (!file.exists()) { return true; // File doesn't exist, so go ahead and save } if (currentAuthoredFile != null && file.compareTo(currentAuthoredFile) == 0){ return true; // we're already authoring this file, so no need to // prompt } final Object[] options = { "Yes", "No" }; return javax.swing.JOptionPane.showOptionDialog(null, "The file '" + file.getName() + "' already exists. " + "Replace existing file?", "Warning", javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, options, options[1]) == javax.swing.JOptionPane.YES_OPTION; } /** * FIXME This method name is confusing. The method first checks for unsaved * changes, and if there are unsaved changes it asks the user if they want to * "don't save", "cancel" or "save" * * @return */ public boolean checkForUnsavedUserData() { if(userSession == null){ return true; } if(userSession.hasUnsavedChanges()) { // show dialog message telling them they haven't // saved their work // FIXME String options[] = { "Don't Save", "Cancel", "Save" }; askedAboutSavingUserData = true; int chosenOption = JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); switch (chosenOption) { case 0: System.err.println("Not saving work"); break; case 1: System.err.println("Canceling close"); return false; case 2: System.err.println("Set needToSaveUserData true"); needToSaveUserData = true; break; } } return true; } /** * Checks if the user has unsaved authored data. If they do then it prompts * them to confirm what they are doing. If they cancel then it returns * false. * * @return */ public boolean checkForUnsavedAuthorData() { if (xmlDB != null) { if (xmlDB.isDirty()) { // show dialog message telling them they haven't // saved their work // FIXME String options[] = { "Don't Save", "Cancel", "Save" }; int chosenOption = JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); switch (chosenOption) { case 0: System.err.println("Not saving authored data"); break; case 1: System.err.println("Canceling close"); return false; case 2: System.err.println("Saving authored data"); saveAction.actionPerformed(null); break; } } } return true; } /** * This does not check for unsaved user data * */ public void newAnonUserData() { newUserData(OTViewerHelper.ANON_SINGLE_USER_NAME); } public void newUserData(String userName) { // call some new method for creating a new un-saved user state // this should set the currentUserFile to null, so the save check // prompts // for a file name if(userSession == null) { throw new IllegalStateException("a OTUserSession must be supplied before newUserData can be called"); } try { userSession.newLayer(); OTUserObject userObject = userSession.getUserObject(); if(userName != null){ userObject.setName(userName); } // This will request the label from the userSession reloadWindow(); } catch (Exception e) { e.printStackTrace(); } } public boolean exit() { try { if (!checkForUnsavedUserData()) { // the user canceled the operation return false; } if (OTConfig.isAuthorMode() && !checkForUnsavedAuthorData()) { // the user canceled the operation return false; } // FIXME there is a problem with this logic. If the user saved data // just before closing // checkForUnsavedUserData will not see any unsaved data. But if // some view creates // data in the viewClosed method then that data will not get saved // here. // I think the key to solving this is to separate the // automatic/logging data from the // user visible data. And then make a rule that saving data in the // viewClosed method // is not allowed. bodyPanel.setCurrentObject(null); conditionalSaveUserData(); if (otrunk != null) otrunk.close(); } catch (Exception exp) { exp.printStackTrace(); // exit anyhow } System.exit(0); return true; } protected void conditionalSaveUserData() { if (!askedAboutSavingUserData) { checkForUnsavedUserData(); } if (needToSaveUserData) { saveUserDataAction.actionPerformed(null); } else { System.err.println("Not saving work before closing."); } // Reset these back to false, so if the user is switching to a new // user or loading a new file we are in a clean state, for that file or // user askedAboutSavingUserData = false; needToSaveUserData = false; } public File getReportFile() { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.saveotml"); mrfd.setFilenameFilter("html"); if (userSession instanceof OTMLUserSession){ OTMLUserSession otmlUserSession = (OTMLUserSession) userSession; if(otmlUserSession.currentUserFile != null){ mrfd.setCurrentDirectory(otmlUserSession.currentUserFile.getParentFile()); } } int retval = mrfd.showSaveDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); String fileName = file.getPath(); if (!fileName.toLowerCase().endsWith(".html")) { file = new File(file.getAbsolutePath() + ".html"); } return file; } return null; } public void createNewUser() { if (!checkForUnsavedUserData()) { // the user canceled the operation return; } // This ensures viewClosed is called bodyPanel.setCurrentObject(null); conditionalSaveUserData(); // call some new method for creating a new un-saved user state // this should set the currentUserFile to null, so the save check // prompts // for a file name newAnonUserData(); exportToHtmlAction.setEnabled(true); } public void openUserData(boolean saveCurrentData) { if(saveCurrentData){ if (!checkForUnsavedUserData()) { // the user canceled the operation return; } // FIXME Calling the method below would insure the view is closed, and // that any data that is // is modified in that view closed operation will get saved, however if // the user // cancels the open dialog then we would be left in an unknown // state. The current view would be closed which they would want to see // again. // bodyPanel.setCurrentObject(null); conditionalSaveUserData(); } if(userSession == null){ throw new IllegalStateException("can't open user data without a userSession"); } boolean success = userSession.open(); try { reloadWindow(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(success){ exportToHtmlAction.setEnabled(true); } } public void instructionPanel() { commDialog.setResizable(false); JPanel panel = new JPanel(); panel.setBackground(Color.WHITE); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 0.5; c.insets = new Insets(5,10,5,10); JLabel lNew = new JLabel("Click the \"New\" button to create a new portfolio:"); JLabel lOpen = new JLabel("Click the \"Open\" button to open a saved portfolio:"); JButton bNew = new JButton("New"); JButton bOpen = new JButton("Open"); c.gridx = 0; c.gridy = 0; panel.add(lNew, c); c.gridx = 1; panel.add(bNew, c); c.gridx = 0; c.gridy = 1; panel.add(lOpen, c); c.gridx = 1; panel.add(bOpen, c); bNew.setOpaque(false); bOpen.setOpaque(false); setUserSession(new OTMLUserSession()); bNew.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { commDialog.setVisible(false); newAnonUserData(); exportToHtmlAction.setEnabled(true); } }); bOpen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { commDialog.setVisible(false); openUserData(false); } }); commDialog.getContentPane().add(panel); commDialog.setBounds(200, 200, 450, 200); SwingUtilities.invokeLater(new Runnable() { public void run() { commDialog.setVisible(true); justStarted = false; updateMenuBar(); } }); } public OTViewContainerPanel getViewContainerPanel() { return this.bodyPanel; } public void setExitAction(AbstractAction exitAction) { this.exitAction = exitAction; } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#about() */ public void about() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#preferences() */ public void preferences() { // TODO Auto-generated method stub } public void setLaunchedBySailOTViewer(boolean launchedBySailOTViewer){ this.launchedBySailOTViewer = launchedBySailOTViewer; } public boolean isLaunchedBySailOTViewer(){ return launchedBySailOTViewer; } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#quit() */ public void quit() { exitAction.actionPerformed(null); } public OTrunk getOTrunk() { return otrunk; } /** * @param sailSaveEnabled the sailSaveEnabled to set */ public void setSailSaveEnabled(boolean sailSaveEnabled) { this.sailSaveEnabled = sailSaveEnabled; } /** * True is sail saving is enabled * @return the sailSaveEnabled */ public boolean isSailSaveEnabled() { return sailSaveEnabled; } } // @jve:decl-index=0:visual-constraint="10,10" class HtmlFileFilter extends javax.swing.filechooser.FileFilter { public boolean accept(File f) { if (f == null) return false; if (f.isDirectory()) return true; return (f.getName().toLowerCase().endsWith(".html")); } public String getDescription() { return "HTML files"; } } // @jve:decl-index=0:visual-constraint="10,10"
package com.jcwhatever.nucleus.utils.reflection; import com.jcwhatever.nucleus.utils.CollectionUtils; import com.jcwhatever.nucleus.utils.PreCon; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * A wrapper for a java class that provides reflection helpers. * */ public class ReflectedType { private final CachedReflectedType _cached; private Map<String, Method> _aliasMethods; private Map<String, ReflectedField> _aliasFields; private Map<String, Constructor<?>> _aliasConstructors; private Map<String, Object> _aliasEnum; /** * Constructor. */ ReflectedType(CachedReflectedType cached) { PreCon.notNull(cached); _cached = cached; } /** * Get the encapsulated class. */ public Class<?> getHandle() { return _cached.getHandle(); } /** * Get fields of the specified type. * * <p>Only stores by the field type. Super types * are not stored.</p> * * <p>Specifying the Object type returns all fields.</p> * * @param fieldType The field type. */ public List<ReflectedField> getFields(Class<?> fieldType) { PreCon.notNull(fieldType, "fieldType"); return CollectionUtils.unmodifiableList(_cached._fieldsByType.get(fieldType)); } /** * Get a field from the type by name. * * <p>If an alias is defined, the alias can also be used.</p> * * @param name The field name. */ public ReflectedField getField(String name) { PreCon.notNullOrEmpty(name, "name"); if (_aliasFields != null) { ReflectedField field = _aliasFields.get(name); if (field != null) return field; } ReflectedField field = _cached._fieldsByName.get(name); if (field == null) { throw new RuntimeException("Field " + name + " not found in type " + getHandle().getName()); } return field; } /** * Get a static field from the type by name. * * <p>If an alias is defined, the alias can also be used.</p> * * @param name The field name. */ public ReflectedField getStaticField(String name) { PreCon.notNullOrEmpty(name, "name"); if (_aliasFields != null) { ReflectedField field = _aliasFields.get(name); if (field != null) return field; } ReflectedField field = _cached._staticFieldsByName.get(name); if (field == null) { throw new RuntimeException("Field " + name + " not found in type " + getHandle().getName()); } return field; } /** * Get an enum constant from the type. * * @param constantName The enum constant name. * * @return The enum constant. */ public Object getEnum(String constantName) { PreCon.notNullOrEmpty(constantName, "constantName"); if (_aliasEnum != null) { Object constant = _aliasEnum.get(constantName); if (constant != null) return constant; } return getEnumConstant(constantName); } /** * Get a static field value. * * @param fieldName The name of the field. */ public Object get(String fieldName) { ReflectedField field = getField(fieldName); return field.get(null); } /** * Set a static field value. * * @param fieldName The name of the field. * @param value The value to set. */ public void set(String fieldName, Object value) { ReflectedField field = getField(fieldName); field.set(null, value); } /** * Create a new instance of the encapsulated class using * a pre-registered constructor alias. * * @param arguments The constructor arguments. * * @return The new instance. */ public Object construct(String alias, Object... arguments) { PreCon.notNullOrEmpty(alias, "alias"); PreCon.notNull(arguments, "arguments"); if (_aliasConstructors == null) throw new RuntimeException("No constructor aliases registered."); Constructor<?> constructor = _aliasConstructors.get(alias); if (constructor == null) throw new RuntimeException("Constructor alias not found : " + alias); try { return constructor.newInstance(arguments); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); throw new RuntimeException("Failed to instantiate constructor."); } } /** * Create a new instance of the encapsulated class using * a pre-registered constructor alias and wrap in * {@code ReflectedInstance}. * * @param arguments The constructor arguments. * * @return The new instance. */ public ReflectedInstance constructReflect(String alias, Object... arguments) { PreCon.notNullOrEmpty(alias, "alias"); PreCon.notNull(arguments, "arguments"); Object instance = construct(alias, arguments); assert instance != null; return new ReflectedInstance(this, instance); } /** * Create a new instance of the encapsulated class. * Searches for the correct constructor based on * provided arguments. * * @param arguments The constructor arguments. * * @return The new instance. */ public Object newInstance(Object... arguments) { PreCon.notNull(arguments, "arguments"); Collection<Constructor<?>> constructors = _cached._constructors.get(arguments.length); Constructor<?> constructor; if (constructors.size() == 0) { throw new RuntimeException("No constructors to instantiate."); } else { constructor = constructors.size() == 1 ? constructors.iterator().next() : ReflectionUtils.findConstructorByArgs(constructors, arguments); } if (constructor == null) throw new RuntimeException("Failed to find a matching constructor."); Object instance; try { instance = constructor.newInstance(arguments); } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); throw new RuntimeException("Failed to instantiate constructor."); } return instance; } /** * Create a new instance of the encapsulated class. * Searches for the correct constructor based on * provided arguments. * * @param arguments The constructor arguments. * * @return The new instance. */ public ReflectedInstance newReflectedInstance(Object... arguments) { PreCon.notNull(arguments, "arguments"); Object instance = newInstance(arguments); return new ReflectedInstance(this, instance); } /** * Create a new array whose component type is * the encapsulated class. * * @param size The size of the array. * * @return {@code ReflectedArray} instance. */ public ReflectedArray newArray(int size) { PreCon.positiveNumber(size); Object array = Array.newInstance(_cached.getHandle(), size); return new ReflectedArray(this, array); } /** * Create a new array whose component type is * the encapsulated class. * * @param sizes The size of each array dimension. * * @return {@code ReflectedArray} instance. */ public ReflectedArray newArray(int... sizes) { PreCon.greaterThanZero(sizes.length, "At least one array dimension must be specified."); Object array = Array.newInstance(_cached.getHandle(), sizes); return new ReflectedArray(this, array); } /** * Create a new {@code ReflectedInstance} to encapsulate * an object instance that is known to be of the same * type as the encapsulated class. * * @param instance The instance to wrap. */ public ReflectedInstance reflect(Object instance) { PreCon.notNull(instance, "instance"); return new ReflectedInstance(this, instance); } /** * Create a new {@code ReflectedArray} to encapsulate * an array instance that is known to be of the same * type as the encapsulated class. * * @param instance The instance to wrap. */ public ReflectedArray reflectArray(Object instance) { PreCon.notNull(instance, "instance"); return new ReflectedArray(this, instance); } /** * Register a constructor signature under an alias name. Improves performance * by allowing the specific constructor to be retrieved by the alias name. * Use {@code #construct} or {@code @constructReflect} to create new instances * using the alias name. * * @param alias The constructor alias. * @param signature The constructor signature. * * @return Self for chaining. */ public ReflectedType constructorAlias(String alias, Class<?>... signature) { PreCon.notNullOrEmpty(alias, "alias"); PreCon.notNull(signature, "signature"); if (_aliasConstructors == null) _aliasConstructors = new HashMap<>(10); if (_aliasConstructors.containsKey(alias)) throw new RuntimeException("Constructor alias already registered: " + alias); Constructor<?> constructor; try { constructor = getHandle().getConstructor(signature); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new RuntimeException("Constructor not found."); } constructor.setAccessible(true); _aliasConstructors.put(alias, constructor); return this; } /** * Register a field alias name. * * @param fieldAlias The field alias. * @param fieldName The field name. * * @return Self for chaining. */ public ReflectedType fieldAlias(String fieldAlias, String fieldName) { PreCon.notNullOrEmpty(fieldAlias, "fieldAlias"); PreCon.notNullOrEmpty(fieldName, "fieldName"); if (_aliasFields == null) _aliasFields = new HashMap<>(10); if (_aliasFields.containsKey(fieldAlias)) throw new RuntimeException("Field alias already registered: " + fieldAlias); ReflectedField field = getField(fieldName); if (field == null) throw new RuntimeException("Field " + fieldName + " not found in type " + getHandle().getName()); _aliasFields.put(fieldAlias, field); return this; } public ReflectedType enumAlias(String constantAlias, String constantName) { PreCon.notNullOrEmpty(constantAlias, "enumAlias"); PreCon.notNullOrEmpty(constantName, "enumName"); if (_aliasEnum == null) _aliasEnum = new HashMap<>(5); if (_aliasEnum.containsKey(constantAlias)) throw new RuntimeException("Enum alias already registered: " + constantAlias); _aliasEnum.put(constantAlias, getEnumConstant(constantName)); return this; } public ReflectedType enumConst(String constantName) { PreCon.notNullOrEmpty(constantName, "enumName"); if (_aliasEnum == null) _aliasEnum = new HashMap<>(5); if (_aliasEnum.containsKey(constantName)) throw new RuntimeException("Enum constant already registered: " + constantName); _aliasEnum.put(constantName, getEnumConstant(constantName)); return this; } /** * Registers a method name to a specific signature. Does not allow * for overloaded methods. Improves code readability and method lookup performance. * * @param methodName The method name. * @param signature The argument types of the method. * * @return Self for chaining. */ public ReflectedType method(String methodName, Class<?>... signature) { PreCon.notNullOrEmpty(methodName, "methodName"); PreCon.notNull(signature, "argTypes"); if (_aliasMethods == null) { _aliasMethods = new HashMap<>(10); } if (_aliasMethods.containsKey(methodName)) throw new RuntimeException("Method already registered: " + methodName); Method method; try { method = getHandle().getDeclaredMethod(methodName, signature); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new RuntimeException("Method not found."); } method.setAccessible(true); _aliasMethods.put(methodName, method); return this; } /** * Register a method alias name to a specific signature to aid * in code readability and method lookup performance. * * @param alias The alias for the method. Can match an actual method name * but will prevent use of overloads. * @param methodName The name of the method. * @param signature The argument types of the method. * * @return Self for chaining. */ public ReflectedType methodAlias(String alias, String methodName, Class<?>... signature) { PreCon.notNullOrEmpty(alias, "alias"); PreCon.notNullOrEmpty(methodName, "methodName"); PreCon.notNull(signature, "argTypes"); if (_aliasMethods == null) { _aliasMethods = new HashMap<>(10); } if (_aliasMethods.containsKey(alias)) throw new RuntimeException("Alias already registered: " + alias); Method method; try { method = getHandle().getDeclaredMethod(methodName, signature); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new RuntimeException("Method not found."); } method.setAccessible(true); _aliasMethods.put(alias, method); return this; } /** * Call a static method on the encapsulated class. * * @param staticMethodName The name of the static method. * @param arguments The method arguments. * * @param <V> The return type. * * @return Null if the method returns null or void. */ @Nullable public <V> V invokeStatic(String staticMethodName, Object... arguments) { PreCon.notNull(staticMethodName, "staticMethodName"); PreCon.notNull(arguments, "arguments"); return invoke(null, staticMethodName, arguments); } /** * Call a method on an instance of the encapsulated class. * * @param instance The instance. * @param methodName The name of the method. * @param arguments The method arguments. * * @param <V> The return type. * * @return Null if the method returns null or void. */ @Nullable public <V> V invoke(@Nullable Object instance, String methodName, Object... arguments) { PreCon.notNullOrEmpty(methodName, "methodName"); PreCon.notNull(arguments, "arguments"); Method method = _aliasMethods != null ? _aliasMethods.get(methodName) : null; if (method == null) { Collection<Method> methods = instance != null ? _cached._methods.get(methodName) : _cached._staticMethods.get(methodName); // get method definition if (methods.size() == 1) { method = methods.iterator().next(); } else { method = ReflectionUtils.findMethodByArgs(methods, methodName, arguments); if (method == null) throw new RuntimeException("Method '" + methodName + "' not found in type " + _cached.getHandle().getCanonicalName()); } } Object result; try { result = method.invoke(instance, arguments); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); return null; } @SuppressWarnings("unchecked") V castedResult = (V)result; return castedResult; } private Object getEnumConstant(String constantName) { Object[] constants = getHandle().getEnumConstants(); Method nameMethod; try { nameMethod = Enum.class.getMethod("name"); } catch (NoSuchMethodException e) { throw new AssertionError(); } nameMethod.setAccessible(true); for (Object constant : constants) { String name; try { name = (String) nameMethod.invoke(constant); } catch (IllegalAccessException | InvocationTargetException e) { throw new AssertionError(); } if (constantName.equals(name)) { return constant; } } throw new RuntimeException("Failed to find enum constant named " + constantName + " in type " + getHandle().getName()); } }
package com.kirbybanman.travelclaimer; import com.kirbybanman.travelclaimer.R; import com.kirbybanman.travelclaimer.R.id; import com.kirbybanman.travelclaimer.R.layout; import com.kirbybanman.travelclaimer.R.menu; import com.kirbybanman.travelclaimer.core.TravelClaimerActivity; import com.kirbybanman.travelclaimer.model.Claim; import com.kirbybanman.travelclaimer.view.ClaimStringRenderer; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; public class IndividualClaimActivity extends TravelClaimerActivity { private Claim claim; TextView summaryText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_individual_claim); summaryText = (TextView) findViewById(R.id.IndividualClaimSummary); } @Override protected void onResume() { super.onResume(); // receive claim position in model from intent int claimPosition = getIntent().getIntExtra("claimPosition", -1); try { claim = getApp().getClaimsList().get(claimPosition); summaryText.setText(new ClaimStringRenderer(claim).getFullDescription()); findViewById(R.id.IndividualClaimEditExpensesButton).setEnabled(claim.isEditable()); } catch (IndexOutOfBoundsException e) { Log.e("intent fail", e.toString()); summaryText.setText("Bad claim number: " + claimPosition); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.individual_claim, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void editDetailsButtonClicked(View view) { Intent intent = new Intent(this, EditClaimActivity.class); intent.putExtra("claimPosition", getApp().getClaimsList().indexOf(claim)); startActivity(intent); } public void editExpensesButtonClicked(View view) { Intent intent = new Intent(this, ExpensesListActivity.class); intent.putExtra("claimPosition", getApp().getClaimsList().indexOf(claim)); startActivity(intent); } public void emailButtonClicked(View view) { ClaimStringRenderer claimStrings = new ClaimStringRenderer(claim); Intent send = new Intent(Intent.ACTION_SENDTO); send.setData(Uri.parse("mailto:")); send.putExtra(Intent.EXTRA_SUBJECT, claimStrings.getStartDate() + " Claim Details"); send.putExtra(Intent.EXTRA_TEXT, claimStrings.getFullDescription()); /*String uriText = "mailto:" + Uri.encode("kdbanman@ualberta.ca") + "?subject=" + Uri.encode("Claim Details") + "&body=" + Uri.encode(new ClaimStringRenderer(claim).getFullDescription()); send.setData(Uri.parse(uriText));*/ //startActivity(Intent.createChooser(send, "Send mail...")); startActivity(send); } }
package com.programmerdan.minecraft.contraptions; import com.programmerdan.minecraft.contraptions.commands.CommandHandler; import java.util.logging.Logger; import org.bukkit.plugin.java.JavaPlugin; import vg.civcraft.mc.civmodcore.ACivMod; /** * <p>The server side technology mod to end all server side technology mods.</p> * <p>See the readme and documentation for more</p> * * @author ProgrammerDan <programmerdan@gmail.com> * @since 1.0.0 */ public class Contraptions extends ACivMod { private static CommandHandler commandHandler; private static Logger logger; private static JavaPlugin plugin; private static ContraptionsConfiguration config; public static CommandHandler commandHandler() { return Contraptions.commandHandler; } protected String getPluginName() { return "Contraptions"; } public static Logger logger() { return Contraptions.logger; } public static JavaPlugin instance() { return Contraptions.plugin; } public static boolean isDebug() { return Contraptions.config.isDebug(); } public static ContraptionsConfiguration config() { return Contraptions.config; } @Override public void onEnable() { super.onEnable(); // setting a couple of static fields so that they are available elsewhere Contraptions.logger = getLogger(); Contraptions.plugin = this; Contraptions.commandHandler = new CommandHandler(this); /* TODO: * 1. Load general Contraptions configuration * 2. Spin up Contraption monitor in startup mode * 3. Load Gadget specifications * 4. Load saved Contraptions (DB access necessary) * 1. Load Gadget locations, types, status * 2. Load Contraption State (connections, activity status, state machine) * 3. Add Contraption to Contraption monitor * 5. Enter Contraption monitor active mode */ } }
package com.vaadin.tests.components.combobox; import com.vaadin.data.Item; import com.vaadin.terminal.Resource; import com.vaadin.terminal.ThemeResource; import com.vaadin.tests.components.TestBase; import com.vaadin.ui.ComboBox; public class ComboBoxItemIcon extends TestBase { @Override protected Integer getTicketNumber() { return 2455; } @Override protected String getDescription() { return "The items in the ComboBox should have icons - also when selected."; } @Override protected void setup() { ComboBox cb = new ComboBox(); cb.addContainerProperty("icon", Resource.class, null); cb.setItemIconPropertyId("icon"); getLayout().addComponent(cb); Item item = cb.addItem("FI"); item.getItemProperty("icon").setValue( new ThemeResource("../sampler/flags/fi.gif")); item = cb.addItem("SE"); item.getItemProperty("icon").setValue( new ThemeResource("../sampler/flags/se.gif")); } }
package org.apache.hadoop.raid; import java.io.FileNotFoundException; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import java.util.HashMap; import java.util.*; //import java.util.Collections; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapred.Counters; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.FileSplit; import org.apache.hadoop.mapred.InputFormat; import org.apache.hadoop.mapred.InputSplit; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.JobID; import org.apache.hadoop.mapred.JobInProgress; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.RecordReader; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.RunningJob; import org.apache.hadoop.mapred.SequenceFileRecordReader; import org.apache.hadoop.mapred.TaskCompletionEvent; import org.apache.hadoop.raid.RaidNode.Statistics; import org.apache.hadoop.raid.protocol.PolicyInfo; import org.apache.hadoop.util.StringUtils; public class DistRaid { protected static final Log LOG = LogFactory.getLog(DistRaid.class); static final String NAME = "distRaid"; static final String JOB_DIR_LABEL = NAME + ".job.dir"; static final String OP_LIST_LABEL = NAME + ".op.list"; static final String OP_COUNT_LABEL = NAME + ".op.count"; static final String SCHEDULER_OPTION_LABEL = NAME + ".scheduleroption"; static final String IGNORE_FAILURES_OPTION_LABEL = NAME + ".ignore.failures"; static final int OP_LIST_BLOCK_SIZE = 32 * 1024 * 1024; // block size of control file static final short OP_LIST_REPLICATION = 10; // replication factor of control file private static final long DEFAULT_OP_PER_MAP = 50; public static final String OP_PER_MAP_KEY = "hdfs.raid.op.per.map"; private static final int DEFAULT_MAX_MAPS_PER_NODE = 20; public static final String MAX_MAPS_PER_NODE_KEY = "hdfs.raid.max.maps.per.node"; public static final int DEFAULT_MAX_FAILURE_RETRY = 3; public static final String MAX_FAILURE_RETRY_KEY = "hdfs.raid.max.failure.retry"; public static final String SLEEP_TIME_BETWEEN_RETRY_KEY = "hdfs.raid.sleep.time.between.retry"; public static final long DEFAULT_SLEEP_TIME_BETWEEN_RETRY = 1000L; private static long opPerMap = DEFAULT_OP_PER_MAP; private static int maxMapsPerNode = DEFAULT_MAX_MAPS_PER_NODE; private static final int SYNC_FILE_MAX = 10; private static final SimpleDateFormat dateForm = new SimpleDateFormat("yyyy-MM-dd HH:mm"); private static String jobName = NAME; public static enum Counter { FILES_SUCCEEDED, FILES_FAILED, PROCESSED_BLOCKS, PROCESSED_SIZE, META_BLOCKS, META_SIZE, SAVING_SIZE } protected JobConf jobconf; /** {@inheritDoc} */ public void setConf(Configuration conf) { if (jobconf != conf) { jobconf = conf instanceof JobConf ? (JobConf) conf : new JobConf(conf); } } /** {@inheritDoc} */ public JobConf getConf() { return jobconf; } public DistRaid(Configuration conf) { setConf(createJobConf(conf)); /* Added by RH Oct 8th, 2014, begins */ jobconf.setEncoding(true); /* Added by RH Oct 8th, 2014, ends */ opPerMap = conf.getLong(OP_PER_MAP_KEY, DEFAULT_OP_PER_MAP); maxMapsPerNode = conf.getInt(MAX_MAPS_PER_NODE_KEY, DEFAULT_MAX_MAPS_PER_NODE); } private static final Random RANDOM = new Random(); protected static String getRandomId() { return Integer.toString(RANDOM.nextInt(Integer.MAX_VALUE), 36); } /* * This class denotes the unit of encoding for a mapper task * The key in the map function is formated as: * "startStripeId encodingId encodingUnit path" * Given a file path /user/dhruba/1 with 13 blocks * Suppose codec's stripe length is 3 and encoding unit is 2 * RaidNode.splitPaths will split the raiding task into 3 tasks * "0 1 2 /user/dhruba/1": will raid the stripe 0 and 1 (blocks 0-5) * "2 2 2 /user/dhruba/1": will raid the stripe 2 and 3 (blocks 6-11) * "4 3 2 /user/dhruba/1": will raid the stripe 4 (blocks 12-13) * encodingId is unique for each task and it's used to construct a temporary * directory to store the partial parity file * modificationTime is the modification time of candidate when job is submitted * it's used for checking if candidate changes after the job submit. */ public static class EncodingCandidate implements Comparable<EncodingCandidate> { public final static int DEFAULT_GET_SRC_STAT_RETRY = 5; public FileStatus srcStat; public long startStripe = 0; public long encodingUnit = 0; public String encodingId = null; final static public String delim = " "; public long modificationTime = 0L; public boolean isEncoded = false; public boolean isRenamed = false; public boolean isConcated = false; public List<List<Block>> srcStripes = null; /* Added by RH Sep 30th, 2014 starts * We add a prefered host which locates in the core rack of the stripe. */ public String preferedHosts; public String preferedRack; /* Added by RH Sep 30th, 2014 ends */ EncodingCandidate(FileStatus newStat, long newStartStripe, String newEncodingId, long newEncodingUnit, long newModificationTime) { this.srcStat = newStat; this.startStripe = newStartStripe; this.encodingId = newEncodingId; this.encodingUnit = newEncodingUnit; this.modificationTime = newModificationTime; /* Added by RH Oct 1st, 2014, starts */ this.preferedHosts = null; this.preferedRack = null; /* Added by RH Oct 1st, 2014, ends */ } /* Added by RH Oct 2nd, 2014, begins */ EncodingCandidate(FileStatus newStat, long newStartStripe, String newEncodingId, long newEncodingUnit, long newModificationTime, String preRack, String preHost) { this.srcStat = newStat; this.startStripe = newStartStripe; this.encodingId = newEncodingId; this.encodingUnit = newEncodingUnit; this.modificationTime = newModificationTime; this.preferedRack = preRack; this.preferedHosts = preHost; } public String getPreHost(){ return preferedHosts; } public void setPreHost(String preHost,String preRack){ this.preferedHosts = preHost; this.preferedRack = preRack; } /* Make Encoding candidate comparable so that we can stripes with same core * rack together */ public int compareTo(EncodingCandidate ec) { return this.preferedRack.compareTo(ec.preferedRack); } /* Added by RH Oct 2nd, 2014, ends */ public String toString() { /* Added by RH Oct 1st, 2014, starts */ return startStripe + delim + encodingId + delim + encodingUnit + delim + modificationTime + delim + this.srcStat.getPath().toString() + delim + preferedRack + delim + preferedHosts; /* Added by RH Oct 1st, 2014, ends */ /* Commented by RH Oct 1st, 2014, starts */ //return startStripe + delim + encodingId + delim + encodingUnit // + delim + modificationTime + delim + this.srcStat.getPath().toString(); /* Commented by RH Oct 1st, 2014, ends */ } public static EncodingCandidate getEncodingCandidate(String key, Configuration jobconf) throws IOException { String[] keys = key.split(delim, 7); Path p = new Path(keys[4]); long startStripe = Long.parseLong(keys[0]); long modificationTime = Long.parseLong(keys[3]); FileStatus srcStat = getSrcStatus(jobconf, p); long encodingUnit = Long.parseLong(keys[2]); /* Added by RH Oct 3rd, 2014 begins */ String host = null; String rack = null; if (!keys[5].equals("null")){ host = keys[5]; } if (!keys[6].equals("null")){ rack = keys[6]; } return new EncodingCandidate(srcStat, startStripe, keys[1], encodingUnit, modificationTime,host,rack); /* Added by RH Oct 3rd, 2014 ends */ } /* Added by RH Oct 2nd, 2014, starts */ //public static EncodingCandidate getEncodingCandidate(String key, // Configuration jobconf) throws IOException { // String[] keys = key.split(delim, 5); // Path p = new Path(keys[4]); // long startStripe = Long.parseLong(keys[0]); // long modificationTime = Long.parseLong(keys[3]); // FileStatus srcStat = getSrcStatus(jobconf, p); // long encodingUnit = Long.parseLong(keys[2]); // return new EncodingCandidate(srcStat, startStripe, keys[1], // encodingUnit, modificationTime); /* Added by RH Oct 2nd, 2014, ends */ public static FileStatus getSrcStatus(Configuration jobconf, Path p) throws IOException { for (int i = 0; i < DEFAULT_GET_SRC_STAT_RETRY; i++) { try { return p.getFileSystem(jobconf).getFileStatus(p); } catch (FileNotFoundException fnfe) { return null; } catch (IOException ioe) { LOG.warn("Get exception ", ioe); if (i == DEFAULT_GET_SRC_STAT_RETRY - 1) { throw ioe; } try { Thread.sleep(3000); } catch (InterruptedException ignore) { } } } throw new IOException("couldn't getFileStatus " + p); } public void refreshFile(Configuration jobconf) throws IOException { srcStat = getSrcStatus(jobconf, srcStat.getPath()); } } /** * * helper class which holds the policy and paths * */ public static class RaidPolicyPathPair { public PolicyInfo policy; public List<EncodingCandidate> srcPaths; RaidPolicyPathPair(PolicyInfo policy, List<EncodingCandidate> srcPaths) { this.policy = policy; this.srcPaths = srcPaths; } } List<RaidPolicyPathPair> raidPolicyPathPairList = new ArrayList<RaidPolicyPathPair>(); private JobClient jobClient; private RunningJob runningJob; private int jobEventCounter = 0; private String lastReport = null; private long startTime = System.currentTimeMillis(); private long totalSaving; /** Responsible for generating splits of the src file list. */ static class DistRaidInputFormat implements InputFormat<Text, PolicyInfo> { /** Do nothing. */ public void validateInput(JobConf job) { } /** * Produce splits such that each is no greater than the quotient of the * total size and the number of splits requested. * * @param job * The handle to the JobConf object * @param numSplits * Number of splits requested */ public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { final int srcCount = job.getInt(OP_COUNT_LABEL, -1); final int targetcount = srcCount / numSplits; String srclist = job.get(OP_LIST_LABEL, ""); if (srcCount < 0 || "".equals(srclist)) { throw new RuntimeException("Invalid metadata: #files(" + srcCount + ") listuri(" + srclist + ")"); } Path srcs = new Path(srclist); FileSystem fs = srcs.getFileSystem(job); List<FileSplit> splits = new ArrayList<FileSplit>(numSplits); Text key = new Text(); PolicyInfo value = new PolicyInfo(); SequenceFile.Reader in = null; long prev = 0L; int count = 0; // count src /* Added by RH Oct 30th, 2014 begins */ Map<String,Integer[]> rackIdxRange=new HashMap<String,Integer[]>(); Map<String,String> rackHostMap=new HashMap<String,String>(); List<Integer> stripeOffset = new ArrayList<Integer>(); long currOffset = 0; String currentRack = null; int index = 0; try { for (in = new SequenceFile.Reader(fs, srcs, job); in.next(key, value);) { currOffset = in.getPosition(); String[] keySplit = key.toString().split(" ",7); LOG.info("prefered rack of stripe" + index + " is " + keySplit[5]); if (currentRack == null || !currentRack.equals(keySplit[5])) { if (currentRack!=null) { rackIdxRange.get(currentRack)[1]=index-1; } currentRack = keySplit[5]; rackIdxRange.put(currentRack,new Integer[2]); rackIdxRange.get(currentRack)[0]=index; rackHostMap.put(keySplit[5],keySplit[6]); } stripeOffset.add((int)currOffset); index++; } } finally { prev = currOffset; rackIdxRange.get(currentRack)[1]=index-1; in.close(); } List<String> sortedKeyList = new ArrayList<String>(); sortedKeyList.addAll(rackIdxRange.keySet()); Collections.sort(sortedKeyList); for(String key : sortedKeyList) { String[] hosts = new String[1]; Integer[] idxRange = rackIdxRange.get(key); hosts[0] = rackHostMap.get(key); long startPos = idxRange[0]==0? 0:stripeOffset.get(idxRange[0]-1); long endPos = stripeOffset.get(idxRange[1]); LOG.info("hosts: " + hosts[0] + "start/end: " + idxRange[0] + "/" + idxRange[1]); splits.add(new FileSplit(srcs, startPos, endPos-startPos, hosts)); } /* Added by RH Oct 30th, 2014 ends */ //try { // for (in = new SequenceFile.Reader(fs, srcs, job); in.next(key, value);) { // long curr = in.getPosition(); // long delta = curr - prev; // if (++count > targetcount) { // count = 0; // //splits.add(new FileSplit(srcs, prev, delta, (String[]) null)); // /* added by RH on Oct 7th, begins // * TODO: currently, we suppose one stripe per map task, but we need to // * generalize our split method */ // String[] keySplit = key.toString().split(" ",7); // String[] hosts = new String[1]; // hosts[0] = keySplit[6]; // LOG.info("key value is " + key.toString()); // LOG.info("prefered host of map task is " + hosts[0]); // splits.add(new FileSplit(srcs, prev, delta, hosts)); // /* added by RH on Oct 7th, ends */ // prev = curr; //} finally { // in.close(); long remaining = fs.getFileStatus(srcs).getLen() - prev; if (remaining != 0) { splits.add(new FileSplit(srcs, prev, remaining, (String[]) null)); } LOG.info("jobname= " + jobName + " numSplits=" + numSplits + ", splits.size()=" + splits.size()); return splits.toArray(new FileSplit[splits.size()]); } /** {@inheritDoc} */ public RecordReader<Text, PolicyInfo> getRecordReader(InputSplit split, JobConf job, Reporter reporter) throws IOException { return new SequenceFileRecordReader<Text, PolicyInfo>(job, (FileSplit) split); } } /** The mapper for raiding files. */ static class DistRaidMapper implements Mapper<Text, PolicyInfo, WritableComparable, Text> { private JobConf jobconf; private boolean ignoreFailures; private int retryNum; private int failcount = 0; private int succeedcount = 0; private Statistics st = null; private Reporter reporter = null; private String getCountString() { return "Succeeded: " + succeedcount + " Failed: " + failcount; } /** {@inheritDoc} */ public void configure(JobConf job) { this.jobconf = job; ignoreFailures = jobconf.getBoolean(IGNORE_FAILURES_OPTION_LABEL, true); retryNum = jobconf.getInt(DistRaid.MAX_FAILURE_RETRY_KEY, DistRaid.DEFAULT_MAX_FAILURE_RETRY); st = new Statistics(); } public static boolean doRaid(int retryNum, String key, Configuration jobconf, PolicyInfo policy, Statistics st, Reporter reporter) throws IOException { String s = "FAIL: " + policy + ", " + key + " "; long sleepTimeBetwRetry = jobconf.getLong(SLEEP_TIME_BETWEEN_RETRY_KEY, DEFAULT_SLEEP_TIME_BETWEEN_RETRY); EncodingCandidate ec = EncodingCandidate.getEncodingCandidate(key, jobconf); for (int i = 0; i < retryNum; i++) { LOG.info("The " + i + "th attempt: " + s); if (ec.srcStat == null) { LOG.info("Raiding Candidate doesn't exist, NO_ACTION"); return false; } if (ec.modificationTime != ec.srcStat.getModificationTime()) { LOG.info("Raiding Candidate was changed, NO_ACTION"); return false; } try { return RaidNode.doRaid(jobconf, policy, ec, st, reporter); } catch (IOException e) { LOG.info(s, e); if (i == retryNum - 1) { throw new IOException(s, e); } ec.refreshFile(jobconf); try { Thread.sleep(sleepTimeBetwRetry); } catch (InterruptedException ie) { throw new IOException(ie); } } } throw new IOException(s); } /** Run a FileOperation */ public void map(Text key, PolicyInfo policy, OutputCollector<WritableComparable, Text> out, Reporter reporter) throws IOException { this.reporter = reporter; try { Codec.initializeCodecs(jobconf); LOG.info("Raiding file=" + key.toString() + " policy=" + policy); boolean result = doRaid(retryNum, key.toString(), jobconf, policy, st, reporter); if (result) { ++succeedcount; reporter.incrCounter(Counter.PROCESSED_BLOCKS, st.numProcessedBlocks); reporter.incrCounter(Counter.PROCESSED_SIZE, st.processedSize); reporter.incrCounter(Counter.META_BLOCKS, st.numMetaBlocks); reporter.incrCounter(Counter.META_SIZE, st.metaSize); reporter.incrCounter(Counter.SAVING_SIZE, st.processedSize - st.remainingSize - st.metaSize); reporter.incrCounter(Counter.FILES_SUCCEEDED, 1); } } catch (IOException e) { ++failcount; reporter.incrCounter(Counter.FILES_FAILED, 1); out.collect(null, new Text(e.getMessage())); } finally { reporter.setStatus(getCountString()); } } /** {@inheritDoc} */ public void close() throws IOException { if (failcount == 0 || ignoreFailures) { return; } throw new IOException(getCountString()); } } /** * create new job conf based on configuration passed. * * @param conf * @return */ private static JobConf createJobConf(Configuration conf) { JobConf jobconf = new JobConf(conf, DistRaid.class); jobName = NAME + " " + dateForm.format(new Date(RaidNode.now())); jobconf.setUser(RaidNode.JOBUSER); jobconf.setJobName(jobName); jobconf.setMapSpeculativeExecution(false); RaidUtils.parseAndSetOptions(jobconf, SCHEDULER_OPTION_LABEL); jobconf.setJarByClass(DistRaid.class); jobconf.setInputFormat(DistRaidInputFormat.class); jobconf.setOutputKeyClass(Text.class); jobconf.setOutputValueClass(Text.class); jobconf.setMapperClass(DistRaidMapper.class); jobconf.setNumReduceTasks(0); return jobconf; } /** Add paths to be raided */ public void addRaidPaths(PolicyInfo info, List<EncodingCandidate> paths) { raidPolicyPathPairList.add(new RaidPolicyPathPair(info, paths)); } /** Calculate how many maps to run. */ private static int getMapCount(int srcCount) { int numMaps = (int) (srcCount / opPerMap); return Math.max(numMaps, maxMapsPerNode); } /** Invokes a map-reduce job do parallel raiding. * @return true if the job was started, false otherwise */ public boolean startDistRaid() throws IOException { assert(raidPolicyPathPairList.size() > 0); if (setup()) { this.jobClient = new JobClient(jobconf); this.runningJob = this.jobClient.submitJob(jobconf); /* added by RH for test Oct 8th, 2014 begins */ if (jobconf.getEncoding()){ LOG.info("startDistRaid(): config successed"); } else { LOG.info("startDistRaid(): config failed"); } /* added by RH for test Oct 8th, 2014 ends */ LOG.info("Job Started " + runningJob.getID()); this.startTime = System.currentTimeMillis(); return true; } return false; } /** * Get the URL of the current running job * @return the tracking URL */ public String getJobTrackingURL() { if (runningJob == null) return null; return runningJob.getTrackingURL(); } /** Checks if the map-reduce job has completed. * * @return true if the job completed, false otherwise. * @throws IOException */ public boolean checkComplete() throws IOException { JobID jobID = runningJob.getID(); if (runningJob.isComplete()) { // delete job directory final String jobdir = jobconf.get(JOB_DIR_LABEL); if (jobdir != null) { final Path jobpath = new Path(jobdir); jobpath.getFileSystem(jobconf).delete(jobpath, true); } if (runningJob.isSuccessful()) { LOG.info("Job Complete(Succeeded): " + jobID); } else { LOG.info("Job Complete(Failed): " + jobID); } raidPolicyPathPairList.clear(); Counters ctrs = runningJob.getCounters(); if (ctrs != null) { RaidNodeMetrics metrics = RaidNodeMetrics.getInstance(RaidNodeMetrics.DEFAULT_NAMESPACE_ID); if (ctrs.findCounter(Counter.FILES_FAILED) != null) { long filesFailed = ctrs.findCounter(Counter.FILES_FAILED).getValue(); metrics.raidFailures.inc(filesFailed); } long slotSeconds = ctrs.findCounter( JobInProgress.Counter.SLOTS_MILLIS_MAPS).getValue() / 1000; metrics.raidSlotSeconds.inc(slotSeconds); } return true; } else { String report = (" job " + jobID + " map " + StringUtils.formatPercent(runningJob.mapProgress(), 0)+ " reduce " + StringUtils.formatPercent(runningJob.reduceProgress(), 0)); if (!report.equals(lastReport)) { LOG.info(report); lastReport = report; } TaskCompletionEvent[] events = runningJob.getTaskCompletionEvents(jobEventCounter); jobEventCounter += events.length; for(TaskCompletionEvent event : events) { if (event.getTaskStatus() == TaskCompletionEvent.Status.FAILED) { LOG.info(" Job " + jobID + " " + event.toString()); } } return false; } } public void killJob() throws IOException { runningJob.killJob(); } public void cleanUp() { for (Codec codec: Codec.getCodecs()) { Path tmpdir = new Path(codec.tmpParityDirectory, this.getJobID()); try { FileSystem fs = tmpdir.getFileSystem(jobconf); if (fs.exists(tmpdir)) { fs.delete(tmpdir, true); } } catch (IOException ioe) { LOG.error("Fail to delete " + tmpdir, ioe); } } } public boolean successful() throws IOException { return runningJob.isSuccessful(); } private void estimateSavings() { for (RaidPolicyPathPair p : raidPolicyPathPairList) { Codec codec = Codec.getCodec(p.policy.getCodecId()); int stripeSize = codec.stripeLength; int paritySize = codec.parityLength; int targetRepl = Integer.parseInt(p.policy.getProperty("targetReplication")); int parityRepl = Integer.parseInt(p.policy.getProperty("metaReplication")); for (EncodingCandidate st : p.srcPaths) { long saving = RaidNode.savingFromRaidingFile( st, stripeSize, paritySize, targetRepl, parityRepl); totalSaving += saving; } } } /** * set up input file which has the list of input files. * * @return boolean * @throws IOException */ private boolean setup() throws IOException { estimateSavings(); final String randomId = getRandomId(); JobClient jClient = new JobClient(jobconf); Path jobdir = new Path(jClient.getSystemDir(), NAME + "_" + randomId); LOG.info(JOB_DIR_LABEL + "=" + jobdir); jobconf.set(JOB_DIR_LABEL, jobdir.toString()); Path log = new Path(jobdir, "_logs"); // The control file should have small size blocks. This helps // in spreading out the load from mappers that will be spawned. jobconf.setInt("dfs.blocks.size", OP_LIST_BLOCK_SIZE); FileOutputFormat.setOutputPath(jobconf, log); LOG.info("log=" + log); // create operation list FileSystem fs = jobdir.getFileSystem(jobconf); Path opList = new Path(jobdir, "_" + OP_LIST_LABEL); jobconf.set(OP_LIST_LABEL, opList.toString()); int opCount = 0, synCount = 0; SequenceFile.Writer opWriter = null; try { opWriter = SequenceFile.createWriter(fs, jobconf, opList, Text.class, PolicyInfo.class, SequenceFile.CompressionType.NONE); for (RaidPolicyPathPair p : raidPolicyPathPairList) { // If a large set of files are Raided for the first time, files // in the same directory that tend to have the same size will end up // with the same map. This shuffle mixes things up, allowing a better // mix of files. java.util.Collections.shuffle(p.srcPaths); /* Added by RH Oct 30th 2014 begins */ Collections.sort(p.srcPaths); /* Added by RH Oct 30th 2014 ends */ for (EncodingCandidate ec : p.srcPaths) { opWriter.append(new Text(ec.toString()), p.policy); opCount++; if (++synCount > SYNC_FILE_MAX) { opWriter.sync(); synCount = 0; } } } } finally { if (opWriter != null) { opWriter.close(); } fs.setReplication(opList, OP_LIST_REPLICATION); // increase replication for control file } raidPolicyPathPairList.clear(); jobconf.setInt(OP_COUNT_LABEL, opCount); LOG.info("Number of files=" + opCount); jobconf.setNumMapTasks(getMapCount(opCount)); LOG.info("jobName= " + jobName + " numMapTasks=" + jobconf.getNumMapTasks()); return opCount != 0; } public long getStartTime() { return this.startTime; } public String toHtmlRow() { return JspUtils.tr( JspUtils.td( JspUtils.link( runningJob.getID().toString(), runningJob.getTrackingURL())) + JspUtils.td(runningJob.getJobName()) + JspUtils.td(StringUtils.humanReadableInt(totalSaving))); } public static String htmlRowHeader() { return JspUtils.tr( JspUtils.td("Job ID") + JspUtils.td("Name") + JspUtils.td("Estimated Saving")); } public Counters getCounters() throws IOException{ return this.runningJob.getCounters(); } public String getJobID() { return this.runningJob.getID().toString(); } }
// This file is part of the OpenNMS(R) Application. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // and included code are below. // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // This program is free software; you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // For more information contact: package org.opennms.netmgt.mock; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Properties; import junit.framework.AssertionFailedError; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.Level; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.spi.LoggingEvent; /** * @author brozow */ public class MockLogAppender extends AppenderSkeleton { private static List s_events = null; private static boolean s_loggingSetup = false; private static Level s_logLevel = Level.ALL; public MockLogAppender() { super(); resetEvents(); resetLogLevel(); } public synchronized void doAppend(LoggingEvent event) { super.doAppend(event); receivedLogLevel(event.getLevel()); } protected void append(LoggingEvent event) { s_events.add(event); } public void close() { } public boolean requiresLayout() { return false; } public static void resetEvents() { s_events = Collections.synchronizedList(new LinkedList()); } public static LoggingEvent[] getEvents() { return (LoggingEvent[]) s_events.toArray(new LoggingEvent[0]); } public static LoggingEvent[] getEventsGreaterOrEqual(Level level) { LinkedList matching = new LinkedList(); synchronized (s_events) { for (Iterator i = s_events.iterator(); i.hasNext(); ) { LoggingEvent event = (LoggingEvent) i.next(); if (event.getLevel().isGreaterOrEqual(level)) { matching.add(event); } } } return (LoggingEvent[]) matching.toArray(new LoggingEvent[0]); } public static void setupLogging() { setupLogging(true); } public static void setupLogging(boolean toConsole) { resetLogLevel(); if (!s_loggingSetup) { String level = System.getProperty("mock.logLevel", "DEBUG"); Properties logConfig = new Properties(); String consoleAppender = (toConsole ? ", CONSOLE" : ""); logConfig.put("log4j.appender.CONSOLE", "org.apache.log4j.ConsoleAppender"); logConfig.put("log4j.appender.CONSOLE.layout", "org.apache.log4j.PatternLayout"); logConfig.put("log4j.appender.CONSOLE.layout.ConversionPattern", "%d %-5p [%t] %c: %m%n"); logConfig.put("log4j.appender.MOCK", "org.opennms.netmgt.mock.MockLogAppender"); logConfig.put("log4j.appender.MOCK.layout", "org.apache.log4j.PatternLayout"); logConfig.put("log4j.appender.MOCK.layout.ConversionPattern", "%-5p [%t] %c: %m%n"); logConfig.put("log4j.rootCategory", level+consoleAppender+", MOCK"); logConfig.put("log4j.org.snmp4j", "ERROR"+consoleAppender+", MOCK"); PropertyConfigurator.configure(logConfig); } } public static void receivedLogLevel(Level level) { if (level.isGreaterOrEqual(s_logLevel)) { s_logLevel = level; } } public static void resetLogLevel() { s_logLevel = Level.ALL; } public static boolean noWarningsOrHigherLogged() { return Level.INFO.isGreaterOrEqual(s_logLevel); } public static void assertNotGreaterOrEqual(Level level) throws AssertionFailedError { try { Thread.sleep(500); } catch (InterruptedException e) { // do nothing } LoggingEvent[] events = getEventsGreaterOrEqual(level); if (events.length == 0) { return; } StringBuffer message = new StringBuffer("Log messages at or greater than the " + "log level " + level.toString() + " received:"); for (int i = 0; i < events.length; i++) { message.append("\n\t[" + events[i].getLevel().toString() + "] " + events[i].getLoggerName() +": " + events[i].getMessage()); } throw new AssertionFailedError(message.toString()); } public static void assertNoWarningsOrGreater() throws AssertionFailedError { assertNotGreaterOrEqual(Level.WARN); } }
/** @file Brain.java * Player agent's central logic and memory center. * * @author Team F(utility) */ package futility; import java.util.ArrayDeque; import java.util.HashMap; import java.util.LinkedList; /** * This class contains the player's sensory data parsing and strategy computation algorithms. */ public class Brain implements Runnable { /** * Enumerator representing the possible strategies that may be used by this * player agent. * * DASH_AROUND_THE_FIELD_CLOCKWISE tells the player to dash around * the field boundaries clockwise. * * DASH_TOWARDS_THE_BALL_AND KICK implements a simple soccer strategy: * 1. Run towards the ball. * 2. Rotate around it until you can see the opponent's goal. * 3. Kick the ball towards said goal. * * LOOK_AROUND tells the player to look around in a circle. * * GET_BETWEEN_BALL_AND_GOAL is pretty self explanatory */ public enum Strategy { PRE_KICK_OFF_POSITION, PRE_KICK_OFF_ANGLE, DRIBBLE_KICK, ACTIVE_INTERCEPT, DASH_AROUND_THE_FIELD_CLOCKWISE, DASH_TOWARDS_BALL_AND_KICK, LOOK_AROUND, GET_BETWEEN_BALL_AND_GOAL, PRE_FREE_KICK_POSITION, PRE_CORNER_KICK_POSITION, TEST_TURNS } // MEMBER VARIABLES Client client; Player player; public int time; public PlayerRole.Role role; // Self info & Play mode private String playMode; private SenseInfo curSenseInfo, lastSenseInfo; public AccelerationVector acceleration; public VelocityVector velocity; private boolean isPositioned = false; HashMap<String, FieldObject> fieldObjects = new HashMap<String, FieldObject>(100); ArrayDeque<String> hearMessages = new ArrayDeque<String>(); LinkedList<Player> lastSeenOpponents = new LinkedList<Player>(); LinkedList<Settings.RESPONSE>responseHistory = new LinkedList<Settings.RESPONSE>(); private long timeLastSee = 0; private long timeLastSenseBody = 0; private int lastRan = -1; private Strategy currentStrategy = Strategy.LOOK_AROUND; private boolean updateStrategy = true; // CONSTRUCTORS /** * This is the primary constructor for the Brain class. * * @param player a back-reference to the invoking player * @param client the server client by which to send commands, etc. */ public Brain(Player player, Client client) { this.player = player; this.client = client; this.curSenseInfo = new SenseInfo(); this.lastSenseInfo = new SenseInfo(); this.velocity = new VelocityVector(); this.acceleration = new AccelerationVector(); // Load the HashMap for (int i = 0; i < Settings.STATIONARY_OBJECTS.length; i++) { StationaryObject object = Settings.STATIONARY_OBJECTS[i]; //client.log(Log.DEBUG, String.format("Adding %s to my HashMap...", object.id)); fieldObjects.put(object.id, object); } // Load the response history this.responseHistory.add(Settings.RESPONSE.NONE); this.responseHistory.add(Settings.RESPONSE.NONE); } // GAME LOGIC /** * Returns this player's acceleration along the x axis. Shortcut function. Remember that * accelerations are usually reset to 0 by the soccer server at the beginning of each time * step. * * @return this player's acceleration along the x axis */ private final double accelX() { return this.acceleration.getX(); } /** * Returns this player's acceleration along the y axis. Shortcut function. * * @return this player's acceleration along the y axis */ private final double accelY() { return this.acceleration.getY(); } /** * Returns the direction, in radians, of the player at the current time. */ private final double dir() { return Math.toRadians(this.player.direction.getDirection()); } /** * Assesses the utility of a strategy for the current time step. * * @param strategy the strategy to assess the utility of * @return an assessment of the strategy's utility in the range [0.0, 1.0] */ private final double assessUtility(Strategy strategy) { double utility = 0; switch (strategy) { case PRE_FREE_KICK_POSITION: case PRE_CORNER_KICK_POSITION: case PRE_KICK_OFF_POSITION: // Check play mode, reposition as necessary. if ( canUseMove() ) utility = 1 - (isPositioned ? 1 : 0); break; case PRE_KICK_OFF_ANGLE: if ( isPositioned ) { utility = this.player.team.side == 'r' ? ( this.canSee("(b)") ? 0.0 : 1.0 ) : 0.0; } break; case DRIBBLE_KICK: // Unimplemented Rectangle OPP_PENALTY_AREA = ( this.player.team.side == 'l' ) ? Settings.PENALTY_AREA_RIGHT : Settings.PENALTY_AREA_LEFT; // If the agent is a goalie, don't dribble! // If we're in the opponent's strike zone, don't dribble! Go for score! if ( this.player.isGoalie || this.player.inRectangle(OPP_PENALTY_AREA) ) { utility = 0.0; } else { utility = ( this.canKickBall() && this.canSee( this.player.getOpponentGoalId()) ) ? 0.95 : 0.0; } break; case DASH_AROUND_THE_FIELD_CLOCKWISE: utility = 0.93; break; case DASH_TOWARDS_BALL_AND_KICK: if (this.role == PlayerRole.Role.STRIKER) { utility = 0.95; } else { // Utility is high if the player is within ~ 5.0 meters of the ball utility = Math.min(0.95, Math.pow(this.getOrCreate("(b)").curInfo.distance / 5.0, -1.0)); } break; case LOOK_AROUND: if (this.player.position.getPosition().isUnknown()) { utility = 1.0; } else { utility = 1 - this.player.position.getConfidence(this.time); } break; case GET_BETWEEN_BALL_AND_GOAL: FieldObject ball = this.getOrCreate("(b)"); // estimate our confidence of where the ball and the player are on the field double ballConf = ball.position.getConfidence(this.time); double playerConf = this.player.position.getConfidence(this.time); double conf = (ballConf + playerConf) / 2; double initial = 1; if (this.player.team.side == Settings.LEFT_SIDE) { if (ball.position.getX() < this.player.position.getX()) { initial = 0.6; } else { initial = 0.9; } } else { if (ball.position.getX() > this.player.position.getX()) { initial = 0.6; } else { initial = 0.9; } } if (this.role == PlayerRole.Role.GOALIE || this.role == PlayerRole.Role.LEFT_DEFENDER || this.role == PlayerRole.Role.RIGHT_DEFENDER) { initial *= 1; } else { initial *= 0.25; } if (!this.canSee("(b)")) { initial = 0; } utility = initial * conf; break; case TEST_TURNS: if (this.currentStrategy == Strategy.TEST_TURNS && !this.updateStrategy) { utility = 0.0; } else { utility = 0.0; } break; default: utility = 0; break; } return utility; } /** * Checks if the play mode allows Move commands * * @return true if move commands can be issued. */ private final boolean canUseMove() { return ( playMode.equals( "before_kick_off" ) || playMode.startsWith( "goal_r_") || playMode.startsWith( "goal_l_" ) || playMode.startsWith( "free_kick_" ) || playMode.startsWith( "corner_kick_" ) ); } /** * A rough estimate of whether the player can kick the ball, dependent * on its distance to the ball and whether it is inside the playing field. * * @return true if the player is on the field and within kicking distance */ public final boolean canKickBall() { if (!player.inRectangle(Settings.FIELD)) { return false; } FieldObject ball = this.getOrCreate("(b)"); if (ball.curInfo.time != time) { return false; } return ball.curInfo.distance < Futil.kickable_radius(); } /** * True if and only if the ball was seen in the most recently-parsed 'see' message. */ public final boolean canSee(String id) { if (!this.fieldObjects.containsKey(id)) { Log.e("Can't see " + id + "!"); return false; } FieldObject obj = this.fieldObjects.get(id); return obj.curInfo.time == this.time; } /** * Accelerates the player in the direction of its body. * * @param power the power of the acceleration (0 to 100) */ private final void dash(double power) { // Update this player's acceleration this.acceleration.addPolar(this.dir(), this.effort()); this.client.sendCommand(Settings.Commands.DASH, Double.toString(power)); } /** * Accelerates the player in the direction of its body, offset by the given * angle. * * @param power the power of the acceleration (0 to 100) * @param offset an offset to be applied to the player's direction, * yielding the direction of acceleration */ public final void dash(double power, double offset) { this.acceleration.addPolar(this.dir() + offset, this.edp(power)); client.sendCommand(Settings.Commands.DASH, Double.toString(power), Double.toString(offset)); } /** * Determines the strategy with the current highest utility. * * @return the strategy this brain thinks is optimal for the current time step */ private final Strategy determineOptimalStrategy() { Strategy optimalStrategy = this.currentStrategy; if (this.updateStrategy) { double bestUtility = 0; for (Strategy strategy : Strategy.values()) { double utility = this.assessUtility(strategy); if (utility > bestUtility) { bestUtility = utility; optimalStrategy = strategy; } } } return optimalStrategy; } /** * Returns this player's effective dash power. Refer to the soccer server manual for more information. * * @return this player's effective dash power */ private final double edp(double power) { return this.effort() * Settings.DASH_POWER_RATE * power; } /** * Returns an effort value for this player. If one wasn't received this time step, we guess. */ private final double effort() { return this.curSenseInfo.effort; } /** * Executes a strategy for the player in the current time step. * * @param strategy the strategy to execute */ private final void executeStrategy(Strategy strategy) { FieldObject ball = this.getOrCreate("(b)"); // Opponent goal FieldObject opGoal = this.getOrCreate(this.player.getOpponentGoalId()); // Our goal FieldObject ourGoal = this.getOrCreate(this.player.getGoalId()); switch (strategy) { case PRE_FREE_KICK_POSITION: if (playMode.equals("free_kick_l")) { if (this.player.team.side == Settings.LEFT_SIDE) { //TODO } else { //TODO } this.move(Settings.FREE_KICK_L_FORMATION[player.number]); } else { if (this.player.team.side == Settings.LEFT_SIDE) { //TODO } else { //TODO } this.move(Settings.FREE_KICK_R_FORMATION[player.number]); } this.isPositioned = true; // Since we have now moved back into formation, derivatives // strategies such as LOOK_AROUND should become dominant. break; case PRE_CORNER_KICK_POSITION: if (playMode.equals("corner_kick_l")) { if (this.player.team.side == Settings.LEFT_SIDE) { //TODO } else { //TODO } this.move(Settings.CORNER_KICK_L_FORMATION[player.number]); } else { if (this.player.team.side == Settings.LEFT_SIDE) { //TODO } else { //TODO } this.move(Settings.CORNER_KICK_R_FORMATION[player.number]); } this.isPositioned = true; // Since we have now moved back into formation, derivatives // strategies such as LOOK_AROUND should become dominant. break; case PRE_KICK_OFF_POSITION: this.move(Settings.FORMATION[player.number]); this.isPositioned = true; // Since we have now moved back into formation, derivatives // strategies such as LOOK_AROUND should become dominant. break; case PRE_KICK_OFF_ANGLE: this.turn(30); break; case DRIBBLE_KICK: /* * Find a dribble angle, weighted by presence of opponents. * Determine dribble velocity based on current velocity. * Dribble! */ // Predict next position: Vector2D v_new = Futil.estimatePositionOf(this.player, 2, this.time).getPosition().asVector(); Vector2D v_target = v_new.add( findDribbleAngle() ); Vector2D v_ball = v_target.add( new Vector2D( -1 * ball.position.getX(), -1 * ball.position.getY() ) ); double traj_power = Math.min(Settings.PLAYER_PARAMS.POWER_MAX, ( v_ball.magnitude() / (1 + Settings.BALL_PARAMS.BALL_DECAY ) ) * 10); // values of 1 or 2 do not give very useful kicks. // Kick! Log.i("Kick trajectory power: " + traj_power); kick( traj_power, Futil.simplifyAngle( Math.toDegrees(v_ball.direction()) ) ); break; case DASH_AROUND_THE_FIELD_CLOCKWISE: double x = player.position.getPosition().getX(); double y = player.position.getPosition().getY(); double targetDirection = 0; if (player.inRectangle(Settings.FIELD)) { targetDirection = -90; } // Then run around clockwise between the physical boundary and the field else if (y <= Settings.FIELD.getTop() && x <= Settings.FIELD.getRight()) { targetDirection = 0; } else if (x >= Settings.FIELD.getRight() && y <= Settings.FIELD.getBottom()) { targetDirection = 90; } else if (y >= Settings.FIELD.getBottom() && x >= Settings.FIELD.getLeft()) { targetDirection = 180; } else if (x <= Settings.FIELD.getLeft() && y >= Settings.FIELD.getTop()) { targetDirection = -90; } else { Log.e("Strategy " + strategy + " doesn't know how to handle position " + this.player.position.getPosition().render() + "."); } double offset = Math.abs(this.player.relativeAngleTo(targetDirection)); if (offset > 10) { this.turnTo(targetDirection); } else { this.dash(50, this.player.relativeAngleTo(targetDirection)); } break; case DASH_TOWARDS_BALL_AND_KICK: Log.d("Estimated ball position: " + ball.position.render(this.time)); Log.d("Estimated opponent goal position: " + opGoal.position.render(this.time)); if (this.canKickBall()) { if (this.canSee(this.player.getOpponentGoalId())) { kick(100.0, this.player.relativeAngleTo(opGoal)); } else { dash(30.0, 90.0); } } else if (ball.position.getConfidence(this.time) > 0.1) { double approachAngle; approachAngle = Futil.simplifyAngle(this.player.relativeAngleTo(ball)); if (Math.abs(approachAngle) > 10) { this.turn(approachAngle); } else { dash(50.0, approachAngle); } } else { turn(7.0); } break; case LOOK_AROUND: turn(7); break; case GET_BETWEEN_BALL_AND_GOAL: double xmid = (ball.position.getX() + ourGoal.position.getX()) / 2; double ymid = (ball.position.getY() + ourGoal.position.getY()) / 2; Point midpoint = new Point(xmid, ymid); this.moveTowards(midpoint); break; case TEST_TURNS: turn(7.0); break; default: break; } } /** * Finds the optimum angle to kick the ball toward within a kickable * area. * * @param p Point to build angle from * @return the vector to dribble toward. */ private final Vector2D findDribbleAngle() { // TODO STUB: Need algorithm for a weighted dribble angle. double d_length = Math.max(1.0, Futil.kickable_radius() ); // 5.0 is arbitrary in case nothing is visible; attempt to kick // toward the lateral center of the field. double d_angle = 5.0 * -1.0 * Math.signum( this.player.position.getY() ); // If opponents are visible, try to kick away from them. if ( !lastSeenOpponents.isEmpty() ) { double weight = 0.0d; double w_angle = 0.0d; for ( Player i : lastSeenOpponents ) { double i_angle = player.relativeAngleTo(i); double new_weight = Math.max(weight, Math.min(1.0, 1 / player.distanceTo(i) * Math.abs( 1 / ( i_angle == 0.0 ? 1.0 : i_angle ) ) ) ); if ( new_weight > weight ) w_angle = i_angle; } // Keep the angle within [-90,90]. Kick forward, not backward! d_angle = Math.max( Math.abs( w_angle ) - 180, -90 ) * Math.signum( w_angle ); } // Otherwise kick toward the goal. else if ( this.canSee( this.player.getOpponentGoalId() ) ) d_angle += this.player.relativeAngleTo( this.getOrCreate(this.player.getOpponentGoalId())); Log.i("Dribble angle chosen: " + d_angle); Vector2D d_vec = new Vector2D(0.0, 0.0); d_vec = d_vec.addPolar(Math.toRadians(d_angle), d_length); return d_vec; /* * Proposed algorithm: * * Finding highest weight opponent: * W_i = ( 1 / opponent_distance ) * abs( 1 / opponent_angle ) ) * * Finding RELATIVE angle: * d_angle = max( abs( Opp_w_relative_angle ) - 180, -90 ) * * signum( Opp_w_relative_angle ) */ } /** * Gets a field object from fieldObjects, or creates it if it doesn't yet exist. * * @param id the object's id * @return the field object */ private final FieldObject getOrCreate(String id) { if (this.fieldObjects.containsKey(id)) { return this.fieldObjects.get(id); } else { return FieldObject.create(id); } } /** * Infers the position and direction of this brain's associated player given two boundary flags * on the same side seen in the current time step. * * @param o1 the first flag * @param o2 the second flag */ private final void inferPositionAndDirection(FieldObject o1, FieldObject o2) { // x1, x2, y1 and y2 are relative Cartesian coordinates to the flags double x1 = Math.cos(Math.toRadians(o1.curInfo.direction)) * o1.curInfo.distance; double y1 = Math.sin(Math.toRadians(o1.curInfo.direction)) * o1.curInfo.distance; double x2 = Math.cos(Math.toRadians(o2.curInfo.direction)) * o2.curInfo.distance; double y2 = Math.sin(Math.toRadians(o2.curInfo.direction)) * o2.curInfo.distance; double direction = -Math.toDegrees(Math.atan((y2 - y1) / (x2 - x1))); // Need to reverse the direction if looking closer to west and using horizontal boundary flags if (o1.position.getY() == o2.position.getY()) { if (Math.signum(o2.position.getX() - o1.position.getX()) != Math.signum(x2 - x1)) { direction += 180.0; } } // Need to offset the direction by +/- 90 degrees if using vertical boundary flags else if (o1.position.getX() == o1.position.getX()) { if (Math.signum(o2.position.getY() - o1.position.getY()) != Math.signum(x2 - x1)) { direction += 270.0; } else { direction += 90.0; } } this.player.direction.update(Futil.simplifyAngle(direction), 0.95, this.time); double x = o1.position.getX() - o1.curInfo.distance * Math.cos(Math.toRadians(direction + o1.curInfo.direction)); double y = o1.position.getY() - o1.curInfo.distance * Math.sin(Math.toRadians(direction + o1.curInfo.direction)); double distance = this.player.position.getPosition().distanceTo(new Point(x, y)); this.player.position.update(x, y, 0.95, this.time); } /** * Moves the player to the specified coordinates (server coords). * * @param p the Point object to pass coordinates with (must be in server coordinates). */ public void move(Point p) { move(p.getX(), p.getY()); } /** * Moves the player to the specified coordinates (server coords). * * @param x x-coordinate * @param y y-coordinate */ public void move(double x, double y) { client.sendCommand(Settings.Commands.MOVE, Double.toString(x), Double.toString(y)); } /** * Overrides the strategy selection system. Used in tests. */ public void overrideStrategy(Strategy strategy) { this.currentStrategy = strategy; this.updateStrategy = false; } /** * Kicks the ball in the direction of the player. * * @param power the level of power with which to kick (0 to 100) */ public void kick(double power) { client.sendCommand(Settings.Commands.KICK, Double.toString(power)); } /** * Kicks the ball in the player's direction, offset by the given angle. * * @param power the level of power with which to kick (0 to 100) * @param offset an angle in degrees to be added to the player's direction, yielding the direction of the kick */ public void kick(double power, double offset) { client.sendCommand(Settings.Commands.KICK, Double.toString(power), Double.toString(offset)); } /** * Parses a message from the soccer server. This method is called whenever * a message from the server is received. * * @param message the message (string), exactly as it was received */ public void parseMessage(String message) { long timeReceived = System.currentTimeMillis(); message = Futil.sanitize(message); // Handle `sense_body` messages if (message.startsWith("(sense_body")) { curSenseInfo.copy(lastSenseInfo); curSenseInfo.reset(); this.timeLastSenseBody = timeReceived; curSenseInfo.time = Futil.extractTime(message); this.time = curSenseInfo.time; // TODO better nested parentheses parsing logic; perhaps // reconcile with Patrick's parentheses logic? Log.d("Received a `sense_body` message at time step " + time + "."); String parts[] = message.split("\\("); for ( String i : parts ) // for each structured argument: { // Clean the string, and break it down into the base arguments. String nMsg = i.split("\\)")[0].trim(); if ( nMsg.isEmpty() ) continue; String nArgs[] = nMsg.split("\\s"); // Check for specific argument types; ignore unknown arguments. if ( nArgs[0].contains("view_mode") ) { // Player's current view mode curSenseInfo.viewQuality = nArgs[1]; curSenseInfo.viewWidth = nArgs[2]; } else if ( nArgs[0].contains("stamina") ) { // Player's stamina data curSenseInfo.stamina = Double.parseDouble(nArgs[1]); curSenseInfo.effort = Double.parseDouble(nArgs[2]); curSenseInfo.staminaCapacity = Double.parseDouble(nArgs[3]); } else if ( nArgs[0].contains("speed") ) { // Player's speed data curSenseInfo.amountOfSpeed = Double.parseDouble(nArgs[1]); curSenseInfo.directionOfSpeed = Double.parseDouble(nArgs[2]); // Update velocity variable double dir = this.dir() + Math.toRadians(curSenseInfo.directionOfSpeed); this.velocity.setPolar(dir, curSenseInfo.amountOfSpeed); } else if ( nArgs[0].contains("head_angle") ) { // Player's head angle curSenseInfo.headAngle = Double.parseDouble(nArgs[1]); } else if ( nArgs[0].contains("ball") || nArgs[0].contains("player") || nArgs[0].contains("post") ) { // COLLISION flags; limitation of this loop approach is we // can't handle nested parentheses arguments well. // Luckily these flags only occur in the collision structure. curSenseInfo.collision = nArgs[0]; } } // If the brain has responded to two see messages in a row, it's time to respond to a sense_body. if (this.responseHistory.get(0) == Settings.RESPONSE.SEE && this.responseHistory.get(1) == Settings.RESPONSE.SEE) { this.run(); this.responseHistory.push(Settings.RESPONSE.SENSE_BODY); this.responseHistory.removeLast(); } } // Handle `hear` messages else if (message.startsWith("(hear")) { String parts[] = message.split("\\s"); this.time = Integer.parseInt(parts[1]); if ( parts[2].startsWith("s") || parts[2].startsWith("o") || parts[2].startsWith("c") ) { // TODO logic for self, on-line coach, and trainer coach. // Self could potentially be for feedback, // On-line coach will require coach language parsing, // And trainer likely will as well. Outside of Sprint #2 scope. return; } else { // Check for a referee message, otherwise continue. String nMsg = parts[3].split("\\)")[0]; // Retrieve the message. if ( nMsg.startsWith("goal_l_") ) nMsg = "goal_l_"; else if ( nMsg.startsWith("goal_r_") ) nMsg = "goal_r_"; if ( parts[2].startsWith("r") // Referee; && Settings.PLAY_MODES.contains(nMsg) ) // Play Mode? { playMode = nMsg; this.isPositioned = false; } else hearMessages.add( nMsg ); } } // Handle `see` messages else if (message.startsWith("(see")) { this.timeLastSee = timeReceived; this.time = Futil.extractTime(message); Log.d("Received `see` message at time step " + this.time); LinkedList<String> infos = Futil.extractInfos(message); lastSeenOpponents.clear(); for (String info : infos) { String id = Futil.extractId(info); if (Futil.isUniqueFieldObject(id)) { FieldObject obj = this.getOrCreate(id); obj.update(this.player, info, this.time); this.fieldObjects.put(id, obj); if ( id.startsWith("(p \"") && !( id.startsWith(this.player.team.name, 4) ) ) lastSeenOpponents.add( (Player)obj ); } } // Immediately run for the current step. Since our computations takes only a few // milliseconds, it's okay to start running over half-way into the 100ms cycle. // That means two out of every three time steps will be executed here. this.run(); // Make sure we stay in sync with the mid-way `see`s if (this.timeLastSee - this.timeLastSenseBody > 30) { this.responseHistory.clear(); this.responseHistory.add(Settings.RESPONSE.SEE); this.responseHistory.add(Settings.RESPONSE.SEE); } else { this.responseHistory.add(Settings.RESPONSE.SEE); this.responseHistory.removeLast(); } } // Handle init messages else if (message.startsWith("(init")) { String[] parts = message.split("\\s"); char teamSide = message.charAt(6); if (teamSide == Settings.LEFT_SIDE) { player.team.side = Settings.LEFT_SIDE; player.otherTeam.side = Settings.RIGHT_SIDE; } else if (teamSide == Settings.RIGHT_SIDE) { player.team.side = Settings.RIGHT_SIDE; player.otherTeam.side = Settings.LEFT_SIDE; } else { // Raise error Log.e("Could not parse teamSide."); } player.number = Integer.parseInt(parts[2]); this.role = Settings.PLAYER_ROLES[this.player.number - 1]; playMode = parts[3].split("\\)")[0]; } else if (message.startsWith("(server_param")) { parseServerParameters(message); } } /** * Parses the initial parameters received from the server. * * @param message the parameters message received from the server */ public void parseServerParameters(String message) { String parts[] = message.split("\\("); for ( String i : parts ) // for each structured argument: { // Clean the string, and break it down into the base arguments. String nMsg = i.split("\\)")[0].trim(); if ( nMsg.isEmpty() ) continue; String nArgs[] = nMsg.split("\\s"); // Check for specific argument types; ignore unknown arguments. if (nArgs[0].startsWith("dash_power_rate")) Settings.setDashPowerRate(Double.parseDouble(nArgs[1])); if ( nArgs[0].startsWith("goal_width") ) Settings.setGoalHeight(Double.parseDouble(nArgs[1])); // Ball arguments: else if ( nArgs[0].startsWith("ball") ) ServerParams_Ball.Builder.dataParser(nArgs); // Player arguments: else if ( nArgs[0].startsWith("player") || nArgs[0].startsWith("min") || nArgs[0].startsWith("max") ) ServerParams_Player.Builder.dataParser(nArgs); } // Rebuild all parameter objects with updated parameters. Settings.rebuildParams(); } /** * Responds for the current time step. */ public void run() { final long startTime = System.currentTimeMillis(); final long endTime; int expectedNextRun = this.lastRan + 1; if (this.time > expectedNextRun) { Log.e("Brain did not run during time step " + expectedNextRun + "."); } this.lastRan = this.time; this.acceleration.reset(); this.updatePositionAndDirection(); this.currentStrategy = this.determineOptimalStrategy(); Log.i("Current strategy: " + this.currentStrategy); this.executeStrategy(this.currentStrategy); Log.d("Estimated player position: " + this.player.position.render(this.time) + "."); Log.d("Estimated player direction: " + this.player.direction.render(this.time) + "."); endTime = System.currentTimeMillis(); final long duration = endTime - startTime; Log.d("Took " + duration + " ms (plus small overhead) to run at time " + this.time + "."); if (duration > 35) { Log.e("Took " + duration + " ms (plus small overhead) to run at time " + this.time + "."); } } /** * Adds the given angle to the player's current direction. * * @param offset an angle in degrees to add to the player's current direction */ public final void turn(double offset) { double moment = Futil.toValidMoment(offset); client.sendCommand(Settings.Commands.TURN, moment); // TODO Potentially take magnitude of offset into account in the // determination of the new confidence in the player's position. player.direction.update(player.direction.getDirection() + moment, 0.95 * player.direction.getConfidence(this.time), this.time); } /** * Updates the player's current direction to be the given direction. * * @param direction angle in degrees, assuming soccer server coordinate system */ public final void turnTo(double direction) { this.turn(this.player.relativeAngleTo(direction)); } /** * Send commands to move the player to a point at maximum power * @param point the point to move to */ private final void moveTowards(Point point){ moveTowards(point, 100d); } /** * Send commands to move the player to a point with the given power * @param point to move towards * @param power to move at */ private final void moveTowards(Point point, double power){ final double x = player.position.getX() - point.getX(); final double y = player.position.getY() - point.getY(); final double theta = Math.toDegrees(Math.atan2(y, x)); turnTo(theta); dash(power); } /** * Updates this this brain's belief about the associated player's position and direction * at the current time step. */ private final void updatePositionAndDirection() { // Infer from the most-recent `see` if it happened in the current time-step for (int i = 0; i < 4; i++) { LinkedList<FieldObject> flagsOnSide = new LinkedList<FieldObject>(); for (String id : Settings.BOUNDARY_FLAG_GROUPS[i]) { FieldObject flag = this.fieldObjects.get(id); if (flag.curInfo.time == this.time) { flagsOnSide.add(flag); } else { //Log.i("Flag " + id + "last updated at time " + flag.info.time + ", not " + this.time); } if (flagsOnSide.size() > 1) { this.inferPositionAndDirection(flagsOnSide.poll(), flagsOnSide.poll()); return; } } } // TODO Handle other cases Log.e("Did not update position or direction at time " + this.time); } /** * Returns this player's x velocity. Shortcut function. * * @return this player's x velocity */ private final double velX() { return this.velocity.getX(); } /** * Returns this player's y velocity. Shortcut function. * * @return this player's y velocity */ private final double velY() { return this.velocity.getY(); } /** * Returns this player's x. * * @return this player's x-coordinate */ private final double x() { return this.player.position.getPosition().getX(); } /** * Returns this player's y. * * @return this player's y coordinate */ private final double y() { return this.player.position.getPosition().getY(); } }
package net.sf.picard.illumina; import net.sf.picard.illumina.parser.*; import net.sf.picard.util.IlluminaUtil; import net.sf.picard.util.Log; import net.sf.picard.util.TabbedTextFileWithHeaderParser; import net.sf.picard.PicardException; import net.sf.picard.cmdline.CommandLineProgram; import net.sf.picard.cmdline.Option; import net.sf.picard.cmdline.StandardOptionDefinitions; import net.sf.picard.cmdline.Usage; import net.sf.picard.io.IoUtil; import net.sf.picard.metrics.MetricBase; import net.sf.picard.metrics.MetricsFile; import net.sf.samtools.util.SequenceUtil; import net.sf.samtools.util.StringUtil; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.util.*; import java.text.NumberFormat; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Determine the barcode for each read in an Illumina lane. * For each tile, a file is written to the basecalls directory of the form s_<lane>_<tile>_barcode.txt. * An output file contains a line for each read in the tile, aligned with the regular basecall output * The output file contains the following tab-separated columns: * - read subsequence at barcode position * - Y or N indicating if there was a barcode match * - matched barcode sequence (empty if read did not match one of the barcodes). If there is no match * but we're close to the threshold of calling it a match we output the barcode that would have been * matched but in lower case * * @author jburke@broadinstitute.org */ public class ExtractIlluminaBarcodes extends CommandLineProgram { // The following attributes define the command-line arguments @Usage public String USAGE = getStandardUsagePreamble() + "Determine the barcode for each read in an Illumina lane.\n" + "For each tile, a file is written to the basecalls directory of the form s_<lane>_<tile>_barcode.txt." + "An output file contains a line for each read in the tile, aligned with the regular basecall output\n" + "The output file contains the following tab-separated columns: \n" + " * read subsequence at barcode position\n" + " * Y or N indicating if there was a barcode match\n" + " * matched barcode sequence\n" + "Note that the order of specification of barcodes can cause arbitrary differences in output for poorly matching barcodes.\n\n"; @Option(doc="The Illumina basecalls output directory. ", shortName="B") public File BASECALLS_DIR; @Option(doc="Where to write _barcode.txt files. By default, these are written to BASECALLS_DIR.", optional = true) public File OUTPUT_DIR; @Option(doc="Lane number. ", shortName= StandardOptionDefinitions.LANE_SHORT_NAME) public Integer LANE; @Option(doc=IlluminaBasecallsToSam.READ_STRUCTURE_DOC, shortName="RS") public String READ_STRUCTURE; @Option(doc="Barcode sequence. These must be unique, and all the same length. This cannot be used with reads that " + "have more than one barcode; use BARCODE_FILE in that case. ", mutex = {"BARCODE_FILE"}) public List<String> BARCODE = new ArrayList<String>(); @Option(doc="Tab-delimited file of barcode sequences, barcode name and and optionally library name. " + "Barcodes must be unique, and all the same length. Column headers must be 'barcode_sequence_1', " + "'barcode_sequence_2' (optional), 'barcode_name', and 'library_name'.", mutex = {"BARCODE"}) public File BARCODE_FILE; @Option(doc="Per-barcode and per-lane metrics written to this file.", shortName = StandardOptionDefinitions.METRICS_FILE_SHORT_NAME) public File METRICS_FILE; @Option(doc="Maximum mismatches for a barcode to be considered a match.") public int MAX_MISMATCHES = 1; @Option(doc="Minimum difference between number of mismatches in the best and second best barcodes for a barcode to be considered a match.") public int MIN_MISMATCH_DELTA = 1; @Option(doc="Maximum allowable number of no-calls in a barcode read before it is considered unmatchable.") public int MAX_NO_CALLS = 2; @Option(shortName="Q", doc="Minimum base quality. Any barcode bases falling below this quality will be considered a mismatch even in the bases match!") public int MINIMUM_BASE_QUALITY = 0; @Option(shortName="GZIP", doc="Compress output s_l_t_barcode.txt files using gzip and append a .gz extension to the filenames.") public boolean COMPRESS_OUTPUTS = false; @Option(doc = "Run this many PerTileBarcodeExtractors in parallel. If NUM_PROCESSORS = 0, number of cores is automatically set to " + "the number of cores available on the machine. If NUM_PROCESSORS < 0 then the number of cores used will be " + "the number available on the machine less NUM_PROCESSORS.") public int NUM_PROCESSORS = 1; private final Log log = Log.getInstance(ExtractIlluminaBarcodes.class); /** The read structure of the actual Illumina Run, i.e. the readStructure of the input data */ private ReadStructure readStructure; /** The read structure of the output cluster data, this may be different from the input readStructure if there are SKIPs in the input readStructure */ private ReadStructure outputReadStructure; private IlluminaDataProviderFactory factory; private final Map<String,BarcodeMetric> barcodeToMetrics = new LinkedHashMap<String,BarcodeMetric>(); private BarcodeMetric noMatchMetric = null; private final NumberFormat tileNumberFormatter = NumberFormat.getNumberInstance(); public ExtractIlluminaBarcodes() { tileNumberFormatter.setMinimumIntegerDigits(4); tileNumberFormatter.setGroupingUsed(false); } @Override protected int doWork() { IoUtil.assertDirectoryIsWritable(BASECALLS_DIR); IoUtil.assertFileIsWritable(METRICS_FILE); if (OUTPUT_DIR == null) { OUTPUT_DIR = BASECALLS_DIR; } IoUtil.assertDirectoryIsWritable(OUTPUT_DIR); // Create BarcodeMetric for counting reads that don't match any barcode final String[] noMatchBarcode = new String[readStructure.barcodes.length()]; int index = 0; for (final ReadDescriptor d : readStructure.descriptors) { if (d.type == ReadType.Barcode) { noMatchBarcode[index++] = StringUtil.repeatCharNTimes('N', d.length); } } noMatchMetric = new BarcodeMetric(null, null, IlluminaUtil.barcodeSeqsToString(noMatchBarcode), noMatchBarcode); final int numProcessors; if (NUM_PROCESSORS == 0) { numProcessors = Runtime.getRuntime().availableProcessors(); } else if (NUM_PROCESSORS < 0) { numProcessors = Runtime.getRuntime().availableProcessors() + NUM_PROCESSORS; } else { numProcessors = NUM_PROCESSORS; } log.info("Processing with " + numProcessors + " PerTileBarcodeExtractor(s)."); final ExecutorService pool = Executors.newFixedThreadPool(numProcessors); final List<PerTileBarcodeExtractor> extractors = new ArrayList<PerTileBarcodeExtractor>(factory.getAvailableTiles().size()); for (final int tile : factory.getAvailableTiles()) { final PerTileBarcodeExtractor extractor = new PerTileBarcodeExtractor(tile, getBarcodeFile(tile)); pool.submit(extractor); extractors.add(extractor); } pool.shutdown(); try { // Wait a while for existing tasks to terminate if (!pool.awaitTermination(6, TimeUnit.HOURS)) { pool.shutdownNow(); // Cancel any still-executing tasks // Wait a while for tasks to respond to being cancelled if (!pool.awaitTermination(60, TimeUnit.SECONDS)) log.error("Pool did not terminate"); return 1; } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); return 2; } log.info("Processed " + extractors.size() + " tiles."); for (final PerTileBarcodeExtractor extractor : extractors) { for (final String key : barcodeToMetrics.keySet()) { barcodeToMetrics.get(key).merge(extractor.getMetrics().get(key)); } noMatchMetric.merge(extractor.getNoMatchMetric()); if (extractor.getException() != null) { log.error("Abandoning metrics calculation because one or more PerTileBarcodeExtractors failed."); return 4; } } // Finish metrics tallying. int totalReads = noMatchMetric.READS; int totalPfReads = noMatchMetric.PF_READS; int totalPfReadsAssigned = 0; for (final BarcodeMetric barcodeMetric : barcodeToMetrics.values()) { totalReads += barcodeMetric.READS; totalPfReads += barcodeMetric.PF_READS; totalPfReadsAssigned += barcodeMetric.PF_READS; } if (totalReads > 0) { noMatchMetric.PCT_MATCHES = noMatchMetric.READS/(double)totalReads; double bestPctOfAllBarcodeMatches = 0; for (final BarcodeMetric barcodeMetric : barcodeToMetrics.values()) { barcodeMetric.PCT_MATCHES = barcodeMetric.READS/(double)totalReads; if (barcodeMetric.PCT_MATCHES > bestPctOfAllBarcodeMatches) { bestPctOfAllBarcodeMatches = barcodeMetric.PCT_MATCHES; } } if (bestPctOfAllBarcodeMatches > 0) { noMatchMetric.RATIO_THIS_BARCODE_TO_BEST_BARCODE_PCT = noMatchMetric.PCT_MATCHES/bestPctOfAllBarcodeMatches; for (final BarcodeMetric barcodeMetric : barcodeToMetrics.values()) { barcodeMetric.RATIO_THIS_BARCODE_TO_BEST_BARCODE_PCT = barcodeMetric.PCT_MATCHES/bestPctOfAllBarcodeMatches; } } } if (totalPfReads > 0) { noMatchMetric.PF_PCT_MATCHES = noMatchMetric.PF_READS/(double)totalPfReads; double bestPctOfAllBarcodeMatches = 0; for (final BarcodeMetric barcodeMetric : barcodeToMetrics.values()) { barcodeMetric.PF_PCT_MATCHES = barcodeMetric.PF_READS/(double)totalPfReads; if (barcodeMetric.PF_PCT_MATCHES > bestPctOfAllBarcodeMatches) { bestPctOfAllBarcodeMatches = barcodeMetric.PF_PCT_MATCHES; } } if (bestPctOfAllBarcodeMatches > 0) { noMatchMetric.PF_RATIO_THIS_BARCODE_TO_BEST_BARCODE_PCT = noMatchMetric.PF_PCT_MATCHES/bestPctOfAllBarcodeMatches; for (final BarcodeMetric barcodeMetric : barcodeToMetrics.values()) { barcodeMetric.PF_RATIO_THIS_BARCODE_TO_BEST_BARCODE_PCT = barcodeMetric.PF_PCT_MATCHES/bestPctOfAllBarcodeMatches; } } } // Calculate the normalized matches if (totalPfReadsAssigned > 0) { final double mean = (double) totalPfReadsAssigned / (double) barcodeToMetrics.values().size(); for (final BarcodeMetric m : barcodeToMetrics.values()) { m.PF_NORMALIZED_MATCHES = m.PF_READS / mean; } } final MetricsFile<BarcodeMetric, Integer> metrics = getMetricsFile(); for (final BarcodeMetric barcodeMetric : barcodeToMetrics.values()) { metrics.addMetric(barcodeMetric); } metrics.addMetric(noMatchMetric); metrics.write(METRICS_FILE); return 0; } /** * Create a barcode filename corresponding to the given tile qseq file. */ private File getBarcodeFile(final int tile) { return new File(OUTPUT_DIR, "s_" + LANE + "_" + tileNumberFormatter.format(tile) + "_barcode.txt" + (COMPRESS_OUTPUTS ? ".gz" : "")); } /** * Validate that POSITION >= 1, and that all BARCODEs are the same length and unique * * @return null if command line is valid. If command line is invalid, returns an array of error message * to be written to the appropriate place. */ @Override protected String[] customCommandLineValidation() { final ArrayList<String> messages = new ArrayList<String>(); /** * In extract illumina barcodes we NEVER want to look at the template reads, therefore replace them with skips because * IlluminaDataProvider and its factory will not open these nor produce ClusterData with the template reads in them, thus reducing * the file IO and value copying done by the data provider */ readStructure = new ReadStructure(READ_STRUCTURE.replaceAll("T", "S")); final IlluminaDataType[] datatypes = (MINIMUM_BASE_QUALITY > 0) ? new IlluminaDataType[] {IlluminaDataType.BaseCalls, IlluminaDataType.PF, IlluminaDataType.QualityScores}: new IlluminaDataType[] {IlluminaDataType.BaseCalls, IlluminaDataType.PF}; factory = new IlluminaDataProviderFactory(BASECALLS_DIR, LANE, readStructure, datatypes); outputReadStructure = factory.getOutputReadStructure(); if (BARCODE_FILE != null) { parseBarcodeFile(messages); } else { final Set<String> barcodes = new HashSet<String>(); for (final String barcode : BARCODE) { if (barcodes.contains(barcode)) { messages.add("Barcode " + barcode + " specified more than once."); } barcodes.add(barcode); final BarcodeMetric metric = new BarcodeMetric(null, null, barcode, new String[]{barcode}); barcodeToMetrics.put(barcode, metric); } } if (barcodeToMetrics.keySet().size() == 0) { messages.add("No barcodes have been specified."); } if (messages.size() == 0) { return null; } return messages.toArray(new String[messages.size()]); } public static void main(final String[] argv) { System.exit(new ExtractIlluminaBarcodes().instanceMain(argv)); } private static final String BARCODE_SEQUENCE_COLUMN = "barcode_sequence"; private static final String BARCODE_SEQUENCE_1_COLUMN = "barcode_sequence_1"; private static final String BARCODE_NAME_COLUMN = "barcode_name"; private static final String LIBRARY_NAME_COLUMN = "library_name"; private void parseBarcodeFile(final ArrayList<String> messages) { final TabbedTextFileWithHeaderParser barcodesParser = new TabbedTextFileWithHeaderParser(BARCODE_FILE); final String sequenceColumn = barcodesParser.hasColumn(BARCODE_SEQUENCE_COLUMN) ? BARCODE_SEQUENCE_COLUMN : barcodesParser.hasColumn(BARCODE_SEQUENCE_1_COLUMN) ? BARCODE_SEQUENCE_1_COLUMN : null; if (sequenceColumn == null) { messages.add(BARCODE_FILE + " does not have " + BARCODE_SEQUENCE_COLUMN + " or " + BARCODE_SEQUENCE_1_COLUMN + " column header"); return; } final boolean hasBarcodeName = barcodesParser.hasColumn(BARCODE_NAME_COLUMN); final boolean hasLibraryName = barcodesParser.hasColumn(LIBRARY_NAME_COLUMN); final int numBarcodes = readStructure.barcodes.length(); final Set<String> barcodes = new HashSet<String>(); for (final TabbedTextFileWithHeaderParser.Row row : barcodesParser) { final String bcStrings[] = new String[numBarcodes]; int barcodeNum = 1; for (final ReadDescriptor rd : readStructure.descriptors) { if (rd.type != ReadType.Barcode) continue; final String header = barcodeNum == 1 ? sequenceColumn : "barcode_sequence_" + String.valueOf(barcodeNum); bcStrings[barcodeNum-1] = row.getField(header); barcodeNum++; } final String bcStr = IlluminaUtil.barcodeSeqsToString(bcStrings); if (barcodes.contains(bcStr)) { messages.add("Barcode " + bcStr + " specified more than once in " + BARCODE_FILE); } barcodes.add(bcStr); final String barcodeName = (hasBarcodeName? row.getField(BARCODE_NAME_COLUMN): ""); final String libraryName = (hasLibraryName? row.getField(LIBRARY_NAME_COLUMN): ""); final BarcodeMetric metric = new BarcodeMetric(barcodeName, libraryName, bcStr, bcStrings); barcodeToMetrics.put(StringUtil.join("", bcStrings), metric); } barcodesParser.close(); } /** * Metrics produced by the ExtractIlluminaBarcodes program that is used to parse data in * the basecalls directory and determine to which barcode each read should be assigned. */ public static class BarcodeMetric extends MetricBase { /** * The barcode (from the set of expected barcodes) for which the following metrics apply. * Note that the "symbolic" barcode of NNNNNN is used to report metrics for all reads that * do not match a barcode. */ public String BARCODE; public String BARCODE_NAME = ""; public String LIBRARY_NAME = ""; /** The total number of reads matching the barcode. */ public int READS = 0; /** The number of PF reads matching this barcode (always less than or equal to READS). */ public int PF_READS = 0; /** The number of all reads matching this barcode that matched with 0 errors or no-calls. */ public int PERFECT_MATCHES = 0; /** The number of PF reads matching this barcode that matched with 0 errors or no-calls. */ public int PF_PERFECT_MATCHES = 0; /** The number of all reads matching this barcode that matched with 1 error or no-call. */ public int ONE_MISMATCH_MATCHES = 0; /** The number of PF reads matching this barcode that matched with 1 error or no-call. */ public int PF_ONE_MISMATCH_MATCHES = 0; /** The percentage of all reads in the lane that matched to this barcode. */ public double PCT_MATCHES = 0d; /** * The rate of all reads matching this barcode to all reads matching the most prevelant barcode. For the * most prevelant barcode this will be 1, for all others it will be less than 1. One over the lowest * number in this column gives you the fold-difference in representation between barcodes. */ public double RATIO_THIS_BARCODE_TO_BEST_BARCODE_PCT = 0d; /** The percentage of PF reads in the lane that matched to this barcode. */ public double PF_PCT_MATCHES = 0d; /** * The rate of PF reads matching this barcode to PF reads matching the most prevelant barcode. For the * most prevelant barcode this will be 1, for all others it will be less than 1. One over the lowest * number in this column gives you the fold-difference in representation of PF reads between barcodes. */ public double PF_RATIO_THIS_BARCODE_TO_BEST_BARCODE_PCT = 0d; /** * The "normalized" matches to each barcode. This is calculated as the number of pf reads matching * this barcode over the sum of all pf reads matching any barcode (excluding orphans). If all barcodes * are represented equally this will be 1. */ public double PF_NORMALIZED_MATCHES; protected byte[][] barcodeBytes; public BarcodeMetric(final String barcodeName, final String libraryName, final String barcodeDisplay, final String[] barcodeSeqs) { this.BARCODE = barcodeDisplay; this.BARCODE_NAME = barcodeName; this.LIBRARY_NAME = libraryName; this.barcodeBytes = new byte[barcodeSeqs.length][]; for (int i = 0; i < barcodeSeqs.length; i++) { barcodeBytes[i] = net.sf.samtools.util.StringUtil.stringToBytes(barcodeSeqs[i]); } } /** * This ctor is necessary for when reading metrics from file */ public BarcodeMetric() { barcodeBytes = null; } /** * Creates a copy of metric initialized with only non-accumulated and non-calculated values set */ public static BarcodeMetric copy(final BarcodeMetric metric) { final BarcodeMetric result = new BarcodeMetric(); result.BARCODE = metric.BARCODE; result.BARCODE_NAME = metric.BARCODE_NAME; result.LIBRARY_NAME = metric.LIBRARY_NAME; result.barcodeBytes = metric.barcodeBytes; return result; } /** * Adds the non-calculated * @param metric */ public void merge(final BarcodeMetric metric) { this.READS += metric.READS; this.PF_READS += metric.PF_READS; this.PERFECT_MATCHES += metric.PERFECT_MATCHES; this.PF_PERFECT_MATCHES += metric.PF_PERFECT_MATCHES; this.ONE_MISMATCH_MATCHES += metric.ONE_MISMATCH_MATCHES; this.PF_ONE_MISMATCH_MATCHES += metric.PF_ONE_MISMATCH_MATCHES; } } /** * Extracts barcodes and accumulates metrics for an entire tile. */ private class PerTileBarcodeExtractor implements Runnable { private final int tile; private final File barcodeFile; private final Map<String,BarcodeMetric> metrics; private final BarcodeMetric noMatch; private Exception exception = null; private final boolean usingQualityScores= MINIMUM_BASE_QUALITY > 0; /** Utility class to hang onto data about the best match for a given barcode */ class BarcodeMatch { boolean matched; String barcode; int mismatches; int mismatchesToSecondBest; } /** * Constructor * @param tile The number of the tile being processed; used for logging only. * @param barcodeFile The file to write the barcodes to */ public PerTileBarcodeExtractor(final int tile, final File barcodeFile) { this.tile = tile; this.barcodeFile = barcodeFile; this.metrics = new LinkedHashMap<String,BarcodeMetric>(barcodeToMetrics.size()); for (final String key : barcodeToMetrics.keySet()) { this.metrics.put(key, BarcodeMetric.copy(barcodeToMetrics.get(key))); } this.noMatch = BarcodeMetric.copy(noMatchMetric); } // These methods return the results of the extraction public synchronized Map<String,BarcodeMetric> getMetrics() { return this.metrics; } public synchronized BarcodeMetric getNoMatchMetric() { return this.noMatch; } public synchronized Exception getException() { return this.exception; } /** * run method which extracts barcodes and accumulates metrics for an entire tile */ synchronized public void run() { log.info("Extracting barcodes for tile " + tile); //Sometimes makeDataProvider takes a while waiting for slow file IO, for each tile the needed set of files //is non-overlapping sets of files so make the data providers in the individual threads for PerTileBarcodeExtractors //so they are not all waiting for each others file operations final IlluminaDataProvider provider = factory.makeDataProvider(Arrays.asList(tile)); //Most likely we have SKIPS in our read structure since we replace all template reads with skips in the input data structure //(see customCommnandLineValidation), therefore we must use the outputReadStructure to index into the output cluster data final int [] barcodeIndices = outputReadStructure.barcodes.getIndices(); final BufferedWriter writer = IoUtil.openFileForBufferedWriting(barcodeFile); try { final byte barcodeSubsequences[][] = new byte[barcodeIndices.length][]; final byte qualityScores[][] = usingQualityScores ? new byte[barcodeIndices.length][] : null; while (provider.hasNext()) { // Extract the barcode from the cluster and write it to the file for the tile final ClusterData cluster = provider.next(); for (int i = 0; i < barcodeIndices.length; i++) { barcodeSubsequences[i] = cluster.getRead(barcodeIndices[i]).getBases(); if (usingQualityScores) qualityScores[i] = cluster.getRead(barcodeIndices[i]).getQualities(); } final boolean passingFilter = cluster.isPf(); final BarcodeMatch match = findBestBarcodeAndUpdateMetrics(barcodeSubsequences, qualityScores, passingFilter, metrics, noMatchMetric); final String yOrN = (match.matched ? "Y" : "N"); for (final byte[] bc : barcodeSubsequences) { writer.write(StringUtil.bytesToString(bc)); } writer.write("\t" + yOrN + "\t" + match.barcode + "\t" + String.valueOf(match.mismatches) + "\t" + String.valueOf(match.mismatchesToSecondBest)); writer.newLine(); } writer.close(); } catch (Exception e) { log.error(e, "Error processing tile ", this.tile); this.exception = e; } } /** * Find the best barcode match for the given read sequence, and accumulate metrics * @param readSubsequences portion of read containing barcode * @param passingFilter PF flag for the current read * @return perfect barcode string, if there was a match within tolerance, or null if not. */ private BarcodeMatch findBestBarcodeAndUpdateMetrics(final byte[][] readSubsequences, final byte[][] qualityScores, final boolean passingFilter, final Map<String, BarcodeMetric> metrics, final BarcodeMetric noMatchBarcodeMetric) { BarcodeMetric bestBarcodeMetric = null; int totalBarcodeReadBases = 0; int numNoCalls = 0; // NoCalls are calculated for all the barcodes combined for (final byte[] bc : readSubsequences) { totalBarcodeReadBases += bc.length; for (final byte b : bc) if (SequenceUtil.isNoCall(b)) ++numNoCalls; } // PIC-506 When forcing all reads to match a single barcode, allow a read to match even if every // base is a mismatch. int numMismatchesInBestBarcode = totalBarcodeReadBases + 1; int numMismatchesInSecondBestBarcode = totalBarcodeReadBases + 1; for (final BarcodeMetric barcodeMetric : metrics.values()) { final int numMismatches = countMismatches(barcodeMetric.barcodeBytes, readSubsequences, qualityScores); if (numMismatches < numMismatchesInBestBarcode) { if (bestBarcodeMetric != null) { numMismatchesInSecondBestBarcode = numMismatchesInBestBarcode; } numMismatchesInBestBarcode = numMismatches; bestBarcodeMetric = barcodeMetric; } else if (numMismatches < numMismatchesInSecondBestBarcode) { numMismatchesInSecondBestBarcode = numMismatches; } } final boolean matched = bestBarcodeMetric != null && numNoCalls <= MAX_NO_CALLS && numMismatchesInBestBarcode <= MAX_MISMATCHES && numMismatchesInSecondBestBarcode - numMismatchesInBestBarcode >= MIN_MISMATCH_DELTA; final BarcodeMatch match = new BarcodeMatch(); // If we have something that's not a "match" but matches one barcode // slightly, we output that matching barcode in lower case if (numNoCalls + numMismatchesInBestBarcode < totalBarcodeReadBases) { match.mismatches = numMismatchesInBestBarcode; match.mismatchesToSecondBest = numMismatchesInSecondBestBarcode; match.barcode = bestBarcodeMetric.BARCODE.toLowerCase().replaceAll(IlluminaUtil.BARCODE_DELIMITER, ""); } else { match.mismatches = totalBarcodeReadBases; match.barcode = ""; } if (matched) { ++bestBarcodeMetric.READS; if (passingFilter) { ++bestBarcodeMetric.PF_READS; } if (numMismatchesInBestBarcode == 0) { ++bestBarcodeMetric.PERFECT_MATCHES; if (passingFilter) { ++bestBarcodeMetric.PF_PERFECT_MATCHES; } } else if (numMismatchesInBestBarcode == 1) { ++bestBarcodeMetric.ONE_MISMATCH_MATCHES; if (passingFilter) { ++bestBarcodeMetric.PF_ONE_MISMATCH_MATCHES; } } match.matched = true; match.barcode = bestBarcodeMetric.BARCODE.replaceAll(IlluminaUtil.BARCODE_DELIMITER, ""); } else { ++noMatchBarcodeMetric.READS; if (passingFilter) { ++noMatchBarcodeMetric.PF_READS; } } return match; } /** * Compare barcode sequence to bases from read * @return how many bases did not match */ private int countMismatches(final byte[][] barcodeBytes, final byte[][] readSubsequence, final byte[][] qualities) { int numMismatches = 0; // Read sequence and barcode length may not be equal, so we just use the shorter of the two for (int j = 0; j < barcodeBytes.length; j++) { final int basesToCheck = Math.min(barcodeBytes[j].length, readSubsequence[j].length); for (int i = 0; i < basesToCheck; ++i) { if (!SequenceUtil.isNoCall(readSubsequence[j][i])) { if (!SequenceUtil.basesEqual(barcodeBytes[j][i], readSubsequence[j][i])) ++numMismatches; else if (qualities != null && qualities[j][i] < MINIMUM_BASE_QUALITY) ++numMismatches; } } } return numMismatches; } } }
package ch.ethz.scu.obit.at; import javax.swing.JOptionPane; import ch.ethz.scu.obit.at.gui.AnnotationToolWindow; import ch.ethz.scu.obit.common.settings.GlobalSettingsManager; /** * AnnotationTool is an application to drive the import of data from the * acquisition stations into openBIS. * @author Aaron Ponti */ public class AnnotationTool { /** * @param args Ignored */ public static void main(String[] args) { // Check whether the application has been set up properly and it is ready // to be used. try { GlobalSettingsManager.isConfigurationValid(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Initialization error", JOptionPane.WARNING_MESSAGE); System.exit(0); } // Open the main window and run the scan in the background javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // Create the Window and scan user's data folder and // openBIS structure. final AnnotationToolWindow w = new AnnotationToolWindow(); // Scan data folder and openBIS w.scan(); } }); } }
package team2.inventory.controller; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Map; import team2.inventory.model.Company; import team2.inventory.model.Item; import team2.inventory.model.Location; import team2.inventory.model.User; /** Tests basic database functionality for MariaDB. * @author James A. Donnell Jr. */ public class DatabaseConnectorTest { /** MariaDB JDBC database prefix. */ private static String prefix = "jdbc:mariadb: /** Database hostname. */ private static String hostname = "warehouse.jdweb.info"; /** Database port. */ private static String port = "3306"; /** Testing all tables in database. * @param args Not utilized. */ public static void main(String[] args) { try { Connection connection = createConnection(args[0], args[1], args[2]); System.out.println("All Barcodes:\n" + getBarcodesTest(connection) + "\n"); System.out.println("All Companies:\n" + getCompaniesTest(connection) + "\n"); System.out.println("All Items:\n" + getItemsTest(connection) + "\n"); System.out.println("All Item Types:\n" + getItemTypesTest(connection) + "\n"); System.out.println("All Locations:\n" + getLocationsTest(connection) + "\n"); System.out.println("All Privileges:\n" + getPrivilegeTest(connection) + "\n"); System.out.println("All Users:\n" + getUsersTest(connection) + "\n"); connection.close(); } catch (SQLException e) { System.err.println(e.getMessage()); } } public static Connection createConnection(String table, String username, String password) throws SQLException { String connectionString = prefix + hostname + ":" + port + "/" + table + "?user=" + username + "&password=" + password; return DriverManager.getConnection(connectionString); } /** Retrieves all barcodes on database in a map of ID-Barcode. * @param connection Database connection. * @throws SQLException Thrown on any SQL Error. * @return Map */ public static Map<Integer, String> getBarcodesTest(Connection connection) throws SQLException { Map<Integer, String> result = new HashMap<Integer, String>(); Statement stmt = connection.createStatement(); stmt.executeUpdate("SELECT * FROM `Barcode`"); while(stmt.getResultSet().next()) { ResultSet resultSet = stmt.getResultSet(); result.put(resultSet.getInt(1), resultSet.getString(2)); } stmt.close(); return result; } /** Retrieves all companies on database in a map of ID-Company. * @param connection Database connection. * @throws SQLException Thrown on any SQL Error. * @return Map */ public static Map<Integer, Company> getCompaniesTest(Connection connection) throws SQLException { Map<Integer, Company> result = new HashMap<Integer, Company>(); Statement stmt = connection.createStatement(); stmt.executeUpdate("SELECT * FROM `Company`"); while(stmt.getResultSet().next()) { ResultSet resultSet = stmt.getResultSet(); Company company = new Company(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3), resultSet.getString(4), resultSet.getString(5)); result.put(resultSet.getInt(1), company); } stmt.close(); return result; } /** Retrieves all items on database in a map of ID-Item. * @param connection Database connection. * @throws SQLException Thrown on any SQL Error. * @return Map */ public static Map<Integer, Item> getItemsTest(Connection connection) throws SQLException { Map<Integer, Item> result = new HashMap<Integer, Item>(); Statement stmt = connection.createStatement(); stmt.executeUpdate("SELECT * FROM `Item`"); while(stmt.getResultSet().next()) { ResultSet resultSet = stmt.getResultSet(); Item item = new Item(resultSet.getInt(1), resultSet.getString(2), resultSet.getInt(3), resultSet.getInt(4), resultSet.getString(5)); result.put(resultSet.getInt(1), item); } stmt.close(); return result; } /** Retrieves all item types on database in a map of ID-ItemType. * @param connection Database connection. * @throws SQLException Thrown on any SQL Error. * @return Map */ public static Map<Integer, String> getItemTypesTest(Connection connection) throws SQLException { Map<Integer, String> result = new HashMap<Integer, String>(); Statement stmt = connection.createStatement(); stmt.executeUpdate("SELECT * FROM `ItemType`"); while(stmt.getResultSet().next()) { ResultSet resultSet = stmt.getResultSet(); result.put(resultSet.getInt(1), resultSet.getString(2)); } stmt.close(); return result; } /** Retrieves all locations on database in a map of ID-Location. * @param connection Database connection. * @throws SQLException Thrown on any SQL Error. * @return Map */ public static Map<Integer, Location> getLocationsTest(Connection connection) throws SQLException { Map<Integer, Location> result = new HashMap<Integer, Location>(); Statement stmt = connection.createStatement(); stmt.executeUpdate("SELECT * FROM `Location`"); while(stmt.getResultSet().next()) { ResultSet resultSet = stmt.getResultSet(); Location location = new Location(resultSet.getInt(1), resultSet.getString(2), resultSet.getInt(3), resultSet.getInt(4)); result.put(resultSet.getInt(1), location); } stmt.close(); return result; } /** Retrieves all privileges on database in a map of ID-Privilege. * @param connection Database connection. * @throws SQLException Thrown on any SQL Error. * @return Map */ public static Map<Integer, String> getPrivilegeTest(Connection connection) throws SQLException { Map<Integer, String> result = new HashMap<Integer, String>(); Statement stmt = connection.createStatement(); stmt.executeUpdate("SELECT * FROM `Privilege`"); while(stmt.getResultSet().next()) { ResultSet resultSet = stmt.getResultSet(); result.put(resultSet.getInt(1), resultSet.getString(2)); } stmt.close(); return result; } /** Retrieves all users on database in a map of ID-User. * @param connection Database connection. * @throws SQLException Thrown on any SQL Error. * @return Map */ public static Map<Integer, User> getUsersTest(Connection connection) throws SQLException { Map<Integer, User> result = new HashMap<Integer, User>(); Statement stmt = connection.createStatement(); stmt.executeUpdate("SELECT * FROM `User`"); while(stmt.getResultSet().next()) { ResultSet resultSet = stmt.getResultSet(); User user = new User(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3), resultSet.getString(4), resultSet.getInt(5)); result.put(resultSet.getInt(1), user); } stmt.close(); return result; } }
package org.apache.commons.collections; import java.util.Comparator; import org.apache.commons.collections.comparators.ComparableComparator; import org.apache.commons.collections.comparators.ReverseComparator; import org.apache.commons.collections.comparators.NullComparator; import org.apache.commons.collections.comparators.TransformingComparator; /** * Provides convenient static utility methods for <Code>Comparator</Code> * objects.<P> * * Most of the utility in this class can also be found in the * <Code>comparators</Code> package; this class merely provides a * convenient central place if you have use for more than one class * in the <Code>comparators</Code> subpackage.<P> * * Note that <I>every</I> method in this class allows you to specify * <Code>null</Code> instead of a comparator, in which case * {@link #NATURAL} will be used. * * @author Paul Jack * @version $Id$ */ public class ComparatorUtils { /** * Comparator for natural sort order. * * @see ComparableComparator#getInstance */ final public static Comparator NATURAL = ComparableComparator.getInstance(); /** * Returns a comparator that reverses the order of the given * comparator. * * @param comparator the comparator whose order to reverse * @return a comparator who reverses that order * @see ReverseComparator */ public static Comparator reverse(Comparator comparator) { if (comparator == null) comparator = NATURAL; return new ReverseComparator(comparator); } /** * Allows the given comparator to compare <Code>null</Code> values.<P> * * The returned comparator will consider a null value to be less than * any nonnull value, and equal to any other null value. Two nonnull * values will be evaluated with the given comparator.<P> * * @param comparator the comparator that wants to allow nulls * @return a version of that comparator that allows nulls * @see NullComparator */ public static Comparator nullLow(Comparator comparator) { if (comparator == null) comparator = NATURAL; return new NullComparator(comparator, false); } /** * Allows the given comparator to compare <Code>null</Code> values.<P> * * The returned comparator will consider a null value to be greater than * any nonnull value, and equal to any other null value. Two nonnull * values will be evaluated with the given comparator.<P> * * @param comparator the comparator that wants to allow nulls * @return a version of that comparator that allows nulls * @see NullComparator */ public static Comparator nullHigh(Comparator comparator) { if (comparator == null) comparator = NATURAL; return new NullComparator(comparator, true); } /** * Passes transformed objects to the given comparator.<P> * * Objects passed to the returned comparator will first be transformed * by the given transformer before they are compared by the given * comparator.<P> * * @param comparator the sort order to use * @param t the transformer to use * @return a comparator that transforms its input objects before * comparing them * @see TransformingComparator */ public static Comparator transform(Comparator comparator, Transformer t) { if (comparator == null) comparator = NATURAL; return new TransformingComparator(t, comparator); } /** * Returns the smaller of the given objects according to the given * comparator. * * @param o1 the first object to compare * @param o2 the second object to compare * @param comparator the sort order to use * @return the smaller of the two objects */ public static Object min(Object o1, Object o2, Comparator comparator) { if (comparator == null) comparator = NATURAL; int c = comparator.compare(o1, o2); return (c < 0) ? o1 : o2; } /** * Returns the smaller of the given objects according to the given * comparator. * * @param o1 the first object to compare * @param o2 the second object to compare * @param comparator the sort order to use * @return the smaller of the two objects */ public static Object max(Object o1, Object o2, Comparator comparator) { if (comparator == null) comparator = NATURAL; int c = comparator.compare(o1, o2); return (c > 0) ? o1 : o2; } }
package app.update; import app.util.*; import spark.*; import spark.template.freemarker.FreeMarkerEngine; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.*; import com.heroku.sdk.jdbc.DatabaseUrl; public class UpdateController { private static final String LAS_VERSION_URL_VALUE ="https: private static final String LAST_VERSION_NUMBER_VALUE = "0.2.26"; private static final String USER_PARAM = "USER"; private static final String VERSION_PARAM = "VERSION"; private static final String MSG_PARAM = "mensaje"; private static final String LAS_VERSION_URL_PARAM = "lasVersionURL"; private static final String LAS_VERSION_NUMBER_PARAM = "lasVersionNumber"; private static final String header = "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n" + "<script>\n" + " (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n" + " (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\n" + " m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n" + " })(window,document,'script','https: "\n" + " ga('create', 'UA-96140168-1', 'auto');\n" + " ga('send', 'pageview');\n" + "\n" + "</script>\n" + "<!--cript type='text/javascript'>\n" + "window.__lo_site_id = 82140;\n" + "\n" + " (function() {\n" + " var wa = document.createElement('script'); wa.type = 'text/javascript'; wa.async = true;\n" + " wa.src = 'https://d10lpsik1i8c69.cloudfront.net/w.js';\n" + " var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(wa, s);\n" + " })();\n" + " </script>\n" + "<script type=\"text/javascript\" src=\"//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js\">\n" + "</script public static Route handleUpdateGet = (Request request, Response response) -> { insertTick(request); //System.out.println("imprimiendo update.ftl"); response.type("application/json"); Map<String, Object> model = new HashMap<>(); model.put(LAS_VERSION_NUMBER_PARAM,LAST_VERSION_NUMBER_VALUE); model.put(LAS_VERSION_URL_PARAM, LAS_VERSION_URL_VALUE);//fuente amazon model.put(MSG_PARAM, "Ud ya tiene la ultima versi&oacute;n instalada disponible"); // return ViewUtil.render(request, model, Path.Template.UPDATE);//SEVERE: ResourceManager : unable to find resource 'update.ftl' in any resource loader. String userVersion = request.queryParams(VERSION_PARAM); if(userVersion!=null) { Double ver=versionToDouble(userVersion); //TODO controlar si la version del usuario es de 32 o 64bites if(versionToDouble(LAST_VERSION_NUMBER_VALUE).equals(ver)) { model.put(MSG_PARAM, //"<HTML>Ud esta ejecutando la ultima version disponible de UrsulaGIS"); "<HTML>" + "<b>Aviso:<\\/b>" + "<br>" + "<ul>" + "<li>Ud esta ejecutando la ultima version disponible de UrsulaGIS<\\/li>" + "<li>Si necesita ayuda para empezar visite <a href=\"https:\\/\\/www.ursulagis.com\"> www.ursulagis.com<\\/a><\\/li>" + "<\\/ul>" + "<\\/HTML>");//XXX va a webView.getEngine().loadContent(message); //Ud esta ejecutando la ultima version disponible de UrsulaGIS }else if(ver>= 0.223) { model.put(MSG_PARAM, "<HTML>" + "<b>Aviso:<\\/b>" + "<br>Ya esta disponible para descargar laversion 0.2.26 de UrsulaGIS" + " que permite abrir las imagenes ndvi en el nuevo formato<\\/b>\\t<br>visite" + " <a href=\\\"www.ursulagis.com\\\"> www.ursulagis.com <\\/a>\\tpara mas informaci&oacute;n <\\/HTML>"); // "<HTML>" // + "<b>Aviso:</b>" // + "<br>Ya esta disponible para descargar la version 0.2.26 de UrsulaGIS que permite abrir las imagenes ndvi en el nuevo formato</b>" // + " </HTML>");//XXX va a webView.getEngine().loadContent(message); } else {//antes de la 0.223 no traia el parametro de la version model.put(MSG_PARAM, "Hay una nueva versi&oacute;n disponible para actualizar "+LAST_VERSION_NUMBER_VALUE); } } FreeMarkerEngine fm= new FreeMarkerEngine(); return fm.render(new ModelAndView(model, Path.Template.UPDATE)); }; public static Double versionToDouble(String ver){ ver= ver.replace(" dev", ""); String[] v =ver.split("\\."); String ret = v[0]+"."; for(int i=1;i<v.length;i++){ ret=ret.concat(v[i]); } try{ return Double.parseDouble(ret); }catch(Exception e){ e.printStackTrace(); return -1.0; } } private static void insertTick(Request request) { Connection connection = null; try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS sessiones (tick timestamp, version varchar(255))"); String version = "unknown"; String user = "unknown"; String ip = "unknown"; try{ version = request.queryParams(VERSION_PARAM); if(version==null)version = "0.2.19?"; user = request.queryParams(USER_PARAM); if(user==null)user = "unknown"; ip = request.headers("X-FORWARDED-FOR"); if(ip==null){ // ip = request.queryParams("fwd"); //if(ip==null) ip = "unknown"; } } catch(Exception e){ System.out.println("ip unknown"); } stmt.executeUpdate("INSERT INTO sessiones VALUES (now(),'"+version+" / "+user+" @ "+ip+"')"); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } } }
package test.beast.evolution.likelihood; import beast.evolution.alignment.Alignment; import beast.evolution.alignment.CodonAlignment; import beast.evolution.alignment.Sequence; import beast.evolution.likelihood.TreeLikelihood; import beast.evolution.sitemodel.SiteModel; import beast.evolution.tree.Tree; import beast.likelihood.DACodonTreeLikelihood; import beast.tree.InternalNodeStates; import codonmodels.CodonFrequencies; import org.junit.Before; import org.junit.Test; import test.beast.evolution.CodonTestData; import java.util.Arrays; import static junit.framework.Assert.assertEquals; /** * Use BEAST 2 core TreeLikelihood result to test DACodonTreeLikelihood. * * @author Walter Xie */ public class DALikelihoodTest { TreeLikelihood treeLikelihood; DACodonTreeLikelihood daTreeLikelihood; int rootNr; InternalNodeStates internalNodeStates; // DecimalFormat df = new DecimalFormat(" @Before public void setUp() { // String newickTree = "(t1:0.5, t2:0.0):0.0;"; // TODO bug for 0 branch length ? String newickTree = "(t1:0.5, t2:0.1):0.0;"; // boolean adjustTipHeights = true; boolean adjustTipHeights = false; treeLikelihood = getTreeLikelihood("equal", newickTree, adjustTipHeights); // need to set internal node states daTreeLikelihood = getDATreeLikelihood("equal", newickTree, adjustTipHeights); rootNr = daTreeLikelihood.treeInput.get().getRoot().getNr(); System.out.println("Root index = " + rootNr); } @Test public void testDALikelihood1Site(){ System.out.println("\n=============== Standard tree likelihood ===============\n"); double logP = treeLikelihood.calculateLogP(); System.out.println(" logP = " + logP); double[] partial = treeLikelihood.getRootPartials(); // root System.out.println("Root partial without freqs = " + Arrays.toString(partial)); System.out.println("\n=============== DA tree likelihood ==============="); final double freq = 1.0/60.0; // vertebrateMitochondrial double daLogP = 0; double daLogP2 = 0; // nodeLd * freq // 0 - 63 for (int s=0; s < 64; s++) { // stop codon states in vertebrateMitochondrial if (s != 8 && s != 10 && s != 48 && s != 50) { // internal nodes internalNodeStates.setNrStates(rootNr, new int[]{s}); System.out.println("\nSet internal node state to " + s); double logPDA = daTreeLikelihood.calculateLogP(); System.out.println(" DA logP = " + logPDA); daLogP += Math.exp(logPDA); // [branch][site] double[][] branchLd = new double[2][1]; daTreeLikelihood.getBranchPartials(0, branchLd[0]); // child 1 daTreeLikelihood.getBranchPartials(1, branchLd[1]); // child 2 System.out.println("Branch likelihood child1 child2 without freqs = " + Arrays.toString(branchLd[0]) + ", " + Arrays.toString(branchLd[1])); double nodeLd = branchLd[0][0] * branchLd[1][0]; System.out.println("Root likelihood without freqs = " + nodeLd); System.out.println("Root partial without freqs = " + partial[s]); assertEquals(partial[s], nodeLd, 1e-16); daLogP2 += nodeLd * freq; // frequencies prior on the root } } daLogP = Math.log(daLogP); daLogP2 = Math.log(daLogP2); System.out.println("\nTotal :"); System.out.println("Total DA tree likelihood logP = " + daLogP); System.out.println("Total DA tree likelihood logP2 = " + daLogP2); System.out.println("Standard tree likelihood logP = " + logP); //Total DA tree likelihood logP = -15.667929146385474 //Standard tree likelihood logP = -15.667929146369291 assertEquals(logP, daLogP, 1e-10); assertEquals(logP, daLogP2, 1e-10); } private CodonAlignment getAlig2Tips1Site() { Sequence s1 = new Sequence("t1", "AAA"); Sequence s2 = new Sequence("t2", "CCC"); Alignment data = new Alignment(); data.initByName("sequence", s1, "sequence", s2, "dataType", "nucleotide" ); // create Codon Alignment CodonAlignment codonAlignment = new CodonAlignment(); codonAlignment.initByName("data", data, "dataType", "codon", "geneticCode", "vertebrateMitochondrial", "verbose", false); return codonAlignment; } // need to set internal node states after this private DACodonTreeLikelihood getDATreeLikelihood(String pi, String newickTree, boolean adjustTipHeights) { CodonAlignment codonAlignment = getAlig2Tips1Site(); CodonFrequencies codonFreq = new CodonFrequencies(); codonFreq.initByName("pi", pi, "data", codonAlignment, "verbose", true); SiteModel siteModel = CodonTestData.getSiteModel("0.3", "5", codonFreq, false); Tree tree = CodonTestData.getTree(codonAlignment, newickTree, adjustTipHeights); System.out.println("Tree is " + newickTree + "\n"); System.setProperty("java.only","true"); int internalNodeCount = tree.getInternalNodeCount(); int siteCount = codonAlignment.getSiteCount(); System.out.println(internalNodeCount + " internal nodes " + siteCount + " codon(s)."); internalNodeStates = new InternalNodeStates(internalNodeCount, siteCount); DACodonTreeLikelihood daTreeLikelihood = new DACodonTreeLikelihood(); daTreeLikelihood.initByName("data", codonAlignment, "tree", tree, "siteModel", siteModel, "internalNodeStates", internalNodeStates); return daTreeLikelihood; } private TreeLikelihood getTreeLikelihood(String pi, String newickTree, boolean adjustTipHeights) { CodonAlignment codonAlignment = getAlig2Tips1Site(); CodonFrequencies codonFreq = new CodonFrequencies(); codonFreq.initByName("pi", pi, "data", codonAlignment, "verbose", true); SiteModel siteModel = CodonTestData.getSiteModel("0.3", "5", codonFreq, false); Tree tree = CodonTestData.getTree(codonAlignment, newickTree, adjustTipHeights); System.out.println("Tree is " + newickTree + "\n"); System.setProperty("java.only","true"); TreeLikelihood treeLikelihood = new TreeLikelihood(); treeLikelihood.initByName("data", codonAlignment, "tree", tree, "siteModel", siteModel); return treeLikelihood; } }
package com.dd.beaconscanner; import er.extensions.eof.ERXKey; public class Beacon implements HealthItem, BeaconItem{ public static final ERXKey<String> LOCATION = new ERXKey<String>("location"); public static final ERXKey<String> UUID = new ERXKey<String>("uuid"); public static final ERXKey<Integer> MAJOR = new ERXKey<Integer>("majorCode"); public static final ERXKey<Integer> MINOR = new ERXKey<Integer>("minorCode"); public static final ERXKey<Integer> POWER = new ERXKey<Integer>("power"); public static final ERXKey<Integer> RSSI = new ERXKey<Integer>("rssi"); public static final ERXKey<String> UNIQUE_KEY = new ERXKey<String>("uniqueKey"); public static final ERXKey<Long> HEALTH = new ERXKey<Long>("health"); private String uuid; private Integer major; private Integer minor; private Integer power; private Integer rssi; private String location; private long creationTime; private long updateTime; private String uniqueKey; public Beacon(String uuid, Integer major, Integer minor, Integer power, Integer rssi, String location) { super(); this.uuid = uuid; this.major = major; this.minor = minor; this.power = power; this.rssi = rssi; this.location = location; creationTime = System.currentTimeMillis(); updateTime = System.currentTimeMillis(); } public Beacon(String[] bleChunks){ creationTime = System.currentTimeMillis(); updateTime = System.currentTimeMillis(); StringBuilder sb = new StringBuilder(); for(int i = 23; i < 39;i++){ sb.append(bleChunks[i]); } uuid = sb.toString(); try{ major = Integer.parseInt(bleChunks[39]+bleChunks[40],16); minor = Integer.parseInt(bleChunks[41]+bleChunks[42],16); uniqueKey = BeaconManager.uniqueKey(uuid,major,minor); power = Integer.parseInt(bleChunks[43],16)-256; rssi = Integer.parseInt(bleChunks[44],16)-256; // uniqueKey = uuid+""+major+""+minor; } catch(Exception e){ System.out.println(e.getMessage()); } //System.out.println(toString()); } public String uuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public Integer majorCode() { return major; } public void setMajorCode(Integer major) { this.major = major; } public Integer minorCode() { return minor; } public void setMinorCode(Integer minor) { this.minor = minor; } public Integer power() { return power; } public void setPower(Integer power) { this.power = power; } public Integer rssi() { return rssi; } public void setRssi(Integer rssi) { this.rssi = rssi; } public String location() { return location; } public void setLocation(String location) { this.location = location; } public int health(){ int factor = (int)(((updateTime-System.currentTimeMillis())/1000)/6);// (float)((updateTime/1000)+50/(System.currentTimeMillis()/1000)); int health = 10+factor; if(health<=0){ return HEALTH_STATUS_LOST; } if(health>10){ return HEALTH_STATUS_BEST; } return health; } public void updateData(String[] bleChunks, String location){ boolean doUpdate = false; int _power = Integer.parseInt(bleChunks[43],16)-256; int _rssi = Integer.parseInt(bleChunks[44],16)-256; this.location = location; if((health()<HEALTH_STATUS_MEDIUM&&rssi()<_rssi)){ doUpdate = true; } else{ if(location.equals(location())){ rssi = _rssi; } } // System.out.println(minor()+" health: "+health()); if(doUpdate){ updateTime = System.currentTimeMillis(); power = _power; rssi = _rssi; this.location = location; } } @Override public String toString() { return "uuid:"+uuid()+" major:"+majorCode()+" minor:"+minor+" power:"+power()+" rssi:"+rssi()+" location:"+location(); } public String uniqueKey(){ return uniqueKey; } }
package backend.resource; import backend.IssueMetadata; import backend.interfaces.IModel; import prefs.Preferences; import java.time.LocalDateTime; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; /** * Thread-safe. The only top-level state in the application. */ @SuppressWarnings("unused") public class MultiModel implements IModel { private final HashMap<String, Model> models; private final Preferences prefs; // A pending repository is one that has been requested to load but has // not finished loading. We keep track of it because we don't want repeated // requests for the same repository to load it multiple times. private final HashSet<String> pendingRepositories; // Guaranteed to have a value throughout private String defaultRepo = null; public MultiModel(Preferences prefs) { this.models = new HashMap<>(); this.pendingRepositories = new HashSet<>(); this.prefs = prefs; } public synchronized MultiModel addPending(Model model) { String repoId = model.getRepoId(); Optional<String> matchingRepoId = pendingRepositories.stream() .filter(pendingRepo -> pendingRepo.equalsIgnoreCase(repoId)) .findFirst(); assert matchingRepoId.isPresent() : "No pending repository " + repoId + "!"; pendingRepositories.remove(matchingRepoId.get()); add(model); preprocessNewIssues(model); return this; } private synchronized MultiModel add(Model model) { this.models.put(model.getRepoId(), model); return this; } public synchronized Model get(String repoId) { return models.get(repoId); } public synchronized List<Model> toModels() { return new ArrayList<>(models.values()); } public synchronized MultiModel replace(List<Model> newModels) { preprocessUpdatedIssues(newModels); this.models.clear(); newModels.forEach(this::add); return this; } public synchronized void insertMetadata(String repoId, Map<Integer, IssueMetadata> metadata, String currentUser) { models.get(repoId).getIssues().forEach(issue -> { if (metadata.containsKey(issue.getId())) { IssueMetadata toBeInserted = metadata.get(issue.getId()); LocalDateTime nonSelfUpdatedAt = reconcileCreationDate(toBeInserted.getNonSelfUpdatedAt(), issue.getCreatedAt(), currentUser, issue.getCreator()); issue.setMetadata(new IssueMetadata(toBeInserted, nonSelfUpdatedAt)); } }); } private static LocalDateTime reconcileCreationDate(LocalDateTime lastNonSelfUpdate, LocalDateTime creationTime, String currentUser, String issueCreator) { // If current user is same as issue creator, we do not consider creation of issue // as an issue update. if (currentUser.equalsIgnoreCase(issueCreator)) return lastNonSelfUpdate; // Current user is not the issue creator. // lastNonSelfUpdate cannot be before creationTime unless it is the default value (epoch 0), // which means the issue has no events or comments. // However, since the current user is not the issue creator, creation of the issue itself // counts as an update. if (lastNonSelfUpdate.compareTo(creationTime) < 0) return creationTime; // Otherwise, the issue actually possesses non-self updates, so we do nothing with the // value. return lastNonSelfUpdate; } @Override public synchronized String getDefaultRepo() { return defaultRepo; } @Override public synchronized void setDefaultRepo(String repoId) { this.defaultRepo = repoId; } @Override public synchronized List<TurboIssue> getIssues() { List<TurboIssue> result = new ArrayList<>(); models.values().forEach(m -> result.addAll(m.getIssues())); return result; } @Override public synchronized List<TurboLabel> getLabels() { List<TurboLabel> result = new ArrayList<>(); models.values().forEach(m -> result.addAll(m.getLabels())); return result; } @Override public synchronized List<TurboMilestone> getMilestones() { List<TurboMilestone> result = new ArrayList<>(); models.values().forEach(m -> result.addAll(m.getMilestones())); return result; } @Override public synchronized List<TurboUser> getUsers() { List<TurboUser> result = new ArrayList<>(); models.values().forEach(m -> result.addAll(m.getUsers())); return result; } @Override public Optional<Model> getModelById(String repoId) { return models.containsKey(repoId) ? Optional.of(models.get(repoId)) : Optional.empty(); } @Override public Optional<TurboUser> getAssigneeOfIssue(TurboIssue issue) { return getModelById(issue.getRepoId()) .flatMap(m -> m.getAssigneeOfIssue(issue)); } @Override public List<TurboLabel> getLabelsOfIssue(TurboIssue issue, Predicate<TurboLabel> predicate) { return getModelById(issue.getRepoId()) .flatMap(m -> Optional.of(m.getLabelsOfIssue(issue))) .get().stream() .filter(predicate) .collect(Collectors.toList()); } @Override public List<TurboLabel> getLabelsOfIssue(TurboIssue issue) { return getModelById(issue.getRepoId()) .flatMap(m -> Optional.of(m.getLabelsOfIssue(issue))) .get(); } @Override public Optional<TurboMilestone> getMilestoneOfIssue(TurboIssue issue) { return getModelById(issue.getRepoId()) .flatMap(m -> m.getMilestoneOfIssue(issue)); } public synchronized boolean isRepositoryPending(String repoId) { return pendingRepositories.stream().anyMatch(pendingRepo -> pendingRepo.equalsIgnoreCase(repoId)); } public void queuePendingRepository(String repoId) { pendingRepositories.add(repoId); } /** * Called on new models which come in. * Mutates TurboIssues with meta-information. * @param model */ private void preprocessNewIssues(Model model) { // All new issues which come in are not read, unless they already were according to prefs. for (TurboIssue issue : model.getIssues()) { Optional<LocalDateTime> time = prefs.getMarkedReadAt(model.getRepoId(), issue.getId()); issue.setMarkedReadAt(time); issue.setIsCurrentlyRead(time.isPresent()); } } /** * Called on existing models that are updated. * Mutates TurboIssues with meta-information. * @param newModels */ private void preprocessUpdatedIssues(List<Model> newModels) { // Updates preferences with the results of issues that have been updated after a refresh. // This makes read issues show up again. for (Model model : newModels) { assert models.containsKey(model.getRepoId()); Model existingModel = models.get(model.getRepoId()); if (!existingModel.getIssues().equals(model.getIssues())) { // Find issues that have changed and update preferences with them for (int i = 1; i <= model.getIssues().size(); i++) { // TODO O(n^2), optimise by preprocessing into a map or sorting if (!existingModel.getIssueById(i).equals(model.getIssueById(i))) { assert model.getIssueById(i).isPresent(); // It's no longer currently read, but it retains its updated time. // No changes to preferences. model.getIssueById(i).get().setIsCurrentlyRead(false); } } } } } private void ______BOILERPLATE______() { } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MultiModel that = (MultiModel) o; return models.equals(that.models); } @Override public int hashCode() { return models.hashCode(); } }
/** * Registers a DownloadReceiver and waits for all Downloads * to complete, then stops * */ package de.danoeh.antennapod.service.download; import java.io.File; import java.io.IOException; import java.lang.Thread.UncaughtExceptionHandler; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaPlayer; import android.os.AsyncTask; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.webkit.URLUtil; import de.danoeh.antennapod.AppConfig; import de.danoeh.antennapod.R; import de.danoeh.antennapod.activity.DownloadActivity; import de.danoeh.antennapod.activity.DownloadLogActivity; import de.danoeh.antennapod.asynctask.DownloadStatus; import de.danoeh.antennapod.feed.Feed; import de.danoeh.antennapod.feed.FeedFile; import de.danoeh.antennapod.feed.FeedImage; import de.danoeh.antennapod.feed.FeedItem; import de.danoeh.antennapod.feed.FeedManager; import de.danoeh.antennapod.feed.FeedMedia; import de.danoeh.antennapod.storage.DownloadRequestException; import de.danoeh.antennapod.storage.DownloadRequester; import de.danoeh.antennapod.syndication.handler.FeedHandler; import de.danoeh.antennapod.syndication.handler.UnsupportedFeedtypeException; import de.danoeh.antennapod.util.ChapterUtils; import de.danoeh.antennapod.util.DownloadError; import de.danoeh.antennapod.util.InvalidFeedException; public class DownloadService extends Service { private static final String TAG = "DownloadService"; public static String ACTION_ALL_FEED_DOWNLOADS_COMPLETED = "action.de.danoeh.antennapod.storage.all_feed_downloads_completed"; public static final String ACTION_ENQUEUE_DOWNLOAD = "action.de.danoeh.antennapod.service.enqueueDownload"; public static final String ACTION_CANCEL_DOWNLOAD = "action.de.danoeh.antennapod.service.cancelDownload"; public static final String ACTION_CANCEL_ALL_DOWNLOADS = "action.de.danoeh.antennapod.service.cancelAllDownloads"; /** Extra for ACTION_CANCEL_DOWNLOAD */ public static final String EXTRA_DOWNLOAD_URL = "downloadUrl"; public static final String ACTION_DOWNLOAD_HANDLED = "action.de.danoeh.antennapod.service.download_handled"; /** * Sent by the DownloadService when the content of the downloads list * changes. */ public static final String ACTION_DOWNLOADS_CONTENT_CHANGED = "action.de.danoeh.antennapod.service.downloadsContentChanged"; public static final String EXTRA_DOWNLOAD_ID = "extra.de.danoeh.antennapod.service.download_id"; /** Extra for ACTION_ENQUEUE_DOWNLOAD intent. */ public static final String EXTRA_REQUEST = "request"; // Download types for ACTION_DOWNLOAD_HANDLED public static final String EXTRA_DOWNLOAD_TYPE = "extra.de.danoeh.antennapod.service.downloadType"; public static final int DOWNLOAD_TYPE_FEED = 1; public static final int DOWNLOAD_TYPE_MEDIA = 2; public static final int DOWNLOAD_TYPE_IMAGE = 3; private CopyOnWriteArrayList<DownloadStatus> completedDownloads; private ExecutorService syncExecutor; private ExecutorService downloadExecutor; /** Number of threads of downloadExecutor. */ private static final int NUM_PARALLEL_DOWNLOADS = 4; private DownloadRequester requester; private FeedManager manager; private NotificationCompat.Builder notificationBuilder; private int NOTIFICATION_ID = 2; private int REPORT_ID = 3; private List<Downloader> downloads; /** Number of completed downloads which are currently being handled. */ private volatile int downloadsBeingHandled; private volatile boolean shutdownInitiated = false; /** True if service is running. */ public static boolean isRunning = false; private Handler handler; private final IBinder mBinder = new LocalBinder(); public class LocalBinder extends Binder { public DownloadService getService() { return DownloadService.this; } } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent.getParcelableExtra(EXTRA_REQUEST) != null) { onDownloadQueued(intent); } return Service.START_NOT_STICKY; } @SuppressLint("NewApi") @Override public void onCreate() { if (AppConfig.DEBUG) Log.d(TAG, "Service started"); isRunning = true; handler = new Handler(); completedDownloads = new CopyOnWriteArrayList<DownloadStatus>( new ArrayList<DownloadStatus>()); downloads = new ArrayList<Downloader>(); registerReceiver(downloadQueued, new IntentFilter( ACTION_ENQUEUE_DOWNLOAD)); IntentFilter cancelDownloadReceiverFilter = new IntentFilter(); cancelDownloadReceiverFilter.addAction(ACTION_CANCEL_ALL_DOWNLOADS); cancelDownloadReceiverFilter.addAction(ACTION_CANCEL_DOWNLOAD); registerReceiver(cancelDownloadReceiver, cancelDownloadReceiverFilter); syncExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { Log.e(TAG, "Thread exited with uncaught exception"); ex.printStackTrace(); downloadsBeingHandled -= 1; queryDownloads(); } }); return t; } }); downloadExecutor = Executors.newFixedThreadPool(NUM_PARALLEL_DOWNLOADS, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); return t; } }); manager = FeedManager.getInstance(); requester = DownloadRequester.getInstance(); } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public void onDestroy() { if (AppConfig.DEBUG) Log.d(TAG, "Service shutting down"); isRunning = false; unregisterReceiver(cancelDownloadReceiver); unregisterReceiver(downloadQueued); } private void setupNotification() { PendingIntent pIntent = PendingIntent.getActivity(this, 0, new Intent( this, DownloadActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.stat_notify_sync); notificationBuilder = new NotificationCompat.Builder(this) .setContentTitle( getString(R.string.download_notification_title)) .setContentText( requester.getNumberOfDownloads() + getString(R.string.downloads_left)) .setOngoing(true).setContentIntent(pIntent).setLargeIcon(icon) .setSmallIcon(R.drawable.stat_notify_sync); startForeground(NOTIFICATION_ID, notificationBuilder.getNotification()); if (AppConfig.DEBUG) Log.d(TAG, "Notification set up"); } private Downloader getDownloader(String downloadUrl) { for (Downloader downloader : downloads) { if (downloader.getStatus().getFeedFile().getDownload_url() .equals(downloadUrl)) { return downloader; } } return null; } private BroadcastReceiver cancelDownloadReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ACTION_CANCEL_DOWNLOAD)) { String url = intent.getStringExtra(EXTRA_DOWNLOAD_URL); if (url == null) { throw new IllegalArgumentException( "ACTION_CANCEL_DOWNLOAD intent needs download url extra"); } if (AppConfig.DEBUG) Log.d(TAG, "Cancelling download with url " + url); Downloader d = getDownloader(url); if (d != null) { d.cancel(); removeDownload(d); } else { Log.e(TAG, "Could not cancel download with url " + url); } } else if (intent.getAction().equals(ACTION_CANCEL_ALL_DOWNLOADS)) { for (Downloader d : downloads) { d.cancel(); DownloadRequester.getInstance().removeDownload( d.getStatus().getFeedFile()); d.getStatus().getFeedFile().setFile_url(null); if (AppConfig.DEBUG) Log.d(TAG, "Cancelled all downloads"); } downloads.clear(); sendBroadcast(new Intent(ACTION_DOWNLOADS_CONTENT_CHANGED)); } queryDownloads(); } }; private void onDownloadQueued(Intent intent) { if (AppConfig.DEBUG) Log.d(TAG, "Received enqueue request"); Request request = intent.getParcelableExtra(EXTRA_REQUEST); if (request == null) { throw new IllegalArgumentException( "ACTION_ENQUEUE_DOWNLOAD intent needs request extra"); } if (shutdownInitiated) { if (AppConfig.DEBUG) Log.d(TAG, "Cancelling shutdown; new download was queued"); shutdownInitiated = false; setupNotification(); } DownloadRequester requester = DownloadRequester.getInstance(); FeedFile feedfile = requester.getDownload(request.source); if (feedfile != null) { DownloadStatus status = new DownloadStatus(feedfile, feedfile.getHumanReadableIdentifier()); Downloader downloader = getDownloader(status); if (downloader != null) { downloads.add(downloader); downloadExecutor.submit(downloader); sendBroadcast(new Intent(ACTION_DOWNLOADS_CONTENT_CHANGED)); } } else { Log.e(TAG, "Could not find feedfile in download requester when trying to enqueue new download"); } queryDownloads(); } private BroadcastReceiver downloadQueued = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { onDownloadQueued(intent); } }; private Downloader getDownloader(DownloadStatus status) { if (URLUtil.isHttpUrl(status.getFeedFile().getDownload_url())) { return new HttpDownloader(this, status); } Log.e(TAG, "Could not find appropriate downloader for " + status.getFeedFile().getDownload_url()); return null; } @SuppressLint("NewApi") public void onDownloadCompleted(final Downloader downloader) { final AsyncTask<Void, Void, Void> handlerTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { if (AppConfig.DEBUG) Log.d(TAG, "Received 'Download Complete' - message."); downloadsBeingHandled += 1; DownloadStatus status = downloader.getStatus(); status.setCompletionDate(new Date()); boolean successful = status.isSuccessful(); FeedFile download = status.getFeedFile(); if (download != null) { if (successful) { if (download.getClass() == Feed.class) { handleCompletedFeedDownload(status); } else if (download.getClass() == FeedImage.class) { handleCompletedImageDownload(status); } else if (download.getClass() == FeedMedia.class) { handleCompletedFeedMediaDownload(status); } } else { download.setFile_url(null); download.setDownloaded(false); if (!successful && !status.isCancelled()) { Log.e(TAG, "Download failed"); saveDownloadStatus(status); } sendDownloadHandledIntent(getDownloadType(download)); downloadsBeingHandled -= 1; } } removeDownload(downloader); if (!successful) { queryDownloads(); } return null; } }; if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) { handlerTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { handlerTask.execute(); } } /** * Remove download from the DownloadRequester list and from the * DownloadService list. */ private void removeDownload(final Downloader d) { downloads.remove(d); DownloadRequester.getInstance().removeDownload( d.getStatus().getFeedFile()); sendBroadcast(new Intent(ACTION_DOWNLOADS_CONTENT_CHANGED)); } /** * Adds a new DownloadStatus object to the list of completed downloads and * saves it in the database * * @param status * the download that is going to be saved */ private void saveDownloadStatus(DownloadStatus status) { completedDownloads.add(status); manager.addDownloadStatus(this, status); } /** Returns correct value for EXTRA_DOWNLOAD_TYPE. */ private int getDownloadType(FeedFile f) { if (f.getClass() == Feed.class) { return DOWNLOAD_TYPE_FEED; } else if (f.getClass() == FeedImage.class) { return DOWNLOAD_TYPE_IMAGE; } else if (f.getClass() == FeedMedia.class) { return DOWNLOAD_TYPE_MEDIA; } else { return 0; } } private void sendDownloadHandledIntent(int type) { Intent intent = new Intent(ACTION_DOWNLOAD_HANDLED); intent.putExtra(EXTRA_DOWNLOAD_TYPE, type); sendBroadcast(intent); } /** * Creates a notification at the end of the service lifecycle to notify the * user about the number of completed downloads. A report will only be * created if the number of successfully downloaded feeds is bigger than 1 * or if there is at least one failed download which is not an image or if * there is at least one downloaded media file. */ private void updateReport() { // check if report should be created boolean createReport = false; int successfulDownloads = 0; int failedDownloads = 0; // a download report is created if at least one download has failed // (excluding failed image downloads) for (DownloadStatus status : completedDownloads) { if (status.isSuccessful()) { successfulDownloads++; } else if (!status.isCancelled()) { if (status.getFeedFile().getClass() != FeedImage.class) { createReport = true; } failedDownloads++; } } if (createReport) { if (AppConfig.DEBUG) Log.d(TAG, "Creating report"); // create notification object Notification notification = new NotificationCompat.Builder(this) .setTicker( getString(de.danoeh.antennapod.R.string.download_report_title)) .setContentTitle( getString(de.danoeh.antennapod.R.string.download_report_title)) .setContentText( String.format( getString(R.string.download_report_content), successfulDownloads, failedDownloads)) .setSmallIcon(R.drawable.stat_notify_sync) .setLargeIcon( BitmapFactory.decodeResource(getResources(), R.drawable.stat_notify_sync)) .setContentIntent( PendingIntent.getActivity(this, 0, new Intent(this, DownloadLogActivity.class), 0)) .setAutoCancel(true).getNotification(); NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(REPORT_ID, notification); } else { if (AppConfig.DEBUG) Log.d(TAG, "No report is created"); } completedDownloads.clear(); } /** Check if there's something else to download, otherwise stop */ void queryDownloads() { int numOfDownloads = downloads.size(); if (AppConfig.DEBUG) { Log.d(TAG, numOfDownloads + " downloads left"); Log.d(TAG, "Downloads being handled: " + downloadsBeingHandled); Log.d(TAG, "ShutdownInitiated: " + shutdownInitiated); } if (numOfDownloads == 0 && downloadsBeingHandled <= 0) { if (AppConfig.DEBUG) Log.d(TAG, "Starting shutdown"); shutdownInitiated = true; updateReport(); stopForeground(true); } else { if (notificationBuilder != null) { // update notification notificationBuilder.setContentText(numOfDownloads + " Downloads left"); NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(NOTIFICATION_ID, notificationBuilder.getNotification()); } else { setupNotification(); } } } /** Is called whenever a Feed is downloaded */ private void handleCompletedFeedDownload(DownloadStatus status) { if (AppConfig.DEBUG) Log.d(TAG, "Handling completed Feed Download"); syncExecutor.execute(new FeedSyncThread(status)); } /** Is called whenever a Feed-Image is downloaded */ private void handleCompletedImageDownload(DownloadStatus status) { if (AppConfig.DEBUG) Log.d(TAG, "Handling completed Image Download"); syncExecutor.execute(new ImageHandlerThread(status)); } /** Is called whenever a FeedMedia is downloaded. */ private void handleCompletedFeedMediaDownload(DownloadStatus status) { if (AppConfig.DEBUG) Log.d(TAG, "Handling completed FeedMedia Download"); syncExecutor.execute(new MediaHandlerThread(status)); } /** * Takes a single Feed, parses the corresponding file and refreshes * information in the manager */ class FeedSyncThread implements Runnable { private static final String TAG = "FeedSyncThread"; private Feed feed; private DownloadStatus status; private int reason; private boolean successful; public FeedSyncThread(DownloadStatus status) { this.feed = (Feed) status.getFeedFile(); this.status = status; } public void run() { Feed savedFeed = null; reason = 0; String reasonDetailed = null; successful = true; FeedManager manager = FeedManager.getInstance(); FeedHandler handler = new FeedHandler(); feed.setDownloaded(true); try { feed = handler.parseFeed(feed); if (AppConfig.DEBUG) Log.d(TAG, feed.getTitle() + " parsed"); if (checkFeedData(feed) == false) { throw new InvalidFeedException(); } // Save information of feed in DB savedFeed = manager.updateFeed(DownloadService.this, feed); // Download Feed Image if provided and not downloaded if (savedFeed.getImage() != null && savedFeed.getImage().isDownloaded() == false) { if (AppConfig.DEBUG) Log.d(TAG, "Feed has image; Downloading...."); savedFeed.getImage().setFeed(savedFeed); try { requester.downloadImage(DownloadService.this, savedFeed.getImage()); } catch (DownloadRequestException e) { e.printStackTrace(); manager.addDownloadStatus(DownloadService.this, new DownloadStatus(savedFeed.getImage(), savedFeed.getImage() .getHumanReadableIdentifier(), DownloadError.ERROR_REQUEST_ERROR, false, e.getMessage())); } } } catch (SAXException e) { successful = false; e.printStackTrace(); reason = DownloadError.ERROR_PARSER_EXCEPTION; reasonDetailed = e.getMessage(); } catch (IOException e) { successful = false; e.printStackTrace(); reason = DownloadError.ERROR_PARSER_EXCEPTION; reasonDetailed = e.getMessage(); } catch (ParserConfigurationException e) { successful = false; e.printStackTrace(); reason = DownloadError.ERROR_PARSER_EXCEPTION; reasonDetailed = e.getMessage(); } catch (UnsupportedFeedtypeException e) { e.printStackTrace(); successful = false; reason = DownloadError.ERROR_UNSUPPORTED_TYPE; reasonDetailed = e.getMessage(); } catch (InvalidFeedException e) { e.printStackTrace(); successful = false; reason = DownloadError.ERROR_PARSER_EXCEPTION; reasonDetailed = e.getMessage(); } // cleanup(); if (savedFeed == null) { savedFeed = feed; } saveDownloadStatus(new DownloadStatus(savedFeed, savedFeed.getHumanReadableIdentifier(), reason, successful, reasonDetailed)); sendDownloadHandledIntent(DOWNLOAD_TYPE_FEED); downloadsBeingHandled -= 1; queryDownloads(); } /** Checks if the feed was parsed correctly. */ private boolean checkFeedData(Feed feed) { if (feed.getTitle() == null) { Log.e(TAG, "Feed has no title."); return false; } if (!hasValidFeedItems(feed)) { Log.e(TAG, "Feed has invalid items"); return false; } if (AppConfig.DEBUG) Log.d(TAG, "Feed appears to be valid."); return true; } private boolean hasValidFeedItems(Feed feed) { for (FeedItem item : feed.getItems()) { if (item.getTitle() == null) { Log.e(TAG, "Item has no title"); return false; } if (item.getPubDate() == null) { Log.e(TAG, "Item has no pubDate. Using current time as pubDate"); if (item.getTitle() != null) { Log.e(TAG, "Title of invalid item: " + item.getTitle()); } item.setPubDate(new Date()); } } return true; } /** Delete files that aren't needed anymore */ private void cleanup() { if (feed.getFile_url() != null) { if (new File(feed.getFile_url()).delete()) if (AppConfig.DEBUG) Log.d(TAG, "Successfully deleted cache file."); else Log.e(TAG, "Failed to delete cache file."); feed.setFile_url(null); } else if (AppConfig.DEBUG) { Log.d(TAG, "Didn't delete cache file: File url is not set."); } } } /** Handles a completed image download. */ class ImageHandlerThread implements Runnable { private FeedImage image; private DownloadStatus status; public ImageHandlerThread(DownloadStatus status) { this.image = (FeedImage) status.getFeedFile(); this.status = status; } @Override public void run() { image.setDownloaded(true); saveDownloadStatus(status); sendDownloadHandledIntent(DOWNLOAD_TYPE_IMAGE); manager.setFeedImage(DownloadService.this, image); if (image.getFeed() != null) { manager.setFeed(DownloadService.this, image.getFeed()); } else { Log.e(TAG, "Image has no feed, image might not be saved correctly!"); } downloadsBeingHandled -= 1; queryDownloads(); } } /** Handles a completed media download. */ class MediaHandlerThread implements Runnable { private FeedMedia media; private DownloadStatus status; public MediaHandlerThread(DownloadStatus status) { super(); this.media = (FeedMedia) status.getFeedFile(); this.status = status; } @Override public void run() { boolean chaptersRead = false; media.setDownloaded(true); // Get duration MediaPlayer mediaplayer = new MediaPlayer(); try { mediaplayer.setDataSource(media.getFile_url()); mediaplayer.prepare(); media.setDuration(mediaplayer.getDuration()); if (AppConfig.DEBUG) Log.d(TAG, "Duration of file is " + media.getDuration()); mediaplayer.reset(); } catch (IOException e) { e.printStackTrace(); } finally { mediaplayer.release(); } if (media.getItem().getChapters() == null) { ChapterUtils.readID3ChaptersFromFeedMediaFileUrl(media .getItem()); if (media.getItem().getChapters() != null) { chaptersRead = true; } } saveDownloadStatus(status); sendDownloadHandledIntent(DOWNLOAD_TYPE_MEDIA); if (chaptersRead) { manager.setFeedItem(DownloadService.this, media.getItem()); } else { manager.setFeedMedia(DownloadService.this, media); } downloadsBeingHandled -= 1; queryDownloads(); } } /** Is used to request a new download. */ public static class Request implements Parcelable { private String destination; private String source; public Request(String destination, String source) { super(); this.destination = destination; this.source = source; } private Request(Parcel in) { destination = in.readString(); source = in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(destination); dest.writeString(source); } public static final Parcelable.Creator<Request> CREATOR = new Parcelable.Creator<Request>() { public Request createFromParcel(Parcel in) { return new Request(in); } public Request[] newArray(int size) { return new Request[size]; } }; public String getDestination() { return destination; } public String getSource() { return source; } } public List<Downloader> getDownloads() { return downloads; } }
package backend.stub; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.*; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.eclipse.egit.github.core.Comment; import org.eclipse.egit.github.core.User; import backend.IssueMetadata; import backend.resource.TurboIssue; import backend.resource.TurboLabel; import backend.resource.TurboMilestone; import backend.resource.TurboUser; import github.IssueEventType; import github.TurboIssueEvent; public class DummyRepoState { private String dummyRepoId; private TreeMap<Integer, TurboIssue> issues = new TreeMap<>(); private TreeMap<String, TurboLabel> labels = new TreeMap<>(); private TreeMap<Integer, TurboMilestone> milestones = new TreeMap<>(); private TreeMap<String, TurboUser> users = new TreeMap<>(); private TreeMap<Integer, TurboIssue> updatedIssues = new TreeMap<>(); private TreeMap<String, TurboLabel> updatedLabels = new TreeMap<>(); private TreeMap<Integer, TurboMilestone> updatedMilestones = new TreeMap<>(); private TreeMap<String, TurboUser> updatedUsers = new TreeMap<>(); public DummyRepoState(String repoId) { this.dummyRepoId = repoId; for (int i = 0; i < 10; i++) { // Issue #7 is a PR TurboIssue dummyIssue = (i != 6) ? makeDummyIssue() : makeDummyPR(); // All default issues are treated as if created a long time ago dummyIssue.setUpdatedAt(LocalDateTime.of(2000 + i, 1, 1, 0, 0)); TurboLabel dummyLabel = makeDummyLabel(); TurboMilestone dummyMilestone = makeDummyMilestone(); TurboUser dummyUser = makeDummyUser(); // Populate state with defaults issues.put(dummyIssue.getId(), dummyIssue); labels.put(dummyLabel.getActualName(), dummyLabel); milestones.put(dummyMilestone.getId(), dummyMilestone); users.put(dummyUser.getLoginName(), dummyUser); } // Issues #1-5 are assigned milestones 1-5 respectively for (int i = 1; i <= 5; i++) { issues.get(i).setMilestone(milestones.get(i)); } // Odd issues are assigned label 1, even issues are assigned label 2 for (int i = 1; i <= 10; i++) { issues.get(i).addLabel((i % 2 == 0) ? "Label 1" : "Label 2"); } // We assign a colorful label to issue 10 labels.put("Label 11", new TurboLabel(dummyRepoId, "ffa500", "Label 11")); issues.get(10).addLabel("Label 11"); // Each user is assigned to his corresponding issue for (int i = 1; i <= 10; i++) { issues.get(i).setAssignee("User " + i); } // Then put down three comments for issue 10 Comment dummyComment1 = new Comment(); Comment dummyComment2 = new Comment(); Comment dummyComment3 = new Comment(); dummyComment1.setCreatedAt(new Date()); // Recently posted dummyComment2.setCreatedAt(new Date()); dummyComment3.setCreatedAt(new Date(0)); // Posted very long ago dummyComment1.setUser(new User().setLogin("User 1")); dummyComment2.setUser(new User().setLogin("User 2")); dummyComment3.setUser(new User().setLogin("User 3")); Comment[] dummyComments = { dummyComment1, dummyComment2, dummyComment3 }; issues.get(10).setMetadata(new IssueMetadata( new ArrayList<>(), new ArrayList<>(Arrays.asList(dummyComments)) )); issues.get(10).setCommentCount(3); issues.get(10).setUpdatedAt(LocalDateTime.now()); // Issue 6 is closed issues.get(6).setOpen(false); } protected ImmutableTriple<List<TurboIssue>, String, Date> getUpdatedIssues(String eTag, Date lastCheckTime) { String currETag = eTag; if (!updatedIssues.isEmpty() || eTag == null) currETag = UUID.randomUUID().toString(); ImmutableTriple<List<TurboIssue>, String, Date> toReturn = new ImmutableTriple<>( new ArrayList<>(updatedIssues.values()), currETag, lastCheckTime); updatedIssues = new TreeMap<>(); return toReturn; } protected ImmutablePair<List<TurboLabel>, String> getUpdatedLabels(String eTag) { String currETag = eTag; if (!updatedLabels.isEmpty() || eTag == null) currETag = UUID.randomUUID().toString(); ImmutablePair<List<TurboLabel>, String> toReturn = new ImmutablePair<>(new ArrayList<>(updatedLabels.values()), currETag); updatedLabels = new TreeMap<>(); return toReturn; } protected ImmutablePair<List<TurboMilestone>, String> getUpdatedMilestones(String eTag) { String currETag = eTag; if (!updatedMilestones.isEmpty() || eTag == null) currETag = UUID.randomUUID().toString(); ImmutablePair<List<TurboMilestone>, String> toReturn = new ImmutablePair<>(new ArrayList<>(updatedMilestones.values()), currETag); updatedMilestones = new TreeMap<>(); return toReturn; } protected ImmutablePair<List<TurboUser>, String> getUpdatedCollaborators(String eTag) { String currETag = eTag; if (!updatedUsers.isEmpty() || eTag == null) currETag = UUID.randomUUID().toString(); ImmutablePair<List<TurboUser>, String> toReturn = new ImmutablePair<>(new ArrayList<>(updatedUsers.values()), currETag); updatedUsers = new TreeMap<>(); return toReturn; } protected List<TurboIssue> getIssues() { return new ArrayList<>(issues.values()); } protected List<TurboLabel> getLabels() { return new ArrayList<>(labels.values()); } protected List<TurboMilestone> getMilestones() { return new ArrayList<>(milestones.values()); } protected List<TurboUser> getCollaborators() { return new ArrayList<>(users.values()); } private TurboIssue makeDummyIssue() { return new TurboIssue(dummyRepoId, issues.size() + 1, "Issue " + (issues.size() + 1), "User " + (issues.size() + 1), LocalDateTime.of(1999 + issues.size(), 1, 1, 0, 0), false); } private TurboIssue makeDummyPR() { return new TurboIssue(dummyRepoId, issues.size() + 1, "PR " + (issues.size() + 1), "User " + (issues.size() + 1), LocalDateTime.of(1999 + issues.size(), 1, 1, 0, 0), true); } private TurboLabel makeDummyLabel() { return new TurboLabel(dummyRepoId, "Label " + (labels.size() + 1)); } private TurboMilestone makeDummyMilestone() { return new TurboMilestone(dummyRepoId, milestones.size() + 1, "Milestone " + (milestones.size() + 1)); } private TurboUser makeDummyUser() { return new TurboUser(dummyRepoId, "User " + (users.size() + 1)); } protected List<TurboIssueEvent> getEvents(int issueId) { TurboIssue issueToGet = issues.get(issueId); if (issueToGet != null) { return issueToGet.getMetadata().getEvents(); } // Fail silently return new ArrayList<>(); } protected List<Comment> getComments(int issueId) { TurboIssue issueToGet = issues.get(issueId); if (issueToGet != null) { return issueToGet.getMetadata().getComments(); } // Fail silently return new ArrayList<>(); } // UpdateEvent methods to directly mutate the repo state protected void makeNewIssue() { TurboIssue toAdd = makeDummyIssue(); issues.put(toAdd.getId(), toAdd); updatedIssues.put(toAdd.getId(), toAdd); } protected void makeNewLabel() { TurboLabel toAdd = makeDummyLabel(); labels.put(toAdd.getActualName(), toAdd); updatedLabels.put(toAdd.getActualName(), toAdd); } protected void makeNewMilestone() { TurboMilestone toAdd = makeDummyMilestone(); milestones.put(toAdd.getId(), toAdd); updatedMilestones.put(toAdd.getId(), toAdd); } protected void makeNewUser() { TurboUser toAdd = makeDummyUser(); users.put(toAdd.getLoginName(), toAdd); updatedUsers.put(toAdd.getLoginName(), toAdd); } // Only updating of issues and milestones is possible. Labels and users are immutable. protected TurboIssue updateIssue(int itemId, String updateText) { TurboIssue issueToUpdate = issues.get(itemId); if (issueToUpdate != null) { return renameIssue(issueToUpdate, updateText); } return null; } private TurboIssue renameIssue(TurboIssue issueToUpdate, String updateText) { // Not allowed to mutate issueToUpdate itself as it introduces immediate changes in the GUI. TurboIssue updatedIssue = new TurboIssue(issueToUpdate); updatedIssue.setTitle(updateText); // Add renamed event to events list of issue List<TurboIssueEvent> eventsOfIssue = updatedIssue.getMetadata().getEvents(); // Not deep copy as the same TurboIssueEvent objects of issueToUpdate are the TurboIssueEvents // of updatedIssue. Might create problems later if eventsOfIssue are to be mutable after downloading // from repo (which should not be the case). // (but this approach works if the metadata of the issue is not modified, which is the current case) // TODO make TurboIssueEvent immutable eventsOfIssue.add(new TurboIssueEvent(new User().setLogin("test"), IssueEventType.Renamed, new Date())); List<Comment> commentsOfIssue = updatedIssue.getMetadata().getComments(); updatedIssue.setMetadata(new IssueMetadata(eventsOfIssue, commentsOfIssue)); updatedIssue.setUpdatedAt(LocalDateTime.now()); // Add to list of updated issues, and replace issueToUpdate in main issues store. updatedIssues.put(updatedIssue.getId(), updatedIssue); issues.put(updatedIssue.getId(), updatedIssue); return issueToUpdate; } protected TurboMilestone updateMilestone(int itemId, String updateText) { TurboMilestone milestoneToUpdate = milestones.get(itemId); if (milestoneToUpdate != null) { return renameMilestone(milestoneToUpdate, updateText); } return null; } private TurboMilestone renameMilestone(TurboMilestone milestoneToUpdate, String updateText) { // Similarly to renameIssue, to avoid immediate update of the GUI when we update // the milestone, milestoneToUpdate is not to be mutated. TurboMilestone updatedMilestone = new TurboMilestone(milestoneToUpdate); updatedMilestone.setTitle(updateText); updatedMilestones.put(updatedMilestone.getId(), updatedMilestone); milestones.put(updatedMilestone.getId(), updatedMilestone); return milestoneToUpdate; } protected TurboIssue deleteIssue(int itemId) { updatedIssues.remove(itemId); return issues.remove(itemId); } protected TurboLabel deleteLabel(String idString) { updatedLabels.remove(idString); return labels.remove(idString); } protected TurboMilestone deleteMilestone(int itemId) { updatedMilestones.remove(itemId); return milestones.remove(itemId); } protected TurboUser deleteUser(String idString) { updatedUsers.remove(idString); return users.remove(idString); } }
package com.github.webdriverextensions; import static com.github.webdriverextensions.Bot.*; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import com.github.webdriverextensions.generator.GeneratedWebRepository; import com.github.webdriverextensions.junitrunner.WebDriverRunner; import com.github.webdriverextensions.junitrunner.annotations.Chrome; import com.github.webdriverextensions.junitrunner.annotations.Edge; import com.github.webdriverextensions.junitrunner.annotations.Firefox; import com.github.webdriverextensions.junitrunner.annotations.HtmlUnit; import com.github.webdriverextensions.junitrunner.annotations.IgnoreSafari; import com.github.webdriverextensions.junitrunner.annotations.InternetExplorer; import com.github.webdriverextensions.junitrunner.annotations.PhantomJS; import com.github.webdriverextensions.junitrunner.annotations.Safari; @RunWith(WebDriverRunner.class) @Chrome //@Firefox @InternetExplorer @Edge @Safari @PhantomJS @HtmlUnit public class BotTest extends GeneratedWebRepository { @Before public void before() { open(botTestPage.url); } /* Click */ @Test public void clickTest() { click(botTestPage.checkbox2); assertIsChecked(botTestPage.checkbox2); } /* Type */ @Test public void typeTest() { clear(botTestPage.textInput); type("text", botTestPage.textInput); assertValueEquals("text", botTestPage.textInput); clear(botTestPage.textInput); type(42.0, botTestPage.textInput); assertValueEquals(42.0, botTestPage.textInput); } /* Clear */ @Test public void clearTest() { clear(botTestPage.textInput); assertValueEquals("", botTestPage.textInput); clearAndType("text", botTestPage.textInput); assertValueEquals("text", botTestPage.textInput); clearAndType(42.0, botTestPage.textInput); assertValueEquals(42.0, botTestPage.textInput); } /* Press Keys */ @Test public void pressKeysTest() { clear(botTestPage.textInput); pressKeys(botTestPage.textInput, "t"); assertValueEquals("t", botTestPage.textInput); pressKeys(botTestPage.textInput, "e"); assertValueEquals("te", botTestPage.textInput); pressKeys(botTestPage.textInput, "x"); assertValueEquals("tex", botTestPage.textInput); pressKeys(botTestPage.textInput, "t"); assertValueEquals("text", botTestPage.textInput); } /* Select/Deselect */ @Test @IgnoreSafari // Fails to select on click in Safari public void selectDeselectTest() { select(botTestPage.multipleSelectOption2); assertIsSelected(botTestPage.multipleSelectOption2); deselect(botTestPage.multipleSelectOption1); assertIsDeselected(botTestPage.multipleSelectOption1); } /* Check/Uncheck */ @Test public void checkUncheckTest() { check(botTestPage.checkbox2); assertIsChecked(botTestPage.checkbox2); uncheck(botTestPage.checkbox1); assertIsUnchecked(botTestPage.checkbox1); } /* Open */ @Test @IgnoreSafari // throws UnsupportedCommandException from RemoteWebElement.isDisplayed() for some reason public void openTest() { debug(driver().getPageSource()); open(botTestPage); assertIsOpen(botTestPage); } /* Wait For */ @Test @IgnoreSafari // throws UnsupportedCommandException from RemoteWebElement.isDisplayed() for some reason public void waitForTest() { waitForElementToDisplay(botTestPage.firstAppendedSpan); assertIsDisplayed(botTestPage.firstAppendedSpan); assertIsNotDisplayed(botTestPage.secondAppendedSpan, 0); waitFor(0.8); waitFor(0.2 / 24 / 60 / 60, TimeUnit.DAYS); waitFor(0.2 / 60 / 60, TimeUnit.HOURS); waitFor(0.2 / 60, TimeUnit.MINUTES); waitFor(0.2, TimeUnit.SECONDS); waitFor(0.2 * 1000, TimeUnit.MILLISECONDS); waitFor(0.2 * 1000 * 1000, TimeUnit.MICROSECONDS); assertIsDisplayed(botTestPage.firstAppendedSpan); assertIsDisplayed(botTestPage.secondAppendedSpan); } @Test @IgnoreSafari // throws UnsupportedCommandException from RemoteWebElement.isDisplayed() for some reason public void waitForElementsToDisplayTest() { waitForElementsToDisplay(botTestPage.appendedSpans); assertIsDisplayed(botTestPage.firstAppendedSpan); assertIsNotDisplayed(botTestPage.secondAppendedSpan); } /* Debug */ @Test public void debugTest() { debug("Text to debug"); debug(botTestPage.attributesSpan); debug(botTestPage.selectAllOption); debug(botTestPage.body); } /* Is Open */ @Test @IgnoreSafari // throws UnsupportedCommandException from RemoteWebElement.isDisplayed() for some reason public void isOpenTest() { assertIsOpen(botTestPage); assertIsNotOpen(webDriverExtensionSite); } /* Is Display */ @Test @IgnoreSafari // throws UnsupportedCommandException from RemoteWebElement.isDisplayed() for some reason public void isDisplayedTest() { assertIsDisplayed(botTestPage.textSpan); assertIsDisplayed(botTestPage.firstAppendedSpan, 2); assertIsNotDisplayed(botTestPage.secondAppendedSpan); assertIsDisplayed(botTestPage.secondAppendedSpan, 2); } /* Size */ @Test public void sizeTest() { assertSizeEquals(3, botTestPage.selectAllOption); assertSizeNotEquals(0, botTestPage.selectAllOption); assertSizeLessThan(4, botTestPage.selectAllOption); assertSizeLessThanOrEquals(3, botTestPage.selectAllOption); assertSizeGreaterThan(2, botTestPage.selectAllOption); assertSizeGreaterThanOrEquals(3, botTestPage.selectAllOption); } /* Url */ @Test public void urlTest() { if (browserIsHtmlUnit()) { assertCurrentUrlEquals(botTestPage.url.replace("file:///", "file:/")); } else { assertCurrentUrlEquals(botTestPage.url); } assertCurrentUrlNotEquals("xxx"); assertCurrentUrlContains("bot-test"); assertCurrentUrlNotContains("xxx"); assertCurrentUrlStartsWith("file:/"); assertCurrentUrlNotStartsWith("xxx"); assertCurrentUrlEndsWith("/bot-test.html"); assertCurrentUrlNotEndsWith("xxx"); assertCurrentUrlMatches(".*bot-test.*"); assertCurrentUrlNotMatches(".*xxx.*"); } /* Title */ @Test public void titleTest() { assertTitleEquals("prefixtitlesuffix"); assertTitleNotEquals("xxx"); assertTitleContains("title"); assertTitleNotContains("xxx"); assertTitleStartsWith("prefixtitle"); assertTitleNotStartsWith("xxx"); assertTitleEndsWith("titlesuffix"); assertTitleNotEndsWith("xxx"); assertTitleMatches(".*title.*"); assertTitleNotMatches(".*xxx.*"); } /* Tag Name */ @Test public void tagNameTest() { assertTagNameEquals("span", botTestPage.attributesSpan); assertTagNameNotEquals("xxx", botTestPage.attributesSpan); } /* Attribute */ @Test public void attributeTest() { assertAttributeEquals("id", "prefixidsuffix", botTestPage.attributesSpan); assertAttributeNotEquals("id", "xxx", botTestPage.attributesSpan); assertAttributeContains("id", "id", botTestPage.attributesSpan); assertAttributeNotContains("id", "xxx", botTestPage.attributesSpan); assertAttributeStartsWith("id", "prefixid", botTestPage.attributesSpan); assertAttributeNotStartsWith("id", "xxx", botTestPage.attributesSpan); assertAttributeEndsWith("id", "idsuffix", botTestPage.attributesSpan); assertAttributeNotEndsWith("id", "xxx", botTestPage.attributesSpan); assertAttributeMatches("id", ".*id.*", botTestPage.attributesSpan); assertAttributeNotMatches("id", ".*xxx.*", botTestPage.attributesSpan); } @Test public void idTest() { assertIdEquals("prefixidsuffix", botTestPage.attributesSpan); assertIdNotEquals("xxx", botTestPage.attributesSpan); assertIdContains("id", botTestPage.attributesSpan); assertIdNotContains("xxx", botTestPage.attributesSpan); assertIdStartsWith("prefixid", botTestPage.attributesSpan); assertIdNotStartsWith("xxx", botTestPage.attributesSpan); assertIdEndsWith("idsuffix", botTestPage.attributesSpan); assertIdNotEndsWith("xxx", botTestPage.attributesSpan); assertIdMatches(".*id.*", botTestPage.attributesSpan); assertIdNotMatches(".*xxx.*", botTestPage.attributesSpan); } /* Name */ @Test public void nameTest() { assertNameEquals("prefixnamesuffix", botTestPage.attributesSpan); assertNameNotEquals("xxx", botTestPage.attributesSpan); assertNameContains("name", botTestPage.attributesSpan); assertNameNotContains("xxx", botTestPage.attributesSpan); assertNameStartsWith("prefixname", botTestPage.attributesSpan); assertNameNotStartsWith("xxx", botTestPage.attributesSpan); assertNameEndsWith("namesuffix", botTestPage.attributesSpan); assertNameNotEndsWith("xxx", botTestPage.attributesSpan); assertNameMatches(".*name.*", botTestPage.attributesSpan); assertNameNotMatches(".*xxx.*", botTestPage.attributesSpan); } /* Class */ @Test public void classTest() { assertHasClass("prefixclass1suffix", botTestPage.attributesSpan); assertHasClass("prefixclass2suffix", botTestPage.attributesSpan); assertHasClass("prefixclass3suffix", botTestPage.attributesSpan); Assert.assertThat(classIn(botTestPage.attributesSpan), equalTo(" prefixclass1suffix prefixclass2suffix prefixclass3suffix ")); List<String> classes = classesIn(botTestPage.attributesSpan); Assert.assertThat(classes, hasItem("prefixclass1suffix")); Assert.assertThat(classes, hasItem("prefixclass2suffix")); Assert.assertThat(classes, hasItem("prefixclass3suffix")); } /* Value */ @Test public void valueTest() { assertValueEquals("prefixvaluesuffix", botTestPage.attributesSpan); assertValueNotEquals("xxx", botTestPage.attributesSpan); assertValueContains("value", botTestPage.attributesSpan); assertValueNotContains("xxx", botTestPage.attributesSpan); assertValueStartsWith("prefixvalue", botTestPage.attributesSpan); assertValueNotStartsWith("xxx", botTestPage.attributesSpan); assertValueEndsWith("valuesuffix", botTestPage.attributesSpan); assertValueNotEndsWith("xxx", botTestPage.attributesSpan); assertValueMatches(".*value.*", botTestPage.attributesSpan); assertValueNotMatches(".*xxx.*", botTestPage.attributesSpan); } /* Value Number */ @Test public void valueNumberTest() { // floatNumberInput assertValueIsNumber(botTestPage.floatNumberInput); assertValueIsNotNumber(botTestPage.textInput); assertValueEquals(42.0, botTestPage.floatNumberInput); assertValueNotEquals(43.0, botTestPage.floatNumberInput); assertValueLessThan(43.0, botTestPage.floatNumberInput); assertValueLessThanOrEquals(42.0, botTestPage.floatNumberInput); assertValueGreaterThan(41.0, botTestPage.floatNumberInput); assertValueGreaterThanOrEquals(42.0, botTestPage.floatNumberInput); // intNumberInput assertValueIsNumber(botTestPage.intNumberInput); assertValueIsNotNumber(botTestPage.textInput); assertValueEquals(42.0, botTestPage.intNumberInput); assertValueNotEquals(43.0, botTestPage.intNumberInput); assertValueLessThan(43.0, botTestPage.intNumberInput); assertValueLessThanOrEquals(42.0, botTestPage.intNumberInput); assertValueGreaterThan(41.0, botTestPage.intNumberInput); assertValueGreaterThanOrEquals(42.0, botTestPage.intNumberInput); } /* Href */ @Test public void hrefTest() { if (browserIsHtmlUnit()) { String filePath = botTestPage.url.replace("file:///", "file:/").replace("bot-test.html", ""); assertHrefEquals(filePath + "prefixhrefsuffix", botTestPage.attributesSpan); } else { assertHrefEquals("prefixhrefsuffix", botTestPage.attributesSpan); } assertHrefNotEquals("xxx", botTestPage.attributesSpan); assertHrefContains("href", botTestPage.attributesSpan); assertHrefNotContains("xxx", botTestPage.attributesSpan); if (browserIsHtmlUnit()) { String filePath = botTestPage.url.replace("file:///", "file:/").replace("bot-test.html", ""); assertHrefStartsWith(filePath + "prefixhref", botTestPage.attributesSpan); } else { assertHrefStartsWith("prefixhref", botTestPage.attributesSpan); } assertHrefNotStartsWith("xxx", botTestPage.attributesSpan); assertHrefEndsWith("hrefsuffix", botTestPage.attributesSpan); assertHrefNotEndsWith("xxx", botTestPage.attributesSpan); assertHrefMatches(".*href.*", botTestPage.attributesSpan); assertHrefNotMatches(".*xxx.*", botTestPage.attributesSpan); } /* Text */ @Test public void textTest() { assertTextEquals("prefixtextsuffix", botTestPage.textSpan); assertTextNotEquals("xxx", botTestPage.textSpan); assertTextEqualsIgnoreCase("PREFIXTEXTSUFFIX", botTestPage.textSpan); assertTextNotEqualsIgnoreCase("xxx", botTestPage.textSpan); assertTextContains("text", botTestPage.textSpan); assertTextNotContains("xxx", botTestPage.textSpan); assertTextContainsIgnoreCase("TEXT", botTestPage.textSpan); assertTextNotContainsIgnoreCase("xxx", botTestPage.textSpan); assertTextStartsWith("prefixtext", botTestPage.textSpan); assertTextNotStartsWith("xxx", botTestPage.textSpan); assertTextStartsWithIgnoreCase("PREFIXTEXT", botTestPage.textSpan); assertTextNotStartsWithIgnoreCase("xxx", botTestPage.textSpan); assertTextEndsWith("textsuffix", botTestPage.textSpan); assertTextNotEndsWith("xxx", botTestPage.textSpan); assertTextEndsWithIgnoreCase("TEXTSUFFIX", botTestPage.textSpan); assertTextNotEndsWithIgnoreCase("xxx", botTestPage.textSpan); assertTextMatches(".*text.*", botTestPage.textSpan); assertTextNotMatches(".*xxx.*", botTestPage.textSpan); } /* Text Number */ @Test public void textNumberTest() { // floatNumberSpan assertTextIsNumber(botTestPage.floatNumberSpan); assertTextIsNotNumber(botTestPage.textSpan); assertTextEquals(42.0, botTestPage.floatNumberSpan); assertTextNotEquals(43.0, botTestPage.floatNumberSpan); assertTextLessThan(43.0, botTestPage.floatNumberSpan); assertTextLessThanOrEquals(42.0, botTestPage.floatNumberSpan); assertTextGreaterThan(41.0, botTestPage.floatNumberSpan); assertTextGreaterThanOrEquals(42.0, botTestPage.floatNumberSpan); // intNumberSpan assertTextIsNumber(botTestPage.intNumberSpan); assertTextIsNotNumber(botTestPage.textSpan); assertTextEquals(42.0, botTestPage.intNumberSpan); assertTextNotEquals(43.0, botTestPage.intNumberSpan); assertTextLessThan(43.0, botTestPage.intNumberSpan); assertTextLessThanOrEquals(42.0, botTestPage.intNumberSpan); assertTextGreaterThan(41.0, botTestPage.intNumberSpan); assertTextGreaterThanOrEquals(42.0, botTestPage.intNumberSpan); } /* Selected/Deselected */ @Test public void selectedDeselectedTest() { assertIsSelected(botTestPage.selectOption1); assertIsDeselected(botTestPage.selectOption2); } /* Checked/Unchecked */ @Test public void checkedUncheckedTest() { // checkboxes assertIsChecked(botTestPage.checkbox1); assertIsUnchecked(botTestPage.checkbox2); // radiobuttons assertIsChecked(botTestPage.radiobutton1); assertIsUnchecked(botTestPage.radiobutton2); } /* Enabled/Disabled */ @Test public void enabledDisabledTest() { assertIsEnabled(botTestPage.selectOption1); assertIsEnabled(botTestPage.selectOption2); assertIsDisabled(botTestPage.selectOption3); } /* Option */ @Test public void optionTest() { // Selected/Deselected assertOptionIsSelected("Option 1", botTestPage.select); assertOptionIsDeselected("Option 2", botTestPage.select); assertOptionIsDeselected("Option 3", botTestPage.select); // Enabled/Disabled assertOptionIsEnabled("Option 1", botTestPage.select); assertOptionIsEnabled("Option 2", botTestPage.select); assertOptionIsDisabled("Option 3", botTestPage.select); } /* Option Value */ @Test public void optionValueTest() { // Selected/Deselected assertOptionWithValueIsSelected("option1value", botTestPage.select); assertOptionWithValueIsDeselected("option2value", botTestPage.select); assertOptionWithValueIsDeselected("option3value", botTestPage.select); // Enabled/Disabled assertOptionWithValueIsEnabled("option1value", botTestPage.select); assertOptionWithValueIsEnabled("option2value", botTestPage.select); assertOptionWithValueIsDisabled("option3value", botTestPage.select); } /* Option Index */ @Test public void optionIndexTest() { // Selected/Deselected assertOptionWithIndexIsSelected(0, botTestPage.select); assertOptionWithIndexIsDeselected(1, botTestPage.select); assertOptionWithIndexIsDeselected(2, botTestPage.select); // Enabled/Disabled assertOptionWithIndexIsEnabled(0, botTestPage.select); assertOptionWithIndexIsEnabled(1, botTestPage.select); assertOptionWithIndexIsDisabled(2, botTestPage.select); } }
package com.everypay.everypay; import android.content.Intent; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Pair; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import com.everypay.everypay.fragment.MessageDialogFragment; import com.everypay.everypay.fragment.SingleChoiceDialogFragment; import com.everypay.everypay.util.DialogUtil; import com.everypay.sdk.EveryPay; import com.everypay.sdk.EveryPayListener; import com.everypay.sdk.activity.CardFormActivity; import com.everypay.sdk.api.EveryPayError; import com.everypay.sdk.api.responsedata.MerchantPaymentResponseData; import com.everypay.sdk.model.Card; import com.everypay.sdk.steps.StepType; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity implements SingleChoiceDialogFragment.SingleChoiceDialogFragmentListener { private static final String ACCOUNT_ID_3DS = "EUR3D1"; private static final String ACCOUNT_ID_NON_3DS = "EUR1"; private static final String API_VERSION = "2"; private static final String EXTRA_CARD = "com.everypay.everypay.EXTRA_CARD"; private static final String TAG_ACCOUNT_CHOICE_DIALOG = "com.everypay.everypay.TAG_ACCOUNT_CHOICE_DIALOG"; private static final String TAG_ENVIRONMENT_CHOICE_DIALOG = "com.everypay.everypay.TAG_ENVIRONMENT_CHOICE_DIALOG"; private static final String TAG_START_FULL_PAYMENT_FLOW = "com.everypay.everypay.TAG_START_FULL_PAYMENT_FLOW"; private static final String EXTRA_DEVICE_INFO = "com.everypay.everypay.EXTRA_DEVICE_INFO"; private static final String STATE_ACCOUNT_ID_CHOICES = "com.everypay.everypay.STATE_ACCOUNT_ID_CHOICES"; private static final String KEY_STAGING_ENVIRONMENT = "Staging Environment"; private static final String KEY_DEMO_ENVIRONMENT = "Demo Environment"; private static final String STATE_BASE_URL_CHOICES = "com.everypay.everypay.STATE_BASE_URL_CHOICES"; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; private static final int REQUEST_CODE_ACCOUNT_ID_CHOICE = 100; private static final int REQUEST_CODE_BASE_URL_CHOICE = 101; private static final String TAG_MESSAGE_DIALOG = "com.everypay.everypay.TAG_MESSAGE_DIALOG"; private static final int REQUEST_CODE_MESSAGE_DIALOG = 102; private static com.everypay.sdk.util.Log log = com.everypay.sdk.util.Log.getInstance(MainActivity.class); private ArrayList<String> accountIdChoices; private ArrayList<String> environments; private HashMap<String, ArrayList<String>> baseUrlMap; private StepStatusViews[] statuses; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (checkPlayServices()) { initializeChoices(); attachUiEvents(); } else { finish(); } if (savedInstanceState != null) { accountIdChoices = savedInstanceState.getStringArrayList(STATE_ACCOUNT_ID_CHOICES); } } private void initializeChoices() { // Account Id choices accountIdChoices = new ArrayList<>(); accountIdChoices.add(ACCOUNT_ID_3DS); accountIdChoices.add(ACCOUNT_ID_NON_3DS); // base URL choices baseUrlMap = new HashMap<>(); // array of URLs in the order: merchantApiBaseUrl, EveryPayApiBaseUrl, EveryPayHost ArrayList<String> stagingURLs = new ArrayList<>(); stagingURLs.add(EveryPay.MERCHANT_API_URL_STAGING); stagingURLs.add(EveryPay.EVERYPAY_API_URL_STAGING); stagingURLs.add(EveryPay.EVERYPAY_API_STAGING_HOST); ArrayList<String> demoURLs = new ArrayList<>(); demoURLs.add(EveryPay.MERCHANT_API_URL_DEMO); demoURLs.add(EveryPay.EVERYPAY_API_URL_DEMO); demoURLs.add(EveryPay.EVERYPAY_API_DEMO_HOST); baseUrlMap.put(KEY_STAGING_ENVIRONMENT, stagingURLs); baseUrlMap.put(KEY_DEMO_ENVIRONMENT, demoURLs); environments = new ArrayList<>(); environments.add(KEY_STAGING_ENVIRONMENT); environments.add(KEY_DEMO_ENVIRONMENT); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CardFormActivity.REQUEST_CODE) { hideStatusViews(StepType.CARD_INPUT); Pair<Card, String> result = CardFormActivity.getCardAndDeviceInfoFromResult(resultCode, data); if (result != null) { Bundle extras = new Bundle(); extras.putParcelable(EXTRA_CARD, result.first); extras.putString(EXTRA_DEVICE_INFO, result.second); SingleChoiceDialogFragment fragment = SingleChoiceDialogFragment.newInstance(getString(R.string.title_choose_environment), getString(R.string.text_choose_environment), environments, extras); DialogUtil.showDialogFragment(MainActivity.this, fragment, TAG_ENVIRONMENT_CHOICE_DIALOG, null, REQUEST_CODE_BASE_URL_CHOICE); statuses[0].good.setVisibility(View.VISIBLE); } else { statuses[0].bad.setVisibility(View.VISIBLE); displayMessageDialog(getString(R.string.ep_title_no_valid_card), getString(R.string.ep_err_no_valid_card)); } } else { super.onActivityResult(requestCode, resultCode, data); } } private void attachUiEvents() { // we need to count out web auth step and confirm3Ds step statuses = new StepStatusViews[StepType.values().length]; statuses[0] = new StepStatusViews(R.id.card_good, R.id.card_bad, R.id.card_progress); statuses[1] = new StepStatusViews(R.id.credentials_good, R.id.credentials_bad, R.id.credentials_progress); statuses[2] = new StepStatusViews(R.id.token_good, R.id.token_bad, R.id.token_progress); statuses[3] = new StepStatusViews(R.id.payment_good, R.id.payment_bad, R.id.payment_progress); for (int i = 0; i < statuses.length - 2; i++) { StepStatusViews view = statuses[i]; view.good.setColorFilter(ContextCompat.getColor(MainActivity.this, R.color.tint_good)); view.bad.setColorFilter(ContextCompat.getColor(MainActivity.this, R.color.tint_bad)); } hideAllStatusViews(); findViewById(R.id.start).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((Button) findViewById(R.id.start)).setText(MainActivity.this.getResources().getString(R.string.ep_btn_restart)); hideAllStatusViews(); statuses[0].progress.setVisibility(View.VISIBLE); // Initial card data is entirely optional. // Use null to let the user fill out the card form. Card initial = new Card(); initial.setName(MainActivity.this.getResources().getString(R.string.ep_initial_card_name)); initial.setNumber(MainActivity.this.getResources().getString(R.string.ep_initial_card_number)); initial.setExpYear(MainActivity.this.getResources().getString(R.string.ep_initial_card_exp_year)); initial.setExpMonth(MainActivity.this.getResources().getString(R.string.ep_initial_card_exp_month)); initial.setCVC(MainActivity.this.getResources().getString(R.string.ep_initial_card_cvc)); CardFormActivity.startForResult(MainActivity.this, initial); } }); } private void hideAllStatusViews() { for (int i = 0; i < statuses.length - 2; i++) { StepStatusViews view = statuses[i]; view.good.setVisibility(View.GONE); view.bad.setVisibility(View.GONE); view.progress.setVisibility(View.GONE); } } private void hideStatusViews(StepType step) { if(!step.equals(StepType.WEB_AUTH_STEP)) { StepStatusViews views = statuses[step.ordinal()]; views.good.setVisibility(View.GONE); views.bad.setVisibility(View.GONE); views.progress.setVisibility(View.GONE); } } @Override protected void onDestroy() { super.onDestroy(); if (EveryPay.getDefault() != null) { EveryPay.getDefault().removeListener(TAG_START_FULL_PAYMENT_FLOW); } } @Override public void onSingleChoicePicked(int requestCode, int position, Bundle extras) { if (requestCode == REQUEST_CODE_BASE_URL_CHOICE) { String baseURLKey = environments.size() > position ? environments.get(position) : null; if (!TextUtils.isEmpty(baseURLKey)) { ArrayList<String> baseURLs = baseUrlMap.get(baseURLKey); if (baseURLs != null && baseURLs.size() != 0) { EveryPay.with(this).setEverypayApiBaseUrl(baseURLs.get(1)).setMerchantApiBaseUrl(baseURLs.get(0)).setEveryPayHost(baseURLs.get(2)).build(API_VERSION).setDefault(); SingleChoiceDialogFragment dialogFragment = SingleChoiceDialogFragment.newInstance(getString(R.string.title_choose_account), getString(R.string.text_choose_account_id), accountIdChoices, extras); DialogUtil.showDialogFragment(MainActivity.this, dialogFragment, TAG_ACCOUNT_CHOICE_DIALOG, null, REQUEST_CODE_ACCOUNT_ID_CHOICE); } } } else if (requestCode == REQUEST_CODE_ACCOUNT_ID_CHOICE) { Card card = extras.getParcelable(EXTRA_CARD); String deviceInfo = extras.getString(EXTRA_DEVICE_INFO); String accountId = accountIdChoices.size() > position ? accountIdChoices.get(position) : null; if (card != null && !TextUtils.isEmpty(deviceInfo) && accountId != null) { EveryPay.getDefault().startFullPaymentFlow(TAG_START_FULL_PAYMENT_FLOW, card, deviceInfo, new EveryPayListener() { @Override public void stepStarted(StepType step) { log.d("Started step " + step); hideStatusViews(step); statuses[step.ordinal()].progress.setVisibility(View.VISIBLE); } @Override public void stepSuccess(StepType step) { log.d("Completed step " + step); hideStatusViews(step); statuses[step.ordinal()].good.setVisibility(View.VISIBLE); } @Override public void fullSuccess(MerchantPaymentResponseData responseData) { displayMessageDialog(getString(R.string.ep_title_payment_successful), getString(R.string.ep_text_payment_successful, responseData.toString())); } @Override public void stepFailure(StepType step, EveryPayError error) { hideStatusViews(step); if(!step.equals(StepType.WEB_AUTH_STEP)){ statuses[step.ordinal()].bad.setVisibility(View.VISIBLE); } displayMessageDialog(getString(R.string.ep_title_step_failed), getString(R.string.ep_text_step_failed,step,error.getMessage())); } }, accountId); } } } private void displayMessageDialog(String title, String message) { MessageDialogFragment fragment = MessageDialogFragment.newInstance(title, message, getString(R.string.ep_btn_ok)); DialogUtil.showDialogFragment(MainActivity.this, fragment, TAG_MESSAGE_DIALOG, null, REQUEST_CODE_MESSAGE_DIALOG); } @Override public void onSingleChoiceCanceled(int requestCode, Bundle extras) { } private class StepStatusViews { public ImageView good; public ImageView bad; public ProgressBar progress; public StepStatusViews(int goodId, int badId, int progressId) { good = (ImageView) findViewById(goodId); bad = (ImageView) findViewById(badId); progress = (ProgressBar) findViewById(progressId); } } /** * Check the device to make sure it has the Google Play Services APK. If * it doesn't, display a dialog that allows users to download the APK from * the Google Play Store or enable it in the device's system settings. */ private boolean checkPlayServices() { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); int resultCode = apiAvailability.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (apiAvailability.isUserResolvableError(resultCode)) { apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST) .show(); } else { log.e("This device is not supported."); finish(); } return false; } return true; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putStringArrayList(STATE_ACCOUNT_ID_CHOICES, accountIdChoices); outState.putSerializable(STATE_BASE_URL_CHOICES, baseUrlMap); } }
import javafx.application.Application; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.geometry.Point2D; import javafx.scene.Scene; import javafx.scene.control.ScrollPane; import javafx.scene.layout.GridPane; import javafx.scene.paint.Paint; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Pair; import java.awt.Toolkit; import java.util.*; import java.util.stream.Collectors; public class Main extends Application { private List<Circle> playerMarkers = new ArrayList<>(); private List<Pair<Circle, Point2D>> circleList = new ArrayList<>(); private Stage stage; private double screenWidth, screenHeight; private BooleanProperty player1Turn = new SimpleBooleanProperty(true); private GameBoard gameBoard; int numInRow = 0; private List<Pair<Circle, Point2D>> checks; public void start(Stage stage) { // Get the user's screensize screenWidth = Toolkit.getDefaultToolkit().getScreenSize().getWidth(); screenHeight = Toolkit.getDefaultToolkit().getScreenSize().getHeight(); this.stage = stage; this.stage.setScene(initGameBoard()); this.stage.setMaximized(true); this.stage.show(); } public static void main(String[] args) { launch(args); } /** * Initiates the Gameboard and sets up the eventlistener * * @return A Scene with a GridPane */ private Scene initGameBoard() { gameBoard = new GameBoard(screenWidth, screenHeight); ScrollPane gamePane = new ScrollPane(); gamePane.setContent(gameBoard); Scene gameScene = new Scene(gamePane, screenWidth, screenHeight); gameBoard.setOnMouseClicked(mouseClick -> { // Find out which column and row the user clicked int clickCol = (int)Math.round(((mouseClick.getX() - (mouseClick.getX() % gameBoard.getCellSize())) / gameBoard.getCellSize())); int clickRow = (int)Math.round(((mouseClick.getY() - (mouseClick.getY() % gameBoard.getCellSize())) / gameBoard.getCellSize())); // Check wether the click was outside the grid if (clickCol > gameBoard.getRows() -1){clickCol = gameBoard.getRows()-1;} if (clickRow > gameBoard.getRows() -1){clickRow = gameBoard.getRows()-1;} // If the click was made in an empty cell // place a marker in that cell with a color // that corresponds to which player is currently playing // and add that marker to a list if (!checkDoubles(clickCol, clickRow)) { if (player1Turn.getValue()) { Circle marker = new PlayerMarker().placeMarker(1); gameBoard.add(marker, clickCol, clickRow); playerMarkers.add(marker); } else { Circle marker = new PlayerMarker().placeMarker(2); gameBoard.add(marker, clickCol, clickRow); playerMarkers.add(marker); } } // Check if the grid is full of markers if(playerMarkers.size()==(gameBoard.getRows()*gameBoard.getRows())) { // Increase the gameboard's size gameBoard.incGameBoard(); // Move the markers playerMarkers.forEach(marker -> { int col = GridPane.getColumnIndex(marker); int row = GridPane.getRowIndex(marker); gameBoard.getChildren().remove(marker); gameBoard.add(marker, col+1, row+1); }); } // Bind the marker's radius so that they always fits in the cells playerMarkers.forEach(marker -> { marker.radiusProperty().bind(gameBoard.getCellSizeProperty().divide(2)); }); checkWinner(); // Change the player to play player1Turn.setValue(!player1Turn.getValue()); }); return gameScene; } /** * Check if the marker is placed in an empty cell * * @param col The column where the player tried to place a marker * @param row The row where the player tried to place a marker * * @return True if there is a double, False otherwise */ private boolean checkDoubles(int col, int row) { for (Circle circle : playerMarkers) { if (GridPane.getColumnIndex(circle) - col == 0 && GridPane.getRowIndex(circle) - row == 0) { return true; } } return false; } /** * Check if there is a player with 3 markers in a row */ private void checkWinner() { System.out.println(" Circle lastMarker = playerMarkers.get(playerMarkers.size()-1); int column = GridPane.getColumnIndex(lastMarker); int row = GridPane.getRowIndex(lastMarker); Paint color = lastMarker.getFill(); circleList.clear(); playerMarkers.forEach(marker -> { circleList.add(new Pair(marker, new Point2D( (int) GridPane.getColumnIndex(marker), (int) GridPane.getRowIndex(marker)))); }); // Inserts all the markers with the same color on a single row in a new list checks = circleList.stream().filter(c -> c.getValue().getY() == row) .filter(c -> c.getKey().getFill() == color).collect(Collectors.toList()); // Sort the new list according to the element's x-coordinate Collections.sort(checks, new Comparator<Pair<Circle, Point2D>>() { @Override public int compare(Pair<Circle, Point2D> c1, Pair<Circle, Point2D> c2) { if(c1.getValue().getX() < c2.getValue().getX()) return -1; if(c1.getValue().getX() > c2.getValue().getX()) return 1; return 0; } }); // Check row numInRow = 0; // Check if 3 adjacent markers have the same color if(checks.size() > 2) { for (int i = 0; i<checks.size()-1; i++) { if (checks.get(i+1).getValue().getX() - checks.get(i).getValue().getX() == 1) { numInRow++; } else {numInRow = 0;} } for (int i = checks.size()-1; i>0; i if (checks.get(i).getValue().getX() - checks.get(i-1).getValue().getX() == 1) { numInRow++; } else {numInRow = 0;} } } if (numInRow > 2) { System.out.println("Vinner row"); } // Check column numInRow = 0; // Check if 3 adjacent markers have the same color if(checks.size() > 2) { for (int i = 0; i<checks.size()-1; i++) { if (checks.get(i+1).getValue().getY() - checks.get(i).getValue().getY() == 1) { numInRow++; } else {numInRow = 0;} } for (int i = checks.size()-1; i>0; i if (checks.get(i).getValue().getY() - checks.get(i-1).getValue().getY() == 1) { numInRow++; } else {numInRow = 0;} } } if (numInRow > 2) { System.out.println("Vinner column"); } // Check diag (forward slash) numInRow = 0; // Check if 3 adjacent markers have the same color if(checks.size() > 2) { for (int i = 0; i<checks.size()-1; i++) { if (checks.get(i+1).getValue().getY() - checks.get(i).getValue().getY() == -1 && checks.get(i+1).getValue().getX() - checks.get(i).getValue().getX() == 1) { numInRow++; } else {numInRow = 0;} } for (int i = checks.size()-1; i>0; i if (checks.get(i).getValue().getY() - checks.get(i-1).getValue().getY() == -1 && checks.get(i).getValue().getX() - checks.get(i-1).getValue().getX() == 1) { numInRow++; } else {numInRow = 0;} } } if (numInRow >= 2) { System.out.println("Vinner /"); } // Check diag (backslash) numInRow = 0; // Check if 3 adjacent markers have the same color if(checks.size() > 2) { for (int i = 0; i<checks.size()-1; i++) { System.out.println(checks.get(i+1).getValue().getY() - checks.get(i).getValue().getY()); System.out.println(checks.get(i+1).getValue().getX() - checks.get(i).getValue().getX()); if (checks.get(i+1).getValue().getY() - checks.get(i).getValue().getY() == 1 && checks.get(i+1).getValue().getX() - checks.get(i).getValue().getX() == 1) { numInRow++; System.out.println(numInRow); } else {numInRow = 0;} } for (int i = checks.size()-1; i>0; i System.out.println(checks.get(i).getValue().getY() - checks.get(i-1).getValue().getY()); System.out.println(checks.get(i).getValue().getX() - checks.get(i-1).getValue().getX()); if (checks.get(i).getValue().getY() - checks.get(i-1).getValue().getY() == 1 && checks.get(i).getValue().getX() - checks.get(i-1).getValue().getX() == 1) { numInRow++; System.out.println(numInRow); } else {numInRow = 0;} } if (numInRow >= 2) { System.out.println("Vinner \\"); } } checks.forEach(circle -> { System.out.println("X: " + circle.getValue().getX() + " Y: " + circle.getValue().getY()); }); } }
package edu.umd.cs.findbugs.detect; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.ConstantNameAndType; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.MethodAnnotation; import edu.umd.cs.findbugs.Priorities; import edu.umd.cs.findbugs.StatelessDetector; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.PruneUnconditionalExceptionThrowerEdges; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.ch.Subtypes2; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.visitclass.DismantleBytecode; public class CloneIdiom extends DismantleBytecode implements Detector, StatelessDetector { private ClassDescriptor cloneDescriptor = DescriptorFactory.createClassDescriptor(java.lang.Cloneable.class); boolean isCloneable,hasCloneMethod; boolean cloneIsDeprecated; MethodAnnotation cloneMethodAnnotation; boolean referencesCloneMethod; boolean invokesSuperClone; boolean isFinal; boolean cloneOnlyThrowsException; boolean check; //boolean throwsExceptions; boolean implementsCloneableDirectly; private BugReporter bugReporter; public CloneIdiom(BugReporter bugReporter) { this.bugReporter = bugReporter; } public void visitClassContext(ClassContext classContext) { classContext.getJavaClass().accept(this); } @Override public void visit(Code obj) { if (getMethodName().equals("clone") && getMethodSig().startsWith("()")) super.visit(obj); } @Override public void sawOpcode(int seen) { if (seen == INVOKESPECIAL && getNameConstantOperand().equals("clone") && getSigConstantOperand().startsWith("()")) { /* System.out.println("Saw call to " + nameConstant + ":" + sigConstant + " in " + betterMethodName); */ invokesSuperClone = true; } } @Override public void visit(JavaClass obj) { implementsCloneableDirectly = false; invokesSuperClone = false; cloneOnlyThrowsException = false; isCloneable = false; check = false; isFinal = obj.isFinal(); if (obj.isInterface()) return; if (obj.isAbstract()) return; // Does this class directly implement Cloneable? String[] interface_names = obj.getInterfaceNames(); for (String interface_name : interface_names) { if (interface_name.equals("java.lang.Cloneable")) { implementsCloneableDirectly = true; isCloneable = true; break; } } Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2(); try { if (subtypes2.isSubtype(getClassDescriptor(), cloneDescriptor)) isCloneable = true; if (subtypes2.isSubtype(DescriptorFactory.createClassDescriptorFromDottedClassName(obj.getSuperclassName()), cloneDescriptor)) implementsCloneableDirectly = false; } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } hasCloneMethod = false; referencesCloneMethod = false; check = true; super.visit(obj); } @Override public void visitAfter(JavaClass obj) { if (!check) return; if (cloneOnlyThrowsException) return; if (implementsCloneableDirectly && !hasCloneMethod) { if (!referencesCloneMethod) bugReporter.reportBug(new BugInstance(this, "CN_IDIOM", NORMAL_PRIORITY) .addClass(this)); } if (hasCloneMethod && isCloneable && !invokesSuperClone && !isFinal && obj.isPublic()) { int priority = LOW_PRIORITY; if (obj.isPublic() || obj.isProtected()) priority = NORMAL_PRIORITY; try { Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2(); if (!subtypes2.getDirectSubtypes(getClassDescriptor()).isEmpty()) priority } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } bugReporter.reportBug(new BugInstance(this, "CN_IDIOM_NO_SUPER_CALL", priority) .addClass(this) .addMethod(cloneMethodAnnotation)); } else if (hasCloneMethod && !isCloneable && !cloneOnlyThrowsException && !cloneIsDeprecated && !obj.isAbstract()) { int priority = Priorities.NORMAL_PRIORITY; if (referencesCloneMethod) priority bugReporter.reportBug(new BugInstance(this, "CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE", priority) .addClass(this) .addMethod(cloneMethodAnnotation)); } } @Override public void visit(ConstantNameAndType obj) { String methodName = obj.getName(getConstantPool()); String methodSig = obj.getSignature(getConstantPool()); if (!methodName.equals("clone")) return; if (!methodSig.startsWith("()")) return; referencesCloneMethod = true; } @Override public void visit(Method obj) { if (obj.isAbstract()) return; if (!obj.isPublic()) return; if (!getMethodName().equals("clone")) return; if (!getMethodSig().startsWith("()")) return; hasCloneMethod = true; cloneIsDeprecated = getXMethod().isDeprecated(); cloneMethodAnnotation = MethodAnnotation.fromVisitedMethod(this); cloneOnlyThrowsException = PruneUnconditionalExceptionThrowerEdges.doesMethodUnconditionallyThrowException(XFactory.createXMethod(this)); //ExceptionTable tbl = obj.getExceptionTable(); //throwsExceptions = tbl != null && tbl.getNumberOfExceptions() > 0; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.Detector#report() */ public void report() { // do nothing } }
package de.geeksfactory.opacclient.frontend; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.json.JSONException; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.WazaBe.HoloEverywhere.app.ProgressDialog; import com.actionbarsherlock.view.Menu; import de.geeksfactory.opacclient.OpacClient; import de.geeksfactory.opacclient.OpacTask; import de.geeksfactory.opacclient.R; import de.geeksfactory.opacclient.frontend.WelcomeActivity.InitTask; import de.geeksfactory.opacclient.objects.Account; import de.geeksfactory.opacclient.objects.Library; import de.geeksfactory.opacclient.storage.AccountDataSource; public class FrontpageActivity extends OpacActivity { protected ProgressDialog dialog; public void urlintent() { Uri d = getIntent().getData(); if (d.getHost().equals("de.geeksfactory.opacclient")) { String medianr = d.getQueryParameter("id"); if (medianr != null) { Intent intent = new Intent(FrontpageActivity.this, SearchResultDetailsActivity.class); intent.putExtra("item_id", medianr); startActivity(intent); finish(); return; } String titel = d.getQueryParameter("titel"); String verfasser = d.getQueryParameter("verfasser"); String schlag_a = d.getQueryParameter("schlag_a"); String schlag_b = d.getQueryParameter("schlag_b"); String isbn = d.getQueryParameter("isbn"); String jahr_von = d.getQueryParameter("jahr_von"); String jahr_bis = d.getQueryParameter("jahr_bis"); String verlag = d.getQueryParameter("verlag"); Intent myIntent = new Intent(FrontpageActivity.this, SearchResultsActivity.class); myIntent.putExtra("titel", (titel != null ? titel : "")); myIntent.putExtra("verfasser", (verfasser != null ? verfasser : "")); myIntent.putExtra("schlag_a", (schlag_a != null ? schlag_a : "")); myIntent.putExtra("schlag_b", (schlag_b != null ? schlag_b : "")); myIntent.putExtra("isbn", (isbn != null ? isbn : "")); myIntent.putExtra("jahr_von", (jahr_von != null ? jahr_von : "")); myIntent.putExtra("jahr_bis", (jahr_bis != null ? jahr_bis : "")); myIntent.putExtra("verlag", (verlag != null ? verlag : "")); startActivity(myIntent); finish(); } else if (d.getHost().equals("www.raphaelmichel.de")) { String bib; try { bib = java.net.URLDecoder.decode(d.getQueryParameter("bib"), "UTF-8"); } catch (UnsupportedEncodingException e) { bib = d.getQueryParameter("bib"); } if (!app.getLibrary().getIdent().equals(bib)) { Intent i = new Intent( Intent.ACTION_VIEW, Uri.parse("http: + d.getQuery())); startActivity(i); return; } String medianr = d.getQueryParameter("id"); Intent intent = new Intent(FrontpageActivity.this, SearchResultDetailsActivity.class); intent.putExtra("item_id", medianr); startActivity(intent); finish(); return; } } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getSupportActionBar().hide(); if (app.getLibrary() == null) { // Migrate SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(this); if (!sp.getString("opac_bib", "").equals("")) { Library lib = null; try { lib = app.getLibrary(sp.getString("opac_bib", "")); } catch (Exception e) { e.printStackTrace(); } if (lib != null) { AccountDataSource data = new AccountDataSource(this); data.open(); Account acc = new Account(); acc.setBib(lib.getIdent()); acc.setLabel(getString(R.string.default_account_name)); if (!sp.getString("opac_usernr", "").equals("")) { acc.setName(sp.getString("opac_usernr", "")); acc.setPassword(sp.getString("opac_password", "")); } long insertedid = data.addAccount(acc); data.close(); sp.edit() .putLong(OpacClient.PREF_SELECTED_ACCOUNT, insertedid).commit(); dialog = ProgressDialog.show(this, "", getString(R.string.connecting_initially), true); dialog.show(); new InitTask().execute(app); Toast.makeText( this, "Neue Version! Alte Accountdaten wurden wiederhergestellt.", Toast.LENGTH_LONG); return; } else { Toast.makeText( this, "Neue Version! Wiederherstellung alter Zugangsdaten ist fehlgeschlagen.", Toast.LENGTH_LONG); } } // Create new Intent intent = new Intent(this, WelcomeActivity.class); startActivity(intent); return; } setContentView(R.layout.frontpage_activity); ImageView ivSearch = (ImageView) findViewById(R.id.ivGoSearch); ImageView ivScan = (ImageView) findViewById(R.id.ivGoScan); ImageView ivAccount = (ImageView) findViewById(R.id.ivGoAccount); ImageView ivStarred = (ImageView) findViewById(R.id.ivGoStarred); ImageView ivMAccs = (ImageView) findViewById(R.id.ivMAcc); ImageView ivMPrefs = (ImageView) findViewById(R.id.ivMPrefs); ImageView ivMInfo = (ImageView) findViewById(R.id.ivMInfo); ImageView ivMAbout = (ImageView) findViewById(R.id.ivMAbout); ivSearch.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(FrontpageActivity.this, SearchActivity.class); startActivity(intent); } }); ivAccount.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(FrontpageActivity.this, AccountActivity.class); startActivity(intent); } }); ivScan.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(FrontpageActivity.this, SearchActivity.class); intent.putExtra("barcode", true); startActivity(intent); } }); ivStarred.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(FrontpageActivity.this, StarredActivity.class); startActivity(intent); } }); ivMAccs.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { selectaccount(new OpacActivity.AccountSelectedListener() { @Override public void accountSelected(Account account) { TextView tvBn = (TextView) findViewById(R.id.tvBibname); if (app.getLibrary().getTitle() != null && !app.getLibrary().getTitle().equals("null")) tvBn.setText(app.getLibrary().getCity() + "\n" + app.getLibrary().getTitle()); else tvBn.setText(app.getLibrary().getCity()); try { if (app.getLibrary().getData() .getString("information") != null) { if (!app.getLibrary().getData() .getString("information") .equals("null")) { ((ImageView) findViewById(R.id.ivMInfo)) .setVisibility(View.VISIBLE); } else { ((ImageView) findViewById(R.id.ivMInfo)) .setVisibility(View.GONE); } } else { ((ImageView) findViewById(R.id.ivMInfo)) .setVisibility(View.GONE); } } catch (JSONException e) { e.printStackTrace(); } } }); } }); ivMPrefs.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(FrontpageActivity.this, MainPreferenceActivity.class); startActivity(intent); } }); ivMInfo.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(FrontpageActivity.this, InfoActivity.class); startActivity(intent); } }); ivMAbout.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(FrontpageActivity.this, AboutActivity.class); startActivity(intent); } }); if (getIntent().getAction() != null) { if (getIntent().getAction().equals("android.intent.action.VIEW")) { urlintent(); return; } } } @Override protected void onResume() { super.onResume(); TextView tvBn = (TextView) findViewById(R.id.tvBibname); if (app.getLibrary().getTitle() != null && !app.getLibrary().getTitle().equals("null")) tvBn.setText(app.getLibrary().getCity() + "\n" + app.getLibrary().getTitle()); else tvBn.setText(app.getLibrary().getCity()); try { if (app.getLibrary().getData().getString("information") != null) { if (!app.getLibrary().getData().getString("information") .equals("null")) { ((ImageView) findViewById(R.id.ivMInfo)) .setVisibility(View.VISIBLE); } else { ((ImageView) findViewById(R.id.ivMInfo)) .setVisibility(View.GONE); } } else { ((ImageView) findViewById(R.id.ivMInfo)) .setVisibility(View.GONE); } } catch (JSONException e) { e.printStackTrace(); } } public class InitTask extends OpacTask<Integer> { @Override protected Integer doInBackground(Object... arg0) { super.doInBackground(arg0); try { app.getApi().start(); } catch (Exception e) { publishProgress(e, "ioerror"); } return 0; } protected void onPostExecute(Integer result) { dialog.dismiss(); Intent intent = new Intent(FrontpageActivity.this, FrontpageActivity.class); startActivity(intent); } } }
package com.bio4j.model; import com.bio4j.angulillos.*; import com.bio4j.angulillos.Arity.*; public final class ENZYMEGraph<V,E> extends TypedGraph<ENZYMEGraph<V,E>,V,E> { public ENZYMEGraph(UntypedGraph<V,E> graph) { super(graph); } @Override public final ENZYMEGraph<V,E> self() { return this; } /* ## Enzymes */ public final class Enzyme extends Vertex<Enzyme> { private Enzyme(V raw) { super(raw, enzyme); } @Override public final Enzyme self() { return this; } } public final EnzymeType enzyme = new EnzymeType(); public final class EnzymeType extends VertexType<Enzyme> { public final Enzyme fromRaw(V raw) { return new Enzyme(raw); } public final ID id = new ID(); public final class ID extends Property<String> implements FromAtMostOne, ToOne { private ID() { super(String.class); } public final Index index = new Index(); public final class Index extends UniqueIndex<ID,String> { private Index() { super(id); } } } public final Cofactors cofactors = new Cofactors(); public final class Cofactors extends Property<String[]> implements FromAny { private Cofactors() { super(String[].class); } } public final Comments comments = new Comments(); public final class Comments extends Property<String[]> implements FromAny { private Comments() { super(String[].class); } } public final Name name = new Name(); public final class Name extends Property<String> implements FromAny, ToOne { private Name() { super(String.class); } } public final AlternateNames alternateNames = new AlternateNames(); public final class AlternateNames extends Property<String[]> implements FromAny { private AlternateNames() { super(String[].class); } } public final CatalyticActivity catalyticActivity = new CatalyticActivity(); public final class CatalyticActivity extends Property<String[]> implements FromAny { private CatalyticActivity() { super(String[].class); } } } public final class EnzymeClass extends Vertex<EnzymeClass> { private EnzymeClass(V raw) { super(raw, enzymeClass); } @Override public final EnzymeClass self() { return this; } } public final EnzymeClassType enzymeClass = new EnzymeClassType(); public final class EnzymeClassType extends VertexType<EnzymeClass> { public final EnzymeClass fromRaw(V raw) { return new EnzymeClass(raw); } } public final class EnzymeSubClass extends Vertex<EnzymeSubClass> { private EnzymeSubClass(V raw) { super(raw, enzymeSubClass); } @Override public final EnzymeSubClass self() { return this; } } public final EnzymeSubClassType enzymeSubClass = new EnzymeSubClassType(); public final class EnzymeSubClassType extends VertexType<EnzymeSubClass> { public final EnzymeSubClass fromRaw(V raw) { return new EnzymeSubClass(raw); } } public final class EnzymeSubSubClass extends Vertex<EnzymeSubSubClass> { private EnzymeSubSubClass(V raw) { super(raw, enzymeSubSubClass); } @Override public final EnzymeSubSubClass self() { return this; } } public final EnzymeSubSubClassType enzymeSubSubClass = new EnzymeSubSubClassType(); public final class EnzymeSubSubClassType extends VertexType<EnzymeSubSubClass> { public final EnzymeSubSubClass fromRaw(V raw) { return new EnzymeSubSubClass(raw); } } public final class SubClass extends Edge<EnzymeClass, SubClass, EnzymeSubClass> { private SubClass(E edge) { super(edge, subClass); } @Override public final SubClass self() { return this; } } public final SubClassType subClass = new SubClassType(); public final class SubClassType extends EdgeType<EnzymeClass, SubClass, EnzymeSubClass> implements FromOne, ToAtLeastOne { private SubClassType() { super(enzymeClass, enzymeSubClass); } @Override public final SubClass fromRaw(E edge) { return new SubClass(edge); } } public final class SubSubClass extends Edge<EnzymeSubClass, SubSubClass, EnzymeSubSubClass> { private SubSubClass(E edge) { super(edge, subSubClass); } @Override public final SubSubClass self() { return this; } } public final SubSubClassType subSubClass = new SubSubClassType(); public final class SubSubClassType extends EdgeType<EnzymeSubClass, SubSubClass, EnzymeSubSubClass> implements FromOne, ToAtLeastOne { private SubSubClassType() { super(enzymeSubClass, enzymeSubSubClass); } @Override public final SubSubClass fromRaw(E edge) { return new SubSubClass(edge); } } public final class Enzymes extends Edge<EnzymeSubSubClass, Enzymes, Enzyme> { private Enzymes(E edge) { super(edge, enzymes); } @Override public final Enzymes self() { return this; } } public final EnzymesType enzymes = new EnzymesType(); public final class EnzymesType extends EdgeType<EnzymeSubSubClass, Enzymes, Enzyme> implements FromOne, ToAtLeastOne { private EnzymesType() { super(enzymeSubSubClass, enzyme); } @Override public final Enzymes fromRaw(E edge) { return new Enzymes(edge); } } }
package com.j256.ormlite.stmt; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.Serializable; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.junit.Test; import com.j256.ormlite.dao.CloseableIterator; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.ForeignCollection; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.db.BaseDatabaseType; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.field.SqlType; import com.j256.ormlite.stmt.QueryBuilder.JoinType; import com.j256.ormlite.stmt.QueryBuilder.JoinWhereOperation; public class QueryBuilderTest extends BaseCoreStmtTest { @Test public void testSelectAll() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testAddColumns() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); String[] columns1 = new String[] { Foo.ID_COLUMN_NAME, Foo.VAL_COLUMN_NAME }; String column2 = "equal"; qb.selectColumns(columns1); qb.selectColumns(column2); StringBuilder sb = new StringBuilder(); sb.append("SELECT "); for (String column : columns1) { databaseType.appendEscapedEntityName(sb, column); sb.append(", "); } databaseType.appendEscapedEntityName(sb, column2); sb.append(" FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test(expected = IllegalArgumentException.class) public void testAddBadColumn() { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); qb.selectColumns("unknown-column"); } @Test public void testDontAddIdColumn() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); String column = Foo.VAL_COLUMN_NAME; String idColumn = Foo.ID_COLUMN_NAME; qb.selectColumns(column); StringBuilder sb = new StringBuilder(); sb.append("SELECT "); databaseType.appendEscapedEntityName(sb, column); sb.append(','); databaseType.appendEscapedEntityName(sb, idColumn); sb.append(" FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testAddColumnsIterable() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); List<String> columns1 = new ArrayList<String>(); columns1.add(Foo.ID_COLUMN_NAME); columns1.add(Foo.VAL_COLUMN_NAME); String column2 = "equal"; qb.selectColumns(columns1); qb.selectColumns(column2); StringBuilder sb = new StringBuilder(); sb.append("SELECT "); for (String column : columns1) { databaseType.appendEscapedEntityName(sb, column); sb.append(", "); } databaseType.appendEscapedEntityName(sb, column2); sb.append(" FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testGroupBy() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); String field1 = Foo.VAL_COLUMN_NAME; qb.groupBy(field1); String field2 = Foo.ID_COLUMN_NAME; qb.groupBy(field2); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(" GROUP BY "); databaseType.appendEscapedEntityName(sb, field1); sb.append(','); databaseType.appendEscapedEntityName(sb, field2); sb.append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testOrderBy() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); String field1 = Foo.VAL_COLUMN_NAME; qb.orderBy(field1, true); String field2 = Foo.ID_COLUMN_NAME; qb.orderBy(field2, true); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(" ORDER BY "); databaseType.appendEscapedEntityName(sb, field1); sb.append(','); databaseType.appendEscapedEntityName(sb, field2); sb.append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testAlias() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); String alias = "zing"; qb.setAlias(alias); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(" AS "); databaseType.appendEscapedEntityName(sb, alias); sb.append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testOrderByDesc() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); String field = Foo.VAL_COLUMN_NAME; qb.orderBy(field, false); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(" ORDER BY "); databaseType.appendEscapedEntityName(sb, field); sb.append(" DESC "); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test(expected = IllegalArgumentException.class) public void testOrderByForeignCollection() throws Exception { Dao<Project, Integer> dao = createDao(Project.class, false); QueryBuilder<Project, Integer> qb = dao.queryBuilder(); qb.orderBy("categories", false); } @Test(expected = IllegalArgumentException.class) public void testGroupByForeignCollection() throws Exception { Dao<Project, Integer> dao = createDao(Project.class, false); QueryBuilder<Project, Integer> qb = dao.queryBuilder(); qb.groupBy("categories"); } @Test public void testDistinct() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); qb.distinct(); StringBuilder sb = new StringBuilder(); sb.append("SELECT DISTINCT * FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testLimit() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); long limit = 103; qb.limit(limit); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(" LIMIT ").append(limit).append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testOffset() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); long offset = 1; long limit = 2; qb.offset(offset); qb.limit(limit); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(" LIMIT ").append(offset).append(',').append(limit).append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testOffsetWorks() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); Foo foo1 = new Foo(); assertEquals(1, dao.create(foo1)); Foo foo2 = new Foo(); assertEquals(1, dao.create(foo2)); assertEquals(2, dao.queryForAll().size()); QueryBuilder<Foo, Integer> qb = dao.queryBuilder(); long offset = 1; long limit = 2; qb.offset(offset); qb.limit(limit); List<Foo> results = dao.query(qb.prepare()); assertEquals(1, results.size()); } @Test public void testLimitAfterSelect() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(new LimitAfterSelectDatabaseType(), baseFooTableInfo, null); long limit = 103; qb.limit(limit); StringBuilder sb = new StringBuilder(); sb.append("SELECT LIMIT ").append(limit); sb.append(" * FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testWhere() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); Where<Foo, Integer> where = qb.where(); String val = "1"; where.eq(Foo.ID_COLUMN_NAME, val); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(" WHERE "); databaseType.appendEscapedEntityName(sb, Foo.ID_COLUMN_NAME); sb.append(" = ").append(val).append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testWhereSelectArg() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); Where<Foo, Integer> where = qb.where(); SelectArg val = new SelectArg(); where.eq(Foo.ID_COLUMN_NAME, val); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(" WHERE "); databaseType.appendEscapedEntityName(sb, Foo.ID_COLUMN_NAME); sb.append(" = ? "); assertEquals(sb.toString(), qb.prepareStatementString()); // set the where to the previous where qb.setWhere(where); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testPrepareStatement() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(databaseType, baseFooTableInfo, null); PreparedQuery<Foo> stmt = qb.prepare(); stmt.getStatement(); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testLimitInline() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(new LimitInline(), baseFooTableInfo, null); long limit = 213; qb.limit(limit); PreparedQuery<Foo> stmt = qb.prepare(); stmt.getStatement(); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(" LIMIT ").append(limit).append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testOffsetAndLimit() throws Exception { QueryBuilder<Foo, Integer> qb = new QueryBuilder<Foo, Integer>(new LimitInline(), baseFooTableInfo, null); long offset = 200; long limit = 213; qb.offset(offset); qb.limit(limit); PreparedQuery<Foo> stmt = qb.prepare(); stmt.getStatement(); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM "); databaseType.appendEscapedEntityName(sb, baseFooTableInfo.getTableName()); sb.append(" LIMIT ").append(limit); sb.append(" OFFSET ").append(offset).append(' '); assertEquals(sb.toString(), qb.prepareStatementString()); } @Test public void testShortCuts() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); Foo foo1 = new Foo(); assertEquals(1, dao.create(foo1)); Foo foo2 = new Foo(); assertEquals(1, dao.create(foo2)); List<Foo> results = dao.queryBuilder().where().eq(Foo.ID_COLUMN_NAME, foo2.id).query(); assertEquals(1, results.size()); assertEquals(foo2.id, results.get(0).id); Iterator<Foo> iterator = dao.queryBuilder().where().eq(Foo.ID_COLUMN_NAME, foo2.id).iterator(); assertTrue(iterator.hasNext()); assertEquals(foo2.id, iterator.next().id); assertFalse(iterator.hasNext()); } @Test public void testOrderByRaw() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.val = 1; foo1.equal = 10; assertEquals(1, dao.create(foo1)); Foo foo2 = new Foo(); foo2.val = 5; foo2.equal = 7; assertEquals(1, dao.create(foo2)); List<Foo> results = dao.queryBuilder() .orderByRaw("(" + Foo.VAL_COLUMN_NAME + "+" + Foo.EQUAL_COLUMN_NAME + ") DESC") .query(); assertEquals(2, results.size()); assertEquals(foo2.id, results.get(0).id); assertEquals(foo1.id, results.get(1).id); } @Test public void testOrderByRawArg() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.val = 1; assertEquals(1, dao.create(foo1)); Foo foo2 = new Foo(); foo2.val = 2; assertEquals(1, dao.create(foo2)); List<Foo> results = dao.queryBuilder() .orderByRaw("(" + Foo.VAL_COLUMN_NAME + " = ? ) DESC", new SelectArg(SqlType.INTEGER, 2)) .query(); assertEquals(2, results.size()); assertEquals(foo2.id, results.get(0).id); assertEquals(foo1.id, results.get(1).id); results = dao.queryBuilder() .orderByRaw("(" + Foo.VAL_COLUMN_NAME + " = ? )", new SelectArg(SqlType.INTEGER, 2)) .query(); assertEquals(2, results.size()); assertEquals(foo1.id, results.get(0).id); assertEquals(foo2.id, results.get(1).id); } @Test public void testOrderByRawAndOrderBy() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.val = 1; foo1.equal = 10; assertEquals(1, dao.create(foo1)); Foo foo2 = new Foo(); foo2.val = 5; foo2.equal = 7; assertEquals(1, dao.create(foo2)); Foo foo3 = new Foo(); foo3.val = 7; foo3.equal = 5; assertEquals(1, dao.create(foo3)); List<Foo> results = dao.queryBuilder() .orderByRaw("(" + Foo.VAL_COLUMN_NAME + "+" + Foo.EQUAL_COLUMN_NAME + ") DESC") .query(); assertEquals(3, results.size()); assertEquals(foo2.id, results.get(0).id); assertEquals(foo3.id, results.get(1).id); assertEquals(foo1.id, results.get(2).id); results = dao.queryBuilder() .orderByRaw("(" + Foo.VAL_COLUMN_NAME + "+" + Foo.EQUAL_COLUMN_NAME + ") DESC") .orderBy(Foo.VAL_COLUMN_NAME, false) .query(); assertEquals(3, results.size()); assertEquals(foo3.id, results.get(0).id); assertEquals(foo2.id, results.get(1).id); assertEquals(foo1.id, results.get(2).id); results = dao.queryBuilder() .orderBy(Foo.VAL_COLUMN_NAME, true) .orderByRaw("(" + Foo.VAL_COLUMN_NAME + "+" + Foo.EQUAL_COLUMN_NAME + ") DESC") .query(); assertEquals(3, results.size()); assertEquals(foo1.id, results.get(0).id); assertEquals(foo2.id, results.get(1).id); assertEquals(foo3.id, results.get(2).id); } @Test public void testQueryForForeign() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Dao<Foreign, Object> foreignDao = createDao(Foreign.class, true); Foo foo = new Foo(); foo.val = 1231; assertEquals(1, fooDao.create(foo)); Foreign foreign = new Foreign(); foreign.foo = foo; assertEquals(1, foreignDao.create(foreign)); // use the auto-extract method to extract by id List<Foreign> results = foreignDao.queryBuilder().where().eq(Foreign.FOO_COLUMN_NAME, foo).query(); assertEquals(1, results.size()); assertEquals(foreign.id, results.get(0).id); // query for the id directly List<Foreign> results2 = foreignDao.queryBuilder().where().eq(Foreign.FOO_COLUMN_NAME, foo.id).query(); assertEquals(1, results2.size()); assertEquals(foreign.id, results2.get(0).id); } @Test(expected = SQLException.class) public void testQueryRawColumnsNotQuery() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); QueryBuilder<Foo, String> qb = dao.queryBuilder(); qb.selectRaw("COUNT(*)"); // we can't get Foo objects with the COUNT(*) dao.query(qb.prepare()); } @Test public void testClear() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, false); QueryBuilder<Foo, String> qb = dao.queryBuilder(); qb.selectColumns(Foo.VAL_COLUMN_NAME); qb.groupBy(Foo.VAL_COLUMN_NAME); qb.having("COUNT(VAL) > 1"); qb.where().eq(Foo.ID_COLUMN_NAME, 1); qb.reset(); assertEquals("SELECT * FROM `foo` ", qb.prepareStatementString()); } @Test public void testInnerCountOf() throws Exception { Dao<Foo, String> fooDao = createDao(Foo.class, true); Dao<Bar, String> barDao = createDao(Bar.class, true); Bar bar1 = new Bar(); int val = 12; bar1.val = val; assertEquals(1, barDao.create(bar1)); Bar bar2 = new Bar(); bar2.val = val + 1; assertEquals(1, barDao.create(bar2)); Foo foo1 = new Foo(); foo1.val = bar1.id; assertEquals(1, fooDao.create(foo1)); Foo foo2 = new Foo(); foo2.val = bar1.id; assertEquals(1, fooDao.create(foo2)); Foo foo3 = new Foo(); foo3.val = bar1.id + 1; assertEquals(1, fooDao.create(foo3)); QueryBuilder<Bar, String> barQb = barDao.queryBuilder(); assertEquals(0, barQb.getSelectColumnCount()); assertEquals("", barQb.getSelectColumnsAsString()); barQb.selectColumns(Bar.ID_FIELD); assertEquals(1, barQb.getSelectColumnCount()); assertEquals('[' + Bar.ID_FIELD + ']', barQb.getSelectColumnsAsString()); barQb.where().eq(Bar.VAL_FIELD, val); QueryBuilder<Foo, String> fooQb = fooDao.queryBuilder(); List<Integer> idList = new ArrayList<Integer>(); idList.add(foo1.id); idList.add(foo2.id); idList.add(foo3.id); fooQb.where().in(Foo.ID_COLUMN_NAME, idList).and().in(Foo.VAL_COLUMN_NAME, barQb); fooQb.setCountOf(true); assertEquals(1, fooQb.getSelectColumnCount()); assertEquals("COUNT(*)", fooQb.getSelectColumnsAsString()); assertEquals(2, fooDao.countOf(fooQb.prepare())); } @SuppressWarnings("unchecked") @Test public void testMixAndOrInline() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.val = 10; foo1.stringField = "zip"; assertEquals(1, dao.create(foo1)); Foo foo2 = new Foo(); foo2.val = foo1.val; foo2.stringField = foo1.stringField + "zap"; assertEquals(1, dao.create(foo2)); /* * Inline */ QueryBuilder<Foo, String> qb = dao.queryBuilder(); Where<Foo, String> where = qb.where(); where.eq(Foo.VAL_COLUMN_NAME, foo1.val) .and() .eq(Foo.STRING_COLUMN_NAME, foo1.stringField) .or() .eq(Foo.STRING_COLUMN_NAME, foo2.stringField); List<Foo> results = dao.queryForAll(); assertEquals(2, results.size()); assertEquals(foo1.id, results.get(0).id); assertEquals(foo2.id, results.get(1).id); /* * Arguments */ qb = dao.queryBuilder(); where = qb.where(); where.and(where.eq(Foo.VAL_COLUMN_NAME, foo1.val), where.or(where.eq(Foo.STRING_COLUMN_NAME, foo1.stringField), where.eq(Foo.STRING_COLUMN_NAME, foo2.stringField))); results = dao.queryForAll(); assertEquals(2, results.size()); assertEquals(foo1.id, results.get(0).id); assertEquals(foo2.id, results.get(1).id); /* * Multiple lines */ qb = dao.queryBuilder(); where = qb.where(); where.eq(Foo.VAL_COLUMN_NAME, foo1.val); where.and(); where.eq(Foo.STRING_COLUMN_NAME, foo1.stringField); where.or(); where.eq(Foo.STRING_COLUMN_NAME, foo2.stringField); results = dao.queryForAll(); assertEquals(2, results.size()); assertEquals(foo1.id, results.get(0).id); assertEquals(foo2.id, results.get(1).id); /* * Postfix */ qb = dao.queryBuilder(); where = qb.where(); where.eq(Foo.VAL_COLUMN_NAME, foo1.val); where.eq(Foo.STRING_COLUMN_NAME, foo1.stringField); where.eq(Foo.STRING_COLUMN_NAME, foo2.stringField); where.or(2); where.and(2); results = dao.queryForAll(); assertEquals(2, results.size()); assertEquals(foo1.id, results.get(0).id); assertEquals(foo2.id, results.get(1).id); } @Test public void testBaseClassComparison() throws Exception { Dao<Bar, String> barDao = createDao(Bar.class, true); Dao<Baz, String> bazDao = createDao(Baz.class, true); BarSuperClass bar1 = new BarSuperClass(); bar1.val = 10; assertEquals(1, barDao.create(bar1)); Baz baz1 = new Baz(); baz1.bar = bar1; assertEquals(1, bazDao.create(baz1)); List<Baz> results = bazDao.queryBuilder().where().eq(Baz.BAR_FIELD, bar1).query(); assertEquals(1, results.size()); assertEquals(bar1.id, results.get(0).bar.id); try { // we allow a super class of the field but _not_ a sub class results = bazDao.queryBuilder().where().eq(Baz.BAR_FIELD, new Object()).query(); fail("Should have thrown"); } catch (SQLException e) { // expected } } @Test public void testReservedWords() throws Exception { Dao<Reserved, Integer> dao = createDao(Reserved.class, true); QueryBuilder<Reserved, Integer> sb = dao.queryBuilder(); sb.where().eq(Reserved.FIELD_NAME_GROUP, "something"); sb.query(); } @Test public void testSimpleJoin() throws Exception { Dao<Bar, Integer> barDao = createDao(Bar.class, true); Dao<Baz, Integer> bazDao = createDao(Baz.class, true); Bar bar1 = new Bar(); bar1.val = 2234; assertEquals(1, barDao.create(bar1)); Bar bar2 = new Bar(); bar2.val = 324322234; assertEquals(1, barDao.create(bar2)); Baz baz1 = new Baz(); baz1.bar = bar1; assertEquals(1, bazDao.create(baz1)); Baz baz2 = new Baz(); baz2.bar = bar2; assertEquals(1, bazDao.create(baz2)); QueryBuilder<Bar, Integer> barQb = barDao.queryBuilder(); barQb.where().eq(Bar.VAL_FIELD, bar1.val); List<Baz> results = bazDao.queryBuilder().query(); assertEquals(2, results.size()); results = bazDao.queryBuilder().join(barQb).query(); assertEquals(1, results.size()); assertEquals(bar1.id, results.get(0).bar.id); } @Test public void testSimpleJoinOr() throws Exception { Dao<Bar, Integer> barDao = createDao(Bar.class, true); Dao<Baz, Integer> bazDao = createDao(Baz.class, true); Bar bar1 = new Bar(); bar1.val = 2234; assertEquals(1, barDao.create(bar1)); Bar bar2 = new Bar(); bar2.val = 324322234; assertEquals(1, barDao.create(bar2)); Baz baz1 = new Baz(); baz1.bar = bar1; baz1.val = 423423; assertEquals(1, bazDao.create(baz1)); Baz baz2 = new Baz(); baz2.bar = bar2; baz2.val = 9570423; assertEquals(1, bazDao.create(baz2)); QueryBuilder<Bar, Integer> barQb = barDao.queryBuilder(); barQb.where().eq(Bar.VAL_FIELD, bar1.val); List<Baz> results = bazDao.queryBuilder().query(); assertEquals(2, results.size()); QueryBuilder<Baz, Integer> bazQb = bazDao.queryBuilder(); bazQb.where().eq(Baz.VAL_FIELD, baz2.val); results = bazQb.joinOr(barQb).query(); assertEquals(2, results.size()); assertEquals(bar1.id, results.get(0).bar.id); assertEquals(bar2.id, results.get(1).bar.id); bazQb.reset(); bazQb.where().eq(Baz.VAL_FIELD, baz2.val); results = bazQb.join(barQb, JoinType.INNER, JoinWhereOperation.OR).query(); assertEquals(2, results.size()); assertEquals(bar1.id, results.get(0).bar.id); assertEquals(bar2.id, results.get(1).bar.id); // now do join which should be an AND bazQb.reset(); bazQb.where().eq(Baz.VAL_FIELD, baz2.val); results = bazQb.join(barQb).query(); // should find no results assertEquals(0, results.size()); } @Test public void testSimpleJoinWhere() throws Exception { Dao<Bar, Integer> barDao = createDao(Bar.class, true); Dao<Baz, Integer> bazDao = createDao(Baz.class, true); Bar bar1 = new Bar(); bar1.val = 2234; assertEquals(1, barDao.create(bar1)); Bar bar2 = new Bar(); bar2.val = 324322234; assertEquals(1, barDao.create(bar2)); Baz baz1 = new Baz(); baz1.bar = bar1; assertEquals(1, bazDao.create(baz1)); Baz baz2 = new Baz(); baz2.bar = bar2; assertEquals(1, bazDao.create(baz2)); QueryBuilder<Bar, Integer> barQb = barDao.queryBuilder(); barQb.where().eq(Bar.VAL_FIELD, bar1.val); List<Baz> results = bazDao.queryBuilder().query(); assertEquals(2, results.size()); QueryBuilder<Baz, Integer> bazQb = bazDao.queryBuilder(); bazQb.where().eq(Baz.VAL_FIELD, baz1.val); results = bazQb.join(barQb).query(); assertEquals(1, results.size()); assertEquals(bar1.id, results.get(0).bar.id); } @Test public void testReverseJoin() throws Exception { Dao<Bar, Integer> barDao = createDao(Bar.class, true); Dao<Baz, Integer> bazDao = createDao(Baz.class, true); Bar bar1 = new Bar(); bar1.val = 2234; assertEquals(1, barDao.create(bar1)); Bar bar2 = new Bar(); bar2.val = 324322234; assertEquals(1, barDao.create(bar2)); Baz baz1 = new Baz(); baz1.bar = bar1; assertEquals(1, bazDao.create(baz1)); Baz baz2 = new Baz(); baz2.bar = bar2; assertEquals(1, bazDao.create(baz2)); QueryBuilder<Baz, Integer> bazQb = bazDao.queryBuilder(); bazQb.where().eq(Baz.ID_FIELD, baz1.id); List<Bar> results = barDao.queryBuilder().query(); assertEquals(2, results.size()); results = barDao.queryBuilder().join(bazQb).query(); assertEquals(1, results.size()); assertEquals(bar1.val, results.get(0).val); } @Test public void testJoinDoubleWhere() throws Exception { Dao<Bar, Integer> barDao = createDao(Bar.class, true); Dao<Baz, Integer> bazDao = createDao(Baz.class, true); Bar bar1 = new Bar(); bar1.val = 2234; assertEquals(1, barDao.create(bar1)); Bar bar2 = new Bar(); bar2.val = 324322234; assertEquals(1, barDao.create(bar2)); Baz baz1 = new Baz(); baz1.bar = bar1; assertEquals(1, bazDao.create(baz1)); Baz baz2 = new Baz(); // both have bar1 baz2.bar = bar1; assertEquals(1, bazDao.create(baz2)); QueryBuilder<Bar, Integer> barQb = barDao.queryBuilder(); barQb.where().eq(Bar.VAL_FIELD, bar1.val); QueryBuilder<Baz, Integer> bazQb = bazDao.queryBuilder(); bazQb.where().eq(Baz.ID_FIELD, baz1.id); List<Baz> results = bazQb.join(barQb).query(); assertNotNull(results); assertEquals(1, results.size()); assertEquals(bar1.id, results.get(0).bar.id); } @Test public void testJoinOrder() throws Exception { Dao<Bar, Integer> barDao = createDao(Bar.class, true); Dao<Baz, Integer> bazDao = createDao(Baz.class, true); Bar bar1 = new Bar(); bar1.val = 2234; assertEquals(1, barDao.create(bar1)); Bar bar2 = new Bar(); bar2.val = 324322234; assertEquals(1, barDao.create(bar2)); Baz baz1 = new Baz(); baz1.bar = bar1; assertEquals(1, bazDao.create(baz1)); Baz baz2 = new Baz(); baz2.bar = bar2; assertEquals(1, bazDao.create(baz2)); QueryBuilder<Bar, Integer> barQb = barDao.queryBuilder(); barQb.orderBy(Bar.VAL_FIELD, true); List<Baz> results = bazDao.queryBuilder().join(barQb).query(); assertEquals(2, results.size()); assertEquals(bar1.id, results.get(0).bar.id); assertEquals(bar2.id, results.get(1).bar.id); // reset the query to change the order direction barQb.reset(); barQb.orderBy(Bar.VAL_FIELD, false); results = bazDao.queryBuilder().join(barQb).query(); assertEquals(2, results.size()); assertEquals(bar2.id, results.get(0).bar.id); assertEquals(bar1.id, results.get(1).bar.id); } @Test public void testJoinMultipleOrder() throws Exception { Dao<Bar, Integer> barDao = createDao(Bar.class, true); Dao<Baz, Integer> bazDao = createDao(Baz.class, true); Bar bar1 = new Bar(); bar1.val = 2234; assertEquals(1, barDao.create(bar1)); Bar bar2 = new Bar(); bar2.val = 324322234; assertEquals(1, barDao.create(bar2)); Baz baz1 = new Baz(); baz1.bar = bar1; assertEquals(1, bazDao.create(baz1)); Baz baz2 = new Baz(); baz2.bar = bar2; assertEquals(1, bazDao.create(baz2)); QueryBuilder<Bar, Integer> barQb = barDao.queryBuilder(); barQb.where().eq(Bar.VAL_FIELD, bar1.val); barQb.orderBy(Bar.ID_FIELD, true); List<Baz> results = bazDao.queryBuilder().query(); assertEquals(2, results.size()); results = bazDao.queryBuilder().orderBy(Baz.ID_FIELD, true).join(barQb).query(); assertEquals(1, results.size()); assertEquals(bar1.id, results.get(0).bar.id); } @Test public void testJoinGroup() throws Exception { Dao<Bar, Integer> barDao = createDao(Bar.class, true); Dao<Baz, Integer> bazDao = createDao(Baz.class, true); Bar bar1 = new Bar(); bar1.val = 2234; assertEquals(1, barDao.create(bar1)); Bar bar2 = new Bar(); bar2.val = 324322234; assertEquals(1, barDao.create(bar2)); Baz baz1 = new Baz(); baz1.bar = bar1; assertEquals(1, bazDao.create(baz1)); Baz baz2 = new Baz(); baz2.bar = bar2; assertEquals(1, bazDao.create(baz2)); QueryBuilder<Bar, Integer> barQb = barDao.queryBuilder(); barQb.where().eq(Bar.VAL_FIELD, bar1.val); barQb.groupBy(Bar.ID_FIELD); List<Baz> results = bazDao.queryBuilder().query(); assertEquals(2, results.size()); results = bazDao.queryBuilder().groupBy(Baz.ID_FIELD).join(barQb).query(); assertEquals(1, results.size()); assertEquals(bar1.id, results.get(0).bar.id); } @Test public void testLeftJoin() throws Exception { Dao<Bar, Integer> barDao = createDao(Bar.class, true); Dao<Baz, Integer> bazDao = createDao(Baz.class, true); Bar bar1 = new Bar(); bar1.val = 2234; assertEquals(1, barDao.create(bar1)); Bar bar2 = new Bar(); bar2.val = 324322234; assertEquals(1, barDao.create(bar2)); Baz baz1 = new Baz(); baz1.bar = bar1; assertEquals(1, bazDao.create(baz1)); Baz baz2 = new Baz(); baz2.bar = bar2; assertEquals(1, bazDao.create(baz2)); Baz baz3 = new Baz(); // no bar assertEquals(1, bazDao.create(baz3)); QueryBuilder<Bar, Integer> barQb = barDao.queryBuilder(); List<Baz> results = bazDao.queryBuilder().query(); assertEquals(3, results.size()); results = bazDao.queryBuilder().join(barQb).query(); assertEquals(2, results.size()); results = bazDao.queryBuilder().leftJoin(barQb).query(); assertEquals(3, results.size()); results = bazDao.queryBuilder().join(barQb, JoinType.LEFT, JoinWhereOperation.AND).query(); assertEquals(3, results.size()); } @Test public void testInnerJoin() throws Exception { Dao<Bar, Integer> barDao = createDao(Bar.class, true); Dao<Baz, Integer> bazDao = createDao(Baz.class, true); Dao<Bing, Integer> bingDao = createDao(Bing.class, true); Bar bar1 = new Bar(); bar1.val = 2234; assertEquals(1, barDao.create(bar1)); Bar bar2 = new Bar(); bar2.val = 324322234; assertEquals(1, barDao.create(bar2)); Baz baz1 = new Baz(); baz1.bar = bar1; assertEquals(1, bazDao.create(baz1)); Baz baz2 = new Baz(); baz2.bar = bar2; assertEquals(1, bazDao.create(baz2)); Bing bing1 = new Bing(); bing1.baz = baz1; assertEquals(1, bingDao.create(bing1)); Bing bing2 = new Bing(); bing2.baz = baz2; assertEquals(1, bingDao.create(bing2)); QueryBuilder<Bar, Integer> barQb = barDao.queryBuilder(); barQb.where().eq(Bar.VAL_FIELD, bar1.val); QueryBuilder<Baz, Integer> bazQb = bazDao.queryBuilder(); assertEquals(2, bazQb.query().size()); bazQb.join(barQb); List<Bing> results = bingDao.queryBuilder().join(bazQb).query(); assertEquals(1, results.size()); assertEquals(bing1.id, results.get(0).id); assertEquals(baz1.id, results.get(0).baz.id); bazDao.refresh(results.get(0).baz); assertEquals(bar1.id, results.get(0).baz.bar.id); } @Test(expected = SQLException.class) public void testBadJoin() throws Exception { Dao<Bar, Integer> barDao = createDao(Bar.class, true); Dao<Foo, Integer> fooDao = createDao(Foo.class, true); fooDao.queryBuilder().join(barDao.queryBuilder()).query(); } @Test public void testMultipleJoin() throws Exception { Dao<Bar, Integer> barDao = createDao(Bar.class, true); Dao<Baz, Integer> bazDao = createDao(Baz.class, true); Dao<Bing, Integer> bingDao = createDao(Bing.class, true); Bar bar1 = new Bar(); bar1.val = 2234; assertEquals(1, barDao.create(bar1)); Bar bar2 = new Bar(); bar2.val = 324322234; assertEquals(1, barDao.create(bar2)); Baz baz1 = new Baz(); baz1.bar = bar1; assertEquals(1, bazDao.create(baz1)); Baz baz2 = new Baz(); baz2.bar = bar2; assertEquals(1, bazDao.create(baz2)); Bing bing1 = new Bing(); bing1.baz = baz1; assertEquals(1, bingDao.create(bing1)); Bing bing2 = new Bing(); bing2.baz = baz1; assertEquals(1, bingDao.create(bing2)); QueryBuilder<Bar, Integer> barQb = barDao.queryBuilder(); barQb.where().eq(Bar.VAL_FIELD, bar1.val); List<Baz> results = bazDao.queryBuilder().query(); assertEquals(2, results.size()); QueryBuilder<Bing, Integer> bingQb = bingDao.queryBuilder(); bingQb.where().eq(Bing.ID_FIELD, bing2.id); List<Baz> bingResults = bazDao.queryBuilder().query(); assertEquals(2, bingResults.size()); results = bazDao.queryBuilder().join(barQb).join(bingQb).query(); assertEquals(1, results.size()); assertEquals(bar1.id, results.get(0).bar.id); } @Test public void testPickTheRightJoin() throws Exception { Dao<One, Integer> oneDao = createDao(One.class, true); Dao<Two, Integer> twoDao = createDao(Two.class, true); One one1 = new One(); one1.val = 2234; assertEquals(1, oneDao.create(one1)); One one2 = new One(); one2.val = 324322234; assertEquals(1, oneDao.create(one2)); Two two1 = new Two(); two1.one = one1; assertEquals(1, twoDao.create(two1)); Two two2 = new Two(); two2.one = one2; assertEquals(1, twoDao.create(two2)); QueryBuilder<One, Integer> oneQb = oneDao.queryBuilder(); oneQb.where().eq(One.VAL_FIELD, one1.val); List<Two> results = twoDao.queryBuilder().query(); assertEquals(2, results.size()); results = twoDao.queryBuilder().join(oneQb).query(); assertEquals(1, results.size()); assertEquals(one1.id, results.get(0).one.id); } @Test public void testPickTheRightJoinReverse() throws Exception { Dao<One, Integer> oneDao = createDao(One.class, true); Dao<Two, Integer> twoDao = createDao(Two.class, true); One one1 = new One(); one1.val = 2234; assertEquals(1, oneDao.create(one1)); One one2 = new One(); one2.val = 324322234; assertEquals(1, oneDao.create(one2)); Two two1 = new Two(); two1.val = 431231232; two1.one = one1; assertEquals(1, twoDao.create(two1)); Two two2 = new Two(); two2.one = one2; assertEquals(1, twoDao.create(two2)); QueryBuilder<Two, Integer> twoQb = twoDao.queryBuilder(); twoQb.where().eq(Two.VAL_FIELD, two1.val); List<One> results = oneDao.queryBuilder().query(); assertEquals(2, results.size()); results = oneDao.queryBuilder().join(twoQb).query(); assertEquals(1, results.size()); assertEquals(two1.one.id, results.get(0).id); } @Test public void testColumnArg() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); int val = 3123123; foo1.val = val; foo1.equal = val; assertEquals(1, fooDao.create(foo1)); Foo foo2 = new Foo(); foo2.val = val; foo2.equal = val + 1; assertEquals(1, fooDao.create(foo2)); QueryBuilder<Foo, Integer> qb = fooDao.queryBuilder(); qb.where().eq(Foo.VAL_COLUMN_NAME, new ColumnArg(Foo.EQUAL_COLUMN_NAME)); List<Foo> results = qb.query(); assertNotNull(results); assertEquals(1, results.size()); assertEquals(foo1.id, results.get(0).id); } @Test public void testColumnArgString() throws Exception { Dao<StringColumnArg, Integer> dao = createDao(StringColumnArg.class, true); StringColumnArg foo1 = new StringColumnArg(); String val = "3123123"; foo1.str1 = val; foo1.str2 = val; assertEquals(1, dao.create(foo1)); StringColumnArg foo2 = new StringColumnArg(); foo2.str1 = val; foo2.str2 = val + "..."; assertEquals(1, dao.create(foo2)); QueryBuilder<StringColumnArg, Integer> qb = dao.queryBuilder(); qb.where().eq(StringColumnArg.STR1_FIELD, new ColumnArg(StringColumnArg.STR2_FIELD)); List<StringColumnArg> results = qb.query(); assertNotNull(results); assertEquals(1, results.size()); assertEquals(foo1.id, results.get(0).id); } @Test public void testSimpleJoinColumnArg() throws Exception { Dao<Bar, Integer> barDao = createDao(Bar.class, true); Dao<Baz, Integer> bazDao = createDao(Baz.class, true); Bar bar1 = new Bar(); int val = 1313123; bar1.val = val; assertEquals(1, barDao.create(bar1)); Bar bar2 = new Bar(); bar2.val = val; assertEquals(1, barDao.create(bar2)); Baz baz1 = new Baz(); baz1.bar = bar1; baz1.val = val; assertEquals(1, bazDao.create(baz1)); Baz baz2 = new Baz(); baz2.bar = bar2; baz2.val = val + 1; assertEquals(1, bazDao.create(baz2)); Baz baz3 = new Baz(); baz1.bar = bar2; baz1.val = val; assertEquals(1, bazDao.create(baz3)); Baz baz4 = new Baz(); baz2.bar = bar1; baz2.val = val; assertEquals(1, bazDao.create(baz4)); QueryBuilder<Bar, Integer> barQb = barDao.queryBuilder(); barQb.where().eq(Bar.VAL_FIELD, new ColumnArg("baz", Baz.VAL_FIELD)); List<Baz> results = bazDao.queryBuilder().query(); assertEquals(4, results.size()); results = bazDao.queryBuilder().join(barQb).query(); assertEquals(1, results.size()); assertEquals(bar1.id, results.get(0).bar.id); } @Test public void testHavingOrderBy() throws Exception { Dao<Foo, Object> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.val = 10; assertEquals(1, fooDao.create(foo1)); Foo foo2 = new Foo(); foo2.val = 20; assertEquals(1, fooDao.create(foo2)); Foo foo3 = new Foo(); foo3.val = 30; assertEquals(1, fooDao.create(foo3)); Foo foo4 = new Foo(); foo4.val = 40; assertEquals(1, fooDao.create(foo4)); QueryBuilder<Foo, Object> qb = fooDao.queryBuilder(); qb.groupBy(Foo.ID_COLUMN_NAME); qb.orderBy(Foo.VAL_COLUMN_NAME, false); qb.having("val < " + foo3.val); List<Foo> results = qb.query(); assertEquals(2, results.size()); assertEquals(foo2.val, results.get(0).val); assertEquals(foo1.val, results.get(1).val); } @Test public void testMaxJoin() throws Exception { Dao<Foo, Object> dao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.val = 10; assertEquals(1, dao.create(foo1)); Foo foo2 = new Foo(); foo2.val = 20; assertEquals(1, dao.create(foo2)); Foo foo3 = new Foo(); foo3.val = 30; assertEquals(1, dao.create(foo3)); Foo foo4 = new Foo(); foo4.val = 40; assertEquals(1, dao.create(foo4)); QueryBuilder<Foo, Object> iqb = dao.queryBuilder(); iqb.selectRaw("max(id)"); QueryBuilder<Foo, Object> oqb = dao.queryBuilder(); Foo result = oqb.where().in(Foo.ID_COLUMN_NAME, iqb).queryForFirst(); assertNotNull(result); assertEquals(foo4.id, result.id); } @Test public void testQueryRawMax() throws Exception { Dao<Foo, Object> dao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stringField = "1"; foo1.val = 10; assertEquals(1, dao.create(foo1)); Foo foo2 = new Foo(); foo2.stringField = "1"; foo2.val = 20; assertEquals(1, dao.create(foo2)); Foo foo3 = new Foo(); foo3.stringField = "2"; foo3.val = 30; assertEquals(1, dao.create(foo3)); Foo foo4 = new Foo(); foo4.stringField = "2"; foo4.val = 40; assertEquals(1, dao.create(foo4)); QueryBuilder<Foo, Object> qb = dao.queryBuilder(); qb.selectRaw("string, max(val) as val"); qb.groupBy(Foo.STRING_COLUMN_NAME); GenericRawResults<Foo> results = dao.queryRaw(qb.prepareStatementString(), dao.getRawRowMapper()); assertNotNull(results); CloseableIterator<Foo> iterator = results.closeableIterator(); try { assertTrue(iterator.hasNext()); assertEquals(foo2.val, iterator.next().val); assertTrue(iterator.hasNext()); assertEquals(foo4.val, iterator.next().val); assertFalse(iterator.hasNext()); } finally { iterator.close(); } } @Test public void testQueryColumnsPlusQueryRawMax() throws Exception { Dao<Foo, Object> dao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stringField = "1"; foo1.val = 10; assertEquals(1, dao.create(foo1)); Foo foo2 = new Foo(); foo2.stringField = "1"; foo2.val = 20; assertEquals(1, dao.create(foo2)); Foo foo3 = new Foo(); foo3.stringField = "2"; foo3.val = 40; assertEquals(1, dao.create(foo3)); Foo foo4 = new Foo(); foo4.stringField = "2"; foo4.val = 30; assertEquals(1, dao.create(foo4)); QueryBuilder<Foo, Object> qb = dao.queryBuilder(); qb.selectColumns(Foo.STRING_COLUMN_NAME); qb.selectRaw("MAX(val) AS val"); qb.groupBy(Foo.STRING_COLUMN_NAME); GenericRawResults<Foo> results = dao.queryRaw(qb.prepareStatementString(), dao.getRawRowMapper()); assertNotNull(results); CloseableIterator<Foo> iterator = results.closeableIterator(); try { assertTrue(iterator.hasNext()); Foo result = iterator.next(); assertEquals(foo2.val, result.val); assertEquals(foo2.stringField, result.stringField); assertTrue(iterator.hasNext()); result = iterator.next(); assertEquals(foo3.val, result.val); assertEquals(foo3.stringField, result.stringField); assertFalse(iterator.hasNext()); } finally { iterator.close(); } } @Test public void testJoinTwoColumns() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Dao<StringColumnArg, Integer> scaDao = createDao(StringColumnArg.class, true); Foo foo1 = new Foo(); foo1.val = 123213213; foo1.stringField = "stuff"; fooDao.create(foo1); Foo foo2 = new Foo(); foo2.stringField = "not stuff"; fooDao.create(foo2); StringColumnArg sca1 = new StringColumnArg(); sca1.str1 = foo1.stringField; scaDao.create(sca1); StringColumnArg sca2 = new StringColumnArg(); sca2.str1 = foo2.stringField; scaDao.create(sca2); StringColumnArg sca3 = new StringColumnArg(); sca3.str1 = "some other field"; scaDao.create(sca3); QueryBuilder<Foo, Integer> fooQb = fooDao.queryBuilder(); fooQb.where().eq(Foo.VAL_COLUMN_NAME, foo1.val); QueryBuilder<StringColumnArg, Integer> scaQb = scaDao.queryBuilder(); scaQb.join(StringColumnArg.STR1_FIELD, Foo.STRING_COLUMN_NAME, fooQb); List<StringColumnArg> results = scaQb.query(); assertNotNull(results); assertEquals(1, results.size()); assertEquals(sca1.id, results.get(0).id); fooQb.reset(); fooQb.where().eq(Foo.VAL_COLUMN_NAME, foo2.val); scaQb.reset(); scaQb.join(StringColumnArg.STR1_FIELD, Foo.STRING_COLUMN_NAME, fooQb); results = scaQb.query(); assertNotNull(results); assertEquals(1, results.size()); assertEquals(sca2.id, results.get(0).id); } @Test public void testLeftJoinTwoColumns() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Dao<StringColumnArg, Integer> scaDao = createDao(StringColumnArg.class, true); Foo foo1 = new Foo(); foo1.val = 123213213; foo1.stringField = "stuff"; fooDao.create(foo1); StringColumnArg sca1 = new StringColumnArg(); sca1.str1 = foo1.stringField; scaDao.create(sca1); StringColumnArg sca2 = new StringColumnArg(); sca2.str1 = "something eles"; scaDao.create(sca2); QueryBuilder<Foo, Integer> fooQb = fooDao.queryBuilder(); QueryBuilder<StringColumnArg, Integer> scaQb = scaDao.queryBuilder(); scaQb.join(StringColumnArg.STR1_FIELD, Foo.STRING_COLUMN_NAME, fooQb); List<StringColumnArg> results = scaQb.query(); assertNotNull(results); assertEquals(1, results.size()); assertEquals(sca1.id, results.get(0).id); scaQb.reset(); scaQb.join(StringColumnArg.STR1_FIELD, Foo.STRING_COLUMN_NAME, fooQb, JoinType.LEFT, JoinWhereOperation.AND); results = scaQb.query(); assertNotNull(results); assertEquals(2, results.size()); assertEquals(sca1.id, results.get(0).id); assertEquals(sca2.id, results.get(1).id); } @Test public void testSpecificJoinLoggingBug() throws Exception { /* * Test trying to specifically reproduce a reported bug. The query built in the logs was enough to show that * either the bug has already been fixed or the test is not reproducing the problem adequately. */ Dao<Category, Integer> categoryDao = createDao(Category.class, true); Dao<Criterion, Integer> criterionDao = createDao(Criterion.class, true); QueryBuilder<Criterion, Integer> criteriaQb = criterionDao.queryBuilder(); criteriaQb.where().eq("active", Boolean.valueOf(true)); QueryBuilder<Category, Integer> categoryQb = categoryDao.queryBuilder(); categoryQb.orderByRaw("id").join(criteriaQb).query(); } @Test public void testSelectColumnsNoId() throws Exception { Dao<NoId, Void> dao = createDao(NoId.class, true); QueryBuilder<NoId, Void> qb = dao.queryBuilder(); qb.selectColumns(NoId.FIELD_NAME_STUFF); /* * Had a subtle, long-standing bug here that threw an exception when building the query if you were selecting * specific columns from an entity _without_ an id field. */ qb.prepare(); } @Test public void testRandomIsNull() throws Exception { Dao<SeralizableNull, Integer> dao = createDao(SeralizableNull.class, true); SeralizableNull sn1 = new SeralizableNull(); assertEquals(1, dao.create(sn1)); SeralizableNull sn2 = new SeralizableNull(); sn2.serializable = "wow"; assertEquals(1, dao.create(sn2)); List<SeralizableNull> results = dao.queryBuilder().where().isNull(SeralizableNull.FIELD_NAME_SERIALIZABLE).query(); assertNotNull(results); assertEquals(1, results.size()); assertEquals(sn1.id, results.get(0).id); results = dao.queryBuilder().where().isNotNull(SeralizableNull.FIELD_NAME_SERIALIZABLE).query(); assertNotNull(results); assertEquals(1, results.size()); assertEquals(sn2.id, results.get(0).id); } @Test public void testCountOf() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); QueryBuilder<Foo, Integer> qb = dao.queryBuilder(); assertEquals(0, qb.countOf()); Foo foo1 = new Foo(); int val = 123213; foo1.val = val; assertEquals(1, dao.create(foo1)); assertEquals(1, qb.countOf()); Foo foo2 = new Foo(); foo2.val = val; assertEquals(1, dao.create(foo2)); assertEquals(2, qb.countOf()); String distinct = "DISTINCT(" + Foo.VAL_COLUMN_NAME + ")"; assertEquals(1, qb.countOf(distinct)); qb.setCountOf(distinct); assertEquals(1, dao.countOf(qb.prepare())); distinct = "DISTINCT(" + Foo.ID_COLUMN_NAME + ")"; assertEquals(2, qb.countOf(distinct)); qb.setCountOf(distinct); assertEquals(2, dao.countOf(qb.prepare())); } @Test public void testUtf8() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); Foo foo = new Foo(); foo.stringField = "اعصاب"; assertEquals(1, dao.create(foo)); QueryBuilder<Foo, Integer> qb = dao.queryBuilder(); List<Foo> results = qb.where().like(Foo.STRING_COLUMN_NAME, '%' + foo.stringField + '%').query(); assertNotNull(results); assertEquals(1, results.size()); assertEquals(foo.id, results.get(0).id); assertEquals(foo.stringField, results.get(0).stringField); qb.reset(); results = qb.where().like(Foo.STRING_COLUMN_NAME, new SelectArg('%' + foo.stringField + '%')).query(); assertNotNull(results); assertEquals(1, results.size()); assertEquals(foo.id, results.get(0).id); assertEquals(foo.stringField, results.get(0).stringField); } @Test public void testOrdersInMultiQueryBuilder() throws Exception { Dao<Bar, Integer> barDao = createDao(Bar.class, true); Dao<Baz, Integer> bazDao = createDao(Baz.class, true); Dao<Bing, Integer> bingDao = createDao(Bing.class, true); Bar bar1 = new Bar(); bar1.val = 1; assertEquals(1, barDao.create(bar1)); Bar bar2 = new Bar(); bar2.val = 3; assertEquals(1, barDao.create(bar2)); Bar bar3 = new Bar(); bar3.val = 2; assertEquals(1, barDao.create(bar3)); Baz baz1 = new Baz(); baz1.bar = bar1; baz1.val = 2; assertEquals(1, bazDao.create(baz1)); Baz baz2 = new Baz(); baz2.bar = bar2; baz2.val = 2; assertEquals(1, bazDao.create(baz2)); Baz baz3 = new Baz(); baz3.bar = bar3; baz3.val = 1; assertEquals(1, bazDao.create(baz3)); Bing bing1 = new Bing(); bing1.baz = baz1; assertEquals(1, bingDao.create(bing1)); Bing bing2 = new Bing(); bing2.baz = baz2; assertEquals(1, bingDao.create(bing2)); Bing bing3 = new Bing(); bing3.baz = baz3; assertEquals(1, bingDao.create(bing3)); QueryBuilder<Bar, Integer> barQb = barDao.queryBuilder(); barQb.orderBy(Bar.VAL_FIELD, true); QueryBuilder<Baz, Integer> bazQb = bazDao.queryBuilder(); assertEquals(3, bazQb.query().size()); bazQb.orderBy(Baz.VAL_FIELD, true); bazQb.join(barQb); List<Bing> results = bingDao.queryBuilder().join(bazQb).query(); assertEquals(3, results.size()); assertEquals(bing3.id, results.get(0).id); assertEquals(baz3.id, results.get(0).baz.id); bazDao.refresh(results.get(0).baz); assertEquals(bar3.id, results.get(0).baz.bar.id); bazDao.refresh(results.get(1).baz); assertEquals(bar1.id, results.get(1).baz.bar.id); bazDao.refresh(results.get(2).baz); assertEquals(bar2.id, results.get(2).baz.bar.id); } @Test public void testCountInReadOnlyField() throws Exception { Dao<AsField, Integer> dao = createDao(AsField.class, true); AsField foo1 = new AsField(); int val1 = 123213; foo1.val = val1; assertEquals(1, dao.create(foo1)); AsField foo2 = new AsField(); int val2 = 122433213; foo2.val = val2; assertEquals(1, dao.create(foo2)); QueryBuilder<AsField, Integer> qb = dao.queryBuilder(); qb.selectRaw("*"); int val3 = 12; qb.selectRaw(val3 + " AS " + AsField.SUM_FIELD); List<AsField> results = dao.queryRaw(qb.prepareStatementString(), dao.getRawRowMapper()).getResults(); assertEquals(2, results.size()); assertEquals(val1, (int) results.get(0).val); assertEquals(val3, (int) results.get(0).sum); assertEquals(val2, (int) results.get(1).val); assertEquals(val3, (int) results.get(1).sum); } private static class LimitInline extends BaseDatabaseType { @Override public boolean isDatabaseUrlThisType(String url, String dbTypePart) { return true; } @Override protected String getDriverClassName() { return "foo.bar.baz"; } @Override public String getDatabaseName() { return "zipper"; } } protected static class Bar { public static final String ID_FIELD = "id"; public static final String VAL_FIELD = "val"; @DatabaseField(generatedId = true, columnName = ID_FIELD) int id; @DatabaseField(columnName = VAL_FIELD) int val; public Bar() { } } private static class BarSuperClass extends Bar { } protected static class Baz { public static final String ID_FIELD = "id"; public static final String VAL_FIELD = "val"; public static final String BAR_FIELD = "bar"; @DatabaseField(generatedId = true, columnName = ID_FIELD) int id; @DatabaseField(columnName = VAL_FIELD) int val; @DatabaseField(foreign = true, columnName = BAR_FIELD) Bar bar; public Baz() { } } protected static class Bing { public static final String ID_FIELD = "id"; public static final String BAZ_FIELD = "baz"; @DatabaseField(generatedId = true, columnName = ID_FIELD) int id; @DatabaseField(foreign = true, columnName = BAZ_FIELD) Baz baz; public Bing() { } } protected static class Reserved { public static final String FIELD_NAME_GROUP = "group"; @DatabaseField(generatedId = true) int id; @DatabaseField(columnName = FIELD_NAME_GROUP) String group; public Reserved() { } } protected static class StringColumnArg { public static final String ID_FIELD = "id"; public static final String STR1_FIELD = "str1"; public static final String STR2_FIELD = "str2"; @DatabaseField(generatedId = true, columnName = ID_FIELD) int id; @DatabaseField(columnName = STR1_FIELD) String str1; @DatabaseField(columnName = STR2_FIELD) String str2; public StringColumnArg() { } } protected static class One { public static final String ID_FIELD = "id"; public static final String VAL_FIELD = "val"; @DatabaseField(generatedId = true, columnName = ID_FIELD) int id; @DatabaseField(columnName = VAL_FIELD) int val; public One() { } } protected static class Two { public static final String ID_FIELD = "id"; public static final String VAL_FIELD = "val"; @DatabaseField(generatedId = true, columnName = ID_FIELD) int id; @DatabaseField(columnName = VAL_FIELD) int val; @DatabaseField(foreign = true) Baz baz; @DatabaseField(foreign = true) One one; @DatabaseField(foreign = true) Bar bar; public Two() { } } protected static class AsField { public static final String VAL_FIELD = "val"; public static final String SUM_FIELD = "sum"; @DatabaseField(generatedId = true) int id; @DatabaseField(columnName = VAL_FIELD) int val; @DatabaseField(readOnly = true, columnName = SUM_FIELD) Integer sum; public AsField() { } } protected static class BaseModel { @DatabaseField(generatedId = true) int id; } protected static class Project extends BaseModel { // nothing here @ForeignCollectionField(eager = false) ForeignCollection<Category> categories; } protected static class Category extends BaseModel { @DatabaseField(canBeNull = false, foreign = true) Project project; @ForeignCollectionField(eager = false) ForeignCollection<Criterion> criteria; public Category() { } } protected static class Criterion extends BaseModel { @DatabaseField boolean active; @DatabaseField Integer weight; @DatabaseField(canBeNull = false, foreign = true) Category category; public Criterion() { } } protected static class NoId { public static final String FIELD_NAME_STUFF = "stuff"; @DatabaseField(columnName = FIELD_NAME_STUFF) String stuff; } protected static class SeralizableNull { public static final String FIELD_NAME_SERIALIZABLE = "serializable"; @DatabaseField(generatedId = true) int id; @DatabaseField(columnName = FIELD_NAME_SERIALIZABLE, dataType = DataType.SERIALIZABLE) Serializable serializable; } }
package com.expidev.gcmapp.db; import android.content.ContentValues; import android.database.Cursor; import android.support.annotation.NonNull; import com.expidev.gcmapp.model.Church; public class ChurchMapper extends BaseMapper<Church> { @Override protected void mapField(@NonNull final ContentValues values, @NonNull final String field, @NonNull final Church church) { switch (field) { case Contract.Church.COLUMN_ID: values.put(field, church.getId()); break; case Contract.Church.COLUMN_MINISTRY_ID: values.put(field, church.getMinistryId()); break; case Contract.Church.COLUMN_NAME: values.put(field, church.getName()); break; case Contract.Church.COLUMN_CONTACT_NAME: values.put(field, church.getContactName()); break; case Contract.Church.COLUMN_CONTACT_EMAIL: values.put(field, church.getContactEmail()); break; case Contract.Church.COLUMN_LATITUDE: values.put(field, church.getLatitude()); break; case Contract.Church.COLUMN_LONGITUDE: values.put(field, church.getLongitude()); break; case Contract.Church.COLUMN_DEVELOPMENT: values.put(field, church.getDevelopment().id); break; case Contract.Church.COLUMN_SIZE: values.put(field, church.getSize()); break; case Contract.Church.COLUMN_SECURITY: values.put(field, church.getSecurity()); break; default: super.mapField(values, field, church); break; } } @NonNull @Override protected Church newObject(@NonNull final Cursor cursor) { return new Church(); } @NonNull @Override public Church toObject(@NonNull final Cursor c) { final Church church = super.toObject(c); church.setId(getLong(c, Contract.Church.COLUMN_ID, Church.INVALID_ID)); church.setName(getString(c, Contract.Church.COLUMN_NAME, null)); church.setContactName(getString(c, Contract.Church.COLUMN_CONTACT_NAME, null)); church.setContactEmail(getString(c, Contract.Church.COLUMN_CONTACT_EMAIL, null)); church.setLatitude(getDouble(c, Contract.Church.COLUMN_LATITUDE)); church.setLongitude(getDouble(c, Contract.Church.COLUMN_LONGITUDE)); church.setDevelopment(getInt(c, Contract.Church.COLUMN_DEVELOPMENT, Church.Development.UNKNOWN.id)); church.setSize(getInt(c, Contract.Church.COLUMN_SIZE, 0)); church.setSecurity(getInt(c, Contract.Church.COLUMN_SECURITY, 2)); return church; } }
package edu.umd.cs.findbugs.util; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import javax.swing.JOptionPane; import edu.umd.cs.findbugs.annotations.CheckForNull; /** * @author pugh */ public class JavaWebStart { static final @CheckForNull Method jnlpShowDocumentMethod; static final @CheckForNull Method jnlpGetCodeBaseMethod; static final Object jnlpBasicService; // will not be null if // jnlpShowMethod!=null static { // attempt to set the JNLP BasicService object and its showDocument(URL) // method Method showMethod = null; Method getCodeBase = null; Object showObject = null; try { Class<?> serviceManagerClass = Class.forName("javax.jnlp.ServiceManager"); Method lookupMethod = serviceManagerClass.getMethod("lookup", new Class[] { String.class }); showObject = lookupMethod.invoke(null, new Object[] { "javax.jnlp.BasicService" }); showMethod = showObject.getClass().getMethod("showDocument", new Class[] { URL.class }); getCodeBase = showObject.getClass().getMethod("getCodeBase", new Class[] {}); } catch (ClassNotFoundException e) { assert true; } catch (NoSuchMethodException e) { assert true; } catch (IllegalAccessException e) { assert true; } catch (InvocationTargetException e) { assert true; } jnlpShowDocumentMethod = showMethod; jnlpGetCodeBaseMethod = getCodeBase; jnlpBasicService = showObject; } public static boolean isRunningViaJavaWebstart() { return JavaWebStart.jnlpBasicService != null; } public static URL resolveRelativeToJnlpCodebase(String s) throws MalformedURLException { if (JavaWebStart.jnlpGetCodeBaseMethod != null) { try { URL base = (URL) JavaWebStart.jnlpGetCodeBaseMethod.invoke(JavaWebStart.jnlpBasicService); if (base != null) return new URL(base, s); } catch (RuntimeException e) { assert true; } catch (Exception e) { assert true; } } return new URL(s); } static Boolean viaWebStart(URL url) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (JavaWebStart.jnlpShowDocumentMethod == null) throw new UnsupportedOperationException("Launch via web start not available"); return (Boolean) JavaWebStart.jnlpShowDocumentMethod.invoke(JavaWebStart.jnlpBasicService, url); } static boolean showViaWebStart(URL url) { if (JavaWebStart.jnlpShowDocumentMethod != null) try { if (LaunchBrowser.DEBUG) JOptionPane.showMessageDialog(null, "Trying browse via webstart"); Boolean b = viaWebStart(url); boolean success = b != null && b.booleanValue(); if (LaunchBrowser.DEBUG) JOptionPane.showMessageDialog(null, " browse via webstart: " + success); return success; } catch (InvocationTargetException ite) { assert true; } catch (IllegalAccessException iae) { assert true; } return false; } }
package mobi.hsz.idea.gitignore.ui; import com.intellij.icons.AllIcons; import com.intellij.ide.CommonActionsManager; import com.intellij.ide.DefaultTreeExpander; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.markup.HighlighterTargetArea; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.OptionAction; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiFile; import com.intellij.ui.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import mobi.hsz.idea.gitignore.IgnoreBundle; import mobi.hsz.idea.gitignore.command.AppendFileCommandAction; import mobi.hsz.idea.gitignore.command.CreateFileCommandAction; import mobi.hsz.idea.gitignore.settings.IgnoreSettings; import mobi.hsz.idea.gitignore.util.Resources; import mobi.hsz.idea.gitignore.util.Utils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.ActionEvent; import java.util.List; import java.util.Set; import static mobi.hsz.idea.gitignore.util.Resources.Template.Container.*; /** * {@link GeneratorDialog} responsible for displaying list of all available templates and adding selected ones * to the specified file. * * @author Jakub Chrzanowski <jakub@hsz.mobi> * @since 0.2 */ public class GeneratorDialog extends DialogWrapper { /** {@link FilterComponent} search history key. */ private static final String TEMPLATES_FILTER_HISTORY = "TEMPLATES_FILTER_HISTORY"; /** Star icon for the favorites action. */ private static final Icon STAR = AllIcons.Ide.Rating; /** Cache set to store checked templates for the current action. */ private final Set<Resources.Template> checked = ContainerUtil.newHashSet(); /** Set of the starred templates. */ private final Set<String> starred = ContainerUtil.newHashSet(); /** Current working project. */ @NotNull private final Project project; /** Settings instance. */ @NotNull private final IgnoreSettings settings; /** Current working file. */ @Nullable private PsiFile file; /** Templates tree root node. */ @NotNull private final TemplateTreeNode root; /** {@link CreateFileCommandAction} action instance to generate new file in the proper time. */ @Nullable private CreateFileCommandAction action; /** Templates tree with checkbox feature. */ private CheckboxTree tree; /** Tree expander responsible for expanding and collapsing tree structure. */ private DefaultTreeExpander treeExpander; /** Dynamic templates filter. */ private FilterComponent profileFilter; /** Preview editor with syntax highlight. */ private Editor preview; /** {@link Document} related to the {@link Editor} feature. */ private Document previewDocument; /** * Builds a new instance of {@link GeneratorDialog}. * * @param project current working project * @param file current working file */ public GeneratorDialog(@NotNull Project project, @Nullable PsiFile file) { super(project, false); this.project = project; this.file = file; this.root = new TemplateTreeNode(); this.action = null; this.settings = IgnoreSettings.getInstance(); setTitle(IgnoreBundle.message("dialog.generator.title")); setOKButtonText(IgnoreBundle.message("global.generate")); setCancelButtonText(IgnoreBundle.message("global.cancel")); init(); } /** * Builds a new instance of {@link GeneratorDialog}. * * @param project current working project * @param action {@link CreateFileCommandAction} action instance to generate new file in the proper time */ public GeneratorDialog(@NotNull Project project, @Nullable CreateFileCommandAction action) { this(project, (PsiFile) null); this.action = action; } /** * Returns component which should be focused when the dialog appears on the screen. * * @return component to focus */ @Nullable @Override public JComponent getPreferredFocusedComponent() { return profileFilter; } @Override protected void dispose() { EditorFactory.getInstance().releaseEditor(preview); super.dispose(); } @Override public void show() { if (ApplicationManager.getApplication().isUnitTestMode()) { dispose(); return; } super.show(); } /** * This method is invoked by default implementation of "OK" action. It just closes dialog * with <code>OK_EXIT_CODE</code>. This is convenient place to override functionality of "OK" action. * Note that the method does nothing if "OK" action isn't enabled. */ @Override protected void doOKAction() { if (isOKActionEnabled()) { performAppendAction(false); } } /** * Performs {@link AppendFileCommandAction} action. * * @param ignoreDuplicates ignores duplicated rules */ private void performAppendAction(boolean ignoreDuplicates) { String content = ""; for (Resources.Template template : checked) { if (template == null) { continue; } content += IgnoreBundle.message("file.templateSection", template.getName()); content += "\n" + template.getContent(); } if (file == null && action != null) { file = action.execute().getResultObject(); } if (file != null && !content.isEmpty()) { new AppendFileCommandAction(project, file, content, ignoreDuplicates).execute(); } super.doOKAction(); } /** Creates default actions with appended {@link OptionOkAction} instance. */ @Override protected void createDefaultActions() { super.createDefaultActions(); myOKAction = new OptionOkAction(); } /** * Factory method. It creates panel with dialog options. Options panel is located at the * center of the dialog's content pane. The implementation can return <code>null</code> * value. In this case there will be no options panel. * * @return center panel */ @Nullable @Override protected JComponent createCenterPanel() { // general panel final JPanel centerPanel = new JPanel(new BorderLayout()); centerPanel.setPreferredSize(new Dimension(800, 500)); // splitter panel - contains tree panel and preview component final JBSplitter splitter = new JBSplitter(false, 0.4f); centerPanel.add(splitter, BorderLayout.CENTER); final JPanel treePanel = new JPanel(new BorderLayout()); previewDocument = EditorFactory.getInstance().createDocument(""); preview = Utils.createPreviewEditor(previewDocument, project, true); splitter.setFirstComponent(treePanel); splitter.setSecondComponent(preview.getComponent()); /* Scroll panel for the templates tree. */ JScrollPane treeScrollPanel = createTreeScrollPanel(); treePanel.add(treeScrollPanel, BorderLayout.CENTER); final JPanel northPanel = new JPanel(new GridBagLayout()); northPanel.setBorder(IdeBorderFactory.createEmptyBorder(2, 0, 2, 0)); northPanel.add(createTreeActionsToolbarPanel(treeScrollPanel).getComponent(), new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); northPanel.add(profileFilter, new GridBagConstraints(1, 0, 1, 1, 1, 1, GridBagConstraints.BASELINE_TRAILING, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); treePanel.add(northPanel, BorderLayout.NORTH); return centerPanel; } /** * Creates scroll panel with templates tree in it. * * @return scroll panel */ private JScrollPane createTreeScrollPanel() { fillTreeData(null, true); final TemplateTreeRenderer renderer = new TemplateTreeRenderer() { protected String getFilter() { return profileFilter != null ? profileFilter.getFilter() : null; } }; tree = new CheckboxTree(renderer, root) { public Dimension getPreferredScrollableViewportSize() { Dimension size = super.getPreferredScrollableViewportSize(); size = new Dimension(size.width + 10, size.height); return size; } @Override protected void onNodeStateChanged(CheckedTreeNode node) { super.onNodeStateChanged(node); Resources.Template template = ((TemplateTreeNode) node).getTemplate(); if (node.isChecked()) { checked.add(template); } else { checked.remove(template); } } }; tree.setCellRenderer(renderer); tree.setRootVisible(false); tree.setShowsRootHandles(true); UIUtil.setLineStyleAngled(tree); TreeUtil.installActions(tree); tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { final TreePath path = getCurrentPath(); if (path != null) { updateDescriptionPanel(path); } } }); final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(tree); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); TreeUtil.expandAll(tree); treeExpander = new DefaultTreeExpander(tree); profileFilter = new TemplatesFilterComponent(); return scrollPane; } @Nullable private TreePath getCurrentPath() { if (tree.getSelectionPaths() != null && tree.getSelectionPaths().length == 1) { return tree.getSelectionPaths()[0]; } return null; } /** * Creates tree toolbar panel with actions for working with templates tree. * * @param target templates tree * @return action toolbar */ private ActionToolbar createTreeActionsToolbarPanel(JComponent target) { final CommonActionsManager actionManager = CommonActionsManager.getInstance(); DefaultActionGroup actions = new DefaultActionGroup(); actions.add(actionManager.createExpandAllAction(treeExpander, tree)); actions.add(actionManager.createCollapseAllAction(treeExpander, tree)); actions.add(new AnAction(IgnoreBundle.message("dialog.generator.unselectAll"), null, AllIcons.Actions.Unselectall) { @Override public void update(AnActionEvent e) { e.getPresentation().setEnabled(!checked.isEmpty()); } @Override public void actionPerformed(AnActionEvent e) { checked.clear(); filterTree(profileFilter.getTextEditor().getText()); } }); actions.add(new AnAction(IgnoreBundle.message("dialog.generator.star"), null, STAR) { @Override public void update(AnActionEvent e) { final TemplateTreeNode node = getCurrentNode(); boolean disabled = node == null || USER.equals(node.getContainer()) || !node.isLeaf(); boolean unstar = node != null && STARRED.equals(node.getContainer()); final Icon icon = disabled ? IconLoader.getDisabledIcon(STAR) : (unstar ? IconLoader.getTransparentIcon(STAR) : STAR); final String text = IgnoreBundle.message(unstar ? "dialog.generator.unstar" : "dialog.generator.star"); final Presentation presentation = e.getPresentation(); presentation.setEnabled(!disabled); presentation.setIcon(icon); presentation.setText(text); } @Override public void actionPerformed(AnActionEvent e) { final TemplateTreeNode node = getCurrentNode(); if (node == null) { return; } final Resources.Template template = node.getTemplate(); if (template != null) { boolean isStarred = !template.isStarred(); template.setStarred(isStarred); refreshTree(); if (isStarred) { starred.add(template.getName()); } else { starred.remove(template.getName()); } settings.setStarredTemplates(ContainerUtil.newArrayList(starred)); } } /** * Returns current {@link TemplateTreeNode} node if available. * * @return current node */ @Nullable private TemplateTreeNode getCurrentNode() { final TreePath path = getCurrentPath(); return path == null ? null : (TemplateTreeNode) path.getLastPathComponent(); } }); final ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actions, true); actionToolbar.setTargetComponent(target); return actionToolbar; } /** * Updates editor's content depending on the selected {@link TreePath}. * * @param path selected tree path */ private void updateDescriptionPanel(@NotNull TreePath path) { final TemplateTreeNode node = (TemplateTreeNode) path.getLastPathComponent(); final Resources.Template template = node.getTemplate(); ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { @Override public void run() { String content = template != null ? StringUtil.replaceChar(StringUtil.notNullize(template.getContent()), '\r', '\0') : ""; previewDocument.replaceString(0, previewDocument.getTextLength(), content); List<Pair<Integer, Integer>> pairs = getFilterRanges(profileFilter.getTextEditor().getText(), content); highlightWords(pairs); } }); } }); } /** * Fills templates tree with templates fetched with {@link Resources#getGitignoreTemplates()}. * * @param filter templates filter * @param forceInclude force include */ private void fillTreeData(@Nullable String filter, boolean forceInclude) { root.removeAllChildren(); root.setChecked(false); for (Resources.Template.Container container : Resources.Template.Container.values()) { TemplateTreeNode node = new TemplateTreeNode(container); node.setChecked(false); root.add(node); } List<Resources.Template> templatesList = Resources.getGitignoreTemplates(); for (Resources.Template template : templatesList) { if (filter != null && filter.length() > 0 && !isTemplateAccepted(template, filter)) { continue; } final TemplateTreeNode node = new TemplateTreeNode(template); node.setChecked(checked.contains(template)); getGroupNode(root, template.getContainer()).add(node); } if (filter != null && forceInclude && root.getChildCount() == 0) { fillTreeData(filter, false); } TreeUtil.sort(root, new TemplateTreeComparator()); } /** * Creates or gets existing group node for specified element. * * @param root tree root node * @param container container type to search * @return group node */ private static TemplateTreeNode getGroupNode(TemplateTreeNode root, Resources.Template.Container container) { final int childCount = root.getChildCount(); for (int i = 0; i < childCount; i++) { TemplateTreeNode child = (TemplateTreeNode) root.getChildAt(i); if (container.equals(child.getContainer())) { return child; } } TemplateTreeNode child = new TemplateTreeNode(container); root.add(child); return child; } /** * Finds for the filter's words in the given content and returns their positions. * * @param filter templates filter * @param content templates content * @return text ranges */ private List<Pair<Integer, Integer>> getFilterRanges(String filter, String content) { List<Pair<Integer, Integer>> pairs = ContainerUtil.newArrayList(); content = content.toLowerCase(); for (String word : Utils.getWords(filter)) { for (int index = content.indexOf(word); index >= 0; index = content.indexOf(word, index + 1)) { pairs.add(Pair.create(index, index + word.length())); } } return pairs; } /** * Checks if given template is accepted by passed filter. * * @param template to check * @param filter templates filter * @return template is accepted */ private boolean isTemplateAccepted(Resources.Template template, String filter) { filter = filter.toLowerCase(); if (StringUtil.containsIgnoreCase(template.getName(), filter)) { return true; } boolean nameAccepted = true; for (String word : Utils.getWords(filter)) { if (!StringUtil.containsIgnoreCase(template.getName(), word)) { nameAccepted = false; } } List<Pair<Integer, Integer>> ranges = getFilterRanges(filter, template.getContent()); return nameAccepted || ranges.size() > 0; } /** * Filters templates tree. * * @param filter text */ private void filterTree(@Nullable String filter) { if (tree != null) { fillTreeData(filter, true); reloadModel(); TreeUtil.expandAll(tree); if (tree.getSelectionPath() == null) { TreeUtil.selectFirstNode(tree); } } } /** Refreshes current tree. */ private void refreshTree() { filterTree(profileFilter.getTextEditor().getText()); } /** * Highlights given text ranges in {@link #preview} content. * * @param pairs text ranges */ private void highlightWords(@NotNull List<Pair<Integer, Integer>> pairs) { final TextAttributes attr = new TextAttributes(); attr.setBackgroundColor(UIUtil.getTreeSelectionBackground()); attr.setForegroundColor(UIUtil.getTreeSelectionForeground()); for (Pair<Integer, Integer> pair : pairs) { preview.getMarkupModel().addRangeHighlighter(pair.first, pair.second, 0, attr, HighlighterTargetArea.EXACT_RANGE); } } /** Reloads tree model. */ private void reloadModel() { ((DefaultTreeModel) tree.getModel()).reload(); } /** * Returns current file. * * @return file */ @Nullable public PsiFile getFile() { return file; } /** Custom templates {@link FilterComponent}. */ private class TemplatesFilterComponent extends FilterComponent { /** Builds a new instance of {@link TemplatesFilterComponent}. */ public TemplatesFilterComponent() { super(TEMPLATES_FILTER_HISTORY, 10); } /** Filters tree using current filter's value. */ @Override public void filter() { filterTree(getFilter()); } } /** {@link OkAction} instance with additional `Generate without duplicates` action. */ protected class OptionOkAction extends OkAction implements OptionAction { @NotNull @Override public Action[] getOptions() { return new Action[]{new DialogWrapperAction(IgnoreBundle.message("global.generate.without.duplicates")) { @Override protected void doAction(ActionEvent e) { performAppendAction(true); } }}; } } }
package org.jdesktop.swingx.painter.effects; import java.awt.Graphics2D; import java.awt.Shape; /** * An effect which works on AbstractPathPainters or any thing else which can provide a shape to be drawn. * @author joshy */ public interface AreaEffect { /* * Applies the shape effect. This effect will be drawn on top of the graphics context. */ /** * Draws an effect on the specified graphics and path using the specified width and height. * @param g * @param clipShape * @param width * @param height */ public abstract void apply(Graphics2D g, Shape clipShape, int width, int height); }
package dk.netarkivet.harvester.datamodel; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import dk.netarkivet.common.exceptions.ArgumentNotValid; import dk.netarkivet.common.exceptions.PermissionDenied; import dk.netarkivet.common.exceptions.UnknownID; import dk.netarkivet.common.utils.Settings; import dk.netarkivet.harvester.HarvesterSettings; /** * This class describes a configuration for harvesting a domain. * It combines a number of seedlists, a number of passwords, an order template, * and some specialised settings to define the way to harvest a domain. * */ public class DomainConfiguration implements Named { private String configName; private String orderXmlName = ""; /** maximum number of objects harvested for this configuration in a snapshot * harvest. Note that the default number is a long, but this is an int. */ private int maxObjects; private int maxRequestRate; /** Maximum number of bytes to download in a harvest */ private long maxBytes; private Domain domain; // List - list of seedlists private List<SeedList> seedlists; // passwords that apply in this configuration private List<Password> passwords; private String comments; /** ID autogenerated by DB, not used in XML. */ private Long id; private final Log log = LogFactory.getLog(DomainConfiguration.class); /** How many objects should be harvested in a harvest to trust that our * expected size of objects is less than the default number */ private static final long MIN_OBJECTS_TO_TRUST_SMALL_EXPECTATION = 50L; /** The smallest number of bytes we accept per object */ private static final int MIN_EXPECTATION = 1; /** Create a new configuration for a domain. * * @param theConfigName The name of this configuration * @param domain The domain thet this configuration is for * @param seedlists Seedlists to use in this configuration. * @param passwords Passwords to use in this configuration. */ public DomainConfiguration(String theConfigName, Domain domain, List<SeedList> seedlists, List<Password> passwords) { ArgumentNotValid.checkNotNullOrEmpty(theConfigName, "theConfigName"); ArgumentNotValid.checkNotNull(domain, "domain"); ArgumentNotValid.checkNotNullOrEmpty(seedlists, "seedlists"); ArgumentNotValid.checkNotNull(passwords, "passwords"); this.configName = theConfigName; this.domain = domain; this.seedlists = seedlists; this.passwords = passwords; this.comments = ""; this.maxRequestRate = Constants.DEFAULT_MAX_REQUEST_RATE; this.maxObjects = (int) Constants.DEFAULT_MAX_OBJECTS; this.maxBytes = Constants.DEFAULT_MAX_BYTES; } /** * Specify the name of the order.xml template to use. * * @param ordername order.xml template name * @throws ArgumentNotValid if filename null or empty */ public void setOrderXmlName(String ordername) { ArgumentNotValid.checkNotNullOrEmpty(ordername, "filename"); orderXmlName = ordername; } /** * Specify the maximum number of objects to retrieve from the domain. * * @param max maximum number of objects to retrieve * @throws ArgumentNotValid if max<-1 */ public void setMaxObjects(int max) { if (max < -MIN_EXPECTATION) { String msg = "maxObjects must be either -1 or positive"; log.debug(msg); throw new ArgumentNotValid(msg); } maxObjects = max; } /** * Specify the maximum request rate to use when harvesting data. * * @param maxrate the maximum request rate * @throws ArgumentNotValid if maxrate<0 */ public void setMaxRequestRate(int maxrate) { ArgumentNotValid.checkNotNegative(maxrate, "maxrate"); maxRequestRate = maxrate; } /** Specify the maximum number of bytes to download from a domain * in a single harvest. * * @param maxBytes Maximum number of bytes to download, or -1 for no limit. * @throws ArgumentNotValid if maxBytes < -1 */ public void setMaxBytes(long maxBytes) { if (maxBytes < -MIN_EXPECTATION) { String msg = "DomainConfiguration.maxBytes must be -1 or positive."; log.debug(msg); throw new ArgumentNotValid(msg); } this.maxBytes = maxBytes; } /** * Get the configuration name. * * @return the configuration name */ public String getName() { return configName; } public String getComments() { return comments; } /** * Returns the name of the order xml file used by the domain. * * @return name of the order.xml file that should be used when harvesting * the domain */ public String getOrderXmlName() { return orderXmlName; } /** * Returns the maximum number of objects to harvest from the domain. * * @return maximum number of objects to harvest */ public int getMaxObjects() { return maxObjects; } /** * Returns the maximum request rate to use when harvesting the domain. * * @return maximum request rate */ public int getMaxRequestRate() { return maxRequestRate; } /** Returns the maximum number of bytes to download during a single harvest * of a domain. * @return Maximum bytes limit, or -1 for no limit. */ public long getMaxBytes() { return maxBytes; } /** * Returns the domain aggregating this config. * * @return the Domain aggregating this config. */ public Domain getDomain() { return domain; } /** Adds harvest information to the configurations history. * @param hi HarvestInfo to add to Domain. */ public void addHarvestInfo(HarvestInfo hi) { domain.getHistory().addHarvestInfo(hi); } /** Get an iterator of seedlists used in this configuration. * * @return seedlists as iterator */ public Iterator<SeedList> getSeedLists() { return seedlists.iterator(); } public void addSeedList(SeedList seedlist) { ArgumentNotValid.checkNotNull(seedlist, "seedlist"); SeedList domainSeedlist = domain.getSeedList(seedlist.getName()); if (!domainSeedlist.equals(seedlist)) { String message = "Cannot add seedlist " + seedlist + " to " + this + " as it differs from the one defined for " + domain + ": " + domainSeedlist; log.debug(message); throw new PermissionDenied(message); } seedlists.add(domainSeedlist); } /** Get an iterator of passwords used in this configuration. * * @return The passwords in an iterator */ public Iterator<Password> getPasswords() { return passwords.iterator(); } public void addPassword(Password password) { ArgumentNotValid.checkNotNull(password, "password"); Password domainPassword = domain.getPassword(password.getName()); if (!domainPassword.equals(password)) { String message = "Cannot add password " + password + " to " + this + " as it differs from the one defined for " + domain + ": " + domainPassword; log.debug(message); throw new PermissionDenied(message); } passwords.add(domainPassword); } /** * Gets the harvest info giving best information for expectation * or how many objects a harvest using this configuration will retrieve. * * @return The Harvest Information for the harvest defining the best * expectation, including the number retrieved and the stop reason. */ private HarvestInfo getBestHarvestInfoExpectation() { //Remember best expectation HarvestInfo best = null; //loop through all harvest infos for this configuration. The iterator is //sorted by date with most recent first for (Iterator<HarvestInfo> i = domain.getHistory().getHarvestInfo(); i.hasNext(); ) { HarvestInfo hi = i.next(); if (hi.getDomainConfigurationName().equals(getName())) { //Remember this expectation, if it harvested at least //as many objects as the previously remembered if ((best == null) || (best.getCountObjectRetrieved() <= hi.getCountObjectRetrieved())) { best = hi; } //if this harvest completed, stop search and return best //expectation, if (hi.getStopReason() == StopReason.DOWNLOAD_COMPLETE) { return best; } } } //Return maximum uncompleted harvest, or null if never harvested return best; } /** * Gets the best expectation for how many objects a harvest using * this configuration will retrieve, given a job with a maximum limit pr. * domain * * @param objectLimit The maximum limit, or 0 for no limit. * This limit overrides the limit set on the configuration, * unless override is in effect. * @param byteLimit The maximum number of bytes that will be used as * limit in the harvest. This limit overrides the limit set on the * configuration, unless override is in effect. It is used to modify * the expected number of objects based on what we know of object sizes. * -1 means not limit. * @return The expected number of objects. */ public long getExpectedNumberOfObjects(long objectLimit, long byteLimit) { long prevresultfactor = Settings.getLong( HarvesterSettings.ERRORFACTOR_PERMITTED_PREVRESULT); //long bestguessfactor // = Settings.getLong( // HarvesterSettings.ERRORFACTOR_PERMITTED_BESTGUESS); HarvestInfo best = getBestHarvestInfoExpectation(); log.trace("Using domain info '" + best + "' for configuration '" + toString() + "'"); long expectedObjectSize = getExpectedBytesPerObject(best); // The maximum number of objects that the maxBytes setting gives. long maximum = -1; if (objectLimit != Constants.HERITRIX_MAXOBJECTS_INFINITY || byteLimit != Constants.HERITRIX_MAXBYTES_INFINITY) { maximum = minObjectsBytesLimit(objectLimit, byteLimit, expectedObjectSize); } else if (maxObjects != Constants.HERITRIX_MAXOBJECTS_INFINITY || maxBytes != Constants.HERITRIX_MAXBYTES_INFINITY) { maximum = minObjectsBytesLimit(maxObjects, maxBytes, expectedObjectSize); } /*else { maximum = Settings.getLong(HarvesterSettings.MAX_DOMAIN_SIZE); } */ long minimum; if (best != null) { minimum = best.getCountObjectRetrieved(); } else { minimum = 0; } // Calculate the expectated number of objects we will harvest. long expectation; if (best != null && best.getStopReason() == StopReason.DOWNLOAD_COMPLETE && maximum != -1) { //We set the expectation, so our harvest will exceed the expectation //at most <factor> times if the domain is a lot larger than //our best guess. expectation = minimum + ((maximum - minimum) / prevresultfactor); } else { // old calculation //expectation = minimum + ((maximum - minimum) / bestguessfactor); // use Settings to define max domain settins bug #928 expectation = Settings.getLong(HarvesterSettings.MAX_DOMAIN_SIZE); } // Always limit to domain specifics if set to do so. We always expect // to actually hit this limit if ((maxObjects > Constants.HERITRIX_MAXOBJECTS_INFINITY && maximum > maxObjects) || (maxBytes > Constants.HERITRIX_MAXBYTES_INFINITY && maximum > maxBytes / expectedObjectSize)) { maximum = minObjectsBytesLimit(maxObjects, maxBytes, expectedObjectSize); } //Never return more than allowed maximum expectation = Math.min(expectation, maximum); log.trace("Expected number of objects for configuration '" + toString() + " is " + expectation); return expectation; } /** Return the lowest limit for the two values, or MAX_DOMAIN_SIZE if both * are infinite, which is the max size we harvest from this domain. * * @param objectLimit A long value defining an object limit, or 0 for * infinite * @param byteLimit A long value defining a byte limit, or -1 for inifite. * @param expectedObjectSize The expected number of bytes per object * @return The lowest of the two boundaries, or MAX_DOMAIN_SIZE if both are * unlimited. * */ public long minObjectsBytesLimit(long objectLimit, long byteLimit, long expectedObjectSize) { long maxObjectsByBytes = byteLimit / expectedObjectSize; if (objectLimit != Constants.HERITRIX_MAXOBJECTS_INFINITY) { if (byteLimit != Constants.HERITRIX_MAXBYTES_INFINITY) { return Math.min(objectLimit, maxObjectsByBytes); } else { return objectLimit; } } else { if (byteLimit != Constants.HERITRIX_MAXBYTES_INFINITY) { return maxObjectsByBytes; } else { return Settings.getLong(HarvesterSettings.MAX_DOMAIN_SIZE); } } } /** How many bytes we can expect the average object of a domain to be. * If we have harvested no objects from this domain before, we use a * setting EXPECTED_AVERAGE_BYTES_PER_OBJECT. If we have objects, we use the * harvestinfo from previous harvests to calculate the harvest, but we * only accept a low estimate if the number of harvested objects is greater * than the setting MIN_OBJECTS_TO_TRUST_SMALL_EXPECTATION. * * @param bestInfo The best (newest complete or biggest, as per * getBestHarvestInfoExpectation()) harvest info we have for the domain. * @return How large we expect the average object to be. This number will * be >= MIN_EXPECTATION (unless nothing is harvested and is * EXPECTED_AVERAGE_BYTES_PER_OBJECT <= 0). */ private long getExpectedBytesPerObject(HarvestInfo bestInfo) { long default_expectation = Settings.getLong( HarvesterSettings.EXPECTED_AVERAGE_BYTES_PER_OBJECT); if (bestInfo != null && bestInfo.getCountObjectRetrieved() > 0) { long expectation = Math.max(MIN_EXPECTATION, bestInfo.getSizeDataRetrieved() / bestInfo.getCountObjectRetrieved()); if (expectation < default_expectation && bestInfo.getCountObjectRetrieved() < MIN_OBJECTS_TO_TRUST_SMALL_EXPECTATION) { return default_expectation; } return expectation; } else { return default_expectation; } } /** Set the comments field. * * @param comments User-entered free-form comments. */ public void setComments(String comments) { this.comments = comments; } /** Remove a password from the list of passwords used in this domain. * @param passwordName Password to Remove. */ public void removePassword(String passwordName) { ArgumentNotValid.checkNotNullOrEmpty(passwordName, "passwordName"); if (!usesPassword(passwordName)) { throw new UnknownID("No password named '" + passwordName + "' found in '" + this + "'"); } for (Iterator<Password> i = passwords.iterator(); i.hasNext();) { Password p = i.next(); if (p.getName().equals(passwordName)) { i.remove(); } } } /** Check whether this domain uses a given password. * @param passwordName The given password * @return whether the given password is used */ public boolean usesPassword(String passwordName) { for (Password p: passwords) { if (p.getName().equals(passwordName)) { return true; } } return false; } /** * Sets the used seedlists to the given list. Note: list is copied. * @param seedlists The seedlists to use. * @throws ArgumentNotValid if the seedslists are null */ public void setSeedLists(List<SeedList> seedlists) { ArgumentNotValid.checkNotNull(seedlists, "seedlists"); this.seedlists = new ArrayList<SeedList>(seedlists.size()); for(SeedList s: seedlists) { addSeedList(s); } } /** * Sets the used passwords to the given list. Note: list is copied. * @param passwords The passwords to use. * @throws ArgumentNotValid if the passwords are null */ public void setPasswords(List<Password> passwords) { ArgumentNotValid.checkNotNull(passwords, "passwords"); this.passwords = new ArrayList<Password>(passwords.size()); for(Password p: passwords) { addPassword(p); } } /** Get the ID of this configuration. Only for use by DBDAO * @return the ID of this configuration */ long getID() { return id; } /** Set the ID of this configuration. Only for use by DBDAO * @param id use this id for this configuration */ void setID(long id) { this.id = id; } /** Check if this configuration has an ID set yet (doesn't happen until * the DBDAO persists it). * @return true, if the configuration has an ID */ boolean hasID() { return id != null; } public String toString() { return "Configuration '" + getName() + "' of domain '" + getDomain().getName() + "'"; } }
package com.codeski.fixchat; public class FixChat { public enum Achievements { ACQUIRE_IRON("Acquire Hardware"), BAKE_CAKE("The Lie"), BOOKCASE("Librarian"), BREED_COW("Repopulation"), BREW_POTION("Local Brewery"), BUILD_BETTER_PICKAXE("Getting an Upgrade"), BUILD_FURNACE("Hot Topic"), BUILD_HOE("Time to Farm!"), BUILD_PICKAXE("Time to Mine!"), BUILD_SWORD("Time to Strike!"), BUILD_WORKBENCH("Benchmarking"), COOK_FISH("Delicious Fish"), DIAMONDS_TO_YOU("Diamonds to you!"), ENCHANTMENTS("Enchanter"), END_PORTAL("The End?"), EXPLORE_ALL_BIOMES("Adventuring Time"), FLY_PIG("When Pigs Fly"), FULL_BEACON("Beaconator"), GET_BLAZE_ROD("Into Fire"), GET_DIAMONDS("DIAMONDS!"), GHAST_RETURN("Return to Sender"), KILL_COW("Cow Tipper"), KILL_ENEMY("Monster Hunter"), KILL_WITHER("The Beginning."), MAKE_BREAD("Bake Bread"), MINE_WOOD("Getting Wood"), NETHER_PORTAL("We Need to Go Deeper"), ON_A_RAIL("On A Rail"), OPEN_INVENTORY("Taking Inventory"), OVERKILL("Overkill"), OVERPOWERED("Overpowered"), SNIPE_SKELETON("Sniper Duel"), SPAWN_WITHER("The Beginning?"), THE_END("The End."); private final String name; private Achievements(String name) { this.name = name; } @Override public String toString() { return name; } } public enum Strings { AWAY(" is away from keyboard"), NO_WHISPER_REPLY("There's no whisper to reply to."), NON_PLAYER_REPLY("Non-players cannot respond because they cannot receive whispers."), NOT_AWAY(" is no longer away from keyboard"); private final String name; private Strings(String name) { this.name = name; } @Override public String toString() { return name; } } public static int _MPS = 1000; public static int _TPS = 20; public static int AWAY = 300 * _MPS; public static int INTERVAL = 30 * _TPS; }
package me.footlights.core; import java.io.*; import java.util.*; import java.util.Map.Entry; import java.util.logging.Logger; import me.footlights.core.crypto.Keychain; import me.footlights.core.plugin.*; public class Core implements Footlights, KernelInterface { public Core() { String configDirName = "~/.footlights/"; File configDir = new File(configDirName); configDir.mkdir(); keychain = new Keychain(); final String keychainFileName = configDirName + "/keychain"; try { keychain.importKeystoreFile(new FileInputStream(new File(keychainFileName))); } catch (Exception e) { Logger.getLogger(Core.class.getName()) .warning("Unable to open keychain: " + e.getLocalizedMessage()); } plugins = new HashMap<String,PluginWrapper>(); pluginServer = new PluginServer(this); uis = new LinkedList<UI>(); } public void registerUI(UI ui) { uis.add(ui); } public void deregisterUI(UI ui) { uis.remove(ui); } public Collection<PluginWrapper> plugins() { return plugins.values(); } /** Load a plugin and wrap it up in a convenient wrapper */ public PluginWrapper loadPlugin(String url) throws PluginLoadException { if(plugins.containsKey(url)) return plugins.get(url); PluginWrapper plugin = new PluginLoader(pluginServer).loadPlugin(url); plugins.put(url, plugin); for(UI ui : uis) ui.pluginLoaded(plugin); return plugin; } /** Unload a plugin; after calling this, set ALL references to null */ public void unloadPlugin(PluginWrapper plugin) { String key = null; for(Entry<String,PluginWrapper> e : plugins.entrySet()) if(e.getValue().equals(plugin)) { key = e.getKey(); break; } if(key == null) return; for(UI ui : uis) ui.pluginUnloading(plugins.get(key)); plugins.remove(key); } // KernelInterface implementation public java.util.UUID generateUUID() { return java.util.UUID.randomUUID(); } /** Name of the Core {@link Logger}. */ public static final String CORE_LOG_NAME = "me.footlights.core"; /** Our keychain */ private Keychain keychain; /** Loaded plugins */ private Map<String,PluginWrapper> plugins; /** Handles plugin requests */ private PluginServer pluginServer; /** UIs which might like to be informed of events */ private List<UI> uis; }
package fr.umlv.ninal.interpreter; import java.io.IOException; import java.math.BigInteger; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import com.oracle.truffle.api.Arguments; import com.oracle.truffle.api.CallTarget; import com.oracle.truffle.api.ExactMath; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.TruffleRuntime; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.frame.FrameSlotKind; import com.oracle.truffle.api.frame.FrameSlotTypeException; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.ExplodeLoop; import com.oracle.truffle.api.nodes.NodeUtil; import fr.umlv.ninal.lang.List; import fr.umlv.ninal.lang.Symbol; import fr.umlv.ninal.parser.Parser; public class Interpreter { static abstract class Node extends com.oracle.truffle.api.nodes.Node { protected Node() { super(); } abstract Object eval(VirtualFrame frame); } static class ConstNode extends Node { private final Object constant; ConstNode(Object constant) { this.constant = constant; } @Override public Object eval(VirtualFrame frame) { return constant; } } static class LiteralListNode extends Node { @Children private final Node[] valueNodes; LiteralListNode(Node[] nodes) { this.valueNodes = adoptChildren(nodes); } @Override @ExplodeLoop public Object eval(VirtualFrame frame) { Object[] values = new Object[valueNodes.length]; for(int i=0; i<values.length; i++) { values[i] = valueNodes[i].eval(frame); } return List.of(values); } } static class EvalNode extends com.oracle.truffle.api.nodes.RootNode { @Child private final Node bodyNode; EvalNode(Node bodyNode) { this.bodyNode = adoptChild(bodyNode); } @Override public Object execute(VirtualFrame frame) { return bodyNode.eval(frame); } } static class FunctionNode extends com.oracle.truffle.api.nodes.RootNode { private final Symbol symbol; @Children private final ParameterNode[] parameterNodes; @Child private final Node bodyNode; FunctionNode(Symbol symbol, ParameterNode[] parameterNodes, Node bodyNode) { this.symbol = symbol; this.parameterNodes = adoptChildren(parameterNodes); this.bodyNode = adoptChild(bodyNode); } @Override @ExplodeLoop public Object execute(VirtualFrame frame) { ArrayArguments arguments = frame.getArguments(ArrayArguments.class); if (parameterNodes.length != arguments.size()) { throw new RuntimeException("invalid number of arguments for function call " + symbol); } for(int i = 0; i < parameterNodes.length; i++) { parameterNodes[i].setObject(frame, arguments.get(i)); } return bodyNode.eval(frame); } } /*non-static*/ class DefNode extends Node { private final Symbol name; private final FrameDescriptor functionFrameDescriptor; @Children private final ParameterNode[] parameterNodes; @Child private final Node bodyNode; DefNode(Symbol name, FrameDescriptor functionFrameDescriptor, ParameterNode[] parameterNodes, Node bodyNode) { this.name = name; this.functionFrameDescriptor = functionFrameDescriptor; this.parameterNodes = adoptChildren(parameterNodes); this.bodyNode = adoptChild(bodyNode); } public Symbol getName() { return name; } @Override public Object eval(VirtualFrame frame) { FunctionNode functionNode = new FunctionNode(name, parameterNodes, bodyNode); NodeUtil.printTree(System.out, functionNode); CallTarget callTarget = Truffle.getRuntime().createCallTarget(functionNode, functionFrameDescriptor); callTargetMap.put(name, callTarget); return List.empty(); } } /*non-static*/ class FunCallNode extends Node { private final Symbol name; @Children private final Node[] argumentNodes; FunCallNode(Symbol name, Node[] argumentNodes) { this.name = name; this.argumentNodes = adoptChildren(argumentNodes); } @Override @ExplodeLoop public Object eval(VirtualFrame frame) { Object[] arguments = new Object[argumentNodes.length]; for(int i=0; i<argumentNodes.length; i++) { arguments[i] = argumentNodes[i].eval(frame); } CallTarget callTarget = callTargetMap.get(name); return callTarget.call(frame.pack(), new ArrayArguments(arguments)); } } static class ParameterNode extends com.oracle.truffle.api.nodes.Node { private final FrameSlot slot; ParameterNode(FrameSlot slot) { this.slot = slot; } void setObject(VirtualFrame frame, Object value) { try { frame.setObject(slot, value); } catch (FrameSlotTypeException e) { throw new RuntimeException(e); } } } //FIXME should be List ? static class ArrayArguments extends Arguments { private final Object[] values; ArrayArguments(Object[] values) { this.values = values; } int size() { return values.length; } Object get(int index) { return values[index]; } } enum BinOp { ADD("+"), SUB("-"), MUL("*"), DIV("/"), LT("<"), GT(">"), LE("<="), GE(">="); private final String name; private BinOp(String name) { this.name = name; } private static final HashMap<String, BinOp> MAP; static { HashMap<String, BinOp> map = new HashMap<>(); for(BinOp binOp: BinOp.values()) { map.put(binOp.name, binOp); } MAP = map; } static BinOp getBinOp(String name) { return MAP.get(name); } } static class NumberOpNode extends Node { private final BinOp binOp; @Child private final Node leftNode; @Child private final Node rightNode; NumberOpNode(BinOp binOp, Node leftNode, Node rightNode) { this.binOp = binOp; this.leftNode = adoptChild(leftNode); this.rightNode = adoptChild(rightNode); } @Override public Object eval(VirtualFrame frame) { Object leftValue = leftNode.eval(frame); Object rightValue = rightNode.eval(frame); if (leftValue instanceof Integer && rightValue instanceof Integer) { return doSmallOp(leftValue, rightValue); } return slowPath(leftValue, rightValue); } private BigInteger slowPath(Object leftValue, Object rightValue) { return doBigOp(asBigInteger(leftValue), asBigInteger(rightValue)); } private static BigInteger asBigInteger(Object value) { if (value instanceof BigInteger) { return (BigInteger)value; } if (value instanceof Integer) { return BigInteger.valueOf((Integer)value); } throw new RuntimeException("invalid type " + value + ' ' + value.getClass()); } private Object doSmallOp(Object leftValue, Object rightValue) { int left = (Integer)leftValue; int right = (Integer)rightValue; try { switch(binOp) { case ADD: return ExactMath.addExact(left, right); case SUB: return ExactMath.subtractExact(left, right); case MUL: return ExactMath.multiplyExact(left, right); case DIV: return left / right; default: throw new AssertionError("unknown " + binOp); } } catch(ArithmeticException e) { return doBigOp(BigInteger.valueOf(left), BigInteger.valueOf(right)); } } private BigInteger doBigOp(BigInteger leftValue, BigInteger rightValue) { switch(binOp) { case ADD: return leftValue.add(rightValue); case SUB: return leftValue.subtract(rightValue); case MUL: return leftValue.multiply(rightValue); case DIV: return leftValue.divide(rightValue); default: throw new AssertionError("unknown " + binOp); } } } static class TestOpNode extends Node { private final BinOp binOp; @Child private final Node leftNode; @Child private final Node rightNode; TestOpNode(BinOp binOp, Node leftNode, Node rightNode) { this.binOp = binOp; this.leftNode = adoptChild(leftNode); this.rightNode = adoptChild(rightNode); } @Override public Object eval(VirtualFrame frame) { Object leftValue = leftNode.eval(frame); Object rightValue = rightNode.eval(frame); if (leftValue instanceof Integer && rightValue instanceof Integer) { return doSmallOp(leftValue, rightValue); } return slowPath(leftValue, rightValue); } private boolean slowPath(Object leftValue, Object rightValue) { return doBigOp(asBigInteger(leftValue), asBigInteger(rightValue)); } private static BigInteger asBigInteger(Object value) { if (value instanceof BigInteger) { return (BigInteger)value; } if (value instanceof Integer) { return BigInteger.valueOf((Integer)value); } throw new RuntimeException("invalid type " + value); } private boolean doSmallOp(Object leftValue, Object rightValue) { int left = (Integer)leftValue; int right = (Integer)rightValue; switch(binOp) { case LT: return left < right; case LE: return left <= right; case GT: return left > right; case GE: return left >= right; default: throw new AssertionError("unknown " + binOp); } } private boolean doBigOp(BigInteger leftValue, BigInteger rightValue) { switch(binOp) { case LT: return leftValue.compareTo(rightValue) < 0; case LE: return leftValue.compareTo(rightValue) <= 0; case GT: return leftValue.compareTo(rightValue) > 0; case GE: return leftValue.compareTo(rightValue) >= 0; default: throw new AssertionError("unknown " + binOp); } } } static class PrintNode extends Node { @Child private final Node node; PrintNode(Node node) { this.node = adoptChild(node); } @Override Object eval(VirtualFrame frame) { System.out.println(node.eval(frame)); return List.empty(); } } static class IfNode extends Node { @Child private final Node condition; @Child private final Node trueNode; @Child private final Node falseNode; IfNode(Node condition, Node trueNode, Node falseNode) { this.condition = adoptChild(condition); this.trueNode = adoptChild(trueNode); this.falseNode = adoptChild(falseNode); } @Override Object eval(VirtualFrame frame) { Object test = condition.eval(frame); if (!(test instanceof Boolean)) { throw new RuntimeException("condition value is not a boolean " + test); } if ((Boolean)test) { return trueNode.eval(frame); } return falseNode.eval(frame); } } static class VarLoadNode extends Node { private final FrameSlot slot; VarLoadNode(FrameSlot slot) { this.slot = slot; } @Override Object eval(VirtualFrame frame) { try { return frame.getObject(slot); } catch (FrameSlotTypeException e) { throw new AssertionError(e); } } } static class VarStoreNode extends Node { private final FrameSlot slot; @Child private final Node initNode; VarStoreNode(FrameSlot slot, Node initNode) { this.slot = slot; this.initNode = adoptChild(initNode); } @Override Object eval(VirtualFrame frame) { Object value = initNode.eval(frame); try { frame.setObject(slot, value); } catch (FrameSlotTypeException e) { throw new AssertionError(e); } return List.empty(); } } final HashMap<Symbol,CallTarget> callTargetMap = new HashMap<>(); public Interpreter() { // do nothing for now } private static void checkArguments(List list, String... descriptions) { Symbol symbol = (Symbol)list.get(0); if (list.size() != 1 + descriptions.length) { throw new RuntimeException("invalid number of arguments for " + symbol + ' ' + list); } for(int i = 0; i<descriptions.length; i++) { checkArgument(symbol, i, descriptions[i], list.get(i + 1)); } } private static void checkArgument(Symbol symbol, int index, String description, Object value) { switch(description) { case "value": case "statement": return; case "symbol": if (!(value instanceof Symbol)) { throw new RuntimeException(symbol + ": invalid argument " + index +", should be a symbol, instead of " + value); } return; case "parameters": if (!(value instanceof List)) { throw new RuntimeException(symbol + ": invalid argument " + index +", should be a list, instead of " + value); } List parameters =(List)value; for(Object parameter: parameters) { if (!(parameter instanceof Symbol)) { throw new RuntimeException(symbol + ": invalid parameter name " + parameter); } } return; default: throw new AssertionError("unknown description " + description); } } private Node createAST(Object value, FrameDescriptor frameDescriptor) { if (value instanceof List) { return createListAST((List)value, frameDescriptor); } if (value instanceof String) { return createLiteralString((String)value); } if (value instanceof Symbol) { Symbol symbol = (Symbol)value; FrameSlot slot = frameDescriptor.findFrameSlot(symbol); if (slot == null) { // not a local variable throw new RuntimeException("unknown local symbol " + symbol); } return createVarLoad(slot); } if (value instanceof Number) { return createLiteralNumber((Number)value); } throw new AssertionError("unknown value " + value); } private Node createListAST(List list, FrameDescriptor frameDescriptor) { if (list.isEmpty()) { return createLiteralList(createChildren(list, 0, frameDescriptor)); } Object first = list.get(0); if (!(first instanceof Symbol)) { return createLiteralList(createChildren(list, 0, frameDescriptor)); } Symbol symbol = (Symbol)first; switch(symbol.getName()) { case "def": { checkArguments(list, "symbol", "parameters", "statement"); Symbol defSymbol = (Symbol)list.get(1); FrameDescriptor functionFrameDescriptor = new FrameDescriptor(); List parameters = (List)list.get(2); ParameterNode[] parameterNodes = new ParameterNode[parameters.size()]; for(int i = 0; i < parameters.size(); i++) { Symbol parameter = (Symbol) parameters.get(i); parameterNodes[i] = new ParameterNode(functionFrameDescriptor.addFrameSlot(parameter, FrameSlotKind.Object)); } Node body = createAST(list.get(3), functionFrameDescriptor); return createDef(defSymbol, functionFrameDescriptor, parameterNodes, body); } case "if": checkArguments(list, "value", "statement", "statement"); return createIf(createAST(list.get(1), frameDescriptor), createAST(list.get(2), frameDescriptor), createAST(list.get(3), frameDescriptor)); case "var": { checkArguments(list, "symbol", "value"); Symbol varSymbol = (Symbol)list.get(1); FrameSlot slot = frameDescriptor.addFrameSlot(varSymbol, FrameSlotKind.Object); return createVarStore(slot, createAST(list.get(2), frameDescriptor)); } case "print": checkArguments(list, "value"); return createPrint(createAST(list.get(1), frameDescriptor)); case "+": case "-": case "*": case "/": case "<": case "<=": case ">": case ">=": checkArguments(list, "value", "value"); BinOp binOp = BinOp.getBinOp(symbol.getName()); return createBinOp(binOp, createAST(list.get(1), frameDescriptor), createAST(list.get(2), frameDescriptor)); default: // variable local access or function call FrameSlot slot = frameDescriptor.findFrameSlot(symbol); if (slot == null) { // not a local variable so it's a method call return createFunCall(symbol, createChildren(list, 1, frameDescriptor)); } return createLiteralList(createChildren(list, 0, frameDescriptor)); } } private Node[] createChildren(List list, int offset, FrameDescriptor frameDescriptor) { Node[] nodes = new Node[list.size() - offset]; for(int i=0; i<nodes.length; i++) { nodes[i] = createAST(list.get(i + offset), frameDescriptor); } return nodes; } private static Node createLiteralNumber(Number number) { return new ConstNode(number); } private static Node createLiteralString(String string) { return new ConstNode(string); } private static Node createLiteralList(Node[] nodes) { return new LiteralListNode(nodes); } private Node createDef(Symbol name, FrameDescriptor functionFrameDescriptor, ParameterNode[] parameterNodes, Node bodyNode) { return new DefNode(name, functionFrameDescriptor, parameterNodes, bodyNode); } private static Node createVarStore(FrameSlot slot, Node init) { return new VarStoreNode(slot, init); } private static Node createPrint(Node node) { return new PrintNode(node); } private static Node createVarLoad(FrameSlot slot) { return new VarLoadNode(slot); } private static Node createIf(Node condition, Node trueNode, Node falseNode) { return new IfNode(condition, trueNode, falseNode); } Node createFunCall(Symbol name, Node[] children) { return new FunCallNode(name, children); } static Node createBinOp(BinOp binOp, Node left, Node right) { switch(binOp) { case ADD: case SUB: case MUL: case DIV: return new NumberOpNode(binOp, left, right); case LT: case LE: case GT: case GE: return new TestOpNode(binOp, left, right); default: throw new AssertionError(binOp); } } public void interpret(Path path) throws IOException { byte[] data = Files.readAllBytes(path); TruffleRuntime runtime = Truffle.getRuntime(); System.out.println("using " + runtime.getName()); Parser parser = new Parser(data); while(!parser.end()) { List list = parser.parseList(); Node node = createAST(list, new FrameDescriptor()); EvalNode evalNode = new EvalNode(node); CallTarget callTarget = runtime.createCallTarget(evalNode); callTarget.call(); } } }
package net.domesdaybook.parser.tree; /** * This enumeration defines the types of nodes which can appear in a {@link ParseTree} * * @author Matt Palmer */ public enum ParseTreeType { // Value-specifying leaf node types // // Have a well defined value, and no children // BYTE("A single byte value"), INTEGER("An integer value"), ALL_BITMASK("A bitmask for matching all of its bits"), ANY_BITMASK("A bitmask for matching any of its bits"), ANY("A wildcard matching any byte value"), CASE_SENSITIVE_STRING("An ASCII string to match case sensitively"), CASE_INSENSITIVE_STRING("An ASCII string to match case insensitively"), // Value-specifying parent node types // // No direct value, but have child ParseTree // // nodes that define its value. // //TODO: range can also have many nodes as the max value. RANGE("A range of byte values with the range defined as two child INTEGER ParseTree nodes, from 0 to 255"), SET("A set of byte values, bitmasks, ranges, or other sets of bytes as children of this node"), // Imperative parent node types // // Specifies what to do with child nodes. // SEQUENCE("An ordered sequence of child ParseTree nodes"), REPEAT("Repeat the third child ParseTree from a minimum (first INTEGER child) to a maximum (second INTEGER or MANY child) number of times."), ALTERNATIVES("A set of alternatives as children of this ParseTree"), ZERO_TO_MANY("Repeat the child ParseTree zero to many times"), ONE_TO_MANY("Repeat the child ParseTree one to many times"), OPTIONAL("The child ParseTree is optional (repeat zero to one times)."); private final String description; private ParseTreeType(final String description) { this.description = description; } public String getDescription() { return description; } }
package dr.evomodel.continuous.hmc; import dr.evolution.tree.Tree; import dr.evolution.tree.TreeTrait; import dr.evomodel.treedatalikelihood.DataLikelihoodDelegate; import dr.evomodel.treedatalikelihood.TreeDataLikelihood; import dr.evomodel.treedatalikelihood.continuous.ContinuousDataLikelihoodDelegate; import dr.evomodel.treedatalikelihood.continuous.IntegratedFactorAnalysisLikelihood; import dr.evomodel.treedatalikelihood.continuous.cdi.PrecisionType; import dr.evomodel.treedatalikelihood.preorder.WrappedNormalSufficientStatistics; import dr.evomodel.treedatalikelihood.preorder.WrappedTipFullConditionalDistributionDelegate; import dr.inference.hmc.GradientWrtParameterProvider; import dr.inference.model.CompoundLikelihood; import dr.inference.model.Likelihood; import dr.inference.model.Parameter; import dr.math.MultivariateFunction; import dr.math.NumericalDerivative; import dr.math.matrixAlgebra.*; import dr.math.matrixAlgebra.missingData.MissingOps; import dr.xml.*; import org.ejml.data.DenseMatrix64F; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static dr.evomodel.continuous.hmc.LinearOrderTreePrecisionTraitProductProvider.castTreeTrait; import static dr.math.matrixAlgebra.missingData.MissingOps.safeInvert; import static dr.math.matrixAlgebra.missingData.MissingOps.weightedAverage; /** * @author Marc A. Suchard * @author Andrew Holbrook */ public class IntegratedLoadingsGradient implements GradientWrtParameterProvider, Reportable { private final TreeTrait<List<WrappedNormalSufficientStatistics>> fullConditionalDensity; private final TreeDataLikelihood treeDataLikelihood; private final IntegratedFactorAnalysisLikelihood factorAnalysisLikelihood; private final int dimTrait; private final int dimFactors; private final Tree tree; private final Likelihood likelihood; private final int threadCount; private final Parameter data; private final boolean[] missing; private static final boolean SMART_POOL = true; private IntegratedLoadingsGradient(TreeDataLikelihood treeDataLikelihood, ContinuousDataLikelihoodDelegate likelihoodDelegate, IntegratedFactorAnalysisLikelihood factorAnalysisLikelihood) { this.treeDataLikelihood = treeDataLikelihood; this.factorAnalysisLikelihood = factorAnalysisLikelihood; String traitName = factorAnalysisLikelihood.getModelName(); String fcdName = WrappedTipFullConditionalDistributionDelegate.getName(traitName); if (treeDataLikelihood.getTreeTrait(fcdName) == null) { likelihoodDelegate.addWrappedFullConditionalDensityTrait(traitName); } this.fullConditionalDensity = castTreeTrait(treeDataLikelihood.getTreeTrait(fcdName)); this.tree = treeDataLikelihood.getTree(); this.dimTrait = factorAnalysisLikelihood.getDataDimension(); this.dimFactors = factorAnalysisLikelihood.getNumberOfFactors(); this.data = factorAnalysisLikelihood.getParameter(); this.missing = getMissing(factorAnalysisLikelihood.getMissingDataIndices(), data.getDimension()); List<Likelihood> likelihoodList = new ArrayList<Likelihood>(); likelihoodList.add(treeDataLikelihood); likelihoodList.add(factorAnalysisLikelihood); this.likelihood = new CompoundLikelihood(likelihoodList); if (SMART_POOL) { this.threadCount = 0; setupParallelServices(tree.getExternalNodeCount(), threadCount); } } private boolean[] getMissing(List<Integer> missingIndices, int length) { boolean[] missing = new boolean[length]; for (int i : missingIndices) { missing[i] = true; } return missing; } @Override public Likelihood getLikelihood() { return likelihood; } @Override public Parameter getParameter() { return factorAnalysisLikelihood.getLoadings(); } @Override public int getDimension() { return dimFactors * dimTrait; } private ReadableMatrix shiftToSecondMoment(WrappedMatrix variance, ReadableVector mean) { assert(variance.getMajorDim() == variance.getMinorDim()); assert(variance.getMajorDim()== mean.getDim()); final int dim = variance.getMajorDim(); for (int i = 0; i < dim; ++i) { for (int j = 0; j < dim; ++j) { variance.set(i,j, variance.get(i,j) + mean.get(i) * mean.get(j)); } } return variance; } private WrappedNormalSufficientStatistics getWeightedAverage(ReadableVector m1, ReadableMatrix p1, ReadableVector m2, ReadableMatrix p2) { assert (m1.getDim() == m2.getDim()); assert (p1.getDim() == p2.getDim()); assert (m1.getDim() == p1.getMinorDim()); assert (m1.getDim() == p1.getMajorDim()); final WrappedVector m12 = new WrappedVector.Raw(new double[m1.getDim()], 0, dimFactors); final DenseMatrix64F p12 = new DenseMatrix64F(dimFactors, dimFactors); final DenseMatrix64F v12 = new DenseMatrix64F(dimFactors, dimFactors); final WrappedMatrix wP12 = new WrappedMatrix.WrappedDenseMatrix(p12); final WrappedMatrix wV12 = new WrappedMatrix.WrappedDenseMatrix(v12); MissingOps.add(p1, p2, wP12); safeInvert(p12, v12, false); weightedAverage(m1, p1, m2, p2, m12, wV12, dimFactors); return new WrappedNormalSufficientStatistics(m12, wP12, wV12); } @Override public double[] getGradientLogDensity() { final double[] gradient = new double[getDimension()]; ReadableVector gamma = new WrappedVector.Parameter(factorAnalysisLikelihood.getPrecision()); ReadableMatrix loadings = ReadableMatrix.Utils.transposeProxy( new WrappedMatrix.MatrixParameter(factorAnalysisLikelihood.getLoadings())); if (DEBUG) { System.err.println("G : " + gamma); System.err.println("L : " + loadings); } assert (gamma.getDim() == dimTrait); assert (loadings.getMajorDim() == dimFactors); assert (loadings.getMinorDim() == dimTrait); // [E(F) Y^t - E(FF^t)L]\Gamma // E(FF^t) = V(F) + E(F)E(F)^t // Y: N x P // F: N x K // L: K x P // (K x N)(N x P)(P x P) - (K x N)(N x K)(K x P)(P x P) // sum_{N} (K x 1)(1 x P)(P x P) - (K x K)(K x P)(P x P) final List<WrappedNormalSufficientStatistics> allStatistics = fullConditionalDensity.getTrait(tree, null); assert (allStatistics.size() == tree.getExternalNodeCount()); List<Callable<Object>> calls = new ArrayList<Callable<Object>>(); if (pool == null) { for (int taxon = 0; taxon < tree.getExternalNodeCount(); ++taxon) { computeGradientForOneTaxon(taxon, loadings, gamma, gradient); } } else { if (SMART_POOL) { for (final IntegratedLoadingsGradient.TaskIndices indices : taskIndices) { calls.add(Executors.callable( new Runnable() { @Override public void run() { for (int taxon = indices.start; taxon < indices.stop; ++taxon) { computeGradientForOneTaxon(taxon, loadings, gamma, gradient); } } } )); } } else { for (int taxon = 0; taxon < tree.getExternalNodeCount(); ++taxon) { final int t = taxon; calls.add(Executors.callable( new Runnable() { @Override public void run() { computeGradientForOneTaxon(t, loadings, gamma, gradient); } } )); } } try { pool.invokeAll(calls); } catch (InterruptedException exception) { exception.printStackTrace(); } } return gradient; } private void computeGradientForOneTaxon(final int taxon, final ReadableMatrix loadings, final ReadableVector gamma, // final WrappedNormalSufficientStatistics statistic, final double[] gradient) { final WrappedVector y = getTipData(taxon); final WrappedNormalSufficientStatistics dataKernel = getTipKernel(taxon); final ReadableVector meanKernel = dataKernel.getMean(); final ReadableMatrix precisionKernel = dataKernel.getPrecision(); if (DEBUG) { System.err.println("Y " + taxon + " : " + y); System.err.println("YM" + taxon + " : " + meanKernel); System.err.println("YP" + taxon + " : " + precisionKernel); } final List<WrappedNormalSufficientStatistics> statistics = fullConditionalDensity.getTrait(tree, tree.getExternalNode(taxon)); for (WrappedNormalSufficientStatistics statistic : statistics) { final ReadableVector meanFactor = statistic.getMean(); final WrappedMatrix precisionFactor = statistic.getPrecision(); final WrappedMatrix varianceFactor = statistic.getVariance(); if (DEBUG) { System.err.println("FM" + taxon + " : " + meanFactor); System.err.println("FP" + taxon + " : " + precisionFactor); System.err.println("FV" + taxon + " : " + varianceFactor); } final WrappedNormalSufficientStatistics convolution = getWeightedAverage( meanFactor, precisionFactor, meanKernel, precisionKernel); final ReadableVector mean = convolution.getMean(); final ReadableMatrix precision = convolution.getPrecision(); final WrappedMatrix variance = convolution.getVariance(); if (DEBUG) { System.err.println("CM" + taxon + " : " + mean); System.err.println("CP" + taxon + " : " + precision); System.err.println("CV" + taxon + " : " + variance); } final ReadableMatrix secondMoment = shiftToSecondMoment(variance, mean); final ReadableMatrix product = ReadableMatrix.Utils.productProxy( secondMoment, loadings ); if (DEBUG) { System.err.println("S" + taxon + " : " + secondMoment); System.err.println("P" + taxon + " : " + product); } for (int factor = 0; factor < dimFactors; ++factor) { for (int trait = 0; trait < dimTrait; ++trait) { if (!missing[taxon * dimTrait + trait]) { gradient[factor * dimTrait + trait] += (mean.get(factor) * y.get(trait) - product.get(factor, trait)) * gamma.get(trait); } } } } } @Override public String getReport() { return getReport(getGradientLogDensity()); } private WrappedVector getTipData(int taxonIndex) { return new WrappedVector.Parameter(data, taxonIndex * dimTrait, dimTrait); } private WrappedNormalSufficientStatistics getTipKernel(int taxonIndex) { double[] buffer = factorAnalysisLikelihood.getTipPartial(taxonIndex, false); return new WrappedNormalSufficientStatistics(buffer, 0, dimFactors, null, PrecisionType.FULL); } private MultivariateFunction numeric = new MultivariateFunction() { @Override public double evaluate(double[] argument) { for (int i = 0; i < argument.length; ++i) { factorAnalysisLikelihood.getLoadings().setParameterValue(i, argument[i]); } treeDataLikelihood.makeDirty(); factorAnalysisLikelihood.makeDirty(); return treeDataLikelihood.getLogLikelihood() + factorAnalysisLikelihood.getLogLikelihood(); } @Override public int getNumArguments() { return factorAnalysisLikelihood.getLoadings().getDimension(); } @Override public double getLowerBound(int n) { return Double.NEGATIVE_INFINITY; } @Override public double getUpperBound(int n) { return Double.POSITIVE_INFINITY; } }; private String getReport(double[] gradient) { String result = new WrappedVector.Raw(gradient).toString(); if (NUMERICAL_CHECK) { Parameter loadings = factorAnalysisLikelihood.getLoadings(); double[] savedValues = loadings.getParameterValues(); double[] testGradient = NumericalDerivative.gradient(numeric, loadings.getParameterValues()); for (int i = 0; i < savedValues.length; ++i) { loadings.setParameterValue(i, savedValues[i]); } result += "\nNumerical estimate: \n" + new WrappedVector.Raw(testGradient) + " @ " + new WrappedVector.Raw(loadings.getParameterValues()) + "\n"; } return result; } private static final boolean DEBUG = false; private static final boolean NUMERICAL_CHECK = true; private static final String PARSER_NAME = "integratedFactorAnalysisLoadingsGradient"; public static AbstractXMLObjectParser PARSER = new AbstractXMLObjectParser() { @Override public Object parseXMLObject(XMLObject xo) throws XMLParseException { TreeDataLikelihood treeDataLikelihood = (TreeDataLikelihood) xo.getChild(TreeDataLikelihood.class); IntegratedFactorAnalysisLikelihood factorAnalysis = (IntegratedFactorAnalysisLikelihood) xo.getChild(IntegratedFactorAnalysisLikelihood.class); DataLikelihoodDelegate likelihoodDelegate = treeDataLikelihood.getDataLikelihoodDelegate(); if (!(likelihoodDelegate instanceof ContinuousDataLikelihoodDelegate)) { throw new XMLParseException("TODO"); } ContinuousDataLikelihoodDelegate continuousDataLikelihoodDelegate = (ContinuousDataLikelihoodDelegate) likelihoodDelegate; // TODO Check dimensions, parameters, etc. return new IntegratedLoadingsGradient( treeDataLikelihood, continuousDataLikelihoodDelegate, factorAnalysis); } @Override public XMLSyntaxRule[] getSyntaxRules() { return rules; } @Override public String getParserDescription() { return "Generates a gradient provider for the loadings matrix when factors are integrated out"; } @Override public Class getReturnType() { return IntegratedLoadingsGradient.class; } @Override public String getParserName() { return PARSER_NAME; } private final XMLSyntaxRule[] rules = new XMLSyntaxRule[] { new ElementRule(IntegratedFactorAnalysisLikelihood.class), new ElementRule(TreeDataLikelihood.class), }; }; private void setupParallelServices(int taxonCount, int threadCount) { if (threadCount > 0) { pool = Executors.newFixedThreadPool(threadCount); } else if (threadCount < 0) { pool = Executors.newCachedThreadPool(); } else { pool = null; } taskIndices = (pool != null) ? setupTasks(taxonCount, threadCount) : null; } private List<IntegratedLoadingsGradient.TaskIndices> setupTasks(int taxonCount, int threadCount) { List<IntegratedLoadingsGradient.TaskIndices> tasks = new ArrayList<IntegratedLoadingsGradient.TaskIndices>(threadCount); int length = taxonCount / threadCount; if (taxonCount % threadCount != 0) ++length; int start = 0; for (int task = 0; task < threadCount && start < taxonCount; ++task) { tasks.add(new IntegratedLoadingsGradient.TaskIndices(start, Math.min(start + length, taxonCount))); start += length; } return tasks; } private class TaskIndices { int start; int stop; TaskIndices(int start, int stop) { this.start = start; this.stop = stop; } public String toString() { return start + " " + stop; } } private ExecutorService pool = null; private List<IntegratedLoadingsGradient.TaskIndices> taskIndices = null; }
package com.sri.ai.test.praise; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Before; import com.sri.ai.brewer.BrewerConfiguration; import com.sri.ai.brewer.api.Grammar; import com.sri.ai.brewer.api.Parser; import com.sri.ai.expresso.api.Expression; import com.sri.ai.expresso.core.DefaultSymbol; import com.sri.ai.expresso.helper.Expressions; import com.sri.ai.grinder.GrinderConfiguration; import com.sri.ai.grinder.api.RewritingProcess; import com.sri.ai.grinder.helper.GrinderUtil; import com.sri.ai.grinder.helper.Justification; import com.sri.ai.grinder.helper.Trace; import com.sri.ai.grinder.parser.antlr.AntlrGrinderParserWrapper; import com.sri.ai.grinder.ui.TreeUtil; import com.sri.ai.praise.LPIGrammar; import com.sri.ai.praise.lbp.LBPFactory; import com.sri.ai.praise.model.Model; import com.sri.ai.util.Configuration; import com.sri.ai.util.concurrent.BranchAndMerge; public abstract class AbstractLPITest { private Grammar grammar; private Parser parser; public AbstractLPITest() { super(); } @Before public void setUp() { TreeUtil.flushData(); Configuration.clear(); DefaultSymbol.flushGlobalSymbolTable(); BranchAndMerge.reset(); grammar = makeGrammar(); // Ensure the grammar class passed in is used where necessary. BrewerConfiguration.setProperty(BrewerConfiguration.KEY_DEFAULT_GRAMMAR_CLASS, grammar.getClass().getName()); parser = makeParser(); } public void tearDown() { parser.close(); Configuration.clear(); } public Grammar makeGrammar() { return new LPIGrammar(); } public Parser makeParser() { return new AntlrGrinderParserWrapper(); } public RewritingProcess newRewritingProcess(Expression rootExpression) { return LBPFactory.newLBPProcess(rootExpression); } // PROTECTED METHODS protected void perform(TestData[] tests) { String assertFailed = null; int run = 0; for (int i = 0; i < tests.length; i++) { String errorMessage = tests[i].perform(i); if (errorMessage != null) { if (GrinderConfiguration.isWaitUntilUIClosedEnabled()) { assertFailed = errorMessage; System.err.println(assertFailed); break; } else { fail(errorMessage); } } run++; } if (!GrinderConfiguration.isWaitUntilUIClosedEnabled()) { assertEquals("Ensure you run all the tests", tests.length, run); } doTreeUtilWaitUnilClosed(); if (assertFailed != null) { fail(assertFailed); } } protected void doTreeUtilWaitUnilClosed() { if (GrinderConfiguration.isWaitUntilUIClosedEnabled()) { TreeUtil.waitUntilUIClosed(); } } protected Expression parse(String expressionString) { return parser.parse(expressionString); } // INNER CLASSES protected abstract class TestData { public boolean isIllegalArgumentTest; public String expected; public String contextualConstraint; public Model model; public TestData(boolean isIllegalArgumentTest, String expected) { this.isIllegalArgumentTest = isIllegalArgumentTest; this.expected = expected; } public TestData(String contextualConstraint, Model model, boolean isIllegalArgumentTest, String expected) { this(isIllegalArgumentTest, expected); this.contextualConstraint = contextualConstraint; this.model = model; } /** Performs i-th test of a batch, indicating an error message in case of failure, or null. */ public String perform(int i) { Expression topExpression; RewritingProcess process; Expression actual = null; topExpression = getTopExpression(); process = newRewritingProcess(topExpression); Expression context = parse(contextualConstraint); if ( ! context.equals(Expressions.TRUE)) { process = GrinderUtil.extendContextualConstraint(context, process); } if (null != model) { Expression modelExpression = parse(model.getModelDeclaration()); Model.setRewritingProcessesModel(modelExpression, model.getKnownRandomVariableNames(), process); } Expression expectedExpression = parse(expected); if (isIllegalArgumentTest) { try { actual = callRewrite(process); fail("tests[i]=" + i + ", " + topExpression + " should have thrown an IllegalArgumentException."); } catch (IllegalArgumentException iae) { // ok this is expected Trace.setTraceLevel(1); Trace.log("-R_: expected IllegalArgumentException thrown:"+iae.getMessage()); Trace.setTraceLevel(0); Justification.setJustificationLevel(1); Justification.getDefaultLogX().trace("-J_: expected IllegalArgumentException thrown:"+iae.getMessage()); Justification.setJustificationLevel(0); } } else { long startTime = System.currentTimeMillis(); Throwable thrown = null; try { actual = callRewrite(process); } catch (Throwable t) { thrown = t; } long rewroteIn = System.currentTimeMillis()-startTime; System.out.println("tests["+ i +" rewrote in "+(rewroteIn)+"ms]:" + topExpression + "\n--->\n" + actual); // Ensure all notifications and cache output are noted if configured that way. process.notifyEndOfRewritingProcess(); if (thrown != null) { String errorMessage = "ERROR tests[" + i + "] = " + topExpression + "\nexpected: " + expectedExpression // better to show expectedExpression than expression, because parsing errors will be more clear + "\n but an unhandled throwable exception was thrown instead: " + thrown.getMessage(); System.out.println(errorMessage); thrown.printStackTrace(); return errorMessage; // indicates that we need to break test loop } else if (!expectedExpression.equals(actual)) { String errorMessage = "ERROR tests[" + i + "] = " + topExpression + "\nexpected: " + expectedExpression // better to show expectedExpression than expression, because parsing errors will be more clear + "\n but was: " + actual; System.out.println(errorMessage); return errorMessage; // indicates that we need to break test loop } } return null; // indicates that we can proceed with testing } public abstract Expression getTopExpression(); public abstract Expression callRewrite(RewritingProcess process); } }
package com.mamewo.malarm24; /** * @author Takashi Masuyama <mamewotoko@gmail.com> */ import android.app.Activity; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.Dialog; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.media.AudioManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.os.Vibrator; import android.preference.PreferenceManager; import android.speech.RecognizerIntent; import android.util.Log; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.View.OnLongClickListener; import android.view.View.OnTouchListener; import android.view.inputmethod.InputMethodManager; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.SlidingDrawer; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.Serializable; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.support.v7.app.ActionBar; import android.support.v7.widget.SwitchCompat; final public class MalarmActivity extends AppCompatActivity implements OnClickListener, OnSharedPreferenceChangeListener, OnLongClickListener, OnKeyListener, ServiceConnection, MalarmPlayerService.PlayerStateListener { final static public String PACKAGE_NAME = MalarmActivity.class.getPackage().getName(); final static public String LOADWEB_ACTION = PACKAGE_NAME + ".LOADWEB_ACTION"; final static public String PLAY_ACTION = PACKAGE_NAME + ".PLAY_ACTION"; final static private String TAG = "malarm"; final static private int SPEECH_RECOGNITION_REQUEST_CODE = 2121; final static private String NATIVE_PLAYER_KEY = "nativeplayer"; final static private Pattern TIME_PATTERN = Pattern.compile("(\\d+)((\\d+)|)?"); final static private Pattern AFTER_TIME_PATTERN = Pattern.compile("((\\d+))?((\\d+)|)?.*"); final static private int DIALOG_PLAY_SLEEP_TUNE = 1; protected static String prefPlaylistPath; private static List<String> WEB_PAGE_LIST = new ArrayList<String>(); private static boolean prefUseNativePlayer; private static Integer prefDefaultHour; private static Integer prefDefaultMin; private static MalarmState state_; private ImageButton speechButton_; private ImageButton previousButton_; private ImageButton nextButton_; private ImageButton playButton_; private TimePicker timePicker_; private TextView timeLabel_; private WebView webview_; private SwitchCompat alarmButton_; private Button setNowButton_; private GestureDetector gd_; private Intent speechIntent_; private ProgressBar loadingIcon_; private boolean runningSpeechActivity_; // private TextView playlistLabel_; //private TextView sleepTimeLabel_; private MalarmPlayerService player_ = null; private SharedPreferences pref_; private static final int DOW_INDEX[] = { Calendar.SUNDAY, Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY, }; final public static class MalarmState implements Serializable { private static final long serialVersionUID = 1L; public Calendar targetTime_; public int webIndex_; public int sleepMin_; public MalarmState() { webIndex_ = 0; targetTime_ = null; sleepMin_ = 0; } } private class WebViewDblTapListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onDoubleTap(MotionEvent e) { int x = (int) e.getX(); int y = (int) e.getY(); Log.d(TAG, "onDoubleTap: " + x + ", " + y); int width = webview_.getWidth(); boolean start_browser = false; int side_width = width / 3; if (x <= side_width) { state_.webIndex_ } else if (x > width - side_width) { state_.webIndex_++; } else { start_browser = true; } if (start_browser) { String url = webview_.getUrl(); if (null == url) { return false; } Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(i); } else { loadWebPage(); } return true; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PreferenceManager.setDefaultValues(this, R.xml.preference, false); //dynamic pref_ = PreferenceManager.getDefaultSharedPreferences(this); if(null == pref_.getString(MalarmPreference.PREFKEY_URL_LIST_FILE, null)){ File defaultSitePath = new File(getExternalFilesDir(null), "urllist.txt"); Log.d(TAG, "urllist.txt path: " + defaultSitePath.getAbsolutePath()); pref_.edit() .putString(MalarmPreference.PREFKEY_URL_LIST_FILE, defaultSitePath.getAbsolutePath()) .apply(); } pref_.registerOnSharedPreferenceChangeListener(this); syncPreferences(pref_, "ALL"); if (pref_.getBoolean("pref_use_drawable_ui", false)) { setContentView(R.layout.main_drawing); } else { setContentView(R.layout.main); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); Log.d(TAG, "toolbar: "+toolbar); setSupportActionBar(toolbar); ActionBar actionbar = getSupportActionBar(); actionbar.setDisplayShowTitleEnabled(false); Intent intent = new Intent(this, MalarmPlayerService.class); startService(intent); //TODO: handle failure of bindService boolean result = bindService(intent, this, Context.BIND_AUTO_CREATE); Log.d(TAG, "bindService: " + result); timePicker_ = (TimePicker) findViewById(R.id.timePicker1); timePicker_.setIs24HourView(true); if (null == savedInstanceState) { state_ = new MalarmState(); } else { state_ = (MalarmState) savedInstanceState.get("state"); } loadingIcon_ = (ProgressBar) findViewById(R.id.loading_icon); loadingIcon_.setOnLongClickListener(this); // playlistLabel_ = (TextView) findViewById(R.id.playlist_name_view); // playlistLabel_.setOnLongClickListener(this); speechButton_ = (ImageButton) findViewById(R.id.set_by_voice); speechButton_.setOnClickListener(this); runningSpeechActivity_ = false; previousButton_ = (ImageButton) findViewById(R.id.previous_button); previousButton_.setOnClickListener(this); previousButton_.setOnLongClickListener(this); playButton_ = (ImageButton) findViewById(R.id.play_button); playButton_.setOnClickListener(this); playButton_.setOnLongClickListener(this); nextButton_ = (ImageButton) findViewById(R.id.next_button); nextButton_.setOnClickListener(this); nextButton_.setOnLongClickListener(this); setNowButton_ = (Button) findViewById(R.id.set_now_button); setNowButton_.setOnClickListener(this); timeLabel_ = (TextView) findViewById(R.id.target_time_label); //sleepTimeLabel_ = (TextView) findViewById(R.id.sleep_time_label); webview_ = (WebView) findViewById(R.id.webView1); alarmButton_ = (SwitchCompat) findViewById(R.id.alarm_button); alarmButton_.setOnClickListener(this); alarmButton_.setLongClickable(true); alarmButton_.setOnLongClickListener(this); //umm... alarmButton_.setOnKeyListener(this); CookieSyncManager.createInstance(this); //umm... webview_.setOnKeyListener(this); WebSettings webSettings = webview_.getSettings(); //to display twitter... webSettings.setDomStorageEnabled(true); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(true); webview_.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { webview_.requestFocus(); gd_.onTouchEvent(event); return false; } }); final Activity activity = this; webview_.setWebChromeClient(new WebChromeClient()); webview_.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { loadingIcon_.setVisibility(View.VISIBLE); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show(); } @Override public void onLoadResource(WebView view, String url) { //addhoc polling... //TODO: move to resource //TODO: automate scrolling in adaptive way } @Override public void onPageFinished(WebView view, String url) { loadingIcon_.setVisibility(View.INVISIBLE); if (url.contains("weather.yahoo")) { view.scrollTo(0, 180); } } }); gd_ = new GestureDetector(this, new WebViewDblTapListener()); } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); if (!player_.isPlaying()) { Intent intent = new Intent(this, MalarmPlayerService.class); stopService(intent); } unbindService(this); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); pref.unregisterOnSharedPreferenceChangeListener(this); super.onDestroy(); } @Override protected void onResume() { super.onResume(); alarmButton_.requestFocus(); //WebView.onResume is hidden, why!?!? webview_.getSettings().setJavaScriptEnabled(true); CookieSyncManager.getInstance().startSync(); loadWebPage(); updateUI(); runningSpeechActivity_ = false; } @Override protected void onPause() { super.onPause(); //stop tokei webview_.getSettings().setJavaScriptEnabled(false); webview_.stopLoading(); CookieSyncManager.getInstance().stopSync(); } @Override protected void onStart() { super.onStart(); Intent i = getIntent(); Log.d(TAG, "onStart: " + i.getAction()); if (MalarmPlayerService.WAKEUP_ACTION.equals(i.getAction()) && pref_.getBoolean("pref_use_drawable_ui", false) && pref_.getBoolean("pref_open_drawable", false)) { SlidingDrawer drawer = (SlidingDrawer) findViewById(R.id.slidingDrawer1); Log.d(TAG, "drawer open"); drawer.open(); i.setAction("android.intent.action.MAIN"); } } @Override protected void onStop() { super.onStop(); } //Avoid finishing activity not to lost _state @Override public void onBackPressed() { if (webview_.canGoBack() && webview_.hasFocus()) { webview_.goBack(); return; } //this activity is not quit by back button //to quit, state of timer should be saved and restored moveTaskToBack(false); } @Override protected void onSaveInstanceState(Bundle outState) { Log.d("malarm", "onSaveInstanceState is called"); outState.putSerializable("state", state_); } private void addURLListFromPref(SharedPreferences pref) { String liststr = pref.getString(MalarmPreference.PREFKEY_URL_LIST, MalarmPreference.DEFAULT_WEB_LIST); String[] tmpURLlist = liststr.split(MultiListPreference.SEPARATOR); for (String url : tmpURLlist) { WEB_PAGE_LIST.add(url); } } //escape preference value into static value //TODO: improve design public void syncPreferences(SharedPreferences pref, String key) { boolean updateAll = "ALL".equals(key); if (updateAll || "default_time".equals(key)) { String timestr = pref.getString(MalarmPreference.PREFKEY_WAKEUP_TIME, MalarmPreference.DEFAULT_WAKEUP_TIME); String[] split_timestr = timestr.split(":"); if (split_timestr.length == 2) { prefDefaultHour = Integer.valueOf(split_timestr[0]); prefDefaultMin = Integer.valueOf(split_timestr[1]); } } if (updateAll || "url_list".equals(key)) { WEB_PAGE_LIST.clear(); //XXX .... get custom urllist String customURLPath = pref_.getString(MalarmPreference.PREFKEY_URL_LIST_FILE, null); File path = null; if(null != customURLPath){ path = new File(customURLPath); } if (null != path && path.exists()){ FileInputStream fis = null; BufferedReader br = null; try { fis = new FileInputStream(path.getAbsolutePath()); br = new BufferedReader(new InputStreamReader(fis)); String line; while (null != (line = br.readLine())) { if (line.startsWith(" continue; } String[] titleURL = line.split("\t"); if (titleURL.length != 2) { continue; } String url = titleURL[1]; WEB_PAGE_LIST.add(url); } } catch (IOException e) { addURLListFromPref(pref); } finally { if (null != br) { try { br.close(); } catch (IOException e) { } } if (null != fis) { try { fis.close(); } catch (IOException e) { } } } } else { addURLListFromPref(pref); } } if (updateAll || "use_native_player".equals(key)) { prefUseNativePlayer = pref.getBoolean(MalarmPreference.PREFKEY_USE_NATIVE_PLAYER, false); } if (updateAll || "playlist_path".equals(key)) { String newpath = pref.getString(key, MalarmPreference.DEFAULT_PLAYLIST_PATH.getAbsolutePath()); if (!newpath.equals(prefPlaylistPath)) { prefPlaylistPath = newpath; if (null != player_) { player_.loadPlaylist(); } } } Log.d(TAG, "syncPref: key " + key); if ("clear_webview_cache".equals(key)) { webview_.clearCache(true); webview_.clearHistory(); webview_.clearFormData(); CookieManager mgr = CookieManager.getInstance(); mgr.removeAllCookie(); showMessage(this, getString(R.string.webview_cache_cleared)); } } @Override public void onSharedPreferenceChanged(SharedPreferences pref, String key) { syncPreferences(pref, key); } private void loadWebPage() { if (state_.webIndex_ < 0) { state_.webIndex_ = WEB_PAGE_LIST.size() - 1; } if (state_.webIndex_ >= WEB_PAGE_LIST.size()) { state_.webIndex_ = 0; } String url = WEB_PAGE_LIST.get(state_.webIndex_); loadWebPage(url); } //TODO: move to resource private void adjustWebviewSetting(String url) { WebSettings config = webview_.getSettings(); if (url.contains("bijo-linux") || url.contains("google") || url.contains("yahoo") || url.contains("so-net")) { config.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); } else { config.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); } if (url.contains("bijo-linux") || url.contains("bijin-tokei")) { config.setDefaultZoom(WebSettings.ZoomDensity.FAR); } else { config.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM); } } private void loadWebPage(String url) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); boolean prefWifiOnly = pref.getBoolean(MalarmPreference.PREFKEY_WIFI_ONLY, false); if (prefWifiOnly) { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeInfo = connMgr.getActiveNetworkInfo(); //TODO: check scheme is file:// or not if (activeInfo != null && activeInfo.getType() != ConnectivityManager.TYPE_WIFI && !url.startsWith("file:")) { //TODO: translate showMessage(this, "Wi-Fi is not available: " + url); return; } } showMessage(this, "Loading... \n" + url); adjustWebviewSetting(url); webview_.loadUrl(url); } /** * call updateUI from caller */ private void cancelAlarmTimer() { if (null == state_.targetTime_) { return; } PendingIntent p = makePlayPintent(MalarmPlayerService.WAKEUP_ACTION, false); AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mgr.cancel(p); state_.targetTime_ = null; } /** * call updateUI from caller */ private void cancelSleepTimer() { if (state_.sleepMin_ == 0) { return; } PendingIntent sleep = makePlayPintent(MalarmPlayerService.SLEEP_ACTION, false); AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mgr.cancel(sleep); state_.sleepMin_ = 0; } //onResume is called after this method is called //TODO: call setNewIntent and handle in onResume? //TODO: this method is not called until home button is pressed @Override protected void onNewIntent(Intent intent) { String action = intent.getAction(); Log.d(TAG, "onNewIntent is called: " + action); if (null == action) { return; } //TODO: modify action name if (MalarmPlayerService.WAKEUP_ACTION.equals(action)) { //native player cannot start until lock screen is displayed if (state_.sleepMin_ > 0) { state_.sleepMin_ = 0; } //TODO: use values.xxxx as default value if (pref_.getBoolean("pref_reset_url_index", true)) { state_.webIndex_ = 0; } setIntent(intent); } else if (LOADWEB_ACTION.equals(action)) { String url = intent.getStringExtra("url"); loadWebPage(url); } else if (PLAY_ACTION.equals(action)) { //sleep | wakeup String playlist = intent.getStringExtra("playlist"); int pos = intent.getIntExtra("position", 0); Playlist list; if (null == playlist || "wakeup".equals(playlist)) { list = MalarmPlayerService.wakeupPlaylist_; } else { list = MalarmPlayerService.sleepPlaylist_; } player_.playMusic(list, pos, null == state_.targetTime_); } } //TODO: design private PendingIntent makePlayPintent(String action, boolean useNative) { Intent i = new Intent(this, MalarmPlayerService.Receiver.class); i.setAction(action); i.putExtra(NATIVE_PLAYER_KEY, useNative); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); return pendingIntent; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.alarm_menu, menu); return true; } private String dateStr(Calendar target) { String dow_str = ""; int dow_int = target.get(Calendar.DAY_OF_WEEK); String[] dow_name_table = getResources().getStringArray(R.array.day_of_week); for (int i = 0; i < DOW_INDEX.length; i++) { if (DOW_INDEX[i] == dow_int) { dow_str = dow_name_table[i]; break; } } return String.format("%2d/%2d %02d:%02d (%s)", target.get(Calendar.MONTH) + 1, target.get(Calendar.DATE), target.get(Calendar.HOUR_OF_DAY), target.get(Calendar.MINUTE), dow_str); } private void updatePlayStopButton(){ if(player_ == null){ return; } if(player_.isPlaying()){ playButton_.setImageResource(android.R.drawable.ic_media_pause); playButton_.setContentDescription(getString(R.string.pause_button_desc)); } else { playButton_.setImageResource(android.R.drawable.ic_media_play); playButton_.setContentDescription(getString(R.string.play_button_desc)); } } private void updateUI() { Calendar target = state_.targetTime_; if (null != target) { timeLabel_.setText(dateStr(target)); timePicker_.setCurrentHour(target.get(Calendar.HOUR_OF_DAY)); timePicker_.setCurrentMinute(target.get(Calendar.MINUTE)); } else { //alarm is not set timeLabel_.setText(""); if (!runningSpeechActivity_) { timePicker_.setCurrentHour(prefDefaultHour); timePicker_.setCurrentMinute(prefDefaultMin); } } updatePlayStopButton(); // int sleepMin = state_.sleepMin_; // if (sleepMin > 0) { // sleepTimeLabel_.setText(MessageFormat.format(getString(R.string.unit_min), // Integer.valueOf(sleepMin))); // else { // sleepTimeLabel_.setText(""); alarmButton_.setChecked(null != state_.targetTime_); //following two buttons can be hidden speechButton_.setEnabled(null == state_.targetTime_); setNowButton_.setEnabled(null == state_.targetTime_); timePicker_.setEnabled(null == state_.targetTime_); //TODO: add function to get player state //playlistLabel_.setText(Player.getCurrentPlaylistName()); } private void stopAlarm() { // NotificationManager mgr = // (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // mgr.cancel(PACKAGE_NAME, 0); player_.clearNotification(); cancelSleepTimer(); cancelAlarmTimer(); updateUI(); player_.stopVibrator(); if (!prefUseNativePlayer) { player_.stopMusic(); showMessage(this, getString(R.string.music_stopped)); } } private void setSleepTimer() { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); long nowMillis = System.currentTimeMillis(); long target = 0; if (state_.targetTime_ != null) { target = state_.targetTime_.getTimeInMillis(); } String minStr = pref.getString(MalarmPreference.PREFKEY_SLEEP_TIME, MalarmPreference.DEFAULT_SLEEPTIME); int min = Integer.valueOf(minStr); long sleepTimeMillis = min * 60 * 1000; state_.sleepMin_ = min; if (target == 0 || target - nowMillis >= sleepTimeMillis) { PendingIntent sleepIntent = makePlayPintent(MalarmPlayerService.SLEEP_ACTION, prefUseNativePlayer); AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC_WAKEUP, nowMillis + sleepTimeMillis, sleepIntent); updateUI(); } } private void playSleepMusic(long targetMillis) { if (player_.isPlaying()) { player_.stopMusic(); } Playlist list = MalarmPlayerService.sleepPlaylist_; Log.d(TAG, "playSleepMusic sleepPlaylist:" + list); if (null == list) { showMessage(this, getString(R.string.sleep_playlist_not_exist)); return; } int sleepVolume = Integer.valueOf(pref_.getString(MalarmPreference.PREFKEY_SLEEP_VOLUME, MalarmPreference.DEFAULT_SLEEP_VOLUME)); AudioManager mgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mgr.setStreamVolume(AudioManager.STREAM_MUSIC, sleepVolume, AudioManager.FLAG_SHOW_UI); player_.playMusic(list, null == state_.targetTime_); setSleepTimer(); } /** * @return target time in epoch time (miliseconds) */ private void setAlarm() { //set timer Calendar now = new GregorianCalendar(); //remove focus from timeticker to save time which is entered by software keyboard timePicker_.clearFocus(); int target_hour = timePicker_.getCurrentHour().intValue(); int target_min = timePicker_.getCurrentMinute().intValue(); Calendar target = new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DATE), target_hour, target_min, 0); long targetMillis = target.getTimeInMillis(); long nowMillis = System.currentTimeMillis(); if (targetMillis <= nowMillis) { //tomorrow targetMillis += 24 * 60 * 60 * 1000; target.setTimeInMillis(targetMillis); } state_.targetTime_ = target; AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); PendingIntent pendingIntent = makePlayPintent(MalarmPlayerService.WAKEUP_ACTION, false); mgr.set(AlarmManager.RTC_WAKEUP, targetMillis, pendingIntent); String title = getString(R.string.notify_waiting_title); title += " " + dateStr(target); player_.showNotification(title, ""); } public void setNow() { if (timePicker_.isEnabled()) { Calendar now = new GregorianCalendar(); timePicker_.setCurrentHour(now.get(Calendar.HOUR_OF_DAY)); timePicker_.setCurrentMinute(now.get(Calendar.MINUTE)); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.stop_vibration: boolean vibrating = player_.isVibrating(); //execute always player_.stopVibrator(); if(vibrating){ showMessage(this, getString(R.string.notify_wakeup_text)); } break; case R.id.pref: //TODO: use startActivityForResult startActivity(new Intent(this, MalarmPreference.class)); break; default: Log.d(TAG, "Unknown menu"); return false; } return true; } @Override public void onClick(View v) { if(v == previousButton_){ player_.playPrevious(); } else if (v == nextButton_) { player_.playNext(); } else if (v == playButton_) { //TODO: set playilst? Log.d(TAG, "playButton_ of main screen"); if(player_.isPlaying()){ player_.pauseMusic(); } else { player_.playMusic(true); } //update ui will called in async way } else if (v == speechButton_) { setTimeBySpeech(); } else if (v == alarmButton_) { InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); mgr.hideSoftInputFromWindow(timePicker_.getWindowToken(), 0); if (state_.targetTime_ != null) { Log.d(TAG, "Stop Alarm"); stopAlarm(); } else { Log.d(TAG, "Set Alarm"); setAlarm(); playSleepMusic(state_.targetTime_.getTimeInMillis()); updateUI(); } } else if (v == setNowButton_) { setNow(); } } @Override public boolean onKey(View view, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP) { boolean handled = false; if ((KeyEvent.KEYCODE_0 <= keyCode) && (keyCode <= KeyEvent.KEYCODE_9)) { state_.webIndex_ = (keyCode - KeyEvent.KEYCODE_0) % WEB_PAGE_LIST.size(); loadWebPage(); handled = true; } return handled; } return false; } private void setTimeBySpeech() { if (!timePicker_.isEnabled() || runningSpeechActivity_) { return; } if (null == speechIntent_) { //to reduce task of onCreate method showMessage(this, getString(R.string.init_voice)); PackageManager pm = getPackageManager(); List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); if (activities.isEmpty()) { return; } speechIntent_ = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); speechIntent_.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); speechIntent_.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.voice_dialog)); } runningSpeechActivity_ = true; webview_.stopLoading(); startActivityForResult(speechIntent_, SPEECH_RECOGNITION_REQUEST_CODE); } static public void showMessage(Context c, String message) { Toast.makeText(c, message, Toast.LENGTH_LONG).show(); } private void shortVibrate() { Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); if (vibrator != null) { vibrator.vibrate(150); } } @Override public boolean onLongClick(View view) { if (view == loadingIcon_) { shortVibrate(); webview_.stopLoading(); showMessage(this, getString(R.string.stop_loading)); return true; } if (view == alarmButton_) { if (alarmButton_.isChecked()) { return false; } shortVibrate(); setAlarm(); //TODO: use new method to display dialog showDialog(DIALOG_PLAY_SLEEP_TUNE); return true; } if (view == playButton_) { shortVibrate(); if (!player_.isPlaying()) { Log.d(TAG, "onLongClick: playMusic"); player_.playMusic(null == state_.targetTime_); } cancelSleepTimer(); setSleepTimer(); updateUI(); showMessage(this, getString(R.string.play_with_sleep_timer)); return true; } return false; } @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch (id) { case DIALOG_PLAY_SLEEP_TUNE: dialog = new AlertDialog.Builder(this) .setTitle(R.string.ask_play_sleep_tune) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { playSleepMusic(state_.targetTime_.getTimeInMillis()); updateUI(); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { updateUI(); } }) .create(); break; default: break; } return dialog; } private class TimePickerTime { public final int hour_; public final int min_; public final String speach_; public TimePickerTime(int hour, int min, String speach) { hour_ = hour; min_ = min; speach_ = speach; } } private class ClickListener implements DialogInterface.OnClickListener { private TimePickerTime[] mTimeList; public ClickListener(TimePickerTime[] time) { mTimeList = time; } @Override public void onClick(DialogInterface dialog, int which) { setTimePickerTime(mTimeList[which]); } } private void setTimePickerTime(TimePickerTime time) { timePicker_.setCurrentHour(time.hour_); timePicker_.setCurrentMinute(time.min_); String msg = MessageFormat.format(getString(R.string.voice_success_format), time.speach_); showMessage(this, msg); } //TODO: support english??? @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == SPEECH_RECOGNITION_REQUEST_CODE) { if (resultCode == RESULT_CANCELED) { //TODO: flag return; } if (resultCode != RESULT_OK) { return; } ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); //ArrayList<TimePickerTime> result = new ArrayList<TimePickerTime>(); Map<String, TimePickerTime> result = new HashMap<String, TimePickerTime>(); for (String speech : matches) { Matcher m = TIME_PATTERN.matcher(speech); if (m.matches()) { int hour = Integer.valueOf(m.group(1)) % 24; int minute; String minStr = m.group(2); if (null == minStr) { minute = 0; } else if ("".equals(minStr)) { minute = 30; } else { minute = Integer.valueOf(m.group(3)) % 60; } String key = hour + ":" + minute; if (!result.containsKey(key)) { result.put(key, new TimePickerTime(hour, minute, speech)); } } else { Matcher m2 = AFTER_TIME_PATTERN.matcher(speech); if (m2.matches()) { String hourStr = m2.group(2); String minStr = m2.group(3); if (null == hourStr && null == minStr) { continue; } long after_millis = 0; if (null != hourStr) { after_millis += 60 * 60 * 1000 * Integer.valueOf(hourStr); } if (null != minStr) { if ("".equals(minStr)) { after_millis += 60 * 1000 * 30; } else { long int_data = Integer.valueOf(m2.group(4)); after_millis += 60 * 1000 * int_data; } } Calendar cal = new GregorianCalendar(); cal.setTimeInMillis(System.currentTimeMillis() + after_millis); int hour = cal.get(Calendar.HOUR_OF_DAY); int min = cal.get(Calendar.MINUTE); String key = hour + ":" + min; if (!result.containsKey(key)) { result.put(key, new TimePickerTime(hour, min, speech)); } } } } if (result.isEmpty()) { showMessage(this, getString(R.string.voice_fail)); } else if (result.size() == 1) { setTimePickerTime(result.values().iterator().next()); } else { String[] speechArray = new String[result.size()]; Iterator<TimePickerTime> iter = result.values().iterator(); for (int i = 0; i < result.size(); i++) { TimePickerTime time = iter.next(); speechArray[i] = time.speach_ + String.format(" (%02d:%02d)", time.hour_, time.min_); } //select from list dialog new AlertDialog.Builder(this) .setTitle(R.string.select_time_from_list) .setItems(speechArray, new ClickListener(result.values().toArray(new TimePickerTime[0]))) .create() .show(); } } } @Override public void onLowMemory() { //TODO: close this activity webview_.clearCache(false); } @Override public void onServiceConnected(ComponentName name, IBinder binder) { Log.d(TAG, "onServiceConnected"); player_ = ((MalarmPlayerService.LocalBinder) binder).getService(); updateUI(); player_.addPlayerStateListener(this); } @Override public void onServiceDisconnected(ComponentName name) { Log.d(TAG, "onServiceDisconnected"); player_.removePlayerStateListener(this); player_ = null; } @Override public void onStartMusic(String title) { updateUI(); } @Override public void onStopMusic() { updateUI(); } }
package net.patrykczarnik.vp.out; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import net.patrykczarnik.ffmpeg.FFFilter; import net.patrykczarnik.ffmpeg.FFFilterChain; import net.patrykczarnik.ffmpeg.FFFilterOption; import net.patrykczarnik.ffmpeg.FFInput; import net.patrykczarnik.utils.CollectionUtils; import net.patrykczarnik.utils.Positioned; import net.patrykczarnik.vp.in.VPScriptOption; public class Segment { private List<FFInput> inputs = new ArrayList<>(); private CurrentOptions remeberedOptions; private FiltersRegistry filtersRegistry; public Segment(FiltersRegistry filtersRegistry) { this.filtersRegistry = filtersRegistry; } public void addInput(FFInput input) { inputs.add(input); } public List<FFInput> getInputs() { return Collections.unmodifiableList(inputs); } public List<FFFilterChain> getCombinedChains(int nseg, int ninp) { FFFilter concatFilter = FFFilter.newFilter("concat", FFFilterOption.integer("n", inputs.size()), FFFilterOption.integer("v", 1), FFFilterOption.integer("a", 0)); List<String> startLabels = IntStream.range(ninp, ninp + inputs.size()) .mapToObj(i -> i + ":0") .collect(Collectors.toList()); String endLabel = segmentLabel(nseg); FFFilterChain chain = FFFilterChain.withLabels(startLabels, List.of(endLabel), List.of(concatFilter)); List<Positioned<FFFilter>> allFilters = new ArrayList<>(); Set<AFilterMapper> mappers = new LinkedHashSet<>(); for(VPScriptOption vpOption : remeberedOptions.getVideo().values()) { AFilterMapper filterMapper = filtersRegistry.get("video", vpOption.getName()); allFilters.addAll(filterMapper.getFFFilters(vpOption)); mappers.add(filterMapper); } for(AFilterMapper filterMapper : mappers) { allFilters.addAll(filterMapper.getPostponed()); } allFilters.sort(null); chain.addFilters(CollectionUtils.mapList(allFilters, Positioned::getValue)); return List.of(chain); } public static String segmentLabel(int nseg) { return "seg" + nseg; } public void remeberOptions(CurrentOptions currentOptions) { remeberedOptions = currentOptions.clone(); } public CurrentOptions getRemeberedOptions() { return remeberedOptions; } }
package net.domesdaybook.parser.tree.node; import java.util.Collections; import java.util.List; import net.domesdaybook.parser.ParseException; import net.domesdaybook.parser.tree.ParseTree; import net.domesdaybook.parser.tree.ParseTreeType; public class BaseNode implements ParseTree { private final ParseTreeType type; private final boolean inverted; public BaseNode(final ParseTreeType type) { this(type, false); } public BaseNode(final ParseTreeType type, final boolean inverted) { this.type = type; this.inverted = inverted; } @Override public ParseTreeType getParseTreeType() { return type; } @Override public byte getByteValue() throws ParseException { throw new ParseException("No byte value is available."); } @Override public int getIntValue() throws ParseException { throw new ParseException("No int value is available."); } @Override public String getTextValue() throws ParseException { throw new ParseException("No text value is available."); } @Override public boolean isValueInverted() throws ParseException { return inverted; } @Override public List<ParseTree> getChildren() { return Collections.emptyList(); } }
package hex; import hex.glm.GLM2.Source; import hex.glm.GLMParams.Link; import org.junit.Assert; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertEquals; import hex.FrameTask.DataInfo; import hex.glm.*; import hex.glm.GLMParams.Family; import org.junit.Test; import water.*; import water.deploy.Node; import water.deploy.NodeVM; import water.fvec.*; import java.io.File; import java.util.HashMap; import java.util.concurrent.ExecutionException; public class GLMTest2 extends TestUtil { final static public void testHTML(GLMModel m) { StringBuilder sb = new StringBuilder(); new GLMModelView(m).toHTML(sb); assert(sb.length() > 0); } @Test public void testGaussianRegression() throws InterruptedException, ExecutionException{ Key raw = Key.make("gaussian_test_data_raw"); Key parsed = Key.make("gaussian_test_data_parsed"); Key modelKey = Key.make("gaussian_test"); GLMModel model = null; Frame fr = null; try { // make data so that the expected coefficients is icept = col[0] = 1.0 FVecTest.makeByteVec(raw, "x,y\n0,0\n1,0.1\n2,0.2\n3,0.3\n4,0.4\n5,0.5\n6,0.6\n7,0.7\n8,0.8\n9,0.9"); fr = ParseDataset2.parse(parsed, new Key[]{raw}); GLMParams glm = new GLMParams(Family.gaussian); new GLM2("GLM test of gaussian(linear) regression.",Key.make(),modelKey,new Source(fr,fr.vec("y"),false),Family.gaussian).doInit().fork().get(); model = DKV.get(modelKey).get(); testHTML(model); Assert.assertTrue(model.get_params().state == Job.JobState.DONE); //HEX-1817 HashMap<String, Double> coefs = model.coefficients(); assertEquals(0.0,coefs.get("Intercept"),1e-4); assertEquals(0.1,coefs.get("x"),1e-4); }finally{ if( fr != null ) fr.delete(); if(model != null)model.delete(); } } /** * Test Poisson regression on simple and small synthetic dataset. * Equation is: y = exp(x+1); */ @Test public void testPoissonRegression() throws InterruptedException, ExecutionException { Key raw = Key.make("poisson_test_data_raw"); Key parsed = Key.make("poisson_test_data_parsed"); Key modelKey = Key.make("poisson_test"); GLMModel model = null; Frame fr = null; try { // make data so that the expected coefficients is icept = col[0] = 1.0 FVecTest.makeByteVec(raw, "x,y\n0,2\n1,4\n2,8\n3,16\n4,32\n5,64\n6,128\n7,256"); fr = ParseDataset2.parse(parsed, new Key[]{raw}); new GLM2("GLM test of poisson regression.",Key.make(),modelKey,new Source(fr,fr.lastVec(),false),Family.poisson).setRegularization(new double []{0},new double[]{0}).doInit().fork().get(); model = DKV.get(modelKey).get(); for(double c:model.beta())assertEquals(Math.log(2),c,1e-4); //new byte []{1,2,3,4,5,6,7,8, 9, 10,11,12,13,14}, // new byte []{0,1,2,3,1,4,9,18,23,31,20,25,37,45}); model.delete(); fr.delete(); FVecTest.makeByteVec(raw, "x,y\n1,0\n2,1\n3,2\n4,3\n5,1\n6,4\n7,9\n8,18\n9,23\n10,31\n11,20\n12,25\n13,37\n14,45\n"); fr = ParseDataset2.parse(parsed, new Key[]{raw}); new GLM2("GLM test of poisson regression(2).",Key.make(),modelKey,new Source(fr,fr.lastVec(),false),Family.poisson).setRegularization(new double []{0},new double[]{0}).doInit().fork().get(); model = DKV.get(modelKey).get(); testHTML(model); assertEquals(0.3396,model.beta()[1],5e-3); assertEquals(0.2565,model.beta()[0],5e-3); }finally{ if( fr != null ) fr.delete(); if(model != null)model.delete(); } } /** * Test Gamma regression on simple and small synthetic dataset. * Equation is: y = 1/(x+1); * @throws ExecutionException * @throws InterruptedException */ @Test public void testGammaRegression() throws InterruptedException, ExecutionException { GLMModel model = null; Frame fr = null; try { // make data so that the expected coefficients is icept = col[0] = 1.0 Key raw = Key.make("gamma_test_data_raw"); Key parsed = Key.make("gamma_test_data_parsed"); FVecTest.makeByteVec(raw, "x,y\n0,1\n1,0.5\n2,0.3333333\n3,0.25\n4,0.2\n5,0.1666667\n6,0.1428571\n7,0.125"); fr = ParseDataset2.parse(parsed, new Key[]{raw}); // /public GLM2(String desc, Key dest, Frame src, Family family, Link link, double alpha, double lambda) { double [] vals = new double[] {1.0,1.0}; //public GLM2(String desc, Key dest, Frame src, Family family, Link link, double alpha, double lambda) { Key modelKey = Key.make("gamma_test"); new GLM2("GLM test of gamma regression.",Key.make(),modelKey,new Source(fr,fr.lastVec(),false),Family.gamma).setRegularization(new double []{0},new double[]{0}).doInit().fork().get(); model = DKV.get(modelKey).get(); testHTML(model); for(double c:model.beta())assertEquals(1.0, c,1e-4); }finally{ if( fr != null ) fr.delete(); if(model != null)model.delete(); } } //simple tweedie test @Test public void testTweedieRegression() throws InterruptedException, ExecutionException{ Key raw = Key.make("tweedie_test_data_raw"); Key parsed = Key.make("tweedie_test_data_parsed"); Key modelKey = Key.make("tweedie_test"); Frame fr = null; GLMModel model = null; try { // make data so that the expected coefficients is icept = col[0] = 1.0 FVecTest.makeByteVec(raw, "x,y\n0,0\n1,0.1\n2,0.2\n3,0.3\n4,0.4\n5,0.5\n6,0.6\n7,0.7\n8,0.8\n9,0.9\n0,0\n1,0\n2,0\n3,0\n4,0\n5,0\n6,0\n7,0\n8,0\n9,0"); fr = ParseDataset2.parse(parsed, new Key[]{raw}); double [] powers = new double [] {1.5,1.1,1.9}; double [] intercepts = new double []{3.643,1.318,9.154}; double [] xs = new double []{-0.260,-0.0284,-0.853}; for(int i = 0; i < powers.length; ++i){ GLM2 glm = new GLM2("GLM test of tweedie regression.",Key.make(),modelKey,new Source(fr,fr.lastVec(),false),Family.tweedie, Link.family_default,0,true);//.doInit().fork().get(); glm.setTweediePower(powers[i]); glm.setLambda(0); glm.max_iter = 1000; glm.doInit().fork().get(); model = DKV.get(modelKey).get(); testHTML(model); HashMap<String, Double> coefs = model.coefficients(); assertEquals(intercepts[i], coefs.get("Intercept"), 1e-3); assertEquals(xs[i],coefs.get("x"),1e-3); } }finally{ if( fr != null ) fr.delete(); if(model != null)model.delete(); } } @Test public void testOffset()throws InterruptedException, ExecutionException{ Key parsed = Key.make("prostate_parsed"); Key modelKey = Key.make("prostate_model"); GLMModel model = null; File f = TestUtil.find_test_file("smalldata/glm_test/prostate_cat_replaced.csv"); Frame fr = getFrameForFile(parsed, "smalldata/glm_test/prostate_cat_replaced.csv", new String[]{"ID"}, "CAPSULE"); Key k = Key.make("rebalanced"); H2O.submitTask(new RebalanceDataSet(fr,k,64)).join(); fr.delete(); fr = DKV.get(k).get(); try{ // R results: // Call: glm(formula = CAPSULE ~ . - ID - AGE, family = binomial, data = D, // offset = D$AGE) // Coefficients: // (Intercept) RACER2 RACER3 DPROS DCAPS PSA VOL GLEASON // -95.16718 -0.67663 -2.11848 2.31296 3.47783 0.10842 -0.08657 2.90452 // Degrees of Freedom: 379 Total (i.e. Null); 372 Residual // Null Deviance: 2015 // Residual Deviance: 1516 AIC: 1532 // H2O differs on has_intercept and race, same residual deviance though String [] cfs1 = new String [] {/*"Intercept","RACE.R2","RACE.R3",*/ "AGE", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON"}; double [] vals = new double [] {/*-95.16718, -0.67663, -2.11848,*/1, 2.31296, 3.47783, 0.10842, -0.08657, 2.90452}; new GLM2("GLM offset test on prostate.",Key.make(),modelKey,new GLM2.Source(fr,fr.vec("CAPSULE"),false,true,fr.vec("AGE")),Family.binomial).setRegularization(new double []{0},new double[]{0}).doInit().fork().get(); model = DKV.get(modelKey).get(); Assert.assertTrue(model.get_params().state == Job.JobState.DONE); //HEX-1817 testHTML(model); HashMap<String, Double> coefs = model.coefficients(); for(int i = 0; i < cfs1.length; ++i) assertEquals(vals[i], coefs.get(cfs1[i]),1e-4); GLMValidation val = model.validation(); assertEquals(2015, model.null_validation.residualDeviance(),1e-1); assertEquals(1516, val.residualDeviance(),1e-1); assertEquals(1532, val.aic(),1e-1); } finally { fr.delete(); if(model != null)model.delete(); } } /** * Simple test for poisson, gamma and gaussian families (no regularization, test both lsm solvers). * Basically tries to predict horse power based on other parameters of the cars in the dataset. * Compare against the results from standard R glm implementation. * @throws ExecutionException * @throws InterruptedException */ @Test public void testCars() throws InterruptedException, ExecutionException{ Key parsed = Key.make("cars_parsed"); Key modelKey = Key.make("cars_model"); Frame fr = null; GLMModel model = null; try { String[] ignores = new String[]{"name"}; String response = "power (hp)"; fr = getFrameForFile(parsed, "smalldata/cars.csv", ignores, response); new GLM2("GLM test on cars.", Key.make(), modelKey, new Source(fr,fr.lastVec(),true),Family.poisson).setRegularization(new double []{0},new double[]{0}).doInit().fork().get(); model = DKV.get(modelKey).get(); testHTML(model); HashMap<String, Double> coefs = model.coefficients(); String[] cfs1 = new String[]{"Intercept", "economy (mpg)", "cylinders", "displacement (cc)", "weight (lb)", "0-60 mph (s)", "year"}; double[] vls1 = new double[]{4.9504805, -0.0095859, -0.0063046, 0.0004392, 0.0001762, -0.0469810, 0.0002891}; for (int i = 0; i < cfs1.length; ++i) assertEquals(vls1[i], coefs.get(cfs1[i]), 1e-4); // test gamma double[] vls2 = new double[]{8.992e-03, 1.818e-04, -1.125e-04, 1.505e-06, -1.284e-06, 4.510e-04, -7.254e-05}; model.delete(); new GLM2("GLM test on cars.", Key.make(), modelKey, new Source(fr,fr.lastVec(),true), Family.gamma).setRegularization(new double []{0},new double[]{0}).doInit().fork().get(); model = DKV.get(modelKey).get(); testHTML(model); coefs = model.coefficients(); for (int i = 0; i < cfs1.length; ++i) assertEquals(vls2[i], coefs.get(cfs1[i]), 1e-4); model.delete(); // test gaussian double[] vls3 = new double[]{166.95862, -0.00531, -2.46690, 0.12635, 0.02159, -4.66995, -0.85724}; new GLM2("GLM test on cars.", Key.make(), modelKey, new Source(fr,fr.lastVec(),true), Family.gaussian).setRegularization(new double []{0},new double[]{0}).doInit().fork().get(); model = DKV.get(modelKey).get(); testHTML(model); coefs = model.coefficients(); for (int i = 0; i < cfs1.length; ++i) assertEquals(vls3[i], coefs.get(cfs1[i]), 1e-4); } catch(Throwable t){ t.printStackTrace(); } finally { if( fr != null ) fr.delete(); if(model != null)model.delete(); } } /** * Simple test for binomial family (no regularization, test both lsm solvers). * Runs the classical prostate, using dataset with race replaced by categoricals (probably as it's supposed to be?), in any case, * it gets to test correct processing of categoricals. * * Compare against the results from standard R glm implementation. * @throws ExecutionException * @throws InterruptedException */ @Test public void testProstate() throws InterruptedException, ExecutionException{ Key parsed = Key.make("prostate_parsed"); Key modelKey = Key.make("prostate_model"); GLMModel model = null; File f = TestUtil.find_test_file("smalldata/glm_test/prostate_cat_replaced.csv"); Frame fr = getFrameForFile(parsed, "smalldata/glm_test/prostate_cat_replaced.csv", new String[]{"ID"}, "CAPSULE"); try{ // R results // Coefficients: // (Intercept) ID AGE RACER2 RACER3 DPROS DCAPS PSA VOL GLEASON // -8.894088 0.001588 -0.009589 0.231777 -0.459937 0.556231 0.556395 0.027854 -0.011355 1.010179 String [] cfs1 = new String [] {"Intercept","AGE", "RACE.R2","RACE.R3", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON"}; double [] vals = new double [] {-8.14867, -0.01368, 0.32337, -0.38028, 0.55964, 0.49548, 0.02794, -0.01104, 0.97704}; new GLM2("GLM test on prostate.",Key.make(),modelKey,new Source(fr,fr.lastVec(),false),Family.binomial).setRegularization(new double []{0},new double[]{0}).doInit().fork().get(); model = DKV.get(modelKey).get(); Assert.assertTrue(model.get_params().state == Job.JobState.DONE); //HEX-1817 testHTML(model); HashMap<String, Double> coefs = model.coefficients(); for(int i = 0; i < cfs1.length; ++i) assertEquals(vals[i], coefs.get(cfs1[i]),1e-4); GLMValidation val = model.validation(); assertEquals(512.3, model.null_validation.residualDeviance(), 1e-1); assertEquals(378.3, val.residualDeviance(),1e-1); assertEquals(396.3, val.aic(), 1e-1); } finally { fr.delete(); if(model != null)model.delete(); } } @Test public void testNoNNegative() { // glmnet's result: // res2 <- glmnet(x=M,y=D$CAPSULE,lower.limits=0,family='binomial') // res2$beta[,100] // AGE RACE DPROS DCAPS PSA VOL GLEASON // 0.00000000 0.00000000 0.54788332 0.53816534 0.02380097 0.00000000 0.98115670 // res2$a0[100] // s99 // -8.945984 Key parsed = Key.make("prostate_parsed"); Key modelKey = Key.make("prostate_model"); GLMModel model = null; Frame fr = getFrameForFile(parsed, "smalldata/logreg/prostate.csv", new String[]{"ID"}, "CAPSULE"); Key k = Key.make("rebalanced"); H2O.submitTask(new RebalanceDataSet(fr, k, 64)).join(); fr.delete(); fr = DKV.get(k).get(); try { // H2O differs on has_intercept and race, same residual deviance though String[] cfs1 = new String[]{"RACE", "AGE", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON","Intercept"}; double[] vals = new double[]{0, 0, 0.54788332,0.53816534, 0.02380097, 0, 0.98115670,-8.945984}; new GLM2("GLM offset test on prostate.", Key.make(), modelKey, new GLM2.Source(fr, fr.vec("CAPSULE"), true, true), Family.binomial).setNonNegative(true).setRegularization(new double[]{1},new double[]{2.22E-5}).doInit().fork().get(); //.setHighAccuracy().doInit().fork().get(); model = DKV.get(modelKey).get(); Assert.assertTrue(model.get_params().state == Job.JobState.DONE); testHTML(model); HashMap<String, Double> coefs = model.coefficients(); for (int i = 0; i < cfs1.length; ++i) assertEquals(vals[i], coefs.get(cfs1[i]), 1e-2); GLMValidation val = model.validation(); assertEquals(512.2888, model.null_validation.residualDeviance(), 1e-1); assertEquals(383.8068, val.residualDeviance(), 1e-1); } finally { fr.delete(); if(model != null)model.delete(); } } @Test public void testNoIntercept(){ // Call: glm(formula = CAPSULE ~ . - ID - 1, family = binomial, data = D) // Coefficients: // AGE RACE DPROS DCAPS PSA VOL GLEASON // -0.07205 -1.23262 0.47899 0.13934 0.03626 -0.01155 0.63645 // Degrees of Freedom: 380 Total (i.e. Null); 373 Residual // Null Deviance: 526.8 // Residual Deviance: 399 AIC: 413 Key parsed = Key.make("prostate_parsed"); Key modelKey = Key.make("prostate_model"); GLMModel model = null; Frame fr = getFrameForFile(parsed, "smalldata/logreg/prostate.csv", new String[]{"ID"}, "CAPSULE"); Key k = Key.make("rebalanced"); H2O.submitTask(new RebalanceDataSet(fr,k,64)).join(); fr.delete(); fr = DKV.get(k).get(); try{ // H2O differs on has_intercept and race, same residual deviance though String [] cfs1 = new String [] {"RACE", "AGE", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON"}; double [] vals = new double [] { -1.23262,-0.07205, 0.47899, 0.13934, 0.03626, -0.01155, 0.63645}; new GLM2("GLM offset test on prostate.",Key.make(),modelKey,new GLM2.Source(fr,fr.vec("CAPSULE"),false,false),Family.binomial).setRegularization(new double[]{0},new double[]{0}).doInit().fork().get(); //.setHighAccuracy().doInit().fork().get(); model = DKV.get(modelKey).get(); Assert.assertTrue(model.get_params().state == Job.JobState.DONE); testHTML(model); HashMap<String, Double> coefs = model.coefficients(); for(int i = 0; i < cfs1.length; ++i) assertEquals(vals[i], coefs.get(cfs1[i]),1e-4); GLMValidation val = model.validation(); assertEquals(526.8, model.null_validation.residualDeviance(),1e-1); assertEquals(399, val.residualDeviance(),1e-1); assertEquals(413, val.aic(),1e-1); // test scoring Frame score = model.score(fr); Vec mu = score.vec("1"); final double [] exp_preds = new double []{ // R predictions using R model 0.2790619,0.4983728,0.1791504,0.3179892,0.1227505,0.6407688,0.6086971,0.8692052,0.2198773,0.08973103, 0.3612737,0.5100686,0.9109716,0.8954879,0.07149991,0.1073158,0.01838251,0.1152114,0.3904417,0.2489027, 0.5629947,0.9801603,0.4037248,0.179598,0.459759,0.06532427,0.3314463,0.1428987,0.2182262,0.5992186, 0.5902301,0.2907103,0.6824957,0.723047,0.3096409,0.3182108,0.4573366,0.4957492,0.6979306,0.3537596, 0.5224244,0.1372099,0.2386254,0.3372425,0.9438167,0.9186791,0.04887559,0.5780143,0.101601,0.2495288, 0.1152114,0.992729,0.3241788,0.9455764,0.527273,0.6789504,0.4396949,0.6118608,0.4396932,0.4433259, 0.09217928,0.1718421,0.2733261,0.534392,0.8947366,0.5070448,0.543244,0.1760429,0.1587279,0.120139, 0.230559,0.1838054,0.6437882,0.2357325,0.3408042,0.7405974,0.225001,0.3285307,0.2709872,0.698206, 0.2430985,0.54366,0.5325359,0.2517555,0.20072,0.2483879,0.957223,0.9493145,0.866129,0.5205794, 0.1206937,0.1304155,0.5742516,0.9235101,0.2142854,0.2317031,0.5402695,0.3272389,0.4129856,0.5158623, 0.3303411,0.3651679,0.1585129,0.1237278,0.4078402,0.4843822,0.2863726,0.8078961,0.4044774,0.5935165, 0.2365318,0.2232613,0.5775281,0.4272229,0.97787,0.9394984,0.5734764,0.5001313,0.1140847,0.7091469, 0.2474317,0.07108103,0.4702847,0.7315436,0.5285277,0.3130729,0.3107732,0.2458944,0.1584744,0.1261198, 0.06565271,0.3980803,0.1742766,0.6937854,0.2508427,0.3177764,0.2621678,0.9889184,0.9792494,0.3773912, 0.1606691,0.7699755,0.3038182,0.9349492,0.222803,0.07258553,0.9597009,0.3351248,0.6378875,0.3786587, 0.06284628,0.1737639,0.1482272,0.6689168,0.4699873,0.04251894,0.6456895,0.3105649,0.4429625,0.595572, 0.3196979,0.5035891,0.7084547,0.6600298,0.2110469,0.5676662,0.2077393,0.2516736,0.5292617,0.777053, 0.2858721,0.3028988,0.7719771,0.6168979,0.1803735,0.3461169,0.7885772,0.1189895,0.2998581,0.6705114, 0.7083223,0.7471706,0.2958453,0.5998061,0.6174054,0.8464897,0.8724295,0.0529646,0.323008,0.5425115, 0.4691805,0.9033616,0.1397801,0.1515056,0.2604321,0.5680744,0.1702089,0.2599474,0.2410981,0.4224218, 0.3699072,0.7741795,0.352852,0.202532,0.3876063,0.5091125,0.1403465,0.3263904,0.4990924,0.3713234, 0.2126325,0.5911457,0.9437311,0.4720828,0.387815,0.2707227,0.8353962,0.896327,0.2910632,0.1353718, 0.5688478,0.6956094,0.09815098,0.675314,0.2265392,0.4702665,0.321468,0.5911756,0.350539,0.5475017, 0.3069707,0.5467453,0.6713496,0.9915501,0.421299,0.2042643,0.1522847,0.2505383,0.3841292,0.0665612, 0.1617935,0.251719,0.8010179,0.1755443,0.2864689,0.3067574,0.1087108,0.4872522,0.1974353,0.8422357, 0.4334588,0.8472403,0.4085235,0.1092982,0.4357049,0.8977747,0.7387849,0.2449383,0.4908928,0.1334274, 0.2282918,0.3815987,0.3493979,0.3307988,0.5747723,0.3146818,0.5184166,0.1786566,0.6330598,0.3373586, 0.2120764,0.134929,0.9091373,0.3451438,0.142635,0.1559291,0.3735968,0.1252362,0.4867681,0.305977, 0.7427962,0.006477887,0.06593239,0.07762176,0.5986354,0.3879587,0.4083299,0.7713339,0.2778816,0.07709849, 0.2372032,0.1341624,0.3215959,0.814327,0.4853451,0.8217658,0.7465689,0.1396363,0.3774837,0.09754716, 0.1782466,0.2008813,0.9958686,0.5042077,0.6177981,0.2189784,0.2797684,0.5289506,0.03569642,0.7797529, 0.03918494,0.2265129,0.6268007,0.2234737,0.3341935,0.6285033,0.3302472,0.2205676,0.8441454,0.2983196, 0.5755281,0.5844469,0.2310026,0.7117795,0.04170531,0.1020103,0.1554328,0.4709666,0.3739278,0.07840264, 0.634026,0.592427,0.06120752,0.692224,0.1963099,0.5465022,0.3068802,0.868874,0.1502109,0.8650777,0.5293211, 0.3454249,0.07389645,0.3731161,0.9075499,0.0944298,0.2188017,0.06919131,0.5516276,0.3083056,0.4818407, 0.2932327,0.8026013,0.6212048,0.01829989,0.2865116,0.005850647,0.1678272,0.3456439,0.260818,0.2883414, 0.2521343,0.5790858,0.6529569,0.1452642,0.2745046,0.1087368,0.546329,0.2560442,0.06902664,0.1696336, 0.3607475,0.1879519,0.9986248,0.2345369,0.4297052,0.028796,0.2803801,0.03908738,0.1887357}; assertEquals(exp_preds.length,mu.length()); for(int i = 0; i < mu.length(); ++i) assertEquals(exp_preds[i],mu.at(i),1e-4); // test that it throws with categoricals fr.delete(); fr = getFrameForFile(parsed, "smalldata/glm_test/prostate_cat_replaced.csv", new String[]{"ID"}, "CAPSULE"); try { new GLM2("GLM offset test on prostate.", Key.make(), modelKey, new GLM2.Source(fr, fr.vec("CAPSULE"), false,false), Family.binomial).doInit().fork().get(); assertTrue("should've thrown",false); } catch(IllegalArgumentException iae){} } finally { fr.delete(); if(model != null)model.delete(); } } @Test public void testNoInterceptAndOffset(){ // r <- glm(data=D,CAPSULE ~ . - ID - 1 - DCAPS,offset=as.numeric(DCAPS),family=binomial) // Call: glm(formula = CAPSULE ~ . - ID - 1 - DCAPS, family = binomial, // data = D, offset = as.numeric(DCAPS)) // Coefficients: // AGE RACE DPROS PSA VOL GLEASON // -0.07731 -1.34515 0.44422 0.03559 -0.01001 0.57414 // Degrees of Freedom: 380 Total (i.e. Null); 374 Residual // Null Deviance: 696.8 // Residual Deviance: 402.9 AIC: 414.9 Key parsed = Key.make("prostate_parsed"); Key modelKey = Key.make("prostate_model"); GLMModel model = null; Frame fr = getFrameForFile(parsed, "smalldata/logreg/prostate.csv", new String[]{"ID"}, "CAPSULE"); Key k = Key.make("rebalanced"); H2O.submitTask(new RebalanceDataSet(fr,k,64)).join(); fr.delete(); fr = DKV.get(k).get(); try{ // H2O differs on has_intercept and race, same residual deviance though String [] cfs1 = new String [] {"RACE", "AGE", "DPROS", "PSA", "VOL", "GLEASON"}; double [] vals = new double [] { -1.34515,-0.07731, 0.44422, 0.03559, -0.01001, 0.57414}; new GLM2("GLM offset test on prostate.",Key.make(),modelKey,new GLM2.Source(fr,fr.vec("CAPSULE"),false,false,fr.vec("DCAPS")),Family.binomial).setRegularization(new double[]{0},new double[]{0}).doInit().fork().get(); //.setHighAccuracy().doInit().fork().get(); model = DKV.get(modelKey).get(); Assert.assertTrue(model.get_params().state == Job.JobState.DONE); testHTML(model); HashMap<String, Double> coefs = model.coefficients(); for(int i = 0; i < cfs1.length; ++i) assertEquals(vals[i], coefs.get(cfs1[i]),1e-4); GLMValidation val = model.validation(); assertEquals(696.8, model.null_validation.residualDeviance(),1e-1); assertEquals(402.9, val.residualDeviance(),1e-1); assertEquals(414.9, val.aic(),1e-1); // test scoring Frame score = model.score(fr); Vec mu = score.vec("1"); final double [] exp_preds = new double []{ // R predictions using R model 0.2714328, 0.6633844, 0.3332337, 0.261754, 0.1286857, 0.7700994, 0.7278019, 0.9234909, 0.2111474, 0.1685586, 0.4976614, 0.6792206, 0.9448146, 0.9433877, 0.07163949, 0.1055238, 0.01654711, 0.1167567, 0.6150695, 0.3851188, 0.5469755, 0.9775073, 0.3686457, 0.1734122, 0.4399385, 0.0647587, 0.3155403, 0.139005, 0.2258441, 0.5898738, 0.5922247, 0.2692957, 0.6137802, 0.8462912, 0.3058918, 0.2957983, 0.462281, 0.6524339, 0.6799241, 0.3226737, 0.4941844, 0.1330671, 0.2254533, 0.3066927, 0.9200088, 0.958889, 0.04513577, 0.5383411, 0.1038777, 0.2440525, 0.1092492, 0.9958668, 0.3193829, 0.9367929, 0.4897762, 0.663691, 0.4023, 0.5698951, 0.4341724, 0.4453501, 0.1106898, 0.1682721, 0.2460871, 0.4990961, 0.8788688, 0.4803311, 0.5465907, 0.1569607, 0.1633997, 0.1044413, 0.2212412, 0.1808158, 0.6181282, 0.2396049, 0.3213105, 0.7081065, 0.2098653, 0.3235215, 0.2801671, 0.6652517, 0.2194231, 0.5277527, 0.4905273, 0.2323389, 0.1850839, 0.2254083, 0.9757958, 0.9727239, 0.8319945, 0.482306, 0.1248545, 0.1360881, 0.5320567, 0.9574291, 0.2080324, 0.2144612, 0.4982939, 0.333785, 0.4088947, 0.4901476, 0.3223926, 0.3371016, 0.1693325, 0.1297989, 0.3793889, 0.6960325, 0.2683522, 0.7797531, 0.3924964, 0.5530082, 0.2158664, 0.1981704, 0.5450428, 0.4019126, 0.9884714, 0.9327079, 0.5102081, 0.495269, 0.112279, 0.6908168, 0.2224574, 0.08042856, 0.4025428, 0.6777602, 0.4874214, 0.3087576, 0.3105473, 0.2562402, 0.146729, 0.1274273, 0.06670393, 0.3613933, 0.1757637, 0.6709157, 0.2491046, 0.3167014, 0.2513937, 0.9851177, 0.9885838, 0.3577745, 0.1546274, 0.72168, 0.2868293, 0.9631664, 0.2343213, 0.06899739, 0.9769368, 0.3338782, 0.6347512, 0.3485507, 0.05771538, 0.175731, 0.1481765, 0.6632638, 0.4730665, 0.04656982, 0.6374328, 0.2778723, 0.4285074, 0.5850365, 0.2805779, 0.4880345, 0.6923684, 0.6431633, 0.2055755, 0.7452229, 0.2049388, 0.2320392, 0.5034929, 0.7341303, 0.2612126, 0.2810201, 0.7449264, 0.5941076, 0.1742119, 0.3320475, 0.7572676, 0.12218, 0.2932756, 0.6242029, 0.8294807, 0.7162603, 0.2853046, 0.5877545, 0.6005982, 0.8300135, 0.8581161, 0.04492492, 0.5175156, 0.5203193, 0.4543528, 0.8947635, 0.1580703, 0.149249, 0.2448207, 0.5182805, 0.1475552, 0.2579333, 0.2301171, 0.3908543, 0.3775577, 0.73236, 0.348705, 0.191458, 0.3810784, 0.6695089, 0.1496464, 0.3539768, 0.4774868, 0.3786629, 0.2268355, 0.5461673, 0.9277121, 0.4923828, 0.3681328, 0.2882241, 0.8115473, 0.9391989, 0.2793372, 0.1293679, 0.5765253, 0.6672549, 0.1085629, 0.6530963, 0.2099487, 0.4395374, 0.3355906, 0.5774188, 0.3320534, 0.553845, 0.2571366, 0.555651, 0.8082447, 0.9878579, 0.3889303, 0.2042754, 0.1462106, 0.2517127, 0.3565349, 0.05953082, 0.1621768, 0.2344363, 0.8734925, 0.1734602, 0.2671484, 0.2510726, 0.1139504, 0.4709787, 0.2081558, 0.8334942, 0.6389909, 0.8736708, 0.3707539, 0.1036151, 0.4302368, 0.9448559, 0.8462579, 0.2411054, 0.4935917, 0.13429, 0.241161, 0.3752208, 0.3194919, 0.3351406, 0.5469151, 0.3131954, 0.4897492, 0.1936143, 0.6055124, 0.324853, 0.2217794, 0.1513135, 0.889535, 0.3500166, 0.1428834, 0.1542479, 0.3720363, 0.1281707, 0.4973429, 0.3057025, 0.7167489, 0.009317823, 0.06013731, 0.07956679, 0.5774665, 0.3988433, 0.3558458, 0.7577223, 0.2729823, 0.08260389, 0.2412571, 0.1479702, 0.3244259, 0.7868388, 0.4718041, 0.7904578, 0.8405282, 0.1406044, 0.3987826, 0.1000184, 0.1835483, 0.1950392, 0.9977054, 0.4791991, 0.6242925, 0.2214897, 0.273065, 0.4966417, 0.04303004, 0.7397745, 0.04042993, 0.2130047, 0.7908355, 0.2323056, 0.3072782, 0.5756885, 0.2978859, 0.2074281, 0.8241888, 0.2913779, 0.5488127, 0.56141, 0.2361691, 0.6870129, 0.04781581, 0.1052127, 0.1451822, 0.482763, 0.3677431, 0.08324137, 0.7907079, 0.5541721, 0.05215705, 0.691283, 0.1813831, 0.5188524, 0.3090686, 0.9383484, 0.1454368, 0.8514089, 0.5071669, 0.2971994, 0.08048813, 0.3643893, 0.8936522, 0.09901629, 0.2188425, 0.07477413, 0.537254, 0.3051141, 0.4667297, 0.2651349, 0.7941239, 0.782783, 0.01870947, 0.2772949, 0.008545014, 0.1708219, 0.3550333, 0.239455, 0.3003783, 0.2502883, 0.7356557, 0.6204092, 0.1454039, 0.2910956, 0.09259536, 0.5196652, 0.2838468, 0.06632939, 0.1611899, 0.3349858, 0.1828278, 0.998065, 0.2499865, 0.3866357, 0.02725202, 0.252886, 0.03562421, 0.1845115 }; assertEquals(exp_preds.length,mu.length()); for(int i = 0; i < mu.length(); ++i) assertEquals(exp_preds[i],mu.at(i),1e-4); // test that it throws with categoricals fr.delete(); fr = getFrameForFile(parsed, "smalldata/glm_test/prostate_cat_replaced.csv", new String[]{"ID"}, "CAPSULE"); try { new GLM2("GLM offset test on prostate.", Key.make(), modelKey, new GLM2.Source(fr, fr.vec("CAPSULE"), false,false), Family.binomial).doInit().fork().get(); assertTrue("should've thrown",false); } catch(IllegalArgumentException iae){} } finally { fr.delete(); if(model != null)model.delete(); } } private static Frame getFrameForFile(Key outputKey, String path,String [] ignores, String response){ File f = TestUtil.find_test_file(path); Key k = NFSFileVec.make(f); Frame fr = ParseDataset2.parse(outputKey, new Key[]{k}); if(ignores != null) for(String s:ignores) UKV.remove(fr.remove(s)._key); // put the response to the end fr.add(response, fr.remove(response)); return fr; } public static void main(String [] args) throws Exception{ System.out.println("Running ParserTest2"); final int nnodes = 1; for( int i = 1; i < nnodes; i++ ) { Node n = new NodeVM(args); n.inheritIO(); n.start(); } H2O.waitForCloudSize(nnodes); System.out.println("Running..."); new GLMTest2().testGaussianRegression(); new GLMTest2().testPoissonRegression(); new GLMTest2().testGammaRegression(); new GLMTest2().testTweedieRegression(); new GLMTest2().testProstate(); new GLMTest2().testCars(); System.out.println("DONE!"); } }
package com.mikepenz.unsplash.models; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; public class Image implements Serializable { private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); private String color; private String image_src; private String author; private Date date; private Date modified_date; private float ratio; private int width; private int height; public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getHighResImage() { return image_src + "?q=100&fm=jpg"; } public String getImage_src() { return image_src + "?q=75&w=720&fit=max&fm=jpg"; } public void setImage_src(String image_src) { this.image_src = image_src; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Date getDate() { return date; } public String getReadableDate() { return sdf.format(date); } public void setDate(Date date) { this.date = date; } public Date getModified_date() { return modified_date; } public String getReadableModified_Date() { return sdf.format(modified_date); } public void setModified_date(Date modified_date) { this.modified_date = modified_date; } public float getRatio() { return ratio; } public void setRatio(float ratio) { this.ratio = ratio; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } }
package com.google.maps.android.utils.demo.model; import com.google.android.gms.maps.model.LatLng; import com.google.maps.android.clustering.ClusterItem; public class MyItem implements ClusterItem { private final LatLng mPosition; public MyItem(double lat, double lng) { mPosition = new LatLng(lat, lng); } @Override public LatLng getPosition() { return mPosition; } }
package org.jetel.ctl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; 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.Properties; import java.util.Set; import java.util.TimeZone; import junit.framework.AssertionFailedError; import org.jetel.component.CTLRecordTransform; import org.jetel.component.RecordTransform; import org.jetel.data.DataField; import org.jetel.data.DataRecord; import org.jetel.data.DataRecordFactory; import org.jetel.data.SetVal; import org.jetel.data.lookup.LookupTable; import org.jetel.data.lookup.LookupTableFactory; import org.jetel.data.primitive.Decimal; import org.jetel.data.sequence.Sequence; import org.jetel.data.sequence.SequenceFactory; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.TransformException; import org.jetel.graph.ContextProvider; import org.jetel.graph.ContextProvider.Context; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataFieldContainerType; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataFieldType; import org.jetel.metadata.DataRecordMetadata; import org.jetel.test.CloverTestCase; import org.jetel.util.MiscUtils; import org.jetel.util.bytes.PackedDecimal; import org.jetel.util.crypto.Base64; import org.jetel.util.crypto.Digest; import org.jetel.util.crypto.Digest.DigestType; import org.jetel.util.primitive.TypedProperties; import org.jetel.util.string.StringUtils; import org.joda.time.DateTime; import org.joda.time.Years; public abstract class CompilerTestCase extends CloverTestCase { protected static final String INPUT_1 = "firstInput"; protected static final String INPUT_2 = "secondInput"; protected static final String INPUT_3 = "thirdInput"; protected static final String INPUT_4 = "multivalueInput"; protected static final String OUTPUT_1 = "firstOutput"; protected static final String OUTPUT_2 = "secondOutput"; protected static final String OUTPUT_3 = "thirdOutput"; protected static final String OUTPUT_4 = "fourthOutput"; protected static final String OUTPUT_5 = "firstMultivalueOutput"; protected static final String OUTPUT_6 = "secondMultivalueOutput"; protected static final String OUTPUT_7 = "thirdMultivalueOutput"; protected static final String LOOKUP = "lookupMetadata"; protected static final String NAME_VALUE = " HELLO "; protected static final Double AGE_VALUE = 20.25; protected static final String CITY_VALUE = "Chong'La"; protected static final Date BORN_VALUE; protected static final Long BORN_MILLISEC_VALUE; static { Calendar c = Calendar.getInstance(); c.set(2008, 12, 25, 13, 25, 55); c.set(Calendar.MILLISECOND, 333); BORN_VALUE = c.getTime(); BORN_MILLISEC_VALUE = c.getTimeInMillis(); } protected static final Integer VALUE_VALUE = Integer.MAX_VALUE - 10; protected static final Boolean FLAG_VALUE = true; protected static final byte[] BYTEARRAY_VALUE = "Abeceda zedla deda".getBytes(); protected static final BigDecimal CURRENCY_VALUE = new BigDecimal("133.525"); protected static final int DECIMAL_PRECISION = 7; protected static final int DECIMAL_SCALE = 3; protected static final int NORMALIZE_RETURN_OK = 0; public static final int DECIMAL_MAX_PRECISION = 32; public static final MathContext MAX_PRECISION = new MathContext(DECIMAL_MAX_PRECISION,RoundingMode.DOWN); /** Flag to trigger Java compilation */ private boolean compileToJava; protected DataRecord[] inputRecords; protected DataRecord[] outputRecords; protected TransformationGraph graph; public CompilerTestCase(boolean compileToJava) { this.compileToJava = compileToJava; } /** * Method to execute tested CTL code in a way specific to testing scenario. * * Assumes that * {@link #graph}, {@link #inputRecords} and {@link #outputRecords} * have already been set. * * @param compiler */ public abstract void executeCode(ITLCompiler compiler); /** * Method which provides access to specified global variable * * @param varName * global variable to be accessed * @return * */ protected abstract Object getVariable(String varName); protected void check(String varName, Object expectedResult) { assertEquals(varName, expectedResult, getVariable(varName)); } protected void checkEquals(String varName1, String varName2) { assertEquals("Comparing " + varName1 + " and " + varName2 + " : ", getVariable(varName1), getVariable(varName2)); } protected void checkNull(String varName) { assertNull(getVariable(varName)); } private void checkArray(String varName, byte[] expected) { byte[] actual = (byte[]) getVariable(varName); assertTrue("Arrays do not match; expected: " + byteArrayAsString(expected) + " but was " + byteArrayAsString(actual), Arrays.equals(actual, expected)); } private static String byteArrayAsString(byte[] array) { final StringBuilder sb = new StringBuilder("["); for (final byte b : array) { sb.append(b); sb.append(", "); } sb.delete(sb.length() - 2, sb.length()); sb.append(']'); return sb.toString(); } @Override protected void setUp() { // set default locale to English to prevent various parsing errors Locale.setDefault(Locale.ENGLISH); initEngine(); } @Override protected void tearDown() throws Exception { super.tearDown(); inputRecords = null; outputRecords = null; graph = null; } protected TransformationGraph createEmptyGraph() { return new TransformationGraph(); } protected TransformationGraph createDefaultGraph() { TransformationGraph g = createEmptyGraph(); final HashMap<String, DataRecordMetadata> metadataMap = new HashMap<String, DataRecordMetadata>(); metadataMap.put(INPUT_1, createDefaultMetadata(INPUT_1)); metadataMap.put(INPUT_2, createDefaultMetadata(INPUT_2)); metadataMap.put(INPUT_3, createDefaultMetadata(INPUT_3)); metadataMap.put(INPUT_4, createDefaultMultivalueMetadata(INPUT_4)); metadataMap.put(OUTPUT_1, createDefaultMetadata(OUTPUT_1)); metadataMap.put(OUTPUT_2, createDefaultMetadata(OUTPUT_2)); metadataMap.put(OUTPUT_3, createDefaultMetadata(OUTPUT_3)); metadataMap.put(OUTPUT_4, createDefault1Metadata(OUTPUT_4)); metadataMap.put(OUTPUT_5, createDefaultMultivalueMetadata(OUTPUT_5)); metadataMap.put(OUTPUT_6, createDefaultMultivalueMetadata(OUTPUT_6)); metadataMap.put(OUTPUT_7, createDefaultMultivalueMetadata(OUTPUT_7)); metadataMap.put(LOOKUP, createDefaultMetadata(LOOKUP)); g.addDataRecordMetadata(metadataMap); g.addSequence(createDefaultSequence(g, "TestSequence")); g.addLookupTable(createDefaultLookup(g, "TestLookup")); Properties properties = new Properties(); properties.put("PROJECT", "."); properties.put("DATAIN_DIR", "${PROJECT}/data-in"); properties.put("COUNT", "`1+2`"); properties.put("NEWLINE", "\\n"); g.setGraphProperties(properties); initDefaultDictionary(g); return g; } private void initDefaultDictionary(TransformationGraph g) { try { g.getDictionary().init(); g.getDictionary().setValue("s", "string", null); g.getDictionary().setValue("i", "integer", null); g.getDictionary().setValue("l", "long", null); g.getDictionary().setValue("d", "decimal", null); g.getDictionary().setValue("n", "number", null); g.getDictionary().setValue("a", "date", null); g.getDictionary().setValue("b", "boolean", null); g.getDictionary().setValue("y", "byte", null); g.getDictionary().setValue("i211", "integer", new Integer(211)); g.getDictionary().setValue("sVerdon", "string", "Verdon"); g.getDictionary().setValue("l452", "long", new Long(452)); g.getDictionary().setValue("d621", "decimal", new BigDecimal(621)); g.getDictionary().setValue("n9342", "number", new Double(934.2)); g.getDictionary().setValue("a1992", "date", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime()); g.getDictionary().setValue("bTrue", "boolean", Boolean.TRUE); g.getDictionary().setValue("yFib", "byte", new byte[]{1,2,3,5,8,13,21,34,55,89} ); g.getDictionary().setValue("stringList", "list", Arrays.asList("aa", "bb", null, "cc")); g.getDictionary().setContentType("stringList", "string"); g.getDictionary().setValue("dateList", "list", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000))); g.getDictionary().setContentType("dateList", "date"); g.getDictionary().setValue("byteList", "list", Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78})); g.getDictionary().setContentType("byteList", "byte"); } catch (ComponentNotReadyException e) { throw new RuntimeException("Error init default dictionary", e); } } protected Sequence createDefaultSequence(TransformationGraph graph, String name) { Sequence seq = SequenceFactory.createSequence(graph, "PRIMITIVE_SEQUENCE", new Object[] { "Sequence0", graph, name }, new Class[] { String.class, TransformationGraph.class, String.class }); try { seq.checkConfig(new ConfigurationStatus()); seq.init(); } catch (ComponentNotReadyException e) { throw new RuntimeException(e); } return seq; } /** * Creates default lookup table of type SimpleLookupTable with 4 records using default metadata and a composite * lookup key Name+Value. Use field City for testing response. * * @param graph * @param name * @return */ protected LookupTable createDefaultLookup(TransformationGraph graph, String name) { final TypedProperties props = new TypedProperties(); props.setProperty("id", "LookupTable0"); props.setProperty("type", "simpleLookup"); props.setProperty("metadata", LOOKUP); props.setProperty("key", "Name;Value"); props.setProperty("name", name); props.setProperty("keyDuplicates", "true"); /* * The test lookup table is populated from file TestLookup.dat. Alternatively uncomment the populating code * below, however this will most probably break down test_lookup() because free() will wipe away all data and * noone will restore them */ URL dataFile = getClass().getSuperclass().getResource("TestLookup.dat"); if (dataFile == null) { throw new RuntimeException("Unable to populate testing lookup table. File 'TestLookup.dat' not found by classloader"); } props.setProperty("fileURL", dataFile.getFile()); LookupTableFactory.init(); LookupTable lkp = LookupTableFactory.createLookupTable(props); lkp.setGraph(graph); try { lkp.checkConfig(new ConfigurationStatus()); lkp.init(); lkp.preExecute(); } catch (ComponentNotReadyException ex) { throw new RuntimeException(ex); } /*DataRecord lkpRecord = createEmptyRecord(createDefaultMetadata("lookupResponse")); lkpRecord.getField("Name").setValue("Alpha"); lkpRecord.getField("Value").setValue(1); lkpRecord.getField("City").setValue("Andorra la Vella"); lkp.put(lkpRecord); lkpRecord.getField("Name").setValue("Bravo"); lkpRecord.getField("Value").setValue(2); lkpRecord.getField("City").setValue("Bruxelles"); lkp.put(lkpRecord); // duplicate entry lkpRecord.getField("Name").setValue("Charlie"); lkpRecord.getField("Value").setValue(3); lkpRecord.getField("City").setValue("Chamonix"); lkp.put(lkpRecord); lkpRecord.getField("Name").setValue("Charlie"); lkpRecord.getField("Value").setValue(3); lkpRecord.getField("City").setValue("Chomutov"); lkp.put(lkpRecord);*/ return lkp; } /** * Creates records with default structure * * @param name * name for the record to use * @return metadata with default structure */ protected DataRecordMetadata createDefaultMetadata(String name) { DataRecordMetadata ret = new DataRecordMetadata(name); ret.addField(new DataFieldMetadata("Name", DataFieldType.STRING, "|")); ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|")); ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|")); DataFieldMetadata dateField = new DataFieldMetadata("Born", DataFieldType.DATE, "|"); dateField.setFormatStr("yyyy-MM-dd HH:mm:ss"); ret.addField(dateField); ret.addField(new DataFieldMetadata("BornMillisec", DataFieldType.LONG, "|")); ret.addField(new DataFieldMetadata("Value", DataFieldType.INTEGER, "|")); ret.addField(new DataFieldMetadata("Flag", DataFieldType.BOOLEAN, "|")); ret.addField(new DataFieldMetadata("ByteArray", DataFieldType.BYTE, "|")); DataFieldMetadata decimalField = new DataFieldMetadata("Currency", DataFieldType.DECIMAL, "\n"); decimalField.setProperty(DataFieldMetadata.LENGTH_ATTR, String.valueOf(DECIMAL_PRECISION)); decimalField.setProperty(DataFieldMetadata.SCALE_ATTR, String.valueOf(DECIMAL_SCALE)); ret.addField(decimalField); return ret; } /** * Creates records with default structure * * @param name * name for the record to use * @return metadata with default structure */ protected DataRecordMetadata createDefault1Metadata(String name) { DataRecordMetadata ret = new DataRecordMetadata(name); ret.addField(new DataFieldMetadata("Field1", DataFieldType.STRING, "|")); ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|")); ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|")); return ret; } /** * Creates records with default structure * containing multivalue fields. * * @param name * name for the record to use * @return metadata with default structure */ protected DataRecordMetadata createDefaultMultivalueMetadata(String name) { DataRecordMetadata ret = new DataRecordMetadata(name); DataFieldMetadata stringListField = new DataFieldMetadata("stringListField", DataFieldType.STRING, "|"); stringListField.setContainerType(DataFieldContainerType.LIST); ret.addField(stringListField); DataFieldMetadata dateField = new DataFieldMetadata("dateField", DataFieldType.DATE, "|"); ret.addField(dateField); DataFieldMetadata byteField = new DataFieldMetadata("byteField", DataFieldType.BYTE, "|"); ret.addField(byteField); DataFieldMetadata dateListField = new DataFieldMetadata("dateListField", DataFieldType.DATE, "|"); dateListField.setContainerType(DataFieldContainerType.LIST); ret.addField(dateListField); DataFieldMetadata byteListField = new DataFieldMetadata("byteListField", DataFieldType.BYTE, "|"); byteListField.setContainerType(DataFieldContainerType.LIST); ret.addField(byteListField); DataFieldMetadata stringField = new DataFieldMetadata("stringField", DataFieldType.STRING, "|"); ret.addField(stringField); DataFieldMetadata integerMapField = new DataFieldMetadata("integerMapField", DataFieldType.INTEGER, "|"); integerMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(integerMapField); DataFieldMetadata stringMapField = new DataFieldMetadata("stringMapField", DataFieldType.STRING, "|"); stringMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(stringMapField); DataFieldMetadata dateMapField = new DataFieldMetadata("dateMapField", DataFieldType.DATE, "|"); dateMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(dateMapField); DataFieldMetadata byteMapField = new DataFieldMetadata("byteMapField", DataFieldType.BYTE, "|"); byteMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(byteMapField); DataFieldMetadata integerListField = new DataFieldMetadata("integerListField", DataFieldType.INTEGER, "|"); integerListField.setContainerType(DataFieldContainerType.LIST); ret.addField(integerListField); DataFieldMetadata decimalListField = new DataFieldMetadata("decimalListField", DataFieldType.DECIMAL, "|"); decimalListField.setContainerType(DataFieldContainerType.LIST); ret.addField(decimalListField); DataFieldMetadata decimalMapField = new DataFieldMetadata("decimalMapField", DataFieldType.DECIMAL, "|"); decimalMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(decimalMapField); return ret; } protected DataRecord createDefaultMultivalueRecord(DataRecordMetadata dataRecordMetadata) { final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata); ret.init(); for (int i = 0; i < ret.getNumFields(); i++) { DataField field = ret.getField(i); DataFieldMetadata fieldMetadata = field.getMetadata(); switch (fieldMetadata.getContainerType()) { case SINGLE: switch (fieldMetadata.getDataType()) { case STRING: field.setValue("John"); break; case DATE: field.setValue(new Date(10000)); break; case BYTE: field.setValue(new byte[] { 0x12, 0x34, 0x56, 0x78 } ); break; default: throw new UnsupportedOperationException("Not implemented."); } break; case LIST: { List<Object> value = new ArrayList<Object>(); switch (fieldMetadata.getDataType()) { case STRING: value.addAll(Arrays.asList("John", "Doe", "Jersey")); break; case INTEGER: value.addAll(Arrays.asList(123, 456, 789)); break; case DATE: value.addAll(Arrays.asList(new Date (12000), new Date(34000))); break; case BYTE: value.addAll(Arrays.asList(new byte[] {0x12, 0x34}, new byte[] {0x56, 0x78})); break; case DECIMAL: value.addAll(Arrays.asList(12.34, 56.78)); break; default: throw new UnsupportedOperationException("Not implemented."); } field.setValue(value); } break; case MAP: { Map<String, Object> value = new HashMap<String, Object>(); switch (fieldMetadata.getDataType()) { case STRING: value.put("firstName", "John"); value.put("lastName", "Doe"); value.put("address", "Jersey"); break; case INTEGER: value.put("count", 123); value.put("max", 456); value.put("sum", 789); break; case DATE: value.put("before", new Date (12000)); value.put("after", new Date(34000)); break; case BYTE: value.put("hash", new byte[] {0x12, 0x34}); value.put("checksum", new byte[] {0x56, 0x78}); break; case DECIMAL: value.put("asset", 12.34); value.put("liability", 56.78); break; default: throw new UnsupportedOperationException("Not implemented."); } field.setValue(value); } break; default: throw new IllegalArgumentException(fieldMetadata.getContainerType().toString()); } } return ret; } protected DataRecord createDefaultRecord(DataRecordMetadata dataRecordMetadata) { final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata); ret.init(); SetVal.setString(ret, "Name", NAME_VALUE); SetVal.setDouble(ret, "Age", AGE_VALUE); SetVal.setString(ret, "City", CITY_VALUE); SetVal.setDate(ret, "Born", BORN_VALUE); SetVal.setLong(ret, "BornMillisec", BORN_MILLISEC_VALUE); SetVal.setInt(ret, "Value", VALUE_VALUE); SetVal.setValue(ret, "Flag", FLAG_VALUE); SetVal.setValue(ret, "ByteArray", BYTEARRAY_VALUE); SetVal.setValue(ret, "Currency", CURRENCY_VALUE); return ret; } /** * Allocates new records with structure prescribed by metadata and sets all its fields to <code>null</code> * * @param metadata * structure to use * @return empty record */ protected DataRecord createEmptyRecord(DataRecordMetadata metadata) { DataRecord ret = DataRecordFactory.newRecord(metadata); ret.init(); for (int i = 0; i < ret.getNumFields(); i++) { SetVal.setNull(ret, i); } return ret; } /** * Executes the code using the default graph and records. */ protected void doCompile(String expStr, String testIdentifier) { TransformationGraph graph = createDefaultGraph(); DataRecord[] inRecords = new DataRecord[] { createDefaultRecord(graph.getDataRecordMetadata(INPUT_1)), createDefaultRecord(graph.getDataRecordMetadata(INPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(INPUT_3)), createDefaultMultivalueRecord(graph.getDataRecordMetadata(INPUT_4)) }; DataRecord[] outRecords = new DataRecord[] { createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_1)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_3)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_4)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_5)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_6)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_7)) }; doCompile(expStr, testIdentifier, graph, inRecords, outRecords); } /** * This method should be used to execute a test with a custom graph and custom input and output records. * * To execute a test with the default graph, * use {@link #doCompile(String)} * or {@link #doCompile(String, String)} instead. * * @param expStr * @param testIdentifier * @param graph * @param inRecords * @param outRecords */ protected void doCompile(String expStr, String testIdentifier, TransformationGraph graph, DataRecord[] inRecords, DataRecord[] outRecords) { this.graph = graph; this.inputRecords = inRecords; this.outputRecords = outRecords; // prepend the compilation mode prefix if (compileToJava) { expStr = "//#CTL2:COMPILE\n" + expStr; } print_code(expStr); DataRecordMetadata[] inMetadata = new DataRecordMetadata[inRecords.length]; for (int i = 0; i < inRecords.length; i++) { inMetadata[i] = inRecords[i].getMetadata(); } DataRecordMetadata[] outMetadata = new DataRecordMetadata[outRecords.length]; for (int i = 0; i < outRecords.length; i++) { outMetadata[i] = outRecords[i].getMetadata(); } ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8"); // try { // System.out.println(compiler.convertToJava(expStr, CTLRecordTransform.class, testIdentifier)); // } catch (ErrorMessageException e) { // System.out.println("Error parsing CTL code. Unable to output Java translation."); List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier); printMessages(messages); if (compiler.errorCount() > 0) { throw new AssertionFailedError("Error in execution. Check standard output for details."); } // CLVFStart parseTree = compiler.getStart(); // parseTree.dump(""); executeCode(compiler); } protected void doCompileExpectError(String expStr, String testIdentifier, List<String> errCodes) { graph = createDefaultGraph(); DataRecordMetadata[] inMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(INPUT_1), graph.getDataRecordMetadata(INPUT_2), graph.getDataRecordMetadata(INPUT_3) }; DataRecordMetadata[] outMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(OUTPUT_1), graph.getDataRecordMetadata(OUTPUT_2), graph.getDataRecordMetadata(OUTPUT_3), graph.getDataRecordMetadata(OUTPUT_4) }; // prepend the compilation mode prefix if (compileToJava) { expStr = "//#CTL2:COMPILE\n" + expStr; } print_code(expStr); ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8"); List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier); printMessages(messages); if (compiler.errorCount() == 0) { throw new AssertionFailedError("No errors in parsing. Expected " + errCodes.size() + " errors."); } if (compiler.errorCount() != errCodes.size()) { throw new AssertionFailedError(compiler.errorCount() + " errors in code, but expected " + errCodes.size() + " errors."); } Iterator<String> it = errCodes.iterator(); for (ErrorMessage errorMessage : compiler.getDiagnosticMessages()) { String expectedError = it.next(); if (!expectedError.equals(errorMessage.getErrorMessage())) { throw new AssertionFailedError("Error : \'" + compiler.getDiagnosticMessages().get(0).getErrorMessage() + "\', but expected: \'" + expectedError + "\'"); } } // CLVFStart parseTree = compiler.getStart(); // parseTree.dump(""); // executeCode(compiler); } protected void doCompileExpectError(String testIdentifier, String errCode) { doCompileExpectErrors(testIdentifier, Arrays.asList(errCode)); } protected void doCompileExpectErrors(String testIdentifier, List<String> errCodes) { URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl"); if (importLoc == null) { throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found"); } final StringBuilder sourceCode = new StringBuilder(); String line = null; try { BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream())); while ((line = rd.readLine()) != null) { sourceCode.append(line).append("\n"); } rd.close(); } catch (IOException e) { throw new RuntimeException("I/O error occured when reading source file", e); } doCompileExpectError(sourceCode.toString(), testIdentifier, errCodes); } /** * Method loads tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should * be stored in the same directory as this class. * * @param Test * identifier defining CTL file to load code from */ protected String loadSourceCode(String testIdentifier) { URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl"); if (importLoc == null) { throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found"); } final StringBuilder sourceCode = new StringBuilder(); String line = null; try { BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream())); while ((line = rd.readLine()) != null) { sourceCode.append(line).append("\n"); } rd.close(); } catch (IOException e) { throw new RuntimeException("I/O error occured when reading source file", e); } return sourceCode.toString(); } /** * Method loads and compiles tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should * be stored in the same directory as this class. * * The default graph and records are used for the execution. * * @param Test * identifier defining CTL file to load code from */ protected void doCompile(String testIdentifier) { String sourceCode = loadSourceCode(testIdentifier); doCompile(sourceCode, testIdentifier); } protected void printMessages(List<ErrorMessage> diagnosticMessages) { for (ErrorMessage e : diagnosticMessages) { System.out.println(e); } } /** * Compares two records if they have the same number of fields and identical values in their fields. Does not * consider (or examine) metadata. * * @param lhs * @param rhs * @return true if records have the same number of fields and the same values in them */ protected static boolean recordEquals(DataRecord lhs, DataRecord rhs) { if (lhs == rhs) return true; if (rhs == null) return false; if (lhs == null) { return false; } if (lhs.getNumFields() != rhs.getNumFields()) { return false; } for (int i = 0; i < lhs.getNumFields(); i++) { if (lhs.getField(i).isNull()) { if (!rhs.getField(i).isNull()) { return false; } } else if (!lhs.getField(i).equals(rhs.getField(i))) { return false; } } return true; } public void print_code(String text) { String[] lines = text.split("\n"); System.out.println("\t: 1 2 3 4 5 "); System.out.println("\t:12345678901234567890123456789012345678901234567890123456789"); for (int i = 0; i < lines.length; i++) { System.out.println((i + 1) + "\t:" + lines[i]); } } @SuppressWarnings("unchecked") public void test_operators_unary_record_allowed() { doCompile("test_operators_unary_record_allowed"); check("value", Arrays.asList(14, 16, 16, 65, 63, 63)); check("bornMillisec", Arrays.asList(14L, 16L, 16L, 65L, 63L, 63L)); List<Double> actualAge = (List<Double>) getVariable("age"); double[] expectedAge = {14.123, 16.123, 16.123, 65.789, 63.789, 63.789}; for (int i = 0; i < actualAge.size(); i++) { assertEquals("age[" + i + "]", expectedAge[i], actualAge.get(i), 0.0001); } check("currency", Arrays.asList( new BigDecimal(BigInteger.valueOf(12500), 3), new BigDecimal(BigInteger.valueOf(14500), 3), new BigDecimal(BigInteger.valueOf(14500), 3), new BigDecimal(BigInteger.valueOf(65432), 3), new BigDecimal(BigInteger.valueOf(63432), 3), new BigDecimal(BigInteger.valueOf(63432), 3) )); } @SuppressWarnings("unchecked") public void test_dynamic_compare() { doCompile("test_dynamic_compare"); String varName = "compare"; List<Integer> compareResult = (List<Integer>) getVariable(varName); for (int i = 0; i < compareResult.size(); i++) { if ((i % 3) == 0) { assertTrue(varName + "[" + i + "]", compareResult.get(i) > 0); } else if ((i % 3) == 1) { assertEquals(varName + "[" + i + "]", Integer.valueOf(0), compareResult.get(i)); } else if ((i % 3) == 2) { assertTrue(varName + "[" + i + "]", compareResult.get(i) < 0); } } varName = "compareBooleans"; compareResult = (List<Integer>) getVariable(varName); assertEquals(varName + "[0]", Integer.valueOf(0), compareResult.get(0)); assertTrue(varName + "[1]", compareResult.get(1) > 0); assertTrue(varName + "[2]", compareResult.get(2) < 0); assertEquals(varName + "[3]", Integer.valueOf(0), compareResult.get(3)); } private void test_dynamic_get_set_loop(String testIdentifier) { doCompile(testIdentifier); check("recordLength", 9); check("value", Arrays.asList(654321, 777777, 654321, 654323, 123456, 112567, 112233)); check("type", Arrays.asList("string", "number", "string", "date", "long", "integer", "boolean", "byte", "decimal")); check("asString", Arrays.asList("1000", "1001.0", "1002", "Thu Jan 01 01:00:01 CET 1970", "1004", "1005", "true", null, "1008.000")); check("isNull", Arrays.asList(false, false, false, false, false, false, false, true, false)); check("fieldName", Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency")); Integer[] indices = new Integer[9]; for (int i = 0; i < indices.length; i++) { indices[i] = i; } check("fieldIndex", Arrays.asList(indices)); // check dynamic write and read with all data types check("booleanVar", true); assertTrue("byteVar", Arrays.equals(new BigInteger("1234567890abcdef", 16).toByteArray(), (byte[]) getVariable("byteVar"))); check("decimalVar", new BigDecimal(BigInteger.valueOf(1000125), 3)); check("integerVar", 1000); check("longVar", 1000000000000L); check("numberVar", 1000.5); check("stringVar", "hello"); check("dateVar", new Date(5000)); } public void test_dynamic_get_set_loop() { test_dynamic_get_set_loop("test_dynamic_get_set_loop"); } public void test_dynamic_get_set_loop_alternative() { test_dynamic_get_set_loop("test_dynamic_get_set_loop_alternative"); } public void test_dynamic_invalid() { doCompileExpectErrors("test_dynamic_invalid", Arrays.asList( "Input record cannot be assigned to", "Input record cannot be assigned to" )); } public void test_return_constants() { // test case for issue 2257 System.out.println("Return constants test:"); doCompile("test_return_constants"); check("skip", RecordTransform.SKIP); check("all", RecordTransform.ALL); check("ok", NORMALIZE_RETURN_OK); } public void test_raise_error_terminal() { // test case for issue 2337 doCompile("test_raise_error_terminal"); } public void test_raise_error_nonliteral() { // test case for issue CL-2071 doCompile("test_raise_error_nonliteral"); } public void test_case_unique_check() { // test case for issue 2515 doCompileExpectErrors("test_case_unique_check", Arrays.asList("Duplicate case", "Duplicate case")); } public void test_case_unique_check2() { // test case for issue 2515 doCompileExpectErrors("test_case_unique_check2", Arrays.asList("Duplicate case", "Duplicate case")); } public void test_case_unique_check3() { doCompileExpectError("test_case_unique_check3", "Default case is already defined"); } public void test_rvalue_for_append() { // test case for issue 3956 doCompile("test_rvalue_for_append"); check("a", Arrays.asList("1", "2")); check("b", Arrays.asList("a", "b", "c")); check("c", Arrays.asList("1", "2", "a", "b", "c")); } public void test_rvalue_for_map_append() { // test case for issue 3960 doCompile("test_rvalue_for_map_append"); HashMap<Integer, String> map1instance = new HashMap<Integer, String>(); map1instance.put(1, "a"); map1instance.put(2, "b"); HashMap<Integer, String> map2instance = new HashMap<Integer, String>(); map2instance.put(3, "c"); map2instance.put(4, "d"); HashMap<Integer, String> map3instance = new HashMap<Integer, String>(); map3instance.put(1, "a"); map3instance.put(2, "b"); map3instance.put(3, "c"); map3instance.put(4, "d"); check("map1", map1instance); check("map2", map2instance); check("map3", map3instance); } public void test_global_field_access() { // test case for issue 3957 doCompileExpectError("test_global_field_access", "Unable to access record field in global scope"); } public void test_global_scope() { // test case for issue 5006 doCompile("test_global_scope"); check("len", "Kokon".length()); } //TODO Implement /*public void test_new() { doCompile("test_new"); }*/ public void test_parser() { System.out.println("\nParser test:"); doCompile("test_parser"); } public void test_ref_res_import() { System.out.println("\nSpecial character resolving (import) test:"); URL importLoc = getClass().getSuperclass().getResource("test_ref_res.ctl"); String expStr = "import '" + importLoc + "';\n"; doCompile(expStr, "test_ref_res_import"); } public void test_ref_res_noimport() { System.out.println("\nSpecial character resolving (no import) test:"); doCompile("test_ref_res"); } public void test_import() { System.out.println("\nImport test:"); URL importLoc = getClass().getSuperclass().getResource("import.ctl"); String expStr = "import '" + importLoc + "';\n"; importLoc = getClass().getSuperclass().getResource("other.ctl"); expStr += "import '" + importLoc + "';\n" + "integer sumInt;\n" + "function integer transform() {\n" + " if (a == 3) {\n" + " otherImportVar++;\n" + " }\n" + " sumInt = sum(a, otherImportVar);\n" + " return 0;\n" + "}\n"; doCompile(expStr, "test_import"); } public void test_scope() throws ComponentNotReadyException, TransformException { System.out.println("\nMapping test:"); // String expStr = // "function string computeSomething(int n) {\n" + // " string s = '';\n" + // " do {\n" + // " int i = n--;\n" + // " s = s + '-' + i;\n" + // " } while (n > 0)\n" + // " return s;" + // "function int transform() {\n" + // " printErr(computeSomething(10));\n" + // " return 0;\n" + URL importLoc = getClass().getSuperclass().getResource("samplecode.ctl"); String expStr = "import '" + importLoc + "';\n"; // "function int getIndexOfOffsetStart(string encodedDate) {\n" + // "int offsetStart;\n" + // "int actualLastMinus;\n" + // "int lastMinus = -1;\n" + // "if ( index_of(encodedDate, '+') != -1 )\n" + // " return index_of(encodedDate, '+');\n" + // "do {\n" + // " actualLastMinus = index_of(encodedDate, '-', lastMinus+1);\n" + // " if ( actualLastMinus != -1 )\n" + // " lastMinus = actualLastMinus;\n" + // "} while ( actualLastMinus != -1 )\n" + // "return lastMinus;\n" + // "function int transform() {\n" + // " getIndexOfOffsetStart('2009-04-24T08:00:00-05:00');\n" + // " return 0;\n" + doCompile(expStr, "test_scope"); } public void test_type_void() { doCompileExpectErrors("test_type_void", Arrays.asList("Syntax error on token 'void'", "Variable 'voidVar' is not declared", "Variable 'voidVar' is not declared", "Syntax error on token 'void'")); } public void test_type_integer() { doCompile("test_type_integer"); check("i", 0); check("j", -1); check("field", VALUE_VALUE); checkNull("nullValue"); check("varWithInitializer", 123); checkNull("varWithNullInitializer"); } public void test_type_integer_edge() { String testExpression = "integer minInt;\n"+ "integer maxInt;\n"+ "function integer transform() {\n" + "minInt=" + Integer.MIN_VALUE + ";\n" + "printErr(minInt, true);\n" + "maxInt=" + Integer.MAX_VALUE + ";\n" + "printErr(maxInt, true);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_int_edge"); check("minInt", Integer.MIN_VALUE); check("maxInt", Integer.MAX_VALUE); } public void test_type_long() { doCompile("test_type_long"); check("i", Long.valueOf(0)); check("j", Long.valueOf(-1)); check("field", BORN_MILLISEC_VALUE); check("def", Long.valueOf(0)); checkNull("nullValue"); check("varWithInitializer", 123L); checkNull("varWithNullInitializer"); } public void test_type_long_edge() { String expStr = "long minLong;\n"+ "long maxLong;\n"+ "function integer transform() {\n" + "minLong=" + (Long.MIN_VALUE) + "L;\n" + "printErr(minLong);\n" + "maxLong=" + (Long.MAX_VALUE) + "L;\n" + "printErr(maxLong);\n" + "return 0;\n" + "}\n"; doCompile(expStr,"test_long_edge"); check("minLong", Long.MIN_VALUE); check("maxLong", Long.MAX_VALUE); } public void test_type_decimal() { doCompile("test_type_decimal"); check("i", new BigDecimal(0, MAX_PRECISION)); check("j", new BigDecimal(-1, MAX_PRECISION)); check("field", CURRENCY_VALUE); check("def", new BigDecimal(0, MAX_PRECISION)); checkNull("nullValue"); check("varWithInitializer", new BigDecimal("123.35", MAX_PRECISION)); checkNull("varWithNullInitializer"); check("varWithInitializerNoDist", new BigDecimal(123.35, MAX_PRECISION)); } public void test_type_decimal_edge() { String testExpression = "decimal minLong;\n"+ "decimal maxLong;\n"+ "decimal minLongNoDist;\n"+ "decimal maxLongNoDist;\n"+ "decimal minDouble;\n"+ "decimal maxDouble;\n"+ "decimal minDoubleNoDist;\n"+ "decimal maxDoubleNoDist;\n"+ "function integer transform() {\n" + "minLong=" + String.valueOf(Long.MIN_VALUE) + "d;\n" + "printErr(minLong);\n" + "maxLong=" + String.valueOf(Long.MAX_VALUE) + "d;\n" + "printErr(maxLong);\n" + "minLongNoDist=" + String.valueOf(Long.MIN_VALUE) + "L;\n" + "printErr(minLongNoDist);\n" + "maxLongNoDist=" + String.valueOf(Long.MAX_VALUE) + "L;\n" + "printErr(maxLongNoDist);\n" + // distincter will cause the double-string be parsed into exact representation within BigDecimal "minDouble=" + String.valueOf(Double.MIN_VALUE) + "D;\n" + "printErr(minDouble);\n" + "maxDouble=" + String.valueOf(Double.MAX_VALUE) + "D;\n" + "printErr(maxDouble);\n" + // no distincter will cause the double-string to be parsed into inexact representation within double // then to be assigned into BigDecimal (which will extract only MAX_PRECISION digits) "minDoubleNoDist=" + String.valueOf(Double.MIN_VALUE) + ";\n" + "printErr(minDoubleNoDist);\n" + "maxDoubleNoDist=" + String.valueOf(Double.MAX_VALUE) + ";\n" + "printErr(maxDoubleNoDist);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_decimal_edge"); check("minLong", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION)); check("maxLong", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION)); check("minLongNoDist", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION)); check("maxLongNoDist", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION)); // distincter will cause the MIN_VALUE to be parsed into exact representation (i.e. 4.9E-324) check("minDouble", new BigDecimal(String.valueOf(Double.MIN_VALUE), MAX_PRECISION)); check("maxDouble", new BigDecimal(String.valueOf(Double.MAX_VALUE), MAX_PRECISION)); // no distincter will cause MIN_VALUE to be parsed into double inexact representation and extraction of // MAX_PRECISION digits (i.e. 4.94065.....E-324) check("minDoubleNoDist", new BigDecimal(Double.MIN_VALUE, MAX_PRECISION)); check("maxDoubleNoDist", new BigDecimal(Double.MAX_VALUE, MAX_PRECISION)); } public void test_type_number() { doCompile("test_type_number"); check("i", Double.valueOf(0)); check("j", Double.valueOf(-1)); check("field", AGE_VALUE); check("def", Double.valueOf(0)); checkNull("nullValue"); checkNull("varWithNullInitializer"); } public void test_type_number_edge() { String testExpression = "number minDouble;\n" + "number maxDouble;\n"+ "function integer transform() {\n" + "minDouble=" + Double.MIN_VALUE + ";\n" + "printErr(minDouble);\n" + "maxDouble=" + Double.MAX_VALUE + ";\n" + "printErr(maxDouble);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_number_edge"); check("minDouble", Double.valueOf(Double.MIN_VALUE)); check("maxDouble", Double.valueOf(Double.MAX_VALUE)); } public void test_type_string() { doCompile("test_type_string"); check("i","0"); check("helloEscaped", "hello\\nworld"); check("helloExpanded", "hello\nworld"); check("fieldName", NAME_VALUE); check("fieldCity", CITY_VALUE); check("escapeChars", "a\u0101\u0102A"); check("doubleEscapeChars", "a\\u0101\\u0102A"); check("specialChars", "špeciálne značky s mäkčeňom môžu byť"); check("dQescapeChars", "a\u0101\u0102A"); //TODO:Is next test correct? check("dQdoubleEscapeChars", "a\\u0101\\u0102A"); check("dQspecialChars", "špeciálne značky s mäkčeňom môžu byť"); check("empty", ""); check("def", ""); checkNull("varWithNullInitializer"); } public void test_type_string_long() { int length = 1000; StringBuilder tmp = new StringBuilder(length); for (int i = 0; i < length; i++) { tmp.append(i % 10); } String testExpression = "string longString;\n" + "function integer transform() {\n" + "longString=\"" + tmp + "\";\n" + "printErr(longString);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_string_long"); check("longString", String.valueOf(tmp)); } public void test_type_date() throws Exception { doCompile("test_type_date"); check("d3", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 1).getTime()); check("d2", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3).getTime()); check("d1", new GregorianCalendar(2006, GregorianCalendar.JANUARY, 1, 1, 2, 3).getTime()); check("field", BORN_VALUE); checkNull("nullValue"); check("minValue", new GregorianCalendar(1970, GregorianCalendar.JANUARY, 1, 1, 0, 0).getTime()); checkNull("varWithNullInitializer"); // test with a default time zone set on the GraphRuntimeContext Context context = null; try { tearDown(); setUp(); TransformationGraph graph = new TransformationGraph(); graph.getRuntimeContext().setTimeZone("GMT+8"); context = ContextProvider.registerGraph(graph); doCompile("test_type_date"); Calendar calendar = new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3); calendar.setTimeZone(TimeZone.getTimeZone("GMT+8")); check("d2", calendar.getTime()); calendar.set(2006, 0, 1, 1, 2, 3); check("d1", calendar.getTime()); } finally { ContextProvider.unregister(context); } } public void test_type_boolean() { doCompile("test_type_boolean"); check("b1", true); check("b2", false); check("b3", false); checkNull("nullValue"); checkNull("varWithNullInitializer"); } public void test_type_boolean_compare() { doCompileExpectErrors("test_type_boolean_compare", Arrays.asList( "Operator '>' is not defined for types 'boolean' and 'boolean'", "Operator '>=' is not defined for types 'boolean' and 'boolean'", "Operator '<' is not defined for types 'boolean' and 'boolean'", "Operator '<=' is not defined for types 'boolean' and 'boolean'", "Operator '<' is not defined for types 'boolean' and 'boolean'", "Operator '>' is not defined for types 'boolean' and 'boolean'", "Operator '>=' is not defined for types 'boolean' and 'boolean'", "Operator '<=' is not defined for types 'boolean' and 'boolean'")); } public void test_type_list() { doCompile("test_type_list"); check("intList", Arrays.asList(1, 2, 3, 4, 5, 6)); check("intList2", Arrays.asList(1, 2, 3)); check("stringList", Arrays.asList( "first", "replaced", "third", "fourth", "fifth", "sixth", "extra")); check("stringListCopy", Arrays.asList( "first", "second", "third", "fourth", "fifth", "seventh")); check("stringListCopy2", Arrays.asList( "first", "replaced", "third", "fourth", "fifth", "sixth", "extra")); assertTrue(getVariable("stringList") != getVariable("stringListCopy")); assertEquals(getVariable("stringList"), getVariable("stringListCopy2")); assertEquals(Arrays.asList(false, null, true), getVariable("booleanList")); assertDeepEquals(Arrays.asList(new byte[] {(byte) 0xAB}, null), getVariable("byteList")); assertDeepEquals(Arrays.asList(null, new byte[] {(byte) 0xCD}), getVariable("cbyteList")); assertEquals(Arrays.asList(new Date(12000), null, new Date(34000)), getVariable("dateList")); assertEquals(Arrays.asList(null, new BigDecimal(BigInteger.valueOf(1234), 2)), getVariable("decimalList")); assertEquals(Arrays.asList(12, null, 34), getVariable("intList3")); assertEquals(Arrays.asList(12l, null, 98l), getVariable("longList")); assertEquals(Arrays.asList(12.34, null, 56.78), getVariable("numberList")); assertEquals(Arrays.asList("aa", null, "bb"), getVariable("stringList2")); List<?> decimalList2 = (List<?>) getVariable("decimalList2"); for (Object o: decimalList2) { assertTrue(o instanceof BigDecimal); } List<?> intList4 = (List<?>) getVariable("intList4"); Set<Object> intList4Set = new HashSet<Object>(intList4); assertEquals(3, intList4Set.size()); } public void test_type_list_field() { doCompile("test_type_list_field"); check("copyByValueTest1", "2"); check("copyByValueTest2", "test"); } public void test_type_map_field() { doCompile("test_type_map_field"); Integer copyByValueTest1 = (Integer) getVariable("copyByValueTest1"); assertEquals(new Integer(2), copyByValueTest1); Integer copyByValueTest2 = (Integer) getVariable("copyByValueTest2"); assertEquals(new Integer(100), copyByValueTest2); } /** * The structure of the objects must be exactly the same! * * @param o1 * @param o2 */ private static void assertDeepCopy(Object o1, Object o2) { if (o1 instanceof DataRecord) { assertFalse(o1 == o2); DataRecord r1 = (DataRecord) o1; DataRecord r2 = (DataRecord) o2; for (int i = 0; i < r1.getNumFields(); i++) { assertDeepCopy(r1.getField(i).getValue(), r2.getField(i).getValue()); } } else if (o1 instanceof Map) { assertFalse(o1 == o2); Map<?, ?> m1 = (Map<?, ?>) o1; Map<?, ?> m2 = (Map<?, ?>) o2; for (Object key: m1.keySet()) { assertDeepCopy(m1.get(key), m2.get(key)); } } else if (o1 instanceof List) { assertFalse(o1 == o2); List<?> l1 = (List<?>) o1; List<?> l2 = (List<?>) o2; for (int i = 0; i < l1.size(); i++) { assertDeepCopy(l1.get(i), l2.get(i)); } } else if (o1 instanceof Date) { assertFalse(o1 == o2); // } else if (o1 instanceof byte[]) { // not required anymore // assertFalse(o1 == o2); } } /** * The structure of the objects must be exactly the same! * * @param o1 * @param o2 */ private static void assertDeepEquals(Object o1, Object o2) { if ((o1 == null) && (o2 == null)) { return; } assertTrue((o1 == null) == (o2 == null)); if (o1 instanceof DataRecord) { DataRecord r1 = (DataRecord) o1; DataRecord r2 = (DataRecord) o2; assertEquals(r1.getNumFields(), r2.getNumFields()); for (int i = 0; i < r1.getNumFields(); i++) { assertDeepEquals(r1.getField(i).getValue(), r2.getField(i).getValue()); } } else if (o1 instanceof Map) { Map<?, ?> m1 = (Map<?, ?>) o1; Map<?, ?> m2 = (Map<?, ?>) o2; assertTrue(m1.keySet().equals(m2.keySet())); for (Object key: m1.keySet()) { assertDeepEquals(m1.get(key), m2.get(key)); } } else if (o1 instanceof List) { List<?> l1 = (List<?>) o1; List<?> l2 = (List<?>) o2; assertEquals("size", l1.size(), l2.size()); for (int i = 0; i < l1.size(); i++) { assertDeepEquals(l1.get(i), l2.get(i)); } } else if (o1 instanceof byte[]) { byte[] b1 = (byte[]) o1; byte[] b2 = (byte[]) o2; if (b1 != b2) { if (b1 == null || b2 == null) { assertEquals(b1, b2); } assertEquals("length", b1.length, b2.length); for (int i = 0; i < b1.length; i++) { assertEquals(String.format("[%d]", i), b1[i], b2[i]); } } } else if (o1 instanceof CharSequence) { String s1 = ((CharSequence) o1).toString(); String s2 = ((CharSequence) o2).toString(); assertEquals(s1, s2); } else if ((o1 instanceof Decimal) || (o1 instanceof BigDecimal)) { BigDecimal d1 = o1 instanceof Decimal ? ((Decimal) o1).getBigDecimalOutput() : (BigDecimal) o1; BigDecimal d2 = o2 instanceof Decimal ? ((Decimal) o2).getBigDecimalOutput() : (BigDecimal) o2; assertEquals(d1, d2); } else { assertEquals(o1, o2); } } private void check_assignment_deepcopy_variable_declaration() { Date testVariableDeclarationDate1 = (Date) getVariable("testVariableDeclarationDate1"); Date testVariableDeclarationDate2 = (Date) getVariable("testVariableDeclarationDate2"); byte[] testVariableDeclarationByte1 = (byte[]) getVariable("testVariableDeclarationByte1"); byte[] testVariableDeclarationByte2 = (byte[]) getVariable("testVariableDeclarationByte2"); assertDeepEquals(testVariableDeclarationDate1, testVariableDeclarationDate2); assertDeepEquals(testVariableDeclarationByte1, testVariableDeclarationByte2); assertDeepCopy(testVariableDeclarationDate1, testVariableDeclarationDate2); assertDeepCopy(testVariableDeclarationByte1, testVariableDeclarationByte2); } @SuppressWarnings("unchecked") private void check_assignment_deepcopy_array_access_expression() { { // JJTARRAYACCESSEXPRESSION - List List<String> stringListField1 = (List<String>) getVariable("stringListField1"); DataRecord recordInList1 = (DataRecord) getVariable("recordInList1"); List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1"); List<DataRecord> recordList2 = (List<DataRecord>) getVariable("recordList2"); assertDeepEquals(stringListField1, recordInList1.getField("stringListField").getValue()); assertDeepEquals(recordInList1, recordList1.get(0)); assertDeepEquals(recordList1, recordList2); assertDeepCopy(stringListField1, recordInList1.getField("stringListField").getValue()); assertDeepCopy(recordInList1, recordList1.get(0)); assertDeepCopy(recordList1, recordList2); } { // map of records Date testDate1 = (Date) getVariable("testDate1"); Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1"); DataRecord recordInMap1 = (DataRecord) getVariable("recordInMap1"); DataRecord recordInMap2 = (DataRecord) getVariable("recordInMap2"); Map<Integer, DataRecord> recordMap2 = (Map<Integer, DataRecord>) getVariable("recordMap2"); assertDeepEquals(testDate1, recordInMap1.getField("dateField").getValue()); assertDeepEquals(recordInMap1, recordMap1.get(0)); assertDeepEquals(recordInMap2, recordMap1.get(0)); assertDeepEquals(recordMap1, recordMap2); assertDeepCopy(testDate1, recordInMap1.getField("dateField").getValue()); assertDeepCopy(recordInMap1, recordMap1.get(0)); assertDeepCopy(recordInMap2, recordMap1.get(0)); assertDeepCopy(recordMap1, recordMap2); } { // map of dates Map<Integer, Date> dateMap1 = (Map<Integer, Date>) getVariable("dateMap1"); Date date1 = (Date) getVariable("date1"); Date date2 = (Date) getVariable("date2"); assertDeepCopy(date1, dateMap1.get(0)); assertDeepCopy(date2, dateMap1.get(1)); } { // map of byte arrays Map<Integer, byte[]> byteMap1 = (Map<Integer, byte[]>) getVariable("byteMap1"); byte[] byte1 = (byte[]) getVariable("byte1"); byte[] byte2 = (byte[]) getVariable("byte2"); assertDeepCopy(byte1, byteMap1.get(0)); assertDeepCopy(byte2, byteMap1.get(1)); } { // JJTARRAYACCESSEXPRESSION - Function call List<String> testArrayAccessFunctionCallStringList = (List<String>) getVariable("testArrayAccessFunctionCallStringList"); DataRecord testArrayAccessFunctionCall = (DataRecord) getVariable("testArrayAccessFunctionCall"); Map<String, DataRecord> function_call_original_map = (Map<String, DataRecord>) getVariable("function_call_original_map"); Map<String, DataRecord> function_call_copied_map = (Map<String, DataRecord>) getVariable("function_call_copied_map"); List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list"); List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list"); assertDeepEquals(testArrayAccessFunctionCallStringList, testArrayAccessFunctionCall.getField("stringListField").getValue()); assertEquals(1, function_call_original_map.size()); assertEquals(2, function_call_copied_map.size()); assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall), function_call_original_list); assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall, testArrayAccessFunctionCall), function_call_copied_list); assertDeepEquals(testArrayAccessFunctionCall, function_call_original_map.get("1")); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("1")); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("2")); assertDeepEquals(testArrayAccessFunctionCall, function_call_original_list.get(1)); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(1)); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(2)); assertDeepCopy(testArrayAccessFunctionCall, function_call_original_map.get("1")); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("1")); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("2")); assertDeepCopy(testArrayAccessFunctionCall, function_call_original_list.get(1)); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(1)); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(2)); } } @SuppressWarnings("unchecked") private void check_assignment_deepcopy_field_access_expression() { // field access Date testFieldAccessDate1 = (Date) getVariable("testFieldAccessDate1"); String testFieldAccessString1 = (String) getVariable("testFieldAccessString1"); List<Date> testFieldAccessDateList1 = (List<Date>) getVariable("testFieldAccessDateList1"); List<String> testFieldAccessStringList1 = (List<String>) getVariable("testFieldAccessStringList1"); Map<String, Date> testFieldAccessDateMap1 = (Map<String, Date>) getVariable("testFieldAccessDateMap1"); Map<String, String> testFieldAccessStringMap1 = (Map<String, String>) getVariable("testFieldAccessStringMap1"); DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1"); DataRecord firstMultivalueOutput = outputRecords[4]; DataRecord secondMultivalueOutput = outputRecords[5]; DataRecord thirdMultivalueOutput = outputRecords[6]; assertDeepEquals(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue()); assertDeepEquals(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0)); assertDeepEquals(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0)); assertDeepEquals(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first")); assertDeepEquals(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first")); assertDeepEquals(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue()); assertDeepEquals(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue()); assertDeepEquals(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue()); assertDeepEquals(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue()); assertDeepEquals(testFieldAccessRecord1, thirdMultivalueOutput); assertDeepCopy(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue()); assertDeepCopy(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0)); assertDeepCopy(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0)); assertDeepCopy(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first")); assertDeepCopy(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first")); assertDeepCopy(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue()); assertDeepCopy(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue()); assertDeepCopy(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue()); assertDeepCopy(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue()); assertDeepCopy(testFieldAccessRecord1, thirdMultivalueOutput); } @SuppressWarnings("unchecked") private void check_assignment_deepcopy_member_access_expression() { { // member access - record Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1"); byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1"); List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1"); List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1"); DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1"); DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); } { // member access - record Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1"); byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1"); List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1"); List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1"); DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1"); DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2"); DataRecord testMemberAccessRecord3 = (DataRecord) getVariable("testMemberAccessRecord3"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); assertDeepEquals(testMemberAccessRecord3, testMemberAccessRecord2); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); assertDeepCopy(testMemberAccessRecord3, testMemberAccessRecord2); // dictionary Date dictionaryDate = (Date) graph.getDictionary().getEntry("a").getValue(); byte[] dictionaryByte = (byte[]) graph.getDictionary().getEntry("y").getValue(); List<String> testMemberAccessStringList1 = (List<String>) getVariable("testMemberAccessStringList1"); List<Date> testMemberAccessDateList2 = (List<Date>) getVariable("testMemberAccessDateList2"); List<byte[]> testMemberAccessByteList2 = (List<byte[]>) getVariable("testMemberAccessByteList2"); List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList"); List<Date> dictionaryDateList = (List<Date>) graph.getDictionary().getValue("dateList"); List<byte[]> dictionaryByteList = (List<byte[]>) graph.getDictionary().getValue("byteList"); assertDeepEquals(dictionaryDate, testMemberAccessDate1); assertDeepEquals(dictionaryByte, testMemberAccessByte1); assertDeepEquals(dictionaryStringList, testMemberAccessStringList1); assertDeepEquals(dictionaryDateList, testMemberAccessDateList2); assertDeepEquals(dictionaryByteList, testMemberAccessByteList2); assertDeepCopy(dictionaryDate, testMemberAccessDate1); assertDeepCopy(dictionaryByte, testMemberAccessByte1); assertDeepCopy(dictionaryStringList, testMemberAccessStringList1); assertDeepCopy(dictionaryDateList, testMemberAccessDateList2); assertDeepCopy(dictionaryByteList, testMemberAccessByteList2); // member access - array of records List<DataRecord> testMemberAccessRecordList1 = (List<DataRecord>) getVariable("testMemberAccessRecordList1"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue()); assertDeepEquals(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2)); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue()); assertDeepCopy(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2)); // member access - map of records Map<Integer, DataRecord> testMemberAccessRecordMap1 = (Map<Integer, DataRecord>) getVariable("testMemberAccessRecordMap1"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue()); assertDeepEquals(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2)); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue()); assertDeepCopy(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2)); } } @SuppressWarnings("unchecked") public void test_assignment_deepcopy() { doCompile("test_assignment_deepcopy"); List<DataRecord> secondRecordList = (List<DataRecord>) getVariable("secondRecordList"); assertEquals("before", secondRecordList.get(0).getField("Name").getValue().toString()); List<DataRecord> firstRecordList = (List<DataRecord>) getVariable("firstRecordList"); assertEquals("after", firstRecordList.get(0).getField("Name").getValue().toString()); check_assignment_deepcopy_variable_declaration(); check_assignment_deepcopy_array_access_expression(); check_assignment_deepcopy_field_access_expression(); check_assignment_deepcopy_member_access_expression(); } public void test_assignment_deepcopy_field_access_expression() { doCompile("test_assignment_deepcopy_field_access_expression"); DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1"); DataRecord firstMultivalueOutput = outputRecords[4]; DataRecord secondMultivalueOutput = outputRecords[5]; DataRecord thirdMultivalueOutput = outputRecords[6]; DataRecord multivalueInput = inputRecords[3]; assertDeepEquals(firstMultivalueOutput, testFieldAccessRecord1); assertDeepEquals(secondMultivalueOutput, multivalueInput); assertDeepEquals(thirdMultivalueOutput, secondMultivalueOutput); assertDeepCopy(firstMultivalueOutput, testFieldAccessRecord1); assertDeepCopy(secondMultivalueOutput, multivalueInput); assertDeepCopy(thirdMultivalueOutput, secondMultivalueOutput); } public void test_assignment_array_access_function_call() { doCompile("test_assignment_array_access_function_call"); Map<String, String> originalMap = new HashMap<String, String>(); originalMap.put("a", "b"); Map<String, String> copiedMap = new HashMap<String, String>(originalMap); copiedMap.put("c", "d"); check("originalMap", originalMap); check("copiedMap", copiedMap); } public void test_assignment_array_access_function_call_wrong_type() { doCompileExpectErrors("test_assignment_array_access_function_call_wrong_type", Arrays.asList( "Expression is not a composite type but is resolved to 'string'", "Type mismatch: cannot convert from 'integer' to 'string'", "Cannot convert from 'integer' to string" )); } @SuppressWarnings("unchecked") public void test_assignment_returnvalue() { doCompile("test_assignment_returnvalue"); { List<String> stringList1 = (List<String>) getVariable("stringList1"); List<String> stringList2 = (List<String>) getVariable("stringList2"); List<String> stringList3 = (List<String>) getVariable("stringList3"); List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1"); Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1"); List<String> stringList4 = (List<String>) getVariable("stringList4"); Map<String, Integer> integerMap1 = (Map<String, Integer>) getVariable("integerMap1"); DataRecord record1 = (DataRecord) getVariable("record1"); DataRecord record2 = (DataRecord) getVariable("record2"); DataRecord firstMultivalueOutput = outputRecords[4]; DataRecord secondMultivalueOutput = outputRecords[5]; DataRecord thirdMultivalueOutput = outputRecords[6]; Date dictionaryDate1 = (Date) getVariable("dictionaryDate1"); Date dictionaryDate = (Date) graph.getDictionary().getValue("a"); Date zeroDate = new Date(0); List<String> testReturnValueDictionary2 = (List<String>) getVariable("testReturnValueDictionary2"); List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList"); List<String> testReturnValue10 = (List<String>) getVariable("testReturnValue10"); DataRecord testReturnValue11 = (DataRecord) getVariable("testReturnValue11"); List<String> testReturnValue12 = (List<String>) getVariable("testReturnValue12"); List<String> testReturnValue13 = (List<String>) getVariable("testReturnValue13"); Map<Integer, DataRecord> function_call_original_map = (Map<Integer, DataRecord>) getVariable("function_call_original_map"); Map<Integer, DataRecord> function_call_copied_map = (Map<Integer, DataRecord>) getVariable("function_call_copied_map"); DataRecord function_call_map_newrecord = (DataRecord) getVariable("function_call_map_newrecord"); List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list"); List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list"); DataRecord function_call_list_newrecord = (DataRecord) getVariable("function_call_list_newrecord"); // identifier assertFalse(stringList1.isEmpty()); assertTrue(stringList2.isEmpty()); assertTrue(stringList3.isEmpty()); // array access expression - list assertDeepEquals("unmodified", recordList1.get(0).getField("stringField").getValue()); assertDeepEquals("modified", recordList1.get(1).getField("stringField").getValue()); // array access expression - map assertDeepEquals("unmodified", recordMap1.get(0).getField("stringField").getValue()); assertDeepEquals("modified", recordMap1.get(1).getField("stringField").getValue()); // array access expression - function call assertDeepEquals(null, function_call_original_map.get(2)); assertDeepEquals("unmodified", function_call_map_newrecord.getField("stringField")); assertDeepEquals("modified", function_call_copied_map.get(2).getField("stringField")); assertDeepEquals(Arrays.asList(null, function_call_list_newrecord), function_call_original_list); assertDeepEquals("unmodified", function_call_list_newrecord.getField("stringField")); assertDeepEquals("modified", function_call_copied_list.get(2).getField("stringField")); // field access expression assertFalse(stringList4.isEmpty()); assertTrue(((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).isEmpty()); assertFalse(integerMap1.isEmpty()); assertTrue(((Map<?, ?>) firstMultivalueOutput.getField("integerMapField").getValue()).isEmpty()); assertDeepEquals("unmodified", record1.getField("stringField")); assertDeepEquals("modified", secondMultivalueOutput.getField("stringField").getValue()); assertDeepEquals("unmodified", record2.getField("stringField")); assertDeepEquals("modified", thirdMultivalueOutput.getField("stringField").getValue()); // member access expression - dictionary // There is no function that could modify a date // assertEquals(zeroDate, dictionaryDate); // assertFalse(zeroDate.equals(testReturnValueDictionary1)); assertFalse(testReturnValueDictionary2.isEmpty()); assertTrue(dictionaryStringList.isEmpty()); // member access expression - record assertFalse(testReturnValue10.isEmpty()); assertTrue(((List<?>) testReturnValue11.getField("stringListField").getValue()).isEmpty()); // member access expression - list of records assertFalse(testReturnValue12.isEmpty()); assertTrue(((List<?>) recordList1.get(2).getField("stringListField").getValue()).isEmpty()); // member access expression - map of records assertFalse(testReturnValue13.isEmpty()); assertTrue(((List<?>) recordMap1.get(2).getField("stringListField").getValue()).isEmpty()); } } @SuppressWarnings("unchecked") public void test_type_map() { doCompile("test_type_map"); Map<String, Integer> testMap = (Map<String, Integer>) getVariable("testMap"); assertEquals(Integer.valueOf(1), testMap.get("zero")); assertEquals(Integer.valueOf(2), testMap.get("one")); assertEquals(Integer.valueOf(3), testMap.get("two")); assertEquals(Integer.valueOf(4), testMap.get("three")); assertEquals(4, testMap.size()); Map<Date, String> dayInWeek = (Map<Date, String>) getVariable("dayInWeek"); Calendar c = Calendar.getInstance(); c.set(2009, Calendar.MARCH, 2, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); assertEquals("Monday", dayInWeek.get(c.getTime())); Map<Date, String> dayInWeekCopy = (Map<Date, String>) getVariable("dayInWeekCopy"); c.set(2009, Calendar.MARCH, 3, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); assertEquals("Tuesday", ((Map<Date, String>) getVariable("tuesday")).get(c.getTime())); assertEquals("Tuesday", dayInWeekCopy.get(c.getTime())); c.set(2009, Calendar.MARCH, 4, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); assertEquals("Wednesday", ((Map<Date, String>) getVariable("wednesday")).get(c.getTime())); assertEquals("Wednesday", dayInWeekCopy.get(c.getTime())); assertFalse(dayInWeek.equals(dayInWeekCopy)); { Map<?, ?> preservedOrder = (Map<?, ?>) getVariable("preservedOrder"); assertEquals(100, preservedOrder.size()); int i = 0; for (Map.Entry<?, ?> entry: preservedOrder.entrySet()) { assertEquals("key" + i, entry.getKey()); assertEquals("value" + i, entry.getValue()); i++; } } } public void test_type_record_list() { doCompile("test_type_record_list"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record_list_global() { doCompile("test_type_record_list_global"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record_map() { doCompile("test_type_record_map"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record_map_global() { doCompile("test_type_record_map_global"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record() { doCompile("test_type_record"); // expected result DataRecord expected = createDefaultRecord(createDefaultMetadata("expected")); // simple copy assertTrue(recordEquals(expected, inputRecords[0])); assertTrue(recordEquals(expected, (DataRecord) getVariable("copy"))); // copy and modify expected.getField("Name").setValue("empty"); expected.getField("Value").setValue(321); Calendar c = Calendar.getInstance(); c.set(1987, Calendar.NOVEMBER, 13, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); expected.getField("Born").setValue(c.getTime()); assertTrue(recordEquals(expected, (DataRecord) getVariable("modified"))); // 2x modified copy expected.getField("Name").setValue("not empty"); assertTrue(recordEquals(expected, (DataRecord)getVariable("modified2"))); // no modification by reference is possible assertTrue(recordEquals(expected, (DataRecord)getVariable("modified3"))); expected.getField("Value").setValue(654321); assertTrue(recordEquals(expected, (DataRecord)getVariable("reference"))); assertTrue(getVariable("modified3") != getVariable("reference")); // output record assertTrue(recordEquals(expected, outputRecords[1])); // null record expected.setToNull(); assertTrue(recordEquals(expected, (DataRecord)getVariable("nullRecord"))); } public void test_variables() { doCompile("test_variables"); check("b1", true); check("b2", true); check("b4", "hi"); check("i", 2); } public void test_operator_plus() { doCompile("test_operator_plus"); check("iplusj", 10 + 100); check("lplusm", Long.valueOf(Integer.MAX_VALUE) + Long.valueOf(Integer.MAX_VALUE / 10)); check("mplusl", getVariable("lplusm")); check("mplusi", Long.valueOf(Integer.MAX_VALUE) + 10); check("iplusm", getVariable("mplusi")); check("nplusm1", Double.valueOf(0.1D + 0.001D)); check("nplusj", Double.valueOf(100 + 0.1D)); check("jplusn", getVariable("nplusj")); check("m1plusm", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) + 0.001d)); check("mplusm1", getVariable("m1plusm")); check("dplusd1", new BigDecimal("0.1", MAX_PRECISION).add(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dplusj", new BigDecimal(100, MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("jplusd", getVariable("dplusj")); check("dplusm", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("mplusd", getVariable("dplusm")); check("dplusn", new BigDecimal("0.1").add(new BigDecimal(0.1D, MAX_PRECISION))); check("nplusd", getVariable("dplusn")); check("spluss1", "hello world"); check("splusj", "hello100"); check("jpluss", "100hello"); check("splusm", "hello" + Long.valueOf(Integer.MAX_VALUE)); check("mpluss", Long.valueOf(Integer.MAX_VALUE) + "hello"); check("splusm1", "hello" + Double.valueOf(0.001D)); check("m1pluss", Double.valueOf(0.001D) + "hello"); check("splusd1", "hello" + new BigDecimal("0.0001")); check("d1pluss", new BigDecimal("0.0001", MAX_PRECISION) + "hello"); } public void test_operator_minus() { doCompile("test_operator_minus"); check("iminusj", 10 - 100); check("lminusm", Long.valueOf(Integer.MAX_VALUE / 10) - Long.valueOf(Integer.MAX_VALUE)); check("mminusi", Long.valueOf(Integer.MAX_VALUE - 10)); check("iminusm", 10 - Long.valueOf(Integer.MAX_VALUE)); check("nminusm1", Double.valueOf(0.1D - 0.001D)); check("nminusj", Double.valueOf(0.1D - 100)); check("jminusn", Double.valueOf(100 - 0.1D)); check("m1minusm", Double.valueOf(0.001D - Long.valueOf(Integer.MAX_VALUE))); check("mminusm1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) - 0.001D)); check("dminusd1", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dminusj", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION)); check("jminusd", new BigDecimal(100, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dminusm", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mminusd", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dminusn", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION)); check("nminusd", new BigDecimal(0.1D, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); } public void test_operator_multiply() { doCompile("test_operator_multiply"); check("itimesj", 10 * 100); check("ltimesm", Long.valueOf(Integer.MAX_VALUE) * (Long.valueOf(Integer.MAX_VALUE / 10))); check("mtimesl", getVariable("ltimesm")); check("mtimesi", Long.valueOf(Integer.MAX_VALUE) * 10); check("itimesm", getVariable("mtimesi")); check("ntimesm1", Double.valueOf(0.1D * 0.001D)); check("ntimesj", Double.valueOf(0.1) * 100); check("jtimesn", getVariable("ntimesj")); check("m1timesm", Double.valueOf(0.001d * Long.valueOf(Integer.MAX_VALUE))); check("mtimesm1", getVariable("m1timesm")); check("dtimesd1", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dtimesj", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(100, MAX_PRECISION))); check("jtimesd", getVariable("dtimesj")); check("dtimesm", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mtimesd", getVariable("dtimesm")); check("dtimesn", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(0.1, MAX_PRECISION), MAX_PRECISION)); check("ntimesd", getVariable("dtimesn")); } public void test_operator_divide() { doCompile("test_operator_divide"); check("idividej", 10 / 100); check("ldividem", Long.valueOf(Integer.MAX_VALUE / 10) / Long.valueOf(Integer.MAX_VALUE)); check("mdividei", Long.valueOf(Integer.MAX_VALUE / 10)); check("idividem", 10 / Long.valueOf(Integer.MAX_VALUE)); check("ndividem1", Double.valueOf(0.1D / 0.001D)); check("ndividej", Double.valueOf(0.1D / 100)); check("jdividen", Double.valueOf(100 / 0.1D)); check("m1dividem", Double.valueOf(0.001D / Long.valueOf(Integer.MAX_VALUE))); check("mdividem1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) / 0.001D)); check("ddivided1", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("ddividej", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION)); check("jdivided", new BigDecimal(100, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("ddividem", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mdivided", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("ddividen", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION)); check("ndivided", new BigDecimal(0.1D, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); } public void test_operator_modulus() { doCompile("test_operator_modulus"); check("imoduloj", 10 % 100); check("lmodulom", Long.valueOf(Integer.MAX_VALUE / 10) % Long.valueOf(Integer.MAX_VALUE)); check("mmoduloi", Long.valueOf(Integer.MAX_VALUE % 10)); check("imodulom", 10 % Long.valueOf(Integer.MAX_VALUE)); check("nmodulom1", Double.valueOf(0.1D % 0.001D)); check("nmoduloj", Double.valueOf(0.1D % 100)); check("jmodulon", Double.valueOf(100 % 0.1D)); check("m1modulom", Double.valueOf(0.001D % Long.valueOf(Integer.MAX_VALUE))); check("mmodulom1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) % 0.001D)); check("dmodulod1", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dmoduloj", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION)); check("jmodulod", new BigDecimal(100, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dmodulom", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mmodulod", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dmodulon", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION)); check("nmodulod", new BigDecimal(0.1D, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); } public void test_operators_unary() { doCompile("test_operators_unary"); // postfix operators // int check("intPlusOrig", Integer.valueOf(10)); check("intPlusPlus", Integer.valueOf(10)); check("intPlus", Integer.valueOf(11)); check("intMinusOrig", Integer.valueOf(10)); check("intMinusMinus", Integer.valueOf(10)); check("intMinus", Integer.valueOf(9)); // long check("longPlusOrig", Long.valueOf(10)); check("longPlusPlus", Long.valueOf(10)); check("longPlus", Long.valueOf(11)); check("longMinusOrig", Long.valueOf(10)); check("longMinusMinus", Long.valueOf(10)); check("longMinus", Long.valueOf(9)); // double check("numberPlusOrig", Double.valueOf(10.1)); check("numberPlusPlus", Double.valueOf(10.1)); check("numberPlus", Double.valueOf(11.1)); check("numberMinusOrig", Double.valueOf(10.1)); check("numberMinusMinus", Double.valueOf(10.1)); check("numberMinus", Double.valueOf(9.1)); // decimal check("decimalPlusOrig", new BigDecimal("10.1")); check("decimalPlusPlus", new BigDecimal("10.1")); check("decimalPlus", new BigDecimal("11.1")); check("decimalMinusOrig", new BigDecimal("10.1")); check("decimalMinusMinus", new BigDecimal("10.1")); check("decimalMinus", new BigDecimal("9.1")); // prefix operators // integer check("plusIntOrig", Integer.valueOf(10)); check("plusPlusInt", Integer.valueOf(11)); check("plusInt", Integer.valueOf(11)); check("minusIntOrig", Integer.valueOf(10)); check("minusMinusInt", Integer.valueOf(9)); check("minusInt", Integer.valueOf(9)); check("unaryInt", Integer.valueOf(-10)); // long check("plusLongOrig", Long.valueOf(10)); check("plusPlusLong", Long.valueOf(11)); check("plusLong", Long.valueOf(11)); check("minusLongOrig", Long.valueOf(10)); check("minusMinusLong", Long.valueOf(9)); check("minusLong", Long.valueOf(9)); check("unaryLong", Long.valueOf(-10)); // double check("plusNumberOrig", Double.valueOf(10.1)); check("plusPlusNumber", Double.valueOf(11.1)); check("plusNumber", Double.valueOf(11.1)); check("minusNumberOrig", Double.valueOf(10.1)); check("minusMinusNumber", Double.valueOf(9.1)); check("minusNumber", Double.valueOf(9.1)); check("unaryNumber", Double.valueOf(-10.1)); // decimal check("plusDecimalOrig", new BigDecimal("10.1")); check("plusPlusDecimal", new BigDecimal("11.1")); check("plusDecimal", new BigDecimal("11.1")); check("minusDecimalOrig", new BigDecimal("10.1")); check("minusMinusDecimal", new BigDecimal("9.1")); check("minusDecimal", new BigDecimal("9.1")); check("unaryDecimal", new BigDecimal("-10.1")); // record values assertEquals(101, ((DataRecord) getVariable("plusPlusRecord")).getField("Value").getValue()); assertEquals(101, ((DataRecord) getVariable("recordPlusPlus")).getField("Value").getValue()); assertEquals(101, ((DataRecord) getVariable("modifiedPlusPlusRecord")).getField("Value").getValue()); assertEquals(101, ((DataRecord) getVariable("modifiedRecordPlusPlus")).getField("Value").getValue()); //record as parameter assertEquals(99, ((DataRecord) getVariable("minusMinusRecord")).getField("Value").getValue()); assertEquals(99, ((DataRecord) getVariable("recordMinusMinus")).getField("Value").getValue()); assertEquals(99, ((DataRecord) getVariable("modifiedMinusMinusRecord")).getField("Value").getValue()); assertEquals(99, ((DataRecord) getVariable("modifiedRecordMinusMinus")).getField("Value").getValue()); // logical not check("booleanValue", true); check("negation", false); check("doubleNegation", true); } public void test_operators_unary_record() { doCompileExpectErrors("test_operators_unary_record", Arrays.asList( "Illegal argument to ++/-- operator", "Illegal argument to ++/-- operator", "Illegal argument to ++/-- operator", "Illegal argument to ++/-- operator", "Input record cannot be assigned to", "Input record cannot be assigned to", "Input record cannot be assigned to", "Input record cannot be assigned to" )); } public void test_operator_equal() { doCompile("test_operator_equal"); check("eq0", true); check("eq1", true); check("eq1a", true); check("eq1b", true); check("eq1c", false); check("eq2", true); check("eq3", true); check("eq4", true); check("eq5", true); check("eq6", false); check("eq7", true); check("eq8", false); check("eq9", true); check("eq10", false); check("eq11", true); check("eq12", false); check("eq13", true); check("eq14", false); check("eq15", false); check("eq16", true); check("eq17", false); check("eq18", false); check("eq19", false); // byte check("eq20", true); check("eq21", true); check("eq22", false); check("eq23", false); check("eq24", true); check("eq25", false); check("eq20c", true); check("eq21c", true); check("eq22c", false); check("eq23c", false); check("eq24c", true); check("eq25c", false); check("eq26", true); check("eq27", true); } public void test_operator_non_equal(){ doCompile("test_operator_non_equal"); check("inei", false); check("inej", true); check("jnei", true); check("jnej", false); check("lnei", false); check("inel", false); check("lnej", true); check("jnel", true); check("lnel", false); check("dnei", false); check("ined", false); check("dnej", true); check("jned", true); check("dnel", false); check("lned", false); check("dned", false); check("dned_different_scale", false); } public void test_operator_in() { doCompile("test_operator_in"); check("a", Integer.valueOf(1)); check("haystack", Collections.EMPTY_LIST); check("needle", Integer.valueOf(2)); check("b1", true); check("b2", false); check("h2", Arrays.asList(2.1D, 2.0D, 2.2D)); check("b3", true); check("h3", Arrays.asList("memento", "mori", "memento mori")); check("n3", "memento mori"); check("b4", true); } public void test_operator_greater_less() { doCompile("test_operator_greater_less"); check("eq1", true); check("eq2", true); check("eq3", true); check("eq4", false); check("eq5", true); check("eq6", false); check("eq7", true); check("eq8", true); check("eq9", true); } public void test_operator_ternary(){ doCompile("test_operator_ternary"); // simple use check("trueValue", true); check("falseValue", false); check("res1", Integer.valueOf(1)); check("res2", Integer.valueOf(2)); // nesting in positive branch check("res3", Integer.valueOf(1)); check("res4", Integer.valueOf(2)); check("res5", Integer.valueOf(3)); // nesting in negative branch check("res6", Integer.valueOf(2)); check("res7", Integer.valueOf(3)); // nesting in both branches check("res8", Integer.valueOf(1)); check("res9", Integer.valueOf(1)); check("res10", Integer.valueOf(2)); check("res11", Integer.valueOf(3)); check("res12", Integer.valueOf(2)); check("res13", Integer.valueOf(4)); check("res14", Integer.valueOf(3)); check("res15", Integer.valueOf(4)); } public void test_operators_logical(){ doCompile("test_operators_logical"); //TODO: please double check this. check("res1", false); check("res2", false); check("res3", true); check("res4", true); check("res5", false); check("res6", false); check("res7", true); check("res8", false); } public void test_regex(){ doCompile("test_regex"); check("eq0", false); check("eq1", true); check("eq2", false); check("eq3", true); check("eq4", false); check("eq5", true); } public void test_if() { doCompile("test_if"); // if with single statement check("cond1", true); check("res1", true); // if with mutliple statements (block) check("cond2", true); check("res21", true); check("res22", true); // else with single statement check("cond3", false); check("res31", false); check("res32", true); // else with multiple statements (block) check("cond4", false); check("res41", false); check("res42", true); check("res43", true); // if with block, else with block check("cond5", false); check("res51", false); check("res52", false); check("res53", true); check("res54", true); // else-if with single statement check("cond61", false); check("cond62", true); check("res61", false); check("res62", true); // else-if with multiple statements check("cond71", false); check("cond72", true); check("res71", false); check("res72", true); check("res73", true); // if-elseif-else test check("cond81", false); check("cond82", false); check("res81", false); check("res82", false); check("res83", true); // if with single statement + inactive else check("cond9", true); check("res91", true); check("res92", false); // if with multiple statements + inactive else with block check("cond10", true); check("res101", true); check("res102", true); check("res103", false); check("res104", false); // if with condition check("i", 0); check("j", 1); check("res11", true); } public void test_switch() { doCompile("test_switch"); // simple switch check("cond1", 1); check("res11", false); check("res12", true); check("res13", false); // switch, no break check("cond2", 1); check("res21", false); check("res22", true); check("res23", true); // default branch check("cond3", 3); check("res31", false); check("res32", false); check("res33", true); // no default branch => no match check("cond4", 3); check("res41", false); check("res42", false); check("res43", false); // multiple statements in a single case-branch check("cond5", 1); check("res51", false); check("res52", true); check("res53", true); check("res54", false); // single statement shared by several case labels check("cond6", 1); check("res61", false); check("res62", true); check("res63", true); check("res64", false); } public void test_int_switch(){ doCompile("test_int_switch"); // simple switch check("cond1", 1); check("res11", true); check("res12", false); check("res13", false); // first case is not followed by a break check("cond2", 1); check("res21", true); check("res22", true); check("res23", false); // first and second case have multiple labels check("cond3", 12); check("res31", false); check("res32", true); check("res33", false); // first and second case have multiple labels and no break after first group check("cond4", 11); check("res41", true); check("res42", true); check("res43", false); // default case intermixed with other case labels in the second group check("cond5", 11); check("res51", true); check("res52", true); check("res53", true); // default case intermixed, with break check("cond6", 16); check("res61", false); check("res62", true); check("res63", false); // continue test check("res7", Arrays.asList( false, false, false, true, true, false, true, true, false, false, true, false, false, true, false, false, false, true)); // return test check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3")); } public void test_non_int_switch(){ doCompile("test_non_int_switch"); // simple switch check("cond1", "1"); check("res11", true); check("res12", false); check("res13", false); // first case is not followed by a break check("cond2", "1"); check("res21", true); check("res22", true); check("res23", false); // first and second case have multiple labels check("cond3", "12"); check("res31", false); check("res32", true); check("res33", false); // first and second case have multiple labels and no break after first group check("cond4", "11"); check("res41", true); check("res42", true); check("res43", false); // default case intermixed with other case labels in the second group check("cond5", "11"); check("res51", true); check("res52", true); check("res53", true); // default case intermixed, with break check("cond6", "16"); check("res61", false); check("res62", true); check("res63", false); // continue test check("res7", Arrays.asList( false, false, false, true, true, false, true, true, false, false, true, false, false, true, false, false, false, true)); // return test check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3")); } public void test_while() { doCompile("test_while"); // simple while check("res1", Arrays.asList(0, 1, 2)); // continue check("res2", Arrays.asList(0, 2)); // break check("res3", Arrays.asList(0)); } public void test_do_while() { doCompile("test_do_while"); // simple while check("res1", Arrays.asList(0, 1, 2)); // continue check("res2", Arrays.asList(0, null, 2)); // break check("res3", Arrays.asList(0)); } public void test_for() { doCompile("test_for"); // simple loop check("res1", Arrays.asList(0,1,2)); // continue check("res2", Arrays.asList(0,null,2)); // break check("res3", Arrays.asList(0)); // empty init check("res4", Arrays.asList(0,1,2)); // empty update check("res5", Arrays.asList(0,1,2)); // empty final condition check("res6", Arrays.asList(0,1,2)); // all conditions empty check("res7", Arrays.asList(0,1,2)); } public void test_for1() { //5125: CTL2: "for" cycle is EXTREMELY memory consuming doCompile("test_for1"); checkEquals("counter", "COUNT"); } @SuppressWarnings("unchecked") public void test_foreach() { doCompile("test_foreach"); check("intRes", Arrays.asList(VALUE_VALUE)); check("longRes", Arrays.asList(BORN_MILLISEC_VALUE)); check("doubleRes", Arrays.asList(AGE_VALUE)); check("decimalRes", Arrays.asList(CURRENCY_VALUE)); check("booleanRes", Arrays.asList(FLAG_VALUE)); check("stringRes", Arrays.asList(NAME_VALUE, CITY_VALUE)); check("dateRes", Arrays.asList(BORN_VALUE)); List<?> integerStringMapResTmp = (List<?>) getVariable("integerStringMapRes"); List<String> integerStringMapRes = new ArrayList<String>(integerStringMapResTmp.size()); for (Object o: integerStringMapResTmp) { integerStringMapRes.add(String.valueOf(o)); } List<Integer> stringIntegerMapRes = (List<Integer>) getVariable("stringIntegerMapRes"); List<DataRecord> stringRecordMapRes = (List<DataRecord>) getVariable("stringRecordMapRes"); Collections.sort(integerStringMapRes); Collections.sort(stringIntegerMapRes); assertEquals(Arrays.asList("0", "1", "2", "3", "4"), integerStringMapRes); assertEquals(Arrays.asList(0, 1, 2, 3, 4), stringIntegerMapRes); final int N = 5; assertEquals(N, stringRecordMapRes.size()); int equalRecords = 0; for (int i = 0; i < N; i++) { for (DataRecord r: stringRecordMapRes) { if (Integer.valueOf(i).equals(r.getField("Value").getValue()) && "A string".equals(String.valueOf(r.getField("Name").getValue()))) { equalRecords++; break; } } } assertEquals(N, equalRecords); } public void test_return(){ doCompile("test_return"); check("lhs", Integer.valueOf(1)); check("rhs", Integer.valueOf(2)); check("res", Integer.valueOf(3)); } public void test_return_incorrect() { doCompileExpectError("test_return_incorrect", "Can't convert from 'string' to 'integer'"); } public void test_return_void() { doCompile("test_return_void"); } public void test_overloading() { doCompile("test_overloading"); check("res1", Integer.valueOf(3)); check("res2", "Memento mori"); } public void test_overloading_incorrect() { doCompileExpectErrors("test_overloading_incorrect", Arrays.asList( "Duplicate function 'integer sum(integer, integer)'", "Duplicate function 'integer sum(integer, integer)'")); } //Test case for 4038 public void test_function_parameter_without_type() { doCompileExpectError("test_function_parameter_without_type", "Syntax error on token ')'"); } public void test_duplicate_import() { URL importLoc = getClass().getSuperclass().getResource("test_duplicate_import.ctl"); String expStr = "import '" + importLoc + "';\n"; expStr += "import '" + importLoc + "';\n"; doCompile(expStr, "test_duplicate_import"); } /*TODO: * public void test_invalid_import() { URL importLoc = getClass().getResource("test_duplicate_import.ctl"); String expStr = "import '/a/b/c/d/e/f/g/h/i/j/k/l/m';\n"; expStr += expStr; doCompileExpectError(expStr, "test_invalid_import", Arrays.asList("TODO: Unknown error")); //doCompileExpectError(expStr, "test_duplicate_import", Arrays.asList("TODO: Unknown error")); } */ public void test_built_in_functions(){ doCompile("test_built_in_functions"); check("notNullValue", Integer.valueOf(1)); checkNull("nullValue"); check("isNullRes1", false); check("isNullRes2", true); assertEquals("nvlRes1", getVariable("notNullValue"), getVariable("nvlRes1")); check("nvlRes2", Integer.valueOf(2)); assertEquals("nvl2Res1", getVariable("notNullValue"), getVariable("nvl2Res1")); check("nvl2Res2", Integer.valueOf(2)); check("iifRes1", Integer.valueOf(2)); check("iifRes2", Integer.valueOf(1)); } public void test_mapping(){ doCompile("test_mapping"); // simple mappings assertEquals("Name", NAME_VALUE, outputRecords[0].getField("Name").getValue().toString()); assertEquals("Age", AGE_VALUE, outputRecords[0].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[0].getField("City").getValue().toString()); assertEquals("Born", BORN_VALUE, outputRecords[0].getField("Born").getValue()); // * mapping assertTrue(recordEquals(inputRecords[1], outputRecords[1])); check("len", 2); } public void test_mapping_null_values() { doCompile("test_mapping_null_values"); assertTrue(recordEquals(inputRecords[2], outputRecords[0])); } public void test_copyByName() { doCompile("test_copyByName"); assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue()); assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString()); } public void test_copyByName_assignment() { doCompile("test_copyByName_assignment"); assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue()); assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString()); } public void test_copyByName_assignment1() { doCompile("test_copyByName_assignment1"); assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue()); assertEquals("Age", null, outputRecords[3].getField("Age").getValue()); assertEquals("City", null, outputRecords[3].getField("City").getValue()); } public void test_sequence(){ doCompile("test_sequence"); check("intRes", Arrays.asList(0,1,2)); check("longRes", Arrays.asList(Long.valueOf(0),Long.valueOf(1),Long.valueOf(2))); check("stringRes", Arrays.asList("0","1","2")); check("intCurrent", Integer.valueOf(2)); check("longCurrent", Long.valueOf(2)); check("stringCurrent", "2"); } //TODO: If this test fails please double check whether the test is correct? public void test_lookup(){ doCompile("test_lookup"); check("alphaResult", Arrays.asList("Andorra la Vella","Andorra la Vella")); check("bravoResult", Arrays.asList("Bruxelles","Bruxelles")); check("charlieResult", Arrays.asList("Chamonix","Chodov","Chomutov","Chamonix","Chodov","Chomutov")); check("countResult", Arrays.asList(3,3)); check("charlieUpdatedCount", 5); check("charlieUpdatedResult", Arrays.asList("Chamonix", "Cheb", "Chodov", "Chomutov", "Chrudim")); check("putResult", true); } public void test_containerlib_append() { doCompile("test_containerlib_append"); check("appendElem", Integer.valueOf(10)); check("appendList", Arrays.asList(1, 2, 3, 4, 5, 10)); } @SuppressWarnings("unchecked") public void test_containerlib_clear() { doCompile("test_containerlib_clear"); assertTrue(((List<Integer>) getVariable("clearList")).isEmpty()); } public void test_containerlib_copy() { doCompile("test_containerlib_copy"); check("copyList", Arrays.asList(1, 2, 3, 4, 5)); check("returnedList", Arrays.asList(1, 2, 3, 4, 5)); Map<String, String> expectedMap = new HashMap<String, String>(); expectedMap.put("a", "a"); expectedMap.put("b", "b"); expectedMap.put("c", "c"); expectedMap.put("d", "d"); check("copyMap", expectedMap); check("returnedMap", expectedMap); } public void test_containerlib_insert() { doCompile("test_containerlib_insert"); check("insertElem", Integer.valueOf(7)); check("insertIndex", Integer.valueOf(3)); check("insertList", Arrays.asList(1, 2, 3, 7, 4, 5)); check("insertList1", Arrays.asList(7, 8, 11, 10, 11)); check("insertList2", Arrays.asList(7, 8, 10, 9, 11)); } public void test_containerlib_isEmpty() { doCompile("test_containerlib_isEmpty"); check("emptyMap", true); check("fullMap", false); check("emptyList", true); check("fullList", false); } public void test_containerlib_poll() { doCompile("test_containerlib_poll"); check("pollElem", Integer.valueOf(1)); check("pollList", Arrays.asList(2, 3, 4, 5)); } public void test_containerlib_pop() { doCompile("test_containerlib_pop"); check("popElem", Integer.valueOf(5)); check("popList", Arrays.asList(1, 2, 3, 4)); } @SuppressWarnings("unchecked") public void test_containerlib_push() { doCompile("test_containerlib_push"); check("pushElem", Integer.valueOf(6)); check("pushList", Arrays.asList(1, 2, 3, 4, 5, 6)); // there is hardly any way to get an instance of DataRecord // hence we just check if the list has correct size // and if its elements have correct metadata List<DataRecord> recordList = (List<DataRecord>) getVariable("recordList"); List<DataRecordMetadata> mdList = Arrays.asList( graph.getDataRecordMetadata(OUTPUT_1), graph.getDataRecordMetadata(INPUT_2), graph.getDataRecordMetadata(INPUT_1) ); assertEquals(mdList.size(), recordList.size()); for (int i = 0; i < mdList.size(); i++) { assertEquals(mdList.get(i), recordList.get(i).getMetadata()); } } public void test_containerlib_remove() { doCompile("test_containerlib_remove"); check("removeElem", Integer.valueOf(3)); check("removeIndex", Integer.valueOf(2)); check("removeList", Arrays.asList(1, 2, 4, 5)); } public void test_containerlib_reverse() { doCompile("test_containerlib_reverse"); check("reverseList", Arrays.asList(5, 4, 3, 2, 1)); } public void test_containerlib_sort() { doCompile("test_containerlib_sort"); check("sortList", Arrays.asList(1, 1, 2, 3, 5)); } public void test_containerlib_containsAll() { doCompile("test_containerlib_containsAll"); check("results", Arrays.asList(true, false, true, false, true, true, true, false, true, true, false)); } public void test_containerlib_containsKey() { doCompile("test_containerlib_containsKey"); check("results", Arrays.asList(false, true, false, true, false, true)); } public void test_containerlib_containsValue() { doCompile("test_containerlib_containsValue"); check("results", Arrays.asList(true, false, false, true, false, false, true, false)); } public void test_containerlib_getKeys() { doCompile("test_containerlib_getKeys"); Map<?, ?> stringIntegerMap = (Map<?, ?>) inputRecords[3].getField("integerMapField").getValue(); Map<?, ?> integerStringMap = (Map<?, ?>) getVariable("integerStringMap"); List<?> stringList = (List<?>) getVariable("stringList"); List<?> integerList = (List<?>) getVariable("integerList"); assertEquals(stringIntegerMap.keySet().size(), stringList.size()); assertEquals(integerStringMap.keySet().size(), integerList.size()); assertEquals(stringIntegerMap.keySet(), new HashSet<Object>(stringList)); assertEquals(integerStringMap.keySet(), new HashSet<Object>(integerList)); } public void test_stringlib_cache() { doCompile("test_stringlib_cache"); check("rep1", "The cat says meow. All cats say meow."); check("rep2", "The cat says meow. All cats say meow."); check("rep3", "The cat says meow. All cats say meow."); check("find1", Arrays.asList("to", "to", "to", "tro", "to")); check("find2", Arrays.asList("to", "to", "to", "tro", "to")); check("find3", Arrays.asList("to", "to", "to", "tro", "to")); check("split1", Arrays.asList("one", "two", "three", "four", "five")); check("split2", Arrays.asList("one", "two", "three", "four", "five")); check("split3", Arrays.asList("one", "two", "three", "four", "five")); check("chop01", "ting soming choping function"); check("chop02", "ting soming choping function"); check("chop03", "ting soming choping function"); check("chop11", "testing end of lines cutting"); check("chop12", "testing end of lines cutting"); } public void test_stringlib_charAt() { doCompile("test_stringlib_charAt"); String input = "The QUICk !!$ broWn fox juMPS over the lazy DOG "; String[] expected = new String[input.length()]; for (int i = 0; i < expected.length; i++) { expected[i] = String.valueOf(input.charAt(i)); } check("chars", Arrays.asList(expected)); } public void test_stringlib_concat() { doCompile("test_stringlib_concat"); final SimpleDateFormat format = new SimpleDateFormat(); format.applyPattern("yyyy MMM dd"); check("concat", ""); check("concat1", "ello hi ELLO 2,today is " + format.format(new Date())); check("concat2", ""); check("concat3", "clover"); } public void test_stringlib_countChar() { doCompile("test_stringlib_countChar"); check("charCount", 3); check("count2", 0); } public void test_stringlib_countChar_emptychar() { // test: attempt to count empty chars in string. try { doCompile("integer charCount;function integer transform() {charCount = countChar('aaa','');return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } // test: attempt to count empty chars in empty string. try { doCompile("integer charCount;function integer transform() {charCount = countChar('','');return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_cut() { doCompile("test_stringlib_cut"); check("cutInput", Arrays.asList("a", "1edf", "h3ijk")); } public void test_string_cut_expect_error() { // test: Attempt to cut substring from position after the end of original string. E.g. string is 6 char long and // user attempt to cut out after position 8. try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[28,3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } // test: Attempt to cut substring longer then possible. E.g. string is 6 characters long and user cuts from // position // 4 substring 4 characters long try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,8]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } // test: Attempt to cut a substring with negative length try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,-3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } // test: Attempt to cut substring from negative position. E.g cut([-3,3]). try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[-3,3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_editDistance() { doCompile("test_stringlib_editDistance"); check("dist", 1); check("dist1", 1); check("dist2", 0); check("dist5", 1); check("dist3", 1); check("dist4", 0); check("dist6", 4); check("dist7", 5); check("dist8", 0); check("dist9", 0); } public void test_stringlib_find() { doCompile("test_stringlib_find"); check("findList", Arrays.asList("The quick br", "wn f", "x jumps ", "ver the lazy d", "g")); check("findList2", Arrays.asList("mark.twain")); check("findList3", Arrays.asList()); check("findList4", Arrays.asList("", "", "", "", "")); check("findList5", Arrays.asList("twain")); } public void test_stringlib_find_expect_error() { try { doCompile("string[] findList;function integer transform() {findList = find('mark.twain@javlin.eu','(^[a-z]*).([a-z]*)',5); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } } public void test_stringlib_join() { doCompile("test_stringlib_join"); //check("joinedString", "Bagr,3,3.5641,-87L,CTL2"); check("joinedString1", "80=5455.987\"-5=5455.987\"3=0.1"); check("joinedString2", "5.054.6567.0231.0"); //check("joinedString3", "554656723180=5455.987-5=5455.9873=0.1CTL242"); } public void test_stringlib_left() { doCompile("test_stringlib_left"); check("lef", "The q"); check("padded", "The q "); check("notPadded", "The q"); check("lef2", "The quick brown fox jumps over the lazy dog"); } public void test_stringlib_length() { doCompile("test_stringlib_length"); check("lenght1", new BigDecimal(50)); check("lenghtByte", 18); check("stringLength", 8); check("listLength", 8); check("mapLength", 3); check("recordLength", 9); } public void test_stringlib_lowerCase() { doCompile("test_stringlib_lowerCase"); check("lower", "the quick !!$ brown fox jumps over the lazy dog bagr "); } public void test_stringlib_matches() { doCompile("test_stringlib_matches"); check("matches1", true); check("matches2", true); check("matches3", false); check("matches4", true); check("matches5", false); check("matches6", false); check("matches7", false); check("matches8", false); check("matches9", true); check("matches10", true); } public void test_stringlib_matchGroups() { doCompile("test_stringlib_matchGroups"); check("result1", null); check("result2", Arrays.asList( //"(([^:]*)([:])([\\(]))(.*)(\\))((( "zip:(zip:(/path/name?.zip)#innerfolder/file.zip)#innermostfolder?/filename*.txt", "zip:(", "zip", ":", "(", "zip:(/path/name?.zip)#innerfolder/file.zip", ")", "#innermostfolder?/filename*.txt", "#innermostfolder?/filename*.txt", " "innermostfolder?/filename*.txt", null ) ); } public void test_stringlib_matchGroups_unmodifiable() { try { doCompile("test_stringlib_matchGroups_unmodifiable"); fail(); } catch (RuntimeException re) { }; } public void test_stringlib_metaphone() { doCompile("test_stringlib_metaphone"); check("metaphone1", "XRS"); check("metaphone2", "KWNTLN"); check("metaphone3", "KWNT"); } public void test_stringlib_nysiis() { doCompile("test_stringlib_nysiis"); check("nysiis1", "CAP"); check("nysiis2", "CAP"); check("nysiis3", "1234"); check("nysiis4", "C2 PRADACTAN"); } public void test_stringlib_replace() { doCompile("test_stringlib_replace"); final SimpleDateFormat format = new SimpleDateFormat(); format.applyPattern("yyyy MMM dd"); check("rep", format.format(new Date()).replaceAll("[lL]", "t")); check("rep1", "The cat says meow. All cats say meow."); } public void test_stringlib_right() { doCompile("test_stringlib_right"); check("righ", "y dog"); check("rightNotPadded", "y dog"); check("rightPadded", "y dog"); check("padded", " y dog"); check("notPadded", "y dog"); check("short", "Dog"); check("shortNotPadded", "Dog"); check("shortPadded", " Dog"); } public void test_stringlib_soundex() { doCompile("test_stringlib_soundex"); check("soundex1", "W630"); check("soundex2", "W643"); } public void test_stringlib_split() { doCompile("test_stringlib_split"); check("split1", Arrays.asList("The quick br", "wn f", "", " jumps " , "ver the lazy d", "g")); } public void test_stringlib_substring() { doCompile("test_stringlib_substring"); check("subs", "UICk "); } public void test_stringlib_trim() { doCompile("test_stringlib_trim"); check("trim1", "im The QUICk !!$ broWn fox juMPS over the lazy DOG"); } public void test_stringlib_upperCase() { doCompile("test_stringlib_upperCase"); check("upper", "THE QUICK !!$ BROWN FOX JUMPS OVER THE LAZY DOG BAGR "); } public void test_stringlib_isFormat() { doCompile("test_stringlib_isFormat"); check("test", "test"); check("isBlank", Boolean.FALSE); check("blank", ""); checkNull("nullValue"); check("isBlank2", true); check("isAscii1", true); check("isAscii2", false); check("isAscii3", false); check("isNumber", false); check("isNumber1", false); check("isNumber2", true); check("isNumber3", true); check("isNumber4", false); check("isNumber5", true); check("isNumber6", true); check("isInteger", false); check("isInteger1", false); check("isInteger2", false); check("isInteger3", true); check("isLong", true); check("isLong1", false); check("isLong2", false); check("isDate", true); check("isDate1", false); // "kk" allows hour to be 1-24 (as opposed to HH allowing hour to be 0-23) check("isDate2", true); check("isDate3", true); check("isDate4", false); check("isDate5", true); check("isDate6", true); check("isDate7", false); check("isDate9", false); check("isDate10", false); check("isDate11", false); check("isDate12", true); check("isDate13", false); check("isDate14", false); // empty string: invalid check("isDate15", false); check("isDate16", false); check("isDate17", true); check("isDate18", true); check("isDate19", false); check("isDate20", false); } public void test_stringlib_empty_strings() { String[] expressions = new String[] { "isInteger(?)", "isNumber(?)", "isLong(?)", "isAscii(?)", "isBlank(?)", "isDate(?, \"yyyy\")", "isUrl(?)", "string x = ?; length(x)", "lowerCase(?)", "matches(?, \"\")", "NYSIIS(?)", "removeBlankSpace(?)", "removeDiacritic(?)", "removeNonAscii(?)", "removeNonPrintable(?)", "replace(?, \"a\", \"a\")", "translate(?, \"ab\", \"cd\")", "trim(?)", "upperCase(?)", "chop(?)", "concat(?)", "getAlphanumericChars(?)", }; StringBuilder sb = new StringBuilder(); for (String expr : expressions) { String emptyString = expr.replace("?", "\"\""); boolean crashesEmpty = test_expression_crashes(emptyString); assertFalse("Function " + emptyString + " crashed", crashesEmpty); String nullString = expr.replace("?", "null"); boolean crashesNull = test_expression_crashes(nullString); sb.append(String.format("|%20s|%5s|%5s|%n", expr, crashesEmpty ? "CRASH" : "ok", crashesNull ? "CRASH" : "ok")); } System.out.println(sb.toString()); } private boolean test_expression_crashes(String expr) { String expStr = "function integer transform() { " + expr + "; return 0; }"; try { doCompile(expStr, "test_stringlib_empty_null_strings"); return false; } catch (RuntimeException e) { return true; } } public void test_stringlib_removeBlankSpace() { String expStr = "string r1;\n" + "function integer transform() {\n" + "r1=removeBlankSpace(\"" + StringUtils.specCharToString(" a b\nc\rd e \u000Cf\r\n") + "\");\n" + "printErr(r1);\n" + "return 0;\n" + "}\n"; doCompile(expStr, "test_removeBlankSpace"); check("r1", "abcdef"); } public void test_stringlib_removeNonPrintable() { doCompile("test_stringlib_removeNonPrintable"); check("nonPrintableRemoved", "AHOJ"); } public void test_stringlib_getAlphanumericChars() { String expStr = "string an1;\n" + "string an2;\n" + "string an3;\n" + "string an4;\n" + "string an5;\n" + "string an6;\n" + "string an7;\n" + "string an8;\n" + "function integer transform() {\n" + "an1=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\");\n" + "printErr(an1);\n" + "an2=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,true);\n" + "printErr(an2);\n" + "an3=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,false);\n" + "printErr(an3);\n" + "an4=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",false,true);\n" + "printErr(an4);\n" + "an5=getAlphanumericChars(\"\");\n" + "an6=getAlphanumericChars(\"\",true,true);\n"+ "an7=getAlphanumericChars(\"\",true,false);\n"+ "an8=getAlphanumericChars(\"\",false,true);\n"+ "return 0;\n" + "}\n"; doCompile(expStr, "test_getAlphanumericChars"); check("an1", "a1bcde2f"); check("an2", "a1bcde2f"); check("an3", "abcdef"); check("an4", "12"); check("an5", ""); check("an6", ""); check("an7", ""); check("an8", ""); } public void test_stringlib_indexOf(){ doCompile("test_stringlib_indexOf"); check("index",2); check("index1",9); check("index2",0); check("index3",-1); check("index4",6); } public void test_stringlib_removeDiacritic(){ doCompile("test_stringlib_removeDiacritic"); check("test","tescik"); check("test1","zabicka"); } public void test_stringlib_translate(){ doCompile("test_stringlib_translate"); check("trans","hippi"); check("trans1","hipp"); check("trans2","hippi"); check("trans3",""); check("trans4","y lanuaX nXXd thX lXttXr X"); } public void test_stringlib_chop() { doCompile("test_stringlib_chop"); check("s1", "hello"); check("s6", "hello"); check("s5", "hello"); check("s2", "hello"); check("s7", "helloworld"); check("s3", "hello "); check("s4", "hello"); check("s8", "hello"); check("s9", "world"); check("s10", "hello"); check("s11", "world"); check("s12", "mark.twain"); check("s13", "two words"); check("s14", ""); check("s15", ""); check("s16", ""); check("s17", ""); check("s18", ""); check("s19", "word"); check("s20", ""); } public void test_bitwise_or() { doCompile("test_bitwise_or"); check("resultInt1", 1); check("resultInt2", 1); check("resultInt3", 3); check("resultInt4", 3); check("resultLong1", 1l); check("resultLong2", 1l); check("resultLong3", 3l); check("resultLong4", 3l); } public void test_bitwise_and() { doCompile("test_bitwise_and"); check("resultInt1", 0); check("resultInt2", 1); check("resultInt3", 0); check("resultInt4", 1); check("resultLong1", 0l); check("resultLong2", 1l); check("resultLong3", 0l); check("resultLong4", 1l); } public void test_bitwise_xor() { doCompile("test_bitwise_xor"); check("resultInt1", 1); check("resultInt2", 0); check("resultInt3", 3); check("resultInt4", 2); check("resultLong1", 1l); check("resultLong2", 0l); check("resultLong3", 3l); check("resultLong4", 2l); } public void test_bitwise_lshift() { doCompile("test_bitwise_lshift"); check("resultInt1", 2); check("resultInt2", 4); check("resultInt3", 10); check("resultInt4", 20); check("resultLong1", 2l); check("resultLong2", 4l); check("resultLong3", 10l); check("resultLong4", 20l); } public void test_bitwise_rshift() { doCompile("test_bitwise_rshift"); check("resultInt1", 2); check("resultInt2", 0); check("resultInt3", 4); check("resultInt4", 2); check("resultLong1", 2l); check("resultLong2", 0l); check("resultLong3", 4l); check("resultLong4", 2l); } public void test_bitwise_negate() { doCompile("test_bitwise_negate"); check("resultInt", -59081717); check("resultLong", -3321654987654105969L); } public void test_set_bit() { doCompile("test_set_bit"); check("resultInt1", 0x2FF); check("resultInt2", 0xFB); check("resultLong1", 0x4000000000000l); check("resultLong2", 0xFFDFFFFFFFFFFFFl); check("resultBool1", true); check("resultBool2", false); check("resultBool3", true); check("resultBool4", false); } public void test_mathlib_abs() { doCompile("test_mathlib_abs"); check("absIntegerPlus", new Integer(10)); check("absIntegerMinus", new Integer(1)); check("absLongPlus", new Long(10)); check("absLongMinus", new Long(1)); check("absDoublePlus", new Double(10.0)); check("absDoubleMinus", new Double(1.0)); check("absDecimalPlus", new BigDecimal(5.0)); check("absDecimalMinus", new BigDecimal(5.0)); } public void test_mathlib_ceil() { doCompile("test_mathlib_ceil"); check("ceil1", -3.0); check("intResult", Arrays.asList(2.0, 3.0)); check("longResult", Arrays.asList(2.0, 3.0)); check("doubleResult", Arrays.asList(3.0, -3.0)); check("decimalResult", Arrays.asList(3.0, -3.0)); } public void test_mathlib_e() { doCompile("test_mathlib_e"); check("varE", Math.E); } public void test_mathlib_exp() { doCompile("test_mathlib_exp"); check("ex", Math.exp(1.123)); } public void test_mathlib_floor() { doCompile("test_mathlib_floor"); check("floor1", -4.0); check("intResult", Arrays.asList(2.0, 3.0)); check("longResult", Arrays.asList(2.0, 3.0)); check("doubleResult", Arrays.asList(2.0, -4.0)); check("decimalResult", Arrays.asList(2.0, -4.0)); } public void test_mathlib_log() { doCompile("test_mathlib_log"); check("ln", Math.log(3)); } public void test_mathlib_log10() { doCompile("test_mathlib_log10"); check("varLog10", Math.log10(3)); } public void test_mathlib_pi() { doCompile("test_mathlib_pi"); check("varPi", Math.PI); } public void test_mathlib_pow() { doCompile("test_mathlib_pow"); check("power1", Math.pow(3,1.2)); check("power2", Double.NaN); check("intResult", Arrays.asList(8d, 8d, 8d, 8d)); check("longResult", Arrays.asList(8d, 8d, 8d, 8d)); check("doubleResult", Arrays.asList(8d, 8d, 8d, 8d)); check("decimalResult", Arrays.asList(8d, 8d, 8d, 8d)); } public void test_mathlib_round() { doCompile("test_mathlib_round"); check("round1", -4l); check("intResult", Arrays.asList(2l, 3l)); check("longResult", Arrays.asList(2l, 3l)); check("doubleResult", Arrays.asList(2l, 4l)); check("decimalResult", Arrays.asList(2l, 4l)); } public void test_mathlib_sqrt() { doCompile("test_mathlib_sqrt"); check("sqrtPi", Math.sqrt(Math.PI)); check("sqrt9", Math.sqrt(9)); } public void test_datelib_cache() { doCompile("test_datelib_cache"); check("b11", true); check("b12", true); check("b21", true); check("b22", true); check("b31", true); check("b32", true); check("b41", true); check("b42", true); checkEquals("date3", "date3d"); checkEquals("date4", "date4d"); checkEquals("date7", "date7d"); checkEquals("date8", "date8d"); } public void test_datelib_trunc() { doCompile("test_datelib_trunc"); check("truncDate", new GregorianCalendar(2004, 00, 02).getTime()); } public void test_datelib_truncDate() { doCompile("test_datelib_truncDate"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)}; cal.clear(); cal.set(Calendar.HOUR_OF_DAY, portion[0]); cal.set(Calendar.MINUTE, portion[1]); cal.set(Calendar.SECOND, portion[2]); cal.set(Calendar.MILLISECOND, portion[3]); check("truncBornDate", cal.getTime()); } public void test_datelib_today() { doCompile("test_datelib_today"); Date expectedDate = new Date(); //the returned date does not need to be exactly the same date which is in expectedData variable //let say 1000ms is tolerance for equality assertTrue("todayDate", Math.abs(expectedDate.getTime() - ((Date) getVariable("todayDate")).getTime()) < 1000); } public void test_datelib_zeroDate() { doCompile("test_datelib_zeroDate"); check("zeroDate", new Date(0)); } public void test_datelib_dateDiff() { doCompile("test_datelib_dateDiff"); long diffYears = Years.yearsBetween(new DateTime(), new DateTime(BORN_VALUE)).getYears(); check("ddiff", diffYears); long[] results = {1, 12, 52, 365, 8760, 525600, 31536000, 31536000000L}; String[] vars = {"ddiffYears", "ddiffMonths", "ddiffWeeks", "ddiffDays", "ddiffHours", "ddiffMinutes", "ddiffSeconds", "ddiffMilliseconds"}; for (int i = 0; i < results.length; i++) { check(vars[i], results[i]); } } public void test_datelib_dateAdd() { doCompile("test_datelib_dateAdd"); check("datum", new Date(BORN_MILLISEC_VALUE + 100)); } public void test_datelib_extractTime() { doCompile("test_datelib_extractTime"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)}; cal.clear(); cal.set(Calendar.HOUR_OF_DAY, portion[0]); cal.set(Calendar.MINUTE, portion[1]); cal.set(Calendar.SECOND, portion[2]); cal.set(Calendar.MILLISECOND, portion[3]); check("bornExtractTime", cal.getTime()); check("originalDate", BORN_VALUE); } public void test_datelib_extractDate() { doCompile("test_datelib_extractDate"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); int[] portion = new int[]{cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH), cal.get(Calendar.YEAR)}; cal.clear(); cal.set(Calendar.DAY_OF_MONTH, portion[0]); cal.set(Calendar.MONTH, portion[1]); cal.set(Calendar.YEAR, portion[2]); check("bornExtractDate", cal.getTime()); check("originalDate", BORN_VALUE); } public void test_datelib_createDate() { doCompile("test_datelib_createDate"); Calendar cal = Calendar.getInstance(); // no time zone cal.clear(); cal.set(2013, 5, 11); check("date1", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); check("dateTime1", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); cal.set(Calendar.MILLISECOND, 123); check("dateTimeMillis1", cal.getTime()); // literal cal.setTimeZone(TimeZone.getTimeZone("GMT+5")); cal.clear(); cal.set(2013, 5, 11); check("date2", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); check("dateTime2", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); cal.set(Calendar.MILLISECOND, 123); check("dateTimeMillis2", cal.getTime()); // variable cal.clear(); cal.set(2013, 5, 11); check("date3", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); check("dateTime3", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); cal.set(Calendar.MILLISECOND, 123); check("dateTimeMillis3", cal.getTime()); } public void test_datelib_getPart() { doCompile("test_datelib_getPart"); Calendar cal = Calendar.getInstance(); cal.clear(); cal.setTimeZone(TimeZone.getTimeZone("GMT+1")); cal.set(2013, 5, 11, 14, 46, 34); cal.set(Calendar.MILLISECOND, 123); Date date = cal.getTime(); cal = Calendar.getInstance(); cal.setTime(date); // no time zone check("year1", cal.get(Calendar.YEAR)); check("month1", cal.get(Calendar.MONTH) + 1); check("day1", cal.get(Calendar.DAY_OF_MONTH)); check("hour1", cal.get(Calendar.HOUR_OF_DAY)); check("minute1", cal.get(Calendar.MINUTE)); check("second1", cal.get(Calendar.SECOND)); check("millisecond1", cal.get(Calendar.MILLISECOND)); cal.setTimeZone(TimeZone.getTimeZone("GMT+5")); // literal check("year2", cal.get(Calendar.YEAR)); check("month2", cal.get(Calendar.MONTH) + 1); check("day2", cal.get(Calendar.DAY_OF_MONTH)); check("hour2", cal.get(Calendar.HOUR_OF_DAY)); check("minute2", cal.get(Calendar.MINUTE)); check("second2", cal.get(Calendar.SECOND)); check("millisecond2", cal.get(Calendar.MILLISECOND)); // variable check("year3", cal.get(Calendar.YEAR)); check("month3", cal.get(Calendar.MONTH) + 1); check("day3", cal.get(Calendar.DAY_OF_MONTH)); check("hour3", cal.get(Calendar.HOUR_OF_DAY)); check("minute3", cal.get(Calendar.MINUTE)); check("second3", cal.get(Calendar.SECOND)); check("millisecond3", cal.get(Calendar.MILLISECOND)); } public void test_convertlib_cache() { // set default locale to en.US so the date is formatted uniformly on all systems Locale.setDefault(Locale.US); doCompile("test_convertlib_cache"); Calendar cal = Calendar.getInstance(); cal.set(2000, 6, 20, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Date checkDate = cal.getTime(); final SimpleDateFormat format = new SimpleDateFormat(); format.applyPattern("yyyy MMM dd"); check("sdate1", format.format(new Date())); check("sdate2", format.format(new Date())); check("date01", checkDate); check("date02", checkDate); check("date03", checkDate); check("date04", checkDate); check("date11", checkDate); check("date12", checkDate); check("date13", checkDate); } public void test_convertlib_base64byte() { doCompile("test_convertlib_base64byte"); assertTrue(Arrays.equals((byte[])getVariable("base64input"), Base64.decode("The quick brown fox jumps over the lazy dog"))); } public void test_convertlib_bits2str() { doCompile("test_convertlib_bits2str"); check("bitsAsString1", "00000000"); check("bitsAsString2", "11111111"); check("bitsAsString3", "010100000100110110100000"); } public void test_convertlib_bool2num() { doCompile("test_convertlib_bool2num"); check("resultTrue", 1); check("resultFalse", 0); } public void test_convertlib_byte2base64() { doCompile("test_convertlib_byte2base64"); check("inputBase64", Base64.encodeBytes("Abeceda zedla deda".getBytes())); } public void test_convertlib_byte2hex() { doCompile("test_convertlib_byte2hex"); check("hexResult", "41626563656461207a65646c612064656461"); } public void test_convertlib_date2long() { doCompile("test_convertlib_date2long"); check("bornDate", BORN_MILLISEC_VALUE); check("zeroDate", 0l); } public void test_convertlib_date2num() { doCompile("test_convertlib_date2num"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); check("yearDate", 1987); check("monthDate", 5); check("secondDate", 0); check("yearBorn", cal.get(Calendar.YEAR)); check("monthBorn", cal.get(Calendar.MONTH) + 1); //Calendar enumerates months from 0, not 1; check("secondBorn", cal.get(Calendar.SECOND)); check("yearMin", 1970); check("monthMin", 1); check("weekMin", 1); check("weekMinCs", 1); check("dayMin", 1); check("hourMin", 1); //TODO: check! check("minuteMin", 0); check("secondMin", 0); check("millisecMin", 0); } public void test_convertlib_date2str() { doCompile("test_convertlib_date2str"); check("inputDate", "1987:05:12"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd"); check("bornDate", sdf.format(BORN_VALUE)); SimpleDateFormat sdfCZ = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("cs.CZ")); check("czechBornDate", sdfCZ.format(BORN_VALUE)); SimpleDateFormat sdfEN = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("en")); check("englishBornDate", sdfEN.format(BORN_VALUE)); { String[] locales = {"en", "pl", null, "cs.CZ", null}; List<String> expectedDates = new ArrayList<String>(); for (String locale: locales) { expectedDates.add(new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale(locale)).format(BORN_VALUE)); } check("loopTest", expectedDates); } SimpleDateFormat sdfGMT8 = new SimpleDateFormat("yyyy:MMMM:dd z", MiscUtils.createLocale("en")); sdfGMT8.setTimeZone(TimeZone.getTimeZone("GMT+8")); check("timeZone", sdfGMT8.format(BORN_VALUE)); } public void test_convertlib_decimal2double() { doCompile("test_convertlib_decimal2double"); check("toDouble", 0.007d); } public void test_convertlib_decimal2integer() { doCompile("test_convertlib_decimal2integer"); check("toInteger", 0); check("toInteger2", -500); check("toInteger3", 1000000); } public void test_convertlib_decimal2long() { doCompile("test_convertlib_decimal2long"); check("toLong", 0l); check("toLong2", -500l); check("toLong3", 10000000000l); } public void test_convertlib_double2integer() { doCompile("test_convertlib_double2integer"); check("toInteger", 0); check("toInteger2", -500); check("toInteger3", 1000000); } public void test_convertlib_double2long() { doCompile("test_convertlib_double2long"); check("toLong", 0l); check("toLong2", -500l); check("toLong3", 10000000000l); } public void test_convertlib_getFieldName() { doCompile("test_convertlib_getFieldName"); check("fieldNames",Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency")); } public void test_convertlib_getFieldType() { doCompile("test_convertlib_getFieldType"); check("fieldTypes",Arrays.asList(DataFieldType.STRING.getName(), DataFieldType.NUMBER.getName(), DataFieldType.STRING.getName(), DataFieldType.DATE.getName(), DataFieldType.LONG.getName(), DataFieldType.INTEGER.getName(), DataFieldType.BOOLEAN.getName(), DataFieldType.BYTE.getName(), DataFieldType.DECIMAL.getName())); } public void test_convertlib_hex2byte() { doCompile("test_convertlib_hex2byte"); assertTrue(Arrays.equals((byte[])getVariable("fromHex"), BYTEARRAY_VALUE)); } public void test_convertlib_long2date() { doCompile("test_convertlib_long2date"); check("fromLong1", new Date(0)); check("fromLong2", new Date(50000000000L)); check("fromLong3", new Date(-5000L)); } public void test_convertlib_long2integer() { doCompile("test_convertlib_long2integer"); check("fromLong1", 10); check("fromLong2", -10); } public void test_convertlib_long2packDecimal() { doCompile("test_convertlib_long2packDecimal"); assertTrue(Arrays.equals((byte[])getVariable("packedLong"), new byte[] {5, 0, 12})); } public void test_convertlib_md5() { doCompile("test_convertlib_md5"); assertTrue(Arrays.equals((byte[])getVariable("md5Hash1"), Digest.digest(DigestType.MD5, "The quick brown fox jumps over the lazy dog"))); assertTrue(Arrays.equals((byte[])getVariable("md5Hash2"), Digest.digest(DigestType.MD5, BYTEARRAY_VALUE))); } public void test_convertlib_num2bool() { doCompile("test_convertlib_num2bool"); check("integerTrue", true); check("integerFalse", false); check("longTrue", true); check("longFalse", false); check("doubleTrue", true); check("doubleFalse", false); check("decimalTrue", true); check("decimalFalse", false); } public void test_convertlib_num2str() { System.out.println("num2str() test:"); doCompile("test_convertlib_num2str"); check("intOutput", Arrays.asList("16", "10000", "20", "10", "1.235E3", "12 350 001 Kcs")); check("longOutput", Arrays.asList("16", "10000", "20", "10", "1.235E13", "12 350 001 Kcs")); check("doubleOutput", Arrays.asList("16.16", "0x1.028f5c28f5c29p4", "1.23548E3", "12 350 001,1 Kcs")); check("decimalOutput", Arrays.asList("16.16", "1235.44", "12 350 001,1 Kcs")); } public void test_convertlib_packdecimal2long() { doCompile("test_convertlib_packDecimal2long"); check("unpackedLong", PackedDecimal.parse(BYTEARRAY_VALUE)); } public void test_convertlib_sha() { doCompile("test_convertlib_sha"); assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA, "The quick brown fox jumps over the lazy dog"))); assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA, BYTEARRAY_VALUE))); } public void test_convertlib_sha256() { doCompile("test_convertlib_sha256"); assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA256, "The quick brown fox jumps over the lazy dog"))); assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA256, BYTEARRAY_VALUE))); } public void test_convertlib_str2bits() { doCompile("test_convertlib_str2bits"); //TODO: uncomment -> test will pass, but is that correct? assertTrue(Arrays.equals((byte[]) getVariable("textAsBits1"), new byte[] {0/*, 0, 0, 0, 0, 0, 0, 0*/})); assertTrue(Arrays.equals((byte[]) getVariable("textAsBits2"), new byte[] {-1/*, 0, 0, 0, 0, 0, 0, 0*/})); assertTrue(Arrays.equals((byte[]) getVariable("textAsBits3"), new byte[] {10, -78, 5/*, 0, 0, 0, 0, 0*/})); } public void test_convertlib_str2bool() { doCompile("test_convertlib_str2bool"); check("fromTrueString", true); check("fromFalseString", false); } public void test_convertlib_str2date() { doCompile("test_convertlib_str2date"); Calendar cal = Calendar.getInstance(); cal.set(2050, 4, 19, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Date checkDate = cal.getTime(); check("date1", checkDate); check("date2", checkDate); cal.clear(); cal.setTimeZone(TimeZone.getTimeZone("GMT+8")); cal.set(2013, 04, 30, 17, 15, 12); check("withTimeZone1", cal.getTime()); cal.clear(); cal.setTimeZone(TimeZone.getTimeZone("GMT-8")); cal.set(2013, 04, 30, 17, 15, 12); check("withTimeZone2", cal.getTime()); assertFalse(getVariable("withTimeZone1").equals(getVariable("withTimeZone2"))); } public void test_convertlib_str2decimal() { doCompile("test_convertlib_str2decimal"); check("parsedDecimal1", new BigDecimal("100.13")); check("parsedDecimal2", new BigDecimal("123123123.123")); check("parsedDecimal3", new BigDecimal("-350000.01")); check("parsedDecimal4", new BigDecimal("1000000")); check("parsedDecimal5", new BigDecimal("1000000.99")); check("parsedDecimal6", new BigDecimal("123123123.123")); } public void test_convertlib_str2double() { doCompile("test_convertlib_str2double"); check("parsedDouble1", 100.13); check("parsedDouble2", 123123123.123); check("parsedDouble3", -350000.01); } public void test_convertlib_str2integer() { doCompile("test_convertlib_str2integer"); check("parsedInteger1", 123456789); check("parsedInteger2", 123123); check("parsedInteger3", -350000); check("parsedInteger4", 419); } public void test_convertlib_str2long() { doCompile("test_convertlib_str2long"); check("parsedLong1", 1234567890123L); check("parsedLong2", 123123123456789L); check("parsedLong3", -350000L); check("parsedLong4", 133L); } public void test_convertlib_toString() { doCompile("test_convertlib_toString"); check("integerString", "10"); check("longString", "110654321874"); check("doubleString", "1.547874E-14"); check("decimalString", "-6847521431.1545874"); check("listString", "[not ALI A, not ALI B, not ALI D..., but, ALI H!]"); check("mapString", "{1=Testing, 2=makes, 3=me, 4=crazy :-)}"); String byteMapString = getVariable("byteMapString").toString(); assertTrue(byteMapString.contains("1=value1")); assertTrue(byteMapString.contains("2=value2")); String fieldByteMapString = getVariable("fieldByteMapString").toString(); assertTrue(fieldByteMapString.contains("key1=value1")); assertTrue(fieldByteMapString.contains("key2=value2")); check("byteListString", "[firstElement, secondElement]"); check("fieldByteListString", "[firstElement, secondElement]"); } public void test_convertlib_str2byte() { doCompile("test_convertlib_str2byte"); checkArray("utf8Hello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("utf8Horse", new byte[] { 80, -59, -103, -61, -83, 108, 105, -59, -95, 32, -59, -66, 108, 117, -59, -91, 111, 117, -60, -115, 107, -61, -67, 32, 107, -59, -81, -59, -120, 32, 112, -60, -101, 108, 32, -60, -113, -61, -95, 98, 108, 115, 107, -61, -87, 32, -61, -77, 100, 121 }); checkArray("utf8Math", new byte[] { -62, -67, 32, -30, -123, -109, 32, -62, -68, 32, -30, -123, -107, 32, -30, -123, -103, 32, -30, -123, -101, 32, -30, -123, -108, 32, -30, -123, -106, 32, -62, -66, 32, -30, -123, -105, 32, -30, -123, -100, 32, -30, -123, -104, 32, -30, -126, -84, 32, -62, -78, 32, -62, -77, 32, -30, -128, -96, 32, -61, -105, 32, -30, -122, -112, 32, -30, -122, -110, 32, -30, -122, -108, 32, -30, -121, -110, 32, -30, -128, -90, 32, -30, -128, -80, 32, -50, -111, 32, -50, -110, 32, -30, -128, -109, 32, -50, -109, 32, -50, -108, 32, -30, -126, -84, 32, -50, -107, 32, -50, -106, 32, -49, -128, 32, -49, -127, 32, -49, -126, 32, -49, -125, 32, -49, -124, 32, -49, -123, 32, -49, -122, 32, -49, -121, 32, -49, -120, 32, -49, -119 }); checkArray("utf16Hello", new byte[] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 }); checkArray("utf16Horse", new byte[] { -2, -1, 0, 80, 1, 89, 0, -19, 0, 108, 0, 105, 1, 97, 0, 32, 1, 126, 0, 108, 0, 117, 1, 101, 0, 111, 0, 117, 1, 13, 0, 107, 0, -3, 0, 32, 0, 107, 1, 111, 1, 72, 0, 32, 0, 112, 1, 27, 0, 108, 0, 32, 1, 15, 0, -31, 0, 98, 0, 108, 0, 115, 0, 107, 0, -23, 0, 32, 0, -13, 0, 100, 0, 121 }); checkArray("utf16Math", new byte[] { -2, -1, 0, -67, 0, 32, 33, 83, 0, 32, 0, -68, 0, 32, 33, 85, 0, 32, 33, 89, 0, 32, 33, 91, 0, 32, 33, 84, 0, 32, 33, 86, 0, 32, 0, -66, 0, 32, 33, 87, 0, 32, 33, 92, 0, 32, 33, 88, 0, 32, 32, -84, 0, 32, 0, -78, 0, 32, 0, -77, 0, 32, 32, 32, 0, 32, 0, -41, 0, 32, 33, -112, 0, 32, 33, -110, 0, 32, 33, -108, 0, 32, 33, -46, 0, 32, 32, 38, 0, 32, 32, 48, 0, 32, 3, -111, 0, 32, 3, -110, 0, 32, 32, 19, 0, 32, 3, -109, 0, 32, 3, -108, 0, 32, 32, -84, 0, 32, 3, -107, 0, 32, 3, -106, 0, 32, 3, -64, 0, 32, 3, -63, 0, 32, 3, -62, 0, 32, 3, -61, 0, 32, 3, -60, 0, 32, 3, -59, 0, 32, 3, -58, 0, 32, 3, -57, 0, 32, 3, -56, 0, 32, 3, -55 }); checkArray("macHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("macHorse", new byte[] { 80, -34, -110, 108, 105, -28, 32, -20, 108, 117, -23, 111, 117, -117, 107, -7, 32, 107, -13, -53, 32, 112, -98, 108, 32, -109, -121, 98, 108, 115, 107, -114, 32, -105, 100, 121 }); checkArray("asciiHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("isoHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("isoHorse", new byte[] { 80, -8, -19, 108, 105, -71, 32, -66, 108, 117, -69, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 }); checkArray("cpHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("cpHorse", new byte[] { 80, -8, -19, 108, 105, -102, 32, -98, 108, 117, -99, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 }); } public void test_convertlib_byte2str() { doCompile("test_convertlib_byte2str"); String hello = "Hello World!"; String horse = "Příliš žluťoučký kůň pěl ďáblské ódy"; String math = "½ ⅓ ¼ ⅕ ⅙ ⅛ ⅔ ⅖ ¾ ⅗ ⅜ ⅘ € ² ³ † × ← → ↔ ⇒ … ‰ Α Β – Γ Δ € Ε Ζ π ρ ς σ τ υ φ χ ψ ω"; check("utf8Hello", hello); check("utf8Horse", horse); check("utf8Math", math); check("utf16Hello", hello); check("utf16Horse", horse); check("utf16Math", math); check("macHello", hello); check("macHorse", horse); check("asciiHello", hello); check("isoHello", hello); check("isoHorse", horse); check("cpHello", hello); check("cpHorse", horse); } public void test_conditional_fail() { doCompile("test_conditional_fail"); check("result", 3); } public void test_expression_statement(){ // test case for issue 4174 doCompileExpectErrors("test_expression_statement", Arrays.asList("Syntax error, statement expected","Syntax error, statement expected")); } public void test_dictionary_read() { doCompile("test_dictionary_read"); check("s", "Verdon"); check("i", Integer.valueOf(211)); check("l", Long.valueOf(226)); check("d", BigDecimal.valueOf(239483061)); check("n", Double.valueOf(934.2)); check("a", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime()); check("b", true); byte[] y = (byte[]) getVariable("y"); assertEquals(10, y.length); assertEquals(89, y[9]); check("sNull", null); check("iNull", null); check("lNull", null); check("dNull", null); check("nNull", null); check("aNull", null); check("bNull", null); check("yNull", null); check("stringList", Arrays.asList("aa", "bb", null, "cc")); check("dateList", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000))); @SuppressWarnings("unchecked") List<byte[]> byteList = (List<byte[]>) getVariable("byteList"); assertDeepEquals(byteList, Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78})); } public void test_dictionary_write() { doCompile("test_dictionary_write"); assertEquals(832, graph.getDictionary().getValue("i") ); assertEquals("Guil", graph.getDictionary().getValue("s")); assertEquals(Long.valueOf(540), graph.getDictionary().getValue("l")); assertEquals(BigDecimal.valueOf(621), graph.getDictionary().getValue("d")); assertEquals(934.2, graph.getDictionary().getValue("n")); assertEquals(new GregorianCalendar(1992, GregorianCalendar.DECEMBER, 2).getTime(), graph.getDictionary().getValue("a")); assertEquals(true, graph.getDictionary().getValue("b")); byte[] y = (byte[]) graph.getDictionary().getValue("y"); assertEquals(2, y.length); assertEquals(18, y[0]); assertEquals(-94, y[1]); assertEquals(Arrays.asList("xx", null), graph.getDictionary().getValue("stringList")); assertEquals(Arrays.asList(new Date(98000), null, new Date(76000)), graph.getDictionary().getValue("dateList")); @SuppressWarnings("unchecked") List<byte[]> byteList = (List<byte[]>) graph.getDictionary().getValue("byteList"); assertDeepEquals(byteList, Arrays.asList(null, new byte[] {(byte) 0xAB, (byte) 0xCD}, new byte[] {(byte) 0xEF})); check("assignmentReturnValue", "Guil"); } public void test_dictionary_write_null() { doCompile("test_dictionary_write_null"); assertEquals(null, graph.getDictionary().getValue("s")); assertEquals(null, graph.getDictionary().getValue("sVerdon")); assertEquals(null, graph.getDictionary().getValue("i") ); assertEquals(null, graph.getDictionary().getValue("i211") ); assertEquals(null, graph.getDictionary().getValue("l")); assertEquals(null, graph.getDictionary().getValue("l452")); assertEquals(null, graph.getDictionary().getValue("d")); assertEquals(null, graph.getDictionary().getValue("d621")); assertEquals(null, graph.getDictionary().getValue("n")); assertEquals(null, graph.getDictionary().getValue("n9342")); assertEquals(null, graph.getDictionary().getValue("a")); assertEquals(null, graph.getDictionary().getValue("a1992")); assertEquals(null, graph.getDictionary().getValue("b")); assertEquals(null, graph.getDictionary().getValue("bTrue")); assertEquals(null, graph.getDictionary().getValue("y")); assertEquals(null, graph.getDictionary().getValue("yFib")); } public void test_dictionary_invalid_key(){ doCompileExpectErrors("test_dictionary_invalid_key", Arrays.asList("Dictionary entry 'invalid' does not exist")); } public void test_dictionary_string_to_int(){ doCompileExpectErrors("test_dictionary_string_to_int", Arrays.asList("Type mismatch: cannot convert from 'string' to 'integer'","Type mismatch: cannot convert from 'string' to 'integer'")); } public void test_utillib_sleep() { long time = System.currentTimeMillis(); doCompile("test_utillib_sleep"); long tmp = System.currentTimeMillis() - time; assertTrue("sleep() function didn't pause execution "+ tmp, tmp >= 1000); } public void test_utillib_random_uuid() { doCompile("test_utillib_random_uuid"); assertNotNull(getVariable("uuid")); } public void test_stringlib_validUrl() { doCompile("test_stringlib_url"); check("urlValid", Arrays.asList(true, true, false, true, false, true)); check("protocol", Arrays.asList("http", "https", null, "sandbox", null, "zip")); check("userInfo", Arrays.asList("", "chuck:norris", null, "", null, "")); check("host", Arrays.asList("example.com", "server.javlin.eu", null, "cloveretl.test.scenarios", null, "")); check("port", Arrays.asList(-1, 12345, -2, -1, -2, -1)); check("path", Arrays.asList("", "/backdoor/trojan.cgi", null, "/graph/UDR_FileURL_SFTP_OneGzipFileSpecified.grf", null, "(sftp://test:test@koule/home/test/data-in/file2.zip)")); check("query", Arrays.asList("", "hash=SHA560;god=yes", null, "", null, "")); check("ref", Arrays.asList("", "autodestruct", null, "", null, "innerfolder2/URLIn21.txt")); } public void test_stringlib_escapeUrl() { doCompile("test_stringlib_escapeUrl"); check("escaped", "http://example.com/foo%20bar%5E"); check("unescaped", "http://example.com/foo bar^"); } public void test_stringlib_resolveParams() { doCompile("test_stringlib_resolveParams"); check("resultNoParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in"); check("resultFalseFalseParams", "Special character representing new line is: \\n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in"); check("resultTrueFalseParams", "Special character representing new line is: \n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in"); check("resultFalseTrueParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in"); check("resultTrueTrueParams", "Special character representing new line is: \n calling CTL function MESSAGE; $DATAIN_DIR=./data-in"); } public void test_utillib_getEnvironmentVariables() { doCompile("test_utillib_getEnvironmentVariables"); check("empty", false); } public void test_utillib_getJavaProperties() { String key1 = "my.testing.property"; String key2 = "my.testing.property2"; String value = "my value"; String value2; assertNull(System.getProperty(key1)); assertNull(System.getProperty(key2)); System.setProperty(key1, value); try { doCompile("test_utillib_getJavaProperties"); value2 = System.getProperty(key2); } finally { System.clearProperty(key1); assertNull(System.getProperty(key1)); System.clearProperty(key2); assertNull(System.getProperty(key2)); } check("java_specification_name", "Java Platform API Specification"); check("my_testing_property", value); assertEquals("my value 2", value2); } public void test_utillib_getParamValues() { doCompile("test_utillib_getParamValues"); Map<String, String> params = new HashMap<String, String>(); params.put("PROJECT", "."); params.put("DATAIN_DIR", "./data-in"); params.put("COUNT", "3"); params.put("NEWLINE", "\\n"); // special characters should NOT be resolved check("params", params); } public void test_utillib_getParamValue() { doCompile("test_utillib_getParamValue"); Map<String, String> params = new HashMap<String, String>(); params.put("PROJECT", "."); params.put("DATAIN_DIR", "./data-in"); params.put("COUNT", "3"); params.put("NEWLINE", "\\n"); // special characters should NOT be resolved params.put("NONEXISTING", null); check("params", params); } public void test_stringlib_getUrlParts() { doCompile("test_stringlib_getUrlParts"); List<Boolean> isUrl = Arrays.asList(true, true, true, true, false); List<String> path = Arrays.asList( "/users/a6/15e83578ad5cba95c442273ea20bfa/msf-183/out5.txt", "/data-in/fileOperation/input.txt", "/data/file.txt", "/data/file.txt", null); List<String> protocol = Arrays.asList("sftp", "sandbox", "ftp", "https", null); List<String> host = Arrays.asList( "ava-fileManipulator1-devel.getgooddata.com", "cloveretl.test.scenarios", "ftp.test.com", "www.test.com", null); List<Integer> port = Arrays.asList(-1, -1, 21, 80, -2); List<String> userInfo = Arrays.asList( "user%40gooddata.com:password", "", "test:test", "test:test", null); List<String> ref = Arrays.asList("", "", "", "", null); List<String> query = Arrays.asList("", "", "", "", null); check("isUrl", isUrl); check("path", path); check("protocol", protocol); check("host", host); check("port", port); check("userInfo", userInfo); check("ref", ref); check("query", query); check("isURL_empty", false); check("path_empty", null); check("protocol_empty", null); check("host_empty", null); check("port_empty", -2); check("userInfo_empty", null); check("ref_empty", null); check("query_empty", null); check("isURL_null", false); check("path_null", null); check("protocol_null", null); check("host_null", null); check("port_null", -2); check("userInfo_null", null); check("ref_null", null); check("query_empty", null); } public void test_randomlib_randomDate() { doCompile("test_randomlib_randomDate"); final long HOUR = 60L * 60L * 1000L; Date BORN_VALUE_NO_MILLIS = new Date(BORN_VALUE.getTime() / 1000L * 1000L); check("noTimeZone1", BORN_VALUE); check("noTimeZone2", BORN_VALUE_NO_MILLIS); check("withTimeZone1", new Date(BORN_VALUE_NO_MILLIS.getTime() + 2*HOUR)); // timezone changes from GMT+5 to GMT+3 check("withTimeZone2", new Date(BORN_VALUE_NO_MILLIS.getTime() - 2*HOUR)); // timezone changes from GMT+3 to GMT+5 } }
package com.cube.storm.ui.view; import com.cube.storm.ui.model.Model; import com.cube.storm.ui.view.holder.ViewHolderController; import com.cube.storm.ui.view.holder.grid.GridItemHolder; import com.cube.storm.ui.view.holder.grid.ImageGridItemHolder; import com.cube.storm.ui.view.holder.grid.StandardGridItemHolder; import com.cube.storm.ui.view.holder.list.AnimatedImageListItemHolder; import com.cube.storm.ui.view.holder.list.AppCollectionItemHolder; import com.cube.storm.ui.view.holder.list.ButtonListItemHolder; import com.cube.storm.ui.view.holder.list.CheckableListItemHolder; import com.cube.storm.ui.view.holder.list.CollectionListItemHolder; import com.cube.storm.ui.view.holder.list.DescriptionListItemHolder; import com.cube.storm.ui.view.holder.list.DividerHolder; import com.cube.storm.ui.view.holder.list.HeaderListItemHolder; import com.cube.storm.ui.view.holder.list.ImageListItemHolder; import com.cube.storm.ui.view.holder.list.ListFooterHolder; import com.cube.storm.ui.view.holder.list.ListHeaderHolder; import com.cube.storm.ui.view.holder.list.LogoListItemHolder; import com.cube.storm.ui.view.holder.list.OrderedListItemHolder; import com.cube.storm.ui.view.holder.list.SpotlightImageListItemHolder; import com.cube.storm.ui.view.holder.list.StandardListItemHolder; import com.cube.storm.ui.view.holder.list.TextListItemHolder; import com.cube.storm.ui.view.holder.list.TitleListItemHolder; import com.cube.storm.ui.view.holder.list.ToggleableListItemHolder; import com.cube.storm.ui.view.holder.list.UnorderedListItemHolder; import com.cube.storm.ui.view.holder.list.VideoListItemHolder; /** * This is the enum class with the list of all supported view types, their model classes and their * corresponding view holder class. This list should not be modified or overridden * * @author Callum Taylor * @project LightningUi */ public enum View { /** * Private views - These are not driven by the CMS, these are internal classes derived from * the list model. */ _ListHeader(com.cube.storm.ui.model.list.List.ListHeader.class, ListHeaderHolder.class), _ListFooter(com.cube.storm.ui.model.list.List.ListFooter.class, ListFooterHolder.class), _Divider(com.cube.storm.ui.model.list.Divider.class, DividerHolder.class), /** * List items */ List(com.cube.storm.ui.model.list.List.class, null), TextListItem(com.cube.storm.ui.model.list.TextListItem.class, TextListItemHolder.class), ImageListItem(com.cube.storm.ui.model.list.ImageListItem.class, ImageListItemHolder.class), TitleListItem(com.cube.storm.ui.model.list.TitleListItem.class, TitleListItemHolder.class), DescriptionListItem(com.cube.storm.ui.model.list.DescriptionListItem.class, DescriptionListItemHolder.class), StandardListItem(com.cube.storm.ui.model.list.StandardListItem.class, StandardListItemHolder.class), OrderedListItem(com.cube.storm.ui.model.list.OrderedListItem.class, OrderedListItemHolder.class), UnorderedListItem(com.cube.storm.ui.model.list.UnorderedListItem.class, UnorderedListItemHolder.class), CheckableListItem(com.cube.storm.ui.model.list.CheckableListItem.class, CheckableListItemHolder.class), ButtonListItem(com.cube.storm.ui.model.list.ButtonListItem.class, ButtonListItemHolder.class), ToggleableListItem(com.cube.storm.ui.model.list.ToggleableListItem.class, ToggleableListItemHolder.class), LogoListItem(com.cube.storm.ui.model.list.LogoListItem.class, LogoListItemHolder.class), VideoListItem(com.cube.storm.ui.model.list.VideoListItem.class, VideoListItemHolder.class), SpotlightImageListItem(com.cube.storm.ui.model.list.SpotlightImageListItem.class, SpotlightImageListItemHolder.class), AnimatedImageListItem(com.cube.storm.ui.model.list.AnimatedImageListItem.class, AnimatedImageListItemHolder.class), HeaderListItem(com.cube.storm.ui.model.list.HeaderListItem.class, HeaderListItemHolder.class), /** * Grid items */ Grid(com.cube.storm.ui.model.grid.Grid.class, null), GridItem(com.cube.storm.ui.model.grid.GridItem.class, GridItemHolder.class), StandardGridItem(com.cube.storm.ui.model.grid.StandardGridItem.class, StandardGridItemHolder.class), ImageGridItem(com.cube.storm.ui.model.grid.ImageGridItem.class, ImageGridItemHolder.class), /** * Collection cells */ CollectionListItem(com.cube.storm.ui.model.list.collection.CollectionListItem.class, CollectionListItemHolder.class), AppCollectionItem(com.cube.storm.ui.model.list.collection.AppCollectionItem.class, AppCollectionItemHolder.class), /** * Pages */ ListPage(com.cube.storm.ui.model.page.ListPage.class, null), GridPage(com.cube.storm.ui.model.page.GridPage.class, null), TabbedPageCollection(com.cube.storm.ui.model.page.TabbedPageCollection.class, null), /** * Descriptors */ PageDescriptor(com.cube.storm.ui.model.descriptor.PageDescriptor.class, null), TabbedPageDescriptor(com.cube.storm.ui.model.descriptor.TabbedPageDescriptor.class, null), /** * Properties */ Image(com.cube.storm.ui.model.property.BundleImageProperty.class, null), NativeImage(com.cube.storm.ui.model.property.NativeImageProperty.class, null), Icon(com.cube.storm.ui.model.property.BundleImageProperty.class, null), AnimationImage(com.cube.storm.ui.model.property.AnimationImageProperty.class, null), SpotlightImage(com.cube.storm.ui.model.property.SpotlightImageProperty.class, null), DestinationLink(com.cube.storm.ui.model.property.DestinationLinkProperty.class, null), InternalLink(com.cube.storm.ui.model.property.InternalLinkProperty.class, null), ExternalLink(com.cube.storm.ui.model.property.ExternalLinkProperty.class, null), UriLink(com.cube.storm.ui.model.property.UriLinkProperty.class, null), NativeLink(com.cube.storm.ui.model.property.NativeLinkProperty.class, null); private Class<? extends Model> model; private Class<? extends ViewHolderController> holder; private View(Class<? extends Model> model, Class<? extends ViewHolderController> holder) { this.model = model; this.holder = holder; } /** * @return Gets the holder class of the view */ public Class<? extends ViewHolderController> getHolderClass() { return holder; } /** * @return Gets the model class of the view */ public Class<? extends Model> getModelClass() { return model; } }
package fr.lip6.jkernelmachines.util.algebra; /** * This class provides level 1 (vector) basic linear algebra operations. * @author picard * */ public class VectorOperations { /** * Performs a linear combination of 2 vectors and store the result in a newly allocated array C: * C = A + lambda * B * @param A first vector * @param lambda weight of the second vector * @param B second vector * @return A + lambda * B */ public static double[] add(final double[] A, final double lambda, final double[] B) { double[] out = new double[A.length]; addi(out, A, lambda, B); return out; } /** * Performs a linear combination of 2 vectors and store the result in an already allocated array C: * C = A + lambda * B * @param C output vector * @param A first vector * @param lambda weight of the second vector * @param B second vector * @return C */ public static double[] addi(double[] C, final double[] A, final double lambda, final double[] B) { int packed = 2 * (A.length / 2); int l = 0; // packed operations for(l = 0 ; l < packed ; l += 2) { C[l] = A[l] + lambda*B[l]; C[l+1] = A[l+1] + lambda*B[l+1]; } // remaining operations for(; l < A.length ; l++) { C[l] = A[l] + lambda*B[l]; } return C; } /** * Multiply a given double array by a constant double: * C = lambda * A * @param A the input array * @param lambda the constant * @return a new array containing the result */ public static double[] mul(final double[] A, final double lambda) { double[] out = new double[A.length]; muli(out, A, lambda); return out; } /** * Multiply a given double array by a constant double: * C = lambda * A * @param A the input array * @param lambda the constant * @return a new array containing the result */ public static double[] muli(double[] C, final double[] A, final double lambda) { int packed = 2 * (A.length / 2); int l = 0; // packed operations for(l = 0 ; l < packed ; l += 2) { C[l] = A[l]*lambda; C[l+1] = A[l+1]*lambda; } // remaining operations for(; l < A.length ; l++) { C[l] = A[l]*lambda; } return C; } /** * Computes the dot product between to double arrays * @param a first array * @param b second array * @return the dot product between A and B */ public static double dot(final double[] A, final double[] B) { double sum = 0; int packed = 2 * (A.length / 2); int k = 0; //packed operations for(k = 0 ; k < packed ; k+=2) { sum += A[k]*B[k] + A[k+1]*B[k+1]; } // remaining operations for(; k < A.length; k++) { sum += A[k]*B[k]; } return sum; } /** * Computes the l2 norm of a double array * @param A the array * @return the l2 norm of A */ public static double n2(final double[] A) { return Math.sqrt(dot(A, A)); } /** * Computes the squared l2 norm of a double array * @param A the array * @return the squared l2 norm of A */ public static double n2p2(final double[] A) { return dot(A, A); } }
package edu.depaul.armada.dao; import static org.junit.Assert.*; import java.util.List; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import edu.depaul.armada.domain.Container; /** * @author ptrzyna * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"/beans/armada-config-test.xml"}) @TransactionConfiguration(transactionManager="operationsTransactionManager") @Transactional public class ContainerDaoTest { @Autowired private ContainerDao<Container> _dao; /** * Test method for {@link edu.depaul.armada.dao.ContainerDao#store(java.lang.Object)}. */ @DirtiesContext @Test public void testStore() { try { _dao.store(null); fail("Expected IllegalArgumentException!"); } catch(IllegalArgumentException iae) { assertEquals("Container instance cannot be null!", iae.getMessage()); } Container container = new Container(); _dao.store(container); List<Container> containers = _dao.getAll(); assertEquals(1, containers.size()); } /** * Test method for {@link edu.depaul.armada.dao.ContainerDao#getAll()}. */ @DirtiesContext @Test public void testGetAll() { Container container = new Container(); _dao.store(container); List<Container> containers = _dao.getAll(); assertEquals(1, containers.size()); } /** * Test method for {@link edu.depaul.armada.dao.ContainerDao#get(long, int)}. */ @Test @Ignore public void testGet() { fail("Not yet implemented"); } /** * Test method for {@link edu.depaul.armada.dao.ContainerDao#findWithDockerId(java.lang.String)}. */ @Test @Ignore public void testFindWithDockerId() { fail("Not yet implemented"); } }
package com.skligys.cardboardcreeper; import android.content.res.Resources; import android.opengl.Matrix; import android.os.SystemClock; import android.util.Log; import com.skligys.cardboardcreeper.model.Block; import com.skligys.cardboardcreeper.model.Chunk; import com.skligys.cardboardcreeper.model.Point3; import com.skligys.cardboardcreeper.perlin.Generator; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; /** Holds a randomly generated hilly landscape of blocks and Steve. */ class World { private static final String TAG = "World"; /** * Do several physics iterations per frame to avoid falling through the floor when dt is large. */ private static final int PHYSICS_ITERATIONS_PER_FRAME = 5; /** Perlin 3d noise based world generator. */ private final Generator generator; /** Lock for synchronizing access to blocks and chunkBlocks from GL and chunk loader threads. */ private final Object blocksLock = new Object(); /** * All blocks in the world. Written from chunk loader thread. Read from chunk loader thread * to create per chunk meshes and from GL thread to perform physics updates per frame. */ private final Set<Block> blocks = new HashSet<Block>(); /** * Maps chunk coordinates to a list of blocks inside the chunk. Written from chunk loader thread. * Read from chunk loader thread to create per chunk meshes and from GL thread during * initialization to determine initial Steve's position. */ private final Map<Chunk, List<Block>> chunkBlocks = new HashMap<Chunk, List<Block>>(); /** OpenGL support for drawing grass blocks. */ private final SquareMesh squareMesh = new SquareMesh(); private final Performance performance = new Performance(); private final Steve steve; private final Physics physics = new Physics(); /** Pre-allocated temporary matrix. */ private final float[] viewProjectionMatrix = new float[16]; private static interface ChunkChange {} private static class ChunkLoad implements ChunkChange { private final Chunk chunk; ChunkLoad(Chunk chunk) { this.chunk = chunk; } } private static class ChunkUnload implements ChunkChange { private final Chunk chunk; ChunkUnload(Chunk chunk) { this.chunk = chunk; } } private final BlockingDeque<ChunkChange> chunkChanges = new LinkedBlockingDeque<ChunkChange>(); private final Thread chunkLoader; World() { generator = new Generator(new Random().nextInt()); // Start the thread for loading chunks in the background. chunkLoader = createChunkLoader(); chunkLoader.start(); List<Chunk> preloadedChunks = preloadedChunks(); for (Chunk chunk : preloadedChunks) { chunkChanges.add(new ChunkLoad(chunk)); } // Wait for the background thread to finish loading all of them. The whole stack of chunks // around the starting position is needed to determine Steve's initial position's y coordinate. while (chunkChanges.size() > 0) { SystemClock.sleep(100L); } int startX = Chunk.CHUNK_SIZE / 2; int startZ = Chunk.CHUNK_SIZE / 2; steve = new Steve(startPosition(startX, startZ)); // Schedule neighboring chunks to load in the background. Chunk currChunk = steve.currentChunk(); Set<Chunk> chunksToLoad = neighboringChunks(currChunk); chunksToLoad.removeAll(preloadedChunks); for (Chunk chunk : chunksToLoad) { chunkChanges.add(new ChunkLoad(chunk)); } } private List<Chunk> preloadedChunks() { // Generate a stack of chunks around the starting position (8, 8), other chunks will be loaded // in the background. int minYChunk = Generator.minElevation() / Chunk.CHUNK_SIZE; int maxYChunk = (Generator.maxElevation() + Chunk.CHUNK_SIZE - 1) / Chunk.CHUNK_SIZE; List<Chunk> preloadedChunks = new ArrayList<Chunk>(); for (int y = minYChunk; y <= maxYChunk; ++y) { preloadedChunks.add(new Chunk(0, y, 0)); } return preloadedChunks; } /** Finds the highest solid block with given xz coordinates and returns it. */ private Block startPosition(int x, int z) { return new Block(x, highestSolidY(x, z), z); } /** Given (x,z) coordinates, finds and returns the highest y so that (x,y,z) is a solid block. */ private int highestSolidY(int x, int z) { int maxY = Generator.minElevation(); int chunkX = x / Chunk.CHUNK_SIZE; int chunkZ = z / Chunk.CHUNK_SIZE; synchronized(blocksLock) { for (Chunk chunk : chunkBlocks.keySet()) { if (chunk.x != chunkX || chunk.z != chunkZ) { continue; } for (Block block : chunkBlocks.get(chunk)) { if (block.x != x || block.z != z) { continue; } if (block.y > maxY) { maxY = block.y; } } } } return maxY; } private static final int SHOWN_CHUNK_RADIUS = 3; /** Returns chunks within some radius of center, but only those containing any blocks. */ private Set<Chunk> neighboringChunks(Chunk center) { Set<Chunk> result = new HashSet<Chunk>(); for (int dx = -SHOWN_CHUNK_RADIUS; dx <= SHOWN_CHUNK_RADIUS; ++dx) { for (int dy = -SHOWN_CHUNK_RADIUS; dy <= SHOWN_CHUNK_RADIUS; ++dy) { for (int dz = -SHOWN_CHUNK_RADIUS; dz <= SHOWN_CHUNK_RADIUS; ++dz) { if (!chunkShown(dx, dy, dz)) { continue; } Chunk chunk = center.plus(new Chunk(dx, dy, dz)); result.add(chunk); } } } return result; } private static boolean chunkShown(int dx, int dy, int dz) { return dx * dx + dy * dy + dz * dz <= SHOWN_CHUNK_RADIUS * SHOWN_CHUNK_RADIUS; } /** Asynchronous chunk loader. */ private Thread createChunkLoader() { Runnable runnable = new Runnable() { @Override public void run() { while (true) { try { ChunkChange cc = chunkChanges.takeFirst(); if (cc instanceof ChunkLoad) { Chunk chunk = ((ChunkLoad) cc).chunk; synchronized(blocksLock) { loadChunk(chunk); squareMesh.load(chunk, shownBlocks(chunkBlocks.get(chunk)), blocks); } } else if (cc instanceof ChunkUnload) { Chunk chunk = ((ChunkUnload) cc).chunk; synchronized(blocksLock) { unloadChunk(chunk); squareMesh.unload(chunk); } } else { throw new RuntimeException("Unknown ChunkChange subtype: " + cc.getClass().getName()); } } catch (InterruptedException e) { throw new RuntimeException(e); } SystemClock.sleep(1); } } }; return new Thread(runnable); } /** Adds blocks within a single chunk generated based on 3d Perlin noise. */ private void loadChunk(Chunk chunk) { if (chunkBlocks.keySet().contains(chunk)) { return; } List<Block> blocksInChunk = generator.generateChunk(chunk); Log.i(TAG, "Loading chunk " + chunk + ", " + blocksInChunk.size() + " blocks"); addChunkBlocks(chunk, blocksInChunk); } private void addChunkBlocks(Chunk chunk, List<Block> blocksInChunk) { blocks.addAll(blocksInChunk); chunkBlocks.put(chunk, blocksInChunk); } private void unloadChunk(Chunk chunk) { List<Block> blocksInChunk = chunkBlocks.get(chunk); if (blocksInChunk == null) { return; } Log.i(TAG, "Unloading chunk " + chunk + ", " + blocksInChunk.size() + " blocks"); chunkBlocks.remove(chunk); blocks.removeAll(blocksInChunk); } private List<Block> shownBlocks(List<Block> blocks) { List<Block> result = new ArrayList<Block>(); if (blocks == null) { return result; } for (Block block : blocks) { if (exposed(block)) { result.add(block); } } return result; } /** * Checks all 6 faces of the given block and returns true if at least one face is not covered * by another block in {@code blocks}. */ private boolean exposed(Block block) { return !blocks.contains(new Block(block.x - 1, block.y, block.z)) || !blocks.contains(new Block(block.x + 1, block.y, block.z)) || !blocks.contains(new Block(block.x, block.y - 1, block.z)) || !blocks.contains(new Block(block.x, block.y + 1, block.z)) || !blocks.contains(new Block(block.x, block.y, block.z - 1)) || !blocks.contains(new Block(block.x, block.y, block.z + 1)); } void surfaceCreated(Resources resources) { squareMesh.surfaceCreated(resources); } void draw(float[] projectionMatrix) { // This has to be first to have up to date tick timestamp for FPS computation. float dt = Math.min(performance.tick(), 0.2f); performance.startPhysics(); Point3 eyePosition = null; synchronized(blocksLock) { // Do several physics iterations per frame to avoid falling through the floor when dt is large. for (int i = 0; i < PHYSICS_ITERATIONS_PER_FRAME; ++i) { // Physics needs all blocks in the world to compute collisions. eyePosition = physics.updateEyePosition(steve, dt / PHYSICS_ITERATIONS_PER_FRAME, blocks); } } performance.endPhysics(); Chunk beforeChunk = steve.currentChunk(); Chunk afterChunk = new Chunk(eyePosition); if (!afterChunk.equals(beforeChunk)) { queueChunkLoads(beforeChunk, afterChunk); steve.setCurrentChunk(afterChunk); } performance.startRendering(); Matrix.multiplyMM(viewProjectionMatrix, 0, projectionMatrix, 0, steve.viewMatrix(), 0); squareMesh.draw(viewProjectionMatrix); performance.endRendering(); float fps = performance.fps(); if (fps > 0.0f) { Point3 position = steve.position(); String status; synchronized(blocksLock) { status = String.format("%f FPS (%f-%f), " + "(%f, %f, %f), " + "%d / %d chunks, %d blocks, " + "physics: %dms, render: %dms", fps, performance.minFps(), performance.maxFps(), position.x, position.y, position.z, squareMesh.chunksLoaded(), chunkBlocks.keySet().size(), blocks.size(), performance.physicsSpent(), performance.renderSpent()); } Log.i(TAG, status); } performance.done(); } private void queueChunkLoads(Chunk beforeChunk, Chunk afterChunk) { Set<Chunk> beforeShownChunks = neighboringChunks(beforeChunk); Set<Chunk> afterShownChunks = neighboringChunks(afterChunk); // chunksToLoad = afterShownChunks \ beforeShownChunks // chunksToUnload = beforeShownChunks \ afterShownChunks for (Chunk chunk : setDiff(afterShownChunks, beforeShownChunks)) { chunkChanges.add(new ChunkLoad(chunk)); } for (Chunk chunk : setDiff(beforeShownChunks, afterShownChunks)) { chunkChanges.add(new ChunkUnload(chunk)); } } private static <T> Set<T> setDiff(Set<T> s1, Set<T> s2) { Set<T> result = new HashSet<T>(s1); result.removeAll(s2); return result; } void drag(float dx, float dy) { steve.rotate(dx, dy); } void walk(boolean start) { steve.walk(start); } }
package org.smoothbuild.testing; import static org.smoothbuild.SmoothConstants.CHARSET; import static org.smoothbuild.lang.base.Location.unknownLocation; import static org.smoothbuild.util.Lists.list; import java.io.IOException; import org.smoothbuild.db.hashed.HashedDb; import org.smoothbuild.db.outputs.OutputDb; import org.smoothbuild.exec.task.Container; import org.smoothbuild.io.fs.base.FileSystem; import org.smoothbuild.io.fs.base.Path; import org.smoothbuild.io.fs.base.SynchronizedFileSystem; import org.smoothbuild.io.fs.mem.MemoryFileSystem; import org.smoothbuild.io.util.TempManager; import org.smoothbuild.lang.base.Field; import org.smoothbuild.lang.object.base.Array; import org.smoothbuild.lang.object.base.ArrayBuilder; import org.smoothbuild.lang.object.base.Blob; import org.smoothbuild.lang.object.base.BlobBuilder; import org.smoothbuild.lang.object.base.Bool; import org.smoothbuild.lang.object.base.SObject; import org.smoothbuild.lang.object.base.SString; import org.smoothbuild.lang.object.base.Struct; import org.smoothbuild.lang.object.base.StructBuilder; import org.smoothbuild.lang.object.db.ObjectDb; import org.smoothbuild.lang.object.db.ObjectFactory; import org.smoothbuild.lang.object.type.BlobType; import org.smoothbuild.lang.object.type.BoolType; import org.smoothbuild.lang.object.type.ConcreteArrayType; import org.smoothbuild.lang.object.type.ConcreteType; import org.smoothbuild.lang.object.type.NothingType; import org.smoothbuild.lang.object.type.StringType; import org.smoothbuild.lang.object.type.StructType; import org.smoothbuild.lang.object.type.TypeType; import org.smoothbuild.lang.plugin.NativeApi; import okio.ByteString; public class TestingContext { private Container container; private ObjectFactory objectFactory; private ObjectFactory emptyCacheObjectFactory; private OutputDb outputDb; private FileSystem outputDbFileSystem; private ObjectDb objectDb; private HashedDb hashedDb; private FileSystem hashedDbFileSystem; private FileSystem fullFileSystem; private TempManager tempManager; private FileSystem tempManagerFileSystem; public NativeApi nativeApi() { return container(); } public Container container() { if (container == null) { container = new Container(fullFileSystem(), objectFactory(), tempManager()); } return container; } /** * instance with File and Message types */ public ObjectFactory objectFactory() { if (objectFactory == null) { objectFactory = new TestingObjectFactory(objectDb()); } return objectFactory; } /** * instance without File and Message types cached */ public ObjectFactory emptyCacheObjectFactory() { if (emptyCacheObjectFactory == null) { emptyCacheObjectFactory = new ObjectFactory(objectDb()); } return emptyCacheObjectFactory; } public ObjectDb objectDb() { if (objectDb == null) { objectDb = ObjectDb.objectDb(hashedDb()); } return objectDb; } public OutputDb outputDb() { if (outputDb == null) { outputDb = new OutputDb(outputDbFileSystem(), objectDb(), objectFactory()); } return outputDb; } public FileSystem outputDbFileSystem() { if (outputDbFileSystem == null) { outputDbFileSystem = new MemoryFileSystem(); } return outputDbFileSystem; } public ObjectDb objectDbOther() { return ObjectDb.objectDb(hashedDb()); } public HashedDb hashedDb() { if (hashedDb == null) { hashedDb = new HashedDb( hashedDbFileSystem(), Path.root(), tempManager()); } return hashedDb; } public FileSystem hashedDbFileSystem() { if (hashedDbFileSystem == null) { hashedDbFileSystem = new SynchronizedFileSystem(new MemoryFileSystem()); } return hashedDbFileSystem; } public TempManager tempManager() { if (tempManager == null) { tempManager = new TempManager(tempManagerFileSystem()); } return tempManager; } public FileSystem tempManagerFileSystem() { if (tempManagerFileSystem == null) { tempManagerFileSystem = new SynchronizedFileSystem(new MemoryFileSystem()); } return tempManagerFileSystem; } public FileSystem fullFileSystem() { if (fullFileSystem == null) { fullFileSystem = new SynchronizedFileSystem(new MemoryFileSystem()); } return fullFileSystem; } public TypeType typeType() { return objectDb().typeType(); } public BoolType boolType() { return objectDb().boolType(); } public StringType stringType() { return objectDb().stringType(); } public BlobType blobType() { return objectDb().blobType(); } public NothingType nothingType() { return objectDb().nothingType(); } public ConcreteArrayType arrayType(ConcreteType elementType) { return objectDb().arrayType(elementType); } public StructType structType(String name, Iterable<Field> fields) { return objectDb().structType(name, fields); } public StructType emptyType() { return structType("Empty", list()); } public StructType personType() { ConcreteType string = stringType(); return structType("Person", list( new Field(string, "firstName", unknownLocation()), new Field(string, "lastName", unknownLocation()))); } public StructType fileType() { return structType("File", list( new Field(blobType(), "content", unknownLocation()), new Field(stringType(), "path", unknownLocation()))); } public Bool bool(boolean value) { return objectDb().bool(value); } public SString string(String string) { return objectDb().string(string); } public BlobBuilder blobBuilder() { return objectDb().blobBuilder(); } public ArrayBuilder arrayBuilder(ConcreteType elemType) { return objectDb().arrayBuilder(elemType); } public StructBuilder structBuilder(StructType type) { return objectDb().structBuilder(type); } public Struct empty() { return structBuilder(emptyType()).build(); } public Struct person(String firstName, String lastName) { return structBuilder(personType()) .set("firstName", string(firstName)) .set("lastName", string(lastName)) .build(); } public Array messageArrayWithOneError() { return array(objectFactory().errorMessage("error message")); } public Array emptyMessageArray() { return array(objectFactory().messageType()); } public <T extends SObject> Array array(SObject... elements) { return array(elements[0].type(), elements); } public <T extends SObject> Array array(ConcreteType elementType, SObject... elements) { return objectDb().arrayBuilder(elementType).addAll(list(elements)).build(); } public SObject errorMessage(String text) { return objectFactory().errorMessage(text); } public SObject warningMessage(String text) { return objectFactory().warningMessage(text); } public SObject infoMessage(String text) { return objectFactory().infoMessage(text); } public Struct file(Path path) { return file(path, ByteString.encodeString(path.value(), CHARSET)); } public Struct file(Path path, ByteString content) { SString string = objectFactory().string(path.value()); Blob blob = blob(content); return objectFactory().file(string, blob); } public Blob blob(ByteString bytes) { try { return objectFactory().blob(sink -> sink.write(bytes)); } catch (IOException e) { throw new RuntimeException(e); } } public static class TestingObjectFactory extends ObjectFactory { public TestingObjectFactory(ObjectDb objectDb) { super(objectDb); structType("File", list( new Field(blobType(), "content", unknownLocation()), new Field(stringType(), "path", unknownLocation()))); structType("Message", list( new Field(stringType(), "text", unknownLocation()), new Field(stringType(), "severity", unknownLocation()))); } } }
package net.ichigotake.yancha.login; import net.ichigotake.yancha.R; import net.ichigotake.yancha.chat.ChatFragment; import net.ichigotake.yancha.data.User; import net.ichigotake.yancha.net.YanchaAuth; import net.ichigotake.yancha.ui.FragmentTransit; import net.ichigotake.yancha.ui.ViewContainer; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; public class LoginContainer implements ViewContainer { final private Fragment fragment; final private YanchaAuth auth; final private User user; public LoginContainer(Fragment fragment) { this.fragment = fragment; this.auth = new YanchaAuth(fragment.getActivity()); this.user = new User(fragment.getActivity()); } @Override public void initializeView(View view) { view.findViewById(R.id.loginAuthSimpleSend).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { EditText nicknameTextView = (EditText) fragment.getActivity().findViewById(R.id.loginAuthSimpleNickname); String nickname = nicknameTextView.getText().toString(); auth.simpleLogin(nickname); new FragmentTransit(fragment).toNext(ChatFragment.newInstance()); } }); EditText loginSimple = (EditText) view.findViewById(R.id.loginAuthSimpleNickname); loginSimple.setText(user.getNickname()); loginSimple.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { EditText nicknameTextView = (EditText) fragment.getActivity().findViewById(R.id.loginAuthSimpleNickname); String nickname = nicknameTextView.getText().toString(); auth.simpleLogin(nickname); new FragmentTransit(fragment).toNext(ChatFragment.newInstance()); return false; } }); view.findViewById(R.id.loginAuthTwitter).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new FragmentTransit(fragment).toNext(ChatFragment.newInstance()); } }); } }
package org.kitchenstudio.entity; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.validation.Valid; import org.hibernate.validator.constraints.NotBlank; @Entity(name = "TABLE_ORDER") public class Order { @Id @GeneratedValue private Long id; @ManyToOne(optional = false) @JoinColumn(name = "CUST_ID", nullable = false) private Staff operator; @NotBlank(message = "") private String lessor; @NotBlank(message = "") private String lessee; @OneToMany(orphanRemoval = true) @JoinColumn(name = "ORDER_ID") @Valid private List<OrderItem> orderItems = new ArrayList<OrderItem>(); @Enumerated(EnumType.STRING) private OrderType type; @ManyToOne @JoinColumn(name = "DRIVER_ID") private Driver driver; @ManyToOne @JoinColumn(name = "CONTRACT_ID") private Contract contract; public Contract getContract() { return contract; } public void setContract(Contract contract) { this.contract = contract; } public OrderType getType() { return type; } public void setType(OrderType type) { this.type = type; } public List<OrderItem> getOrderItems() { return orderItems; } public void setOrderItems(List<OrderItem> orderItems) { this.orderItems = orderItems; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Staff getOperator() { return operator; } public void setOperator(Staff operator) { this.operator = operator; } public String getLessor() { return lessor; } public void setLessor(String lessor) { this.lessor = lessor; } public String getLessee() { return lessee; } public void setLessee(String lessee) { this.lessee = lessee; } public Driver getDriver() { return driver; } public void setDriver(Driver driver) { this.driver = driver; } }
package agaricus.mods.highlighttips; import cpw.mods.fml.client.registry.KeyBindingRegistry; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.ITickHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.TickType; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.registry.TickRegistry; import cpw.mods.fml.relauncher.FMLRelauncher; import cpw.mods.fml.relauncher.Side; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumMovingObjectType; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.Configuration; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.liquids.ILiquidTank; import net.minecraftforge.liquids.ITankContainer; import net.minecraftforge.liquids.LiquidStack; import java.util.EnumSet; import java.util.logging.Level; @Mod(modid = "HighlightTips", name = "HighlightTips", version = "1.0-SNAPSHOT") // TODO: version from resource @NetworkMod(clientSideRequired = false, serverSideRequired = false) public class HighlightTips implements ITickHandler { private static final int DEFAULT_KEY_TOGGLE = 62; private static final double DEFAULT_RANGE = 300; private static final int DEFAULT_X = 0; private static final int DEFAULT_Y = 0; private static final int DEFAULT_COLOR = 0xffffff; private boolean enable = true; private int keyToggle = DEFAULT_KEY_TOGGLE; private double range = DEFAULT_RANGE; private int x = DEFAULT_X; private int y = DEFAULT_Y; private int color = DEFAULT_COLOR; private ToggleKeyHandler toggleKeyHandler; @Mod.PreInit public void preInit(FMLPreInitializationEvent event) { Configuration cfg = new Configuration(event.getSuggestedConfigurationFile()); try { cfg.load(); enable = cfg.get(Configuration.CATEGORY_GENERAL, "enable", true).getBoolean(true); keyToggle = cfg.get(Configuration.CATEGORY_GENERAL, "key.toggle", DEFAULT_KEY_TOGGLE).getInt(DEFAULT_KEY_TOGGLE); range = cfg.get(Configuration.CATEGORY_GENERAL, "range", DEFAULT_RANGE).getDouble(DEFAULT_RANGE); x = cfg.get(Configuration.CATEGORY_GENERAL, "x", DEFAULT_X).getInt(DEFAULT_X); y = cfg.get(Configuration.CATEGORY_GENERAL, "y", DEFAULT_Y).getInt(DEFAULT_Y); color = cfg.get(Configuration.CATEGORY_GENERAL, "color", DEFAULT_COLOR).getInt(DEFAULT_COLOR); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "HighlightTips had a problem loading it's configuration"); } finally { cfg.save(); } if (!FMLRelauncher.side().equals("CLIENT")) { // gracefully disable on non-client (= server) instead of crashing enable = false; } if (!enable) { FMLLog.log(Level.INFO, "HighlightTips disabled"); return; } TickRegistry.registerTickHandler(this, Side.CLIENT); KeyBindingRegistry.registerKeyBinding(toggleKeyHandler = new ToggleKeyHandler(keyToggle)); } private String describeBlock(int id, int meta, TileEntity tileEntity) { StringBuilder sb = new StringBuilder(); describeBlockID(sb, id, meta); describeTileEntity(sb, tileEntity); return sb.toString(); } private void describeTileEntity(StringBuilder sb, TileEntity te) { if (te == null) return; sb.append(te.getClass().getName()); sb.append(' '); if (te instanceof ITankContainer) { sb.append(" ITankContainer: "); ILiquidTank[] tanks = ((ITankContainer) te).getTanks(ForgeDirection.UP); for (ILiquidTank tank : tanks) { sb.append(describeLiquidStack(tank.getLiquid())); sb.append(' '); //sb.append(tank.getTankPressure()); // TODO: tank capacity *used*? this is not it.. //sb.append('/'); sb.append(tank.getCapacity()); int pressure = tank.getTankPressure(); if (pressure < 0) { sb.append(pressure); } else { sb.append('+'); sb.append(pressure); } sb.append(' '); } } } private String describeLiquidStack(LiquidStack liquidStack) { if (liquidStack == null) return "Empty"; ItemStack itemStack = liquidStack.canonical().asItemStack(); if (itemStack == null) return "Empty"; return itemStack.getDisplayName(); } private void describeBlockID(StringBuilder sb, int id, int meta) { Block block = Block.blocksList[id]; if (block == null) { sb.append("block return; } // block info sb.append(id); sb.append(':'); sb.append(meta); sb.append(' '); String blockName = block.getLocalizedName(); sb.append(blockName); // item info, if it was mined (this often has more user-friendly information, but sometimes is identical) sb.append(" "); int itemDropDamage = block.damageDropped(meta); if (Item.itemsList[id + 256] != null) { ItemStack itemDropStack = new ItemStack(id, 1, itemDropDamage); String itemDropName = itemDropStack.getDisplayName(); if (!blockName.equals(itemDropName)) { sb.append(itemDropName); } // item info guess if item damage corresponds to block metadata, not necessarily if mined - sometimes more informative try { ItemStack itemMetaStack = new ItemStack(id, 1, meta); String itemMetaName = itemMetaStack.getDisplayName(); if (itemMetaName != null && !blockName.equals(itemMetaName) && !itemDropName.equals(itemMetaName)) { sb.append(' '); sb.append(itemMetaName); } } catch (Throwable t) { } } if (itemDropDamage != meta) { sb.append(' '); sb.append(itemDropDamage); } } // copied from net/minecraft/item/Item since it is needlessly protected protected MovingObjectPosition getMovingObjectPositionFromPlayer(World par1World, EntityPlayer par2EntityPlayer, boolean isBucketEmpty) { float f = 1.0F; float f1 = par2EntityPlayer.prevRotationPitch + (par2EntityPlayer.rotationPitch - par2EntityPlayer.prevRotationPitch) * f; float f2 = par2EntityPlayer.prevRotationYaw + (par2EntityPlayer.rotationYaw - par2EntityPlayer.prevRotationYaw) * f; double d0 = par2EntityPlayer.prevPosX + (par2EntityPlayer.posX - par2EntityPlayer.prevPosX) * (double)f; double d1 = par2EntityPlayer.prevPosY + (par2EntityPlayer.posY - par2EntityPlayer.prevPosY) * (double)f + 1.62D - (double)par2EntityPlayer.yOffset; double d2 = par2EntityPlayer.prevPosZ + (par2EntityPlayer.posZ - par2EntityPlayer.prevPosZ) * (double)f; Vec3 vec3 = par1World.getWorldVec3Pool().getVecFromPool(d0, d1, d2); float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI); float f5 = -MathHelper.cos(-f1 * 0.017453292F); float f6 = MathHelper.sin(-f1 * 0.017453292F); float f7 = f4 * f5; float f8 = f3 * f5; double d3 = 5.0D; if (par2EntityPlayer instanceof EntityPlayerMP) { d3 = ((EntityPlayerMP)par2EntityPlayer).theItemInWorldManager.getBlockReachDistance(); } Vec3 vec31 = vec3.addVector((double)f7 * d3, (double)f6 * d3, (double)f8 * d3); return par1World.rayTraceBlocks_do_do(vec3, vec31, isBucketEmpty, !isBucketEmpty); } @Override public void tickEnd(EnumSet<TickType> type, Object... tickData) { if (!toggleKeyHandler.showInfo) return; Minecraft mc = Minecraft.getMinecraft(); GuiScreen screen = mc.currentScreen; if (screen != null) return; float partialTickTime = 1; MovingObjectPosition mop = getMovingObjectPositionFromPlayer(mc.theWorld, mc.thePlayer, true); String s; if (mop == null) { return; } else if (mop.typeOfHit == EnumMovingObjectType.ENTITY) { // TODO: find out why this apparently never triggers s = "entity " + mop.entityHit.getClass().getName(); } else if (mop.typeOfHit == EnumMovingObjectType.TILE) { int id = mc.thePlayer.worldObj.getBlockId(mop.blockX, mop.blockY, mop.blockZ); int meta = mc.thePlayer.worldObj.getBlockMetadata(mop.blockX, mop.blockY, mop.blockZ); TileEntity tileEntity = mc.thePlayer.worldObj.blockHasTileEntity(mop.blockX, mop.blockY, mop.blockZ) ? mc.thePlayer.worldObj.getBlockTileEntity(mop.blockX, mop.blockY, mop.blockZ) : null; try { s = describeBlock(id, meta, tileEntity); } catch (Throwable t) { s = id + ":" + meta + " - " + t; t.printStackTrace(); } } else { s = "unknown"; } mc.fontRenderer.drawStringWithShadow(s, x, y, color); } @Override public void tickStart(EnumSet<TickType> type, Object... tickData) { } @Override public EnumSet<TickType> ticks() { return EnumSet.of(TickType.RENDER); } @Override public String getLabel() { return "HighlightTips"; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package homesoil; import com.google.common.base.*; import com.google.common.collect.*; import java.util.*; import org.bukkit.*; import org.bukkit.block.*; import org.bukkit.event.*; import org.bukkit.event.world.*; import org.bukkit.plugin.*; import org.bukkit.scheduler.*; // TODO: we need to respawn the chunk with the lava pillar in it on server restart. /** * DoomSchedule regenerates the world, a chunk at a time. Each chunk is filled * with a Warning- presently a stream of lava- before it is regenerated. Home * chunks are skipped. * * The dooms schedule passes through loaded chunks in straight lines. It is not * guaranteed to hit every chunk; it passes through a random x or z row, then * picks another. * * @author DanJ and AppleJinx */ public final class DoomSchedule extends BukkitRunnable implements Listener { private final HomeSoilPlugin plugin; public DoomSchedule(HomeSoilPlugin plugin) { this.plugin = Preconditions.checkNotNull(plugin); } // Scheduling /** * This delay is how many ticks we wait between segments of the doom * pillars. */ private final int doomSegmentDelay = 16; /** * This delay is how long we wait between doom pillars; we compute this to * be long enough that only one pillar at a time is in play. */ private final int doomChunkDelay = doomSegmentDelay * 16; /** * This method is called to start the task; it schedules it to run * regularly, and also hooks up events so we can tell what chunks are * loaded. * * @param plugin The plugin object for home soil; we register events with * this. */ public void start(Plugin plugin) { plugin.getServer().getPluginManager().registerEvents(this, plugin); runTaskTimer(plugin, 10, doomChunkDelay); } /** * This method is called to stop the task, when the plugin is disabled; it * also unregisters the events, so its safe to call start() again to begin * all over again. */ public void stop() { cancel(); HandlerList.unregisterAll(this); } @Override public void run() { if (!loadedChunks.isEmpty()) { if (doomSchedule.isEmpty()) { prepareDoomSchedule(); } if (!doomSchedule.isEmpty()) { ChunkPosition where = doomSchedule.get(0); if (!plugin.getPlayerInfos().getHomeChunks().contains(where)) { //System.out.println(String.format( // "Doom at %d, %d", where.x * 16 + 8, where.z * 16 + 8)); // Removed server log message because placing is so constant placeSegmentOfDoomLater(where, 15); } //we need to remove the entry whether or not we placed a pillar //because if it's a home chunk, otherwise it freezes doomSchedule.remove(0); } } } // Pillars of Doom /** * This method does not do anything now, but schedules a segment of the * pillar; this segment fills a 16x16x16 area, specified in chunk * co-ordinates. The topmost chunk is at chunkY=15. * * We start the doom pillar by passing 15 here. After a delay, the chunk * will be updated, and then this method is called again to do the next * lower chunk. When we hit 0, we regenerate instead of building a doom * pillar. * * @param where The chunk to be filled with doom. * @param chunkY The y-chunk to affect. If 0, we regenerate instead. */ private void placeSegmentOfDoomLater(final ChunkPosition where, final int chunkY) { new BukkitRunnable() { @Override public void run() { placeSegmentOfDoom(where, chunkY); } }.runTaskLater(plugin, doomSegmentDelay); } /** * This method places a doom pillar segment; if chunkY is 0, this * regenerates the chunk. * * If it does not regenerate the chunk, then it will schedule the next chunk * of the pillar. This means we don't need to keep so many runnables alive * at once. * * @param where The chunk to be filled with doom. * @param chunkY The y-chunk to affect. If 0, we regenerate instead. */ private void placeSegmentOfDoom(ChunkPosition where, int chunkY) { World world = where.getWorld(plugin.getServer()); if (chunkY <= 0) { world.regenerateChunk(where.x, where.z); } else { int top = chunkY * 16; int centerX = (where.x * 16) + 8; int centerZ = (where.z * 16) + 8; for (int y = top - 16; y < top; ++y) { Location loc = new Location(world, centerX, y, centerZ); Block block = world.getBlockAt(loc); block.setType(Material.LAVA); } Location thunderLoc = new Location(world, centerX, top, centerZ); float thunderPitch = (0.5f + (top / 512)); world.playSound(thunderLoc, Sound.AMBIENCE_THUNDER, 8.0f, thunderPitch); placeSegmentOfDoomLater(where, chunkY - 1); } } // Path of Doom private final List<ChunkPosition> doomSchedule = Lists.newArrayList(); private final Random regenRandom = new Random(); /** * This method generates the doomSchedule, the list of chunks we mean to * visit. Once a chunk is doomed, nothing (but a server reset) can save it. * We pick randomly which direction to run the schedule. */ private void prepareDoomSchedule() { boolean isX = regenRandom.nextBoolean(); boolean reversed = regenRandom.nextBoolean(); int index = regenRandom.nextInt(loadedChunks.size()); ChunkPosition origin = loadedChunks.get(index); doomSchedule.clear(); if (isX) { getLoadedChunkXRow(doomSchedule, origin.x); } else { getLoadedChunkZRow(doomSchedule, origin.z); } if (reversed) { Collections.sort(doomSchedule, Collections.reverseOrder()); } else { Collections.sort(doomSchedule); } } /** * This method finds every loaded chunk whose 'x' co-ordinate matches the * parameter, and adds each one to 'destination'. * * @param destination The collection to populate. * @param x The chunk-x co-ordinate for the row you want. */ private void getLoadedChunkXRow(Collection<ChunkPosition> destination, int x) { for (ChunkPosition pos : loadedChunks) { if (pos.x == x) { destination.add(pos); } } } /** * This method finds every loaded chunk whose 'z' co-ordinate matches the * parameter, and adds each one to 'destination'. * * @param destination The collection to populate. * @param z The chunk-z co-ordinate for the row you want. */ private void getLoadedChunkZRow(Collection<ChunkPosition> destination, int z) { for (ChunkPosition pos : loadedChunks) { if (pos.z == z) { destination.add(pos); } } } // Chunk tracking private final List<ChunkPosition> loadedChunks = Lists.newArrayList(); @EventHandler public void onChunkLoad(ChunkLoadEvent e) { Chunk chunk = e.getChunk(); if (chunk.getWorld().getEnvironment() == World.Environment.NORMAL) { loadedChunks.add(ChunkPosition.of(chunk)); } } @EventHandler public void onChunkUnload(ChunkUnloadEvent e) { Chunk chunk = e.getChunk(); if (chunk.getWorld().getEnvironment() == World.Environment.NORMAL) { loadedChunks.remove(ChunkPosition.of(chunk)); } } }
package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.orm.jpa.EntityScan; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import com.fasterxml.uuid.EthernetAddress; import com.fasterxml.uuid.Generators; import com.fasterxml.uuid.impl.TimeBasedGenerator; @SpringBootApplication @EnableJpaAuditing @EntityScan(basePackageClasses = {DemoApplication.class, org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters.class}) public class DemoApplication { private static final TimeBasedGenerator UUID_GENERATOR = Generators.timeBasedGenerator(EthernetAddress.fromInterface()); public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } public static UUIDGenerator uuidGenerator() { return () -> UUID_GENERATOR.generate(); } }
package org.voltdb.messaging; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import org.voltcore.messaging.Subject; import org.voltcore.messaging.VoltMessage; import org.voltcore.utils.MiscUtils; import org.voltdb.VoltTable; import org.voltdb.exceptions.SerializableException; /** * Message from an execution site which is participating in a transaction * to the stored procedure coordinator for that transaction. The contents * are the tables output by the plan fragments and a status code. In the * event of an error, a text message can be embedded in a table attached. * */ public class FragmentResponseMessage extends VoltMessage { public static final byte SUCCESS = 1; public static final byte USER_ERROR = 2; public static final byte UNEXPECTED_ERROR = 3; long m_executorHSId; long m_destinationHSId; long m_txnId; byte m_status; // default dirty to true until proven otherwise // Not currently used; leaving it in for now boolean m_dirty = true; boolean m_recovering = false; // WHA? Why do we have a separate dependency count when // the array lists will tell you their lengths? Doesn't look like // we do anything else with this value other than track the length short m_dependencyCount = 0; ArrayList<Integer> m_dependencyIds = new ArrayList<Integer>(); ArrayList<VoltTable> m_dependencies = new ArrayList<VoltTable>(); SerializableException m_exception; /** Empty constructor for de-serialization */ FragmentResponseMessage() { m_subject = Subject.DEFAULT.getId(); } public FragmentResponseMessage(FragmentTaskMessage task, long HSId) { m_executorHSId = HSId; m_txnId = task.getTxnId(); m_destinationHSId = task.getCoordinatorHSId(); m_subject = Subject.DEFAULT.getId(); } /** * If the status code is failure then an exception may be included. * @param status * @param e */ public void setStatus(byte status, SerializableException e) { m_status = status; m_exception = e; } public boolean isRecovering() { return m_recovering; } public void setRecovering(boolean recovering) { m_recovering = recovering; } public void addDependency(int dependencyId, VoltTable table) { m_dependencyIds.add(dependencyId); m_dependencies.add(table); m_dependencyCount++; } public long getExecutorSiteId() { return m_executorHSId; } public long getDestinationSiteId() { return m_destinationHSId; } public long getTxnId() { return m_txnId; } public byte getStatusCode() { return m_status; } public int getTableCount() { return m_dependencyCount; } public int getTableDependencyIdAtIndex(int index) { return m_dependencyIds.get(index); } public VoltTable getTableAtIndex(int index) { return m_dependencies.get(index); } public RuntimeException getException() { return m_exception; } @Override public int getSerializedSize() { int msgsize = super.getSerializedSize(); msgsize += 8 // executorHSId + 8 // destinationHSId + 8 // txnId + 1 // status byte + 1 // dirty flag + 1 // node recovering flag + 2; // dependency count // one int per dependency ID msgsize += 4 * m_dependencyCount; // Add the actual result lengths for (VoltTable dep : m_dependencies) { msgsize += dep.getSerializedSize(); } if (m_exception != null) { msgsize += m_exception.getSerializedSize(); } else { msgsize += 4; //Still serialize exception length 0 } return msgsize; } @Override public void flattenToBuffer(ByteBuffer buf) { assert(m_exception == null || m_status != SUCCESS); buf.put(VoltDbMessageFactory.FRAGMENT_RESPONSE_ID); buf.putLong(m_executorHSId); buf.putLong(m_destinationHSId); buf.putLong(m_txnId); buf.put(m_status); buf.put((byte) (m_dirty ? 1 : 0)); buf.put((byte) (m_recovering ? 1 : 0)); buf.putShort(m_dependencyCount); for (int i = 0; i < m_dependencyCount; i++) buf.putInt(m_dependencyIds.get(i)); for (int i = 0; i < m_dependencyCount; i++) { m_dependencies.get(i).flattenToBuffer(buf); } if (m_exception != null) { m_exception.serializeToBuffer(buf); } else { buf.putInt(0); } assert(buf.capacity() == buf.position()); buf.limit(buf.position()); } @Override public void initFromBuffer(ByteBuffer buf) { m_executorHSId = buf.getLong(); m_destinationHSId = buf.getLong(); m_txnId = buf.getLong(); m_status = buf.get(); m_dirty = buf.get() == 0 ? false : true; m_recovering = buf.get() == 0 ? false : true; m_dependencyCount = buf.getShort(); for (int i = 0; i < m_dependencyCount; i++) m_dependencyIds.add(buf.getInt()); for (int i = 0; i < m_dependencyCount; i++) { FastDeserializer fds = new FastDeserializer(buf); try { m_dependencies.add(fds.readObject(VoltTable.class)); } catch (IOException e) { e.printStackTrace(); assert(false); } } m_exception = SerializableException.deserializeFromBuffer(buf); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("FRAGMENT_RESPONSE (FROM "); sb.append(MiscUtils.hsIdToString(m_executorHSId)); sb.append(" TO "); sb.append(MiscUtils.hsIdToString(m_destinationHSId)); sb.append(") FOR TXN "); sb.append(m_txnId); if (m_status == SUCCESS) sb.append("\n SUCCESS"); else if (m_status == UNEXPECTED_ERROR) sb.append("\n UNEXPECTED_ERROR"); else sb.append("\n USER_ERROR"); if (m_dirty) sb.append("\n DIRTY"); else sb.append("\n PRISTINE"); for (int i = 0; i < m_dependencyCount; i++) { sb.append("\n DEP ").append(m_dependencyIds.get(i)); sb.append(" WITH ").append(m_dependencies.get(i).getRowCount()).append(" ROWS ("); for (int j = 0; j < m_dependencies.get(i).getColumnCount(); j++) { sb.append(m_dependencies.get(i).getColumnName(j)).append(", "); } sb.setLength(sb.lastIndexOf(", ")); sb.append(")"); } return sb.toString(); } }
package edu.harvard.iq.dataverse.api; import com.jayway.restassured.RestAssured; import com.jayway.restassured.path.json.JsonPath; import com.jayway.restassured.response.Response; import java.io.File; import java.util.Arrays; import java.util.logging.Logger; import static javax.ws.rs.core.Response.Status.CREATED; import static javax.ws.rs.core.Response.Status.OK; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; public class TabularIT { private static final Logger logger = Logger.getLogger(TabularIT.class.getCanonicalName()); @BeforeClass public static void setUpClass() { RestAssured.baseURI = UtilIT.getRestAssuredBaseUri(); } @Ignore @Test public void testTabularFile() throws InterruptedException { Response createUser = UtilIT.createRandomUser(); createUser.then().assertThat() .statusCode(OK.getStatusCode()); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); createDataverseResponse.then().assertThat() .statusCode(CREATED.getStatusCode()); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDatasetResponse = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDatasetResponse.prettyPrint(); createDatasetResponse.then().assertThat() .statusCode(CREATED.getStatusCode()); Integer datasetId = JsonPath.from(createDatasetResponse.body().asString()).getInt("data.id"); String persistentId = JsonPath.from(createDatasetResponse.body().asString()).getString("data.persistentId"); logger.info("Dataset created with id " + datasetId + " and persistent id " + persistentId); String pathToFileThatGoesThroughIngest = "scripts/search/data/tabular/50by1000.dta"; Response uploadIngestableFile = UtilIT.uploadFileViaNative(datasetId.toString(), pathToFileThatGoesThroughIngest, apiToken); uploadIngestableFile.prettyPrint(); uploadIngestableFile.then().assertThat() .statusCode(OK.getStatusCode()); long fileId = JsonPath.from(uploadIngestableFile.body().asString()).getLong("data.files[0].dataFile.id"); String fileIdAsString = Long.toString(fileId); // String filePersistentId = JsonPath.from(uploadIngestableFile.body().asString()).getString("data.files[0].dataFile.persistentId"); System.out.println("fileId: " + fileId); // System.out.println("filePersistentId: " + filePersistentId); // Give file time to ingest Thread.sleep(10000); Response fileMetadataNoFormat = UtilIT.getFileMetadata(fileIdAsString, null, apiToken); fileMetadataNoFormat.prettyPrint(); fileMetadataNoFormat.then().assertThat() .statusCode(OK.getStatusCode()) .body("codeBook.fileDscr.fileTxt.fileName", equalTo("50by1000.tab")); Response fileMetadataNoFormatFileId = UtilIT.getFileMetadata(fileIdAsString, null, apiToken); fileMetadataNoFormatFileId.prettyPrint(); fileMetadataNoFormatFileId.then().assertThat() .statusCode(OK.getStatusCode()) .body("codeBook.fileDscr.fileTxt.fileName", equalTo("50by1000.tab")); Response fileMetadataDdi = UtilIT.getFileMetadata(fileIdAsString, "ddi", apiToken); fileMetadataDdi.prettyPrint(); fileMetadataDdi.then().assertThat() .statusCode(OK.getStatusCode()) .body("codeBook.fileDscr.fileTxt.fileName", equalTo("50by1000.tab")) .body("codeBook.dataDscr.var[0].@name", equalTo("var1")) // Yes, it's odd that we go from "var1" to "var3" to "var2" to "var5" .body("codeBook.dataDscr.var[1].@name", equalTo("var3")) .body("codeBook.dataDscr.var[2].@name", equalTo("var2")) .body("codeBook.dataDscr.var[3].@name", equalTo("var5")); boolean testPreprocessedMetadataFormat = false; if (testPreprocessedMetadataFormat) { // If you don't have all the dependencies in place, such as Rserve, you might get a 503 and this error: // org.rosuda.REngine.Rserve.RserveException: Cannot connect: Connection refused Response fileMetadataPreProcessed = UtilIT.getFileMetadata(fileIdAsString, "preprocessed", apiToken); fileMetadataPreProcessed.prettyPrint(); fileMetadataPreProcessed.then().assertThat() .statusCode(OK.getStatusCode()) .body("codeBook.fileDscr.fileTxt.fileName", equalTo("50by1000.tab")); } } @Ignore @Test public void test50by1000() { // cp scripts/search/data/tabular/50by1000.dta /tmp String fileName = "/tmp/50by1000.dta"; String fileType = "application/x-stata"; Response response = UtilIT.testIngest(fileName, fileType); response.prettyPrint(); assertEquals("NVARS: 50", response.body().asString().split("\n")[0]); } @Ignore @Test public void testStata13TinyFile() { // cp scripts/search/data/tabular/120745.dta /tmp String fileName = "/tmp/120745.dta"; String fileType = "application/x-stata"; Response response = UtilIT.testIngest(fileName, fileType); response.prettyPrint(); assertEquals("NVARS: 1", response.body().asString().split("\n")[0]); } @Ignore @Test public void testStata13Auto() { String fileName = "/tmp/stata13-auto.dta"; String fileType = "application/x-stata-13"; Response response = UtilIT.testIngest(fileName, fileType); response.prettyPrint(); assertEquals("NVARS: 12", response.body().asString().split("\n")[0]); } @Ignore @Test public void testStata14OpenSourceAtHarvard() { // cp scripts/search/data/tabular/open-source-at-harvard118.dta /tmp String fileName = "/tmp/open-source-at-harvard118.dta"; String fileType = "application/x-stata-14"; Response response = UtilIT.testIngest(fileName, fileType); response.prettyPrint(); assertEquals("NVARS: 10", response.body().asString().split("\n")[0]); } @Ignore @Test public void testStata14Aggregated() { String fileName = "/tmp/2018_04_06_Aggregated_dataset_v2.dta"; String fileType = "application/x-stata-14"; Response response = UtilIT.testIngest(fileName, fileType); response.prettyPrint(); assertEquals("NVARS: 227", response.body().asString().split("\n")[0]); } @Ignore @Test public void testStata14MmPublic() { // TODO: This file was downloaded at random. We could keep trying to get it to ingest. // For this file "hasSTRLs" is true so it might be nice to get it working. String fileName = "/tmp/mm_public_120615_v14.dta"; String fileType = "application/x-stata-14"; Response response = UtilIT.testIngest(fileName, fileType); response.prettyPrint(); // We don't know how many variables it has. Probably not 12. assertEquals("NVARS: 12", response.body().asString().split("\n")[0]); } @Ignore @Test public void testStata15() { // for i in `echo {0..33000}`; do echo -n "var$i,"; done > 33k.csv // Then open Stata 15, run `set maxvar 40000` and import. String fileName = "/tmp/33k.dta"; String fileType = "application/x-stata-15"; Response response = UtilIT.testIngest(fileName, fileType); response.prettyPrint(); assertEquals("NVARS: 33001", response.body().asString().split("\n")[0]); } @Ignore @Test public void testStata13Multiple() { String fileType = "application/x-stata-13"; // From /usr/local/dvn-admin/stata on dvn-build String stata13directory = "/tmp/stata-13"; File folder = new File(stata13directory); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { File file = listOfFiles[i]; String filename = file.getName(); String filenameFullPath = file.getAbsolutePath(); Response response = UtilIT.testIngest(filenameFullPath, fileType); String firstLine = response.body().asString().split("\n")[0]; String[] parts = firstLine.split(":"); String[] justErrors = Arrays.copyOfRange(parts, 1, parts.length); System.out.println(i + "\t" + filename + "\t" + Arrays.toString(justErrors) + "\t" + firstLine); } } @Ignore @Test public void testStata14Multiple() { String fileType = "application/x-stata-14"; // From /usr/local/dvn-admin/stata on dvn-build String stata13directory = "/tmp/stata-14"; File folder = new File(stata13directory); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { File file = listOfFiles[i]; String filename = file.getName(); String filenameFullPath = file.getAbsolutePath(); Response response = UtilIT.testIngest(filenameFullPath, fileType); String firstLine = response.body().asString().split("\n")[0]; String[] parts = firstLine.split(":"); String[] justErrors = Arrays.copyOfRange(parts, 1, parts.length); System.out.println(i + "\t" + filename + "\t" + Arrays.toString(justErrors) + "\t" + firstLine); } } }
package com.x1unix.avi; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.webkit.WebResourceResponse; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import com.x1unix.avi.helpers.AdBlocker; import com.x1unix.avi.helpers.AviMoviePlayerWebViewClient; import java.util.HashMap; import java.util.Map; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. */ public class MoviePlayerActivity extends AppCompatActivity { private WebView webView; private String LSECTION = "MoviePlayer"; private String currentUrl = ""; private ProgressBar preloader; private boolean movieLoaded = false; private Intent receivedIntent; private AviMoviePlayerWebViewClient webClient; // Begin Android FullScreen Routine /** * Whether or not the system UI should be auto-hidden after * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. */ private static final boolean AUTO_HIDE = true; /** * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after * user interaction before hiding the system UI. */ private static final int AUTO_HIDE_DELAY_MILLIS = 3000; /** * Some older devices needs a small delay between UI widget updates * and a change of the status and navigation bar. */ private static final int UI_ANIMATION_DELAY = 300; private final Handler mHideHandler = new Handler(); private final Runnable mHidePart2Runnable = new Runnable() { @SuppressLint("InlinedApi") @Override public void run() { // Delayed removal of status and navigation bar // Note that some of these constants are new as of API 16 (Jelly Bean) // and API 19 (KitKat). It is safe to use them, as they are inlined // at compile-time and do nothing on earlier devices. webView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); // Load movie player in webview after fullscreen mode entered if (!movieLoaded) { // Load player with intent data if (receivedIntent != null) { loadPlayer(receivedIntent.getStringExtra("movieId")); } } } }; private final Runnable mShowPart2Runnable = new Runnable() { @Override public void run() { // Delayed display of UI elements ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.show(); } } }; private boolean mVisible; private final Runnable mHideRunnable = new Runnable() { @Override public void run() { hide(); } }; /** * Touch listener to use for in-layout UI controls to delay hiding the * system UI. This is to prevent the jarring behavior of controls going away * while interacting with activity UI. */ private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (AUTO_HIDE) { delayedHide(AUTO_HIDE_DELAY_MILLIS); } return false; } }; // End @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_player); // Set activity title receivedIntent = getIntent(); if (receivedIntent != null) { setTitle(receivedIntent.getStringExtra("movieTitle")); } webView = (WebView) findViewById(R.id.webplayer); mVisible = true; preloader = (ProgressBar) findViewById(R.id.movie_player_preloader); // Set up the user interaction to manually show or hide the system UI. webView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toggle(); } }); } @Override public void onPause() { super.onPause(); if (webView != null) webView.onPause(); } @Override public void onResume() { super.onResume(); delayedHide(100); if (webView != null) webView.onResume(); } private void loadPlayer(String kpId) { AdBlocker.init(this); String propAdDisabled = getResources().getString(R.string.avi_prop_no_ads); SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(getBaseContext()); boolean isAdBlockEnabled = preferences.getBoolean(propAdDisabled, true); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); webClient = new AviMoviePlayerWebViewClient(isAdBlockEnabled); // Clean memory propAdDisabled = null; preferences = null; webView.setWebViewClient(webClient); // Hide preloader and show webView webView.setVisibility(View.VISIBLE); preloader.setVisibility(View.GONE); setMovieId(kpId); movieLoaded = true; } public void setMovieId(String kpId) { currentUrl = "http://avi.x1unix.com/?kpid=" + kpId; webClient.updateCurrentUrl(currentUrl); Log.i(LSECTION, "Loading url: " + currentUrl); webView.loadUrl(currentUrl); } @Override public void onDestroy() { super.onDestroy(); finishJob(); } private void finishJob() { // Close player page webView.loadUrl("about:blank"); webView.clearCache(true); webView = null; movieLoaded = false; } // Begin Android FullScreen helpers @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. delayedHide(100); } private void toggle() { if (mVisible) { hide(); } else { show(); } } private void hide() { // Hide UI first ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.hide(); } mVisible = false; // Schedule a runnable to remove the status and navigation bar after a delay mHideHandler.removeCallbacks(mShowPart2Runnable); mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY); } @SuppressLint("InlinedApi") private void show() { // Show the system bar webView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); mVisible = true; // Schedule a runnable to display UI elements after a delay mHideHandler.removeCallbacks(mHidePart2Runnable); mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY); } /** * Schedules a call to hide() in [delay] milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); } // End }
package com.dtcc.csc.jrparks.final_project; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.Scanner; /** * @author jrparks * */ public class Game { private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final Random rand = new Random(); private Scanner inputScanner; private List<Puzzle> puzzles; private String revealedPuzzle; private Boolean solved, quit, incorrectGuess; private char[] guessableLetters, guessedLetters; private List<Player> players; private int currentPlayerIndex, currentPuzzleIndex; private GameWheel wheel; /** * Game constructor */ public Game() { this.guessableLetters = ALPHABET.toCharArray(); this.guessedLetters = new char[guessableLetters.length]; this.puzzles = new LinkedList<Puzzle>(); this.revealedPuzzle = ""; this.solved = this.quit = this.incorrectGuess = false; this.players = new LinkedList<Player>(); this.currentPlayerIndex = this.currentPuzzleIndex = 0; this.wheel = new GameWheel(); this.inputScanner = new Scanner(System.in); generateNewPuzzle(); } /** * @return the revealedPuzzle */ public String getRevealedPuzzle() { return generateRevealedPuzzle(); } /** * @return whether the puzzle is solved */ public Boolean getSolved() { return this.solved; } /** * @return whether to quit the game */ public Boolean getQuit() { return this.quit; } /** * Add a new puzzle(s) to the game. * * @param puzzles */ public void addPuzzles(Puzzle... puzzles) { for (Puzzle puzzle : puzzles) this.puzzles.add(puzzle); generateNewPuzzle(); } /** * Retrieve the current puzzle. * * @return Current Puzzle */ public Puzzle currentPuzzle() { return this.puzzles.get(this.currentPuzzleIndex); } /** * Reset game and generate new puzzle. */ public void generateNewPuzzle() { int prevPuzzle = this.currentPuzzleIndex; if (this.puzzles.isEmpty()) this.currentPuzzleIndex = 0; else do { // Prevent repeat puzzles this.currentPuzzleIndex = rand.nextInt(this.puzzles.size()); } while (prevPuzzle == this.currentPuzzleIndex && solved); // Reset game this.solved = false; // Empty guessed letters this.guessedLetters = new char[guessableLetters.length]; } /** * Add a new player(s) to the game. * * @param players */ public void addPlayers(Player... players) { for (Player player : players) this.players.add(player); } /** * Retrieve the current player. * * @return Current player. */ public Player currentPlayer() { return this.players.get(this.currentPlayerIndex); } /** * Draw the game screen */ public void drawGame() { for (int i = 0; i < 8; ++i) System.out.println(); System.out.println("Welcome to the Wheel of Fortune"); System.out.println(); for (Player player : this.players) { System.out.printf("%s\t", player.getName()); } System.out.println(); for (Player player : this.players) { System.out.printf("$%10d\t", player.getWinnings()); } System.out.println(); System.out.printf("Available Letters: %s\n", getAvailableLetters()); System.out.println(); System.out.printf("Puzzle: (%s)\n", this.currentPuzzle().getHint()); System.out.printf("\t%s\n", getRevealedPuzzle()); System.out.println(); if (this.incorrectGuess) { this.incorrectGuess = false; System.out.println("The puzzel guess was incorrect."); System.out.println(); } System.out.printf("Player %s - would you like to Spin (1) or Guess (2) the puzzle?\n", currentPlayer().getName()); System.out.print("Action (q to quit): "); } /** * Ask the current player for action */ public void queryPlayer() { String action = this.inputScanner.next(); this.inputScanner.nextLine(); switch (action) { default: break; case "1": case "s": case "spin": int spinPrize = this.spinWheel(); System.out.printf("You landed on $%d.\n", spinPrize); if (spinPrize <= 0) { this.currentPlayer().setWinnings(this.currentPlayer().getWinnings() + spinPrize); System.out.println("You have lost your turn."); ++this.currentPlayerIndex; } else { Object[] letterData = this.guessLetter(); if ((int) letterData[1] > 0) { if ((int) letterData[1] > 1) System.out.printf("There are %d %s's in the puzzle.\n", (int) letterData[1], letterData[0]); else System.out.printf("There is %d %s in the puzzle.\n", (int) letterData[1], letterData[0]); this.currentPlayer().setWinnings(this.currentPlayer().getWinnings() + (spinPrize * (int) letterData[1])); } else { System.out.printf("I'm sorry but the letter '%s' is not a valid choice.\n", letterData[0]); ++this.currentPlayerIndex; } } sleep(5 * 1000); break; case "2": case "g": case "guess": if (this.querySolve()) { System.out.println("The puzzel guess was correct."); System.out.printf("Player %s has won the current round.\n", currentPlayer().getName()); } else { System.out.println("The puzzel guess was incorrect."); } ++this.currentPlayerIndex; sleep(5 * 1000); break; case "q": case "quit": case "exit": case "stop": this.quit = true; break; } if (this.currentPlayerIndex >= this.players.size()) this.currentPlayerIndex = 0; } /** * Ask the current player for a letter * * @return [letter, count] */ public Object[] guessLetter() { char letter; do { System.out.print("Please guess a letter: "); letter = this.inputScanner.next().toUpperCase().charAt(0); } while (Arrays.asList(this.guessedLetters).contains(letter)); this.inputScanner.nextLine(); return new Object[] { letter, this.guessLetter(letter) }; } /** * Try for game solve * * @return whether puzzle was solved */ public Boolean querySolve() { System.out.print("Please guess the puzzle: "); String guess = ""; guess = this.inputScanner.nextLine(); return this.solvePuzzle(guess); } /** * Return available letter choices * * @return String of letters */ public String getAvailableLetters() { String availableLetters = new String(guessableLetters); for (char c : guessedLetters) { availableLetters = availableLetters.replace(c, '_'); } return availableLetters; } /** * Get revealed puzzle * * @return revealed puzzle */ private String generateRevealedPuzzle() { this.revealedPuzzle = ""; if (!this.solved) { String[] puzzleWords = this.currentPuzzle().getPuzzle().split(" "); for (String puzzleWord : puzzleWords) { for (char c : puzzleWord.toCharArray()) { if (new String(guessedLetters).indexOf(c) >= 0) this.revealedPuzzle += c; else this.revealedPuzzle += "_"; } this.revealedPuzzle += " "; } this.revealedPuzzle.trim(); } else { this.revealedPuzzle = this.currentPuzzle().getPuzzle(); } return this.revealedPuzzle; } /** * Guess letter * * @param c * - Letter to guess * @return letter count */ public int guessLetter(char c) { c = Character.toUpperCase(c); int count = 0, index = this.getAvailableLetters().indexOf(c); if (index >= 0) { guessedLetters[index] = guessableLetters[index]; for (char _c : this.currentPuzzle().getPuzzle().toCharArray()) { if (_c == c) { ++count; } } } return count; } /** * Solve puzzle * * @param guess * - Puzzle guess * @return whether guess was correct */ public Boolean solvePuzzle(String guess) { Boolean solve = guess.equalsIgnoreCase(this.currentPuzzle().getPuzzle()); this.solved = solve; return solve; } /** * Spin the wheel * * @return wheel value */ public int spinWheel() { return this.wheel.spin(); } /** * Sleep * * @param millis */ protected void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } }
package net.java.sip.communicator.service.gui; import java.awt.event.*; import java.util.*; import javax.swing.event.*; import javax.swing.text.*; import net.java.sip.communicator.service.gui.event.*; /** * The <tt>Chat</tt> interface is meant to be implemented by the GUI component * class representing a chat. Through the <i>isChatFocused</i> method the other * bundles could check the visibility of the chat component. The * <tt>ChatFocusListener</tt> is used to inform other bundles when a chat has * changed its focus state. * * @author Yana Stamcheva */ public interface Chat { /** * The message type representing outgoing messages. */ public static final String OUTGOING_MESSAGE = "OutgoingMessage"; /** * The message type representing incoming messages. */ public static final String INCOMING_MESSAGE = "IncomingMessage"; /** * The message type representing status messages. */ public static final String STATUS_MESSAGE = "StatusMessage"; /** * The message type representing action messages. These are message specific * for IRC, but could be used in other protocols also. */ public static final String ACTION_MESSAGE = "ActionMessage"; /** * The message type representing system messages. */ public static final String SYSTEM_MESSAGE = "SystemMessage"; /** * The message type representing sms messages. */ public static final String SMS_MESSAGE = "SmsMessage"; /** * The message type representing error messages. */ public static final String ERROR_MESSAGE = "ErrorMessage"; /** * The history incoming message type. */ public static final String HISTORY_INCOMING_MESSAGE = "HistoryIncomingMessage"; /** * The history outgoing message type. */ public static final String HISTORY_OUTGOING_MESSAGE = "HistoryOutgoingMessage"; /** * The size of the buffer that indicates how many messages will be stored * in the conversation area in the chat window. */ public static final int CHAT_BUFFER_SIZE = 50000; /** * Checks if this <tt>Chat</tt> is currently focused. * * @return TRUE if the chat is focused, FALSE - otherwise */ public boolean isChatFocused(); /** * Returns the message written by user in the chat write area. * * @return the message written by user in the chat write area */ public String getMessage(); /** * Bring this chat to front if <tt>b</tt> is true, hide it otherwise. * * @param isVisible tells if the chat will be made visible or not. */ public void setChatVisible(boolean isVisible); /** * Sets the given message as a message in the chat write area. * * @param message the text that would be set to the chat write area */ public void setMessage(String message); /** * Adds the given <tt>ChatFocusListener</tt> to this <tt>Chat</tt>. * The <tt>ChatFocusListener</tt> is used to inform other bundles when a * chat has changed its focus state. * * @param l the <tt>ChatFocusListener</tt> to add */ public void addChatFocusListener(ChatFocusListener l); /** * Removes the given <tt>ChatFocusListener</tt> from this <tt>Chat</tt>. * The <tt>ChatFocusListener</tt> is used to inform other bundles when a * chat has changed its focus state. * * @param l the <tt>ChatFocusListener</tt> to remove */ public void removeChatFocusListener(ChatFocusListener l); /** * Adds the given {@link KeyListener} to this <tt>Chat</tt>. * The <tt>KeyListener</tt> is used to inform other bundles when a user has * typed in the chat editor area. * * @param l the <tt>KeyListener</tt> to add */ public void addChatEditorKeyListener(KeyListener l); /** * Removes the given {@link KeyListener} from this <tt>Chat</tt>. * The <tt>KeyListener</tt> is used to inform other bundles when a user has * typed in the chat editor area. * * @param l the <tt>ChatFocusListener</tt> to remove */ public void removeChatEditorKeyListener(KeyListener l); /** * Adds the given {@link ChatMenuListener} to this <tt>Chat</tt>. * The <tt>ChatMenuListener</tt> is used to determine menu elements * that should be added on right clicks. * * @param l the <tt>ChatMenuListener</tt> to add */ public void addChatEditorMenuListener(ChatMenuListener l); /** * Adds the given {@link CaretListener} to this <tt>Chat</tt>. * The <tt>CaretListener</tt> is used to inform other bundles when a user has * moved the caret in the chat editor area. * * @param l the <tt>CaretListener</tt> to add */ public void addChatEditorCaretListener(CaretListener l); /** * Adds the given {@link DocumentListener} to this <tt>Chat</tt>. * The <tt>DocumentListener</tt> is used to inform other bundles when a user has * modified the document in the chat editor area. * * @param l the <tt>DocumentListener</tt> to add */ public void addChatEditorDocumentListener(DocumentListener l); /** * Removes the given {@link ChatMenuListener} to this <tt>Chat</tt>. * The <tt>ChatMenuListener</tt> is used to determine menu elements * that should be added on right clicks. * * @param l the <tt>ChatMenuListener</tt> to add */ public void removeChatEditorMenuListener(ChatMenuListener l); /** * Removes the given {@link CaretListener} from this <tt>Chat</tt>. * The <tt>CaretListener</tt> is used to inform other bundles when a user has * moved the caret in the chat editor area. * * @param l the <tt>CaretListener</tt> to remove */ public void removeChatEditorCaretListener(CaretListener l); /** * Removes the given {@link DocumentListener} from this <tt>Chat</tt>. * The <tt>DocumentListener</tt> is used to inform other bundles when a user has * modified the document in the chat editor area. * * @param l the <tt>DocumentListener</tt> to remove */ public void removeChatEditorDocumentListener(DocumentListener l); /** * Adds a message to this <tt>Chat</tt>. * * @param contactName the name of the contact sending the message * @param date the time at which the message is sent or received * @param messageType the type of the message * @param message the message text * @param contentType the content type */ public void addMessage(String contactName, Date date, String messageType, String message, String contentType); /** * Adds a new ChatLinkClickedListener. The callback is called for every * link whose scheme is <tt>jitsi</tt>. It is the callback's responsibility * to filter the action based on the URI. * * Example:<br> * <tt>jitsi://classname/action?query</tt><br> * Use the name of the registering class as the host, the action to execute * as the path and any parameters as the query. * * @param listener callback that is notified when a link was clicked. */ public void addChatLinkClickedListener(ChatLinkClickedListener listener); /** * Removes an existing ChatLinkClickedListener * * @param listener the already registered listener to remove. */ public void removeChatLinkClickedListener(ChatLinkClickedListener listener); /** * Provides the {@link Highlighter} used in rendering the chat editor. * * @return highlighter used to render message being composed */ public Highlighter getHighlighter(); /** * Gets the caret position in the chat editor. * @return index of caret in message being composed */ public int getCaretPosition(); /** * Causes the chat to validate its appearance (suggests a repaint operation * may be necessary). */ public void promptRepaint(); }
package au.com.sealink.printing.utils; import au.com.sealink.printing.ticket_printer.TicketElement; import au.com.sealink.printing.ticket_printer.printables.PrintableElement; import org.apache.commons.codec.binary.Base64; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; public class ImageLoader { public static BufferedImage loadImage(TicketElement element) { BufferedImage img = null; try { if (element.isImageBase64()) { String imgEncodedInBase64 = element.getImageValue(); img = loadImgFromBase64(imgEncodedInBase64); } else { img = loadImageFromUrl(element.getImageValue()); } } catch (IOException ex) { Logger logger = Logger.getLogger(PrintableElement.class.getName()); logger.log(Level.SEVERE, "Could not load image:\n" + element.getImageValue(), ex); } return img; } private static BufferedImage loadImageFromUrl(String imageUrlString) throws IOException { URL url = new URL(imageUrlString); return ImageIO.read(url); } private static BufferedImage loadImgFromBase64(String imgEncodedInBase64) throws IOException { byte[] imgData = Base64.decodeBase64(imgEncodedInBase64); InputStream in = new ByteArrayInputStream(imgData); return ImageIO.read(in); } }
package housing; import agent.Agent; import housing.gui.ResidentGui; import housing.interfaces.Resident; import housing.test.mock.EventLog; import housing.test.mock.LoggedEvent; import java.util.*; import java.util.concurrent.Semaphore; /** * Housing renter agent. */ public class ResidentAgent extends Agent implements Resident { private String name; // agent correspondents private Housing housing; private double amt; private String type, foodPreference; private ResidentGui renterGui; private Semaphore moving = new Semaphore(1, true); private Building building; public EventLog log = new EventLog(); public enum State {idle, enteringHouse, readyToCook, noFood, foodDone, wantsMaintenance, maintenanceDone, goingToBed, leavingHouse}; State state = State.idle; /** * Constructor for RenterAgent class * * @param name name of the customer */ public ResidentAgent(String name, String type){ super(); this.name = name; this.type = type; building = new Building(type); state = State.idle; } public String getCustomerName() { return name; } class Building { String type; Timer timer = new Timer(); private HashMap<String, Integer> inventory = new HashMap<String, Integer>(); Building(String t) { type = t; inventory.put("Mexican", 1); inventory.put("Southern", 1); inventory.put("Italian", 1); inventory.put("German", 1); inventory.put("American", 1); } private boolean getFood(String f) { if (inventory.get(f) != 0) { inventory.put(f, inventory.get(f)-1); return true; } else { return false; } } public void cookFood() { timer.schedule(new TimerTask() { public void run() { if (getFood(foodPreference)) { print("food done"); log.add(new LoggedEvent("Food is done")); state = State.foodDone; stateChanged(); } else { print("no food"); log.add(new LoggedEvent("Food is done")); state = State.noFood; stateChanged(); } } }, 5000); } } // Messages public void msgAnimationFinished(){ moving.release(); stateChanged(); } public void msgDoMaintenance(){ state = State.wantsMaintenance; stateChanged(); } public void msgMaintenanceAnimationFinished(){ moving.release(); print("finished maintenance"); log.add(new LoggedEvent("Finished maintenance")); state = State.maintenanceDone; stateChanged(); } public void msgLeave() { //from Housing class log.add(new LoggedEvent("Leaving")); state = State.leavingHouse; stateChanged(); } public void msgCookFood(String choice) { //from Housing class foodPreference = choice; state = State.readyToCook; stateChanged(); } public void msgHome() { //from Housing class state = State.enteringHouse; stateChanged(); } public void msgToBed() { //from Housing class state = State.goingToBed; stateChanged(); } /** * Scheduler. Determine what action is called for, and do it. */ public boolean pickAndExecuteAnAction() { if(state == State.enteringHouse){ Do("Entering house"); EnterHouse(); state = State.idle; // state = State.readyToCook; //hack return true; } else if(state == State.readyToCook){ CookFood(); state = State.idle; return true; } else if(state == State.noFood){ housing.msgFoodDone(this, false); state = State.idle; // state = State.wantsMaintenance; //hack return true; } else if(state == State.foodDone){ housing.msgFoodDone(this, true); EatFood(); state = State.idle; // state = State.wantsMaintenance; //hack return true; } else if(state == State.wantsMaintenance){ DoMaintenance(); state = State.idle; return true; } else if(state == State.maintenanceDone){ housing.msgFinishedMaintenance(this); state = State.idle; // state = State.leavingHouse; //hack return true; } else if(state == State.goingToBed){ GoToBed(); state = State.idle; return true; } else if(state == State.leavingHouse){ Do("Leaving house"); LeaveHouse(); state = State.idle; return true; } return false; } // Actions private void EnterHouse(){ try { moving.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } renterGui.DoEnterHouse(); housing.msgEntered(this); } private void CookFood(){ try { moving.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } renterGui.DoGoToKitchen(); building.cookFood(); } private void EatFood(){ try { moving.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } renterGui.DoGoToTable(); } private void DoMaintenance(){ try { moving.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } renterGui.DoMaintenance(); } private void GoToBed(){ try { moving.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } renterGui.DoGoToBed(); } private void LeaveHouse(){ try { moving.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } renterGui.DoLeaveHouse(); housing.msgLeft(this); } // Accessors, etc. public String getName() { return name; } public void setHousing(Housing h) { housing = h; } public String toString() { return "renter " + getName(); } public void setGui(ResidentGui r) { renterGui = r; } public ResidentGui getGui() { return renterGui; } }
package router.client; import com.google.gwt.core.client.EntryPoint; import elemental2.Element; import elemental2.Global; import java.util.Objects; public final class Router implements EntryPoint { private RouteManager _routeManager; private void route2( final Object element, final String string ) { ( (Element) element ).innerHTML = "<h1>" + string + "</h1>"; } public void onModuleLoad() { final Element rootElement = Global.document.getElementById( "hook" ); final RouteDefinition[] routes = new RouteDefinition[] { new RouteDefinition( 1, "/", null, null, ( route, element ) -> route2( element, "/" ), null, null ), new RouteDefinition( 1, "/foo", null, null, ( route, element ) -> route2( element, "/foo" ), null, null ), new RouteDefinition( 1, new RegExp( "^/baz/(\\d+)/(\\d+)$" ), new String[]{ "bazID", "buzID" }, null, null, ( route, element ) -> route2( element, "/baz/" + route.getData( "bazID" ) + "/" + route.getData( "buzID" ) ), null, null ), new RouteDefinition( 1, new RegExp( "^/baz/(\\d+)$" ), new String[]{ "bazID" }, ( route -> Objects.equals( route.getData( "bazID" ), "42" ) ), null, ( route, element ) -> route2( element, "/baz/" + route.getData( "bazID" ) ), null, null ), new RouteDefinition( 1, new RegExp( "^/biz/(\\d+)$" ), new String[]{ "bazID" }, ( route -> Objects.equals( route.getData( "bazID" ), "42" ) ), null, ( route, element ) -> route2( element, "/biz/" + route.getData( "bazID" ) ), null, ( route -> info( "PostRoute " + route ) ) ), new RouteDefinition( 1, new RegExp( "^/ding/(\\d+)$" ), new String[]{ "bazID" }, null, null, ( route, element ) -> route2( element, "/ding/" + route.getData( "bazID" ) ), route -> route2( Global.document.getElementById( "hook" ), "/ding/" + route.getData( "bazID" ) + " (NoRoute)" ), null ), new RouteDefinition( 1, new RegExp( "^/end$" ), new String[ 0 ], null, null, ( route, element ) -> { route2( element, "/end" ); _routeManager.uninstall(); }, null, null ), }; final boolean useElemental = true; @SuppressWarnings( "ConstantConditions" ) final RoutingBackend backend = useElemental ? new Elemental2RoutingBackend() : new GwtFrameworkRoutingBackend(); _routeManager = new RouteManager( backend, rootElement ); _routeManager.setDefaultLocation( "/" ); for ( final RouteDefinition route : routes ) { _routeManager.addRoute( route ); } _routeManager.install(); try { info( "Router started" ); _routeManager.route(); } catch ( final Exception e ) { warn( "Unexpected problem initializing the Router application: " + e ); Global.window.alert( "Error: " + e.getMessage() ); } } public static native void error( String message ) /*-{ window.console.error( message ); }-*/; public static native void warn( String message ) /*-{ window.console.warn( message ); }-*/; public static native void info( String message ) /*-{ window.console.info( message ); }-*/; public static native void log( String message ) /*-{ window.console.log( message ); }-*/; }
package com.gistlabs.mechanize; import static com.gistlabs.mechanize.query.QueryBuilder.byIdOrClass; import static com.gistlabs.mechanize.query.QueryBuilder.byIdOrClassOrName; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpRequestBase; import com.gistlabs.mechanize.exceptions.MechanizeException; import com.gistlabs.mechanize.form.Form; import com.gistlabs.mechanize.form.Forms; import com.gistlabs.mechanize.image.Images; import com.gistlabs.mechanize.link.Link; import com.gistlabs.mechanize.link.Links; import com.gistlabs.mechanize.util.CopyInputStream; import com.gistlabs.mechanize.util.JsoupDataUtil; import com.gistlabs.mechanize.util.NullOutputStream; import com.gistlabs.mechanize.util.Util; /** Represents an HTML page. * * @author Martin Kersten<Martin.Kersten.mk@gmail.com> * @version 1.0 * @since 2012-09-12 */ public class Page implements RequestBuilderFactory { private final MechanizeAgent agent; protected final String uri; private final HttpRequestBase request; protected final HttpResponse response; private ByteArrayOutputStream originalContent; private Links links; private Forms forms; private Images images; public Page(MechanizeAgent agent, HttpRequestBase request, HttpResponse response) { this.agent = agent; this.request = request; this.response = response; this.uri = inspectUri(request, response); try { loadPage(); } catch(RuntimeException rex) { throw rex; } catch(Throwable th) { throw new MechanizeException(th); } } protected void loadPage() throws Exception { preLoadContent(); } protected void preLoadContent() throws IOException { Util.copy(getInputStream(), new NullOutputStream()); } protected String getContentEncoding(HttpResponse response) { return JsoupDataUtil.getCharsetFromContentType(response.getEntity().getContentType()); } /** * This will return (and cache) the response entity content input stream, or return a stream from the previously cached value. * * @return * @throws IOException */ public InputStream getInputStream() throws IOException { if (this.originalContent==null) { this.originalContent = new ByteArrayOutputStream(getIntContentLength(this.response)); return new CopyInputStream(response.getEntity().getContent(), this.originalContent); } else { // use cached data return new ByteArrayInputStream(this.originalContent.toByteArray()); } } /** * (From HttpEntity) Tells the length of the content, if known. * * @return the number of bytes of the content, or * a negative number if unknown. If the content length is known * but exceeds {@link java.lang.Long#MAX_VALUE Long.MAX_VALUE}, * a negative number is returned. */ public long getLength() { return this.response.getEntity().getContentLength(); } protected int getIntContentLength(HttpResponse response) { long longLength = response.getEntity().getContentLength(); if (longLength<0) return 0; else if (longLength>Integer.MAX_VALUE) return Integer.MAX_VALUE; else return (int)longLength; } protected String inspectUri(HttpRequestBase request, HttpResponse response) { Header contentLocation = Util.findHeader(response, "content-location"); if(contentLocation != null && contentLocation.getValue() != null) return contentLocation.getValue(); else return request.getURI().toString(); } public String getContentType() { return response.getEntity().getContentType().getValue(); } @Override public RequestBuilder doRequest(String uri) { return getAgent().doRequest(uri); } /** * * @return */ public String getTitle() { return ""; } /** * Query for a matching link, find first match by either id or by class attributes. * * @param query wrapped with byIdOrClass() * @return first Link found */ public Link link(String query) { return links().get(byIdOrClass(query)); } public Links links() { if(this.links == null) { this.links = loadLinks(); } return this.links; } protected Links loadLinks() { return new Links(this, null); } /** * Query for a matching form, find first match by either id or by class attributes. * * @param query wrapped with byIdOrClass() * @return first Form found */ public Form form(String query) { return forms().get(byIdOrClassOrName(query)); } public Forms forms() { if(this.forms == null) { this.forms = loadForms(); } return this.forms; } protected Forms loadForms() { return new Forms(this, null); } public Images images() { if(this.images == null) { this.images = loadImages(); } return this.images; } protected Images loadImages() { return new Images(this, null); } public String getUri() { return uri; } public int size() { return originalContent.size(); } public HttpRequestBase getRequest() { return request; } public HttpResponse getResponse() { return response; } public MechanizeAgent getAgent() { return agent; } /** * Serialize the contents of this page into a string * * @return */ public String asString() { ByteArrayOutputStream result = new ByteArrayOutputStream(getIntContentLength(this.response)); saveTo(result); return result.toString(); } public void saveTo(File file) { if(file.exists()) throw new IllegalArgumentException("File '" + file.toString() + "' already exists."); try { saveTo(new FileOutputStream(file)); } catch (FileNotFoundException e) { throw new MechanizeException(e); } } public void saveTo(OutputStream out) { try { Util.copy(getInputStream(), out); } catch (IOException e) { throw new MechanizeException(e); } } }
package me.itszooti.geojson; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class GeoJSONEncoderTest { private GeoJSONEncoder encoder; private JsonParser jsonParser; @Before public void before() { encoder = GeoJSONEncoder.create(); jsonParser = new JsonParser(); } @Test public void encodePoint() { GeoPoint point = new GeoPoint(new GeoPosition(100.0, 0.0)); String json = encoder.encode(point); JsonElement element = jsonParser.parse(json); assertThat(element, instanceOf(JsonObject.class)); JsonObject object = element.getAsJsonObject(); assertThat(object.has("type"), equalTo(true)); assertThat(object.getAsJsonPrimitive("type").getAsString(), equalTo("Point")); assertThat(object.has("coordinates"), equalTo(true)); JsonArray coords = object.getAsJsonArray("coordinates"); assertThat(coords.size(), equalTo(2)); assertThat(coords.get(0).getAsDouble(), equalTo(100.0)); assertThat(coords.get(1).getAsDouble(), equalTo(0.0)); } @Test public void encodeMultiPoint() { GeoMultiPoint multiPoint = new GeoMultiPoint(Arrays.asList(new GeoPosition[] { new GeoPosition(1.0, 2.0), new GeoPosition(3.0, 4.0) })); String json = encoder.encode(multiPoint); JsonElement element = jsonParser.parse(json); assertThat(element, instanceOf(JsonObject.class)); JsonObject object = element.getAsJsonObject(); assertThat(object.has("type"), equalTo(true)); assertThat(object.getAsJsonPrimitive("type").getAsString(), equalTo("MultiPoint")); assertThat(object.has("coordinates"), equalTo(true)); JsonArray coords = object.getAsJsonArray("coordinates"); testPositions(coords, new double[][] { new double[] { 1.0, 2.0 }, new double[] { 3.0, 4.0 } }); } private void testPositions(JsonArray positions, double[][] expected) { assertThat(positions.size(), equalTo(expected.length)); for (int i = 0; i < positions.size(); i++) { JsonArray position = positions.get(i).getAsJsonArray(); assertThat(position.get(0).getAsDouble(), equalTo(expected[i][0])); assertThat(position.get(1).getAsDouble(), equalTo(expected[i][1])); } } @Test public void encodeLineString() { GeoLineString lineString = new GeoLineString(Arrays.asList(new GeoPosition[] { new GeoPosition(1.0, 1.0), new GeoPosition(3.0, 3.0) })); String json = encoder.encode(lineString); JsonElement element = jsonParser.parse(json); assertThat(element, instanceOf(JsonObject.class)); JsonObject object = element.getAsJsonObject(); assertThat(object.has("type"), equalTo(true)); assertThat(object.getAsJsonPrimitive("type").getAsString(), equalTo("LineString")); assertThat(object.has("coordinates"), equalTo(true)); JsonArray coords = object.getAsJsonArray("coordinates"); testPositions(coords, new double[][] { new double[] { 1.0, 1.0 }, new double[] { 3.0, 3.0 } }); } @Test public void encodeMultiLineString() { GeoMultiLineString multiLineString = new GeoMultiLineString(new GeoPosition[][] { new GeoPosition[] { new GeoPosition(100.0, 0.0), new GeoPosition(101.0, 1.0) }, new GeoPosition[] { new GeoPosition(102.0, 2.0), new GeoPosition(103.0, 3.0) } }); String json = encoder.encode(multiLineString); JsonElement element = jsonParser.parse(json); assertThat(element, instanceOf(JsonObject.class)); JsonObject object = element.getAsJsonObject(); assertThat(object.has("type"), equalTo(true)); assertThat(object.getAsJsonPrimitive("type").getAsString(), equalTo("MultiLineString")); assertThat(object.has("coordinates"), equalTo(true)); JsonArray coords = object.getAsJsonArray("coordinates"); assertThat(coords.size(), equalTo(2)); testPositions(coords.get(0).getAsJsonArray(), new double[][] { new double[] { 100.0, 0.0 }, new double[] { 101.0, 1.0 } }); testPositions(coords.get(1).getAsJsonArray(), new double[][] { new double[] { 102.0, 2.0 }, new double[] { 103.0, 3.0 } }); } @Test public void encodePolygonNoHoles() { List<GeoPosition> exterior = Arrays.asList(new GeoPosition[] { new GeoPosition(100.0, 0.0), new GeoPosition(101.0, 0.0), new GeoPosition(101.0, 1.0), new GeoPosition(100.0, 1.0), new GeoPosition(100.0, 0.0) }); GeoPolygon polygonNoHoles = new GeoPolygon(exterior); String json = encoder.encode(polygonNoHoles); JsonElement element = jsonParser.parse(json); assertThat(element, instanceOf(JsonObject.class)); JsonObject object = element.getAsJsonObject(); assertThat(object.has("type"), equalTo(true)); assertThat(object.getAsJsonPrimitive("type").getAsString(), equalTo("Polygon")); assertThat(object.has("coordinates"), equalTo(true)); JsonArray coords = object.getAsJsonArray("coordinates"); assertThat(coords.size(), equalTo(1)); JsonArray exteriorCoords = coords.get(0).getAsJsonArray(); testPositions(exteriorCoords, new double[][] { new double[] { 100.0, 0.0 }, new double[] { 101.0, 0.0 }, new double[] { 101.0, 1.0 }, new double[] { 100.0, 1.0 }, new double[] { 100.0, 0.0 } }); } @Test public void encodePolygonWithHoles() { List<GeoPosition> exterior = Arrays.asList(new GeoPosition[] { new GeoPosition(100.0, 0.0), new GeoPosition(101.0, 0.0), new GeoPosition(101.0, 1.0), new GeoPosition(100.0, 1.0), new GeoPosition(100.0, 0.0) }); List<List<GeoPosition>> interiors = new ArrayList<List<GeoPosition>>(); interiors.add(Arrays.asList(new GeoPosition[] { new GeoPosition(100.2, 0.2), new GeoPosition(100.8, 0.2), new GeoPosition(100.8, 0.8), new GeoPosition(100.2, 0.8), new GeoPosition(100.2, 0.2) })); GeoPolygon polygonWithHoles = new GeoPolygon(exterior, interiors); String json = encoder.encode(polygonWithHoles); JsonElement element = jsonParser.parse(json); assertThat(element, instanceOf(JsonObject.class)); JsonObject object = element.getAsJsonObject(); assertThat(object.has("type"), equalTo(true)); assertThat(object.getAsJsonPrimitive("type").getAsString(), equalTo("Polygon")); assertThat(object.has("coordinates"), equalTo(true)); JsonArray coords = object.getAsJsonArray("coordinates"); assertThat(coords.size(), equalTo(2)); JsonArray exteriorCoords = coords.get(0).getAsJsonArray(); testPositions(exteriorCoords, new double[][] { new double[] { 100.0, 0.0 }, new double[] { 101.0, 0.0 }, new double[] { 101.0, 1.0 }, new double[] { 100.0, 1.0 }, new double[] { 100.0, 0.0 } }); JsonArray interiorCoords = coords.get(1).getAsJsonArray(); testPositions(interiorCoords, new double[][] { new double[] { 100.2, 0.2 }, new double[] { 100.8, 0.2 }, new double[] { 100.8, 0.8 }, new double[] { 100.2, 0.8 }, new double[] { 100.2, 0.2 } }); } @Test public void encodeMultiPolygon() { List<List<GeoPosition>> exteriors = new ArrayList<List<GeoPosition>>(); exteriors.add(Arrays.asList(new GeoPosition[] { new GeoPosition(100.0, 0.0), new GeoPosition(101.0, 0.0), new GeoPosition(101.0, 1.0), new GeoPosition(100.0, 1.0), new GeoPosition(100.0, 0.0) })); exteriors.add(Arrays.asList(new GeoPosition[] { new GeoPosition(100.0, 0.0), new GeoPosition(101.0, 0.0), new GeoPosition(101.0, 1.0), new GeoPosition(100.0, 1.0), new GeoPosition(100.0, 0.0) })); List<List<List<GeoPosition>>> interiors = new ArrayList<List<List<GeoPosition>>>(); interiors.add(new ArrayList<List<GeoPosition>>()); List<List<GeoPosition>> interior = new ArrayList<List<GeoPosition>>(); interior.add(Arrays.asList(new GeoPosition[] { new GeoPosition(100.2, 0.2), new GeoPosition(100.8, 0.2), new GeoPosition(100.8, 0.8), new GeoPosition(100.2, 0.8), new GeoPosition(100.2, 0.2) })); interiors.add(interior); GeoMultiPolygon multiPolygon = new GeoMultiPolygon(exteriors, interiors); String json = encoder.encode(multiPolygon); JsonElement element = jsonParser.parse(json); assertThat(element, instanceOf(JsonObject.class)); JsonObject object = element.getAsJsonObject(); assertThat(object.has("type"), equalTo(true)); assertThat(object.getAsJsonPrimitive("type").getAsString(), equalTo("MultiPolygon")); assertThat(object.has("coordinates"), equalTo(true)); JsonArray coords = object.getAsJsonArray("coordinates"); assertThat(coords.size(), equalTo(2)); JsonArray firstCoords = coords.get(0).getAsJsonArray(); assertThat(firstCoords.size(), equalTo(1)); // no interiors testPositions(firstCoords.get(0).getAsJsonArray(), new double[][] { new double[] { 100.0, 0.0 }, new double[] { 101.0, 0.0 }, new double[] { 101.0, 1.0 }, new double[] { 100.0, 1.0 }, new double[] { 100.0, 0.0 } }); JsonArray secondCoords = coords.get(1).getAsJsonArray(); assertThat(secondCoords.size(), equalTo(2)); // has interior testPositions(secondCoords.get(0).getAsJsonArray(), new double[][] { new double[] { 100.0, 0.0 }, new double[] { 101.0, 0.0 }, new double[] { 101.0, 1.0 }, new double[] { 100.0, 1.0 }, new double[] { 100.0, 0.0 } }); testPositions(secondCoords.get(1).getAsJsonArray(), new double[][] { new double[] { 100.2, 0.2 }, new double[] { 100.8, 0.2 }, new double[] { 100.8, 0.8 }, new double[] { 100.2, 0.8 }, new double[] { 100.2, 0.2 } }); } @Test public void encodeGeometryCollection() { assertThat(true, equalTo(false)); } @Test public void encodeMassiveGeometryCollection() { assertThat(true, equalTo(false)); } @Test public void encodeFeature() { assertThat(true, equalTo(false)); } @Test public void encodeFeatureCollection() { assertThat(true, equalTo(false)); } }
package de.ironjan.mensaupb.menus_ui; import android.annotation.SuppressLint; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.support.v4.view.PagerTabStrip; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.InstanceState; import org.androidannotations.annotations.OptionsItem; import org.androidannotations.annotations.OptionsMenu; import org.androidannotations.annotations.Trace; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import org.androidannotations.annotations.sharedpreferences.Pref; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import arrow.core.Either; import de.ironjan.mensaupb.BuildConfig; import de.ironjan.mensaupb.R; import de.ironjan.mensaupb.api.ClientV3Implementation; import de.ironjan.mensaupb.api.model.Menu; import de.ironjan.mensaupb.api.model.Restaurant; import de.ironjan.mensaupb.app_info.About_; import de.ironjan.mensaupb.prefs.InternalKeyValueStore_; @SuppressWarnings("WeakerAccess") @SuppressLint("Registered") @EActivity(R.layout.activity_menu_listing) @OptionsMenu(R.menu.main) public class Menus extends AppCompatActivity implements ActionBar.OnNavigationListener, MenusNavigationCallback { public static final String KEY_DAY_OFFSET = "KEY_DAY_OFFSET"; public static final String KEY_DATE = "KEY_DATE"; public static final String KEY_RESTAURANT = "KEY_RESTAURANT"; private final Logger LOGGER = LoggerFactory.getLogger(Menus.class.getSimpleName()); @Extra(value = KEY_DATE) String dateAsString = null; @ViewById(R.id.pager) ViewPager mViewPager; @ViewById(R.id.pager_title_strip) PagerTabStrip mPagerTabStrip; String[] mRestaurantKeys = Restaurant.Companion.getKeys(); @Bean WeekdayHelper mwWeekdayHelper; @Extra(value = KEY_RESTAURANT) String restaurant = mRestaurantKeys[0]; @InstanceState int mLocation = 0; @InstanceState int mDayOffset = 0; @Pref InternalKeyValueStore_ mInternalKeyValueStore; @Bean WeekdayHelper mWeekdayHelper; private WeekdayPagerAdapter[] adapters; private WeekdayPagerAdapter mWeekdayPagerAdapter; @Trace @AfterViews @Background void init() { mLocation = mInternalKeyValueStore.lastLocation().get(); initPager(); initActionBar(); } @Trace @UiThread void initActionBar() { final ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayShowTitleEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); List<Integer> nameStringIds = Restaurant.Companion.getNameStringIds(); int restaurantCount = nameStringIds.size(); String[] mDisplayedRestaurantNames = new String[restaurantCount]; final Resources resources = getResources(); for (int i = 0; i < restaurantCount; i++) { mDisplayedRestaurantNames[i] = resources.getString(nameStringIds.get(i)); } ArrayAdapter<String> adapter = new ArrayAdapter<>(actionBar.getThemedContext(), android.R.layout.simple_spinner_item, android.R.id.text1, mDisplayedRestaurantNames); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); actionBar.setListNavigationCallbacks(adapter, this); actionBar.setSelectedNavigationItem(mLocation); } @Trace @UiThread void initPager() { mPagerTabStrip.setTabIndicatorColorResource(R.color.iconBg); mPagerTabStrip.setDrawFullUnderline(true); loadPagerAdapter(mLocation); } @Background @Trace void loadPagerAdapter(int i) { if (BuildConfig.DEBUG) LOGGER.debug("loadPagerAdapter({})", i); mWeekdayPagerAdapter = getPagerAdapter(i); if (BuildConfig.DEBUG) LOGGER.info("Got adapter: {}", mWeekdayPagerAdapter); if (mWeekdayPagerAdapter != null) { switchAdapterTo(mDayOffset); } } @UiThread void switchAdapterTo(int currentItem) { LOGGER.warn("switch to {}", currentItem); mViewPager.setAdapter(mWeekdayPagerAdapter); mViewPager.setCurrentItem(currentItem); } @Trace WeekdayPagerAdapter getPagerAdapter(int i) { if (BuildConfig.DEBUG) LOGGER.debug("getPagerAdapter({})", i); if (adapters == null) { adapters = new WeekdayPagerAdapter[mRestaurantKeys.length]; } if (adapters[i] == null) { createNewAdapter(i); } return adapters[i]; } @Trace @Background void createNewAdapter(int i) { if (BuildConfig.DEBUG) LOGGER.debug("createNewAdapter({})", i); adapters[i] = new WeekdayPagerAdapter(this, getSupportFragmentManager(), mRestaurantKeys[i]); loadPagerAdapter(i); } @Override @Trace public boolean onNavigationItemSelected(int i, long l) { mLocation = i; if (BuildConfig.DEBUG) LOGGER.debug("onNavigationItemSelected({},{}), location := {}", new Object[]{i, l, mLocation}); mDayOffset = mViewPager.getCurrentItem(); loadPagerAdapter(i); restaurant = mRestaurantKeys[i]; return true; } @Override public void showMenu(String key) { MenuDetails_.intent(this) .menuKey(key) .start(); } @Override public void showMenu(Menu m) { MenuDetails_.intent(this) .restaurant(m.getRestaurant()) .date(m.getDate()) .nameEn(m.getName_en()) .start(); } @Override protected void onPause() { super.onPause(); mInternalKeyValueStore.edit().lastLocation().put(mLocation).apply(); } @OptionsItem(R.id.ab_refresh) void refreshClicked() { mWeekdayPagerAdapter.onRefresh(); } @OptionsItem(R.id.ab_openingTimes) void openBrowserWithOpeningTimes(){ final String OPENING_TIMES_URL = "http: Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(OPENING_TIMES_URL)); startActivity(intent); } @OptionsItem(R.id.ab_about) void aboutClicked() { About_.intent(this).start(); } }
package net.md_5.bungee; import com.google.common.base.Preconditions; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import io.netty.channel.Channel; import java.util.Objects; import java.util.Queue; import lombok.RequiredArgsConstructor; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.config.TexturePackInfo; import net.md_5.bungee.api.event.ServerConnectedEvent; import net.md_5.bungee.api.event.ServerKickEvent; import net.md_5.bungee.api.scoreboard.Objective; import net.md_5.bungee.api.scoreboard.Team; import net.md_5.bungee.connection.CancelSendSignal; import net.md_5.bungee.connection.DownstreamBridge; import net.md_5.bungee.netty.HandlerBoss; import net.md_5.bungee.packet.DefinedPacket; import net.md_5.bungee.packet.Packet1Login; import net.md_5.bungee.packet.Packet9Respawn; import net.md_5.bungee.packet.PacketCDClientStatus; import net.md_5.bungee.packet.PacketCEScoreboardObjective; import net.md_5.bungee.packet.PacketD1Team; import net.md_5.bungee.packet.PacketFAPluginMessage; import net.md_5.bungee.packet.PacketFDEncryptionRequest; import net.md_5.bungee.packet.PacketFFKick; import net.md_5.bungee.packet.PacketHandler; @RequiredArgsConstructor public class ServerConnector extends PacketHandler { private final ProxyServer bungee; private Channel ch; private final UserConnection user; private final ServerInfo target; private State thisState = State.ENCRYPT_REQUEST; private enum State { ENCRYPT_REQUEST, LOGIN, FINISHED; } @Override public void connected(Channel channel) throws Exception { this.ch = channel; ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF( "Login" ); out.writeUTF( user.getAddress().getAddress().getHostAddress() ); out.writeInt( user.getAddress().getPort() ); channel.write( new PacketFAPluginMessage( "BungeeCord", out.toByteArray() ) ); channel.write( user.handshake ); channel.write( PacketCDClientStatus.CLIENT_LOGIN ); } @Override public void handle(Packet1Login login) throws Exception { Preconditions.checkState( thisState == State.LOGIN, "Not exepcting LOGIN" ); ServerConnection server = new ServerConnection( ch, target, login ); ServerConnectedEvent event = new ServerConnectedEvent( user, server ); bungee.getPluginManager().callEvent( event ); ch.write( BungeeCord.getInstance().registerChannels() ); // TODO: Race conditions with many connects Queue<DefinedPacket> packetQueue = ( (BungeeServerInfo) target ).getPacketQueue(); while ( !packetQueue.isEmpty() ) { ch.write( packetQueue.poll() ); } if ( user.settings != null ) { ch.write( user.settings ); } synchronized ( user.getSwitchMutex() ) { if ( user.getServer() == null ) { BungeeCord.getInstance().connections.put( user.getName(), user ); bungee.getTabListHandler().onConnect( user ); // Once again, first connection user.clientEntityId = login.entityId; user.serverEntityId = login.entityId; // Set tab list size Packet1Login modLogin = new Packet1Login( login.entityId, login.levelType, login.gameMode, (byte) login.dimension, login.difficulty, login.unused, (byte) user.getPendingConnection().getListener().getTabListSize() ); user.ch.write( modLogin ); ch.write( BungeeCord.getInstance().registerChannels() ); TexturePackInfo texture = user.getPendingConnection().getListener().getTexturePack(); if ( texture != null ) { ch.write( new PacketFAPluginMessage( "MC|TPack", ( texture.getUrl() + "\00" + texture.getSize() ).getBytes() ) ); } } else { bungee.getTabListHandler().onServerChange( user ); for ( Objective objective : user.serverSentScoreboard.getObjectives() ) { user.ch.write( new PacketCEScoreboardObjective( objective.getName(), objective.getValue(), (byte) 1 ) ); } for ( Team team : user.serverSentScoreboard.getTeams() ) { user.ch.write( PacketD1Team.destroy( team.getName() ) ); } user.serverSentScoreboard.clear(); user.sendPacket( Packet9Respawn.DIM1_SWITCH ); user.sendPacket( Packet9Respawn.DIM2_SWITCH ); user.serverEntityId = login.entityId; user.ch.write( new Packet9Respawn( login.dimension, login.difficulty, login.gameMode, (short) 256, login.levelType ) ); // Remove from old servers user.getServer().setObsolete( true ); user.getServer().disconnect( "Quitting" ); } // TODO: Fix this? if ( !user.ch.isActive() ) { server.disconnect( "Quitting" ); // Silly server admins see stack trace and die bungee.getLogger().warning( "No client connected for pending server!" ); return; } // Add to new server // TODO: Move this to the connected() method of DownstreamBridge target.addPlayer( user ); user.pendingConnects.remove( target ); user.setServer( server ); ch.pipeline().get( HandlerBoss.class ).setHandler( new DownstreamBridge( bungee, user, server ) ); } thisState = State.FINISHED; throw new CancelSendSignal(); } @Override public void handle(PacketFDEncryptionRequest encryptRequest) throws Exception { Preconditions.checkState( thisState == State.ENCRYPT_REQUEST, "Not expecting ENCRYPT_REQUEST" ); thisState = State.LOGIN; } @Override public void handle(PacketFFKick kick) throws Exception { ServerInfo def = bungee.getServerInfo( user.getPendingConnection().getListener().getFallbackServer() ); if ( Objects.equals( target, def ) ) { def = null; } ServerKickEvent event = bungee.getPluginManager().callEvent( new ServerKickEvent( user, kick.message, def ) ); if ( event.isCancelled() && event.getCancelServer() != null ) { user.connect( event.getCancelServer() ); return; } String message = ChatColor.RED + "Kicked whilst connecting to " + target.getName() + ": " + kick.message; if ( user.getServer() == null ) { user.disconnect( message ); } else { user.sendMessage( message ); } } @Override public String toString() { return "[" + user.getName() + "] <-> ServerConnector [" + target.getName() + "]"; } }
package com.btr.proxy.search.browser; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import org.junit.Test; import com.btr.proxy.TestUtil; import com.btr.proxy.search.browser.ie.IELocalByPassFilter; import com.btr.proxy.search.browser.ie.IEProxySearchStrategy; import com.btr.proxy.util.PlatformUtil; import com.btr.proxy.util.ProxyException; import com.btr.proxy.util.PlatformUtil.Platform; import com.btr.proxy.util.UriFilter; public class IeTest { @Test public void testInvoke() throws ProxyException { if (Platform.WIN.equals(PlatformUtil.getCurrentPlattform())) { IEProxySearchStrategy st = new IEProxySearchStrategy(); // Try at least to invoke it and test if the dll does not crash st.getProxySelector(); } } @Test public void testLocalByPassFilter() throws ProxyException, MalformedURLException, URISyntaxException { UriFilter filter = new IELocalByPassFilter(); assertTrue(filter.accept(TestUtil.LOCAL_TEST_URI)); assertFalse(filter.accept(TestUtil.HTTP_TEST_URI)); assertFalse(filter.accept(new URL("http://123.45.55.6").toURI())); } }