answer
stringlengths
17
10.2M
package org.usfirst.frc.team166.robot.subsystems; import edu.wpi.first.wpilibj.AnalogGyro; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.PIDSourceType; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.Servo; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.interfaces.Gyro; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc.team166.robot.PIDSpeedController; import org.usfirst.frc.team166.robot.Robot; import org.usfirst.frc.team166.robot.RobotMap; import org.usfirst.frc.team166.robot.commands.drive.DriveWithJoysticks; public class Drive extends Subsystem { double distancePerPulse = 12 / 56320.0; // this makes perfect cents // no it doesn't it makes 2.1306818181... double gyroConstant = -0.3 / 10.0; double driveSpeedModifierConstant = .7; double gyroVal = 0; boolean highGear; boolean neutral; boolean isShiftingOK; double highGearValue = 0.0; double lowGearValue = 1.0; Victor leftTopVictor = new Victor(RobotMap.Pwm.leftTopDrive); Victor leftBotVictor = new Victor(RobotMap.Pwm.leftBotDrive); Victor rightTopVictor = new Victor(RobotMap.Pwm.rightTopDrive); Victor rightBotVictor = new Victor(RobotMap.Pwm.rightBotDrive); Servo transmission1Servo = new Servo(RobotMap.Pwm.leftTransmissionServoPort); Servo transmission2Servo = new Servo(RobotMap.Pwm.rightTransmissionServoPort);// dont be dumb by putting double 1s Encoder leftEncoder = new Encoder(RobotMap.Digital.leftEncoderA, RobotMap.Digital.leftEncoderB);// more Encoder rightEncoder = new Encoder(RobotMap.Digital.rightEncoderA, RobotMap.Digital.rightEncoderB); Encoder leftEncoder1 = new Encoder(RobotMap.Digital.leftEncoder1A, RobotMap.Digital.leftEncoder1B); // delete these // later when we have the real robot Encoder rightEncoder1 = new Encoder(RobotMap.Digital.rightEncoder1A, RobotMap.Digital.rightEncoder1B); PIDSpeedController leftTopPID = new PIDSpeedController(leftEncoder, leftTopVictor, "Drive", "LeftTopPID"); // specify PIDSpeedController leftBotPID = new PIDSpeedController(leftEncoder1, leftBotVictor, "Drive", "LeftBotPID"); PIDSpeedController rightTopPID = new PIDSpeedController(rightEncoder, rightTopVictor, "Drive", "RightTopPID"); PIDSpeedController rightBotPID = new PIDSpeedController(rightEncoder1, rightBotVictor, "Drive", "RightBotPID"); // bot // motors Gyro gyro = new AnalogGyro(RobotMap.Analog.gyroPort); RobotDrive tankDrive = new RobotDrive(leftTopPID, leftBotPID, rightTopPID, rightBotPID); // RobotDrive tankDrive = new RobotDrive(leftTopVictor, leftBotVictor, rightTopVictor, rightBotVictor); public Drive() { leftEncoder.setDistancePerPulse(distancePerPulse); rightEncoder.setDistancePerPulse(distancePerPulse); leftEncoder.setPIDSourceType(PIDSourceType.kRate); rightEncoder.setPIDSourceType(PIDSourceType.kRate); leftEncoder1.setDistancePerPulse(distancePerPulse); rightEncoder1.setDistancePerPulse(distancePerPulse); leftEncoder1.setPIDSourceType(PIDSourceType.kRate); // delete these later rightEncoder1.setPIDSourceType(PIDSourceType.kRate); } public double getGyroOffset() { gyroVal = Robot.drive.getGyro() * gyroConstant; if (Math.abs(gyroVal) > (1.0 - driveSpeedModifierConstant)) { gyroVal = (1.0 - driveSpeedModifierConstant) * Math.abs(gyroVal) / gyroVal; // sets gyroVal to either 1 or } return gyroVal; } public void driveWithGyro() { double rightPower = Robot.oi.getRightYAxis() * driveSpeedModifierConstant; double leftPower = Robot.oi.getLeftYAxis() * driveSpeedModifierConstant; double power = 0; power = (rightPower + leftPower) / 2; if (Math.abs(Robot.oi.getRightYAxis()) > .1) { tankDrive.tankDrive(power + getGyroOffset(), power - getGyroOffset()); } } public void highGear() { if (isShiftingOK == true) { transmission1Servo.set(highGearValue); transmission2Servo.set(highGearValue); highGear = true; neutral = false; leftEncoder.setDistancePerPulse(3 * distancePerPulse); rightEncoder.setDistancePerPulse(3 * distancePerPulse); leftEncoder1.setDistancePerPulse(3 * distancePerPulse); // delete this later rightEncoder1.setDistancePerPulse(3 * distancePerPulse); } } public void lowGear() { if (isShiftingOK == true) { transmission1Servo.set(lowGearValue); transmission2Servo.set(lowGearValue); highGear = false; neutral = false; leftEncoder.setDistancePerPulse(distancePerPulse); rightEncoder.setDistancePerPulse(distancePerPulse); leftEncoder1.setDistancePerPulse(distancePerPulse); // delete this later rightEncoder1.setDistancePerPulse(distancePerPulse); // delete this later } } public void neutral() { transmission1Servo.set(0.5); transmission2Servo.set(0.5); neutral = true; } public void driveWithJoysticks() { // integrate gyro into drive. i.e. correct for imperfect forward motion // with a proportional controller double rightPower = Robot.oi.getRightYAxis() * driveSpeedModifierConstant; boolean areJoysticksSimilar = false; if ((Math.abs(Robot.oi.getLeftYAxis()) > .1) || (Math.abs(Robot.oi.getRightYAxis()) > .1)) { isShiftingOK = true; SmartDashboard.putNumber("Gyro Offset", getGyroOffset()); SmartDashboard.putNumber("Right Power", rightPower); SmartDashboard.putBoolean("areJoysticksSimilar", areJoysticksSimilar); tankDrive.tankDrive(Robot.oi.getLeftYAxis(), Robot.oi.getRightYAxis()); // if not trying to go straight, // } else { isShiftingOK = false; stop(); } } public void driveWithJoysticksBackward() { // integrate gyro into drive. i.e. correct for imperfect forward motion // with a proportional controller double rightPower = -Robot.oi.getRightYAxis() * driveSpeedModifierConstant; boolean areJoysticksSimilar = false; if ((Math.abs(Robot.oi.getLeftYAxis()) > .1) || (Math.abs(Robot.oi.getRightYAxis()) > .1)) { isShiftingOK = true; SmartDashboard.putNumber("Gyro Offset", getGyroOffset()); SmartDashboard.putNumber("Right Power", rightPower); SmartDashboard.putBoolean("areJoysticksSimilar", areJoysticksSimilar); if (Math.abs(Robot.oi.getLeftYAxis()) > 0.1 ^ Math.abs(Robot.oi.getRightYAxis()) > 0.1) { double powerBoth = (Robot.oi.getLeftYAxis() + Robot.oi.getRightYAxis()) / 2; tankDrive.tankDrive(-powerBoth, -powerBoth); } else if (Math.abs(Robot.oi.getLeftYAxis()) > 0.1 && Math.abs(Robot.oi.getRightYAxis()) > 0.1) { tankDrive.tankDrive(-Robot.oi.getLeftYAxis(), -Robot.oi.getRightYAxis()); } } else { isShiftingOK = false; stop(); } } public void stop() { tankDrive.tankDrive(0, 0); } public void resetGyro() { gyro.reset(); } public void resetEncoders() { leftEncoder.reset(); rightEncoder.reset(); } public double getLeftEncoder() { SmartDashboard.putNumber("Left Encoder", leftEncoder.getRate()); return leftEncoder.getRate(); } public double getRightEncoder() { SmartDashboard.putNumber("Right Encoder", rightEncoder.getRate()); return rightEncoder.getRate(); } public double getDistance() { return (((getLeftEncoder() + getRightEncoder()) / 2.0) / 1024.0) / 31.4; } public double getGyro() { return gyro.getAngle(); } public void turnAngle(double angle) { double power = (angle - getGyro()) / angle; if (getGyro() < angle - 7.0) { tankDrive.tankDrive(power, -power); // rightMotor(-power); // leftMotor(power); } else if (getGyro() > angle + 7) { tankDrive.tankDrive(-power, power); // rightMotor(power); // leftMotor(-power); } else if (getGyro() >= angle - 7 && getGyro() <= angle + 7) { tankDrive.tankDrive(0, 0); } } public void driveDistance(double distance) { // inches double power = (distance - getDistance()) / distance; if (getDistance() <= (Math.PI * distance) - 4) { tankDrive.tankDrive(power, power); } else { tankDrive.tankDrive(0, 0); } } public void driveDirection(double angle, double distance) { turnAngle(angle); driveDistance(distance); } public void setPIDConstants() { // double p = 1; // double i = 2; // double d = 0; // double f = 1; double p = 0.000001; double i = 0.000001; double d = 0.000001; double f = 1; leftTopPID.setConstants(p, i, d, f); leftBotPID.setConstants(p, i, d, f); rightTopPID.setConstants(p, i, d, f); rightBotPID.setConstants(p, i, d, f); } @Override public void initDefaultCommand() { setDefaultCommand(new DriveWithJoysticks()); } }
package dr.evomodel.antigenic; import dr.inference.model.MatrixParameter; import dr.inference.model.Parameter; import dr.inference.model.Variable; import dr.inference.operators.MCMCOperator; import dr.inference.operators.SimpleMCMCOperator; import dr.math.MathUtils; import dr.xml.*; import javax.lang.model.element.Element; /** * An operator to split or merge clusters. * * @author Andrew Rambaut * @author Marc Suchard * @version $Id: DirichletProcessGibbsOperator.java,v 1.16 2005/06/14 10:40:34 rambaut Exp $ */ public class ClusterSplitMergeOperator extends SimpleMCMCOperator { public final static String CLUSTER_SPLIT_MERGE_OPERATOR = "clusterSplitMergeOperator"; private final int N; // the number of items private int K; // the number of occupied clusters private final Parameter allocationParameter; private final MatrixParameter clusterLocations; public ClusterSplitMergeOperator(Parameter allocationParameter, MatrixParameter clusterLocations, double weight) { this.allocationParameter = allocationParameter; this.clusterLocations = clusterLocations; this.N = allocationParameter.getDimension(); setWeight(weight); } /** * @return the parameter this operator acts on. */ public Parameter getParameter() { return (Parameter) allocationParameter; } /** * @return the Variable this operator acts on. */ public Variable getVariable() { return allocationParameter; } /** * change the parameter and return the hastings ratio. */ public final double doOperation() { // get a copy of the allocations to work with... int[] allocations = new int[allocationParameter.getDimension()]; // construct cluster occupancy vector excluding the selected item and count // the unoccupied clusters. int[] occupancy = new int[N]; int X = N; // X = number of unoccupied clusters for (int i = 0; i < allocations.length; i++) { allocations[i] = (int) allocationParameter.getParameterValue(i); occupancy[allocations[i]] += 1; if (occupancy[allocations[i]] == 1) { // first item in cluster X -= 1; // one fewer unoccupied } } K = N - X; // Container for split/merge random variable (only 2 draws in 2D) int paramDim = clusterLocations.getParameter(0).getDimension(); double[] splitDraw = new double[paramDim]; // Need to keep these for computing MHG ratio double scale = 1.0; // TODO make tunable int moveType = MathUtils.nextInt(2); // 0 for split, 1 for merge if ( (moveType == 0 && K < N) || K == 1) { // always split when K==1 // Split operation int cluster1; int cluster2; do { // pick an occupied cluster cluster1 = MathUtils.nextInt(K); cluster2 = K; // next available unoccupied cluster for (int i = 0; i < allocations.length; i++) { if (allocations[i] == cluster1) { if (MathUtils.nextDouble() < 0.5) { allocations[i] = cluster2; occupancy[cluster1] occupancy[cluster2] ++; } } } // For reversibility, merge step requires that both resulting clusters are occupied, // so we should resample until condition is true } while (occupancy[cluster1] == 0); // set both clusters to a location based on the first cluster with some random jitter... Parameter param1 = clusterLocations.getParameter(cluster1); Parameter param2 = clusterLocations.getParameter(cluster2); double[] loc = param1.getParameterValues(); for (int dim = 0; dim < param1.getDimension(); dim++) { splitDraw[dim] = MathUtils.nextGaussian(); param1.setParameterValue(dim, loc[dim] + (splitDraw[dim] * scale)); param2.setParameterValue(dim, loc[dim] - (splitDraw[dim] * scale)); // Move in opposite direction } } if ( (moveType == 1 && K > 1 ) || K == N) { // always merge when K==N // Merge operation // pick 2 occupied clusters int cluster1 = MathUtils.nextInt(K); int cluster2; do { cluster2 = MathUtils.nextInt(K); // resample until cluster1 != cluster2 to maintain reversibility, because split assumes they are different } while (cluster1 == cluster2); if (cluster1 > cluster2) { // swap the cluster indices to keep the destination cluster lower int tmp = cluster1; cluster1 = cluster2; cluster2 = tmp; } for (int i = 0; i < allocations.length; i++) { if (allocations[i] == cluster2) { allocations[i] = cluster1; occupancy[cluster1] ++; occupancy[cluster2] } } // set the merged cluster to the mean location of the two original clusters Parameter loc1 = clusterLocations.getParameter(cluster1); Parameter loc2 = clusterLocations.getParameter(cluster2); for (int dim = 0; dim < loc1.getDimension(); dim++) { double average = (loc1.getParameterValue(dim) + loc2.getParameterValue(dim)) / 2.0; splitDraw[dim] = (loc1.getParameterValue(dim) - average) / scale; // Record that the reverse step would need to draw loc1.setParameterValue(dim, average); } } // set the final allocations (only for those that have changed) for (int i = 0; i < allocations.length; i++) { int k = (int) allocationParameter.getParameterValue(i); if (allocations[i] != k) { allocationParameter.setParameterValue(i, allocations[i]); } } // todo the Hastings ratio return 1.0; } //MCMCOperator INTERFACE public final String getOperatorName() { return CLUSTER_SPLIT_MERGE_OPERATOR +"(" + allocationParameter.getId() + ")"; } public final void optimize(double targetProb) { throw new RuntimeException("This operator cannot be optimized!"); } public boolean isOptimizing() { return false; } public void setOptimizing(boolean opt) { throw new RuntimeException("This operator cannot be optimized!"); } public double getMinimumAcceptanceLevel() { return 0.1; } public double getMaximumAcceptanceLevel() { return 0.4; } public double getMinimumGoodAcceptanceLevel() { return 0.20; } public double getMaximumGoodAcceptanceLevel() { return 0.30; } public String getPerformanceSuggestion() { if (Utils.getAcceptanceProbability(this) < getMinimumAcceptanceLevel()) { return ""; } else if (Utils.getAcceptanceProbability(this) > getMaximumAcceptanceLevel()) { return ""; } else { return ""; } } public String toString() { return getOperatorName(); } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public final static String CHI = "chi"; public final static String LIKELIHOOD = "likelihood"; public String getParserName() { return CLUSTER_SPLIT_MERGE_OPERATOR; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT); Parameter allocationParameter = (Parameter) xo.getChild(Parameter.class); MatrixParameter locationsParameter = (MatrixParameter) xo.getElementFirstChild("locations"); return new ClusterSplitMergeOperator(allocationParameter, locationsParameter, weight); }
package com.minecraftuberverse.tannery; import org.apache.logging.log4j.Logger; import com.minecraftuberverse.tannery.proxy.CommonProxy; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; @Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.VERSION, canBeDeactivated = true) public class Tannery { @Instance(Reference.MOD_ID) public static Tannery modInstance; @SidedProxy(clientSide = "com.minecraftuberverse.tannery.proxy.ClientProxy", serverSide = "com.minecraftuberverse.tannery.proxy.ServerProxy") public static CommonProxy proxy; public static CreativeTabs tabTannery; public static Logger logger; @EventHandler public void preInit(FMLPreInitializationEvent event) { logger = event.getModLog(); tabTannery = new CreativeTabs(CreativeTabs.getNextID(), "tabTannery") { @Override public Item getTabIconItem() { // TODO Assign proper item as icon return Items.leather; } }; proxy.preInit(); } @EventHandler public void init(FMLInitializationEvent event) { proxy.init(); } @EventHandler public void postInit(FMLPostInitializationEvent event) { proxy.postInit(); } }
package org.broadinstitute.sting.playground.gatk.walkers; import org.broadinstitute.sting.gatk.*; import org.broadinstitute.sting.gatk.refdata.*; import org.broadinstitute.sting.gatk.walkers.*; import org.broadinstitute.sting.playground.utils.*; import org.broadinstitute.sting.playground.utils.GenotypeLikelihoods.IndelCall; import org.broadinstitute.sting.utils.cmdLine.Argument; import org.broadinstitute.sting.utils.BasicPileup; import org.broadinstitute.sting.utils.ReadBackedPileup; import org.broadinstitute.sting.utils.BaseUtils; import org.broadinstitute.sting.utils.MathUtils; import org.broadinstitute.sting.utils.QualityUtils; import net.sf.samtools.*; import java.io.*; import java.util.*; // Draft single sample genotyper // j.maguire 3-7-2009 public class SingleSampleGenotyper extends LocusWalker<AlleleFrequencyEstimate, String> { @Argument(fullName="calls", shortName="calls", doc="File to write SNP calls to", required=true) public String callsFileName; @Argument(fullName="metrics", shortName="met", doc="metrics", required=false) public String metricsFileName = "/dev/null"; @Argument(fullName="metInterval", shortName="mi", doc="metInterval", required=false) public Integer metricsInterval = 50000; @Argument(fullName="printMetrics", shortName="printMetrics", doc="printMetrics", required=false) public Boolean printMetrics = true; @Argument(fullName="lodThreshold", shortName="lod", doc="lodThreshold", required=false) public Double lodThreshold = 5.0; @Argument(fullName="fourBaseMode", shortName="fb", doc="fourBaseMode", required=false) public Boolean fourBaseMode = false; @Argument(fullName="call_indels", shortName="call_indels", doc="Call Indels", required=false) public Boolean call_indels = false; @Argument(fullName="refPrior", shortName="refPrior", required=false, doc="Prior likelihood of the reference theory") public double REF_PRIOR = 0.999; @Argument(fullName="hetVarPrior", shortName="hetVarPrior", required=false, doc="Prior likelihood of a heterozygous variant theory") public double HETVAR_PRIOR = 1e-3; @Argument(fullName="homVarPrior", shortName="homVarPrior", required=false, doc="Prior likelihood of the homozygous variant theory") public double HOMVAR_PRIOR = 1e-5; @Argument(fullName="geli", shortName="geli", doc="If true, output will be in Geli/Picard format", required=false) public boolean GeliOutputFormat = false; @Argument(fullName="sample_name_regex", shortName="sample_name_regex", doc="sample_name_regex", required=false) public String SAMPLE_NAME_REGEX = null; public AlleleMetrics metrics; public PrintStream calls_file; public String sample_name; public boolean filter(RefMetaDataTracker tracker, char ref, LocusContext context) { return true; } public boolean requiresReads() { return true; } public void initialize() { try { sample_name = null; if (metricsFileName != null) { metrics = new AlleleMetrics(metricsFileName, lodThreshold); } if (callsFileName != null) { calls_file = new PrintStream(callsFileName); String header = GeliOutputFormat ? AlleleFrequencyEstimate.geliHeaderString() : AlleleFrequencyEstimate.asTabularStringHeader(); calls_file.println(header); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } public AlleleFrequencyEstimate map(RefMetaDataTracker tracker, char ref, LocusContext context) { String rodString = getRodString(tracker); ref = Character.toUpperCase(ref); if (ref == 'N') { return null; } if (context.getReads().size() != 0) { SAMRecord read = context.getReads().get(0); String RG = (String)(read.getAttribute("RG")); SAMReadGroupRecord read_group_record = read.getHeader().getReadGroup(RG); if (read_group_record != null) { String local_sample_name = read.getHeader().getReadGroup(RG).getSample(); if (SAMPLE_NAME_REGEX != null) { local_sample_name = local_sample_name.replaceAll(SAMPLE_NAME_REGEX, "$1"); } if (sample_name == null) { sample_name = local_sample_name; } else { if (! sample_name.equals(local_sample_name)) { System.out.printf("SAMPLE NAME MIXUP: %s vs. %s\n", sample_name, local_sample_name); } assert(sample_name.equals(local_sample_name)); } } } AlleleFrequencyEstimate freq = getAlleleFrequency(ref, context, rodString, sample_name); if (printMetrics) { if (freq != null) { metrics.nextPosition(freq, tracker); } metrics.printMetricsAtLocusIntervals(metricsInterval); } return freq; } private AlleleFrequencyEstimate getAlleleFrequency(char ref, LocusContext context, String rodString, String sample_name) { ReadBackedPileup pileup = new ReadBackedPileup(ref, context); String bases = pileup.getBases(); if (bases.length() == 0) { GenotypeLikelihoods G = new GenotypeLikelihoods(); return G.toAlleleFrequencyEstimate(context.getLocation(), ref, bases.length(), bases, G.likelihoods, sample_name); } List<SAMRecord> reads = context.getReads(); List<Integer> offsets = context.getOffsets(); ref = Character.toUpperCase(ref); // Handle indels. if (call_indels) { String[] indels = BasicPileup.indelPileup(reads, offsets); IndelCall indel_call = GenotypeLikelihoods.callIndel(indels); if (indel_call != null) { if (! indel_call.type.equals("ref")) { System.out.printf("INDEL %s %s\n", context.getLocation(), indel_call); } } } // Handle single-base polymorphisms. GenotypeLikelihoods G = new GenotypeLikelihoods(); for ( int i = 0; i < reads.size(); i++ ) { SAMRecord read = reads.get(i); int offset = offsets.get(i); G.add(ref, read.getReadString().charAt(offset), read.getBaseQualities()[offset]); } G.ApplyPrior(ref, this.alt_allele, this.allele_frequency_prior); if (fourBaseMode && pileup.getBases().length() < 750) { G.applySecondBaseDistributionPrior(pileup.getBases(), pileup.getSecondaryBasePileup()); } return G.toAlleleFrequencyEstimate(context.getLocation(), ref, bases.length(), bases, G.likelihoods, sample_name); } private String getRodString(RefMetaDataTracker tracker) { String rodString = ""; for ( ReferenceOrderedDatum datum : tracker.getAllRods() ) { if ( datum != null ) { if ( datum instanceof rodDbSNP) { rodDbSNP dbsnp = (rodDbSNP)datum; rodString += dbsnp.toString(); } else { rodString += datum.toSimpleString(); } } } if ( rodString != "" ) { rodString = "[ROD: " + rodString + "]"; } return rodString; } double allele_frequency_prior = -1; char alt_allele; public void setAlleleFrequencyPrior(double freq, char alt) { this.allele_frequency_prior = freq; this.alt_allele = alt; } // Given result of map function private String confident_ref_interval_contig = ""; private long confident_ref_interval_start = 0; private double confident_ref_interval_LOD_sum = 0; private double confident_ref_interval_length = 0; private long last_position_considered = -1; private boolean inside_confident_ref_interval = false; public String reduceInit() { confident_ref_interval_contig = ""; confident_ref_interval_start = 0; confident_ref_interval_LOD_sum = 0; confident_ref_interval_length = 0; last_position_considered = -1; inside_confident_ref_interval = false; return ""; } public String reduce(AlleleFrequencyEstimate alleleFreq, String sum) { if ( alleleFreq.lodVsRef >= lodThreshold ) { String line = GeliOutputFormat ? alleleFreq.asGeliString() : alleleFreq.asTabularString(); calls_file.println(line); } return ""; } public void onTraversalDone() { if (callsFileName != null) { calls_file.close(); } } /* public String reduce(AlleleFrequencyEstimate alleleFreq, String sum) { // Print RESULT data for confident calls long current_offset = alleleFreq.location.getStart(); //Integer.parseInt(tokens[1]); if (inside_confident_ref_interval && ((alleleFreq.lodVsRef > -5.0) || (current_offset != last_position_considered + 1)) ) { // No longer hom-ref, so output a ref line. double lod = confident_ref_interval_LOD_sum / confident_ref_interval_length; calls_file.format("%s\tCALLER\tREFERENCE\t%d\t%d\t%f\t.\t.\tLENGTH %d\n", confident_ref_interval_contig, confident_ref_interval_start, last_position_considered, lod, (int)(confident_ref_interval_length)); inside_confident_ref_interval = false; } else if (inside_confident_ref_interval && (alleleFreq.lodVsRef <= -5.0)) { // Still hom-ref so increment the counters. confident_ref_interval_LOD_sum += alleleFreq.lodVsRef; confident_ref_interval_length += 1; } else if ((!inside_confident_ref_interval) && (alleleFreq.lodVsRef > -5.0)) { // do nothing. } else if ((!inside_confident_ref_interval) && (alleleFreq.lodVsRef <= -5.0)) { // We moved into a hom-ref region so start a new interval. confident_ref_interval_contig = alleleFreq.location.getContig(); confident_ref_interval_start = alleleFreq.location.getStart(); confident_ref_interval_LOD_sum = alleleFreq.lodVsRef; confident_ref_interval_length = 1; inside_confident_ref_interval = true; } last_position_considered = current_offset; if (alleleFreq.lodVsRef >= 5) { calls_file.print(alleleFreq.asGFFString()); //String gtype = genotypeTypeString(alleleFreq.qstar, alleleFreq.N); //System.out.print("DEBUG " + gtype + " "); //if (gtype.contentEquals("het")) { // System.out.println(alleleFreq.ref + "" + alleleFreq.alt); //} else if (gtype.contentEquals("hom")) { // System.out.println(alleleFreq.ref + "" + alleleFreq.ref); //} else { // System.out.println(alleleFreq.alt + "" + alleleFreq.alt); //} } return ""; } */ }
package org.uwcs.choob.plugins; import java.io.*; import java.net.*; import java.security.*; import java.util.*; import java.util.regex.*; import org.uwcs.choob.*; import org.uwcs.choob.support.events.*; import org.uwcs.choob.support.*; import org.uwcs.choob.modules.*; import org.mozilla.javascript.*; import org.mozilla.javascript.regexp.*; /* * Deals with all the magic for JavaScript plugins. Woo. * @author silver */ public class JavaScriptPluginManager extends ChoobPluginManager { /* * The plugin map tracks which plugin instances have which commands, and * keeps a command name --> function map in particular. */ private JavaScriptPluginMap pluginMap; // The size of the reading buffer when loading JS files. private static final int READER_CHUNK = 1024; // For passing to plugin constructors. private final Modules mods; private final IRCInterface irc; private final int CALL_UNKNOWN = 0; private final int CALL_WANT_TASK = 1; private final int CALL_WANT_RESULT = 2; public JavaScriptPluginManager(Modules mods, IRCInterface irc) { this.mods = mods; this.irc = irc; this.pluginMap = new JavaScriptPluginMap(); } /* * Utility method for JS scripts, so they can print debug information out * easily. Signature stolen from Mozilla/Firefox. */ public static void dump(String text) { System.out.print("JS dump: " + text); } /* * Utility method for JS scripts, so they can print debug information out * easily. */ public static void dumpln(String text) { System.out.println("JS dump: " + text); } protected Object createPlugin(String pluginName, URL fromLocation) throws ChoobException { System.out.println("JavaScriptPluginManager.createPlugin"); String code = ""; URLConnection con; try { // First thing's first; we must connect to the identified resource. con = fromLocation.openConnection(); } catch(IOException e) { throw new ChoobException("Unable to open a connection to the source location <" + fromLocation + ">."); } try { /* * This lot reads the resource in in chunks, using a buffer, and * simply keeps the code in a local variable (once it has be * evaluated in a plugin instances, it is no longer needed). */ con.connect(); InputStream stream = con.getInputStream(); InputStreamReader streamReader = new InputStreamReader(stream); int read = 0; char[] chars = new char[READER_CHUNK]; while (true) { int r = streamReader.read(chars, 0, READER_CHUNK); if (r == -1) break; for (int i = 0; i < r; i++) code += chars[i]; read += r; } System.out.println("JavaScriptPluginManager.createPlugin: loaded " + read + " characters."); } catch(IOException e) { throw new ChoobException("Unable to fetch the source from <" + fromLocation + ">."); } // Create the new plugin instance. JavaScriptPlugin plug = new JavaScriptPlugin(this, pluginName, code, mods, irc); // Update bot's overall command list, for spell-check-based suggestions. String[] newCommands = new String[0]; String[] oldCommands = new String[0]; synchronized(pluginMap) { List<String> commands; // Get list of commands for plugin before setting up new one. commands = pluginMap.getCommands(pluginName); if (commands != null) oldCommands = (String[])commands.toArray(oldCommands); // Clear the old instance's map data and load the new plugin map. pluginMap.unloadPluginMap(pluginName); pluginMap.loadPluginMap(pluginName, plug); // Get list of commands for newly loaded plugin. commands = pluginMap.getCommands(pluginName); if (commands != null) newCommands = (String[])commands.toArray(newCommands); } // Update bot's command list now. for (int i = 0; i < oldCommands.length; i++) removeCommand(oldCommands[i]); for (int i = 0; i < newCommands.length; i++) addCommand(newCommands[i]); return plug; } protected void destroyPlugin(String pluginName) throws ChoobException { synchronized(pluginMap) { pluginMap.unloadPluginMap(pluginName); } } public ChoobTask commandTask(String pluginName, String command, Message ev) { // Call a command! Look it up, and then call if something was found. JavaScriptPluginMethod method = pluginMap.getCommand(pluginName + "." + command); if (method != null) { return callCommand(method, ev); } return null; } public ChoobTask intervalTask(String pluginName, Object param) { // Call the interval callback function. JavaScriptPluginMethod method = pluginMap.getInterval(pluginName); if (method != null) { return callCommand(method, param); } return null; } public List<ChoobTask> eventTasks(IRCEvent ev) { // Call the event hook functions. List<ChoobTask> events = new LinkedList<ChoobTask>(); List<JavaScriptPluginMethod> methods = pluginMap.getEvent(ev.getMethodName()); if (methods != null) { for (JavaScriptPluginMethod method: methods) { events.add(callCommand(method, ev)); } } return events; } public List<ChoobTask> filterTasks(Message ev) { // Call the filter hook functions. List<ChoobTask> tasks = new LinkedList<ChoobTask>(); List<JavaScriptPluginMethod> methods = pluginMap.getFilter(ev.getMessage()); if (methods != null) { for (JavaScriptPluginMethod method: methods) { tasks.add(callCommand(method, ev)); } } return tasks; } public Object doGeneric(String pluginName, String prefix, String genericName, Object... params) throws ChoobException { String fullName = pluginName + "." + prefix + ":" + genericName; JavaScriptPluginExport method = pluginMap.getGeneric(fullName); if (method == null) { throw new ChoobNoSuchCallException("No call found for " + fullName); } return callMethod(method, params, CALL_WANT_RESULT); } public Object doAPI(String pluginName, String APIName, final Object... params) throws ChoobException { return doGeneric(pluginName, "api", APIName, params); } private ChoobTask callCommand(JavaScriptPluginMethod method, Object param) { Object[] params = { param, mods, irc }; return (ChoobTask)callMethod(method, params, CALL_WANT_TASK); } private Object callMethod(final JavaScriptPluginExport export, final Object[] params, final int result) { final JavaScriptPlugin plugin = export.getPlugin(); final String pluginName = plugin.getName(); ProtectionDomain accessDomain = mods.security.getProtectionDomain(pluginName); final AccessControlContext accessContext = new AccessControlContext(new ProtectionDomain[] { accessDomain }); final PrivilegedExceptionAction action = new PrivilegedExceptionAction() { public Object run() throws ChoobException { Context cx = Context.enter(); try { Scriptable scope = plugin.getScope(); Scriptable inst = plugin.getInstance(); if (export instanceof JavaScriptPluginMethod) { JavaScriptPluginMethod method = (JavaScriptPluginMethod)export; Function function = method.getFunction(); return mapJSToJava(function.call(cx, scope, inst, params)); } if (export instanceof JavaScriptPluginProperty) { JavaScriptPluginProperty prop = (JavaScriptPluginProperty)export; return mapJSToJava(prop.getValue()); } throw new ChoobException("Unknown export type for " + export.getName() + "."); } catch (RhinoException e) { if (params[0] instanceof Message) { irc.sendContextReply((Message)params[0], e.details() + " Line " + e.lineNumber() + ", col " + e.columnNumber() + " of " + e.sourceName() + "."); } else { System.err.println("Exception invoking method " + export.getName() + ":"); e.printStackTrace(); } } catch (Exception e) { if (params[0] instanceof Message) { irc.sendContextReply((Message)params[0], mods.plugin.exceptionReply(e)); } else { System.err.println("Exception invoking method " + export.getName() + ":"); e.printStackTrace(); } } finally { cx.exit(); } return null; } }; if (result == CALL_WANT_TASK) { final Object[] params2 = params; return new ChoobTask(pluginName) { public void run() { try { AccessController.doPrivileged(action, accessContext); } catch (PrivilegedActionException e) { //throw (ChoobException)(e.getCause()); } } }; } if (result == CALL_WANT_RESULT) { try { return AccessController.doPrivileged(action, accessContext); } catch (PrivilegedActionException e) { //throw (ChoobException)(e.getCause()); } } return null; } private Object mapJSToJava(Object jsObject) { // Most Native* types from Rhino are automatically converted, or // something. Arrays, however, definately are not. This code will map // JS arrays into Java ones. It tries to use sensible types, as well. if (jsObject instanceof NativeArray) { NativeArray ary = (NativeArray)jsObject; int aryLen = (int)ary.getLength(); Object[] aryO = new Object [aryLen]; String[] aryS = new String [aryLen]; boolean[] aryB = new boolean[aryLen]; double[] aryN = new double [aryLen]; boolean isStringArray = true; boolean isBooleanArray = true; boolean isNumberArray = true; for (int i = 0; i < aryLen; i++) { Object item = ary.get(i, ary); aryO[i] = mapJSToJava(item); if (isStringArray) { if (item instanceof String) { aryS[i] = (String)item; } else { isStringArray = false; } } if (isBooleanArray) { if (item instanceof Boolean) { aryB[i] = ((Boolean)item).booleanValue(); } else { isBooleanArray = false; } } if (isNumberArray) { if (item instanceof Number) { aryN[i] = ((Number)item).doubleValue(); } else { isNumberArray = false; } } } if (isStringArray) { return aryS; } if (isBooleanArray) { return aryB; } if (isNumberArray) { return aryN; } return aryO; } return jsObject; } } final class JavaScriptPluginMap { /* Naming for items loaded from plugins: * * TYPE NAME IN PLUGIN RELATION NAME IN MAP * Command commandFoo one pluginname.foo * Event onFoo many onfoo * Filter filterFoo ? /regexp/ * Generic otherFooBar one pluginname.other:foobar * Interval interval one pluginname */ // List of plugins. private final Map<String,JavaScriptPlugin> plugins; // List of function for each command. private final Map<String,JavaScriptPluginMethod> commands; // List of function for each event. private final Map<String,List<JavaScriptPluginMethod>> events; // List of function for each filter. private final Map<NativeRegExp,JavaScriptPluginMethod> filters; // List of function for each generic. private final Map<String,JavaScriptPluginExport> generics; // List of function for each interval callback. private final Map<String,JavaScriptPluginMethod> intervals; public JavaScriptPluginMap() { plugins = new HashMap<String,JavaScriptPlugin>(); commands = new HashMap<String,JavaScriptPluginMethod>(); events = new HashMap<String,List<JavaScriptPluginMethod>>(); filters = new HashMap<NativeRegExp,JavaScriptPluginMethod>(); generics = new HashMap<String,JavaScriptPluginExport>(); intervals = new HashMap<String,JavaScriptPluginMethod>(); } synchronized void loadPluginMap(String pluginName, JavaScriptPlugin pluginObj) { System.out.println("JavaScriptPluginMap.loadPluginMap(" + pluginName + ")"); String lname = pluginName.toLowerCase(); System.out.println("Loading " + pluginName + ":"); System.out.println(" TYPE NAME"); plugins.put(lname, pluginObj); int count = 0; Scriptable inst = pluginObj.getInstance(); while (inst != null) { Object[] propList = inst.getIds(); String propString; for (Object prop: propList) { if (prop instanceof String) { propString = (String)prop; if (propString.startsWith("command")) { // Looks like a command definition. Object propVal = inst.get(propString, inst); if (!(propVal instanceof Function)) { System.err.println(" WARNING: Command-like property that is not a function: " + propString); continue; } // It's a function, yay! Function func = (Function)propVal; JavaScriptPluginMethod method = new JavaScriptPluginMethod(pluginObj, propString, func); String commandName = lname + "." + propString.substring(7).toLowerCase(); commands.put(commandName, method); count++; System.out.println(" Command " + commandName); // Check for command help. Object helpVal = func.get("help", func); if (helpVal == Scriptable.NOT_FOUND) { continue; } JavaScriptPluginExport helpExport; if (helpVal instanceof Function) { // It's a function, yay! Function helpFunc = (Function)helpVal; helpExport = new JavaScriptPluginMethod(pluginObj, propString + ".help", helpFunc); } else { helpExport = new JavaScriptPluginProperty(pluginObj, propString + ".help"); } String fullName = lname + ".help:" + propString.toLowerCase(); generics.put(fullName, helpExport); count++; System.out.println(" Generic " + fullName); } else if (propString.startsWith("on")) { // Looks like an event handler definition. Object propVal = inst.get(propString, inst); if (!(propVal instanceof Function)) { System.err.println(" WARNING: Event-like property that is not a function: " + propString); continue; } // It's a function, yay! Function func = (Function)propVal; JavaScriptPluginMethod method = new JavaScriptPluginMethod(pluginObj, propString, func); String eventName = propString.toLowerCase(); if (events.get(eventName) == null) { events.put(eventName, new LinkedList<JavaScriptPluginMethod>()); } events.get(eventName).add(method); count++; System.out.println(" Event " + eventName + " (" + pluginName + ")"); } else if (propString.startsWith("filter")) { // Looks like a filter definition. Object propVal = inst.get(propString, inst); if (!(propVal instanceof Function)) { System.err.println(" WARNING: Filter-like property that is not a function: " + propString); continue; } // It's a function, yay! Function func = (Function)propVal; Object regexpVal = func.get("regexp", func); if (regexpVal == Scriptable.NOT_FOUND) { System.err.println(" WARNING: Filter function (" + propString + ") missing 'regexp' property."); continue; } if (!(regexpVal instanceof NativeRegExp)) { System.err.println(" WARNING: Filter function (" + propString + ") property 'regexp' is not a Regular Expression: " + regexpVal.getClass().getName()); continue; } JavaScriptPluginMethod method = new JavaScriptPluginMethod(pluginObj, propString, func); String filterName = lname + "." + propString.substring(6).toLowerCase(); NativeRegExp filterPattern = (NativeRegExp)regexpVal; filters.put(filterPattern, method); count++; System.out.println(" Filter " + filterPattern + " (" + pluginName + ")"); } else if (propString.equals("interval")) { // Looks like an interval callback. Object propVal = inst.get(propString, inst); if (!(propVal instanceof Function)) { System.err.println(" WARNING: Interval-like property that is not a function: " + propString); continue; } // It's a function, yay! Function func = (Function)propVal; JavaScriptPluginMethod method = new JavaScriptPluginMethod(pluginObj, propString, func); intervals.put(lname, method); count++; System.out.println(" Interval " + lname); } else { Matcher matcher = Pattern.compile("([a-z]+)([A-Z].+)?").matcher(propString); if (matcher.matches()) { // Looks like a generic definition. Object propVal = inst.get(propString, inst); JavaScriptPluginExport export; if (propVal instanceof Function) { // It's a function, yay! Function func = (Function)propVal; export = new JavaScriptPluginMethod(pluginObj, propString, func); } else { export = new JavaScriptPluginProperty(pluginObj, propString); } String prefix = matcher.group(1); String gName = propString.substring(prefix.length()).toLowerCase(); String fullName = lname + "." + prefix + ":" + gName; generics.put(fullName, export); count++; System.out.println(" Generic " + fullName); } else { System.err.println(" WARNING: Unknown property: " + propString); } } } else { System.out.println(" Found property of type: " + prop.getClass().getName()); } } inst = inst.getPrototype(); } System.out.println("Done (" + count + " items added)."); } synchronized void unloadPluginMap(String pluginName) { System.out.println("JavaScriptPluginMap.unloadPluginMap(" + pluginName + ")"); String lname = pluginName.toLowerCase(); if (plugins.get(lname) == null) { return; } JavaScriptPlugin pluginObj = plugins.get(lname); System.out.println("Unloading " + pluginName + ":"); System.out.println(" TYPE NAME"); int count = 0; // Commands List<String> commandsToRemove = new LinkedList<String>(); for (String command: commands.keySet()) { if (commands.get(command).getPlugin() == pluginObj) { commandsToRemove.add(command); } } for (String command: commandsToRemove) { System.out.println(" Command " + command); count++; commands.remove(command); } // Events for (String event: events.keySet()) { List<JavaScriptPluginMethod> eventHooksToRemove = new LinkedList<JavaScriptPluginMethod>(); for (JavaScriptPluginMethod method: events.get(event)) { if (method.getPlugin() == pluginObj) { eventHooksToRemove.add(method); } } for (JavaScriptPluginMethod method: eventHooksToRemove) { System.out.println(" Event " + event + " (" + method.getPlugin().getName() + ")"); count++; events.get(event).remove(method); } } // Filters List<NativeRegExp> filtersToRemove = new LinkedList<NativeRegExp>(); for (NativeRegExp filter: filters.keySet()) { if (filters.get(filter).getPlugin() == pluginObj) { filtersToRemove.add(filter); } } for (NativeRegExp filter: filtersToRemove) { System.out.println(" Filter " + filter + " (" + filters.get(filter).getPlugin().getName() + ")"); count++; filters.remove(filter); } // Generics List<String> genericsToRemove = new LinkedList<String>(); for (String generic: generics.keySet()) { if (generics.get(generic).getPlugin() == pluginObj) { genericsToRemove.add(generic); } } for (String generic: genericsToRemove) { System.out.println(" Generic " + generic); count++; generics.remove(generic); } // Intervals if (intervals.get(lname) != null) { System.out.println(" Interval " + lname); count++; intervals.remove(lname); } plugins.remove(lname); System.out.println("Done (" + count + " items removed)."); } synchronized List<String> getCommands(String pluginName) { JavaScriptPlugin pluginObj = plugins.get(pluginName.toLowerCase()); List<String> rv = new LinkedList<String>(); for (String command: commands.keySet()) { if (commands.get(command).getPlugin() == pluginObj) { rv.add(command); } } return rv; } synchronized JavaScriptPluginMethod getCommand(String commandName) { return commands.get(commandName.toLowerCase()); } synchronized List<JavaScriptPluginMethod> getEvent(String eventName) { Object event = events.get(eventName.toLowerCase()); if (event == null) { return null; } LinkedList<JavaScriptPluginMethod> list = (LinkedList<JavaScriptPluginMethod>)event; return (List<JavaScriptPluginMethod>)list.clone(); } synchronized List<JavaScriptPluginMethod> getFilter(String message) { List<JavaScriptPluginMethod> rv = new LinkedList<JavaScriptPluginMethod>(); Iterator<NativeRegExp> regexps = filters.keySet().iterator(); while (regexps.hasNext()) { NativeRegExp regexp = regexps.next(); JavaScriptPluginMethod method = filters.get(regexp); JavaScriptPlugin plugin = method.getPlugin(); Scriptable scope = plugin.getScope(); Object[] args = { message }; Context cx = Context.enter(); try { Object ret = regexp.call(cx, scope, null, args); if (ret != null) { rv.add(method); } } finally { cx.exit(); } } return rv; } synchronized JavaScriptPluginExport getGeneric(String genericName) { return generics.get(genericName.toLowerCase()); } synchronized JavaScriptPluginMethod getInterval(String pluginName) { return intervals.get(pluginName.toLowerCase()); } } class JavaScriptPluginExport { private JavaScriptPlugin plugin; private String name; public JavaScriptPluginExport(JavaScriptPlugin plugin, String name) { this.plugin = plugin; this.name = name; } public JavaScriptPlugin getPlugin() { return plugin; } public String getName() { return name; } } /* * This class represents a single function in a plugin that can be called from * the outside. It keeps track of the plugin instance, the function name, and * the actual function so it can be identified and called with the right * scope (in JS, the call scope must be preserved, and this is handled by the * plugin object here). */ final class JavaScriptPluginMethod extends JavaScriptPluginExport { private Function function; public JavaScriptPluginMethod(JavaScriptPlugin plugin, String name, Function function) { super(plugin, name); this.function = function; } public Function getFunction() { return function; } } final class JavaScriptPluginProperty extends JavaScriptPluginExport { private Function function; public JavaScriptPluginProperty(JavaScriptPlugin plugin, String name) { super(plugin, name); } public Object getValue() throws ChoobException { String[] parts = getName().split("\\."); Scriptable obj = getPlugin().getInstance(); for (int i = 0; i < parts.length; i++) { obj = getObjectProp(obj, parts[i]); } return obj; } private static Scriptable getObjectProp(Scriptable obj, String prop) throws ChoobException { while (obj != null) { Object val = obj.get(prop, obj); if (val != Scriptable.NOT_FOUND) { if (!(val instanceof Scriptable)) { throw new ChoobException("Property '" + prop + "' is not valid!"); } return (Scriptable)val; } obj = obj.getPrototype(); } throw new ChoobException("No property called '" + prop + "' found."); } } final class JavaScriptPlugin { private String pluginName; private Scriptable scope; private Scriptable inst; public JavaScriptPlugin(JavaScriptPluginManager plugMan, String pluginName, String code, Modules mods, IRCInterface irc) throws ChoobException { this.pluginName = pluginName; Context cx = Context.enter(); try { scope = cx.initStandardObjects(); // Set up dump() and dumpln() functions. try { scope.put("dump", scope, new FunctionObject("dump", JavaScriptPluginManager.class.getMethod("dump", String.class), scope)); scope.put("dumpln", scope, new FunctionObject("dumpln", JavaScriptPluginManager.class.getMethod("dumpln", String.class), scope)); } catch(NoSuchMethodException e) { System.err.println("Method not found: " + e); // Ignore for now. } // Pull in script. Object result = cx.evaluateString(scope, code, pluginName, 1, null); Object ctor = scope.get(pluginName, scope); if (ctor == Scriptable.NOT_FOUND) { throw new ChoobException("Constructor property '" + pluginName + "' for JavaScript plugin not found."); } if (!(ctor instanceof Function)) { throw new ChoobException("Constructor property '" + pluginName + "' for JavaScript plugin is not a function."); } // Construct instance. final Object args[] = { mods, irc }; final Scriptable scopeF = scope; final String pluginNameF = pluginName; final Context cxF = cx; ProtectionDomain accessDomain = mods.security.getProtectionDomain(pluginName); AccessControlContext accessContext = new AccessControlContext(new ProtectionDomain[] { accessDomain }); try { inst = (Scriptable)AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws ChoobException { return cxF.newObject(scopeF, pluginNameF, args); } }, accessContext); } catch (PrivilegedActionException e) { throw (ChoobException)(e.getCause()); } System.out.println("JavaScriptPlugin ctor result: " + cx.toString(inst)); } catch (EvaluatorException e) { throw new ChoobException(e.details() + " at line " + e.lineNumber() + ", col " + e.columnNumber() + " of " + e.sourceName() + "."); } catch (RhinoException e) { throw new ChoobException(e.details() + " Line " + e.lineNumber() + ", col " + e.columnNumber() + " of " + e.sourceName() + "."); } finally { cx.exit(); } } public String getName() { return pluginName; } public Scriptable getScope() { return scope; } public Scriptable getInstance() { return inst; } }
package dr.evomodel.continuous; import dr.inference.model.*; import dr.math.distributions.NormalDistribution; import dr.util.DataTable; import dr.xml.*; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * @author Andrew Rambaut * @author Marc Suchard * @version $Id$ */ public class AntigenicTraitLikelihood extends AbstractModelLikelihood { public final static String ANTIGENIC_TRAIT_LIKELIHOOD = "antigenicTraitLikelihood"; public AntigenicTraitLikelihood( int mdsDimension, Parameter mdsPrecision, CompoundParameter tipTraitParameter, MatrixParameter virusLocationsParameter, MatrixParameter serumLocationsParameter, DataTable<double[]> dataTable) { super(ANTIGENIC_TRAIT_LIKELIHOOD); this.mdsDimension = mdsDimension; String[] virusNames = dataTable.getRowLabels(); String[] serumNames = dataTable.getColumnLabels(); // mdsDimension = virusLocationsParameter.getColumnDimension(); // the total number of viruses is the number of rows in the table int virusCount = dataTable.getRowCount(); // the number of sera is the number of columns int serumCount = dataTable.getColumnCount(); tipCount = virusCount; Map<String, Integer> tipNameMap = null; if (tipTraitParameter != null) { if (tipCount != tipTraitParameter.getNumberOfParameters()) { System.err.println("Tree has different number of tips than the number of viruses"); } // the tip -> virus map tipIndices = new int[tipCount]; tipNameMap = new HashMap<String, Integer>(); for (int i = 0; i < tipCount; i++) { String label = tipTraitParameter.getParameter(i).getParameterName(); tipNameMap.put(label, i); tipIndices[i] = -1; } } else { tipIndices = null; } // the virus -> tip map virusIndices = new int[virusCount]; // a set of vectors for each virus giving serum indices for which assay data is available measuredSerumIndices = new int[virusCount][]; // a compressed (no missing values) set of measured assay values between virus and sera. this.assayTable = new double[virusCount][]; int totalMeasurementCount = 0; for (int i = 0; i < virusCount; i++) { virusIndices[i] = -1; double[] dataRow = dataTable.getRow(i); if (tipIndices != null) { // if the virus is in the tree then add a entry to map tip to virus Integer tipIndex = tipNameMap.get(virusNames[i]); if (tipIndex != null) { tipIndices[tipIndex] = i; virusIndices[i] = tipIndex; } else { System.err.println("Virus, " + virusNames[i] + ", not found in tree"); } } int measuredCount = 0; for (int j = 0; j < serumCount; j++) { if (!Double.isNaN(dataRow[j]) && dataRow[j] > 0) { measuredCount ++; } } assayTable[i] = new double[measuredCount]; measuredSerumIndices[i] = new int[measuredCount]; int k = 0; for (int j = 0; j < serumCount; j++) { if (!Double.isNaN(dataRow[j]) && dataRow[j] > 0) { this.assayTable[i][k] = transform(dataRow[j]); // TODO Code review here, was dataRow[k] measuredSerumIndices[i][k] = j; k ++; } } totalMeasurementCount += measuredCount; } this.totalMeasurementCount = totalMeasurementCount; // a cache of virus to serum distances (serum indices given by array above). distances = new double[totalMeasurementCount]; storedDistances = new double[totalMeasurementCount]; // a cache of individual truncations // truncations = new double[totalMeasurementCount]; // storedTruncations = new double[totalMeasurementCount]; if (tipIndices != null) { for (int i = 0; i < tipCount; i++) { if (tipIndices[i] == -1) { String label = tipTraitParameter.getParameter(i).getParameterName(); System.err.println("Tree tip, " + label + ", not found in virus assay table"); } } } // add tipTraitParameter to enable store / restore this.tipTraitParameter = tipTraitParameter; if (tipTraitParameter != null) { addVariable(tipTraitParameter); } this.virusLocationsParameter = virusLocationsParameter; virusLocationsParameter.setColumnDimension(mdsDimension); virusLocationsParameter.setRowDimension(virusCount); addVariable(virusLocationsParameter); this.serumLocationsParameter = serumLocationsParameter; serumLocationsParameter.setColumnDimension(mdsDimension); serumLocationsParameter.setRowDimension(serumCount); addVariable(serumLocationsParameter); this.mdsParameter = mdsPrecision; addVariable(mdsPrecision); this.isLeftTruncated = true; // Re-normalize likelihood for strictly positive distances } private double transform(final double value) { // transform to log_2 return Math.log(value) / Math.log(2.0); } @Override protected void handleModelChangedEvent(Model model, Object object, int index) { } @Override protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) { // TODO Flag which cachedDistances or mdsPrecision need to be updated if (variable == virusLocationsParameter) { if (tipTraitParameter != null) { // the virus locations have changed so update the tipTraitParameter int k = 0; for (int i = 0; i < tipCount; i++) { if (tipIndices[i] != -1) { Parameter virusLoc = virusLocationsParameter.getParameter(tipIndices[i]); for (int j = 0; j < mdsDimension; j++) { tipTraitParameter.setParameterValue(k, virusLoc.getValue(j)); k++; } } else { k += mdsDimension; } } } distancesKnown = false; } else if (variable == serumLocationsParameter) { distancesKnown = false; } distancesKnown = false; truncationKnown = false; likelihoodKnown = false; } @Override protected void storeState() { // System.arraycopy(distances, 0, storedDistances, 0, distances.length); // System.arraycopy(truncations, 0, storedTruncations, 0, truncations.length); storedLogLikelihood = logLikelihood; storedTruncation = truncation; storedSumOfSquaredResiduals = sumOfSquaredResiduals; } @Override protected void restoreState() { // double[] tmp = storedDistances; // storedDistances = distances; // distances = tmp; // distancesKnown = true; // tmp = storedTruncations; // storedTruncations = truncations; // truncations = tmp; logLikelihood = storedLogLikelihood; likelihoodKnown = true; truncation = storedTruncation; truncationKnown = true; sumOfSquaredResiduals = storedSumOfSquaredResiduals; makeDirty(); } @Override protected void acceptState() { // do nothing } public void makeDirty() { distancesKnown = false; likelihoodKnown = false; truncationKnown = false; } public Model getModel() { return this; } public double getLogLikelihood() { // TODO Only recompute when not known: distances or mdsPrecision changed if (!likelihoodKnown) { if (!distancesKnown) { calculateDistances(); sumOfSquaredResiduals = calculateSumOfSquaredResiduals(); distancesKnown = true; } logLikelihood = computeLogLikelihood(); likelihoodKnown = true; } return logLikelihood; } // This function can be overwritten to implement other sampling densities, i.e. discrete ranks protected double computeLogLikelihood() { double precision = mdsParameter.getParameterValue(0); double logLikelihood = (totalMeasurementCount / 2) * Math.log(precision) - 0.5 * precision * sumOfSquaredResiduals; if (isLeftTruncated) { if (!truncationKnown) { truncation = calculateTruncation(precision); truncationKnown = true; } logLikelihood -= truncation; } return logLikelihood; } private double calculateTruncation(double precision) { double sum = 0.0; double sd = 1.0 / Math.sqrt(precision); int k = 0; for (int i = 0; i < assayTable.length; i++) { for (int j = 0; j < assayTable[i].length; j++) { double t = Math.log(NormalDistribution.cdf(distances[k], 0.0, sd)); // truncations[k] = t; sum += t; k++; } } return sum; } private double calculateSumOfSquaredResiduals() { double sum = 0.0; int k = 0; for (int i = 0; i < assayTable.length; i++) { for (int j = 0; j < assayTable[i].length; j++) { double residual = distances[k] - assayTable[i][j]; sum += residual * residual; k++; } } return sum; } private void calculateDistances() { int k = 0; for (int i = 0; i < assayTable.length; i++) { for (int j = 0; j < assayTable[i].length; j++) { distances[k] = calculateDistance(virusLocationsParameter.getParameter(i), serumLocationsParameter.getParameter(measuredSerumIndices[i][j])); k++; } } } private double calculateDistance(Parameter X, Parameter Y) { double sum = 0.0; for (int i = 0; i < mdsDimension; i++) { double difference = X.getParameterValue(i) - Y.getParameterValue(i); sum += difference * difference; } return Math.sqrt(sum); } // XMLObjectParser public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public final static String FILE_NAME = "fileName"; public final static String TIP_TRAIT = "tipTrait"; public final static String VIRUS_LOCATIONS = "virusLocations"; public final static String SERUM_LOCATIONS = "serumLocations"; public static final String MDS_DIMENSION = "mdsDimension"; public static final String MDS_PRECISION = "mdsPrecision"; public String getParserName() { return ANTIGENIC_TRAIT_LIKELIHOOD; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { String fileName = xo.getStringAttribute(FILE_NAME); DataTable<double[]> assayTable; try { assayTable = DataTable.Double.parse(new FileReader(fileName)); } catch (IOException e) { throw new XMLParseException("Unable to read assay data from file, " + fileName); } int mdsDimension = xo.getIntegerAttribute(MDS_DIMENSION); // This parameter needs to be linked to the one in the IntegratedMultivariateTreeLikelihood (I suggest that the parameter is created // here and then a reference passed to IMTL - which optionally takes the parameter of tip trait values, in which case it listens and // updates accordingly. CompoundParameter tipTraitParameter = null; if (xo.hasChildNamed(TIP_TRAIT)) { tipTraitParameter = (CompoundParameter) xo.getElementFirstChild(TIP_TRAIT); } MatrixParameter virusLocationsParameter = (MatrixParameter) xo.getElementFirstChild(VIRUS_LOCATIONS); MatrixParameter serumLocationsParameter = (MatrixParameter) xo.getElementFirstChild(SERUM_LOCATIONS); if (serumLocationsParameter.getColumnDimension() != virusLocationsParameter.getColumnDimension()) { throw new XMLParseException("Virus Locations parameter and Serum Locations parameter have different column dimensions"); } Parameter mdsPrecision = (Parameter) xo.getElementFirstChild(MDS_PRECISION); return new AntigenicTraitLikelihood(mdsDimension, mdsPrecision, tipTraitParameter, virusLocationsParameter, serumLocationsParameter, assayTable); }
package bisq.core.trade.protocol; import bisq.core.offer.Offer; import bisq.core.trade.Trade; import bisq.core.trade.TradeManager; import bisq.core.trade.messages.CounterCurrencyTransferStartedMessage; import bisq.core.trade.messages.DepositTxAndDelayedPayoutTxMessage; import bisq.core.trade.messages.TradeMessage; import bisq.network.p2p.AckMessage; import bisq.network.p2p.AckMessageSourceType; import bisq.network.p2p.DecryptedDirectMessageListener; import bisq.network.p2p.DecryptedMessageWithPubKey; import bisq.network.p2p.MailboxMessage; import bisq.network.p2p.NodeAddress; import bisq.network.p2p.SendMailboxMessageListener; import bisq.network.p2p.messaging.DecryptedMailboxListener; import bisq.common.Timer; import bisq.common.UserThread; import bisq.common.crypto.PubKeyRing; import bisq.common.proto.network.NetworkEnvelope; import bisq.common.taskrunner.Task; import java.security.PublicKey; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; @Slf4j public abstract class TradeProtocol implements DecryptedDirectMessageListener, DecryptedMailboxListener { protected final ProcessModel processModel; protected final Trade trade; private Timer timeoutTimer; // Constructor public TradeProtocol(Trade trade) { this.trade = trade; this.processModel = trade.getProcessModel(); } // API public void initialize(ProcessModelServiceProvider serviceProvider, TradeManager tradeManager, Offer offer) { processModel.applyTransient(serviceProvider, tradeManager, offer); onInitialized(); } protected void onInitialized() { if (!trade.isWithdrawn()) { processModel.getP2PService().addDecryptedDirectMessageListener(this); } // We delay a bit here as the trade gets updated from the wallet to update the trade // state (deposit confirmed) and that happens after our method is called. // TODO To fix that in a better way we would need to change the order of some routines // from the TradeManager, but as we are close to a release I dont want to risk a bigger // change and leave that for a later PR UserThread.runAfter(() -> { processModel.getP2PService().addDecryptedMailboxListener(this); processModel.getP2PService().getMailBoxMessages() .forEach(this::handleDecryptedMessageWithPubKey); }, 100, TimeUnit.MILLISECONDS); } public void onWithdrawCompleted() { cleanup(); } protected void onMailboxMessage(TradeMessage message, NodeAddress peerNodeAddress) { log.info("Received {} as MailboxMessage from {} with tradeId {} and uid {}", message.getClass().getSimpleName(), peerNodeAddress, message.getTradeId(), message.getUid()); } // DecryptedDirectMessageListener @Override public void onDirectMessage(DecryptedMessageWithPubKey message, NodeAddress peer) { NetworkEnvelope networkEnvelope = message.getNetworkEnvelope(); if (networkEnvelope instanceof TradeMessage && isMyMessage((TradeMessage) networkEnvelope) && isPubKeyValid(message)) { onTradeMessage((TradeMessage) networkEnvelope, peer); } else if (networkEnvelope instanceof AckMessage && isMyMessage((AckMessage) networkEnvelope) && isPubKeyValid(message)) { onAckMessage((AckMessage) networkEnvelope, peer); } } // DecryptedMailboxListener @Override public void onMailboxMessageAdded(DecryptedMessageWithPubKey message, NodeAddress peer) { handleDecryptedMessageWithPubKey(message, peer); } private void handleDecryptedMessageWithPubKey(DecryptedMessageWithPubKey decryptedMessageWithPubKey) { MailboxMessage mailboxMessage = (MailboxMessage) decryptedMessageWithPubKey.getNetworkEnvelope(); NodeAddress senderNodeAddress = mailboxMessage.getSenderNodeAddress(); handleDecryptedMessageWithPubKey(decryptedMessageWithPubKey, senderNodeAddress); } protected void handleDecryptedMessageWithPubKey(DecryptedMessageWithPubKey decryptedMessageWithPubKey, NodeAddress peer) { NetworkEnvelope networkEnvelope = decryptedMessageWithPubKey.getNetworkEnvelope(); if (networkEnvelope instanceof TradeMessage && isMyMessage((TradeMessage) networkEnvelope) && isPubKeyValid(decryptedMessageWithPubKey)) { TradeMessage tradeMessage = (TradeMessage) networkEnvelope; // We only remove here if we have already completed the trade. // Otherwise removal is done after successfully applied the task runner. if (trade.isWithdrawn()) { processModel.getP2PService().removeMailboxMsg(decryptedMessageWithPubKey); log.info("Remove {} from the P2P network.", tradeMessage.getClass().getSimpleName()); return; } onMailboxMessage(tradeMessage, peer); } else if (networkEnvelope instanceof AckMessage && isMyMessage((AckMessage) networkEnvelope) && isPubKeyValid(decryptedMessageWithPubKey)) { if (!trade.isWithdrawn()) { // We only apply the msg if we have not already completed the trade onAckMessage((AckMessage) networkEnvelope, peer); } // In any case we remove the msg processModel.getP2PService().removeMailboxMsg(decryptedMessageWithPubKey); log.info("Remove {} from the P2P network.", networkEnvelope.getClass().getSimpleName()); } } public void removeMailboxMessageAfterProcessing(TradeMessage tradeMessage) { if (tradeMessage instanceof MailboxMessage && processModel.getTradingPeer() != null && processModel.getTradingPeer().getPubKeyRing() != null && processModel.getTradingPeer().getPubKeyRing().getSignaturePubKey() != null) { PublicKey sigPubKey = processModel.getTradingPeer().getPubKeyRing().getSignaturePubKey(); // We reconstruct the DecryptedMessageWithPubKey from the message and the peers signature pubKey DecryptedMessageWithPubKey decryptedMessageWithPubKey = new DecryptedMessageWithPubKey(tradeMessage, sigPubKey); processModel.getP2PService().removeMailboxMsg(decryptedMessageWithPubKey); log.info("Remove {} from the P2P network.", tradeMessage.getClass().getSimpleName()); } } // Abstract protected abstract void onTradeMessage(TradeMessage message, NodeAddress peer); // FluentProtocol // We log an error if condition is not met and call the protocol error handler protected FluentProtocol expect(FluentProtocol.Condition condition) { return new FluentProtocol(this) .condition(condition) .resultHandler(result -> { if (!result.isValid()) { log.error(result.getInfo()); handleTaskRunnerFault(null, result.name(), result.getInfo()); } }); } // We execute only if condition is met but do not log an error. protected FluentProtocol given(FluentProtocol.Condition condition) { return new FluentProtocol(this) .condition(condition); } protected FluentProtocol.Condition phase(Trade.Phase expectedPhase) { return new FluentProtocol.Condition(trade).phase(expectedPhase); } protected FluentProtocol.Condition anyPhase(Trade.Phase... expectedPhases) { return new FluentProtocol.Condition(trade).anyPhase(expectedPhases); } @SafeVarargs public final FluentProtocol.Setup tasks(Class<? extends Task<Trade>>... tasks) { return new FluentProtocol.Setup(this, trade).tasks(tasks); } // ACK msg private void onAckMessage(AckMessage ackMessage, NodeAddress peer) { // We handle the ack for CounterCurrencyTransferStartedMessage and DepositTxAndDelayedPayoutTxMessage // as we support automatic re-send of the msg in case it was not ACKed after a certain time if (ackMessage.getSourceMsgClassName().equals(CounterCurrencyTransferStartedMessage.class.getSimpleName())) { processModel.setPaymentStartedAckMessage(ackMessage); } else if (ackMessage.getSourceMsgClassName().equals(DepositTxAndDelayedPayoutTxMessage.class.getSimpleName())) { processModel.setDepositTxSentAckMessage(ackMessage); } if (ackMessage.isSuccess()) { log.info("Received AckMessage for {} from {} with tradeId {} and uid {}", ackMessage.getSourceMsgClassName(), peer, trade.getId(), ackMessage.getSourceUid()); } else { log.warn("Received AckMessage with error state for {} from {} with tradeId {} and errorMessage={}", ackMessage.getSourceMsgClassName(), peer, trade.getId(), ackMessage.getErrorMessage()); } } protected void sendAckMessage(TradeMessage message, boolean result, @Nullable String errorMessage) { PubKeyRing peersPubKeyRing = processModel.getTradingPeer().getPubKeyRing(); if (peersPubKeyRing == null) { log.error("We cannot send the ACK message as peersPubKeyRing is null"); return; } String tradeId = message.getTradeId(); String sourceUid = message.getUid(); AckMessage ackMessage = new AckMessage(processModel.getMyNodeAddress(), AckMessageSourceType.TRADE_MESSAGE, message.getClass().getSimpleName(), sourceUid, tradeId, result, errorMessage); // If there was an error during offer verification, the tradingPeerNodeAddress of the trade might not be set yet. // We can find the peer's node address in the processModel's tempTradingPeerNodeAddress in that case. NodeAddress peer = trade.getTradingPeerNodeAddress() != null ? trade.getTradingPeerNodeAddress() : processModel.getTempTradingPeerNodeAddress(); log.info("Send AckMessage for {} to peer {}. tradeId={}, sourceUid={}", ackMessage.getSourceMsgClassName(), peer, tradeId, sourceUid); processModel.getP2PService().sendEncryptedMailboxMessage( peer, peersPubKeyRing, ackMessage, new SendMailboxMessageListener() { @Override public void onArrived() { log.info("AckMessage for {} arrived at peer {}. tradeId={}, sourceUid={}", ackMessage.getSourceMsgClassName(), peer, tradeId, sourceUid); } @Override public void onStoredInMailbox() { log.info("AckMessage for {} stored in mailbox for peer {}. tradeId={}, sourceUid={}", ackMessage.getSourceMsgClassName(), peer, tradeId, sourceUid); } @Override public void onFault(String errorMessage) { log.error("AckMessage for {} failed. Peer {}. tradeId={}, sourceUid={}, errorMessage={}", ackMessage.getSourceMsgClassName(), peer, tradeId, sourceUid, errorMessage); } } ); } // Timeout protected void startTimeout(long timeoutSec) { stopTimeout(); timeoutTimer = UserThread.runAfter(() -> { log.error("Timeout reached. TradeID={}, state={}, timeoutSec={}", trade.getId(), trade.stateProperty().get(), timeoutSec); trade.setErrorMessage("Timeout reached. Protocol did not complete in " + timeoutSec + " sec."); processModel.getTradeManager().requestPersistence(); cleanup(); }, timeoutSec); } protected void stopTimeout() { if (timeoutTimer != null) { timeoutTimer.stop(); timeoutTimer = null; } } // Task runner protected void handleTaskRunnerSuccess(TradeMessage message) { handleTaskRunnerSuccess(message, message.getClass().getSimpleName()); } protected void handleTaskRunnerSuccess(FluentProtocol.Event event) { handleTaskRunnerSuccess(null, event.name()); } protected void handleTaskRunnerFault(TradeMessage message, String errorMessage) { handleTaskRunnerFault(message, message.getClass().getSimpleName(), errorMessage); } protected void handleTaskRunnerFault(FluentProtocol.Event event, String errorMessage) { handleTaskRunnerFault(null, event.name(), errorMessage); } // Validation private boolean isPubKeyValid(DecryptedMessageWithPubKey message) { // We can only validate the peers pubKey if we have it already. If we are the taker we get it from the offer // Otherwise it depends on the state of the trade protocol if we have received the peers pubKeyRing already. PubKeyRing peersPubKeyRing = processModel.getTradingPeer().getPubKeyRing(); boolean isValid = true; if (peersPubKeyRing != null && !message.getSignaturePubKey().equals(peersPubKeyRing.getSignaturePubKey())) { isValid = false; log.error("SignaturePubKey in message does not match the SignaturePubKey we have set for our trading peer."); } return isValid; } // Private private void handleTaskRunnerSuccess(@Nullable TradeMessage message, String source) { log.info("TaskRunner successfully completed. Triggered from {}, tradeId={}", source, trade.getId()); if (message != null) { sendAckMessage(message, true, null); // Once a taskRunner is completed we remove the mailbox message. To not remove it directly at the task // adds some resilience in case of minor errors, so after a restart the mailbox message can be applied // again. removeMailboxMessageAfterProcessing(message); } } void handleTaskRunnerFault(@Nullable TradeMessage message, String source, String errorMessage) { log.error("Task runner failed with error {}. Triggered from {}", errorMessage, source); if (message != null) { sendAckMessage(message, false, errorMessage); } cleanup(); } private boolean isMyMessage(TradeMessage message) { return message.getTradeId().equals(trade.getId()); } private boolean isMyMessage(AckMessage ackMessage) { return ackMessage.getSourceType() == AckMessageSourceType.TRADE_MESSAGE && ackMessage.getSourceId().equals(trade.getId()); } private void cleanup() { stopTimeout(); // We do not remove the decryptedDirectMessageListener as in case of not critical failures we want allow to receive // follow-up messages still } }
package dr.evomodel.tree; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.tree.TreeTrait; import dr.evolution.util.Taxon; import dr.evomodel.branchratemodel.BranchRateModel; import dr.math.MathUtils; import dr.inference.operators.MCMCOperator; import dr.inference.operators.OperatorFailedException; import dr.inference.operators.SimpleMCMCOperator; import dr.inference.model.Statistic; import dr.inference.model.StatisticList; import dr.inference.model.AbstractModel; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; /** * @author Andrew Rambaut * @version $Id$ */ public class EmpiricalTreeDistributionModel extends TreeModel /* implements BranchRateModel */ { public EmpiricalTreeDistributionModel(final Tree[] trees, final String rateAttributeName) { super(EMPIRICAL_TREE_DISTRIBUTION_MODEL); this.rateAttributeName = rateAttributeName; this.trees = trees; drawTreeIndex(); addStatistic(new Statistic.Abstract("Current Tree") { public int getDimension() { return 1; } public double getStatisticValue(int dim) { return currentTreeIndex; } }); } protected void storeState() { storedTreeIndex = currentTreeIndex; } protected void restoreState() { currentTreeIndex = storedTreeIndex; } protected void acceptState() { } public void drawTreeIndex() { // System.err.print("Drawing new tree, (old tree = " + currentTreeIndex); currentTreeIndex = MathUtils.nextInt(trees.length); // Force computation of node heights now rather than later in the evaluation // where multithreading may get conflicts. trees[currentTreeIndex].getNodeHeight(trees[currentTreeIndex].getRoot()); // System.err.println(") new tree = " + currentTreeIndex); fireModelChanged(new TreeModel.TreeChangedEvent()); } public NodeRef getRoot() { return trees[currentTreeIndex].getRoot(); } public int getNodeCount() { return trees[currentTreeIndex].getNodeCount(); } public NodeRef getNode(final int i) { return trees[currentTreeIndex].getNode(i); } public NodeRef getInternalNode(final int i) { return trees[currentTreeIndex].getInternalNode(i); } public NodeRef getExternalNode(final int i) { return trees[currentTreeIndex].getExternalNode(i); } public int getExternalNodeCount() { return trees[currentTreeIndex].getExternalNodeCount(); } public int getInternalNodeCount() { return trees[currentTreeIndex].getInternalNodeCount(); } public Taxon getNodeTaxon(final NodeRef node) { return trees[currentTreeIndex].getNodeTaxon(node); } public boolean hasNodeHeights() { return trees[currentTreeIndex].hasNodeHeights(); } public double getNodeHeight(final NodeRef node) { return trees[currentTreeIndex].getNodeHeight(node); } public boolean hasBranchLengths() { return trees[currentTreeIndex].hasBranchLengths(); } public double getBranchLength(final NodeRef node) { return trees[currentTreeIndex].getBranchLength(node); } public double getNodeRate(final NodeRef node) { return trees[currentTreeIndex].getNodeRate(node); } public Object getNodeAttribute(final NodeRef node, final String name) { return trees[currentTreeIndex].getNodeAttribute(node, name); } public Iterator getNodeAttributeNames(final NodeRef node) { return trees[currentTreeIndex].getNodeAttributeNames(node); } public boolean isExternal(final NodeRef node) { return trees[currentTreeIndex].isExternal(node); } public boolean isRoot(final NodeRef node) { return trees[currentTreeIndex].isRoot(node); } public int getChildCount(final NodeRef node) { return trees[currentTreeIndex].getChildCount(node); } public NodeRef getChild(final NodeRef node, final int j) { return trees[currentTreeIndex].getChild(node, j); } public NodeRef getParent(final NodeRef node) { return trees[currentTreeIndex].getParent(node); } public Tree getCopy() { return trees[currentTreeIndex].getCopy(); } public int getTaxonCount() { return trees[currentTreeIndex].getTaxonCount(); } public Taxon getTaxon(final int taxonIndex) { return trees[currentTreeIndex].getTaxon(taxonIndex); } public String getTaxonId(final int taxonIndex) { return trees[currentTreeIndex].getTaxonId(taxonIndex); } public int getTaxonIndex(final String id) { return trees[currentTreeIndex].getTaxonIndex(id); } public int getTaxonIndex(final Taxon taxon) { return trees[currentTreeIndex].getTaxonIndex(taxon); } public List<Taxon> asList() { return trees[currentTreeIndex].asList(); } public Object getTaxonAttribute(final int taxonIndex, final String name) { return trees[currentTreeIndex].getTaxonAttribute(taxonIndex, name); } public Iterator<Taxon> iterator() { return trees[currentTreeIndex].iterator(); } public Type getUnits() { return trees[currentTreeIndex].getUnits(); } public void setUnits(final Type units) { trees[currentTreeIndex].setUnits(units); } public void setAttribute(final String name, final Object value) { trees[currentTreeIndex].setAttribute(name, value); } public Object getAttribute(final String name) { return trees[currentTreeIndex].getAttribute(name); } public Iterator<String> getAttributeNames() { return trees[currentTreeIndex].getAttributeNames(); } /* @Override public double getBranchRate(Tree tree, NodeRef node) { if (rateAttributeName != null) { assert(tree == trees[currentTreeIndex]); Object value = tree.getNodeAttribute(node, rateAttributeName); return Double.parseDouble((String)value); } else { return 1.0; } } @Override public String getTraitName() { return rateAttributeName; } @Override public Intent getIntent() { return Intent.BRANCH; } @Override public Class getTraitClass() { return Double.class; } @Override public Double getTrait(Tree tree, NodeRef node) { return getBranchRate(tree, node); } @Override public String getTraitString(Tree tree, NodeRef node) { return getTrait(tree, node).toString(); } @Override public boolean getLoggable() { return true; } @Override public TreeTrait[] getTreeTraits() { return new TreeTrait[] { this }; } @Override public TreeTrait getTreeTrait(String key) { return this; } */ public static final String EMPIRICAL_TREE_DISTRIBUTION_MODEL = "empiricalTreeDistributionModel"; private final Tree[] trees; private int currentTreeIndex; private int storedTreeIndex; private final String rateAttributeName; }
package com.redhat.ceylon.compiler.js; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.ceylon.CeylonUtils; import com.redhat.ceylon.cmr.impl.ShaSigner; import com.redhat.ceylon.common.Constants; import com.redhat.ceylon.common.FileUtil; import com.redhat.ceylon.compiler.js.util.JsIdentifierNames; import com.redhat.ceylon.compiler.js.util.JsJULLogger; import com.redhat.ceylon.compiler.js.util.JsOutput; import com.redhat.ceylon.compiler.js.util.Options; import com.redhat.ceylon.compiler.loader.MetamodelVisitor; import com.redhat.ceylon.compiler.loader.ModelEncoder; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.model.typechecker.model.Module; /** A simple program that takes the main JS module file and replaces #include markers with the contents of other files. * * @author Enrique Zamudio */ public class Stitcher { private static TypeCheckerBuilder langmodtc; private static Path tmpDir; public static final File clSrcDir = new File("../ceylon.language/src/ceylon/language/"); public static final File LANGMOD_JS_SRC = new File("../ceylon.language/runtime-js"); public static final File LANGMOD_JS_SRC2 = new File("../ceylon.language/runtime-js/ceylon/language"); private static JsIdentifierNames names; private static Module mod; private static final HashSet<File> compiledFiles = new HashSet<>(256); private static int compileLanguageModule(final String line, final JsOutput writer) throws IOException { File clsrcTmpDir = Files.createTempDirectory(tmpDir, "clsrc").toFile(); final File tmpout = new File(clsrcTmpDir, Constants.DEFAULT_MODULE_DIR); tmpout.mkdir(); final Options opts = new Options().addRepo("build/runtime").comment(false).optimize(true) .outRepo(tmpout.getAbsolutePath()).modulify(false).minify(true); //Typecheck the whole language module if (langmodtc == null) { langmodtc = new TypeCheckerBuilder().addSrcDirectory(clSrcDir.getParentFile().getParentFile()) .addSrcDirectory(LANGMOD_JS_SRC) .encoding("UTF-8"); langmodtc.setRepositoryManager(CeylonUtils.repoManager().systemRepo(opts.getSystemRepo()) .userRepos(opts.getRepos()).outRepo(opts.getOutRepo()).buildManager()); } final File mod2 = new File(LANGMOD_JS_SRC2, "module.ceylon"); if (!mod2.exists()) { try (FileWriter w2 = new FileWriter(mod2); FileReader r2 = new FileReader(new File(clSrcDir, "module.ceylon"))) { char[] c = new char[512]; int r = r2.read(c); while (r != -1) { w2.write(c, 0, r); r = r2.read(c); } mod2.deleteOnExit(); } finally { } } final TypeChecker tc = langmodtc.getTypeChecker(); tc.process(); if (tc.getErrors() > 0) { return 1; } //Compile these files final List<File> includes = new ArrayList<File>(); for (String filename : line.split(",")) { filename = filename.trim(); final boolean isJsSrc = filename.endsWith(".js"); final boolean isDir = filename.endsWith("/"); final boolean exclude = filename.charAt(0)=='-'; if (exclude) { filename = filename.substring(1); } final File src = ".".equals(filename) ? clSrcDir : new File(isJsSrc ? LANGMOD_JS_SRC : clSrcDir, isJsSrc || isDir ? filename : String.format("%s.ceylon", filename)); if (src.exists() && src.isFile() && src.canRead()) { if (exclude) { System.out.println("EXCLUDING " + src); compiledFiles.add(src); } else if (!compiledFiles.contains(src)) { includes.add(src); compiledFiles.add(src); } } else if (src.exists() && src.isDirectory()) { for (File sub : src.listFiles()) { if (!compiledFiles.contains(sub)) { includes.add(sub); compiledFiles.add(sub); } } } else { final File src2 = new File(LANGMOD_JS_SRC2, isDir ? filename : String.format("%s.ceylon", filename)); if (src2.exists() && src2.isFile() && src2.canRead()) { if (exclude) { System.out.println("EXCLUDING " + src); compiledFiles.add(src2); } else if (!compiledFiles.contains(src2)) { includes.add(src2); compiledFiles.add(src2); } } else if (src2.exists() && src2.isDirectory()) { for (File sub : src2.listFiles()) { if (!compiledFiles.contains(sub)) { includes.add(sub); compiledFiles.add(sub); } } } else { throw new IllegalArgumentException("Invalid Ceylon language module source " + src + " or " + src2); } } } if (includes.isEmpty()) { return 0; } //Compile only the files specified in the line //Set this before typechecking to share some decls that otherwise would be private JsCompiler.compilingLanguageModule=true; JsCompiler jsc = new JsCompiler(tc, opts).stopOnErrors(false); jsc.setSourceFiles(includes); jsc.generate(); if (names == null) { names = jsc.getNames(); } JsCompiler.compilingLanguageModule=false; File compsrc = new File(tmpout, "delete/me/delete-me.js"); if (compsrc.exists() && compsrc.isFile() && compsrc.canRead()) { try { writer.outputFile(compsrc); } finally { compsrc.delete(); } } else { System.out.println("Can't find generated js for language module in " + compsrc.getAbsolutePath()); return 1; } return 0; } private static int encodeModel(final File moduleFile) throws IOException { final String name = moduleFile.getName(); final File file = new File(moduleFile.getParentFile(), name.substring(0,name.length()-3)+ArtifactContext.JS_MODEL); System.out.println("Generating language module compile-time model in JSON..."); TypeCheckerBuilder tcb = new TypeCheckerBuilder().usageWarnings(false); tcb.addSrcDirectory(clSrcDir.getParentFile().getParentFile()); TypeChecker tc = tcb.getTypeChecker(); tc.process(); MetamodelVisitor mmg = null; final ErrorVisitor errVisitor = new ErrorVisitor(); for (PhasedUnit pu : tc.getPhasedUnits().getPhasedUnits()) { if (errVisitor.hasErrors(pu.getCompilationUnit())) { System.out.println("whoa, errors in the language module " + pu.getCompilationUnit().getLocation()); return 1; } if (mmg == null) { mmg = new MetamodelVisitor(pu.getPackage().getModule()); } pu.getCompilationUnit().visit(mmg); } mod = tc.getPhasedUnits().getPhasedUnits().get(0).getPackage().getModule(); try (FileWriter writer = new FileWriter(file)) { JsCompiler.beginWrapper(writer); writer.write("ex$.$CCMM$="); ModelEncoder.encodeModel(mmg.getModel(), writer); writer.write(";\n"); final JsOutput jsout = new JsOutput(mod, "UTF-8") { @Override public Writer getWriter() throws IOException { return writer; } }; jsout.outputFile(new File(LANGMOD_JS_SRC, "MODEL.js")); JsCompiler.endWrapper(writer); } finally { ShaSigner.sign(file, new JsJULLogger(), true); } return 0; } private static int stitch(File infile, final JsOutput writer) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(infile), "UTF-8")); try { String line = null; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { if (line.startsWith("COMPILE ")) { final String sourceFiles = line.substring(8); System.out.println("Compiling language module sources: " + sourceFiles); int exitCode = compileLanguageModule(sourceFiles, writer); if (exitCode != 0) { return exitCode; } } } } } finally { if (reader != null) reader.close(); } return 0; } public static void main(String[] args) throws IOException { if (args.length < 2) { System.err.println("This program requires 2 arguments to run:"); System.err.println("1. The path to the master file (the one with the list of files to compile)"); System.err.println("2. The path of the resulting JS file"); System.exit(1); return; } int exitCode = 0; tmpDir = Files.createTempDirectory("ceylon-jsstitcher-"); try { File infile = new File(args[0]); if (infile.exists() && infile.isFile() && infile.canRead()) { File outfile = new File(args[1]); if (!outfile.getParentFile().exists()) { outfile.getParentFile().mkdirs(); } exitCode = encodeModel(outfile); if (exitCode == 0) { final int p0 = args[1].indexOf(".language-"); final String version = args[1].substring(p0+10,args[1].length()-3); try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8")) { final JsOutput jsout = new JsOutput(mod, "UTF-8") { @Override public Writer getWriter() throws IOException { return writer; } }; //CommonJS wrapper JsCompiler.beginWrapper(writer); //Model jsout.out("var _CTM$;function $CCMM$(){if (_CTM$===undefined)_CTM$=require('", "ceylon/language/", version, "/ceylon.language-", version, "-model", "').$CCMM$;return _CTM$;}\nex$.$CCMM$=$CCMM$;"); //Compile all the listed files exitCode = stitch(infile, jsout); //Unshared declarations if (names != null) { jsout.publishUnsharedDeclarations(names); } //Close the commonJS wrapper JsCompiler.endWrapper(writer); } finally { ShaSigner.sign(outfile, new JsJULLogger(), true); } } } else { System.err.println("Input file is invalid: " + infile); exitCode = 2; } } finally { FileUtil.deleteQuietly(tmpDir.toFile()); } if (exitCode != 0) { System.exit(exitCode); } } }
package com.sandbox.runtime; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.sandbox.runtime.converters.HttpServletConverter; import com.sandbox.runtime.js.converters.HTTPRequestConverter; import com.sandbox.runtime.js.services.RuntimeService; import com.sandbox.runtime.models.Cache; import com.sandbox.runtime.models.Error; import com.sandbox.runtime.models.HTTPRequest; import com.sandbox.runtime.models.HttpRuntimeRequest; import com.sandbox.runtime.models.HttpRuntimeResponse; import com.sandbox.runtime.models.MatchedRouteDetails; import com.sandbox.runtime.models.RoutingTable; import com.sandbox.runtime.services.CommandLineProcessor; import com.sandbox.runtime.utils.FormatUtils; import com.sandbox.runtime.utils.MapUtils; import org.apache.cxf.jaxrs.model.URITemplate; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.UUID; @Component @Lazy public class HttpRequestHandler extends AbstractHandler { @Autowired ApplicationContext context; @Autowired ObjectMapper mapper; @Autowired MapUtils mapUtils; @Autowired FormatUtils formatUtils; @Autowired Cache cache; @Autowired CommandLineProcessor commandLine; @Autowired private HttpServletConverter servletConverter; @Autowired private HTTPRequestConverter serviceConverter; private static Logger logger = LoggerFactory.getLogger(HttpRequestHandler.class); @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); //defaulted String sandboxId = "1"; String sandboxName = "name"; try { long startedRequest = System.currentTimeMillis(); String requestId = UUID.randomUUID().toString(); //convert incoming request to InstanceHttpRequest HttpRuntimeRequest runtimeRequest = servletConverter.httpServletToInstanceHttpRequest(request); //get a runtime service instance RuntimeService runtimeService = context.getBean(RuntimeService.class); //create and lookup routing table RoutingTable routingTable = cache.getRoutingTableForSandboxId(sandboxId); if(routingTable == null) { routingTable = runtimeService.handleRoutingTableRequest(sandboxId); cache.setRoutingTableForSandboxId(sandboxId, routingTable); } MatchedRouteDetails routeMatch = findMatchedRoute(runtimeRequest, routingTable); //if no route match for given request, then log message and send error response. if(routeMatch == null){ logger.warn("** Error processing request for {} {} - Invalid route", runtimeRequest.getMethod(), runtimeRequest.getPath() == null ? request.getRequestURI() : runtimeRequest.getPath()); response.setStatus(500); response.setHeader("Content-Type","application/json"); response.getWriter().write(convertExceptionMessageToResponse("Invalid route")); return; } //log request with route logRequest(runtimeRequest, routeMatch, requestId); //run request HTTPRequest httpRequest = serviceConverter.fromInstanceHttpRequest(runtimeService.getSandboxScriptEngine().getEngine(), runtimeRequest); HttpRuntimeResponse runtimeResponse = null; if("options".equalsIgnoreCase(httpRequest.getMethod())){ //if options request, send back CORS headers runtimeResponse = new HttpRuntimeResponse("", 200, new HashMap<>(), new ArrayList<>()); runtimeResponse.getHeaders().put("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); runtimeResponse.getHeaders().put("Access-Control-Allow-Origin", httpRequest.getHeaders().getOrDefault("Origin", "*")); runtimeResponse.getHeaders().put("Access-Control-Allow-Headers", httpRequest.getHeaders().getOrDefault("Access-Control-Request-Headers", "Content-Type")); runtimeResponse.getHeaders().put("Access-Control-Allow-Credentials", "true"); }else{ //otherwise process normally runtimeResponse = runtimeService.handleRequest(sandboxId, sandboxId, httpRequest); } runtimeResponse.setDurationMillis(System.currentTimeMillis() - startedRequest); logConsole(runtimeService); logResponse(runtimeResponse, requestId); //set response data back onto servlet response mapResponse(runtimeResponse, response); } catch (Exception e) { logger.error("Error processing request", e); //write out error as json response.setStatus(500); response.setHeader("Content-Type","application/json"); response.getWriter().write(convertExceptionToResponse(e)); } } private void logRequest(HttpRuntimeRequest request, MatchedRouteDetails matchedRouteDetails, String requestId){ String matchedRouteDescription = "No matching route"; if(matchedRouteDetails != null) matchedRouteDescription = "Matched route '" + matchedRouteDetails.getPath() + "'"; String bodyDescription = "No body found"; if(StringUtils.hasLength(request.getBody())) { String truncatedBody = renderBody(request.getBody(), request.getHeaders()); bodyDescription = "Body: '" + truncatedBody + "' (" + truncatedBody.length() + " bytes)"; } logger.info("\n>> HTTP {} {} ({})\n" + ">> Headers: {}\n" + ">> {}", request.getMethod(), request.getRawUrl(), matchedRouteDescription, getSafe(request.getHeaders(), new HashMap<>()), bodyDescription); } private void logConsole(RuntimeService service){ for (String logItem : service.getConsole()._getMessages()){ String trimmedLogItem = logItem.trim(); if(trimmedLogItem.endsWith("\n")) trimmedLogItem = trimmedLogItem.substring(0, trimmedLogItem.length()-2); logger.info(trimmedLogItem); } } private void logResponse(HttpRuntimeResponse response, String requestId){ //then response String bodyDescription = "No body found"; if(StringUtils.hasLength(response.getBody())) { String truncatedBody = renderBody(response.getBody(), response.getHeaders()); bodyDescription = "Body: '" + truncatedBody + "'"; } logger.info("<< Status: {} (took {}ms)\n" + "<< Headers: {}\n" + "<< {}", response.getStatusCode(), response.getDurationMillis(), getSafe(response.getHeaders(), new HashMap<>()), bodyDescription); } private String renderBody(String body, Map<String, String> headers){ if(commandLine.isVerboseLogging()){ if(formatUtils.isXml(headers)) return formatUtils.formatXml(body); return body; }else{ body = body.replace('\n',' '); if(body.length() > 150){ return body.substring(0,150)+"..."; }else{ return body; } } } private <T> T getSafe(T obj, T defaultValue){ if(obj == null) return defaultValue; return obj; } //gets the matching route (if any) out of the routing table private MatchedRouteDetails findMatchedRoute(HttpRuntimeRequest request, RoutingTable table) throws Exception { MatchedRouteDetails match = table.findMatch(request.getMethod(), request.getUrl(), request.getHeaders()); if(match == null) return null; Map<String, String> flattenedPathParams = mapUtils.flattenMultiValue(match.getPathParams(), URITemplate.FINAL_MATCH_GROUP); request.setPath(match.getPath()); request.setParams(flattenedPathParams); return match; } //wraps the exception message to mimic the standard sandbox proxy response private String convertExceptionMessageToResponse(String message){ ObjectNode errorWrapper = mapper.createObjectNode(); ObjectNode error = mapper.convertValue(new Error(message), ObjectNode.class); errorWrapper.put("errors", mapper.convertValue(Arrays.asList(error), ArrayNode.class)); return errorWrapper.toString(); } private String convertExceptionToResponse(Exception e){ return convertExceptionMessageToResponse(e.getMessage()); } //map a non-exception response, could be success or error private void mapResponse(HttpRuntimeResponse runtimeResponse, HttpServletResponse response) throws Exception { //status if (runtimeResponse.getStatusCode() <= 0) { response.setStatus(200); } else { response.setStatus(runtimeResponse.getStatusCode()); } //headers if (runtimeResponse.getHeaders() != null) { for (String key : runtimeResponse.getHeaders().keySet()) { response.setHeader(key, runtimeResponse.getHeaders().get(key)); } } //cookies if (runtimeResponse.getCookies() != null) { for (String[] cookie : runtimeResponse.getCookies()) { response.addHeader("Set-Cookie", cookie[0] + "=" + cookie[1]); } } if(runtimeResponse.isError()){ //write out the error response.setContentType("application/json"); response.getWriter().append(mapper.writeValueAsString(runtimeResponse.getError())); }else{ //write out the body response.getWriter().append(runtimeResponse.getBody()); } } }
package com.hazelcast.core; import org.junit.After; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Map; import java.util.concurrent.*; public class TransactionTest { @Test @Ignore public void testMapPutSimple() { TransactionalMap txnMap = newTransactionalMapProxy("testMapPutSimple"); txnMap.begin(); txnMap.put("1", "value"); txnMap.commit(); } @Test public void testMapIterateEntries() { TransactionalMap txnMap = newTransactionalMapProxy("testMapIterateEntries"); txnMap.put("1", "value1"); assertEquals(1, txnMap.size()); txnMap.begin(); txnMap.put("2", "value2"); assertEquals(2, txnMap.size()); Set<Map.Entry> entries = txnMap.entrySet(); for (Map.Entry entry : entries) { if ("1".equals(entry.getKey())) { assertEquals("value1", entry.getValue()); } else if ("2".equals(entry.getKey())) { assertEquals("value2", entry.getValue()); } else throw new RuntimeException ("cannot contain another entry with key " + entry.getKey()); } txnMap.commit(); assertEquals(2, txnMap.size()); } @Test public void testMapIterateEntries2() { TransactionalMap txnMap = newTransactionalMapProxy("testMapIterateEntries2"); assertEquals(0, txnMap.size()); txnMap.begin(); txnMap.put("1", "value1"); txnMap.put("2", "value2"); assertEquals(2, txnMap.size()); Set<Map.Entry> entries = txnMap.entrySet(); for (Map.Entry entry : entries) { if ("1".equals(entry.getKey())) { assertEquals("value1", entry.getValue()); } else if ("2".equals(entry.getKey())) { assertEquals("value2", entry.getValue()); } else throw new RuntimeException ("cannot contain another entry with key " + entry.getKey()); } txnMap.commit(); assertEquals(2, txnMap.size()); } @Test public void testMapIterateEntries3() { TransactionalMap txnMap = newTransactionalMapProxy("testMapIterateEntries3"); txnMap.put("1", "value1"); assertEquals(1, txnMap.size()); txnMap.begin(); txnMap.put("1", "value2"); assertEquals(1, txnMap.size()); Set<Map.Entry> entries = txnMap.entrySet(); for (Map.Entry entry : entries) { if ("1".equals(entry.getKey())) { assertEquals("value2", entry.getValue()); } else throw new RuntimeException ("cannot contain another entry with key " + entry.getKey()); } txnMap.rollback(); assertEquals(1, txnMap.size()); entries = txnMap.entrySet(); for (Map.Entry entry : entries) { if ("1".equals(entry.getKey())) { assertEquals("value1", entry.getValue()); } else throw new RuntimeException ("cannot contain another entry with key " + entry.getKey()); } } @Test public void testMapPutCommitSize() { TransactionalMap txnMap = newTransactionalMapProxy("testMapPutCommitSize"); IMap imap = newMapProxy("testMapPutCommitSize"); txnMap.put("1", "item"); assertEquals(1, txnMap.size()); assertEquals(1, imap.size()); txnMap.begin(); txnMap.put(2, "newone"); assertEquals(2, txnMap.size()); assertEquals(1, imap.size()); txnMap.commit(); assertEquals(2, txnMap.size()); assertEquals(2, imap.size()); } @Test public void testMapPutRollbackSize() { TransactionalMap txnMap = newTransactionalMapProxy("testMapPutRollbackSize"); IMap imap = newMapProxy("testMapPutRollbackSize"); txnMap.put("1", "item"); assertEquals(1, txnMap.size()); assertEquals(1, imap.size()); txnMap.begin(); txnMap.put(2, "newone"); assertEquals(2, txnMap.size()); assertEquals(1, imap.size()); txnMap.rollback(); assertEquals(1, txnMap.size()); assertEquals(1, imap.size()); } @Test public void testSetAddWithTwoTxn() { Hazelcast.getSet("test").add("1"); Hazelcast.getSet("test").add("1"); TransactionalSet set = newTransactionalSetProxy("test"); TransactionalSet set2 = newTransactionalSetProxy("test"); assertEquals(1, set.size()); assertEquals(1, set2.size()); set.begin(); set.add("2"); assertEquals(2, set.size()); assertEquals(1, set2.size()); set.commit(); assertEquals(2, set.size()); assertEquals(2, set2.size()); set2.begin(); assertEquals(2, set.size()); assertEquals(2, set2.size()); set2.remove("1"); assertEquals(2, set.size()); assertEquals(1, set2.size()); set2.commit(); assertEquals(1, set.size()); assertEquals(1, set2.size()); } @Test public void testMapPutWithTwoTxn() { TransactionalMap txnMap = newTransactionalMapProxy("testMap"); TransactionalMap txnMap2 = newTransactionalMapProxy("testMap"); txnMap.begin(); txnMap.put("1", "value"); txnMap.commit(); txnMap2.begin(); txnMap2.put("1", "value2"); txnMap2.commit(); } @Test public void testMapRemoveWithTwoTxn() { Hazelcast.getMap("testMapRemoveWithTwoTxn").put("1", "value"); TransactionalMap txnMap = newTransactionalMapProxy("testMapRemoveWithTwoTxn"); TransactionalMap txnMap2 = newTransactionalMapProxy("testMapRemoveWithTwoTxn"); txnMap.begin(); txnMap.remove("1"); txnMap.commit(); txnMap2.begin(); txnMap2.remove("1"); txnMap2.commit(); } @Test public void testTryLock() { Hazelcast.getMap("testTryLock").put("1", "value"); TransactionalMap txnMap = newTransactionalMapProxy("testTryLock"); TransactionalMap txnMap2 = newTransactionalMapProxy("testTryLock"); txnMap.lock("1"); long start = System.currentTimeMillis(); assertFalse(txnMap2.tryLock("1", 2, TimeUnit.SECONDS)); long end = System.currentTimeMillis(); long took = (end - start); assertTrue((took > 1000) ? (took < 4000) : false); assertFalse(txnMap2.tryLock("1")); txnMap.unlock("1"); assertTrue(txnMap2.tryLock("1", 2, TimeUnit.SECONDS)); } @Test public void testMapRemoveRollback() { Hazelcast.getMap("testMapRemoveRollback").put("1", "value"); TransactionalMap txnMap = newTransactionalMapProxy("testMapRemoveRollback"); TransactionalMap txnMap2 = newTransactionalMapProxy("testMapRemoveRollback"); txnMap.begin(); assertEquals(1, txnMap.size()); txnMap.remove("1"); assertEquals(0, txnMap.size()); assertEquals(1, txnMap2.size()); txnMap.rollback(); assertEquals(1, txnMap.size()); assertEquals(1, txnMap2.size()); txnMap2.begin(); txnMap2.remove("1"); txnMap2.commit(); assertEquals(0, txnMap.size()); assertEquals(0, txnMap2.size()); } @Test public void testMapRemoveWithTwoTxn2() { TransactionalMap txnMap = newTransactionalMapProxy("testMapRemoveWithTwoTxn2"); TransactionalMap txnMap2 = newTransactionalMapProxy("testMapRemoveWithTwoTxn2"); txnMap.begin(); txnMap.remove("1"); txnMap.commit(); txnMap2.begin(); txnMap2.remove("1"); txnMap2.commit(); } @Test public void testMapRemoveWithTwoTxn3() { TransactionalMap txnMap = newTransactionalMapProxy("testMapRemoveWithTwoTxn3"); TransactionalMap txnMap2 = newTransactionalMapProxy("testMapRemoveWithTwoTxn3"); txnMap.put("1", "value1"); assertEquals(1, txnMap.size()); assertEquals(1, txnMap2.size()); txnMap.begin(); txnMap.remove("1"); assertEquals(0, txnMap.size()); assertEquals(1, txnMap2.size()); txnMap.commit(); assertEquals(0, txnMap.size()); assertEquals(0, txnMap2.size()); txnMap.put("1", "value1"); assertEquals(1, txnMap.size()); assertEquals(1, txnMap2.size()); txnMap2.begin(); txnMap2.remove("1"); assertEquals(1, txnMap.size()); assertEquals(0, txnMap2.size()); txnMap2.commit(); assertEquals(0, txnMap.size()); assertEquals(0, txnMap2.size()); } @Test public void testQueueOfferCommitSize() { TransactionalQueue txnq = newTransactionalQueueProxy("testQueueOfferCommitSize"); TransactionalQueue txnq2 = newTransactionalQueueProxy("testQueueOfferCommitSize"); txnq.begin(); txnq.offer("item"); assertEquals(1, txnq.size()); assertEquals(0, txnq2.size()); txnq.commit(); assertEquals(1, txnq.size()); assertEquals(1, txnq2.size()); } @Test public void testQueueOfferRollbackSize() { TransactionalQueue txnq = newTransactionalQueueProxy("testQueueOfferRollbackSize"); TransactionalQueue txnq2 = newTransactionalQueueProxy("testQueueOfferRollbackSize"); txnq.begin(); txnq.offer("item"); assertEquals(1, txnq.size()); assertEquals(0, txnq2.size()); txnq.rollback(); assertEquals(0, txnq.size()); assertEquals(0, txnq2.size()); } @Test public void testQueueOfferCommitIterator() { TransactionalQueue txnq = newTransactionalQueueProxy("testQueueOfferCommitIterator"); TransactionalQueue txnq2 = newTransactionalQueueProxy("testQueueOfferCommitIterator"); assertEquals(0, txnq.size()); assertEquals(0, txnq2.size()); txnq.begin(); txnq.offer("item"); Iterator it = txnq.iterator(); int size = 0; while (it.hasNext()) { assertNotNull(it.next()); size++; } assertEquals(1, size); it = txnq2.iterator(); size = 0; while (it.hasNext()) { assertNotNull(it.next()); size++; } assertEquals(0, size); txnq.commit(); it = txnq.iterator(); size = 0; while (it.hasNext()) { assertNotNull(it.next()); size++; } assertEquals(1, size); it = txnq2.iterator(); size = 0; while (it.hasNext()) { assertNotNull(it.next()); size++; } assertEquals(1, size); assertEquals(1, txnq.size()); assertEquals(1, txnq2.size()); } @Test public void testQueueOfferCommitIterator2() { TransactionalQueue txnq = newTransactionalQueueProxy("testQueueOfferCommitIterator2"); TransactionalQueue txnq2 = newTransactionalQueueProxy("testQueueOfferCommitIterator2"); txnq.offer("item0"); assertEquals(1, txnq.size()); assertEquals(1, txnq2.size()); txnq.begin(); txnq.offer("item"); Iterator it = txnq.iterator(); int size = 0; while (it.hasNext()) { assertNotNull(it.next()); size++; } assertEquals(2, size); it = txnq2.iterator(); size = 0; while (it.hasNext()) { assertNotNull(it.next()); size++; } assertEquals(1, size); txnq.commit(); it = txnq.iterator(); size = 0; while (it.hasNext()) { assertNotNull(it.next()); size++; } assertEquals(2, size); it = txnq2.iterator(); size = 0; while (it.hasNext()) { assertNotNull(it.next()); size++; } assertEquals(2, size); assertEquals(2, txnq.size()); assertEquals(2, txnq2.size()); } @Test public void testQueueOfferRollbackIterator2() { TransactionalQueue txnq = newTransactionalQueueProxy("testQueueOfferRollbackIterator2"); TransactionalQueue txnq2 = newTransactionalQueueProxy("testQueueOfferRollbackIterator2"); txnq.offer("item0"); assertEquals(1, txnq.size()); assertEquals(1, txnq2.size()); txnq.begin(); txnq.offer("item"); Iterator it = txnq.iterator(); int size = 0; while (it.hasNext()) { assertNotNull(it.next()); size++; } assertEquals(2, size); it = txnq2.iterator(); size = 0; while (it.hasNext()) { assertNotNull(it.next()); size++; } assertEquals(1, size); txnq.rollback(); it = txnq.iterator(); size = 0; while (it.hasNext()) { assertNotNull(it.next()); size++; } assertEquals(1, size); it = txnq2.iterator(); size = 0; while (it.hasNext()) { assertNotNull(it.next()); size++; } assertEquals(1, size); assertEquals(1, txnq.size()); assertEquals(1, txnq2.size()); } @Test public void testQueuePollCommitSize() { TransactionalQueue txnq = newTransactionalQueueProxy("testQueuePollCommitSize"); TransactionalQueue txnq2 = newTransactionalQueueProxy("testQueuePollCommitSize"); txnq.offer("item1"); txnq.offer("item2"); assertEquals(2, txnq.size()); assertEquals(2, txnq2.size()); txnq.begin(); assertEquals("item1", txnq.poll()); assertEquals(1, txnq.size()); assertEquals(1, txnq2.size()); txnq.commit(); assertEquals(1, txnq.size()); assertEquals(1, txnq2.size()); } @Test public void testQueuePollRollbackSize() { TransactionalQueue txnq = newTransactionalQueueProxy("testQueuePollRollbackSize"); TransactionalQueue txnq2 = newTransactionalQueueProxy("testQueuePollRollbackSize"); txnq.offer("item1"); txnq.offer("item2"); assertEquals(2, txnq.size()); assertEquals(2, txnq2.size()); txnq.begin(); assertEquals("item1", txnq.poll()); assertEquals(1, txnq.size()); assertEquals(1, txnq2.size()); txnq.rollback(); assertEquals(2, txnq.size()); assertEquals(2, txnq2.size()); assertEquals("item2", txnq2.poll()); assertEquals("item1", txnq2.poll()); } @After public void cleanUp() { Iterator<Instance> it = mapsUsed.iterator(); while (it.hasNext()) { Instance instance = it.next(); instance.destroy(); } mapsUsed.clear(); } List<Instance> mapsUsed = new CopyOnWriteArrayList<Instance>(); TransactionalMap newTransactionalMapProxy(String name) { IMap imap = Hazelcast.getMap(name); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class[] interfaces = new Class[]{TransactionalMap.class}; Object proxy = Proxy.newProxyInstance(classLoader, interfaces, new ThreadBoundInvocationHandler(imap)); TransactionalMap txnalMap = (TransactionalMap) proxy; mapsUsed.add(txnalMap); return txnalMap; } TransactionalQueue newTransactionalQueueProxy(String name) { IQueue q = Hazelcast.getQueue(name); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class[] interfaces = new Class[]{TransactionalQueue.class}; Object proxy = Proxy.newProxyInstance(classLoader, interfaces, new ThreadBoundInvocationHandler(q)); TransactionalQueue txnalQ = (TransactionalQueue) proxy; mapsUsed.add(txnalQ); return txnalQ; } TransactionalSet newTransactionalSetProxy(String name) { ISet s = Hazelcast.getSet(name); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class[] interfaces = new Class[]{TransactionalSet.class}; Object proxy = Proxy.newProxyInstance(classLoader, interfaces, new ThreadBoundInvocationHandler(s)); TransactionalSet txnSet = (TransactionalSet) proxy; mapsUsed.add(txnSet); return txnSet; } IMap newMapProxy(String name) { IMap imap = Hazelcast.getMap(name); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class[] interfaces = new Class[]{IMap.class}; IMap proxy = (IMap) Proxy.newProxyInstance(classLoader, interfaces, new ThreadBoundInvocationHandler(imap)); mapsUsed.add(proxy); return proxy; } interface TransactionalMap extends IMap { void begin(); void commit(); void rollback(); } interface TransactionalQueue extends IQueue { void begin(); void commit(); void rollback(); } interface TransactionalSet extends ISet { void begin(); void commit(); void rollback(); } public static class ThreadBoundInvocationHandler implements InvocationHandler { final Object target; final ExecutorService es = Executors.newSingleThreadExecutor(); final static Object NULL_OBJECT = new Object(); public ThreadBoundInvocationHandler(Object target) { this.target = target; } public Object invoke(final Object o, final Method method, final Object[] objects) throws Throwable { final String name = method.getName(); final BlockingQueue resultQ = new ArrayBlockingQueue(1); if (name.equals("begin") || name.equals("commit") || name.equals("rollback")) { es.execute(new Runnable() { public void run() { try { Transaction txn = Hazelcast.getTransaction(); if (name.equals("begin")) { txn.begin(); } else if (name.equals("commit")) { txn.commit(); } else if (name.equals("rollback")) { txn.rollback(); } resultQ.put(NULL_OBJECT); } catch (Exception e) { try { resultQ.put(e); } catch (InterruptedException ignored) { } } } }); } else { es.execute(new Runnable() { public void run() { try { Object result = method.invoke(target, objects); resultQ.put((result == null) ? NULL_OBJECT : result); } catch (Exception e) { try { resultQ.put(e); } catch (InterruptedException ignored) { } } } }); } Object result = resultQ.poll(5, TimeUnit.SECONDS); if (result == null) throw new RuntimeException("Method [" + name + "] took more than 5 seconds!"); if (name.equals("destroy")) { es.shutdown(); } if (result instanceof Throwable) { throw ((Throwable) result); } return (result == NULL_OBJECT) ? null : result; } } }
package edu.usc.glidein.service.impl; import java.net.URL; import java.rmi.RemoteException; import javax.naming.NamingException; import org.apache.axis.MessageContext; import org.apache.axis.message.addressing.EndpointReferenceType; import org.globus.wsrf.ResourceContext; import org.globus.wsrf.ResourceKey; import org.globus.wsrf.container.ServiceHost; import org.globus.wsrf.utils.AddressingUtils; import edu.usc.glidein.stubs.types.Sites; import edu.usc.glidein.stubs.types.Site; public class SiteFactoryService { public EndpointReferenceType createSite(Site site) throws RemoteException { // Get resource home SiteResourceHome home = null; try { home = SiteResourceHome.getInstance(); } catch (NamingException ne) { throw new RemoteException("Unable to get SiteResourceHome", ne); } // Create resource ResourceKey key = home.create(site); // Create an endpoint reference for the new resource EndpointReferenceType epr = null; try { URL baseURL = ServiceHost.getBaseURL(); MessageContext mctx = MessageContext.getCurrentContext(); String svc = (String) mctx.getService().getOption("instance"); String instanceURI = baseURL.toString() + svc; epr = AddressingUtils.createEndpointReference(instanceURI, key); } catch (Exception e) { throw new RemoteException("Unable to create endpoint reference", e); } // Return the endpoint reference to the client return epr; } public Sites listSites(boolean longFormat) throws RemoteException { try { ResourceContext rctx = ResourceContext.getResourceContext(); SiteResourceHome home = (SiteResourceHome) rctx.getResourceHome(); Site[] sites = home.list(longFormat); return new Sites(sites); } catch (Exception e) { throw new RemoteException("Unable to list sites", e); } } }
package com.sandwell.JavaSimulation; import com.jaamsim.controllers.RenderManager; import com.jaamsim.events.ProcessTarget; import com.jaamsim.input.InputAgent; import com.jaamsim.input.ValueInput; import com.jaamsim.ui.EntityPallet; import com.jaamsim.ui.ExceptionBox; import com.jaamsim.ui.FrameBox; import com.jaamsim.units.TimeUnit; import com.sandwell.JavaSimulation3D.Clock; import com.sandwell.JavaSimulation3D.GUIFrame; /** * Class Simulation - Sandwell Discrete Event Simulation * <p> * Class structure defining essential simulation objects. Eventmanager is * instantiated to manage events generated in the simulation. Function prototypes * are defined which any simulation must define in order to run. */ public class Simulation extends Entity { @Keyword(description = "The initialization period for the simulation run. The model will " + "run for the initialization period and then clear the statistics " + "and execute for the specified run duration. The total length of the " + "simulation run will be the sum of Initialization and Duration.", example = "Simulation Initialization { 720 h }") protected final DoubleInput initializationTime; @Keyword(description = "Date at which the simulation run is started (yyyy-mm-dd). This " + "input has no effect on the simulation results unless the seasonality " + "factors vary from month to month.", example = "Simulation StartDate { 2011-01-01 }") protected final StringInput startDate; @Keyword(description = "Time at which the simulation run is started (hh:mm).", example = "Simulation StartTime { 2160 h }") private final ValueInput startTimeInput; @Keyword(description = "The duration of the simulation run in which all statistics will be recorded.", example = "Simulation Duration { 8760 h }") protected final DoubleInput runDuration; @Keyword(description = "The number of discrete time units in one hour.", example = "Simulation SimulationTimeScale { 4500 }") private final DoubleInput simTimeScaleInput; @Keyword(description = "If the value is TRUE, then the input report file will be printed after loading the " + "configuration file. The input report can always be generated when needed by selecting " + "\"Print Input Report\" under the File menu.", example = "Simulation PrintInputReport { TRUE }") private final BooleanInput printInputReport; @Keyword(description = "This is placeholder description text", example = "This is placeholder example text") private final BooleanInput traceEventsInput; @Keyword(description = "This is placeholder description text", example = "This is placeholder example text") private final BooleanInput verifyEventsInput; @Keyword(description = "This is placeholder description text", example = "This is placeholder example text") private final BooleanInput exitAtStop; @Keyword(description = "The real time speed up factor", example = "RunControl RealTimeFactor { 1200 }") private final IntegerInput realTimeFactor; public static final int DEFAULT_REAL_TIME_FACTOR = 10000; public static final int MIN_REAL_TIME_FACTOR = 1; public static final int MAX_REAL_TIME_FACTOR= 1000000; @Keyword(description = "A Boolean to turn on or off real time in the simulation run", example = "RunControl RealTime { TRUE }") private final BooleanInput realTime; protected double startTime; protected double endTime; private static String modelName = "JaamSim"; { runDuration = new DoubleInput( "Duration", "Key Inputs", 8760.0 ); runDuration.setValidRange( 1e-15d, Double.POSITIVE_INFINITY ); runDuration.setUnits( "h" ); this.addInput( runDuration, true, "RunDuration" ); initializationTime = new DoubleInput( "Initialization", "Key Inputs", 0.0 ); initializationTime.setValidRange( 0.0d, Double.POSITIVE_INFINITY ); initializationTime.setUnits( "h" ); this.addInput( initializationTime, true, "InitializationDuration" ); startDate = new StringInput("StartDate", "Key Inputs", null); this.addInput(startDate, true); startTimeInput = new ValueInput("StartTime", "Key Inputs", 0.0d); startTimeInput.setUnitType(TimeUnit.class); startTimeInput.setValidRange(0.0d, Double.POSITIVE_INFINITY); this.addInput(startTimeInput, true); exitAtStop = new BooleanInput( "ExitAtStop", "Key Inputs", false ); this.addInput( exitAtStop, true ); simTimeScaleInput = new DoubleInput( "SimulationTimeScale", "Key Inputs", 4000.0d ); simTimeScaleInput.setValidRange( 1e-15d, Double.POSITIVE_INFINITY ); this.addInput( simTimeScaleInput, true ); traceEventsInput = new BooleanInput( "TraceEvents", "Key Inputs", false ); this.addInput( traceEventsInput, false ); verifyEventsInput = new BooleanInput( "VerifyEvents", "Key Inputs", false ); this.addInput( verifyEventsInput, false ); printInputReport = new BooleanInput( "PrintInputReport", "Key Inputs", false ); this.addInput( printInputReport, true ); realTimeFactor = new IntegerInput("RealTimeFactor", "Key Inputs", DEFAULT_REAL_TIME_FACTOR); realTimeFactor.setValidRange(MIN_REAL_TIME_FACTOR, MAX_REAL_TIME_FACTOR); this.addInput(realTimeFactor, true); realTime = new BooleanInput("RealTime", "Key Inputs", false); this.addInput(realTime, true); } /** * Constructor for the Simulation * Protected makes this a 'singleton' class -- only one instance of it exists. is instantiated through 'getSimulation()' method. */ public Simulation() { // Create clock Clock.setStartDate(2000, 1, 1); // Initialize basic model information startTime = 0.0; endTime = 8760.0; } @Override public void validate() { super.validate(); if( startDate.getValue() != null && !Tester.isDate( startDate.getValue() ) ) { throw new InputErrorException("The value for Start Date must be a valid date."); } } @Override public void earlyInit() { super.earlyInit(); Process.setSimTimeScale(simTimeScaleInput.getValue()); if( startDate.getValue() != null ) { Clock.getStartingDateFromString( startDate.getValue() ); } double startTimeHours = startTimeInput.getValue() / 3600.0d; startTime = Clock.calcTimeForYear_Month_Day_Hour(1, Clock.getStartingMonth(), Clock.getStartingDay(), startTimeHours); endTime = this.getStartTime() + this.getInitializationTime() + this.getRunDuration(); } private static class EndAtTarget extends ProcessTarget { final Simulation sim; EndAtTarget(Simulation sim) { this.sim = sim; } @Override public String getDescription() { return sim.getInputName() + ".doEndAt"; } @Override public void process() { sim.doEndAt(); } } @Override public void startUp() { super.startUp(); double timeUntilEnd = this.getEndTime() - getCurrentTime(); scheduleProcess(timeUntilEnd, EventManager.PRIO_DEFAULT, new EndAtTarget(this)); } @Override public void updateForInput( Input<?> in ) { super.updateForInput( in ); if(in == realTimeFactor || in == realTime) { EventManager.rootManager.setExecuteRealTime(realTime.getValue(), realTimeFactor.getValue()); GUIFrame.instance().updateForRealTime(this.getRealTimeExecution(), this.getRealTimeFactor()); return; } if (in == printInputReport) { InputAgent.setPrintInputs(printInputReport.getValue()); return; } } public void clear() { EventManager.clear(); this.resetInputs(); // Create clock Clock.setStartDate(2000, 1, 1); // Initialize basic model information startTime = 0.0; endTime = 8760.0; // close warning/error trace file InputAgent.closeLogFile(); FrameBox.clear(); EntityPallet.clear(); RenderManager.clear(); // Kill all entities except simulation while(Entity.getAll().size() > 1) { Entity ent = Entity.getAll().get(Entity.getAll().size()-1); ent.kill(); } GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_LOADED); } /** * Initializes and starts the model * 1) Initializes EventManager to accept events. * 2) calls startModel() to allow the model to add its starting events to EventManager * 3) start EventManager processing events */ public void start() { EventManager.clear(); if( traceEventsInput.getValue() ) { EventTracer.traceAllEvents(traceEventsInput.getValue()); } else if( verifyEventsInput.getValue() ) { EventTracer.verifyAllEvents(verifyEventsInput.getValue()); } // Validate each entity based on inputs only for (int i = 0; i < Entity.getAll().size(); i++) { try { Entity.getAll().get(i).validate(); } catch (Throwable e) { InputAgent.doError(e); ExceptionBox.instance().setInputError(Entity.getAll().get(i), e); return; } } EventManager.rootManager.scheduleProcess(0, EventManager.PRIO_DEFAULT, new StartModelTarget(this)); Simulation.resume(); } public static final void resume() { EventManager.rootManager.resume(); GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_RUNNING); } /** * Requests the EventManager to stop processing events. */ public static final void pause() { EventManager.rootManager.pause(); GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_PAUSED); } /** * Requests the EventManager to stop processing events. */ public static final void stop() { EventManager.rootManager.pause(); GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_STOPPED); // kill all generated objects for (int i = 0; i < Entity.getAll().size();) { Entity ent = Entity.getAll().get(i); if (ent.testFlag(Entity.FLAG_GENERATED)) ent.kill(); else i++; } } private static class StartUpTarget extends ProcessTarget { final Entity ent; StartUpTarget(Entity ent) { this.ent = ent; } @Override public String getDescription() { return ent.getInputName() + ".startUp"; } @Override public void process() { ent.startUp(); } } private static class StartModelTarget extends ProcessTarget { final Simulation ent; StartModelTarget(Simulation sim) { this.ent = sim; } @Override public String getDescription() { return ent.getInputName() + ".startModel"; } @Override public void process() { ent.startModel(); } } /** * Called by Simulation to inform the model to begin simulation networks. Events should not be * added to the EventManager before startModel(); **/ public void startModel() { for (int i = 0; i < Entity.getAll().size(); i++) { Entity.getAll().get(i).earlyInit(); } if( this.getStartTime() > 0.0 ) { scheduleWait( this.getStartTime() ); } // Initialize each entity based on early initialization and start networks for (int i = 0; i < Entity.getAll().size(); i++) { Process.start(new StartUpTarget(Entity.getAll().get(i))); } } /** * Called at the end of the run */ public void doEndAt() { Simulation.pause(); for (int i = 0; i < Entity.getAll().size(); i++) { Entity.getAll().get(i).doEnd(); } System.out.println( "Made it to do end at" ); // close warning/error trace file InputAgent.closeLogFile(); if( this.getExitAtStop() ) { GUIFrame.shutdown(0); } Simulation.pause(); } /** * Returns the end time of the run. * @return double - the time the current run will stop */ public double getEndTime() { return endTime; } /** * Return the run duration for the run (not including intialization) */ public double getRunDuration() { return runDuration.getValue(); } /** * Returns the start time of the run. */ public double getStartTime() { return startTime; } /** * Return the initialization duration in hours */ public double getInitializationTime() { return initializationTime.getValue(); } /** returns whether the simulation is currently executing in real time execution mode */ public boolean getRealTimeExecution() { return realTime.getValue(); } /** retrieves the current value for speedup factor for real time execution mode */ public int getRealTimeFactor() { return realTimeFactor.getValue(); } public static void setModelName(String newModelName) { modelName = newModelName; } public static String getModelName() { return modelName; } public boolean getExitAtStop() { if (InputAgent.getBatch()) return true; return exitAtStop.getValue(); } }
package edu.wpi.first.wpilibj.team2903.subsystems; import edu.wpi.first.wpilibj.Jaguar; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.team2903.RobotMap; public class Drive extends Subsystem { public Jaguar leftFrontMotor1 = new Jaguar(RobotMap.leftFrontMotor1); public Jaguar leftFrontMotor2 = new Jaguar(RobotMap.leftFrontMotor2); public Jaguar rightFrontMotor1 = new Jaguar(RobotMap.rightFrontMotor1); public Jaguar rightFrontMotor2 = new Jaguar(RobotMap.rightFrontMotor2); public Jaguar leftBackMotor1 = new Jaguar(RobotMap.leftBackMotor1); public Jaguar leftBackMotor2 = new Jaguar(RobotMap.leftBackMotor2); public Jaguar rightBackMotor1 = new Jaguar(RobotMap.rightBackMotor1); public Jaguar rightBackMotor2 = new Jaguar(RobotMap.rightBackMotor2); public void initDefaultCommand() { // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } public void leftFrontMotors(double speed){ leftFrontMotor1.set(speed);//RIGHT FRONT MOTOR leftFrontMotor2.set(speed); } public void leftBackMotors(double speed){ leftBackMotor1.set(speed);//LEFT BACK MOTOR leftBackMotor2.set(speed); } public void rightFrontMotors(double speed){ rightFrontMotor1.set(speed);//RIGHT FRONT MOTOR rightFrontMotor2.set(speed); } public void rightBackMotors(double speed){ rightBackMotor1.set(speed);//RIGHT BACK MOTOR rightBackMotor2.set(speed); } public void drive(double Ch1, double Ch3, double Ch4){ leftFrontMotors(Ch3 + Ch1 + Ch4);//RIGHT FRONT MOTOR leftBackMotors(Ch3 + Ch1 - Ch4);//LEFT BACK MOTOR rightFrontMotors(Ch3 - Ch1 - Ch4);//RIGHT FRONT MOTOR rightBackMotors(Ch3 - Ch1 + Ch4);//RIGHT BACK MOTOR } }
import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.BufferedWriter; import java.io.FileWriter; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JRadioButton; import javax.swing.JTextField; public class settingsWindow extends JFrame { private static final long serialVersionUID = 1L; private static String windowsPath; private static String linuxPath; public settingsWindow() { windowsPath = "C:\\Users\\" + mainWindow.username + "\\Pictures\\Screenshots\\"; linuxPath = "//home//" + mainWindow.username + "//Pictures//Screenshots//"; try { mainWindow.loadInfo(); } catch (Exception e1) { e1.printStackTrace(); } final JPanel buttonPanel = new JPanel(); buttonPanel.setBounds(0,0,110,360); buttonPanel.setLayout(null); buttonPanel.requestFocus(); buttonPanel.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent arg0) { } public void keyReleased(KeyEvent arg0) { } public void keyTyped(KeyEvent arg0) { }}); final JPanel uploadPanel = new JPanel(); uploadPanel.setBounds(5+110+5,0,530,360); // uploadPanel.setBackground(Color.BLUE); uploadPanel.setLayout(null); final JPanel imgurPanel = new JPanel(); imgurPanel.setBounds(5+110+5,0,530,360); // imgurPanel.setBackground(Color.BLUE); imgurPanel.setLayout(null); final JPanel localPanel = new JPanel(); localPanel.setBounds(5+110+5,0,530,360); // localPanel.setBackground(Color.BLUE); localPanel.setLayout(null); localPanel.setVisible(false); customButton uploadSettings = new customButton(" FTP Settings", "ftp.png"); uploadSettings.setBounds(5, 5,100, 20); uploadSettings.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent arg0) { localPanel.setVisible(false); uploadPanel.setVisible(true); } public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { } public void mousePressed(MouseEvent arg0) { } public void mouseReleased(MouseEvent arg0) { } }); buttonPanel.add(uploadSettings); final customButton imgurSettings = new customButton(" Imgur Settings", "imgur.png"); imgurSettings.setBounds(5, 27, 100, 20); imgurSettings.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent arg0) { uploadPanel.setVisible(false); localPanel.setVisible(true); } public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { } public void mousePressed(MouseEvent arg0) { imgurSettings.setBackground(new Color(153, 204, 255)); } public void mouseReleased(MouseEvent arg0) { imgurSettings.setBackground(null); } }); buttonPanel.add(imgurSettings); final JRadioButton imgurBtn = new JRadioButton("Use Imgur"); imgurBtn.setActionCommand(""); try {imgurBtn.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} imgurBtn.setBounds(10,65,(int)imgurBtn.getPreferredSize().getWidth(),(int)imgurBtn.getPreferredSize().getHeight()); imgurBtn.setFocusPainted(false); if(mainWindow.isImgur) { imgurBtn.setSelected(true); } else { imgurBtn.setSelected(false); } JRadioButton ftpBtn = new JRadioButton("Use FTP"); ftpBtn.setActionCommand(""); try {ftpBtn.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} ftpBtn.setBounds(10,65+(int)imgurBtn.getPreferredSize().getHeight(),(int)ftpBtn.getPreferredSize().getWidth(),(int)ftpBtn.getPreferredSize().getHeight()); ftpBtn.setFocusPainted(false); if(mainWindow.isImgur) { ftpBtn.setSelected(false); } else { ftpBtn.setSelected(true); } ButtonGroup group = new ButtonGroup(); group.add(ftpBtn); group.add(imgurBtn); buttonPanel.add(ftpBtn); buttonPanel.add(imgurBtn); JLabel imgurLbl = new JLabel("<html><u>Imgur Settings</u></html>"); imgurLbl.setBounds(5,0,110,25); try {imgurLbl.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} imgurPanel.add(imgurLbl); JLabel uploadLbl = new JLabel("<html><u>Upload Settings</u></html>"); uploadLbl.setBounds(5,0,110,25); try {uploadLbl.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} uploadPanel.add(uploadLbl); JLabel hostLbl = new JLabel("Hostname: "); hostLbl.setBounds(5, 30, 275, 25); try {hostLbl.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} uploadPanel.add(hostLbl); JLabel userLbl = new JLabel("Username: "); userLbl.setBounds(5, 60, 275, 25); try {userLbl.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} uploadPanel.add(userLbl); JLabel passLbl = new JLabel("Password: "); passLbl.setBounds(5, 90, 275, 25); try {passLbl.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} uploadPanel.add(passLbl); JLabel uploadDirLbl = new JLabel("Upload dir: "); uploadDirLbl.setBounds(5, 120, 275, 25); try {uploadDirLbl.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} uploadPanel.add(uploadDirLbl); final JTextField hostname = new JTextField(mainWindow.hostStr); hostname.setBounds(70, 30, 180, 25); try {hostname.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} uploadPanel.add(hostname); final JTextField user = new JTextField(mainWindow.userStr); user.setBounds(70, 60, 180, 25); try {user.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} uploadPanel.add(user); final JTextField pass = new JPasswordField(mainWindow.passStr); pass.setBounds(70, 90, 180, 25); try {pass.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} uploadPanel.add(pass); final JTextField uploadDir = new JTextField(mainWindow.uploadDir); uploadDir.setBounds(70, 120, 180, 25); try {uploadDir.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} uploadPanel.add(uploadDir); JButton save = new JButton("Save"); save.setBounds(110, 150, 70, 25); save.setFocusable(false); try {save.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} save.setFocusPainted(false); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(imgurBtn.isSelected()) { mainWindow.isImgur = true; } else { mainWindow.isImgur = false; } mainWindow.hostStr = hostname.getText(); mainWindow.userStr = user.getText(); mainWindow.passStr = pass.getText(); mainWindow.uploadDir = uploadDir.getText(); try { saveInfo(); } catch (Exception e1) { e1.printStackTrace(); } dispose(); } }); uploadPanel.add(save); JButton cancel = new JButton("Cancel"); cancel.setBounds(181, 150, 70, 25); cancel.setFocusable(false); try {cancel.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} cancel.setFocusPainted(false); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); uploadPanel.add(cancel); /*JLabel localLbl = new JLabel("<html><u>Imgur Settings</u></html>"); localLbl.setBounds(5,0,110,25); try {localLbl.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} localPanel.add(localLbl); JLabel imgurUsrLbl = new JLabel("Imgur username: "); imgurUsrLbl.setBounds(5, 30, 275, 25); try {imgurUsrLbl.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} localPanel.add(imgurUsrLbl); final JTextField imgurUsr = new JTextField(); imgurUsr.setBounds(70, 30, 180, 25); localPanel.add(imgurUsr); JButton saveLocal = new JButton("Save"); saveLocal.setBounds(110, 60, 70, 25); saveLocal.setFocusable(false); try {saveLocal.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} saveLocal.setFocusPainted(false); saveLocal.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); localPanel.add(saveLocal); JButton cancelLocal = new JButton("Cancel"); cancelLocal.setBounds(181, 60, 70, 25); cancelLocal.setFocusable(false); try {cancelLocal.setFont(new customButton("","").defaultFont());} catch (Exception e2) {} cancelLocal.setFocusPainted(false); cancelLocal.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); localPanel.add(cancelLocal);*/ setTitle("ScreenSlice - Settings"); setSize(420-35,420/16*9-25); setLocationRelativeTo(null); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setIconImage(new ImageIcon(getClass().getResource("icon.png")).getImage()); setResizable(false); setVisible(true); add(uploadPanel); add(localPanel); add(buttonPanel); } public void saveInfo() throws Exception { String path = ""; if (System.getProperty("os.name").contains("Windows")) { path = windowsPath; } else { path = linuxPath; } BufferedWriter hostFile = new BufferedWriter(new FileWriter(path + "//ScreenSlice Files//" + "host.txt")); BufferedWriter userFile = new BufferedWriter(new FileWriter(path + "//ScreenSlice Files//" + "user.txt")); BufferedWriter passFile = new BufferedWriter(new FileWriter(path + "//ScreenSlice Files//" + "pass.txt")); BufferedWriter uploadDirFile = new BufferedWriter(new FileWriter(path + "//ScreenSlice Files//" + "uploadDir.txt")); hostFile.write(mainWindow.hostStr); userFile.write(mainWindow.userStr); passFile.write(mainWindow.passStr); uploadDirFile.write(mainWindow.uploadDir); if (hostFile != null || userFile != null || passFile != null || uploadDirFile != null) { hostFile.close(); userFile.close(); passFile.close(); uploadDirFile.close(); } } }
package com.sandwell.JavaSimulation3D; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Rectangle2D; import java.net.URL; import java.util.ArrayList; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.JWindow; import javax.swing.SpinnerNumberModel; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import com.jaamsim.controllers.RenderManager; import com.jaamsim.events.EventErrorListener; import com.jaamsim.events.EventManager; import com.jaamsim.events.EventTimeListener; import com.jaamsim.events.Process; import com.jaamsim.input.InputAgent; import com.jaamsim.math.Vec3d; import com.jaamsim.ui.AboutBox; import com.jaamsim.ui.EditBox; import com.jaamsim.ui.EntityPallet; import com.jaamsim.ui.FrameBox; import com.jaamsim.ui.LogBox; import com.jaamsim.ui.OutputBox; import com.jaamsim.ui.PropertyBox; import com.jaamsim.ui.View; import com.sandwell.JavaSimulation.Entity; import com.sandwell.JavaSimulation.ErrorException; import com.sandwell.JavaSimulation.FileEntity; import com.sandwell.JavaSimulation.Simulation; import com.sandwell.JavaSimulation.Tester; /** * The main window for a Graphical Simulation. It provides the controls for managing then * EventManager (run, pause, ...) and the graphics (zoom, pan, ...) */ public class GUIFrame extends JFrame implements EventTimeListener, EventErrorListener { private static GUIFrame instance; // global shutdown flag static private AtomicBoolean shuttingDown; private JMenu fileMenu; private JMenu viewMenu; private JMenu windowList; private JMenu optionMenu; private JCheckBoxMenuItem showPosition; private JCheckBoxMenuItem alwaysTop; //private JCheckBoxMenuItem tooltip; private JCheckBoxMenuItem graphicsDebug; private JMenuItem printInputItem; private JMenuItem saveConfigurationMenuItem; // "Save" private JLabel clockDisplay; private JLabel speedUpDisplay; private JLabel remainingDisplay; private JToggleButton controlRealTime; private JSpinner spinner; private JToggleButton controlStartResume; private JToggleButton controlStop; private JTextField pauseTime; private JLabel locatorPos; private JLabel locatorLabel; JButton toolButtonIsometric; JButton toolButtonXYPlane; JButton toolButtonUndo; JButton toolButtonRedo; private int lastValue = -1; private JProgressBar progressBar; private static Image iconImage; private static boolean SAFE_GRAPHICS; // Collection of default window parameters public static int COL1_WIDTH; public static int COL2_WIDTH; public static int COL3_WIDTH; public static int COL1_START; public static int COL2_START; public static int COL3_START; public static int HALF_TOP; public static int HALF_BOTTOM; public static int TOP_START; public static int BOTTOM_START; public static int LOWER_HEIGHT; public static int LOWER_START; public static int VIEW_HEIGHT; public static int VIEW_WIDTH; static final String infinitySign = "\u221e"; static { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { LogBox.logLine("Unable to change look and feel."); } try { URL file = GUIFrame.class.getResource("/resources/images/icon.png"); iconImage = Toolkit.getDefaultToolkit().getImage(file); } catch (Exception e) { LogBox.logLine("Unable to load icon file."); iconImage = null; } shuttingDown = new AtomicBoolean(false); } private GUIFrame() { super(); getContentPane().setLayout( new BorderLayout() ); setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ); this.addWindowListener(new CloseListener()); // Initialize the working environment initializeMenus(); initializeMainToolBars(); initializeStatusBar(); this.setIconImage(GUIFrame.getWindowIcon()); //Set window size and make visible pack(); setResizable( false ); controlStartResume.setSelected( false ); controlStartResume.setEnabled( false ); controlStop.setSelected( false ); controlStop.setEnabled( false ); setProgress( 0 ); ToolTipManager.sharedInstance().setLightWeightPopupEnabled( false ); JPopupMenu.setDefaultLightWeightPopupEnabled( false ); } public static synchronized GUIFrame instance() { if (instance == null) instance = new GUIFrame(); return instance; } private class CloseListener extends WindowAdapter implements ActionListener { @Override public void windowClosing(WindowEvent e) { GUIFrame.this.close(); } @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.close(); } } /** * Perform exit window duties */ void close() { // close warning/error trace file InputAgent.closeLogFile(); // check for unsaved changes if (InputAgent.isSessionEdited()) { int userOption = JOptionPane.showConfirmDialog( null, "Do you want to save the changes?", "Confirm Exit Without Saving", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE ); if (userOption == JOptionPane.YES_OPTION) { InputAgent.save(this); GUIFrame.shutdown(0); } else if (userOption == JOptionPane.NO_OPTION) { GUIFrame.shutdown(0); } } else { GUIFrame.shutdown(0); } } /** * Clears the simulation and user interface for a new run */ public void clear() { // Clear the simulation Simulation.clear(); FrameBox.clear(); EntityPallet.clear(); RenderManager.clear(); this.updateForSimulationState(GUIFrame.SIM_STATE_LOADED); FrameBox.timeUpdate(0); // Clear the title bar setTitle(Simulation.getModelName()); // Clear the status bar setProgress( 0 ); speedUpDisplay.setText(" remainingDisplay.setText(" locatorPos.setText( "(-, -, -)" ); // Read the autoload configuration file InputAgent.clear(); InputAgent.setRecordEdits(false); InputAgent.readResource("inputs/autoload.cfg"); } public void initializeMenus() { // Initialize main menus JMenuBar mainMenuBar = new JMenuBar(); // File menu creation fileMenu = new JMenu( "File" ); fileMenu.setMnemonic( 'F' ); fileMenu.setEnabled( false ); JMenuItem newMenuItem = new JMenuItem( "New" ); newMenuItem.setMnemonic( 'N' ); newMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { Simulation.pause(); // check for unsaved changes if (InputAgent.isSessionEdited()) { int userOption = JOptionPane.showConfirmDialog( null, "A new simulation will overwrite the existing simulation without saving changes.\n" + "Do you wish to continue with a new simulation?", "Confirm New Simulation", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); if(userOption == JOptionPane.NO_OPTION) { return; } } clear(); InputAgent.setRecordEdits(true); InputAgent.loadDefault(); displayWindows(false); } } ); fileMenu.add( newMenuItem ); JMenuItem configMenuItem = new JMenuItem( "Open..." ); configMenuItem.setMnemonic( 'O' ); configMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { Simulation.pause(); // check for unsaved changes if (InputAgent.isSessionEdited()) { int userOption = JOptionPane.showConfirmDialog( null, "Opening a simulation will overwrite the existing simulation without saving changes.\n" + "Do you wish to continue opening a simulation?", "Confirm Open", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); if (userOption == JOptionPane.NO_OPTION) { return; } } InputAgent.load(GUIFrame.this); } } ); fileMenu.add( configMenuItem ); saveConfigurationMenuItem = new JMenuItem( "Save" ); saveConfigurationMenuItem.setMnemonic( 'S' ); saveConfigurationMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.save(GUIFrame.this); } } ); fileMenu.add( saveConfigurationMenuItem ); JMenuItem saveConfigurationAsMenuItem = new JMenuItem( "Save As..." ); saveConfigurationAsMenuItem.setMnemonic( 'V' ); saveConfigurationAsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.saveAs(GUIFrame.this); } } ); fileMenu.add( saveConfigurationAsMenuItem ); printInputItem = new JMenuItem( "Print Input Report" ); printInputItem.setMnemonic( 'I' ); printInputItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.printInputFileKeywords(); } } ); fileMenu.add( printInputItem ); JMenuItem exitMenuItem = new JMenuItem( "Exit" ); exitMenuItem.setMnemonic( 'x' ); exitMenuItem.addActionListener(new CloseListener()); fileMenu.add( exitMenuItem ); mainMenuBar.add( fileMenu ); // End File menu creation // View menu creation viewMenu = new JMenu( "Tools" ); viewMenu.setMnemonic( 'T' ); JMenuItem showBasicToolsMenuItem = new JMenuItem( "Show Basic Tools" ); showBasicToolsMenuItem.setMnemonic( 'B' ); showBasicToolsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { EntityPallet.getInstance().setVisible(true); ObjectSelector.getInstance().setVisible(true); EditBox.getInstance().makeVisible(); OutputBox.getInstance().makeVisible(); FrameBox.setSelectedEntity(ObjectSelector.currentEntity); } } ); viewMenu.add( showBasicToolsMenuItem ); JMenuItem closeAllToolsMenuItem = new JMenuItem( "Close All Tools" ); closeAllToolsMenuItem.setMnemonic( 'C' ); closeAllToolsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { EntityPallet.getInstance().setVisible(false); ObjectSelector.getInstance().setVisible(false); EditBox.getInstance().setVisible(false); OutputBox.getInstance().setVisible(false); PropertyBox.getInstance().setVisible(false); } } ); viewMenu.add( closeAllToolsMenuItem ); JMenuItem objectPalletMenuItem = new JMenuItem( "Model Builder" ); objectPalletMenuItem.setMnemonic( 'O' ); objectPalletMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { EntityPallet.getInstance().setVisible(true); } } ); viewMenu.add( objectPalletMenuItem ); JMenuItem objectSelectorMenuItem = new JMenuItem( "Object Selector" ); objectSelectorMenuItem.setMnemonic( 'S' ); objectSelectorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ObjectSelector.getInstance().setVisible(true); } } ); viewMenu.add( objectSelectorMenuItem ); JMenuItem inputEditorMenuItem = new JMenuItem( "Input Editor" ); inputEditorMenuItem.setMnemonic( 'I' ); inputEditorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { EditBox.getInstance().makeVisible(); if(ObjectSelector.getInstance().isVisible()) FrameBox.setSelectedEntity(ObjectSelector.currentEntity); } } ); viewMenu.add( inputEditorMenuItem ); JMenuItem outputMenuItem = new JMenuItem( "Output Viewer" ); outputMenuItem.setMnemonic( 'U' ); outputMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { OutputBox.getInstance().makeVisible(); if(ObjectSelector.getInstance().isVisible()) FrameBox.setSelectedEntity(ObjectSelector.currentEntity); } } ); viewMenu.add( outputMenuItem ); JMenuItem propertiesMenuItem = new JMenuItem( "Property Viewer" ); propertiesMenuItem.setMnemonic( 'P' ); propertiesMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { PropertyBox.getInstance().makeVisible(); if(ObjectSelector.getInstance().isVisible()) FrameBox.setSelectedEntity(ObjectSelector.currentEntity); } } ); viewMenu.add( propertiesMenuItem ); JMenuItem logMenuItem = new JMenuItem( "Log Viewer" ); logMenuItem.setMnemonic( 'L' ); logMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { LogBox.getInstance().makeVisible(); } } ); viewMenu.add( logMenuItem ); mainMenuBar.add( viewMenu ); // End File menu creation // Window menu creation JMenu windowMenu = new NewRenderWindowMenu("Views"); windowMenu.setMnemonic( 'V' ); // Initialize list of windows windowList = new WindowMenu("Select Window"); windowList.setMnemonic( 'S' ); //windowMenu.add( windowList ); mainMenuBar.add( windowMenu ); // End window menu creation optionMenu = new JMenu( "Options" ); optionMenu.setMnemonic( 'O' ); mainMenuBar.add( optionMenu ); showPosition = new JCheckBoxMenuItem( "Show Position", true ); showPosition.setMnemonic( 'P' ); optionMenu.add( showPosition ); alwaysTop = new JCheckBoxMenuItem( "Always on top", false ); alwaysTop.setMnemonic( 'A' ); optionMenu.add( alwaysTop ); alwaysTop.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { if( GUIFrame.this.isAlwaysOnTop() ) { GUIFrame.this.setAlwaysOnTop( false ); } else { GUIFrame.this.setAlwaysOnTop( true ); } } } ); /*tooltip = new JCheckBoxMenuItem( "Tooltip", true ); tooltip.setMnemonic( 'L' ); optionMenu.add( tooltip ); tooltip.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { // TODO Needs to be implemented for the new Renderer } } );*/ graphicsDebug = new JCheckBoxMenuItem( "Graphics Debug Info", false ); graphicsDebug.setMnemonic( 'G' ); optionMenu.add( graphicsDebug ); graphicsDebug.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { RenderManager.setDebugInfo(graphicsDebug.getState()); } } ); showPosition.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { setShowPositionXY(); } } ); // Help menu creation JMenu helpMenu = new JMenu( "Help" ); helpMenu.setMnemonic( 'H' ); JMenuItem aboutMenu = new JMenuItem( "About" ); aboutMenu.setMnemonic( 'A' ); aboutMenu.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { AboutBox.instance().setVisible(true); } } ); helpMenu.add( aboutMenu ); mainMenuBar.add( helpMenu ); // End help menu creation // Add main menu to the window setJMenuBar( mainMenuBar ); } /** * Returns the pixel length of the string with specified font */ private static int getPixelWidthOfString_ForFont(String str, Font font) { FontMetrics metrics = new FontMetrics(font) {}; Rectangle2D bounds = metrics.getStringBounds(str, null); return (int)bounds.getWidth(); } public void initializeMainToolBars() { // Insets used in setting the toolbar components Insets noMargin = new Insets( 0, 0, 0, 0 ); Insets smallMargin = new Insets( 1, 1, 1, 1 ); // Initilize the main toolbar JToolBar mainToolBar = new JToolBar(); mainToolBar.setMargin( smallMargin ); mainToolBar.setFloatable(false); // Create Run Label and run control buttons controlStartResume = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/run.png"))); controlStartResume.setSelectedIcon( new ImageIcon(GUIFrame.class.getResource("/resources/images/pause.png"))); controlStartResume.setToolTipText( "Run" ); controlStartResume.setMargin( noMargin ); controlStartResume.setEnabled( false ); controlStartResume.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { JToggleButton startResume = (JToggleButton)event.getSource(); if(startResume.isSelected()) { GUIFrame.this.startSimulation(); } else { GUIFrame.this.pauseSimulation(); } } } ); controlStop = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/stop.png"))); controlStop.setToolTipText( "Stop" ); controlStop.setMargin( noMargin ); controlStop.setEnabled( false ); controlStop.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if( getSimState() == SIM_STATE_RUNNING ) { GUIFrame.this.pauseSimulation(); } int userOption = JOptionPane.showConfirmDialog( null, "WARNING: If you stop the run, it can only be re-started from time 0.\n" + "Do you really want to stop?", "Confirm Stop", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); // stop only if yes if (userOption == JOptionPane.YES_OPTION) { GUIFrame.this.stopSimulation(); FrameBox.timeUpdate(0); lastSimTimeHours = 0.0d; lastSystemTime = System.currentTimeMillis(); setSpeedUp(0.0d); } } } ); // Separators have 5 pixels before and after and the preferred height of controlStartResume button Dimension separatorDim = new Dimension(11, controlStartResume.getPreferredSize().height); // dimension for 5 pixels gaps Dimension gapDim = new Dimension(5, separatorDim.height); mainToolBar.add( controlStartResume ); mainToolBar.add(Box.createRigidArea(gapDim)); mainToolBar.add( controlStop ); mainToolBar.add(Box.createRigidArea(gapDim)); JLabel pauseAt = new JLabel( "Pause at:" ); mainToolBar.add(pauseAt); mainToolBar.add(Box.createRigidArea(gapDim)); pauseTime = new JTextField("2000-00-00") { @Override protected void processFocusEvent( FocusEvent fe ) { if ( fe.getID() == FocusEvent.FOCUS_GAINED ) { if(getText().equals(infinitySign)) { this.setHorizontalAlignment(JTextField.RIGHT); this.setText(""); } // select entire text string selectAll(); } else if (fe.getID() == FocusEvent.FOCUS_LOST) { if(getText().isEmpty()) { this.setText(infinitySign); this.setHorizontalAlignment(JTextField.CENTER); } } super.processFocusEvent( fe ); } }; // avoid height increase for pauseTime pauseTime.setMaximumSize(pauseTime.getPreferredSize()); // avoid stretching for puaseTime when focusing in and out pauseTime.setPreferredSize(pauseTime.getPreferredSize()); mainToolBar.add(pauseTime); pauseTime.setText(infinitySign); pauseTime.setHorizontalAlignment(JTextField.CENTER); SpinnerNumberModel numberModel = new SpinnerModel(Simulation.DEFAULT_REAL_TIME_FACTOR, Simulation.MIN_REAL_TIME_FACTOR, Simulation.MAX_REAL_TIME_FACTOR, 1); spinner = new JSpinner(numberModel); // make sure spinner TextField is no wider than 9 digits int diff = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().getPreferredSize().width - getPixelWidthOfString_ForFont("9", spinner.getFont()) * 9; Dimension dim = spinner.getPreferredSize(); dim.width -= diff; spinner.setMaximumSize(dim); spinner.addChangeListener(new SpeedFactorListener()); mainToolBar.addSeparator(separatorDim); controlRealTime = new JToggleButton( "Real Time" ); controlRealTime.setToolTipText( "Toggle Real Time" ); controlRealTime.setMargin( smallMargin ); controlRealTime.addActionListener(new RealTimeActionListener()); mainToolBar.add( controlRealTime ); mainToolBar.add(Box.createRigidArea(gapDim)); mainToolBar.add( spinner ); mainToolBar.addSeparator(separatorDim); // End creation of real-time label and menu // Create view control label and controls JLabel viewLabel = new JLabel( " View Control: " ); mainToolBar.add( viewLabel ); // add a button to show isometric view in windows toolButtonIsometric = new JButton( "Isometric" ); toolButtonIsometric.setToolTipText( "Set Isometric View" ); toolButtonIsometric.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (RenderManager.isGood()) RenderManager.inst().setIsometricView(); } } ); mainToolBar.add( toolButtonIsometric ); // add a button to show xy-plane view in windows toolButtonXYPlane = new JButton( "XY-Plane" ); toolButtonXYPlane.setToolTipText( "Set XY-Plane View" ); toolButtonXYPlane.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (RenderManager.isGood()) RenderManager.inst().setXYPlaneView(); } } ); mainToolBar.add( toolButtonXYPlane ); mainToolBar.addSeparator(separatorDim); // add a button to undo the last step ( viewer and window ) toolButtonUndo = new JButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/previous.png"))); toolButtonUndo.setToolTipText( "Previous view" ); toolButtonUndo.setEnabled( false ); toolButtonUndo.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { // Not implemented } } ); //mainToolBar.add( toolButtonUndo ); // add a button to redo the last step ( viewer and window ) toolButtonRedo = new JButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/next.png"))); toolButtonRedo.setToolTipText( "Next view" ); toolButtonRedo.setEnabled( false ); toolButtonRedo.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { // Not implemented } } ); //mainToolBar.add( toolButtonRedo ); //mainToolBar.addSeparator(separatorDim); // End creation of view control label and buttons // Add toolbar to the window getContentPane().add( mainToolBar, BorderLayout.NORTH ); } private static class WindowMenu extends JMenu implements MenuListener { WindowMenu(String text) { super(text); this.addMenuListener(this); } @Override public void menuCanceled(MenuEvent arg0) {} @Override public void menuDeselected(MenuEvent arg0) { this.removeAll(); } @Override public void menuSelected(MenuEvent arg0) { if (!RenderManager.isGood()) { return; } ArrayList<Integer> windowIDs = RenderManager.inst().getOpenWindowIDs(); for (int id : windowIDs) { String windowName = RenderManager.inst().getWindowName(id); this.add(new WindowSelector(id, windowName)); } } } private static class WindowSelector extends JMenuItem implements ActionListener { private final int windowID; WindowSelector(int windowID, String windowName) { this.windowID = windowID; this.setText(windowName); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { return; } RenderManager.inst().focusWindow(windowID); } } private static class NewRenderWindowMenu extends JMenu implements MenuListener { NewRenderWindowMenu(String text) { super(text); this.addMenuListener(this); } @Override public void menuSelected(MenuEvent e) { for (View view : View.getAll()) { this.add(new NewRenderWindowLauncher(view)); } this.addSeparator(); this.add(new ViewDefiner()); } @Override public void menuCanceled(MenuEvent arg0) { } @Override public void menuDeselected(MenuEvent arg0) { this.removeAll(); } } private static class NewRenderWindowLauncher extends JMenuItem implements ActionListener { private final View view; NewRenderWindowLauncher(View v) { view = v; this.setText(view.getName()); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { if (RenderManager.canInitialize()) { RenderManager.initialize(SAFE_GRAPHICS); } else { // A fatal error has occurred, don't try to initialize again return; } } RenderManager.inst().createWindow(view); } } private static class ViewDefiner extends JMenuItem implements ActionListener { ViewDefiner() {} { this.setText("Define new View"); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { if (RenderManager.canInitialize()) { RenderManager.initialize(SAFE_GRAPHICS); } else { // A fatal error has occurred, don't try to initialize again return; } } View tmp = InputAgent.defineEntityWithUniqueName(View.class, "View", true); RenderManager.inst().createWindow(tmp); FrameBox.setSelectedEntity(tmp); } } public void initializeStatusBar() { // Create the status bar JPanel statusBar = new JPanel(); statusBar.setBorder( BorderFactory.createLineBorder( Color.darkGray ) ); statusBar.setLayout( new FlowLayout( FlowLayout.LEFT, 10, 5 ) ); // Create the display clock and label JLabel clockLabel = new JLabel( "Simulation Time (hrs):" ); clockDisplay = new JLabel( " clockDisplay.setPreferredSize( new Dimension( 55, 16 ) ); clockDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); statusBar.add( clockLabel ); statusBar.add( clockDisplay ); //statusBar.addSeparator(); // Create the progress bar progressBar = new JProgressBar( 0, 100 ); progressBar.setValue( 0 ); progressBar.setStringPainted( true ); // Add the progress bar to the status bar statusBar.add( progressBar ); // Create a speed-up factor display JLabel speedUpLabel = new JLabel( "Speed Up:" ); speedUpDisplay = new JLabel( " speedUpDisplay.setPreferredSize( new Dimension( 60, 16 ) ); speedUpDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); statusBar.add( speedUpLabel ); statusBar.add( speedUpDisplay ); // Create a remaining run time display JLabel remainingLabel = new JLabel( "Time Remaining (mins):" ); remainingDisplay = new JLabel( " remainingDisplay.setPreferredSize( new Dimension( 40, 16 ) ); remainingDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); statusBar.add( remainingLabel ); statusBar.add( remainingDisplay ); locatorPos = new JLabel( "(-, -, -)" ); locatorPos.setPreferredSize( new Dimension( 140, 16 ) ); locatorPos.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); locatorLabel = new JLabel( "Pos: " ); statusBar.add( locatorLabel ); statusBar.add( locatorPos ); // Add the status bar to the window getContentPane().add( statusBar, BorderLayout.SOUTH ); } private long lastSystemTime = System.currentTimeMillis(); private double lastSimTimeHours = 0.0d; public void setClock(double simTime) { double clockContents = simTime / 3600.0d; clockDisplay.setText(String.format("%.2f", clockContents)); long cTime = System.currentTimeMillis(); double duration = Simulation.getRunDurationHours() + Simulation.getInitializationHours(); double timeElapsed = clockContents - Simulation.getStartHours(); int progress = (int)(timeElapsed * 100.0d / duration); this.setProgress(progress); if (cTime - lastSystemTime > 5000) { long elapsedMillis = cTime - lastSystemTime; double elapsedSimHours = timeElapsed - lastSimTimeHours; // Determine the speed-up factor double speedUp = (elapsedSimHours * 3600000.0d) / elapsedMillis; setSpeedUp(speedUp); double remainingSimTime = duration - timeElapsed; double remainingMinutes = (remainingSimTime * 60.0d) / speedUp; setRemaining(remainingMinutes); lastSystemTime = cTime; lastSimTimeHours = timeElapsed; } } public void setProgress( int val ) { if (lastValue == val) return; progressBar.setValue( val ); progressBar.repaint(25); lastValue = val; if (getSimState() >= SIM_STATE_CONFIGURED) { String title = String.format("%d%% %s - %s", val, Simulation.getModelName(), InputAgent.getRunName()); setTitle(title); } } public void setProgressText( String txt ) { progressBar.setString( txt ); } public void setSpeedUp( double val ) { speedUpDisplay.setText(String.format("%,.0f", val)); } public void setRemaining( double val ) { remainingDisplay.setText(String.format("%.1f", val)); } private void startSimulation() { // pause at a time double runToSecs = Double.POSITIVE_INFINITY; if(! pauseTime.getText().equalsIgnoreCase(infinitySign)) { try { if (Tester.isDate(pauseTime.getText())) { String[] str = pauseTime.getText().split("-"); if (str.length < 3) { throw new NumberFormatException ("Date string must be of form yyyy-mm-dd"); } int year = Integer.valueOf(str[0]).intValue(); int month = Integer.valueOf(str[1]).intValue(); int day = Integer.valueOf(str[2]).intValue(); double time = Clock.calcTimeForYear_Month_Day_Hour(year, month, day, 0.0); int startingYear = Clock.getStartingYear(); int startingMonth = Clock.getStartingMonth(); int startingDay = Clock.getStartingDay(); double startingTime = Clock.calcTimeForYear_Month_Day_Hour( startingYear, startingMonth, startingDay, 0.0); runToSecs = (time - startingTime) * 3600.0d; } else { runToSecs = Double.parseDouble(pauseTime.getText()) * 3600.0d; } } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(this, String.format( "Invalid time \n %s", pauseTime.getText()), "error", JOptionPane.ERROR_MESSAGE); // it is not running any more controlStartResume.setSelected(! controlStartResume.isSelected() ); return; } } if( getSimState() <= SIM_STATE_CONFIGURED ) { if (InputAgent.isSessionEdited()) { InputAgent.saveAs(this); } Simulation.start(); Simulation.resume(runToSecs); updateForSimulationState(GUIFrame.SIM_STATE_RUNNING); } else if( getSimState() == SIM_STATE_PAUSED ) { Simulation.resume(runToSecs); updateForSimulationState(GUIFrame.SIM_STATE_RUNNING); } else if( getSimState() == SIM_STATE_STOPPED ) { updateForSimulationState(SIM_STATE_CONFIGURED); Simulation.start(); Simulation.resume(runToSecs); updateForSimulationState(GUIFrame.SIM_STATE_RUNNING); } else throw new ErrorException( "Invalid Simulation State for Start/Resume" ); } private void pauseSimulation() { if( getSimState() == SIM_STATE_RUNNING ) Simulation.pause(); else throw new ErrorException( "Invalid Simulation State for pause" ); } private void stopSimulation() { if( getSimState() == SIM_STATE_RUNNING || getSimState() == SIM_STATE_PAUSED ) Simulation.stop(); else throw new ErrorException( "Invalid Simulation State for stop" ); } /** model was executed, but no configuration performed */ public static final int SIM_STATE_LOADED = 0; /** essential model elements created, no configuration performed */ public static final int SIM_STATE_UNCONFIGURED = 1; /** model has been configured, not started */ public static final int SIM_STATE_CONFIGURED = 2; /** model is presently executing events */ public static final int SIM_STATE_RUNNING = 3; /** model has run, but presently is paused */ public static final int SIM_STATE_PAUSED = 4; /** model has run, but presently is stopped */ public static final int SIM_STATE_STOPPED = 5; private int simState; public int getSimState() { return simState; } public void updateForSimulationState(int state) { simState = state; switch( getSimState() ) { case SIM_STATE_LOADED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setEnabled( false ); controlStop.setSelected( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( false ); break; case SIM_STATE_UNCONFIGURED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); controlStartResume.setEnabled( false ); controlStartResume.setSelected( false ); controlStop.setSelected( false ); controlStop.setEnabled( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( false ); showPosition.setState( true ); setShowPositionXY(); break; case SIM_STATE_CONFIGURED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( true ); remainingDisplay.setEnabled( true ); controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setSelected( false ); controlStop.setEnabled( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( true ); break; case SIM_STATE_RUNNING: controlStartResume.setEnabled( true ); controlStartResume.setSelected( true ); controlStartResume.setToolTipText( "Pause" ); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; case SIM_STATE_PAUSED: controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; case SIM_STATE_STOPPED: controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setEnabled( false ); controlStop.setSelected( false ); break; default: throw new ErrorException( "Unrecognized Graphics State" ); } fileMenu.setEnabled( true ); } /** * updates RealTime button and Spinner */ public void updateForRealTime(boolean executeRT, int factorRT) { controlRealTime.setSelected(executeRT); spinner.setValue(factorRT); } public static Image getWindowIcon() { return iconImage; } public void copyLocationToClipBoard(Vec3d pos) { String data = String.format("(%.3f, %.3f, %.3f)", pos.x, pos.y, pos.z); StringSelection stringSelection = new StringSelection(data); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents( stringSelection, null ); } public void showLocatorPosition(Vec3d pos) { // null indicates nothing to display if( pos == null ) { locatorPos.setText( "(-, -, -)" ); } else { if( showPosition.getState() ) { Locale loc = null; locatorPos.setText(String.format(loc, "(%.3f, %.3f, %.3f)", pos.x, pos.y, pos.z)); } } } public void setShowPositionXY() { boolean show = showPosition.getState(); showPosition.setState( show ); locatorLabel.setVisible( show ); locatorPos.setVisible( show ); locatorLabel.setText( "Pos: " ); locatorPos.setText( "(-, -, -)" ); } public void enableSave(boolean bool) { saveConfigurationMenuItem.setEnabled(bool); } private static void calcWindowDefaults() { Dimension guiSize = GUIFrame.instance().getSize(); Rectangle winSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); COL1_WIDTH = 220; COL2_WIDTH = Math.min(520, (winSize.width - COL1_WIDTH) / 2); COL3_WIDTH = Math.min(420, winSize.width - COL1_WIDTH - COL2_WIDTH); COL1_START = 0; COL2_START = COL1_START + COL1_WIDTH; COL3_START = COL2_START + COL2_WIDTH; HALF_TOP = (winSize.height - guiSize.height) / 2; HALF_BOTTOM = (winSize.height - guiSize.height - HALF_TOP); TOP_START = guiSize.height; BOTTOM_START = TOP_START + HALF_TOP; LOWER_HEIGHT = (winSize.height - guiSize.height) / 3; LOWER_START = winSize.height - LOWER_HEIGHT; VIEW_WIDTH = COL2_WIDTH + COL3_WIDTH; VIEW_HEIGHT = winSize.height - TOP_START - LOWER_HEIGHT; } /** * Displays the view windows and tools on startup. * * @param viewOnly - boolean that determines whether the tools are to be displayed. * TRUE - show just the view windows. * FALSE - show the view windows and the tools. */ public static void displayWindows(boolean viewOnly) { // Show the view windows specified in the configuration file for (View v : View.getAll()) { if (v.showOnStart()) RenderManager.inst().createWindow(v); } if (viewOnly) return; // Show the four basic tools EntityPallet.getInstance().setVisible(true); // Model Builder ObjectSelector.getInstance().setVisible(true); // Object Selector EditBox.getInstance().setVisible(true); // Input Editor OutputBox.getInstance().setVisible(true); // Output Viewer // Set the selected entity to the first view window if (View.getAll().size() > 0) FrameBox.setSelectedEntity(View.getAll().get(0)); } // MAIN public static void main( String args[] ) { // Process the input arguments and filter out directives ArrayList<String> configFiles = new ArrayList<String>(args.length); boolean batch = false; boolean minimize = false; boolean quiet = false; for (String each : args) { // Batch mode if (each.equalsIgnoreCase("-b") || each.equalsIgnoreCase("-batch")) { batch = true; continue; } // z-buffer offset if (each.equalsIgnoreCase("-z") || each.equalsIgnoreCase("-zbuffer")) { // Parse the option, but do nothing continue; } // Minimize model window if (each.equalsIgnoreCase("-m") || each.equalsIgnoreCase("-minimize")) { minimize = true; continue; } // Do not open default windows if (each.equalsIgnoreCase("-q") || each.equalsIgnoreCase("-quiet")) { quiet = true; continue; } if (each.equalsIgnoreCase("-sg") || each.equalsIgnoreCase("-safe_graphics")) { SAFE_GRAPHICS = true; continue; } // Not a program directive, add to list of config files configFiles.add(each); } // If not running in batch mode, create the splash screen JWindow splashScreen = null; if (!batch) { URL splashImage = GUIFrame.class.getResource("/resources/images/splashscreen.png"); ImageIcon imageIcon = new ImageIcon(splashImage); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int splashX = (screen.width - imageIcon.getIconWidth()) / 2; int splashY = (screen.height - imageIcon.getIconHeight()) / 2; // Set the window's bounds, centering the window splashScreen = new JWindow(); splashScreen.setAlwaysOnTop(true); splashScreen.setBounds(splashX, splashY, imageIcon.getIconWidth(), imageIcon.getIconHeight()); // Build the splash screen splashScreen.getContentPane().add(new JLabel(imageIcon)); // Display it splashScreen.setVisible(true); // Begin initializing the rendering system RenderManager.initialize(SAFE_GRAPHICS); } FileEntity.setRootDirectory(System.getProperty("user.dir")); // create a graphic simulation LogBox.logLine("Loading Simulation Environment ... "); EventManager evt = Entity.initEVT(); GUIFrame gui = GUIFrame.instance(); gui.updateForSimulationState(SIM_STATE_LOADED); evt.setTimeListener(gui); evt.setErrorListener(gui); LogBox.logLine("Simulation Environment Loaded"); if (batch) InputAgent.setBatch(true); if (minimize) gui.setExtendedState(JFrame.ICONIFIED); // Show the Control Panel gui.setVisible(true); GUIFrame.calcWindowDefaults(); // Load the autoload file InputAgent.setRecordEdits(false); InputAgent.readResource("inputs/autoload.cfg"); gui.setTitle(Simulation.getModelName()); // Process any configuration files passed on command line // (Multiple configuration files are not supported at present) for (int i = 0; i < configFiles.size(); i++) { InputAgent.configure(gui, configFiles.get(i)); } // If no configuration files were specified on the command line, then load the default configuration file if( configFiles.size() == 0 ) { InputAgent.setRecordEdits(true); InputAgent.loadDefault(); gui.updateForSimulationState(GUIFrame.SIM_STATE_CONFIGURED); } // Show the view windows and tools if(!quiet && !batch) { displayWindows(false); } // Set RecordEdits mode (if it has not already been set in the configuration file) InputAgent.setRecordEdits(true); // Hide the splash screen if (splashScreen != null) { try { Thread.sleep(1000); } catch (InterruptedException e) {} splashScreen.dispose(); splashScreen = null; gui.toFront(); } // Start the model if in batch mode if (batch) { if (InputAgent.numErrors() > 0) GUIFrame.shutdown(0); Simulation.start(); Simulation.resume(Double.POSITIVE_INFINITY); GUIFrame.instance.updateForSimulationState(GUIFrame.SIM_STATE_RUNNING); } } public static class SpeedFactorListener implements ChangeListener { @Override public void stateChanged( ChangeEvent e ) { String factorRT = String.format("%d", ((JSpinner)e.getSource()).getValue()); Simulation.setRealTimeFactor(factorRT); FrameBox.valueUpdate(); } } /* * this class is created so the next value will be value * 2 and the * previous value will be value / 2 */ public static class SpinnerModel extends SpinnerNumberModel { private int value; public SpinnerModel( int val, int min, int max, int stepSize) { super(val, min, max, stepSize); } @Override @SuppressWarnings("unchecked") public Object getPreviousValue() { value = this.getNumber().intValue() / 2; // Avoid going beyond limit if(this.getMinimum().compareTo(value) > 0 ) { return this.getMinimum(); } return value; } @Override @SuppressWarnings("unchecked") public Object getNextValue() { value = this.getNumber().intValue() * 2; // Avoid going beyond limit if(this.getMaximum().compareTo(value) < 0 ) { return this.getMaximum(); } return value; } } public static class RealTimeActionListener implements ActionListener { @Override public void actionPerformed( ActionEvent event ) { Simulation.setRealTime(((JToggleButton)event.getSource()).isSelected()); FrameBox.valueUpdate(); } } public static boolean getShuttingDownFlag() { return shuttingDown.get(); } public static void shutdown(int errorCode) { shuttingDown.set(true); if (RenderManager.isGood()) { RenderManager.inst().shutdown(); } System.exit(errorCode); } @Override public void tickUpdate(long tick) { FrameBox.timeUpdate(tick); } @Override public void timeRunning(boolean running) { if (running) { } else { updateForSimulationState(SIM_STATE_PAUSED); } } @Override public void handleError(Throwable t, long currentTick) { if (t instanceof OutOfMemoryError) { OutOfMemoryError e = (OutOfMemoryError)t; LogBox.logLine("Out of Memory use the -Xmx flag during execution for more memory"); LogBox.logLine("Further debug information:"); LogBox.logLine("Error: " + e.getMessage()); for (StackTraceElement each : e.getStackTrace()) LogBox.logLine(each.toString()); GUIFrame.shutdown(1); return; } else { double curSec = Process.ticksToSeconds(currentTick); LogBox.format("EXCEPTION AT TIME: %f s%n", curSec); LogBox.logLine("Error: " + t.getMessage()); for (StackTraceElement each : t.getStackTrace()) LogBox.logLine(each.toString()); LogBox.getInstance().setVisible(true); } if (InputAgent.getBatch()) GUIFrame.shutdown(1); } }
package com.cliqz.jsengine; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import android.util.Log; import com.cliqz.jsengine.v8.V8Engine; import com.eclipsesource.v8.V8; import com.eclipsesource.v8.V8Array; import com.eclipsesource.v8.V8Object; import com.eclipsesource.v8.V8ResultUndefined; import com.eclipsesource.v8.utils.MemoryManager; import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @RunWith(AndroidJUnit4.class) public class AdblockerTest { private Context appContext; @Before public void setUp() throws Exception { appContext = InstrumentationRegistry.getTargetContext(); } @After public void tearDown() throws Exception { // reset prefs appContext.deleteFile("cliqz.prefs.json"); } @Test public void testBasicApi() throws Exception { Engine extension = new Engine(appContext, true); Adblocker adb = new Adblocker(extension); extension.startup(adb.getDefaultPrefs()); adb.setEnabled(true); //extension.shutdown(); } @Test public void testBlackListing() throws Exception { Context appContext = InstrumentationRegistry.getTargetContext(); Engine extension = new Engine(appContext, true); Adblocker adb = new Adblocker(extension); extension.startup(adb.getDefaultPrefs()); extension.setLoggingEnabled(true); adb.setEnabled(true); extension.jsengine.queryEngine(new V8Engine.Query<Object>() { @Override public Object query(V8 runtime) { runtime.executeVoidScript("console.log(JSON.stringify(Object.keys(System.get('adblocker/adblocker').default)))"); return null; } }); final String testUrl = "https://cliqz.com"; assertFalse(adb.isBlacklisted(testUrl)); adb.toggleUrl(testUrl, true); assertTrue(adb.isBlacklisted(testUrl)); adb.toggleUrl(testUrl, true); assertFalse(adb.isBlacklisted(testUrl)); } @Test public void testListLoading() throws Exception { final int MAX_TRIES = 20; Context appContext = InstrumentationRegistry.getTargetContext(); final Engine extension = new Engine(appContext, false); Adblocker adb = new Adblocker(extension); extension.startup(adb.getDefaultPrefs()); adb.setEnabled(true); final V8Object requestDetails = extension.jsengine.queryEngine(new V8Engine.Query<V8Object>() { @Override public V8Object query(V8 runtime) { V8Object details = new V8Object(runtime); details.add("type", 2); details.add("method", "GET"); details.add("source", "http: details.add("url", "http://me-cdn.effectivemeasure.net/em.js"); return details; } }); final V8Object adblocker = extension.system.loadModule("adblocker/adblocker"); boolean isBlocked = false; int tryCtr = 0; do { isBlocked = extension.jsengine.queryEngine(new V8Engine.Query<Boolean>() { @Override public Boolean query(V8 runtime) { MemoryManager scope = new MemoryManager(runtime); try { V8Object mod = adblocker.getObject("default"); V8Object observer = mod.getObject("httpopenObserver"); V8Array parameters = new V8Array(runtime).push(requestDetails); V8Object response = observer.executeObjectFunction("observe", parameters); return response.getBoolean("cancel"); } catch(V8ResultUndefined e) { return false; } finally { scope.release(); } } }); if (!isBlocked) { tryCtr++; Thread.sleep(50); } } while(!isBlocked && tryCtr < MAX_TRIES); // check adblock info is available JSONObject adbInfo = adb.getAdBlockingInfo("http: assertTrue(adbInfo.getJSONObject("advertisersList").has("Effective Measure")); extension.jsengine.queryEngine(new V8Engine.Query<Object>() { @Override public Object query(V8 runtime) { adblocker.release(); requestDetails.release(); return null; } }); if (tryCtr == MAX_TRIES) { fail(); } } }
package peergos.shared.user.fs; import peergos.shared.*; import peergos.shared.cbor.*; import peergos.shared.crypto.*; import peergos.shared.crypto.random.*; import peergos.shared.crypto.symmetric.*; import peergos.shared.user.*; import peergos.shared.util.*; import java.util.*; import java.util.concurrent.*; /** An instance of EncryptedChunkRetriever holds a list of fragment hashes for a chunk, and the nonce used in * decrypting the resulting chunk, along with a link to the next chunk (if any). * */ public class EncryptedChunkRetriever implements FileRetriever { private final FragmentedPaddedCipherText linksToData; private final byte[] nextChunkLabel; private final SymmetricKey dataKey; public EncryptedChunkRetriever(FragmentedPaddedCipherText linksToData, byte[] nextChunkLabel, SymmetricKey dataKey) { this.linksToData = linksToData; this.nextChunkLabel = nextChunkLabel; this.dataKey = dataKey; } @Override public CompletableFuture<AsyncReader> getFile(WriterData version, NetworkAccess network, SafeRandom random, AbsoluteCapability ourCap, long fileSize, MaybeMultihash ourExistingHash, ProgressConsumer<Long> monitor) { return getChunk(version, network, random, 0, fileSize, ourCap, ourExistingHash, monitor) .thenApply(chunk -> { Location nextChunkPointer = ourCap.withMapKey(nextChunkLabel).getLocation(); return new LazyInputStreamCombiner(version, 0, chunk.get().chunk.data(), nextChunkPointer, chunk.get().chunk.data(), nextChunkPointer, network, random, ourCap.rBaseKey, fileSize, monitor); }); } public CompletableFuture<Optional<byte[]>> getMapLabelAt(WriterData version, AbsoluteCapability startCap, long offset, NetworkAccess network) { if (offset < Chunk.MAX_SIZE) return CompletableFuture.completedFuture(Optional.of(startCap.getMapKey())); if (offset < 2*Chunk.MAX_SIZE) return CompletableFuture.completedFuture(Optional.of(nextChunkLabel)); // chunk at this location hasn't been written yet, only referenced by previous chunk return network.getMetadata(version, startCap.withMapKey(nextChunkLabel)) .thenCompose(meta -> meta.isPresent() ? meta.get().retriever(startCap.rBaseKey).getMapLabelAt(version, startCap.withMapKey(nextChunkLabel), offset - Chunk.MAX_SIZE, network) : CompletableFuture.completedFuture(Optional.empty()) ); } public CompletableFuture<Optional<LocatedChunk>> getChunk(WriterData version, NetworkAccess network, SafeRandom random, long startIndex, long truncateTo, AbsoluteCapability ourCap, MaybeMultihash ourExistingHash, ProgressConsumer<Long> monitor) { if (startIndex >= Chunk.MAX_SIZE) { AbsoluteCapability nextChunkCap = ourCap.withMapKey(nextChunkLabel); return network.getMetadata(version, nextChunkCap) .thenCompose(meta -> { if (meta.isPresent()) return meta.get().retriever(ourCap.rBaseKey) .getChunk(version, network, random, startIndex - Chunk.MAX_SIZE, truncateTo - Chunk.MAX_SIZE, nextChunkCap, meta.get().committedHash(), l -> {}); Chunk newEmptyChunk = new Chunk(new byte[0], dataKey, nextChunkLabel, dataKey.createNonce()); LocatedChunk withLocation = new LocatedChunk(nextChunkCap.getLocation(), MaybeMultihash.empty(), newEmptyChunk); return CompletableFuture.completedFuture(Optional.of(withLocation)); }); } return linksToData.getAndDecrypt(dataKey, c -> ((CborObject.CborByteArray)c).value, network, monitor) .thenApply(data -> Optional.of(new LocatedChunk(ourCap.getLocation(), ourExistingHash, new Chunk(truncate(data, (int) Math.min(Chunk.MAX_SIZE, truncateTo)), dataKey, ourCap.getMapKey(), ourCap.rBaseKey.createNonce())))); } public static byte[] truncate(byte[] in, int length) { if (in.length == length) return in; return Arrays.copyOfRange(in, 0, length); } }
package com.sandwell.JavaSimulation3D; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.net.URL; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.JWindow; import javax.swing.SpinnerNumberModel; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import com.jaamsim.controllers.RenderManager; import com.jaamsim.input.InputAgent; import com.jaamsim.math.Vec3d; import com.jaamsim.ui.AboutBox; import com.jaamsim.ui.EditBox; import com.jaamsim.ui.EntityPallet; import com.jaamsim.ui.FrameBox; import com.jaamsim.ui.InfoBox; import com.jaamsim.ui.OutputBox; import com.jaamsim.ui.PropertyBox; import com.jaamsim.ui.View; import com.sandwell.JavaSimulation.ErrorException; import com.sandwell.JavaSimulation.FileEntity; import com.sandwell.JavaSimulation.Input; import com.sandwell.JavaSimulation.Simulation; import com.sandwell.JavaSimulation.Tester; import com.sandwell.JavaSimulation.Util; /** * The main window for a Graphical Simulation. It provides the controls for managing then * EventManager (run, pause, ...) and the graphics (zoom, pan, ...) */ public class GUIFrame extends JFrame { private static GUIFrame instance; // global shutdown flag static private AtomicBoolean shuttingDown; private JMenu fileMenu; private JMenu viewMenu; private JMenu windowList; private JMenu optionMenu; private JCheckBoxMenuItem showPosition; private JCheckBoxMenuItem alwaysTop; private JCheckBoxMenuItem tooltip; private JCheckBoxMenuItem expControls; private JMenuItem showEventViewer; private JMenuItem printInputItem; private JLabel clockDisplay; private JLabel speedUpDisplay; private JLabel remainingDisplay; private JToggleButton controlRealTime; private JSpinner spinner; private JToggleButton controlStartResume; private JToggleButton controlStop; private JTextField pauseTime; private JLabel locatorPos; private JLabel locatorLabel; JButton toolButtonIsometric; JButton toolButtonXYPlane; JButton toolButtonUndo; JButton toolButtonRedo; private int lastValue = -1; private JProgressBar progressBar; private static Image iconImage; private static boolean SAFE_GRAPHICS; // Collection of default window parameters public static int COL1_WIDTH; public static int COL2_WIDTH; public static int COL3_WIDTH; public static int COL1_START; public static int COL2_START; public static int COL3_START; public static int HALF_TOP; public static int HALF_BOTTOM; public static int TOP_START; public static int BOTTOM_START; public static int LOWER_HEIGHT; public static int LOWER_START; public static int VIEW_HEIGHT; public static int VIEW_WIDTH; static final String infinitySign = "\u221e"; static { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println("Unable to change look and feel."); } try { URL file = GUIFrame.class.getResource("/resources/images/icon.png"); iconImage = Toolkit.getDefaultToolkit().getImage(file); } catch (Exception e) { System.err.println("Unable to load icon file."); iconImage = null; } shuttingDown = new AtomicBoolean(false); } private GUIFrame() { super(); getContentPane().setLayout( new BorderLayout() ); setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ); this.addWindowListener(new CloseListener()); // Initialize the working environment initializeMenus(); initializeMainToolBars(); initializeStatusBar(); this.setIconImage(GUIFrame.getWindowIcon()); //Set window size and make visible pack(); setResizable( false ); controlStartResume.setSelected( false ); controlStartResume.setEnabled( false ); controlStop.setSelected( false ); controlStop.setEnabled( false ); setProgress( 0 ); ToolTipManager.sharedInstance().setLightWeightPopupEnabled( false ); JPopupMenu.setDefaultLightWeightPopupEnabled( false ); } public static synchronized GUIFrame instance() { if (instance == null) instance = new GUIFrame(); return instance; } private class CloseListener extends WindowAdapter implements ActionListener { @Override public void windowClosing(WindowEvent e) { GUIFrame.this.close(); } @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.close(); } } /** * Perform exit window duties */ void close() { // close warning/error trace file InputAgent.closeLogFile(); // check for unsaved changes if (InputAgent.isSessionEdited()) { int userOption = JOptionPane.showConfirmDialog( null, "Do you want to save the changes?", "Confirm Exit Without Saving", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE ); if (userOption == JOptionPane.YES_OPTION) { InputAgent.save(this); GUIFrame.shutdown(0); } else if (userOption == JOptionPane.NO_OPTION) { GUIFrame.shutdown(0); } } else { GUIFrame.shutdown(0); } } /** * Clears the simulation and user interface for a new run */ public void clear() { // Clear the simulation DisplayEntity.simulation.clear(); FrameBox.timeUpdate(0.0d); // Clear the title bar setTitle(Simulation.getModelName()); // Clear the status bar setProgress( 0 ); speedUpDisplay.setText(" remainingDisplay.setText(" locatorPos.setText( "(-, -, -)" ); // Read the autoload configuration file InputAgent.clear(); InputAgent.readURL(InputAgent.class.getResource("/resources/inputs/autoload.cfg")); } public void initializeMenus() { // Initialize main menus JMenuBar mainMenuBar = new JMenuBar(); // File menu creation fileMenu = new JMenu( "File" ); fileMenu.setMnemonic( 'F' ); fileMenu.setEnabled( false ); JMenuItem newMenuItem = new JMenuItem( "New" ); newMenuItem.setMnemonic( 'N' ); newMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { Simulation.pause(); // check for unsaved changes if (InputAgent.isSessionEdited()) { int userOption = JOptionPane.showConfirmDialog( null, "A new simulation will overwrite the existing simulation without saving changes. Do you wish to continue with a new simulation?", "Confirm New Simulation", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); if(userOption == JOptionPane.NO_OPTION) { return; } } clear(); InputAgent.loadDefault(); displayWindows(false); } } ); fileMenu.add( newMenuItem ); JMenuItem configMenuItem = new JMenuItem( "Open..." ); configMenuItem.setMnemonic( 'O' ); configMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { Simulation.pause(); // check for unsaved changes if (InputAgent.isSessionEdited()) { int userOption = JOptionPane.showConfirmDialog( null, "Opening a simulation will overwrite the existing simulation without saving changes. Do you wish to continue opening a simulation?", "Confirm Open", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); if (userOption == JOptionPane.NO_OPTION) { return; } } InputAgent.load(GUIFrame.this); } } ); fileMenu.add( configMenuItem ); JMenuItem saveConfigurationMenuItem = new JMenuItem( "Save" ); saveConfigurationMenuItem.setMnemonic( 'S' ); saveConfigurationMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.save(GUIFrame.this); } } ); fileMenu.add( saveConfigurationMenuItem ); JMenuItem saveConfigurationAsMenuItem = new JMenuItem( "Save As..." ); saveConfigurationAsMenuItem.setMnemonic( 'V' ); saveConfigurationAsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.saveAs(GUIFrame.this); } } ); fileMenu.add( saveConfigurationAsMenuItem ); printInputItem = new JMenuItem( "Print Input Report" ); printInputItem.setMnemonic( 'I' ); printInputItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.printInputFileKeywords(); } } ); fileMenu.add( printInputItem ); JMenuItem exitMenuItem = new JMenuItem( "Exit" ); exitMenuItem.setMnemonic( 'x' ); exitMenuItem.addActionListener(new CloseListener()); fileMenu.add( exitMenuItem ); mainMenuBar.add( fileMenu ); // End File menu creation // View menu creation viewMenu = new JMenu( "Tools" ); viewMenu.setMnemonic( 'T' ); JMenuItem objectPalletMenuItem = new JMenuItem( "Model Builder" ); objectPalletMenuItem.setMnemonic( 'O' ); objectPalletMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { EntityPallet.getInstance().setVisible(true); } } ); viewMenu.add( objectPalletMenuItem ); JMenuItem objectSelectorMenuItem = new JMenuItem( "Object Selector" ); objectSelectorMenuItem.setMnemonic( 'S' ); objectSelectorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ObjectSelector.getInstance().setVisible(true); } } ); viewMenu.add( objectSelectorMenuItem ); JMenuItem inputEditorMenuItem = new JMenuItem( "Input Editor" ); inputEditorMenuItem.setMnemonic( 'I' ); inputEditorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { EditBox.getInstance().makeVisible(); if(ObjectSelector.getInstance().isVisible()) FrameBox.setSelectedEntity(ObjectSelector.currentEntity); } } ); viewMenu.add( inputEditorMenuItem ); JMenuItem outputMenuItem = new JMenuItem( "Output Viewer" ); outputMenuItem.setMnemonic( 'U' ); outputMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { OutputBox.getInstance().makeVisible(); if(ObjectSelector.getInstance().isVisible()) FrameBox.setSelectedEntity(ObjectSelector.currentEntity); } } ); viewMenu.add( outputMenuItem ); JMenuItem propertiesMenuItem = new JMenuItem( "Property Viewer" ); propertiesMenuItem.setMnemonic( 'P' ); propertiesMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { PropertyBox.getInstance().makeVisible(); if(ObjectSelector.getInstance().isVisible()) FrameBox.setSelectedEntity(ObjectSelector.currentEntity); } } ); viewMenu.add( propertiesMenuItem ); JMenuItem infoMenuItem = new JMenuItem( "Info Viewer" ); infoMenuItem.setMnemonic( 'I' ); infoMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InfoBox.getInstance().makeVisible(); if(ObjectSelector.getInstance().isVisible()) FrameBox.setSelectedEntity(ObjectSelector.currentEntity); } } ); viewMenu.add( infoMenuItem ); // JMenuItem eventListMenuItem = new JMenuItem( "Event Viewer" ); // eventListMenuItem.setMnemonic( 'E' ); // eventListMenuItem.addActionListener( new ActionListener() { // public void actionPerformed( ActionEvent e ) { // new EventViewer( DisplayEntity.simulation.getEventManager() ); // viewMenu.add( eventListMenuItem ); mainMenuBar.add( viewMenu ); // End File menu creation // Window menu creation JMenu windowMenu = new NewRenderWindowMenu("Views"); windowMenu.setMnemonic( 'V' ); // Initialize list of windows windowList = new WindowMenu("Select Window"); windowList.setMnemonic( 'S' ); //windowMenu.add( windowList ); mainMenuBar.add( windowMenu ); // End window menu creation optionMenu = new JMenu( "Options" ); optionMenu.setMnemonic( 'O' ); mainMenuBar.add( optionMenu ); showPosition = new JCheckBoxMenuItem( "Show Position", true ); showPosition.setMnemonic( 'P' ); optionMenu.add( showPosition ); alwaysTop = new JCheckBoxMenuItem( "Always on top", false ); alwaysTop.setMnemonic( 'A' ); optionMenu.add( alwaysTop ); alwaysTop.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { if( GUIFrame.this.isAlwaysOnTop() ) { GUIFrame.this.setAlwaysOnTop( false ); } else { GUIFrame.this.setAlwaysOnTop( true ); } } } ); tooltip = new JCheckBoxMenuItem( "Tooltip", true ); tooltip.setMnemonic( 'L' ); optionMenu.add( tooltip ); tooltip.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { // TODO Needs to be implemented for the new Renderer } } ); expControls = new JCheckBoxMenuItem( "Experimental Controls", true ); expControls.setMnemonic( 'E' ); optionMenu.add( expControls ); showPosition.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { setShowPositionXY(); } } ); // Help menu creation JMenu helpMenu = new JMenu( "Help" ); helpMenu.setMnemonic( 'H' ); JMenuItem aboutMenu = new JMenuItem( "About" ); aboutMenu.setMnemonic( 'A' ); aboutMenu.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { AboutBox.instance().setVisible(true); } } ); helpMenu.add( aboutMenu ); mainMenuBar.add( helpMenu ); // End help menu creation // Add main menu to the window setJMenuBar( mainMenuBar ); } public void initializeMainToolBars() { // Insets used in setting the toolbar components Insets noMargin = new Insets( 0, 0, 0, 0 ); Insets smallMargin = new Insets( 1, 1, 1, 1 ); // Initilize the main toolbar JToolBar mainToolBar = new JToolBar(); mainToolBar.setMargin( smallMargin ); mainToolBar.setFloatable(false); // Create Run Label and run control buttons controlStartResume = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/run.png"))); controlStartResume.setSelectedIcon( new ImageIcon(GUIFrame.class.getResource("/resources/images/pause.png"))); controlStartResume.setToolTipText( "Run" ); controlStartResume.setMargin( noMargin ); controlStartResume.setEnabled( false ); controlStartResume.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { JToggleButton startResume = (JToggleButton)event.getSource(); if(startResume.isSelected()) { GUIFrame.this.startSimulation(); } else { GUIFrame.this.pauseSimulation(); } GUIFrame.this.updateForSimulationState(); } } ); controlStop = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/stop.png"))); controlStop.setToolTipText( "Stop" ); controlStop.setMargin( noMargin ); controlStop.setEnabled( false ); controlStop.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if( Simulation.getSimulationState() == Simulation.SIM_STATE_RUNNING ) { GUIFrame.this.pauseSimulation(); } int userOption = JOptionPane.showConfirmDialog( null, "WARNING: If you stop the run, it cannot continue from the present time and can only be re-started from time 0. Do you really want to stop?", "Confirm Stop", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); // stop only if yes if (userOption == JOptionPane.YES_OPTION) { GUIFrame.this.stopSimulation(); FrameBox.timeUpdate(0.0d); } } } ); // Separators have 5 pixels before and after and the preferred height of controlStartResume button Dimension separatorDim = new Dimension(11, controlStartResume.getPreferredSize().height); // dimension for 5 pixels gaps Dimension gapDim = new Dimension(5, separatorDim.height); mainToolBar.add( controlStartResume ); mainToolBar.add(Box.createRigidArea(gapDim)); mainToolBar.add( controlStop ); mainToolBar.add(Box.createRigidArea(gapDim)); JLabel pauseAt = new JLabel( "Pause at:" ); mainToolBar.add(pauseAt); mainToolBar.add(Box.createRigidArea(gapDim)); pauseTime = new JTextField("2000-00-00") { @Override protected void processFocusEvent( FocusEvent fe ) { if ( fe.getID() == FocusEvent.FOCUS_GAINED ) { if(getText().equals(infinitySign)) { this.setHorizontalAlignment(JTextField.RIGHT); this.setText(""); } // select entire text string selectAll(); } else if (fe.getID() == FocusEvent.FOCUS_LOST) { if(getText().isEmpty()) { this.setText(infinitySign); this.setHorizontalAlignment(JTextField.CENTER); } } super.processFocusEvent( fe ); } }; // avoid height increase for pauseTime pauseTime.setMaximumSize(pauseTime.getPreferredSize()); // avoid stretching for puaseTime when focusing in and out pauseTime.setPreferredSize(pauseTime.getPreferredSize()); mainToolBar.add(pauseTime); pauseTime.setText(infinitySign); pauseTime.setHorizontalAlignment(JTextField.CENTER); SpinnerNumberModel numberModel = new SpinnerModel(Simulation.DEFAULT_REAL_TIME_FACTOR, Simulation.MIN_REAL_TIME_FACTOR, Simulation.MAX_REAL_TIME_FACTOR, 1); spinner = new JSpinner(numberModel); // make sure spinner TextField is no wider than 9 digits int diff = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().getPreferredSize().width - Util.getPixelWidthOfString_ForFont("9", spinner.getFont()) * 9; Dimension dim = spinner.getPreferredSize(); dim.width -= diff; spinner.setMaximumSize(dim); spinner.addChangeListener(new SpeedFactorListener()); mainToolBar.addSeparator(separatorDim); controlRealTime = new JToggleButton( "Real Time" ); controlRealTime.setToolTipText( "Toggle Real Time" ); controlRealTime.setMargin( smallMargin ); controlRealTime.addActionListener(new RealTimeActionListener()); mainToolBar.add( controlRealTime ); mainToolBar.add(Box.createRigidArea(gapDim)); mainToolBar.add( spinner ); mainToolBar.addSeparator(separatorDim); // End creation of real-time label and menu // Create view control label and controls JLabel viewLabel = new JLabel( " View Control: " ); mainToolBar.add( viewLabel ); // add a button to show isometric view in windows toolButtonIsometric = new JButton( "Isometric" ); toolButtonIsometric.setToolTipText( "Set Isometric View" ); toolButtonIsometric.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (RenderManager.isGood()) RenderManager.inst().setIsometricView(); } } ); mainToolBar.add( toolButtonIsometric ); // add a button to show xy-plane view in windows toolButtonXYPlane = new JButton( "XY-Plane" ); toolButtonXYPlane.setToolTipText( "Set XY-Plane View" ); toolButtonXYPlane.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (RenderManager.isGood()) RenderManager.inst().setXYPlaneView(); } } ); mainToolBar.add( toolButtonXYPlane ); mainToolBar.addSeparator(separatorDim); // add a button to undo the last step ( viewer and window ) toolButtonUndo = new JButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/previous.png"))); toolButtonUndo.setToolTipText( "Previous view" ); toolButtonUndo.setEnabled( false ); toolButtonUndo.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { // Not implemented } } ); //mainToolBar.add( toolButtonUndo ); // add a button to redo the last step ( viewer and window ) toolButtonRedo = new JButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/next.png"))); toolButtonRedo.setToolTipText( "Next view" ); toolButtonRedo.setEnabled( false ); toolButtonRedo.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { // Not implemented } } ); //mainToolBar.add( toolButtonRedo ); //mainToolBar.addSeparator(separatorDim); // End creation of view control label and buttons // Add toolbar to the window getContentPane().add( mainToolBar, BorderLayout.NORTH ); } private static class WindowMenu extends JMenu implements MenuListener { WindowMenu(String text) { super(text); this.addMenuListener(this); } @Override public void menuCanceled(MenuEvent arg0) {} @Override public void menuDeselected(MenuEvent arg0) { this.removeAll(); } @Override public void menuSelected(MenuEvent arg0) { if (!RenderManager.isGood()) { return; } ArrayList<Integer> windowIDs = RenderManager.inst().getOpenWindowIDs(); for (int id : windowIDs) { String windowName = RenderManager.inst().getWindowName(id); this.add(new WindowSelector(id, windowName)); } } } private static class WindowSelector extends JMenuItem implements ActionListener { private final int windowID; WindowSelector(int windowID, String windowName) { this.windowID = windowID; this.setText(windowName); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { return; } RenderManager.inst().focusWindow(windowID); } } private static class NewRenderWindowMenu extends JMenu implements MenuListener { NewRenderWindowMenu(String text) { super(text); this.addMenuListener(this); } @Override public void menuSelected(MenuEvent e) { for (View view : View.getAll()) { this.add(new NewRenderWindowLauncher(view)); } this.addSeparator(); this.add(new ViewDefiner()); } @Override public void menuCanceled(MenuEvent arg0) { } @Override public void menuDeselected(MenuEvent arg0) { this.removeAll(); } } private static class NewRenderWindowLauncher extends JMenuItem implements ActionListener { private final View view; NewRenderWindowLauncher(View v) { view = v; this.setText(view.getName()); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { if (RenderManager.canInitialize()) { RenderManager.initialize(SAFE_GRAPHICS); } else { // A fatal error has occurred, don't try to initialize again return; } } RenderManager.inst().createWindow(view); } } private static class ViewDefiner extends JMenuItem implements ActionListener { ViewDefiner() {} { this.setText("Define new View"); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { if (RenderManager.canInitialize()) { RenderManager.initialize(SAFE_GRAPHICS); } else { // A fatal error has occurred, don't try to initialize again return; } } View tmp = InputAgent.defineEntityWithUniqueName(View.class, "View", true); RenderManager.inst().createWindow(tmp); FrameBox.setSelectedEntity(tmp); } } public void initializeStatusBar() { // Create the status bar JPanel statusBar = new JPanel(); statusBar.setBorder( BorderFactory.createLineBorder( Color.darkGray ) ); statusBar.setLayout( new FlowLayout( FlowLayout.LEFT, 10, 5 ) ); // Create the display clock and label JLabel clockLabel = new JLabel( "Simulation Time (hrs):" ); clockDisplay = new JLabel( " clockDisplay.setPreferredSize( new Dimension( 55, 16 ) ); clockDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); statusBar.add( clockLabel ); statusBar.add( clockDisplay ); //statusBar.addSeparator(); // Create the progress bar progressBar = new JProgressBar( 0, 100 ); progressBar.setValue( 0 ); progressBar.setStringPainted( true ); // Add the progress bar to the status bar statusBar.add( progressBar ); // Create a speed-up factor display JLabel speedUpLabel = new JLabel( "Speed Up:" ); speedUpDisplay = new JLabel( " speedUpDisplay.setPreferredSize( new Dimension( 60, 16 ) ); speedUpDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); statusBar.add( speedUpLabel ); statusBar.add( speedUpDisplay ); // Create a remaining run time display JLabel remainingLabel = new JLabel( "Time Remaining (mins):" ); remainingDisplay = new JLabel( " remainingDisplay.setPreferredSize( new Dimension( 40, 16 ) ); remainingDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); statusBar.add( remainingLabel ); statusBar.add( remainingDisplay ); locatorPos = new JLabel( "(-, -, -)" ); locatorPos.setPreferredSize( new Dimension( 140, 16 ) ); locatorPos.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); locatorLabel = new JLabel( "Pos: " ); statusBar.add( locatorLabel ); statusBar.add( locatorPos ); // Add the status bar to the window getContentPane().add( statusBar, BorderLayout.SOUTH ); } private long lastSystemTime = System.currentTimeMillis(); private double lastSimTimeHours = 0.0d; public void setClock(double simTime) { double clockContents = simTime / 3600.0d; clockDisplay.setText(String.format("%.2f", clockContents)); long cTime = System.currentTimeMillis(); Simulation sim = DisplayEntity.simulation; double duration = sim.getRunDuration() + sim.getInitializationTime(); double timeElapsed = clockContents - sim.getStartTime(); int progress = (int)(timeElapsed * 100.0d / duration); this.setProgress(progress); if (cTime - lastSystemTime > 5000) { long elapsedMillis = cTime - lastSystemTime; double elapsedSimHours = timeElapsed - lastSimTimeHours; // Determine the speed-up factor double speedUp = (elapsedSimHours * 3600000.0d) / elapsedMillis; setSpeedUp(speedUp); double remainingSimTime = duration - timeElapsed; double remainingMinutes = (remainingSimTime * 60.0d) / speedUp; setRemaining(remainingMinutes); lastSystemTime = cTime; lastSimTimeHours = timeElapsed; } } public void setProgress( int val ) { if (lastValue == val) return; progressBar.setValue( val ); progressBar.repaint(25); lastValue = val; if (Simulation.getSimulationState() >= Simulation.SIM_STATE_CONFIGURED) { String title = String.format("%d%% %s - %s", val, Simulation.getModelName(), InputAgent.getRunName()); setTitle(title); } } public void setProgressText( String txt ) { progressBar.setString( txt ); } public void setSpeedUp( double val ) { speedUpDisplay.setText(String.format("%,.0f", val)); } public void setRemaining( double val ) { remainingDisplay.setText(String.format("%.1f", val)); } private void startSimulation() { // pause at a time double runToTime = Double.POSITIVE_INFINITY; if(! pauseTime.getText().equalsIgnoreCase(infinitySign)) { try { if (Tester.isDate(pauseTime.getText())) { String[] str = pauseTime.getText().split("-"); if (str.length < 3) { throw new NumberFormatException ("Date string must be of form yyyy-mm-dd"); } int year = Integer.valueOf(str[0]).intValue(); int month = Integer.valueOf(str[1]).intValue(); int day = Integer.valueOf(str[2]).intValue(); double time = Clock.calcTimeForYear_Month_Day_Hour(year, month, day, 0.0); int startingYear = Clock.getStartingYear(); int startingMonth = Clock.getStartingMonth(); int startingDay = Clock.getStartingDay(); double startingTime = Clock.calcTimeForYear_Month_Day_Hour( startingYear, startingMonth, startingDay, 0.0); runToTime = time - startingTime; } else { runToTime = Double.parseDouble(pauseTime.getText()); } } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(this, String.format( "Invalid time \n %s", pauseTime.getText()), "error", JOptionPane.ERROR_MESSAGE); // it is not running any more controlStartResume.setSelected(! controlStartResume.isSelected() ); return; } } if(runToTime <= DisplayEntity.simulation.getCurrentTime() ) { return; } if( Simulation.getSimulationState() <= Simulation.SIM_STATE_CONFIGURED ) { if (InputAgent.isSessionEdited()) { InputAgent.saveAs(this); } DisplayEntity.simulation.start(); } else if( Simulation.getSimulationState() == Simulation.SIM_STATE_PAUSED ) { // it is not a run to time if(Double.isInfinite( runToTime ) ) { Simulation.resume(); return; } } else if( Simulation.getSimulationState() == Simulation.SIM_STATE_STOPPED ) { DisplayEntity.simulation.restart(); } else throw new ErrorException( "Invalid Simulation State for Start/Resume" ); if( ! Double.isInfinite(runToTime) ) { DisplayEntity.simulation.getEventManager().runToTime(runToTime); } } private void pauseSimulation() { if( Simulation.getSimulationState() == Simulation.SIM_STATE_RUNNING ) Simulation.pause(); else throw new ErrorException( "Invalid Simulation State for pause" ); } private void stopSimulation() { if( Simulation.getSimulationState() == Simulation.SIM_STATE_RUNNING || Simulation.getSimulationState() == Simulation.SIM_STATE_PAUSED ) Simulation.stop(); else throw new ErrorException( "Invalid Simulation State for stop" ); } public void updateForSimulationState() { switch( Simulation.getSimulationState() ) { case Simulation.SIM_STATE_LOADED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setEnabled( false ); controlStop.setSelected( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( false ); if( showEventViewer != null ) showEventViewer.setEnabled( false ); break; case Simulation.SIM_STATE_UNCONFIGURED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); controlStartResume.setEnabled( false ); controlStartResume.setSelected( false ); controlStop.setSelected( false ); controlStop.setEnabled( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( false ); showPosition.setState( true ); setShowPositionXY(); if( showEventViewer != null ) showEventViewer.setEnabled( false ); break; case Simulation.SIM_STATE_CONFIGURED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( true ); remainingDisplay.setEnabled( true ); controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setSelected( false ); controlStop.setEnabled( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( true ); if( showEventViewer != null ) showEventViewer.setEnabled( true ); break; case Simulation.SIM_STATE_RUNNING: controlStartResume.setEnabled( true ); controlStartResume.setSelected( true ); controlStartResume.setToolTipText( "Pause" ); controlStop.setEnabled( true ); controlStop.setSelected( false ); if( showEventViewer != null ) showEventViewer.setEnabled( true ); break; case Simulation.SIM_STATE_PAUSED: controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; case Simulation.SIM_STATE_STOPPED: controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setEnabled( false ); controlStop.setSelected( false ); break; default: throw new ErrorException( "Unrecognized Graphics State" ); } fileMenu.setEnabled( true ); } /** * updates RealTime button and Spinner */ public void updateForRealTime(boolean executeRT, int factorRT) { controlRealTime.setSelected(executeRT); spinner.setValue(factorRT); } public static Image getWindowIcon() { return iconImage; } public void copyLocationToClipBoard(Vec3d pos) { String data = String.format("(%.3f, %.3f, %.3f)", pos.x, pos.y, pos.z); StringSelection stringSelection = new StringSelection(data); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents( stringSelection, null ); } public void showLocatorPosition(Vec3d pos) { // null indicates nothing to display if( pos == null ) { locatorPos.setText( "(-, -, -)" ); } else { if( showPosition.getState() ) { locatorPos.setText(String.format("(%.3f, %.3f, %.3f)", pos.x, pos.y, pos.z)); } } } public void setShowPositionXY() { boolean show = showPosition.getState(); showPosition.setState( show ); locatorLabel.setVisible( show ); locatorPos.setVisible( show ); locatorLabel.setText( "Pos: " ); locatorPos.setText( "(-, -, -)" ); } public boolean getExperimentalControls() { return expControls.getState(); } private static void calcWindowDefaults() { Dimension guiSize = GUIFrame.instance().getSize(); Rectangle winSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); COL1_WIDTH = 220; COL2_WIDTH = Math.min(520, (winSize.width - COL1_WIDTH) / 2); COL3_WIDTH = Math.min(420, winSize.width - COL1_WIDTH - COL2_WIDTH); COL1_START = 0; COL2_START = COL1_START + COL1_WIDTH; COL3_START = COL2_START + COL2_WIDTH; HALF_TOP = (winSize.height - guiSize.height) / 2; HALF_BOTTOM = (winSize.height - guiSize.height - HALF_TOP); TOP_START = guiSize.height; BOTTOM_START = TOP_START + HALF_TOP; LOWER_HEIGHT = (winSize.height - guiSize.height) / 3; LOWER_START = winSize.height - LOWER_HEIGHT; VIEW_WIDTH = COL2_WIDTH + COL3_WIDTH; VIEW_HEIGHT = winSize.height - TOP_START - LOWER_HEIGHT; } public static void displayWindows(boolean viewOnly) { for (View v : View.getAll()) { if (v.showOnStart()) RenderManager.inst().createWindow(v); } if (viewOnly) return; EntityPallet.getInstance().setVisible(true); ObjectSelector.getInstance().setVisible(true); EditBox.getInstance().setVisible(true); OutputBox.getInstance().setVisible(true); FrameBox.setSelectedEntity(View.getAll().get(0)); } // MAIN public static void main( String args[] ) { // Process the input arguments and filter out directives ArrayList<String> configFiles = new ArrayList<String>(args.length); boolean batch = false; boolean minimize = false; boolean quiet = false; for (String each : args) { // Batch mode if (each.equalsIgnoreCase("-b") || each.equalsIgnoreCase("-batch")) { batch = true; continue; } // z-buffer offset if (each.equalsIgnoreCase("-z") || each.equalsIgnoreCase("-zbuffer")) { // Parse the option, but do nothing continue; } // Minimize model window if (each.equalsIgnoreCase("-m") || each.equalsIgnoreCase("-minimize")) { minimize = true; continue; } // Do not open default windows if (each.equalsIgnoreCase("-q") || each.equalsIgnoreCase("-quiet")) { quiet = true; continue; } if (each.equalsIgnoreCase("-sg") || each.equalsIgnoreCase("-safe_graphics")) { SAFE_GRAPHICS = true; continue; } // Not a program directive, add to list of config files configFiles.add(each); } // If not running in batch mode, create the splash screen JWindow splashScreen = null; if (!batch) { URL splashImage = GUIFrame.class.getResource("/resources/images/splashscreen.png"); ImageIcon imageIcon = new ImageIcon(splashImage); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int splashX = (screen.width - imageIcon.getIconWidth()) / 2; int splashY = (screen.height - imageIcon.getIconHeight()) / 2; // Set the window's bounds, centering the window splashScreen = new JWindow(); splashScreen.setAlwaysOnTop(true); splashScreen.setBounds(splashX, splashY, imageIcon.getIconWidth(), imageIcon.getIconHeight()); // Build the splash screen splashScreen.getContentPane().add(new JLabel(imageIcon)); // Display it splashScreen.setVisible(true); // Begin initializing the rendering system RenderManager.initialize(SAFE_GRAPHICS); } FileEntity.setRootDirectory(System.getProperty("user.dir")); // create a graphic simulation System.out.println( "Loading Simulation Environment ... " ); System.out.flush(); GUIFrame gui = GUIFrame.instance(); gui.updateForSimulationState(); Simulation gsim = new Simulation(); DisplayEntity.setSimulation(gsim); gui.setTitle(Simulation.getModelName()); gsim.setInputName("Simulation"); System.out.println( "Simulation Environment Loaded" ); if (batch) InputAgent.setBatch(true); if (minimize) gui.setExtendedState(JFrame.ICONIFIED); gui.setVisible(true); GUIFrame.calcWindowDefaults(); InputAgent.readURL(InputAgent.class.getResource("/resources/inputs/autoload.cfg")); if( configFiles.size() == 0 ) { InputAgent.loadDefault(); } // Process any config files passed on command line for (int i = 0; i < configFiles.size(); i++) { // Consume regular configuration files InputAgent.configure(gui, configFiles.get(i)); continue; } if(!quiet && !batch) { displayWindows(false); } // Hide the splash screen if (splashScreen != null) { try { Thread.sleep(1000); } catch (InterruptedException e) {} splashScreen.dispose(); splashScreen = null; gui.toFront(); } // Start the model if in batch mode if (batch) { if (InputAgent.numErrors() > 0) GUIFrame.shutdown(0); gsim.start(); } } public static class SpeedFactorListener implements ChangeListener { @Override public void stateChanged( ChangeEvent e ) { String factorRT = String.format("%d", ((JSpinner)e.getSource()).getValue()); InputAgent.processEntity_Keyword_Value(DisplayEntity.simulation, "RealTimeFactor", factorRT); FrameBox.valueUpdate(); } } /* * this class is created so the next value will be value * 2 and the * previous value will be value / 2 */ public static class SpinnerModel extends SpinnerNumberModel { private int value; public SpinnerModel( int val, int min, int max, int stepSize) { super(val, min, max, stepSize); } @Override @SuppressWarnings("unchecked") public Object getPreviousValue() { value = this.getNumber().intValue() / 2; // Avoid going beyond limit if(this.getMinimum().compareTo(value) > 0 ) { return this.getMinimum(); } return value; } @Override @SuppressWarnings("unchecked") public Object getNextValue() { value = this.getNumber().intValue() * 2; // Avoid going beyond limit if(this.getMaximum().compareTo(value) < 0 ) { return this.getMaximum(); } return value; } } public static class RealTimeActionListener implements ActionListener { @Override public void actionPerformed( ActionEvent event ) { Input<?> in = DisplayEntity.simulation.getInput("RealTime"); String val = "FALSE"; if(((JToggleButton)event.getSource()).isSelected()) val = "TRUE"; InputAgent.processEntity_Keyword_Value(DisplayEntity.simulation, in, val); FrameBox.valueUpdate(); } } public static boolean getShuttingDownFlag() { return shuttingDown.get(); } public static void shutdown(int errorCode) { shuttingDown.set(true); if (RenderManager.isGood()) { RenderManager.inst().shutdown(); } System.exit(errorCode); } }
//TODO: Lots of stuff needs to be done with the window, but I'll settle for making it close // automatically when the user quits. Eventually. //TODO: Make player.role and associated variables enums. import java.util.Scanner; //import java.io.*; import javax.swing.*; import javax.swing.text.*; import java.awt.*; import java.awt.event.*; import java.awt.event.KeyEvent; import java.lang.String; public class main { public final static boolean DEBUG = true; public final static String SAVEPATH = "./javagame/save/"; public boolean alive = true; public static JTextField textField = new JTextField(); public static JTextArea textWindow = new JTextArea(); public static JScrollPane gameWindow = new JScrollPane(textWindow); public static JFrame frame = new JFrame("Text Adventure"); public final static int ENTER = KeyEvent.VK_ENTER; public final static int OUT_WIDTH = 80; public static int outCol = 0; //A single function to handle all text output. Should make un-consoleing it easier later on. public static void out (String outtext){ System.out.print(outtext); textWindow.append(outtext); } public static void output (String outtext){ outCol = 0; if (outtext.length() <= OUT_WIDTH){ out(outtext); if (outtext.length() < OUT_WIDTH){ out("\n"); } } else { int lastSpace = outtext.lastIndexOf(' ',OUT_WIDTH); if (lastSpace <= 0){ lastSpace = OUT_WIDTH; } StringBuffer outString = new StringBuffer(outtext.substring(0,lastSpace)); output(outString.toString()); output(outtext.substring(lastSpace+1)); } } public void keyPressed(KeyEvent e) { if(e.getKeyCode() == ENTER){ } } public static void main (String[] args) { //JScrollPane scrollPane = new JScrollPane(textWindow); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Add contents to the window. frame.setSize(660, 500); textWindow.setSize(640, 480); textWindow.setLocation(0, 0); textWindow.setEditable(false); textWindow.setLineWrap(true); textWindow.setWrapStyleWord(true); textWindow.setVisible(true); textField.setBounds(0, 480, 640, 20); gameWindow.add(textWindow); gameWindow.setVisible(true); frame.add(textWindow); frame.add(textField); frame.setVisible(true); Scanner scanner = new Scanner( System.in ); String input = null; Rooms loc = null; Player pl = null; Items it = null; Mobs mo = null; Magic mag = null; Room r = null; Skills skl = null; Parser p = new Parser(); loc = new Rooms(); pl = new Player(); it = new Items(); mo = new Mobs(); mag = new Magic(); skl = new Skills(); loc.initalizeRooms(); it.initializeItems(); mo.initializeMobs(); mo.populateMobs(loc); mag.initalizeSpells(); skl.initializeSkills(); it.populateItems(loc, pl); if (!main.DEBUG){ pl.charGen(); Room inv = loc.getRoomFromName("Inventory"); if (pl.role == 0b00000001) it.getEquipFromName("longsword").move(inv); if (pl.role == 0b00000010) it.getEquipFromName("dagger").move(inv); if (pl.role == 0b00000100) it.getEquipFromName("hammer").move(inv); if (pl.role == 0b00001000) it.getEquipFromName("staff").move(inv); if (pl.role == 0b00010000) it.getEquipFromName("flail").move(inv); if (pl.role == 0b00100000) it.getEquipFromName("rapier").move(inv); } if (main.DEBUG) { pl.gold = 65535; } it.setEquippable(pl); r = loc.getRoom(1); //ASCII art title! out(" out("\n A text adventure by Jeff Morse.\nType \"quit\" to exit, and 'help' to get help.\n"); p.Parse("look", loc, r,pl,it, mo, mag, skl); //Runs Parser in a loop until user types "Quit" do { input = scanner.nextLine(); try { r = p.Parse(input, loc, r, pl, it, mo, mag, skl); } catch(IllegalArgumentException e){ System.err.println("IllegalArgumentException: " + e.getMessage()); } //main.output(r); } while (r != loc.roomVector.elementAt(0));//while (!input.equalsIgnoreCase("quit")); } public static void output(int outtext) { System.out.println(outtext); } }
package com.senseidb.clue.commands; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.TreeMap; import org.apache.lucene.index.AtomicReader; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.index.FieldInfo.IndexOptions; import org.apache.lucene.index.FieldInfos; import org.apache.lucene.index.Fields; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Terms; import com.senseidb.clue.ClueContext; public class InfoCommand extends ClueCommand { public InfoCommand(ClueContext ctx) { super(ctx); } @Override public String getName() { return "info"; } @Override public String help() { return "displays information about the index, <segment number> to get information on the segment"; } @SuppressWarnings("unchecked") private static String toString(Object[] info) throws IOException { FieldInfo finfo = (FieldInfo) info[0]; List<Terms> termList = (List<Terms>) info[1]; TreeMap<String, String> valMap = new TreeMap<String, String>(); valMap.put("name", finfo.name); valMap.put("docval", String.valueOf(finfo.hasDocValues())); valMap.put("norms", String.valueOf(finfo.hasNorms())); valMap.put("payloads", String.valueOf(finfo.hasPayloads())); valMap.put("vectors", String.valueOf(finfo.hasVectors())); valMap.put("attributes", finfo.attributes().toString()); IndexOptions indexOptions = finfo.getIndexOptions(); if (indexOptions != null) { valMap.put("index-options", finfo.getIndexOptions().name()); } if (finfo.hasNorms()) { valMap.put("norm_type", String.valueOf(finfo.getNormType())); } if (finfo.hasDocValues()) { valMap.put("docval_type", String.valueOf(finfo.getDocValuesType())); } else { if (termList != null) { long numTerms = 0L; long docCount = 0L; long sumDocFreq = 0L; long sumTotalTermFreq = 0L; for (Terms t : termList) { if (t != null) { numTerms += t.size(); docCount += t.getDocCount(); sumDocFreq += t.getSumDocFreq(); sumTotalTermFreq += t.getSumTotalTermFreq(); } } if (numTerms < 0) { numTerms = -1; } if (docCount < 0) { docCount = -1; } if (sumDocFreq < 0) { sumDocFreq = -1; } if (sumTotalTermFreq < 0) { sumTotalTermFreq = -1; } valMap.put("num_terms", String.valueOf(numTerms)); valMap.put("doc_count", String.valueOf(docCount)); valMap.put("sum_doc_freq", String.valueOf(sumDocFreq)); valMap.put("sum_total_term_freq", String.valueOf(sumTotalTermFreq)); } } return valMap.toString(); } @Override @SuppressWarnings("unchecked") public void execute(String[] args, PrintStream out) throws Exception { IndexReader r = ctx.getIndexReader(); out.println("readonly mode: " + getContext().isReadOnlyMode()); List<AtomicReaderContext> leaves = r.leaves(); if (args.length == 0) { out.println("numdocs: " + r.numDocs()); out.println("maxdoc: " + r.maxDoc()); out.println("num deleted docs: " + r.numDeletedDocs()); out.println("segment count: " + leaves.size()); HashMap<String, Object[]> fields = new HashMap<String, Object[]>(); for (AtomicReaderContext leaf : leaves) { AtomicReader ar = leaf.reader(); FieldInfos fldInfos = ar.getFieldInfos(); Iterator<FieldInfo> finfoIter = fldInfos.iterator(); Fields flds = ar.fields(); while (finfoIter.hasNext()) { FieldInfo finfo = finfoIter.next(); Object[] data = fields.get(finfo.name); Terms t = flds.terms(finfo.name); if (data == null) { data = new Object[2]; LinkedList<Terms> termsList = new LinkedList<Terms>(); termsList.add(t); data[0] = finfo; data[1] = termsList; fields.put(finfo.name, data); } else { List<Terms> termsList = (List<Terms>) data[1]; termsList.add(t); } } } out.println("number of fields: " + fields.size()); for (Object[] finfo : fields.values()) { out.println(toString(finfo)); } } else { int segid; try { segid = Integer.parseInt(args[0]); if (segid < 0 || segid >= leaves.size()) { throw new IllegalArgumentException("invalid segment"); } } catch (Exception e) { out.println("segment id must be a number betweem 0 and " + (leaves.size() - 1)); return; } AtomicReaderContext leaf = leaves.get(segid); AtomicReader atomicReader = leaf.reader(); out.println("segment " + segid + ": "); out.println("doc base: " + leaf.docBase); out.println("numdocs: " + atomicReader.numDocs()); out.println("maxdoc: " + atomicReader.maxDoc()); out.println("num deleted docs: " + atomicReader.numDeletedDocs()); FieldInfos fields = atomicReader.getFieldInfos(); Fields flds = atomicReader.fields(); out.println("number of fields: " + fields.size()); for (int i = 0; i < fields.size(); ++i) { FieldInfo finfo = fields.fieldInfo(i); Terms te = flds.terms(finfo.name); out.println(toString(new Object[] { finfo, Arrays.asList(te) })); } } out.flush(); } }
package de.bwaldvogel.mongo.backend; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.BadValueException; class Projection { private final Document fields; private final String idField; private final boolean onlyExclusions; Projection(Document fields, String idField) { validateFields(fields); this.fields = fields; this.idField = idField; this.onlyExclusions = onlyExclusions(fields); } Document projectDocument(Document document) { if (document == null) { return null; } Document newDocument = new Document(); // implicitly add _id if not mentioned // http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/#return-the-specified-fields-and-the-id-field-only if (!fields.containsKey(idField)) { newDocument.put(idField, document.get(idField)); } if (onlyExclusions) { newDocument.putAll(document); } for (Entry<String, Object> entry : fields.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); projectField(document, newDocument, key, value); } return newDocument; } private static void validateFields(Document fields) { for (Entry<String, Object> entry : fields.entrySet()) { Object value = entry.getValue(); if (value instanceof Document) { Document document = (Document) value; if (document.size() > 1) { throw new BadValueException(">1 field in obj: " + document.toString(true, "{ ", " }")); } } } } private boolean onlyExclusions(Document fields) { Map<Boolean, Long> result = fields.entrySet().stream() //Special case: if the idField is to be excluded that's always ok: .filter(entry->!(entry.getKey().equals(idField) && !Utils.isTrue(entry.getValue()))) .collect(Collectors.partitioningBy( entry -> Utils.isTrue(fields.get(entry.getKey())), Collectors.counting() )); //Mongo will police that all the entries are inclusions or exclusions. long inclusions = result.get(true); long exclusions = result.get(false); if(inclusions > 0 && exclusions > 0) { throw new BadValueException("Projections cannot have a mix of inclusion and exclusions"); } return exclusions>0; } private static void projectField(Document document, Document newDocument, String key, Object projectionValue) { if (key.contains(Utils.PATH_DELIMITER)) { List<String> pathFragments = Utils.splitPath(key); String mainKey = pathFragments.get(0); String subKey = Utils.joinTail(pathFragments); Object object = document.get(mainKey); // do not project the subdocument if it is not of type Document if (object instanceof Document) { Document subDocument = (Document) newDocument.computeIfAbsent(mainKey, k -> new Document()); projectField((Document) object, subDocument, subKey, projectionValue); } else if (object instanceof List) { List<?> values = (List<?>) object; List<Object> projectedValues = (List<Object>) newDocument.computeIfAbsent(mainKey, k -> new ArrayList<>()); if ("$".equals(subKey) && !values.isEmpty()) { Object firstValue = values.get(0); if (firstValue instanceof Document) { projectedValues.add(firstValue); } } else { if(projectedValues.isEmpty()) { //In this case we're projecting in, so start with empty documents: for (Object value : values) { if (value instanceof Document) { projectedValues.add(new Document()); } //Primatives can never be projected-in. } } //Now loop over the underlying values and project int idx = 0; for (Object value : values) { if (value instanceof Document) { final Document projectedDocument; //If this fails it means the newDocument's list differs from the oldDocuments list projectedDocument = (Document)projectedValues.get(idx); projectField((Document) value, projectedDocument, subKey, projectionValue); idx++; } //Bit of a kludge here: if we're projecting in then we need to count only the Document instances //but if we're projecting away we need to count everything. else if(!Utils.isTrue(projectionValue)) { idx++; } } } } } else { Object value = document.getOrMissing(key); if (projectionValue instanceof Document) { Document projectionDocument = (Document) projectionValue; if (projectionDocument.keySet().equals(Collections.singleton(QueryOperator.ELEM_MATCH.getValue()))) { Document elemMatch = (Document) projectionDocument.get(QueryOperator.ELEM_MATCH.getValue()); projectElemMatch(newDocument, elemMatch, key, value); } else if (projectionDocument.keySet().equals(Collections.singleton("$slice"))) { Object slice = projectionDocument.get("$slice"); projectSlice(newDocument, slice, key, value); } else { throw new IllegalArgumentException("Unsupported projection: " + projectionValue); } } else { if (Utils.isTrue(projectionValue)) { if(!(value instanceof Missing)) { newDocument.put(key, value); } } else { newDocument.remove(key); } } } } private static void projectElemMatch(Document newDocument, Document elemMatch, String key, Object value) { QueryMatcher queryMatcher = new DefaultQueryMatcher(); if (value instanceof List) { ((List<?>) value).stream() .filter(sourceObject -> sourceObject instanceof Document) .filter(sourceObject -> queryMatcher.matches((Document) sourceObject, elemMatch)) .findFirst() .ifPresent(v -> newDocument.put(key, Collections.singletonList(v))); } } private static void projectSlice(Document newDocument, Object slice, String key, Object value) { if (!(value instanceof List)) { newDocument.put(key, value); return; } List<?> values = (List<?>) value; int fromIndex = 0; int toIndex = values.size(); if (slice instanceof Integer) { int num = ((Integer) slice).intValue(); if (num < 0) { fromIndex = values.size() + num; } else { toIndex = num; } } else if (slice instanceof List) { List<?> sliceParams = (List<?>) slice; if (sliceParams.size() != 2) { throw new BadValueException("$slice array wrong size"); } if (sliceParams.get(0) instanceof Number) { fromIndex = ((Number) sliceParams.get(0)).intValue(); } if (fromIndex < 0) { fromIndex += values.size(); } int limit = 0; if (sliceParams.get(1) instanceof Number) { limit = ((Number) sliceParams.get(1)).intValue(); } if (limit <= 0) { throw new BadValueException("$slice limit must be positive"); } toIndex = fromIndex + limit; } else { throw new BadValueException("$slice only supports numbers and [skip, limit] arrays"); } List<?> slicedValue = values.subList(Math.max(0, fromIndex), Math.min(values.size(), toIndex)); newDocument.put(key, slicedValue); } }
package com.sgrailways.giftidea; import android.R; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v4.widget.SimpleCursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import com.google.inject.Inject; import roboguice.fragment.RoboListFragment; import static android.provider.BaseColumns._ID; import static com.sgrailways.giftidea.Database.RecipientsTable.NAME; import static com.sgrailways.giftidea.Database.RecipientsTable.TABLE_NAME; public class RecipientsList extends RoboListFragment { @Inject Database database; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ListAdapter adapter = new SimpleCursorAdapter( this.getActivity(), R.layout.simple_list_item_1, cursor(), new String[]{NAME}, new int[]{R.id.text1} ); setListAdapter(adapter); return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onResume() { ((SimpleCursorAdapter)getListAdapter()).swapCursor(cursor()); super.onResume(); } private Cursor cursor() { SQLiteDatabase rdb = database.getReadableDatabase(); return rdb.query(TABLE_NAME, new String[]{_ID, NAME}, null, null, null, null, NAME + " ASC"); } }
package novoda.lib.sqliteprovider.util; import java.io.*; import java.util.ArrayList; import java.util.List; /** * Parsing .sql files and get single statements suitable for insertion. */ public class SQLFile { private static final String STATEMENT_END_CHARACTER = ";"; private static final String LINE_COMMENT_START_CHARACTERS = " private static final String BLOCK_COMMENT_START_CHARACTERS = "/*"; private static final String BLOCK_COMMENT_END_CHARACTERS = "*/"; private static final String LINE_CONCATENATION_CHARACTER = " "; private List<String> statements; private boolean inComment = false; public void parse(Reader in) throws IOException { BufferedReader reader = new BufferedReader(in); statements = new ArrayList<String>(); String line = null; StringBuilder statement = new StringBuilder(); while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() == 0) { continue; } if (line.startsWith(LINE_COMMENT_START_CHARACTERS)) { continue; } if (line.startsWith(BLOCK_COMMENT_START_CHARACTERS)) { inComment = true; continue; } if (line.endsWith(BLOCK_COMMENT_END_CHARACTERS) && inComment) { inComment = false; continue; } if (inComment) { continue; } statement.append(line); if (!line.endsWith(STATEMENT_END_CHARACTER)) { statement.append(LINE_CONCATENATION_CHARACTER); continue; } statements.add(statement.toString()); statement.setLength(0); } reader.close(); } public List<String> getStatements() { return statements; } public static List<String> statementsFrom(Reader reader) throws IOException { SQLFile file = new SQLFile(); file.parse(reader); return file.getStatements(); } public static List<String> statementsFrom(File sqlfile) throws IOException { FileReader reader = null; try { reader = new FileReader(sqlfile); SQLFile file = new SQLFile(); file.parse(reader); return file.getStatements(); } finally { if (reader != null) { reader.close(); } } } }
package com.sibilantsolutions.grison.demo; import java.net.InetSocketAddress; import javax.swing.JLabel; import com.sibilantsolutions.grison.driver.foscam.net.FoscamSession; import com.sibilantsolutions.grison.evt.AudioHandlerI; import com.sibilantsolutions.grison.ui.Ui; public class Demo { // final static private Logger log = LoggerFactory.getLogger( Demo.class ); static private AudioHandlerI audioHandler = new DemoAudioHandler(); static private JLabel label = new JLabel(); static private DemoImageHandler imageHandler = new DemoImageHandler(); static { imageHandler.setLabel( label ); } static public void demo( final String hostname, final int port, String username, String password ) { Ui.buildUi( label ); FoscamSession session = FoscamSession.connect( new InetSocketAddress( hostname, port ), username, password, audioHandler, imageHandler ); session.audioStart(); // session.talkStart(); session.videoStart(); } }
package com.suse.salt.netapi.client; import com.suse.salt.netapi.AuthModule; import com.suse.salt.netapi.calls.Call; import com.suse.salt.netapi.calls.Client; import com.suse.salt.netapi.calls.wheel.Key; import com.suse.salt.netapi.client.impl.HttpClientConnectionFactory; import com.suse.salt.netapi.config.ClientConfig; import com.suse.salt.netapi.config.ProxySettings; import com.suse.salt.netapi.datatypes.Job; import com.suse.salt.netapi.datatypes.ScheduledJob; import com.suse.salt.netapi.datatypes.Token; import com.suse.salt.netapi.datatypes.cherrypy.Stats; import com.suse.salt.netapi.datatypes.target.Target; import com.suse.salt.netapi.event.EventListener; import com.suse.salt.netapi.event.EventStream; import com.suse.salt.netapi.exception.SaltException; import com.suse.salt.netapi.parser.JsonParser; import com.suse.salt.netapi.results.Return; import com.suse.salt.netapi.results.SSHRawResult; import com.suse.salt.netapi.results.Result; import com.suse.salt.netapi.results.ResultInfoSet; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import java.net.URI; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Salt API client. */ public class SaltClient { /** The configuration object */ private final ClientConfig config = new ClientConfig(); /** The connection factory object */ private final ConnectionFactory connectionFactory; /** The executor for async operations */ private final ExecutorService executor; private final Gson gson = new GsonBuilder().create(); /** * Constructor for connecting to a given URL. * * @param url the Salt API URL */ public SaltClient(URI url) { this(url, new HttpClientConnectionFactory()); } /** * Constructor for connecting to a given URL using a specific connection factory. * * @param url the Salt API URL * @param connectionFactory ConnectionFactory implementation */ public SaltClient(URI url, ConnectionFactory connectionFactory) { this(url, connectionFactory, Executors.newCachedThreadPool()); } /** * Constructor for connecting to a given URL. * * @param url the Salt API URL * @param executor ExecutorService to be used for async operations */ public SaltClient(URI url, ExecutorService executor) { this(url, new HttpClientConnectionFactory(), executor); } /** * Constructor for connecting to a given URL using a specific connection factory. * * @param url the Salt API URL * @param connectionFactory ConnectionFactory implementation * @param executor ExecutorService to be used for async operations */ public SaltClient(URI url, ConnectionFactory connectionFactory, ExecutorService executor) { // Put the URL in the config config.put(ClientConfig.URL, url); this.connectionFactory = connectionFactory; this.executor = executor; } /** * Directly access the configuration. * * @return the configuration object */ public ClientConfig getConfig() { return config; } /** * Configure to use a proxy when connecting to the Salt API. * * @param settings the proxy settings */ public void setProxy(ProxySettings settings) { if (settings.getHostname() != null) { config.put(ClientConfig.PROXY_HOSTNAME, settings.getHostname()); config.put(ClientConfig.PROXY_PORT, settings.getPort()); } if (settings.getUsername() != null) { config.put(ClientConfig.PROXY_USERNAME, settings.getUsername()); if (settings.getPassword() != null) { config.put(ClientConfig.PROXY_PASSWORD, settings.getPassword()); } } } /** * Perform login and return the token. * <p> * {@code POST /login} * * @param username the username * @param password the password * @param eauth the eauth type * @return the authentication token * @throws SaltException if anything goes wrong */ public Token login(final String username, final String password, final AuthModule eauth) throws SaltException { Map<String, String> props = new LinkedHashMap<>(); props.put("username", username); props.put("password", password); props.put("eauth", eauth.getValue()); String payload = gson.toJson(props); Return<List<Token>> result = connectionFactory .create("/login", JsonParser.TOKEN, config) .getResult(payload); // For whatever reason they return a list of tokens here, take the first Token token = result.getResult().get(0); config.put(ClientConfig.TOKEN, token.getToken()); return token; } /** * Asynchronously perform login and return a Future with the token. * <p> * {@code POST /login} * * @param username the username * @param password the password * @param eauth the eauth type * @return Future containing the authentication token */ public Future<Token> loginAsync(final String username, final String password, final AuthModule eauth) { return executor.submit(() -> login(username, password, eauth)); } /** * Perform logout and clear the session token from the config. * <p> * {@code POST /logout} * * @return true if the logout was successful, otherwise false * @throws SaltException if anything goes wrong */ public boolean logout() throws SaltException { Return<String> stringResult = connectionFactory .create("/logout", JsonParser.STRING, config).getResult(""); String logoutMessage = "Your token has been cleared"; boolean result = logoutMessage.equals((stringResult.getResult())); if (result) { config.remove(ClientConfig.TOKEN); } return result; } /** * Asynchronously perform logout and clear the session token from the config. * <p> * {@code POST /logout} * * @return Future containing a boolean result, true if logout was successful */ public Future<Boolean> logoutAsync() { return executor.submit(() -> (Boolean) this.logout()); } public Map<String, Map<String, Object>> getMinions() throws SaltException { return connectionFactory.create("/minions", JsonParser.RETMAPS, config) .getResult().getResult().get(0); } public Future<Map<String, Map<String, Object>>> getMinionsAsync() throws SaltException { return executor.submit(this::getMinions); } public Map<String, Object> getMinionDetails(String minionId) throws SaltException { return connectionFactory.create("/minions/" + minionId, JsonParser.RETMAPS, config) .getResult().getResult().get(0).get(minionId); } public Future<Map<String, Object>> getMinionDetailsAsync(final String minionId) throws SaltException { return executor.submit(() -> getMinionDetails(minionId)); } /** * Generic interface to start any execution command and immediately return an object * representing the scheduled job. * <p> * {@code POST /minions} * * @param <T> type of the tgt property for this command * @param target the target * @param function the function to execute * @param args list of non-keyword arguments * @param kwargs map containing keyword arguments * @return object representing the scheduled job * @throws SaltException if anything goes wrong */ public <T> ScheduledJob startCommand(final Target<T> target, final String function, List<Object> args, Map<String, Object> kwargs) throws SaltException { Map<String, Object> props = new LinkedHashMap<>(); props.put("tgt", target.getTarget()); props.put("expr_form", target.getType()); props.put("fun", function); props.put("arg", args); props.put("kwarg", kwargs); String payload = gson.toJson(Collections.singleton(props)); // Connect to the minions endpoint and send the above lowstate data Return<List<ScheduledJob>> result = connectionFactory .create("/minions", JsonParser.SCHEDULED_JOB, config) .getResult(payload); // They return a list of tokens here, we take the first return result.getResult().get(0); } /** * Asynchronously start any execution command and immediately return an object * representing the scheduled job. * <p> * {@code POST /minions} * * @param <T> type of the tgt property for this command * @param target the target * @param function the function to execute * @param args list of non-keyword arguments * @param kwargs map containing keyword arguments * @return Future containing the scheduled job */ public <T> Future<ScheduledJob> startCommandAsync(final Target<T> target, final String function, final List<Object> args, final Map<String, Object> kwargs) { return executor.submit(() -> startCommand(target, function, args, kwargs)); } /** * Query for the result of a supplied job. * <p> * {@code GET /job/<job-id>} * * @param job {@link ScheduledJob} object representing scheduled job * @return {@link ResultInfoSet} representing result set from minions * @throws SaltException if anything goes wrong */ public ResultInfoSet getJobResult(final ScheduledJob job) throws SaltException { return getJobResult(job.getJid()); } /** * Query for the result of a supplied job. * <p> * {@code GET /job/<job-id>} * * @param job String representing scheduled job * @return {@link ResultInfoSet} representing result set from minions * @throws SaltException if anything goes wrong */ public ResultInfoSet getJobResult(final String job) throws SaltException { return connectionFactory .create("/jobs/" + job, JsonParser.JOB_RESULTS, config) .getResult(); } /** * Get previously run jobs. * <p> * {@code GET /jobs} * * @return map containing run jobs keyed by job id * @throws SaltException if anything goes wrong */ public Map<String, Job> getJobs() throws SaltException { Return<List<Map<String, Job>>> result = connectionFactory .create("/jobs", JsonParser.JOBS, config) .getResult(); return result.getResult().get(0); } /** * Asynchronously get previously run jobs. * <p> * {@code GET /jobs} * * @return Future with a map containing run jobs keyed by job id */ public Future<Map<String, Job>> getJobsAsync() { return executor.submit(this::getJobs); } /** * Generic interface to start any execution command bypassing normal session handling. * <p> * {@code POST /run} * * @param <T> type of the tgt property for this command * @param username the username * @param password the password * @param eauth the eauth type * @param client the client * @param target the target * @param function the function to execute * @param args list of non-keyword arguments * @param kwargs map containing keyword arguments * @return Map key: minion id, value: command result from that minion * @throws SaltException if anything goes wrong */ public <T> Map<String, Object> run(final String username, final String password, final AuthModule eauth, final String client, final Target<T> target, final String function, List<Object> args, Map<String, Object> kwargs) throws SaltException { Map<String, Object> props = new HashMap<>(); props.put("username", username); props.put("password", password); props.put("eauth", eauth.getValue()); props.put("client", client); props.put("tgt", target.getTarget()); props.put("expr_form", target.getType()); props.put("fun", function); props.put("arg", args); props.put("kwarg", kwargs); List<Map<String, Object>> list = Collections.singletonList(props); String payload = gson.toJson(list); Return<List<Map<String, Object>>> result = connectionFactory .create("/run", JsonParser.RUN_RESULTS, config) .getResult(payload); // A list with one element is returned, we take the first return result.getResult().get(0); } public <T> Map<String, Result<SSHRawResult>> runRawSSHCommand(final String command, final Target<T> target) throws SaltException { Map<String, Object> props = new HashMap<>(); props.put("client", Client.SSH.getValue()); props.put("tgt", target.getTarget()); props.put("expr_form", target.getType()); props.put("fun", command); props.put("raw_shell", true); List<Map<String, Object>> list = Collections.singletonList(props); String payload = gson.toJson(list); Return<List<Map<String, Result<SSHRawResult>>>> result = connectionFactory .create("/run", JsonParser.RUNSSHRAW_RESULTS, config).getResult(payload); return result.getResult().get(0); } /** * Asynchronously start any execution command bypassing normal session handling. * <p> * {@code POST /run} * * @param <T> type of the tgt property for this command * @param username the username * @param password the password * @param eauth the eauth type * @param client the client * @param target the target * @param function the function to execute * @param args list of non-keyword arguments * @param kwargs map containing keyword arguments * @return Future containing Map key: minion id, value: command result from that minion */ public <T> Future<Map<String, Object>> runAsync(final String username, final String password, final AuthModule eauth, final String client, final Target<T> target, final String function, final List<Object> args, final Map<String, Object> kwargs) { return executor.submit(() -> run(username, password, eauth, client, target, function, args, kwargs)); } /** * Query statistics from the CherryPy Server. * <p> * {@code GET /stats} * * @return the stats * @throws SaltException if anything goes wrong */ public Stats stats() throws SaltException { return connectionFactory.create("/stats", JsonParser.STATS, config).getResult(); } /** * Asynchronously query statistics from the CherryPy Server. * <p> * {@code GET /stats} * * @return Future containing the stats */ public Future<Stats> statsAsync() { return executor.submit(this::stats); } public Key.Names keys() throws SaltException { return connectionFactory.create("/keys", JsonParser.KEYS, config).getResult() .getResult(); } public Future<Key.Names> keysAsync() { return executor.submit(this::keys); } /** * Returns a WebSocket @ClientEndpoint annotated object connected * to the /ws ServerEndpoint. * <p> * The stream object supports the {@link EventStream} interface which allows the caller * to register/unregister for stream event notifications as well as close the event * stream. * <p> * Note: {@link SaltClient#login(String, String, AuthModule)} or * {@link SaltClient#loginAsync(String, String, AuthModule)} must be called prior * to calling this method. * <p> * {@code GET /events} * * @param listeners event listeners to be added before the stream is initialized * @return the event stream * @throws SaltException in case of an error during websocket stream initialization */ public EventStream events(EventListener... listeners) throws SaltException { return new EventStream(config, listeners); } /** * Trigger an event in Salt with the specified tag and data. * <p> * {@code POST /hook} * * @param eventTag the event tag * @param eventData the event data. Must be valid JSON. * @return the boolean value returned by Salt. If true the event was triggered * successfully. * A value of false is returned only if Salt itself returns false; it does not mean a * communication failure. * @throws SaltException if anything goes wrong */ public boolean sendEvent(String eventTag, String eventData) throws SaltException { String tag = eventTag != null ? eventTag : ""; Map<String, Object> result = connectionFactory .create("/hook/" + tag, JsonParser.MAP, config) .getResult(eventData); return Boolean.TRUE.equals(result.get("success")); } /** * Asynchronously trigger an event in Salt with the specified tag and data. * <p> * {@code POST /hook} * * @param eventTag the event tag * @param eventData the event data. Must be valid JSON. * @return Future containing a boolean value indicating the success or failure of * triggering the event. */ public Future<Boolean> sendEventAsync(final String eventTag, final String eventData) { return executor.submit(() -> { return sendEvent(eventTag, eventData); }); } /** * Generic interface to make a {@link Call} to an endpoint using a given {@link Client}. * * @param <R> the object type that will be returned * @param call the call * @param client the client to use * @param endpoint the endpoint * @param custom map of arguments * @param type return type as a TypeToken * @return the result of the call * @throws SaltException if anything goes wrong */ public <R> R call(Call<?> call, Client client, String endpoint, Optional<Map<String, Object>> custom, TypeToken<R> type) throws SaltException { Map<String, Object> props = new HashMap<>(); props.putAll(call.getPayload()); props.put("client", client.getValue()); custom.ifPresent(props::putAll); List<Map<String, Object>> list = Collections.singletonList(props); String payload = gson.toJson(list); return connectionFactory .create(endpoint, new JsonParser<>(type), config) .getResult(payload); } /** * Convenience method to make a call without arguments. * * @param <R> the object type that will be returned * @param call the call * @param client the client to use * @param endpoint the endpoint * @param type return type as a TypeToken * @return the result of the call * @throws SaltException if anything goes wrong */ public <R> R call(Call<?> call, Client client, String endpoint, TypeToken<R> type) throws SaltException { return call(call, client, endpoint, Optional.empty(), type); } }
package org.mwg.core.chunk.heap; import org.mwg.Constants; import org.mwg.Graph; import org.mwg.Type; import org.mwg.chunk.ChunkType; import org.mwg.chunk.StateChunk; import org.mwg.core.CoreConstants; import org.mwg.base.AbstractExternalAttribute; import org.mwg.plugin.ExternalAttributeFactory; import org.mwg.utility.HashHelper; import org.mwg.utility.Base64; import org.mwg.plugin.NodeStateCallback; import org.mwg.struct.*; import java.util.Arrays; class HeapStateChunk implements StateChunk { private final long _index; private final HeapChunkSpace _space; private int _capacity; private volatile int _size; private long[] _k; private Object[] _v; private int[] _next; private int[] _hash; private byte[] _type; private boolean _dirty; Graph graph() { return _space.graph(); } HeapStateChunk(final HeapChunkSpace p_space, final long p_index) { _space = p_space; _index = p_index; //null hash function _next = null; _hash = null; _type = null; //init to empty size _size = 0; _capacity = 0; _dirty = false; } @Override public final long world() { return _space.worldByIndex(_index); } @Override public final long time() { return _space.timeByIndex(_index); } @Override public final long id() { return _space.idByIndex(_index); } @Override public final byte chunkType() { return ChunkType.STATE_CHUNK; } @Override public final long index() { return _index; } @Override public synchronized final Object get(final long p_key) { return internal_get(p_key); } private int internal_find(final long p_key) { if (_size == 0) { return -1; } else if (_hash == null) { for (int i = 0; i < _size; i++) { if (_k[i] == p_key) { return i; } } return -1; } else { final int hashIndex = (int) HashHelper.longHash(p_key, _capacity * 2); int m = _hash[hashIndex]; while (m >= 0) { if (p_key == _k[m]) { return m; } else { m = _next[m]; } } return -1; } } private Object internal_get(final long p_key) { //empty chunk, we return immediately if (_size == 0) { return null; } int found = internal_find(p_key); Object result; if (found != -1) { result = _v[found]; if (result != null) { switch (_type[found]) { case Type.DOUBLE_ARRAY: double[] castedResultD = (double[]) result; double[] copyD = new double[castedResultD.length]; System.arraycopy(castedResultD, 0, copyD, 0, castedResultD.length); return copyD; case Type.LONG_ARRAY: long[] castedResultL = (long[]) result; long[] copyL = new long[castedResultL.length]; System.arraycopy(castedResultL, 0, copyL, 0, castedResultL.length); return copyL; case Type.INT_ARRAY: int[] castedResultI = (int[]) result; int[] copyI = new int[castedResultI.length]; System.arraycopy(castedResultI, 0, copyI, 0, castedResultI.length); return copyI; default: return result; } } } return null; } @Override public synchronized final void set(final long p_elementIndex, final byte p_elemType, final Object p_unsafe_elem) { internal_set(p_elementIndex, p_elemType, p_unsafe_elem, true, false); } @Override public synchronized final void setFromKey(final String key, final byte p_elemType, final Object p_unsafe_elem) { internal_set(_space.graph().resolver().stringToHash(key, true), p_elemType, p_unsafe_elem, true, false); } @Override public synchronized final Object getFromKey(final String key) { return internal_get(_space.graph().resolver().stringToHash(key, false)); } @Override public final <A> A getFromKeyWithDefault(final String key, final A defaultValue) { final Object result = getFromKey(key); if (result == null) { return defaultValue; } else { return (A) result; } } @Override public final <A> A getWithDefault(final long key, final A defaultValue) { final Object result = get(key); if (result == null) { return defaultValue; } else { return (A) result; } } @Override public synchronized final byte getType(final long p_key) { if (_size == 0) { return -1; } if (_hash == null) { for (int i = 0; i < _capacity; i++) { if (_k[i] == p_key) { return _type[i]; } } } else { int hashIndex = (int) HashHelper.longHash(p_key, _capacity * 2); int m = _hash[hashIndex]; while (m >= 0) { if (p_key == _k[m]) { return _type[m]; } else { m = _next[m]; } } } return -1; } @Override public byte getTypeFromKey(final String key) { return getType(_space.graph().resolver().stringToHash(key, false)); } @Override public synchronized final Object getOrCreate(final long p_key, final byte p_type) { final int found = internal_find(p_key); if (found != -1) { if (_type[found] == p_type) { return _v[found]; } } Object toSet = null; switch (p_type) { case Type.RELATION: toSet = new HeapRelation(this, null); break; case Type.RELATION_INDEXED: toSet = new HeapRelationIndexed(this); break; case Type.MATRIX: toSet = new HeapMatrix(this, null); break; case Type.LMATRIX: toSet = new HeapLMatrix(this, null); break; case Type.EGRAPH: toSet = new HeapEGraph(this); break; case Type.STRING_TO_LONG_MAP: toSet = new HeapStringLongMap(this); break; case Type.LONG_TO_LONG_MAP: toSet = new HeapLongLongMap(this); break; case Type.LONG_TO_LONG_ARRAY_MAP: toSet = new HeapLongLongArrayMap(this); break; } internal_set(p_key, p_type, toSet, true, false); return toSet; } @Override public synchronized Object getOrCreateExternal(long p_key, String externalTypeName) { final int found = internal_find(p_key); if (found != -1) { if (_type[found] == Type.EXTERNAL) { return _v[found]; } } AbstractExternalAttribute toSet = null; final ExternalAttributeFactory factory = _space.graph().externalAttribute(externalTypeName); if (factory != null) { toSet = factory.create(); } internal_set(p_key, Type.EXTERNAL, toSet, true, false); toSet.notifyDirty(() -> declareDirty()); return toSet; } @Override public final Object getOrCreateFromKey(final String key, final byte elemType) { return getOrCreate(_space.graph().resolver().stringToHash(key, true), elemType); } final void declareDirty() { if (_space != null && !_dirty) { _dirty = true; _space.notifyUpdate(_index); } } @Override public synchronized final void save(final Buffer buffer) { Base64.encodeIntToBuffer(_size, buffer); for (int i = 0; i < _size; i++) { if (_v[i] != null) { //there is a real value final Object loopValue = _v[i]; if (loopValue != null) { buffer.write(CoreConstants.CHUNK_SEP); Base64.encodeLongToBuffer(_k[i], buffer); buffer.write(CoreConstants.CHUNK_SUB_SEP); Base64.encodeIntToBuffer(_type[i], buffer); buffer.write(CoreConstants.CHUNK_SUB_SEP); switch (_type[i]) { case Type.STRING: Base64.encodeStringToBuffer((String) loopValue, buffer); break; case Type.BOOL: if ((Boolean) _v[i]) { buffer.write(CoreConstants.BOOL_TRUE); } else { buffer.write(CoreConstants.BOOL_FALSE); } break; case Type.LONG: Base64.encodeLongToBuffer((Long) loopValue, buffer); break; case Type.DOUBLE: Base64.encodeDoubleToBuffer((Double) loopValue, buffer); break; case Type.INT: Base64.encodeIntToBuffer((Integer) loopValue, buffer); break; case Type.DOUBLE_ARRAY: double[] castedDoubleArr = (double[]) loopValue; Base64.encodeIntToBuffer(castedDoubleArr.length, buffer); for (int j = 0; j < castedDoubleArr.length; j++) { buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP); Base64.encodeDoubleToBuffer(castedDoubleArr[j], buffer); } break; case Type.EXTERNAL: AbstractExternalAttribute externalAttribute = (AbstractExternalAttribute) loopValue; final long encodedName = _space.graph().resolver().stringToHash(externalAttribute.name(), false); Base64.encodeLongToBuffer(encodedName, buffer); buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP); String saved = externalAttribute.save(); if (saved != null) { Base64.encodeStringToBuffer(saved, buffer); } break; case Type.RELATION: HeapRelation castedLongArrRel = (HeapRelation) loopValue; Base64.encodeIntToBuffer(castedLongArrRel.size(), buffer); for (int j = 0; j < castedLongArrRel.size(); j++) { buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP); Base64.encodeLongToBuffer(castedLongArrRel.unsafe_get(j), buffer); } break; case Type.LONG_ARRAY: long[] castedLongArr = (long[]) loopValue; Base64.encodeIntToBuffer(castedLongArr.length, buffer); for (int j = 0; j < castedLongArr.length; j++) { buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP); Base64.encodeLongToBuffer(castedLongArr[j], buffer); } break; case Type.INT_ARRAY: int[] castedIntArr = (int[]) loopValue; Base64.encodeIntToBuffer(castedIntArr.length, buffer); for (int j = 0; j < castedIntArr.length; j++) { buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP); Base64.encodeIntToBuffer(castedIntArr[j], buffer); } break; case Type.MATRIX: HeapMatrix castedMatrix = (HeapMatrix) loopValue; final double[] unsafeContent = castedMatrix.unsafe_data(); if (unsafeContent != null) { Base64.encodeIntToBuffer(unsafeContent.length, buffer); for (int j = 0; j < unsafeContent.length; j++) { buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP); Base64.encodeDoubleToBuffer(unsafeContent[j], buffer); } } break; case Type.LMATRIX: HeapLMatrix castedLMatrix = (HeapLMatrix) loopValue; final long[] unsafeLContent = castedLMatrix.unsafe_data(); if (unsafeLContent != null) { Base64.encodeIntToBuffer(unsafeLContent.length, buffer); for (int j = 0; j < unsafeLContent.length; j++) { buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP); Base64.encodeLongToBuffer(unsafeLContent[j], buffer); } } break; case Type.STRING_TO_LONG_MAP: HeapStringLongMap castedStringLongMap = (HeapStringLongMap) loopValue; Base64.encodeLongToBuffer(castedStringLongMap.size(), buffer); castedStringLongMap.unsafe_each(new StringLongMapCallBack() { @Override public void on(final String key, final long value) { buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP); Base64.encodeStringToBuffer(key, buffer); buffer.write(CoreConstants.CHUNK_SUB_SUB_SUB_SEP); Base64.encodeLongToBuffer(value, buffer); } }); break; case Type.LONG_TO_LONG_MAP: HeapLongLongMap castedLongLongMap = (HeapLongLongMap) loopValue; Base64.encodeLongToBuffer(castedLongLongMap.size(), buffer); castedLongLongMap.unsafe_each(new LongLongMapCallBack() { @Override public void on(final long key, final long value) { buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP); Base64.encodeLongToBuffer(key, buffer); buffer.write(CoreConstants.CHUNK_SUB_SUB_SUB_SEP); Base64.encodeLongToBuffer(value, buffer); } }); break; case Type.RELATION_INDEXED: case Type.LONG_TO_LONG_ARRAY_MAP: HeapLongLongArrayMap castedLongLongArrayMap = (HeapLongLongArrayMap) loopValue; Base64.encodeLongToBuffer(castedLongLongArrayMap.size(), buffer); castedLongLongArrayMap.unsafe_each(new LongLongArrayMapCallBack() { @Override public void on(final long key, final long value) { buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP); Base64.encodeLongToBuffer(key, buffer); buffer.write(CoreConstants.CHUNK_SUB_SUB_SUB_SEP); Base64.encodeLongToBuffer(value, buffer); } }); break; default: break; } } } } _dirty = false; } @Override public void saveDiff(Buffer buffer) { } @Override public synchronized final void each(final NodeStateCallback callBack) { for (int i = 0; i < _size; i++) { if (_v[i] != null) { callBack.on(_k[i], _type[i], _v[i]); } } } @Override public synchronized void loadFrom(final StateChunk origin) { if (origin == null) { return; } HeapStateChunk casted = (HeapStateChunk) origin; _capacity = casted._capacity; _size = casted._size; //copy keys if (casted._k != null) { long[] cloned_k = new long[_capacity]; System.arraycopy(casted._k, 0, cloned_k, 0, _capacity); _k = cloned_k; } //copy values /* Object[] cloned_v = new Object[_capacity]; System.arraycopy(casted._v, 0, cloned_v, 0, _capacity); _v = cloned_v; */ //copy types if (casted._type != null) { byte[] cloned_type = new byte[_capacity]; System.arraycopy(casted._type, 0, cloned_type, 0, _capacity); _type = cloned_type; } //copy next if not empty if (casted._next != null) { int[] cloned_next = new int[_capacity]; System.arraycopy(casted._next, 0, cloned_next, 0, _capacity); _next = cloned_next; } if (casted._hash != null) { int[] cloned_hash = new int[_capacity * 2]; System.arraycopy(casted._hash, 0, cloned_hash, 0, _capacity * 2); _hash = cloned_hash; } if (casted._v != null) { _v = new Object[_capacity]; for (int i = 0; i < _size; i++) { switch (casted._type[i]) { case Type.LONG_TO_LONG_MAP: if (casted._v[i] != null) { _v[i] = ((HeapLongLongMap) casted._v[i]).cloneFor(this); } break; case Type.RELATION_INDEXED: if (casted._v[i] != null) { _v[i] = ((HeapRelationIndexed) casted._v[i]).cloneIRelFor(this); } break; case Type.LONG_TO_LONG_ARRAY_MAP: if (casted._v[i] != null) { _v[i] = ((HeapLongLongArrayMap) casted._v[i]).cloneFor(this); } break; case Type.STRING_TO_LONG_MAP: if (casted._v[i] != null) { _v[i] = ((HeapStringLongMap) casted._v[i]).cloneFor(this); } break; case Type.RELATION: if (casted._v[i] != null) { _v[i] = new HeapRelation(this, (HeapRelation) casted._v[i]); } break; case Type.MATRIX: if (casted._v[i] != null) { _v[i] = new HeapMatrix(this, (HeapMatrix) casted._v[i]); } break; case Type.LMATRIX: if (casted._v[i] != null) { _v[i] = new HeapLMatrix(this, (HeapLMatrix) casted._v[i]); } break; case Type.EXTERNAL: if (casted._v[i] != null) { _v[i] = ((AbstractExternalAttribute) casted._v[i]).copy(); } break; default: _v[i] = casted._v[i]; break; } } } } private void internal_set(final long p_key, final byte p_type, final Object p_unsafe_elem, boolean replaceIfPresent, boolean initial) { Object param_elem = null; //check the param type if (p_unsafe_elem != null) { try { switch (p_type) { case Type.BOOL: param_elem = (boolean) p_unsafe_elem; break; case Type.INT: if (p_unsafe_elem instanceof Integer) { param_elem = (int) p_unsafe_elem; } else if (p_unsafe_elem instanceof Double) { double preCasting = (Double) p_unsafe_elem; param_elem = (int) preCasting; } else if (p_unsafe_elem instanceof Long) { long preCastingLong = (Long) p_unsafe_elem; param_elem = (int) preCastingLong; } else if (p_unsafe_elem instanceof Float) { float preCastingLong = (Float) p_unsafe_elem; param_elem = (int) preCastingLong; } else if (p_unsafe_elem instanceof Byte) { byte preCastingLong = (Byte) p_unsafe_elem; param_elem = (int) preCastingLong; } else { param_elem = (int) p_unsafe_elem; } break; case Type.DOUBLE: if (p_unsafe_elem instanceof Double) { param_elem = (double) p_unsafe_elem; } else if (p_unsafe_elem instanceof Integer) { int preCasting = (Integer) p_unsafe_elem; param_elem = (double) preCasting; } else if (p_unsafe_elem instanceof Long) { long preCastingLong = (Long) p_unsafe_elem; param_elem = (double) preCastingLong; } else if (p_unsafe_elem instanceof Float) { float preCastingLong = (Float) p_unsafe_elem; param_elem = (double) preCastingLong; } else if (p_unsafe_elem instanceof Byte) { byte preCastingLong = (Byte) p_unsafe_elem; param_elem = (double) preCastingLong; } else { param_elem = (double) p_unsafe_elem; } break; case Type.LONG: if (p_unsafe_elem instanceof Long) { param_elem = (long) p_unsafe_elem; } else if (p_unsafe_elem instanceof Integer) { int preCasting = (Integer) p_unsafe_elem; param_elem = (long) preCasting; } else if (p_unsafe_elem instanceof Double) { double preCastingLong = (Double) p_unsafe_elem; param_elem = (long) preCastingLong; } else if (p_unsafe_elem instanceof Float) { float preCastingLong = (Float) p_unsafe_elem; param_elem = (long) preCastingLong; } else if (p_unsafe_elem instanceof Byte) { byte preCastingLong = (Byte) p_unsafe_elem; param_elem = (long) preCastingLong; } else { param_elem = (long) p_unsafe_elem; } break; case Type.STRING: param_elem = (String) p_unsafe_elem; break; case Type.MATRIX: param_elem = (Matrix) p_unsafe_elem; break; case Type.LMATRIX: param_elem = (LMatrix) p_unsafe_elem; break; case Type.RELATION: param_elem = (Relation) p_unsafe_elem; break; case Type.EXTERNAL: param_elem = p_unsafe_elem; break; case Type.DOUBLE_ARRAY: double[] castedParamDouble = (double[]) p_unsafe_elem; double[] clonedDoubleArray = new double[castedParamDouble.length]; System.arraycopy(castedParamDouble, 0, clonedDoubleArray, 0, castedParamDouble.length); param_elem = clonedDoubleArray; break; case Type.LONG_ARRAY: long[] castedParamLong = (long[]) p_unsafe_elem; long[] clonedLongArray = new long[castedParamLong.length]; System.arraycopy(castedParamLong, 0, clonedLongArray, 0, castedParamLong.length); param_elem = clonedLongArray; break; case Type.INT_ARRAY: int[] castedParamInt = (int[]) p_unsafe_elem; int[] clonedIntArray = new int[castedParamInt.length]; System.arraycopy(castedParamInt, 0, clonedIntArray, 0, castedParamInt.length); param_elem = clonedIntArray; break; case Type.STRING_TO_LONG_MAP: param_elem = (StringLongMap) p_unsafe_elem; break; case Type.LONG_TO_LONG_MAP: param_elem = (LongLongMap) p_unsafe_elem; break; case Type.LONG_TO_LONG_ARRAY_MAP: param_elem = (LongLongArrayMap) p_unsafe_elem; break; case Type.RELATION_INDEXED: param_elem = (RelationIndexed) p_unsafe_elem; break; case Type.EGRAPH: param_elem = (EGraph) p_unsafe_elem; break; default: throw new RuntimeException("Internal Exception, unknown type"); } } catch (Exception e) { throw new RuntimeException("mwDB usage error, set method called with type " + Type.typeName(p_type) + " while param object is " + p_unsafe_elem); } } //first value if (_k == null) { //we do not allocate for empty element if (param_elem == null) { return; } _capacity = Constants.MAP_INITIAL_CAPACITY; _k = new long[_capacity]; _v = new Object[_capacity]; _type = new byte[_capacity]; _k[0] = p_key; _v[0] = param_elem; _type[0] = p_type; _size = 1; if (!initial) { declareDirty(); } return; } int entry = -1; int p_entry = -1; int hashIndex = -1; if (_hash == null) { for (int i = 0; i < _size; i++) { if (_k[i] == p_key) { entry = i; break; } } } else { hashIndex = (int) HashHelper.longHash(p_key, _capacity * 2); int m = _hash[hashIndex]; while (m != -1) { if (_k[m] == p_key) { entry = m; break; } p_entry = m; m = _next[m]; } } //case already present if (entry != -1) { if (replaceIfPresent || (p_type != _type[entry])) { if (param_elem == null) { if (_hash != null) { //unHash previous if (p_entry != -1) { _next[p_entry] = _next[entry]; } else { _hash[hashIndex] = -1; } } int indexVictim = _size - 1; //just pop the last value if (entry == indexVictim) { _k[entry] = -1; _v[entry] = null; _type[entry] = -1; } else { //we need to reHash the new last element at our place _k[entry] = _k[indexVictim]; _v[entry] = _v[indexVictim]; _type[entry] = _type[indexVictim]; if (_hash != null) { _next[entry] = _next[indexVictim]; int victimHash = (int) HashHelper.longHash(_k[entry], _capacity * 2); int m = _hash[victimHash]; if (m == indexVictim) { //the victim was the head of hashing list _hash[victimHash] = entry; } else { //the victim is in the next, reChain it while (m != -1) { if (_next[m] == indexVictim) { _next[m] = entry; break; } m = _next[m]; } } } } _size } else { _v[entry] = param_elem; if (_type[entry] != p_type) { _type[entry] = p_type; } } } if (!initial) { declareDirty(); } return; } if (_size < _capacity) { _k[_size] = p_key; _v[_size] = param_elem; _type[_size] = p_type; if (_hash != null) { _next[_size] = _hash[hashIndex]; _hash[hashIndex] = _size; } _size++; declareDirty(); return; } //extend capacity int newCapacity = _capacity * 2; long[] ex_k = new long[newCapacity]; System.arraycopy(_k, 0, ex_k, 0, _capacity); _k = ex_k; Object[] ex_v = new Object[newCapacity]; System.arraycopy(_v, 0, ex_v, 0, _capacity); _v = ex_v; byte[] ex_type = new byte[newCapacity]; System.arraycopy(_type, 0, ex_type, 0, _capacity); _type = ex_type; _capacity = newCapacity; //insert the next _k[_size] = p_key; _v[_size] = param_elem; _type[_size] = p_type; _size++; //reHash _hash = new int[_capacity * 2]; Arrays.fill(_hash, 0, _capacity * 2, -1); _next = new int[_capacity]; Arrays.fill(_next, 0, _capacity, -1); for (int i = 0; i < _size; i++) { int keyHash = (int) HashHelper.longHash(_k[i], _capacity * 2); _next[i] = _hash[keyHash]; _hash[keyHash] = i; } if (!initial) { declareDirty(); } } private void allocate(int newCapacity) { if (newCapacity <= _capacity) { return; } long[] ex_k = new long[newCapacity]; if (_k != null) { System.arraycopy(_k, 0, ex_k, 0, _capacity); } _k = ex_k; Object[] ex_v = new Object[newCapacity]; if (_v != null) { System.arraycopy(_v, 0, ex_v, 0, _capacity); } _v = ex_v; byte[] ex_type = new byte[newCapacity]; if (_type != null) { System.arraycopy(_type, 0, ex_type, 0, _capacity); } _type = ex_type; _capacity = newCapacity; _hash = new int[_capacity * 2]; Arrays.fill(_hash, 0, _capacity * 2, -1); _next = new int[_capacity]; Arrays.fill(_next, 0, _capacity, -1); for (int i = 0; i < _size; i++) { int keyHash = (int) HashHelper.longHash(_k[i], _capacity * 2); _next[i] = _hash[keyHash]; _hash[keyHash] = i; } } @Override public final synchronized void load(final Buffer buffer) { if (buffer == null || buffer.length() == 0) { return; } final boolean initial = _k == null; //reset size int cursor = 0; long payloadSize = buffer.length(); int previousStart = -1; long currentChunkElemKey = CoreConstants.NULL_LONG; byte currentChunkElemType = -1; //init detections boolean isFirstElem = true; //array sub creation variable double[] currentDoubleArr = null; long[] currentLongArr = null; int[] currentIntArr = null; //map sub creation variables HeapMatrix currentMatrix = null; HeapLMatrix currentLMatrix = null; HeapRelation currentRelation = null; HeapStringLongMap currentStringLongMap = null; HeapLongLongMap currentLongLongMap = null; HeapLongLongArrayMap currentLongLongArrayMap = null; //array variables long currentSubSize = -1; int currentSubIndex = 0; //map key variables long currentMapLongKey = CoreConstants.NULL_LONG; String currentMapStringKey = null; while (cursor < payloadSize) { byte current = buffer.read(cursor); if (current == CoreConstants.CHUNK_SEP) { if (isFirstElem) { //initial the map isFirstElem = false; final int stateChunkSize = Base64.decodeToIntWithBounds(buffer, 0, cursor); final int closePowerOfTwo = (int) Math.pow(2, Math.ceil(Math.log(stateChunkSize) / Math.log(2))); allocate(closePowerOfTwo); previousStart = cursor + 1; } else { if (currentChunkElemType != -1) { Object toInsert = null; switch (currentChunkElemType) { case Type.BOOL: if (buffer.read(previousStart) == CoreConstants.BOOL_FALSE) { toInsert = false; } else if (buffer.read(previousStart) == CoreConstants.BOOL_TRUE) { toInsert = true; } break; case Type.STRING: toInsert = Base64.decodeToStringWithBounds(buffer, previousStart, cursor); break; case Type.DOUBLE: toInsert = Base64.decodeToDoubleWithBounds(buffer, previousStart, cursor); break; case Type.LONG: toInsert = Base64.decodeToLongWithBounds(buffer, previousStart, cursor); break; case Type.INT: toInsert = Base64.decodeToIntWithBounds(buffer, previousStart, cursor); break; case Type.DOUBLE_ARRAY: if (currentDoubleArr == null) { currentDoubleArr = new double[Base64.decodeToIntWithBounds(buffer, previousStart, cursor)]; } else { currentDoubleArr[currentSubIndex] = Base64.decodeToDoubleWithBounds(buffer, previousStart, cursor); } toInsert = currentDoubleArr; break; case Type.LONG_ARRAY: if (currentLongArr == null) { currentLongArr = new long[Base64.decodeToIntWithBounds(buffer, previousStart, cursor)]; } else { currentLongArr[currentSubIndex] = Base64.decodeToLongWithBounds(buffer, previousStart, cursor); } toInsert = currentLongArr; break; case Type.INT_ARRAY: if (currentIntArr == null) { currentIntArr = new int[Base64.decodeToIntWithBounds(buffer, previousStart, cursor)]; } else { currentIntArr[currentSubIndex] = Base64.decodeToIntWithBounds(buffer, previousStart, cursor); } toInsert = currentIntArr; break; case Type.RELATION: if (currentRelation == null) { currentRelation = new HeapRelation(this, null); currentRelation.allocate(Base64.decodeToIntWithBounds(buffer, previousStart, cursor)); } else { currentRelation.add(Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); } toInsert = currentRelation; break; case Type.MATRIX: if (currentMatrix == null) { currentMatrix = new HeapMatrix(this, null); currentMatrix.unsafe_init(Base64.decodeToIntWithBounds(buffer, previousStart, cursor)); } else { currentMatrix.unsafe_set(currentSubIndex, Base64.decodeToDoubleWithBounds(buffer, previousStart, cursor)); } toInsert = currentMatrix; break; case Type.LMATRIX: if (currentLMatrix == null) { currentLMatrix = new HeapLMatrix(this, null); currentLMatrix.unsafe_init(Base64.decodeToIntWithBounds(buffer, previousStart, cursor)); } else { currentLMatrix.unsafe_set(currentSubIndex, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); } toInsert = currentLMatrix; break; case Type.STRING_TO_LONG_MAP: if (currentMapStringKey != null) { currentStringLongMap.put(currentMapStringKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); } toInsert = currentStringLongMap; break; case Type.LONG_TO_LONG_MAP: if (currentMapLongKey != CoreConstants.NULL_LONG) { currentLongLongMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); } toInsert = currentLongLongMap; break; case Type.RELATION_INDEXED: case Type.LONG_TO_LONG_ARRAY_MAP: if (currentMapLongKey != CoreConstants.NULL_LONG) { currentLongLongArrayMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); } toInsert = currentLongLongArrayMap; break; } if (toInsert != null) { //insert K/V internal_set(currentChunkElemKey, currentChunkElemType, toInsert, true, initial); //enhance this with boolean array } } //next round, reset all variables... previousStart = cursor + 1; currentChunkElemKey = CoreConstants.NULL_LONG; currentChunkElemType = -1; currentSubSize = -1; currentSubIndex = 0; currentMapLongKey = CoreConstants.NULL_LONG; currentMapStringKey = null; } } else if (current == CoreConstants.CHUNK_SUB_SEP) { //SEPARATION BETWEEN KEY,TYPE,VALUE if (currentChunkElemKey == CoreConstants.NULL_LONG) { currentChunkElemKey = Base64.decodeToLongWithBounds(buffer, previousStart, cursor); previousStart = cursor + 1; } else if (currentChunkElemType == -1) { currentChunkElemType = (byte) Base64.decodeToIntWithBounds(buffer, previousStart, cursor); previousStart = cursor + 1; } } else if (current == CoreConstants.CHUNK_SUB_SUB_SEP) { //SEPARATION BETWEEN ARRAY VALUES AND MAP KEY/VALUE TUPLES if (currentSubSize == -1) { currentSubSize = Base64.decodeToLongWithBounds(buffer, previousStart, cursor); //init array or maps switch (currentChunkElemType) { case Type.DOUBLE_ARRAY: currentDoubleArr = new double[(int) currentSubSize]; break; case Type.LONG_ARRAY: currentLongArr = new long[(int) currentSubSize]; break; case Type.INT_ARRAY: currentIntArr = new int[(int) currentSubSize]; break; case Type.RELATION: currentRelation = new HeapRelation(this, null); currentRelation.allocate((int) currentSubSize); break; case Type.MATRIX: currentMatrix = new HeapMatrix(this, null); currentMatrix.unsafe_init((int) currentSubSize); break; case Type.LMATRIX: currentLMatrix = new HeapLMatrix(this, null); currentLMatrix.unsafe_init((int) currentSubSize); break; case Type.STRING_TO_LONG_MAP: currentStringLongMap = new HeapStringLongMap(this); currentStringLongMap.reallocate((int) currentSubSize); break; case Type.LONG_TO_LONG_MAP: currentLongLongMap = new HeapLongLongMap(this); currentLongLongMap.reallocate((int) currentSubSize); break; case Type.LONG_TO_LONG_ARRAY_MAP: currentLongLongArrayMap = new HeapLongLongArrayMap(this); currentLongLongArrayMap.reallocate((int) currentSubSize); break; case Type.RELATION_INDEXED: currentLongLongArrayMap = new HeapRelationIndexed(this); currentLongLongArrayMap.reallocate((int) currentSubSize); break; } } else { switch (currentChunkElemType) { case Type.DOUBLE_ARRAY: currentDoubleArr[currentSubIndex] = Base64.decodeToDoubleWithBounds(buffer, previousStart, cursor); currentSubIndex++; break; case Type.RELATION: currentRelation.add(Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); break; case Type.MATRIX: currentMatrix.unsafe_set(currentSubIndex, Base64.decodeToDoubleWithBounds(buffer, previousStart, cursor)); currentSubIndex++; break; case Type.LMATRIX: currentLMatrix.unsafe_set(currentSubIndex, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); currentSubIndex++; break; case Type.LONG_ARRAY: currentLongArr[currentSubIndex] = Base64.decodeToLongWithBounds(buffer, previousStart, cursor); currentSubIndex++; break; case Type.INT_ARRAY: currentIntArr[currentSubIndex] = Base64.decodeToIntWithBounds(buffer, previousStart, cursor); currentSubIndex++; break; case Type.STRING_TO_LONG_MAP: if (currentMapStringKey != null) { currentStringLongMap.put(currentMapStringKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); currentMapStringKey = null; } break; case Type.LONG_TO_LONG_MAP: if (currentMapLongKey != CoreConstants.NULL_LONG) { currentLongLongMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); currentMapLongKey = CoreConstants.NULL_LONG; } break; case Type.RELATION_INDEXED: case Type.LONG_TO_LONG_ARRAY_MAP: if (currentMapLongKey != CoreConstants.NULL_LONG) { currentLongLongArrayMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); currentMapLongKey = CoreConstants.NULL_LONG; } break; } } previousStart = cursor + 1; } else if (current == CoreConstants.CHUNK_SUB_SUB_SUB_SEP) { switch (currentChunkElemType) { case Type.STRING_TO_LONG_MAP: if (currentMapStringKey == null) { currentMapStringKey = Base64.decodeToStringWithBounds(buffer, previousStart, cursor); } else { currentStringLongMap.put(currentMapStringKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); //reset key for next loop currentMapStringKey = null; } break; case Type.LONG_TO_LONG_MAP: if (currentMapLongKey == CoreConstants.NULL_LONG) { currentMapLongKey = Base64.decodeToLongWithBounds(buffer, previousStart, cursor); } else { currentLongLongMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); //reset key for next loop currentMapLongKey = CoreConstants.NULL_LONG; } break; case Type.RELATION_INDEXED: case Type.LONG_TO_LONG_ARRAY_MAP: if (currentMapLongKey == CoreConstants.NULL_LONG) { currentMapLongKey = Base64.decodeToLongWithBounds(buffer, previousStart, cursor); } else { currentLongLongArrayMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); //reset key for next loop currentMapLongKey = CoreConstants.NULL_LONG; } break; } previousStart = cursor + 1; } cursor++; } //take the last element if (currentChunkElemType != -1) { Object toInsert = null; switch (currentChunkElemType) { case Type.BOOL: if (buffer.read(previousStart) == CoreConstants.BOOL_FALSE) { toInsert = false; } else if (buffer.read(previousStart) == CoreConstants.BOOL_TRUE) { toInsert = true; } break; case Type.STRING: toInsert = Base64.decodeToStringWithBounds(buffer, previousStart, cursor); break; case Type.DOUBLE: toInsert = Base64.decodeToDoubleWithBounds(buffer, previousStart, cursor); break; case Type.LONG: toInsert = Base64.decodeToLongWithBounds(buffer, previousStart, cursor); break; case Type.INT: toInsert = Base64.decodeToIntWithBounds(buffer, previousStart, cursor); break; case Type.DOUBLE_ARRAY: if (currentDoubleArr == null) { currentDoubleArr = new double[Base64.decodeToIntWithBounds(buffer, previousStart, cursor)]; } else { currentDoubleArr[currentSubIndex] = Base64.decodeToDoubleWithBounds(buffer, previousStart, cursor); } toInsert = currentDoubleArr; break; case Type.LONG_ARRAY: if (currentLongArr == null) { currentLongArr = new long[Base64.decodeToIntWithBounds(buffer, previousStart, cursor)]; } else { currentLongArr[currentSubIndex] = Base64.decodeToLongWithBounds(buffer, previousStart, cursor); } toInsert = currentLongArr; break; case Type.INT_ARRAY: if (currentIntArr == null) { currentIntArr = new int[Base64.decodeToIntWithBounds(buffer, previousStart, cursor)]; } else { currentIntArr[currentSubIndex] = Base64.decodeToIntWithBounds(buffer, previousStart, cursor); } toInsert = currentIntArr; break; case Type.RELATION: if (currentRelation != null) { currentRelation.add(Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); } toInsert = currentRelation; break; case Type.MATRIX: if (currentMatrix != null) { currentMatrix.unsafe_set(currentSubIndex, Base64.decodeToDoubleWithBounds(buffer, previousStart, cursor)); } toInsert = currentMatrix; break; case Type.LMATRIX: if (currentLMatrix != null) { currentLMatrix.unsafe_set(currentSubIndex, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); } toInsert = currentLMatrix; break; case Type.STRING_TO_LONG_MAP: if (currentMapStringKey != null) { currentStringLongMap.put(currentMapStringKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); } toInsert = currentStringLongMap; break; case Type.LONG_TO_LONG_MAP: if (currentMapLongKey != CoreConstants.NULL_LONG) { currentLongLongMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); } toInsert = currentLongLongMap; break; case Type.RELATION_INDEXED: case Type.LONG_TO_LONG_ARRAY_MAP: if (currentMapLongKey != CoreConstants.NULL_LONG) { currentLongLongArrayMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor)); } toInsert = currentLongLongArrayMap; break; } if (toInsert != null) { internal_set(currentChunkElemKey, currentChunkElemType, toInsert, true, initial); //enhance this with boolean array } } } @Override public void loadDiff(Buffer buffer) { //TODO } }
package com.tkhoon.framework; import com.tkhoon.framework.bean.ActionBean; import com.tkhoon.framework.bean.Page; import com.tkhoon.framework.bean.RequestBean; import com.tkhoon.framework.bean.Result; import com.tkhoon.framework.exception.AccessException; import com.tkhoon.framework.exception.UploadException; import com.tkhoon.framework.helper.ActionHelper; import com.tkhoon.framework.helper.BeanHelper; import com.tkhoon.framework.helper.ConfigHelper; import com.tkhoon.framework.helper.UploadHelper; import com.tkhoon.framework.util.CastUtil; import com.tkhoon.framework.util.MapUtil; import com.tkhoon.framework.util.StringUtil; import com.tkhoon.framework.util.WebUtil; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package soot.jimple; import soot.*; import soot.util.Chain; import java.util.*; /** Implementation of the Body class for the Jimple IR. */ public class JimpleBody extends StmtBody { /** Construct an empty JimpleBody **/ JimpleBody(SootMethod m) { super(m); } /** Construct an extremely empty JimpleBody, for parsing into. **/ JimpleBody() { } /** Clones the current body, making deep copies of the contents. */ public Object clone() { Body b = new JimpleBody(getMethod()); b.importBodyContentsFrom(this); return b; } /** Make sure that the JimpleBody is well formed. If not, throw * an exception. Right now, performs only a handful of checks. */ public void validate() { super.validate(); validateIdentityStatements(); } /** * Checks the following invariants on this Jimple body: * <ol> * <li> this-references may only occur in instance methods * <li> this-references may only occur as the first statement in a method, if they occur at all * <li> param-references must precede all statements that are not themselves param-references or this-references, * if they occur at all * </ol> */ public void validateIdentityStatements() { if (method.isAbstract()) return; Body body=method.getActiveBody(); Chain<Unit> units=body.getUnits().getNonPatchingChain(); boolean foundNonThisOrParamIdentityStatement = false; boolean firstStatement = true; for (Unit unit : units) { if(unit instanceof IdentityStmt) { IdentityStmt identityStmt = (IdentityStmt) unit; if(identityStmt.getRightOp() instanceof ThisRef) { if(method.isStatic()) { throw new RuntimeException("@this-assignment in a static method!"); } if(!firstStatement) { throw new RuntimeException("@this-assignment statement should precede all other statements"); } } else if(identityStmt.getRightOp() instanceof ParameterRef) { if(foundNonThisOrParamIdentityStatement) { throw new RuntimeException("@param-assignment statements should precede all non-identity statements"); } } else { //@caughtexception statement foundNonThisOrParamIdentityStatement = true; } } else { //non-identity statement foundNonThisOrParamIdentityStatement = true; } firstStatement = false; } } /** Inserts usual statements for handling this & parameters into body. */ public void insertIdentityStmts() { int i = 0; if (!getMethod().isStatic()) { Local l = Jimple.v().newLocal("this", RefType.v(getMethod().getDeclaringClass())); getLocals().add(l); getUnits().addFirst(Jimple.v().newIdentityStmt(l, Jimple.v().newThisRef((RefType)l.getType()))); } Iterator parIt = getMethod().getParameterTypes().iterator(); while (parIt.hasNext()) { Type t = (Type)parIt.next(); Local l = Jimple.v().newLocal("parameter"+i, t); getLocals().add(l); getUnits().addFirst(Jimple.v().newIdentityStmt(l, Jimple.v().newParameterRef(l.getType(), i))); i++; } } /** Returns the first non-identity stmt in this body. */ public Stmt getFirstNonIdentityStmt() { Iterator it = getUnits().iterator(); Object o = null; while (it.hasNext()) if (!((o = it.next()) instanceof IdentityStmt)) break; if (o == null) throw new RuntimeException("no non-id statements!"); return (Stmt)o; } }
package com.github.ruediste.laf.core; import java.io.IOException; import java.io.PrintWriter; import javax.inject.Inject; import javax.servlet.http.HttpServletResponse; import com.github.ruediste.laf.core.front.ReloadCountHolder; import com.github.ruediste.laf.core.httpRequest.HttpRequest; import com.github.ruediste.laf.core.web.assetPipeline.AssetPipelineConfiguration; import com.github.ruediste.laf.core.web.assetPipeline.AssetRequestMapper; import com.github.ruediste.laf.util.Initializer; public class CoreDynamicInitializer implements Initializer { @Inject CoreConfiguration config; @Inject AssetPipelineConfiguration pipelineConfig; @Inject AssetRequestMapper assetRequestMapper; @Inject PathInfoIndex index; @Inject ReloadCountHolder holder; @Inject CoreRequestInfo info; @Override public void initialize() { config.dynamicClassLoader = Thread.currentThread() .getContextClassLoader(); config.initialize(); pipelineConfig.initialize(); assetRequestMapper.initialize(); index.registerPathInfo("/~reloadQuery", new RequestParser() { @Override public RequestParseResult parse(HttpRequest request) { return new RequestParseResult() { @Override public void handle() { boolean doReload = holder.waitForReload(Long .parseLong(request.getParameter("nr"))); HttpServletResponse response = info .getServletResponse(); response.setContentType("text/plain;charset=utf-8"); PrintWriter out; try { out = response.getWriter(); out.write(doReload ? "true" : "false"); out.close(); } catch (IOException e) { throw new RuntimeException("Error sending response"); } } }; } }); } }
package crazypants.enderio.fluid; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.apache.commons.lang3.StringUtils; import crazypants.enderio.EnderIO; import crazypants.enderio.ModObject; import crazypants.enderio.config.Config; import net.minecraft.block.Block; import net.minecraft.block.BlockFire; import net.minecraft.block.BlockLiquid; import net.minecraft.block.material.Material; import net.minecraft.block.material.MaterialLiquid; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.VertexBuffer; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.init.MobEffects; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.potion.PotionEffect; import net.minecraft.util.DamageSource; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing.Axis; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.client.event.EntityViewRenderEvent; import net.minecraftforge.client.event.RenderBlockOverlayEvent; import net.minecraftforge.client.event.RenderBlockOverlayEvent.OverlayType; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fluids.BlockFluidClassic; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.IFluidBlock; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.relauncher.ReflectionHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import static crazypants.enderio.config.Config.rocketFuelIsExplosive; public class BlockFluidEio extends BlockFluidClassic { public static BlockFluidEio create(Fluid fluid, Material material, int fogColor) { BlockFluidEio res; if (fluid == Fluids.fluidFireWater) { res = new FireWater(fluid, material, fogColor); } else if (fluid == Fluids.fluidHootch) { res = new Hootch(fluid, material, fogColor); } else if (fluid == Fluids.fluidRocketFuel) { res = new RocketFuel(fluid, material, fogColor); } else if (fluid == Fluids.fluidNutrientDistillation) { res = new NutrientDistillation(fluid, material, fogColor); } else if (fluid == Fluids.fluidLiquidSunshine) { res = new LiquidSunshine(fluid, material, fogColor); } else if (fluid == Fluids.fluidCloudSeedConcentrated) { res = new CloudSeedConcentrated(fluid, material, fogColor); } else if (fluid == Fluids.fluidVaporOfLevity) { res = new VaporOfLevity(fluid, material, fogColor); } else { res = new BlockFluidEio(fluid, material, fogColor); } res.init(); fluid.setBlock(res); return res; } public static BlockFluidEio createMetal(Fluid fluid, Material material, int fogColor) { BlockFluidEio res = new MoltenMetal(fluid, material, fogColor); res.init(); fluid.setBlock(res); return res; } protected final Fluid fluid; protected float fogColorRed = 1; protected float fogColorGreen = 1; protected float fogColorBlue = 1; protected BlockFluidEio(Fluid fluid, Material material, int fogColor) { super(fluid, new MaterialLiquid(material.getMaterialMapColor()) { // new Material for each liquid so neighboring different liquids render correctly and don't bleed into each other @Override public boolean blocksMovement() { return true; // so our liquids are not replaced by water } }); this.fluid = fluid; // darken fog color to fit the fog rendering float dim = 1; while (fogColorRed > .2f || fogColorGreen > .2f || fogColorBlue > .2f) { fogColorRed = (fogColor >> 16 & 255) / 255f * dim; fogColorGreen = (fogColor >> 8 & 255) / 255f * dim; fogColorBlue = (fogColor & 255) / 255f * dim; dim *= .9f; } setNames(fluid); } protected void setNames(Fluid fluid) { setUnlocalizedName(fluid.getUnlocalizedName()); setRegistryName("block" + StringUtils.capitalize(fluid.getName())); } protected void init() { GameRegistry.register(this); } // START VISUALS static { MinecraftForge.EVENT_BUS.register(BlockFluidEio.class); } // net.minecraft.client.renderer.EntityRenderer.getNightVisionBrightness(EntityLivingBase, float) is private :-( @SideOnly(Side.CLIENT) private static float getNightVisionBrightness(EntityLivingBase entitylivingbaseIn, float partialTicks) { @SuppressWarnings("null") int i = entitylivingbaseIn.getActivePotionEffect(MobEffects.NIGHT_VISION).getDuration(); return i > 200 ? 1.0F : 0.7F + MathHelper.sin((i - partialTicks) * (float) Math.PI * 0.2F) * 0.3F; } @Override public Boolean isEntityInsideMaterial(IBlockAccess world, BlockPos blockpos, IBlockState iblockstate, Entity entity, double yToTest, Material materialIn, boolean testingHead) { if (materialIn == Material.WATER || materialIn == this.blockMaterial) { return Boolean.TRUE; } return super.isEntityInsideMaterial(world, blockpos, iblockstate, entity, yToTest, materialIn, testingHead); } private static Field FfogColor1, FfogColor2, FbossColorModifier, FbossColorModifierPrev, FcloudFog; @SubscribeEvent @SideOnly(Side.CLIENT) public static void onFOVModifier(EntityViewRenderEvent.FOVModifier event) { if (event.getState() instanceof BlockFluidEio) { event.setFOV(event.getFOV() * 60.0F / 70.0F); } } private static final ResourceLocation RES_UNDERFLUID_OVERLAY = new ResourceLocation(EnderIO.DOMAIN, "textures/misc/underfluid.png"); @SubscribeEvent @SideOnly(Side.CLIENT) public static void onRenderBlockOverlay(RenderBlockOverlayEvent event) { if (event.getOverlayType() == OverlayType.WATER) { final EntityPlayer player = event.getPlayer(); // the event has the wrong BlockPos (entity center instead of eyes) final BlockPos blockpos = new BlockPos(player.posX, player.posY + player.getEyeHeight(), player.posZ); final Block block = player.worldObj.getBlockState(blockpos).getBlock(); if (block instanceof BlockFluidEio) { float fogColorRed = ((BlockFluidEio) block).fogColorRed; float fogColorGreen = ((BlockFluidEio) block).fogColorGreen; float fogColorBlue = ((BlockFluidEio) block).fogColorBlue; Minecraft.getMinecraft().getTextureManager().bindTexture(RES_UNDERFLUID_OVERLAY); Tessellator tessellator = Tessellator.getInstance(); VertexBuffer vertexbuffer = tessellator.getBuffer(); float f = player.getBrightness(event.getRenderPartialTicks()); GlStateManager.color(f * fogColorRed, f * fogColorGreen, f * fogColorBlue, 0.5F); GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); GlStateManager.pushMatrix(); float f7 = -player.rotationYaw / 64.0F; float f8 = player.rotationPitch / 64.0F; vertexbuffer.begin(7, DefaultVertexFormats.POSITION_TEX); vertexbuffer.pos(-1.0D, -1.0D, -0.5D).tex(4.0F + f7, 4.0F + f8).endVertex(); vertexbuffer.pos(1.0D, -1.0D, -0.5D).tex(0.0F + f7, 4.0F + f8).endVertex(); vertexbuffer.pos(1.0D, 1.0D, -0.5D).tex(0.0F + f7, 0.0F + f8).endVertex(); vertexbuffer.pos(-1.0D, 1.0D, -0.5D).tex(4.0F + f7, 0.0F + f8).endVertex(); tessellator.draw(); GlStateManager.popMatrix(); GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); GlStateManager.disableBlend(); event.setCanceled(true); } } } @SubscribeEvent @SideOnly(Side.CLIENT) public static void onFogDensity(EntityViewRenderEvent.FogDensity event) throws IllegalArgumentException, IllegalAccessException { if (FcloudFog == null) { FcloudFog = ReflectionHelper.findField(EntityRenderer.class, "cloudFog", "field_78500_U"); } if (event.getState() instanceof BlockFluidEio) { final EntityRenderer renderer = event.getRenderer(); final Entity entity = event.getEntity(); final boolean cloudFog = FcloudFog.getBoolean(renderer); // again the event is fired at a bad location... if (entity instanceof EntityLivingBase && ((EntityLivingBase) entity).isPotionActive(MobEffects.BLINDNESS)) { return; } else if (cloudFog) { return; } GlStateManager.setFog(GlStateManager.FogMode.EXP); if (entity instanceof EntityLivingBase) { if (((EntityLivingBase) entity).isPotionActive(MobEffects.WATER_BREATHING)) { event.setDensity(0.01F); } else { event.setDensity(0.1F - EnchantmentHelper.getRespirationModifier((EntityLivingBase) entity) * 0.03F); } } else { event.setDensity(0.1F); } } } @SubscribeEvent @SideOnly(Side.CLIENT) public static void onFogColor(EntityViewRenderEvent.FogColors event) throws IllegalArgumentException, IllegalAccessException { if (FfogColor1 == null || FfogColor2 == null || FbossColorModifier == null || FbossColorModifierPrev == null) { FfogColor1 = ReflectionHelper.findField(EntityRenderer.class, "fogColor1", "field_78539_ae"); FfogColor2 = ReflectionHelper.findField(EntityRenderer.class, "fogColor2", "field_78535_ad"); FbossColorModifier = ReflectionHelper.findField(EntityRenderer.class, "bossColorModifier", "field_82831_U"); FbossColorModifierPrev = ReflectionHelper.findField(EntityRenderer.class, "bossColorModifierPrev", "field_82832_V"); } if (event.getState().getBlock() instanceof BlockFluidEio) { float fogColorRed = ((BlockFluidEio) event.getState().getBlock()).fogColorRed; float fogColorGreen = ((BlockFluidEio) event.getState().getBlock()).fogColorGreen; float fogColorBlue = ((BlockFluidEio) event.getState().getBlock()).fogColorBlue; // the following was copied as-is from net.minecraft.client.renderer.EntityRenderer.updateFogColor() because that %&!$ Forge event is fired after the // complete fog color calculation is done final EntityRenderer renderer = event.getRenderer(); final float fogColor1 = FfogColor1.getFloat(renderer); final float fogColor2 = FfogColor2.getFloat(renderer); final float partialTicks = (float) event.getRenderPartialTicks(); final Entity entity = event.getEntity(); final World world = entity.getEntityWorld(); final float bossColorModifier = FbossColorModifier.getFloat(renderer); final float bossColorModifierPrev = FbossColorModifierPrev.getFloat(renderer); float f12 = 0.0F; if (entity instanceof EntityLivingBase) { f12 = EnchantmentHelper.getRespirationModifier((EntityLivingBase) entity) * 0.2F; if (((EntityLivingBase) entity).isPotionActive(MobEffects.WATER_BREATHING)) { f12 = f12 * 0.3F + 0.6F; } } fogColorRed += f12; fogColorGreen += f12; fogColorBlue += f12; float f13 = fogColor2 + (fogColor1 - fogColor2) * partialTicks; fogColorRed *= f13; fogColorGreen *= f13; fogColorBlue *= f13; double d1 = (entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks) * world.provider.getVoidFogYFactor(); if (entity instanceof EntityLivingBase && ((EntityLivingBase) entity).isPotionActive(MobEffects.BLINDNESS)) { @SuppressWarnings("null") int i = ((EntityLivingBase) entity).getActivePotionEffect(MobEffects.BLINDNESS).getDuration(); if (i < 20) { d1 *= 1.0F - i / 20.0F; } else { d1 = 0.0D; } } if (d1 < 1.0D) { if (d1 < 0.0D) { d1 = 0.0D; } d1 = d1 * d1; fogColorRed = (float) (fogColorRed * d1); fogColorGreen = (float) (fogColorGreen * d1); fogColorBlue = (float) (fogColorBlue * d1); } if (bossColorModifier > 0.0F) { float f14 = bossColorModifierPrev + (bossColorModifier - bossColorModifierPrev) * partialTicks; fogColorRed = fogColorRed * (1.0F - f14) + fogColorRed * 0.7F * f14; fogColorGreen = fogColorGreen * (1.0F - f14) + fogColorGreen * 0.6F * f14; fogColorBlue = fogColorBlue * (1.0F - f14) + fogColorBlue * 0.6F * f14; } if (entity instanceof EntityLivingBase && ((EntityLivingBase) entity).isPotionActive(MobEffects.NIGHT_VISION)) { float f15 = getNightVisionBrightness((EntityLivingBase) entity, partialTicks); float f6 = 1.0F / fogColorRed; if (f6 > 1.0F / fogColorGreen) { f6 = 1.0F / fogColorGreen; } if (f6 > 1.0F / fogColorBlue) { f6 = 1.0F / fogColorBlue; } fogColorRed = fogColorRed * (1.0F - f15) + fogColorRed * f6 * f15; fogColorGreen = fogColorGreen * (1.0F - f15) + fogColorGreen * f6 * f15; fogColorBlue = fogColorBlue * (1.0F - f15) + fogColorBlue * f6 * f15; } if (Minecraft.getMinecraft().gameSettings.anaglyph) { float f16 = (fogColorRed * 30.0F + fogColorGreen * 59.0F + fogColorBlue * 11.0F) / 100.0F; float f17 = (fogColorRed * 30.0F + fogColorGreen * 70.0F) / 100.0F; float f7 = (fogColorRed * 30.0F + fogColorBlue * 70.0F) / 100.0F; fogColorRed = f16; fogColorGreen = f17; fogColorBlue = f7; } event.setRed(fogColorRed); event.setGreen(fogColorGreen); event.setBlue(fogColorBlue); } } // END VISUALS @Override public boolean canDisplace(IBlockAccess world, BlockPos pos) { IBlockState bs = world.getBlockState(pos); if (bs.getMaterial().isLiquid()) { return false; } return super.canDisplace(world, pos); } @Override public boolean displaceIfPossible(World world, BlockPos pos) { IBlockState bs = world.getBlockState(pos); if (bs.getMaterial().isLiquid()) { return false; } return super.displaceIfPossible(world, pos); } @Override @SideOnly(Side.CLIENT) public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list) { if (tab != null) { super.getSubBlocks(itemIn, tab, list); } } // Fire Water private static class FireWater extends BlockFluidEio { protected FireWater(Fluid fluid, Material material, int fogColor) { super(fluid, material, fogColor); } @Override public void onEntityCollidedWithBlock(World world, BlockPos pos, IBlockState state, Entity entity) { if (!world.isRemote) { entity.setFire(50); } super.onEntityCollidedWithBlock(world, pos, state, entity); } @Override public boolean isFlammable(IBlockAccess world, BlockPos pos, EnumFacing face) { return true; } @Override public boolean isFireSource(World world, BlockPos pos, EnumFacing side) { return true; } @Override public int getFireSpreadSpeed(IBlockAccess world, BlockPos pos, EnumFacing face) { return 60; } } // Hootch private static class Hootch extends BlockFluidEio { protected Hootch(Fluid fluid, Material material, int fogColor) { super(fluid, material, fogColor); } @Override public void onEntityCollidedWithBlock(World world, BlockPos pos, IBlockState state, Entity entity) { if (!world.isRemote && entity instanceof EntityLivingBase) { ((EntityLivingBase) entity).addPotionEffect(new PotionEffect(MobEffects.NAUSEA, 150, 0, true, true)); } super.onEntityCollidedWithBlock(world, pos, state, entity); } @Override public boolean isFlammable(IBlockAccess world, BlockPos pos, EnumFacing face) { return true; } @Override public boolean isFireSource(World world, BlockPos pos, EnumFacing side) { return true; } @Override public int getFlammability(IBlockAccess world, BlockPos pos, EnumFacing face) { return 1; } @Override public int getFireSpreadSpeed(IBlockAccess world, BlockPos pos, EnumFacing face) { return 60; } } // Rocket Fuel private static class RocketFuel extends BlockFluidEio { protected RocketFuel(Fluid fluid, Material material, int fogColor) { super(fluid, material, fogColor); } @Override public void onEntityCollidedWithBlock(World world, BlockPos pos, IBlockState state, Entity entity) { if (!world.isRemote && entity instanceof EntityLivingBase) { ((EntityLivingBase) entity).addPotionEffect(new PotionEffect(MobEffects.JUMP_BOOST, 150, 3, true, true)); } super.onEntityCollidedWithBlock(world, pos, state, entity); } @Override public boolean isFlammable(IBlockAccess world, BlockPos pos, EnumFacing face) { return true; } @Override public boolean isFireSource(World world, BlockPos pos, EnumFacing side) { return true; } @Override public int getFireSpreadSpeed(IBlockAccess world, BlockPos pos, EnumFacing face) { return 60; } @Override public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn) { checkForFire(worldIn, pos); super.neighborChanged(state, worldIn, pos, blockIn); } protected void checkForFire(World worldIn, BlockPos pos) { if (rocketFuelIsExplosive) { for (EnumFacing side : EnumFacing.values()) { IBlockState neighbor = worldIn.getBlockState(pos.offset(side)); if (neighbor.getBlock() instanceof BlockFire && neighbor.getBlock() != ModObject.blockColdFire.getBlock()) { if (worldIn.rand.nextFloat() < .5f) { List<BlockPos> explosions = new ArrayList<BlockPos>(); explosions.add(pos); BlockPos up = pos.up(); while (worldIn.getBlockState(up).getBlock() == this) { explosions.add(up); up = up.up(); } if (isSourceBlock(worldIn, pos)) { worldIn.newExplosion(null, pos.getX() + .5f, pos.getY() + .5f, pos.getZ() + .5f, 2, true, true); } float strength = .5f; for (BlockPos explosion : explosions) { worldIn.newExplosion(null, explosion.getX() + .5f, explosion.getY() + .5f, explosion.getZ() + .5f, strength, true, true); strength = Math.min(strength * 1.05f, 7f); } return; } } } } } @Override public void updateTick(World world, BlockPos pos, IBlockState state, Random rand) { checkForFire(world, pos); super.updateTick(world, pos, state, rand); } } // Nutrient Distillation private static class NutrientDistillation extends BlockFluidEio { protected NutrientDistillation(Fluid fluid, Material material, int fogColor) { super(fluid, material, fogColor); } @Override public void onEntityCollidedWithBlock(World world, BlockPos pos, IBlockState state, Entity entity) { if (!world.isRemote && entity instanceof EntityPlayerMP) { long time = entity.worldObj.getTotalWorldTime(); EntityPlayerMP player = (EntityPlayerMP) entity; if (time % Config.nutrientFoodBoostDelay == 0 && player.getEntityData().getLong("eioLastFoodBoost") != time) { player.getFoodStats().addStats(1, 0.1f); player.getEntityData().setLong("eioLastFoodBoost", time); } } super.onEntityCollidedWithBlock(world, pos, state, entity); } } // Liquid Sunshine private static class LiquidSunshine extends BlockFluidEio { protected LiquidSunshine(Fluid fluid, Material material, int fogColor) { super(fluid, material, fogColor); } @Override public void onEntityCollidedWithBlock(World world, BlockPos pos, IBlockState state, Entity entity) { if (!world.isRemote && entity instanceof EntityLivingBase) { ((EntityLivingBase) entity).addPotionEffect(new PotionEffect(MobEffects.LEVITATION, 50, 0, true, true)); ((EntityLivingBase) entity).addPotionEffect(new PotionEffect(MobEffects.GLOWING, 1200, 0, true, true)); } super.onEntityCollidedWithBlock(world, pos, state, entity); } } // Cloud Seed, Concentrated private static class CloudSeedConcentrated extends BlockFluidEio { protected CloudSeedConcentrated(Fluid fluid, Material material, int fogColor) { super(fluid, material, fogColor); } @Override public void onEntityCollidedWithBlock(World world, BlockPos pos, IBlockState state, Entity entity) { if (!world.isRemote && entity instanceof EntityLivingBase) { ((EntityLivingBase) entity).addPotionEffect(new PotionEffect(MobEffects.BLINDNESS, 40, 0, true, true)); } super.onEntityCollidedWithBlock(world, pos, state, entity); } } // Vapor Of Levity private static class VaporOfLevity extends BlockFluidEio { protected VaporOfLevity(Fluid fluid, Material material, int fogColor) { super(fluid, material, fogColor); } @Override public void onEntityCollidedWithBlock(World world, BlockPos pos, IBlockState state, Entity entity) { if (entity instanceof EntityPlayer || (!world.isRemote && entity instanceof EntityLivingBase)) { ((EntityLivingBase) entity).motionY += 0.1; } super.onEntityCollidedWithBlock(world, pos, state, entity); } private static final int[] COLORS = { 0x0c82d0, 0x90c8ec, 0x5174ed, 0x0d2f65, 0x4accee }; @Override @SideOnly(Side.CLIENT) public void randomDisplayTick(IBlockState state, World worldIn, BlockPos pos, Random rand) { if (rand.nextFloat() < .5f) { final EnumFacing face = EnumFacing.values()[rand.nextInt(EnumFacing.values().length)]; final BlockPos neighborPos = pos.offset(face); final IBlockState neighborState = worldIn.getBlockState(neighborPos); if (!neighborState.isFullCube()) { double xd = face.getFrontOffsetX() == 0 ? rand.nextDouble() : face.getFrontOffsetX() < 0 ? -0.05 : 1.05; double yd = face.getFrontOffsetY() == 0 ? rand.nextDouble() : face.getFrontOffsetY() < 0 ? -0.05 : 1.05; double zd = face.getFrontOffsetZ() == 0 ? rand.nextDouble() : face.getFrontOffsetZ() < 0 ? -0.05 : 1.05; double x = pos.getX() + xd; double y = pos.getY() + yd; double z = pos.getZ() + zd; int col = COLORS[rand.nextInt(COLORS.length)]; worldIn.spawnParticle(EnumParticleTypes.REDSTONE, x, y, z, (col >> 16 & 255) / 255d, (col >> 8 & 255) / 255d, (col & 255) / 255d); } } } @Override public void updateTick(World world, BlockPos pos, IBlockState state, Random rand) { if (!world.isRemote && rand.nextFloat() < .1f) { final BlockPos neighborPos = getNeighbor(pos, rand); final IBlockState neighborState = world.getBlockState(neighborPos); final Block neighborBlock = neighborState.getBlock(); final BlockPos belowNeighborPos = neighborPos.down(); if (neighborBlock != Blocks.SNOW_LAYER && !(neighborBlock instanceof IFluidBlock) && !(neighborBlock instanceof BlockLiquid) && neighborBlock.isReplaceable(world, neighborPos) && world.getBlockState(belowNeighborPos).isSideSolid(world, belowNeighborPos, EnumFacing.UP)) { world.setBlockState(neighborPos, Blocks.SNOW_LAYER.getDefaultState()); } else if (neighborBlock == Blocks.WATER && neighborState.getValue(BlockLiquid.LEVEL) == 0 && world.canBlockBePlaced(Blocks.ICE, neighborPos, false, EnumFacing.DOWN, (Entity) null, (ItemStack) null)) { world.setBlockState(neighborPos, Blocks.ICE.getDefaultState()); } } super.updateTick(world, pos, state, rand); if (!world.isUpdateScheduled(pos, this)) { world.scheduleUpdate(pos, this, tickRate * 10); } } protected BlockPos getNeighbor(BlockPos pos, Random rand) { EnumFacing face = EnumFacing.values()[rand.nextInt(EnumFacing.values().length)]; if (face.getAxis() != Axis.Y && rand.nextBoolean()) { return pos.offset(face).offset(face.rotateY()); } else { return pos.offset(face); } } @Override public float getFluidHeightForRender(IBlockAccess world, BlockPos pos) { IBlockState down = world.getBlockState(pos.down()); if (down.getMaterial().isLiquid() || down.getBlock() instanceof IFluidBlock) { return 1; } else { return 0.995F; } } } // Molten Metal private static class MoltenMetal extends BlockFluidEio { protected MoltenMetal(Fluid fluid, Material material, int fogColor) { super(fluid, material, fogColor); } @Override public void onEntityCollidedWithBlock(World world, BlockPos pos, IBlockState state, Entity entity) { if (!world.isRemote && !entity.isImmuneToFire()) { entity.attackEntityFrom(DamageSource.lava, 4.0F); entity.setFire(15); } super.onEntityCollidedWithBlock(world, pos, state, entity); } @Override public Boolean isEntityInsideMaterial(IBlockAccess world, BlockPos blockpos, IBlockState iblockstate, Entity entity, double yToTest, Material materialIn, boolean testingHead) { if (materialIn == Material.LAVA || materialIn == this.blockMaterial) { return Boolean.TRUE; } // Note: There's no callback for Entity.isInLava(), so just pretend we're also WATER. It has some drawbacks, but we don't really expect people to go // swimming in molten metals, do we? return super.isEntityInsideMaterial(world, blockpos, iblockstate, entity, yToTest, materialIn, testingHead); } } // TiC Fluids public static abstract class TicFluids extends BlockFluidEio { protected TicFluids(Fluid fluid, Material material, int fogColor) { super(fluid, material, fogColor); } @Override protected void setNames(Fluid fluid) { setUnlocalizedName(fluid.getUnlocalizedName()); setRegistryName("fluid" + StringUtils.capitalize(fluid.getName())); } } // Molten Glowstone public static class MoltenGlowstone extends TicFluids { public MoltenGlowstone(Fluid fluid, Material material, int fogColor) { // 0xffbc5e super(fluid, material, fogColor); } @Override public void onEntityCollidedWithBlock(World world, BlockPos pos, IBlockState state, Entity entity) { if (!world.isRemote && entity instanceof EntityLivingBase) { ((EntityLivingBase) entity).addPotionEffect(new PotionEffect(MobEffects.LEVITATION, 200, 0, true, true)); ((EntityLivingBase) entity).addPotionEffect(new PotionEffect(MobEffects.GLOWING, 2400, 0, true, true)); } super.onEntityCollidedWithBlock(world, pos, state, entity); } @Override public void init() { super.init(); } } // Molten Redstone public static class MoltenRedstone extends TicFluids { public MoltenRedstone(Fluid fluid, Material material, int fogColor) { // 0xff0000 super(fluid, material, fogColor); } @Override public void onEntityCollidedWithBlock(World world, BlockPos pos, IBlockState state, Entity entity) { if (!world.isRemote && entity instanceof EntityLivingBase) { ((EntityLivingBase) entity).addPotionEffect(new PotionEffect(MobEffects.HASTE, 20 * 60, 0, true, true)); ((EntityLivingBase) entity).addPotionEffect(new PotionEffect(MobEffects.JUMP_BOOST, 20 * 60, 0, true, true)); ((EntityLivingBase) entity).addPotionEffect(new PotionEffect(MobEffects.SPEED, 20 * 60, 0, true, true)); ((EntityLivingBase) entity).addPotionEffect(new PotionEffect(MobEffects.HUNGER, 20 * 60, 0, true, true)); } super.onEntityCollidedWithBlock(world, pos, state, entity); } @Override public void init() { super.init(); } } // Molten Ender public static class MoltenEnder extends TicFluids { private static final Random rand = new Random(); private static final ResourceLocation SOUND = new ResourceLocation("entity.endermen.teleport"); public MoltenEnder(Fluid fluid, Material material, int fogColor) { // 0xff0000 super(fluid, material, fogColor); } @Override public void onEntityCollidedWithBlock(World world, BlockPos pos, IBlockState state, Entity entity) { if (!world.isRemote && entity.timeUntilPortal == 0) { teleportEntity(world, entity); } super.onEntityCollidedWithBlock(world, pos, state, entity); } private void teleportEntity(World world, Entity entity) { double origX = entity.posX, origY = entity.posY, origZ = entity.posZ; for (int i = 0; i < 5; i++) { double targetX = origX + rand.nextGaussian() * 16f; double targetY = -1; while (targetY < 1.1) { targetY = origY + rand.nextGaussian() * 8f; } double targetZ = origZ + rand.nextGaussian() * 16f; entity.setPosition(targetX, targetY, targetZ); if (isClear(world, entity)) { entity.setPosition(origX, origY, origZ); if (entity instanceof EntityPlayerMP) { ((EntityPlayerMP) entity).connection.setPlayerLocation(targetX, targetY, targetZ, entity.rotationYaw, entity.rotationPitch); } else { entity.setPositionAndRotation(targetX, targetY, targetZ, entity.rotationYaw, entity.rotationPitch); } final SoundEvent sound = SoundEvent.REGISTRY.getObject(SOUND); if (sound != null) { world.playSound(null, origX, origY, origZ, sound, SoundCategory.BLOCKS, 1, 1); world.playSound(null, targetX, targetY, targetZ, sound, SoundCategory.BLOCKS, 1, 1); } entity.timeUntilPortal = 5; return; } } entity.setPosition(origX, origY, origZ); } private boolean isClear(World world, Entity entity) { return world.checkNoEntityCollision(entity.getEntityBoundingBox(), entity) && world.getCollisionBoxes(entity, entity.getEntityBoundingBox()).isEmpty(); } @Override public void init() { super.init(); } } }
package pt.fccn.saw.selenium; import java.net.URL; import java.util.concurrent.TimeUnit; import java.util.NoSuchElementException; import pt.fccn.saw.selenium.RetryRule; import java.util.ArrayList; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.By; import org.openqa.selenium.remote.*; import com.saucelabs.common.SauceOnDemandAuthentication; import pt.fccn.saw.selenium.SauceHelpers; import org.junit.*; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.openqa.selenium.remote.CapabilityType; import com.saucelabs.junit.ConcurrentParameterized; import com.saucelabs.junit.SauceOnDemandTestWatcher; import java.net.URL; import java.util.LinkedList; import org.json.*; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import com.saucelabs.common.SauceOnDemandSessionIdProvider; //import org.json.*; /** * The base class for tests using WebDriver to test specific browsers. * This test read system properties to know which browser to test or, * if tests are te be run remotely, it also read login information and * the browser, browser version and OS combination to be used. * * The WebDriver tests provide the more precise results without the * restrictions present in selenium due to browers' security models. */ @Ignore @RunWith(ConcurrentParameterized.class) public class WebDriverTestBaseParalell implements SauceOnDemandSessionIdProvider{ public String username = System.getenv("SAUCE_USERNAME"); public String accesskey = System.getenv("SAUCE_ACCESS_KEY"); public static String seleniumURI; public static String buildTag; /** * Constructs a {@link SauceOnDemandAuthentication} instance using the supplied user name/access key. To use the authentication * supplied by environment variables or from an external file, use the no-arg {@link SauceOnDemandAuthentication} constructor. */ public SauceOnDemandAuthentication authentication = new SauceOnDemandAuthentication(username, accesskey); /** * JUnit Rule which will mark the Sauce Job as passed/failed when the test succeeds or fails. */ @Rule public SauceOnDemandTestWatcher resultReportingTestWatcher = new SauceOnDemandTestWatcher(this, authentication); @Rule public TestName name = new TestName() { public String getMethodName() { return String.format("%s", super.getMethodName()); } }; /** * Test decorated with @Retry will be run 3 times in case they fail using this rule. */ @Rule public RetryRule rule = new RetryRule(3); /** * Represents the browser to be used as part of the test run. */ protected String browser; /** * Represents the operating system to be used as part of the test run. */ protected String os; /** * Represents the version of the browser to be used as part of the test run. */ protected String version; /** * Represents the deviceName of mobile device */ protected String deviceName; /** * Represents the device-orientation of mobile device */ protected String deviceOrientation; /** * Instance variable which contains the Sauce Job Id. */ protected String sessionId; protected WebDriver driver; //protected static ArrayList<WebDriver> drivers; protected static String testURL; protected static String browserVersion; protected static String titleOfFirstResult; protected static String pre_prod="preprod"; //protected static String pre_prod="p24"; protected static boolean Ispre_prod=false; public WebDriverTestBaseParalell(String os, String version, String browser, String deviceName, String deviceOrientation) { super(); this.os = os; this.version = version; this.browser = browser; this.deviceName = deviceName; this.deviceOrientation = deviceOrientation; testURL = System.getProperty("test.url"); System.out.println("OS: " + os); System.out.println("Version: " + version); System.out.println("Browser: " + browser); System.out.println("Device: " +deviceName); System.out.println("Orientation: " + deviceOrientation); } /** * @return a LinkedList containing String arrays representing the browser combinations the test should be run against. The values * in the String array are used as part of the invocation of the test constructor */ @ConcurrentParameterized.Parameters public static LinkedList browsersStrings() { String browsersJSON = System.getenv("SAUCE_ONDEMAND_BROWSERS"); LinkedList browsers = new LinkedList(); System.out.println("JSON: " + browsersJSON); JSONObject browsersJSONObject = new JSONObject("{browsers:"+browsersJSON+"}"); JSONArray browsersJSONArray = browsersJSONObject.getJSONArray("browsers"); if(browsersJSON == null){ System.out.println("You did not specify browsers, testing with firefox and chrome..."); browsers.add(new String[]{"Windows 7", "41", "chrome", null, null}); browsers.add(new String[]{"Windows 8.1", "46", "firefox", null, null}); } else{ for (int i = 0; i < browsersJSONArray.length(); i++) { //TODO:: find names of extra properties for mobile Devices such as orientation and device name JSONObject browserConfigs = browsersJSONArray.getJSONObject(i); String browserOS = browsersJSONArray.getJSONString("os"); String browserPlatform= browsersJSONArray.getJSONString("platform"); String browserName= browsersJSONArray.getJSONString("browser"); String browserVersion = browsersJSONArray.getJSONString("browser-version"); browsers.add(new String[]{browserOS, browserVersion, browserName, null, null}); } } // windows xp, IE 8 //browsers.add(new String[]{"Windows XP", "8", "internet explorer", null, null}); // OS X 10.8, Safari 6 // browsers.add(new String[]{"OSX 10.8", "6", "safari", null, null}); return browsers; } /** * Constructs a new {@link RemoteWebDriver} instance which is configured to use the capabilities defined by the {@link #browser}, * {@link #version} and {@link #os} instance variables, and which is configured to run against ondemand.saucelabs.com, using * the username and access key populated by the {@link #authentication} instance. * * @throws Exception if an error occurs during the creation of the {@link RemoteWebDriver} instance. */ @Before public void setUp() throws Exception { System.out.println("USER: " + username); System.out.println("PASS: " + accesskey); DesiredCapabilities capabilities = new DesiredCapabilities(); if (browser != null) capabilities.setCapability(CapabilityType.BROWSER_NAME, browser); if (version != null) capabilities.setCapability(CapabilityType.VERSION, version); if (deviceName != null) capabilities.setCapability("deviceName", deviceName); if (deviceOrientation != null) capabilities.setCapability("device-orientation", deviceOrientation); capabilities.setCapability(CapabilityType.PLATFORM, os); String methodName = name.getMethodName() + " " + browser + " " + version; capabilities.setCapability("name", methodName); //Getting the build name. //Using the Jenkins ENV var. You can use your own. If it is not set test will run without a build id. if (buildTag != null) { capabilities.setCapability("build", buildTag); } SauceHelpers.addSauceConnectTunnelId(capabilities); this.driver = new RemoteWebDriver( new URL("https://" + username+ ":" + accesskey + seleniumURI +"/wd/hub"), capabilities); this.driver.get(testURL); this.sessionId = (((RemoteWebDriver) driver).getSessionId()).toString(); String message = String.format("SauceOnDemandSessionID=%1$s job-name=%2$s", this.sessionId, methodName); System.out.println(message); } /** * This method is run before each test. * It sets the browsers to the starting test url */ @Before public void preTest() { //for(WebDriver d: drivers) driver.get(testURL); } /** * Releases the resources used for the tests, i.e., * It closes the WebDriver. */ @After public void tearDown() throws Exception { driver.quit(); } /** * Creates a Local WebDriver given a string with the web browser name. * * @param browser The browser name for the WebDriver initialization * @return The initialized Local WebDriver */ private static WebDriver selectLocalBrowser(String browser) throws java.net.MalformedURLException{ WebDriver driver = null; if (browser.contains("firefox")) { driver = new FirefoxDriver(); } else if (browser.contains("iexplorer")) { driver = new InternetExplorerDriver(); } else if (browser.contains("chrome")) { //DesiredCapabilities capabilities = DesiredCapabilities.chrome(); //capabilities.setCapability("chrome.binary", "/usr/lib/chromium-browser/chromium-browser"); //driver = new ChromeDriver(capabilities); driver = new ChromeDriver(); } else if (browser.contains("opera")) { driver = new OperaDriver(); } else if (browser.contains("remote-chrome")) { DesiredCapabilities capabilities = DesiredCapabilities.chrome(); driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities); } else if (browser.contains("remote-firefox")) { DesiredCapabilities capabilities = DesiredCapabilities.firefox(); driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities); driver.get("http: } else { // OH NOEZ! I DOAN HAZ DAT BROWSR! System.err.println("Cannot find suitable browser driver for ["+ browser +"]"); } return driver; } /** * Gets a suitable Platform object given a OS/Platform string.. * * @param platformString The given string for the OS/Platform to use * @return The Platform object that represent the requested OS/Platform */ private static Platform selectPlatform(String platformString) { Platform platform = null; if (platformString.contains("Windows")) { if (platformString.contains("2008")) { platform = Platform.VISTA; } else { platform = Platform.XP; } } else if (platformString.toLowerCase().equals("linux")){ platform = Platform.LINUX; } else { System.err.println("Cannot find a suitable platform/OS for ["+ platformString +"]"); } return platform; } /** * Miscellaneous cleaning for browser and browser's version strings. * @param browser The browser string to clean * @param browserVersion The browser version string to clean */ private static void parameterCleanupForRemote(String browser, String browserVersion) { // Selenium1 likes to prepend a "*" to browser string. if (browser.startsWith("*")) { browser = browser.substring(1); } // SauceLabs doesn't use version numbering for Google Chrome due to // the fast release schedule of that browser. if (browser.contains("googlechrome")) { browserVersion = ""; } } /** * Utility class to obtain the Class name in a static context. */ public static class CurrentClassGetter extends SecurityManager { public String getClassName() { return getClassContext()[1].getName(); } } @BeforeClass public static void setupClass(){ //get the uri to send the commands to. seleniumURI = SauceHelpers.buildSauceUri(); //If available add build tag. When running under Jenkins BUILD_TAG is automatically set. //You can set this manually on manual runs. buildTag = System.getenv("BUILD_TAG"); } /** * * @return the value of the Sauce Job id. */ @Override public String getSessionId() { return sessionId; } /** * Checks if an element is present in the page */ protected boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } } }
package pt.webdetails.cda.filetests; import java.math.BigDecimal; import javax.swing.table.TableModel; import org.pentaho.reporting.engine.classic.core.util.TypedTableModel; import pt.webdetails.cda.CdaEngine; import pt.webdetails.cda.cache.IQueryCache; import pt.webdetails.cda.cache.TableCacheKey; import pt.webdetails.cda.dataaccess.Olap4JDataAccess; import pt.webdetails.cda.query.QueryOptions; import pt.webdetails.cda.settings.CdaSettings; import pt.webdetails.cda.test.util.TableModelChecker; public class Olap4jTest extends CdaTestCase { public Olap4jTest() { super(); } public Olap4jTest( final String name ) { super( name ); } public void testOlap4jQuery() throws Exception { final CdaSettings cdaSettings = parseSettingsFile( "sample-olap4j.cda" ); final CdaEngine engine = CdaEngine.getInstance(); final QueryOptions queryOptions = new QueryOptions(); queryOptions.setDataAccessId( "2" ); queryOptions.setOutputType( "json" ); queryOptions.addParameter( "status", "Shipped" ); TableModel result = engine.doQuery( cdaSettings, queryOptions ); TypedTableModel expected = new TypedTableModel( new String[] { "[Time].[(All)]", "Year", "price", "PriceInK" }, new Class<?>[] { String.class, String.class, Double.class, BigDecimal.class }, 2 ); expected.addRow( "All Years", "2003", 3573701.2500000023d, new BigDecimal( "3.5737012500000023" ) ); expected.addRow( "All Years", "2004", 4750205.889999998d, new BigDecimal( "4.750205889999998" ) ); expected.addRow( "All Years", "2005", 1513074.4600000002d, new BigDecimal( "1.5130744600000002" ) ); TableModelChecker checker = new TableModelChecker( true, true ); checker.setDoubleComparison( 2, 1e-7 ); checker.setBigDecimalComparison( 3, "1e-12" ); checker.assertEquals( expected, result ); } /** * this test is the same as testOlap4jQuery(), but now calls for a new data-access id 3, which in its turn is set to * use the new connection id 3, that has been defined to use new type 'olap4j.defaultolap4j' */ public void testDefaultOlap4jQuery() throws Exception { final CdaSettings cdaSettings = parseSettingsFile( "sample-olap4j.cda" ); final CdaEngine engine = CdaEngine.getInstance(); final QueryOptions queryOptions = new QueryOptions(); // same as data-access id 2, but using new connection type 'olap4j.defaultolap4j' queryOptions.setDataAccessId( "3" ); queryOptions.setOutputType( "json" ); queryOptions.addParameter( "status", "Shipped" ); TableModel result = engine.doQuery( cdaSettings, queryOptions ); TypedTableModel expected = new TypedTableModel( new String[] { "[Time].[(All)]", "Year", "price", "PriceInK" }, new Class<?>[] { String.class, String.class, Double.class, BigDecimal.class }, 2 ); expected.addRow( "All Years", "2003", 3573701.2500000023d, new BigDecimal( "3.5737012500000023" ) ); expected.addRow( "All Years", "2004", 4750205.889999998d, new BigDecimal( "4.750205889999998" ) ); expected.addRow( "All Years", "2005", 1513074.4600000002d, new BigDecimal( "1.5130744600000002" ) ); TableModelChecker checker = new TableModelChecker( true, true ); checker.setDoubleComparison( 2, 1e-7 ); checker.setBigDecimalComparison( 3, "1e-12" ); checker.assertEquals( expected, result ); } }
package org.languagetool.language; import org.jetbrains.annotations.NotNull; import org.languagetool.Language; import org.languagetool.LanguageMaintainedState; import org.languagetool.chunking.Chunker; import org.languagetool.chunking.GermanChunker; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.languagemodel.LuceneLanguageModel; import org.languagetool.rules.*; import org.languagetool.rules.de.*; import org.languagetool.rules.de.LongSentenceRule; import org.languagetool.rules.de.SentenceWhitespaceRule; import org.languagetool.rules.neuralnetwork.NeuralNetworkRuleCreator; import org.languagetool.rules.neuralnetwork.Word2VecModel; import org.languagetool.synthesis.GermanSynthesizer; import org.languagetool.synthesis.Synthesizer; import org.languagetool.tagging.Tagger; import org.languagetool.tagging.de.GermanTagger; import org.languagetool.tagging.disambiguation.Disambiguator; import org.languagetool.tagging.disambiguation.rules.de.GermanRuleDisambiguator; import org.languagetool.tokenizers.CompoundWordTokenizer; import org.languagetool.tokenizers.SRXSentenceTokenizer; import org.languagetool.tokenizers.SentenceTokenizer; import org.languagetool.tokenizers.de.GermanCompoundTokenizer; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ResourceBundle; /** * Support for German - use the sub classes {@link GermanyGerman}, {@link SwissGerman}, or {@link AustrianGerman} * if you need spell checking. */ public class German extends Language implements AutoCloseable { private static final Language GERMANY_GERMAN = new GermanyGerman(); private Tagger tagger; private Synthesizer synthesizer; private SentenceTokenizer sentenceTokenizer; private Disambiguator disambiguator; private GermanChunker chunker; private CompoundWordTokenizer compoundTokenizer; private GermanCompoundTokenizer strictCompoundTokenizer; private LanguageModel languageModel; private List<Rule> nnRules; private Word2VecModel word2VecModel; /** * @deprecated use {@link GermanyGerman}, {@link AustrianGerman}, or {@link SwissGerman} instead - * they have rules for spell checking, this class doesn't (deprecated since 3.2) */ @Deprecated public German() { } @Override public Language getDefaultLanguageVariant() { return GERMANY_GERMAN; } @Override public Disambiguator getDisambiguator() { if (disambiguator == null) { disambiguator = new GermanRuleDisambiguator(); } return disambiguator; } /** * @since 2.9 */ @Override public Chunker getPostDisambiguationChunker() { if (chunker == null) { chunker = new GermanChunker(); } return chunker; } @Override public String getName() { return "German"; } @Override public String getShortCode() { return "de"; } @Override public String[] getCountries() { return new String[]{"LU", "LI", "BE"}; } @Override public Tagger getTagger() { Tagger t = tagger; if (t == null) { synchronized (this) { t = tagger; if (t == null) { tagger = t = new GermanTagger(); } } } return t; } @Override @NotNull public Synthesizer getSynthesizer() { if (synthesizer == null) { synthesizer = new GermanSynthesizer(); } return synthesizer; } @Override public SentenceTokenizer getSentenceTokenizer() { if (sentenceTokenizer == null) { sentenceTokenizer = new SRXSentenceTokenizer(this); } return sentenceTokenizer; } @Override public Contributor[] getMaintainers() { return new Contributor[] { new Contributor("Jan Schreiber"), Contributors.DANIEL_NABER, }; } @Override public List<Rule> getRelevantRules(ResourceBundle messages) throws IOException { return Arrays.asList( new CommaWhitespaceRule(messages, Example.wrong("Die Partei<marker> ,</marker> die die letzte Wahl gewann."), Example.fixed("Die Partei<marker>,</marker> die die letzte Wahl gewann.")), new GenericUnpairedBracketsRule(messages, Arrays.asList("[", "(", "{", "„", "»", "«", "\""), Arrays.asList("]", ")", "}", "“", "«", "»", "\"")), new UppercaseSentenceStartRule(messages, this, Example.wrong("Das Haus ist alt. <marker>es</marker> wurde 1950 gebaut."), Example.fixed("Das Haus ist alt. <marker>Es</marker> wurde 1950 gebaut.")), new MultipleWhitespaceRule(messages, this), // specific to German: new OldSpellingRule(messages), new SentenceWhitespaceRule(messages), new GermanDoublePunctuationRule(messages), new MissingVerbRule(messages, this), new GermanWordRepeatRule(messages, this), new GermanWordRepeatBeginningRule(messages, this), new GermanWrongWordInContextRule(messages), new AgreementRule(messages, this), new CaseRule(messages, this), new CompoundRule(messages), new DashRule(messages), new VerbAgreementRule(messages, this), new SubjectVerbAgreementRule(messages, this), new WordCoherencyRule(messages), new SimilarNameRule(messages), new WiederVsWiderRule(messages), new WhiteSpaceBeforeParagraphEnd(messages), new WhiteSpaceAtBeginOfParagraph(messages), new EmptyLineRule(messages), new GermanStyleRepeatedWordRule(messages), new CompoundCoherencyRule(messages), new LongSentenceRule(messages), new DuUpperLowerCaseRule(messages) ); } /** * @since 2.7 */ public CompoundWordTokenizer getNonStrictCompoundSplitter() { if (compoundTokenizer == null) { try { GermanCompoundTokenizer tokenizer = new GermanCompoundTokenizer(false); // there's a spelling mistake in (at least) one part, so strict mode wouldn't split the word compoundTokenizer = word -> new ArrayList<>(tokenizer.tokenize(word)); } catch (IOException e) { throw new RuntimeException("Could not set up German compound splitter", e); } } return compoundTokenizer; } /** * @since 2.7 */ public GermanCompoundTokenizer getStrictCompoundTokenizer() { if (strictCompoundTokenizer == null) { try { strictCompoundTokenizer = new GermanCompoundTokenizer(); } catch (IOException e) { throw new RuntimeException("Could not set up strict German compound splitter", e); } } return strictCompoundTokenizer; } @Override public synchronized LanguageModel getLanguageModel(File indexDir) throws IOException { if (languageModel == null) { languageModel = new LuceneLanguageModel(new File(indexDir, getShortCode())); // for testing: //languageModel = new BerkeleyRawLanguageModel(new File("/media/Data/berkeleylm/google_books_binaries/ger.blm.gz")); //languageModel = new BerkeleyLanguageModel(new File("/media/Data/berkeleylm/google_books_binaries/ger.blm.gz")); } return languageModel; } /** @since 4.0 */ @Override public synchronized Word2VecModel getWord2VecModel(File indexDir) throws IOException { if (word2VecModel == null) { word2VecModel = new Word2VecModel(indexDir + File.separator + getShortCode()); } return word2VecModel; } /** @since 3.1 */ @Override public List<Rule> getRelevantLanguageModelRules(ResourceBundle messages, LanguageModel languageModel) throws IOException { return Arrays.asList( new GermanConfusionProbabilityRule(messages, languageModel, this), new ProhibitedCompoundRule(messages, languageModel) ); } /** @since 4.0 */ @Override public List<Rule> getRelevantWord2VecModelRules(ResourceBundle messages, Word2VecModel word2vecModel) throws IOException { if (nnRules == null) { nnRules = NeuralNetworkRuleCreator.createRules(messages, this, word2vecModel); } return nnRules; } /** * Closes the language model, if any. * @since 3.1 */ @Override public void close() throws Exception { if (languageModel != null) { languageModel.close(); } } @Override public LanguageMaintainedState getMaintainedState() { return LanguageMaintainedState.ActivelyMaintained; } @Override public int getPriorityForId(String id) { switch (id) { case "OLD_SPELLING_INTERNAL": return 10; case "DE_PROHIBITED_COMPOUNDS": return 1; // a more detailed error message than from spell checker case "ANS_OHNE_APOSTROPH": return 1; case "CONFUSION_RULE": return -1; // probably less specific than the rules from grammar.xml case "AKZENT_STATT_APOSTROPH": return -1; // lower prio than PLURAL_APOSTROPH case "PUNKT_ENDE_ABSATZ": return -10; // should never hide other errors, as chance for a false alarm is quite high case "KOMMA_ZWISCHEN_HAUPT_UND_NEBENSATZ": return -10; } return 0; } }
package org.grouplens.lenskit.cursors; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; /** * Tests for the cursor utility methods. This has the side effect of also testing some of the * general cursor support code. */ public class CursorsTest { //region The empty cursor @Test public void testEmptyCursor() { Cursor<String> cur = Cursors.empty(); try { assertThat(cur.hasNext(), equalTo(false)); assertThat(cur.getRowCount(), equalTo(0)); try { cur.next(); fail("next() on empty cursor should fail"); } catch (NoSuchElementException e) { /* expected */ } } finally { cur.close(); } } @Test public void testEmptyCursorIterable() { Cursor<String> cur = Cursors.empty(); try { assertThat(Iterables.isEmpty(cur), equalTo(true)); } finally { cur.close(); } } //endregion //region Collection and Iterator Wrapping @Test public void testWrapEmptyCollection() { Cursor<?> cursor = Cursors.wrap(Collections.emptyList()); try { assertThat(cursor.getRowCount(), equalTo(0)); assertThat(cursor.hasNext(), equalTo(false)); try { cursor.next(); fail("next should fail on empty cursor"); } catch (NoSuchElementException e) { /* expected */ } } finally { cursor.close(); } } @Test public void testWrapCollection() { Cursor<String> cursor = Cursors.wrap(Lists.newArrayList("foo", "bar")); try { assertThat(cursor.getRowCount(), equalTo(2)); assertThat(cursor.hasNext(), equalTo(true)); assertThat(cursor.next(), equalTo("foo")); assertThat(cursor.next(), equalTo("bar")); assertThat(cursor.hasNext(), equalTo(false)); try { cursor.next(); fail("next should fail on empty cursor"); } catch (NoSuchElementException e) { /* expected */ } } finally { cursor.close(); } } @Test public void testWrapCollectionIterator() { Cursor<String> cursor = Cursors.wrap(Lists.newArrayList("foo", "bar")); try { List<String> strs = Lists.newArrayList(cursor.iterator()); assertThat(strs, hasSize(2)); assertThat(strs, contains("foo", "bar")); } finally { cursor.close(); } } @Test public void testWrapIterator() { Cursor<String> cursor = Cursors.wrap(Lists.newArrayList("foo", "bar").iterator()); try { assertThat(cursor.getRowCount(), lessThan(0)); // since collection wrapping tested general capabilities, these tests will be terser assertThat(cursor, contains("foo", "bar")); } finally { cursor.close(); } } //endregion //region Making Collections @Test public void testMakeListEmpty() { List<?> lst = Cursors.makeList(Cursors.empty()); assertThat(lst, hasSize(0)); } @Test public void testMakeListOfIterator() { String[] strings = { "READ ME", "ZELGO NER", "HACKEM MUCHE" }; // go through an iteator so the cursor doesn't know its length List<String> lst = Cursors.makeList(Cursors.wrap(Iterators.forArray(strings))); assertThat(lst, hasSize(3)); assertThat(lst, contains(strings)); } @Test public void testMakeListOfList() { // same test as previous, but with a cursor with a known length String[] strings = { "READ ME", "ZELGO NER", "HACKEM MUCHE" }; List<String> lst = Cursors.makeList(Cursors.wrap(Arrays.asList(strings))); assertThat(lst, hasSize(3)); assertThat(lst, contains(strings)); } //endregion //region Concat @Test public void testEmptyConcat() { @SuppressWarnings("unchecked") Cursor<String> cursor = Cursors.concat(); assertThat(cursor.hasNext(), equalTo(false)); try { cursor.next(); fail("next on empty cursor should fail"); } catch (NoSuchElementException e) { /* expected */ } } @SuppressWarnings("unchecked") @Test public void testConcatEmpty() { Cursor<String> cursor = Cursors.concat(Cursors.<String>empty()); assertThat(cursor.hasNext(), equalTo(false)); try { cursor.next(); fail("next on empty cursor should fail"); } catch (NoSuchElementException e) { /* expected */ } } @Test public void testConcatOne() { @SuppressWarnings("unchecked") Cursor<String> cursor = Cursors.concat(Cursors.of("foo")); assertThat(cursor.hasNext(), equalTo(true)); assertThat(cursor.next(), equalTo("foo")); assertThat(cursor.hasNext(), equalTo(false)); try { cursor.next(); fail("next on consumed cursor should fail"); } catch (NoSuchElementException e) { /* expected */ } } @Test public void testConcatTwo() { @SuppressWarnings("unchecked") Cursor<String> cursor = Cursors.concat(Cursors.of("foo", "bar")); assertThat(cursor.hasNext(), equalTo(true)); assertThat(cursor.next(), equalTo("foo")); assertThat(cursor.next(), equalTo("bar")); assertThat(cursor.hasNext(), equalTo(false)); try { cursor.next(); fail("next on consumed cursor should fail"); } catch (NoSuchElementException e) { /* expected */ } } @Test public void testConcatTwoCursors() { @SuppressWarnings("unchecked") Cursor<String> cursor = Cursors.concat(Cursors.of("foo"), Cursors.of("bar")); assertThat(cursor.hasNext(), equalTo(true)); assertThat(cursor.next(), equalTo("foo")); assertThat(cursor.next(), equalTo("bar")); assertThat(cursor.hasNext(), equalTo(false)); try { cursor.next(); fail("next on consumed cursor should fail"); } catch (NoSuchElementException e) { /* expected */ } } @Test public void testConcatWithEmpty() { @SuppressWarnings("unchecked") Cursor<String> cursor = Cursors.concat(Cursors.of("foo"), Cursors.<String>empty(), Cursors.of("bar")); assertThat(cursor, contains("foo", "bar")); assertThat(cursor.hasNext(), equalTo(false)); } //endregion @Test public void testConsumeNone() { Cursor<String> cur = Cursors.of("foo", "bar"); cur = Cursors.consume(0, cur); assertThat(cur, contains("foo", "bar")); } @Test public void testConsumeOne() { Cursor<String> cur = Cursors.of("foo", "bar"); cur = Cursors.consume(1, cur); assertThat(cur, contains("bar")); } @Test public void testConsumeTooMany() { Cursor<String> cur = Cursors.of("foo", "bar"); cur = Cursors.consume(3, cur); assertThat(cur.hasNext(), equalTo(false)); } }
package soot; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import soot.dava.toolkits.base.misc.PackageNamer; import soot.options.Options; import soot.tagkit.AbstractHost; import soot.util.Chain; import soot.util.HashChain; import soot.util.Numberable; import soot.util.NumberedString; import soot.util.SmallNumberedMap; import soot.validation.ClassValidator; import soot.validation.MethodDeclarationValidator; import soot.validation.OuterClassValidator; import soot.validation.ValidationException; /* * Incomplete and inefficient implementation. * * Implementation notes: * * 1. The getFieldOf() method is slow because it traverses the list of fields, comparing the names, * one by one. If you establish a Dictionary of Name->Field, you will need to add a * notifyOfNameChange() method, and register fields which belong to classes, because the hashtable * will need to be updated. I will do this later. - kor 16-Sep-97 * * 2. Note 1 is kept for historical (i.e. amusement) reasons. In fact, there is no longer a list of fields; * these are kept in a Chain now. But that's ok; there is no longer a getFieldOf() method, * either. There still is no efficient way to get a field by name, although one could establish * a Chain of EquivalentValue-like objects and do an O(1) search on that. - plam 2-24-00 */ public class SootClass extends AbstractHost implements Numberable { protected String name, shortName, fixedShortName, packageName, fixedPackageName; protected int modifiers; protected Chain<SootField> fields = new HashChain<SootField>(); protected SmallNumberedMap<SootMethod> subSigToMethods = new SmallNumberedMap<SootMethod>( Scene.v().getSubSigNumberer()); // methodList is just for keeping the methods in a consistent order. It // needs to be kept consistent with subSigToMethods. protected List<SootMethod> methodList = new ArrayList<SootMethod>(); protected Chain<SootClass> interfaces = new HashChain<SootClass>(); protected boolean isInScene; protected SootClass superClass; protected SootClass outerClass; protected boolean isPhantom; public final static String INVOKEDYNAMIC_DUMMY_CLASS_NAME = "soot.dummy.InvokeDynamic"; /** * Constructs an empty SootClass with the given name and modifiers. */ public SootClass(String name, int modifiers) { if (name.charAt(0) == '[') throw new RuntimeException("Attempt to make a class whose name starts with ["); setName(name); this.modifiers = modifiers; refType = RefType.v(name); refType.setSootClass(this); if (Options.v().debug_resolver()) G.v().out.println("created " + name + " with modifiers " + modifiers); setResolvingLevel(BODIES); Scene.v().getClassNumberer().add(this); } /** * Constructs an empty SootClass with the given name and no modifiers. */ public SootClass(String name) { this(name, 0); } public final static int DANGLING = 0; public final static int HIERARCHY = 1; public final static int SIGNATURES = 2; public final static int BODIES = 3; private volatile int resolvingLevel = DANGLING; private String levelToString(int level) { switch (level) { case DANGLING: return "DANGLING"; case HIERARCHY: return "HIERARCHY"; case SIGNATURES: return "SIGNATURES"; case BODIES: return "BODIES"; default: throw new RuntimeException("unknown resolving level"); } } /** * Checks if the class has at lease the resolving level specified. This * check does nothing is the class resolution process is not completed. * * @param level * the resolution level, one of DANGLING, HIERARCHY, SIGNATURES, * and BODIES * @throws java.lang.RuntimeException * if the resolution is at an insufficient level */ public void checkLevel(int level) { if (!Scene.v().doneResolving() || Options.v().ignore_resolving_levels()) return; checkLevelIgnoreResolving(level); } /** * Checks if the class has at lease the resolving level specified. This * check ignores the resolution completeness. * * @param level * the resolution level, one of DANGLING, HIERARCHY, SIGNATURES, * and BODIES * @throws java.lang.RuntimeException * if the resolution is at an insufficient level */ public void checkLevelIgnoreResolving(int level) { if (resolvingLevel < level) { String hint = "\nIf you are extending Soot, try to add the following call before calling soot.Main.main(..):\n" + "Scene.v().addBasicClass(" + getName() + "," + levelToString(level) + ");\n" + "Otherwise, try whole-program mode (-w)."; throw new RuntimeException("This operation requires resolving level " + levelToString(level) + " but " + name + " is at resolving level " + levelToString(resolvingLevel) + hint); } } public int resolvingLevel() { return resolvingLevel; } public void setResolvingLevel(int newLevel) { resolvingLevel = newLevel; } public boolean isInScene() { return isInScene; } /** Tells this class if it is being managed by a Scene. */ public void setInScene(boolean isInScene) { this.isInScene = isInScene; } /** * Returns the number of fields in this class. */ public int getFieldCount() { checkLevel(SIGNATURES); return fields.size(); } /** * Returns a backed Chain of fields. */ public Chain<SootField> getFields() { checkLevel(SIGNATURES); return fields; } /* * public void setFields(Field[] fields) { this.fields = new * ArraySet(fields); } */ /** * Adds the given field to this class. */ public void addField(SootField f) { checkLevel(SIGNATURES); if (f.isDeclared()) throw new RuntimeException("already declared: " + f.getName()); if (declaresField(f.getName(), f.getType())) throw new RuntimeException("Field already exists : " + f.getName() + " of type " + f.getType()); fields.add(f); f.isDeclared = true; f.declaringClass = this; } /** * Removes the given field from this class. */ public void removeField(SootField f) { checkLevel(SIGNATURES); if (!f.isDeclared() || f.getDeclaringClass() != this) throw new RuntimeException("did not declare: " + f.getName()); fields.remove(f); f.isDeclared = false; } /** * Returns the field of this class with the given name and type. If the * field cannot be found, an exception is thrown. */ public SootField getField(String name, Type type) { SootField sf = getFieldUnsafe(name, type); if (sf == null) throw new RuntimeException("No field " + name + " in class " + getName()); return sf; } /** * Returns the field of this class with the given name and type. If the * field cannot be found, null is returned. */ public SootField getFieldUnsafe(String name, Type type) { checkLevel(SIGNATURES); for (SootField field : fields.getElementsUnsorted()) { if (field.getName().equals(name) && field.getType().equals(type)) return field; } return null; } /** * Returns the field of this class with the given name. Throws a * RuntimeException if there is more than one field with the given name or * if no such field exists at all. */ public SootField getFieldByName(String name) { SootField foundField = getFieldByNameUnsafe(name); if (foundField == null) throw new RuntimeException("No field " + name + " in class " + getName()); return foundField; } /** * Returns the field of this class with the given name. Throws a * RuntimeException if there is more than one field with the given name. * Returns null if no field with the given name exists. */ public SootField getFieldByNameUnsafe(String name) { checkLevel(SIGNATURES); SootField foundField = null; for (SootField field : fields.getElementsUnsorted()) { if (field.getName().equals(name)) { if (foundField == null) foundField = field; else throw new RuntimeException("ambiguous field: " + name); } } return foundField; } /** * Returns the field of this class with the given subsignature. If such a * field does not exist, an exception is thrown. */ public SootField getField(String subsignature) { SootField sf = getFieldUnsafe(subsignature); if (sf == null) throw new RuntimeException("No field " + subsignature + " in class " + getName()); return sf; } /** * Returns the field of this class with the given subsignature. If such a * field does not exist, null is returned. */ public SootField getFieldUnsafe(String subsignature) { checkLevel(SIGNATURES); for (SootField field : fields.getElementsUnsorted()) { if (field.getSubSignature().equals(subsignature)) return field; } return null; } /** * Does this class declare a field with the given subsignature? */ public boolean declaresField(String subsignature) { checkLevel(SIGNATURES); return getFieldUnsafe(subsignature) != null; } /** * Returns the method of this class with the given subsignature. If no * method with the given subsignature can be found, an exception is thrown. */ public SootMethod getMethod(NumberedString subsignature) { SootMethod ret = getMethodUnsafe(subsignature); if (ret == null) throw new RuntimeException("No method " + subsignature + " in class " + getName()); else return ret; } /** * Returns the method of this class with the given subsignature. If no * method with the given subsignature can be found, null is returned. */ public SootMethod getMethodUnsafe(NumberedString subsignature) { checkLevel(SIGNATURES); SootMethod ret = subSigToMethods.get(subsignature); return ret; } /** * Does this class declare a method with the given subsignature? */ public boolean declaresMethod(NumberedString subsignature) { checkLevel(SIGNATURES); SootMethod ret = subSigToMethods.get(subsignature); return ret != null; } /* * Returns the method of this class with the given subsignature. If no * method with the given subsignature can be found, an exception is thrown. */ public SootMethod getMethod(String subsignature) { checkLevel(SIGNATURES); return getMethod(Scene.v().getSubSigNumberer().findOrAdd(subsignature)); } /* * Returns the method of this class with the given subsignature. If no * method with the given subsignature can be found, null is returned. */ public SootMethod getMethodUnsafe(String subsignature) { checkLevel(SIGNATURES); return getMethodUnsafe(Scene.v().getSubSigNumberer().findOrAdd(subsignature)); } /** * Does this class declare a method with the given subsignature? */ public boolean declaresMethod(String subsignature) { checkLevel(SIGNATURES); return declaresMethod(Scene.v().getSubSigNumberer().findOrAdd(subsignature)); } /** * Does this class declare a field with the given name? */ public boolean declaresFieldByName(String name) { checkLevel(SIGNATURES); for (SootField field : fields) { if (field.getName().equals(name)) return true; } return false; } /** * Does this class declare a field with the given name and type. */ public boolean declaresField(String name, Type type) { checkLevel(SIGNATURES); for (SootField field : fields) { if (field.getName().equals(name) && field.getType().equals(type)) return true; } return false; } /** * Returns the number of methods in this class. */ public int getMethodCount() { checkLevel(SIGNATURES); return subSigToMethods.nonNullSize(); } /** * Returns an iterator over the methods in this class. */ public Iterator<SootMethod> methodIterator() { checkLevel(SIGNATURES); return new Iterator<SootMethod>() { final Iterator<SootMethod> internalIterator = methodList.iterator(); private SootMethod currentMethod; @Override public boolean hasNext() { return internalIterator.hasNext(); } @Override public SootMethod next() { currentMethod = internalIterator.next(); return currentMethod; } @Override public void remove() { internalIterator.remove(); subSigToMethods.put(currentMethod.getNumberedSubSignature(), null); currentMethod.setDeclared(false); } }; } public List<SootMethod> getMethods() { checkLevel(SIGNATURES); return methodList; } /** * Attempts to retrieve the method with the given name, parameters and * return type. If no matching method can be found, an exception is thrown. */ public SootMethod getMethod(String name, List<Type> parameterTypes, Type returnType) { SootMethod sm = getMethodUnsafe(name, parameterTypes, returnType); if (sm != null) return sm; throw new RuntimeException("Class " + getName() + " doesn't have method " + name + "(" + parameterTypes + ")" + " : " + returnType); } /** * Attempts to retrieve the method with the given name, parameters and * return type. If no matching method can be found, null is returned. */ public SootMethod getMethodUnsafe(String name, List<Type> parameterTypes, Type returnType) { checkLevel(SIGNATURES); for (SootMethod method : methodList) { if (method.getName().equals(name) && parameterTypes.equals(method.getParameterTypes()) && returnType.equals(method.getReturnType())) { return method; } } return null; } /** * Attempts to retrieve the method with the given name and parameters. This * method may throw an AmbiguousMethodException if there is more than one * method with the given name and parameter. */ public SootMethod getMethod(String name, List<Type> parameterTypes) { checkLevel(SIGNATURES); SootMethod foundMethod = null; for (SootMethod method : methodList) { if (method.getName().equals(name) && parameterTypes.equals(method.getParameterTypes())) { if (foundMethod == null) foundMethod = method; else throw new RuntimeException("ambiguous method"); } } if (foundMethod == null) throw new RuntimeException("couldn't find method " + name + "(" + parameterTypes + ") in " + this); return foundMethod; } /** * Attempts to retrieve the method with the given name. This method may * throw an AmbiguousMethodException if there are more than one method with * the given name. If no method with the given is found, null is returned. */ public SootMethod getMethodByNameUnsafe(String name) { checkLevel(SIGNATURES); SootMethod foundMethod = null; for (SootMethod method : methodList) { if (method.getName().equals(name)) { if (foundMethod == null) foundMethod = method; else throw new RuntimeException("ambiguous method: " + name + " in class " + this); } } return foundMethod; } /** * Attempts to retrieve the method with the given name. This method may * throw an AmbiguousMethodException if there are more than one method with * the given name. If no method with the given is found, an exception is * thrown as well. */ public SootMethod getMethodByName(String name) { SootMethod foundMethod = getMethodByNameUnsafe(name); if (foundMethod == null) throw new RuntimeException("couldn't find method " + name + "(*) in " + this); return foundMethod; } /** * Does this class declare a method with the given name and parameter types? */ public boolean declaresMethod(String name, List<Type> parameterTypes) { checkLevel(SIGNATURES); for (SootMethod method : methodList) { if (method.getName().equals(name) && method.getParameterTypes().equals(parameterTypes)) return true; } return false; } /** * Does this class declare a method with the given name, parameter types, * and return type? */ public boolean declaresMethod(String name, List<Type> parameterTypes, Type returnType) { checkLevel(SIGNATURES); for (SootMethod method : methodList) { if (method.getName().equals(name) && method.getParameterTypes().equals(parameterTypes) && method.getReturnType().equals(returnType)) return true; } return false; } /** * Does this class declare a method with the given name? */ public boolean declaresMethodByName(String name) { checkLevel(SIGNATURES); for (SootMethod method : methodList) { if (method.getName().equals(name)) return true; } return false; } /* * public void setMethods(Method[] method) { methods = new ArraySet(method); * } */ /** * Adds the given method to this class. */ public void addMethod(SootMethod m) { checkLevel(SIGNATURES); if (m.isDeclared()) throw new RuntimeException("already declared: " + m.getName()); /* * if(declaresMethod(m.getName(), m.getParameterTypes())) throw new * RuntimeException("duplicate signature for: " + m.getName()); */ if (subSigToMethods.get(m.getNumberedSubSignature()) != null) { throw new RuntimeException("Attempting to add method " + m.getSubSignature() + " to class " + this + ", but the class already has a method with that signature."); } subSigToMethods.put(m.getNumberedSubSignature(), m); methodList.add(m); m.setDeclared(true); m.setDeclaringClass(this); } synchronized SootMethod getOrAddMethod(SootMethod m) { checkLevel(SIGNATURES); if (m.isDeclared()) throw new RuntimeException("already declared: " + m.getName()); SootMethod old = subSigToMethods.get(m.getNumberedSubSignature()); if (old != null) return old; subSigToMethods.put(m.getNumberedSubSignature(), m); methodList.add(m); m.setDeclared(true); m.setDeclaringClass(this); return m; } /** * Removes the given method from this class. */ public void removeMethod(SootMethod m) { checkLevel(SIGNATURES); if (!m.isDeclared() || m.getDeclaringClass() != this) throw new RuntimeException("incorrect declarer for remove: " + m.getName()); if (subSigToMethods.get(m.getNumberedSubSignature()) == null) { throw new RuntimeException( "Attempt to remove method " + m.getSubSignature() + " which is not in class " + this); } subSigToMethods.put(m.getNumberedSubSignature(), null); methodList.remove(m); m.setDeclared(false); } /** * Returns the modifiers of this class. */ public int getModifiers() { return modifiers; } /** * Sets the modifiers for this class. */ public void setModifiers(int modifiers) { this.modifiers = modifiers; } /** * Returns the number of interfaces being directly implemented by this * class. Note that direct implementation corresponds to an "implements" * keyword in the Java class file and that this class may still be * implementing additional interfaces in the usual sense by being a subclass * of a class which directly implements some interfaces. */ public int getInterfaceCount() { checkLevel(HIERARCHY); return interfaces.size(); } /** * Returns a backed Chain of the interfaces that are directly implemented by * this class. (see getInterfaceCount()) */ public Chain<SootClass> getInterfaces() { checkLevel(HIERARCHY); return interfaces; } /** * Does this class directly implement the given interface? (see * getInterfaceCount()) */ public boolean implementsInterface(String name) { checkLevel(HIERARCHY); Iterator<SootClass> interfaceIt = getInterfaces().iterator(); while (interfaceIt.hasNext()) { SootClass SootClass = interfaceIt.next(); if (SootClass.getName().equals(name)) return true; } return false; } /** * Add the given class to the list of interfaces which are directly * implemented by this class. */ public void addInterface(SootClass interfaceClass) { checkLevel(HIERARCHY); if (implementsInterface(interfaceClass.getName())) throw new RuntimeException("duplicate interface: " + interfaceClass.getName()); interfaces.add(interfaceClass); } /** * Removes the given class from the list of interfaces which are directly * implemented by this class. */ public void removeInterface(SootClass interfaceClass) { checkLevel(HIERARCHY); if (!implementsInterface(interfaceClass.getName())) throw new RuntimeException("no such interface: " + interfaceClass.getName()); interfaces.remove(interfaceClass); } /** * WARNING: interfaces are subclasses of the java.lang.Object class! Does * this class have a superclass? False implies that this is the * java.lang.Object class. Note that interfaces are subclasses of the * java.lang.Object class. */ public boolean hasSuperclass() { checkLevel(HIERARCHY); return superClass != null; } /** * WARNING: interfaces are subclasses of the java.lang.Object class! Returns * the superclass of this class. (see hasSuperclass()) */ public SootClass getSuperclass() { checkLevel(HIERARCHY); if (superClass == null && !isPhantom()) throw new RuntimeException("no superclass for " + getName()); else return superClass; } /** * Sets the superclass of this class. Note that passing a null will cause * the class to have no superclass. */ public void setSuperclass(SootClass c) { checkLevel(HIERARCHY); superClass = c; } public boolean hasOuterClass() { checkLevel(HIERARCHY); return outerClass != null; } public SootClass getOuterClass() { checkLevel(HIERARCHY); if (outerClass == null) throw new RuntimeException("no outer class"); else return outerClass; } public void setOuterClass(SootClass c) { checkLevel(HIERARCHY); outerClass = c; } public boolean isInnerClass() { return hasOuterClass(); } /** * Returns the name of this class. */ public String getName() { return name; } public String getJavaStyleName() { if (PackageNamer.v().has_FixedNames()) { if (fixedShortName == null) fixedShortName = PackageNamer.v().get_FixedClassName(name); if (PackageNamer.v().use_ShortName(getJavaPackageName(), fixedShortName) == false) return getJavaPackageName() + "." + fixedShortName; return fixedShortName; } return shortName; } public String getShortJavaStyleName() { if (PackageNamer.v().has_FixedNames()) { if (fixedShortName == null) fixedShortName = PackageNamer.v().get_FixedClassName(name); return fixedShortName; } return shortName; } public String getShortName() { return shortName; } /** * Returns the package name of this class. */ public String getPackageName() { return packageName; } public String getJavaPackageName() { if (PackageNamer.v().has_FixedNames()) { if (fixedPackageName == null) fixedPackageName = PackageNamer.v().get_FixedPackageName(packageName); return fixedPackageName; } return packageName; } /** * Sets the name of this class. */ public void setName(String name) { this.name = name.intern(); shortName = name; packageName = ""; int index = name.lastIndexOf('.'); if (index > 0) { shortName = name.substring(index + 1); packageName = name.substring(0, index); } fixedShortName = null; fixedPackageName = null; } /** Convenience method; returns true if this class is an interface. */ public boolean isInterface() { checkLevel(HIERARCHY); return Modifier.isInterface(this.getModifiers()); } /** Returns true if this class is not an interface and not abstract. */ public boolean isConcrete() { return !isInterface() && !isAbstract(); } /** Convenience method; returns true if this class is public. */ public boolean isPublic() { return Modifier.isPublic(this.getModifiers()); } /** Returns true if some method in this class has an active Baf body. */ public boolean containsBafBody() { Iterator<SootMethod> methodIt = methodIterator(); while (methodIt.hasNext()) { SootMethod m = methodIt.next(); if (m.hasActiveBody() && m.getActiveBody() instanceof soot.baf.BafBody) { return true; } } return false; } private RefType refType; // made public for obfuscator.. public void setRefType(RefType refType) { this.refType = refType; } public boolean hasRefType() { return refType != null; } /** Returns the RefType corresponding to this class. */ public RefType getType() { return refType; } /** Returns the name of this class. */ @Override public String toString() { return getName(); } /* Renames private fields and methods with numeric names. */ public void renameFieldsAndMethods(boolean privateOnly) { checkLevel(SIGNATURES); // Rename fields. Ignore collisions for now. { Iterator<SootField> fieldIt = this.getFields().iterator(); int fieldCount = 0; if (fieldIt.hasNext()) { while (fieldIt.hasNext()) { SootField f = fieldIt.next(); if (!privateOnly || Modifier.isPrivate(f.getModifiers())) { String newFieldName = "__field" + (fieldCount++); f.setName(newFieldName); } } } } // Rename methods. Again, ignore collisions for now. { Iterator<SootMethod> methodIt = methodIterator(); int methodCount = 0; if (methodIt.hasNext()) { while (methodIt.hasNext()) { SootMethod m = methodIt.next(); if (!privateOnly || Modifier.isPrivate(m.getModifiers())) { String newMethodName = "__method" + (methodCount++); m.setName(newMethodName); } } } } } /** * Convenience method returning true if this class is an application class. * * @see Scene#getApplicationClasses() */ public boolean isApplicationClass() { return Scene.v().getApplicationClasses().contains(this); } /** Makes this class an application class. */ public void setApplicationClass() { if (isApplicationClass()) return; Chain<SootClass> c = Scene.v().getContainingChain(this); if (c != null) c.remove(this); Scene.v().getApplicationClasses().add(this); isPhantom = false; } /** * Convenience method returning true if this class is a library class. * * @see Scene#getLibraryClasses() */ public boolean isLibraryClass() { return Scene.v().getLibraryClasses().contains(this); } /** Makes this class a library class. */ public void setLibraryClass() { if (isLibraryClass()) return; Chain<SootClass> c = Scene.v().getContainingChain(this); if (c != null) c.remove(this); Scene.v().getLibraryClasses().add(this); isPhantom = false; } /** * Sometimes we need to know which class is a JDK class. There is no simple * way to distinguish a user class and a JDK class, here we use the package * prefix as the heuristic. * * @author xiao */ public boolean isJavaLibraryClass() { if (name.startsWith("java.") || name.startsWith("sun.") || name.startsWith("javax.") || name.startsWith("com.sun.") || name.startsWith("org.omg.") || name.startsWith("org.xml.") || name.startsWith("org.w3c.dom")) return true; return false; } /** * Convenience method returning true if this class is a phantom class. * * @see Scene#getPhantomClasses() */ public boolean isPhantomClass() { return Scene.v().getPhantomClasses().contains(this); } /** Makes this class a phantom class. */ public void setPhantomClass() { Chain<SootClass> c = Scene.v().getContainingChain(this); if (c != null) c.remove(this); Scene.v().getPhantomClasses().add(this); isPhantom = true; } /** Convenience method returning true if this class is phantom. */ public boolean isPhantom() { return isPhantom; } /** * Convenience method returning true if this class is private. */ public boolean isPrivate() { return Modifier.isPrivate(this.getModifiers()); } /** * Convenience method returning true if this class is protected. */ public boolean isProtected() { return Modifier.isProtected(this.getModifiers()); } /** * Convenience method returning true if this class is abstract. */ public boolean isAbstract() { return Modifier.isAbstract(this.getModifiers()); } /** * Convenience method returning true if this class is final. */ public boolean isFinal() { return Modifier.isFinal(this.getModifiers()); } /** * Convenience method returning true if this class is static. */ public boolean isStatic() { return Modifier.isStatic(this.getModifiers()); } @Override public final int getNumber() { return number; } @Override public final void setNumber(int number) { this.number = number; } private int number = 0; public void rename(String newName) { this.name = newName; // resolvingLevel = BODIES; if (this.refType != null) { refType.setClassName(name); } else { refType = RefType.v(name); } Scene.v().addRefType(refType); } private static ClassValidator[] validators; /** * Returns an array containing some validators in order to validate the * SootClass * * @return the array containing validators */ private synchronized static ClassValidator[] getValidators() { if (validators == null) { validators = new ClassValidator[] { OuterClassValidator.v(), MethodDeclarationValidator.v() }; } return validators; }; /** * Validates this SootClass for logical errors. Note that this does not * validate the method bodies, only the class structure. */ public void validate() { final List<ValidationException> exceptionList = new ArrayList<ValidationException>(); validate(exceptionList); if (!exceptionList.isEmpty()) throw exceptionList.get(0); } /** * Validates this SootClass for logical errors. Note that this does not * validate the method bodies, only the class structure. All found errors * are saved into the given list. */ public void validate(List<ValidationException> exceptionList) { final boolean runAllValidators = Options.v().debug() || Options.v().validate(); for (ClassValidator validator : getValidators()) { if (!validator.isBasicValidator() && !runAllValidators) continue; validator.validate(this, exceptionList); } } }
package de.htw_berlin.HoboOthello.GUI; import de.htw_berlin.HoboOthello.Core.Field; import de.htw_berlin.HoboOthello.Core.Player; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ComponentListener; public class Gameview extends JFrame { private static final long serialVersionUID = 1L; private String blackPlayerTyp = "BLACK"; private String whitePlayerTyp = "WHITE"; private JLabel whiteScore = new JLabel(whitePlayerTyp); private JLabel blackScore = new JLabel(blackPlayerTyp); private JLabel whosTurn = new JLabel(); private JPanel scorePanel; private JPanel actionPanel; private JPanel eastPanel; private JPanel westPanel; private JPanel boardPanel; private Color backgroundColor; private JButton[][] fieldView; private JButton showHint; private JMenuItem[] toogleMenu; private JMenu gameMenu; private JMenuItem closeGame; private JMenuItem newGame; private JMenu aboutMenu; private JMenuItem aboutItem; Font font18 = new Font("Courier new", Font.BOLD, 18); Font font14 = new Font("Courier new", Font.BOLD, 14); //Create the Stones private ImageIcon white; private ImageIcon black; private ImageIcon grey; private ImageIcon hint; private int var; private int varSmall; /* * values to scale the center panel if window size changes */ int trueWidth; int trueHeight; int newWidth; int newHeight; /** * Constructor to create the gui */ public Gameview(int boardSize) { /* * sets up the main frame of the game */ this.setTitle("HoboOthello"); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(800, 800); this.setLayout(new BorderLayout()); this.setVisible(true); this.backgroundColor = new Color(0, 150, 0); /* * MenuBar and menu components */ gameMenu = new JMenu("Datei"); closeGame = new JMenuItem("Exit"); newGame = new JMenuItem("New Game"); aboutMenu = new JMenu("About"); aboutItem = new JMenuItem("About"); gameMenu.add(newGame); gameMenu.add(closeGame); aboutMenu.add(aboutItem); toogleMenu = new JMenuItem[3]; toogleMenu[0] = newGame; toogleMenu[1] = closeGame; toogleMenu[2] = aboutItem; /* * create a board. board is the center panel. adding buttons to the board */ boardPanel = new JPanel(); boardPanel.setLayout(new GridLayout(boardSize, boardSize)); //boardPanel.setBorder(BorderFactory.createEtchedBorder()); fieldView = new JButton[boardSize][boardSize]; for (int x = 0; x < fieldView.length; x++) { for (int y = 0; y < fieldView.length; y++) { fieldView[x][y] = new JButton(); fieldView[x][y].setBackground(backgroundColor); //fieldView[x][y].setBorder(BorderFactory.createLineBorder(Color.BLACK, 1)); boardPanel.add(fieldView[x][y]).setVisible(true); //fieldView[x][y].setBorder(null); //fieldView[x][y].setBackground(null); } } /* * the action panel which holds the hint button */ actionPanel = new JPanel(); //actionPanel.setBorder(BorderFactory.createEtchedBorder()); // a frame around the panel showHint = new JButton("hint"); actionPanel.add(showHint); /* * the score panel to display the actual score */ scorePanel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 2; c.gridy = 0; scorePanel.add(whiteScore, c); c.gridx = 2; c.gridy = 1; scorePanel.add(blackScore, c); whosTurn.setPreferredSize(new Dimension(220, 30)); whosTurn.setFont(font18); c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.PAGE_END; c.weighty = 1.0; c.gridwidth = 2; c.gridx = 1; c.gridy = 2; scorePanel.add(whosTurn, c); /* * filler spaces for the right and left hand side */ eastPanel = new JPanel(); westPanel = new JPanel(); /* * BorderLayout dimensions of the Center Panel * DO NOT CHANGE THIS */ actionPanel.setPreferredSize(new Dimension(0, 58)); scorePanel.setPreferredSize(new Dimension(0, 78)); westPanel.setPreferredSize(new Dimension(92, 0)); eastPanel.setPreferredSize(new Dimension(92, 0)); actionPanel.setBackground(new Color(120, 160, 160)); scorePanel.setBackground(new Color(120, 160, 160)); westPanel.setBackground(new Color(120, 160, 160)); eastPanel.setBackground(new Color(120, 160, 160)); boardPanel.setBackground(new Color(120, 160, 160)); /* * adding all elements to the main frame */ this.getContentPane().add(scorePanel, BorderLayout.NORTH); this.getContentPane().add(boardPanel, BorderLayout.CENTER); this.getContentPane().add(actionPanel, BorderLayout.SOUTH); this.getContentPane().add(eastPanel, BorderLayout.EAST); this.getContentPane().add(westPanel, BorderLayout.WEST); /* * adding the menu bar to the main frame */ this.setJMenuBar(new JMenuBar()); this.getJMenuBar().add(gameMenu); this.getJMenuBar().add(aboutMenu); /* * initialise all stones */ grey = new ImageIcon(this.getClass().getResource("greybutton.png")); white = new ImageIcon(this.getClass().getResource("whitebutton.png")); black = new ImageIcon(this.getClass().getResource("blackbutton.png")); hint = new ImageIcon(this.getClass().getResource("hint.png")); setupScaleFactors(fieldView.length); setupBlackImageIcon(var); setupGreyImageIcon(var); setUpWhiteImageIcon(var); } /** * all methods to add ActionListeners to the board */ public void addBoardListener(ActionListener listenerForFieldButton) { for (int x = 0; x < fieldView.length; x++) { for (int y = 0; y < fieldView.length; y++) { fieldView[x][y].addActionListener(listenerForFieldButton); } } } public void addMenuListener(ActionListener listenerForMenuClick) { for (int i = 0; i < toogleMenu.length; i++) { toogleMenu[i].addActionListener(listenerForMenuClick); } } public void addHintListener(ActionListener listenerForHintClick) { this.showHint.addActionListener(listenerForHintClick); } public void addSizeListener(ComponentListener listenerForReSize) { this.getContentPane().addComponentListener(listenerForReSize); } /** * Getter for the board to check which Button was clicked * and to check the length of the board (6, 8, 10) * used in GameController -> inner Class BoardListener */ public JButton getFieldView(int x, int y) { return fieldView[x][y]; } public int getFieldViewLength() { return fieldView.length; } public JMenuItem getToogleMenu(int nbr) { return toogleMenu[nbr]; } public JButton getShowHint() { return showHint; } public void displayErrorMessage(String errorMessage) { JOptionPane.showMessageDialog(this, errorMessage); } /** * update a Field in GameView * * @param field The field which should be update */ //TODO This method calls non GUI Parameters : remove from GUI public void updateBoardFields(Field field) { Color color = backgroundColor; if (field.isOccupiedByStone()) { switch (field.getStone().getColor()) { case BLACK: changeStone(1, field.getX(), field.getY()); //color = Color.BLACK; break; case WHITE: changeStone(0, field.getX(), field.getY()); //color = Color.WHITE; break; } } if (field.isPossibleMove()) { changeStone(2, field.getX(), field.getY()); //color = Color.blue; } //fieldView[field.getX()][field.getY()].setBackground(color); } public void updateBoardPlayerPoints(de.htw_berlin.HoboOthello.Core.Color color, int points) { if (color == de.htw_berlin.HoboOthello.Core.Color.BLACK) { this.blackScore.setText(this.blackPlayerTyp + " " + points); this.blackScore.setFont(font14); this.blackScore.setForeground(Color.BLACK); } else { this.whiteScore.setText(this.whitePlayerTyp + " " + points); this.whiteScore.setFont(font14); this.whiteScore.setForeground(Color.WHITE); } } /** * Show the current Player Name (White or Black) * * @param currentPlayerName String which can be Black or White */ public void updateCurrentPlayer(String currentPlayerName) { // TODO: this is an check for equality of the objectid if (currentPlayerName == "WHITE") { this.whosTurn.setText("Players turn: " + currentPlayerName); this.whosTurn.setForeground(Color.WHITE); } else //(currentPlayerName == "Black") { this.whosTurn.setText("Players turn: " + currentPlayerName); this.whosTurn.setForeground(Color.BLACK); } /* else { this.whosTurn.setText("Players turn: " + currentPlayerName); this.whosTurn.setForeground(Color.BLACK); } */ } public void setPlayerTyp(Player blackPlayer, Player whitePlayer) { switch (blackPlayer.getPlayerType()) { case DESKTOP: this.blackPlayerTyp = "HUMAN"; break; case KI_LEVEL1: this.blackPlayerTyp = "KI 1"; break; case KI_LEVEL2: this.blackPlayerTyp = "KI 2"; break; case KI_LEVEL3: this.blackPlayerTyp = "KI 3"; break; case NETWORK_SERVER: this.blackPlayerTyp = "NETWORK SERVER"; break; } switch (whitePlayer.getPlayerType()) { case DESKTOP: this.whitePlayerTyp = "HUMAN"; break; case KI_LEVEL1: this.whitePlayerTyp = "KI 1"; break; case KI_LEVEL2: this.whitePlayerTyp = "KI 2"; break; case KI_LEVEL3: this.whitePlayerTyp = "KI 3"; break; case NETWORK_CLIENT: this.whitePlayerTyp = "NETWORK CLIENT"; break; } } /** * Show the best possible move for the current player * * @param field */ public void showHint(Field field) { this.fieldView[field.getX()][field.getY()].setIcon(null); this.changeStone(3, field.getX(), field.getY()); //fieldView[field.getX()][field.getY()].setBackground(Color.MAGENTA); } /** * @param stone can be 0, 1, 2, 3 * whereas 0=white, 1=black, 2=grey, 3=hint * @param x: the row designator * @param y: the column designator */ public void changeStone(int stone, int x, int y) { if (stone == 0) { fieldView[x][y].setIcon(white); } else if (stone == 1) { fieldView[x][y].setIcon(black); } else if (stone == 2) { fieldView[x][y].setIcon(grey); } else if (stone == 3) { Image hintImage = hint.getImage(); Image newHint = hintImage.getScaledInstance(varSmall, varSmall, java.awt.Image.SCALE_SMOOTH); hint = new ImageIcon(newHint); fieldView[x][y].setIcon(hint); } } private void setupScaleFactors(int scale) { var = (int) (60 * 0.88); varSmall = (int) (60 * 0.48); switch (scale) { case 6: { var = (int) (100 * 0.88); varSmall = (int) (100 * 0.48); break; } case 8: { varSmall = (int) (75 * 0.48); var = (int) (75 * 0.88); break; } case 10: { varSmall = (int) (60 * 0.48); var = (int) (60 * 0.88); break; } default: System.out.println("Ups! Something went wrong"); break; } } private void setupGreyImageIcon(int varSmall) { Image greyImage = grey.getImage(); Image newGrey = greyImage.getScaledInstance(varSmall, varSmall, Image.SCALE_SMOOTH); grey = new ImageIcon(newGrey); } private void setupBlackImageIcon(int var) { Image blackImage = black.getImage(); Image newBlack = blackImage.getScaledInstance(var, var, Image.SCALE_SMOOTH); black = new ImageIcon(newBlack); } private void setUpWhiteImageIcon(int var) { Image whiteImage = white.getImage(); Image newWhite = whiteImage.getScaledInstance(var, var, Image.SCALE_SMOOTH); white = new ImageIcon(newWhite); } /* * adapt values width and height to changes of the size of the frame */ public void getTrueSize(int width, int height) { this.trueHeight = height; this.trueWidth = width; int frameSize; //extra variable for calculation issues if (this.trueHeight >= this.trueWidth) { frameSize = (int) ((double) this.trueWidth * 0.885); } else { frameSize = (int) ((double) this.trueHeight * 0.83); // the int value of the pixels used for the this.newWidth = (this.trueWidth - frameSize) / 2; this.newHeight = (this.trueHeight - frameSize) / 2; } } /* * to resize if the frame size is being changed */ public void reSize(){ this.getTrueSize(this.getContentPane().getWidth(), this.getContentPane().getHeight()); this.actionPanel.setPreferredSize(new Dimension(trueWidth,newHeight)); this.scorePanel.setPreferredSize(new Dimension(trueWidth,newHeight)); this.eastPanel.setPreferredSize(new Dimension(newWidth,trueHeight)); this.westPanel.setPreferredSize(new Dimension(newWidth,trueHeight)); } }
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.UserNotification.Type; import edu.harvard.iq.dataverse.authorization.Permission; import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser; import edu.harvard.iq.dataverse.engine.command.Command; import edu.harvard.iq.dataverse.engine.command.exception.CommandException; import edu.harvard.iq.dataverse.engine.command.impl.CreateDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.DeleteDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.PublishDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.UpdateDataverseCommand; import edu.harvard.iq.dataverse.util.JsfHelper; import static edu.harvard.iq.dataverse.util.JsfHelper.JH; import java.util.List; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import java.util.ArrayList; import java.util.logging.Logger; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import org.primefaces.model.DualListModel; import java.net.InetAddress; import java.net.UnknownHostException; import javax.ejb.EJBException; import javax.faces.model.SelectItem; import org.apache.commons.lang.StringUtils; /** * * @author gdurand */ @ViewScoped @Named("DataversePage") public class DataversePage implements java.io.Serializable { private static final Logger logger = Logger.getLogger(DataversePage.class.getCanonicalName()); public enum EditMode { CREATE, INFO, PERMISSIONS, SETUP, THEME } @EJB DataverseServiceBean dataverseService; @EJB DatasetServiceBean datasetService; @Inject DataverseSession session; @EJB EjbDataverseEngine commandEngine; @EJB SearchServiceBean searchService; @EJB DatasetFieldServiceBean datasetFieldService; @EJB DataverseFacetServiceBean dataverseFacetService; @EJB UserNotificationServiceBean userNotificationService; @EJB FeaturedDataverseServiceBean featuredDataverseService; @EJB DataverseFieldTypeInputLevelServiceBean dataverseFieldTypeInputLevelService; @EJB PermissionServiceBean permissionService; private Dataverse dataverse = new Dataverse(); private EditMode editMode; private Long ownerId; private DualListModel<DatasetFieldType> facets; private DualListModel<Dataverse> featuredDataverses; // private TreeNode treeWidgetRootNode = new DefaultTreeNode("Root", null); public Dataverse getDataverse() { return dataverse; } public void setDataverse(Dataverse dataverse) { this.dataverse = dataverse; } public EditMode getEditMode() { return editMode; } public void setEditMode(EditMode editMode) { this.editMode = editMode; } public Long getOwnerId() { return ownerId; } public void setOwnerId(Long ownerId) { this.ownerId = ownerId; } // public TreeNode getTreeWidgetRootNode() { // return treeWidgetRootNode; // public void setTreeWidgetRootNode(TreeNode treeWidgetRootNode) { // this.treeWidgetRootNode = treeWidgetRootNode; public String init() { if (dataverse.getAlias() != null || dataverse.getId() != null || ownerId == null ){// view mode for a dataverse if (dataverse.getAlias() != null) { dataverse = dataverseService.findByAlias(dataverse.getAlias()); } else if (dataverse.getId() != null) { dataverse = dataverseService.find(dataverse.getId()); } else { try { dataverse = dataverseService.findRootDataverse(); } catch (EJBException e) { // @todo handle case with no root dataverse (a fresh installation) with message about using API to create the root dataverse = null; } } if (dataverse == null) { return "/404.xhtml"; } if (!dataverse.isReleased() && !permissionService.on(dataverse).has(Permission.ViewUnpublishedDataverse)) { return "/loginpage.xhtml" + DataverseHeaderFragment.getRedirectPage(); } ownerId = dataverse.getOwner() != null ? dataverse.getOwner().getId() : null; } else { // ownerId != null; create mode for a new child dataverse editMode = EditMode.INFO; dataverse.setOwner(dataverseService.find(ownerId)); if (dataverse.getOwner() == null) { return "/404.xhtml"; } else if (!permissionService.on(dataverse.getOwner()).has(Permission.AddDataverse)) { return "/loginpage.xhtml" + DataverseHeaderFragment.getRedirectPage(); } // set defaults - contact e-mail and affiliation from user dataverse.getDataverseContacts().add(new DataverseContact(session.getUser().getDisplayInfo().getEmailAddress())); dataverse.setAffiliation(session.getUser().getDisplayInfo().getAffiliation()); // FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Create New Dataverse", " - Create a new dataverse that will be a child dataverse of the parent you clicked from. Asterisks indicate required fields.")); } List<DatasetFieldType> facetsSource = new ArrayList<>(); List<DatasetFieldType> facetsTarget = new ArrayList<>(); facetsSource.addAll(datasetFieldService.findAllFacetableFieldTypes()); List<DataverseFacet> facetsList = dataverseFacetService.findByDataverseId(dataverse.getFacetRootId()); for (DataverseFacet dvFacet : facetsList) { DatasetFieldType dsfType = dvFacet.getDatasetFieldType(); facetsTarget.add(dsfType); facetsSource.remove(dsfType); } facets = new DualListModel<>(facetsSource, facetsTarget); List<Dataverse> featuredSource = new ArrayList<>(); List<Dataverse> featuredTarget = new ArrayList<>(); featuredSource.addAll(dataverseService.findAllPublishedByOwnerId(dataverse.getId())); List<DataverseFeaturedDataverse> featuredList = featuredDataverseService.findByDataverseId(dataverse.getId()); for (DataverseFeaturedDataverse dfd : featuredList) { Dataverse fd = dfd.getFeaturedDataverse(); featuredTarget.add(fd); featuredSource.remove(fd); } featuredDataverses = new DualListModel<>(featuredSource, featuredTarget); refreshAllMetadataBlocks(); return null; } public List<Dataverse> getCarouselFeaturedDataverses() { List<Dataverse> retList = new ArrayList(); List<DataverseFeaturedDataverse> featuredList = featuredDataverseService.findByDataverseId(dataverse.getId()); for (DataverseFeaturedDataverse dfd : featuredList) { Dataverse fd = dfd.getFeaturedDataverse(); retList.add(fd); } return retList; } public List getContents() { List contentsList = dataverseService.findByOwnerId(dataverse.getId()); contentsList.addAll(datasetService.findByOwnerId(dataverse.getId())); return contentsList; } public void edit(EditMode editMode) { this.editMode = editMode; if (editMode == EditMode.INFO) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Edit Dataverse", " - Edit your dataverse and click Save. Asterisks indicate required fields.")); } else if (editMode == EditMode.SETUP) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Edit Dataverse Setup", " - Edit the Metadata Blocks and Facets you want to associate with your dataverse. Note: facets will appear in the order shown on the list.")); } } public void refresh(){ } private boolean openMetadataBlock; public boolean isOpenMetadataBlock() { return openMetadataBlock; } public void setOpenMetadataBlock(boolean openMetadataBlock) { this.openMetadataBlock = openMetadataBlock; } public void showDatasetFieldTypes(Long mdbId) { for (MetadataBlock mdb : allMetadataBlocks){ if(mdb.getId().equals(mdbId)){ mdb.setShowDatasetFieldTypes(true); openMetadataBlock = true; } } } public void hideDatasetFieldTypes(Long mdbId) { for (MetadataBlock mdb : allMetadataBlocks){ if(mdb.getId().equals(mdbId)){ mdb.setShowDatasetFieldTypes(false); openMetadataBlock = false; } } } public void updateInclude(Long mdbId, long dsftId) { List<DatasetFieldType> childDSFT = new ArrayList(); for (MetadataBlock mdb : allMetadataBlocks) { if (mdb.getId().equals(mdbId)) { for (DatasetFieldType dsftTest : mdb.getDatasetFieldTypes()) { if (dsftTest.getId().equals(dsftId)) { dsftTest.setOptionSelectItems(resetSelectItems(dsftTest)); if ((dsftTest.isHasParent() && !dsftTest.getParentDatasetFieldType().isInclude()) || (!dsftTest.isHasParent() && !dsftTest.isInclude())){ dsftTest.setRequiredDV(false); } if (dsftTest.isHasChildren() && !dsftTest.isInclude()) { childDSFT.addAll(dsftTest.getChildDatasetFieldTypes()); } } } } } if (!childDSFT.isEmpty()) { for (DatasetFieldType dsftUpdate : childDSFT) { for (MetadataBlock mdb : allMetadataBlocks) { if (mdb.getId().equals(mdbId)) { for (DatasetFieldType dsftTest : mdb.getDatasetFieldTypes()) { if (dsftTest.getId().equals(dsftUpdate.getId())) { dsftTest.setOptionSelectItems(resetSelectItems(dsftTest)); } } } } } } } public List<SelectItem> resetSelectItems(DatasetFieldType typeIn){ List retList = new ArrayList(); if ((typeIn.isHasParent() && typeIn.getParentDatasetFieldType().isInclude()) || (!typeIn.isHasParent() && typeIn.isInclude())){ SelectItem requiredItem = new SelectItem(); requiredItem.setLabel("Required"); requiredItem.setValue(true); retList.add(requiredItem); SelectItem optional = new SelectItem(); optional.setLabel("Optional"); optional.setValue(false); retList.add(optional); } else { SelectItem hidden = new SelectItem(); hidden.setLabel("Hidden"); hidden.setValue(false); hidden.setDisabled(true); retList.add(hidden); } return retList; } public void updateRequiredDatasetFieldTypes(Long mdbId, Long dsftId, boolean inVal) { for (MetadataBlock mdb : allMetadataBlocks){ if(mdb.getId().equals(mdbId)){ for (DatasetFieldType dsft : mdb.getDatasetFieldTypes()){ if (dsft.getId().equals(dsftId)){ dsft.setRequiredDV(!inVal); } } } } } public void updateOptionsRadio(Long mdbId, Long dsftId) { for (MetadataBlock mdb : allMetadataBlocks){ if(mdb.getId().equals(mdbId)){ for (DatasetFieldType dsft : mdb.getDatasetFieldTypes()){ if (dsft.getId().equals(dsftId)){ dsft.setOptionSelectItems(resetSelectItems(dsft)); } } } } } public String save() { List<DataverseFieldTypeInputLevel> listDFTIL = new ArrayList(); List<MetadataBlock> selectedBlocks = new ArrayList(); if (dataverse.isMetadataBlockRoot()) { dataverse.getMetadataBlocks().clear(); } for (MetadataBlock mdb : this.allMetadataBlocks) { if (dataverse.isMetadataBlockRoot() && (mdb.isSelected() || mdb.isRequired())) { selectedBlocks.add(mdb); for (DatasetFieldType dsft : mdb.getDatasetFieldTypes()) { if (dsft.isRequiredDV() && !dsft.isRequired() && ((!dsft.isHasParent() && dsft.isInclude()) || (dsft.isHasParent() && dsft.getParentDatasetFieldType().isInclude()))) { DataverseFieldTypeInputLevel dftil = new DataverseFieldTypeInputLevel(); dftil.setDatasetFieldType(dsft); dftil.setDataverse(dataverse); dftil.setRequired(true); dftil.setInclude(true); listDFTIL.add(dftil); } if ( (!dsft.isHasParent() && !dsft.isInclude()) || (dsft.isHasParent() && !dsft.getParentDatasetFieldType().isInclude())) { DataverseFieldTypeInputLevel dftil = new DataverseFieldTypeInputLevel(); dftil.setDatasetFieldType(dsft); dftil.setDataverse(dataverse); dftil.setRequired(false); dftil.setInclude(false); listDFTIL.add(dftil); } } } } if (!selectedBlocks.isEmpty()) { dataverse.setMetadataBlocks(selectedBlocks); } if(!dataverse.isFacetRoot()){ facets.getTarget().clear(); } Command<Dataverse> cmd = null; //TODO change to Create - for now the page is expecting INFO instead. Boolean create; if (dataverse.getId() == null) { dataverse.setOwner(ownerId != null ? dataverseService.find(ownerId) : null); create = Boolean.TRUE; cmd = new CreateDataverseCommand(dataverse, session.getUser(), facets.getTarget(), listDFTIL); } else { create=Boolean.FALSE; cmd = new UpdateDataverseCommand(dataverse, facets.getTarget(), featuredDataverses.getTarget(), session.getUser(), listDFTIL); } try { dataverse = commandEngine.submit(cmd); if (session.getUser() instanceof AuthenticatedUser) { userNotificationService.sendNotification((AuthenticatedUser) session.getUser(), dataverse.getCreateDate(), Type.CREATEDV, dataverse.getId()); } editMode = null; } catch (CommandException ex) { JH.addMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage()); return null; } String msg = (create)? "You have successfully created your dataverse.": "You have successfully updated your dataverse."; JsfHelper.addSuccessMessage(msg); return "/dataverse.xhtml?alias=" + dataverse.getAlias() + "&faces-redirect=true"; } public void cancel(ActionEvent e) { // reset values dataverse = dataverseService.find(dataverse.getId()); ownerId = dataverse.getOwner() != null ? dataverse.getOwner().getId() : null; editMode = null; } public boolean isRootDataverse() { return dataverse.getOwner() == null; } public Dataverse getOwner() { return (ownerId != null) ? dataverseService.find(ownerId) : null; } // METHODS for Dataverse Setup public boolean isInheritMetadataBlockFromParent() { return !dataverse.isMetadataBlockRoot(); } public void setInheritMetadataBlockFromParent(boolean inheritMetadataBlockFromParent) { dataverse.setMetadataBlockRoot(!inheritMetadataBlockFromParent); } public void editMetadataBlocks() { refreshAllMetadataBlocks(); } public boolean isInheritFacetFromParent() { return !dataverse.isFacetRoot(); } public void setInheritFacetFromParent(boolean inheritFacetFromParent) { dataverse.setFacetRoot(!inheritFacetFromParent); } public void editFacets() { List<DatasetFieldType> facetsSource = new ArrayList<>(); List<DatasetFieldType> facetsTarget = new ArrayList<>(); facetsSource.addAll(datasetFieldService.findAllFacetableFieldTypes()); List<DataverseFacet> facetsList = dataverseFacetService.findByDataverseId(dataverse.getFacetRootId()); for (DataverseFacet dvFacet : facetsList) { DatasetFieldType dsfType = dvFacet.getDatasetFieldType(); facetsTarget.add(dsfType); facetsSource.remove(dsfType); } facets = new DualListModel<>(facetsSource, facetsTarget); } public DualListModel<DatasetFieldType> getFacets() { return facets; } public void setFacets(DualListModel<DatasetFieldType> facets) { this.facets = facets; } public DualListModel<Dataverse> getFeaturedDataverses() { return featuredDataverses; } public void setFeaturedDataverses(DualListModel<Dataverse> featuredDataverses) { this.featuredDataverses = featuredDataverses; } public String releaseDataverse() { PublishDataverseCommand cmd = new PublishDataverseCommand(session.getUser(), dataverse); try { commandEngine.submit(cmd); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseReleased", "Your dataverse is now public."); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?alias=" + dataverse.getAlias() + "&faces-redirect=true"; } catch (CommandException ex) { String msg = "There was a problem publishing your dataverse: " + ex; logger.severe(msg); /** * @todo how do we get this message to show up in the GUI? */ FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseNotReleased", msg); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?alias=" + dataverse.getAlias() + "&faces-redirect=true"; } } public String deleteDataverse() { DeleteDataverseCommand cmd = new DeleteDataverseCommand(session.getUser(), dataverse); try { commandEngine.submit(cmd); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseDeleted", "Your dataverse ihas been deleted."); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?alias=" + dataverse.getOwner().getAlias() + "&faces-redirect=true"; } catch (CommandException ex) { String msg = "There was a problem deleting your dataverse: " + ex; logger.severe(msg); /** * @todo how do we get this message to show up in the GUI? */ FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseNotDeleted", msg); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?alias=" + dataverse.getAlias() + "&faces-redirect=true"; } } public String getMetadataBlockPreview(MetadataBlock mdb, int numberOfItems) { /// for beta, we will just preview the first n fields StringBuilder mdbPreview = new StringBuilder(); int count = 0; for (DatasetFieldType dsfType : mdb.getDatasetFieldTypes()) { if (!dsfType.isChild()) { if (count != 0) { mdbPreview.append(", "); if (count == numberOfItems) { mdbPreview.append("etc."); break; } } mdbPreview.append(dsfType.getDisplayName()); count++; } } return mdbPreview.toString(); } public Boolean isEmptyDataverse() { return !dataverseService.hasData(dataverse); } private List<MetadataBlock> allMetadataBlocks; public List<MetadataBlock> getAllMetadataBlocks() { return this.allMetadataBlocks; } public void setAllMetadataBlocks(List<MetadataBlock> inBlocks) { this.allMetadataBlocks = inBlocks; } private void refreshAllMetadataBlocks() { Long dataverseIdForInputLevel = dataverse.getId(); List<MetadataBlock> retList = new ArrayList(); for (MetadataBlock mdb : dataverseService.findAllMetadataBlocks()) { mdb.setSelected(false); mdb.setShowDatasetFieldTypes(false); if (!dataverse.isMetadataBlockRoot() && dataverse.getOwner() != null) { dataverseIdForInputLevel = dataverse.getMetadataRootId(); for (MetadataBlock mdbTest : dataverse.getOwner().getMetadataBlocks()) { if (mdb.equals(mdbTest)) { mdb.setSelected(true); } } } else { for (MetadataBlock mdbTest : dataverse.getMetadataBlocks(true)) { if (mdb.equals(mdbTest)) { mdb.setSelected(true); } } } for (DatasetFieldType dsft : mdb.getDatasetFieldTypes()) { DataverseFieldTypeInputLevel dsfIl = dataverseFieldTypeInputLevelService.findByDataverseIdDatasetFieldTypeId(dataverseIdForInputLevel, dsft.getId()); if (dsfIl != null) { dsft.setRequiredDV(dsfIl.isRequired()); dsft.setInclude(dsfIl.isInclude()); } else { dsft.setRequiredDV(dsft.isRequired()); dsft.setInclude(true); } dsft.setOptionSelectItems(resetSelectItems(dsft)); } retList.add(mdb); } setAllMetadataBlocks(retList); } public void validateAlias(FacesContext context, UIComponent toValidate, Object value) { if (!StringUtils.isEmpty((String)value)) { String alias = (String) value; boolean aliasFound = false; Dataverse dv = dataverseService.findByAlias(alias); if (editMode == DataversePage.EditMode.CREATE) { if (dv != null) { aliasFound = true; } } else { if (dv != null && !dv.getId().equals(dataverse.getId())) { aliasFound = true; } } if (aliasFound) { ((UIInput) toValidate).setValid(false); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "alias", "This Alias is already taken."); context.addMessage(toValidate.getClientId(context), message); } } } }
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.UserNotification.Type; import edu.harvard.iq.dataverse.engine.command.Command; import edu.harvard.iq.dataverse.engine.command.exception.CommandException; import edu.harvard.iq.dataverse.engine.command.impl.CreateDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.DeleteDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.PublishDataverseCommand; import edu.harvard.iq.dataverse.engine.command.impl.UpdateDataverseCommand; import static edu.harvard.iq.dataverse.util.JsfHelper.JH; import java.util.List; import javax.ejb.EJB; import javax.ejb.EJBException; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.NoResultException; import java.util.ArrayList; import java.util.logging.Logger; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import org.primefaces.model.DualListModel; import java.net.InetAddress; import java.net.UnknownHostException; /** * * @author gdurand */ @ViewScoped @Named("DataversePage") public class DataversePage implements java.io.Serializable { private static final Logger logger = Logger.getLogger(DataversePage.class.getCanonicalName()); public enum EditMode { CREATE, INFO, PERMISSIONS, SETUP, THEME } @EJB DataverseServiceBean dataverseService; @EJB DatasetServiceBean datasetService; @Inject DataverseSession session; @EJB EjbDataverseEngine commandEngine; @EJB SearchServiceBean searchService; @EJB DatasetFieldServiceBean datasetFieldService; @EJB DataverseFacetServiceBean dataverseFacetService; @EJB UserNotificationServiceBean userNotificationService; @EJB FeaturedDataverseServiceBean featuredDataverseService; private Dataverse dataverse = new Dataverse(); private EditMode editMode; private Long ownerId; private DualListModel<DatasetFieldType> facets; private DualListModel<Dataverse> featuredDataverses; // private TreeNode treeWidgetRootNode = new DefaultTreeNode("Root", null); public Dataverse getDataverse() { return dataverse; } public void setDataverse(Dataverse dataverse) { this.dataverse = dataverse; } public EditMode getEditMode() { return editMode; } public void setEditMode(EditMode editMode) { this.editMode = editMode; } public Long getOwnerId() { return ownerId; } public void setOwnerId(Long ownerId) { this.ownerId = ownerId; } // public TreeNode getTreeWidgetRootNode() { // return treeWidgetRootNode; // public void setTreeWidgetRootNode(TreeNode treeWidgetRootNode) { // this.treeWidgetRootNode = treeWidgetRootNode; public void init() { // FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Create Root Dataverse", " - To get started, you need to create your root dataverse.")); if (dataverse.getId() != null) { // view mode for a dataverse dataverse = dataverseService.find(dataverse.getId()); ownerId = dataverse.getOwner() != null ? dataverse.getOwner().getId() : null; } else if (ownerId != null) { // create mode for a new child dataverse editMode = EditMode.INFO; dataverse.setOwner(dataverseService.find(ownerId)); dataverse.setContactEmail(session.getUser().getEmail()); dataverse.setAffiliation(session.getUser().getAffiliation()); // FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Create New Dataverse", " - Create a new dataverse that will be a child dataverse of the parent you clicked from. Asterisks indicate required fields.")); } else { // view mode for root dataverse (or create root dataverse) try { dataverse = dataverseService.findRootDataverse(); } catch (EJBException e) { if (e.getCause() instanceof NoResultException) { editMode = EditMode.INFO; FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Create Root Dataverse", " - To get started, you need to create your root dataverse. Asterisks indicate required fields.")); } else { throw e; } } } List<DatasetFieldType> facetsSource = new ArrayList<>(); List<DatasetFieldType> facetsTarget = new ArrayList<>(); facetsSource.addAll(datasetFieldService.findAllFacetableFieldTypes()); List<DataverseFacet> facetsList = dataverseFacetService.findByDataverseId(dataverse.getId()); for (DataverseFacet dvFacet : facetsList) { DatasetFieldType dsfType = dvFacet.getDatasetFieldType(); facetsTarget.add(dsfType); facetsSource.remove(dsfType); } facets = new DualListModel<>(facetsSource, facetsTarget); List<Dataverse> featuredSource = new ArrayList<>(); List<Dataverse> featuredTarget = new ArrayList<>(); featuredSource.addAll(dataverseService.findAllPublishedByOwnerId(dataverse.getId())); List<DataverseFeaturedDataverse> featuredList = featuredDataverseService.findByDataverseId(dataverse.getId()); for (DataverseFeaturedDataverse dfd : featuredList) { Dataverse fd = dfd.getFeaturedDataverse(); featuredTarget.add(fd); featuredSource.remove(fd); } featuredDataverses = new DualListModel<>(featuredSource, featuredTarget); } // TODO: // this method will need to be moved somewhere else, possibly some // equivalent of the old VDCRequestBean - but maybe application-scoped? // -- L.A. 4.0 beta public String getDvnUrl() { String hostUrl = System.getProperty("dataverse.siteUrl"); if (hostUrl != null && !"".equals(hostUrl)) { return hostUrl; } String hostName = System.getProperty("dataverse.fqdn"); if (hostName == null) { try { hostName = InetAddress.getLocalHost().getCanonicalHostName(); } catch (UnknownHostException e) { return null; } } hostUrl = "http://"+hostName; return hostUrl; } public List<Dataverse> getCarouselFeaturedDataverses() { List<Dataverse> retList = new ArrayList(); List<DataverseFeaturedDataverse> featuredList = featuredDataverseService.findByDataverseId(dataverse.getId()); for (DataverseFeaturedDataverse dfd : featuredList) { Dataverse fd = dfd.getFeaturedDataverse(); retList.add(fd); } return retList; } public List getContents() { List contentsList = dataverseService.findByOwnerId(dataverse.getId()); contentsList.addAll(datasetService.findByOwnerId(dataverse.getId())); return contentsList; } public void edit(EditMode editMode) { this.editMode = editMode; if (editMode == EditMode.INFO) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Edit Dataverse", " - Edit your dataverse and click Save. Asterisks indicate required fields.")); } else if (editMode == EditMode.SETUP) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Edit Dataverse Setup", " - Edit the Metadata Blocks and Facets you want to associate with your dataverse. Note: facets will appear in the order shown on the list.")); } } public String save() { Command<Dataverse> cmd = null; //TODO change to Create - for now the page is expecting INFO instead. if (dataverse.getId() == null) { dataverse.setOwner(ownerId != null ? dataverseService.find(ownerId) : null); cmd = new CreateDataverseCommand(dataverse, session.getUser()); } else { cmd = new UpdateDataverseCommand(dataverse, facets.getTarget(), featuredDataverses.getTarget(), session.getUser()); } try { dataverse = commandEngine.submit(cmd); userNotificationService.sendNotification(session.getUser(), dataverse.getCreateDate(), Type.CREATEDV, dataverse.getId()); editMode = null; } catch (CommandException ex) { JH.addMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage()); return null; } return "/dataverse.xhtml?id=" + dataverse.getId() + "&faces-redirect=true"; } public void cancel(ActionEvent e) { // reset values dataverse = dataverseService.find(dataverse.getId()); ownerId = dataverse.getOwner() != null ? dataverse.getOwner().getId() : null; editMode = null; } public boolean isRootDataverse() { return dataverse.getOwner() == null; } public Dataverse getOwner() { return (ownerId != null) ? dataverseService.find(ownerId) : null; } // METHODS for Dataverse Setup public boolean isInheritMetadataBlockFromParent() { return !dataverse.isMetadataBlockRoot(); } public void setInheritMetadataBlockFromParent(boolean inheritMetadataBlockFromParent) { dataverse.setMetadataBlockRoot(!inheritMetadataBlockFromParent); } public void editMetadataBlocks() { if (dataverse.isMetadataBlockRoot()) { dataverse.getMetadataBlocks().addAll(dataverse.getOwner().getMetadataBlocks()); } else { dataverse.getMetadataBlocks(true).clear(); } } public boolean isInheritFacetFromParent() { return !dataverse.isFacetRoot(); } public void setInheritFacetFromParent(boolean inheritFacetFromParent) { dataverse.setFacetRoot(!inheritFacetFromParent); } public void editFacets() { if (dataverse.isFacetRoot()) { dataverse.getDataverseFacets().addAll(dataverse.getOwner().getDataverseFacets()); } else { dataverse.getDataverseFacets(true).clear(); } } public DualListModel<DatasetFieldType> getFacets() { return facets; } public void setFacets(DualListModel<DatasetFieldType> facets) { this.facets = facets; } public DualListModel<Dataverse> getFeaturedDataverses() { return featuredDataverses; } public void setFeaturedDataverses(DualListModel<Dataverse> featuredDataverses) { this.featuredDataverses = featuredDataverses; } public String releaseDataverse() { PublishDataverseCommand cmd = new PublishDataverseCommand(session.getUser(), dataverse); try { commandEngine.submit(cmd); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseReleased", "Your dataverse is now public."); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?id=" + dataverse.getId() + "&faces-redirect=true"; } catch (CommandException ex) { String msg = "There was a problem publishing your dataverse: " + ex; logger.severe(msg); /** * @todo how do we get this message to show up in the GUI? */ FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseNotReleased", msg); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?id=" + dataverse.getId() + "&faces-redirect=true"; } } public String deleteDataverse() { DeleteDataverseCommand cmd = new DeleteDataverseCommand(session.getUser(), dataverse); try { commandEngine.submit(cmd); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseDeleted", "Your dataverse ihas been deleted."); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?id=" + dataverse.getOwner().getId() + "&faces-redirect=true"; } catch (CommandException ex) { String msg = "There was a problem deleting your dataverse: " + ex; logger.severe(msg); /** * @todo how do we get this message to show up in the GUI? */ FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "DataverseNotDeleted", msg); FacesContext.getCurrentInstance().addMessage(null, message); return "/dataverse.xhtml?id=" + dataverse.getId() + "&faces-redirect=true"; } } public String getMetadataBlockPreview(MetadataBlock mdb, int numberOfItems) { /// for beta, we will just preview the first n fields StringBuilder mdbPreview = new StringBuilder(); int count = 0; for (DatasetFieldType dsfType : mdb.getDatasetFieldTypes()) { if (!dsfType.isChild()) { if (count != 0) { mdbPreview.append(", "); if (count == numberOfItems) { mdbPreview.append("etc."); break; } } mdbPreview.append(dsfType.getDisplayName()); count++; } } return mdbPreview.toString(); } public Boolean isEmptyDataverse() { return !dataverseService.hasData(dataverse); } public void validateAlias(FacesContext context, UIComponent toValidate, Object value) { String alias = (String) value; boolean aliasFound = false; Dataverse dv = dataverseService.findByAlias(alias); if (editMode == DataversePage.EditMode.CREATE) { if (dv != null) { aliasFound = true; } } else { if (dv != null && !dv.getId().equals(dataverse.getId())) { aliasFound = true; } } if (aliasFound) { ((UIInput) toValidate).setValid(false); FacesMessage message = new FacesMessage("This Alias is already taken."); context.addMessage(toValidate.getClientId(context), message); } } }
package edu.hm.hafner.analysis; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; /** * Computes old, new, and fixed issues based on the reports of two consecutive static analysis runs for the same * software artifact. * * @author Ullrich Hafner */ public class IssueDifference { private static final List<Issue> EMPTY = Collections.emptyList(); private final Report newIssues; private final Report fixedIssues; private final Report outstandingIssues; private final Map<Integer, List<Issue>> referencesByHash; private final Map<String, List<Issue>> referencesByFingerprint; /** * Creates a new instance of {@link IssueDifference}. * * @param currentIssues * the issues of the current report * @param referenceId * ID identifying the reference report * @param referenceIssues * the issues of a previous report (reference) */ public IssueDifference(final Report currentIssues, final String referenceId, final Report referenceIssues) { newIssues = currentIssues.copy(); fixedIssues = referenceIssues.copy(); outstandingIssues = new Report(); referencesByHash = new HashMap<>(); referencesByFingerprint = new HashMap<>(); for (Issue issue : referenceIssues) { addIssueToMap(referencesByHash, issue.hashCode(), issue); addIssueToMap(referencesByFingerprint, issue.getFingerprint(), issue); } List<UUID> removed = matchIssuesByEquals(currentIssues); Report secondPass = currentIssues.copy(); removed.forEach(secondPass::remove); matchIssuesByFingerprint(secondPass); newIssues.forEach(issue -> issue.setReference(referenceId)); } private List<UUID> matchIssuesByEquals(final Report currentIssues) { List<UUID> removedIds = new ArrayList<>(); for (Issue current : currentIssues) { List<Issue> equalIssues = findReferenceByEquals(current); if (!equalIssues.isEmpty()) { removedIds.add(remove(current, selectIssueWithSameFingerprint(current, equalIssues))); } } return removedIds; } private void matchIssuesByFingerprint(final Report currentIssues) { for (Issue current : currentIssues) { findReferenceByFingerprint(current).ifPresent(issue -> remove(current, issue)); } } private <K> void addIssueToMap(final Map<K, List<Issue>> map, final K key, final Issue issue) { map.computeIfAbsent(key, k -> new ArrayList<>()).add(issue); } private <K> void removeIssueFromMap(final Map<K, List<Issue>> map, final K key, final Issue issue) { List<Issue> issues = map.get(key); issues.remove(issue); if (issues.isEmpty()) { map.remove(key); } } private UUID remove(final Issue current, final Issue oldIssue) { UUID id = current.getId(); Issue issueWithLatestProperties = newIssues.remove(id); issueWithLatestProperties.setReference(oldIssue.getReference()); outstandingIssues.add(issueWithLatestProperties); fixedIssues.remove(oldIssue.getId()); removeIssueFromMap(referencesByFingerprint, oldIssue.getFingerprint(), oldIssue); removeIssueFromMap(referencesByHash, oldIssue.hashCode(), oldIssue); return id; } private Issue selectIssueWithSameFingerprint(final Issue current, final List<Issue> equalIssues) { return equalIssues.stream() .filter(issue -> issue.getFingerprint().equals(current.getFingerprint())) .findFirst() .orElse(equalIssues.get(0)); } private Optional<Issue> findReferenceByFingerprint(final Issue current) { return referencesByFingerprint.getOrDefault(current.getFingerprint(), EMPTY).stream().findAny(); } private List<Issue> findReferenceByEquals(final Issue current) { List<Issue> equalIssues = new ArrayList<>(); for (Issue reference : referencesByHash.getOrDefault(current.hashCode(), EMPTY)) { if (current.equals(reference)) { equalIssues.add(reference); } } return equalIssues; } /** * Returns the outstanding issues. I.e. all issues, that are part of the previous report and that are still part of * the current report. * * @return the outstanding issues */ public Report getOutstandingIssues() { return outstandingIssues; } /** * Returns the new issues. I.e. all issues, that are part of the current report but that have not been shown up in * the previous report. * * @return the new issues */ public Report getNewIssues() { return newIssues; } /** * Returns the fixed issues. I.e. all issues, that are part of the previous report but that are not present in the * current report anymore. * * @return the fixed issues */ public Report getFixedIssues() { return fixedIssues; } }
package bugfree.example; import static org.assertj.core.api.BDDAssertions.then; import org.junit.Test; /** * This is an example whose goal is to show that writing the simplest code first * and them add code only driven by additional requirements helps avoid trivial * but dangerous bugs. * * @author ste */ public class BugFreeSimplestFirst { @Test public void setValidationKeyValid_sets_validation_key_by_user() { ActivationKeyDAO dao = new ActivationKeyDAO(); // set validation key for a user for (String username: new String[] {"user-one", "user-two", "user-three"}) { for (boolean value: new boolean[] {true, false, false, true}) { dao.setValidationKeyValidity(username, value); then(dao.isValidationKeyValid(username)).isEqualTo(value); } } } @Test public void validation_key_is_invalid_if_the_user_does_not_exist() { ActivationKeyDAO dao = new ActivationKeyDAO(); // no validations so far... for (String username: new String[] {"user-one", "user-two", "user-three"}) { then(dao.isValidationKeyValid(username)).isFalse(); } // adding some validation dao.setValidationKeyValidity("anotheruser1", true); dao.setValidationKeyValidity("anotheruser2", false); for (String username: new String[] {"user-one", "user-two", "user-three"}) { then(dao.isValidationKeyValid(username)).isFalse(); } } @Test public void isValidationKeyValid_returns_true_if_validation_key_is_valid() { } }
package ee.tuleva.onboarding.config; import lombok.extern.slf4j.Slf4j; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import org.springframework.web.filter.GenericFilterBean; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; import java.util.List; @Slf4j @Component @Order(Ordered.HIGHEST_PRECEDENCE) public class CORSFilter extends GenericFilterBean { String DEFAULT_ALLOWED_ORIGIN = "https://pension.tuleva.ee"; private List<String> allowedOrigins = Arrays.asList(DEFAULT_ALLOWED_ORIGIN, "https://tuleva.ee"); @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; String origin = request.getHeader("Origin"); String allowedOriginResponse = allowedOrigins.contains(origin) ? origin : DEFAULT_ALLOWED_ORIGIN; response.setHeader("Access-Control-Allow-Origin", allowedOriginResponse); response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Authorization"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("P3P", "CP=\"ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI\""); List<String> allowedHeaders = Arrays.asList( "x-requested-with", "x-statistics-identifier", HttpHeaders.CONTENT_TYPE, HttpHeaders.AUTHORIZATION, HttpHeaders.USER_AGENT, HttpHeaders.ORIGIN, HttpHeaders.ACCEPT ); response.setHeader("Access-Control-Allow-Headers", String.join(", ", allowedHeaders)); if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, res); } } }
package ganymedes01.etfuturum.blocks; import ganymedes01.etfuturum.EtFuturum; import ganymedes01.etfuturum.IConfigurable; import ganymedes01.etfuturum.core.utils.Utils; import ganymedes01.etfuturum.lib.RenderIDs; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class GrassPath extends Block implements IConfigurable { @SideOnly(Side.CLIENT) private IIcon sideIcon; public GrassPath() { super(Material.grass); setHardness(0.6F); setHarvestLevel("shovel", 0); setStepSound(soundTypeGrass); setBlockTextureName("grass_path"); setBlockName(Utils.getUnlocalisedName("grass_path")); setCreativeTab(EtFuturum.enableGrassPath ? EtFuturum.creativeTab : null); } @Override public Item getItemDropped(int meta, Random rand, int fortune) { return Blocks.dirt.getItemDropped(meta, rand, fortune); } @Override public boolean renderAsNormalBlock() { return false; } @Override public boolean isOpaqueCube() { return false; } @Override public int getRenderType() { return RenderIDs.GRASS_PATH; } @Override public void onNeighborBlockChange(World world, int x, int y, int z, Block block) { if (world.getBlock(x, y + 1, z).isSideSolid(world, x, y + 1, z, ForgeDirection.DOWN)) world.setBlock(x, y, z, Blocks.dirt, 0, 2); } @Override public boolean isSideSolid(IBlockAccess world, int x, int y, int z, ForgeDirection side) { return side != ForgeDirection.UP; } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta) { return side == 0 || side == 1 ? blockIcon : sideIcon; } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister reg) { blockIcon = reg.registerIcon(getTextureName() + "_top"); sideIcon = reg.registerIcon(getTextureName() + "_side"); } @Override public boolean isEnabled() { return EtFuturum.enableGrassPath; } }
package com.github.davidmoten.jns; import static com.github.davidmoten.jns.Util.pressureAtDepth; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.davidmoten.jns.CellImpl.Builder; public class SolverTest { private static final Logger log = LoggerFactory.getLogger(SolverTest.class); private static final double VELOCITY_PRECISION = 0.0000001; private static final double PRESSURE_PRECISION = 0.01; @Test public void testGetVelocityAfterTime() { final Solver solver = new Solver(); final Vector result = solver.getVelocityAfterTime(createCell(), 1); log.info("velocityAfterTime={}", result); checkEquals(Vector.ZERO, result, VELOCITY_PRECISION); } @Test public void testGetVelocityAfterTimeWithRegularGridStillWater() { final Solver solver = new Solver(); final RegularGrid grid = createGrid(); final Cell cell = grid.cell(5, 5, 5); assertNotNull(cell); Vector result = solver.getVelocityAfterTime(cell, 1); checkEquals(Vector.ZERO, result, VELOCITY_PRECISION); } @Test public void testStepWithRegularGridStillWaterCellFromCentreOfGrid() { checkNoChange(5, 5, 5); } @Test public void testStepWithRegularGridStillWaterCellFromBottomOfGrid() { checkNoChange(5, 5, 0); } @Test public void testStepWithRegularGridStillWaterCellFromSurfaceOfGrid() { checkNoChange(5, 5, 9); } @Test public void testStepWithRegularGridStillWaterCellFromEastSideOfGrid() { checkNoChange(0, 5, 5); } @Test public void testStepWithRegularGridStillWaterCellFromNorthSideOfGrid() { checkNoChange(5, 0, 5); } @Test public void testStepWithRegularGridStillWaterCellFromBottomCornerofGrid() { checkNoChange(0, 0, 0); } @Test public void testStepWithRegularGridStillWaterCellFromSurfaceSouthEastCornerofGrid() { checkNoChange(9, 9, 9); } @Test public void testStepWithRegularGrid2DStillWaterCellFromCentreOfGrid() { checkNoChange2D(5, 5, 0); } private void checkNoChange(int eastIndex, int northIndex, int upIndex) { final Solver solver = new Solver(); final RegularGrid grid = createGrid(); final Cell cell = grid.cell(eastIndex, northIndex, upIndex); double pressure = cell.pressure(); assertNotNull(cell); VelocityPressure result = solver.step(cell, 1); checkEquals(Vector.ZERO, result.getVelocity(), VELOCITY_PRECISION); assertEquals(pressure, result.getPressure(), PRESSURE_PRECISION); } private void checkNoChange2D(int eastIndex, int northIndex, int upIndex) { final Solver solver = new Solver(); final RegularGrid grid = createGrid2D(); final Cell cell = grid.cell(eastIndex, northIndex, upIndex); double pressure = cell.pressure(); assertNotNull(cell); VelocityPressure result = solver.step(cell, 1); checkEquals(Vector.ZERO, result.getVelocity(), VELOCITY_PRECISION); assertEquals(pressure, result.getPressure(), PRESSURE_PRECISION); } private RegularGrid createGrid() { return RegularGrid.builder().cellSize(1).cellsEast(10).cellsNorth(10) .cellsUp(10).density(1025).viscosity(30).build(); } private RegularGrid createGrid2D() { return RegularGrid.builder().cellSize(1).cellsEast(10).cellsNorth(10) .cellsUp(1).density(1025).viscosity(30).build(); } private static void checkEquals(Vector a, Vector b, double precision) { assertEquals(a.east(), b.east(), precision); } private static Cell createCell() { final Cell north = builder().position(0, 1, -1).build(); final Cell south = builder().position(0, -1, -1).build(); final Cell east = builder().position(-1, 0, -1).build(); final Cell west = builder().position(1, 0, -1).build(); final Cell up = builder().position(0, 0, 0) .pressure(pressureAtDepth(0)).build(); final Cell down = builder().position(0, 0, -2) .pressure(pressureAtDepth(2)).build(); final Cell centre = builder().position(0, 0, -1).north(north) .south(south).east(east).west(west).up(up).down(down).build(); return centre; } private static Builder builder() { return CellImpl.builder().pressure(pressureAtDepth(1)) .density(Util.DENSITY_KG_PER_M3).viscosity(30) .type(CellType.FLUID).velocity(0, 0, 0); } }
package org.jboss.forge.furnace.maven.plugin; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator; import java.util.ServiceLoader; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.jboss.forge.furnace.addons.AddonId; import org.jboss.forge.furnace.impl.graph.AddonDependencyEdge; import org.jboss.forge.furnace.impl.graph.AddonDependencyEdgeNameProvider; import org.jboss.forge.furnace.impl.graph.AddonVertex; import org.jboss.forge.furnace.impl.graph.AddonVertexNameProvider; import org.jboss.forge.furnace.manager.spi.AddonDependencyResolver; import org.jboss.forge.furnace.manager.spi.AddonInfo; import org.jboss.forge.furnace.repositories.AddonDependencyEntry; import org.jgrapht.DirectedGraph; import org.jgrapht.ext.DOTExporter; import org.jgrapht.ext.IntegerNameProvider; import org.jgrapht.graph.DefaultDirectedGraph; /** * Generate a DOT file from the graph */ @Mojo(defaultPhase = LifecyclePhase.PREPARE_PACKAGE, name = "generate-dot", threadSafe = true) public class GenerateDOTMojo extends AbstractMojo { /** * Output directoy */ @Parameter(defaultValue = "${project.build.outputDirectory}/META-INF/resources") private String outputDirectory; /** * The output filename. Default will be the addonId name (without the groupId) */ @Parameter private String outputFileName; /** * Include transitive addons */ @Parameter private boolean includeTransitiveAddons; /** * Addon IDs to install */ @Parameter private String[] addonIds; /** * Should the produced artifact be attached to the project? */ @Parameter private boolean attach; /** * Skip this execution ? */ @Parameter(property="furnace.dot.skip") private boolean skip; /** * The current maven project */ @Component private MavenProject mavenProject; /** * Maven Project Helper */ @Component private MavenProjectHelper projectHelper; @Override public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info("Execution skipped."); return; } Iterator<AddonDependencyResolver> it = ServiceLoader.load(AddonDependencyResolver.class).iterator(); if (!it.hasNext()) { throw new MojoExecutionException( "No AddonDependencyResolver implementation found. Please add one in the <dependencies> section of the forge-maven-plugin."); } AddonDependencyResolver addonResolver = it.next(); if (addonIds == null || addonIds.length == 0) { // XXX // if (!"forge-addon".equals(mavenProject.getArtifact().getClassifier())) // getLog().warn("No <addonIds> informed and current project is not a forge-addon. Skipping"); // return; AddonId id = AddonId.from(mavenProject.getGroupId() + ":" + mavenProject.getArtifactId(), mavenProject.getVersion()); String fileName = outputFileName == null ? id.getName().substring(id.getName().indexOf(':') + 1) + "-" + id.getVersion() + ".dot" : outputFileName; File file = generateDOTFile(addonResolver, id, fileName); if (attach && file.isFile()) { projectHelper.attachArtifact(mavenProject, "dot", file); } } else { for (String addonId : addonIds) { AddonId id = AddonId.fromCoordinates(addonId); String fileName = id.getName().substring(id.getName().indexOf(':') + 1) + "-" + id.getVersion() + ".dot"; generateDOTFile(addonResolver, id, fileName); } } } /** * Generates the DOT file for a given addonId * * @param addonResolver * @param id * @return generated file */ private File generateDOTFile(AddonDependencyResolver addonResolver, AddonId id, String fileName) { AddonInfo addonInfo = addonResolver.resolveAddonDependencyHierarchy(id); File parent = new File(outputDirectory); parent.mkdirs(); File file = new File(parent, fileName); getLog().info("Generating " + file); toDOT(file, toGraph(addonInfo)); return file; } DirectedGraph<AddonVertex, AddonDependencyEdge> toGraph(AddonInfo info) { DirectedGraph<AddonVertex, AddonDependencyEdge> graph = new DefaultDirectedGraph<AddonVertex, AddonDependencyEdge>( AddonDependencyEdge.class); AddonId addon = info.getAddon(); AddonVertex rootVertex = new AddonVertex(addon.getName(), addon.getVersion()); graph.addVertex(rootVertex); for (AddonDependencyEntry entry : info.getDependencyEntries()) { AddonVertex depVertex = new AddonVertex(entry.getName(), entry.getVersionRange().getMax()); graph.addVertex(depVertex); graph.addEdge(rootVertex, depVertex, new AddonDependencyEdge(entry.getVersionRange(), entry.isExported())); } if (includeTransitiveAddons) { // TODO } return graph; } void toDOT(File file, DirectedGraph<AddonVertex, AddonDependencyEdge> graph) { FileWriter fw = null; try { DOTExporter<AddonVertex, AddonDependencyEdge> exporter = new DOTExporter<AddonVertex, AddonDependencyEdge>( new IntegerNameProvider<AddonVertex>(), new AddonVertexNameProvider(), new AddonDependencyEdgeNameProvider()); fw = new FileWriter(file); exporter.export(fw, graph); fw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null) try { fw.close(); } catch (IOException ignored) { } } } }
package de.bmoth.architecture; import guru.nidi.codeassert.config.AnalyzerConfig; import guru.nidi.codeassert.dependency.DependencyRule; import guru.nidi.codeassert.dependency.DependencyRuler; import guru.nidi.codeassert.dependency.DependencyRules; import guru.nidi.codeassert.model.ModelAnalyzer; import org.junit.Before; import org.junit.Test; import java.io.File; import static guru.nidi.codeassert.junit.CodeAssertMatchers.*; import static org.junit.Assert.assertThat; public class DependencyTest { private String[] packages = new String[] { "app", "backend", "checkers", "eventbus", "modelchecker", "parser" }; private AnalyzerConfig config; @Before public void setup() { // Analyze all sources in src/main/java config = new AnalyzerConfig(); config = config.withSources(new File("src/main/java/de/bmoth"), packages); config = config.withClasses(new File("build/classes/main/de/bmoth"), packages); } @Test public void noCycles() { assertThat(new ModelAnalyzer(config).analyze(), hasNoClassCycles()); assertThat(new ModelAnalyzer(config).analyze(), hasNoPackageCycles()); } @Test public void dependency() { class ExternalPackages extends DependencyRuler { DependencyRule comMicrosoftZ3, comMicrosoftZ3Enumerations, deBmothApp, deBmothBackendZ3, deBmothModelchecker, deBmothModelchecker_, deBmothCheckers_, deSaxsysMvvmfx; @Override public void defineRules() { deBmothApp.mayUse(comMicrosoftZ3, comMicrosoftZ3Enumerations, deSaxsysMvvmfx); deBmothBackendZ3.mustUse(comMicrosoftZ3); deBmothBackendZ3.mayUse(comMicrosoftZ3Enumerations); deBmothModelchecker.mustUse(comMicrosoftZ3); deBmothModelchecker_.mustUse(comMicrosoftZ3); deBmothCheckers_.mustUse(comMicrosoftZ3); } } class InternalPackages extends DependencyRuler { DependencyRule deBmothParserAst, deBmothParserAst_, deBmothParserCst, deBmothParserAstNodes, deBmothParserAstNodesLtl, deBmothParserAstTypes, deBmothParserAstVisitors; @Override public void defineRules() { deBmothParserAst.mustUse(deBmothParserAst_, deBmothParserCst); deBmothParserAstNodes.mustUse(deBmothParserAstTypes); deBmothParserAstVisitors.mustUse(deBmothParserAstNodes, deBmothParserAstNodesLtl); deBmothParserAstNodesLtl.mustUse(deBmothParserAstNodes); } } class DeBmoth extends DependencyRuler { // $self is de.bmoth, added _ refers to subpackages of package DependencyRule app, antlr, backend, backend_, checkers_, eventbus, modelchecker, modelchecker_, parser, parser_, preferences, parserAst; @Override public void defineRules() { app.mayUse(backend_, checkers_, eventbus, modelchecker, modelchecker_, parser, parser_, preferences); backend_.mayUse(preferences, backend, backend_, parser, parser_); checkers_.mayUse(backend, backend_, parser, parser_); modelchecker.mayUse(backend, backend_, parser_); modelchecker_.mayUse(backend_, modelchecker, parser_, preferences); parser.mayUse(antlr, parser_); parser_.mayUse(antlr); parserAst.mayUse(backend); } } // All dependencies are forbidden, except the ones defined above // java, javafx, com and org are ignored // maybe we should include com.microsoft again and check who is // allowed to directly speak to z3 DependencyRules rules = DependencyRules.denyAll().withAbsoluteRules(new InternalPackages()) .withAbsoluteRules(new ExternalPackages()).withRelativeRules(new DeBmoth()) .withExternals("com.google.*", "java.*", "javafx.*", "org.*"); assertThat(new ModelAnalyzer(config).analyze(), packagesMatchExactly(rules)); } }
package info.faceland.strife.effects; import info.faceland.strife.data.StrifeMob; import org.bukkit.Location; import org.bukkit.Sound; public class PlaySound extends Effect { private Sound sound; private float volume; private float pitch; @Override public void apply(StrifeMob caster, StrifeMob target) { Location loc = target.getEntity().getLocation().clone(); loc.getWorld().playSound(loc, sound, volume, pitch); } public void playAtLocation(Location location) { location.getWorld().playSound(location, sound, volume, pitch); } public Sound getSound() { return sound; } public void setSound(Sound sound) { this.sound = sound; } public float getVolume() { return volume; } public void setVolume(float volume) { this.volume = volume; } public float getPitch() { return pitch; } public void setPitch(float pitch) { this.pitch = pitch; } }
package net.imagej.ops; import static org.junit.Assert.assertTrue; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import org.scijava.command.CommandService; import org.scijava.module.ModuleItem; import org.scijava.plugin.Parameter; import org.scijava.util.ClassUtils; import org.scijava.util.ConversionUtils; import org.scijava.util.GenericUtils; import org.scijava.util.MiscUtils; /** * Base class for unit testing of namespaces. In particular, this class has * functionality to verify the completeness of the namespace's built-in method * signatures. * * @author Curtis Rueden */ public abstract class AbstractNamespaceTest extends AbstractOpTest { @Parameter private CommandService commandService; /** * Checks that all ops of the given namespace are "covered" by * {@link OpMethod}-annotated methods declared in the given namespace class. * * @param namespace The namespace of the ops to scrutinize (e.g., "math"). * @param namespaceClass Class with the {@link OpMethod}-annotated methods. */ public void assertComplete(final String namespace, final Class<?> namespaceClass) { boolean success = true; // whether the test will succeed for (final String op : ops.ops()) { final String ns = OpUtils.getNamespace(op); if (!MiscUtils.equal(namespace, ns)) continue; if (!checkComplete(namespaceClass, op)) success = false; } assertTrue("Coverage mismatch", success); } public boolean checkComplete(final Class<?> namespaceClass, final String qName) { final String namespace = OpUtils.getNamespace(qName); final String opName = OpUtils.stripNamespace(qName); // obtain the list of built-in methods final List<Method> allMethods = ClassUtils.getAnnotatedMethods(namespaceClass, OpMethod.class); // obtain the list of ops final Collection<OpInfo> allOps = ops.infos(); // filter methods and ops to only those with the given name final List<Method> methods; final Collection<OpInfo> opList; if (opName == null) { methods = allMethods; opList = allOps; } else { // filter the methods methods = new ArrayList<>(); for (final Method method : allMethods) { if (opName.equals(method.getName())) methods.add(method); } // filter the ops opList = new ArrayList<>(); for (final OpInfo op : allOps) { if (qName.equals(op.getName())) opList.add(op); } } // cross-check them! return checkComplete(namespace, methods, opList); } /** * Checks that the given list of methods corresponds to the specified list of * available ops. The test will fail if either: * <ol> * <li>There is a method that does not correspond to an op; or</li> * <li>There is an op that cannot be invoked by any method.</li> * </ol> * <p> * Note that this test does not verify sanity of either priorities or * {@link Contingent} ops. It assumes that if a candidate's types match, there * might be some possibility that it could potentially match in the proper * circumstances. * </p> * * @param namespace The namespace prefix of the ops in question. * @param methods List of methods. * @param infos List of ops. */ public boolean checkComplete(final String namespace, final Collection<Method> methods, final Collection<? extends OpInfo> infos) { final OpCoverSet coverSet = new OpCoverSet(); boolean success = true; for (final Method method : methods) { final String name = method.getName(); final String qName = namespace == null ? name : namespace + "." + name; if (!checkVarArgs(method)) success = false; for (final Class<? extends Op> opType : opTypes(method)) { if (opType.isInterface()) { if (!checkOpIface(method, qName, opType)) success = false; } else { if (!checkOpImpl(method, qName, opType, coverSet)) success = false; } } } // verify that all ops have been completely covered final StringBuilder missingMessage = new StringBuilder("Missing methods:"); int missingCount = 0; for (final OpInfo info : infos) { int requiredCount = 0, inputCount = 0; for (final ModuleItem<?> input : info.cInfo().inputs()) { if (input.isRequired()) requiredCount++; inputCount++; } for (int argCount = requiredCount; argCount <= inputCount; argCount++) { if (!coverSet.contains(info, argCount)) { missingMessage.append("\n\n" + methodString(info, argCount - requiredCount)); missingCount++; } } } if (missingCount > 0) { error(missingMessage.toString()); success = false; } return success; } // -- Helper methods -- /** * Ensures that, if the method's last argument is an array, it was written as * varargs. * <p> * Good: {@code foo(int a, Number... nums)}<br> * Bad: {@code foo(int a, Number[] num)} * </p> */ private boolean checkVarArgs(final Method method) { final Class<?>[] argTypes = method.getParameterTypes(); if (argTypes.length == 0) return true; if (!argTypes[argTypes.length - 1].isArray()) return true; if (method.isVarArgs()) return true; error("Last argument should be varargs for method:\n\t" + method); return false; } /** * Gets the list of {@link Op} classes associated with the given method via * the {@link OpMethod} annotation. */ private Set<Class<? extends Op>> opTypes(final Method method) { final Set<Class<? extends Op>> opSet = new HashSet<>(); final OpMethod ann = method.getAnnotation(OpMethod.class); if (ann != null) { final Class<? extends Op>[] opTypes = ann.ops(); if (opTypes.length == 0) opSet.add(ann.op()); for (Class<? extends Op> opType : opTypes) { opSet.add(opType); } } return opSet; } /** * Checks whether the given op interface matches the specified method, * particularly with respect to the interface's {@code NAME} constant. * @param method The method to which the {@link Op} should be compared. * @param qName The fully qualified (with namespace) name of the op. * @param opType The {@link Op} to which the method should be compared. * @return true iff the method and {@link Op} match up. */ private boolean checkOpIface(final Method method, final String qName, final Class<? extends Op> opType) { try { final Field nameField = opType.getField("NAME"); if (nameField.getType() != String.class) { error("Non-String NAME field", opType, method); return false; } final String nameFieldValue = (String) nameField.get(null); if (!qName.equals(nameFieldValue)) { error("NAME field mismatch", opType, method); return false; } } catch (final NoSuchFieldException exc) { error("No NAME field", opType, method); return false; } catch (final IllegalAccessException exc) { error("Inaccessible NAME field", opType, method); return false; } final Object[] argTypes = method.getParameterTypes(); // verify that the method argument is "Object..." as expected if (argTypes.length != 1 || argTypes[0] != Object[].class) { error("Expected single Object... argument", opType, method); return false; } return true; } /** * Checks whether the given op implementation matches the specified method, * including op name, as well as input and output type parameters. * * @param method The method to which the {@link Op} should be compared. * @param qName The fully qualified (with namespace) name of the op. * @param opType The {@link Op} to which the method should be compared. * @param coverSet The set of ops which have already matched a method. * @return true iff the method and {@link Op} match up. */ private boolean checkOpImpl(final Method method, final String qName, final Class<? extends Op> opType, final OpCoverSet coverSet) { // TODO: Type matching needs to be type<->type instead of class<->type. // That is, the "special class placeholder" also needs to work with Type. // Then we can pass Types here instead of Class instances. // final Object[] argTypes = method.getGenericParameterTypes(); final Object[] argTypes = method.getParameterTypes(); final OpRef<Op> ref = OpRef.create(qName, argTypes); final OpInfo info = ops.info(opType); final OpCandidate<Op> candidate = new OpCandidate<>(ops, ref, info); // check input types if (!inputTypesMatch(candidate)) { error("Mismatched inputs", opType, method); return false; } // check output types final Type returnType = method.getGenericReturnType(); if (!outputTypesMatch(returnType, candidate)) { error("Mismatched outputs", opType, method); return false; } // mark this op as covered (w.r.t. the given number of args) coverSet.add(info, argTypes.length); return true; } private boolean inputTypesMatch(final OpCandidate<Op> candidate) { // check for assignment compatibility, including generics if (!matcher.typesMatch(candidate)) return false; // also check that raw types exactly match final Object[] paddedArgs = matcher.padArgs(candidate); int i = 0; for (final ModuleItem<?> input : candidate.cInfo().inputs()) { final Object arg = paddedArgs[i++]; if (!typeMatches(arg, input.getType())) return false; } return true; } private boolean typeMatches(final Object arg, final Class<?> type) { if (arg == null) return true; // NB: Handle special typed null placeholder. final Class<?> argType = arg instanceof Class ? ((Class<?>) arg) : arg.getClass(); return argType == type; } private boolean outputTypesMatch(final Type returnType, final OpCandidate<Op> candidate) { final List<Type> outTypes = new ArrayList<>(); for (final ModuleItem<?> output : candidate.cInfo().outputs()) { outTypes.add(output.getGenericType()); } if (outTypes.size() == 0) return returnType == void.class; final Type baseType; if (outTypes.size() == 1) baseType = returnType; else { // multiple return types; so the method return type must be a list if (GenericUtils.getClass(returnType) != List.class) return false; // use the list's generic type parameter as the base type baseType = GenericUtils.getTypeParameter(returnType, List.class, 0); } for (final Type outType : outTypes) { if (!isSuperType(baseType, outType)) return false; } return true; } private boolean isSuperType(final Type baseType, final Type subType) { // TODO: Handle generics. final Class<?> baseClass = GenericUtils.getClass(baseType); final Class<?> subClass = GenericUtils.getClass(subType); // NB: This avoids a bug in generics reflection processing. // But it means that List return type matching is imperfect. if (baseClass == null || subClass == null) return true; return baseClass.isAssignableFrom(subClass); } private void error(final String message, final Class<? extends Op> opType, final Method method) { error(message + ":\n\top = " + opType.getName() + "\n\tmethod = " + method); } private void error(final String message) { System.err.println("[ERROR] " + message); } private String methodString(final OpInfo info, final int optionalsToFill) { final StringBuilder sb = new StringBuilder(); // outputs int outputCount = 0; String returnType = "void"; String castPrefix = ""; for (final ModuleItem<?> output : info.cInfo().outputs()) { if (++outputCount == 1) { returnType = typeString(output); castPrefix = "(" + castTypeString(output) + ") "; } else { returnType = "List"; castPrefix = "(List) "; break; } } final String className = info.cInfo().getDelegateClassName().replaceAll("\\$", ".") + ".class"; sb.append("\t@OpMethod(op = " + className + ")\n"); final String methodName = info.getSimpleName(); sb.append("\tpublic " + returnType + " " + methodName + "("); // inputs boolean first = true; int optionalIndex = 0; final StringBuilder args = new StringBuilder(); args.append(className); for (final ModuleItem<?> input : info.cInfo().inputs()) { if (!input.isRequired()) { // leave off unspecified optional arguments if (++optionalIndex > optionalsToFill) continue; } if (first) first = false; else sb.append(", "); sb.append("final " + typeString(input) + " " + input.getName()); args.append(", " + input.getName()); } sb.append(") {\n"); sb.append("\t\t"); if (outputCount > 0) { sb.append("final " + returnType + " result =\n" + "\t\t\t" + castPrefix); } sb.append("ops().run(" + args + ");\n"); if (outputCount > 0) sb.append("\t\treturn result;\n"); sb.append("\t}"); return sb.toString(); } private String typeString(final ModuleItem<?> item) { return item.getType().getSimpleName(); } private String castTypeString(final ModuleItem<?> item) { return ConversionUtils.getNonprimitiveType(item.getType()).getSimpleName(); } // -- Helper classes -- /** A data structure which maps each key to a set of values. */ private static class MultiMap<K, V> extends HashMap<K, Set<V>> { public void add(final K key, final V value) { Set<V> set = get(key); if (set == null) { set = new HashSet<>(); put(key, set); } set.add(value); } public boolean contains(final K key, final V value) { final Set<V> set = get(key); return set != null && set.contains(value); } } /** * Maps an op implementation (i.e., {@link OpInfo}) to a list of integers. * Each integer represents a different number of arguments to the op. */ public static class OpCoverSet extends MultiMap<OpInfo, Integer> { // NB: No implementation needed. } }
package no.finn.unleash.event; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static no.finn.unleash.repository.FeatureToggleResponse.Status.UNAVAILABLE; import static org.assertj.core.api.Assertions.assertThat; import com.github.jenspiegsa.wiremockextension.ConfigureWireMock; import com.github.jenspiegsa.wiremockextension.InjectServer; import com.github.jenspiegsa.wiremockextension.WireMockExtension; import com.github.jenspiegsa.wiremockextension.WireMockSettings; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.core.Options; import java.util.ArrayList; import java.util.List; import no.finn.unleash.DefaultUnleash; import no.finn.unleash.SynchronousTestExecutor; import no.finn.unleash.Unleash; import no.finn.unleash.UnleashException; import no.finn.unleash.metric.ClientMetrics; import no.finn.unleash.metric.ClientRegistration; import no.finn.unleash.repository.FeatureToggleResponse; import no.finn.unleash.repository.HttpToggleFetcher; import no.finn.unleash.repository.ToggleBootstrapHandler; import no.finn.unleash.util.UnleashConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @ExtendWith(WireMockExtension.class) @WireMockSettings(failOnUnmatchedRequests = false) public class SubscriberTest { @ConfigureWireMock Options options = wireMockConfig().dynamicPort(); @InjectServer WireMockServer serverMock; private TestSubscriber testSubscriber = new TestSubscriber(); private UnleashConfig unleashConfig; @BeforeEach void setup() { unleashConfig = new UnleashConfig.Builder() .appName(SubscriberTest.class.getSimpleName()) .instanceId(SubscriberTest.class.getSimpleName()) .synchronousFetchOnInitialisation(true) .unleashAPI("http://localhost:" + serverMock.port()) .subscriber(testSubscriber) .scheduledExecutor(new SynchronousTestExecutor()) .build(); } @Test void subscriberAreNotified() { Unleash unleash = new DefaultUnleash(unleashConfig); unleash.isEnabled("myFeature"); unleash.isEnabled("myFeature"); unleash.isEnabled("myFeature"); assertThat(testSubscriber.togglesFetchedCounter).isEqualTo(2); // one forced, one scheduled assertThat(testSubscriber.status).isEqualTo(UNAVAILABLE); assertThat(testSubscriber.toggleEvalutatedCounter).isEqualTo(3); assertThat(testSubscriber.toggleName).isEqualTo("myFeature"); assertThat(testSubscriber.toggleEnabled).isFalse(); assertThat(testSubscriber.errors).hasSize(2); // assertThat(testSubscriber.events).filteredOn(e -> e instanceof ToggleBootstrapHandler.ToggleBootstrapRead).hasSize(1); assertThat(testSubscriber.events).filteredOn(e -> e instanceof UnleashReady).hasSize(1); assertThat(testSubscriber.events).filteredOn(e -> e instanceof ToggleEvaluated).hasSize(3); assertThat(testSubscriber.events).filteredOn(e -> e instanceof FeatureToggleResponse).hasSize(2); assertThat(testSubscriber.events).filteredOn(e -> e instanceof ClientRegistration).hasSize(1); assertThat(testSubscriber.events).filteredOn(e -> e instanceof ClientMetrics).hasSize(1); assertThat(testSubscriber.events).hasSize(9); } private class TestSubscriber implements UnleashSubscriber { private int togglesFetchedCounter; private FeatureToggleResponse.Status status; private int toggleEvalutatedCounter; private String toggleName; private boolean toggleEnabled; private List<UnleashEvent> events = new ArrayList<>(); private List<UnleashException> errors = new ArrayList<>(); @Override public void on(UnleashEvent unleashEvent) { this.events.add(unleashEvent); } @Override public void onError(UnleashException unleashException) { this.errors.add(unleashException); } @Override public void toggleEvaluated(ToggleEvaluated toggleEvaluated) { this.toggleEvalutatedCounter++; this.toggleName = toggleEvaluated.getToggleName(); this.toggleEnabled = toggleEvaluated.isEnabled(); } @Override public void togglesFetched(FeatureToggleResponse toggleResponse) { this.togglesFetchedCounter++; this.status = toggleResponse.getStatus(); } } }
package org.apache.geronimo.kernel.service; import javax.management.MBeanServer; import javax.management.Notification; import javax.management.ObjectName; import org.apache.geronimo.kernel.management.State; public class GeronimoMBeanContext { /** * The MBean server in which the Geronimo MBean is registered. */ private MBeanServer server; /** * The GeronimoMBean which owns the target. */ private GeronimoMBean geronimoMBean; /** * The object name of the Geronimo MBean. */ private ObjectName objectName; /** * Creates a new context for a target. * * @param server a reference to the mbean server in which the Geronimo Mbean is registered * @param geronimoMBean the Geronimo Mbean the contains the target * @param objectName the registered name of the Geronimo MBean */ public GeronimoMBeanContext(MBeanServer server, GeronimoMBean geronimoMBean, ObjectName objectName) { this.server = server; this.geronimoMBean = geronimoMBean; this.objectName = objectName; } /** * Gets a reference to the MBean server in which the Geronimo MBean is registered. * @return a reference to the MBean server in which the Geronimo MBean is registered */ public MBeanServer getServer() { return server; } /** * Gets the registered name of the Geronimo MBean * @return the registered name of the Geronimo MBean */ public ObjectName getObjectName() { return objectName; } /** * Gets the state of this component as an int. * The int return is required by the JSR77 specification. * * @return the current state of this component */ public int getState() { return geronimoMBean.getState(); } /** * Attempts to bring the component into the fully running state. If an Exception occurs while * starting the component, the component is automaticaly failed. * * There is no guarantee that the Geronimo MBean will be running when the method returns. * * @throws Exception if a problem occurs while starting the component */ public void start() throws Exception { geronimoMBean.attemptFullStart(); } /** * Attempt to bring the component into the fully stopped state. If an exception occurs while * stopping the component, tthe component is automaticaly failed. * * There is no guarantee that the Geronimo MBean will be stopped when the method returns. * * @throws Exception if a problem occurs while stopping the component */ public void stop() throws Exception { final int state = geronimoMBean.getState(); if (state == State.RUNNING_INDEX || state == State.STARTING_INDEX) { geronimoMBean.stop(); } else if (state == State.STOPPING_INDEX) { geronimoMBean.attemptFullStop(); } } /** * Moves this component to the FAILED state. * * The component is guaranteed to be in the failed state when the method returns. * */ public void fail() { geronimoMBean.fail(); } /** * Sends the specified notification in a javax.management.Notification. * The message must be declared in the a GeronimoNotificationInfo. * @param message the message to send */ public void sendNotification(String message) { geronimoMBean.sendNotification(message); } /** * Sends the specified notification. * The norification must be declared in the a GeronimoNotificationInfo. * @param notification the notification to send */ public void sendNotification(Notification notification) { geronimoMBean.sendNotification(notification); } /** * Gets the default target object from the GeronimoMBean. This allows * targets within the same MBean to communicate with each other. * @return the default target or null if there is no default target */ public Object getTarget() { GeronimoMBeanInfo mbeanInfo = (GeronimoMBeanInfo) geronimoMBean.getMBeanInfo(); return mbeanInfo.targets.get(GeronimoMBeanInfo.DEFAULT_TARGET_NAME); } /** * Gets the named target object from the GeronimoMBean. This allows * targets within the same MBean to communicate with each other. * @param name name of the target to get * @return the named target or null if there is no default target */ public Object getTarget(String name) { GeronimoMBeanInfo mbeanInfo = (GeronimoMBeanInfo) geronimoMBean.getMBeanInfo(); return mbeanInfo.targets.get(name); } }
package io.github.likcoras.asuka; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.pircbotx.User; import lombok.Cleanup; public class IgnoreManager { private Set<String> ignored; public IgnoreManager() { ignored = Collections.synchronizedSet(new HashSet<String>()); } public void addIgnored(User user) { addIgnored(BotUtil.getId(user)); } public void addIgnored(String user) { ignored.add(user); } public void removeIgnored(User user) { removeIgnored(BotUtil.getId(user)); } public void removeIgnored(String user) { ignored.remove(user); } public boolean isIgnored(User user) { return ignored.contains(BotUtil.getId(user)); } public void readFile(Path ignoreFile) throws IOException { @Cleanup BufferedReader read = Files.newBufferedReader(ignoreFile); synchronized (ignored) { String line; while ((line = read.readLine()) != null) ignored.add(line); } } public void writeFile(Path ignoreFile) throws IOException { @Cleanup BufferedWriter write = Files.newBufferedWriter(ignoreFile); synchronized (ignored) { for (String user : ignored) write.write(user + "\n"); } write.flush(); } }
package io.vertx.example.kubernetes; import io.vertx.core.AbstractVerticle; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.example.util.Runner; import io.vertx.ext.configuration.ConfigurationService; import io.vertx.ext.configuration.ConfigurationServiceOptions; import io.vertx.ext.configuration.ConfigurationStoreOptions; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; public class SimpleRest extends AbstractVerticle { private static final Logger LOG = LoggerFactory.getLogger(SimpleRest.class); // Convenience method so you can run it in your IDE public static void main(String[] args) { Runner.runExample(SimpleRest.class); } private Map<String, JsonObject> products = new HashMap<>(); private ConfigurationService conf; private HttpServer httpServer; @Override public void start() { setUpInitialData(); setUpConfiguration(); Router router = Router.router(vertx); router.route().handler(BodyHandler.create()); router.get("/products/:productID").handler(this::handleGetProduct); router.put("/products/:productID").handler(this::handleAddProduct); router.get("/products").handler(this::handleListProducts); conf.getConfiguration(ar -> { if (ar.succeeded()) { int port = ar.result().getInteger("port", 8080); LOG.info("ConfigMap -> port : " + port); httpServer = vertx.createHttpServer(); httpServer.requestHandler(router::accept).listen(port); } else { ar.cause().printStackTrace(); } }); conf.listen((newConf -> { LOG.info("New configuration: " + newConf.encodePrettily()); int port = newConf.getInteger("port", 8080); LOG.info("Port has changed: " + port); httpServer.close(); LOG.info("The HttpServer will be stopped and restarted."); httpServer.requestHandler(router::accept).listen(port); })); } private void handleGetProduct(RoutingContext routingContext) { String productID = routingContext.request().getParam("productID"); HttpServerResponse response = routingContext.response(); if (productID == null) { sendError(400, response); } else { JsonObject product = products.get(productID); if (product == null) { sendError(404, response); } else { response.putHeader("content-type", "application/json").end(product.encodePrettily()); } } } private void handleAddProduct(RoutingContext routingContext) { String productID = routingContext.request().getParam("productID"); HttpServerResponse response = routingContext.response(); if (productID == null) { sendError(400, response); } else { JsonObject product = routingContext.getBodyAsJson(); if (product == null) { sendError(400, response); } else { products.put(productID, product); response.end(); } } } private void handleListProducts(RoutingContext routingContext) { JsonArray arr = new JsonArray(); products.forEach((k, v) -> arr.add(v)); routingContext.response().putHeader("content-type", "application/json").end(arr.encodePrettily()); } private void sendError(int statusCode, HttpServerResponse response) { response.setStatusCode(statusCode).end(); } private void setUpInitialData() { addProduct(new JsonObject().put("id", "prod3568").put("name", "Egg Whisk").put("price", 3.99) .put("weight", 150)); addProduct(new JsonObject().put("id", "prod7340").put("name", "Tea Cosy").put("price", 5.99) .put("weight", 100)); addProduct(new JsonObject().put("id", "prod8643").put("name", "Spatula").put("price", 1.00) .put("weight", 80)); } private void setUpConfiguration() { ConfigurationStoreOptions appStore = new ConfigurationStoreOptions(); appStore.setType("configmap") .setConfig(new JsonObject() .put("namespace", "vertx-demo") .put("name", "app-config") .put("key","app.json")); conf = ConfigurationService.create(vertx, new ConfigurationServiceOptions() .addStore(appStore)); } private void addProduct(JsonObject product) { products.put(product.getString("id"), product); } }
package org.ngrinder.perftest.service; import static org.ngrinder.common.util.Preconditions.checkNotEmpty; import static org.ngrinder.common.util.Preconditions.checkNotNull; import static org.ngrinder.common.util.Preconditions.checkNotZero; import static org.ngrinder.model.Status.getProcessingOrTestingTestStatus; import static org.ngrinder.perftest.repository.PerfTestSpecification.emptyPredicate; import static org.ngrinder.perftest.repository.PerfTestSpecification.idEqual; import static org.ngrinder.perftest.repository.PerfTestSpecification.idSetEqual; import static org.ngrinder.perftest.repository.PerfTestSpecification.lastModifiedOrCreatedBy; import static org.ngrinder.perftest.repository.PerfTestSpecification.likeTestNameOrDescription; import static org.ngrinder.perftest.repository.PerfTestSpecification.statusSetEqual; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import net.grinder.SingleConsole; import net.grinder.StopReason; import net.grinder.common.GrinderProperties; import net.grinder.common.processidentity.AgentIdentity; import net.grinder.console.model.ConsoleProperties; import net.grinder.util.ConsolePropertiesFactory; import net.grinder.util.Directory; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Predicate; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import org.ngrinder.common.constant.NGrinderConstants; import org.ngrinder.common.exception.NGrinderRuntimeException; import org.ngrinder.infra.config.Config; import org.ngrinder.model.PerfTest; import org.ngrinder.model.Role; import org.ngrinder.model.Status; import org.ngrinder.model.User; import org.ngrinder.monitor.controller.model.SystemDataModel; import org.ngrinder.perftest.model.PerfTestStatistics; import org.ngrinder.perftest.model.ProcessAndThread; import org.ngrinder.perftest.repository.PerfTestRepository; import org.ngrinder.script.model.FileEntry; import org.ngrinder.script.model.FileType; import org.ngrinder.script.service.FileEntryService; import org.ngrinder.service.IPerfTestService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specifications; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * {@link PerfTest} Service Class. * * This class contains various method which mainly get the {@link PerfTest} matching specific * conditions from DB. * * @author Mavlarn * @author JunHo Yoon * @since 3.0 */ @Service public class PerfTestService implements NGrinderConstants, IPerfTestService { private static final Logger LOGGER = LoggerFactory.getLogger(PerfTestService.class); private static final String DATA_FILE_EXTENSION = ".data"; @Autowired private PerfTestRepository perfTestRepository; @Autowired private ConsoleManager consoleManager; @Autowired private AgentManager agentManager; @Autowired private Config config; @Autowired private FileEntryService fileEntryService; private NumberFormat formatter = new DecimalFormat(" private int maximumConcurrentTestCount = 0; /** * Get {@link PerfTest} list on the user. * * @param user * user * @param query * @param isFinished * only find finished test * @param pageable * paging info * @return found {@link PerfTest} list */ public Page<PerfTest> getPerfTestList(User user, String query, boolean isFinished, Pageable pageable) { Specifications<PerfTest> spec = Specifications.where(emptyPredicate()); // User can see only his own test if (user.getRole().equals(Role.USER)) { spec = spec.and(lastModifiedOrCreatedBy(user)); } if (isFinished) { spec = spec.and(statusSetEqual(Status.FINISHED)); } if (StringUtils.isNotBlank(query)) { spec = spec.and(likeTestNameOrDescription(query)); } return perfTestRepository.findAll(spec, pageable); } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#getPerfTest(org.ngrinder .model.User, * java.lang.Integer) */ @Override public PerfTest getPerfTest(User user, Long id) { Specifications<PerfTest> spec = Specifications.where(emptyPredicate()); // User can see only his own test if (user.getRole().equals(Role.USER)) { spec = spec.and(lastModifiedOrCreatedBy(user)); } spec = spec.and(idEqual(id)); return perfTestRepository.findOne(spec); } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#getPerfTest(org.ngrinder .model.User, * java.lang.Integer[]) */ @Override public List<PerfTest> getPerfTest(User user, Long[] ids) { Specifications<PerfTest> spec = Specifications.where(emptyPredicate()); // User can see only his own test if (user.getRole().equals(Role.USER)) { spec = spec.and(lastModifiedOrCreatedBy(user)); } spec = spec.and(idSetEqual(ids)); return perfTestRepository.findAll(spec); } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#getPerfTestCount(org.ngrinder * .model.User, org.ngrinder.perftest.model.Status) */ @Override public long getPerfTestCount(User user, Status... statuses) { Specifications<PerfTest> spec = Specifications.where(emptyPredicate()); // User can see only his own test if (user != null) { spec = spec.and(lastModifiedOrCreatedBy(user)); } if (statuses.length != 0) { spec = spec.and(statusSetEqual(statuses)); } return perfTestRepository.count(spec); } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#getPerfTest(org.ngrinder .model.User, * org.ngrinder.perftest.model.Status) */ @Override public List<PerfTest> getPerfTest(User user, Status... statuses) { Specifications<PerfTest> spec = Specifications.where(emptyPredicate()); // User can see only his own test if (user != null) { spec = spec.and(lastModifiedOrCreatedBy(user)); } if (statuses.length != 0) { spec = spec.and(statusSetEqual(statuses)); } return perfTestRepository.findAll(spec); } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#savePerfTest(org.ngrinder .model.User, * org.ngrinder.perftest.model.PerfTest) */ @Override @Transactional public PerfTest savePerfTest(User user, PerfTest perfTest) { if (perfTest.getStatus() == Status.READY) { FileEntry scriptEntry = fileEntryService.getFileEntry(user, perfTest.getScriptName()); long revision = scriptEntry != null ? scriptEntry.getRevision() : -1; perfTest.setScriptRevision(revision); } return savePerfTest(perfTest); } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#savePerfTest(org.ngrinder * .perftest.model.PerfTest ) */ @Override @Transactional public PerfTest savePerfTest(PerfTest perfTest) { checkNotNull(perfTest); // Merge if necessary if (perfTest.exist()) { PerfTest existingPerfTest = perfTestRepository.findOne(perfTest.getId()); perfTest = existingPerfTest.merge(perfTest); } else { perfTest.clearMessages(); } return perfTestRepository.save(perfTest); } /** * Save performance test with given status. * * This method is only used for changing {@link Status} * * @param perfTest * {@link PerfTest} instance which will be saved. * @param status * Status to be assigned * @return saved {@link PerfTest} */ @Transactional public PerfTest setRecodingStarting(PerfTest perfTest, long systemTimeMills) { checkNotNull(perfTest); checkNotNull(perfTest.getId(), "perfTest with status should save Id"); PerfTest findOne = perfTestRepository.findOne(perfTest.getId()); if (findOne == null) { return null; } findOne.setStartTime(new Date(systemTimeMills)); return perfTestRepository.save(findOne); } /** * Mark test error on {@link PerfTest} instance. * * @param perfTest * {@link PerfTest} * @param singleConsole * console in use * @param e * exception occurs. * @return */ public PerfTest markAbromalTermination(PerfTest perfTest, StopReason reason) { // Leave last status as test error cause PerfTest findOne = perfTestRepository.findOne(perfTest.getId()); if (findOne == null) { return null; } findOne.setTestErrorCause(perfTest.getStatus()); findOne.setLastProgressMessage(reason.name()); findOne.setStatus(Status.ABNORMAL_TESTING); return perfTestRepository.save(findOne); } /** * Save performance test with given status. * * This method is only used for changing {@link Status} * * @param perfTest * {@link PerfTest} instance which will be saved. * @param status * Status to be assigned * @return saved {@link PerfTest} */ @Transactional public PerfTest changePerfTestStatus(PerfTest perfTest, Status status, String message) { checkNotNull(perfTest); checkNotNull(perfTest.getId(), "perfTest with status should save Id"); perfTest.setStatus(checkNotNull(status, "status should not be null")); PerfTest findOne = perfTestRepository.findOne(perfTest.getId()); if (findOne == null) { return null; } findOne.setStatus(status); findOne.setLastProgressMessage(message); return perfTestRepository.save(findOne); } /** * Add a progress message on the given perfTest. * * @param perfTest * perf test * @param message * message to be recored. */ @Transactional public void markProgress(PerfTest perfTest, String message) { PerfTest findOne = perfTestRepository.findOne(perfTest.getId()); if (findOne == null) { return; } findOne.setLastProgressMessage(message); perfTestRepository.save(findOne); } /** * Add a progress message on the given perfTest and change the status. * * @param perfTest * perf test * @param status * status to be recorded. * @param message * message to be recored. */ @Transactional public PerfTest markProgressAndStatus(PerfTest perfTest, Status status, String message) { PerfTest findOne = perfTestRepository.findOne(perfTest.getId()); if (findOne == null) { return null; } findOne.setStatus(status); findOne.setLastProgressMessage(message); return perfTestRepository.save(findOne); } /** * Add a progress message on the given perfTest and change the status. In addition, the finish * time and various test statistic are recorded as well. * * @param perfTest * perf test * @param status * status to be recorded. * @param message * message to be recored. */ @Transactional public PerfTest markProgressAndStatusAndFinishTimeAndStatistics(PerfTest perfTest, Status status, String message) { PerfTest findOne = perfTestRepository.findOne(perfTest.getId()); if (findOne == null) { return null; } findOne.setStatus(status); findOne.setLastProgressMessage(message); findOne.setFinishTime(new Date()); updatePerfTestAfterTestFinish(findOne); return perfTestRepository.save(findOne); } /** * Mark test error on {@link PerfTest} instance. * * @param perfTest * {@link PerfTest} * @param reason * error reason */ @Transactional public void markPerfTestError(PerfTest perfTest, String message) { PerfTest findOne = perfTestRepository.findOne(perfTest.getId()); if (findOne == null) { return; } findOne.setStatus(Status.ABNORMAL_TESTING); findOne.setTestErrorCause(findOne.getStatus()); findOne.setLastProgressMessage(message); perfTestRepository.save(findOne); } @Transactional public void markPerfTestConsoleStart(PerfTest perfTest, int consolePort) { PerfTest findOne = perfTestRepository.findOne(perfTest.getId()); if (findOne == null) { return; } findOne.setPort(consolePort); findOne.setStatus(Status.START_CONSOLE_FINISHED); findOne.setLastProgressMessage("Console is started on port " + consolePort); perfTestRepository.save(findOne); } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#getPerfTest(long) */ @Override public PerfTest getPerfTest(Long testId) { return perfTestRepository.findOne(testId); } /** * Get next runnable PerfTest list. * * @return found {@link PerfTest}, null otherwise */ @Transactional public PerfTest getPerfTestCandiate() { List<PerfTest> readyPerfTests = perfTestRepository.findAllByStatusOrderByScheduledTimeAsc(Status.READY); List<PerfTest> usersFirstPerfTests = filterCurrentlyRunningTestUsersTest(readyPerfTests); return usersFirstPerfTests.isEmpty() ? null : readyPerfTests.get(0); } /** * Get currently running {@link PerfTest} list. * * @return */ public List<PerfTest> getCurrentlyRunningTest() { return getPerfTest(null, Status.getProcessingOrTestingTestStatus()); } /** * Filter out {@link PerfTest} whose owner is running another test now.. * * @param perfTestLists * perf test * @return filtered perf test */ private List<PerfTest> filterCurrentlyRunningTestUsersTest(List<PerfTest> perfTestLists) { List<PerfTest> currentlyRunningTests = getCurrentlyRunningTest(); final Set<User> currentlyRunningTestOwners = new HashSet<User>(); for (PerfTest each : currentlyRunningTests) { currentlyRunningTestOwners.add((User) ObjectUtils.defaultIfNull(each.getLastModifiedUser(), each.getCreatedUser())); } CollectionUtils.filter(perfTestLists, new Predicate() { @Override public boolean evaluate(Object object) { PerfTest perfTest = (PerfTest) object; return !currentlyRunningTestOwners.contains(ObjectUtils.defaultIfNull(perfTest.getLastModifiedUser(), perfTest.getCreatedUser())); } }); return perfTestLists; } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#getTestingPerfTest() */ @Override public List<PerfTest> getTestingPerfTest() { return getPerfTest(null, Status.getTestingTestStates()); } /** * Get abnormally testing PerfTest. * * @return found {@link PerfTest} list */ public List<PerfTest> getAbnoramlTestingPerfTest() { return getPerfTest(null, Status.ABNORMAL_TESTING); } /** * Delete PerfTest by id. * * Never use this method in runtime. This method is used only for testing. * * @param id * {@link PerfTest} it */ public void deletePerfTest(long id) { perfTestRepository.delete(id); } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#getPerfTestFilePath(org * .ngrinder.perftest. model.PerfTest) */ @Override public File getPerfTestFilePath(PerfTest perfTest) { return config.getHome().getPerfTestDirectory( checkNotZero(perfTest.getId(), "perftest id should not be 0 or zero").toString()); } public String getCustomClassPath(PerfTest perfTest) { File perfTestDirectory = getPerfTestDirectory(perfTest); File libFolder = new File(perfTestDirectory, "lib"); final StringBuffer customClassPath = new StringBuffer(); customClassPath.append("."); if (libFolder.exists()) { customClassPath.append(File.pathSeparator).append("lib"); libFolder.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.endsWith(".jar")) { customClassPath.append(File.pathSeparator).append("lib/").append(name); } return true; } }); } return customClassPath.toString(); } /** * Create {@link GrinderProperties} based on the passed {@link PerfTest}. * * @param perfTest * base data * @return created {@link GrinderProperties} instance */ public GrinderProperties getGrinderProperties(PerfTest perfTest) { try { // Copy grinder properties File userGrinderPropertiesPath = new File(getPerfTestDirectory(perfTest), DEFAULT_GRINDER_PROPERTIES_PATH); FileUtils.copyFile(config.getHome().getDefaultGrinderProperties(), userGrinderPropertiesPath); GrinderProperties grinderProperties = new GrinderProperties(userGrinderPropertiesPath); grinderProperties.setAssociatedFile(new File(userGrinderPropertiesPath.getName())); grinderProperties.setProperty(GrinderProperties.SCRIPT, FilenameUtils.getName(checkNotEmpty(perfTest.getScriptName()))); grinderProperties.setProperty(GRINDER_PROP_TEST_ID, "test_" + perfTest.getId()); grinderProperties.setInt(GRINDER_PROP_THREAD, perfTest.getThreads()); grinderProperties.setInt(GRINDER_PROP_PROCESSES, perfTest.getProcesses()); if ("D".equals(perfTest.getThreshold())) { grinderProperties.setLong(GRINDER_PROP_DURATION, perfTest.getDuration()); grinderProperties.setInt(GRINDER_PROP_RUNS, 0); } else { grinderProperties.setInt(GRINDER_PROP_RUNS, perfTest.getRunCount()); if (grinderProperties.containsKey(GRINDER_PROP_DURATION)) { grinderProperties.remove(GRINDER_PROP_DURATION); } } grinderProperties.setProperty(NGRINDER_PROP_ETC_HOSTS, StringUtils.defaultIfBlank(perfTest.getTargetHosts(), "")); grinderProperties.setBoolean(GRINDER_PROP_USE_CONSOLE, true); if (perfTest.isUseRampUp()) { grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT, perfTest.getProcessIncrement()); grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT_INTERVAL, perfTest.getProcessIncrementInterval()); grinderProperties.setInt(GRINDER_PROP_INITIAL_SLEEP_TIME, perfTest.getInitSleepTime()); } else { grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT, 0); } grinderProperties.setProperty(GRINDER_PROP_JVM_CLASSPATH, getCustomClassPath(perfTest)); grinderProperties.setInt(GRINDER_PROP_IGNORE_SAMPLE_COUNT, perfTest.getIgnoreSampleCount()); boolean securityEnabled = config.isSecurityEnabled(); grinderProperties.setBoolean(GRINDER_PROP_SECURITY, securityEnabled); // set security.manager argument if (securityEnabled) { String jvmArguments = "-Djava.security.manager=org.ngrinder.sm.NGrinderSecurityManager"; grinderProperties.setProperty(GRINDER_PROP_JVM_ARGUMENTS, jvmArguments); } LOGGER.info("Grinder Properties : {} ", grinderProperties); return grinderProperties; } catch (Exception e) { throw new NGrinderRuntimeException("error while prepare grinder property for " + perfTest.getTestName(), e); } } /** * Prepare files for distribution. This method store the files on the path * ${NGRINDER_HOME}/perftest/{test_id}/dist folder. * * @param perfTest * perfTest * @return File location in which the perftest should have. */ public File prepareDistribution(PerfTest perfTest) { checkNotNull(perfTest.getId(), "perfTest should have id"); String scriptName = checkNotEmpty(perfTest.getScriptName(), "perfTest should have script name"); User user = perfTest.getCreatedUser(); // Get all files in the script path FileEntry scriptEntry = checkNotNull(fileEntryService.getFileEntry(user, perfTest.getScriptName(), perfTest.getScriptRevision()), "script should not exist"); List<FileEntry> fileEntries = fileEntryService.getLibAndResourcesEntries(user, checkNotEmpty(scriptName), perfTest.getScriptRevision()); File perfTestDirectory = getPerfTestDirectory(perfTest); fileEntries.add(scriptEntry); perfTestDirectory.mkdirs(); String basePath = FilenameUtils.getPath(scriptEntry.getPath()); // To minimize log.. InputStream io = null; FileOutputStream fos = null; try { io = new ClassPathResource("/logback/logback-worker.xml").getInputStream(); fos = new FileOutputStream(new File(perfTestDirectory, "logback-worker.xml")); IOUtils.copy(io, fos); } catch (IOException e) { LOGGER.error("error while writing logback-worker", e); } finally { IOUtils.closeQuietly(io); IOUtils.closeQuietly(fos); } // Distribute each files in that folder. for (FileEntry each : fileEntries) { // Directory is not subject to be distributed. if (each.getFileType() == FileType.DIR) { continue; } String path = FilenameUtils.getPath(each.getPath()); path = path.substring(basePath.length()); File toDir = new File(perfTestDirectory, path); LOGGER.info("{} is being written in {} for test {}", new Object[] { each.getPath(), toDir.toString(), perfTest.getTestIdentifier() }); fileEntryService.writeContentTo(user, each.getPath(), toDir); } LOGGER.info("File write is completed in " + perfTestDirectory); return perfTestDirectory; } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#getPerfTestBaseDirectory * (org.ngrinder.perftest .model.PerfTest) */ @Override public File getPerfTestBaseDirectory(PerfTest perfTest) { return config.getHome().getPerfTestDirectory(perfTest.getId().toString()); } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#getPerfTestDirectory(org * .ngrinder.perftest .model.PerfTest) */ @Override public File getPerfTestDirectory(PerfTest perfTest) { return new File(getPerfTestBaseDirectory(perfTest), NGrinderConstants.PATH_DIST); } /** * Get the process and thread policy java script. * * @return policy javascript */ public String getProcessAndThreadPolicyScript() { return config.getProcessAndThreadPolicyScript(); } /** * Get the optimal process and thread count. * * * @param newVuser * the count of virtual users per agent * @return optimal process thread count */ public ProcessAndThread calcProcessAndThread(int newVuser) { try { String script = getProcessAndThreadPolicyScript(); ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript"); engine.eval(script); int processCount = ((Double) engine.eval("getProcessCount(" + newVuser + ")")).intValue(); int threadCount = ((Double) engine.eval("getThreadCount(" + newVuser + ")")).intValue(); return new ProcessAndThread(processCount, threadCount); } catch (ScriptException e) { LOGGER.error("Error occurs while calc process and thread", e); } return new ProcessAndThread(1, 1); } /** * get the data point interval of report data. * * @param testId * @param dataType * @param imgWidth * @return interval value */ public int getReportDataInterval(long testId, String dataType, int imgWidth) { if (imgWidth < 100) { imgWidth = 100; } int pointCount = imgWidth; File reportFolder = config.getHome().getPerfTestDirectory( testId + File.separator + NGrinderConstants.PATH_REPORT); int lineNumber; int interval = 0; File targetFile = null; targetFile = new File(reportFolder, dataType + DATA_FILE_EXTENSION); if (!targetFile.exists()) { LOGGER.error("Report data for {} in {} does not exisit.", testId, dataType); return 0; } LineNumberReader lnr = null; FileInputStream in = null; InputStreamReader isr = null; try { in = new FileInputStream(targetFile); isr = new InputStreamReader(in); lnr = new LineNumberReader(isr); lnr.skip(targetFile.length()); lineNumber = lnr.getLineNumber() + 1; interval = lineNumber / pointCount; } catch (Exception e) { LOGGER.error("Get report data for " + dataType + " failed:" + e.getMessage(), e); } finally { IOUtils.closeQuietly(lnr); IOUtils.closeQuietly(isr); IOUtils.closeQuietly(in); } return interval; } /** * get the test report data as a string. * * @param testId * test id * @param dataType * data type * @param imgWidth * image width * @return report data * @throws IOException */ public String getReportDataAsString(long testId, String dataType, int interval) { StringBuilder reportData = new StringBuilder("["); File reportFolder = config.getHome().getPerfTestDirectory( testId + File.separator + NGrinderConstants.PATH_REPORT); File targetFile = null; targetFile = new File(reportFolder, dataType + DATA_FILE_EXTENSION); if (!targetFile.exists()) { LOGGER.error("Report data for {} in {} does not exisit.", testId, dataType); return "[ ]"; } FileReader reader = null; BufferedReader br = null; try { reader = new FileReader(targetFile); br = new BufferedReader(reader); String data = br.readLine(); int current = 0; while (StringUtils.isNotBlank(data)) { if (0 == current) { double number = NumberUtils.createDouble(data); reportData.append(number); reportData.append(","); } if (++current >= interval) { current = 0; } data = br.readLine(); } reportData.append("]"); } catch (IOException e) { LOGGER.error("Get report data for " + dataType + " failed:" + e.getMessage(), e); } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(br); } return reportData.toString(); } /** * Get report file name for give test id. * * @param testId * @return report file path */ public File getReportFile(long testId) { return new File(getReportFileDirectory(testId), NGrinderConstants.REPORT_CSV); } /** * Get log file names for give test id. * * @param testId * @return report file path */ public File getLogFile(long testId, String fileName) { return new File(getLogFileDirectory(testId), fileName); } /** * Get report file directory for give test id. * * @param testId * @return report file path */ public File getLogFileDirectory(long testId) { return new File(config.getHome().getPerfTestDirectory(String.valueOf(testId)), NGrinderConstants.PATH_LOG); } /** * Get log files list on the given test. * * @param testId * @return */ public List<String> getLogFiles(long testId) { File logFileDirectory = getLogFileDirectory(testId); if (!logFileDirectory.exists() || !logFileDirectory.isDirectory()) { return Collections.emptyList(); } return Arrays.asList(logFileDirectory.list()); } /** * Get report file directory for give test id. * * @param testId * @return report file path */ public File getReportFileDirectory(long testId) { return new File(config.getHome().getPerfTestDirectory(String.valueOf(testId)), NGrinderConstants.PATH_REPORT); } /** * To get statistics data when test is running If the console is not available.. it returns * empty map. */ public Map<String, Object> getStatistics(int port) { return consoleManager.getConsoleUsingPort(port).getStatictisData(); } /** * To get statistics data when test is running If the console is not available.. it returns * empty map. */ public Map<AgentIdentity, SystemDataModel> getAgentsInfo(int port) { List<AgentIdentity> allAttachedAgents = consoleManager.getConsoleUsingPort(port).getAllAttachedAgents(); Set<AgentIdentity> allControllerAgents = agentManager.getAllAttachedAgents(); Map<AgentIdentity, SystemDataModel> result = new HashMap<AgentIdentity, SystemDataModel>(); for (AgentIdentity eachAgent : allAttachedAgents) { for (AgentIdentity eachControllerAgent : allControllerAgents) { if (eachControllerAgent.getName().equals(eachAgent.getName())) { result.put(eachControllerAgent, agentManager.getSystemDataModel(eachControllerAgent)); } } } return result; } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#getAllPerfTest() */ @Override public List<PerfTest> getAllPerfTest() { return perfTestRepository.findAll(); } /** * Create {@link ConsoleProperties} based on given {@link PerfTest} instance. * * @param perfTest * perfTest * @return {@link ConsoleProperties} */ public ConsoleProperties createConsoleProperties(PerfTest perfTest) { ConsoleProperties consoleProperties = ConsolePropertiesFactory.createEmptyConsoleProperties(); try { consoleProperties.setAndSaveDistributionDirectory(new Directory(getPerfTestDirectory(perfTest))); } catch (Exception e) { throw new NGrinderRuntimeException("Error while setting console properties", e); } return consoleProperties; } /** * Update the given {@link PerfTest} properties after test finished. * * @param perfTest * perfTest */ public void updatePerfTestAfterTestFinish(PerfTest perfTest) { checkNotNull(perfTest); int port = perfTest.getPort(); Map<String, Object> result = getStatistics(port); if (result == null || result.get("totalStatistics") == null) { return; } @SuppressWarnings("unchecked") Map<String, Object> totalStatistics = (Map<String, Object>) result.get("totalStatistics"); LOGGER.info("Total Statistics for test {} is {}", perfTest.getId(), totalStatistics); //if the test is finished abnormally, sometime, there is no statistic data can be got. if (totalStatistics.containsKey("TPS")) { //if "TPS" data exist, all the other should exist too, so I didn't check Null value in map perfTest.setErrors((int) ((Double) totalStatistics.get("Errors")).doubleValue()); perfTest.setTps(Double.parseDouble(formatter.format(totalStatistics.get("TPS")))); perfTest.setMeanTestTime(Double.parseDouble(formatter.format(totalStatistics.get("Mean_Test_Time_(ms)")))); perfTest.setPeakTps(Double.parseDouble(formatter.format(totalStatistics.get("Peak_TPS")))); perfTest.setTests((int) ((Double) totalStatistics.get("Tests")).doubleValue()); } } /** * Get maximum concurrent test count. * * @return maximum concurrent test */ public int getMaximumConcurrentTestCount() { if (maximumConcurrentTestCount == 0) { maximumConcurrentTestCount = config.getSystemProperties().getPropertyInt( NGrinderConstants.NGRINDER_PROP_MAX_CONCURRENT_TEST, NGrinderConstants.NGRINDER_PROP_MAX_CONCURRENT_TEST_VALUE); } return maximumConcurrentTestCount; } /** * Check the test can be executed more. * * @return true if possible */ public boolean canExecuteTestMore() { return getPerfTestCount(null, Status.getProcessingOrTestingTestStatus()) < getMaximumConcurrentTestCount(); } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#stopPerfTest(org.ngrinder .model.User, * java.lang.Long) */ @Override @Transactional public void stopPerfTest(User user, Long id) { PerfTest perfTest = getPerfTest(id); // If it's not requested by user who started job. It's wrong request. if (user.getRole() != Role.ADMIN && !perfTest.getLastModifiedUser().equals(user)) { return; } // If it's not stoppable status.. It's wrong request. if (!perfTest.getStatus().isStoppable()) { return; } perfTest.setStopRequest(true); // Just mark cancel on console SingleConsole consoleUsingPort = consoleManager.getConsoleUsingPort(perfTest.getPort()); if (consoleUsingPort != null) { consoleUsingPort.cancel(); } perfTestRepository.save(perfTest); } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#getStopRequestedPerfTest() */ @Override public List<PerfTest> getStopRequestedPerfTest() { final List<PerfTest> perfTests = getPerfTest(null, getProcessingOrTestingTestStatus()); CollectionUtils.filter(perfTests, new Predicate() { @Override public boolean evaluate(Object object) { return (((PerfTest) object).getStopRequest() == Boolean.TRUE); } }); return perfTests; } /* * (non-Javadoc) * * @see org.ngrinder.perftest.service.IPerfTestService#addCommentOn(org.ngrinder .model.User, * int, java.lang.String) */ @Override @Transactional public void addCommentOn(User user, Long testId, String testComment) { PerfTest perfTest = getPerfTest(user, testId); perfTest.setTestComment(testComment); perfTestRepository.save(perfTest); } @Transactional public Collection<PerfTestStatistics> getCurrentPerfTestStatistics() { Map<User, PerfTestStatistics> perfTestPerUser = new HashMap<User, PerfTestStatistics>(); for (PerfTest each : getPerfTest(null, getProcessingOrTestingTestStatus())) { User lastModifiedUser = each.getLastModifiedUser(); PerfTestStatistics perfTestStatistics = perfTestPerUser.get(lastModifiedUser); if (perfTestStatistics == null) { perfTestStatistics = new PerfTestStatistics(lastModifiedUser); perfTestPerUser.put(lastModifiedUser, perfTestStatistics); } perfTestStatistics.addPerfTest(each); } return perfTestPerUser.values(); } }
package org.artifactory.client; import groovyx.net.http.HttpResponseException; import groovyx.net.http.ResponseParseException; import org.testng.Assert; import org.testng.annotations.Test; import java.util.List; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; /** * @author jbaruch * @since 03/08/12 */ public class SearchesTests extends ArtifactoryTests { @Test public void testLimitlessQuickSearch() throws HttpResponseException { List<String> results = artifactory.searches().search("junit"); assertJUnits(results); } @Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = "Not Found") public void testQuickSearchWithWrongSingleLimit() throws HttpResponseException { //should fail artifactory.searches().limitToRepository(LIBS_RELEASES_LOCAL).search("junit"); } @Test public void testQuickSearchWithRightSingleLimit() throws HttpResponseException { List<String> results = artifactory.searches().limitToRepository(REPO1_CACHE).search("junit"); assertJUnits(results); } @Test public void testQuickSearchWithMultipleLimits() throws HttpResponseException { List<String> results = artifactory.searches().limitToRepository(LIBS_RELEASES_LOCAL).limitToRepository(REPO1_CACHE).search("junit"); assertJUnits(results); } @Test(dependsOnGroups = "uploadBasics") public void testSearchByProperty() throws HttpResponseException { List<String> results = artifactory.searches().filterBy().property("released", false).search(); assertEquals(results.size(), 1); assertTrue(results.get(0).contains("a/b/c.txt")); } @Test(dependsOnGroups = "uploadBasics") public void testSearchByPropertyAndRepoFilter() throws HttpResponseException { List<String> results = artifactory.searches().limitToRepository(NEW_LOCAL).filterBy().property("released", false).search(); assertEquals(results.size(), 1); assertTrue(results.get(0).contains("a/b/c.txt")); } @Test(dependsOnGroups = "uploadBasics", expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = "Not Found") public void testSearchByPropertyAndWrongRepoFilter() throws HttpResponseException { artifactory.searches().limitToRepository(REPO1).filterBy().property("released", false).search(); } @Test(dependsOnGroups = "uploadBasics", expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = "Not Found") public void testSearchByPropertyWithMulipleValue() throws HttpResponseException { artifactory.searches().filterBy().property("colors", "red", "green", "blue").search(); } @Test(dependsOnGroups = "uploadBasics") public void testSearchByPropertyWithoutValue() throws HttpResponseException { List<String> results = artifactory.searches().filterBy().property("released").property("build", 28).search(); assertEquals(results.size(), 1); assertTrue(results.get(0).contains("a/b/c.txt")); } private void assertJUnits(List<String> results) { assertEquals(results.size(), 5); for (String result : results) { assertTrue(result.contains("junit")); } } }
package me.abje.lingua.interpreter.obj; import me.abje.lingua.interpreter.Interpreter; import me.abje.lingua.interpreter.InterpreterException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * A Lingua list. Mutable, but designed with functional usage in mind. */ public class ListObj extends Obj { public static final ClassObj SYNTHETIC = ClassObj.builder("List"). withFunction("map", (interpreter, self, args) -> { if (args.size() != 1) throw new InterpreterException("CallException", "invalid number of arguments for map", interpreter); return ((ListObj) self).map(interpreter, args.get(0)); }). withFunction("filter", (interpreter, self, args) -> { if (args.size() != 1) throw new InterpreterException("CallException", "invalid number of arguments for filter", interpreter); return ((ListObj) self).filter(interpreter, args.get(0)); }). withFunction("forEach", (interpreter, self, args) -> { if (args.size() != 1) throw new InterpreterException("CallException", "invalid number of arguments for forEach", interpreter); return ((ListObj) self).each(interpreter, args.get(0)); }). withFunction("reverse", (interpreter, self, args) -> { if (args.size() != 0) throw new InterpreterException("CallException", "too many arguments for reverse", interpreter); return ((ListObj) self).reverse(); }). withFunction("add", (interpreter, self, args) -> { if (args.size() != 1) throw new InterpreterException("CallException", "invalid number of arguments for reverse", interpreter); return ((ListObj) self).add(args.get(0)); }). withFunction("size", (interpreter, self, args) -> { if (args.size() != 0) throw new InterpreterException("CallException", "invalid number of arguments for size", interpreter); return new NumberObj(((ListObj) self).items.size()); }). build(); /** * This list's items. Must be mutable for mutator methods to work. */ private List<Obj> items; /** * Creates a new list with the given items. * * @param items The items. */ public ListObj(List<Obj> items) { super(SYNTHETIC); this.items = items; } /** * Returns this list's items. */ public List<Obj> all() { return items; } /** * Gets an item in the list. * * @param i The index of the item. * @return The item. * @throws me.abje.lingua.interpreter.InterpreterException If the list index is out of bounds. */ public Obj get(int i) { if (i >= 0 && i < items.size()) { return items.get(i); } else { throw new InterpreterException("OutOfBoundsException", "list index out of bounds: " + i); } } /** * Sets an item in the list. * * @param i The index of the item. * @param value The new item. * @throws me.abje.lingua.interpreter.InterpreterException If the list index is out of bounds. */ public void set(int i, Obj value) { if (i >= 0 && i < items.size()) { items.set(i, value); } else { throw new InterpreterException("OutOfBoundsException", "list index out of bounds: " + i); } } @Override public Obj getAtIndex(Obj index) { if (index instanceof NumberObj) return get((int) ((NumberObj) index).getValue()); else throw new InterpreterException("CallException", "list index not a number"); } @Override public void setAtIndex(Obj index, Obj value) { if (index instanceof NumberObj) set((int) ((NumberObj) index).getValue(), value); else throw new InterpreterException("CallException", "list index not a number"); } /** * Maps this list by applying the given function to each item. * Returns a new list, and does not mutate the original. * * @param interpreter The Interpreter to run the function in. * @param function The function to apply to each item. * @return The mapped list. */ public ListObj map(Interpreter interpreter, Obj function) { List<Obj> newList = items.stream().map(obj -> function.call(interpreter, Collections.singletonList(obj))). collect(Collectors.toList()); return new ListObj(newList); } /** * Filters this list by applying the given predicate to each item. * Returns a new list, and does not mutate the original. * * @param interpreter The Interpreter to run the predicate in. * @param predicate The predicate to apply to each item. * @return The filtered list. */ public ListObj filter(Interpreter interpreter, Obj predicate) { List<Obj> newList = items.stream().filter(obj -> predicate.call(interpreter, Collections.singletonList(obj)).isTruthy()). collect(Collectors.toList()); return new ListObj(newList); } private Obj each(Interpreter interpreter, Obj function) { for (Obj obj : items) { function.call(interpreter, Collections.singletonList(obj)); } return NullObj.get(); } /** * Reverses this list. * Returns a new list, and does not mutate the original. * * @return The reversed list. */ public ListObj reverse() { List<Obj> newList = new ArrayList<>(items); Collections.reverse(newList); return new ListObj(newList); } /** * Adds an item to the end of this list. * * @param obj The item. * @return This list. */ public ListObj add(Obj obj) { items.add(obj); return this; } /** * Lists are truthy when non-empty. * * @return Whether this list is non-empty. */ @Override public boolean isTruthy() { return !items.isEmpty(); } @Override public String toString() { return items.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ListObj listObj = (ListObj) o; return items.equals(listObj.items); } @Override public int hashCode() { return items.hashCode(); } }
package org.iq80.cli; import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.iq80.cli.GitLikeCommandParser.Builder; import org.iq80.cli.model.GlobalMetadata; import org.testng.annotations.Test; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static org.iq80.cli.HelpCommand.help; import static org.iq80.cli.OptionType.GLOBAL; public class GalaxyCommandLineParser { @Test public void test() { parse(); parse("help"); parse("help", "galaxy"); parse("help", "show"); parse("help", "install"); parse("help", "upgrade"); parse("help", "upgrade"); parse("help", "terminate"); parse("help", "start"); parse("help", "stop"); parse("help", "restart"); parse("help", "reset-to-actual"); parse("help", "ssh"); parse("help", "agent"); parse("help", "agent", "show"); parse("help", "agent", "add"); parse("--debug", "show", "-u", "b2", "--state", "r"); parse("--debug", "install", "com.proofpoint.discovery:discovery-server:1.1", "@discovery:general:1.0"); parse("--debug", "upgrade", "-u", "b2", "1.1", "@1.0"); parse("--debug", "upgrade", "-u", "b2", "1.1", "@1.0", "-s", "r"); parse("--debug", "terminate", "-u", "b2"); parse("--debug", "start", "-u", "b2"); parse("--debug", "stop", "-u", "b2"); parse("--debug", "restart", "-u", "b2"); parse("--debug", "reset-to-actual", "-u", "b2"); parse("--debug", "ssh"); parse("--debug", "ssh", "-u", "b2", "--state", "r", "tail -F var/log/launcher.log"); parse("--debug", "agent"); parse("--debug", "agent", "show"); parse("--debug", "agent", "add", "--count", "4", "t1.micro"); } private GitLikeCommandParser<GalaxyCommand> createParser() { Builder<GalaxyCommand> builder = GitLikeCommandParser.parser("galaxy", GalaxyCommand.class) .withDescription("cloud management system") .defaultCommand(HelpCommand.class) .addCommand(HelpCommand.class) .addCommand(ShowCommand.class) .addCommand(InstallCommand.class) .addCommand(UpgradeCommand.class) .addCommand(TerminateCommand.class) .addCommand(StartCommand.class) .addCommand(StopCommand.class) .addCommand(RestartCommand.class) .addCommand(SshCommand.class) .addCommand(ResetToActualCommand.class); builder.addGroup("agent") .withDescription("Manage agents") .defaultCommand(AgentShowCommand.class) .addCommand(AgentShowCommand.class) .addCommand(AgentAddCommand.class); GitLikeCommandParser<GalaxyCommand> galaxy = builder.build(); return galaxy; } private void parse(String... args) { System.out.println("$ galaxy " + Joiner.on(" ").join(args)); GalaxyCommand command = createParser().parse(args); System.out.println(command); System.out.println(); } public static class GlobalOptions { @Option(type = GLOBAL, name = "--debug", description = "Enable debug messages") public boolean debug = false; @Option(type = GLOBAL, name = "--coordinator", description = "Galaxy coordinator host (overrides GALAXY_COORDINATOR)") public String coordinator = Objects.firstNonNull(System.getenv("GALAXY_COORDINATOR"), "http://localhost:64000"); @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("GlobalOptions"); sb.append("{debug=").append(debug); sb.append(", coordinator='").append(coordinator).append('\''); sb.append('}'); return sb.toString(); } } public static class SlotFilter { @Option(name = {"-b", "--binary"}, description = "Select slots with a given binary") public List<String> binary; @Option(name = {"-c", "--config"}, description = "Select slots with a given configuration") public List<String> config; @Option(name = {"-i", "--host"}, description = "Select slots on the given host") public List<String> host; @Option(name = {"-I", "--ip"}, description = "Select slots at the given IP address") public List<String> ip; @Option(name = {"-u", "--uuid"}, description = "Select slot with the given UUID") public List<String> uuid; @Option(name = {"-s", "--state"}, description = "Select 'r{unning}', 's{topped}' or 'unknown' slots") public List<String> state; @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Filter"); sb.append("{binary=").append(binary); sb.append(", config=").append(config); sb.append(", host=").append(host); sb.append(", ip=").append(ip); sb.append(", uuid=").append(uuid); sb.append(", state=").append(state); sb.append('}'); return sb.toString(); } } public static class AgentFilter { @Option(name = {"-i", "--host"}, description = "Select slots on the given host") public final List<String> host = newArrayList(); @Option(name = {"-I", "--ip"}, description = "Select slots at the given IP address") public final List<String> ip = newArrayList(); @Option(name = {"-u", "--uuid"}, description = "Select slot with the given UUID") public final List<String> uuid = newArrayList(); @Option(name = {"-s", "--state"}, description = "Select 'r{unning}', 's{topped}' or 'unknown' slots") public final List<String> state = newArrayList(); @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Filter"); sb.append("{host=").append(host); sb.append(", ip=").append(ip); sb.append(", uuid=").append(uuid); sb.append(", state=").append(state); sb.append('}'); return sb.toString(); } } public static abstract class GalaxyCommand { @Options public GlobalOptions globalOptions = new GlobalOptions(); } @Command(name = "help", description = "Display help information about galaxy") public static class HelpCommand extends GalaxyCommand { @Options public GlobalMetadata global; @Arguments public List<String> command = newArrayList(); @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); help(global, command, stringBuilder); return stringBuilder.toString(); } } @Command(name = "show", description = "Show state of all slots") public static class ShowCommand extends GalaxyCommand { @Options public final SlotFilter slotFilter = new SlotFilter(); @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("ShowCommand"); sb.append("{slotFilter=").append(slotFilter); sb.append(", globalOptions=").append(globalOptions); sb.append('}'); return sb.toString(); } } @Command(name = "install", description = "Install software in a new slot") public static class InstallCommand extends GalaxyCommand { @Option(name = {"--count"}, description = "Number of instances to install") public int count = 1; @Options public final AgentFilter agentFilter = new AgentFilter(); @Arguments(usage = "<groupId:artifactId[:packaging[:classifier]]:version> @<component:pools:version>", description = "The binary and @configuration to install. The default packaging is tar.gz") public final List<String> assignment = Lists.newArrayList(); @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("InstallCommand"); sb.append("{count=").append(count); sb.append(", agentFilter=").append(agentFilter); sb.append(", assignment=").append(assignment); sb.append(", globalOptions=").append(globalOptions); sb.append('}'); return sb.toString(); } } @Command(name = "upgrade", description = "Upgrade software in a slot") public static class UpgradeCommand extends GalaxyCommand { @Options public final SlotFilter slotFilter = new SlotFilter(); @Arguments(usage = "[<binary-version>] [@<config-version>]", description = "Version of the binary and/or @configuration") public final List<String> versions = Lists.newArrayList(); @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("UpgradeCommand"); sb.append("{slotFilter=").append(slotFilter); sb.append(", versions=").append(versions); sb.append(", globalOptions=").append(globalOptions); sb.append('}'); return sb.toString(); } } @Command(name = "terminate", description = "Terminate (remove) a slot") public static class TerminateCommand extends GalaxyCommand { @Options public final SlotFilter slotFilter = new SlotFilter(); @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("TerminateCommand"); sb.append("{slotFilter=").append(slotFilter); sb.append(", globalOptions=").append(globalOptions); sb.append('}'); return sb.toString(); } } @Command(name = "start", description = "Start a server") public static class StartCommand extends GalaxyCommand { @Options public final SlotFilter slotFilter = new SlotFilter(); @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("StartCommand"); sb.append("{slotFilter=").append(slotFilter); sb.append(", globalOptions=").append(globalOptions); sb.append('}'); return sb.toString(); } } @Command(name = "stop", description = "Stop a server") public static class StopCommand extends GalaxyCommand { @Options public final SlotFilter slotFilter = new SlotFilter(); @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("StopCommand"); sb.append("{slotFilter=").append(slotFilter); sb.append(", globalOptions=").append(globalOptions); sb.append('}'); return sb.toString(); } } @Command(name = "restart", description = "Restart server") public static class RestartCommand extends GalaxyCommand { @Options public final SlotFilter slotFilter = new SlotFilter(); @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("RestartCommand"); sb.append("{slotFilter=").append(slotFilter); sb.append(", globalOptions=").append(globalOptions); sb.append('}'); return sb.toString(); } } @Command(name = "reset-to-actual", description = "Reset slot expected state to actual") public static class ResetToActualCommand extends GalaxyCommand { @Options public final SlotFilter slotFilter = new SlotFilter(); @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("ResetToActualCommand"); sb.append("{slotFilter=").append(slotFilter); sb.append(", globalOptions=").append(globalOptions); sb.append('}'); return sb.toString(); } } @Command(name = "ssh", description = "ssh to slot installation") public static class SshCommand extends GalaxyCommand { @Options public final SlotFilter slotFilter = new SlotFilter(); @Arguments(description = "Command to execute on the remote host") public String command; @Override public String toString() { return "SshCommand{" + "slotFilter=" + slotFilter + ", command='" + command + '\'' + '}'; } } @Command(name = "add", description = "Provision a new agent") public static class AgentAddCommand extends GalaxyCommand { @Option(name = {"--count"}, description = "Number of agents to provision") public int count = 1; @Option(name = {"--availability-zone"}, description = "Availability zone to provision") public String availabilityZone; @Arguments(usage = "[<instance-type>]", description = "Instance type to provision") public String instanceType; @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("AgentAddCommand"); sb.append("{count=").append(count); sb.append(", availabilityZone='").append(availabilityZone).append('\''); sb.append(", instanceType=").append(instanceType); sb.append(", globalOptions=").append(globalOptions); sb.append('}'); return sb.toString(); } } @Command(name = "show", description = "Show agent details") public static class AgentShowCommand extends GalaxyCommand { @Options public final AgentFilter agentFilter = new AgentFilter(); @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("AgentShowCommand"); sb.append("{globalOptions=").append(globalOptions); sb.append(", agentFilter=").append(agentFilter); sb.append('}'); return sb.toString(); } } @Command(name = "terminate", description = "Provision a new agent") public static class AgentTerminateCommand extends GalaxyCommand { @Arguments(title = "agent-id", description = "Agent to terminate", required = true) public String agentId; @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("AgentTerminateCommand"); sb.append("{agentId='").append(agentId).append('\''); sb.append(", globalOptions=").append(globalOptions); sb.append('}'); return sb.toString(); } } }
package org.kohsuke.github; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.List; import static org.hamcrest.CoreMatchers.*; public class GHPullRequestTest extends AbstractGitHubWireMockTest { @Before @After public void cleanUp() throws Exception { // Cleanup is only needed when proxying if (!mockGitHub.isUseProxy()) { return; } for (GHPullRequest pr : getRepository(this.getGitHubBeforeAfter()).getPullRequests(GHIssueState.OPEN)) { pr.close(); } } @Test public void createPullRequest() throws Exception { String name = "createPullRequest"; GHRepository repo = getRepository(); GHPullRequest p = repo.createPullRequest(name, "test/stable", "master", "## test"); assertEquals(name, p.getTitle()); assertThat(p.canMaintainerModify(), is(false)); assertThat(p.isDraft(), is(false)); } @Test public void createDraftPullRequest() throws Exception { String name = "createDraftPullRequest"; GHRepository repo = getRepository(); GHPullRequest p = repo.createPullRequest(name, "test/stable", "master", "## test", false, true); assertEquals(name, p.getTitle()); assertThat(p.canMaintainerModify(), is(false)); assertThat(p.isDraft(), is(true)); // There are multiple paths to get PRs and each needs to read draft correctly p.draft = false; p.refresh(); assertThat(p.isDraft(), is(true)); GHPullRequest p2 = repo.getPullRequest(p.getNumber()); assertThat(p2.getNumber(), is(p.getNumber())); assertThat(p2.isDraft(), is(true)); p = repo.queryPullRequests().state(GHIssueState.OPEN).head("test/stable").list().toList().get(0); assertThat(p2.getNumber(), is(p.getNumber())); assertThat(p.isDraft(), is(true)); } @Test public void createPullRequestComment() throws Exception { String name = "createPullRequestComment"; GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); p.comment("Some comment"); } @Test public void closePullRequest() throws Exception { String name = "closePullRequest"; GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); // System.out.println(p.getUrl()); assertEquals(name, p.getTitle()); assertEquals(GHIssueState.OPEN, getRepository().getPullRequest(p.getNumber()).getState()); p.close(); assertEquals(GHIssueState.CLOSED, getRepository().getPullRequest(p.getNumber()).getState()); } @Test public void pullRequestReviews() throws Exception { String name = "testPullRequestReviews"; GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); GHPullRequestReview draftReview = p.createReview() .body("Some draft review") .comment("Some niggle", "README.md", 1) .create(); assertThat(draftReview.getState(), is(GHPullRequestReviewState.PENDING)); assertThat(draftReview.getBody(), is("Some draft review")); assertThat(draftReview.getCommitId(), notNullValue()); List<GHPullRequestReview> reviews = p.listReviews().toList(); assertThat(reviews.size(), is(1)); GHPullRequestReview review = reviews.get(0); assertThat(review.getState(), is(GHPullRequestReviewState.PENDING)); assertThat(review.getBody(), is("Some draft review")); assertThat(review.getCommitId(), notNullValue()); draftReview.submit("Some review comment", GHPullRequestReviewEvent.COMMENT); List<GHPullRequestReviewComment> comments = review.listReviewComments().toList(); assertEquals(1, comments.size()); GHPullRequestReviewComment comment = comments.get(0); assertEquals("Some niggle", comment.getBody()); draftReview = p.createReview().body("Some new review").comment("Some niggle", "README.md", 1).create(); draftReview.delete(); } @Test public void pullRequestReviewComments() throws Exception { String name = "pullRequestReviewComments"; GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); // System.out.println(p.getUrl()); assertTrue(p.listReviewComments().toList().isEmpty()); p.createReviewComment("Sample review comment", p.getHead().getSha(), "README.md", 1); List<GHPullRequestReviewComment> comments = p.listReviewComments().toList(); assertEquals(1, comments.size()); GHPullRequestReviewComment comment = comments.get(0); assertEquals("Sample review comment", comment.getBody()); // Assert htmlUrl is not null assertNotNull(comment.getHtmlUrl()); assertEquals(new URL("https://github.com/github-api-test-org/github-api/pull/266#discussion_r321995146"), comment.getHtmlUrl()); comment.update("Updated review comment"); comments = p.listReviewComments().toList(); assertEquals(1, comments.size()); comment = comments.get(0); assertEquals("Updated review comment", comment.getBody()); comment.delete(); comments = p.listReviewComments().toList(); assertTrue(comments.isEmpty()); } @Test public void testPullRequestReviewRequests() throws Exception { String name = "testPullRequestReviewRequests"; GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); // System.out.println(p.getUrl()); assertTrue(p.getRequestedReviewers().isEmpty()); GHUser kohsuke2 = gitHub.getUser("kohsuke2"); p.requestReviewers(Collections.singletonList(kohsuke2)); p.refresh(); assertFalse(p.getRequestedReviewers().isEmpty()); } @Test public void testPullRequestTeamReviewRequests() throws Exception { String name = "testPullRequestTeamReviewRequests"; GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); // System.out.println(p.getUrl()); assertTrue(p.getRequestedReviewers().isEmpty()); GHOrganization testOrg = gitHub.getOrganization("github-api-test-org"); GHTeam testTeam = testOrg.getTeamBySlug("dummy-team"); p.requestTeamReviewers(Collections.singletonList(testTeam)); int baseRequestCount = mockGitHub.getRequestCount(); p.refresh(); assertThat("We should not eagerly load organizations for teams", mockGitHub.getRequestCount() - baseRequestCount, equalTo(1)); assertThat(p.getRequestedTeams().size(), equalTo(1)); assertThat("We should not eagerly load organizations for teams", mockGitHub.getRequestCount() - baseRequestCount, equalTo(1)); assertThat("Org should be queried for automatically if asked for", p.getRequestedTeams().get(0).getOrganization(), notNullValue()); assertThat("Request count should show lazy load occurred", mockGitHub.getRequestCount() - baseRequestCount, equalTo(2)); } @Test public void mergeCommitSHA() throws Exception { String name = "mergeCommitSHA"; GHRepository repo = getRepository(); GHPullRequest p = repo.createPullRequest(name, "test/mergeable_branch", "master", "## test"); int baseRequestCount = mockGitHub.getRequestCount(); assertThat(p.getMergeableNoRefresh(), nullValue()); assertThat("Used existing value", mockGitHub.getRequestCount() - baseRequestCount, equalTo(0)); // mergeability computation takes time, this should still be null immediately after creation assertThat(p.getMergeable(), nullValue()); assertThat("Asked for PR information", mockGitHub.getRequestCount() - baseRequestCount, equalTo(1)); for (int i = 2; i <= 10; i++) { if (Boolean.TRUE.equals(p.getMergeable()) && p.getMergeCommitSha() != null) { assertThat("Asked for PR information", mockGitHub.getRequestCount() - baseRequestCount, equalTo(i)); // make sure commit exists GHCommit commit = repo.getCommit(p.getMergeCommitSha()); assertNotNull(commit); assertThat("Asked for PR information", mockGitHub.getRequestCount() - baseRequestCount, equalTo(i + 1)); return; } // mergeability computation takes time. give it more chance Thread.sleep(1000); } // hmm? fail(); } @Test public void squashMerge() throws Exception { String name = "squashMerge"; String branchName = "test/" + name; GHRef masterRef = getRepository().getRef("heads/master"); GHRef branchRef = getRepository().createRef("refs/heads/" + branchName, masterRef.getObject().getSha()); getRepository().createContent(name, name, name, branchName); Thread.sleep(1000); GHPullRequest p = getRepository().createPullRequest(name, branchName, "master", "## test squash"); Thread.sleep(1000); p.merge("squash merge", null, GHPullRequest.MergeMethod.SQUASH); } @Test public void updateContentSquashMerge() throws Exception { String name = "updateContentSquashMerge"; String branchName = "test/" + name; GHRef masterRef = getRepository().getRef("heads/master"); GHRef branchRef = getRepository().createRef("refs/heads/" + branchName, masterRef.getObject().getSha()); GHContentUpdateResponse response = getRepository().createContent(name, name, name, branchName); Thread.sleep(1000); getRepository().createContent() .content(name + name) .path(name) .branch(branchName) .message(name) .sha(response.getContent().getSha()) .commit(); GHPullRequest p = getRepository().createPullRequest(name, branchName, "master", "## test squash"); Thread.sleep(1000); p.merge("squash merge", null, GHPullRequest.MergeMethod.SQUASH); } @Test public void queryPullRequestsQualifiedHead() throws Exception { GHRepository repo = getRepository(); // Create PRs from two different branches to master repo.createPullRequest("queryPullRequestsQualifiedHead_stable", "test/stable", "master", null); repo.createPullRequest("queryPullRequestsQualifiedHead_rc", "test/rc", "master", null); // Query by one of the heads and make sure we only get that branch's PR back. List<GHPullRequest> prs = repo.queryPullRequests() .state(GHIssueState.OPEN) .head("github-api-test-org:test/stable") .base("master") .list() .toList(); assertNotNull(prs); assertEquals(1, prs.size()); assertEquals("test/stable", prs.get(0).getHead().getRef()); } @Test public void queryPullRequestsUnqualifiedHead() throws Exception { GHRepository repo = getRepository(); // Create PRs from two different branches to master repo.createPullRequest("queryPullRequestsUnqualifiedHead_stable", "test/stable", "master", null); repo.createPullRequest("queryPullRequestsUnqualifiedHead_rc", "test/rc", "master", null); // Query by one of the heads and make sure we only get that branch's PR back. List<GHPullRequest> prs = repo.queryPullRequests() .state(GHIssueState.OPEN) .head("test/stable") .base("master") .list() .toList(); assertNotNull(prs); assertEquals(1, prs.size()); assertEquals("test/stable", prs.get(0).getHead().getRef()); } @Test // Requires push access to the test repo to pass public void setLabels() throws Exception { GHPullRequest p = getRepository().createPullRequest("setLabels", "test/stable", "master", "## test"); String label = "setLabels_label_name"; p.setLabels(label); Collection<GHLabel> labels = getRepository().getPullRequest(p.getNumber()).getLabels(); assertEquals(1, labels.size()); assertEquals(label, labels.iterator().next().getName()); } @Test // Requires push access to the test repo to pass public void setAssignee() throws Exception { GHPullRequest p = getRepository().createPullRequest("setAssignee", "test/stable", "master", "## test"); GHMyself user = gitHub.getMyself(); p.assignTo(user); assertEquals(user, getRepository().getPullRequest(p.getNumber()).getAssignee()); } @Test public void getUserTest() throws IOException { GHPullRequest p = getRepository().createPullRequest("getUserTest", "test/stable", "master", "## test"); GHPullRequest prSingle = getRepository().getPullRequest(p.getNumber()); assertNotNull(prSingle.getUser().root); prSingle.getMergeable(); assertNotNull(prSingle.getUser().root); PagedIterable<GHPullRequest> ghPullRequests = getRepository().listPullRequests(GHIssueState.OPEN); for (GHPullRequest pr : ghPullRequests) { assertNotNull(pr.getUser().root); pr.getMergeable(); assertNotNull(pr.getUser().root); } } protected GHRepository getRepository() throws IOException { return getRepository(gitHub); } private GHRepository getRepository(GitHub gitHub) throws IOException { return gitHub.getOrganization("github-api-test-org").getRepository("github-api"); } }
package net.aicomp.javachallenge2015; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class Bookmaker { private static boolean DEBUG = false; private static final int PLAYERS_NUM = 4; private static final int MAP_WIDTH = 40; private static final int BLOCK_WIDTH = 5; private static final int INITIAL_LIFE = 5; private static final int FORCED_END_TURN = 10000; private static final int PANEL_REBIRTH_TURN = 5 * 4; public static final int PLAYER_REBIRTH_TURN = 5 * 4; public static final int ATTACKED_PAUSE_TURN = 5 * 4; public static final int MUTEKI_TURN = 10 * 4; private static final int REPULSION = 7; public static final int ACTION_TIME_LIMIT = 2000; private static final int TIME_TO_FALL = 1 * 4; public static final String READY = "READY"; public static final String UP = "U"; public static final String DOWN = "D"; public static final String RIGHT = "R"; public static final String LEFT = "L"; public static final String ATTACK = "A"; public static final String NONE = "N"; public static final String[] DIRECTION = { UP, LEFT, DOWN, RIGHT }; private static Player[] players; private static Random rnd; private static int turn; private static int[][] board = new int[MAP_WIDTH][MAP_WIDTH]; private static final String EXEC_COMMAND = "a"; private static final String PAUSE_COMMAND = "p"; private static final String UNPAUSE_COMMAND = "u"; public static void main(String[] args) throws InterruptedException, ParseException { Options options = new Options() .addOption( EXEC_COMMAND, true, "The command and arguments with double quotation marks to execute AI program (e.g. -a \"java MyAI\")") .addOption( PAUSE_COMMAND, true, "The command and arguments with double quotation marks to pause AI program (e.g. -p \"echo pause\")") .addOption( UNPAUSE_COMMAND, true, "The command and arguments with double quotation marks to unpause AI program (e.g. -u \"echo unpause\")"); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (!hasCompleteArgs(line)) { HelpFormatter help = new HelpFormatter(); help.printHelp("java -jar JavaChallenge2015.jar [OPTIONS]\n" + "[OPTIONS]: ", "", options, "", true); return; } String[] execAICommands = line.getOptionValues(EXEC_COMMAND); String[] pauseAICommands = line.hasOption(PAUSE_COMMAND) ? line .getOptionValues(PAUSE_COMMAND) : new String[PLAYERS_NUM]; String[] unpauseAICommands = line.hasOption(UNPAUSE_COMMAND) ? line .getOptionValues(UNPAUSE_COMMAND) : new String[PLAYERS_NUM]; rnd = new Random(System.currentTimeMillis()); turn = 0; players = new Player[PLAYERS_NUM]; for (int i = 0; i < players.length; i++) { players[i] = new Player(INITIAL_LIFE, execAICommands[i], pauseAICommands[i], unpauseAICommands[i]); } rebirthPhase(); while (!isFinished()) { int turnPlayer = turn % PLAYERS_NUM; String command = infromationPhase(turnPlayer); printLOG(command); // DEBUG if (DEBUG && turnPlayer == 0 && players[turnPlayer].isOnBoard() && !players[turnPlayer].isPausing(turn)) { command = new Scanner(System.in).next(); } actionPhase(turnPlayer, command); rebirthPhase(); turn++; } System.out.println("Game Finished!"); } /** * null4 * 14 * * @param line * @author J.Kobayashi * @return {@code true}{@code false} */ private static boolean hasCompleteArgs(CommandLine line) { if (line == null) { return false; } if (!line.hasOption(EXEC_COMMAND) || line.getOptionValues(EXEC_COMMAND).length != PLAYERS_NUM) { return false; } if (!line.hasOption(PAUSE_COMMAND)) { return true; } if (line.getOptionValues(PAUSE_COMMAND).length != PLAYERS_NUM) { return false; } if (!line.hasOption(UNPAUSE_COMMAND)) { return true; } if (line.getOptionValues(UNPAUSE_COMMAND).length != PLAYERS_NUM) { return false; } return true; } private static void printLOG(String command) { System.out.println(turn); for (Player player : players) { System.out.print(player.life + " "); } System.out.println(); for (int x = 0; x < MAP_WIDTH; x++) { outer: for (int y = 0; y < MAP_WIDTH; y++) { if (DEBUG) { for (int playerID = 0; playerID < PLAYERS_NUM; playerID++) { Player player = players[playerID]; if (player.isOnBoard() && player.x == x && player.y == y) { char c = (char) (playerID + 'A'); System.out.print(c + "" + c); continue outer; } } } System.out.print(" " + board[x][y]); } System.out.println(); } for (Player player : players) { if (player.isOnBoard()) { System.out.println(player.x + " " + player.y + " " + Bookmaker.DIRECTION[player.dir]); } else { System.out.println((-1) + " " + (-1) + " " + Bookmaker.DIRECTION[player.dir]); } } System.out.println(command); } private static void rebirthPhase() { for (int i = 0; i < MAP_WIDTH; i++) { for (int j = 0; j < MAP_WIDTH; j++) { if (board[i][j] < 0) { board[i][j]++; } else if (board[i][j] == 1) { board[i][j] = -PANEL_REBIRTH_TURN; } else if (board[i][j] > 1) { board[i][j] } } } for (int i = 0; i < PLAYERS_NUM; i++) { Player p = players[i]; if (p.isOnBoard() && !p.isMuteki(turn)) { if (board[p.x][p.y] < 0) { p.drop(turn); } } else if (p.isAlive() && !p.isOnBoard() && p.rebirthTurn == turn) { search: while (true) { int x = nextInt(); int y = nextInt(); for (int j = 0; j < PLAYERS_NUM; j++) { if (i == j) { continue; } Player other = players[j]; if (other.isOnBoard() && dist(x, y, other.x, other.y) <= REPULSION) { continue search; } } p.reBirthOn(x, y, turn); p.dir = nextDir(); break; } } } } private static String infromationPhase(int turnPlayer) { if (!players[turnPlayer].isAlive()) { return NONE; } ArrayList<Integer> lifes = new ArrayList<Integer>(); ArrayList<String> wheres = new ArrayList<String>(); for (int i = 0; i < PLAYERS_NUM; i++) { lifes.add(players[i].life); if (players[i].isOnBoard()) { wheres.add(players[i].x + " " + players[i].y); } else { wheres.add((-1) + " " + (-1)); } } String command = players[turnPlayer].getAction(turnPlayer, turn, board, lifes, wheres); return command; } private static void actionPhase(int turnPlayer, String command) { Player p = players[turnPlayer]; if (!p.isOnBoard() || p.isPausing(turn) || command.equals(NONE)) { return; } if (command.equals(ATTACK)) { int xNow = p.x / BLOCK_WIDTH; int yNow = p.y / BLOCK_WIDTH; for (int x = 0; x < MAP_WIDTH; x++) { for (int y = 0; y < MAP_WIDTH; y++) { int xBlock = x / BLOCK_WIDTH; int yBlock = y / BLOCK_WIDTH; if (p.dir == 0) { if (yBlock == yNow && xBlock < xNow && board[x][y] == 0) { board[x][y] = dist(xBlock, yBlock, xNow, yNow) * TIME_TO_FALL; } } else if (p.dir == 1) { if (xBlock == xNow && yBlock < yNow && board[x][y] == 0) { board[x][y] = dist(xBlock, yBlock, xNow, yNow) * TIME_TO_FALL; } } else if (p.dir == 2) { if (yBlock == yNow && xBlock > xNow && board[x][y] == 0) { board[x][y] = dist(xBlock, yBlock, xNow, yNow) * TIME_TO_FALL; } } else if (p.dir == 3) { if (xBlock == xNow && yBlock > yNow && board[x][y] == 0) { board[x][y] = dist(xBlock, yBlock, xNow, yNow) * TIME_TO_FALL; } } } } p.attackedPause(turn); return; } { int tox = -1, toy = -1; if (command.equals(UP)) { tox = p.x - 1; toy = p.y; } else if (command.equals(RIGHT)) { tox = p.x; toy = p.y + 1; } else if (command.equals(DOWN)) { tox = p.x + 1; toy = p.y; } else if (command.equals(LEFT)) { tox = p.x; toy = p.y - 1; } else { return; } if (!isInside(tox, toy)) { return; } p.directTo(command); for (int i = 0; i < PLAYERS_NUM; i++) { if (!players[i].isOnBoard() || i == turnPlayer) { continue; } if (dist(tox, toy, players[i].x, players[i].y) < REPULSION) { return; } } p.moveTo(tox, toy); } } private static int dist(int x1, int y1, int x2, int y2) { return Math.abs(x1 - x2) + Math.abs(y1 - y2); } private static int nextInt() { int ret = (int) (rnd.nextDouble() * MAP_WIDTH); return ret; } private static int nextDir() { int rng = rnd.nextInt(4); return rng; } private static boolean isInside(int x, int y) { return 0 <= x && x < MAP_WIDTH && 0 <= y && y < MAP_WIDTH; } private static boolean isFinished() { int livingCnt = 0; for (int i = 0; i < players.length; i++) { if (players[i].life > 0) { livingCnt++; } } return livingCnt == 1 || turn > FORCED_END_TURN; } }
package net.aicomp.javachallenge2015; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class Bookmaker { private static boolean DEBUG = false; private static final int PLAYERS_NUM = 4; private static final int MAP_WIDTH = 40; private static final int BLOCK_WIDTH = 5; private static final int INITIAL_LIFE = 5; private static final int FORCED_END_TURN = 10000; private static final int PANEL_REBIRTH_TURN = 5 * 4; public static final int PLAYER_REBIRTH_TURN = 5 * 4; public static final int ATTACKED_PAUSE_TURN = 5 * 4; public static final int MUTEKI_TURN = 10 * 4; private static final int REPULSION = 7; public static final int ACTION_TIME_LIMIT = 2000; private static final int TIME_TO_FALL = 1 * 4; public static final String READY = "Ready"; public static final String UP = "U"; public static final String DOWN = "D"; public static final String RIGHT = "R"; public static final String LEFT = "L"; public static final String ATTACK = "A"; public static final String NONE = "N"; public static final String[] DIRECTION = { UP, LEFT, DOWN, RIGHT }; private static Player[] players; private static Random rnd; private static int turn; private static int[][] board = new int[MAP_WIDTH][MAP_WIDTH]; private static final String EXEC_COMMAND = "a"; private static final String PAUSE_COMMAND = "p"; private static final String UNPAUSE_COMMAND = "u"; public static void main(String[] args) throws InterruptedException, ParseException { Options options = new Options() .addOption(EXEC_COMMAND, true, "Commands to execute AI program") .addOption(PAUSE_COMMAND, true, "Commands to pause AI program") .addOption(UNPAUSE_COMMAND, true, "Commands to unpause AI program"); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (!hasCompleteArgs(line)) { HelpFormatter help = new HelpFormatter(); help.printHelp("java -jar JavaChallenge2015.jar [OPTIONS]\n" + "[OPTIONS]: ", "", options, "", true); return; } String[] execAICommands = line.getOptionValues(EXEC_COMMAND); String[] pauseAICommands = line.getOptionValues(PAUSE_COMMAND); String[] unpauseAICommands = line.getOptionValues(UNPAUSE_COMMAND); rnd = new Random(System.currentTimeMillis()); turn = 0; players = new Player[PLAYERS_NUM]; for (int i = 0; i < players.length; i++) { players[i] = new Player(INITIAL_LIFE, execAICommands[i], pauseAICommands[i], unpauseAICommands[i]); } rebirthPhase(); while (!isFinished()) { int turnPlayer = turn % PLAYERS_NUM; String command = infromationPhase(turnPlayer); printLOG(command); // DEBUG if (DEBUG && turnPlayer == 0 && players[turnPlayer].isOnBoard() && !players[turnPlayer].isPausing(turn)) { command = new Scanner(System.in).next(); } actionPhase(turnPlayer, command); rebirthPhase(); turn++; } System.out.println("Game Finished!"); } /** * * * @param line * @author J.Kobayashi * @return 4 * {@code true}{@code false} */ private static boolean hasCompleteArgs(CommandLine line) { return line != null && line.getOptionValues(EXEC_COMMAND).length == PLAYERS_NUM && line.getOptionValues(PAUSE_COMMAND).length == PLAYERS_NUM && line.getOptionValues(UNPAUSE_COMMAND).length == PLAYERS_NUM; } private static void printLOG(String command) { System.out.println(turn); for (Player player : players) { System.out.print(player.life + " "); } System.out.println(); for (int x = 0; x < MAP_WIDTH; x++) { outer: for (int y = 0; y < MAP_WIDTH; y++) { if (DEBUG) { for (int playerID = 0; playerID < PLAYERS_NUM; playerID++) { Player player = players[playerID]; if (player.isOnBoard() && player.x == x && player.y == y) { char c = (char) (playerID + 'A'); System.out.print(c + "" + c); continue outer; } } } System.out.print(" " + board[x][y]); } System.out.println(); } for (Player player : players) { if (player.isOnBoard()) { System.out.println(player.x + " " + player.y + " " + Bookmaker.DIRECTION[player.dir]); } else { System.out.println((-1) + " " + (-1) + " " + Bookmaker.DIRECTION[player.dir]); } } System.out.println(command); } private static void rebirthPhase() { for (int i = 0; i < MAP_WIDTH; i++) { for (int j = 0; j < MAP_WIDTH; j++) { if (board[i][j] < 0) { board[i][j]++; } else if (board[i][j] == 1) { board[i][j] = -PANEL_REBIRTH_TURN; } else if (board[i][j] > 1) { board[i][j] } } } for (int i = 0; i < PLAYERS_NUM; i++) { Player p = players[i]; if (p.isOnBoard() && !p.isMuteki(turn)) { if (board[p.x][p.y] < 0) { p.drop(turn); } } else if (p.isAlive() && !p.isOnBoard() && p.rebirthTurn == turn) { search: while (true) { int x = nextInt(); int y = nextInt(); for (int j = 0; j < PLAYERS_NUM; j++) { if (i == j) { continue; } Player other = players[j]; if (other.isOnBoard() && dist(x, y, other.x, other.y) <= REPULSION) { continue search; } } p.reBirthOn(x, y, turn); p.dir = nextDir(); break; } } } } private static String infromationPhase(int turnPlayer) { if (!players[turnPlayer].isAlive()) { return NONE; } ArrayList<Integer> lifes = new ArrayList<Integer>(); ArrayList<String> wheres = new ArrayList<String>(); for (int i = 0; i < PLAYERS_NUM; i++) { lifes.add(players[i].life); if (players[i].isOnBoard()) { wheres.add(players[i].x + " " + players[i].y); } else { wheres.add((-1) + " " + (-1)); } } String command = players[turnPlayer].getAction(turnPlayer, turn, board, lifes, wheres); return command; } private static void actionPhase(int turnPlayer, String command) { Player p = players[turnPlayer]; if (!p.isOnBoard() || p.isPausing(turn) || command.equals(NONE)) { return; } if (command.equals(ATTACK)) { int xNow = p.x / BLOCK_WIDTH; int yNow = p.y / BLOCK_WIDTH; for (int x = 0; x < MAP_WIDTH; x++) { for (int y = 0; y < MAP_WIDTH; y++) { int xBlock = x / BLOCK_WIDTH; int yBlock = y / BLOCK_WIDTH; if (p.dir == 0) { if (yBlock == yNow && xBlock < xNow && board[x][y] == 0) { board[x][y] = dist(xBlock, yBlock, xNow, yNow) * TIME_TO_FALL; } } else if (p.dir == 1) { if (xBlock == xNow && yBlock < yNow && board[x][y] == 0) { board[x][y] = dist(xBlock, yBlock, xNow, yNow) * TIME_TO_FALL; } } else if (p.dir == 2) { if (yBlock == yNow && xBlock > xNow && board[x][y] == 0) { board[x][y] = dist(xBlock, yBlock, xNow, yNow) * TIME_TO_FALL; } } else if (p.dir == 3) { if (xBlock == xNow && yBlock > yNow && board[x][y] == 0) { board[x][y] = dist(xBlock, yBlock, xNow, yNow) * TIME_TO_FALL; } } } } p.attackedPause(turn); return; } { int tox = -1, toy = -1; if (command.equals(UP)) { tox = p.x - 1; toy = p.y; } else if (command.equals(RIGHT)) { tox = p.x; toy = p.y + 1; } else if (command.equals(DOWN)) { tox = p.x + 1; toy = p.y; } else if (command.equals(LEFT)) { tox = p.x; toy = p.y - 1; } else { return; } if (!isInside(tox, toy)) { return; } p.directTo(command); for (int i = 0; i < PLAYERS_NUM; i++) { if (!players[i].isOnBoard() || i == turnPlayer) { continue; } if (dist(tox, toy, players[i].x, players[i].y) < REPULSION) { return; } } p.moveTo(tox, toy); } } private static int dist(int x1, int y1, int x2, int y2) { return Math.abs(x1 - x2) + Math.abs(y1 - y2); } private static int nextInt() { int ret = (int) (rnd.nextDouble() * MAP_WIDTH); return ret; } private static int nextDir() { int rng = rnd.nextInt(4); return rng; } private static boolean isInside(int x, int y) { return 0 <= x && x < MAP_WIDTH && 0 <= y && y < MAP_WIDTH; } private static boolean isFinished() { int livingCnt = 0; for (int i = 0; i < players.length; i++) { if (players[i].life > 0) { livingCnt++; } } return livingCnt == 1 || turn > FORCED_END_TURN; } }
package net.anyflow.menton.http; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import net.anyflow.menton.Configurator; import net.anyflow.menton.exception.DefaultException; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.jboss.netty.handler.codec.http.QueryStringDecoder; import org.jboss.netty.util.CharsetUtil; import org.reflections.Reflections; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author anyflow Base class for business logic. The class contains common * stuffs for generating business logic. */ public class RequestHandler { private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class); private HttpRequest request; private HttpResponse response; private Map<String, List<String>> parameters; private Map<String, String> headers; /** * @return the parameters */ public Map<String, List<String>> getParameters() { return parameters; } public void initialize(HttpRequest request, HttpResponse response) { this.request = request; this.response = response; parseParameters(); parseHeaders(); } public HttpRequest getRequest() { return request; } public HttpResponse getResponse() { return response; } public String getUri() { return request.getUri(); } public String getHttpMethod() { return request.getMethod().toString(); } public String getProtocolVersion() { return request.getProtocolVersion().toString(); } public String getHost() { return HttpHeaders.getHost(request, "unknown"); } private void parseParameters() { String httpMethod = request.getMethod().toString(); String queryStringParam = null; if(httpMethod.equalsIgnoreCase("GET")) { queryStringParam = request.getUri(); } else if(httpMethod.equalsIgnoreCase("POST")) { String dummy = "/dummy?"; queryStringParam = dummy + request.getContent().toString(CharsetUtil.UTF_8); } else { response.setStatus(HttpResponseStatus.METHOD_NOT_ALLOWED); throw new UnsupportedOperationException("only GET/POST http methods are supported."); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(queryStringParam); parameters = queryStringDecoder.getParameters(); } private void parseHeaders() { HashMap<String,String> headerMap = new HashMap<String,String>(); List<Entry<String, String>> headerList = this.request.getHeaders(); Iterator itr = headerList.iterator(); while(itr.hasNext()) { Entry<String, String> itm = (Entry<String, String>) itr.next(); headerMap.put(itm.getKey().toLowerCase(), itm.getValue()); } headers = headerMap; } public String getParameter(String key) { if(parameters.containsKey(key)) { return parameters.get(key).get(0); } else { return ""; } } public String getHeader(String key) { if(headers.containsKey(key.toLowerCase())) { return headers.get(key.toLowerCase()); } else { return ""; } } public List<String> getArrayParameter(String key) { if(parameters.containsKey(key)) { return parameters.get(key); } else { return (new ArrayList<String>()); } } /** * @return processed content string */ public String call() { throw new UnsupportedOperationException("Derived class's method should be called instead of this."); } /** * @author anyflow */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) public @interface Handles { /** * @return supported paths */ String[] paths(); /** * supported http methods * * @return http method string */ String[] httpMethods(); } /** * @param requestedPath * @param httpMethod * @return * @throws DefaultException */ public static Class<? extends RequestHandler> find(String requestedPath, String httpMethod) throws DefaultException { Reflections reflections = new Reflections(Configurator.getRequestHandlerPackageRoot()); String contextRoot = Configurator.getHttpContextRoot(); Set<Class<? extends RequestHandler>> requestHandler = reflections.getSubTypesOf(RequestHandler.class); for(Class<? extends RequestHandler> item : requestHandler) { RequestHandler.Handles bl = item.getAnnotation(RequestHandler.Handles.class); if(bl == null) { continue; } for(String method : bl.httpMethods()) { if(method.equalsIgnoreCase(httpMethod) == false) { continue; } for(String rawPath : bl.paths()) { String path = (rawPath.charAt(0) == '/') ? rawPath : contextRoot + rawPath; if(requestedPath.equalsIgnoreCase(path)) { return item; } } } } logger.error("Failed to find requestHandler."); return null; } /** * @param requestedPath * @param httpMethod * @return * @throws DefaultException */ public java.lang.reflect.Method findHandler(String requestedPath, String httpMethod) throws DefaultException { String contextRoot = Configurator.getHttpContextRoot(); Method[] methods = this.getClass().getMethods(); for(Method item : methods) { RequestHandler.Handles bl = item.getAnnotation(RequestHandler.Handles.class); if(bl == null) { continue; } for(String method : bl.httpMethods()) { if(method.equalsIgnoreCase(httpMethod) == false) { continue; } for(String rawPath : bl.paths()) { String path = (rawPath.charAt(0) == '/') ? rawPath : contextRoot + rawPath; if(requestedPath.equalsIgnoreCase(path)) { return item; } } } } logger.error("Failed to find requestHandler."); return null; } }
package net.exodiusmc.example.layers; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import javafx.scene.canvas.GraphicsContext; import javafx.scene.image.Image; import javafx.scene.input.KeyCode; import javafx.scene.paint.Color; import javafx.scene.text.Font; import net.exodiusmc.engine.InputManager; import net.exodiusmc.engine.Location; import net.exodiusmc.engine.animation.SpriteAnimation; import net.exodiusmc.engine.enums.Direction; import net.exodiusmc.engine.layers.Layer; import net.exodiusmc.engine.shape.Rectangle; import net.exodiusmc.engine.util.CoreUtils; import net.exodiusmc.engine.util.FileUtils; import net.exodiusmc.example.Main; import net.exodiusmc.example.entity.Entity; import net.exodiusmc.example.entity.LivingEntity; import net.exodiusmc.example.entity.living.Hero; import net.exodiusmc.example.entity.living.Monster; import net.exodiusmc.example.entity.powerup.HeartExtra; import net.exodiusmc.example.entity.powerup.HeartPower; public class GameLayer implements Layer { private Image groundImg; private Image heroImg; private Image monsterHead; private Image monsterImg; private Image heartFull; private Image heartEmpty; private Image heartExtra; private Image trees; private Hero hero; private SpriteAnimation heroSprite; private SpriteAnimation monsterSprite; private Rectangle playField; private InputManager input; private boolean updateSprite; private boolean updateMonsterSprite; private Font scoreFont; private int score; private int heartSize = 20; private float fade; public ArrayList<Entity> entities; public GameLayer() { this.groundImg = FileUtils.LoadImage("ground.png"); this.heroImg = FileUtils.LoadImage("hero_anim.png"); this.monsterImg = FileUtils.LoadImage("monster_anim.png"); this.heartEmpty = FileUtils.LoadImage("heart_empty.png"); this.heartFull = FileUtils.LoadImage("heart_full.png"); this.heartExtra = FileUtils.LoadImage("heart_plus.png"); this.trees = FileUtils.LoadImage("trees.png"); this.playField = new Rectangle(new Location(50, 50), new Location(564, 525)); this.input = Main.getInputMngr(); this.heroSprite = new SpriteAnimation(heroImg, 5); this.monsterSprite = new SpriteAnimation(monsterImg, 5); this.updateSprite = false; this.monsterHead = FileUtils.LoadImage("head.png"); this.scoreFont = (new Font("Arial", 25)); this.entities = new ArrayList<Entity>(); this.fade = 0; Location l = playField.getLocationRelative(0.59, 0.59); this.hero = new Hero(l); this.entities.add(this.hero); this.heroSprite.setSpriteOrder(new int[]{0, 1, 2, 3, 4, 3, 2, 1}); this.monsterSprite.setSpriteOrder(new int[]{0, 1, 2, 3, 4, 3, 2, 1}); } @Override public void update(double delta, long frame) { if(this.hero.getHealth() > 0) { boolean r1 = handleMovement(new KeyCode[]{KeyCode.UP, KeyCode.W}, Direction.UP); boolean r2 = handleMovement(new KeyCode[]{KeyCode.RIGHT, KeyCode.D}, Direction.RIGHT); boolean r3 = handleMovement(new KeyCode[]{KeyCode.DOWN, KeyCode.S}, Direction.DOWN); boolean r4 = handleMovement(new KeyCode[]{KeyCode.LEFT, KeyCode.A}, Direction.LEFT); if(frame % 5 == 0 && (r1 || r2 || r3 || r4)) { this.updateSprite = true; } else { this.updateSprite = false; } if(frame % 5 == 0) { this.updateMonsterSprite = true; } else { this.updateMonsterSprite = false; } if(this.hero.facingCache != this.hero.facing) { this.hero.facingCache = this.hero.facing; } if(frame % 100 == 0) { this.entities.add(new Monster(this.playField)); } if(frame % 90 == 0) { if(CoreUtils.randomIntInRange(0, 8) == 0) this.entities.add(new HeartPower(this.playField)); } if(frame % 120 == 0) { if(CoreUtils.randomIntInRange(0, 20) == 0) this.entities.add(new HeartExtra(this.playField)); } sortEntities(); Location heroLoc = this.hero.getLocation(); Iterator<Entity> i = this.entities.iterator(); while(i.hasNext()) { Entity m = i.next(); if(m instanceof LivingEntity) { ((LivingEntity) m).handleMovement(this.playField); } switch(m.getEntityType()) { case EXTRA_HEART: if(m.getLocation().distance(heroLoc) < 30) { ((HeartExtra) m).pickup(this.hero); i.remove(); } break; case MONSTER: if(m.getLocation().distance(heroLoc) < 30 && this.hero.dmgTick == 0) { this.hero.damageHero(1); ((LivingEntity) m).damage(1); i.remove(); } else { ((LivingEntity) m).moveTo(this.playField, this.hero.getLocation()); } break; case MUMMY: break; case POWER_HEART: if(m.getLocation().distance(heroLoc) < 30 && this.hero.getMaxHealth() != this.hero.getHealth()) { ((HeartPower) m).pickup(this.hero); i.remove(); } break; case SKELETON: break; default: break; } } if(this.hero.damageTick > 0) { this.hero.damageTick -= 0.1; } else { this.hero.damageTick = 0; } if(this.hero.dmgTick > 0) { this.hero.dmgTick -= 0.1; } else { this.hero.dmgTick = 0; }; } else if(this.fade <= 0.4) { this.fade += 0.03; } } @Override public void render(GraphicsContext gfx) { Image sprite = heroSprite.nextFrame(this.updateSprite); Image monSprite = monsterSprite.nextFrame(this.updateMonsterSprite); sprite = FileUtils.colorizeImage(sprite, Color.RED, this.hero.dmgTick); /* Gameplay */ gfx.drawImage(groundImg, 0, 0, groundImg.getWidth() * 0.3, groundImg.getHeight() * 0.3); for(Entity e : this.entities) { switch(e.getEntityType()) { case EXTRA_HEART: gfx.drawImage(this.heartExtra, e.getLocation().getX() - (this.heartFull.getWidth() / 2), e.getLocation().getY() - (this.heartFull.getHeight() / 2), this.heartExtra.getWidth() * 0.75, this.heartExtra.getHeight() * 0.75); break; case MONSTER: gfx.drawImage(monSprite, e.getLocation().getX() - (monSprite.getWidth() / 2), e.getLocation().getY() - (monSprite.getHeight() / 2), 30, 30); break; case MUMMY: break; case POWER_HEART: gfx.drawImage(this.heartFull, e.getLocation().getX() - (this.heartFull.getWidth() / 2), e.getLocation().getY() - (this.heartFull.getHeight() / 2), this.heartFull.getWidth() * 0.75, this.heartFull.getHeight() * 0.75); break; case SKELETON: break; default: break; } } gfx.drawImage(sprite, this.hero.getLocation().getX() - (heroImg.getWidth() / 2), this.hero.getLocation().getY() - (sprite.getHeight() / 2), 30, 30); /* HUD */ gfx.drawImage(this.monsterHead, 38, 68, 38, 38); gfx.setFill(Color.YELLOW); gfx.setFont(this.scoreFont); gfx.fillText(String.valueOf(score), 83, 95); gfx.setStroke(Color.YELLOW); gfx.strokeText(String.valueOf(score), 83, 95); for(int h = 0; h < this.hero.getHealth(); h++) { gfx.drawImage(this.heartFull, 42 + ((this.heartSize + 2) * h), 45, this.heartSize, this.heartSize); } for(int h = this.hero.getHealth(); h < this.hero.getMaxHealth(); h++) { gfx.drawImage(this.heartEmpty, 42 + ((this.heartSize + 2) * h), 45, this.heartSize, this.heartSize); } /* Final */ gfx.drawImage(trees, 0, 0, groundImg.getWidth() * 0.3, groundImg.getHeight() * 0.3); if(this.fade > 0) { gfx.setGlobalAlpha(this.fade); gfx.setFill(Color.BLACK); gfx.fillRect(0, 0, Main.window.getWidth(), Main.window.getHeight()); gfx.setGlobalAlpha(1); } } @Override public boolean updateOnCover() { return true; } private boolean handleMovement(KeyCode[] kl, Direction d) { for(KeyCode k : kl) { if(input.isKeyPressed(k)) { this.hero.saveLocation(); this.hero.move(d, this.playField); if(!this.playField.contains(this.hero.getLocation())) { hero.restoreLocation(); } return true; } } return false; } public void score() { this.score++; } @Override public void dispose() {} private void sortEntities() { Collections.sort(this.entities, new Comparator<Entity>() { public int compare(Entity e1, Entity e2) { return e1.getLocation().getY() > e2.getLocation().getY() ? 1 : -1; } }); } }
package org.scm4j.releaser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.io.FileUtils; import org.junit.Test; import org.scm4j.commons.progress.ProgressConsole; import org.scm4j.releaser.actions.IAction; import org.scm4j.releaser.branch.ReleaseBranchCurrent; import org.scm4j.releaser.branch.ReleaseBranchFactory; import org.scm4j.releaser.conf.Component; import org.scm4j.releaser.conf.MDepsFile; import org.scm4j.releaser.exceptions.EBuildOnNotForkedRelease; import org.scm4j.releaser.exceptions.ENoBuilder; import org.yaml.snakeyaml.Yaml; public class WorkflowBuildTest extends WorkflowTestBase { @Test public void testBuildAfterForkInParts() throws Exception { // fork unTillDb IAction action = execAndGetActionFork(compUnTillDb); assertActionDoesFork(action, compUnTillDb); checkUnTillDbForked(); // fork UBL action = execAndGetActionFork(compUBL); assertActionDoesFork(action, compUBL); assertActionDoesNothing(action, BuildStatus.BUILD, null, compUnTillDb); checkUBLForked(); // build UBL and unTillDb action = execAndGetActionBuild(compUBL); assertActionDoesBuild(action, compUnTillDb); assertActionDoesBuild(action, compUBL, BuildStatus.BUILD_MDEPS); checkUBLBuilt(); } @Test public void testBuildSingleComponentTwice() throws Exception { forkAndBuild(compUnTillDb); env.generateFeatureCommit(env.getUnTillDbVCS(), repoUnTillDb.getDevelopBranch(), "feature commit added"); forkAndBuild(compUnTillDb, 2); } @Test public void testBuildOnNotForkedReleaseException() { try { execAndGetActionBuild(compUnTill); fail(); } catch (EBuildOnNotForkedRelease e) { assertEquals(compUnTillDb, e.getComp()); } } @SuppressWarnings("unchecked") @Test public void testNoBuilderException() throws Exception { // simulate no builder Yaml yaml = new Yaml(); Map<String, ?> content = (Map<String, String>) yaml.load(FileUtils.readFileToString(env.getCcFile(), StandardCharsets.UTF_8)); ((Map<String, ?>) content.get("eu.untill:(.*)")).remove("releaseCommand"); FileUtils.writeStringToFile(env.getCcFile(), yaml.dumpAsMap(content), StandardCharsets.UTF_8); repoFactory = env.getRepoFactory(); try { forkAndBuild(compUnTillDb); fail(); } catch (ENoBuilder e) { } } @Test public void testActualizePatches() { fork(compUnTill); build(compUnTillDb); // add feature to existing unTillDb release ReleaseBranchCurrent crb = ReleaseBranchFactory.getCRB(repoUnTillDb); env.generateFeatureCommit(env.getUnTillDbVCS(), crb.getName(), "patch feature added"); // build unTillDb patch Component compUnTillDbPatch = new Component(UNTILLDB + ":" + env.getUnTillDbVer().toRelease()); execAndGetActionBuild(compUnTillDbPatch); // UBL should actualize its mdeps IAction action = execAndGetActionBuild(compUnTill); assertActionDoesBuild(action, compUnTill, BuildStatus.BUILD_MDEPS); assertActionDoesBuild(action, compUBL, BuildStatus.ACTUALIZE_PATCHES); assertActionDoesNothing(action, compUnTillDb); // check unTill actualized unTillDb version checkUnTillMDepsVersions(1); // check UBL actualized unTillDb version checkUBLMDepsVersions(1); } @Test public void testNoActualizePatchesIfHasNewReleases() { forkAndBuild(compUnTill); // release next 2.60 unTillDb minor env.generateFeatureCommit(env.getUnTillDbVCS(), repoUnTillDb.getDevelopBranch(), "feature added"); forkAndBuild(compUnTillDb, 2); IAction action = execAndGetActionBuild(compUnTill.clone(getCrbVersion(compUnTill))); assertActionDoesNothing(action, compUnTill); assertActionDoesNothing(action, compUBL); assertActionDoesNothing(action, compUnTillDb); } @Test public void testLockMDeps() { fork(compUBL); // simulate mdeps not locked ReleaseBranchCurrent crb = ReleaseBranchFactory.getCRB(repoUBL); MDepsFile mdf = new MDepsFile(env.getUblVCS().getFileContent(crb.getName(), Constants.MDEPS_FILE_NAME, null)); mdf.replaceMDep(mdf.getMDeps().get(0).clone("")); env.getUblVCS().setFileContent(crb.getName(), Constants.MDEPS_FILE_NAME, mdf.toFileContent(), "mdeps not locked"); // UBL should lock its mdeps IAction action = execAndGetActionBuild(compUBL); assertActionDoesBuild(action, compUBL, BuildStatus.LOCK); // check UBL mdeps locked checkUBLMDepsVersions(1); } @Test public void testBuiltRootIfNestedBuiltAndModified() { fork(compUnTill); build(compUnTillDb); // add feature to trunk and release branch ReleaseBranchCurrent crb = ReleaseBranchFactory.getCRB(repoUnTillDb); env.generateFeatureCommit(env.getUnTillDbVCS(), crb.getName(), "patch feature added"); env.generateFeatureCommit(env.getUnTillDbVCS(), null, "patch feature added"); // unTill should be built using locked unTillDb version IAction action = execAndGetActionBuild(compUnTill); assertActionDoesBuild(action, compUnTill, BuildStatus.BUILD_MDEPS); assertActionDoesBuild(action, compUBL, BuildStatus.BUILD); assertActionDoesNothing(action, compUnTillDb); checkCompBuilt(1, compUnTill); checkCompBuilt(1, compUBL); crb = ReleaseBranchFactory.getCRB(repoUnTillDb); assertEquals(env.getUnTillDbVer().toReleaseZeroPatch().toNextPatch(), crb.getVersion()); } @Test public void testMinorUpgradeIsOKOnMinor() { fork(compUnTill); build(compUnTillDb); // add feature to trunk and release branch env.generateFeatureCommit(env.getUnTillDbVCS(), null, "feature added"); // release next unTillDb version forkAndBuild(compUnTillDb, 2); //execAndGetActionBuildDelayedTag(compUnTillDb); // expect no EMinorUpgradeDowngrade exception because areMDepsPatchesActualForMinor should be used for minor status(compUBL); } @Test public void testShouldRemoveFromCacheOnErrorsOnMinor() { ExtendedStatusBuilder esb = spy(new ExtendedStatusBuilder(repoFactory)); CachedStatuses cache = spy(new CachedStatuses()); RuntimeException testException = new RuntimeException(""); ProgressConsole pc = new ProgressConsole(); ConcurrentHashMap<Component, ExtendedStatus> subComponentsLocal = new ConcurrentHashMap<Component, ExtendedStatus>(); Component versionedUBL = compUBL.clone("1.0"); doThrow(testException).when(esb).recursiveGetAndCacheStatus(cache, pc, subComponentsLocal, compUnTillDb, false); try { esb.getAndCacheStatus(versionedUBL, cache, pc, false); fail(); } catch (RuntimeException e) { verify(cache, atLeast(1)).remove(eq(repoUBL.getUrl())); } } @Test public void testShouldRemoveFromCacheOnErrorsOnPatch() { forkAndBuild(compUBL); ExtendedStatusBuilder esb = spy(new ExtendedStatusBuilder(repoFactory)); CachedStatuses cache = spy(new CachedStatuses()); RuntimeException testException = new RuntimeException(""); ProgressConsole pc = new ProgressConsole(); ConcurrentHashMap<Component, ExtendedStatus> subComponentsLocal = new ConcurrentHashMap<Component, ExtendedStatus>(); Component versionedUBL = compUBL.clone(getCrbVersion(compUBL)); Component versionedUnTillDb = new Component("eu.untill:unTillDb:2.59.0#comment 3"); doThrow(testException).when(esb).recursiveGetAndCacheStatus(cache, pc, subComponentsLocal, versionedUnTillDb, true); try { esb.getAndCacheStatus(versionedUBL, cache, pc, true); fail(); } catch (RuntimeException e) { verify(cache, atLeast(1)).remove(eq(repoUBL.getUrl())); } } @Test public void testSouldRemoveFromCacheOnErrorsIsNeedToFork() { ExtendedStatusBuilder esb = spy(new ExtendedStatusBuilder(repoFactory)); CachedStatuses cache = spy(new CachedStatuses()); RuntimeException testException = new RuntimeException(""); ProgressConsole pc = new ProgressConsole(); ConcurrentHashMap<Component, ExtendedStatus> subComponentsLocal = new ConcurrentHashMap<Component, ExtendedStatus>(); doThrow(testException).when(esb).recursiveGetAndCacheStatus(cache, pc, subComponentsLocal, compUnTillDb, false); try { esb.getAndCacheStatus(compUBL, cache, pc, false); fail(); } catch (RuntimeException e) { verify(cache, atLeast(1)).remove(eq(repoUBL.getUrl())); } } }
package org.caleydo.core.data.selection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.caleydo.core.data.selection.delta.DeltaConverter; import org.caleydo.core.data.selection.delta.SelectionDelta; import org.caleydo.core.event.EventListenerManager.DeepScan; import org.caleydo.core.event.EventListenerManager.ListenTo; import org.caleydo.core.event.EventPublisher; import org.caleydo.core.event.data.SelectionCommandEvent; import org.caleydo.core.event.data.SelectionUpdateEvent; import org.caleydo.core.id.IDCategory; import org.caleydo.core.id.IDMappingManagerRegistry; import org.caleydo.core.id.IDType; import com.google.common.collect.Iterators; /** * a mixin container class for handling selection in a single class * * important: annotate the field of this element with the {@link DeepScan} annotation to ensure that the listener will * be created * * @author Samuel Gratzl * */ public class MultiSelectionManagerMixin implements Iterable<SelectionManager> { protected final List<SelectionManager> selectionManagers = new ArrayList<>(2); protected final ISelectionMixinCallback callback; public MultiSelectionManagerMixin(ISelectionMixinCallback callback) { this.callback = callback; } public final void add(SelectionManager manager) { this.selectionManagers.add(manager); } public final SelectionManager get(int index) { return selectionManagers.get(index); } public final void clear() { this.selectionManagers.clear(); } @ListenTo private void onSelectionUpdate(SelectionUpdateEvent event) { if (event.getSender() == this) return; SelectionDelta selectionDelta = event.getSelectionDelta(); final IDType idType = selectionDelta.getIDType(); for (SelectionManager selectionManager : selectionManagers) { final IDType sidType = selectionManager.getIDType(); if (idType.resolvesTo(sidType) && event.getSender() != selectionManager) { // Check for type that can be handled selectionDelta = convert(selectionDelta, sidType); selectionManager.setDelta(selectionDelta); callback.onSelectionUpdate(selectionManager); } } } private SelectionDelta convert(SelectionDelta selectionDelta, IDType sidType) { if (selectionDelta.getIDType().equals(sidType)) return selectionDelta; return DeltaConverter.convertDelta(IDMappingManagerRegistry.get().getIDMappingManager(sidType), sidType, selectionDelta); } @ListenTo private void onSelectionCommand(SelectionCommandEvent event) { if (event.getSender() == this) return; IDCategory idCategory = event.getIdCategory(); SelectionCommand cmd = event.getSelectionCommand(); for (SelectionManager selectionManager : selectionManagers) { final IDType sidType = selectionManager.getIDType(); // match but not send by me if ((idCategory == null || idCategory.isOfCategory(sidType)) && (event.getSender() != selectionManager)) { selectionManager.executeSelectionCommand(cmd); callback.onSelectionUpdate(selectionManager); } } } public final void fireSelectionDelta(IDType type) { for (SelectionManager m : selectionManagers) { if (m.getIDType().equals(type)) fireSelectionDelta(m); } } public final SelectionManager getSelectionManager(IDType type) { for (SelectionManager m : selectionManagers) { if (m.getIDType().equals(type)) return m; } return null; } @Override public final Iterator<SelectionManager> iterator() { return Iterators.unmodifiableIterator(selectionManagers.iterator()); } public final void fireSelectionDelta(SelectionManager manager) { SelectionDelta selectionDelta = manager.getDelta(); SelectionUpdateEvent event = createEvent(manager); event.setSelectionDelta(selectionDelta); EventPublisher.trigger(event); } protected SelectionUpdateEvent createEvent(Object sender) { SelectionUpdateEvent event = new SelectionUpdateEvent(); event.setSender(sender); return event; } public interface ISelectionMixinCallback { void onSelectionUpdate(SelectionManager manager); } }
package net.gigimoi.zombietc.tile; import net.gigimoi.zombietc.ZombieTC; import net.gigimoi.zombietc.util.IListenerZTC; import net.minecraft.nbt.NBTTagCompound; public class TileNodeDoor extends TileNode implements IListenerZTC { public int direction; public int animationTime; public int animationDirection = -1; @Override public void readFromNBT(NBTTagCompound tag) { direction = tag.getInteger("Direction"); animationTime = tag.getInteger("Animation Time"); animationDirection = tag.getInteger("Animation Direction"); super.readFromNBT(tag); } @Override public void writeToNBT(NBTTagCompound tag) { tag.setInteger("Direction", direction); tag.setInteger("Animation Time", animationTime); tag.setInteger("Animation Direction", animationDirection); super.writeToNBT(tag); } boolean isEventTriggering; @Override public void updateEntity() { super.updateEntity(); if (ZombieTC.editorModeManager.enabled) { animationTime = 0; animationDirection = -1; } if (isEventTriggering) { isEventTriggering = false; if(animationDirection == 0) { animationDirection = -1; } animationDirection = -animationDirection; } animationTime = Math.min(100, Math.max(0, animationTime + animationDirection * 5)); } @Override public void onEvent(String event) { if(deactivatedUntilEvent && eventWaitFor.equals(event)) { isEventTriggering = true; deactivated = false; } } }
package org.caleydo.util.r.filter; import org.caleydo.core.data.collection.Histogram; import org.caleydo.core.data.collection.ISet; import org.caleydo.core.data.collection.set.statistics.FoldChangeSettings; import org.caleydo.core.data.collection.set.statistics.FoldChangeSettings.FoldChangeEvaluator; import org.caleydo.core.data.filter.ContentFilter; import org.caleydo.core.data.filter.ContentMetaFilter; import org.caleydo.core.data.filter.event.RemoveContentFilterEvent; import org.caleydo.core.data.filter.representation.AFilterRepresentation; import org.caleydo.core.data.virtualarray.ContentVirtualArray; import org.caleydo.core.data.virtualarray.delta.ContentVADelta; import org.caleydo.core.data.virtualarray.delta.VADeltaItem; import org.caleydo.core.manager.GeneralManager; import org.caleydo.core.manager.datadomain.DataDomainManager; import org.caleydo.view.histogram.GLHistogram; import org.caleydo.view.histogram.RcpBasicGLHistogramView; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Slider; import org.eclipse.swt.widgets.Text; public class FilterRepresentationFoldChange extends AFilterRepresentation<ContentVADelta, ContentFilter> { private final static String TITLE = "Fold Change Filter"; private ISet set1; private ISet set2; private float foldChange = 2; Button[] evaluatorCheckBox; private Histogram histogram; public void create() { super.create(); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { ((Shell) parentComposite).setText(TITLE); Composite infoComposite = new Composite(parentComposite, SWT.NULL); GridData gridData = new GridData(); infoComposite.setLayoutData(gridData); infoComposite.setLayout(new GridLayout(4, false)); final Label foldChangeLabel = new Label(infoComposite, SWT.NULL); foldChangeLabel.setText("Fold change:"); final Text foldChangeInputField = new Text(infoComposite, SWT.SINGLE); final Slider foldChangeSlider = new Slider(infoComposite, SWT.HORIZONTAL); // gridData.grabExcessHorizontalSpace = true; // gridData.horizontalAlignment = GridData.FILL; // pValueSlider.setLayoutData(gridData); foldChangeInputField.setEditable(true); foldChangeInputField.setText(Float.toString(foldChange)); foldChangeInputField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { String enteredValue = foldChangeInputField.getText(); if (enteredValue != null && !enteredValue.isEmpty()) { foldChange = new Float(enteredValue); foldChangeSlider.setSelection((int) (foldChange * 10)); isDirty = true; } } }); final Button applyFilterButton = new Button(infoComposite, SWT.PUSH); applyFilterButton.setText("Apply"); applyFilterButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { applyFilter(); } }); evaluatorCheckBox = new Button[3]; evaluatorCheckBox[0] = new Button(parentComposite, SWT.CHECK); evaluatorCheckBox[0].setText("Less (down regulated)"); evaluatorCheckBox[1] = new Button(parentComposite, SWT.CHECK); evaluatorCheckBox[1].setText("Greater (up regulated)"); try { FoldChangeSettings settings = set1.getStatisticsResult() .getFoldChangeResult(set2) .getSecond(); switch( settings.getEvaluator() ) { case GREATER: evaluatorCheckBox[1].setSelection(true); break; case BOTH: evaluatorCheckBox[1].setSelection(true); case LESS: evaluatorCheckBox[0].setSelection(true); } } catch (Exception e) // fails on filter creation { evaluatorCheckBox[0].setSelection(true); } evaluatorCheckBox[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { isDirty = true; } }); evaluatorCheckBox[1].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { isDirty = true; } }); foldChangeSlider.setMinimum(0); foldChangeSlider.setMaximum(100); foldChangeSlider.setIncrement(1); foldChangeSlider.setPageIncrement(10); foldChangeSlider.setSelection((int) (foldChange * 10)); foldChangeSlider.addMouseListener(new MouseAdapter() { @Override public void mouseUp(MouseEvent e) { foldChange = foldChangeSlider.getSelection() / 10f; foldChangeInputField.setText("" + foldChange); isDirty = true; // int reducedNumberOfElements = // set1.getStatisticsResult() // .getElementNumberOfFoldChangeReduction(set2); // label.setText("The fold change reduced results in a dataset of the size " // + reducedNumberOfElements); // parentComposite.layout(); } }); ; set1.getStatisticsResult().getFoldChangeResult(set2).getFirst(); Composite histoComposite = new Composite(parentComposite, SWT.NULL); histoComposite.setLayout(new FillLayout(SWT.VERTICAL)); gridData = new GridData(); gridData.heightHint = 300; gridData.widthHint = 500; // gridData.verticalAlignment = GridData.FILL; // gridData2.grabExcessVerticalSpace = true; histoComposite.setLayoutData(gridData); RcpBasicGLHistogramView histogramView = new RcpBasicGLHistogramView(); histogramView.setDataDomain(DataDomainManager.get().getDataDomain( "org.caleydo.datadomain.genetic")); histogramView.createDefaultSerializedView(); histogramView.createPartControl(histoComposite); ((GLHistogram) (histogramView.getGLView())).setHistogram(histogram); // Usually the canvas is registered to the GL animator in the // PartListener. // Because the GL histogram is no usual RCP view we have to do // it on our // own GeneralManager.get().getViewGLCanvasManager() .registerGLCanvasToAnimator(histogramView.getGLCanvas()); } }); addOKCancel(); } public void setHistogram(Histogram histogram) { this.histogram = histogram; } public void setSet1(ISet set1) { this.set1 = set1; } public void setSet2(ISet set2) { this.set2 = set2; } @Override protected void createVADelta() { if (filter instanceof ContentMetaFilter) { for (ContentFilter subFilter : ((ContentMetaFilter) filter).getFilterList()) { createVADelta(subFilter); } } else createVADelta(filter); } private void createVADelta(ContentFilter subFilter) { ContentVADelta contentVADelta = new ContentVADelta(ISet.CONTENT, subFilter .getDataDomain().getContentIDType()); ContentVirtualArray contentVA = subFilter.getDataDomain() .getContentFilterManager().getBaseVA(); double[] resultVector = set1.getStatisticsResult().getFoldChangeResult(set2) .getFirst(); FoldChangeSettings settings = set1.getStatisticsResult() .getFoldChangeResult(set2).getSecond(); double foldChangeRatio = settings.getRatio(); FoldChangeEvaluator foldChangeEvaluator = settings.getEvaluator(); for (Integer contentIndex = 0; contentIndex < contentVA.size(); contentIndex++) { switch (foldChangeEvaluator) { case LESS: if (resultVector[contentIndex] * -1 > foldChangeRatio) continue; break; case GREATER: if (resultVector[contentIndex] > foldChangeRatio) continue; break; case BOTH: if (Math.abs(resultVector[contentIndex]) > foldChangeRatio) continue; break; } contentVADelta.add(VADeltaItem.removeElement(contentVA.get(contentIndex))); } subFilter.setDelta(contentVADelta); } @Override protected void triggerRemoveFilterEvent() { RemoveContentFilterEvent filterEvent = new RemoveContentFilterEvent(); filterEvent.setDataDomainType(filter.getDataDomain().getDataDomainType()); filterEvent.setFilter(filter); GeneralManager.get().getEventPublisher().triggerEvent(filterEvent); } @Override protected void applyFilter() { if (isDirty) { FoldChangeEvaluator foldChangeEvaluator = null; if (evaluatorCheckBox[0].getSelection() == true && evaluatorCheckBox[1].getSelection() == true) { foldChangeEvaluator = FoldChangeEvaluator.BOTH; } else if (evaluatorCheckBox[0].getSelection() == true) { foldChangeEvaluator = FoldChangeEvaluator.LESS; } else if (evaluatorCheckBox[1].getSelection() == true) { foldChangeEvaluator = FoldChangeEvaluator.GREATER; } FoldChangeSettings foldChangeSettings = new FoldChangeSettings(foldChange, foldChangeEvaluator); set1.getStatisticsResult().setFoldChangeSettings(set2, foldChangeSettings); set2.getStatisticsResult().setFoldChangeSettings(set1, foldChangeSettings); createVADelta(); filter.updateFilterManager(); } isDirty = false; } }
package net.imagej.legacy; import java.awt.GraphicsEnvironment; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import net.imagej.DatasetService; import net.imagej.display.DatasetView; import net.imagej.display.ImageDisplay; import net.imagej.display.ImageDisplayService; import net.imagej.display.OverlayService; import net.imagej.legacy.plugin.LegacyCommand; import net.imagej.legacy.plugin.LegacyPluginFinder; import net.imagej.legacy.ui.LegacyUI; import net.imagej.options.OptionsChannels; import net.imagej.patcher.LegacyEnvironment; import net.imagej.patcher.LegacyInjector; import net.imagej.threshold.ThresholdService; import net.imagej.ui.viewer.image.ImageDisplayViewer; import org.scijava.Priority; import org.scijava.app.StatusService; import org.scijava.command.Command; import org.scijava.command.CommandInfo; import org.scijava.command.CommandService; import org.scijava.display.DisplayService; import org.scijava.display.event.DisplayActivatedEvent; import org.scijava.display.event.input.KyPressedEvent; import org.scijava.display.event.input.KyReleasedEvent; import org.scijava.event.EventHandler; import org.scijava.event.EventService; import org.scijava.input.KeyCode; import org.scijava.log.LogService; import org.scijava.menu.MenuService; import org.scijava.module.ModuleService; import org.scijava.options.OptionsService; import org.scijava.options.event.OptionsEvent; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.plugin.PluginInfo; import org.scijava.plugin.PluginService; import org.scijava.service.AbstractService; import org.scijava.service.Service; import org.scijava.service.event.ServicesLoadedEvent; import org.scijava.ui.ApplicationFrame; import org.scijava.ui.UIService; import org.scijava.ui.UserInterface; import org.scijava.ui.viewer.DisplayWindow; import org.scijava.util.ColorRGB; /** * Default service for working with legacy ImageJ 1.x. * <p> * The legacy service overrides the behavior of various legacy ImageJ methods, * inserting seams so that (e.g.) the modern UI is aware of legacy ImageJ events * as they occur. * </p> * <p> * It also maintains an image map between legacy ImageJ {@link ij.ImagePlus} * objects and modern ImageJ {@link ImageDisplay}s. * </p> * <p> * In this fashion, when a legacy command is executed on a {@link ImageDisplay}, * the service transparently translates it into an {@link ij.ImagePlus}, and vice * versa, enabling backward compatibility with legacy commands. * </p> * * @author Barry DeZonia * @author Curtis Rueden * @author Johannes Schindelin * @author Mark Hiner */ @Plugin(type = Service.class, priority = Priority.NORMAL_PRIORITY + 1) public final class DefaultLegacyService extends AbstractService implements LegacyService { static { LegacyInjector.preinit(); } @Parameter private OverlayService overlayService; @Parameter private LogService log; @Parameter private EventService eventService; @Parameter private PluginService pluginService; @Parameter private CommandService commandService; @Parameter private OptionsService optionsService; @Parameter private ImageDisplayService imageDisplayService; @Parameter private DisplayService displayService; @Parameter private ThresholdService thresholdService; @Parameter private DatasetService datasetService; @Parameter private MenuService menuService; @Parameter private ModuleService moduleService; @Parameter private StatusService statusService; private UIService uiService; private static DefaultLegacyService instance; private static Throwable instantiationStackTrace; /** Mapping between modern and legacy image data structures. */ private LegacyImageMap imageMap; /** Method of synchronizing modern & legacy options. */ private OptionsSynchronizer optionsSynchronizer; /** Keep references to ImageJ 1.x separate */ private IJ1Helper ij1Helper; public IJ1Helper getIJ1Helper() { return ij1Helper; } private ThreadLocal<Boolean> isProcessingEvents = new ThreadLocal<Boolean>(); private Set<String> legacyCompatibleCommands = new HashSet<String>(); // -- LegacyService methods -- @Override public LogService log() { return log; } @Override public StatusService status() { return statusService; } @Override public synchronized LegacyImageMap getImageMap() { if (imageMap == null) imageMap = new LegacyImageMap(this); return imageMap; } @Override public OptionsSynchronizer getOptionsSynchronizer() { return optionsSynchronizer; } @Override public void runLegacyCommand(final String ij1ClassName, final String argument) { final String arg = argument == null ? "" : argument; final Map<String, Object> inputMap = new HashMap<String, Object>(); inputMap.put("className", ij1ClassName); inputMap.put("arg", arg); commandService.run(LegacyCommand.class, true, inputMap); } public Object runLegacyCompatibleCommand(final String commandClass) { if (!legacyCompatibleCommands.contains(commandClass)) { return null; } return commandService.run(commandClass, true, new Object[0]); } @Override public void syncActiveImage() { final ImageDisplay activeDisplay = imageDisplayService.getActiveImageDisplay(); ij1Helper.syncActiveImage(activeDisplay); } @Override public boolean isInitialized() { return instance != null; } @Override public void syncColors() { final DatasetView view = imageDisplayService.getActiveDatasetView(); if (view == null) return; final OptionsChannels channels = getChannels(); final ColorRGB fgColor = view.getColor(channels.getFgValues()); final ColorRGB bgColor = view.getColor(channels.getBgValues()); optionsSynchronizer.colorOptions(fgColor, bgColor); } @Override public boolean isLegacyMode() { return ij1Helper != null && ij1Helper.isVisible(); } @Override public void toggleLegacyMode(final boolean wantIJ1) { toggleLegacyMode(wantIJ1, false); } public synchronized void toggleLegacyMode(final boolean wantIJ1, final boolean initializing) { // TODO: hide/show Brightness/Contrast, Color Picker, Command Launcher, etc // TODO: prevent IJ1 from quitting without IJ2 quitting, too if (!initializing) { if (uiService() != null) { // hide/show the IJ2 main window final UserInterface ui = uiService.getDefaultUI(); if (ui != null && ui instanceof LegacyUI) { UserInterface modern = null; for (final UserInterface ui2 : uiService.getAvailableUIs()) { if (ui2 == ui) continue; modern = ui2; break; } if (modern == null) { log.error("No modern UI available"); return; } final ApplicationFrame frame = ui.getApplicationFrame(); ApplicationFrame modernFrame = modern.getApplicationFrame(); if (!wantIJ1 && modernFrame == null) { modern.show(); modernFrame = modern.getApplicationFrame(); } if (frame == null || modernFrame == null) { log.error("Application frame missing: " + frame + " / " + modernFrame); return; } frame.setVisible(wantIJ1); modernFrame.setVisible(!wantIJ1); } else { final ApplicationFrame appFrame = ui == null ? null : ui.getApplicationFrame(); if (appFrame == null) { if (ui != null && !wantIJ1) uiService.showUI(); } else { appFrame.setVisible(!wantIJ1); } } } // TODO: move this into the LegacyImageMap's toggleLegacyMode, passing // the uiService // hide/show the IJ2 datasets corresponding to legacy ImagePlus instances for (final ImageDisplay display : getImageMap().getImageDisplays()) { final ImageDisplayViewer viewer = (ImageDisplayViewer) uiService.getDisplayViewer(display); if (viewer == null) continue; final DisplayWindow window = viewer.getWindow(); if (window != null) window.showDisplay(!wantIJ1); } } // hide/show IJ1 main window ij1Helper.setVisible(wantIJ1); if (wantIJ1 && !initializing) { optionsSynchronizer.updateLegacyImageJSettingsFromModernImageJ(); } getImageMap().toggleLegacyMode(wantIJ1); } @Override public String getLegacyVersion() { return ij1Helper.getVersion(); } // -- Service methods -- @Override public void initialize() { checkInstance(); optionsSynchronizer = new OptionsSynchronizer(optionsService); try { final ClassLoader loader = getClass().getClassLoader(); final boolean ij1Initialized = LegacyEnvironment.isImageJ1Initialized(loader); if (!ij1Initialized) { getLegacyEnvironment(loader).newImageJ1(true); } ij1Helper = new IJ1Helper(this); } catch (final Throwable t) { throw new RuntimeException("Failed to instantiate IJ1.", t); } synchronized (DefaultLegacyService.class) { checkInstance(); instance = this; instantiationStackTrace = new Throwable("Initialized here:"); LegacyInjector.installHooks(getClass().getClassLoader(), new DefaultLegacyHooks(this, ij1Helper)); } ij1Helper.initialize(); SwitchToModernMode.registerMenuItem(); addNonLegacyCommandsToMenu(); // discover legacy plugins final boolean enableBlacklist = true; addLegacyCommands(enableBlacklist); } // -- Package protected events processing methods -- /** * NB: This method is not intended for public consumption. It is really * intended to be "jar protected". It is used to toggle a {@link ThreadLocal} * flag as to whether or not legacy UI components are in the process of * handling {@code StatusEvents}. * <p> * USE AT YOUR OWN RISK! * </p> * * @return the old processing value */ public boolean setProcessingEvents(boolean processing) { boolean result = isProcessingEvents(); if (result != processing) { isProcessingEvents.set(processing); } return result; } /** * {@link ThreadLocal} check to see if components are in the middle of * processing events. * * @return True iff this thread is already processing events through the * {@code DefaultLegacyService}. */ public boolean isProcessingEvents() { Boolean result = isProcessingEvents.get(); return result == Boolean.TRUE; } // -- Disposable methods -- @Override public void dispose() { ij1Helper.dispose(); LegacyInjector.installHooks(getClass().getClassLoader(), null); synchronized(DefaultLegacyService.class) { instance = null; instantiationStackTrace = null; } } // -- Event handlers -- protected void onEvent(final ServicesLoadedEvent e) { uiService = getContext().getService(UIService.class); } /** * Keeps the active legacy {@link ij.ImagePlus} in sync with the active modern * {@link ImageDisplay}. */ @EventHandler protected void onEvent(final DisplayActivatedEvent event) { syncActiveImage(); } @EventHandler protected void onEvent(final OptionsEvent event) { optionsSynchronizer.updateModernImageJSettingsFromLegacyImageJ(); } @EventHandler protected void onEvent(final KyPressedEvent event) { final KeyCode code = event.getCode(); if (code == KeyCode.SPACE) ij1Helper.setKeyDown(KeyCode.SPACE.getCode()); if (code == KeyCode.ALT) ij1Helper.setKeyDown(KeyCode.ALT.getCode()); if (code == KeyCode.SHIFT) ij1Helper.setKeyDown(KeyCode.SHIFT.getCode()); if (code == KeyCode.CONTROL) ij1Helper.setKeyDown(KeyCode.CONTROL.getCode()); if (ij1Helper.isMacintosh() && code == KeyCode.META) { ij1Helper.setKeyDown(KeyCode.CONTROL.getCode()); } } @EventHandler protected void onEvent(final KyReleasedEvent event) { final KeyCode code = event.getCode(); if (code == KeyCode.SPACE) ij1Helper.setKeyUp(KeyCode.SPACE.getCode()); if (code == KeyCode.ALT) ij1Helper.setKeyUp(KeyCode.ALT.getCode()); if (code == KeyCode.SHIFT) ij1Helper.setKeyUp(KeyCode.SHIFT.getCode()); if (code == KeyCode.CONTROL) ij1Helper.setKeyUp(KeyCode.CONTROL.getCode()); if (ij1Helper.isMacintosh() && code == KeyCode.META) { ij1Helper.setKeyUp(KeyCode.CONTROL.getCode()); } } // -- pre-initialization /** * Makes sure that the ImageJ 1.x classes are patched. * <p> * We absolutely require that the LegacyInjector did its job before we use the * ImageJ 1.x classes. * </p> * <p> * Just loading the {@link DefaultLegacyService} class is not enough; it will * not necessarily get initialized. So we provide this method just to force * class initialization (and thereby the LegacyInjector to patch ImageJ 1.x). * </p> * * @deprecated use {@link LegacyInjector#preinit()} instead */ public static void preinit() { try { getLegacyEnvironment(Thread.currentThread().getContextClassLoader()); } catch (Throwable t) { t.printStackTrace(); } } private static LegacyEnvironment getLegacyEnvironment(final ClassLoader loader) throws ClassNotFoundException { final boolean headless = GraphicsEnvironment.isHeadless(); final LegacyEnvironment ij1 = new LegacyEnvironment(loader, headless); ij1.disableInitializer(); ij1.noPluginClassLoader(); ij1.applyPatches(); return ij1; } // -- helpers -- /** * Returns the legacy service associated with the ImageJ 1.x instance in the * current class loader. This method is intended to be used by the * {@link CodeHacker}; it is invoked by the javassisted methods. * * @return the legacy service */ public static DefaultLegacyService getInstance() { return instance; } /** * @throws UnsupportedOperationException if the singleton * {@code DefaultLegacyService} already exists. */ private void checkInstance() { if (instance != null) { throw new UnsupportedOperationException( "Cannot instantiate more than one DefaultLegacyService", instantiationStackTrace); } } private OptionsChannels getChannels() { return optionsService.getOptions(OptionsChannels.class); } @SuppressWarnings("unused") private void updateMenus(final boolean enableBlacklist) { pluginService.reloadPlugins(); addLegacyCommands(enableBlacklist); } private void addLegacyCommands(final boolean enableBlacklist) { final LegacyPluginFinder finder = new LegacyPluginFinder(log, menuService.getMenu(), enableBlacklist); final ArrayList<PluginInfo<?>> plugins = new ArrayList<PluginInfo<?>>(); finder.findPlugins(plugins); pluginService.addPlugins(plugins); } // -- Menu population -- /** * Adds all {@link LegacyCompatibleCommand}s to the ImageJ1 menus. The * nested menu structure of each {@code LegacyCompatibleCommand} is * preserved. */ private void addNonLegacyCommandsToMenu() { List<CommandInfo> commands = commandService.getCommandsOfType(Command.class); legacyCompatibleCommands = new HashSet<String>(); for (final Iterator<CommandInfo> iter = commands.iterator(); iter.hasNext(); ) { final CommandInfo info = iter.next(); if (info.getMenuPath().size() == 0 || info.is("no-legacy")) { iter.remove(); } else { legacyCompatibleCommands.add(info.getDelegateClassName()); } } ij1Helper.addMenuItems(commands); } public synchronized UIService uiService() { if (uiService == null) uiService = getContext().getService(UIService.class); return uiService; } }
package org.eclipse.scanning.server.servlet; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.eclipse.scanning.api.IScannable; import org.eclipse.scanning.api.event.EventException; import org.eclipse.scanning.api.event.core.IConsumerProcess; import org.eclipse.scanning.api.event.core.IPublisher; import org.eclipse.scanning.api.event.scan.ScanBean; import org.eclipse.scanning.api.event.scan.ScanRequest; import org.eclipse.scanning.api.event.status.Status; import org.eclipse.scanning.api.points.GeneratorException; import org.eclipse.scanning.api.points.IPointGenerator; import org.eclipse.scanning.api.points.IPointGeneratorService; import org.eclipse.scanning.api.points.IPosition; import org.eclipse.scanning.api.points.models.IScanPathModel; import org.eclipse.scanning.api.scan.AbstractRunnableDevice; import org.eclipse.scanning.api.scan.IDeviceService; import org.eclipse.scanning.api.scan.IFilePathService; import org.eclipse.scanning.api.scan.IRunnableDevice; import org.eclipse.scanning.api.scan.IWritableDetector; import org.eclipse.scanning.api.scan.ScanningException; import org.eclipse.scanning.api.scan.event.IPositioner; import org.eclipse.scanning.api.scan.models.ScanModel; /** * Object for running a scan. * * @author Matthew Gerring * */ class ScanProcess implements IConsumerProcess<ScanBean> { private IPositioner positioner; private ScanBean bean; private IPublisher<ScanBean> response; private IRunnableDevice<ScanModel> device; private boolean blocking; public ScanProcess(ScanBean scanBean, IPublisher<ScanBean> response, boolean blocking) throws EventException { this.bean = scanBean; this.response = response; this.blocking = blocking; if (bean.getScanRequest().getStart()!=null || bean.getScanRequest().getEnd()!=null) { try { this.positioner = Services.getScanService().createPositioner(); } catch (ScanningException e) { throw new EventException(e); } } bean.setPreviousStatus(Status.SUBMITTED); bean.setStatus(Status.QUEUED); response.broadcast(bean); } @Override public ScanBean getBean() { return bean; } @Override public IPublisher<ScanBean> getPublisher() { return response; } @Override public void execute() throws EventException { try { if (bean.getScanRequest().getStart()!=null) { positioner.setPosition(bean.getScanRequest().getStart()); } this.device = createRunnableDevice(bean); if (blocking) { device.run(null); // Runs until done if (bean.getScanRequest().getEnd()!=null) { positioner.setPosition(bean.getScanRequest().getEnd()); } } else { ((AbstractRunnableDevice<ScanModel>)device).start(null); if (bean.getScanRequest().getEnd()!=null) throw new EventException("Cannot perform end position when scan is async."); } bean.setPreviousStatus(Status.RUNNING); bean.setStatus(Status.COMPLETE); bean.setPercentComplete(100); response.broadcast(bean); } catch (ScanningException | InterruptedException ne) { ne.printStackTrace(); bean.setPreviousStatus(Status.RUNNING); bean.setStatus(Status.FAILED); bean.setMessage(ne.getMessage()); response.broadcast(bean); throw new EventException(ne); } } private IRunnableDevice<ScanModel> createRunnableDevice(ScanBean bean) throws ScanningException, EventException { ScanRequest req = bean.getScanRequest(); if (req==null) throw new ScanningException("There must be a scan request to run a new scan!"); try { final ScanModel smodel = new ScanModel(); smodel.setPositionIterable(getPositionIterable(req)); smodel.setDetectors(getDetectors(req.getDetectors())); smodel.setMonitors(getMonitors(req.getMonitorNames())); smodel.setBean(bean); // the name of the scan should be set here. if (req.getFilePath()==null) { IFilePathService fservice = Services.getFilePathService(); if (fservice!=null) { try { smodel.setFilePath(fservice.nextPath()); } catch (Exception e) { throw new EventException(e); } } else { smodel.setFilePath(null); // It is allowable to run a scan without a nexus file. } } else { smodel.setFilePath(req.getFilePath()); } bean.setFilePath(smodel.getFilePath()); return Services.getScanService().createRunnableDevice(smodel, response); } catch (Exception e) { bean.setStatus(Status.FAILED); bean.setMessage(e.getMessage()); response.broadcast(bean); if (e instanceof EventException) throw (EventException)e; throw new EventException(e); } } @SuppressWarnings("unchecked") private Iterable<IPosition> getPositionIterable(ScanRequest<?> req) throws GeneratorException { IPointGeneratorService service = Services.getGeneratorService(); IPointGenerator<?,? extends IPosition> ret = null; for (IScanPathModel model : req.getModels()) { IPointGenerator<?,? extends IPosition> gen = service.createGenerator(model, req.getRegions(model.getUniqueKey())); if (ret != null) ret = service.createCompoundGenerator(ret, gen); if (ret==null) ret = gen; } return (Iterable<IPosition>)ret; } @Override public void terminate() throws EventException { if (bean.getStatus()==Status.COMPLETE) return; // Nothing to terminate. try { bean.setPreviousStatus(Status.RUNNING); bean.setStatus(Status.TERMINATED); response.broadcast(bean); device.abort(); } catch (ScanningException e) { bean.setPreviousStatus(Status.RUNNING); bean.setStatus(Status.FAILED); response.broadcast(bean); throw new EventException(e); } } @SuppressWarnings("unchecked") private List<IRunnableDevice<?>> getDetectors(Map<String, ?> detectors) throws EventException { if (detectors==null) return null; try { final List<IRunnableDevice<?>> ret = new ArrayList<>(3); final IDeviceService service = Services.getScanService(); for (String name : detectors.keySet()) { @SuppressWarnings("rawtypes") Object dmodel = detectors.get(name); IRunnableDevice<?> detector = (IWritableDetector<?>)service.createRunnableDevice(dmodel); ret.add(detector); } return ret; } catch (ScanningException ne) { throw new EventException(ne); } } private List<IScannable<?>> getMonitors(String... monitorNames) throws EventException { if (monitorNames==null) return null; try { final List<IScannable<?>> ret = new ArrayList<>(3); for (String name : monitorNames) ret.add(Services.getConnector().getScannable(name)); return ret; } catch (ScanningException ne) { throw new EventException(ne); } } }
package org.metaborg.spoofax.core; import org.metaborg.core.MetaborgModule; import org.metaborg.core.action.IActionService; import org.metaborg.core.analysis.IAnalysisService; import org.metaborg.core.analysis.IAnalyzer; import org.metaborg.core.build.IBuildOutputInternal; import org.metaborg.core.build.IBuilder; import org.metaborg.core.build.paths.ILanguagePathProvider; import org.metaborg.core.completion.ICompletionService; import org.metaborg.core.context.IContextFactory; import org.metaborg.core.language.ILanguageComponentFactory; import org.metaborg.core.language.ILanguageDiscoveryService; import org.metaborg.core.language.dialect.IDialectIdentifier; import org.metaborg.core.language.dialect.IDialectProcessor; import org.metaborg.core.language.dialect.IDialectService; import org.metaborg.core.menu.IMenuService; import org.metaborg.core.outline.IOutlineService; import org.metaborg.core.processing.IProcessor; import org.metaborg.core.processing.IProcessorRunner; import org.metaborg.core.processing.analyze.IAnalysisResultProcessor; import org.metaborg.core.processing.analyze.IAnalysisResultRequester; import org.metaborg.core.processing.analyze.IAnalysisResultUpdater; import org.metaborg.core.processing.parse.IParseResultProcessor; import org.metaborg.core.processing.parse.IParseResultRequester; import org.metaborg.core.processing.parse.IParseResultUpdater; import org.metaborg.core.style.ICategorizerService; import org.metaborg.core.style.IStylerService; import org.metaborg.core.syntax.IParser; import org.metaborg.core.syntax.ISyntaxService; import org.metaborg.core.tracing.IHoverService; import org.metaborg.core.tracing.IResolverService; import org.metaborg.core.tracing.ITracingService; import org.metaborg.core.transform.ITransformService; import org.metaborg.core.transform.ITransformer; import org.metaborg.core.unit.IInputUnitService; import org.metaborg.core.unit.IUnitService; import org.metaborg.meta.nabl2.spoofax.primitives.SG_analysis_has_errors; import org.metaborg.meta.nabl2.spoofax.primitives.SG_debug_constraints; import org.metaborg.meta.nabl2.spoofax.primitives.SG_debug_name_resolution; import org.metaborg.meta.nabl2.spoofax.primitives.SG_debug_scope_graph; import org.metaborg.meta.nabl2.spoofax.primitives.SG_debug_symbolic_constraints; import org.metaborg.meta.nabl2.spoofax.primitives.SG_debug_unifier; import org.metaborg.meta.nabl2.spoofax.primitives.SG_erase_ast_indices; import org.metaborg.meta.nabl2.spoofax.primitives.SG_focus_term; import org.metaborg.meta.nabl2.spoofax.primitives.SG_fresh; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_all_decls; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_all_refs; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_all_scopes; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_ast_index; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_ast_property; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_ast_resolution; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_custom_analysis; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_decl_property; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_decl_scope; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_direct_edges; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_direct_edges_inv; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_export_edges; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_export_edges_inv; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_import_edges; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_import_edges_inv; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_reachable_decls; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_ref_resolution; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_ref_scope; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_scope_decls; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_scope_refs; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_symbolic_facts; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_symbolic_goals; import org.metaborg.meta.nabl2.spoofax.primitives.SG_get_visible_decls; import org.metaborg.meta.nabl2.spoofax.primitives.SG_index_ast; import org.metaborg.meta.nabl2.spoofax.primitives.SG_is_debug_collection_enabled; import org.metaborg.meta.nabl2.spoofax.primitives.SG_is_debug_custom_enabled; import org.metaborg.meta.nabl2.spoofax.primitives.SG_is_debug_resolution_enabled; import org.metaborg.meta.nabl2.spoofax.primitives.SG_set_ast_index; import org.metaborg.runtime.task.primitives.TaskLibrary; import org.metaborg.spoofax.core.action.ActionService; import org.metaborg.spoofax.core.analysis.AnalysisCommon; import org.metaborg.spoofax.core.analysis.ISpoofaxAnalysisService; import org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzer; import org.metaborg.spoofax.core.analysis.SpoofaxAnalysisService; import org.metaborg.spoofax.core.analysis.constraint.ConstraintMultiFileAnalyzer; import org.metaborg.spoofax.core.analysis.constraint.ConstraintSingleFileAnalyzer; import org.metaborg.spoofax.core.analysis.legacy.StrategoAnalyzer; import org.metaborg.spoofax.core.analysis.taskengine.TaskEngineAnalyzer; import org.metaborg.spoofax.core.build.ISpoofaxBuilder; import org.metaborg.spoofax.core.build.SpoofaxBuildOutput; import org.metaborg.spoofax.core.build.SpoofaxBuilder; import org.metaborg.spoofax.core.build.paths.BuiltinLanguagePathProvider; import org.metaborg.spoofax.core.completion.JSGLRCompletionService; import org.metaborg.spoofax.core.context.IndexTaskContextFactory; import org.metaborg.spoofax.core.context.LegacyContextFactory; import org.metaborg.spoofax.core.context.scopegraph.MultiFileScopeGraphContextFactory; import org.metaborg.spoofax.core.context.scopegraph.SingleFileScopeGraphContextFactory; import org.metaborg.spoofax.core.language.LanguageComponentFactory; import org.metaborg.spoofax.core.language.LanguageDiscoveryService; import org.metaborg.spoofax.core.language.dialect.DialectIdentifier; import org.metaborg.spoofax.core.language.dialect.DialectProcessor; import org.metaborg.spoofax.core.language.dialect.DialectService; import org.metaborg.spoofax.core.menu.MenuService; import org.metaborg.spoofax.core.outline.ISpoofaxOutlineService; import org.metaborg.spoofax.core.outline.OutlineService; import org.metaborg.spoofax.core.processing.ISpoofaxProcessor; import org.metaborg.spoofax.core.processing.ISpoofaxProcessorRunner; import org.metaborg.spoofax.core.processing.SpoofaxBlockingProcessor; import org.metaborg.spoofax.core.processing.SpoofaxProcessorRunner; import org.metaborg.spoofax.core.processing.analyze.ISpoofaxAnalysisResultProcessor; import org.metaborg.spoofax.core.processing.analyze.ISpoofaxAnalysisResultRequester; import org.metaborg.spoofax.core.processing.analyze.ISpoofaxAnalysisResultUpdater; import org.metaborg.spoofax.core.processing.analyze.SpoofaxAnalysisResultProcessor; import org.metaborg.spoofax.core.processing.parse.ISpoofaxParseResultProcessor; import org.metaborg.spoofax.core.processing.parse.ISpoofaxParseResultRequester; import org.metaborg.spoofax.core.processing.parse.ISpoofaxParseResultUpdater; import org.metaborg.spoofax.core.processing.parse.SpoofaxParseResultProcessor; import org.metaborg.spoofax.core.stratego.IStrategoCommon; import org.metaborg.spoofax.core.stratego.IStrategoRuntimeService; import org.metaborg.spoofax.core.stratego.StrategoCommon; import org.metaborg.spoofax.core.stratego.StrategoRuntimeService; import org.metaborg.spoofax.core.stratego.primitive.AbsolutePathPrimitive; import org.metaborg.spoofax.core.stratego.primitive.CallStrategyPrimitive; import org.metaborg.spoofax.core.stratego.primitive.DigestPrimitive; import org.metaborg.spoofax.core.stratego.primitive.GetSortNamePrimitive; import org.metaborg.spoofax.core.stratego.primitive.IsLanguageActivePrimitive; import org.metaborg.spoofax.core.stratego.primitive.LanguageComponentsPrimitive; import org.metaborg.spoofax.core.stratego.primitive.LanguageImplementationPrimitive; import org.metaborg.spoofax.core.stratego.primitive.LanguageIncludeDirectoriesPrimitive; import org.metaborg.spoofax.core.stratego.primitive.LanguageIncludeFilesPrimitive; import org.metaborg.spoofax.core.stratego.primitive.LanguagePrimitive; import org.metaborg.spoofax.core.stratego.primitive.LanguageSourceDirectoriesPrimitive; import org.metaborg.spoofax.core.stratego.primitive.LanguageSourceFilesPrimitive; import org.metaborg.spoofax.core.stratego.primitive.LocalPathPrimitive; import org.metaborg.spoofax.core.stratego.primitive.LocalReplicatePrimitive; import org.metaborg.spoofax.core.stratego.primitive.ParsePrimitive; import org.metaborg.spoofax.core.stratego.primitive.ProjectPathPrimitive; import org.metaborg.spoofax.core.stratego.primitive.ScopeGraphLibrary; import org.metaborg.spoofax.core.stratego.primitive.SpoofaxPrimitiveLibrary; import org.metaborg.spoofax.core.stratego.primitive.generic.DummyPrimitive; import org.metaborg.spoofax.core.stratego.primitive.legacy.LegacyForeignCallPrimitive; import org.metaborg.spoofax.core.stratego.primitive.legacy.LegacyLanguageIncludeFilesPrimitive; import org.metaborg.spoofax.core.stratego.primitive.legacy.LegacyLanguageIncludeLocationsPrimitive; import org.metaborg.spoofax.core.stratego.primitive.legacy.LegacyLanguageIncludeLocationsPrimitive2; import org.metaborg.spoofax.core.stratego.primitive.legacy.LegacyLanguageSourceFilesPrimitive; import org.metaborg.spoofax.core.stratego.primitive.legacy.LegacyLanguageSourceLocationsPrimitive; import org.metaborg.spoofax.core.stratego.primitive.legacy.LegacyLanguageSourceLocationsPrimitive2; import org.metaborg.spoofax.core.stratego.primitive.legacy.LegacyProjectPathPrimitive; import org.metaborg.spoofax.core.stratego.primitive.legacy.LegacySpoofaxPrimitiveLibrary; import org.metaborg.spoofax.core.stratego.primitive.legacy.parse.LegacyParseFilePrimitive; import org.metaborg.spoofax.core.stratego.primitive.legacy.parse.LegacyParseFilePtPrimitive; import org.metaborg.spoofax.core.stratego.primitive.legacy.parse.LegacySpoofaxJSGLRLibrary; import org.metaborg.spoofax.core.stratego.strategies.ParseFileStrategy; import org.metaborg.spoofax.core.stratego.strategies.ParseStrategoFileStrategy; import org.metaborg.spoofax.core.style.CategorizerService; import org.metaborg.spoofax.core.style.ISpoofaxCategorizerService; import org.metaborg.spoofax.core.style.ISpoofaxStylerService; import org.metaborg.spoofax.core.style.StylerService; import org.metaborg.spoofax.core.syntax.ISpoofaxParser; import org.metaborg.spoofax.core.syntax.ISpoofaxSyntaxService; import org.metaborg.spoofax.core.syntax.JSGLRParseService; import org.metaborg.spoofax.core.syntax.JSGLRParserConfiguration; import org.metaborg.spoofax.core.syntax.SpoofaxSyntaxService; import org.metaborg.spoofax.core.terms.ITermFactoryService; import org.metaborg.spoofax.core.terms.TermFactoryService; import org.metaborg.spoofax.core.tracing.HoverService; import org.metaborg.spoofax.core.tracing.ISpoofaxHoverService; import org.metaborg.spoofax.core.tracing.ISpoofaxResolverService; import org.metaborg.spoofax.core.tracing.ISpoofaxTracingService; import org.metaborg.spoofax.core.tracing.ResolverService; import org.metaborg.spoofax.core.tracing.TracingCommon; import org.metaborg.spoofax.core.tracing.TracingService; import org.metaborg.spoofax.core.transform.ISpoofaxTransformService; import org.metaborg.spoofax.core.transform.IStrategoTransformer; import org.metaborg.spoofax.core.transform.SpoofaxTransformService; import org.metaborg.spoofax.core.transform.StrategoTransformer; import org.metaborg.spoofax.core.unit.ISpoofaxAnalyzeUnit; import org.metaborg.spoofax.core.unit.ISpoofaxAnalyzeUnitUpdate; import org.metaborg.spoofax.core.unit.ISpoofaxInputUnit; import org.metaborg.spoofax.core.unit.ISpoofaxInputUnitService; import org.metaborg.spoofax.core.unit.ISpoofaxParseUnit; import org.metaborg.spoofax.core.unit.ISpoofaxTransformUnit; import org.metaborg.spoofax.core.unit.ISpoofaxUnitService; import org.metaborg.spoofax.core.unit.UnitService; import org.spoofax.interpreter.library.AbstractPrimitive; import org.spoofax.interpreter.library.IOperatorRegistry; import org.spoofax.interpreter.library.index.primitives.legacy.LegacyIndexLibrary; import org.spoofax.interpreter.terms.IStrategoTerm; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.MapBinder; import com.google.inject.multibindings.Multibinder; import com.google.inject.name.Names; /** * Guice module that specifies which implementations to use for services and factories. */ public class SpoofaxModule extends MetaborgModule { private MapBinder<String, IParser<ISpoofaxInputUnit, ISpoofaxParseUnit>> parserBinder; private MapBinder<String, ISpoofaxParser> spoofaxParserBinder; private MapBinder<String, IAnalyzer<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxAnalyzeUnitUpdate>> analyzerBinder; private MapBinder<String, ISpoofaxAnalyzer> spoofaxAnalyzerBinder; public SpoofaxModule() { this(SpoofaxModule.class.getClassLoader()); } public SpoofaxModule(ClassLoader resourceClassLoader) { super(resourceClassLoader); } @Override protected void configure() { super.configure(); parserBinder = MapBinder.newMapBinder(binder(), new TypeLiteral<String>() {}, new TypeLiteral<IParser<ISpoofaxInputUnit, ISpoofaxParseUnit>>() {}); spoofaxParserBinder = MapBinder.newMapBinder(binder(), String.class, ISpoofaxParser.class); analyzerBinder = MapBinder.newMapBinder(binder(), new TypeLiteral<String>() {}, new TypeLiteral<IAnalyzer<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxAnalyzeUnitUpdate>>() {}); spoofaxAnalyzerBinder = MapBinder.newMapBinder(binder(), String.class, ISpoofaxAnalyzer.class); Multibinder.newSetBinder(binder(), ClassLoader.class).permitDuplicates(); bindUnit(); bindSyntax(); bindParsers(parserBinder, spoofaxParserBinder); bindAnalyzers(analyzerBinder, spoofaxAnalyzerBinder); bindCompletion(); bindAction(); bindTransformer(); bindCategorizer(); bindStyler(); bindTracing(); bindOutline(); bindMenu(); } protected void bindUnit() { bind(UnitService.class).in(Singleton.class); bind(ISpoofaxUnitService.class).to(UnitService.class); bind( new TypeLiteral<IUnitService<ISpoofaxInputUnit, ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxAnalyzeUnitUpdate, ISpoofaxTransformUnit<ISpoofaxParseUnit>, ISpoofaxTransformUnit<ISpoofaxAnalyzeUnit>>>() {}) .to(UnitService.class); bind(new TypeLiteral<IUnitService<?, ?, ?, ?, ?, ?>>() {}).to(UnitService.class); bind(IUnitService.class).to(UnitService.class); bind(ISpoofaxInputUnitService.class).to(UnitService.class); bind(new TypeLiteral<IInputUnitService<ISpoofaxInputUnit>>() {}).to(UnitService.class); bind(new TypeLiteral<IInputUnitService<?>>() {}).to(UnitService.class); bind(IInputUnitService.class).to(UnitService.class); } @Override protected void bindLanguage() { super.bindLanguage(); bind(ILanguageComponentFactory.class).to(LanguageComponentFactory.class).in(Singleton.class); bind(ILanguageDiscoveryService.class).to(LanguageDiscoveryService.class).in(Singleton.class); bind(IDialectService.class).to(DialectService.class).in(Singleton.class); bind(IDialectIdentifier.class).to(DialectIdentifier.class).in(Singleton.class); bind(IDialectProcessor.class).to(DialectProcessor.class).in(Singleton.class); } @Override protected void bindLanguagePathProviders(Multibinder<ILanguagePathProvider> binder) { // Bind builtin path provider before other providers such that builtin // paths have preference over others. binder.addBinding().to(BuiltinLanguagePathProvider.class); super.bindLanguagePathProviders(binder); } @Override protected void bindContextFactories(MapBinder<String, IContextFactory> binder) { super.bindContextFactories(binder); binder.addBinding(IndexTaskContextFactory.name).to(IndexTaskContextFactory.class).in(Singleton.class); binder.addBinding(LegacyContextFactory.name).to(LegacyContextFactory.class).in(Singleton.class); binder.addBinding(MultiFileScopeGraphContextFactory.name).to(MultiFileScopeGraphContextFactory.class) .in(Singleton.class); binder.addBinding(SingleFileScopeGraphContextFactory.name).to(SingleFileScopeGraphContextFactory.class) .in(Singleton.class); } protected void bindSyntax() { bind(SpoofaxSyntaxService.class).in(Singleton.class); bind(ISpoofaxSyntaxService.class).to(SpoofaxSyntaxService.class); bind(new TypeLiteral<ISyntaxService<ISpoofaxInputUnit, ISpoofaxParseUnit>>() {}).to(SpoofaxSyntaxService.class); bind(new TypeLiteral<ISyntaxService<?, ?>>() {}).to(SpoofaxSyntaxService.class); bind(ISyntaxService.class).to(SpoofaxSyntaxService.class); bind(TermFactoryService.class).in(Singleton.class); bind(ITermFactoryService.class).to(TermFactoryService.class); languageCacheBinder.addBinding().to(TermFactoryService.class); } protected void bindParsers(MapBinder<String, IParser<ISpoofaxInputUnit, ISpoofaxParseUnit>> parserBinder, MapBinder<String, ISpoofaxParser> spoofaxParserBinder) { bind(JSGLRParseService.class).in(Singleton.class); parserBinder.addBinding(JSGLRParseService.name).to(JSGLRParseService.class); spoofaxParserBinder.addBinding(JSGLRParseService.name).to(JSGLRParseService.class); languageCacheBinder.addBinding().to(JSGLRParseService.class); bind(JSGLRParserConfiguration.class).toInstance(new JSGLRParserConfiguration()); } /** * Overrides {@link MetaborgModule#bindAnalysis()} to provide Spoofax-specific bindings with Spoofax interfaces, and * to provide analyzers. */ @Override protected void bindAnalysis() { // Analysis service bind(SpoofaxAnalysisService.class).in(Singleton.class); bind(ISpoofaxAnalysisService.class).to(SpoofaxAnalysisService.class); bind(new TypeLiteral<IAnalysisService<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxAnalyzeUnitUpdate>>() {}) .to(SpoofaxAnalysisService.class); bind(new TypeLiteral<IAnalysisService<?, ?, ?>>() {}).to(SpoofaxAnalysisService.class); bind(IAnalysisService.class).to(SpoofaxAnalysisService.class); // Stratego runtime bind(StrategoRuntimeService.class).in(Singleton.class); bind(IStrategoRuntimeService.class).to(StrategoRuntimeService.class); languageCacheBinder.addBinding().to(StrategoRuntimeService.class); // Utilities bind(IStrategoCommon.class).to(StrategoCommon.class).in(Singleton.class); bind(AnalysisCommon.class).in(Singleton.class); // Stratego primitives bind(ParseFileStrategy.class).in(Singleton.class); bind(ParseStrategoFileStrategy.class).in(Singleton.class); final Multibinder<IOperatorRegistry> libraryBinder = Multibinder.newSetBinder(binder(), IOperatorRegistry.class); bindPrimitiveLibrary(libraryBinder, TaskLibrary.class); bindPrimitiveLibrary(libraryBinder, LegacyIndexLibrary.class); bindPrimitiveLibrary(libraryBinder, SpoofaxPrimitiveLibrary.class); bindPrimitiveLibrary(libraryBinder, ScopeGraphLibrary.class); bindPrimitiveLibrary(libraryBinder, LegacySpoofaxPrimitiveLibrary.class); bindPrimitiveLibrary(libraryBinder, LegacySpoofaxJSGLRLibrary.class); final Multibinder<AbstractPrimitive> spoofaxPrimitiveLibrary = Multibinder.newSetBinder(binder(), AbstractPrimitive.class, Names.named(SpoofaxPrimitiveLibrary.name)); bindPrimitive(spoofaxPrimitiveLibrary, DigestPrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, LanguageComponentsPrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, LanguageImplementationPrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, LanguagePrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, ProjectPathPrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, LocalPathPrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, LocalReplicatePrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, AbsolutePathPrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, LanguageSourceDirectoriesPrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, LanguageSourceFilesPrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, LanguageIncludeDirectoriesPrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, LanguageIncludeFilesPrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, ParsePrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, CallStrategyPrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, IsLanguageActivePrimitive.class); bindPrimitive(spoofaxPrimitiveLibrary, GetSortNamePrimitive.class); final Multibinder<AbstractPrimitive> spoofaxScopeGraphLibrary = Multibinder.newSetBinder(binder(), AbstractPrimitive.class, Names.named("ScopeGraphLibrary")); bindPrimitive(spoofaxScopeGraphLibrary, SG_analysis_has_errors.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_debug_constraints.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_debug_name_resolution.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_debug_scope_graph.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_debug_symbolic_constraints.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_debug_unifier.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_erase_ast_indices.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_fresh.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_focus_term.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_all_decls.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_all_refs.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_all_scopes.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_ast_index.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_ast_property.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_ast_resolution.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_custom_analysis.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_decl_property.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_decl_scope.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_direct_edges_inv.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_direct_edges.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_export_edges_inv.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_export_edges.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_import_edges_inv.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_import_edges.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_reachable_decls.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_ref_resolution.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_ref_scope.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_scope_decls.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_scope_refs.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_symbolic_facts.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_symbolic_goals.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_get_visible_decls.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_index_ast.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_is_debug_collection_enabled.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_is_debug_custom_enabled.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_is_debug_resolution_enabled.class); bindPrimitive(spoofaxScopeGraphLibrary, SG_set_ast_index.class); final Multibinder<AbstractPrimitive> legacySpoofaxLibrary = Multibinder.newSetBinder(binder(), AbstractPrimitive.class, Names.named(LegacySpoofaxPrimitiveLibrary.name)); bindPrimitive(legacySpoofaxLibrary, LegacyProjectPathPrimitive.class); bindPrimitive(legacySpoofaxLibrary, LegacyLanguageSourceLocationsPrimitive.class); bindPrimitive(legacySpoofaxLibrary, LegacyLanguageSourceLocationsPrimitive2.class); bindPrimitive(legacySpoofaxLibrary, LegacyLanguageIncludeLocationsPrimitive.class); bindPrimitive(legacySpoofaxLibrary, LegacyLanguageIncludeLocationsPrimitive2.class); bindPrimitive(legacySpoofaxLibrary, LegacyLanguageSourceFilesPrimitive.class); bindPrimitive(legacySpoofaxLibrary, LegacyLanguageIncludeFilesPrimitive.class); bindPrimitive(legacySpoofaxLibrary, LegacyForeignCallPrimitive.class); bindPrimitive(legacySpoofaxLibrary, new DummyPrimitive("SSL_EXT_set_total_work_units", 0, 0)); bindPrimitive(legacySpoofaxLibrary, new DummyPrimitive("SSL_EXT_set_markers", 0, 1)); bindPrimitive(legacySpoofaxLibrary, new DummyPrimitive("SSL_EXT_refreshresource", 0, 1)); bindPrimitive(legacySpoofaxLibrary, new DummyPrimitive("SSL_EXT_queue_strategy", 0, 2)); bindPrimitive(legacySpoofaxLibrary, new DummyPrimitive("SSL_EXT_complete_work_unit", 0, 0)); bindPrimitive(legacySpoofaxLibrary, new DummyPrimitive("SSL_EXT_pluginpath", 0, 0)); final Multibinder<AbstractPrimitive> legacySpoofaxJSGLRLibrary = Multibinder.newSetBinder(binder(), AbstractPrimitive.class, Names.named(LegacySpoofaxJSGLRLibrary.injectionName)); bindPrimitive(legacySpoofaxJSGLRLibrary, LegacyParseFilePrimitive.class); bindPrimitive(legacySpoofaxJSGLRLibrary, LegacyParseFilePtPrimitive.class); bindPrimitive(legacySpoofaxJSGLRLibrary, new DummyPrimitive("STRSGLR_open_parse_table", 0, 1)); bindPrimitive(legacySpoofaxJSGLRLibrary, new DummyPrimitive("STRSGLR_close_parse_table", 0, 1)); } private void bindAnalyzers( MapBinder<String, IAnalyzer<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxAnalyzeUnitUpdate>> analyzerBinder, MapBinder<String, ISpoofaxAnalyzer> spoofaxAnalyzerBinder) { bind(StrategoAnalyzer.class).in(Singleton.class); bind(TaskEngineAnalyzer.class).in(Singleton.class); bind(ConstraintSingleFileAnalyzer.class).in(Singleton.class); bind(ConstraintMultiFileAnalyzer.class).in(Singleton.class); analyzerBinder.addBinding(StrategoAnalyzer.name).to(StrategoAnalyzer.class); spoofaxAnalyzerBinder.addBinding(StrategoAnalyzer.name).to(StrategoAnalyzer.class); analyzerBinder.addBinding(TaskEngineAnalyzer.name).to(TaskEngineAnalyzer.class); spoofaxAnalyzerBinder.addBinding(TaskEngineAnalyzer.name).to(TaskEngineAnalyzer.class); analyzerBinder.addBinding(ConstraintSingleFileAnalyzer.name).to(ConstraintSingleFileAnalyzer.class); spoofaxAnalyzerBinder.addBinding(ConstraintSingleFileAnalyzer.name).to(ConstraintSingleFileAnalyzer.class); analyzerBinder.addBinding(ConstraintMultiFileAnalyzer.name).to(ConstraintMultiFileAnalyzer.class); spoofaxAnalyzerBinder.addBinding(ConstraintMultiFileAnalyzer.name).to(ConstraintMultiFileAnalyzer.class); } protected void bindAction() { bind(IActionService.class).to(ActionService.class).in(Singleton.class); } protected void bindTransformer() { // Analysis service bind(SpoofaxTransformService.class).in(Singleton.class); bind(ISpoofaxTransformService.class).to(SpoofaxTransformService.class); bind( new TypeLiteral<ITransformService<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxTransformUnit<ISpoofaxParseUnit>, ISpoofaxTransformUnit<ISpoofaxAnalyzeUnit>>>() {}) .to(SpoofaxTransformService.class); bind(new TypeLiteral<ITransformService<?, ?, ?, ?>>() {}).to(SpoofaxTransformService.class); bind(ITransformService.class).to(SpoofaxTransformService.class); // Analyzers bind(StrategoTransformer.class).in(Singleton.class); bind(IStrategoTransformer.class).to(StrategoTransformer.class); bind( new TypeLiteral<ITransformer<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxTransformUnit<ISpoofaxParseUnit>, ISpoofaxTransformUnit<ISpoofaxAnalyzeUnit>>>() {}) .to(StrategoTransformer.class); bind(new TypeLiteral<ITransformer<?, ?, ?, ?>>() {}).to(StrategoTransformer.class); bind(ITransformer.class).to(StrategoTransformer.class); } /** * Overrides {@link MetaborgModule#bindBuilder()} to provide Spoofax-specific bindings with generics filled in as * {@link IStrategoTerm}. */ @Override protected void bindBuilder() { bind(SpoofaxParseResultProcessor.class).in(Singleton.class); bind(ISpoofaxParseResultRequester.class).to(SpoofaxParseResultProcessor.class); bind(new TypeLiteral<IParseResultRequester<ISpoofaxInputUnit, ISpoofaxParseUnit>>() {}) .to(SpoofaxParseResultProcessor.class); bind(new TypeLiteral<IParseResultRequester<?, ?>>() {}).to(SpoofaxParseResultProcessor.class); bind(IParseResultRequester.class).to(SpoofaxParseResultProcessor.class); bind(ISpoofaxParseResultUpdater.class).to(SpoofaxParseResultProcessor.class); bind(new TypeLiteral<IParseResultUpdater<ISpoofaxParseUnit>>() {}).to(SpoofaxParseResultProcessor.class); bind(new TypeLiteral<IParseResultUpdater<?>>() {}).to(SpoofaxParseResultProcessor.class); bind(IParseResultUpdater.class).to(SpoofaxParseResultProcessor.class); bind(ISpoofaxParseResultProcessor.class).to(SpoofaxParseResultProcessor.class); bind(new TypeLiteral<IParseResultProcessor<ISpoofaxInputUnit, ISpoofaxParseUnit>>() {}) .to(SpoofaxParseResultProcessor.class); bind(new TypeLiteral<IParseResultProcessor<?, ?>>() {}).to(SpoofaxParseResultProcessor.class); bind(IParseResultProcessor.class).to(SpoofaxParseResultProcessor.class); bind(SpoofaxAnalysisResultProcessor.class).in(Singleton.class); bind(ISpoofaxAnalysisResultRequester.class).to(SpoofaxAnalysisResultProcessor.class); bind(new TypeLiteral<IAnalysisResultRequester<ISpoofaxInputUnit, ISpoofaxAnalyzeUnit>>() {}) .to(SpoofaxAnalysisResultProcessor.class); bind(new TypeLiteral<IAnalysisResultRequester<?, ?>>() {}).to(SpoofaxAnalysisResultProcessor.class); bind(IAnalysisResultRequester.class).to(SpoofaxAnalysisResultProcessor.class); bind(ISpoofaxAnalysisResultUpdater.class).to(SpoofaxAnalysisResultProcessor.class); bind(new TypeLiteral<IAnalysisResultUpdater<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit>>() {}) .to(SpoofaxAnalysisResultProcessor.class); bind(new TypeLiteral<IAnalysisResultUpdater<?, ?>>() {}).to(SpoofaxAnalysisResultProcessor.class); bind(IAnalysisResultUpdater.class).to(SpoofaxAnalysisResultProcessor.class); bind(ISpoofaxAnalysisResultProcessor.class).to(SpoofaxAnalysisResultProcessor.class); bind(new TypeLiteral<IAnalysisResultProcessor<ISpoofaxInputUnit, ISpoofaxParseUnit, ISpoofaxAnalyzeUnit>>() {}) .to(SpoofaxAnalysisResultProcessor.class); bind(new TypeLiteral<IAnalysisResultProcessor<?, ?, ?>>() {}).to(SpoofaxAnalysisResultProcessor.class); bind(IAnalysisResultProcessor.class).to(SpoofaxAnalysisResultProcessor.class); bind(SpoofaxBuilder.class).in(Singleton.class); bind(ISpoofaxBuilder.class).to(SpoofaxBuilder.class); bind( new TypeLiteral<IBuilder<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxAnalyzeUnitUpdate, ISpoofaxTransformUnit<?>>>() {}) .to(SpoofaxBuilder.class); bind(new TypeLiteral<IBuilder<?, ?, ?, ?>>() {}).to(SpoofaxBuilder.class); bind(IBuilder.class).to(SpoofaxBuilder.class); // No scope for build output, new instance for every request. bind( new TypeLiteral<IBuildOutputInternal<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxAnalyzeUnitUpdate, ISpoofaxTransformUnit<?>>>() {}) .to(SpoofaxBuildOutput.class); } /** * Overrides {@link MetaborgModule#bindProcessorRunner()} to provide Spoofax-specific bindings with generics filled * in as {@link IStrategoTerm}. */ @Override protected void bindProcessorRunner() { bind(SpoofaxProcessorRunner.class).in(Singleton.class); bind(ISpoofaxProcessorRunner.class).to(SpoofaxProcessorRunner.class); bind( new TypeLiteral<IProcessorRunner<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxAnalyzeUnitUpdate, ISpoofaxTransformUnit<?>>>() {}) .to(SpoofaxProcessorRunner.class); bind(new TypeLiteral<IProcessorRunner<?, ?, ?, ?>>() {}).to(SpoofaxProcessorRunner.class); bind(IProcessorRunner.class).to(SpoofaxProcessorRunner.class); } /** * Overrides {@link MetaborgModule#bindProcessor()} to provide Spoofax-specific bindings with generics filled in as * {@link IStrategoTerm}. */ @Override protected void bindProcessor() { bind(SpoofaxBlockingProcessor.class).in(Singleton.class); bind(ISpoofaxProcessor.class).to(SpoofaxBlockingProcessor.class); bind( new TypeLiteral<IProcessor<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxAnalyzeUnitUpdate, ISpoofaxTransformUnit<?>>>() {}) .to(SpoofaxBlockingProcessor.class); bind(new TypeLiteral<IProcessor<?, ?, ?, ?>>() {}).to(SpoofaxBlockingProcessor.class); bind(IProcessor.class).to(SpoofaxBlockingProcessor.class); } protected void bindCategorizer() { bind(CategorizerService.class).in(Singleton.class); bind(ISpoofaxCategorizerService.class).to(CategorizerService.class); bind(new TypeLiteral<ICategorizerService<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, IStrategoTerm>>() {}) .to(CategorizerService.class); bind(new TypeLiteral<ICategorizerService<?, ?, ?>>() {}).to(CategorizerService.class); bind(ICategorizerService.class).to(CategorizerService.class); } protected void bindStyler() { bind(StylerService.class).in(Singleton.class); bind(ISpoofaxStylerService.class).to(StylerService.class); bind(new TypeLiteral<IStylerService<IStrategoTerm>>() {}).to(StylerService.class); bind(new TypeLiteral<IStylerService<?>>() {}).to(StylerService.class); bind(IStylerService.class).to(StylerService.class); } protected void bindTracing() { bind(TracingService.class).in(Singleton.class); bind(ISpoofaxTracingService.class).to(TracingService.class); bind( new TypeLiteral<ITracingService<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit, ISpoofaxTransformUnit<?>, IStrategoTerm>>() {}) .to(TracingService.class); bind(new TypeLiteral<ITracingService<?, ?, ?, ?>>() {}).to(TracingService.class); bind(ITracingService.class).to(TracingService.class); bind(TracingCommon.class).in(Singleton.class); bind(ResolverService.class).in(Singleton.class); bind(ISpoofaxResolverService.class).to(ResolverService.class); bind(new TypeLiteral<IResolverService<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit>>() {}).to(ResolverService.class); bind(new TypeLiteral<IResolverService<?, ?>>() {}).to(ResolverService.class); bind(IResolverService.class).to(ResolverService.class); bind(HoverService.class).in(Singleton.class); bind(ISpoofaxHoverService.class).to(HoverService.class); bind(new TypeLiteral<IHoverService<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit>>() {}).to(HoverService.class); bind(new TypeLiteral<IHoverService<?, ?>>() {}).to(HoverService.class); bind(IHoverService.class).to(HoverService.class); } protected void bindCompletion() { bind(JSGLRCompletionService.class).in(Singleton.class); bind(new TypeLiteral<ICompletionService<ISpoofaxParseUnit>>() {}).to(JSGLRCompletionService.class); bind(new TypeLiteral<ICompletionService<?>>() {}).to(JSGLRCompletionService.class); bind(ICompletionService.class).to(JSGLRCompletionService.class); } protected void bindOutline() { bind(OutlineService.class).in(Singleton.class); bind(ISpoofaxOutlineService.class).to(OutlineService.class); bind(new TypeLiteral<IOutlineService<ISpoofaxParseUnit, ISpoofaxAnalyzeUnit>>() {}).to(OutlineService.class); bind(new TypeLiteral<IOutlineService<?, ?>>() {}).to(OutlineService.class); bind(IOutlineService.class).to(OutlineService.class); } protected void bindMenu() { bind(IMenuService.class).to(MenuService.class).in(Singleton.class); } protected static void bindPrimitive(Multibinder<AbstractPrimitive> binder, AbstractPrimitive primitive) { binder.addBinding().toInstance(primitive); } protected static void bindPrimitive(Multibinder<AbstractPrimitive> binder, Class<? extends AbstractPrimitive> primitive) { binder.addBinding().to(primitive).in(Singleton.class); } protected static void bindPrimitiveLibrary(Multibinder<IOperatorRegistry> binder, Class<? extends IOperatorRegistry> primitiveLibrary) { binder.addBinding().to(primitiveLibrary).in(Singleton.class); } }
package net.malisis.core.client.gui; import java.io.FileDescriptor; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Set; import java.util.function.Supplier; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; import net.malisis.core.MalisisCore; import net.malisis.core.client.gui.component.IKeyListener; import net.malisis.core.client.gui.component.UIComponent; import net.malisis.core.client.gui.component.UISlot; import net.malisis.core.client.gui.component.container.UIContainer; import net.malisis.core.inventory.MalisisInventoryContainer; import net.malisis.core.inventory.MalisisInventoryContainer.ActionType; import net.malisis.core.inventory.MalisisSlot; import net.malisis.core.inventory.message.InventoryActionMessage; import net.malisis.core.renderer.RenderType; import net.malisis.core.renderer.animation.Animation; import net.malisis.core.renderer.animation.AnimationRenderer; import net.malisis.core.renderer.font.FontOptions; import net.malisis.core.util.ItemUtils; import net.malisis.core.util.MouseButton; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.item.ItemStack; import net.minecraft.util.SoundEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; /** * GuiScreenProxy * * @author Ordinastie */ public abstract class MalisisGui extends GuiScreen { public static GuiTexture BLOCK_TEXTURE = new GuiTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); /** Whether or not to cancel the next gui close event. */ public static boolean cancelClose = false; /** Renderer drawing the components. */ protected GuiRenderer renderer; /** Width of the window. */ protected int displayWidth; /** Height of the window. */ protected int displayHeight; /** Currently used gui scale. */ protected int currentGuiScale; /** The resolution for the GUI **/ protected ScaledResolution resolution; /** Top level container which hold the user components. Spans across the whole screen. */ private UIContainer<?> screen; /** Determines if the screen should be darkened when the GUI is opened. */ protected boolean guiscreenBackground = true; /** Last known position of the mouse. */ protected int lastMouseX, lastMouseY; /** Last clicked button */ protected long lastClickButton = -1; /** How long since last click. */ protected long lastClickTime = 0; /** Inventory container that handles the inventories and slots actions. */ protected MalisisInventoryContainer inventoryContainer; /** Whether this GUI is considered as an overlay **/ protected boolean isOverlay = false; /** {@link AnimationRenderer} */ private AnimationRenderer ar; /** Currently hovered child component. */ protected UIComponent<?> hoveredComponent; /** Currently focused child component. */ protected UIComponent<?> focusedComponent; /** Component for which to display the tooltip (can be disabled and not receive events). */ protected UIComponent<?> tooltipComponent; /** Whether this GUI has been constructed. */ protected boolean constructed = false; /** List of {@link IKeyListener} registered. */ protected Set<IKeyListener> keyListeners = new HashSet<>(); /** Debug **/ private boolean debug = false; private HashMap<String, Supplier<String>> debugMap = new HashMap<>(); protected MalisisGui() { this.mc = Minecraft.getMinecraft(); this.itemRender = mc.getRenderItem(); this.fontRenderer = mc.fontRenderer; this.renderer = new GuiRenderer(); this.screen = new UIContainer<>(this).setName("Screen"); this.ar = new AnimationRenderer(); this.ar.autoClearAnimations(); this.screen.setClipContent(false); Keyboard.enableRepeatEvents(true); } /** * Called before display() if this {@link MalisisGui} is not constructed yet.<br> * Called when Ctrl+R is pressed to rebuild the GUI. */ public abstract void construct(); protected boolean doConstruct() { try { if (!constructed) { debugMap.clear(); addDefaultDebug(); construct(); constructed = true; } } catch (Exception e) { MalisisCore.message("A problem occured while constructing " + getClass().getSimpleName() + ": " + e.getMessage()); MalisisCore.log.error("A problem occured while constructing " + getClass().getSimpleName(), e); } return constructed; } /** * Gets the {@link GuiRenderer} for this {@link MalisisGui}. * * @return the renderer */ public GuiRenderer getRenderer() { return renderer; } /** * Sets the {@link MalisisInventoryContainer} for this {@link MalisisGui}. * * @param container the inventory container */ public void setInventoryContainer(MalisisInventoryContainer container) { this.inventoryContainer = container; } /** * Gets the {@link MalisisInventoryContainer} for this {@link MalisisGui}. * * @return inventory container */ public MalisisInventoryContainer getInventoryContainer() { return inventoryContainer; } /** * Gets the default {@link GuiTexture} used by the {@link GuiRenderer}. * * @return the defaultGuiTexture */ public GuiTexture getGuiTexture() { return renderer.getDefaultTexture(); } /** * Gets elapsed time since the GUI was opened. * * @return the time */ public long getElapsedTime() { return ar.getElapsedTime(); } /** * Called when game resolution changes. */ @Override public final void setWorldAndResolution(Minecraft minecraft, int width, int height) { setResolution(); } /** * Sets the resolution for this {@link MalisisGui}. */ public void setResolution() { boolean set = resolution == null; set |= displayWidth != Display.getWidth() || displayHeight != Display.getHeight(); set |= currentGuiScale != mc.gameSettings.guiScale; if (!set) return; displayWidth = Display.getWidth(); displayHeight = Display.getHeight(); currentGuiScale = mc.gameSettings.guiScale; resolution = new ScaledResolution(mc); renderer.setScaleFactor(resolution.getScaleFactor()); width = renderer.isIgnoreScale() ? displayWidth : resolution.getScaledWidth(); height = renderer.isIgnoreScale() ? displayHeight : resolution.getScaledHeight(); screen.setSize(width, height); } /** * Checks whether this {@link MalisisGui} is used as an overlay. * * @return true, if is overlay */ public boolean isOverlay() { return isOverlay; } /** * Adds the {@link UIComponent} to the screen. * * @param component the component */ public void addToScreen(UIComponent<?> component) { screen.add(component); component.onAddedToScreen(); } /** * Removes the {@link UIComponent} from screen. * * @param component the component */ public void removeFromScreen(UIComponent<?> component) { screen.remove(component); } /** * Removes all the components from the screen */ public void clearScreen() { screen.removeAll(); } /** * Registers a {@link IKeyListener} that will always receive keys types, even when not focused or hovered. * * @param listener the listener */ public void registerKeyListener(IKeyListener listener) { keyListeners.add(listener); } /** * Unregisters a previously registered IKeyListener. * * @param listener the listener */ public void unregisterKeyListener(IKeyListener listener) { keyListeners.remove(listener); } /** * Gets the {@link UIContainer} at the specified coordinates inside this {@link MalisisGui}. * * @param x the x coordinate * @param y the y coordinate * @return the component, null if component is {@link #screen} */ public UIComponent<?> getComponentAt(int x, int y) { UIComponent<?> component = screen.getComponentAt(x, y); return component == screen ? null : component; } /** * Called every frame to handle mouse input. */ @Override public void handleMouseInput() { try { int mouseX = Mouse.getEventX() * this.width / this.mc.displayWidth; int mouseY = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; //if we ignore scaling, use real mouse position on screen if (renderer.isIgnoreScale()) { mouseX = Mouse.getX(); mouseY = this.height - Mouse.getY() - 1; } int button = Mouse.getEventButton(); if (Mouse.getEventButtonState()) { if (this.mc.gameSettings.touchscreen && this.touchValue++ > 0) return; this.eventButton = button; this.lastMouseEvent = Minecraft.getSystemTime(); this.mouseClicked(mouseX, mouseY, this.eventButton); } else if (button != -1) { if (this.mc.gameSettings.touchscreen && --this.touchValue > 0) return; this.eventButton = -1; this.mouseReleased(mouseX, mouseY, button); } else if (this.eventButton != -1 && this.lastMouseEvent > 0L) { long l = Minecraft.getSystemTime() - this.lastMouseEvent; this.mouseClickMove(mouseX, mouseY, this.eventButton, l); } if (lastMouseX != mouseX || lastMouseY != mouseY) { UIComponent<?> component = getComponentAt(mouseX, mouseY); if (component != null) { tooltipComponent = component; if (!component.isDisabled()) { component.onMouseMove(lastMouseX, lastMouseY, mouseX, mouseY); component.setHovered(true); } } else setHoveredComponent(null, false); } lastMouseX = mouseX; lastMouseY = mouseY; int delta = Mouse.getEventDWheel(); if (delta == 0) return; else if (delta > 1) delta = 1; else if (delta < -1) delta = -1; UIComponent<?> component = getComponentAt(mouseX, mouseY); if (component != null && !component.isDisabled()) { component.onScrollWheel(mouseX, mouseY, delta); } } catch (Exception e) { MalisisCore.message("A problem occured : " + e.getClass().getSimpleName() + ": " + e.getMessage()); e.printStackTrace(new PrintStream(new FileOutputStream(FileDescriptor.out))); } } /** * Called when a mouse button is pressed down. */ @Override protected void mouseClicked(int x, int y, int button) { try { long time = System.currentTimeMillis(); UIComponent<?> component = getComponentAt(x, y); if (component != null && !component.isDisabled()) { //double click if (button == lastClickButton && time - lastClickTime < 250) { component.onDoubleClick(x, y, MouseButton.getButton(button)); lastClickTime = 0; } else //do not trigger onButtonPress when double clicked (fixed shift-double click issue in inventory) component.onButtonPress(x, y, MouseButton.getButton(button)); component.setFocused(true); } else { setFocusedComponent(null, true); if (inventoryContainer != null && !inventoryContainer.getPickedItemStack().isEmpty()) { ActionType action = button == 1 ? ActionType.DROP_ONE : ActionType.DROP_STACK; MalisisGui.sendAction(action, null, button); } } lastClickTime = time; lastClickButton = button; } catch (Exception e) { MalisisCore.message("A problem occured : " + e.getClass().getSimpleName() + ": " + e.getMessage()); e.printStackTrace(new PrintStream(new FileOutputStream(FileDescriptor.out))); } } /** * Called when the mouse is moved while a button is pressed. */ @Override protected void mouseClickMove(int x, int y, int button, long timer) { try { if (focusedComponent != null) focusedComponent.onDrag(lastMouseX, lastMouseY, x, y, MouseButton.getButton(button)); } catch (Exception e) { MalisisCore.message("A problem occured : " + e.getClass().getSimpleName() + ": " + e.getMessage()); e.printStackTrace(new PrintStream(new FileOutputStream(FileDescriptor.out))); } } /** * Called when a mouse button is released. */ @Override protected void mouseReleased(int x, int y, int button) { try { if (inventoryContainer != null) { if (inventoryContainer.shouldResetDrag(button)) { MalisisGui.sendAction(ActionType.DRAG_RESET, null, 0); UISlot.buttonRelased = false; return; } if (inventoryContainer.shouldEndDrag(button)) { MalisisGui.sendAction(ActionType.DRAG_END, null, 0); return; } } UIComponent<?> component = getComponentAt(x, y); if (component != null && !component.isDisabled()) { MouseButton mb = MouseButton.getButton(button); component.onButtonRelease(x, y, mb); if (component == focusedComponent) { if (mb == MouseButton.LEFT) component.onClick(x, y); else if (mb == MouseButton.RIGHT) component.onRightClick(x, y); } } } catch (Exception e) { MalisisCore.message("A problem occured : " + e.getClass().getSimpleName() + ": " + e.getMessage()); e.printStackTrace(new PrintStream(new FileOutputStream(FileDescriptor.out))); } } /** * Called when a key is pressed on the keyboard. */ @Override protected void keyTyped(char keyChar, int keyCode) { try { boolean ret = false; for (IKeyListener listener : keyListeners) ret |= listener.onKeyTyped(keyChar, keyCode); if (ret) return; if (focusedComponent != null && !keyListeners.contains(focusedComponent) && focusedComponent.onKeyTyped(keyChar, keyCode)) return; if (hoveredComponent != null && !keyListeners.contains(hoveredComponent) && hoveredComponent.onKeyTyped(keyChar, keyCode)) return; if (isGuiCloseKey(keyCode) && mc.currentScreen == this) close(); if (!MalisisCore.isObfEnv && isCtrlKeyDown() && (currentGui() != null || isOverlay)) { if (keyCode == Keyboard.KEY_R) { clearScreen(); setResolution(); construct(); } if (keyCode == Keyboard.KEY_D) debug = !debug; } } catch (Exception e) { MalisisCore.message("A problem occured while handling key typed for " + e.getClass().getSimpleName() + ": " + e.getMessage()); e.printStackTrace(new PrintStream(new FileOutputStream(FileDescriptor.out))); } } /** * Draws this {@link MalisisGui}. */ @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { ar.animate(); //if we ignore scaling, use real mouse position on screen if (renderer.isIgnoreScale()) { mouseX = Mouse.getX(); mouseY = this.height - Mouse.getY() - 1; } update(mouseX, mouseY, partialTicks); if (guiscreenBackground) drawWorldBackground(1); RenderHelper.enableGUIStandardItemLighting(); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_LIGHTING); renderer.drawScreen(screen, mouseX, mouseY, partialTicks); renderDebug(mouseX, mouseY, partialTicks); if (inventoryContainer != null) { ItemStack itemStack = inventoryContainer.getPickedItemStack(); if (!itemStack.isEmpty()) renderer.renderPickedItemStack(itemStack); else if (tooltipComponent != null) renderer.drawTooltip(tooltipComponent.getTooltip()); } else if (tooltipComponent != null) renderer.drawTooltip(tooltipComponent.getTooltip()); GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_DEPTH_TEST); } //#region Debug private void addDefaultDebug() { addDebug("Focus", () -> String.valueOf(focusedComponent)); addDebug("Hover", () -> String.valueOf(hoveredComponent)); if (inventoryContainer != null) addDebug("Picked", () -> ItemUtils.toString(inventoryContainer.getPickedItemStack())); } public void addDebug(String name, String value) { addDebug(name, () -> value); } public void addDebug(String name, Supplier<String> supplier) { debugMap.put(name, supplier); } public void removeDebug(String name) { debugMap.remove(name); } private void renderDebug(int mouseX, int mouseY, float partialTicks) { if (debug) { renderer.set(mouseX, mouseY, partialTicks); renderer.prepare(RenderType.GUI); int dy = 0, oy = 5; FontOptions fro = FontOptions.builder().color(0xFFFFFF).shadow().build(); //hard code mouse renderer.drawText(null, "Mouse : " + mouseX + "," + mouseY, 5, dy++ * 10 + oy, 0, fro, false); if (hoveredComponent != null) renderer.drawText( null, "(" + hoveredComponent.relativeX(mouseX) + ", " + hoveredComponent.relativeY(mouseY) + ")", 100, (dy - 1) * 10 + oy, 0, fro, false); for (Entry<String, Supplier<String>> entry : debugMap.entrySet()) renderer.drawText(null, entry.getKey() + " : " + entry.getValue().get(), 5, dy++ * 10 + oy, 0, fro, false); renderer.clean(); } } //#end Debug /** * Called every frame. * * @param mouseX the mouse x * @param mouseY the mouse y * @param partialTick the partial tick */ public void update(int mouseX, int mouseY, float partialTick) {} /** * Called from TE when TE is updated. Override this method when you want to change displayed informations when the TileEntity changes. */ public void updateGui() {} public void animate(Animation<?> animation) { animate(animation, 0); } public void animate(Animation<?> animation, int delay) { animation.setDelay((int) ar.getElapsedTicks() + delay); ar.addAnimation(animation); } @Override public boolean doesGuiPauseGame() { return false; } /** * Displays this {@link MalisisGui}. */ public void display() { display(false); } /** * Display this {@link MalisisGui}. * * @param cancelClose the wether or not to cancel the next Gui close event (used for when the GUI is opened from command) */ public void display(boolean cancelClose) { setResolution(); if (!doConstruct()) return; MalisisGui.cancelClose = cancelClose; Minecraft.getMinecraft().displayGuiScreen(this); } /** * Closes this {@link MalisisGui}. */ public void close() { setFocusedComponent(null, true); setHoveredComponent(null, true); Keyboard.enableRepeatEvents(false); if (this.mc.player != null) this.mc.player.closeScreen(); this.mc.displayGuiScreen((GuiScreen) null); this.mc.setIngameFocus(); return; } public void displayOverlay() { isOverlay = true; setResolution(); if (!doConstruct()) return; MinecraftForge.EVENT_BUS.register(this); } public void closeOverlay() { if (mc.currentScreen == this) close(); MinecraftForge.EVENT_BUS.unregister(this); onGuiClosed(); } @Override public void onGuiClosed() { if (inventoryContainer != null) inventoryContainer.onContainerClosed(this.mc.player); } @SubscribeEvent public void renderOverlay(RenderGameOverlayEvent.Post event) { if (event.getType() != RenderGameOverlayEvent.ElementType.ALL || Minecraft.getMinecraft().currentScreen == this) return; setResolution(); drawScreen(0, 0, event.getPartialTicks()); } @SubscribeEvent public void keyEvent(InputEvent.KeyInputEvent event) { if (!isOverlay || mc.currentScreen == this) return; if (Keyboard.getEventKeyState()) keyTyped(Keyboard.getEventCharacter(), Keyboard.getEventKey()); } /** * Gets the current {@link MalisisGui} displayed. * * @return null if no GUI being displayed or if not a {@link MalisisGui} */ public static MalisisGui currentGui() { return currentGui(MalisisGui.class); } /** * Gets the current {@link MalisisGui} of the specified type displayed.<br> * If the current gu is not of <i>type</i>, null is returned. * * @param <T> the generic type * @param type the type * @return the t */ public static <T extends MalisisGui> T currentGui(Class<T> type) { GuiScreen gui = Minecraft.getMinecraft().currentScreen; if (gui == null || !(gui instanceof MalisisGui)) return null; try { return type.cast(gui); } catch (ClassCastException e) { return null; } } /** * Sends a GUI action to the server. * * @param action the action * @param slot the slot * @param code the keyboard code */ public static void sendAction(ActionType action, MalisisSlot slot, int code) { if (action == null || currentGui() == null || currentGui().inventoryContainer == null) return; int inventoryId = slot != null ? slot.getInventoryId() : 0; int slotNumber = slot != null ? slot.getSlotIndex() : 0; currentGui().inventoryContainer.handleAction(action, inventoryId, slotNumber, code); InventoryActionMessage.sendAction(action, inventoryId, slotNumber, code); } /** * @return the currently hovered {@link UIComponent}. null if there is no current GUI. */ public static UIComponent<?> getHoveredComponent() { return currentGui() != null ? currentGui().hoveredComponent : null; } /** * Sets the hovered state for a {@link UIComponent}. If a <code>UIComponent</code> is currently hovered, it will be "unhovered" first. * * @param component the component that gets his state changed * @param hovered the hovered state * @return true, if the state was changed */ public static boolean setHoveredComponent(UIComponent<?> component, boolean hovered) { MalisisGui gui = currentGui(); if (gui == null) return false; if (gui.hoveredComponent == component) { if (!hovered) { gui.hoveredComponent = null; return true; } return false; } if (hovered) { if (gui.hoveredComponent != null) gui.hoveredComponent.setHovered(false); gui.hoveredComponent = component; } return true; } /** * Gets the currently focused {@link UIComponent} * * @return the component */ public static UIComponent<?> getFocusedComponent() { return currentGui() != null ? currentGui().focusedComponent : null; } public static boolean setFocusedComponent(UIComponent<?> component, boolean focused) { MalisisGui gui = currentGui(); if (gui == null) return false; if (gui.focusedComponent == component) { if (!focused) { gui.focusedComponent = null; return true; } return false; } if (focused) { if (gui.focusedComponent != null) gui.focusedComponent.setFocused(false); gui.focusedComponent = component; } return true; } public static void playSound(SoundEvent sound) { playSound(sound, 1.0F); } public static void playSound(SoundEvent sound, float level) { Minecraft.getMinecraft().getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(sound, level)); } public static boolean isGuiCloseKey(int keyCode) { MalisisGui gui = currentGui(); return keyCode == Keyboard.KEY_ESCAPE || (gui != null && gui.inventoryContainer != null && keyCode == gui.mc.gameSettings.keyBindInventory.getKeyCode()); } }
//$HeadURL$ package org.deegree.metadata; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.xml.namespace.QName; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import org.apache.axiom.om.OMElement; import org.deegree.commons.tom.datetime.Date; import org.deegree.commons.xml.CommonNamespaces; import org.deegree.commons.xml.NamespaceContext; import org.deegree.commons.xml.XMLAdapter; import org.deegree.commons.xml.XPath; import org.deegree.commons.xml.stax.StAXParsingHelper; import org.deegree.cs.CRS; import org.deegree.cs.CRSCodeType; import org.deegree.filter.Filter; import org.deegree.geometry.Envelope; import org.deegree.geometry.GeometryFactory; import org.deegree.metadata.persistence.MetadataStoreException; import org.deegree.metadata.persistence.iso.parsing.ISOQPParsing; import org.deegree.metadata.persistence.iso.parsing.ParsedProfileElement; import org.deegree.metadata.persistence.iso19115.jaxb.ISOMetadataStoreConfig.AnyText; import org.deegree.metadata.persistence.types.BoundingBox; import org.deegree.metadata.persistence.types.Format; import org.deegree.metadata.persistence.types.Keyword; import org.deegree.protocol.csw.CSWConstants.ReturnableElement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents an ISO 19115 {@link MetadataRecord}. * * @author <a href="mailto:schneider@lat-lon.de">Markus Schneider</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class ISORecord implements MetadataRecord { private static Logger LOG = LoggerFactory.getLogger( ISORecord.class ); private OMElement root; private ParsedProfileElement pElem; private AnyText anyText; private final static String STOPWORD = " "; private static String[] summaryLocalParts = new String[14]; private static String[] briefLocalParts = new String[9]; private static String[] briefSummaryLocalParts = new String[23]; private static final NamespaceContext ns = CommonNamespaces.getNamespaceContext(); private static XPath[] xpathAll = new XPath[1]; static { xpathAll[0] = new XPath( "//child::text()", null ); summaryLocalParts[0] = "/gmd:MD_Metadata/gmd:dataSetURI"; summaryLocalParts[1] = "/gmd:MD_Metadata/gmd:locale"; summaryLocalParts[2] = "/gmd:MD_Metadata/gmd:spatialRepresentationInfo"; summaryLocalParts[3] = "/gmd:MD_Metadata/gmd:metadataExtensionInfo"; summaryLocalParts[4] = "/gmd:MD_Metadata/gmd:contentInfo"; summaryLocalParts[5] = "/gmd:MD_Metadata/gmd:portrayalCatalogueInfo"; summaryLocalParts[6] = "/gmd:MD_Metadata/gmd:metadataConstraints"; summaryLocalParts[7] = "/gmd:MD_Metadata/gmd:applicationSchemaInfo"; summaryLocalParts[8] = "/gmd:MD_Metadata/gmd:metadataMaintenance"; summaryLocalParts[9] = "/gmd:MD_Metadata/gmd:series"; summaryLocalParts[10] = "/gmd:MD_Metadata/gmd:describes"; summaryLocalParts[11] = "/gmd:MD_Metadata/gmd:propertyType"; summaryLocalParts[12] = "/gmd:MD_Metadata/gmd:featureType"; summaryLocalParts[13] = "/gmd:MD_Metadata/gmd:featureAttribute"; briefLocalParts[0] = "/gmd:MD_Metadata/gmd:language"; briefLocalParts[1] = "/gmd:MD_Metadata/gmd:characterSet"; briefLocalParts[2] = "/gmd:MD_Metadata/gmd:parentIdentifier"; briefLocalParts[3] = "/gmd:MD_Metadata/gmd:hierarchieLevelName"; briefLocalParts[4] = "/gmd:MD_Metadata/gmd:metadataStandardName"; briefLocalParts[5] = "/gmd:MD_Metadata/gmd:metadataStandardVersion"; briefLocalParts[6] = "/gmd:MD_Metadata/gmd:referenceSystemInfo"; briefLocalParts[7] = "/gmd:MD_Metadata/gmd:distributionInfo"; briefLocalParts[8] = "/gmd:MD_Metadata/gmd:dataQualityInfo"; // metadatacharacterSet briefSummaryLocalParts[0] = "/gmd:MD_Metadata/gmd:dataSetURI"; briefSummaryLocalParts[1] = "/gmd:MD_Metadata/gmd:locale"; briefSummaryLocalParts[2] = "/gmd:MD_Metadata/gmd:spatialRepresentationInfo"; briefSummaryLocalParts[3] = "/gmd:MD_Metadata/gmd:metadataExtensionInfo"; briefSummaryLocalParts[4] = "/gmd:MD_Metadata/gmd:contentInfo"; briefSummaryLocalParts[5] = "/gmd:MD_Metadata/gmd:portrayalCatalogueInfo"; briefSummaryLocalParts[6] = "/gmd:MD_Metadata/gmd:metadataConstraints"; briefSummaryLocalParts[7] = "/gmd:MD_Metadata/gmd:applicationSchemaInfo"; briefSummaryLocalParts[8] = "/gmd:MD_Metadata/gmd:metadataMaintenance"; briefSummaryLocalParts[9] = "/gmd:MD_Metadata/gmd:series"; briefSummaryLocalParts[10] = "/gmd:MD_Metadata/gmd:describes"; briefSummaryLocalParts[11] = "/gmd:MD_Metadata/gmd:propertyType"; briefSummaryLocalParts[12] = "/gmd:MD_Metadata/gmd:featureType"; briefSummaryLocalParts[13] = "/gmd:MD_Metadata/gmd:featureAttribute"; briefSummaryLocalParts[14] = "/gmd:MD_Metadata/gmd:language"; briefSummaryLocalParts[15] = "/gmd:MD_Metadata/gmd:characterSet"; briefSummaryLocalParts[16] = "/gmd:MD_Metadata/gmd:parentIdentifier"; briefSummaryLocalParts[17] = "/gmd:MD_Metadata/gmd:hierarchieLevelName"; briefSummaryLocalParts[18] = "/gmd:MD_Metadata/gmd:metadataStandardName"; briefSummaryLocalParts[19] = "/gmd:MD_Metadata/gmd:metadataStandardVersion"; briefSummaryLocalParts[20] = "/gmd:MD_Metadata/gmd:referenceSystemInfo"; briefSummaryLocalParts[21] = "/gmd:MD_Metadata/gmd:distributionInfo"; briefSummaryLocalParts[22] = "/gmd:MD_Metadata/gmd:dataQualityInfo"; } private static List<XPath> summaryFilterElementsXPath; private static List<XPath> briefFilterElementsXPath; public ISORecord( XMLStreamReader xmlStream, AnyText anyText ) throws MetadataStoreException { this.anyText = anyText; this.root = new XMLAdapter( xmlStream ).getRootElement(); this.pElem = new ISOQPParsing().parseAPISO( root ); root.declareDefaultNamespace( "http: summaryFilterElementsXPath = removeElementsXPath( summaryLocalParts ); briefFilterElementsXPath = removeElementsXPath( briefSummaryLocalParts ); } public ISORecord( OMElement root, AnyText anyText ) throws MetadataStoreException { this( root.getXMLStreamReader(), anyText ); } @Override public QName getName() { return root.getQName(); } @Override public boolean eval( Filter filter ) { // TODO Auto-generated method stub return false; } @Override public String[] getAbstract() { List<String> l = pElem.getQueryableProperties().get_abstract(); String[] s = new String[l.size()]; int counter = 0; for ( String st : l ) { s[counter++] = st; } return s; } @Override public String getAnyText() { String anyTextString = null; if ( anyText == null || anyText.getCore() != null ) { StringBuilder sb = new StringBuilder(); for ( String s : getAbstract() ) { sb.append( s ).append( STOPWORD ); } for ( String f : getFormat() ) { sb.append( f ).append( STOPWORD ); } for ( String i : getIdentifier() ) { sb.append( i ).append( STOPWORD ); } if ( getLanguage() != null ) { sb.append( getLanguage() ).append( STOPWORD ); } for ( Date i : getModified() ) { sb.append( i.getDate() ).append( STOPWORD ); } for ( String f : getRelation() ) { sb.append( f ).append( STOPWORD ); } for ( String f : getTitle() ) { sb.append( f ).append( STOPWORD ); } if ( getType() != null ) { sb.append( getType() ).append( STOPWORD ); } for ( String f : getSubject() ) { sb.append( f ).append( STOPWORD ); } sb.append( isHasSecurityConstraints() ).append( STOPWORD ); for ( String f : getRights() ) { sb.append( f ).append( STOPWORD ); } if ( getContributor() != null ) { sb.append( getContributor() ).append( STOPWORD ); } if ( getPublisher() != null ) { sb.append( getPublisher() ).append( STOPWORD ); } if ( getSource() != null ) { sb.append( getSource() ).append( STOPWORD ); } if ( getCreator() != null ) { sb.append( getCreator() ).append( STOPWORD ); } if ( getParentIdentifier() != null ) { sb.append( getParentIdentifier() ).append( STOPWORD ); } anyTextString = sb.toString(); } else if ( anyText.getAll() != null ) { StringBuilder sb = new StringBuilder(); try { XMLStreamReader xmlStream = getAsXMLStream(); while ( xmlStream.hasNext() ) { xmlStream.next(); if ( xmlStream.getEventType() == XMLStreamConstants.CHARACTERS && !xmlStream.isWhiteSpace() ) { sb.append( xmlStream.getText() ).append( STOPWORD ); } } } catch ( XMLStreamException e ) { // TODO Auto-generated catch block e.printStackTrace(); } anyTextString = sb.toString(); } else if ( anyText.getCustom() != null ) { List<String> xpathList = anyText.getCustom().getXPath(); if ( xpathList != null && !xpathList.isEmpty() ) { XPath[] path = new XPath[xpathList.size()]; int counter = 0; for ( String x : xpathList ) { path[counter++] = new XPath( x, ns ); } anyTextString = generateAnyText( path ).toString(); } } else { anyTextString = ""; } return anyTextString; } @Override public Envelope[] getBoundingBox() { List<BoundingBox> bboxList = pElem.getQueryableProperties().getBoundingBox(); if ( pElem.getQueryableProperties().getCrs().isEmpty() ) { List<CRSCodeType> newCRSList = new LinkedList<CRSCodeType>(); for ( BoundingBox b : bboxList ) { newCRSList.add( new CRSCodeType( "4326", "EPSG" ) ); } pElem.getQueryableProperties().setCrs( newCRSList ); } Envelope[] env = new Envelope[bboxList.size()]; int counter = 0; for ( BoundingBox box : bboxList ) { CRSCodeType bboxCRS = pElem.getQueryableProperties().getCrs().get( counter ); CRS crs = new CRS( bboxCRS.toString() ); env[counter++] = new GeometryFactory().createEnvelope( box.getWestBoundLongitude(), box.getSouthBoundLatitude(), box.getEastBoundLongitude(), box.getNorthBoundLatitude(), crs ); } return env; } @Override public String[] getFormat() { List<Format> formats = pElem.getQueryableProperties().getFormat(); String[] format = new String[formats.size()]; int counter = 0; for ( Format f : formats ) { format[counter++] = f.getName(); } return format; } @Override public String[] getIdentifier() { return pElem.getQueryableProperties().getIdentifier(); } @Override public Date[] getModified() { return pElem.getQueryableProperties().getModified(); } @Override public String[] getRelation() { List<String> l = pElem.getReturnableProperties().getRelation(); String[] s = new String[l.size()]; int counter = 0; for ( String st : l ) { s[counter++] = st; } return s; } @Override public Object[] getSpatial() { // TODO Auto-generated method stub return null; } @Override public String[] getTitle() { List<String> l = pElem.getQueryableProperties().getTitle(); String[] s = new String[l.size()]; int counter = 0; for ( String st : l ) { s[counter++] = st; } return s; } @Override public String getType() { return pElem.getQueryableProperties().getType(); } @Override public String[] getSubject() { List<Keyword> keywords = pElem.getQueryableProperties().getKeywords(); int keywordSizeCount = 0; for ( Keyword k : keywords ) { keywordSizeCount += k.getKeywords().size(); } List<String> topicCategories = pElem.getQueryableProperties().getTopicCategory(); String[] subjects = new String[keywordSizeCount + topicCategories.size()]; int counter = 0; for ( Keyword k : keywords ) { for ( String kName : k.getKeywords() ) { subjects[counter++] = kName; } } for ( String topics : topicCategories ) { subjects[counter++] = topics; } return subjects; } /** * * @return the ISORecord as xmlStreamReader with skipped startDocument-preamble * @throws XMLStreamException */ public XMLStreamReader getAsXMLStream() throws XMLStreamException { root.declareDefaultNamespace( "http: XMLStreamReader xmlStream = root.getXMLStreamReader(); StAXParsingHelper.skipStartDocument( xmlStream ); return xmlStream; } public OMElement getAsOMElement() { return root; } public byte[] getAsByteArray() throws XMLStreamException, FactoryConfigurationError { // XMLStreamReader reader = new WhitespaceElementFilter( getAsXMLStream() ); // XMLStreamReader reader = getAsXMLStream(); // XMLStreamWriter writer = null; // try { // writer = XMLOutputFactory.newInstance().createXMLStreamWriter( // new FileOutputStream( // "/home/thomas/Desktop/ztest.xml" ) ); // } catch ( FileNotFoundException e ) { // // TODO Auto-generated catch block // e.printStackTrace(); // generateOutput( writer, reader ); root.declareDefaultNamespace( "http: return root.toString().getBytes(); } @Override public void serialize( XMLStreamWriter writer, ReturnableElement returnType ) throws XMLStreamException { XMLStreamReader xmlStream = root.getXMLStreamReader(); switch ( returnType ) { case brief: StAXParsingHelper.skipStartDocument( xmlStream ); toISOBrief( writer, xmlStream ); break; case summary: StAXParsingHelper.skipStartDocument( xmlStream ); toISOSummary( writer, xmlStream ); break; case full: StAXParsingHelper.skipStartDocument( xmlStream ); XMLAdapter.writeElement( writer, xmlStream ); break; default: StAXParsingHelper.skipStartDocument( xmlStream ); toISOSummary( writer, xmlStream ); break; } } @Override public void serialize( XMLStreamWriter writer, String[] elementNames ) throws XMLStreamException { List<XPath> xpathEN = new ArrayList<XPath>(); for ( String s : elementNames ) { xpathEN.add( new XPath( s, CommonNamespaces.getNamespaceContext() ) ); } OMElement elem = new XPathElementFilter( root, xpathEN ); elem.serialize( writer ); } @Override public DCRecord toDublinCore() { return new DCRecord( this ); } public boolean isHasSecurityConstraints() { return pElem.getQueryableProperties().isHasSecurityConstraints(); } @Override public String getContributor() { return pElem.getReturnableProperties().getContributor(); } @Override public String getPublisher() { return pElem.getReturnableProperties().getPublisher(); } @Override public String[] getRights() { List<String> l = pElem.getReturnableProperties().getRights(); String[] s = new String[l.size()]; int counter = 0; for ( String st : l ) { s[counter++] = st; } return s; } @Override public String getSource() { return pElem.getReturnableProperties().getSource(); } @Override public String getCreator() { return pElem.getReturnableProperties().getCreator(); } public String getLanguage() { return pElem.getQueryableProperties().getLanguage(); } public String getParentIdentifier() { return pElem.getQueryableProperties().getParentIdentifier(); } public ParsedProfileElement getParsedElement() { return pElem; } private void toISOSummary( XMLStreamWriter writer, XMLStreamReader xmlStream ) throws XMLStreamException { // XMLStreamReader filter = new NamedElementFilter( xmlStream, summaryFilterElements ); OMElement filter = new XPathElementFilter( root, summaryFilterElementsXPath ); filter.detach(); generateOutput( writer, filter.getXMLStreamReader() ); } private void toISOBrief( XMLStreamWriter writer, XMLStreamReader xmlStream ) throws XMLStreamException { // XMLStreamReader filter = new NamedElementFilter( xmlStream, briefSummaryFilterElements ); OMElement filter = new XPathElementFilter( root, briefFilterElementsXPath ); filter.detach(); generateOutput( writer, filter.getXMLStreamReader() ); } private Set<QName> removeElementsISONamespace( String[] localParts ) { Set<QName> removeElements = new HashSet<QName>(); for ( String l : localParts ) { removeElements.add( new QName( "http: } return removeElements; } private List<XPath> removeElementsXPath( String[] xpathExpr ) { List<XPath> removeElements = new ArrayList<XPath>(); for ( String l : xpathExpr ) { removeElements.add( new XPath( l, ns ) ); } return removeElements; } private void generateOutput( XMLStreamWriter writer, XMLStreamReader filter ) throws XMLStreamException { while ( filter.hasNext() ) { if ( filter.getEventType() == XMLStreamConstants.START_ELEMENT ) { XMLAdapter.writeElement( writer, filter ); } else { filter.next(); } } filter.close(); } private StringBuilder generateAnyText( XPath[] xpath ) { StringBuilder sb = new StringBuilder(); List<String> textNodes = new ArrayList<String>(); for ( XPath x : xpath ) { String[] tmp = new XMLAdapter().getNodesAsStrings( root, x ); for ( String s : tmp ) { textNodes.add( s ); } } for ( String s : textNodes ) { sb.append( s ).append( STOPWORD ); } return sb; } }
package org.jdesktop.swingx.rollover; import java.awt.Color; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.AbstractListModel; import javax.swing.Action; import javax.swing.JPopupMenu; import javax.swing.JTree; import javax.swing.ListModel; import javax.swing.table.TableModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXList; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.CompoundHighlighter; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlightPredicate.AndHighlightPredicate; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.test.AncientSwingTeam; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class RolloverTest extends InteractiveTestCase { /** * @param args */ public static void main(String[] args) { RolloverTest test = new RolloverTest(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Rend.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } private TableModel sortableTableModel; private Highlighter backgroundHighlighter; private Highlighter foregroundHighlighter; private ListModel listModel; private FileSystemModel treeTableModel; @Test public void testDummy() { } public void interactiveTableRollover() { JXTable table = new JXTable(sortableTableModel); final CompoundHighlighter compoundHighlighter = new CompoundHighlighter(foregroundHighlighter); table.setHighlighters(compoundHighlighter); JXFrame frame = wrapWithScrollingInFrame(table, "Table with rollover"); Action toggleAction = new AbstractAction("toggle foreground/background") { boolean isBackground; public void actionPerformed(ActionEvent e) { if (isBackground) { compoundHighlighter.addHighlighter(foregroundHighlighter); compoundHighlighter.removeHighlighter(backgroundHighlighter); } else { compoundHighlighter.addHighlighter(backgroundHighlighter); compoundHighlighter.removeHighlighter(foregroundHighlighter); } isBackground = !isBackground; } }; addAction(frame, toggleAction); frame.setVisible(true); } public void interactiveListRollover() { final JXList table = new JXList(listModel); table.setRolloverEnabled(true); final CompoundHighlighter compoundHighlighter = new CompoundHighlighter(foregroundHighlighter); table.setHighlighters(compoundHighlighter); JXFrame frame = wrapWithScrollingInFrame(table, "List with rollover"); Action toggleAction = new AbstractAction("toggle foreground/background") { boolean isBackground; public void actionPerformed(ActionEvent e) { if (isBackground) { compoundHighlighter.addHighlighter(foregroundHighlighter); compoundHighlighter.removeHighlighter(backgroundHighlighter); } else { compoundHighlighter.addHighlighter(backgroundHighlighter); compoundHighlighter.removeHighlighter(foregroundHighlighter); } isBackground = !isBackground; } }; addAction(frame, toggleAction); frame.setVisible(true); } public void interactiveTreeRollover() { final JXTree table = new JXTree(treeTableModel); table.setRolloverEnabled(true); table.setComponentPopupMenu(createPopup()); final CompoundHighlighter compoundHighlighter = new CompoundHighlighter(foregroundHighlighter); table.setHighlighters(compoundHighlighter); JTree tree = new JTree(treeTableModel); tree.setComponentPopupMenu(createPopup()); JXFrame frame = wrapWithScrollingInFrame(table, tree, "JXTree (at left) with rollover"); Action toggleAction = new AbstractAction("toggle foreground/background") { boolean isBackground; public void actionPerformed(ActionEvent e) { if (isBackground) { compoundHighlighter.addHighlighter(foregroundHighlighter); compoundHighlighter.removeHighlighter(backgroundHighlighter); } else { compoundHighlighter.addHighlighter(backgroundHighlighter); compoundHighlighter.removeHighlighter(foregroundHighlighter); } isBackground = !isBackground; } }; addAction(frame, toggleAction); addMessage(frame, "background highlight not working in JXTree"); frame.setVisible(true); } public JPopupMenu createPopup() { JPopupMenu popup = new JPopupMenu(); popup.add("dummy"); return popup; } public void interactiveTreeTableRollover() { final JXTreeTable table = new JXTreeTable(treeTableModel); final CompoundHighlighter compoundHighlighter = new CompoundHighlighter(foregroundHighlighter); table.setHighlighters(compoundHighlighter); JXFrame frame = wrapWithScrollingInFrame(table, "TreeTable with rollover"); Action toggleAction = new AbstractAction("toggle foreground/background") { boolean isBackground; public void actionPerformed(ActionEvent e) { if (isBackground) { compoundHighlighter.addHighlighter(foregroundHighlighter); compoundHighlighter.removeHighlighter(backgroundHighlighter); } else { compoundHighlighter.addHighlighter(backgroundHighlighter); compoundHighlighter.removeHighlighter(foregroundHighlighter); } isBackground = !isBackground; } }; addAction(frame, toggleAction); frame.setVisible(true); } /** * Example for per-cell rollover decoration in JXTreeTable. */ public void interactiveTreeTableRolloverHierarchical() { final JXTreeTable table = new JXTreeTable(treeTableModel); HighlightPredicate andPredicate = new AndHighlightPredicate( new HighlightPredicate.ColumnHighlightPredicate(0), HighlightPredicate.ROLLOVER_ROW ); final Highlighter foregroundHighlighter = new ColorHighlighter(andPredicate, null, Color.MAGENTA); final Highlighter backgroundHighlighter = new ColorHighlighter(andPredicate, Color.YELLOW, null); table.setHighlighters(foregroundHighlighter); JXFrame frame = wrapWithScrollingInFrame(table, "TreeTable with rollover - effect hierarchical column"); Action toggleAction = new AbstractAction("toggle foreground/background") { boolean isBackground; public void actionPerformed(ActionEvent e) { if (isBackground) { table.setHighlighters(foregroundHighlighter); } else { table.setHighlighters(backgroundHighlighter); } isBackground = !isBackground; } }; addAction(frame, toggleAction); frame.setVisible(true); } @Override protected void setUp() throws Exception { super.setUp(); sortableTableModel = new AncientSwingTeam(); listModel = new AbstractListModel() { public int getSize() { return sortableTableModel.getRowCount(); } public Object getElementAt(int index) { return sortableTableModel.getValueAt(index, 0); } }; treeTableModel = new FileSystemModel(); foregroundHighlighter = new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, null, Color.MAGENTA); backgroundHighlighter = new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, Color.YELLOW, null); } }
package org.mwc.debrief.lite.graph; import java.awt.Color; import java.awt.Component; import java.awt.FlowLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JPanel; import javax.swing.JToggleButton; import org.jfree.chart.annotations.XYTextAnnotation; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.ui.TextAnchor; import org.mwc.debrief.lite.gui.LiteStepControl; import org.mwc.debrief.lite.gui.custom.AbstractTrackConfiguration; import org.mwc.debrief.lite.gui.custom.AbstractTrackConfiguration.TrackWrapperSelect; import org.mwc.debrief.lite.gui.custom.JSelectTrack; import org.mwc.debrief.lite.gui.custom.JSelectTrackModel; import org.mwc.debrief.lite.gui.custom.SimpleEditablePropertyPanel; import Debrief.Tools.FilterOperations.ShowTimeVariablePlot3; import Debrief.Tools.FilterOperations.ShowTimeVariablePlot3.CalculationHolder; import Debrief.Tools.Tote.Calculations.atbCalc; import Debrief.Tools.Tote.Calculations.bearingCalc; import Debrief.Tools.Tote.Calculations.bearingRateCalc; import Debrief.Tools.Tote.Calculations.courseCalc; import Debrief.Tools.Tote.Calculations.depthCalc; import Debrief.Tools.Tote.Calculations.rangeCalc; import Debrief.Tools.Tote.Calculations.relBearingCalc; import Debrief.Tools.Tote.Calculations.speedCalc; import Debrief.Wrappers.TrackWrapper; import MWC.GUI.Defaults; import MWC.GUI.Editable; import MWC.GUI.Layer; import MWC.GUI.Layers; import MWC.GUI.Layers.DataListener; import MWC.GUI.JFreeChart.BearingRateFormatter; import MWC.GUI.JFreeChart.CourseFormatter; import MWC.GUI.JFreeChart.DepthFormatter; import MWC.GUI.JFreeChart.RelBearingFormatter; import MWC.GUI.JFreeChart.formattingOperation; import MWC.GenericData.WatchableList; import MWC.Utilities.XYPlot.XYPlotUtilities; public class GraphPanelToolbar extends JPanel { private static final long serialVersionUID = 8529947841065977007L; public static final String ACTIVE_STATE = "ACTIVE"; public static final String INACTIVE_STATE = "INACTIVE"; public static final String STATE_PROPERTY = "STATE"; private ShowTimeVariablePlot3 _xytool; private final LiteStepControl _stepControl; private final List<JComponent> componentsToDisable = new ArrayList<>(); private AbstractTrackConfiguration selectTrackModel; private String _state = INACTIVE_STATE; private final SimpleEditablePropertyPanel _xyPanel; public PropertyChangeListener enableDisableButtons = new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent event) { final boolean isActive = ACTIVE_STATE.equals(event.getNewValue()); for (final JComponent component : componentsToDisable) { component.setEnabled(isActive); } } }; private final ArrayList<PropertyChangeListener> stateListeners; public GraphPanelToolbar(final LiteStepControl stepControl, final SimpleEditablePropertyPanel xyPanel) { super(new FlowLayout(FlowLayout.LEFT)); _stepControl = stepControl; _xyPanel = xyPanel; init(); stateListeners = new ArrayList<>(Arrays.asList(enableDisableButtons)); setState(INACTIVE_STATE); } private JButton createCommandButton(final String command, final String image) { final ImageIcon icon = getIcon(image); final JButton button = new JButton(icon); button.setToolTipText(command); return button; } private JToggleButton createJToggleButton(final String command, final String image) { final ImageIcon icon = getIcon(image); final JToggleButton button = new JToggleButton(icon); button.setToolTipText(command); return button; } private ImageIcon getIcon(final String image) { final URL imageIcon = getClass().getClassLoader().getResource(image); ImageIcon icon = null; try { icon = new ImageIcon(imageIcon); } catch (final Exception e) { throw new IllegalArgumentException("Icon missing:" + image); } return icon; } protected void init() { formattingOperation theFormatter = null; if (relBearingCalc.useUKFormat()) { theFormatter = new RelBearingFormatter(); } else { theFormatter = null; } final JComboBox<CalculationHolder> operationComboBox = new JComboBox<>( new CalculationHolder[] {new CalculationHolder(new depthCalc(), new DepthFormatter(), false, 0), new CalculationHolder(new courseCalc(), new CourseFormatter(), false, 360), new CalculationHolder(new speedCalc(), null, false, 0), new CalculationHolder(new rangeCalc(), null, true, 0), new CalculationHolder(new bearingCalc(), null, true, 180), new CalculationHolder(new bearingRateCalc(), new BearingRateFormatter(), true, 180), new CalculationHolder( new relBearingCalc(), theFormatter, true, 180), new CalculationHolder(new atbCalc(), theFormatter, true, 180)}); operationComboBox.setSize(50, 20); operationComboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(final ItemEvent event) { selectTrackModel.setOperation((CalculationHolder) event.getItem()); } }); final List<TrackWrapper> tracks = new ArrayList<>(); selectTrackModel = new JSelectTrackModel(tracks, (CalculationHolder) operationComboBox.getSelectedItem()); // Re-renderer listener. selectTrackModel.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent arg0) { updateXYPlot(operationComboBox); } }); // Adding listener for filtering. _stepControl.getLayers().addDataReformattedListener(new DataListener() { @Override public void dataExtended(final Layers theData) { // not implemented } @Override public void dataModified(final Layers theData, final Layer changedLayer) { // not implemented } @Override public void dataReformatted(final Layers theData, final Layer changedLayer) { updateXYPlot(operationComboBox); } }); if (_stepControl != null && _stepControl.getLayers() != null) { final DataListener trackChangeListener = new DataListener() { @Override public void dataExtended(final Layers theData) { } @Override public void dataModified(final Layers theData, final Layer changedLayer) { final Enumeration<Editable> elem = _stepControl.getLayers() .elements(); while (elem.hasMoreElements()) { final Editable nextItem = elem.nextElement(); if (nextItem instanceof TrackWrapper) { tracks.add((TrackWrapper) nextItem); } } selectTrackModel.setTracks(tracks); } @Override public void dataReformatted(final Layers theData, final Layer changedLayer) { } }; _stepControl.getLayers().addDataModifiedListener(trackChangeListener); } final JSelectTrack selectTrack = new JSelectTrack(selectTrackModel); final JButton fixToWindowsButton = createCommandButton( "Scale the graph to show all data", "icons/16/fit_to_win.png"); fixToWindowsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { _xytool.getGeneratedChartPanel().getChart().getPlot().zoom(.0); } }); // final JToggleButton switchAxesButton = createJToggleButton("Switch axes", // "icons/16/swap_axis.png"); // switchAxesButton.addActionListener(new ActionListener() // @Override // public void actionPerformed(final ActionEvent e) // if (switchAxesButton.isSelected()) // _xytool.getGeneratedChartPanel().getChart().getXYPlot() // .setOrientation(PlotOrientation.HORIZONTAL); // else // _xytool.getGeneratedChartPanel().getChart().getXYPlot() // .setOrientation(PlotOrientation.VERTICAL); final String symbolOn = "icons/16/symbol_on.png"; final String symbolOff = "icons/16/symbol_off.png"; final JToggleButton showSymbolsButton = createJToggleButton("Show Symbols", symbolOff); showSymbolsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final boolean isSelected = showSymbolsButton.isSelected(); _xytool.getGeneratedJFreeChart().setShowSymbols(isSelected); showSymbolsButton.setIcon(new ImageIcon(isSelected ? getClass() .getClassLoader().getResource(symbolOn) : getClass() .getClassLoader().getResource(symbolOff))); showSymbolsButton.setToolTipText(isSelected ? "Hide Symbols" : "Show Symbols"); } }); final JToggleButton hideCrosshair = createJToggleButton( "Hide the crosshair from the graph (for printing)", "icons/16/fix.png"); final XYTextAnnotation _crosshairValueText = new XYTextAnnotation(" ", 0, 0); _crosshairValueText.setTextAnchor(TextAnchor.TOP_LEFT); _crosshairValueText.setFont(Defaults.getFont()); _crosshairValueText.setPaint(Color.black); _crosshairValueText.setBackgroundPaint(Color.white); hideCrosshair.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { _xytool.getGeneratedChartPanel().getChart().getXYPlot() .setDomainCrosshairVisible(hideCrosshair.isSelected()); _xytool.getGeneratedChartPanel().getChart().getXYPlot() .setRangeCrosshairVisible(hideCrosshair.isSelected()); if (hideCrosshair.isSelected()) { _xytool.getGeneratedJFreeChart().getXYPlot().addAnnotation( _crosshairValueText); } else { _xytool.getGeneratedJFreeChart().getXYPlot().removeAnnotation( _crosshairValueText); } _xytool.getGeneratedChartPanel().invalidate(); } }); // final JToggleButton expandButton = createJToggleButton( // "Expand Period covered in sync with scenario time", // "icons/16/clock.png"); // expandButton.addActionListener(new ActionListener() // @Override // public void actionPerformed(final ActionEvent e) // _xytool.getGeneratedXYPlot().setGrowWithTime(expandButton.isSelected()); // _xytool.getGeneratedChartPanel().invalidate(); final JButton wmfButton = createCommandButton( "Produce a WMF file of the graph", "icons/16/ex_2word_256_1.png"); wmfButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { final JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { final File dir = fileChooser.getSelectedFile(); _xytool.getGeneratedSwingPlot().doWMF(dir.getPath()); } } }); final JButton placeBitmapButton = createCommandButton( "Place a bitmap image of the graph on the clipboard", "icons/16/copy_to_clipboard.png"); placeBitmapButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { org.mwc.debrief.lite.util.ClipboardUtils.copyToClipboard(_xytool .getGeneratedChartPanel()); } }); final JButton copyGraph = createCommandButton( "Copies the graph as a text matrix to the clipboard", "icons/16/export.png"); copyGraph.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final TimeSeriesCollection dataset = (TimeSeriesCollection) _xytool .getGeneratedXYPlot().getDataset(); XYPlotUtilities.copyToClipboard(_xytool.getGeneratedChartPanel() .getName(), dataset); } }); final JButton propertiesButton = createCommandButton( "Change editable properties for this chart", "icons/16/properties.png"); propertiesButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { _xyPanel.addEditor(_xytool.getGeneratedJFreeChart().getInfo(), null); } }); final JComboBox<String> selectTracksLabel = new JComboBox<>(new String[] {"Select Tracks"}); selectTracksLabel.setEnabled(true); selectTracksLabel.addMouseListener(new MouseListener() { @Override public void mouseClicked(final MouseEvent e) { } @Override public void mouseEntered(final MouseEvent e) { } @Override public void mouseExited(final MouseEvent e) { } @Override public void mousePressed(final MouseEvent e) { if (selectTracksLabel.isEnabled()) { // Get the event source final Component component = (Component) e.getSource(); selectTrack.show(component, 0, 0); // Get the location of the point 'on the screen' final Point p = component.getLocationOnScreen(); selectTrack.setLocation(p.x, p.y + component.getHeight()); } } @Override public void mouseReleased(final MouseEvent e) { } }); add(operationComboBox); add(selectTracksLabel); add(fixToWindowsButton); add(showSymbolsButton); add(hideCrosshair); add(wmfButton); add(placeBitmapButton); add(copyGraph); add(propertiesButton); componentsToDisable.addAll(Arrays.asList(new JComponent[] {fixToWindowsButton, showSymbolsButton, hideCrosshair, wmfButton, placeBitmapButton, copyGraph, propertiesButton})); } private void notifyListenersStateChanged(final Object source, final String property, final String oldValue, final String newValue) { for (final PropertyChangeListener event : stateListeners) { event.propertyChange(new PropertyChangeEvent(source, property, oldValue, newValue)); } } public void setState(final String newState) { final String oldState = _state; this._state = newState; notifyListenersStateChanged(this, STATE_PROPERTY, oldState, newState); } private void updateXYPlot( final JComboBox<CalculationHolder> operationComboBox) { _xytool = new ShowTimeVariablePlot3(_xyPanel, _stepControl); final CalculationHolder operation = (CalculationHolder) operationComboBox .getSelectedItem(); _xytool.setPreselectedOperation(operation); Vector<WatchableList> selectedTracksByUser = null; if (selectTrackModel != null && _stepControl != null && _stepControl .getStartTime() != null && _stepControl.getEndTime() != null) { _xytool.setPreselectedPrimaryTrack(selectTrackModel.getPrimaryTrack()); final List<TrackWrapperSelect> tracks = selectTrackModel.getTracks(); selectedTracksByUser = new Vector<>(); for (final TrackWrapperSelect currentTrack : tracks) { if (currentTrack.selected) { selectedTracksByUser.add(currentTrack.track); } } if (!selectedTracksByUser.isEmpty() && (!operation .isARelativeCalculation() || selectTrackModel .getPrimaryTrack() != null)) { _xytool.setTracks(selectedTracksByUser); _xytool.setPeriod(_stepControl.getStartTime(), _stepControl .getEndTime()); // _xytool _xytool.getData(); setState(ACTIVE_STATE); } } } }
package net.md_5.mc.protocol; import java.io.DataInput; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class PacketDefinitions { private static final Instruction[][] opCodes = new Instruction[256][]; private static final Instruction BYTE = new JumpOpCode(1); private static final Instruction BOOLEAN = BYTE; private static final Instruction SHORT = new JumpOpCode(2); private static final Instruction INT = new JumpOpCode(4); private static final Instruction FLOAT = INT; private static final Instruction LONG = new JumpOpCode(8); private static final Instruction DOUBLE = LONG; private static final Instruction SHORT_BYTE = new ShortHeader(BYTE); private static final Instruction BYTE_INT = new ByteHeader(INT); private static final Instruction INT_BYTE = new IntHeader(BYTE); private static final Instruction INT_3 = new IntHeader(new JumpOpCode(3)); private static final Instruction STRING = new ShortHeader(SHORT); private static final Instruction ITEM = new Instruction() { @Override void read(DataInput in) throws IOException { short type = in.readShort(); if (type >= 0) { skip(in, 3); SHORT_BYTE.read(in); } } @Override public String toString() { return "Item"; } }; private static final Instruction SHORT_ITEM = new ShortHeader(ITEM); private static final Instruction METADATA = new Instruction() { @Override void read(DataInput in) throws IOException { int x = in.readUnsignedByte(); while (x != 127) { int type = x >> 5; switch (type) { case 0: BYTE.read(in); break; case 1: SHORT.read(in); break; case 2: INT.read(in); break; case 3: FLOAT.read(in); break; case 4: STRING.read(in); break; case 5: skip(in, 5); // short, byte, short break; case 6: skip(in, 6); // int, int, int break; default: throw new IllegalArgumentException("Unknown metadata type " + type); } x = in.readByte(); } } @Override public String toString() { return "Metadata"; } }; private static final Instruction BULK_CHUNK = new Instruction() { @Override void read(DataInput in) throws IOException { short count = in.readShort(); INT_BYTE.read(in); skip(in, count * 12); } @Override public String toString() { return "Bulk Chunk"; } }; private static final Instruction UBYTE_BYTE = new Instruction() { @Override void read(DataInput in) throws IOException { int size = in.readUnsignedByte(); skip(in, size); } @Override public String toString() { return "Unsigned Byte Byte"; } }; static { opCodes[0x00] = new Instruction[]{INT}; opCodes[0x01] = new Instruction[]{INT, STRING, BYTE, BYTE, BYTE, BYTE, BYTE}; opCodes[0x02] = new Instruction[]{BYTE, STRING, STRING, INT}; opCodes[0x03] = new Instruction[]{STRING}; opCodes[0x04] = new Instruction[]{LONG}; opCodes[0x05] = new Instruction[]{INT, SHORT, ITEM}; opCodes[0x06] = new Instruction[]{INT, INT, INT}; opCodes[0x07] = new Instruction[]{INT, INT, BOOLEAN}; opCodes[0x08] = new Instruction[]{SHORT, SHORT, FLOAT}; opCodes[0x09] = new Instruction[]{INT, BYTE, BYTE, SHORT, STRING}; opCodes[0x0A] = new Instruction[]{BOOLEAN}; opCodes[0x0B] = new Instruction[]{DOUBLE, DOUBLE, DOUBLE, DOUBLE, BOOLEAN}; opCodes[0x0C] = new Instruction[]{FLOAT, FLOAT, BOOLEAN}; opCodes[0x0D] = new Instruction[]{DOUBLE, DOUBLE, DOUBLE, DOUBLE, FLOAT, FLOAT, BOOLEAN}; opCodes[0x0E] = new Instruction[]{BYTE, INT, BYTE, INT, BYTE}; opCodes[0x0F] = new Instruction[]{INT, BYTE, INT, BYTE, ITEM, BYTE, BYTE, BYTE}; opCodes[0x10] = new Instruction[]{SHORT}; opCodes[0x11] = new Instruction[]{INT, BYTE, INT, BYTE, INT}; opCodes[0x12] = new Instruction[]{INT, BYTE}; opCodes[0x13] = new Instruction[]{INT, BYTE}; opCodes[0x14] = new Instruction[]{INT, STRING, INT, INT, INT, BYTE, BYTE, SHORT, METADATA}; opCodes[0x15] = new Instruction[]{INT, SHORT, BYTE, SHORT, INT, INT, INT, BYTE, BYTE, BYTE}; opCodes[0x16] = new Instruction[]{INT, INT}; opCodes[0x17] = new Instruction[]{INT, BYTE, INT, INT, INT, INT, SHORT, SHORT, SHORT}; opCodes[0x18] = new Instruction[]{INT, BYTE, INT, INT, INT, BYTE, BYTE, BYTE, SHORT, SHORT, SHORT, METADATA}; opCodes[0x19] = new Instruction[]{INT, STRING, INT, INT, INT, INT}; opCodes[0x1A] = new Instruction[]{INT, INT, INT, INT, SHORT}; opCodes[0x1B] = null; // Does not exist opCodes[0x1C] = new Instruction[]{INT, SHORT, SHORT, SHORT}; opCodes[0x1D] = new Instruction[]{BYTE_INT}; opCodes[0x1E] = new Instruction[]{INT}; opCodes[0x1F] = new Instruction[]{INT, BYTE, BYTE, BYTE}; opCodes[0x20] = new Instruction[]{INT, BYTE, BYTE}; opCodes[0x21] = new Instruction[]{INT, BYTE, BYTE, BYTE, BYTE, BYTE}; opCodes[0x22] = new Instruction[]{INT, INT, INT, INT, BYTE, BYTE}; opCodes[0x23] = new Instruction[]{INT, BYTE}; opCodes[0x24] = null; // Does not exist opCodes[0x25] = null; // Does not exist opCodes[0x26] = new Instruction[]{INT, BYTE}; opCodes[0x27] = new Instruction[]{INT, INT}; opCodes[0x28] = new Instruction[]{INT, METADATA}; opCodes[0x29] = new Instruction[]{INT, BYTE, BYTE, SHORT}; opCodes[0x2A] = new Instruction[]{INT, BYTE}; opCodes[0x2B] = new Instruction[]{FLOAT, SHORT, SHORT}; // 0x2C -> 0x32 Do not exist opCodes[0x33] = new Instruction[]{INT, INT, BOOLEAN, SHORT, SHORT, INT_BYTE}; opCodes[0x34] = new Instruction[]{INT, INT, SHORT, INT_BYTE}; opCodes[0x35] = new Instruction[]{INT, BYTE, INT, SHORT, BYTE}; opCodes[0x36] = new Instruction[]{INT, SHORT, INT, BYTE, BYTE, SHORT}; opCodes[0x37] = new Instruction[]{INT, INT, INT, INT, BYTE}; opCodes[0x38] = new Instruction[]{BULK_CHUNK}; opCodes[0x39] = null; // Does not exist opCodes[0x3A] = null; // Does not exist opCodes[0x3B] = null; // Does not exist opCodes[0x3C] = new Instruction[]{DOUBLE, DOUBLE, DOUBLE, FLOAT, INT_3, FLOAT, FLOAT, FLOAT}; opCodes[0x3D] = new Instruction[]{INT, INT, BYTE, INT, INT}; opCodes[0x3E] = new Instruction[]{STRING, INT, INT, INT, FLOAT, BYTE}; // 0x3F -> 0x45 Do not exist opCodes[0x46] = new Instruction[]{BYTE, BYTE}; opCodes[0x47] = new Instruction[]{INT, BOOLEAN, INT, INT, INT}; // 0x4A -> 0x63 Do not exist opCodes[0x64] = new Instruction[]{BYTE, BYTE, STRING, BYTE}; opCodes[0x65] = new Instruction[]{BYTE}; opCodes[0x66] = new Instruction[]{BYTE, SHORT, BOOLEAN, SHORT, BOOLEAN, ITEM}; opCodes[0x67] = new Instruction[]{BYTE, SHORT, ITEM}; opCodes[0x68] = new Instruction[]{BYTE, SHORT_ITEM}; opCodes[0x69] = new Instruction[]{BYTE, SHORT, SHORT}; opCodes[0x6A] = new Instruction[]{BYTE, SHORT, BOOLEAN}; opCodes[0x6B] = new Instruction[]{SHORT, ITEM}; opCodes[0x6C] = new Instruction[]{BYTE, BYTE}; // 0x6D -> 0x81 Do not exist opCodes[0x82] = new Instruction[]{INT, SHORT, INT, STRING, STRING, STRING, STRING}; opCodes[0x83] = new Instruction[]{SHORT, SHORT, UBYTE_BYTE}; opCodes[0x84] = new Instruction[]{INT, SHORT, INT, BYTE, SHORT_BYTE}; // 0x85 -> 0xC7 Do not exist opCodes[0xC8] = new Instruction[]{INT, BYTE}; opCodes[0xC9] = new Instruction[]{STRING, BOOLEAN, SHORT}; opCodes[0xCA] = new Instruction[]{BYTE, BYTE, BYTE}; opCodes[0xCB] = new Instruction[]{STRING}; opCodes[0xCC] = new Instruction[]{STRING, BYTE, BYTE, BYTE}; opCodes[0xCD] = new Instruction[]{BYTE}; // 0xCE -> 0xF9 Do not exist opCodes[0xFA] = new Instruction[]{STRING, SHORT_BYTE}; opCodes[0xFB] = null; // Does not exist opCodes[0xFC] = new Instruction[]{SHORT_BYTE, SHORT_BYTE}; opCodes[0xFD] = new Instruction[]{STRING, SHORT_BYTE, SHORT_BYTE}; opCodes[0xFE] = new Instruction[]{}; opCodes[0xFF] = new Instruction[]{STRING}; crushInstructions(); } private static void crushInstructions() { for (int i = 0; i < opCodes.length; i++) { Instruction[] instructions = opCodes[i]; if (instructions != null) { List<Instruction> crushed = new ArrayList<Instruction>(); int nextJumpSize = 0; for (Instruction child : instructions) { if (child instanceof JumpOpCode) { nextJumpSize += ((JumpOpCode) child).len; } else { if (nextJumpSize != 0) { crushed.add(new JumpOpCode(nextJumpSize)); } crushed.add(child); nextJumpSize = 0; } } if (nextJumpSize != 0) { crushed.add(new JumpOpCode(nextJumpSize)); } opCodes[i] = crushed.toArray(new Instruction[crushed.size()]); } } } public static void readPacket(DataInput in) throws IOException { int packetId = in.readUnsignedByte(); Instruction[] instructions = opCodes[packetId]; if (instructions == null) { throw new IOException("Unknown packet id " + packetId); } for (Instruction instruction : instructions) { instruction.read(in); } } static abstract class Instruction { abstract void read(DataInput in) throws IOException; final void skip(DataInput in, int len) throws IOException { for (int i = 0; i < len; i++) { in.readByte(); } } @Override public abstract String toString(); } static class JumpOpCode extends Instruction { private final int len; public JumpOpCode(int len) { if (len < 0) { throw new IndexOutOfBoundsException(); } this.len = len; } @Override void read(DataInput in) throws IOException { skip(in, len); } @Override public String toString() { return "Jump(" + len + ")"; } } static class ByteHeader extends Instruction { private final Instruction child; public ByteHeader(Instruction child) { this.child = child; } @Override void read(DataInput in) throws IOException { byte size = in.readByte(); for (byte b = 0; b < size; b++) { child.read(in); } } @Override public String toString() { return "ByteHeader(" + child + ")"; } } static class ShortHeader extends Instruction { private final Instruction child; public ShortHeader(Instruction child) { this.child = child; } @Override void read(DataInput in) throws IOException { short size = in.readShort(); for (short s = 0; s < size; s++) { child.read(in); } } @Override public String toString() { return "ShortHeader(" + child + ")"; } } static class IntHeader extends Instruction { private final Instruction child; public IntHeader(Instruction child) { this.child = child; } @Override void read(DataInput in) throws IOException { int size = in.readInt(); for (int i = 0; i < size; i++) { child.read(in); } } @Override public String toString() { return "IntHeader(" + child + ")"; } } }
package org.smoothbuild.db.value; import static com.google.common.collect.Lists.newArrayList; import static org.testory.Testory.given; import static org.testory.Testory.thenReturned; import static org.testory.Testory.when; import org.junit.Test; import org.smoothbuild.plugin.Value; import org.smoothbuild.testing.plugin.FakeHashed; import com.google.common.collect.Lists; public class HashedSorterTest { FakeHashed hashed1; FakeHashed hashed2; FakeHashed hashed3; FakeHashed hashed4; @Test public void hashed_objects_are_sorted_by_their_hashes() { given(hashed1 = new FakeHashed(new byte[] { 0, 0 })); given(hashed2 = new FakeHashed(new byte[] { 0, 1 })); given(hashed3 = new FakeHashed(new byte[] { 1, 0 })); given(hashed4 = new FakeHashed(new byte[] { 1, 1 })); when(HashedSorter.sort(newArrayList(hashed4, hashed3, hashed2, hashed1))); thenReturned(newArrayList(hashed1, hashed2, hashed3, hashed4)); } @Test public void sorting_empty_list_returns_empty_list() throws Exception { when(HashedSorter.sort(Lists.<Value> newArrayList())); thenReturned(Lists.<Value> newArrayList()); } }
package net.mingsoft.cms.action.web; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.PageUtil; import freemarker.core.ParseException; import freemarker.template.MalformedTemplateNameException; import freemarker.template.TemplateNotFoundException; import net.mingsoft.base.constant.Const; import net.mingsoft.basic.util.BasicUtil; import net.mingsoft.basic.util.StringUtil; import net.mingsoft.cms.bean.ContentBean; import net.mingsoft.cms.biz.ICategoryBiz; import net.mingsoft.cms.biz.IContentBiz; import net.mingsoft.cms.entity.CategoryEntity; import net.mingsoft.cms.entity.ContentEntity; import net.mingsoft.cms.util.CmsParserUtil; import net.mingsoft.mdiy.bean.PageBean; import net.mingsoft.mdiy.biz.IModelBiz; import net.mingsoft.mdiy.biz.IPageBiz; import net.mingsoft.mdiy.entity.ModelEntity; import net.mingsoft.mdiy.util.ParserUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * * @author * @date 20181217 */ @Controller("dynamicPageAction") @RequestMapping("/mcms") public class MCmsAction extends net.mingsoft.cms.action.BaseAction { @Autowired private IPageBiz pageBiz; @Autowired private IContentBiz contentBiz; @Autowired private ICategoryBiz categoryBiz; public static final String SEARCH = "search"; @Autowired private IModelBiz modelBiz; @GetMapping("/index.do") public void index(HttpServletRequest req, HttpServletResponse resp) { Map map = BasicUtil.assemblyRequestMap(); map.forEach((k,v)->{ map.put(k,v.toString().replaceAll("('|\"|\\\\)","\\$1")); }); map.put(ParserUtil.URL, BasicUtil.getUrl()); map.put(ParserUtil.IS_DO,true); map.put(ParserUtil.MODEL_NAME, "mcms"); String content = ""; try { content = CmsParserUtil.generate(ParserUtil.INDEX+ParserUtil.HTM_SUFFIX, map); } catch (TemplateNotFoundException e) { e.printStackTrace(); } catch (MalformedTemplateNameException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } this.outString(resp, content); } /** * * @param req * @param resp */ @GetMapping("/list.do") public void list(HttpServletRequest req, HttpServletResponse resp) { Map map = BasicUtil.assemblyRequestMap(); int typeId = BasicUtil.getInt(ParserUtil.TYPE_ID,0); int size = BasicUtil.getInt(ParserUtil.SIZE,10); List<ContentBean> columnArticles = contentBiz.queryIdsByCategoryIdForParser(String.valueOf(typeId), null, null); if(columnArticles.size()==0){ this.outJson(resp, false); } PageBean page = new PageBean(); int total = PageUtil.totalPage(columnArticles.size(), size); map.put(ParserUtil.COLUMN, columnArticles.get(0)); page.setTotal(total); map.put(ParserUtil.TYPE_ID, typeId); map.put(ParserUtil.PAGE_NO, BasicUtil.getInt(ParserUtil.PAGE_NO,1)); map.put(ParserUtil.URL, BasicUtil.getUrl()); map.put(ParserUtil.PAGE, page); map.put(ParserUtil.IS_DO,true); map.put(ParserUtil.MODEL_NAME, "mcms"); String content = ""; try { content = CmsParserUtil.generate(columnArticles.get(0).getCategoryListUrl(),map); } catch (TemplateNotFoundException e) { e.printStackTrace(); } catch (MalformedTemplateNameException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } this.outString(resp, content); } /** * * @param id */ @GetMapping("/view.do") public void view(String orderby,String order,HttpServletRequest req, HttpServletResponse resp) { ContentEntity article = (ContentEntity) contentBiz.getEntity(BasicUtil.getInt(ParserUtil.ID)); if(ObjectUtil.isNull(article)){ this.outJson(resp, null,false,getResString("err.empty", this.getResString("id"))); return; } if(StringUtils.isNotBlank(order)){ if(!order.toLowerCase().equals("asc")&&!order.toLowerCase().equals("desc")){ this.outJson(resp, null,false,getResString("err.error", this.getResString("order"))); return; } } orderby= orderby.replaceAll("('|\"|\\\\)","\\$1"); PageBean page = new PageBean(); CategoryEntity column = (CategoryEntity) categoryBiz.getEntity(Integer.parseInt(article.getContentCategoryId())); String content = ""; Map map = BasicUtil.assemblyRequestMap(); map.forEach((k,v)->{ //sql map.put(k,v.toString().replaceAll("('|\"|\\\\)","\\$1")); }); map.put(ParserUtil.IS_DO,true); map.put(ParserUtil.MODEL_NAME, "mcms"); map.put(ParserUtil.URL, BasicUtil.getUrl()); map.put(ParserUtil.PAGE, page); map.put(ParserUtil.ID, article.getId()); List<ContentBean> articleIdList = contentBiz.queryIdsByCategoryIdForParser(column.getCategoryId(), null, null,orderby,order); Map<Object, Object> contentModelMap = new HashMap<Object, Object>(); ModelEntity contentModel = null; for (int artId = 0; artId < articleIdList.size();) { if(articleIdList.get(artId).getArticleId() != Integer.parseInt(article.getId())){ artId++; continue; } String articleColumnPath = articleIdList.get(artId).getCategoryPath(); String columnContentModelId = articleIdList.get(artId).getMdiyModelId(); Map<String, Object> parserParams = new HashMap<String, Object>(); parserParams.put(ParserUtil.COLUMN, articleIdList.get(artId)); if ( StringUtils.isNotBlank(columnContentModelId)) { if (contentModelMap.containsKey(columnContentModelId)) { parserParams.put(ParserUtil.TABLE_NAME, contentModel.getModelTableName()); } else { contentModel=(ModelEntity)modelBiz.getEntity(Integer.parseInt(columnContentModelId)); // key contentModelMap.put(columnContentModelId, contentModel.getModelTableName()); parserParams.put(ParserUtil.TABLE_NAME, contentModel.getModelTableName()); } } if (artId > 0) { ContentBean preCaBean = articleIdList.get(artId - 1); if(articleColumnPath.contains(preCaBean.getCategoryId()+"")){ page.setPreId(preCaBean.getArticleId()); } } if (artId + 1 < articleIdList.size()) { ContentBean nextCaBean = articleIdList.get(artId + 1); if(articleColumnPath.contains(nextCaBean.getCategoryId()+"")){ page.setNextId(nextCaBean.getArticleId()); } } break; } try { content = CmsParserUtil.generate(column.getCategoryUrl(), map); } catch (TemplateNotFoundException e) { e.printStackTrace(); } catch (MalformedTemplateNameException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } this.outString(resp, content); } /** * * * @param request * id * @param response */ @RequestMapping(value = "search") @ResponseBody public void search(HttpServletRequest request, HttpServletResponse response) throws IOException { Map<String, Object> map = new HashMap<>(); Map<String, Object> field = BasicUtil.assemblyRequestMap(); Map<String, String> diyFieldName = new HashMap<String, String>(); CategoryEntity column = null; ModelEntity contentModel = null; List<DiyModelMap> fieldValueList = new ArrayList<DiyModelMap>(); int typeId = 0; String categoryIds = BasicUtil.getString("categoryId"); if(!StringUtil.isBlank(categoryIds) && !categoryIds.contains(",")){ typeId = Integer.parseInt(categoryIds); } String url = BasicUtil.getUrl(); List filedStr = new ArrayList<>(); if(typeId>0){ column = (CategoryEntity) categoryBiz.getEntity(Integer.parseInt(typeId+"")); if (column != null&&ObjectUtil.isNotNull(column.getMdiyModelId())) { contentModel = (ModelEntity) modelBiz.getEntity(Integer.parseInt(column.getMdiyModelId())); if (contentModel != null) { Map<String,String> fieldMap = contentModel.getFieldMap(); for (String s : fieldMap.keySet()) { filedStr.add(fieldMap.get(s)); } map.put(ParserUtil.TABLE_NAME, contentModel.getModelTableName()); } } map.put(ParserUtil.COLUMN, column); } if (field != null) { for (Map.Entry<String, Object> entry : field.entrySet()) { if (entry != null) { String value = entry.getValue().toString().replaceAll("('|\"|\\\\)","\\$1"); // get if (ObjectUtil.isNull(value)) { continue; } if (request.getMethod().equals(RequestMethod.GET)) { // get try { value = new String(value.getBytes("ISO-8859-1"), Const.UTF8); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } if (!StringUtil.isBlank(value)) { diyFieldName.put(entry.getKey(), value); if(filedStr.contains(entry.getKey())){ DiyModelMap diyMap = new DiyModelMap(); diyMap.setKey(entry.getKey()); diyMap.setValue(value); fieldValueList.add(diyMap); } } } } } if(fieldValueList.size()>0){ map.put("diyModel", fieldValueList); } PageBean page = new PageBean(); Map<String, Object> searchMap = field; StringBuilder urlParams=new StringBuilder(); searchMap.forEach((k,v)->{ //sql searchMap.put(k,v.toString().replaceAll("('|\"|\\\\)","\\$1")); urlParams.append(k).append("=").append(searchMap.get(k)).append("&"); }); int count= contentBiz.getSearchCount(contentModel,fieldValueList,searchMap,BasicUtil.getAppId(),categoryIds); map.put(ParserUtil.URL, url); map.put(SEARCH, searchMap); map.put(ParserUtil.APP_ID, BasicUtil.getAppId()); map.put(ParserUtil.PAGE, page); map.put(ParserUtil.HTML, ParserUtil.HTML); map.put(ParserUtil.IS_DO,false); map.put(ParserUtil.MODEL_NAME, "mcms"); searchMap.put(ParserUtil.PAGE_NO, 0); ParserUtil.read(SEARCH+ParserUtil.HTM_SUFFIX,map, page); int total = PageUtil.totalPage(count, page.getSize()); int pageNo = BasicUtil.getInt(ParserUtil.PAGE_NO, 1); if(pageNo >= total && total!=0) { pageNo = total; } page.setTotal(total); page.setPageNo(pageNo); url = url +request.getServletPath() +"?" + urlParams; String pageNoStr = ParserUtil.SIZE+"="+page.getSize()+"&"+ParserUtil.PAGE_NO+"="; String nextUrl = url + pageNoStr+((pageNo+1 > total)?total:pageNo+1); String indexUrl = url + pageNoStr + 1; String lastUrl = url + pageNoStr + total; String preUrl = url + pageNoStr + ((pageNo==1) ? 1:pageNo-1); page.setIndexUrl(indexUrl); page.setNextUrl(nextUrl); page.setPreUrl(preUrl); page.setLastUrl(lastUrl); searchMap.put(ParserUtil.PAGE_NO, pageNo); String content = ""; try { content = CmsParserUtil.generate(SEARCH+ParserUtil.HTM_SUFFIX,map); } catch (TemplateNotFoundException e) { e.printStackTrace(); } catch (MalformedTemplateNameException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } this.outString(response, content); } /** * * @author * @date 201935 */ public class DiyModelMap { String key; Object value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } } }
package nl.mpi.kinnate.svg; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.util.HashSet; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.arbil.ui.GuiHelper; import nl.mpi.kinnate.KinTermSavePanel; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.kindata.EntityRelation; import nl.mpi.kinnate.uniqueidentifiers.IdentifierException; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import org.apache.batik.bridge.UpdateManager; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.w3c.dom.events.EventTarget; import org.w3c.dom.svg.SVGLocatable; import org.w3c.dom.svg.SVGRect; public class SvgUpdateHandler { private GraphPanel graphPanel; private KinTermSavePanel kinTermSavePanel; private boolean dragUpdateRequired = false; private boolean threadRunning = false; private boolean relationThreadRunning = false; private int updateDragNodeX = 0; private int updateDragNodeY = 0; private int updateDragRelationX = 0; private int updateDragRelationY = 0; private float[][] dragRemainders = null; private boolean resizeRequired = false; protected RelationDragHandle relationDragHandle = null; private HashSet<UniqueIdentifier> highlightedIdentifiers = new HashSet<UniqueIdentifier>(); public enum GraphicsTypes { Label, Circle, Square, Polyline, Ellipse // * Rectangle <rect> // * Circle <circle> // * Ellipse <ellipse> // * Line <line> // * Polyline <polyline> // * Polygon <polygon> // * Path <path> } protected SvgUpdateHandler(GraphPanel graphPanelLocal, KinTermSavePanel kinTermSavePanelLocal) { graphPanel = graphPanelLocal; kinTermSavePanel = kinTermSavePanelLocal; } private void removeRelationHighLights() { // this must be only called from within a svg runnable Element relationOldHighlightGroup = graphPanel.doc.getElementById("RelationHighlightGroup"); if (relationOldHighlightGroup != null) { // remove the relation highlight group relationOldHighlightGroup.getParentNode().removeChild(relationOldHighlightGroup); } } private void removeEntityHighLights() { for (Element entityHighlightGroup = graphPanel.doc.getElementById("highlight"); entityHighlightGroup != null; entityHighlightGroup = graphPanel.doc.getElementById("highlight")) { entityHighlightGroup.getParentNode().removeChild(entityHighlightGroup); } } private void updateSanguineHighlights(Element entityGroup) { // this must be only called from within a svg runnable removeRelationHighLights(); if (graphPanel.dataStoreSvg.highlightRelationLines) { // add highlights for relation lines Element relationHighlightGroup = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); relationHighlightGroup.setAttribute("id", "RelationHighlightGroup"); entityGroup.getParentNode().insertBefore(relationHighlightGroup, entityGroup); Element relationsGroup = graphPanel.doc.getElementById("RelationGroup"); for (Node currentRelation = relationsGroup.getFirstChild(); currentRelation != null; currentRelation = currentRelation.getNextSibling()) { Node dataElement = currentRelation.getFirstChild(); if (dataElement != null && dataElement.hasAttributes()) { NamedNodeMap dataAttributes = dataElement.getAttributes(); if (dataAttributes.getNamedItemNS(DataStoreSvg.kinDataNameSpace, "lineType").getNodeValue().equals("sanguineLine")) { Element polyLineElement = (Element) dataElement.getNextSibling().getFirstChild(); try { if (graphPanel.selectedGroupId.contains(new UniqueIdentifier(dataAttributes.getNamedItemNS(DataStoreSvg.kinDataNameSpace, "ego").getNodeValue())) || graphPanel.selectedGroupId.contains(new UniqueIdentifier(dataAttributes.getNamedItemNS(DataStoreSvg.kinDataNameSpace, "alter").getNodeValue()))) { // try creating a use node for the highlight (these use nodes do not get updated when a node is dragged and the colour attribute is ignored) // Element useNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "use"); // useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + polyLineElement.getAttribute("id")); // useNode.setAttributeNS(null, "stroke", "blue"); // relationHighlightGroup.appendChild(useNode); // try creating a new node based on the original lines attributes (these lines do not get updated when a node is dragged) // as a comprimise these highlighs can be removed when a node is dragged // add a white background Element highlightBackgroundLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline"); highlightBackgroundLine.setAttribute("stroke-width", polyLineElement.getAttribute("stroke-width")); highlightBackgroundLine.setAttribute("fill", polyLineElement.getAttribute("fill")); highlightBackgroundLine.setAttribute("points", polyLineElement.getAttribute("points")); highlightBackgroundLine.setAttribute("stroke", "white"); relationHighlightGroup.appendChild(highlightBackgroundLine); // add a blue dotted line Element highlightLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline"); highlightLine.setAttribute("stroke-width", polyLineElement.getAttribute("stroke-width")); highlightLine.setAttribute("fill", polyLineElement.getAttribute("fill")); highlightLine.setAttribute("points", polyLineElement.getAttribute("points")); highlightLine.setAttribute("stroke", "blue"); highlightLine.setAttribute("stroke-dasharray", "3"); highlightLine.setAttribute("stroke-dashoffset", "0"); relationHighlightGroup.appendChild(highlightLine); // try changing the target lines attributes (does not get updated maybe due to the 'use' node rendering) // polyLineElement.getAttributes().getNamedItem("stroke").setNodeValue("blue"); // polyLineElement.setAttributeNS(null, "stroke", "blue"); // polyLineElement.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth * 2)); } else { // polyLineElement.getAttributes().getNamedItem("stroke").setNodeValue("green"); // polyLineElement.setAttributeNS(null, "stroke", "grey"); // polyLineElement.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth)); } } catch (IdentifierException exception) { GuiHelper.linorgBugCatcher.logError(exception); ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("Failed to read relation data, highlight might not be correct", "Sanguine Highlights"); } } } } } } private void updateDragRelationLines(Element entityGroup, float localDragNodeX, float localDragNodeY) { // this must be only called from within a svg runnable RelationDragHandle localRelationDragHandle = relationDragHandle; if (localRelationDragHandle != null) { if (localRelationDragHandle instanceof GraphicsDragHandle) { ((GraphicsDragHandle) localRelationDragHandle).updatedElement(localDragNodeX, localDragNodeY); } else { float dragNodeX = localRelationDragHandle.getTranslatedX(localDragNodeX); float dragNodeY = localRelationDragHandle.getTranslatedY(localDragNodeY); localRelationDragHandle.targetIdentifier = graphPanel.entitySvg.getClosestEntity(new float[]{dragNodeX, dragNodeY}, 30, graphPanel.selectedGroupId); if (localRelationDragHandle.targetIdentifier != null) { float[] closestEntityPoint = graphPanel.entitySvg.getEntityLocation(localRelationDragHandle.targetIdentifier); dragNodeX = closestEntityPoint[0]; dragNodeY = closestEntityPoint[1]; } Element relationHighlightGroup = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); relationHighlightGroup.setAttribute("id", "RelationHighlightGroup"); entityGroup.getParentNode().insertBefore(relationHighlightGroup, entityGroup); float vSpacing = graphPanel.graphPanelSize.getVerticalSpacing(); float hSpacing = graphPanel.graphPanelSize.getHorizontalSpacing(); // for (Node currentRelation = relationsGroup.getFirstChild(); currentRelation != null; currentRelation = currentRelation.getNextSibling()) { for (UniqueIdentifier uniqueIdentifier : graphPanel.selectedGroupId) { String dragLineElementId = "dragLine-" + uniqueIdentifier.getAttributeIdentifier(); float[] egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(uniqueIdentifier); // try creating a use node for the highlight (these use nodes do not get updated when a node is dragged and the colour attribute is ignored) // Element useNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "use"); // useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + polyLineElement.getAttribute("id")); // useNode.setAttributeNS(null, "stroke", "blue"); // relationHighlightGroup.appendChild(useNode); // try creating a new node based on the original lines attributes (these lines do not get updated when a node is dragged) // as a comprimise these highlighs can be removed when a node is dragged // add a white background Element highlightBackgroundLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline"); highlightBackgroundLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth)); highlightBackgroundLine.setAttribute("fill", "none"); // highlightBackgroundLine.setAttribute("points", polyLineElement.getAttribute("points")); highlightBackgroundLine.setAttribute("stroke", "white"); new RelationSvg().setPolylinePointsAttribute(null, dragLineElementId, highlightBackgroundLine, localRelationDragHandle.relationType, vSpacing, egoSymbolPoint[0], egoSymbolPoint[1], dragNodeX, dragNodeY); relationHighlightGroup.appendChild(highlightBackgroundLine); // add a blue dotted line Element highlightLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline"); highlightLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth)); highlightLine.setAttribute("fill", "none"); // highlightLine.setAttribute("points", highlightBackgroundLine.getAttribute("points")); new RelationSvg().setPolylinePointsAttribute(null, dragLineElementId, highlightLine, localRelationDragHandle.relationType, vSpacing, egoSymbolPoint[0], egoSymbolPoint[1], dragNodeX, dragNodeY); highlightLine.setAttribute("stroke", "blue"); highlightLine.setAttribute("stroke-dasharray", "3"); highlightLine.setAttribute("stroke-dashoffset", "0"); relationHighlightGroup.appendChild(highlightLine); } Element symbolNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "circle"); symbolNode.setAttribute("cx", Float.toString(dragNodeX)); symbolNode.setAttribute("cy", Float.toString(dragNodeY)); symbolNode.setAttribute("r", "5"); symbolNode.setAttribute("fill", "blue"); symbolNode.setAttribute("stroke", "none"); relationHighlightGroup.appendChild(symbolNode); } } // ArbilComponentBuilder.savePrettyFormatting(graphPanel.doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/desktop/src/main/resources/output.svg")); } protected void addRelationDragHandles(Element highlightGroupNode, SVGRect bbox, int paddingDistance) { for (DataTypes.RelationType relationType : new DataTypes.RelationType[]{DataTypes.RelationType.ancestor, DataTypes.RelationType.descendant}) { Element symbolNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "circle"); symbolNode.setAttribute("cx", Float.toString(bbox.getX() + bbox.getWidth() / 2)); switch (relationType) { case ancestor: symbolNode.setAttribute("cy", Float.toString(bbox.getY() - paddingDistance)); break; case descendant: symbolNode.setAttribute("cy", Float.toString(bbox.getY() + bbox.getHeight() + paddingDistance)); break; } symbolNode.setAttribute("r", "5"); symbolNode.setAttribute("handletype", relationType.name()); symbolNode.setAttribute("fill", "blue"); symbolNode.setAttribute("stroke", "none"); ((EventTarget) symbolNode).addEventListener("mousedown", graphPanel.mouseListenerSvg, false); highlightGroupNode.appendChild(symbolNode); } } protected void addGraphicsDragHandles(Element highlightGroupNode, UniqueIdentifier targetIdentifier, SVGRect bbox, int paddingDistance) { Element symbolNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "circle"); symbolNode.setAttribute("cx", Float.toString(bbox.getX() + bbox.getWidth() + paddingDistance)); symbolNode.setAttribute("cy", Float.toString(bbox.getY() + bbox.getHeight() + paddingDistance)); symbolNode.setAttribute("r", "5"); symbolNode.setAttribute("target", targetIdentifier.getAttributeIdentifier()); symbolNode.setAttribute("fill", "blue"); symbolNode.setAttribute("stroke", "none"); ((EventTarget) symbolNode).addEventListener("mousedown", graphPanel.mouseListenerSvg, false); highlightGroupNode.appendChild(symbolNode); } protected void updateSvgSelectionHighlights() { if (kinTermSavePanel != null) { String kinTypeStrings = ""; for (UniqueIdentifier entityID : graphPanel.selectedGroupId) { if (kinTypeStrings.length() != 0) { kinTypeStrings = kinTypeStrings + "|"; } kinTypeStrings = kinTypeStrings + graphPanel.getKinTypeForElementId(entityID); } if (kinTypeStrings != null) { kinTermSavePanel.setSelectedKinTypeSting(kinTypeStrings); } } UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); if (updateManager != null) { // todo: there may be issues related to the updateManager being null, this should be looked into if symptoms arise. updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() { public void run() { if (graphPanel.doc != null) { // for (String groupString : new String[]{"EntityGroup", "LabelsGroup"}) { // Element entityGroup = graphPanel.doc.getElementById(groupString); { boolean isLeadSelection = true; for (UniqueIdentifier currentIdentifier : highlightedIdentifiers.toArray(new UniqueIdentifier[]{})) { // remove old highlights but leave existing selections if (!graphPanel.selectedGroupId.contains(currentIdentifier)) { Element existingHighlight = graphPanel.doc.getElementById("highlight_" + currentIdentifier.getAttributeIdentifier()); if (existingHighlight != null) { existingHighlight.getParentNode().removeChild(existingHighlight); } highlightedIdentifiers.remove(currentIdentifier); } } for (UniqueIdentifier uniqueIdentifier : graphPanel.selectedGroupId) { Element selectedGroup = graphPanel.doc.getElementById(uniqueIdentifier.getAttributeIdentifier()); Element existingHighlight = graphPanel.doc.getElementById("highlight_" + uniqueIdentifier.getAttributeIdentifier()); // for (Node currentChild = entityGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) { // if ("g".equals(currentChild.getLocalName())) { // Node idAttrubite = currentChild.getAttributes().getNamedItem("id"); // if (idAttrubite != null) { // UniqueIdentifier entityId = new UniqueIdentifier(idAttrubite.getTextContent()); // System.out.println("group id: " + entityId.getAttributeIdentifier()); // Node existingHighlight = null; // find any existing highlight // for (Node subGoupNode = currentChild.getFirstChild(); subGoupNode != null; subGoupNode = subGoupNode.getNextSibling()) { // if ("g".equals(subGoupNode.getLocalName())) { // Node subGroupIdAttrubite = subGoupNode.getAttributes().getNamedItem("id"); // if (subGroupIdAttrubite != null) { // if ("highlight".equals(subGroupIdAttrubite.getTextContent())) { // existingHighlight = subGoupNode; // if (!graphPanel.selectedGroupId.contains(entityId)) { // remove all old highlights // if (existingHighlight != null) { // currentChild.removeChild(existingHighlight); // add the current highlights // } else { if (existingHighlight == null) { // svgCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); SVGRect bbox = ((SVGLocatable) selectedGroup).getBBox(); // System.out.println("bbox X: " + bbox.getX()); // System.out.println("bbox Y: " + bbox.getY()); // System.out.println("bbox W: " + bbox.getWidth()); // System.out.println("bbox H: " + bbox.getHeight()); Element highlightGroupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); highlightGroupNode.setAttribute("id", "highlight_" + uniqueIdentifier.getAttributeIdentifier()); Element symbolNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "rect"); int paddingDistance = 20; symbolNode.setAttribute("x", Float.toString(bbox.getX() - paddingDistance)); symbolNode.setAttribute("y", Float.toString(bbox.getY() - paddingDistance)); symbolNode.setAttribute("width", Float.toString(bbox.getWidth() + paddingDistance * 2)); symbolNode.setAttribute("height", Float.toString(bbox.getHeight() + paddingDistance * 2)); symbolNode.setAttribute("fill", "none"); symbolNode.setAttribute("stroke-width", "1"); //if (graphPanel.selectedGroupId.indexOf(entityId) == 0) { if (isLeadSelection) { symbolNode.setAttribute("stroke-dasharray", "3"); symbolNode.setAttribute("stroke-dashoffset", "0"); } else { symbolNode.setAttribute("stroke-dasharray", "6"); symbolNode.setAttribute("stroke-dashoffset", "0"); } symbolNode.setAttribute("stroke", "blue"); // if (graphPanel.dataStoreSvg.highlightRelationLines) { // // add highlights for relation lines // Element relationsGroup = graphPanel.doc.getElementById("RelationGroup"); // for (Node currentRelation = relationsGroup.getFirstChild(); currentRelation != null; currentRelation = currentRelation.getNextSibling()) { // Node dataElement = currentRelation.getFirstChild(); // NamedNodeMap dataAttributes = dataElement.getAttributes(); // if (dataAttributes.getNamedItemNS(DataStoreSvg.kinDataNameSpace, "lineType").getNodeValue().equals("sanguineLine")) { // if (entityId.equals(dataAttributes.getNamedItemNS(DataStoreSvg.kinDataNameSpace, "ego").getNodeValue()) || entityId.equals(dataAttributes.getNamedItemNS(DataStoreSvg.kinDataNameSpace, "alter").getNodeValue())) { // Element polyLineElement = (Element) dataElement.getNextSibling().getFirstChild(); // Element useNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "use"); // useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + polyLineElement.getAttribute("id")); // useNode.setAttributeNS(null, "stroke", "blue"); // highlightGroupNode.appendChild(useNode); // make sure the rect is added before the drag handles, otherwise the rect can block the mouse actions highlightGroupNode.appendChild(symbolNode); if (((Element) selectedGroup).getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "path").length() > 0) { addRelationDragHandles(highlightGroupNode, bbox, paddingDistance); } else { if (!"text".equals(selectedGroup.getLocalName())) { // add a drag handle for all graphics but not text nodes addGraphicsDragHandles(highlightGroupNode, uniqueIdentifier, bbox, paddingDistance); } } if ("g".equals(selectedGroup.getLocalName())) { selectedGroup.appendChild(highlightGroupNode); } else { highlightGroupNode.setAttribute("transform", selectedGroup.getAttribute("transform")); selectedGroup.getParentNode().appendChild(highlightGroupNode); } highlightedIdentifiers.add(uniqueIdentifier); } isLeadSelection = false; } updateSanguineHighlights(graphPanel.doc.getElementById("EntityGroup")); } } // Em:1:FMDH:1: // ArbilComponentBuilder.savePrettyFormatting(graphPanel.doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/desktop/src/main/resources/output.svg")); } }); } } protected void dragCanvas(int updateDragNodeXLocal, int updateDragNodeYLocal) { AffineTransform at = new AffineTransform(); at.translate(updateDragNodeXLocal, updateDragNodeYLocal); at.concatenate(graphPanel.svgCanvas.getRenderingTransform()); graphPanel.svgCanvas.setRenderingTransform(at); } protected void updateDragRelation(int updateDragNodeXLocal, int updateDragNodeYLocal) { // System.out.println("updateDragRelation: " + updateDragNodeXLocal + " : " + updateDragNodeYLocal); UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); synchronized (SvgUpdateHandler.this) { updateDragRelationX = updateDragNodeXLocal; updateDragRelationY = updateDragNodeYLocal; if (!relationThreadRunning) { relationThreadRunning = true; updateManager.getUpdateRunnableQueue().invokeLater(getRelationRunnable()); } } } private Runnable getRelationRunnable() { return new Runnable() { public void run() { Element entityGroup = graphPanel.doc.getElementById("EntityGroup"); int updateDragNodeXLocal = 0; int updateDragNodeYLocal = 0; while (updateDragNodeXLocal != updateDragRelationX && updateDragNodeYLocal != updateDragRelationY) { synchronized (SvgUpdateHandler.this) { updateDragNodeXLocal = updateDragRelationX; updateDragNodeYLocal = updateDragRelationY; } removeRelationHighLights(); removeEntityHighLights(); updateDragRelationLines(entityGroup, updateDragNodeXLocal, updateDragNodeYLocal); } synchronized (SvgUpdateHandler.this) { relationThreadRunning = false; } } }; } protected void startDrag() { // dragRemainders is used to store the remainder after snap between drag updates dragRemainders = null; } protected void updateDragNode(int updateDragNodeXLocal, int updateDragNodeYLocal) { resizeRequired = true; UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); synchronized (SvgUpdateHandler.this) { dragUpdateRequired = true; updateDragNodeX += updateDragNodeXLocal; updateDragNodeY += updateDragNodeYLocal; if (!threadRunning) { threadRunning = true; updateManager.getUpdateRunnableQueue().invokeLater(getRunnable()); } } } private Runnable getRunnable() { return new Runnable() { public void run() { if (dragRemainders == null) { dragRemainders = new float[graphPanel.selectedGroupId.size()][]; for (int dragCounter = 0; dragCounter < dragRemainders.length; dragCounter++) { dragRemainders[dragCounter] = new float[]{0, 0}; } } // Element relationOldHighlightGroup = graphPanel.doc.getElementById("RelationHighlightGroup"); // if (relationOldHighlightGroup != null) { // // remove the relation highlight group because lines will be out of date when the entities are moved // relationOldHighlightGroup.getParentNode().removeChild(relationOldHighlightGroup); Element entityGroup = graphPanel.doc.getElementById("EntityGroup"); boolean continueUpdating = true; while (continueUpdating) { continueUpdating = false; int updateDragNodeXInner; int updateDragNodeYInner; synchronized (SvgUpdateHandler.this) { dragUpdateRequired = false; updateDragNodeXInner = updateDragNodeX; updateDragNodeYInner = updateDragNodeY; updateDragNodeX = 0; updateDragNodeY = 0; } // System.out.println("updateDragNodeX: " + updateDragNodeXInner); // System.out.println("updateDragNodeY: " + updateDragNodeYInner); if (graphPanel.doc == null || graphPanel.dataStoreSvg.graphData == null) { GuiHelper.linorgBugCatcher.logError(new Exception("graphData or the svg document is null, is this an old file format? try redrawing before draging.")); } else { // if (relationDragHandleType != null) { // // drag relation handles //// updateSanguineHighlights(entityGroup); // removeHighLights(); // updateDragRelationLines(entityGroup, updateDragNodeXInner, updateDragNodeYInner); // } else { // drag the entities boolean allRealtionsSelected = true; relationLoop: for (EntityData selectedEntity : graphPanel.dataStoreSvg.graphData.getDataNodes()) { if (selectedEntity.isVisible && graphPanel.selectedGroupId.contains(selectedEntity.getUniqueIdentifier())) { for (EntityRelation entityRelation : selectedEntity.getVisiblyRelateNodes()) { EntityData relatedEntity = entityRelation.getAlterNode(); if (relatedEntity.isVisible && !graphPanel.selectedGroupId.contains(relatedEntity.getUniqueIdentifier())) { allRealtionsSelected = false; break relationLoop; } } } } int dragCounter = 0; for (UniqueIdentifier entityId : graphPanel.selectedGroupId) { // store the remainder after snap for re use on each update dragRemainders[dragCounter] = graphPanel.entitySvg.moveEntity(graphPanel, entityId, updateDragNodeXInner + dragRemainders[dragCounter][0], updateDragNodeYInner + dragRemainders[dragCounter][1], graphPanel.dataStoreSvg.snapToGrid, allRealtionsSelected); dragCounter++; } // Element entityGroup = doc.getElementById("EntityGroup"); // for (Node currentChild = entityGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) { // if ("g".equals(currentChild.getLocalName())) { // Node idAttrubite = currentChild.getAttributes().getNamedItem("id"); // if (idAttrubite != null) { // String entityPath = idAttrubite.getTextContent(); // if (selectedGroupElement.contains(entityPath)) { // SVGRect bbox = ((SVGLocatable) currentChild).getBBox(); //// ((SVGLocatable) currentDraggedElement).g // // drageboth x and y //// ((Element) currentChild).setAttribute("transform", "translate(" + String.valueOf(updateDragNodeXInner * svgCanvas.getRenderingTransform().getScaleX() - bbox.getX()) + ", " + String.valueOf(updateDragNodeYInner - bbox.getY()) + ")"); // // limit drag to x only // ((Element) currentChild).setAttribute("transform", "translate(" + String.valueOf(updateDragNodeXInner * svgCanvas.getRenderingTransform().getScaleX() - bbox.getX()) + ", 0)"); //// updateDragNodeElement.setAttribute("x", String.valueOf(updateDragNodeXInner)); //// updateDragNodeElement.setAttribute("y", String.valueOf(updateDragNodeYInner)); // // SVGRect bbox = ((SVGLocatable) currentDraggedElement).getBBox(); //// System.out.println("bbox X: " + bbox.getX()); //// System.out.println("bbox Y: " + bbox.getY()); //// System.out.println("bbox W: " + bbox.getWidth()); //// System.out.println("bbox H: " + bbox.getHeight()); //// todo: look into transform issues when dragging ellements eg when the canvas is scaled or panned //// SVGLocatable.getTransformToElement() //// SVGPoint.matrixTransform() int vSpacing = graphPanel.graphPanelSize.getVerticalSpacing(); // graphPanel.dataStoreSvg.graphData.gridHeight); int hSpacing = graphPanel.graphPanelSize.getHorizontalSpacing(); // graphPanel.dataStoreSvg.graphData.gridWidth); new RelationSvg().updateRelationLines(graphPanel, graphPanel.selectedGroupId, hSpacing, vSpacing); updateSanguineHighlights(entityGroup); //new CmdiComponentBuilder().savePrettyFormatting(doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/src/main/resources/output.svg")); } // graphPanel.updateCanvasSize(); // updating the canvas size here is too slow so it is moved into the drag ended // if (graphPanel.dataStoreSvg.graphData.isRedrawRequired()) { // this has been abandoned in favour of preventing dragging past zero // todo: update the position of all nodes // todo: any labels and other non entity graphics must also be taken into account here // for (EntityData selectedEntity : graphPanel.dataStoreSvg.graphData.getDataNodes()) { // if (selectedEntity.isVisible) { // graphPanel.entitySvg.moveEntity(graphPanel, selectedEntity.getUniqueIdentifier(), updateDragNodeXInner + dragRemainders[dragCounter][0], updateDragNodeYInner + dragRemainders[dragCounter][1], graphPanel.dataStoreSvg.snapToGrid, true); synchronized (SvgUpdateHandler.this) { continueUpdating = dragUpdateRequired; if (!continueUpdating) { threadRunning = false; } } } } }; } private void resizeCanvas(Element svgRoot, Element diagramGroupNode) { Rectangle graphSize = graphPanel.dataStoreSvg.graphData.getGraphSize(graphPanel.entitySvg.entityPositions); // set the diagram offset so that no element is less than zero diagramGroupNode.setAttribute("transform", "translate(" + Integer.toString(-graphSize.x) + ", " + Integer.toString(-graphSize.y) + ")"); // Set the width and height attributes on the root 'svg' element. svgRoot.setAttribute("width", Integer.toString(graphSize.width - graphSize.x)); svgRoot.setAttribute("height", Integer.toString(graphSize.height - graphSize.y)); if (graphPanel.dataStoreSvg.showDiagramBorder) { // draw hidious green and yellow rectangle for debugging Element pageBorderNode = graphPanel.doc.getElementById("PageBorder"); if (pageBorderNode == null) { pageBorderNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "rect"); pageBorderNode.setAttribute("id", "PageBorder"); pageBorderNode.setAttribute("x", Float.toString(graphSize.x + 2)); pageBorderNode.setAttribute("y", Float.toString(graphSize.y + 2)); pageBorderNode.setAttribute("width", Float.toString(graphSize.width - graphSize.x - 4)); pageBorderNode.setAttribute("height", Float.toString(graphSize.height - graphSize.y - 4)); pageBorderNode.setAttribute("fill", "none"); pageBorderNode.setAttribute("stroke-width", "2"); pageBorderNode.setAttribute("stroke", "grey"); diagramGroupNode.appendChild(pageBorderNode); } else { pageBorderNode.setAttribute("x", Float.toString(graphSize.x + 2)); pageBorderNode.setAttribute("y", Float.toString(graphSize.y + 2)); pageBorderNode.setAttribute("width", Float.toString(graphSize.width - graphSize.x - 4)); pageBorderNode.setAttribute("height", Float.toString(graphSize.height - graphSize.y - 4)); } // end draw hidious green rectangle for debugging } else { Element pageBorderNode = graphPanel.doc.getElementById("PageBorder"); if (pageBorderNode != null) { pageBorderNode.getParentNode().removeChild(pageBorderNode); } } } public void updateCanvasSize() { UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); if (updateManager != null) { updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() { public void run() { if (resizeRequired) { resizeRequired = false; Element svgRoot = graphPanel.doc.getDocumentElement(); Element diagramGroupNode = graphPanel.doc.getElementById("DiagramGroup"); resizeCanvas(svgRoot, diagramGroupNode); } } }); } } public void addGraphics(final GraphicsTypes graphicsType, final float xPos, final float yPos) { UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); if (updateManager != null) { updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() { public void run() { Rectangle graphSize; // if (graphPanel.dataStoreSvg.graphData == null) { // handle case where the diagram has not been drawn yet and the graph data and graph size is not available // graphSize = new Rectangle(0, 0, 0, 0); // } else { graphSize = graphPanel.dataStoreSvg.graphData.getGraphSize(graphPanel.entitySvg.entityPositions); Element labelText; switch (graphicsType) { case Circle: labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "circle"); labelText.setAttribute("r", "100"); labelText.setAttribute("fill", "#ffffff"); labelText.setAttribute("stroke", "#000000"); labelText.setAttribute("stroke-width", "2"); break; case Ellipse: labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "ellipse"); labelText.setAttribute("rx", "100"); labelText.setAttribute("ry", "100"); labelText.setAttribute("fill", "#ffffff"); labelText.setAttribute("stroke", "#000000"); labelText.setAttribute("stroke-width", "2"); break; case Label: labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "text"); labelText.setAttribute("fill", "#000000"); labelText.setAttribute("stroke-width", "0"); labelText.setAttribute("font-size", "28"); Text textNode = graphPanel.doc.createTextNode("Label"); labelText.appendChild(textNode); break; case Polyline: labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline"); break; case Square: labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "rect"); labelText.setAttribute("width", "100"); labelText.setAttribute("height", "100"); labelText.setAttribute("fill", "#ffffff"); labelText.setAttribute("stroke", "#000000"); labelText.setAttribute("stroke-width", "2"); break; default: return; } // * Rectangle <rect> // * Circle <circle> // * Ellipse <ellipse> // * Line <line> // * Polyline <polyline> // * Polygon <polygon> // * Path <path> UniqueIdentifier labelId = new UniqueIdentifier(UniqueIdentifier.IdentifierType.gid); // String labelIdString = "label" + labelGroup.getChildNodes().getLength(); float[] labelPosition = new float[]{graphSize.x + graphSize.width / 2, graphSize.y + graphSize.height / 2}; // labelText.setAttribute("x", "0"); // todo: update this to use the mouse click location // xPos // labelText.setAttribute("y", "0"); // yPos labelText.setAttribute("id", labelId.getAttributeIdentifier()); labelText.setAttribute("transform", "translate(" + Float.toString(labelPosition[0]) + ", " + Float.toString(labelPosition[1]) + ")"); // put this into the geometry group or the label group depending on its type so that labels sit above entitis and graphics sit below entities if (graphicsType.equals(GraphicsTypes.Label)) { Element labelGroup = graphPanel.doc.getElementById("LabelsGroup"); labelGroup.appendChild(labelText); } else { Element graphicsGroup = graphPanel.doc.getElementById("GraphicsGroup"); graphicsGroup.appendChild(labelText); } graphPanel.entitySvg.entityPositions.put(labelId, labelPosition); // graphPanel.doc.getDocumentElement().appendChild(labelText); ((EventTarget) labelText).addEventListener("mousedown", graphPanel.mouseListenerSvg, false); resizeCanvas(graphPanel.doc.getDocumentElement(), graphPanel.doc.getElementById("DiagramGroup")); } }); } } public void updateEntities() { UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); if (updateManager != null) { updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() { public void run() { drawEntities(); } }); } else { // on the first draw there will be on update manager drawEntities(); } } public void drawEntities() { // todo: this is public due to the requirements of saving files by users, but this should be done in a more thread safe way. graphPanel.dataStoreSvg.graphData.setPadding(graphPanel.graphPanelSize); graphPanel.lineLookUpTable = new LineLookUpTable(); int vSpacing = graphPanel.graphPanelSize.getVerticalSpacing(); //dataStoreSvg.graphData.gridHeight); int hSpacing = graphPanel.graphPanelSize.getHorizontalSpacing(); //dataStoreSvg.graphData.gridWidth); // currentWidth = graphPanelSize.getWidth(dataStoreSvg.graphData.gridWidth, hSpacing); // currentHeight = graphPanelSize.getHeight(dataStoreSvg.graphData.gridHeight, vSpacing); try { removeRelationHighLights(); Element svgRoot = graphPanel.doc.getDocumentElement(); Element diagramGroupNode = graphPanel.doc.getElementById("DiagramGroup"); if (diagramGroupNode == null) { // make sure the diagram group exists diagramGroupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); diagramGroupNode.setAttribute("id", "DiagramGroup"); svgRoot.appendChild(diagramGroupNode); } Element labelsGroup = graphPanel.doc.getElementById("LabelsGroup"); if (labelsGroup == null) { labelsGroup = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); labelsGroup.setAttribute("id", "LabelsGroup"); diagramGroupNode.appendChild(labelsGroup); } else if (!labelsGroup.getParentNode().equals(diagramGroupNode)) { labelsGroup.getParentNode().removeChild(labelsGroup); diagramGroupNode.appendChild(labelsGroup); } Element relationGroupNode; Element entityGroupNode; // if (doc == null) { // } else { Node relationGroupNodeOld = graphPanel.doc.getElementById("RelationGroup"); Node entityGroupNodeOld = graphPanel.doc.getElementById("EntityGroup"); // remove the old relation lines relationGroupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); relationGroupNode.setAttribute("id", "RelationGroup"); diagramGroupNode.insertBefore(relationGroupNode, labelsGroup); if (relationGroupNodeOld != null) { relationGroupNodeOld.getParentNode().removeChild(relationGroupNodeOld); } // remove the old entity symbols making sure the entities sit above the relations but below the labels entityGroupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); entityGroupNode.setAttribute("id", "EntityGroup"); diagramGroupNode.insertBefore(entityGroupNode, labelsGroup); if (entityGroupNodeOld != null) { entityGroupNodeOld.getParentNode().removeChild(entityGroupNodeOld); } // remove old kin diagram data NodeList dataNodes = graphPanel.doc.getElementsByTagNameNS("http://mpi.nl/tla/kin", "KinDiagramData"); for (int nodeCounter = 0; nodeCounter < dataNodes.getLength(); nodeCounter++) { dataNodes.item(nodeCounter).getParentNode().removeChild(dataNodes.item(nodeCounter)); } graphPanel.dataStoreSvg.graphData.placeAllNodes(graphPanel.entitySvg.entityPositions); resizeCanvas(svgRoot, diagramGroupNode); // entitySvg.removeOldEntities(relationGroupNode); // todo: find the real text size from batik // store the selected kin type strings and other data in the dom graphPanel.dataStoreSvg.storeAllData(graphPanel.doc); // new GraphPlacementHandler().placeAllNodes(this, dataStoreSvg.graphData.getDataNodes(), entityGroupNode, hSpacing, vSpacing); for (EntityData currentNode : graphPanel.dataStoreSvg.graphData.getDataNodes()) { if (currentNode.isVisible) { entityGroupNode.appendChild(graphPanel.entitySvg.createEntitySymbol(graphPanel, currentNode)); } } for (EntityData currentNode : graphPanel.dataStoreSvg.graphData.getDataNodes()) { if (currentNode.isVisible) { for (EntityRelation graphLinkNode : currentNode.getVisiblyRelateNodes()) { if ((graphPanel.dataStoreSvg.showKinTermLines || graphLinkNode.relationLineType != DataTypes.RelationLineType.kinTermLine) && (graphPanel.dataStoreSvg.showSanguineLines || graphLinkNode.relationLineType != DataTypes.RelationLineType.sanguineLine)) { new RelationSvg().insertRelation(graphPanel, relationGroupNode, currentNode, graphLinkNode, hSpacing, vSpacing); } } } } // todo: allow the user to set an entity as the provider of new dat being entered, this selected user can then be added to each field that is updated as the providence for that data. this would be best done in a cascading fashon so that there is a default informant for the entity and if required for sub nodes and fields // ArbilComponentBuilder.savePrettyFormatting(graphPanel.doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/desktop/src/main/resources/output.svg")); // svgCanvas.revalidate(); // svgUpdateHandler.updateSvgSelectionHighlights(); // todo: does this rsolve the issue after an update that the selection highlight is lost but the selection is still made? // zoomDrawing(); // if (zoomAffineTransform != null) { // // re apply the last zoom // // todo: asses why this does not work // svgCanvas.setRenderingTransform(zoomAffineTransform); } catch (DOMException exception) { GuiHelper.linorgBugCatcher.logError(exception); } // todo: this repaint might not resolve all cases of redraw issues graphPanel.svgCanvas.repaint(); // make sure no remnants are left over after the last redraw } }
package etomica.modules.glass; import etomica.data.*; import etomica.data.meter.*; import etomica.data.types.DataDouble; import etomica.data.types.DataFunction; import etomica.data.types.DataGroup; import etomica.data.types.DataTensor; import etomica.integrator.IntegratorHard; import etomica.integrator.IntegratorVelocityVerlet; import etomica.space.Vector; import etomica.units.dimensions.Null; import etomica.util.ParseArgs; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class GlassProd { public static void main(String[] args) { SimParams params = new SimParams(); if (args.length > 0) { ParseArgs.doParseArgs(params, args); } else { params.doSwap = true; params.potential = SimGlass.PotentialChoice.HS; params.nA = 50; params.nB = 50; params.density = 1.2; // 2D params.density = 0.509733; //3D = 0.69099; params.D = 3; params.temperature = 1.0; params.numStepsEq = 10000; params.numSteps = 100000; params.minDrFilter = 0.4; params.qx = 7.0; } SimGlass sim = new SimGlass(params.D, params.nA, params.nB, params.density, params.temperature, params.doSwap, params.potential, params.tStep); System.out.println(params.D +"D " + sim.potentialChoice); System.out.println("nA:nB = " + params.nA + ":" + params.nB); double volume = sim.box.getBoundary().volume(); int numAtoms = params.nA + params.nB; double rho= numAtoms/volume; System.out.println("T = " + params.temperature); System.out.println( params.numSteps + " MD steps after " + params.numStepsEq + " equilibaration steps , using dt = " + sim.integrator.getTimeStep()); //Equilibration double temperature0 = Math.max(params.temperatureMelt, params.temperature); if (temperature0 > params.temperature) System.out.println("Equilibrating at T=" + temperature0); sim.integrator.setIsothermal(true); sim.integrator.setIntegratorMC(sim.integratorMC, 1000); sim.integrator.setTemperature(temperature0); sim.activityIntegrate.setMaxSteps(params.numStepsEq); sim.getController().actionPerformed(); sim.getController().reset(); if (temperature0 > params.temperature) { System.out.println("Equilibrating at T=" + params.temperature); sim.integrator.setTemperature(params.temperature); sim.getController().actionPerformed(); sim.getController().reset(); } //Production sim.integrator.setIntegratorMC(null, 0); sim.integrator.setIsothermal(false); sim.activityIntegrate.setMaxSteps(params.numSteps); long blocksize = params.numSteps / 100; IDataSource pTensorMeter; if (sim.integrator instanceof IntegratorVelocityVerlet) { pTensorMeter = new MeterPressureTensorFromIntegrator(sim.getSpace()); ((MeterPressureTensorFromIntegrator) pTensorMeter).setIntegrator((IntegratorVelocityVerlet) sim.integrator); } else { pTensorMeter = new MeterPressureHardTensor(sim.getSpace()); ((MeterPressureHardTensor) pTensorMeter).setIntegrator((IntegratorHard) sim.integrator); new MeterPressureHard((IntegratorHard) sim.integrator); } //Viscosity DataFork pTensorFork = new DataFork(); int dn = 1; AccumulatorPTensor pTensorAccumVisc = new AccumulatorPTensor(sim.integrator, dn*sim.integrator.getTimeStep()); pTensorAccumVisc.setEnabled(true); pTensorFork.addDataSink(pTensorAccumVisc); DataPumpListener pTensorAccumViscPump = new DataPumpListener(pTensorMeter, pTensorFork, dn); AccumulatorAverageFixed gTensorAccumulator = new AccumulatorAverageFixed(blocksize); if (params.potential != SimGlass.PotentialChoice.HS) { DataProcessor dpSquared = new DataProcessor() { DataDouble data = new DataDouble(); @Override protected IData processData(IData inputData) { data.x = 0; int n = 0; for (int i = 0; i < params.D; i++) { for (int j = i + 1; j < params.D; j++) { double c = ((DataTensor) inputData).x.component(i, j); data.x += c * c; n++; } } data.x /= n; return data; } @Override protected IDataInfo processDataInfo(IDataInfo inputDataInfo) { dataInfo = new DataDouble.DataInfoDouble("G", Null.DIMENSION); return dataInfo; } }; pTensorFork.addDataSink(dpSquared); dpSquared.setDataSink(gTensorAccumulator); } sim.integrator.getEventManager().addListener(pTensorAccumViscPump); GlassGraphic.DataProcessorTensorTrace tracer = new GlassGraphic.DataProcessorTensorTrace(); pTensorFork.addDataSink(tracer); DataFork pFork = new DataFork(); tracer.setDataSink(pFork); AccumulatorAverageFixed pAccumulator = new AccumulatorAverageFixed(blocksize); pFork.setDataSink(pAccumulator); AccumulatorAverageFixed tAccumulator = null; AccumulatorAverageFixed accPE = null; if (sim.potentialChoice != SimGlass.PotentialChoice.HS) { MeterPotentialEnergy meterPE = new MeterPotentialEnergy(sim.integrator.getPotentialMaster(), sim.box); long bs = blocksize / 5; if (bs == 0) bs = 1; accPE = new AccumulatorAverageFixed(bs); DataPumpListener pumpPE = new DataPumpListener(meterPE, accPE, 5); sim.integrator.getEventManager().addListener(pumpPE); MeterTemperature tMeter = new MeterTemperature(sim, sim.box, params.D); tAccumulator = new AccumulatorAverageFixed(blocksize / 5); DataPumpListener tPump = new DataPumpListener(tMeter, tAccumulator, 5); tAccumulator.addDataSink(pTensorAccumVisc.makeTemperatureSink(), new AccumulatorAverage.StatType[]{tAccumulator.AVERAGE}); sim.integrator.getEventManager().addListener(tPump); } //shear stress AC AccumulatorAutocorrelationShearStress dpxyAutocor = new AccumulatorAutocorrelationShearStress(256, sim.integrator.getTimeStep()); boolean doPxyAutocor = params.doPxyAutocor && sim.potentialChoice != SimGlass.PotentialChoice.HS; if (doPxyAutocor) { pTensorFork.addDataSink(dpxyAutocor); } dpxyAutocor.setPushInterval(16384); //MSD ConfigurationStorage configStorageMSD = new ConfigurationStorage(sim.box, ConfigurationStorage.StorageType.MSD); configStorageMSD.setEnabled(true); ConfigurationStorage configStorageMSD3 = new ConfigurationStorage(sim.box, ConfigurationStorage.StorageType.MSD, 60, 3); configStorageMSD3.setEnabled(true); DataSourceMSD meterMSD = new DataSourceMSD(configStorageMSD); configStorageMSD.addListener(meterMSD); DataSourceMSD meterMSDA = new DataSourceMSD(configStorageMSD, sim.speciesA.getLeafType()); configStorageMSD.addListener(meterMSDA); DataSourceMSD meterMSDB = new DataSourceMSD(configStorageMSD, sim.speciesB.getLeafType()); configStorageMSD.addListener(meterMSDB); DataSourceCorMSD dsCorMSD = new DataSourceCorMSD(sim.integrator); dsCorMSD.setMinInterval(3); meterMSD.addMSDSink(dsCorMSD); dsCorMSD.setEnabled(true); DataSourceBlockAvgCor dsCorP = new DataSourceBlockAvgCor(sim.integrator); pFork.addDataSink(dsCorP); dsCorP.setEnabled(true); DataSourceMSDcorP dsMSDcorP = new DataSourceMSDcorP(sim.integrator); pFork.addDataSink(dsMSDcorP); meterMSD.addMSDSink(dsMSDcorP); dsMSDcorP.setEnabled(true); //VAC DataSourceVAC meterVAC = new DataSourceVAC(configStorageMSD); configStorageMSD.addListener(meterVAC); DataSourceFs meterFs = new DataSourceFs(configStorageMSD); Vector q = sim.getSpace().makeVector(); q.setX(0, params.qx); meterFs.setQ(q); configStorageMSD.addListener(meterFs); //Percolation AtomTestDeviation atomFilterDeviation = new AtomTestDeviation(sim.box, configStorageMSD); atomFilterDeviation.setMinDistance(params.minDrFilter); atomFilterDeviation.setDoMobileOnly(false); DataSourcePercolation meterPerc = new DataSourcePercolation(configStorageMSD, atomFilterDeviation, params.log2StepMin); configStorageMSD.addListener(meterPerc); AtomTestDeviation atomFilterDeviation3 = new AtomTestDeviation(sim.box, configStorageMSD3); atomFilterDeviation3.setMinDistance(params.minDrFilter); atomFilterDeviation3.setDoMobileOnly(false); DataSourcePercolation meterPerc3 = new DataSourcePercolation(configStorageMSD3, atomFilterDeviation3, params.log2StepMin, meterPerc.getHistogram()); configStorageMSD3.addListener(meterPerc3); DataSourcePercolation0 meterPerc0 = new DataSourcePercolation0(sim.box, sim.getRandom()); meterPerc0.setImmFracs(new double[]{0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.55, 0.65, 0.75, 0.85, 1}); AccumulatorAverageFixed accPerc0 = new AccumulatorAverageFixed(10); DataPumpListener pumpPerc0 = new DataPumpListener(meterPerc0, accPerc0, 10000); sim.integrator.getEventManager().addListener(pumpPerc0); DataSourceQ4 meterQ4 = new DataSourceQ4(configStorageMSD, 8); meterQ4.setMaxDr(0.2); configStorageMSD.addListener(meterQ4); //Strings DataSourceStrings meterL = new DataSourceStrings(configStorageMSD, 4); configStorageMSD.addListener(meterL); //Alpha2 DataSourceAlpha2 meterAlpha2 = new DataSourceAlpha2(configStorageMSD); configStorageMSD.addListener(meterAlpha2); AccumulatorAverageFixed accSFac = new AccumulatorAverageFixed(1); // just average, no uncertainty double cut1 = 10; if (numAtoms > 500) cut1 /= Math.pow(numAtoms / 500.0, 1.0 / sim.getSpace().D()); MeterStructureFactor meterSFac = new MeterStructureFactor(sim.box, cut1); meterSFac.setNormalizeByN(true); DataPumpListener pumpSFac = new DataPumpListener(meterSFac, accSFac, 1000); sim.integrator.getEventManager().addListener(pumpSFac); double vB = sim.getSpace().powerD(sim.sigmaB); ((MeterStructureFactor.AtomSignalSourceByType) meterSFac.getSignalSource()).setAtomTypeFactor(sim.speciesB.getAtomType(0), vB); AccumulatorAverageFixed[] accSFacMobility = new AccumulatorAverageFixed[30]; for (int i = 0; i < 30; i++) { AtomSignalMobility signalMobility = new AtomSignalMobility(configStorageMSD); signalMobility.setPrevConfig(i + 1); MeterStructureFactor meterSFacMobility = new MeterStructureFactor(sim.box, 3, signalMobility); meterSFacMobility.setNormalizeByN(true); DataFork forkSFacMobility = new DataFork(); DataPump pumpSFacMobility = new DataPump(meterSFacMobility, forkSFacMobility); accSFacMobility[i] = new AccumulatorAverageFixed(1); // just average, no uncertainty forkSFacMobility.addDataSink(accSFacMobility[i]); // ensures pump fires when config with delta t is available ConfigurationStoragePumper cspMobility = new ConfigurationStoragePumper(pumpSFacMobility, configStorageMSD); cspMobility.setPrevStep(Math.max(i, 9)); configStorageMSD.addListener(cspMobility); } AccumulatorAverageFixed[] accSFacMotion = new AccumulatorAverageFixed[30]; for (int i = 0; i < 30; i++) { AtomSignalMotion signalMotion = new AtomSignalMotion(configStorageMSD, 0); signalMotion.setPrevConfig(i + 1); MeterStructureFactor meterSFacMotion = new MeterStructureFactor(sim.box, 3, signalMotion); meterSFacMotion.setNormalizeByN(true); DataFork forkSFacMotion = new DataFork(); DataPump pumpSFacMotion = new DataPump(meterSFacMotion, forkSFacMotion); accSFacMotion[i] = new AccumulatorAverageFixed(1); // just average, no uncertainty forkSFacMotion.addDataSink(accSFacMotion[i]); // ensures pump fires when config with delta t is available ConfigurationStoragePumper cspMotion = new ConfigurationStoragePumper(pumpSFacMotion, configStorageMSD); cspMotion.setPrevStep(Math.max(i, 9)); configStorageMSD.addListener(cspMotion); } AtomStressSource stressSource = null; if (sim.potentialChoice == SimGlass.PotentialChoice.HS) { AtomHardStressCollector ahsc = new AtomHardStressCollector((IntegratorHard) sim.integrator); ((IntegratorHard) sim.integrator).addCollisionListener(ahsc); stressSource = ahsc; } else { PotentialCalculationForceSumGlass pcForce = new PotentialCalculationForceSumGlass(sim.box); ((IntegratorVelocityVerlet) sim.integrator).setForceSum(pcForce); stressSource = pcForce; } int[][] normalComps = new int[sim.getSpace().getD()][2]; for (int i = 0; i < normalComps.length; i++) { normalComps[i][0] = normalComps[i][1] = i; } AtomSignalStress signalStressNormal = new AtomSignalStress(stressSource, normalComps); Vector[] wv = meterSFac.getWaveVectors(); java.util.List<Vector> myWV = new ArrayList<>(); double L = sim.box.getBoundary().getBoxSize().getX(0); double wvMax2 = 8.01 * Math.PI / L; for (Vector vector : wv) { int nd = 0; for (int i = 0; i < vector.getD(); i++) if (vector.getX(i) != 0) nd++; if (vector.squared() > wvMax2 * wvMax2 || nd > 1) continue; myWV.add(vector); } int minIntervalSfac2 = 8; wv = myWV.toArray(new Vector[0]); int[] motionMap = StructureFactorComponentCorrelation.makeWaveVectorMap(wv, 0); int[] mobilityMap = StructureFactorComponentCorrelation.makeWaveVectorMap(wv, -1); MeterStructureFactor meterSFacStress2 = new MeterStructureFactor(sim.box, 3, signalStressNormal); meterSFacStress2.setNormalizeByN(true); meterSFacStress2.setWaveVec(wv); StructureFactorComponentCorrelation sfcStress2Cor = new StructureFactorComponentCorrelation(mobilityMap, configStorageMSD); sfcStress2Cor.setMinInterval(0); DataSinkBlockAveragerSFac dsbaSfacStress2 = new DataSinkBlockAveragerSFac(configStorageMSD, 0, meterSFacStress2); dsbaSfacStress2.addSink(sfcStress2Cor); DataPump pumpSFacStress2Cor = new DataPump(meterSFacStress2, dsbaSfacStress2); ConfigurationStoragePumper cspStress2 = new ConfigurationStoragePumper(pumpSFacStress2Cor, configStorageMSD); configStorageMSD.addListener(cspStress2); cspStress2.setPrevStep(0); DataSourceCorrelation dsCorSFacStress2Mobility = new DataSourceCorrelation(configStorageMSD, mobilityMap.length); dsbaSfacStress2.addSink(dsCorSFacStress2Mobility.makeReceiver(0)); MeterStructureFactor[] meterSFacMotion2 = new MeterStructureFactor[30]; StructureFactorComponentCorrelation sfcMotionCor = new StructureFactorComponentCorrelation(motionMap, configStorageMSD); sfcMotionCor.setMinInterval(minIntervalSfac2); MeterStructureFactor[] meterSFacMobility2 = new MeterStructureFactor[30]; StructureFactorComponentCorrelation sfcMobilityCor = new StructureFactorComponentCorrelation(mobilityMap, configStorageMSD); sfcMobilityCor.setMinInterval(minIntervalSfac2); MeterStructureFactor meterSFacDensity2 = new MeterStructureFactor(sim.box, 3); meterSFacDensity2.setNormalizeByN(true); meterSFacDensity2.setWaveVec(wv); StructureFactorComponentCorrelation sfcDensityCor = new StructureFactorComponentCorrelation(mobilityMap, configStorageMSD); sfcDensityCor.setMinInterval(0); DataSinkBlockAveragerSFac dsbaSfacDensity2 = new DataSinkBlockAveragerSFac(configStorageMSD, 0, meterSFacDensity2); dsbaSfacDensity2.addSink(sfcDensityCor); DataPump pumpSFacDensity2 = new DataPump(meterSFacDensity2, dsbaSfacDensity2); ConfigurationStoragePumper cspDensity2 = new ConfigurationStoragePumper(pumpSFacDensity2, configStorageMSD); configStorageMSD.addListener(cspDensity2); cspDensity2.setPrevStep(0); DataSourceCorrelation dsCorSFacDensityMobility = new DataSourceCorrelation(configStorageMSD, mobilityMap.length); dsbaSfacDensity2.addSink(dsCorSFacDensityMobility.makeReceiver(0)); MeterStructureFactor.AtomSignalSourceByType atomSignalPacking = new MeterStructureFactor.AtomSignalSourceByType(); atomSignalPacking.setAtomTypeFactor(sim.speciesB.getLeafType(), sim.potentialChoice == SimGlass.PotentialChoice.HS ? vB : 0); MeterStructureFactor meterSFacPacking2 = new MeterStructureFactor(sim.box, 3, atomSignalPacking); meterSFacPacking2.setNormalizeByN(true); meterSFacPacking2.setWaveVec(wv); StructureFactorComponentCorrelation sfcPackingCor = new StructureFactorComponentCorrelation(mobilityMap, configStorageMSD); sfcPackingCor.setMinInterval(0); DataSinkBlockAveragerSFac dsbaSfacPacking2 = new DataSinkBlockAveragerSFac(configStorageMSD, 0, meterSFacPacking2); dsbaSfacPacking2.addSink(sfcPackingCor); DataPump pumpSFacPacking2 = new DataPump(meterSFacPacking2, dsbaSfacPacking2); ConfigurationStoragePumper cspPacking2 = new ConfigurationStoragePumper(pumpSFacPacking2, configStorageMSD); configStorageMSD.addListener(cspPacking2); cspPacking2.setPrevStep(0); DataSourceCorrelation dsCorSFacPackingMobility = new DataSourceCorrelation(configStorageMSD, mobilityMap.length); dsbaSfacPacking2.addSink(dsCorSFacPackingMobility.makeReceiver(0)); DataSourceCorrelation dsCorSFacPackingDensity = new DataSourceCorrelation(configStorageMSD, mobilityMap.length); dsbaSfacPacking2.addSink(dsCorSFacPackingDensity.makeReceiver(0)); dsbaSfacDensity2.addSink(dsCorSFacPackingDensity.makeReceiver(1)); for (int i = 0; i < 30; i++) { AtomSignalMotion signalMotion = new AtomSignalMotion(configStorageMSD, 0); signalMotion.setPrevConfig(i + 1); meterSFacMotion2[i] = new MeterStructureFactor(sim.box, 3, signalMotion); meterSFacMotion2[i].setNormalizeByN(true); meterSFacMotion2[i].setWaveVec(wv); DataPump pumpSFacMotion2 = new DataPump(meterSFacMotion2[i], sfcMotionCor.makeSink(i, meterSFacMotion2[i])); ConfigurationStoragePumper cspMotion2 = new ConfigurationStoragePumper(pumpSFacMotion2, configStorageMSD); cspMotion2.setPrevStep(i); cspMotion2.setBigStep(minIntervalSfac2); configStorageMSD.addListener(cspMotion2); AtomSignalMobility signalMobility = new AtomSignalMobility(configStorageMSD); signalMobility.setPrevConfig(i + 1); meterSFacMobility2[i] = new MeterStructureFactor(sim.box, 3, signalMobility); meterSFacMobility2[i].setNormalizeByN(true); meterSFacMobility2[i].setWaveVec(wv); DataFork sfacMobility2Fork = new DataFork(); sfacMobility2Fork.addDataSink(sfcMobilityCor.makeSink(i, meterSFacMobility2[i])); DataPump pumpSFacMobility2 = new DataPump(meterSFacMobility2[i], sfacMobility2Fork); ConfigurationStoragePumper cspMobility2 = new ConfigurationStoragePumper(pumpSFacMobility2, configStorageMSD); cspMobility2.setPrevStep(i); cspMobility2.setBigStep(minIntervalSfac2); configStorageMSD.addListener(cspMobility2); sfacMobility2Fork.addDataSink(new StructorFactorComponentExtractor(meterSFacMobility2, i, dsCorSFacDensityMobility)); sfacMobility2Fork.addDataSink(new StructorFactorComponentExtractor(meterSFacMobility2, i, dsCorSFacPackingMobility)); sfacMobility2Fork.addDataSink(new StructorFactorComponentExtractor(meterSFacMobility2, i, dsCorSFacStress2Mobility)); } double xGsMax = 3; int gsMinConfig = 5; MeterGs meterGs = new MeterGs(configStorageMSD); meterGs.setMinConfigIndex(gsMinConfig); configStorageMSD.addListener(meterGs); meterGs.getXDataSource().setXMax(xGsMax); MeterGs meterGsA = new MeterGs(configStorageMSD); meterGsA.setAtomTypes(sim.speciesA.getLeafType()); meterGsA.setMinConfigIndex(gsMinConfig); configStorageMSD.addListener(meterGsA); meterGsA.getXDataSource().setXMax(xGsMax); MeterGs meterGsB = new MeterGs(configStorageMSD); meterGsB.setAtomTypes(sim.speciesB.getLeafType()); meterGsB.setMinConfigIndex(gsMinConfig); configStorageMSD.addListener(meterGsB); meterGsB.getXDataSource().setXMax(xGsMax); MeterCorrelationSelf meterCorrelationSelf = new MeterCorrelationSelf(configStorageMSD, MeterCorrelationSelf.CorrelationType.TOTAL); configStorageMSD.addListener(meterCorrelationSelf); MeterCorrelationSelf meterCorrelationSelfMagA = new MeterCorrelationSelf(configStorageMSD, MeterCorrelationSelf.CorrelationType.MAGNITUDE); meterCorrelationSelfMagA.setAtomType(sim.speciesA.getLeafType()); configStorageMSD.addListener(meterCorrelationSelfMagA); MeterCorrelationSelf meterCorrelationSelfMagB = new MeterCorrelationSelf(configStorageMSD, MeterCorrelationSelf.CorrelationType.MAGNITUDE); meterCorrelationSelfMagB.setAtomType(sim.speciesB.getLeafType()); configStorageMSD.addListener(meterCorrelationSelfMagB); CorrelationSelf2 correlationSelf2 = new CorrelationSelf2(configStorageMSD, CorrelationSelf2.CorrelationType.TOTAL, 0.001, 20); configStorageMSD.addListener(correlationSelf2); sim.integrator.getEventManager().addListener(configStorageMSD3); sim.integrator.getEventManager().addListener(configStorageMSD); //Run long time0 = System.nanoTime(); sim.getController().actionPerformed(); //Pressure DataGroup dataP = (DataGroup)pAccumulator.getData(); IData dataPAvg = dataP.getData(pAccumulator.AVERAGE.index); IData dataPErr = dataP.getData(pAccumulator.ERROR.index); IData dataPCorr = dataP.getData(pAccumulator.BLOCK_CORRELATION.index); double pAvg = dataPAvg.getValue(0); double pErr = dataPErr.getValue(0); double pCorr = dataPCorr.getValue(0); String filenameVisc, filenameMSD, filenameMSDA, filenameMSDB, filenameFs, filenamePerc, filenamePerc0, filenameImmFrac, filenameImmFracA, filenameImmFracB, filenameImmFracPerc, filenameL, filenameAlpha2, filenameSq, filenameVAC; String fileTag = ""; String filenamePxyAC = ""; if(sim.potentialChoice == SimGlass.PotentialChoice.HS){ double phi; if(params.D == 2){ phi = Math.PI/4*(params.nA+params.nB/(1.4*1.4))/volume; }else{ phi = Math.PI/6*(params.nA+params.nB/(1.4*1.4*1.4))/volume; } System.out.println("rho: " + params.density + " phi: " + phi+"\n"); System.out.println("Z: " + pAvg / params.density / params.temperature + " " + pErr / params.density / params.temperature + " cor: " + pCorr); fileTag = String.format("Rho%1.3f", rho); filenameVisc = String.format("viscRho%1.3f.out", rho); filenameMSD = String.format("msdRho%1.3f.out", rho); filenameMSDA = String.format("msdARho%1.3f.out", rho); filenameMSDB = String.format("msdBRho%1.3f.out", rho); filenameVAC = String.format("vacRho%1.3f.out", rho); filenameFs = String.format("fsRho%1.3fQ%1.2f.out", rho, params.qx); filenamePerc = String.format("percRho%1.3f.out", rho); filenamePerc0 = String.format("perc0Rho%1.3f.out", rho); filenameL = String.format("lRho%1.3f.out", rho); filenameImmFrac = String.format("immFracRho%1.3f.out", rho); filenameImmFracA = String.format("immFracARho%1.3f.out", rho); filenameImmFracB = String.format("immFracBRho%1.3f.out", rho); filenameImmFracPerc = String.format("immFracPercRho%1.3f.out", rho); filenameAlpha2 = String.format("alpha2Rho%1.3f.out", rho); filenameSq = String.format("sqRho%1.3f.out",rho); }else{ // Energy DataGroup dataU = (DataGroup) accPE.getData(); IData dataUAvg = dataU.getData(accPE.AVERAGE.index); IData dataUErr = dataU.getData(accPE.ERROR.index); IData dataUCorr = dataU.getData(accPE.BLOCK_CORRELATION.index); double uAvg = dataUAvg.getValue(0); double uErr = dataUErr.getValue(0); double uCorr = dataUCorr.getValue(0); //Pressure Tensor (G_inf) IData dataG = gTensorAccumulator.getData(); double avgG = dataG.getValue(gTensorAccumulator.AVERAGE.index); double errG = dataG.getValue(gTensorAccumulator.ERROR.index); double corG = dataG.getValue(gTensorAccumulator.BLOCK_CORRELATION.index); DataGroup dataT = (DataGroup)tAccumulator.getData(); IData dataTAvg = dataT.getData(tAccumulator.AVERAGE.index); IData dataTErr = dataT.getData(tAccumulator.ERROR.index); IData dataTCorr = dataT.getData(tAccumulator.BLOCK_CORRELATION.index); double tAvg = dataTAvg.getValue(0); double tErr = dataTErr.getValue(0); double tCorr = dataTCorr.getValue(0); System.out.println("rho: " + params.density+"\n"); System.out.println("T: " + tAvg +" "+ tErr +" cor: "+tCorr); System.out.println("Z: " + pAvg/params.density/tAvg +" "+ pErr/params.density/tAvg +" cor: "+pCorr); System.out.println("U: " + uAvg / numAtoms + " " + uErr / numAtoms + " cor: " + uCorr); fileTag = String.format("Rho%1.3fT%1.3f", rho, params.temperature); filenameVisc = String.format("viscRho%1.3fT%1.3f.out", rho, params.temperature); filenameMSD = String.format("msdRho%1.3fT%1.3f.out", rho, params.temperature); filenameMSDA = String.format("msdARho%1.3fT%1.3f.out", rho, params.temperature); filenameMSDB = String.format("msdBRho%1.3fT%1.3f.out", rho, params.temperature); filenameVAC = String.format("vacRho%1.3fT%1.3f.out", rho, params.temperature); filenameFs = String.format("fsRho%1.3fT%1.3fQ%1.2f.out", rho, params.temperature, params.qx); filenamePerc = String.format("percRho%1.3fT%1.3f.out", rho, params.temperature); filenamePerc0 = String.format("perc0Rho%1.3fT%1.3f.out", rho, params.temperature); filenameL = String.format("lRho%1.3fT%1.3f.out", rho, params.temperature); filenameImmFrac = String.format("immFracRho%1.3fT%1.3f.out", rho, params.temperature); filenameImmFracA = String.format("immFracARho%1.3fT%1.3f.out", rho, params.temperature); filenameImmFracB = String.format("immFracBRho%1.3fT%1.3f.out", rho, params.temperature); filenameImmFracPerc = String.format("immFracPercRho%1.3fT%1.3f.out", rho, params.temperature); filenameAlpha2 = String.format("alpha2Rho%1.3fT%1.3f.out", rho, params.temperature); filenamePxyAC = String.format("acPxyRho%1.3fT%1.3f.out", rho, params.temperature); filenameSq = String.format("sqRho%1.3fT%1.3f.out", rho, params.temperature); double V = sim.box.getBoundary().volume(); System.out.println("G: " + V * avgG / tAvg + " " + V * errG / tAvg + " cor: " + corG + "\n"); } System.out.println("P: " + pAvg +" "+ pErr +" cor: "+pCorr); try { if (doPxyAutocor) { GlassProd.writeDataToFile(dpxyAutocor, filenamePxyAC); } GlassProd.writeDataToFile(dsCorMSD, "MSDcor.dat"); GlassProd.writeDataToFile(dsCorP, "Pcor.dat"); GlassProd.writeDataToFile(dsMSDcorP, "MSDcorP.dat"); for (int i = 0; i < configStorageMSD.getLastConfigIndex() - 1; i++) { meterGs.setConfigIndex(i); GlassProd.writeDataToFile(meterGs, "Gs_t" + i + ".dat"); meterGsA.setConfigIndex(i); GlassProd.writeDataToFile(meterGsA, "GsA_t" + i + ".dat"); meterGsB.setConfigIndex(i); GlassProd.writeDataToFile(meterGsB, "GsB_t" + i + ".dat"); } for (int i = 0; i < accSFacMobility.length; i++) { if (accSFacMobility[i].getSampleCount() < 2) continue; GlassProd.writeDataToFile(accSFacMobility[i], "sfacMobility" + i + ".dat"); GlassProd.writeDataToFile(accSFacMotion[i], "sfacMotionx" + i + ".dat"); } double fac = L / (2 * Math.PI); int[] foo = new int[mobilityMap.length]; for (int j = 0; j < mobilityMap.length; j++) { String packing = sim.potentialChoice == SimGlass.PotentialChoice.HS ? "Packing" : "DensityA"; if (foo[mobilityMap[j]] != 0) continue; foo[mobilityMap[j]] = 1; String label = String.format("q%d%d%d.dat", Math.round(Math.abs(myWV.get(j).getX(0)) * fac), Math.round(Math.abs(myWV.get(j).getX(1)) * fac), Math.round(Math.abs(myWV.get(j).getX(2)) * fac)); StructureFactorComponentCorrelation.Meter m = sfcMobilityCor.makeMeter(mobilityMap[j]); GlassProd.writeDataToFile(m, "sfacMobilityCor_" + label); m = sfcDensityCor.makeMeter(mobilityMap[j]); GlassProd.writeDataToFile(m, "sfacDensityCor_" + label); m = sfcPackingCor.makeMeter(mobilityMap[j]); GlassProd.writeDataToFile(m, "sfac" + packing + "Cor_" + label); m = sfcStress2Cor.makeMeter(mobilityMap[j]); GlassProd.writeDataToFile(m, "sfacStressCor_" + label); DataSourceCorrelation.Meter mm = dsCorSFacDensityMobility.makeMeter(j); GlassProd.writeDataToFile(mm, "sfacDensityMobilityCor_" + label); mm = dsCorSFacPackingMobility.makeMeter(j); GlassProd.writeDataToFile(mm, "sfac" + packing + "MobilityCor_" + label); mm = dsCorSFacPackingDensity.makeMeter(j); GlassProd.writeDataToFile(mm, "sfac" + packing + "DensityCor_" + label); mm = dsCorSFacStress2Mobility.makeMeter(j); GlassProd.writeDataToFile(mm, "sfacStressMobilityCor_" + label); } foo = new int[motionMap.length]; for (int j = 0; j < motionMap.length; j++) { if (foo[motionMap[j]] != 0) continue; foo[motionMap[j]] = 1; String label = String.format("q%d%d%d.dat", Math.round(myWV.get(j).getX(0) * fac), Math.round(myWV.get(j).getX(1) * fac), Math.round(myWV.get(j).getX(2) * fac)); StructureFactorComponentCorrelation.Meter m = sfcMotionCor.makeMeter(motionMap[j]); GlassProd.writeDataToFile(m, "sfacMotionCor_" + label); } GlassProd.writeDataToFile(meterCorrelationSelf, "corSelf.dat"); GlassProd.writeDataToFile(meterCorrelationSelfMagA, "corSelfMagA.dat"); GlassProd.writeDataToFile(meterCorrelationSelfMagB, "corSelfMagB.dat"); for (int i = 0; i < correlationSelf2.getNumDt(); i++) { CorrelationSelf2.MeterCorrelationSelf2 m = correlationSelf2.makeMeter(i); GlassProd.writeDataToFile(m, "corRSelf_t" + i + ".dat"); } GlassProd.writeDataToFile(meterFs, filenameFs); GlassProd.writeCombinedDataToFile(new IDataSource[]{meterPerc, meterPerc3}, filenamePerc); GlassProd.writeCombinedDataToFile(new IDataSource[]{meterPerc.makeImmFractionSource(), meterPerc3.makeImmFractionSource()}, filenameImmFrac); GlassProd.writeCombinedDataToFile(new IDataSource[]{meterPerc.makeImmFractionSource(sim.speciesA.getLeafType()), meterPerc3.makeImmFractionSource(sim.speciesA.getLeafType())}, filenameImmFracA); GlassProd.writeCombinedDataToFile(new IDataSource[]{meterPerc.makeImmFractionSource(sim.speciesB.getLeafType()), meterPerc3.makeImmFractionSource(sim.speciesB.getLeafType())}, filenameImmFracB); GlassProd.writeDataToFile(meterPerc.makePerclationByImmFracSource(), filenameImmFracPerc); GlassProd.writeDataToFile(meterPerc0, filenamePerc0); GlassProd.writeDataToFile(meterQ4, "Q4" + fileTag + ".out"); GlassProd.writeDataToFile(meterL, filenameL); GlassProd.writeCombinedDataToFile(new IDataSource[]{meterPerc.makeChi4Source(), meterPerc3.makeChi4Source()}, "chi4Star" + fileTag + ".out"); GlassProd.writeDataToFile(meterQ4.makeChi4Meter(), "chi4" + fileTag + ".out"); GlassProd.writeDataToFile(meterAlpha2, filenameAlpha2); GlassProd.writeDataToFile(meterSFac, filenameSq); GlassProd.writeDataToFile(meterMSD, meterMSD.errData, filenameMSD); GlassProd.writeDataToFile(meterMSDA, meterMSDA.errData, filenameMSDA); GlassProd.writeDataToFile(meterMSDB, meterMSDB.errData, filenameMSDB); GlassProd.writeDataToFile(meterVAC, meterVAC.errData, filenameVAC); GlassProd.writeDataToFile(pTensorAccumVisc, pTensorAccumVisc.errData, filenameVisc); } catch (IOException e) { System.err.println("Cannot open a file, caught IOException: " + e.getMessage()); } long time1 = System.nanoTime(); double sim_time = (time1 - time0) / 1e9; System.out.println(String.format("\ntime: %3.2f s", sim_time)); } public static class SimParams extends SimGlass.GlassParams { public int numStepsEq = 10000; public int numSteps = 1000000; public double minDrFilter = 0.4; public int log2StepMin = 9; public double temperatureMelt = 0; public double qx = 7.0; public boolean doPxyAutocor = false; } public static void writeDataToFile(IDataSource meter, String filename) throws IOException { writeDataToFile(meter, null, filename); } public static void writeDataToFile(IDataSource meter, IData errData, String filename) throws IOException { IData data; IData xData; if (meter instanceof AccumulatorAverage) { AccumulatorAverage acc = (AccumulatorAverage) meter; data = acc.getData(acc.AVERAGE); xData = ((DataFunction.DataInfoFunction) ((DataGroup.DataInfoGroup) acc.getDataInfo()).getSubDataInfo(acc.AVERAGE.index)).getXDataSource().getIndependentData(0); } else { data = meter.getData(); xData = ((DataFunction.DataInfoFunction) meter.getDataInfo()).getXDataSource().getIndependentData(0); } boolean allNaN = true; for (int i = 0; i < xData.getLength(); i++) { if (!Double.isNaN(data.getValue(i))) allNaN = false; } if (allNaN) return; FileWriter fw = new FileWriter(filename); for (int i = 0; i < xData.getLength(); i++) { double y = data.getValue(i); if (Double.isNaN(y)) continue; if (errData == null) { fw.write(xData.getValue(i) + " " + y + "\n"); } else { fw.write(xData.getValue(i) + " " + y + " " + errData.getValue(i) + "\n"); } } fw.close(); } public static void writeCombinedDataToFile(IDataSource[] meters, String filename) { List<double[]> allData = new ArrayList<>(); for (int j = 0; j < meters.length; j++) { IData data = meters[j].getData(); IData xData = ((DataFunction.DataInfoFunction) meters[j].getDataInfo()).getXDataSource().getIndependentData(0); for (int i = 0; i < xData.getLength(); i++) { double y = data.getValue(i); if (Double.isNaN(y)) continue; allData.add(new double[]{xData.getValue(i), y}); } } allData.sort(new Comparator<double[]>() { @Override public int compare(double[] o1, double[] o2) { return Double.compare(o1[0], o2[0]); } }); try { FileWriter fw = new FileWriter(filename); for (double[] xy : allData) { fw.write(xy[0] + " " + xy[1] + "\n"); } fw.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } }
package nl.mpi.kinnate.svg; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.util.ArrayList; import java.util.HashSet; import nl.mpi.arbil.util.BugCatcherManager; import nl.mpi.arbil.util.MessageDialogHandler; import nl.mpi.kinnate.KinTermSavePanel; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.kindata.EntityRelation; import nl.mpi.kinnate.kindata.RelationTypeDefinition; import nl.mpi.kinnate.kindata.RelationTypeDefinition.CurveLineOrientation; import nl.mpi.kinnate.kintypestrings.KinType; import nl.mpi.kinnate.uniqueidentifiers.IdentifierException; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import org.apache.batik.bridge.UpdateManager; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.w3c.dom.events.EventTarget; import org.w3c.dom.svg.SVGLocatable; import org.w3c.dom.svg.SVGRect; public class SvgUpdateHandler { private GraphPanel graphPanel; private KinTermSavePanel kinTermSavePanel; private MessageDialogHandler dialogHandler; private boolean dragUpdateRequired = false; private boolean threadRunning = false; private boolean relationThreadRunning = false; private int updateDragNodeX = 0; private int updateDragNodeY = 0; private int updateDragRelationX = 0; private int updateDragRelationY = 0; private float[][] dragRemainders = null; private boolean resizeRequired = false; protected RelationDragHandle relationDragHandle = null; private HashSet<UniqueIdentifier> highlightedIdentifiers = new HashSet<UniqueIdentifier>(); public enum GraphicsTypes { Label, Circle, Square, Polyline, Ellipse // * Rectangle <rect> // * Circle <circle> // * Ellipse <ellipse> // * Line <line> // * Polyline <polyline> // * Polygon <polygon> // * Path <path> } public SvgUpdateHandler(GraphPanel graphPanel, KinTermSavePanel kinTermSavePanel, MessageDialogHandler dialogHandler) { this.graphPanel = graphPanel; this.kinTermSavePanel = kinTermSavePanel; this.dialogHandler = dialogHandler; } public void clearHighlights() { removeRelationHighLights(); for (UniqueIdentifier currentIdentifier : highlightedIdentifiers.toArray(new UniqueIdentifier[]{})) { // remove old highlights Element existingHighlight = graphPanel.doc.getElementById("highlight_" + currentIdentifier.getAttributeIdentifier()); if (existingHighlight != null) { existingHighlight.getParentNode().removeChild(existingHighlight); } highlightedIdentifiers.remove(currentIdentifier); } } private void removeRelationHighLights() { // this must be only called from within a svg runnable Element relationOldHighlightGroup = graphPanel.doc.getElementById("RelationHighlightGroup"); if (relationOldHighlightGroup != null) { // remove the relation highlight group relationOldHighlightGroup.getParentNode().removeChild(relationOldHighlightGroup); } } private void removeEntityHighLights() { for (Element entityHighlightGroup = graphPanel.doc.getElementById("highlight"); entityHighlightGroup != null; entityHighlightGroup = graphPanel.doc.getElementById("highlight")) { entityHighlightGroup.getParentNode().removeChild(entityHighlightGroup); } } private void updateSanguineHighlights(Element entityGroup) { // this must be only called from within a svg runnable removeRelationHighLights(); if (graphPanel.dataStoreSvg.highlightRelationLines) { // add highlights for relation lines Element relationHighlightGroup = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); relationHighlightGroup.setAttribute("id", "RelationHighlightGroup"); entityGroup.getParentNode().insertBefore(relationHighlightGroup, entityGroup); Element relationsGroup = graphPanel.doc.getElementById("RelationGroup"); for (Node currentRelation = relationsGroup.getFirstChild(); currentRelation != null; currentRelation = currentRelation.getNextSibling()) { Node dataElement = currentRelation.getFirstChild(); if (dataElement != null && dataElement.hasAttributes()) { NamedNodeMap dataAttributes = dataElement.getAttributes(); if (DataTypes.isSanguinLine(dataAttributes.getNamedItemNS(DataStoreSvg.kinDataNameSpace, "relationType").getNodeValue())) { Element polyLineElement = (Element) dataElement.getNextSibling().getFirstChild(); try { if (graphPanel.selectedGroupId.contains(new UniqueIdentifier(dataAttributes.getNamedItemNS(DataStoreSvg.kinDataNameSpace, "ego").getNodeValue())) || graphPanel.selectedGroupId.contains(new UniqueIdentifier(dataAttributes.getNamedItemNS(DataStoreSvg.kinDataNameSpace, "alter").getNodeValue()))) { // try creating a use node for the highlight (these use nodes do not get updated when a node is dragged and the colour attribute is ignored) // Element useNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "use"); // useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + polyLineElement.getAttribute("id")); // useNode.setAttributeNS(null, "stroke", "blue"); // relationHighlightGroup.appendChild(useNode); // try creating a new node based on the original lines attributes (these lines do not get updated when a node is dragged) // as a comprimise these highlighs can be removed when a node is dragged // add a white background Element highlightBackgroundLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline"); highlightBackgroundLine.setAttribute("stroke-width", polyLineElement.getAttribute("stroke-width")); highlightBackgroundLine.setAttribute("fill", polyLineElement.getAttribute("fill")); highlightBackgroundLine.setAttribute("points", polyLineElement.getAttribute("points")); highlightBackgroundLine.setAttribute("stroke", "white"); relationHighlightGroup.appendChild(highlightBackgroundLine); // add a blue dotted line Element highlightLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline"); highlightLine.setAttribute("stroke-width", polyLineElement.getAttribute("stroke-width")); highlightLine.setAttribute("fill", polyLineElement.getAttribute("fill")); highlightLine.setAttribute("points", polyLineElement.getAttribute("points")); highlightLine.setAttribute("stroke", "blue"); highlightLine.setAttribute("stroke-dasharray", "3"); highlightLine.setAttribute("stroke-dashoffset", "0"); relationHighlightGroup.appendChild(highlightLine); // try changing the target lines attributes (does not get updated maybe due to the 'use' node rendering) // polyLineElement.getAttributes().getNamedItem("stroke").setNodeValue("blue"); // polyLineElement.setAttributeNS(null, "stroke", "blue"); // polyLineElement.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth * 2)); } else { // polyLineElement.getAttributes().getNamedItem("stroke").setNodeValue("green"); // polyLineElement.setAttributeNS(null, "stroke", "grey"); // polyLineElement.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth)); } } catch (IdentifierException exception) { BugCatcherManager.getBugCatcher().logError(exception); dialogHandler.addMessageDialogToQueue("Failed to read relation data, highlight might not be correct", "Sanguine Highlights"); } } } } } } private void updateDragRelationLines(Element entityGroup, float localDragNodeX, float localDragNodeY) { // this must be only called from within a svg runnable RelationDragHandle localRelationDragHandle = relationDragHandle; if (localRelationDragHandle != null) { if (localRelationDragHandle instanceof GraphicsDragHandle) { ((GraphicsDragHandle) localRelationDragHandle).updatedElement(localDragNodeX, localDragNodeY); } else { float dragNodeX = localRelationDragHandle.getTranslatedX(localDragNodeX); float dragNodeY = localRelationDragHandle.getTranslatedY(localDragNodeY); localRelationDragHandle.targetIdentifier = graphPanel.entitySvg.getClosestEntity(new float[]{dragNodeX, dragNodeY}, 30, graphPanel.selectedGroupId); if (localRelationDragHandle.targetIdentifier != null) { float[] closestEntityPoint = graphPanel.entitySvg.getEntityLocation(localRelationDragHandle.targetIdentifier); dragNodeX = closestEntityPoint[0]; dragNodeY = closestEntityPoint[1]; } Element relationHighlightGroup = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); relationHighlightGroup.setAttribute("id", "RelationHighlightGroup"); entityGroup.getParentNode().insertBefore(relationHighlightGroup, entityGroup); float vSpacing = graphPanel.graphPanelSize.getVerticalSpacing(); float hSpacing = graphPanel.graphPanelSize.getHorizontalSpacing(); for (UniqueIdentifier uniqueIdentifier : graphPanel.selectedGroupId) { String dragLineElementId = "dragLine-" + uniqueIdentifier.getAttributeIdentifier(); float[] egoSymbolPoint;// = graphPanel.entitySvg.getEntityLocation(uniqueIdentifier); float[] parentPoint; // = graphPanel.entitySvg.getAverageParentLocation(uniqueIdentifier); float[] dragPoint; DataTypes.RelationType directedRelation = localRelationDragHandle.getRelationType(); if (directedRelation == DataTypes.RelationType.descendant) { // make sure the ancestral relations are unidirectional egoSymbolPoint = new float[]{dragNodeX, dragNodeY}; dragPoint = graphPanel.entitySvg.getEntityLocation(uniqueIdentifier); parentPoint = dragPoint; directedRelation = DataTypes.RelationType.ancestor; } else { egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(uniqueIdentifier); dragPoint = new float[]{dragNodeX, dragNodeY}; parentPoint = dragPoint; } // try creating a use node for the highlight (these use nodes do not get updated when a node is dragged and the colour attribute is ignored) // Element useNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "use"); // useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + polyLineElement.getAttribute("id")); // useNode.setAttributeNS(null, "stroke", "blue"); // relationHighlightGroup.appendChild(useNode); // try creating a new node based on the original lines attributes (these lines do not get updated when a node is dragged) // as a comprimise these highlighs can be removed when a node is dragged String svgLineType = (DataTypes.isSanguinLine(directedRelation)) ? "polyline" : "path"; // add a white background Element highlightBackgroundLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, svgLineType); highlightBackgroundLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth)); highlightBackgroundLine.setAttribute("fill", "none"); // highlightBackgroundLine.setAttribute("points", polyLineElement.getAttribute("points")); highlightBackgroundLine.setAttribute("stroke", "white"); if (DataTypes.isSanguinLine(directedRelation)) { new RelationSvg(dialogHandler).setPolylinePointsAttribute(null, dragLineElementId, highlightBackgroundLine, directedRelation, vSpacing, egoSymbolPoint[0], egoSymbolPoint[1], dragPoint[0], dragPoint[1], parentPoint); } else { new RelationSvg(dialogHandler).setPathPointsAttribute(highlightBackgroundLine, localRelationDragHandle.getCurveLineOrientation(), hSpacing, vSpacing, egoSymbolPoint[0], egoSymbolPoint[1], dragPoint[0], dragPoint[1]); } relationHighlightGroup.appendChild(highlightBackgroundLine); // add a blue dotted line Element highlightLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, svgLineType); highlightLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth)); highlightLine.setAttribute("fill", "none"); // highlightLine.setAttribute("points", highlightBackgroundLine.getAttribute("points")); if (DataTypes.isSanguinLine(directedRelation)) { new RelationSvg(dialogHandler).setPolylinePointsAttribute(null, dragLineElementId, highlightLine, directedRelation, vSpacing, egoSymbolPoint[0], egoSymbolPoint[1], dragPoint[0], dragPoint[1], parentPoint); } else { new RelationSvg(dialogHandler).setPathPointsAttribute(highlightLine, localRelationDragHandle.getCurveLineOrientation(), hSpacing, vSpacing, egoSymbolPoint[0], egoSymbolPoint[1], dragPoint[0], dragPoint[1]); } highlightLine.setAttribute("stroke", localRelationDragHandle.getRelationColour()); highlightLine.setAttribute("stroke-dasharray", "3"); highlightLine.setAttribute("stroke-dashoffset", "0"); relationHighlightGroup.appendChild(highlightLine); } Element symbolNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "circle"); symbolNode.setAttribute("cx", Float.toString(dragNodeX)); symbolNode.setAttribute("cy", Float.toString(dragNodeY)); symbolNode.setAttribute("r", "5"); symbolNode.setAttribute("fill", localRelationDragHandle.getRelationColour()); symbolNode.setAttribute("stroke", "none"); relationHighlightGroup.appendChild(symbolNode); } } // ArbilComponentBuilder.savePrettyFormatting(graphPanel.doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/desktop/src/main/resources/output.svg")); } protected void addRelationDragHandles(RelationTypeDefinition[] relationTypeDefinitions, Element highlightGroupNode, SVGRect bbox, int paddingDistance) { // add the standard relation types for (DataTypes.RelationType relationType : new DataTypes.RelationType[]{DataTypes.RelationType.ancestor, DataTypes.RelationType.descendant}) { Element symbolNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "circle"); symbolNode.setAttribute("cx", Float.toString(bbox.getX() + bbox.getWidth() / 2)); switch (relationType) { case ancestor: symbolNode.setAttribute("cy", Float.toString(bbox.getY() - paddingDistance)); break; case descendant: symbolNode.setAttribute("cy", Float.toString(bbox.getY() + bbox.getHeight() + paddingDistance)); break; } symbolNode.setAttribute("r", "5"); symbolNode.setAttribute("handletype", relationType.name()); symbolNode.setAttribute("fill", "blue"); symbolNode.setAttribute("stroke", "none"); ((EventTarget) symbolNode).addEventListener("mousedown", graphPanel.mouseListenerSvg, false); highlightGroupNode.appendChild(symbolNode); } // add the custom relation types float currentCX = bbox.getX() + bbox.getWidth() + paddingDistance; float minCY = bbox.getY() - paddingDistance; float currentCY = minCY; float stepC = 12; //(bbox.getHeight() + paddingDistance) / relationTypeDefinitions.length; float maxCY = bbox.getHeight() + paddingDistance; for (RelationTypeDefinition typeDefinition : relationTypeDefinitions) { // use a constant spacing between the drag handle dots and to start a new column when each line is full Element symbolNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "circle"); symbolNode.setAttribute("cx", Float.toString(currentCX)); symbolNode.setAttribute("cy", Float.toString(currentCY)); currentCY += stepC; if (currentCY >= maxCY) { currentCY = minCY; currentCX += stepC; } symbolNode.setAttribute("r", "5"); symbolNode.setAttribute("handletype", "custom:" + typeDefinition.hashCode()); symbolNode.setAttribute("fill", typeDefinition.getLineColour()); symbolNode.setAttribute("stroke", "none"); ((EventTarget) symbolNode).addEventListener("mousedown", graphPanel.mouseListenerSvg, false); highlightGroupNode.appendChild(symbolNode); } } protected void addGraphicsDragHandles(Element highlightGroupNode, UniqueIdentifier targetIdentifier, SVGRect bbox, int paddingDistance) { Element symbolNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "circle"); symbolNode.setAttribute("cx", Float.toString(bbox.getX() + bbox.getWidth() + paddingDistance)); symbolNode.setAttribute("cy", Float.toString(bbox.getY() + bbox.getHeight() + paddingDistance)); symbolNode.setAttribute("r", "5"); symbolNode.setAttribute("target", targetIdentifier.getAttributeIdentifier()); symbolNode.setAttribute("fill", "blue"); symbolNode.setAttribute("stroke", "none"); ((EventTarget) symbolNode).addEventListener("mousedown", graphPanel.mouseListenerSvg, false); highlightGroupNode.appendChild(symbolNode); } protected void updateSvgSelectionHighlights() { if (kinTermSavePanel != null) { String kinTypeStrings = ""; for (UniqueIdentifier entityID : graphPanel.selectedGroupId) { if (kinTypeStrings.length() != 0) { kinTypeStrings = kinTypeStrings + KinType.separator; } kinTypeStrings = kinTypeStrings + graphPanel.getKinTypeForElementId(entityID); } if (kinTypeStrings != null) { kinTermSavePanel.setSelectedKinTypeSting(kinTypeStrings); } } UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); if (updateManager != null) { // todo: there may be issues related to the updateManager being null, this should be looked into if symptoms arise. updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() { public void run() { if (graphPanel.doc != null) { // for (String groupString : new String[]{"EntityGroup", "LabelsGroup"}) { // Element entityGroup = graphPanel.doc.getElementById(groupString); { boolean isLeadSelection = true; for (UniqueIdentifier currentIdentifier : highlightedIdentifiers.toArray(new UniqueIdentifier[]{})) { // remove old highlights but leave existing selections if (!graphPanel.selectedGroupId.contains(currentIdentifier)) { Element existingHighlight = graphPanel.doc.getElementById("highlight_" + currentIdentifier.getAttributeIdentifier()); if (existingHighlight != null) { existingHighlight.getParentNode().removeChild(existingHighlight); } highlightedIdentifiers.remove(currentIdentifier); } } for (UniqueIdentifier uniqueIdentifier : graphPanel.selectedGroupId.toArray(new UniqueIdentifier[0])) { Element selectedGroup = graphPanel.doc.getElementById(uniqueIdentifier.getAttributeIdentifier()); Element existingHighlight = graphPanel.doc.getElementById("highlight_" + uniqueIdentifier.getAttributeIdentifier()); // for (Node currentChild = entityGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) { // if ("g".equals(currentChild.getLocalName())) { // Node idAttrubite = currentChild.getAttributes().getNamedItem("id"); // if (idAttrubite != null) { // UniqueIdentifier entityId = new UniqueIdentifier(idAttrubite.getTextContent()); // System.out.println("group id: " + entityId.getAttributeIdentifier()); // Node existingHighlight = null; // find any existing highlight // for (Node subGoupNode = currentChild.getFirstChild(); subGoupNode != null; subGoupNode = subGoupNode.getNextSibling()) { // if ("g".equals(subGoupNode.getLocalName())) { // Node subGroupIdAttrubite = subGoupNode.getAttributes().getNamedItem("id"); // if (subGroupIdAttrubite != null) { // if ("highlight".equals(subGroupIdAttrubite.getTextContent())) { // existingHighlight = subGoupNode; // if (!graphPanel.selectedGroupId.contains(entityId)) { // remove all old highlights // if (existingHighlight != null) { // currentChild.removeChild(existingHighlight); // add the current highlights // } else { if (existingHighlight == null && selectedGroup != null) { // svgCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); SVGRect bbox = ((SVGLocatable) selectedGroup).getBBox(); // System.out.println("bbox X: " + bbox.getX()); // System.out.println("bbox Y: " + bbox.getY()); // System.out.println("bbox W: " + bbox.getWidth()); // System.out.println("bbox H: " + bbox.getHeight()); Element highlightGroupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); ((EventTarget) highlightGroupNode).addEventListener("mousedown", graphPanel.mouseListenerSvg, false); highlightGroupNode.setAttribute("id", "highlight_" + uniqueIdentifier.getAttributeIdentifier()); Element symbolNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "rect"); int paddingDistance = 20; symbolNode.setAttribute("x", Float.toString(bbox.getX() - paddingDistance)); symbolNode.setAttribute("y", Float.toString(bbox.getY() - paddingDistance)); symbolNode.setAttribute("width", Float.toString(bbox.getWidth() + paddingDistance * 2)); symbolNode.setAttribute("height", Float.toString(bbox.getHeight() + paddingDistance * 2)); symbolNode.setAttribute("fill", "#999999"); // provide a fill so that the mouse selection extends to the bounding box, but but make it transparent symbolNode.setAttribute("fill-opacity", "0"); symbolNode.setAttribute("stroke-width", "1"); //if (graphPanel.selectedGroupId.indexOf(entityId) == 0) { if (isLeadSelection) { symbolNode.setAttribute("stroke-dasharray", "3"); symbolNode.setAttribute("stroke-dashoffset", "0"); } else { symbolNode.setAttribute("stroke-dasharray", "6"); symbolNode.setAttribute("stroke-dashoffset", "0"); } symbolNode.setAttribute("stroke", "blue"); // if (graphPanel.dataStoreSvg.highlightRelationLines) { // // add highlights for relation lines // Element relationsGroup = graphPanel.doc.getElementById("RelationGroup"); // for (Node currentRelation = relationsGroup.getFirstChild(); currentRelation != null; currentRelation = currentRelation.getNextSibling()) { // Node dataElement = currentRelation.getFirstChild(); // NamedNodeMap dataAttributes = dataElement.getAttributes(); // if (dataAttributes.getNamedItemNS(DataStoreSvg.kinDataNameSpace, "lineType").getNodeValue().equals("sanguineLine")) { // if (entityId.equals(dataAttributes.getNamedItemNS(DataStoreSvg.kinDataNameSpace, "ego").getNodeValue()) || entityId.equals(dataAttributes.getNamedItemNS(DataStoreSvg.kinDataNameSpace, "alter").getNodeValue())) { // Element polyLineElement = (Element) dataElement.getNextSibling().getFirstChild(); // Element useNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "use"); // useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + polyLineElement.getAttribute("id")); // useNode.setAttributeNS(null, "stroke", "blue"); // highlightGroupNode.appendChild(useNode); // make sure the rect is added before the drag handles, otherwise the rect can block the mouse actions highlightGroupNode.appendChild(symbolNode); if (((Element) selectedGroup).getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "path").length() > 0) { addRelationDragHandles(graphPanel.dataStoreSvg.getRelationTypeDefinitions(), highlightGroupNode, bbox, paddingDistance); } else { if (uniqueIdentifier.isGraphicsIdentifier()) { if (!"text".equals(selectedGroup.getLocalName())) { // add a drag handle for all graphics but not text nodes addGraphicsDragHandles(highlightGroupNode, uniqueIdentifier, bbox, paddingDistance); } } } if ("g".equals(selectedGroup.getLocalName())) { selectedGroup.appendChild(highlightGroupNode); } else { highlightGroupNode.setAttribute("transform", selectedGroup.getAttribute("transform")); selectedGroup.getParentNode().appendChild(highlightGroupNode); } highlightedIdentifiers.add(uniqueIdentifier); } isLeadSelection = false; } updateSanguineHighlights(graphPanel.doc.getElementById("EntityGroup")); } } // Em:1:FMDH:1: // ArbilComponentBuilder.savePrettyFormatting(graphPanel.doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/desktop/src/main/resources/output.svg")); } }); } } protected void dragCanvas(int updateDragNodeXLocal, int updateDragNodeYLocal) { AffineTransform at = new AffineTransform(); at.translate(updateDragNodeXLocal, updateDragNodeYLocal); at.concatenate(graphPanel.svgCanvas.getRenderingTransform()); graphPanel.svgCanvas.setRenderingTransform(at); } protected void updateDragRelation(int updateDragNodeXLocal, int updateDragNodeYLocal) { // System.out.println("updateDragRelation: " + updateDragNodeXLocal + " : " + updateDragNodeYLocal); UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); synchronized (SvgUpdateHandler.this) { updateDragRelationX = updateDragNodeXLocal; updateDragRelationY = updateDragNodeYLocal; if (!relationThreadRunning) { relationThreadRunning = true; updateManager.getUpdateRunnableQueue().invokeLater(getRelationRunnable()); } } } private Runnable getRelationRunnable() { return new Runnable() { public void run() { Element entityGroup = graphPanel.doc.getElementById("EntityGroup"); int updateDragNodeXLocal = 0; int updateDragNodeYLocal = 0; while (updateDragNodeXLocal != updateDragRelationX && updateDragNodeYLocal != updateDragRelationY) { synchronized (SvgUpdateHandler.this) { updateDragNodeXLocal = updateDragRelationX; updateDragNodeYLocal = updateDragRelationY; } removeRelationHighLights(); removeEntityHighLights(); updateDragRelationLines(entityGroup, updateDragNodeXLocal, updateDragNodeYLocal); } synchronized (SvgUpdateHandler.this) { relationThreadRunning = false; } } }; } protected void startDrag() { // dragRemainders is used to store the remainder after snap between drag updates // reset all remainders float[][] tempRemainders = new float[graphPanel.selectedGroupId.size()][]; for (int dragCounter = 0; dragCounter < tempRemainders.length; dragCounter++) { tempRemainders[dragCounter] = new float[]{0, 0}; } synchronized (SvgUpdateHandler.this) { dragRemainders = tempRemainders; } } protected void updateDragNode(int updateDragNodeXLocal, int updateDragNodeYLocal) { resizeRequired = true; UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); synchronized (SvgUpdateHandler.this) { dragUpdateRequired = true; updateDragNodeX += updateDragNodeXLocal; updateDragNodeY += updateDragNodeYLocal; if (!threadRunning) { threadRunning = true; updateManager.getUpdateRunnableQueue().invokeLater(getRunnable()); } } } private Runnable getRunnable() { return new Runnable() { public void run() { // Element relationOldHighlightGroup = graphPanel.doc.getElementById("RelationHighlightGroup"); // if (relationOldHighlightGroup != null) { // // remove the relation highlight group because lines will be out of date when the entities are moved // relationOldHighlightGroup.getParentNode().removeChild(relationOldHighlightGroup); Element entityGroup = graphPanel.doc.getElementById("EntityGroup"); boolean continueUpdating = true; while (continueUpdating) { continueUpdating = false; int updateDragNodeXInner; int updateDragNodeYInner; synchronized (SvgUpdateHandler.this) { dragUpdateRequired = false; updateDragNodeXInner = updateDragNodeX; updateDragNodeYInner = updateDragNodeY; updateDragNodeX = 0; updateDragNodeY = 0; } // System.out.println("updateDragNodeX: " + updateDragNodeXInner); // System.out.println("updateDragNodeY: " + updateDragNodeYInner); if (graphPanel.doc == null || graphPanel.dataStoreSvg.graphData == null) { BugCatcherManager.getBugCatcher().logError(new Exception("graphData or the svg document is null, is this an old file format? try redrawing before draging.")); } else { // if (relationDragHandleType != null) { // // drag relation handles //// updateSanguineHighlights(entityGroup); // removeHighLights(); // updateDragRelationLines(entityGroup, updateDragNodeXInner, updateDragNodeYInner); // } else { // drag the entities boolean allRealtionsSelected = true; relationLoop: for (EntityData selectedEntity : graphPanel.dataStoreSvg.graphData.getDataNodes()) { if (selectedEntity.isVisible && graphPanel.selectedGroupId.contains(selectedEntity.getUniqueIdentifier())) { for (EntityData relatedEntity : selectedEntity.getVisiblyRelated()) { if (relatedEntity.isVisible && !graphPanel.selectedGroupId.contains(relatedEntity.getUniqueIdentifier())) { allRealtionsSelected = false; break relationLoop; } } } } int dragCounter = 0; for (UniqueIdentifier entityId : graphPanel.selectedGroupId) { // store the remainder after snap for re use on each update synchronized (SvgUpdateHandler.this) { if (dragRemainders.length > dragCounter) { dragRemainders[dragCounter] = graphPanel.entitySvg.moveEntity(graphPanel, entityId, updateDragNodeXInner + dragRemainders[dragCounter][0], updateDragNodeYInner + dragRemainders[dragCounter][1], graphPanel.dataStoreSvg.snapToGrid, allRealtionsSelected); } } dragCounter++; } // Element entityGroup = doc.getElementById("EntityGroup"); // for (Node currentChild = entityGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) { // if ("g".equals(currentChild.getLocalName())) { // Node idAttrubite = currentChild.getAttributes().getNamedItem("id"); // if (idAttrubite != null) { // String entityPath = idAttrubite.getTextContent(); // if (selectedGroupElement.contains(entityPath)) { // SVGRect bbox = ((SVGLocatable) currentChild).getBBox(); //// ((SVGLocatable) currentDraggedElement).g // // drageboth x and y //// ((Element) currentChild).setAttribute("transform", "translate(" + String.valueOf(updateDragNodeXInner * svgCanvas.getRenderingTransform().getScaleX() - bbox.getX()) + ", " + String.valueOf(updateDragNodeYInner - bbox.getY()) + ")"); // // limit drag to x only // ((Element) currentChild).setAttribute("transform", "translate(" + String.valueOf(updateDragNodeXInner * svgCanvas.getRenderingTransform().getScaleX() - bbox.getX()) + ", 0)"); //// updateDragNodeElement.setAttribute("x", String.valueOf(updateDragNodeXInner)); //// updateDragNodeElement.setAttribute("y", String.valueOf(updateDragNodeYInner)); // // SVGRect bbox = ((SVGLocatable) currentDraggedElement).getBBox(); //// System.out.println("bbox X: " + bbox.getX()); //// System.out.println("bbox Y: " + bbox.getY()); //// System.out.println("bbox W: " + bbox.getWidth()); //// System.out.println("bbox H: " + bbox.getHeight()); //// todo: look into transform issues when dragging ellements eg when the canvas is scaled or panned //// SVGLocatable.getTransformToElement() //// SVGPoint.matrixTransform() int vSpacing = graphPanel.graphPanelSize.getVerticalSpacing(); // graphPanel.dataStoreSvg.graphData.gridHeight); int hSpacing = graphPanel.graphPanelSize.getHorizontalSpacing(); // graphPanel.dataStoreSvg.graphData.gridWidth); new RelationSvg(dialogHandler).updateRelationLines(graphPanel, graphPanel.selectedGroupId, hSpacing, vSpacing); updateSanguineHighlights(entityGroup); //new CmdiComponentBuilder().savePrettyFormatting(doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/src/main/resources/output.svg")); } // graphPanel.updateCanvasSize(); // updating the canvas size here is too slow so it is moved into the drag ended // if (graphPanel.dataStoreSvg.graphData.isRedrawRequired()) { // this has been abandoned in favour of preventing dragging past zero // todo: update the position of all nodes // todo: any labels and other non entity graphics must also be taken into account here // for (EntityData selectedEntity : graphPanel.dataStoreSvg.graphData.getDataNodes()) { // if (selectedEntity.isVisible) { // graphPanel.entitySvg.moveEntity(graphPanel, selectedEntity.getUniqueIdentifier(), updateDragNodeXInner + dragRemainders[dragCounter][0], updateDragNodeYInner + dragRemainders[dragCounter][1], graphPanel.dataStoreSvg.snapToGrid, true); synchronized (SvgUpdateHandler.this) { continueUpdating = dragUpdateRequired; if (!continueUpdating) { threadRunning = false; } } } graphPanel.setRequiresSave(); } }; } private void resizeCanvas(Element svgRoot, Element diagramGroupNode) { Rectangle graphSize = graphPanel.dataStoreSvg.graphData.getGraphSize(graphPanel.entitySvg.entityPositions); // set the diagram offset so that no element is less than zero diagramGroupNode.setAttribute("transform", "translate(" + Integer.toString(-graphSize.x) + ", " + Integer.toString(-graphSize.y) + ")"); // System.out.println("graphSize: " + graphSize.x + " : " + graphSize.y + " : " + graphSize.width + " : " + graphSize.height); // SVGRect bbox = ((SVGLocatable) svgRoot).getBBox(); // System.out.println("bbox X: " + bbox.getX()); // System.out.println("bbox Y: " + bbox.getY()); // System.out.println("bbox W: " + bbox.getWidth()); // System.out.println("bbox H: " + bbox.getHeight()); // graphSize.x = graphSize.x + (int) bbox.getX(); // graphSize.y = graphSize.y + (int) bbox.getY(); // svgRoot.setAttribute("viewBox", Float.toString(bbox.getX()) + " " + Float.toString(bbox.getY()) + " " + Float.toString(bbox.getWidth()) + " " + Float.toString(bbox.getHeight())); // viewBox="0.0 0.0 1024.0 768.0" // Set the width and height attributes on the root 'svg' element. svgRoot.setAttribute("width", Integer.toString(graphSize.width - graphSize.x)); svgRoot.setAttribute("height", Integer.toString(graphSize.height - graphSize.y)); if (graphPanel.dataStoreSvg.showDiagramBorder) { // draw a grey rectangle to show the diagram bounds Element pageBorderNode = graphPanel.doc.getElementById("PageBorder"); if (pageBorderNode == null) { pageBorderNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "rect"); pageBorderNode.setAttribute("id", "PageBorder"); pageBorderNode.setAttribute("x", Float.toString(graphSize.x + 2)); pageBorderNode.setAttribute("y", Float.toString(graphSize.y + 2)); pageBorderNode.setAttribute("width", Float.toString(graphSize.width - graphSize.x - 4)); pageBorderNode.setAttribute("height", Float.toString(graphSize.height - graphSize.y - 4)); pageBorderNode.setAttribute("fill", "none"); pageBorderNode.setAttribute("stroke-width", "2"); pageBorderNode.setAttribute("stroke", "grey"); diagramGroupNode.appendChild(pageBorderNode); } else { pageBorderNode.setAttribute("x", Float.toString(graphSize.x + 2)); pageBorderNode.setAttribute("y", Float.toString(graphSize.y + 2)); pageBorderNode.setAttribute("width", Float.toString(graphSize.width - graphSize.x - 4)); pageBorderNode.setAttribute("height", Float.toString(graphSize.height - graphSize.y - 4)); } // end draw a grey rectangle to show the diagram bounds } else { Element pageBorderNode = graphPanel.doc.getElementById("PageBorder"); if (pageBorderNode != null) { pageBorderNode.getParentNode().removeChild(pageBorderNode); } } } public void updateCanvasSize() { UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); if (updateManager != null) { updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() { public void run() { if (resizeRequired) { resizeRequired = false; Element svgRoot = graphPanel.doc.getDocumentElement(); Element diagramGroupNode = graphPanel.doc.getElementById("DiagramGroup"); resizeCanvas(svgRoot, diagramGroupNode); } } }); } } public void deleteGraphics(UniqueIdentifier uniqueIdentifier) { final Element graphicsElement = graphPanel.doc.getElementById(uniqueIdentifier.getAttributeIdentifier()); final Node parentElement = graphicsElement.getParentNode(); UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); if (updateManager != null) { updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() { public void run() { parentElement.removeChild(graphicsElement); graphPanel.setRequiresSave(); } }); } } public void addGraphics(final GraphicsTypes graphicsType, final float xPos, final float yPos) { UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); if (updateManager != null) { updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() { public void run() { Rectangle graphSize; // if (graphPanel.dataStoreSvg.graphData == null) { // handle case where the diagram has not been drawn yet and the graph data and graph size is not available // graphSize = new Rectangle(0, 0, 0, 0); // } else { graphSize = graphPanel.dataStoreSvg.graphData.getGraphSize(graphPanel.entitySvg.entityPositions); Element labelText; switch (graphicsType) { case Circle: labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "circle"); labelText.setAttribute("r", "100"); labelText.setAttribute("fill", "#ffffff"); labelText.setAttribute("stroke", "#000000"); labelText.setAttribute("stroke-width", "2"); break; case Ellipse: labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "ellipse"); labelText.setAttribute("rx", "100"); labelText.setAttribute("ry", "100"); labelText.setAttribute("fill", "#ffffff"); labelText.setAttribute("stroke", "#000000"); labelText.setAttribute("stroke-width", "2"); break; case Label: labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "text"); labelText.setAttribute("fill", "#000000"); labelText.setAttribute("stroke-width", "0"); labelText.setAttribute("font-size", "28"); Text textNode = graphPanel.doc.createTextNode("Label"); labelText.appendChild(textNode); break; case Polyline: labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline"); break; case Square: labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "rect"); labelText.setAttribute("width", "100"); labelText.setAttribute("height", "100"); labelText.setAttribute("fill", "#ffffff"); labelText.setAttribute("stroke", "#000000"); labelText.setAttribute("stroke-width", "2"); break; default: return; } // * Rectangle <rect> // * Circle <circle> // * Ellipse <ellipse> // * Line <line> // * Polyline <polyline> // * Polygon <polygon> // * Path <path> UniqueIdentifier labelId = new UniqueIdentifier(UniqueIdentifier.IdentifierType.gid); // String labelIdString = "label" + labelGroup.getChildNodes().getLength(); float[] labelPosition = new float[]{graphSize.x + graphSize.width / 2, graphSize.y + graphSize.height / 2}; // labelText.setAttribute("x", "0"); // todo: update this to use the mouse click location // xPos // labelText.setAttribute("y", "0"); // yPos labelText.setAttribute("id", labelId.getAttributeIdentifier()); labelText.setAttribute("transform", "translate(" + Float.toString(labelPosition[0]) + ", " + Float.toString(labelPosition[1]) + ")"); // put this into the geometry group or the label group depending on its type so that labels sit above entitis and graphics sit below entities if (graphicsType.equals(GraphicsTypes.Label)) { Element labelGroup = graphPanel.doc.getElementById("LabelsGroup"); labelGroup.appendChild(labelText); } else { Element graphicsGroup = graphPanel.doc.getElementById("GraphicsGroup"); graphicsGroup.appendChild(labelText); } graphPanel.entitySvg.entityPositions.put(labelId, labelPosition); // graphPanel.doc.getDocumentElement().appendChild(labelText); ((EventTarget) labelText).addEventListener("mousedown", graphPanel.mouseListenerSvg, false); resizeCanvas(graphPanel.doc.getDocumentElement(), graphPanel.doc.getElementById("DiagramGroup")); } }); } } public void updateEntities() { UpdateManager updateManager = graphPanel.svgCanvas.getUpdateManager(); if (updateManager != null) { updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() { public void run() { drawEntities(); } }); } else { // on the first draw there will be on update manager drawEntities(); } } public void drawEntities() { // todo: this is public due to the requirements of saving files by users, but this should be done in a more thread safe way. graphPanel.dataStoreSvg.graphData.setPadding(graphPanel.graphPanelSize); graphPanel.lineLookUpTable = new LineLookUpTable(); int vSpacing = graphPanel.graphPanelSize.getVerticalSpacing(); //dataStoreSvg.graphData.gridHeight); int hSpacing = graphPanel.graphPanelSize.getHorizontalSpacing(); //dataStoreSvg.graphData.gridWidth); // currentWidth = graphPanelSize.getWidth(dataStoreSvg.graphData.gridWidth, hSpacing); // currentHeight = graphPanelSize.getHeight(dataStoreSvg.graphData.gridHeight, vSpacing); try { removeRelationHighLights(); Element svgRoot = graphPanel.doc.getDocumentElement(); Element diagramGroupNode = graphPanel.doc.getElementById("DiagramGroup"); if (diagramGroupNode == null) { // make sure the diagram group exists diagramGroupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); diagramGroupNode.setAttribute("id", "DiagramGroup"); svgRoot.appendChild(diagramGroupNode); } Element labelsGroup = graphPanel.doc.getElementById("LabelsGroup"); if (labelsGroup == null) { labelsGroup = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); labelsGroup.setAttribute("id", "LabelsGroup"); diagramGroupNode.appendChild(labelsGroup); } else if (!labelsGroup.getParentNode().equals(diagramGroupNode)) { labelsGroup.getParentNode().removeChild(labelsGroup); diagramGroupNode.appendChild(labelsGroup); } Element relationGroupNode; Element entityGroupNode; // if (doc == null) { // } else { Node relationGroupNodeOld = graphPanel.doc.getElementById("RelationGroup"); Node entityGroupNodeOld = graphPanel.doc.getElementById("EntityGroup"); // remove the old relation lines relationGroupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); relationGroupNode.setAttribute("id", "RelationGroup"); diagramGroupNode.insertBefore(relationGroupNode, labelsGroup); if (relationGroupNodeOld != null) { relationGroupNodeOld.getParentNode().removeChild(relationGroupNodeOld); } // remove the old entity symbols making sure the entities sit above the relations but below the labels entityGroupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); entityGroupNode.setAttribute("id", "EntityGroup"); diagramGroupNode.insertBefore(entityGroupNode, labelsGroup); if (entityGroupNodeOld != null) { entityGroupNodeOld.getParentNode().removeChild(entityGroupNodeOld); } graphPanel.dataStoreSvg.graphData.placeAllNodes(graphPanel.entitySvg.entityPositions); resizeCanvas(svgRoot, diagramGroupNode); // entitySvg.removeOldEntities(relationGroupNode); // todo: find the real text size from batik // store the selected kin type strings and other data in the dom graphPanel.dataStoreSvg.storeAllData(graphPanel.doc); // new GraphPlacementHandler().placeAllNodes(this, dataStoreSvg.graphData.getDataNodes(), entityGroupNode, hSpacing, vSpacing); for (EntityData currentNode : graphPanel.dataStoreSvg.graphData.getDataNodes()) { if (currentNode.isVisible) { entityGroupNode.appendChild(graphPanel.entitySvg.createEntitySymbol(graphPanel, currentNode)); } } RelationSvg relationSvg = new RelationSvg(dialogHandler); ArrayList<String> doneRelations = new ArrayList<String>(); for (EntityData currentNode : graphPanel.dataStoreSvg.graphData.getDataNodes()) { if (currentNode.isVisible) { for (EntityRelation graphLinkNode : currentNode.getAllRelations()) { if ((graphPanel.dataStoreSvg.showKinTermLines || graphLinkNode.getRelationType() != DataTypes.RelationType.kinterm) && (graphPanel.dataStoreSvg.showSanguineLines || !DataTypes.isSanguinLine(graphLinkNode.getRelationType())) && (graphLinkNode.getAlterNode() != null && graphLinkNode.getAlterNode().isVisible)) { // make directed and exclude any lines that are already done DataTypes.RelationType directedRelation = graphLinkNode.getRelationType(); EntityData leftEntity; EntityData rightEntity; if (graphLinkNode.getRelationType() == DataTypes.RelationType.descendant) { // make sure the ancestral relations are unidirectional directedRelation = DataTypes.RelationType.ancestor; leftEntity = graphLinkNode.getAlterNode(); rightEntity = currentNode; } else if (graphLinkNode.getRelationType() == DataTypes.RelationType.ancestor) { // make sure the ancestral relations are unidirectional leftEntity = currentNode; rightEntity = graphLinkNode.getAlterNode(); } else if (currentNode.getUniqueIdentifier().getQueryIdentifier().compareTo(graphLinkNode.getAlterNode().getUniqueIdentifier().getQueryIdentifier()) > 0) { // make sure all other relations are directed by the string sort order so that they can be made unique leftEntity = graphLinkNode.getAlterNode(); rightEntity = currentNode; } else { // make sure all other relations are directed by the string sort order so that they can be made unique leftEntity = currentNode; rightEntity = graphLinkNode.getAlterNode(); } String compoundIdentifier = leftEntity.getUniqueIdentifier().getQueryIdentifier() + rightEntity.getUniqueIdentifier().getQueryIdentifier() + directedRelation.name() + ":" + graphLinkNode.dcrType + ":" + graphLinkNode.customType; // make sure each equivalent relation is drawn only once if (!doneRelations.contains(compoundIdentifier)) { boolean skipCurrentRelation = false; if (DataTypes.isSanguinLine(graphLinkNode.getRelationType())) { if (relationSvg.hasCommonParent(leftEntity, graphLinkNode)) { // do not draw lines for siblings if the common parent is visible because the ancestor lines will take the place of the sibling lines skipCurrentRelation = true; } } if (!skipCurrentRelation) { doneRelations.add(compoundIdentifier); String lineColour = graphLinkNode.lineColour; CurveLineOrientation curveLineOrientation = CurveLineOrientation.horizontal; int lineWidth = EntitySvg.strokeWidth; if (lineColour == null) { for (RelationTypeDefinition relationTypeDefinition : graphPanel.dataStoreSvg.getRelationTypeDefinitions()) { if (relationTypeDefinition.matchesType(graphLinkNode)) { lineColour = relationTypeDefinition.getLineColour(); lineWidth = relationTypeDefinition.getLineWidth(); curveLineOrientation = relationTypeDefinition.getCurveLineOrientation(); break; } } } relationSvg.insertRelation(graphPanel, relationGroupNode, leftEntity, rightEntity, directedRelation, lineWidth, curveLineOrientation, lineColour, graphLinkNode.labelString, hSpacing, vSpacing); } } } } } } // todo: allow the user to set an entity as the provider of new dat being entered, this selected user can then be added to each field that is updated as the providence for that data. this would be best done in a cascading fashon so that there is a default informant for the entity and if required for sub nodes and fields // ArbilComponentBuilder.savePrettyFormatting(graphPanel.doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/desktop/src/main/resources/output.svg")); // svgCanvas.revalidate(); // svgUpdateHandler.updateSvgSelectionHighlights(); // todo: does this rsolve the issue after an update that the selection highlight is lost but the selection is still made? // zoomDrawing(); // if (zoomAffineTransform != null) { // // re apply the last zoom // // todo: asses why this does not work // svgCanvas.setRenderingTransform(zoomAffineTransform); } catch (DOMException exception) { BugCatcherManager.getBugCatcher().logError(exception); } // todo: this repaint might not resolve all cases of redraw issues graphPanel.svgCanvas.repaint(); // make sure no remnants are left over after the last redraw } }
package etomica.modules.clustergenerator; import etomica.virial.cluster.ClusterDiagram; //import etomica.virial.simulations.GenCluster; public class ClusterPanel extends Plot { private double[] x; private double[] y; private boolean drawPoints; private boolean drawNumbersWhite, drawNumbersBlack; private final boolean fBonds, eBonds; private ClusterDiagram cluster; public ClusterPanel(ClusterDiagram aCluster,boolean drawPoints, boolean drawNumbersWhite, boolean drawNumbersWBlack, boolean fDrawBonds, boolean eDrawBonds) { super(null,400,400); cluster = aCluster; x = new double[cluster.mNumBody]; y = new double[cluster.mNumBody]; this.drawPoints = drawPoints; this.drawNumbersWhite = drawNumbersWhite; this.drawNumbersBlack = drawNumbersWBlack; fBonds = fDrawBonds; eBonds = eDrawBonds; } public ClusterDiagram getCluster(){ return cluster; } public void paint(){ int nPoints = cluster.mNumBody; clear(); double size=1.3; double max=13.0; double r = 8.0; double rotateAngle = 2.0*Math.PI/nPoints; double angle = -Math.PI/2.0 - rotateAngle*((cluster.getNumRootPoints()-1)*0.5); setWindow(-max,max,-max,max); for(int i=0; i<nPoints;i++){ x[i]=-r*Math.cos(angle+(i*rotateAngle));y[i]=r*Math.sin(angle+(i*rotateAngle)); } for (int i=0; i<nPoints; i++) { int lastBond = i; int[] iConnections = cluster.mConnections[i]; for (int j=0; j<nPoints-1; j++) { if (iConnections[j] > i) { if (eBonds) { setColor("red"); for (int k=lastBond+1; k<iConnections[j]; k++) { if (!cluster.isRootPoint(i) || !cluster.isRootPoint(k)) { plotLine(x[i],y[i], x[k],y[k]); } } setColor("black"); } if (fBonds) { plotLine(x[i],y[i] , x[iConnections[j]],y[iConnections[j]]); } lastBond = iConnections[j]; } else if ((lastBond>i || iConnections[j] == -1) && eBonds) { setColor("red"); for (int k=lastBond+1; k<nPoints; k++) { if (!cluster.isRootPoint(i) || !cluster.isRootPoint(k)) { plotLine(x[i],y[i], x[k],y[k]); } } setColor("black"); } if (iConnections[j] == -1) break; } } setColor("black"); for(int i=0; i<nPoints;i++){ if (drawPoints) { if(i < cluster.getNumRootPoints()) { setColor("white"); floodInside(x[i]-size,x[i]+size,y[i]-size,y[i]+size); setColor("black"); circle(x[i]-size,x[i]+size,y[i]-size,y[i]+size); } else { floodCircle(x[i]-size,x[i]+size,y[i]-size,y[i]+size); } } if(i < cluster.getNumRootPoints() && drawNumbersWhite) { plotStringCenter(Integer.toString(i),(-r*1.4)*Math.cos(angle+(i*rotateAngle))-0.2,(r*1.4)*Math.sin(angle+(i*rotateAngle))-1.0); } else if(i >= cluster.getNumRootPoints() && drawNumbersBlack){ plotStringCenter(Integer.toString(i),(-r*1.4)*Math.cos(angle+(i*rotateAngle))-0.2,(r*1.4)*Math.sin(angle+(i*rotateAngle))-1.0); } } } }
package org.aksw.mlbenchmark.config; import java.util.Iterator; import org.apache.commons.configuration2.Configuration; import org.apache.commons.lang3.StringUtils; public class DebugUtils { public static void printConfig(Configuration conf) { System.out.println(configToString(conf)); } public static String configToString(Configuration conf) { StringBuilder res = new StringBuilder(); Iterator<String> it = conf.getKeys(); while (it.hasNext()) { String k = it.next(); res.append(k); res.append(" = "); String[] v = conf.getStringArray(k); res.append(StringUtils.join(v, ',')); res.append('\n'); } return res.toString(); } }
package net.miz_hi.smileessence.menu; import net.miz_hi.smileessence.activity.MainActivity; import net.miz_hi.smileessence.core.UiHandler; import net.miz_hi.smileessence.data.StatusModel; import net.miz_hi.smileessence.dialog.DialogAdapter; import android.app.Activity; public class StatusMenuAddReply extends StatusMenuItemBase { public StatusMenuAddReply(Activity activity, DialogAdapter adapter, StatusModel model) { super(activity, adapter, model); } @Override public boolean isVisible() { return true; } @Override public String getText() { return "vCɒlj"; } @Override public void work() { MainActivity.getInstance().openTweetViewToReply(model.screenName, -1, true); new UiHandler() { @Override public void run() { MainActivity.getInstance().closeTweetView(); } }.postDelayed(800); } }
package net.thegreshams.openstates4j.service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.thegreshams.openstates4j.model.Bill; import net.thegreshams.openstates4j.model.Committee; import net.thegreshams.openstates4j.model.District; import net.thegreshams.openstates4j.model.District.Boundary; import net.thegreshams.openstates4j.model.Event; import org.apache.log4j.Logger; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; public class OpenStates { protected static final Logger LOGGER = Logger.getRootLogger(); private final String baseUrl = "http://openstates.org/api/v1/"; private final String apiKey; private final ObjectMapper mapper; // API public OpenStates( String apiKey ) { this.apiKey = apiKey; this.mapper = new ObjectMapper(); SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); this.mapper.setDateFormat( sdf ); } // BILLS public List<Bill> findBills( Map<String, String> queryParameters ) throws OpenStatesException { LOGGER.debug( "getting bills using query-parameters: " + queryParameters ); StringBuilder sbQueryPath = new StringBuilder( "bills" ); return this.queryForJsonAndBuildObject( sbQueryPath.toString(), queryParameters, new TypeReference<List<Bill>>(){} ); } public List<Bill> getBill( String stateAbbr, String session, String chamber, String billId ) throws OpenStatesException { return null; } // COMMITTEES public List<Committee> findCommittees( Map<String, String> queryParameters ) throws OpenStatesException { LOGGER.debug( "getting committees using query-parameters: " + queryParameters ); StringBuilder sbQueryPath = new StringBuilder( "committees" ); return this.queryForJsonAndBuildObject( sbQueryPath.toString(), queryParameters, new TypeReference<List<Committee>>(){} ); } public Committee getCommittee( String committeeId ) throws OpenStatesException { LOGGER.debug( "getting committee for committee-id(" + committeeId + ")" ); StringBuilder sbQueryPath = new StringBuilder( "committees/" + committeeId ); return this.queryForJsonAndBuildObject( sbQueryPath.toString(), Committee.class ); } // EVENTS public List<Event> findEvents( Map<String, String> queryParameters ) throws OpenStatesException { LOGGER.debug( "getting events using query-parameters: " + queryParameters ); StringBuilder sbQueryPath = new StringBuilder( "events" ); return this.queryForJsonAndBuildObject( sbQueryPath.toString(), queryParameters, new TypeReference<List<Event>>(){} ); } public Event getEvent( String eventId ) throws OpenStatesException { LOGGER.debug( "finding event for event-id(" + eventId + ")" ); StringBuilder sbQueryPath = new StringBuilder( "events/" + eventId ); return this.queryForJsonAndBuildObject( sbQueryPath.toString(), Event.class ); } // DISTRICTS public List<District> findDistricts( String stateAbbr ) throws OpenStatesException { return this.findDistricts( stateAbbr, null ); } public List<District> findDistricts( String stateAbbr, String chamber ) throws OpenStatesException { LOGGER.debug( "finding districts for state(" + stateAbbr + ") and chamber(" + chamber + ")" ); StringBuilder sbQueryPath = new StringBuilder( "districts/" + stateAbbr ); if( chamber != null ) { sbQueryPath.append( "/" + chamber ); } return this.queryForJsonAndBuildObject( sbQueryPath.toString(), new TypeReference<List<District>>(){} ); } public Boundary getBoundary( District district ) throws OpenStatesException { return this.getBoundary( district.boundaryId ); } public Boundary getBoundary( String boundaryId ) throws OpenStatesException { LOGGER.debug( "getting boundary for boundary-id(" + boundaryId + ")" ); StringBuilder sbQueryPath = new StringBuilder( "districts/boundary/" + boundaryId ); return this.queryForJsonAndBuildObject( sbQueryPath.toString(), Boundary.class ); } // PRIVATE HELPERS private String buildUrlQueryStringAndGetJsonResponse( String queryPath ) throws OpenStatesException { return this.buildUrlQueryStringAndGetJsonResponse( queryPath, null ); } private String buildUrlQueryStringAndGetJsonResponse( String queryPath, Map<String, String> queryParameters ) throws OpenStatesException { String urlQueryString = this.buildUrlQueryString( queryPath, queryParameters ); String jsonResponse = this.getJsonResponse( urlQueryString ); return jsonResponse; } private String getJsonResponse( String urlQuery ) throws OpenStatesException { LOGGER.debug( "getting json-response from url-query: " + urlQuery ); String jsonResponse = null; InputStream is = null; try { URL url = new URL( urlQuery ); is = url.openStream(); Writer writer = new StringWriter(); char[] buffer = new char[1024]; Reader reader = new BufferedReader( new InputStreamReader( is, "UTF-8" ) ); int n; while( (n=reader.read(buffer)) != -1 ) { writer.write( buffer, 0, n ); } jsonResponse = writer.toString(); } catch( Throwable t ) { throw new OpenStatesException( "unable to read response from request (" + urlQuery + ")", t ); } finally { if( is != null ) { try { is.close(); } catch( IOException ioe ) { LOGGER.warn( "unable to close input-stream", ioe ); } } } LOGGER.debug( "received json-response: " + jsonResponse ); return jsonResponse; } private String buildUrlQueryString( String queryPath ) { return this.buildUrlQueryString( queryPath, null ); } private String buildUrlQueryString( String queryPath, Map<String, String> queryParameters ) { StringBuilder sb = new StringBuilder( baseUrl ); sb.append( queryPath + "/" ); sb.append( "?apikey=" + this.apiKey ); if( queryParameters != null ) { Iterator<String> it = queryParameters.keySet().iterator(); while( it.hasNext() ) { String key = it.next(); String value = queryParameters.get(key); sb.append( "&" + key + "=" + value ); } } return sb.toString(); } private <T> T mapObject( String json, Class<T> valueType ) throws OpenStatesException { T result = null; try { result = this.mapper.readValue( json, valueType ); } catch( Throwable t ) { String msg = "error mapping to object-type(" + valueType.getCanonicalName() + ") from json: " + json; LOGGER.warn( msg ); throw new OpenStatesException( msg, t ); } //log StringBuilder sbLogMsg = new StringBuilder( "json mapped to " ); if( result == null ) { sbLogMsg.append( "NULL" ); } else { sbLogMsg.append( "type " + valueType.getCanonicalName() ); } LOGGER.debug( sbLogMsg.toString() ); return result; } private <T> T mapObject( String json, TypeReference<?> valueTypeRef ) throws OpenStatesException { T result = null; try { result = this.mapper.readValue( json, valueTypeRef ); } catch( Throwable t ) { String msg = "error mapping to object-type(" + valueTypeRef.getType() + ") from json: " + json; LOGGER.warn( msg ); throw new OpenStatesException( msg, t ); } // log StringBuilder sbLogMsg = new StringBuilder( "json mapped to " ); if( result == null ) { sbLogMsg.append( "NULL" ); } else if( result instanceof Collection ) { int size = ((Collection<?>) result).size(); sbLogMsg.append( "type " + valueTypeRef.getType() + " with " + size + " elements" ); } else { sbLogMsg.append( "type " + valueTypeRef.getType() ); } LOGGER.debug( sbLogMsg.toString() ); return result; } private <T> T queryForJsonAndBuildObject( String queryPath, Class<T> valueType ) throws OpenStatesException { return this.queryForJsonAndBuildObject( queryPath, null, valueType ); } private <T> T queryForJsonAndBuildObject( String queryPath, TypeReference<?> valueTypeRef ) throws OpenStatesException { return this.queryForJsonAndBuildObject( queryPath, null, valueTypeRef ); } private <T> T queryForJsonAndBuildObject( String queryPath, Map<String, String> queryParams, Class<T> valueType ) throws OpenStatesException { String jsonResponse = this.buildUrlQueryStringAndGetJsonResponse( queryPath, queryParams ); return this.mapObject( jsonResponse, valueType ); } private <T> T queryForJsonAndBuildObject( String queryPath, Map<String, String> queryParams, TypeReference<?> valueTypeRef ) throws OpenStatesException { String jsonResponse = this.buildUrlQueryStringAndGetJsonResponse( queryPath, queryParams ); return this.mapObject( jsonResponse, valueTypeRef ); } // MAIN public static void main( String[] args ) throws OpenStatesException { // get the API key String apiKey = null; for( String s : args ) { if( s == null || s.trim().isEmpty() ) continue; if( s.trim().split( "=" )[0].equals( "apiKey" ) ) { apiKey = s.trim().split( "=" )[1]; } } if( apiKey == null || apiKey.trim().isEmpty() ) { throw new IllegalArgumentException( "Program-argument 'apiKey' not found but required" ); } OpenStates os = new OpenStates( apiKey ); System.out.println( "*** DISTRICTS ***\n" ); List<District> allUtahDistricts = os.findDistricts( "ut" ); List<District> utahLowerDistricts = os.findDistricts( "ut", "lower" ); List<District> utahUpperDistricts = os.findDistricts( "ut", "upper" ); System.out.println( "Utah's lower house has " + utahLowerDistricts.size() + " districts" ); System.out.println( "Utah's upper house has " + utahUpperDistricts.size() + " districts" ); System.out.println( "Utah has " + allUtahDistricts.size() + " total districts" ); Boundary boundary = os.getBoundary( utahUpperDistricts.get(5) ); System.out.println( "Utah's " + boundary.chamber + " district " + boundary.name + " has " + boundary.numSeats + " seat(s) (" + boundary.boundaryId + ")" ); System.out.println( "\n*** COMMITTEES ***\n" ); Map<String, String> queryParams = new HashMap<String, String>(); queryParams.put( "state", "ut" ); List<Committee> committees = os.findCommittees( queryParams ); System.out.println( "Utah has " + committees.size() + " committees" ); System.out.println( "One of Utah's committees is: " + committees.get(0).committee ); queryParams.put( "chamber", "upper" ); committees = os.findCommittees( queryParams ); System.out.println( "Utah's upper house has " + committees.size() + " committees" ); String targetCommitteeId = committees.get(0).id; System.out.println( "\nGetting committee: " + targetCommitteeId ); Committee targetCommittee = os.getCommittee( targetCommitteeId ); System.out.println( "Found committee... " + targetCommittee.committee ); System.out.println( "\n*** EVENTS ***\n" ); queryParams = new HashMap<String, String>(); queryParams.put( "state", "tx" ); List<Event> events = os.findEvents( queryParams ); System.out.println( "Texas has " + events.size() + " events" ); System.out.println( "One of Texas's events is: " + events.get(0).description ); String targetEventId = events.get(0).id; System.out.println( "\nGetting event: " + targetEventId ); Event targetEvent = os.getEvent( targetEventId ); System.out.println( "Found event... " + targetEvent.description ); System.out.println( "\n*** BILLS ***\n" ); queryParams = new HashMap<String, String>(); queryParams.put( "state", "ut" ); queryParams.put( "updated_since", "2012-01-01" ); queryParams.put( "chamber", "upper" ); List<Bill> bills = os.findBills( queryParams ); System.out.println( "Utah's upper-house has " + bills.size() + " bills that have been updated in 2012" ); System.out.println( "One of Utah's 2012 upper-house bills is: " + bills.get(0).title ); } }
package org.cyanogenmod.launcher.cards; import it.gmariotti.cardslib.library.internal.Card; import it.gmariotti.cardslib.library.internal.Card.OnUndoSwipeListListener; import org.cyanogenmod.launcher.cardprovider.CmHomeApiCardProvider; import org.cyanogenmod.launcher.home.api.cards.DataCard; import android.content.Context; public class ApiCard extends Card implements OnUndoSwipeListListener { private DataCard mDataCard; public ApiCard(Context context, DataCard dataCard) { super(context); init(dataCard); } public ApiCard(Context context, int innerLayout, DataCard dataCard) { super(context, innerLayout); init(dataCard); } private void init(DataCard dataCard) { mDataCard = dataCard; setSwipeable(true); setOnUndoSwipeListListener(this); if (dataCard != null) { setId(dataCard.getGlobalId()); } } public void setApiAuthority(String authority) { mDataCard.setAuthority(authority); } public String getApiAuthority() { return mDataCard.getAuthority(); } public long getDbId() { return mDataCard.getId(); } public void updateFromDataCard(DataCard dataCard) { mDataCard = dataCard; } public DataCard getDataCard() { return mDataCard; } @Override public void onUndoSwipe(Card card, boolean timedOut) { if (mDataCard != null && timedOut) { boolean deleted = mDataCard.unpublish(mContext); if (deleted) { CmHomeApiCardProvider.sendCardDeletedBroadcast(mContext, mDataCard); } } } }
package net.wurstclient.gui.options.zoom; import org.lwjgl.input.Keyboard; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.wurstclient.WurstClient; import net.wurstclient.files.ConfigFiles; import net.wurstclient.gui.options.GuiPressAKey; import net.wurstclient.gui.options.GuiPressAKeyCallback; import net.wurstclient.options.OptionsManager; public class GuiZoomManager extends GuiScreen implements GuiPressAKeyCallback { private GuiScreen prevScreen; public GuiZoomManager(GuiScreen par1GuiScreen) { prevScreen = par1GuiScreen; } @Override public void initGui() { buttonList.clear(); buttonList.add(new GuiButton(0, width / 2 - 100, height / 4 + 144 - 16, 200, 20, "Back")); buttonList.add(new GuiButton(1, width / 2 - 79, height / 4 + 24 - 16, 158, 20, "Zoom Key: " + Keyboard .getKeyName(WurstClient.INSTANCE.options.zoom.keybind))); buttonList.add(new GuiButton(2, width / 2 - 79, height / 4 + 72 - 16, 50, 20, "More")); buttonList.add(new GuiButton(3, width / 2 - 25, height / 4 + 72 - 16, 50, 20, "Less")); buttonList.add(new GuiButton(4, width / 2 + 29, height / 4 + 72 - 16, 50, 20, "Default")); buttonList.add(new GuiButton(5, width / 2 - 79, height / 4 + 96 - 16, 158, 20, "Use Mouse Wheel: " + (WurstClient.INSTANCE.options.zoom.scroll ? "ON" : "OFF"))); WurstClient.INSTANCE.analytics.trackPageView("/options/keybind-manager", "Keybind Manager"); } /** * Called from the main game loop to update the screen. */ @Override public void updateScreen() { } @Override protected void actionPerformed(GuiButton button) { if(button.enabled) switch(button.id) { case 0: // Back mc.displayGuiScreen(prevScreen); break; case 1: // Zoom Key mc.displayGuiScreen(new GuiPressAKey(this)); break; case 2: // Zoom Level More WurstClient.INSTANCE.options.zoom.level = Math.min(Math.round( WurstClient.INSTANCE.options.zoom.level * 10F + 1F) / 10F, 10F); ConfigFiles.OPTIONS.save(); break; case 3: // Zoom Level Less WurstClient.INSTANCE.options.zoom.level = Math.max(Math.round( WurstClient.INSTANCE.options.zoom.level * 10F - 1F) / 10F, 1F); ConfigFiles.OPTIONS.save(); break; case 4: // Zoom Level Default WurstClient.INSTANCE.options.zoom.level = new OptionsManager().zoom.level; ConfigFiles.OPTIONS.save(); break; case 5: // Use Mouse Wheel WurstClient.INSTANCE.options.zoom.scroll = !WurstClient.INSTANCE.options.zoom.scroll; ConfigFiles.OPTIONS.save(); buttonList.get(5).displayString = "Use Mouse Wheel: " + (WurstClient.INSTANCE.options.zoom.scroll ? "ON" : "OFF"); break; } } /** * Fired when a key is typed. This is the equivalent of * KeyListener.keyTyped(KeyEvent e). */ @Override protected void keyTyped(char par1, int par2) { } /** * Draws the screen and all the components in it. */ @Override public void drawScreen(int par1, int par2, float par3) { drawBackground(0); drawCenteredString(fontRendererObj, "Zoom Manager", width / 2, 40, 0xffffff); drawString( fontRendererObj, "Zoom Level: " + WurstClient.INSTANCE.options.zoom.level + " x normal", width / 2 - 75, height / 4 + 44, 0xcccccc); super.drawScreen(par1, par2, par3); } @Override public void setKey(String key) { WurstClient.INSTANCE.options.zoom.keybind = Keyboard.getKeyIndex(key); ConfigFiles.OPTIONS.save(); buttonList.get(1).displayString = "Zoom Key: " + key; } }
package org.deepsymmetry.beatlink.data; import io.kaitai.struct.ByteBufferKaitaiStream; import org.deepsymmetry.beatlink.Util; import org.deepsymmetry.beatlink.dbserver.BinaryField; import org.deepsymmetry.beatlink.dbserver.Message; import org.deepsymmetry.beatlink.dbserver.NumberField; import org.deepsymmetry.cratedigger.pdb.RekordboxAnlz; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.*; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Provides information about each memory point, hot cue, and loop stored for a track. * * @author James Elliott */ @SuppressWarnings("WeakerAccess") public class CueList { private static final Logger logger = LoggerFactory.getLogger(CueList.class); /** * The message holding the cue list information as it was read over the network. This can be used to analyze fields * that have not yet been reliably understood, and is also used for storing the cue list in a cache file. This will * be {@code null} if the cue list was not obtained from a dbserver query. */ public final Message rawMessage; /** * The bytes from which the Kaitai Struct tags holding cue list information were parsed from an ANLZ file. * Will be {@code null} if the cue list was obtained from a dbserver query. */ public final List<ByteBuffer> rawTags; /** * The bytes from which the Kaitai Struct tags holding the nxs2 cue list information (which can include DJ-assigned * comment text for each cue) were parsed from an extended ANLZ file. Will be {@code null} if the cue list was * obtained from a dbserver query, and empty if there were no nxs2 cue tags available in the analysis data. */ public final List<ByteBuffer> rawExtendedTags; /** * Return the number of entries in the cue list that represent hot cues. * * @return the number of cue list entries that are hot cues */ public int getHotCueCount() { if (rawMessage != null) { return (int) ((NumberField) rawMessage.arguments.get(5)).getValue(); } int total = 0; for (Entry entry : entries) { if (entry.hotCueNumber > 0) { ++total; } } return total; } /** * Return the number of entries in the cue list that represent ordinary memory points, rather than hot cues. * The memory points can also be loops. * * @return the number of cue list entries other than hot cues */ public int getMemoryPointCount() { if (rawMessage != null) { return (int) ((NumberField) rawMessage.arguments.get(6)).getValue(); } int total = 0; for (Entry entry : entries) { if (entry.hotCueNumber == 0) { ++total; } } return total; } /** * Breaks out information about each entry in the cue list. */ public static class Entry { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Entry entry = (Entry) o; if (hotCueNumber != entry.hotCueNumber) return false; if (isLoop != entry.isLoop) return false; if (cuePosition != entry.cuePosition) return false; if (cueTime != entry.cueTime) return false; if (loopPosition != entry.loopPosition) return false; return loopTime == entry.loopTime; } @Override public int hashCode() { int result = hotCueNumber; result = 31 * result + (isLoop ? 1 : 0); result = 31 * result + (int) (cuePosition ^ (cuePosition >>> 32)); result = 31 * result + (int) (cueTime ^ (cueTime >>> 32)); result = 31 * result + (int) (loopPosition ^ (loopPosition >>> 32)); result = 31 * result + (int) (loopTime ^ (loopTime >>> 32)); return result; } /** * If this has a non-zero value, this entry is a hot cue with that identifier. */ public final int hotCueNumber; /** * Indicates whether this entry represents a loop, as opposed to a simple cue point. */ public final boolean isLoop; /** * Indicates the location of the cue in half-frame units, which are 1/150 of a second. If the cue is a loop, * this is the start of the loop. */ public final long cuePosition; /** * Indicates the location of the cue in milliseconds. If the cue is a loop, this is the start of the loop. */ public final long cueTime; /** * If the entry represents a loop, indicates the loop point in half-frame units, which are 1/150 of a second. * The loop point is the end of the loop, at which point playback jumps back to {@link #cuePosition}. */ public final long loopPosition; /** * If the entry represents a loop, indicates the loop point in milliseconds. The loop point is the end of the * loop, at which point playback jumps back to {@link #cueTime}. */ public final long loopTime; /** * If the entry was constructed from an extended nxs2-style commented cue tag, and the DJ assigned a comment * to the cue, this will contain the comment text. Otherwise it will be an empty string. */ public final String comment; /** * The explicit color embedded into the cue, or {@code null} if there was none. */ public final Color embeddedColor; /** * The color with which this cue will be displayed in rekordbox, if it is a hot cue with a recognized * color code, or {@code null} if that does not apply. */ public final Color rekordboxColor; /** * Constructor for non-loop entries. * * @param number if non-zero, this is a hot cue, with the specified identifier * @param position the position of this cue/memory point in half-frame units, which are 1/150 of a second * @param comment the DJ-assigned comment, or an empty string if none was assigned * @param embeddedColor the explicit color embedded in the cue, if any * @param rekordboxColor the color that rekordbox will display for this cue, if available */ public Entry(int number, long position, String comment, Color embeddedColor, Color rekordboxColor) { if (comment == null) throw new NullPointerException("comment must not be null"); hotCueNumber = number; cuePosition = position; cueTime = Util.halfFrameToTime(position); isLoop = false; loopPosition = 0; loopTime = 0; this.comment = comment.trim(); this.embeddedColor = embeddedColor; this.rekordboxColor = rekordboxColor; } /** * Constructor for loop entries. * * @param number if non-zero, this is a hot cue, with the specified identifier * @param startPosition the position of the start of this loop in half-frame units, which are 1/150 of a second * @param endPosition the position of the end of this loop in half-frame units * @param comment the DJ-assigned comment, or an empty string if none was assigned * @param embeddedColor the explicit color embedded in the cue, if any * @param rekordboxColor the color that rekordbox will display for this cue, if available */ public Entry(int number, long startPosition, long endPosition, String comment, Color embeddedColor, Color rekordboxColor) { if (comment == null) throw new NullPointerException("comment must not be null"); hotCueNumber = number; cuePosition = startPosition; cueTime = Util.halfFrameToTime(startPosition); isLoop = true; loopPosition = endPosition; loopTime = Util.halfFrameToTime(endPosition); this.comment = comment.trim(); this.embeddedColor = embeddedColor; this.rekordboxColor = rekordboxColor; } /** * Determine the color that an original Nexus series player would use to display this cue. Hot cues are * green, loops are orange, and ordinary memory points are red. * * @return the color that represents this cue on players that don't support nxs2 colored cues. */ public Color getNexusColor() { if (hotCueNumber > 0) { return Color.GREEN; } if (isLoop) { return Color.ORANGE; } return Color.RED; } /** * Determine the best color to be used to display this cue. If there is an indexed rekordbox color in the cue, * use that; otherwise, if there is an explicit color embedded, use that, and if neither of those is available, * delegate to {@link #getNexusColor()}. * * @return the most suitable available display color for the cue */ public Color getColor() { if (rekordboxColor != null) { return rekordboxColor; } if (embeddedColor != null) { return embeddedColor; } return getNexusColor(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (hotCueNumber == 0) { if (isLoop) { sb.append("Loop["); } else { sb.append("Memory Point["); } } else { sb.append("Hot Cue ").append((char)(hotCueNumber + '@')).append('['); } sb.append("time ").append(cueTime).append("ms"); if (isLoop) { sb.append(", loop time ").append(loopTime).append("ms"); } if (!comment.isEmpty()) { sb.append(", comment ").append(comment); } sb.append(']'); return sb.toString(); } } /** * The entries present in the cue list, sorted into order by increasing position, with hot cues coming after * ordinary memory points if both are at the same position (as often seems to happen). */ public final List<Entry> entries; /** * Sorts the entries into the order we want to present them in, which is by position, with hot cues coming after * ordinary memory points if both exist at the same position, which often happens. * * @param loadedEntries the unsorted entries we have loaded from a dbserver message, metadata cache, or rekordbox * database export * @return an immutable list of the collections in the proper order */ private List<Entry> sortEntries(List<Entry> loadedEntries) { Collections.sort(loadedEntries, new Comparator<Entry>() { @Override public int compare(Entry entry1, Entry entry2) { int result = (int) (entry1.cuePosition - entry2.cuePosition); if (result == 0) { int h1 = (entry1.hotCueNumber != 0) ? 1 : 0; int h2 = (entry2.hotCueNumber != 0) ? 1 : 0; result = h1 - h2; } return result; } }); return Collections.unmodifiableList(loadedEntries); } /** * Helper method to add cue list entries from a parsed ANLZ cue tag * * @param entries the list of entries being accumulated * @param tag the tag whose entries are to be added */ private void addEntriesFromTag(List<Entry> entries, RekordboxAnlz.CueTag tag) { for (RekordboxAnlz.CueEntry cueEntry : tag.cues()) { // TODO: Need to figure out how to identify deleted entries to ignore. if (cueEntry.type() == RekordboxAnlz.CueEntryType.LOOP) { entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time()), Util.timeToHalfFrame(cueEntry.loopTime()), "", null, null)); } else { entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time()), "", null, null)); } } } /** * Look up the embedded color that we expect to be paired with a given rekordbox color code, so we can warn if * something else is found instead, which implies our understanding of cue colors is incorrect. * * @param colorCode the first color byte * @return the color corresponding to the three bytes that are expected to follow it */ private Color expectedEmbeddedColor(int colorCode) { switch (colorCode) { case 0x31: // magenta return new Color(0xff, 0x00, 0xa1); case 0x38: // violet return new Color(0x83, 0x00, 0xff); case 0x3c: // fuchsia return new Color(0x80, 0x00, 0xff); case 0x3e: // light slate blue return new Color(0x33, 0x00, 0xff); case 0x01: // blue return new Color(0x00, 0x00, 0xff); case 0x05: // steel blue return new Color(0x50, 0x07, 0xff); case 0x09: // aqua return new Color(0x00, 0xe0, 0xff); case 0x0e: // sea green return new Color(0x1f, 0xff, 0xa3); case 0x12: // teal return new Color(0x00, 0xff, 0x47); case 0x16: // green return new Color(0x1a, 0xff, 0x00); case 0x1a: // lime return new Color(0x80,0xff, 0x00); case 0x1e: // olive return new Color(0xe6, 0xff, 0x00); case 0x20: // yellow return new Color(0xff, 0xe8, 0x00); case 0x26: // orange return new Color(0xff, 0x5e, 0x00); case 0x2a: // red return new Color(0xff, 0x00, 0x00); case 0x2d: // pink return new Color(0xff, 0x00, 0x73); default: return null; } } /** * Decode the embedded color present in the cue entry, if there is one. * * @param entry the parsed cue entry * @return the embedded color value, or {@code null} if there is none present */ private Color findEmbeddedColor(RekordboxAnlz.CueExtendedEntry entry) { if (entry.colorRed() == 0 && entry.colorGreen() == 0 && entry.colorBlue() == 0) { return null; } return new Color(entry.colorRed(), entry.colorGreen(), entry.colorBlue()); } /** * Look up the color that rekordbox would use to display this cue. The colors in this table correspond * to the 4x4 grid that is available inside the hot cue configuration interface. * * @param colorCode the color index found in the cue * @return the corresponding color or {@code null} if the index is not recognized */ private Color findRekordboxColor(int colorCode) { switch (colorCode) { case 0x31: // magenta return new Color(0xde, 0x44, 0xcf); case 0x38: // violet return new Color(0x84, 0x32, 0xff); case 0x3c: // fuchsia return new Color(0xaa, 0x72, 0xff); case 0x3e: // light slate blue return new Color(0x64, 0x73, 0xff); case 0x01: // blue return new Color(0x30, 0x5a, 0xff); case 0x05: // steel blue return new Color(0x50, 0xb4, 0xff); case 0x09: // aqua return new Color(0x00, 0xe0, 0xff); case 0x0e: // sea green return new Color(0x1f, 0xa3, 0x92); case 0x12: // teal return new Color(0x10, 0xb1, 0x76); case 0x16: // green return new Color(0x28, 0xe2, 0x14); case 0x1a: // lime return new Color(0xa2,0xdd, 0x16); case 0x1e: // olive return new Color(0xb4, 0xbe, 0x04); case 0x20: // yellow return new Color(0xc3, 0xaf, 0x04); case 0x26: // orange return new Color(0xe0, 0x64, 0x1b); case 0x2a: // red return new Color(0xe5, 0x28, 0x28); case 0x2d: // pink return new Color(0xfe, 0x12, 0x7a); case 0x00: // none return null; default: logger.warn("Unrecognized rekordbox color code, " + colorCode + ", returning null."); return null; } } /** * Helper method to add cue list entries from a parsed extended ANLZ nxs2 comment cue tag * * @param entries the list of entries being accumulated * @param tag the tag whose entries are to be added */ private void addEntriesFromTag(List<Entry> entries, RekordboxAnlz.CueExtendedTag tag) { for (RekordboxAnlz.CueExtendedEntry cueEntry : tag.cues()) { final Color embeddedColor = findEmbeddedColor(cueEntry); final Color expectedColor = expectedEmbeddedColor(cueEntry.colorCode()); final Color rekordboxColor = findRekordboxColor(cueEntry.colorCode()); if ((embeddedColor == null && expectedColor != null) || (embeddedColor != null && !embeddedColor.equals(expectedColor))) { logger.warn("Was expecting embedded color " + expectedEmbeddedColor(cueEntry.colorCode()) + " for rekordbox color code " + cueEntry.colorCode() + ", but found color " + embeddedColor); } if (cueEntry.type() == RekordboxAnlz.CueEntryType.LOOP) { entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time()), Util.timeToHalfFrame(cueEntry.loopTime()), cueEntry.comment(), embeddedColor, rekordboxColor)); } else { entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time()), cueEntry.comment(), embeddedColor, rekordboxColor)); } } } /** * Constructor for when reading from a rekordbox track analysis file. Finds the cues sections and * translates them into the objects Beat Link uses to represent them. * * @param anlzFile the recordbox analysis file corresponding to that track */ public CueList(RekordboxAnlz anlzFile) { rawMessage = null; // We did not create this from a dbserver response. List<ByteBuffer> tagBuffers = new ArrayList<ByteBuffer>(2); List<ByteBuffer> extendedTagBuffers = new ArrayList<ByteBuffer>(2); List<Entry> mutableEntries = new ArrayList<Entry>(); // First see if there are any nxs2-style cue comment tags available. for (RekordboxAnlz.TaggedSection section : anlzFile.sections()) { if (section.body() instanceof RekordboxAnlz.CueExtendedTag) { RekordboxAnlz.CueExtendedTag tag = (RekordboxAnlz.CueExtendedTag) section.body(); extendedTagBuffers.add(ByteBuffer.wrap(section._raw_body()).asReadOnlyBuffer()); addEntriesFromTag(mutableEntries, tag); } } // Then, collect any old style cue tags, but ignore their entries if we found nxs2-style ones. for (RekordboxAnlz.TaggedSection section : anlzFile.sections()) { if (section.body() instanceof RekordboxAnlz.CueTag) { RekordboxAnlz.CueTag tag = (RekordboxAnlz.CueTag) section.body(); tagBuffers.add(ByteBuffer.wrap(section._raw_body()).asReadOnlyBuffer()); if (extendedTagBuffers.isEmpty()) { addEntriesFromTag(mutableEntries, tag); } } } entries = sortEntries(mutableEntries); rawTags = Collections.unmodifiableList(tagBuffers); rawExtendedTags = Collections.unmodifiableList(extendedTagBuffers); } /** * Constructor for when recreating from cache files containing the raw tag bytes if there were no nxs2-style * extended cue tags. Included for backwards compatibility. * @param rawTags the un-parsed ANLZ file tags holding the cue list entries */ public CueList(List<ByteBuffer> rawTags) { this (rawTags, Collections.<ByteBuffer>emptyList()); } /** * Constructor for when recreating from cache files containing the raw tag bytes and raw nxs2-style * cue comment tag bytes. * @param rawTags the un-parsed ANLZ file tags holding the cue list entries * @param rawExtendedTags the un-parsed extended ANLZ file tags holding the nxs2-style commented cue list entries */ public CueList(List<ByteBuffer> rawTags, List<ByteBuffer> rawExtendedTags) { rawMessage = null; this.rawTags = Collections.unmodifiableList(rawTags); this.rawExtendedTags = Collections.unmodifiableList(rawExtendedTags); List<Entry> mutableEntries = new ArrayList<Entry>(); if (rawExtendedTags.isEmpty()) { for (ByteBuffer buffer : rawTags) { RekordboxAnlz.CueTag tag = new RekordboxAnlz.CueTag(new ByteBufferKaitaiStream(buffer)); addEntriesFromTag(mutableEntries, tag); } } else { for (ByteBuffer buffer : rawExtendedTags) { RekordboxAnlz.CueExtendedTag tag = new RekordboxAnlz.CueExtendedTag(new ByteBufferKaitaiStream(buffer)); addEntriesFromTag(mutableEntries, tag); } } entries = sortEntries(mutableEntries); } /** * Constructor when reading from the network or a cache file. * * @param message the response that contains the cue list information */ public CueList(Message message) { rawMessage = message; rawTags = null; rawExtendedTags = null; byte[] entryBytes = ((BinaryField) message.arguments.get(3)).getValueAsArray(); final int entryCount = entryBytes.length / 36; ArrayList<Entry> mutableEntries = new ArrayList<Entry>(entryCount); for (int i = 0; i < entryCount; i++) { final int offset = i * 36; final int cueFlag = entryBytes[offset + 1]; final int hotCueNumber = entryBytes[offset + 2]; if ((cueFlag != 0) || (hotCueNumber != 0)) { // This entry is not empty, so represent it. final long position = Util.bytesToNumberLittleEndian(entryBytes, offset + 12, 4); if (entryBytes[offset] != 0) { // This is a loop final long endPosition = Util.bytesToNumberLittleEndian(entryBytes, offset + 16, 4); mutableEntries.add(new Entry(hotCueNumber, position, endPosition, "", null, null)); } else { mutableEntries.add(new Entry(hotCueNumber, position, "", null, null)); } } } entries = sortEntries(mutableEntries); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CueList cueList = (CueList) o; return entries != null ? entries.equals(cueList.entries) : cueList.entries == null; } @Override public int hashCode() { return entries != null ? entries.hashCode() : 0; } @Override public String toString() { return "Cue List[entries: " + entries + "]"; } }
package org.voltdb.utils; import static java.util.Objects.requireNonNull; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.NoSuchFileException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.Executor; import java.util.stream.Collectors; import java.util.zip.CRC32; import org.voltcore.logging.VoltLogger; import org.voltcore.utils.DBBPool; import org.voltcore.utils.DBBPool.BBContainer; import org.voltcore.utils.DeferredSerialization; import org.voltcore.utils.Pair; import org.voltdb.NativeLibraryLoader; import org.voltdb.utils.BinaryDeque.TruncatorResponse.Status; import org.voltdb.utils.BinaryDequeReader.NoSuchOffsetException; import org.voltdb.utils.BinaryDequeReader.SeekErrorRule; import com.google_voltpatches.common.base.Throwables; /** * A deque that specializes in providing persistence of binary objects to disk. Any object placed in the deque will be * persisted to disk asynchronously. Objects placed in the deque can be persisted synchronously by invoking sync. The * files backing this deque all start with a nonce provided at construction time followed by a segment index that is * stored in the filename. Files grow to a maximum size of 64 megabytes and then a new segment is created. The index * starts at 0. Segments are deleted once all objects from the segment have been polled and all the containers returned * by poll have been discarded. Push is implemented by creating new segments at the head of the deque containing the * objects to be pushed. * * @param M Type of extra header metadata stored in the PBD */ public class PersistentBinaryDeque<M> implements BinaryDeque<M> { private static RetentionPolicyMgr s_retentionPolicyMgr; public static synchronized void setupRetentionPolicyMgr(int numThreads, int numCompactionThreads) { if (s_retentionPolicyMgr == null) { s_retentionPolicyMgr = new RetentionPolicyMgr(); } s_retentionPolicyMgr.configure(numThreads, numCompactionThreads); } public static RetentionPolicyMgr getRetentionPolicyMgr() { return s_retentionPolicyMgr; } class GapWriter implements BinaryDequeGapWriter<M> { private M m_gapHeader; private PBDSegment<M> m_activeSegment; private boolean m_closed; @Override public void updateGapHeader(M gapHeader) throws IOException { synchronized (PersistentBinaryDeque.this) { if (m_closed) { throw new IOException("updateGapHeader call on closed PBD " + m_nonce); } m_gapHeader = gapHeader; if (m_activeSegment!= null) { finishActiveSegmentWrite(); } } } private void finishActiveSegmentWrite() throws IOException { finishWrite(m_activeSegment); if (m_retentionPolicy != null) { m_retentionPolicy.finishedGapSegment(); } m_activeSegment = null; } @Override public int offer(BBContainer data, long startId, long endId, long timestamp) throws IOException { try { return offer0(data, startId, endId, timestamp); } finally { data.discard(); } } private int offer0(BBContainer data, long startId, long endId, long timestamp) throws IOException { synchronized (PersistentBinaryDeque.this) { if (m_closed) { throw new IOException("updateGapHeader call on closed PBD " + m_nonce); } assert(m_gapHeader != null); assert(startId != PBDSegment.INVALID_ID && endId >= startId); PBDSegment<M> prev = m_activeSegment; if (m_activeSegment == null || startId != m_activeSegment.getEndId()+1) { Map.Entry<Long, PBDSegment<M>> entry = m_segments.floorEntry(startId); prev = findValidSegmentFrom((entry == null ? null : entry.getValue()), false, true); if (m_activeSegment!= null && m_activeSegment.m_id != m_segments.lastKey()) { finishActiveSegmentWrite(); } } PBDSegment<M> next = null; if (prev == null) { // inserting at the beginning next = findValidSegmentFrom(peekFirstSegment(), true, true); } else { Map.Entry<Long, PBDSegment<M>> nextEntry = m_segments.higherEntry(prev.m_id); next = findValidSegmentFrom((nextEntry == null ? null : nextEntry.getValue()), true, true); } // verify that these ids don't already exist if (prev!=null && startId <= prev.getEndId()) { throw new IllegalArgumentException("PBD segment with range [" + prev.getStartId() + "-" + prev.getEndId() + "] already contains some entries offered in the range [" + startId + "-" + endId + "]"); } if (next!=null && endId >= next.getStartId()) { throw new IllegalArgumentException("PBD segment with range [" + next.getStartId() + "-" + next.getEndId() + "] already contains some entries offered in the range [" + startId + "-" + endId + "]"); } // By now prev.endId < startId. But it may not be the next id, in which case, we need to start a new segment if (prev != null && startId != prev.getEndId()+1) { prev = null; } Pair<Integer, PBDSegment<M>> result = offerToSegment(prev, data, startId, endId, timestamp, m_gapHeader, false); m_activeSegment = result.getSecond(); updateCursorsReadCount(m_activeSegment, 1); assertions(); return result.getFirst(); } } @Override public void close() throws IOException { synchronized (PersistentBinaryDeque.this) { if (m_closed) { return; } if (m_activeSegment != null) { finishActiveSegmentWrite(); } m_closed = true; m_gapWriter = null; } } } /** * Used to read entries from the PBD. Multiple readers may be active at the same time, * but only one read or write may happen concurrently. */ class ReadCursor implements BinaryDequeReader<M> { private final String m_cursorId; private PBDSegment<M> m_segment; private final Set<PBDSegmentReader<M>> m_segmentReaders = new HashSet<>(); // Number of objects out of the total //that were deleted at the time this cursor was created private final long m_numObjectsDeleted; private long m_numRead; // If a rewind occurred this is set to the segment id where this cursor was before the rewind private long m_rewoundFromId = -1; private boolean m_cursorClosed = false; private final boolean m_isTransient; /** * True if m_segment had its entry count modified under this cursor and m_numRead is not reliable. This is set * by {@link #updateReadCount(long, int)} */ boolean m_hasBadCount = false; public ReadCursor(String cursorId, long numObjectsDeleted) { this(cursorId, numObjectsDeleted, false); } public ReadCursor(String cursorId, long numObjectsDeleted, boolean isTransient) { m_cursorId = cursorId; m_numObjectsDeleted = numObjectsDeleted; m_isTransient = isTransient; } @Override public Wrapper poll(OutputContainerFactory ocf) throws IOException { synchronized (PersistentBinaryDeque.this) { if (m_cursorClosed) { throw new IOException("PBD.ReadCursor.poll(): " + m_cursorId + " - Reader has been closed"); } assertions(); if (moveToValidSegment() == null) { return null; } PBDSegmentReader<M> segmentReader = getOrOpenReader(); long lastSegmentId = m_segments.lastEntry().getValue().segmentId(); while (!segmentReader.hasMoreEntries()) { if (m_segment.segmentId() == lastSegmentId) { // nothing more to read return null; } // Save closed readers until everything in the segment is acked. if (m_isTransient || segmentReader.allReadAndDiscarded()) { segmentReader.close(); } else { segmentReader.closeAndSaveReaderState(); } m_segment = m_segments.higherEntry(m_segment.segmentId()).getValue(); // push to PBD will rewind cursors. So, this cursor may have already opened this segment segmentReader = getOrOpenReader(); } BBContainer retcont = segmentReader.poll(ocf); if (retcont == null) { return null; } m_numRead++; assertions(); assert (retcont.b() != null); return wrapRetCont(m_segment, segmentReader, retcont); } } @Override public BinaryDequeReader.Entry<M> pollEntry(OutputContainerFactory ocf) throws IOException { synchronized (PersistentBinaryDeque.this) { Wrapper wrapper = poll(ocf); if (wrapper == null) { return null; } M extraHeader = m_segment.getExtraHeader(); return new BinaryDequeReader.Entry<M>() { @Override public M getExtraHeader() { return extraHeader; } @Override public ByteBuffer getData() { return wrapper.b(); } @Override public void release() { wrapper.discard(); } @Override public void free() { wrapper.free(); } }; } } PBDSegment<M> getCurrentSegment() { return m_segment; } public void seekToFirstSegment() throws IOException { synchronized (PersistentBinaryDeque.this) { if (m_segments.isEmpty() || (getCurrentSegment() != null && getCurrentSegment().m_id == m_segments.firstKey())) { return; } seekToSegment(m_segments.firstEntry().getValue()); } } @Override public void seekToSegment(long entryId, SeekErrorRule errorRule) throws NoSuchOffsetException, IOException { assert(entryId >= 0); synchronized (PersistentBinaryDeque.this) { PBDSegment<M> seekSegment = findSegmentWithEntry(entryId, errorRule); seekToSegment(seekSegment); } } private void seekToSegment(PBDSegment<M> seekSegment) throws IOException { if (moveToValidSegment() == null) { return; } if (m_segment.segmentId() == seekSegment.segmentId()) { //Close and open to rewind reader to the beginning and reset everything PBDSegmentReader<M> reader = m_segment.getReader(m_cursorId); if (reader != null) { m_numRead -= reader.readIndex(); closeSegmentReader(reader); } } else { // rewind or fastforward, adjusting the numRead accordingly if (m_segment.segmentId() > seekSegment.segmentId()) { // rewind for (PBDSegment<M> curr : m_segments .subMap(seekSegment.segmentId(), true, m_segment.segmentId(), true).values()) { PBDSegmentReader<M> currReader = curr.getReader(m_cursorId); if (assertionsOn) { if (curr.segmentId() == m_segment.segmentId()) { if (currReader != null) { m_numRead -= currReader.readIndex(); } } else { m_numRead -= curr.getNumEntries(); } } if (currReader != null) { closeSegmentReader(currReader); } } } else { // fastforward PBDSegmentReader<M> segmentReader = m_segment.getReader(m_cursorId); m_numRead += m_segment.getNumEntries(); if (segmentReader != null) { m_numRead -= segmentReader.readIndex(); closeSegmentReader(segmentReader); } if (assertionsOn) { // increment numRead for (PBDSegment<M> curr : m_segments .subMap(m_segment.segmentId(), false, seekSegment.segmentId(), false).values()) { m_numRead += curr.getNumEntries(); } } } m_segment = seekSegment; } } /** * Advance the cursor to the next segment if this segment is older than the specified time. * This is a method implemented specifically to make it easier to implement retention policy * on PBDs and hence not exposed outside the package. * * @param millis time in milliseconds * @return returns true if the reader advanced to the next segment. False otherwise. * @throws IOException if there was an error reading the segments or reading the timestamp */ boolean skipToNextSegmentIfOlder(long millis) throws IOException { synchronized (PersistentBinaryDeque.this) { if (m_cursorClosed) { throw new IOException("PBD.ReadCursor.skipToNextSegmentIfOlder(): " + m_cursorId + " - Reader has been closed"); } if (m_segments.size() == 0) { return false; } long recordTime = getSegmentTimestamp(); // If this one is invalid keep searching forward until there are no more or there is a valid one boolean foundInvalid = recordTime == PBDSegment.INVALID_TIMESTAMP; while (recordTime == PBDSegment.INVALID_TIMESTAMP) { PBDSegment<M> nextValidSegment = findNextValidSegmentFrom(m_segment, true, false); if (nextValidSegment == null) { return false; } else { m_segment = nextValidSegment; recordTime = getSegmentTimestamp(); } } if (System.currentTimeMillis() - recordTime < millis) { // can't skip yet return false; } if (m_segment.isActive() || m_segment.segmentId() == m_segments.lastEntry().getValue().segmentId()) { if (foundInvalid) { // Current segment is old enough to be deleted but is active or latest so delete invalid ones deleteSegmentsBefore(m_segment); } return false; } skipToNextSegment(true); return true; } } @Override public void skipPast(long id) throws IOException { synchronized(PersistentBinaryDeque.this) { if (moveToValidSegment() == null) { return; } while (id >= m_segment.getEndId() && skipToNextSegment(false)) {} } } // This is used by retention cursor and regular skip forward. // With retention cursors, you want to delete the current segment, // while with regular skip forward, you want to delete the older segments only. // In regular skip, current segment is ready to be deleted only after at least // one entry from the next segment is read and discarded. private boolean skipToNextSegment(boolean isRetention) throws IOException { PBDSegmentReader<M> segmentReader = getOrOpenReader(); m_numRead += m_segment.getNumEntries() - segmentReader.readIndex(); segmentReader.markRestReadAndDiscarded(); Map.Entry<Long, PBDSegment<M>> entry = m_segments.higherEntry(m_segment.segmentId()); if (entry == null) { // on the last segment // We are marking this one as read. So OK to delete segments before this callDeleteSegmentsBefore(m_segment, 1, isRetention); return false; } if (!segmentReader.hasOutstandingEntries()) { segmentReader.close(); } PBDSegment<M> oldSegment = m_segment; m_segment = entry.getValue(); PBDSegment<M> segmentToDeleteBefore = isRetention ? m_segment : oldSegment; callDeleteSegmentsBefore(segmentToDeleteBefore, 1, isRetention); return true; } /** * Advance the cursor to the next segment if this reader has >= bytes than the specified number * of bytes after advancing to the next segment. * This is a method implemented specifically to make it easier to implement retention policy * on PBDs and hence not exposed outside the package. * * @param maxBytes the minimum number of bytes this reader should have after advancing to next segment. * @return returns returns 0 if the reader can successfully advance to the next segment. * Otherwise it returns the number of bytes that must be added to the segment before it can advance. * @throws IOException if the reader was closed or on other error opening the segment files. */ long skipToNextSegmentIfBigger(long maxBytes) throws IOException { synchronized (PersistentBinaryDeque.this) { if (m_cursorClosed) { throw new IOException("PBD.ReadCursor.skipToNextSegmentIfBigger(): " + m_cursorId + " - Reader has been closed"); } if (moveToValidSegment() == null) { return maxBytes; } if (m_segment.isActive() || m_segment.segmentId() == m_segments.lastKey()) { long needed = maxBytes - remainingFileSize(); return (needed == 0) ? 1 : needed; // To fix: 0 is a special value indicating we skipped. } long diff = remainingFileSize(); if (diff < maxBytes) { return maxBytes - diff; } skipToNextSegment(true); return 0; } } private long remainingFileSize() { long size = 0; for (PBDSegment<M> segment: m_segments.tailMap(m_segment.segmentId(), false).values()) { size += segment.getFileSize(); } return size; } void rewindTo(PBDSegment<M> segment) { if (m_rewoundFromId == -1 && m_segment != null) { m_rewoundFromId = m_segment.segmentId(); } m_segment = segment; } private PBDSegment<M> moveToValidSegment() { PBDSegment<M> firstSegment = peekFirstSegment(); // It is possible that m_segment got closed and removed if (m_segment == null || firstSegment == null || m_segment.segmentId() < firstSegment.segmentId()) { m_segment = firstSegment; } return m_segment; } @Override public long getNumObjects() throws IOException { synchronized(PersistentBinaryDeque.this) { if (m_cursorClosed) { throw new IOException("Cannot compute object count of " + m_cursorId + " - Reader has been closed"); } return m_numObjects - m_numObjectsDeleted - m_numRead; } } /* * Don't use size in bytes to determine empty, could potentially * diverge from object count on crash or power failure * although incredibly unlikely */ @Override public long sizeInBytes() throws IOException { synchronized(PersistentBinaryDeque.this) { if (m_cursorClosed) { throw new IOException("Cannot compute size of " + m_cursorId + " - Reader has been closed"); } assertions(); if (moveToValidSegment() == null) { return 0; } long size = 0; boolean inclusive = true; if (m_segment.isOpenForReading(m_cursorId)) { //this reader has started reading from curr segment. // Find out how much is left to read. size = m_segment.getReader(m_cursorId).uncompressedBytesToRead(); inclusive = false; } // Get the size of all unread segments for (PBDSegment<M> currSegment : m_segments.tailMap(m_segment.segmentId(), inclusive).values()) { size += currSegment.size(); } return size; } } @Override public boolean isEmpty() throws IOException { synchronized(PersistentBinaryDeque.this) { if (m_cursorClosed) { throw new IOException("Closed"); } assertions(); if (moveToValidSegment() == null) { return true; } boolean inclusive = true; if (m_segment.isOpenForReading(m_cursorId)) { //this reader has started reading from curr segment. // Check if there are more to read. if (m_segment.getReader(m_cursorId).hasMoreEntries()) { return false; } inclusive = false; } for (PBDSegment<M> currSegment : m_segments.tailMap(m_segment.segmentId(), inclusive).values()) { if (currSegment.getNumEntries() > 0) { return false; } } return true; } } private Wrapper wrapRetCont(PBDSegment<M> segment, PBDSegmentReader<M> segmentReader, final BBContainer retcont) { if (m_isTransient) { return new Wrapper(retcont); } int entryNumber = segmentReader.readIndex(); return new Wrapper(retcont) { @Override public void discard() { synchronized(PersistentBinaryDeque.this) { free(); assert m_cursorClosed || m_segments.containsKey(segment.segmentId()); // Cursor or reader was closed so just essentially ignore this discard if (m_cursorClosed) { return; } if (segment.getReader(m_cursorId) != segmentReader) { m_usageSpecificLog.warn(segment.m_file + ": Reader removed or replaced. Ignoring discard of entry " + entryNumber); return; } assert(m_segment != null); // If the reader has moved past this and all have been acked close this segment reader. if (segmentReader.allReadAndDiscarded() && segment.segmentId() < m_segment.m_id) { try { closeSegmentReader(segmentReader); } catch(IOException e) { m_usageSpecificLog.warn("Unexpected error closing PBD file " + segment.m_file, e); } } deleteSegmentsOnAck(segment, entryNumber); } } }; } private void closeSegmentReader(PBDSegmentReader<M> segmentReader) throws IOException { m_segmentReaders.remove(segmentReader); segmentReader.close(); } private void deleteSegmentsOnAck(PBDSegment<M> segment, int entryNumber) { // Only continue if open and there is another segment if (m_cursorClosed || m_segments.size() == 1) { return; } // If this segment is already marked for deletion, check if it is the first one // and delete it if fully acked. All the subsequent marked ones can be checked and deleted as well. if (segment.m_deleteOnAck == true && segment.segmentId() == m_segments.firstKey()) { m_deferredDeleter.execute(this::deleteMarkedSegments); return; } callDeleteSegmentsBefore(segment, entryNumber, false); } private void deleteMarkedSegments() { synchronized(PersistentBinaryDeque.this) { // With deferred deleters, this may be executed later, so check closed status again if (m_cursorClosed) { return; } Iterator<PBDSegment<M>> itr = m_segments.values().iterator(); while (itr.hasNext()) { PBDSegment<M> toDelete = itr.next(); try { if (toDelete.m_deleteOnAck == true && canDeleteSegment(toDelete)) { itr.remove(); closeAndDeleteSegment(toDelete); } else { break; } } catch(IOException e) { m_usageSpecificLog.error("Unexpected error deleting segment after all have been read and acked", e); } } } } private void callDeleteSegmentsBefore(PBDSegment<M> segment, int entryNumber, boolean isRetention) { if (m_isTransient) { return; } // If this is the first entry of a segment, see if previous segments can be deleted or marked ready to // delete if (m_cursorClosed || m_segments.size() == 1 || (entryNumber != 1 && m_rewoundFromId != segment.m_id) || !PersistentBinaryDeque.this.canDeleteSegmentsBefore(segment)) { return; } if (isRetention) { try { Map.Entry<Long, PBDSegment<M>> lower = m_segments.lowerEntry(segment.segmentId()); m_retentionDeletePoint = (lower == null) ? m_retentionDeletePoint : lower.getValue().getEndId(); } catch(IOException e) { // cannot happen because header is read at open time of retention reader. // If it does happen, don't delete without being able to save the deletion point. // Next retention will hopefully be successful and delete everything. m_usageSpecificLog.error("Unexpected error getting endId of segment. " + segment.m_file + ". PBD files may not be deleted.", e); return; } } m_deferredDeleter.execute(() -> deleteReaderSegmentsBefore(segment)); } private void deleteReaderSegmentsBefore(PBDSegment<M> segment) { synchronized(PersistentBinaryDeque.this) { // With deferred deleters, this may be executed later, so check closed status again if (m_cursorClosed) { return; } if (m_rewoundFromId == segment.m_id) { m_rewoundFromId = -1; } try { deleteSegmentsBefore(segment); } catch (IOException e) { m_usageSpecificLog.error("Exception closing and deleting PBD segment", e); } } } void close() { for (PBDSegmentReader<M> reader : m_segmentReaders) { try { reader.close(); } catch (IOException e) { m_usageSpecificLog.warn("Failed to close reader " + reader, e); } } m_segmentReaders.clear(); m_segment = null; m_cursorClosed = true; } @Override public boolean isOpen() { return !m_cursorClosed; } /** * Used to find out if the current segment that this reader is on, is one that is being actively written to. * * @return Returns true if the current segment that the reader is on is also being written to. False otherwise. */ boolean isCurrentSegmentActive() { synchronized(PersistentBinaryDeque.this) { return (moveToValidSegment() == null) ? false : m_segment.isActive(); } } /** * Returns the time the last record in this segment was written. * * @return timestamp in millis of the last record in this segment. */ public long getSegmentTimestamp() { synchronized (PersistentBinaryDeque.this) { try { return moveToValidSegment() == null ? PBDSegment.INVALID_TIMESTAMP : m_segment.getTimestamp(); } catch (IOException e) { m_usageSpecificLog.warn("Failed to read timestamp", e); return PBDSegment.INVALID_TIMESTAMP; } } } /** * Notify this cursor that the number of entries has changed but not at the head or the tail. This can be done * by gap fill and update entries * * @param segmentId ID of segment which was changed * @param countChange The change in the number of entries. This can be either positive or negative */ void updateReadCount(long segmentId, int countChange) { if (m_segment != null) { if (m_segment.segmentId() > segmentId) { m_numRead += countChange; } else { m_hasBadCount = true; } } } private PBDSegmentReader<M> getOrOpenReader() throws IOException { PBDSegmentReader<M> reader = m_segment.getReader(m_cursorId); if (reader == null) { reader = m_segment.openForRead(m_cursorId); m_segmentReaders.add(reader); } return reader; } } public static final OutputContainerFactory UNSAFE_CONTAINER_FACTORY = DBBPool::allocateUnsafeByteBuffer; /** * Processors also log using this facility. */ private final VoltLogger m_usageSpecificLog; private final File m_path; private final String m_nonce; private final boolean m_compress; private final PBDSegmentFactory m_pbdSegmentFactory; private boolean m_initializedFromExistingFiles = false; private final BinaryDequeSerializer<M> m_extraHeaderSerializer; //Segments that are no longer being written to and can be polled //These segments are "immutable". They will not be modified until deletion private final TreeMap<Long, PBDSegment<M>> m_segments = new TreeMap<>(); // Current active segment being written to or the most recent segment if m_requiresId is false private PBDSegment<M> m_activeSegment; private volatile boolean m_closed = false; private final HashMap<String, ReadCursor> m_readCursors = new HashMap<>(); private long m_numObjects; private long m_numDeleted; private M m_extraHeader; private Executor m_deferredDeleter = Runnable::run; private PBDRetentionPolicy m_retentionPolicy; private long m_retentionDeletePoint = PBDSegment.INVALID_ID; private boolean m_requiresId; private GapWriter m_gapWriter; /** The number of entries which are in closed segments since the last time {@link #updateEntries()} was called */ private long m_entriesClosedSinceUpdate; // The amount of time in nanosecond a segment can be left open for write since the segment is constructed. private long m_segmentRollTimeLimitNs = Long.MAX_VALUE; /** * Create a persistent binary deque with the specified nonce and storage back at the specified path. This is a * convenience method for testing so that poll with delete can be tested. * * @param m_nonce * @param extraHeader * @param m_path * @param deleteEmpty * @throws IOException */ private PersistentBinaryDeque(Builder<M> builder) throws IOException { NativeLibraryLoader.loadVoltDB(); m_path = builder.m_path; m_nonce = builder.m_nonce; m_usageSpecificLog = builder.m_logger; m_compress = builder.m_useCompression; m_extraHeader = builder.m_initialExtraHeader; m_extraHeaderSerializer = builder.m_extraHeaderSerializer; m_pbdSegmentFactory = builder.m_pbdSegmentFactory; m_requiresId = builder.m_requiresId; if (!m_path.exists() || !m_path.canRead() || !m_path.canWrite() || !m_path.canExecute() || !m_path.isDirectory()) { throw new IOException( m_path + " is not usable ( !exists || !readable " + "|| !writable || !executable || !directory)"); } parseFiles(builder.m_deleteExisting); m_numObjects = countNumObjects(); assertions(); } TreeMap<Long, PBDSegment<M>> getSegments() { return m_segments; } String getNonce() { return m_nonce; } VoltLogger getUsageSpecificLog() { return m_usageSpecificLog; } /** * Return a segment file name from m_nonce and current segment id * * @see parseFiles for file name structure * @param currentId current segment id * @return segment file name */ private String getSegmentFileName(long currentId) { return PbdSegmentName.createName(m_nonce, currentId, false); } /** * Parse files for this PBD; if creating, delete any crud left by a previous homonym. * * @param deleteExisting true if should delete any existing PBD files * * @throws IOException */ private void parseFiles(boolean deleteExisting) throws IOException { TreeMap<Long, PbdSegmentName> filesById = new TreeMap<>(); List<String> invalidPbds = new ArrayList<>(); try { for (File file : m_path.listFiles()) { if (file.isDirectory() || !file.isFile() || file.isHidden()) { continue; } PbdSegmentName segmentName = PbdSegmentName.parseFile(m_usageSpecificLog, file); switch (segmentName.m_result) { case INVALID_NAME: invalidPbds.add(file.getName()); //$FALL-THROUGH$ case NOT_PBD: continue; default: } // Is this one of our PBD files? if (!m_nonce.equals(segmentName.m_nonce)) { // Not my PBD continue; } // From now on we're dealing with one of our PBD files if (file.length() == 0 || deleteExisting) { deleteStalePbdFile(file, deleteExisting); continue; } filesById.put(segmentName.m_id, segmentName); } if (!invalidPbds.isEmpty()) { if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Found invalid PBDs in " + m_path + ": " + invalidPbds); } else { m_usageSpecificLog.warn("Found " + invalidPbds.size() + " invalid PBD" + (invalidPbds.size() > 1 ? "s" : "") + " in " + m_path); } } // Handle common cases: no PBD files or just one if (filesById.size() == 0) { if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("No PBD segments for " + m_nonce); } return; } m_initializedFromExistingFiles = true; Long prevId = null; for (Map.Entry<Long, PbdSegmentName> entry : filesById.entrySet()) { long currId = entry.getKey(); if (!m_requiresId && prevId != null && currId != prevId+1) { throw new IOException("Found " + entry.getValue().m_file + " with id " + currId + " after previous id " + prevId); } recoverSegment(currId, entry.getValue()); prevId = currId; } if (!m_requiresId && prevId != null) { m_activeSegment = m_segments.get(prevId); } } catch (RuntimeException e) { if (e.getCause() instanceof IOException) { throw new IOException(e); } throw(e); } } /** * Delete a PBD segment that was identified as 'stale' i.e. produced by earlier VoltDB releases * * Note that this file may be concurrently deleted from multiple instances so we ignore * NoSuchFileException. * * @param file file to delete * @param create true if creating PBD * @throws IOException */ private void deleteStalePbdFile(File file, boolean create) throws IOException { try { PBDSegment.setFinal(file, false); if (m_usageSpecificLog.isDebugEnabled()) { String createStr = create ? ", forced by creation." : ""; m_usageSpecificLog.debug("Segment " + file.getName() + " (final: " + PBDSegment.isFinal(file) + "), is closed and deleted during init" + createStr); } file.delete(); } catch (Exception e) { if (e instanceof NoSuchFileException) { // Concurrent delete, noop } else { throw e; } } } /** * Quarantine a segment which was already added to {@link #m_segments} * * @param prevEntry {@link Map.Entry} from {@link #m_segments} to quarantine * @throws IOException */ void quarantineSegment(Map.Entry<Long, PBDSegment<M>> prevEntry) throws IOException { quarantineSegment(prevEntry, prevEntry.getValue(), prevEntry.getValue().getNumEntries()); } /** * Quarantine a segment which has not yet been added to {@link #m_segments} * * @param segment * @throws IOException */ private void quarantineSegment(PBDSegment<M> segment) throws IOException { quarantineSegment(null, segment, 0); } private void quarantineSegment(Map.Entry<Long, PBDSegment<M>> prevEntry, PBDSegment<M> segment, int decrementEntryCount) throws IOException { try { PbdSegmentName quarantinedSegment = PbdSegmentName.asQuarantinedSegment(m_usageSpecificLog, segment.file()); if (!segment.file().renameTo(quarantinedSegment.m_file)) { throw new IOException("Failed to quarantine segment: " + segment.file()); } PBDSegment<M> quarantined = new PbdQuarantinedSegment<>(quarantinedSegment.m_file, segment.segmentId()); if (prevEntry == null) { PBDSegment<M> prev = m_segments.put(segment.segmentId(), quarantined); assert prev == null; } else { PBDSegment<M> prev = prevEntry.setValue(quarantined); assert segment == prev; } m_numObjects -= decrementEntryCount; } finally { segment.close(); } } private PBDSegment<M> findValidSegmentFrom(PBDSegment<M> segment, boolean higher) throws IOException { return findValidSegmentFrom(segment, higher, false); } private PBDSegment<M> findValidSegmentFrom(PBDSegment<M> segment, boolean higher, boolean deleteInvalid) throws IOException { if (segment == null || segment.getNumEntries() > 0) { return segment; } return findNextValidSegmentFrom(segment, higher, deleteInvalid); } private PBDSegment<M> findNextValidSegmentFrom(PBDSegment<M> segment, boolean higher, boolean deleteInvalid) throws IOException { // skip past quarantined segments do { Map.Entry<Long, PBDSegment<M>> nextEntry; if (higher) { nextEntry = m_segments.higherEntry(segment.segmentId()); } else { nextEntry = m_segments.lowerEntry(segment.segmentId()); } if (deleteInvalid) { m_segments.remove(segment.segmentId()); segment.m_file.delete(); } segment = (nextEntry == null) ? null : nextEntry.getValue(); } while (segment != null && segment.getNumEntries() == 0); return segment; } private PBDSegment<M> findSegmentWithEntry(long entryId, SeekErrorRule errorRule) throws NoSuchOffsetException, IOException { if (!m_requiresId) { throw new IllegalStateException("Seek is not supported in PBDs that don't store id ranges"); } PBDSegment<M> first = findValidSegmentFrom(peekFirstSegment(), true); if (first == null) { throw new NoSuchOffsetException("Offset " + entryId + "not found. Empty PBD"); } Map.Entry<Long, PBDSegment<M>> floorEntry = m_segments.floorEntry(entryId); PBDSegment<M> candidate = findValidSegmentFrom((floorEntry == null ? null : floorEntry.getValue()), false); if (candidate != null) { if (entryId >= candidate.getStartId() && entryId <= candidate.getEndId()) { return candidate; } else { // in a gap or after the last id available in the PBD if (errorRule == SeekErrorRule.THROW) { throw new NoSuchOffsetException("PBD does not contain offset: " + entryId); } else if (errorRule == SeekErrorRule.SEEK_BEFORE) { return candidate; } else { Map.Entry<Long, PBDSegment<M>> nextEntry = m_segments.higherEntry(candidate.getStartId()); PBDSegment<M> next = findValidSegmentFrom((nextEntry == null ? null : nextEntry.getValue()), true); if (next == null) { throw new NoSuchOffsetException("PBD does not contain offset: " + entryId); } else { return next; } } } } else { // entryId is before the first id available in the PBD if (errorRule == SeekErrorRule.THROW || errorRule == SeekErrorRule.SEEK_BEFORE) { throw new NoSuchOffsetException("PBD does not contain offset: " + entryId); } else { return first; } } } /** * Recover a PBD segment and add it to m_segments * * @param segment * @param deleteEmpty * @throws IOException */ private void recoverSegment(long segmentId, PbdSegmentName segmentName) throws IOException { PBDSegment<M> segment; if (segmentName.m_quarantined) { segment = new PbdQuarantinedSegment<>(segmentName.m_file, segmentId); } else { segment = m_pbdSegmentFactory.create(segmentId, segmentName.m_file, m_usageSpecificLog, m_extraHeaderSerializer); segment.saveFileSize(); try { // Delete preceding empty segment if (segment.getNumEntries() == 0 && m_segments.isEmpty()) { if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Found Empty Segment with entries: " + segment.getNumEntries() + " For: " + segment.file().getName()); m_usageSpecificLog.debug("Segment " + segment.file() + " (final: " + segment.isFinal() + "), will be closed and deleted during init"); } segment.closeAndDelete(); return; } assert(!m_requiresId || segment.getNumEntries() == 0 || segment.getEndId() >= segment.getStartId()); assert (!m_requiresId || m_activeSegment == null || segment.getNumEntries() == 0 || m_activeSegment.getEndId() < segment.getStartId()); // Any recovered segment that is not final should be checked // for internal consistency. if (!segment.isFinal()) { m_usageSpecificLog.warn("Segment " + segment.file() + " (final: " + segment.isFinal() + "), has been recovered but is not in a final state"); } else if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug( "Segment " + segment.file() + " (final: " + segment.isFinal() + "), has been recovered"); } } catch (IOException e) { m_usageSpecificLog.warn( "Failed to retrieve entry count from segment " + segment.file() + ". Quarantining segment", e); quarantineSegment(segment); return; } finally { segment.close(); } } m_entriesClosedSinceUpdate += segment.getNumEntries(); m_segments.put(segment.segmentId(), segment); } private int countNumObjects() throws IOException { int numObjects = 0; for (PBDSegment<M> segment : m_segments.values()) { numObjects += segment.getNumEntries(); } return numObjects; } @Override public synchronized void parseAndTruncate(BinaryDequeTruncator truncator) throws IOException { if (m_closed) { throw new IOException("Cannot parseAndTruncate(): PBD has been closed"); } assertions(); if (m_segments.isEmpty()) { if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("PBD " + m_nonce + " has no finished segments"); } return; } // Close the last write segment for now, will reopen after truncation if (m_activeSegment != null) { m_activeSegment.close(); } /* * Iterator all the objects in all the segments and pass them to the truncator * When it finds the truncation point */ Long lastSegmentIndex = null; for (Map.Entry<Long, PBDSegment<M>> entry : m_segments.entrySet()) { PBDSegment<M> segment = entry.getValue(); final long segmentIndex = segment.segmentId(); final int truncatedEntries; try { truncatedEntries = segment.parseAndTruncate(truncator); } catch (IOException e) { m_usageSpecificLog.warn("Error performing parse and trunctate on segment " + segment.file() + ". Marking segment quarantined", e); quarantineSegment(entry); continue; } if (truncatedEntries == Integer.MAX_VALUE) { // This whole segment will be truncated in the truncation loop below lastSegmentIndex = segmentIndex - 1; break; } else if (truncatedEntries != 0) { m_numObjects -= Math.abs(truncatedEntries); if (truncatedEntries > 0) { // Set last segment and break the loop over this segment lastSegmentIndex = segmentIndex; break; } else if (segment.getNumEntries() == 0) { // All entries were truncated because of corruption mark the segment as quarantined quarantineSegment(entry); } } // truncatedEntries == 0 means nothing is truncated in this segment, // should move on to the next segment. } /* * If it was found that no truncation is necessary, lastSegmentIndex will be null. * Return and the parseAndTruncate is a noop, except for the finalization. */ if (lastSegmentIndex == null) { return; } /* * Now truncate all the segments after the truncation point. */ Iterator<PBDSegment<M>> iterator = m_segments.tailMap(lastSegmentIndex, false).values().iterator(); while (iterator.hasNext()) { PBDSegment<M> segment = iterator.next(); m_numObjects -= segment.getNumEntries(); iterator.remove(); // Ensure the file is not final before closing and truncating segment.closeAndDelete(); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + segment.file() + " (final: " + segment.isFinal() + "), has been closed and deleted by truncator"); } } if (!m_requiresId) { m_activeSegment = m_segments.isEmpty() ? null : m_segments.lastEntry().getValue(); } assertions(); } private PBDSegment<M> initializeNewSegment(long segmentId, File file, String reason, M extraHeader) throws IOException { PBDSegment<M> segment = m_pbdSegmentFactory.create(segmentId, file, m_usageSpecificLog, m_extraHeaderSerializer); try { segment.openNewSegment(m_compress); if (extraHeader != null) { segment.writeExtraHeader(extraHeader); } if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + segment.file() + " (final: " + segment.isFinal() + "), has been opened for writing because of " + reason); } } catch (Throwable t) { segment.close(); throw t; } return segment; } private PBDSegment<M> peekFirstSegment() { Map.Entry<Long, PBDSegment<M>> entry = m_segments.firstEntry(); // entry may be null in ctor and while we are manipulating m_segments in addSegment, for example return (entry==null) ? null : entry.getValue(); } @Override public synchronized void updateExtraHeader(M extraHeader) throws IOException { m_extraHeader = extraHeader; if (m_activeSegment != null) { finishWrite(m_activeSegment); } } @Override public synchronized int offer(BBContainer object) throws IOException { return offer(object, PBDSegment.INVALID_ID, PBDSegment.INVALID_ID, PBDSegment.INVALID_TIMESTAMP); } @Override public synchronized int offer(BBContainer object, long startId, long endId, long timestamp) throws IOException { try { return commonOffer(object, startId, endId, timestamp); } finally { object.discard(); } } @Override public synchronized int offer(DeferredSerialization ds) throws IOException { return commonOffer(ds, PBDSegment.INVALID_ID, PBDSegment.INVALID_ID, PBDSegment.INVALID_TIMESTAMP); } private int commonOffer(Object object, long startId, long endId, long timestamp) throws IOException { boolean isDs = (object instanceof DeferredSerialization); assertions(); if (m_closed) { throw new IOException("Cannot offer(): PBD has been Closed"); } if (isDs) { assert(!m_requiresId && startId == PBDSegment.INVALID_ID && endId == PBDSegment.INVALID_ID); } else { assert(!m_requiresId || (startId != PBDSegment.INVALID_ID && endId != PBDSegment.INVALID_ID && endId >= startId)); assert (!m_requiresId || m_activeSegment == null || m_activeSegment.getEndId() < startId); } Pair<Integer, PBDSegment<M>> result; result = offerToSegment(m_activeSegment, object, startId, endId, timestamp, m_extraHeader, isDs); m_activeSegment = result.getSecond(); assertions(); return result.getFirst(); } private Pair<Integer, PBDSegment<M>> offerToSegment(PBDSegment<M> segment, Object object, long startId, long endId, long timestamp, M extraHeader, boolean isDs) throws IOException { if (segment == null || !segment.isActive()) { segment = addSegment(segment, startId, extraHeader); } else if ((System.nanoTime() - segment.getCreationTime()) > m_segmentRollTimeLimitNs) { finishWrite(segment); segment = addSegment(segment, startId, extraHeader); } int written = (isDs) ? segment.offer((DeferredSerialization) object) : segment.offer((BBContainer) object, startId, endId, timestamp); if (written < 0) { finishWrite(segment); segment = addSegment(segment, startId, extraHeader); written = (isDs) ? segment.offer((DeferredSerialization) object) : segment.offer((BBContainer) object, startId, endId, timestamp); if (written < 0) { throw new IOException("Failed to offer object in PBD"); } } m_numObjects++; callBytesAdded(written); return new Pair<>(written, segment); } private void callBytesAdded(int dataBytes) { if (m_retentionPolicy != null) { m_retentionPolicy.bytesAdded(dataBytes + PBDSegment.ENTRY_HEADER_BYTES); } } private void finishWrite(PBDSegment<M> tail) throws IOException { //Check to see if the tail is completely consumed so we can close it tail.finalize(!tail.isBeingPolled()); tail.saveFileSize(); m_entriesClosedSinceUpdate += tail.getNumEntries(); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug( "Segment " + tail.file() + " (final: " + tail.isFinal() + "), has been closed by offer to PBD"); } } private PBDSegment<M> addSegment(PBDSegment<M> tail, long startId, M extraHeader) throws IOException { long curId = (startId == PBDSegment.INVALID_ID) ? ((tail == null) ? 1 : tail.segmentId() + 1) : startId; String fname = getSegmentFileName(curId); PBDSegment<M> newSegment = initializeNewSegment(curId, new VoltFile(m_path, fname), "an offer", extraHeader); m_segments.put(newSegment.segmentId(), newSegment); if (m_retentionPolicy != null) { m_retentionPolicy.newSegmentAdded(newSegment.m_file.length()); } return newSegment; } private void closeAndDeleteSegment(PBDSegment<M> segment) throws IOException { int toDelete = segment.getNumEntries(); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Closing and deleting segment " + segment.file() + " (final: " + segment.isFinal() + ")"); } if (assertionsOn) { // track the numRead for transient readers, when we delete ones not read by them. for (ReadCursor reader : m_readCursors.values()) { if (!reader.m_isTransient) { continue; } if (reader.m_segment == null) { reader.m_numRead += toDelete; } else if (segment.m_id >= reader.m_segment.m_id) { PBDSegmentReader<M> sreader = segment.getReader(reader.m_cursorId); reader.m_numRead += toDelete - (sreader == null ? 0 : sreader.readIndex()); } } } segment.closeAndDelete(); m_numDeleted += toDelete; } @Override public void push(BBContainer[] objects) throws IOException { push(objects, m_extraHeader); } @Override public void push(BBContainer objects[], M extraHeader) throws IOException { try { push0(objects, extraHeader); } finally { for (BBContainer obj : objects) { obj.discard(); } } } private synchronized void push0(BBContainer objects[], M extraHeader) throws IOException { assertions(); if (m_closed) { throw new IOException("Cannot push(): PBD has been Closed"); } ArrayDeque<ArrayDeque<BBContainer>> segments = new ArrayDeque<ArrayDeque<BBContainer>>(); ArrayDeque<BBContainer> currentSegment = new ArrayDeque<BBContainer>(); //Take the objects that were provided and separate them into deques of objects //that will fit in a single write segment int maxObjectSize = PBDSegment.CHUNK_SIZE - PBDSegment.SEGMENT_HEADER_BYTES; if (extraHeader != null) { maxObjectSize -= m_extraHeaderSerializer.getMaxSize(extraHeader); } int available = maxObjectSize; for (BBContainer object : objects) { int needed = PBDSegment.ENTRY_HEADER_BYTES + object.b().remaining(); if (available < needed) { if (needed > maxObjectSize) { throw new IOException("Maximum object size is " + maxObjectSize); } segments.offer(currentSegment); currentSegment = new ArrayDeque<BBContainer>(); available = maxObjectSize; } available -= needed; currentSegment.add(object); } segments.offer(currentSegment); assert(segments.size() > 0); // Calculate first index to push PBDSegment<M> first = peekFirstSegment(); Long nextIndex = first == null ? 1L : first.segmentId() - 1; while (segments.peek() != null) { ArrayDeque<BBContainer> currentSegmentContents = segments.poll(); String fname = getSegmentFileName(nextIndex); PBDSegment<M> writeSegment = initializeNewSegment(nextIndex, new VoltFile(m_path, fname), "a push", extraHeader); // Prepare for next file nextIndex while (currentSegmentContents.peek() != null) { writeSegment.offer(currentSegmentContents.pollFirst(), PBDSegment.INVALID_ID, PBDSegment.INVALID_ID, PBDSegment.INVALID_TIMESTAMP); m_numObjects++; } // If this segment is to become the writing segment, don't close and // finalize it. if (!m_segments.isEmpty()) { writeSegment.finalize(true); } if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + writeSegment.file() + " (final: " + writeSegment.isFinal() + "), has been created because of a push"); } m_segments.put(writeSegment.segmentId(), writeSegment); } // Because we inserted at the beginning, cursors need to be rewound to the beginning rewindCursors(); assertions(); } private void rewindCursors() { PBDSegment<M> firstSegment = peekFirstSegment(); for (ReadCursor cursor : m_readCursors.values()) { cursor.rewindTo(firstSegment); } } @Override public synchronized BinaryDequeGapWriter<M> openGapWriter() throws IOException { if (m_closed) { throw new IOException("Cannot openGapWriter(): PBD has been Closed"); } assert(m_requiresId); if (m_gapWriter != null) { throw new IOException("A gap writer is already open on this PBD"); } m_gapWriter = new GapWriter(); return m_gapWriter; } @Override public synchronized ReadCursor openForRead(String cursorId) throws IOException { return openForRead(cursorId, false); } @Override public synchronized ReadCursor openForRead(String cursorId, boolean isTransient) throws IOException { if (m_closed) { throw new IOException("Cannot openForRead(): PBD has been Closed"); } ReadCursor reader = m_readCursors.get(cursorId); if (reader == null) { reader = new ReadCursor(cursorId, m_numDeleted, isTransient); m_readCursors.put(cursorId, reader); } assert(reader.m_isTransient == isTransient); return reader; } synchronized boolean isCursorOpen(String cursorId) { return m_readCursors.containsKey(cursorId); } @Override public synchronized void closeCursor(String cursorId, boolean purgeOnLastCursor) { if (m_closed) { return; } ReadCursor reader = m_readCursors.remove(cursorId); if (reader == null) { return; } reader.close(); if (m_retentionPolicy != null) { assert !purgeOnLastCursor : " retention policy and purgeOnLastCursor are mutually exclusive options"; return; } // Purge segments // Check all segments from latest to oldest to see if segments before that segment can be deleted. // Never purge when closing transient readers. // By default with {@code purgeOnLastCursor} == false, attempt to purge segments except when closing // the last cursor. // In the one-to-many DR use case, the snapshot placeholder cursor prevents purging segments that have // been read by the other cursors. Therefore, DR calls this method with {@code purgeOnLastCursor} == true, // in order to ensure that closing the last DR cursor will purge those segments. if (reader.m_isTransient || (m_readCursors.isEmpty() && !purgeOnLastCursor)) { return; } try { boolean deleteSegment = false; Iterator<PBDSegment<M>> iter = m_segments.descendingMap().values().iterator(); while (iter.hasNext()) { PBDSegment<M> segment = iter.next(); if (deleteSegment) { closeAndDeleteSegment(segment); iter.remove(); } else { deleteSegment = canDeleteSegmentsBefore(segment); } } } catch (IOException e) { m_usageSpecificLog.error("Exception closing and deleting PBD segment", e); } } /** * Return true if segments before this one can be deleted, i.e. no open readers on previous segments. * <p> * Note: returns true when no read cursors are open. * * @param segment * @return */ private boolean canDeleteSegmentsBefore(PBDSegment<M> segment) { String retentionCursor = (m_retentionPolicy == null) ? null : m_retentionPolicy.getCursorId(); for (ReadCursor cursor : m_readCursors.values()) { if (cursor.m_isTransient) { continue; } if (cursor.m_segment == null) { return false; } long segmentIndex = segment.segmentId(); long cursorSegmentIndex = cursor.m_segment.segmentId(); if (cursorSegmentIndex < segmentIndex) { return false; } PBDSegmentReader<M> segmentReader = segment.getReader(cursor.m_cursorId); if (Objects.equals(cursor.m_cursorId, retentionCursor)) { // retention cursor doesn't read records and discard. continue; // It just moves to the segment and stays till the policy expires. } // So, just the segmentIndex check above is sufficient. if (segmentReader == null) { // segmentReader is null, if the PBD reader hasn't reached this segment OR // if PBD reader has moved past this and all buffers were acked. if (segment.segmentId() > cursorSegmentIndex) { return false; } } else if (!segmentReader.anyReadAndDiscarded()) { return false; } } return true; } // Deletions initiated by this method should not go through deferred deleter. // This is only called when this volt node receives retention point update from partition leader. // It is problematic to switch deferred deleter on partition leader updates, so always keep the // same deferred deleter, but delete here without going through deferred deleter. @Override public synchronized void deleteSegmentsToEntryId(long entryId) throws IOException { assert(m_requiresId); PBDSegment<M> entrySegment = null; try { entrySegment = findSegmentWithEntry(entryId, SeekErrorRule.SEEK_BEFORE); } catch(NoSuchOffsetException e) { // This means that the entryId is before any entries available in this PBD. Nothing to delete return; } assert(entrySegment.getStartId() <= entryId); if (entrySegment.getEndId() <= entryId && entrySegment.segmentId() != m_segments.lastKey()) { // this segment can also be deleted entrySegment = m_segments.higherEntry(entrySegment.segmentId()).getValue(); } deleteSegmentsBefore(entrySegment); } private synchronized void deleteSegmentsBefore(PBDSegment<M> segment) throws IOException { Iterator<PBDSegment<M>> iter = m_segments.headMap(segment.segmentId(), false).values() .iterator(); boolean markForDel = false; while (iter.hasNext()) { // Only delete a segment if all buffers have been acked. // If not, mark this and all following segments for deletion. PBDSegment<M> earlierSegment = iter.next(); if (markForDel) { earlierSegment.m_deleteOnAck = true; } else if (canDeleteSegment(earlierSegment)) { iter.remove(); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + earlierSegment.file() + " has been closed and deleted after discarding last buffer"); } closeAndDeleteSegment(earlierSegment); } else { earlierSegment.m_deleteOnAck = true; markForDel = true; } } } private boolean canDeleteSegment(PBDSegment<M> segment) throws IOException { if (segment.getNumEntries() == 0) { return true; } for (ReadCursor cursor : m_readCursors.values()) { if (cursor.m_isTransient) { continue; } PBDSegmentReader<M> segmentReader = segment.getReader(cursor.m_cursorId); // segment reader is null if the cursor hasn't reached this segment or // all has been read and discarded. if (segmentReader == null && (cursor.m_segment == null || cursor.m_segment.segmentId() <= segment.segmentId()) ) { return false; } if (segmentReader != null && !segmentReader.allReadAndDiscarded()) { return false; } } return true; } @Override public synchronized void sync() throws IOException { if (m_closed) { throw new IOException("Cannot sync(): PBD has been Closed"); } for (PBDSegment<M> segment : m_segments.values()) { if (!segment.isClosed()) { segment.sync(); } } } @Override public void close() throws IOException { close(false); } @Override public synchronized Pair<Integer, Long> getBufferCountAndSize() throws IOException { int count = 0; long size = 0; for (PBDSegment<M> segment : m_segments.values()) { count += segment.getNumEntries(); size += segment.size(); } return Pair.of(count, size); } @Override public synchronized long getFirstId() throws IOException { return (m_segments.size() == 0) ? PBDSegment.INVALID_ID : m_segments.firstEntry().getValue().getStartId(); } @Override public void closeAndDelete() throws IOException { close(true); } private synchronized void close(boolean delete) throws IOException { if (m_closed) { return; } stopRetentionPolicyEnforcement(); if (m_gapWriter != null) { m_gapWriter.close(); } m_readCursors.values().forEach(ReadCursor::close); m_readCursors.clear(); for (PBDSegment<M> segment : m_segments.values()) { if (delete) { closeAndDeleteSegment(segment); } else { // When closing a PBD, all segments may be finalized because on // recover a new segment will be opened for writing segment.finalize(true); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug( "Closed segment " + segment.file() + " (final: " + segment.isFinal() + "), on PBD close"); } } } m_activeSegment = null; m_segments.clear(); m_closed = true; } public static class ByteBufferTruncatorResponse extends TruncatorResponse { private final ByteBuffer m_retval; private final CRC32 m_crc; public ByteBufferTruncatorResponse(ByteBuffer retval) { this(retval, -1); } public ByteBufferTruncatorResponse(ByteBuffer retval, long rowId) { super(Status.PARTIAL_TRUNCATE, rowId); assert retval.remaining() > 0; m_retval = retval; m_crc = new CRC32(); } @Override public int getTruncatedBuffSize() { return m_retval.remaining(); } @Override public int writeTruncatedObject(ByteBuffer output, int entryId) { int objectSize = m_retval.remaining(); // write entry header PBDUtils.writeEntryHeader(m_crc, output, m_retval, entryId, PBDSegment.NO_FLAGS); // write buffer after resetting position changed by writeEntryHeader // Note: cannot do this in writeEntryHeader as it breaks JUnit tests m_retval.position(0); output.put(m_retval); return objectSize; } } public static class DeferredSerializationTruncatorResponse extends TruncatorResponse { public static interface Callback { public void bytesWritten(int bytes); } private final DeferredSerialization m_ds; private final Callback m_truncationCallback; private final CRC32 m_crc32 = new CRC32(); public DeferredSerializationTruncatorResponse(DeferredSerialization ds, Callback truncationCallback) { super(Status.PARTIAL_TRUNCATE); m_ds = ds; m_truncationCallback = truncationCallback; } @Override public int getTruncatedBuffSize() throws IOException { return m_ds.getSerializedSize(); } @Override public int writeTruncatedObject(ByteBuffer output, int entryId) throws IOException { output.position(PBDSegment.ENTRY_HEADER_BYTES); int bytesWritten = MiscUtils.writeDeferredSerialization(output, m_ds); output.flip(); output.position(PBDSegment.ENTRY_HEADER_BYTES); ByteBuffer header = output.duplicate(); header.position(PBDSegment.ENTRY_HEADER_START_OFFSET); PBDUtils.writeEntryHeader(m_crc32, header, output, entryId, PBDSegment.NO_FLAGS); if (m_truncationCallback != null) { m_truncationCallback.bytesWritten(bytesWritten); } return bytesWritten; } } public static TruncatorResponse fullTruncateResponse() { return new TruncatorResponse(Status.FULL_TRUNCATE); } @Override public boolean initializedFromExistingFiles() { return m_initializedFromExistingFiles; } private static final boolean assertionsOn; static { boolean assertOn = false; assert(assertOn = true); assertionsOn = assertOn; } private void assertions() { if (!assertionsOn || m_closed) { return; } class SegmentWithReader { final boolean m_currentSegment; final long m_id; final int m_entryCount; final int m_readerIndex; final boolean m_allReadAndDiscarded; SegmentWithReader(ReadCursor cursor, PBDSegment<M> segment, PBDSegmentReader<M> reader) throws IOException { m_currentSegment = cursor.m_segment != null && cursor.m_segment.segmentId() == segment.segmentId(); m_id = segment.segmentId(); m_entryCount = segment.getNumEntries(); m_readerIndex = reader.readIndex(); m_allReadAndDiscarded = reader.allReadAndDiscarded(); } @Override public String toString() { return "SegmentWithReader [currentSegment=" + m_currentSegment + ", id=" + m_id + ", entryCount=" + m_entryCount + ", readerIndex=" + m_readerIndex + ", allReadAndDiscarded=" + m_allReadAndDiscarded + "]"; } } List<String> badCounts = new ArrayList<>(); List<SegmentWithReader> segmentsWithReaders = new ArrayList<>(); for (ReadCursor cursor : m_readCursors.values()) { if (cursor.m_hasBadCount) { continue; } boolean noReaderForCurrent = false; long numObjects = 0; int nullReadersBefore = 0, nullReadersAfter = 0; segmentsWithReaders.clear(); try { for (PBDSegment<M> segment : m_segments.values()) { PBDSegmentReader<M> reader = segment.getReader(cursor.m_cursorId); if (reader == null) { // reader will be null if the pbd reader has not reached this segment or has passed this and all were acked. if (cursor.m_segment == null || cursor.m_segment.segmentId() <= segment.m_id) { noReaderForCurrent |= cursor.m_segment != null && cursor.m_segment.segmentId() == segment.segmentId(); ++nullReadersAfter; numObjects += segment.getNumEntries(); } else { ++nullReadersBefore; } } else { segmentsWithReaders.add(new SegmentWithReader(cursor, segment, reader)); numObjects += segment.getNumEntries() - reader.readIndex(); } } if (numObjects != cursor.getNumObjects()) { badCounts.add(cursor.m_cursorId + " expects " + cursor.getNumObjects() + " entries but found " + numObjects + ". noReaderForCurrent=" + noReaderForCurrent + ", nullReadersBefore=" + nullReadersBefore + ", nullReadersAfter=" + nullReadersAfter + ", segments with reader=" + segmentsWithReaders + ", numObjectsDeleted=" + cursor.m_numObjectsDeleted + ", numRead=" + cursor.m_numRead); } } catch (Exception e) { Throwables.throwIfUnchecked(e); throw new RuntimeException(e); } } assert badCounts.isEmpty() : "numDeleted=" + m_numDeleted + ", numObjects=" + m_numObjects + ": \n" + badCounts.stream().map(Object::toString).collect(Collectors.joining("\n")); } int numberOfSegments() { return m_segments.size(); } // Used by test only int numOpenSegments() { int numOpen = 0; for (PBDSegment<M> segment : m_segments.values()) { if (!segment.isClosed()) { numOpen++; } } return numOpen; } @Override public synchronized void scanEntries(BinaryDequeScanner scanner) throws IOException { if (m_closed) { throw new IOException("Cannot scanForGap(): PBD has been closed"); } assertions(); if (m_segments.isEmpty()) { if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("PBD " + m_nonce + " has no finished segments"); } return; } /* * Iterator all the objects in all the segments and pass them to the scanner */ for (Map.Entry<Long, PBDSegment<M>> entry : m_segments.entrySet()) { PBDSegment<M> segment = entry.getValue(); try { int truncatedEntries = segment.scan(scanner); if (truncatedEntries > 0) { m_numObjects -= truncatedEntries; if (segment.getNumEntries() == 0) { // All entries were truncated mark the segment as quarantined quarantineSegment(entry); } } } catch (IOException e) { m_usageSpecificLog.warn("Error scanning segment: " + segment.file() + ". Quarantining segment."); quarantineSegment(entry); } } return; } @Override public synchronized boolean deletePBDSegment(BinaryDequeValidator<M> validator) throws IOException { boolean segmentDeleted = false; if (m_closed) { throw new IOException("Cannot deletePBDSegment(): PBD has been closed"); } assertions(); if (m_segments.isEmpty()) { if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("PBD " + m_nonce + " has no segments to delete."); } return segmentDeleted; } /* * Iterator all the objects in all the segments and pass them to the scanner */ Iterator<Map.Entry<Long, PBDSegment<M>>> iter = m_segments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<Long, PBDSegment<M>> entry = iter.next(); PBDSegment<M> segment = entry.getValue(); try { int entriesToDelete = segment.validate(validator); if (entriesToDelete != 0) { iter.remove(); closeAndDeleteSegment(segment); segmentDeleted = true; } } catch (IOException e) { m_usageSpecificLog.warn("Error validating segment: " + segment.file() + ". Quarantining segment.", e); quarantineSegment(entry); } } return segmentDeleted; } @Override public void registerDeferredDeleter(Executor deferredDeleter) { m_deferredDeleter = (deferredDeleter == null) ? Runnable::run : deferredDeleter; } @Override public synchronized void setRetentionPolicy(RetentionPolicyType policyType, Object... params) { if (m_retentionPolicy != null) { assert !m_retentionPolicy.isPolicyEnforced() : "Retention policy on PBD " + m_nonce + " must be stopped before replacing it"; } m_retentionPolicy = (policyType == null) ? null : s_retentionPolicyMgr.addRetentionPolicy(policyType, this, params); } @Override public synchronized void startRetentionPolicyEnforcement() { try { if (m_retentionPolicy != null) { m_retentionPolicy.startPolicyEnforcement(); } } catch(IOException e) { // Unexpected error. Hence runtime error throw new RuntimeException(e); } } @Override public synchronized void stopRetentionPolicyEnforcement() { if (m_retentionPolicy != null) { m_retentionPolicy.stopPolicyEnforcement(); } } @Override public synchronized boolean isRetentionPolicyEnforced() { return m_retentionPolicy != null && m_retentionPolicy.isPolicyEnforced(); } @Override public synchronized long getRetentionDeletionPoint() { return m_retentionDeletePoint; } /** * Create a new builder for constructing instances of {@link PersistentBinaryDeque} * * @param nonce To be used by the {@link PersistentBinaryDeque} * @param path to a directory where the {@link PersistentBinaryDeque} files will be stored * @param logger to use to log any messages generated by the {@link PersistentBinaryDeque} instance * @throws NullPointerException if any parameters are {@code null} */ public static Builder<Void> builder(String nonce, File path, VoltLogger logger) { return new Builder<>(nonce, path, logger); } /** * Builder class for constructing an instance of a {@link PersistentBinaryDeque} * * @param <M> Type of extra header metadata used with this PBD */ public static final class Builder<M> { final String m_nonce; final File m_path; final VoltLogger m_logger; boolean m_useCompression = false; boolean m_deleteExisting = false; BinaryDequeSerializer<M> m_extraHeaderSerializer; M m_initialExtraHeader; PBDSegmentFactory m_pbdSegmentFactory = PBDRegularSegment::new; boolean m_requiresId = false; private Builder(String nonce, File path, VoltLogger logger) { super(); m_nonce = requireNonNull(nonce, "nonce"); m_path = requireNonNull(path, "path"); m_logger = requireNonNull(logger, "logger"); } private Builder(Builder<?> builder, M extraHeader, BinaryDequeSerializer<M> serializer) { this(builder.m_nonce, builder.m_path, builder.m_logger); m_useCompression = builder.m_useCompression; m_initialExtraHeader = extraHeader; m_extraHeaderSerializer = serializer; m_pbdSegmentFactory = builder.m_pbdSegmentFactory; m_requiresId = builder.m_requiresId; } /** * Set whether compression should be enabled or not. * <p> * Default: {@code false} * * @param enabled {@code true} if compression should be used. * @return An updated {@link Builder} instance */ public Builder<M> compression(boolean enabled) { m_useCompression = enabled; return this; } /** * Set whether the pre-existing PBD files should be deleted. * <p> * Default: {@code false} * * @param deleteExisting {@code true} if existing PBD files should be deleted. * @return An updated {@link Builder} instance */ public Builder<M> deleteExisting(boolean deleteExisting) { m_deleteExisting = deleteExisting; return this; } /** * Set the initial extra header metadata to be stored with entries as well as a {@link BinaryDequeSerializer} to * write and read that type of metadata. * <p> * Default: {@code null} * * @param <T> Type of extra header metadata * @param extraHeader Instance of extra header metadata * @param serializer {@link BinaryDequeSerializer} used write and read the extra header * @return An updated {@link Builder} instance * @throws NullPointerException if {@code serializer} is {@code null} */ public <T> Builder<T> initialExtraHeader(T extraHeader, BinaryDequeSerializer<T> serializer) { return new Builder<>(this, extraHeader, requireNonNull(serializer, "serializer")); } /** * Set whether this PBD requires start and end ids for offers. * <p> * Default: {@code false} * * @param requiresId {@code true} if this PBD requires start id and end id to be specified with offers * @return An updated {@link Builder} instance */ public Builder<M> requiresId(boolean requiresId) { m_requiresId = requiresId; return this; } /** * @return A new instance of {@link PersistentBinaryDeque} constructed by this builder * @throws IOException If there was an error constructing the instance */ public PersistentBinaryDeque<M> build() throws IOException { return new PersistentBinaryDeque<>(this); } Builder<M> pbdSegmentFactory(PBDSegmentFactory pbdSegmentFactory) { m_pbdSegmentFactory = requireNonNull(pbdSegmentFactory); return this; } } /** Internal interface for a factory to create {@link PBDSegment}s */ interface PBDSegmentFactory { <M> PBDSegment<M> create(long segmentId, File file, VoltLogger logger, BinaryDequeSerializer<M> extraHeaderSerializer); } @Override public synchronized int countCursors() { return m_readCursors.size(); } @Override public synchronized long newEligibleUpdateEntries() { return m_entriesClosedSinceUpdate; } /* * In order to prevent holding a object monitor for an extended period of time the monitor will only be held to * process each segment and at the end to clean up trailing segments */ @Override public void updateEntries(BinaryDeque.EntryUpdater<? super M> updater) throws IOException { try (BinaryDeque.EntryUpdater<?> u = updater) { synchronized (this) { m_entriesClosedSinceUpdate = 0; } Long prevSegmentId = Long.MAX_VALUE; Map.Entry<Long, PBDSegment<M>> entry; do { synchronized (this) { entry = m_segments.lowerEntry(prevSegmentId); if (entry == null) { break; } prevSegmentId = entry.getKey(); PBDSegment<M> segment = entry.getValue(); if (segment.isActive() || segment.size() == 0) { continue; } Pair<PBDSegment<M>, Boolean> result = segment.updateEntries(updater); PBDSegment<M> updated = result.getFirst(); if (updated != null) { int updateCount = updated.getNumEntries() - segment.getNumEntries(); m_numObjects += updateCount; updateCursorsReadCount(segment, updateCount); m_segments.put(prevSegmentId, updated); } if (result.getSecond()) { return; } } Thread.yield(); } while (true); synchronized (this) { Iterator<PBDSegment<M>> iter = m_segments.values().iterator(); PBDSegment<M> segment; while (iter.hasNext() && (segment = iter.next()).size() == 0) { segment.closeAndDelete(); iter.remove(); } } } } /** * Update the read counts of cursors when a segment entry count has changed and the segment is not the head or the * tail * * @param segment whose entry count has changed * @param entryCountChange difference in the entry count before to now */ private void updateCursorsReadCount(PBDSegment<M> segment, int entryCountChange) { // read count is only really used for assertions() so don't bother doing the work when assertions are disabled if (assertionsOn) { long segmentId = segment.segmentId(); for (ReadCursor cursor : m_readCursors.values()) { cursor.updateReadCount(segmentId, entryCountChange); } } } /** * Simple wrapper around a {@link BBContainer} which exposes a {@link #free()} method to directly call the * underlying discard */ private class Wrapper extends DBBPool.DBBDelegateContainer { Wrapper(BBContainer delegate) { super(delegate); } void free() { super.discard(); } } @Override public synchronized void setSegmentRollTimeLimit(long limit) { m_segmentRollTimeLimitNs = limit; } }
package nu.validator.checker.schematronequiv; import java.io.ByteArrayInputStream; import java.io.StringReader; import java.util.concurrent.ConcurrentHashMap; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Arrays; import java.util.Collections; import javax.servlet.http.HttpServletRequest; import nu.validator.checker.AttributeUtil; import nu.validator.checker.Checker; import nu.validator.checker.LocatorImpl; import nu.validator.checker.TaintableLocatorImpl; import nu.validator.checker.VnuBadAttrValueException; import nu.validator.checker.VnuBadElementNameException; import nu.validator.client.TestRunner; import nu.validator.datatype.AutocompleteDetailsAny; import nu.validator.datatype.AutocompleteDetailsDate; import nu.validator.datatype.AutocompleteDetailsEmail; import nu.validator.datatype.AutocompleteDetailsMonth; import nu.validator.datatype.AutocompleteDetailsNumeric; import nu.validator.datatype.AutocompleteDetailsPassword; import nu.validator.datatype.AutocompleteDetailsTel; import nu.validator.datatype.AutocompleteDetailsText; import nu.validator.datatype.AutocompleteDetailsUrl; import nu.validator.datatype.Color; import nu.validator.datatype.CustomElementName; import nu.validator.datatype.Html5DatatypeException; import nu.validator.datatype.ImageCandidateStringsWidthRequired; import nu.validator.datatype.ImageCandidateStrings; import nu.validator.datatype.ImageCandidateURL; import nu.validator.htmlparser.impl.NCName; import nu.validator.messages.MessageEmitterAdapter; import org.relaxng.datatype.DatatypeException; import org.w3c.css.css.StyleSheetParser; import org.w3c.css.parser.CssError; import org.w3c.css.parser.CssParseException; import org.w3c.css.parser.Errors; import org.w3c.css.util.ApplContext; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.apache.log4j.Logger; public class Assertions extends Checker { private static final Logger log4j = Logger.getLogger(Assertions.class); private static boolean equalsIgnoreAsciiCase(String one, String other) { if (other == null) { return one == null; } if (one.length() != other.length()) { return false; } for (int i = 0; i < one.length(); i++) { char c0 = one.charAt(i); char c1 = other.charAt(i); if (c0 >= 'A' && c0 <= 'Z') { c0 += 0x20; } if (c1 >= 'A' && c1 <= 'Z') { c1 += 0x20; } if (c0 != c1) { return false; } } return true; } private static final String trimSpaces(String str) { return trimLeadingSpaces(trimTrailingSpaces(str)); } private static final String trimLeadingSpaces(String str) { if (str == null) { return null; } for (int i = str.length(); i > 0; --i) { char c = str.charAt(str.length() - i); if (!(' ' == c || '\t' == c || '\n' == c || '\f' == c || '\r' == c)) { return str.substring(str.length() - i, str.length()); } } return ""; } private static final String trimTrailingSpaces(String str) { if (str == null) { return null; } for (int i = str.length() - 1; i >= 0; --i) { char c = str.charAt(i); if (!(' ' == c || '\t' == c || '\n' == c || '\f' == c || '\r' == c)) { return str.substring(0, i + 1); } } return ""; } private static final Map<String, String[]> INPUT_ATTRIBUTES = new HashMap<>(); static { INPUT_ATTRIBUTES.put("autocomplete", new String[] { "hidden", "text", "search", "url", "tel", "email", "password", "date", "month", "week", "time", "datetime-local", "number", "range", "color" }); INPUT_ATTRIBUTES.put("list", new String[] { "text", "search", "url", "tel", "email", "date", "month", "week", "time", "datetime-local", "number", "range", "color" }); INPUT_ATTRIBUTES.put("maxlength", new String[] { "text", "search", "url", "tel", "email", "password" }); INPUT_ATTRIBUTES.put("minlength", new String[] { "text", "search", "url", "tel", "email", "password" }); INPUT_ATTRIBUTES.put("pattern", new String[] { "text", "search", "url", "tel", "email", "password" }); INPUT_ATTRIBUTES.put("placeholder", new String[] { "text", "search", "url", "tel", "email", "password", "number" }); INPUT_ATTRIBUTES.put("readonly", new String[] { "text", "search", "url", "tel", "email", "password", "date", "month", "week", "time", "datetime-local", "number" }); INPUT_ATTRIBUTES.put("required", new String[] { "text", "search", "url", "tel", "email", "password", "date", "month", "week", "time", "datetime-local", "number", "checkbox", "radio", "file" }); INPUT_ATTRIBUTES.put("size", new String[] { "text", "search", "url", "tel", "email", "password" }); for (String[] allowedTypes: INPUT_ATTRIBUTES.values()) { Arrays.sort(allowedTypes); } } private static final Map<String, String> OBSOLETE_ELEMENTS = new HashMap<>(); static { OBSOLETE_ELEMENTS.put("keygen", ""); OBSOLETE_ELEMENTS.put("center", "Use CSS instead."); OBSOLETE_ELEMENTS.put("font", "Use CSS instead."); OBSOLETE_ELEMENTS.put("big", "Use CSS instead."); OBSOLETE_ELEMENTS.put("strike", "Use CSS instead."); OBSOLETE_ELEMENTS.put("tt", "Use CSS instead."); OBSOLETE_ELEMENTS.put("acronym", "Use the \u201Cabbr\u201D element instead."); OBSOLETE_ELEMENTS.put("dir", "Use the \u201Cul\u201D element instead."); OBSOLETE_ELEMENTS.put("applet", "Use the \u201Cobject\u201D element instead."); OBSOLETE_ELEMENTS.put("basefont", "Use CSS instead."); OBSOLETE_ELEMENTS.put("frameset", "Use the \u201Ciframe\u201D element and CSS instead, or use server-side includes."); OBSOLETE_ELEMENTS.put("noframes", "Use the \u201Ciframe\u201D element and CSS instead, or use server-side includes."); } private static final Map<String, String[]> OBSOLETE_ATTRIBUTES = new HashMap<>(); static { OBSOLETE_ATTRIBUTES.put("abbr", new String[] { "td" }); OBSOLETE_ATTRIBUTES.put("archive", new String[] { "object" }); OBSOLETE_ATTRIBUTES.put("axis", new String[] { "td", "th" }); OBSOLETE_ATTRIBUTES.put("charset", new String[] { "link", "a" }); OBSOLETE_ATTRIBUTES.put("classid", new String[] { "object" }); OBSOLETE_ATTRIBUTES.put("code", new String[] { "object" }); OBSOLETE_ATTRIBUTES.put("codebase", new String[] { "object" }); OBSOLETE_ATTRIBUTES.put("codetype", new String[] { "object" }); OBSOLETE_ATTRIBUTES.put("coords", new String[] { "a" }); OBSOLETE_ATTRIBUTES.put("datafld", new String[] { "span", "div", "object", "input", "select", "textarea", "button", "table" }); OBSOLETE_ATTRIBUTES.put("dataformatas", new String[] { "span", "div", "object", "input", "select", "textarea", "button", "table" }); OBSOLETE_ATTRIBUTES.put("datasrc", new String[] { "span", "div", "object", "input", "select", "textarea", "button", "table" }); OBSOLETE_ATTRIBUTES.put("datapagesize", new String[] { "table" }); OBSOLETE_ATTRIBUTES.put("declare", new String[] { "object" }); OBSOLETE_ATTRIBUTES.put("event", new String[] { "script" }); OBSOLETE_ATTRIBUTES.put("for", new String[] { "script" }); OBSOLETE_ATTRIBUTES.put("language", new String[] { "script" }); OBSOLETE_ATTRIBUTES.put("longdesc", new String[] { "img", "iframe" }); OBSOLETE_ATTRIBUTES.put("methods", new String[] { "link", "a" }); OBSOLETE_ATTRIBUTES.put("name", new String[] { "img", "embed", "option" }); OBSOLETE_ATTRIBUTES.put("nohref", new String[] { "area" }); OBSOLETE_ATTRIBUTES.put("profile", new String[] { "head" }); OBSOLETE_ATTRIBUTES.put("scheme", new String[] { "meta" }); OBSOLETE_ATTRIBUTES.put("scope", new String[] { "td" }); OBSOLETE_ATTRIBUTES.put("shape", new String[] { "a" }); OBSOLETE_ATTRIBUTES.put("standby", new String[] { "object" }); OBSOLETE_ATTRIBUTES.put("target", new String[] { "link" }); OBSOLETE_ATTRIBUTES.put("type", new String[] { "param" }); OBSOLETE_ATTRIBUTES.put("urn", new String[] { "a", "link" }); OBSOLETE_ATTRIBUTES.put("usemap", new String[] { "input" }); OBSOLETE_ATTRIBUTES.put("valuetype", new String[] { "param" }); OBSOLETE_ATTRIBUTES.put("version", new String[] { "html" }); for (String[] elementNames: OBSOLETE_ATTRIBUTES.values()) { Arrays.sort(elementNames); } } private static final Map<String, String> OBSOLETE_ATTRIBUTES_MSG = new HashMap<>(); static { OBSOLETE_ATTRIBUTES_MSG.put("abbr", "Consider instead beginning the cell contents with concise text, followed by further elaboration if needed."); OBSOLETE_ATTRIBUTES_MSG.put("archive", "Use the \u201Cdata\u201D and \u201Ctype\u201D attributes to invoke plugins. To set a parameter with the name \u201Carchive\u201D, use the \u201Cparam\u201D element."); OBSOLETE_ATTRIBUTES_MSG.put("axis", "Use the \u201Cscope\u201D attribute."); OBSOLETE_ATTRIBUTES_MSG.put("charset", "Use an HTTP Content-Type header on the linked resource instead."); OBSOLETE_ATTRIBUTES_MSG.put("classid", "Use the \u201Cdata\u201D and \u201Ctype\u201D attributes to invoke plugins. To set a parameter with the name \u201Cclassid\u201D, use the \u201Cparam\u201D element."); OBSOLETE_ATTRIBUTES_MSG.put("code", "Use the \u201Cdata\u201D and \u201Ctype\u201D attributes to invoke plugins. To set a parameter with the name \u201Ccode\u201D, use the \u201Cparam\u201D element."); OBSOLETE_ATTRIBUTES_MSG.put("codebase", "Use the \u201Cdata\u201D and \u201Ctype\u201D attributes to invoke plugins. To set a parameter with the name \u201Ccodebase\u201D, use the \u201Cparam\u201D element."); OBSOLETE_ATTRIBUTES_MSG.put("codetype", "Use the \u201Cdata\u201D and \u201Ctype\u201D attributes to invoke plugins. To set a parameter with the name \u201Ccodetype\u201D, use the \u201Cparam\u201D element."); OBSOLETE_ATTRIBUTES_MSG.put("coords", "Use \u201Carea\u201D instead of \u201Ca\u201D for image maps."); OBSOLETE_ATTRIBUTES_MSG.put("datapagesize", "You can safely omit it."); OBSOLETE_ATTRIBUTES_MSG.put("datafld", "Use script and a mechanism such as XMLHttpRequest to populate the page dynamically"); OBSOLETE_ATTRIBUTES_MSG.put("dataformatas", "Use script and a mechanism such as XMLHttpRequest to populate the page dynamically"); OBSOLETE_ATTRIBUTES_MSG.put("datasrc", "Use script and a mechanism such as XMLHttpRequest to populate the page dynamically"); OBSOLETE_ATTRIBUTES_MSG.put("for", "Use DOM Events mechanisms to register event listeners."); OBSOLETE_ATTRIBUTES_MSG.put("event", "Use DOM Events mechanisms to register event listeners."); OBSOLETE_ATTRIBUTES_MSG.put("declare", "Repeat the \u201Cobject\u201D element completely each time the resource is to be reused."); OBSOLETE_ATTRIBUTES_MSG.put("language", "Use the \u201Ctype\u201D attribute instead."); OBSOLETE_ATTRIBUTES_MSG.put("longdesc", "Use a regular \u201Ca\u201D element to link to the description."); OBSOLETE_ATTRIBUTES_MSG.put("methods", "Use the HTTP OPTIONS feature instead."); OBSOLETE_ATTRIBUTES_MSG.put("name", "Use the \u201Cid\u201D attribute instead."); OBSOLETE_ATTRIBUTES_MSG.put("nohref", "Omitting the \u201Chref\u201D attribute is sufficient."); OBSOLETE_ATTRIBUTES_MSG.put("profile", "To declare which \u201Cmeta\u201D terms are used in the document, instead register the names as meta extensions. To trigger specific UA behaviors, use a \u201Clink\u201D element instead."); OBSOLETE_ATTRIBUTES_MSG.put("scheme", "Use only one scheme per field, or make the scheme declaration part of the value."); OBSOLETE_ATTRIBUTES_MSG.put("scope", "Use the \u201Cscope\u201D attribute on a \u201Cth\u201D element instead."); OBSOLETE_ATTRIBUTES_MSG.put("shape", "Use \u201Carea\u201D instead of \u201Ca\u201D for image maps."); OBSOLETE_ATTRIBUTES_MSG.put("standby", "Optimise the linked resource so that it loads quickly or, at least, incrementally."); OBSOLETE_ATTRIBUTES_MSG.put("target", "You can safely omit it."); OBSOLETE_ATTRIBUTES_MSG.put("type", "Use the \u201Cname\u201D and \u201Cvalue\u201D attributes without declaring value types."); OBSOLETE_ATTRIBUTES_MSG.put("urn", "Specify the preferred persistent identifier using the \u201Chref\u201D attribute instead."); OBSOLETE_ATTRIBUTES_MSG.put("usemap", "Use the \u201Cimg\u201D element instead of the \u201Cinput\u201D element for image maps."); OBSOLETE_ATTRIBUTES_MSG.put("valuetype", "Use the \u201Cname\u201D and \u201Cvalue\u201D attributes without declaring value types."); OBSOLETE_ATTRIBUTES_MSG.put("version", "You can safely omit it."); } private static final Map<String, String[]> OBSOLETE_STYLE_ATTRS = new HashMap<>(); static { OBSOLETE_STYLE_ATTRS.put("align", new String[] { "caption", "iframe", "img", "input", "object", "embed", "legend", "table", "hr", "div", "h1", "h2", "h3", "h4", "h5", "h6", "p", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr" }); OBSOLETE_STYLE_ATTRS.put("alink", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("allowtransparency", new String[] { "iframe" }); OBSOLETE_STYLE_ATTRS.put("background", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("bgcolor", new String[] { "table", "tr", "td", "th", "body" }); OBSOLETE_STYLE_ATTRS.put("cellpadding", new String[] { "table" }); OBSOLETE_STYLE_ATTRS.put("cellspacing", new String[] { "table" }); OBSOLETE_STYLE_ATTRS.put("char", new String[] { "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr" }); OBSOLETE_STYLE_ATTRS.put("charoff", new String[] { "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr" }); OBSOLETE_STYLE_ATTRS.put("clear", new String[] { "br" }); OBSOLETE_STYLE_ATTRS.put("color", new String[] { "hr" }); OBSOLETE_STYLE_ATTRS.put("compact", new String[] { "dl", "menu", "ol", "ul" }); OBSOLETE_STYLE_ATTRS.put("frameborder", new String[] { "iframe" }); OBSOLETE_STYLE_ATTRS.put("frame", new String[] { "table" }); OBSOLETE_STYLE_ATTRS.put("height", new String[] { "td", "th" }); OBSOLETE_STYLE_ATTRS.put("hspace", new String[] { "embed", "iframe", "input", "img", "object" }); OBSOLETE_STYLE_ATTRS.put("link", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("bottommargin", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("marginheight", new String[] { "iframe", "body" }); OBSOLETE_STYLE_ATTRS.put("leftmargin", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("rightmargin", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("topmargin", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("marginwidth", new String[] { "iframe", "body" }); OBSOLETE_STYLE_ATTRS.put("noshade", new String[] { "hr" }); OBSOLETE_STYLE_ATTRS.put("nowrap", new String[] { "td", "th" }); OBSOLETE_STYLE_ATTRS.put("rules", new String[] { "table" }); OBSOLETE_STYLE_ATTRS.put("scrolling", new String[] { "iframe" }); OBSOLETE_STYLE_ATTRS.put("size", new String[] { "hr" }); OBSOLETE_STYLE_ATTRS.put("text", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("type", new String[] { "li", "ul" }); OBSOLETE_STYLE_ATTRS.put("valign", new String[] { "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr" }); OBSOLETE_STYLE_ATTRS.put("vlink", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("vspace", new String[] { "embed", "iframe", "input", "img", "object" }); OBSOLETE_STYLE_ATTRS.put("width", new String[] { "hr", "table", "td", "th", "col", "colgroup", "pre" }); for (String[] elementNames: OBSOLETE_STYLE_ATTRS.values()) { Arrays.sort(elementNames); } } private static final HashSet<String> JAVASCRIPT_MIME_TYPES = new HashSet<>(); static { JAVASCRIPT_MIME_TYPES.add("application/ecmascript"); JAVASCRIPT_MIME_TYPES.add("application/javascript"); JAVASCRIPT_MIME_TYPES.add("application/x-ecmascript"); JAVASCRIPT_MIME_TYPES.add("application/x-javascript"); JAVASCRIPT_MIME_TYPES.add("text/ecmascript"); JAVASCRIPT_MIME_TYPES.add("text/javascript"); JAVASCRIPT_MIME_TYPES.add("text/javascript1.0"); JAVASCRIPT_MIME_TYPES.add("text/javascript1.1"); JAVASCRIPT_MIME_TYPES.add("text/javascript1.2"); JAVASCRIPT_MIME_TYPES.add("text/javascript1.3"); JAVASCRIPT_MIME_TYPES.add("text/javascript1.4"); JAVASCRIPT_MIME_TYPES.add("text/javascript1.5"); JAVASCRIPT_MIME_TYPES.add("text/jscript"); JAVASCRIPT_MIME_TYPES.add("text/livescript"); JAVASCRIPT_MIME_TYPES.add("text/x-ecmascript"); JAVASCRIPT_MIME_TYPES.add("text/x-javascript"); } private static final String[] ARIA_HIDDEN_NOT_ALLOWED_ELEMENTS = { "base", "col", "colgroup", "head", "html", "link", "map", "meta", "noscript", "param", "picture", "script", "slot", "source", "style", "template", "title", "track" }; private static final String[] INTERACTIVE_ELEMENTS = { "a", "button", "details", "dialog", "embed", "iframe", "label", "select", "textarea" }; private static final String[] INTERACTIVE_ROLES = { "button", "checkbox", "combobox", "grid", "gridcell", "listbox", "menu", "menubar", "menuitem", "menuitemcheckbox", "menuitemradio", "option", "radio", "scrollbar", "searchbox", "slider", "spinbutton", "switch", "tab", "textbox", "treeitem" }; private static final String[] PROHIBITED_INTERACTIVE_ANCESTOR_ROLES = { "button", "link" }; private static final String[] PROHIBITED_MAIN_ANCESTORS = { "a", "address", "article", "aside", "audio", "blockquote", "canvas", "caption", "dd", "del", "details", "dialog", "dt", "fieldset", "figure", "footer", "header", "ins", "li", "main", "map", "nav", "noscript", "object", "section", "slot", "td", "th", "video" }; private static final String[] SPECIAL_ANCESTORS = { "a", "address", "body", "button", "caption", "dfn", "dt", "figcaption", "figure", "footer", "form", "header", "label", "map", "noscript", "th", "time", "progress", "meter", "article", "section", "aside", "nav", "h1", "h2", "h3", "h4", "h5", "h6" }; private static int specialAncestorNumber(String name) { for (int i = 0; i < SPECIAL_ANCESTORS.length; i++) { if (name == SPECIAL_ANCESTORS[i]) { return i; } } return -1; } private static Map<String, Integer> ANCESTOR_MASK_BY_DESCENDANT = new HashMap<>(); private static void registerProhibitedAncestor(String ancestor, String descendant) { int number = specialAncestorNumber(ancestor); if (number == -1) { throw new IllegalStateException( "Ancestor not found in array: " + ancestor); } Integer maskAsObject = ANCESTOR_MASK_BY_DESCENDANT.get(descendant); int mask = 0; if (maskAsObject != null) { mask = maskAsObject.intValue(); } mask |= (1 << number); ANCESTOR_MASK_BY_DESCENDANT.put(descendant, Integer.valueOf(mask)); } static { registerProhibitedAncestor("form", "form"); registerProhibitedAncestor("progress", "progress"); registerProhibitedAncestor("meter", "meter"); registerProhibitedAncestor("dfn", "dfn"); registerProhibitedAncestor("noscript", "noscript"); registerProhibitedAncestor("label", "label"); registerProhibitedAncestor("address", "address"); registerProhibitedAncestor("address", "section"); registerProhibitedAncestor("address", "nav"); registerProhibitedAncestor("address", "article"); registerProhibitedAncestor("header", "header"); registerProhibitedAncestor("footer", "header"); registerProhibitedAncestor("address", "header"); registerProhibitedAncestor("header", "footer"); registerProhibitedAncestor("footer", "footer"); registerProhibitedAncestor("dt", "header"); registerProhibitedAncestor("dt", "footer"); registerProhibitedAncestor("dt", "article"); registerProhibitedAncestor("dt", "nav"); registerProhibitedAncestor("dt", "section"); registerProhibitedAncestor("dt", "h1"); registerProhibitedAncestor("dt", "h2"); registerProhibitedAncestor("dt", "h2"); registerProhibitedAncestor("dt", "h3"); registerProhibitedAncestor("dt", "h4"); registerProhibitedAncestor("dt", "h5"); registerProhibitedAncestor("dt", "h6"); registerProhibitedAncestor("dt", "hgroup"); registerProhibitedAncestor("th", "header"); registerProhibitedAncestor("th", "footer"); registerProhibitedAncestor("th", "article"); registerProhibitedAncestor("th", "nav"); registerProhibitedAncestor("th", "section"); registerProhibitedAncestor("th", "h1"); registerProhibitedAncestor("th", "h2"); registerProhibitedAncestor("th", "h2"); registerProhibitedAncestor("th", "h3"); registerProhibitedAncestor("th", "h4"); registerProhibitedAncestor("th", "h5"); registerProhibitedAncestor("th", "h6"); registerProhibitedAncestor("th", "hgroup"); registerProhibitedAncestor("address", "footer"); registerProhibitedAncestor("address", "h1"); registerProhibitedAncestor("address", "h2"); registerProhibitedAncestor("address", "h3"); registerProhibitedAncestor("address", "h4"); registerProhibitedAncestor("address", "h5"); registerProhibitedAncestor("address", "h6"); registerProhibitedAncestor("caption", "table"); for (String elementName : INTERACTIVE_ELEMENTS) { registerProhibitedAncestor("a", elementName); registerProhibitedAncestor("button", elementName); } } private static final int BODY_MASK = (1 << specialAncestorNumber("body")); private static final int A_BUTTON_MASK = (1 << specialAncestorNumber("a")) | (1 << specialAncestorNumber("button")); private static final int FIGCAPTION_MASK = (1 << specialAncestorNumber( "figcaption")); private static final int FIGURE_MASK = (1 << specialAncestorNumber( "figure")); private static final int H1_MASK = (1 << specialAncestorNumber("h1")); private static final int H2_MASK = (1 << specialAncestorNumber("h2")); private static final int H3_MASK = (1 << specialAncestorNumber("h3")); private static final int H4_MASK = (1 << specialAncestorNumber("h4")); private static final int H5_MASK = (1 << specialAncestorNumber("h5")); private static final int H6_MASK = (1 << specialAncestorNumber("h6")); private static final int MAP_MASK = (1 << specialAncestorNumber("map")); private static final int HREF_MASK = (1 << 30); private static final int LABEL_FOR_MASK = (1 << 29); private static final Map<String, Set<String>> REQUIRED_ROLE_ANCESTOR_BY_DESCENDANT = new HashMap<>(); private static final Map<String, Set<String>> ariaOwnsIdsByRole = new HashMap<>(); private static void registerRequiredAncestorRole(String parent, String child) { Set<String> parents = REQUIRED_ROLE_ANCESTOR_BY_DESCENDANT.get(child); if (parents == null) { parents = new HashSet<>(); } parents.add(parent); REQUIRED_ROLE_ANCESTOR_BY_DESCENDANT.put(child, parents); } static { registerRequiredAncestorRole("listbox", "option"); registerRequiredAncestorRole("menu", "menuitem"); registerRequiredAncestorRole("menu", "menuitemcheckbox"); registerRequiredAncestorRole("menu", "menuitemradio"); registerRequiredAncestorRole("menubar", "menuitem"); registerRequiredAncestorRole("menubar", "menuitemcheckbox"); registerRequiredAncestorRole("menubar", "menuitemradio"); registerRequiredAncestorRole("tablist", "tab"); registerRequiredAncestorRole("tree", "treeitem"); registerRequiredAncestorRole("group", "treeitem"); registerRequiredAncestorRole("group", "listitem"); registerRequiredAncestorRole("group", "menuitemradio"); registerRequiredAncestorRole("list", "listitem"); registerRequiredAncestorRole("row", "cell"); registerRequiredAncestorRole("row", "gridcell"); registerRequiredAncestorRole("row", "columnheader"); registerRequiredAncestorRole("row", "rowheader"); registerRequiredAncestorRole("grid", "row"); registerRequiredAncestorRole("grid", "rowgroup"); registerRequiredAncestorRole("rowgroup", "row"); registerRequiredAncestorRole("treegrid", "row"); registerRequiredAncestorRole("treegrid", "rowgroup"); registerRequiredAncestorRole("table", "rowgroup"); registerRequiredAncestorRole("table", "row"); } private static final Set<String> MUST_NOT_DANGLE_IDREFS = new HashSet<>(); static { MUST_NOT_DANGLE_IDREFS.add("aria-controls"); MUST_NOT_DANGLE_IDREFS.add("aria-describedby"); MUST_NOT_DANGLE_IDREFS.add("aria-flowto"); MUST_NOT_DANGLE_IDREFS.add("aria-labelledby"); MUST_NOT_DANGLE_IDREFS.add("aria-owns"); } private static final Map<String, String> ELEMENTS_WITH_IMPLICIT_ROLE = new HashMap<>(); static { ELEMENTS_WITH_IMPLICIT_ROLE.put("article", "article"); ELEMENTS_WITH_IMPLICIT_ROLE.put("aside", "complementary"); ELEMENTS_WITH_IMPLICIT_ROLE.put("body", "document"); ELEMENTS_WITH_IMPLICIT_ROLE.put("button", "button"); ELEMENTS_WITH_IMPLICIT_ROLE.put("datalist", "listbox"); ELEMENTS_WITH_IMPLICIT_ROLE.put("dd", "definition"); ELEMENTS_WITH_IMPLICIT_ROLE.put("details", "group"); ELEMENTS_WITH_IMPLICIT_ROLE.put("dialog", "dialog"); ELEMENTS_WITH_IMPLICIT_ROLE.put("dfn", "term"); ELEMENTS_WITH_IMPLICIT_ROLE.put("dt", "term"); ELEMENTS_WITH_IMPLICIT_ROLE.put("fieldset", "group"); ELEMENTS_WITH_IMPLICIT_ROLE.put("figure", "figure"); ELEMENTS_WITH_IMPLICIT_ROLE.put("form", "form"); ELEMENTS_WITH_IMPLICIT_ROLE.put("footer", "contentinfo"); ELEMENTS_WITH_IMPLICIT_ROLE.put("h1", "heading"); ELEMENTS_WITH_IMPLICIT_ROLE.put("h2", "heading"); ELEMENTS_WITH_IMPLICIT_ROLE.put("h3", "heading"); ELEMENTS_WITH_IMPLICIT_ROLE.put("h4", "heading"); ELEMENTS_WITH_IMPLICIT_ROLE.put("h5", "heading"); ELEMENTS_WITH_IMPLICIT_ROLE.put("h6", "heading"); ELEMENTS_WITH_IMPLICIT_ROLE.put("hr", "separator"); ELEMENTS_WITH_IMPLICIT_ROLE.put("header", "banner"); ELEMENTS_WITH_IMPLICIT_ROLE.put("img", "img"); ELEMENTS_WITH_IMPLICIT_ROLE.put("li", "listitem"); ELEMENTS_WITH_IMPLICIT_ROLE.put("link", "link"); ELEMENTS_WITH_IMPLICIT_ROLE.put("main", "main"); ELEMENTS_WITH_IMPLICIT_ROLE.put("nav", "navigation"); ELEMENTS_WITH_IMPLICIT_ROLE.put("ol", "list"); ELEMENTS_WITH_IMPLICIT_ROLE.put("output", "status"); ELEMENTS_WITH_IMPLICIT_ROLE.put("progress", "progressbar"); ELEMENTS_WITH_IMPLICIT_ROLE.put("section", "region"); ELEMENTS_WITH_IMPLICIT_ROLE.put("summary", "button"); ELEMENTS_WITH_IMPLICIT_ROLE.put("table", "table"); ELEMENTS_WITH_IMPLICIT_ROLE.put("tbody", "rowgroup"); ELEMENTS_WITH_IMPLICIT_ROLE.put("textarea", "textbox"); ELEMENTS_WITH_IMPLICIT_ROLE.put("tfoot", "rowgroup"); ELEMENTS_WITH_IMPLICIT_ROLE.put("thead", "rowgroup"); ELEMENTS_WITH_IMPLICIT_ROLE.put("td", "cell"); ELEMENTS_WITH_IMPLICIT_ROLE.put("tr", "row"); ELEMENTS_WITH_IMPLICIT_ROLE.put("ul", "list"); } private static final Map<String, String[]> ELEMENTS_WITH_IMPLICIT_ROLES = new HashMap<>(); static { ELEMENTS_WITH_IMPLICIT_ROLES.put("th", new String[] { "columnheader", "rowheader" }); } private static final Map<String, String> ELEMENTS_THAT_NEVER_NEED_ROLE = new HashMap<>(); static { ELEMENTS_THAT_NEVER_NEED_ROLE.put("body", "document"); ELEMENTS_THAT_NEVER_NEED_ROLE.put("datalist", "listbox"); ELEMENTS_THAT_NEVER_NEED_ROLE.put("details", "group"); ELEMENTS_THAT_NEVER_NEED_ROLE.put("form", "form"); ELEMENTS_THAT_NEVER_NEED_ROLE.put("main", "main"); ELEMENTS_THAT_NEVER_NEED_ROLE.put("meter", "progressbar"); ELEMENTS_THAT_NEVER_NEED_ROLE.put("nav", "navigation"); ELEMENTS_THAT_NEVER_NEED_ROLE.put("option", "option"); ELEMENTS_THAT_NEVER_NEED_ROLE.put("optgroup", "group"); ELEMENTS_THAT_NEVER_NEED_ROLE.put("progress", "progressbar"); ELEMENTS_THAT_NEVER_NEED_ROLE.put("summary", "button"); ELEMENTS_THAT_NEVER_NEED_ROLE.put("textarea", "textbox"); } private static final Map<String, String> INPUT_TYPES_WITH_IMPLICIT_ROLE = new HashMap<>(); static { INPUT_TYPES_WITH_IMPLICIT_ROLE.put("button", "button"); INPUT_TYPES_WITH_IMPLICIT_ROLE.put("checkbox", "checkbox"); INPUT_TYPES_WITH_IMPLICIT_ROLE.put("image", "button"); INPUT_TYPES_WITH_IMPLICIT_ROLE.put("number", "spinbutton"); INPUT_TYPES_WITH_IMPLICIT_ROLE.put("radio", "radio"); INPUT_TYPES_WITH_IMPLICIT_ROLE.put("range", "slider"); INPUT_TYPES_WITH_IMPLICIT_ROLE.put("reset", "button"); INPUT_TYPES_WITH_IMPLICIT_ROLE.put("submit", "button"); } private static final Set<String> ATTRIBUTES_WITH_IMPLICIT_STATE_OR_PROPERTY = new HashSet<>(); static { ATTRIBUTES_WITH_IMPLICIT_STATE_OR_PROPERTY.add("colspan"); ATTRIBUTES_WITH_IMPLICIT_STATE_OR_PROPERTY.add("disabled"); ATTRIBUTES_WITH_IMPLICIT_STATE_OR_PROPERTY.add("hidden"); ATTRIBUTES_WITH_IMPLICIT_STATE_OR_PROPERTY.add("readonly"); ATTRIBUTES_WITH_IMPLICIT_STATE_OR_PROPERTY.add("required"); ATTRIBUTES_WITH_IMPLICIT_STATE_OR_PROPERTY.add("rowspan"); } private static final String h1WarningMessage = "Consider using the" + " \u201Ch1\u201D element as a top-level heading only (all" + " \u201Ch1\u201D elements are treated as top-level headings" + " by many screen readers and other tools)."; private class IdrefLocator { private final Locator locator; private final String idref; private final String additional; /** * @param locator * @param idref */ public IdrefLocator(Locator locator, String idref) { this.locator = new LocatorImpl(locator); this.idref = idref; this.additional = null; } public IdrefLocator(Locator locator, String idref, String additional) { this.locator = new LocatorImpl(locator); this.idref = idref; this.additional = additional; } /** * Returns the locator. * * @return the locator */ public Locator getLocator() { return locator; } /** * Returns the idref. * * @return the idref */ public String getIdref() { return idref; } /** * Returns the additional. * * @return the additional */ public String getAdditional() { return additional; } } private class StackNode { private final int ancestorMask; private final String name; // null if not HTML private final StringBuilder textContent; private final String role; private final String activeDescendant; private final String forAttr; private Set<Locator> imagesLackingAlt = new HashSet<>(); private Locator nonEmptyOption = null; private Locator locator = null; private boolean selectedOptions = false; private boolean labeledDescendants = false; private boolean trackDescendants = false; private boolean textNodeFound = false; private boolean imgFound = false; private boolean embeddedContentFound = false; private boolean figcaptionNeeded = false; private boolean figcaptionContentFound = false; private boolean headingFound = false; private boolean optionNeeded = false; private boolean optionFound = false; private boolean noValueOptionFound = false; private boolean emptyValueOptionFound = false; private boolean isCollectingCharacters = false; /** * @param ancestorMask */ public StackNode(int ancestorMask, String name, String role, String activeDescendant, String forAttr) { this.ancestorMask = ancestorMask; this.name = name; this.role = role; this.activeDescendant = activeDescendant; this.forAttr = forAttr; this.textContent = new StringBuilder(); } /** * Returns the ancestorMask. * * @return the ancestorMask */ public int getAncestorMask() { return ancestorMask; } /** * Returns the name. * * @return the name */ public String getName() { return name; } /** * Returns the selectedOptions. * * @return the selectedOptions */ public boolean isSelectedOptions() { return selectedOptions; } /** * Sets the selectedOptions. * * @param selectedOptions * the selectedOptions to set */ public void setSelectedOptions() { this.selectedOptions = true; } /** * Returns the labeledDescendants. * * @return the labeledDescendants */ public boolean isLabeledDescendants() { return labeledDescendants; } /** * Sets the labeledDescendants. * * @param labeledDescendants * the labeledDescendants to set */ public void setLabeledDescendants() { this.labeledDescendants = true; } /** * Returns the trackDescendants. * * @return the trackDescendants */ public boolean isTrackDescendant() { return trackDescendants; } /** * Sets the trackDescendants. * * @param trackDescendants * the trackDescendants to set */ public void setTrackDescendants() { this.trackDescendants = true; } /** * Returns the role. * * @return the role */ public String getRole() { return role; } /** * Returns the activeDescendant. * * @return the activeDescendant */ public String getActiveDescendant() { return activeDescendant; } /** * Returns the forAttr. * * @return the forAttr */ public String getForAttr() { return forAttr; } /** * Returns the textNodeFound. * * @return the textNodeFound */ public boolean hasTextNode() { return textNodeFound; } /** * Sets the textNodeFound. */ public void setTextNodeFound() { this.textNodeFound = true; } /** * Returns the imgFound. * * @return the imgFound */ public boolean hasImg() { return imgFound; } /** * Sets the imgFound. */ public void setImgFound() { this.imgFound = true; } /** * Returns the embeddedContentFound. * * @return the embeddedContentFound */ public boolean hasEmbeddedContent() { return embeddedContentFound; } /** * Sets the embeddedContentFound. */ public void setEmbeddedContentFound() { this.embeddedContentFound = true; } /** * Returns the figcaptionNeeded. * * @return the figcaptionNeeded */ public boolean needsFigcaption() { return figcaptionNeeded; } /** * Sets the figcaptionNeeded. */ public void setFigcaptionNeeded() { this.figcaptionNeeded = true; } /** * Returns the figcaptionContentFound. * * @return the figcaptionContentFound */ public boolean hasFigcaptionContent() { return figcaptionContentFound; } /** * Sets the figcaptionContentFound. */ public void setFigcaptionContentFound() { this.figcaptionContentFound = true; } /** * Returns the headingFound. * * @return the headingFound */ public boolean hasHeading() { return headingFound; } /** * Sets the headingFound. */ public void setHeadingFound() { this.headingFound = true; } /** * Returns the imagesLackingAlt * * @return the imagesLackingAlt */ public Set<Locator> getImagesLackingAlt() { return imagesLackingAlt; } /** * Adds to the imagesLackingAlt */ public void addImageLackingAlt(Locator locator) { this.imagesLackingAlt.add(locator); } /** * Returns the optionNeeded. * * @return the optionNeeded */ public boolean isOptionNeeded() { return optionNeeded; } /** * Sets the optionNeeded. */ public void setOptionNeeded() { this.optionNeeded = true; } /** * Returns the optionFound. * * @return the optionFound */ public boolean hasOption() { return optionFound; } /** * Sets the optionFound. */ public void setOptionFound() { this.optionFound = true; } /** * Returns the noValueOptionFound. * * @return the noValueOptionFound */ public boolean hasNoValueOption() { return noValueOptionFound; } /** * Sets the noValueOptionFound. */ public void setNoValueOptionFound() { this.noValueOptionFound = true; } /** * Returns the emptyValueOptionFound. * * @return the emptyValueOptionFound */ public boolean hasEmptyValueOption() { return emptyValueOptionFound; } /** * Sets the emptyValueOptionFound. */ public void setEmptyValueOptionFound() { this.emptyValueOptionFound = true; } /** * Returns the nonEmptyOption. * * @return the nonEmptyOption */ public Locator nonEmptyOptionLocator() { return nonEmptyOption; } /** * Sets the nonEmptyOption. */ public void setNonEmptyOption(Locator locator) { this.nonEmptyOption = locator; } /** * Sets the collectingCharacters. */ public void setIsCollectingCharacters(boolean isCollectingCharacters) { this.isCollectingCharacters = isCollectingCharacters; } /** * Gets the collectingCharacters. */ public boolean getIsCollectingCharacters() { return this.isCollectingCharacters; } /** * Appends to the textContent. */ public void appendToTextContent(char ch[], int start, int length) { this.textContent.append(ch, start, length); } /** * Gets the textContent. */ public StringBuilder getTextContent() { return this.textContent; } /** * Returns the locator. * * @return the locator */ public Locator locator() { return locator; } /** * Sets the locator. */ public void setLocator(Locator locator) { this.locator = locator; } } private StackNode[] stack; private int currentPtr; private int currentSectioningDepth; public Assertions() { super(); } private HttpServletRequest request; private boolean sourceIsCss; public void setSourceIsCss(boolean sourceIsCss) { this.sourceIsCss = sourceIsCss; } private boolean hasPageEmitterInCallStack() { for (StackTraceElement el : Thread.currentThread().getStackTrace()) { if (el.getClassName().equals("nu.validator.servlet.PageEmitter")) { return true; } } return false; } private boolean isAriaLabelMisuse(String ariaLabel, String localName, String role, Attributes atts) { if (ariaLabel == null) { return false; } if (Arrays.binarySearch(INTERACTIVE_ELEMENTS, localName) >= 0) { return false; } if (isLabelableElement(localName, atts)) { return false; } if ( // "a" == localName // INTERACTIVE_ELEMENTS "area" == localName // https://github.com/validator/validator/issues/775#issuecomment-494455608 || "article" == localName || "aside" == localName || "audio" == localName // "button" == localName // INTERACTIVE_ELEMENTS // "details" == localName // INTERACTIVE_ELEMENTS // "dialog" == localName // INTERACTIVE_ELEMENTS || "dl" == localName || "fieldset" == localName || "figure" == localName || "footer" == localName || "form" == localName || "h1" == localName || "h2" == localName || "h3" == localName || "h4" == localName || "h5" == localName || "h6" == localName || "header" == localName || "hr" == localName // "iframe" == localName // INTERACTIVE_ELEMENTS || "img" == localName // "input" == localName // isLabelableElement || "main" == localName // "meter" == localName // isLabelableElement || "nav" == localName || "ol" == localName // "progress" == localName // isLabelableElement || "section" == localName // "select" == localName // isLabelableElement || "summary" == localName // https://github.com/validator/validator/issues/775#issuecomment-494459220 || "svg" == localName || "table" == localName // "textarea" == localName // INTERACTIVE_ELEMENTS || "video" == localName || "ul" == localName ) { return false; } if (role != null) { return false; } return true; } private boolean isLabelableElement(String localName, Attributes atts) { if ("button" == localName || ("input" == localName && !AttributeUtil .lowerCaseLiteralEqualsIgnoreAsciiCaseString("hidden", atts.getValue("", "type"))) || "meter" == localName || "output" == localName || "progress" == localName || "select" == localName || "textarea" == localName) { return true; } return false; } private void incrementUseCounter(String useCounterName) { if (request != null) { request.setAttribute( "http://validator.nu/properties/" + useCounterName, true); } } private void push(StackNode node) { currentPtr++; if (currentPtr == stack.length) { StackNode[] newStack = new StackNode[stack.length + 64]; System.arraycopy(stack, 0, newStack, 0, stack.length); stack = newStack; } stack[currentPtr] = node; } private StackNode pop() { return stack[currentPtr } private StackNode peek() { return stack[currentPtr]; } private Map<StackNode, Locator> openSingleSelects = new HashMap<>(); private Map<StackNode, Locator> openLabels = new HashMap<>(); private Map<StackNode, TaintableLocatorImpl> openMediaElements = new HashMap<>(); private Map<StackNode, Locator> openActiveDescendants = new HashMap<>(); private LinkedHashSet<IdrefLocator> formControlReferences = new LinkedHashSet<>(); private LinkedHashSet<IdrefLocator> formElementReferences = new LinkedHashSet<>(); private LinkedHashSet<IdrefLocator> needsAriaOwner = new LinkedHashSet<>(); private Set<String> formControlIds = new HashSet<>(); private Set<String> formElementIds = new HashSet<>(); private LinkedHashSet<IdrefLocator> listReferences = new LinkedHashSet<>(); private Set<String> listIds = new HashSet<>(); private LinkedHashSet<IdrefLocator> ariaReferences = new LinkedHashSet<>(); private Set<String> allIds = new HashSet<>(); private int currentFigurePtr; private int currentHeadingPtr; private int currentSectioningElementPtr; private boolean hasVisibleMain; private boolean hasMetaCharset; private boolean hasMetaDescription; private boolean hasContentTypePragma; private boolean hasAutofocus; private boolean hasTopLevelH1; private int numberOfTemplatesDeep = 0; private Set<Locator> secondLevelH1s = new HashSet<>(); private Map<Locator, Map<String, String>> siblingSources = new ConcurrentHashMap<>(); private final void errContainedInOrOwnedBy(String role, Locator locator) throws SAXException { err("An element with \u201Crole=" + role + "\u201D" + " must be contained in, or owned by, an element with " + renderRoleSet(REQUIRED_ROLE_ANCESTOR_BY_DESCENDANT.get(role)) + ".", locator); } private final void errObsoleteAttribute(String attribute, String element, String suggestion) throws SAXException { err("The \u201C" + attribute + "\u201D attribute on the \u201C" + element + "\u201D element is obsolete." + suggestion); } private final void warnObsoleteAttribute(String attribute, String element, String suggestion) throws SAXException { warn("The \u201C" + attribute + "\u201D attribute on the \u201C" + element + "\u201D element is obsolete." + suggestion); } private final void warnExplicitRoleUnnecessaryForType(String element, String role, String type) throws SAXException { warn("The \u201C" + role + "\u201D role is unnecessary for element" + " \u201C" + element + "\u201D whose" + " type is" + " \u201C" + type + "\u201D."); } private boolean currentElementHasRequiredAncestorRole( Set<String> requiredAncestorRoles) { for (String role : requiredAncestorRoles) { for (int i = 0; i < currentPtr; i++) { if (role.equals(stack[currentPtr - i].getRole())) { return true; } String openElementName = stack[currentPtr - i].getName(); if (ELEMENTS_WITH_IMPLICIT_ROLE.containsKey(openElementName) && ELEMENTS_WITH_IMPLICIT_ROLE.get(openElementName) .equals(role)) { return true; } if (ELEMENTS_WITH_IMPLICIT_ROLES.containsKey(openElementName) && Arrays.binarySearch(ELEMENTS_WITH_IMPLICIT_ROLES .get(openElementName), role) >= 0) { return true; } } } return false; } private void checkForInteractiveAncestorRole(String descendantUiString) throws SAXException { for (int i = 0; i < currentPtr; i++) { String ancestorRole = stack[currentPtr - i].getRole(); if (ancestorRole != null && ancestorRole != "" && Arrays.binarySearch( PROHIBITED_INTERACTIVE_ANCESTOR_ROLES, ancestorRole) >= 0) { err(descendantUiString + " must not appear as a" + " descendant of an element with the attribute" + " \u201Crole=" + ancestorRole + "\u201D."); } } } /** * @see nu.validator.checker.Checker#endDocument() */ @Override public void endDocument() throws SAXException { // label for for (IdrefLocator idrefLocator : formControlReferences) { if (!formControlIds.contains(idrefLocator.getIdref())) { err("The value of the \u201Cfor\u201D attribute of the" + " \u201Clabel\u201D element must be the ID of a" + " non-hidden form control.", idrefLocator.getLocator()); } } // references to IDs from form attributes for (IdrefLocator idrefLocator : formElementReferences) { if (!formElementIds.contains(idrefLocator.getIdref())) { err("The \u201Cform\u201D attribute must refer to a form element.", idrefLocator.getLocator()); } } // input list for (IdrefLocator idrefLocator : listReferences) { if (!listIds.contains(idrefLocator.getIdref())) { err("The \u201Clist\u201D attribute of the \u201Cinput\u201D element must refer to a \u201Cdatalist\u201D element.", idrefLocator.getLocator()); } } // ARIA idrefs for (IdrefLocator idrefLocator : ariaReferences) { if (!allIds.contains(idrefLocator.getIdref())) { err("The \u201C" + idrefLocator.getAdditional() + "\u201D attribute must point to an element in the same document.", idrefLocator.getLocator()); } } // ARIA required owners for (IdrefLocator idrefLocator : needsAriaOwner) { boolean foundOwner = false; String role = idrefLocator.getAdditional(); for (String ownerRole : REQUIRED_ROLE_ANCESTOR_BY_DESCENDANT.get( role)) { if (ariaOwnsIdsByRole.size() != 0 && ariaOwnsIdsByRole.get(ownerRole) != null && ariaOwnsIdsByRole.get(ownerRole).contains( idrefLocator.getIdref())) { foundOwner = true; break; } } if (!foundOwner) { errContainedInOrOwnedBy(role, idrefLocator.getLocator()); } } if (hasTopLevelH1) { for (Locator locator : secondLevelH1s) { warn(h1WarningMessage, locator); } } reset(); stack = null; } private static double getDoubleAttribute(Attributes atts, String name) { String str = atts.getValue("", name); if (str == null) { return Double.NaN; } else { try { return Double.parseDouble(str); } catch (NumberFormatException e) { return Double.NaN; } } } /** * @see nu.validator.checker.Checker#endElement(java.lang.String, * java.lang.String, java.lang.String) */ @Override public void endElement(String uri, String localName, String name) throws SAXException { if ("http: && "template".equals(localName)) { numberOfTemplatesDeep if (numberOfTemplatesDeep != 0) { return; } } else if (numberOfTemplatesDeep > 0) { return; } StackNode node = pop(); String systemId = node.locator().getSystemId(); String publicId = node.locator().getPublicId(); Locator locator = null; openSingleSelects.remove(node); openLabels.remove(node); openMediaElements.remove(node); if ("http: if ("figure" == localName) { if (node.hasFigcaptionContent() && (node.role != null)) { err("A \u201Cfigure\u201D element with a" + " \u201Cfigcaption\u201D descendant must not" + " have a \u201Crole\u201D attribute."); } if ((node.needsFigcaption() && !node.hasFigcaptionContent()) || node.hasTextNode() || node.hasEmbeddedContent()) { for (Locator imgLocator : node.getImagesLackingAlt()) { err("An \u201Cimg\u201D element must have an" + " \u201Calt\u201D attribute, except under" + " certain conditions. For details, consult" + " guidance on providing text alternatives" + " for images.", imgLocator); } } } else if ("picture" == localName) { siblingSources.clear(); } else if ("select" == localName && node.isOptionNeeded()) { if (!node.hasOption()) { err("A \u201Cselect\u201D element with a" + " \u201Crequired\u201D attribute, and without a" + " \u201Cmultiple\u201D attribute, and without a" + " \u201Csize\u201D attribute whose value is" + " greater than" + " \u201C1\u201D, must have a child" + " \u201Coption\u201D element."); } if (node.nonEmptyOptionLocator() != null) { err("The first child \u201Coption\u201D element of a" + " \u201Cselect\u201D element with a" + " \u201Crequired\u201D attribute, and without a" + " \u201Cmultiple\u201D attribute, and without a" + " \u201Csize\u201D attribute whose value is" + " greater than" + " \u201C1\u201D, must have either an empty" + " \u201Cvalue\u201D attribute, or must have no" + " text content." + " Consider either adding a placeholder option" + " label, or adding a" + " \u201Csize\u201D attribute with a value equal" + " to the number of" + " \u201Coption\u201D elements.", node.nonEmptyOptionLocator()); } } else if ("section" == localName && !node.hasHeading()) { warn("Section lacks heading. Consider using" + " \u201ch2\u201d-\u201ch6\u201d elements to add" + " identifying headings to all sections.", node.locator()); } else if ("article" == localName && !node.hasHeading()) { warn("Article lacks heading. Consider using" + " \u201ch2\u201d-\u201ch6\u201d elements to add" + " identifying headings to all articles.", node.locator()); } else if (("h1" == localName || "h2" == localName || "h3" == localName || "h4" == localName || "h5" == localName || "h6" == localName) && !node.hasTextNode() && !node.hasImg()) { warn("Empty heading.", node.locator()); } else if ("option" == localName && !stack[currentPtr].hasOption()) { stack[currentPtr].setOptionFound(); } else if ("style" == localName) { String styleContents = node.getTextContent().toString(); int lineOffset = 0; if (styleContents.startsWith("\n")) { lineOffset = 1; } ApplContext ac = new ApplContext("en"); ac.setCssVersionAndProfile("css3svg"); ac.setMedium("all"); ac.setSuggestPropertyName(false); ac.setTreatVendorExtensionsAsWarnings(true); ac.setTreatCssHacksAsWarnings(true); ac.setWarningLevel(-1); ac.setFakeURL("file://localhost/StyleElement"); StyleSheetParser styleSheetParser = new StyleSheetParser(); styleSheetParser.parseStyleSheet(ac, new StringReader(styleContents.substring(lineOffset)), null); styleSheetParser.getStyleSheet().findConflicts(ac); Errors errors = styleSheetParser.getStyleSheet().getErrors(); if (errors.getErrorCount() > 0) { incrementUseCounter("style-element-errors-found"); } for (int i = 0; i < errors.getErrorCount(); i++) { String message = ""; String cssProperty = ""; String cssMessage = ""; CssError error = errors.getErrorAt(i); int beginLine = error.getBeginLine() + lineOffset; int beginColumn = error.getBeginColumn(); int endLine = error.getEndLine() + lineOffset; int endColumn = error.getEndColumn(); if (beginLine == 0) { continue; } Throwable ex = error.getException(); if (ex instanceof CssParseException) { CssParseException cpe = (CssParseException) ex; if ("generator.unrecognize" .equals(cpe.getErrorType())) { cssMessage = "Parse Error"; } if (cpe.getProperty() != null) { cssProperty = String.format("\u201c%s\u201D: ", cpe.getProperty()); } if (cpe.getMessage() != null) { cssMessage = cpe.getMessage(); } if (!"".equals(cssMessage)) { message = cssProperty + cssMessage.trim(); if (!".".equals( message.substring(message.length() - 1))) { message = message + "."; } } } else { message = ex.getMessage(); } if (!"".equals(message)) { int lastLine = node.locator.getLineNumber() + endLine - 1; int lastColumn = endColumn; int columnOffset = node.locator.getColumnNumber(); if (error.getBeginLine() == 1) { if (lineOffset != 0) { columnOffset = 0; } } else { columnOffset = 0; } String prefix = sourceIsCss ? "" : "CSS: "; SAXParseException spe = new SAXParseException( prefix + message, publicId, systemId, lastLine, lastColumn); int[] start = { node.locator.getLineNumber() + beginLine - 1, beginColumn, columnOffset }; if ((getErrorHandler() instanceof MessageEmitterAdapter) && !(getErrorHandler() instanceof TestRunner)) { ((MessageEmitterAdapter) getErrorHandler()) .errorWithStart(spe, start); } else { getErrorHandler().error(spe); } } } } if ("article" == localName || "aside" == localName || "nav" == localName || "section" == localName) { currentSectioningElementPtr = currentPtr - 1; currentSectioningDepth } } if ((locator = openActiveDescendants.remove(node)) != null) { warn("Attribute \u201Caria-activedescendant\u201D value should " + "either refer to a descendant element, or should " + "be accompanied by attribute \u201Caria-owns\u201D.", locator); } } /** * @see nu.validator.checker.Checker#startDocument() */ @Override public void startDocument() throws SAXException { reset(); request = getRequest(); stack = new StackNode[32]; currentPtr = 0; currentFigurePtr = -1; currentHeadingPtr = -1; currentSectioningElementPtr = -1; currentSectioningDepth = 0; stack[0] = null; hasVisibleMain = false; hasMetaCharset = false; hasMetaDescription = false; hasContentTypePragma = false; hasAutofocus = false; hasTopLevelH1 = false; numberOfTemplatesDeep = 0; } @Override public void reset() { openSingleSelects.clear(); openLabels.clear(); openMediaElements.clear(); openActiveDescendants.clear(); ariaOwnsIdsByRole.clear(); needsAriaOwner.clear(); formControlReferences.clear(); formElementReferences.clear(); formControlIds.clear(); formElementIds.clear(); listReferences.clear(); listIds.clear(); ariaReferences.clear(); allIds.clear(); siblingSources.clear(); secondLevelH1s.clear(); } /** * @see nu.validator.checker.Checker#startElement(java.lang.String, * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException { if ("http: && "template".equals(localName)) { numberOfTemplatesDeep++; if (numberOfTemplatesDeep != 1) { return; } } else if (numberOfTemplatesDeep > 0) { return; } Set<String> ids = new HashSet<>(); String role = null; String inputTypeVal = null; String activeDescendant = null; String ariaLabel = null; String owns = null; String forAttr = null; boolean href = false; boolean activeDescendantWithAriaOwns = false; // see nu.validator.datatype.ImageCandidateStrings System.setProperty("nu.validator.checker.imageCandidateString.hasWidth", "0"); StackNode parent = peek(); int ancestorMask = 0; String parentRole = null; String parentName = null; if (parent != null) { ancestorMask = parent.getAncestorMask(); parentName = parent.getName(); parentRole = parent.getRole(); } if ("http: && "math".equals(localName) && atts.getIndex("", "role") > -1 && "math".equals(atts.getValue("", "role"))) { warn("Element \u201Cmath\u201D does not need a" + " \u201Crole\u201D attribute."); } if ("http: boolean controls = false; boolean hidden = false; boolean toolbar = false; boolean usemap = false; boolean ismap = false; boolean selected = false; boolean itemid = false; boolean itemref = false; boolean itemscope = false; boolean itemtype = false; boolean tabindex = false; boolean languageJavaScript = false; boolean typeNotTextJavaScript = false; boolean hasAriaAttributesOtherThanAriaHidden = false; boolean isCustomElement = false; String xmlLang = null; String lang = null; String id = null; String list = null; int len = atts.getLength(); for (int i = 0; i < len; i++) { String attUri = atts.getURI(i); if (attUri.length() == 0) { String attLocal = atts.getLocalName(i); if ("aria-hidden".equals(attLocal)) { if (Arrays.binarySearch( ARIA_HIDDEN_NOT_ALLOWED_ELEMENTS, localName) >= 0) { err("The \u201Caria-hidden\u201D attribute must not" + " be specified on the \u201C" + localName + "\u201D element."); } else if ("input" == localName && "hidden".equals(atts.getValue("", "type"))) { err("The \u201Caria-hidden\u201D attribute must not" + " be specified on an \u201Cinput\u201D" + " element whose \u201Ctype\u201D" + " attribute has the value" + " \u201Chidden\u201D."); } } else if (attLocal.startsWith("aria-")) { hasAriaAttributesOtherThanAriaHidden = true; } if (ATTRIBUTES_WITH_IMPLICIT_STATE_OR_PROPERTY.contains( attLocal)) { String stateOrProperty = "aria-" + attLocal; if (atts.getIndex("", stateOrProperty) > -1) { String attLocalValue = atts.getValue("", attLocal); String stateOrPropertyValue = atts.getValue("", stateOrProperty); if ("true".equals(stateOrPropertyValue) || attLocalValue.equals( stateOrPropertyValue)) { warn("Attribute \u201C" + stateOrProperty + "\u201D is unnecessary for elements" + " that have attribute \u201C" + attLocal + "\u201D."); } else if ("false".equals(stateOrPropertyValue)) { err("Attribute \u201C" + stateOrProperty + "\u201D must not be specified on" + " elements that have attribute" + " \u201C" + attLocal + "\u201D."); } else if (!attLocalValue.equals( stateOrPropertyValue)) { err("Attribute \u201C" + stateOrProperty + "\u201D must not be specified with" + " a different value than attribute" + " \u201C" + attLocal + "\u201D."); } } } if ("embed".equals(localName)) { for (int j = 0; j < attLocal.length(); j++) { char c = attLocal.charAt(j); if (c >= 'A' && c <= 'Z') { err("Bad attribute name \u201c" + attLocal + "\u201d. Attribute names for the" + " \u201cembed\u201d element must not" + " contain uppercase ASCII letters."); } } if (!NCName.isNCName(attLocal)) { err("Bad attribute name \u201c" + attLocal + "\u201d. Attribute names for the" + " \u201cembed\u201d element must be" + " XML-compatible."); } } if ("style" == attLocal) { String styleContents = atts.getValue(i); ApplContext ac = new ApplContext("en"); ac.setCssVersionAndProfile("css3svg"); ac.setMedium("all"); ac.setSuggestPropertyName(false); ac.setTreatVendorExtensionsAsWarnings(true); ac.setTreatCssHacksAsWarnings(true); ac.setWarningLevel(-1); ac.setFakeURL("file://localhost/StyleAttribute"); StyleSheetParser styleSheetParser = new StyleSheetParser(); styleSheetParser.parseStyleAttribute(ac, new ByteArrayInputStream( styleContents.getBytes()), "", ac.getFakeURL(), getDocumentLocator().getLineNumber()); styleSheetParser.getStyleSheet().findConflicts(ac); Errors errors = styleSheetParser.getStyleSheet().getErrors(); if (errors.getErrorCount() > 0) { incrementUseCounter("style-attribute-errors-found"); } for (int j = 0; j < errors.getErrorCount(); j++) { String message = ""; String cssProperty = ""; String cssMessage = ""; CssError error = errors.getErrorAt(j); Throwable ex = error.getException(); if (ex instanceof CssParseException) { CssParseException cpe = (CssParseException) ex; if ("generator.unrecognize" .equals(cpe.getErrorType())) { cssMessage = "Parse Error"; } if (cpe.getProperty() != null) { cssProperty = String.format( "\u201c%s\u201D: ", cpe.getProperty()); } if (cpe.getMessage() != null) { cssMessage = cpe.getMessage(); } if (!"".equals(cssMessage)) { message = cssProperty + cssMessage.trim(); if (!".".equals(message.substring( message.length() - 1))) { message = message + "."; } } } else { message = ex.getMessage(); } if (!"".equals(message)) { err("CSS: " + message); } } } else if ("tabindex" == attLocal) { tabindex = true; } else if ("href" == attLocal) { href = true; } else if ("controls" == attLocal) { controls = true; } else if ("type" == attLocal && "param" != localName && "ol" != localName && "ul" != localName && "li" != localName) { if ("input" == localName) { inputTypeVal = atts.getValue(i).toLowerCase(); } String attValue = atts.getValue(i); if (AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "hidden", attValue)) { hidden = true; } else if (AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "toolbar", attValue)) { toolbar = true; } if (!AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "text/javascript", attValue)) { typeNotTextJavaScript = true; } } else if ("role" == attLocal) { role = atts.getValue(i); } else if ("aria-activedescendant" == attLocal) { activeDescendant = atts.getValue(i); } else if ("aria-label" == attLocal) { ariaLabel = atts.getValue(i); } else if ("aria-owns" == attLocal) { owns = atts.getValue(i); } else if ("list" == attLocal) { list = atts.getValue(i); } else if ("lang" == attLocal) { lang = atts.getValue(i); } else if ("id" == attLocal) { id = atts.getValue(i); } else if ("for" == attLocal && "label" == localName) { forAttr = atts.getValue(i); ancestorMask |= LABEL_FOR_MASK; } else if ("ismap" == attLocal) { ismap = true; } else if ("selected" == attLocal) { selected = true; } else if ("usemap" == attLocal && "input" != localName) { usemap = true; } else if ("itemid" == attLocal) { itemid = true; } else if ("itemref" == attLocal) { itemref = true; } else if ("itemscope" == attLocal) { itemscope = true; } else if ("itemtype" == attLocal) { itemtype = true; } else if ("language" == attLocal && AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "javascript", atts.getValue(i))) { languageJavaScript = true; } else if ("rev" == attLocal && !("1".equals(System.getProperty( "nu.validator.schema.rdfa-full")))) { errObsoleteAttribute("rev", localName, " Use the \u201Crel\u201D attribute instead," + " with a term having the opposite meaning."); } else if (OBSOLETE_ATTRIBUTES.containsKey(attLocal) && "ol" != localName && "ul" != localName && "li" != localName) { String[] elementNames = OBSOLETE_ATTRIBUTES.get( attLocal); if (Arrays.binarySearch(elementNames, localName) >= 0) { String suggestion = OBSOLETE_ATTRIBUTES_MSG.containsKey( attLocal) ? " " + OBSOLETE_ATTRIBUTES_MSG.get( attLocal) : ""; errObsoleteAttribute(attLocal, localName, suggestion); } } else if (OBSOLETE_STYLE_ATTRS.containsKey(attLocal)) { String[] elementNames = OBSOLETE_STYLE_ATTRS.get( attLocal); if (Arrays.binarySearch(elementNames, localName) >= 0) { errObsoleteAttribute(attLocal, localName, " Use CSS instead."); } } else if (INPUT_ATTRIBUTES.containsKey(attLocal) && "input" == localName) { String[] allowedTypes = INPUT_ATTRIBUTES.get(attLocal); inputTypeVal = inputTypeVal == null ? "text" : inputTypeVal; if (Arrays.binarySearch(allowedTypes, inputTypeVal) < 0) { err("Attribute \u201c" + attLocal + "\u201d is only allowed when the input" + " type is " + renderTypeList(allowedTypes) + "."); } } else if ("autofocus" == attLocal) { if (hasAutofocus) { err("A document must not include more than one" + " \u201Cautofocus\u201D attribute."); } hasAutofocus = true; } } else if ("http: if ("lang" == atts.getLocalName(i)) { xmlLang = atts.getValue(i); } } if (atts.getType(i) == "ID" || "id" == atts.getLocalName(i)) { String attVal = atts.getValue(i); if (attVal.length() != 0) { ids.add(attVal); } } } if (localName.contains("-")) { isCustomElement = true; if (atts.getIndex("", "is") > -1) { err("Autonomous custom elements must not specify the" + " \u201cis\u201d attribute."); } try { CustomElementName.THE_INSTANCE.checkValid(localName); } catch (DatatypeException e) { try { if (getErrorHandler() != null) { String msg = e.getMessage(); if (e instanceof Html5DatatypeException) { msg = msg.substring(msg.indexOf(": ") + 2); } VnuBadElementNameException ex = new VnuBadElementNameException( localName, uri, msg, getDocumentLocator(), CustomElementName.class, false); getErrorHandler().error(ex); } } catch (ClassNotFoundException ce) { } } } if ("input".equals(localName)) { if (atts.getIndex("", "name") > -1 && "isindex".equals(atts.getValue("", "name"))) { err("The value \u201cisindex\u201d for the \u201cname\u201d" + " attribute of the \u201cinput\u201d element is" + " not allowed."); } if (atts.getIndex("", "hidden") > -1 && (atts.getIndex("", "aria-hidden") > -1 || hasAriaAttributesOtherThanAriaHidden)) { err("An \u201cinput\u201d element with a \u201ctype\u201d" + " attribute whose value is \u201chidden\u201d" + " must not have any \u201Caria-*\u201D" + " attributes."); } inputTypeVal = inputTypeVal == null ? "text" : inputTypeVal; if (atts.getIndex("", "autocomplete") > -1) { Class<?> datatypeClass = null; String autocompleteVal = atts.getValue("", "autocomplete"); try { if (!"on".equals(autocompleteVal) && !"off".equals(autocompleteVal)) { if ("hidden".equals(inputTypeVal)) { AutocompleteDetailsAny.THE_INSTANCE.checkValid( autocompleteVal); datatypeClass = AutocompleteDetailsAny.class; } else if ("text".equals(inputTypeVal) || "search".equals(autocompleteVal)) { AutocompleteDetailsText.THE_INSTANCE.checkValid( autocompleteVal); datatypeClass = AutocompleteDetailsText.class; } else if ("password".equals(inputTypeVal)) { AutocompleteDetailsPassword.THE_INSTANCE.checkValid( autocompleteVal); datatypeClass = AutocompleteDetailsPassword.class; } else if ("url".equals(inputTypeVal)) { AutocompleteDetailsUrl.THE_INSTANCE.checkValid( autocompleteVal); datatypeClass = AutocompleteDetailsUrl.class; } else if ("email".equals(inputTypeVal)) { AutocompleteDetailsEmail.THE_INSTANCE.checkValid( autocompleteVal); datatypeClass = AutocompleteDetailsEmail.class; } else if ("tel".equals(inputTypeVal)) { AutocompleteDetailsTel.THE_INSTANCE.checkValid( autocompleteVal); datatypeClass = AutocompleteDetailsTel.class; } else if ("number".equals(inputTypeVal)) { AutocompleteDetailsNumeric.THE_INSTANCE.checkValid( autocompleteVal); datatypeClass = AutocompleteDetailsNumeric.class; } else if ("month".equals(inputTypeVal)) { AutocompleteDetailsMonth.THE_INSTANCE.checkValid( autocompleteVal); datatypeClass = AutocompleteDetailsMonth.class; } else if ("date".equals(inputTypeVal)) { AutocompleteDetailsDate.THE_INSTANCE.checkValid( autocompleteVal); datatypeClass = AutocompleteDetailsDate.class; } } } catch (DatatypeException e) { try { if (getErrorHandler() != null) { String msg = e.getMessage(); msg = msg.substring(msg.indexOf(": ") + 2); VnuBadAttrValueException ex = new VnuBadAttrValueException( localName, uri, "autocomplete", autocompleteVal, msg, getDocumentLocator(), datatypeClass, false); getErrorHandler().error(ex); } } catch (ClassNotFoundException ce) { } } } } if ("img".equals(localName) || "source".equals(localName)) { if (atts.getIndex("", "srcset") > -1) { String srcsetVal = atts.getValue("", "srcset"); try { if (atts.getIndex("", "sizes") > -1) { ImageCandidateStringsWidthRequired.THE_INSTANCE.checkValid( srcsetVal); } else { ImageCandidateStrings.THE_INSTANCE.checkValid( srcsetVal); } // see nu.validator.datatype.ImageCandidateStrings if ("1".equals(System.getProperty( "nu.validator.checker.imageCandidateString.hasWidth"))) { if (atts.getIndex("", "sizes") < 0) { err("When the \u201csrcset\u201d attribute has" + " any image candidate string with a" + " width descriptor, the" + " \u201csizes\u201d attribute" + " must also be present."); } } } catch (DatatypeException e) { Class<?> datatypeClass = ImageCandidateStrings.class; if (atts.getIndex("", "sizes") > -1) { datatypeClass = ImageCandidateStringsWidthRequired.class; } try { if (getErrorHandler() != null) { String msg = e.getMessage(); if (e instanceof Html5DatatypeException) { Html5DatatypeException ex5 = (Html5DatatypeException) e; if (!ex5.getDatatypeClass().equals( ImageCandidateURL.class)) { msg = msg.substring( msg.indexOf(": ") + 2); } } VnuBadAttrValueException ex = new VnuBadAttrValueException( localName, uri, "srcset", srcsetVal, msg, getDocumentLocator(), datatypeClass, false); getErrorHandler().error(ex); } } catch (ClassNotFoundException ce) { } } if ("picture".equals(parentName) && !siblingSources.isEmpty()) { for (Map.Entry<Locator, Map<String, String>> entry : siblingSources.entrySet()) { Locator locator = entry.getKey(); Map<String, String> sourceAtts = entry.getValue(); String media = sourceAtts.get("media"); if (media == null && sourceAtts.get("type") == null) { err("A \u201csource\u201d element that has a" + " following sibling" + " \u201csource\u201d element or" + " \u201cimg\u201d element with a" + " \u201csrcset\u201d attribute" + " must have a" + " \u201cmedia\u201d attribute and/or" + " \u201ctype\u201d attribute.", locator); siblingSources.remove(locator); } else if (media != null && "".equals(trimSpaces(media))) { err("Value of \u201cmedia\u201d attribute here" + " must not be empty.", locator); } else if (media != null && AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "all", trimSpaces(media))) { err("Value of \u201cmedia\u201d attribute here" + " must not be \u201call\u201d.", locator); } } } } else if (atts.getIndex("", "sizes") > -1) { err("The \u201csizes\u201d attribute may be specified" + " only if the \u201csrcset\u201d attribute is" + " also present."); } } if ("picture".equals(parentName) && "source".equals(localName)) { Map<String, String> sourceAtts = new HashMap<>(); for (int i = 0; i < atts.getLength(); i++) { sourceAtts.put(atts.getLocalName(i), atts.getValue(i)); } siblingSources.put((new LocatorImpl(getDocumentLocator())), sourceAtts); } if ("figure" == localName) { currentFigurePtr = currentPtr + 1; } if ((ancestorMask & FIGURE_MASK) != 0) { if ("img" == localName) { if (stack[currentFigurePtr].hasImg()) { stack[currentFigurePtr].setEmbeddedContentFound(); } else { stack[currentFigurePtr].setImgFound(); } } else if ("audio" == localName || "canvas" == localName || "embed" == localName || "iframe" == localName || "math" == localName || "object" == localName || "svg" == localName || "video" == localName) { stack[currentFigurePtr].setEmbeddedContentFound(); } } if ("article" == localName || "aside" == localName || "nav" == localName || "section" == localName) { currentSectioningElementPtr = currentPtr + 1; currentSectioningDepth++; } if ("h1" == localName || "h2" == localName || "h3" == localName || "h4" == localName || "h5" == localName || "h6" == localName) { currentHeadingPtr = currentPtr + 1; if (currentSectioningElementPtr > -1) { stack[currentSectioningElementPtr].setHeadingFound(); } } if (((ancestorMask & H1_MASK) != 0 || (ancestorMask & H2_MASK) != 0 || (ancestorMask & H3_MASK) != 0 || (ancestorMask & H4_MASK) != 0 || (ancestorMask & H5_MASK) != 0 || (ancestorMask & H6_MASK) != 0) && "img" == localName && atts.getIndex("", "alt") > -1 && !"".equals(atts.getValue("", "alt"))) { stack[currentHeadingPtr].setImgFound(); } if ("option" == localName && !parent.hasOption()) { if (atts.getIndex("", "value") < 0) { parent.setNoValueOptionFound(); } else if (atts.getIndex("", "value") > -1 && "".equals(atts.getValue("", "value"))) { parent.setEmptyValueOptionFound(); } else { parent.setNonEmptyOption( (new LocatorImpl(getDocumentLocator()))); } } // Obsolete elements if (OBSOLETE_ELEMENTS.get(localName) != null) { String suggestion = ""; if (!"".equals(OBSOLETE_ELEMENTS.get(localName))) { suggestion = " " + OBSOLETE_ELEMENTS.get(localName); } err("The \u201C" + localName + "\u201D element is obsolete." + suggestion); } // Exclusions Integer maskAsObject; int mask = 0; String descendantUiString = "The element \u201C" + localName + "\u201D"; if ((maskAsObject = ANCESTOR_MASK_BY_DESCENDANT.get( localName)) != null) { mask = maskAsObject.intValue(); } else if ("video" == localName && controls) { mask = A_BUTTON_MASK; descendantUiString = "The element \u201Cvideo\u201D with the" + " attribute \u201Ccontrols\u201D"; checkForInteractiveAncestorRole(descendantUiString); } else if ("audio" == localName && controls) { mask = A_BUTTON_MASK; descendantUiString = "The element \u201Caudio\u201D with the" + " attribute \u201Ccontrols\u201D"; checkForInteractiveAncestorRole(descendantUiString); } else if ("menu" == localName && toolbar) { mask = A_BUTTON_MASK; descendantUiString = "The element \u201Cmenu\u201D with the" + " attribute \u201Ctype=toolbar\u201D"; checkForInteractiveAncestorRole(descendantUiString); } else if ("img" == localName && usemap) { mask = A_BUTTON_MASK; descendantUiString = "The element \u201Cimg\u201D with the" + " attribute \u201Cusemap\u201D"; checkForInteractiveAncestorRole(descendantUiString); } else if ("object" == localName && usemap) { mask = A_BUTTON_MASK; descendantUiString = "The element \u201Cobject\u201D with the" + " attribute \u201Cusemap\u201D"; checkForInteractiveAncestorRole(descendantUiString); } else if ("input" == localName && !hidden) { mask = A_BUTTON_MASK; checkForInteractiveAncestorRole(descendantUiString); } else if (tabindex) { mask = A_BUTTON_MASK; descendantUiString = "An element with the attribute" + " \u201Ctabindex\u201D"; checkForInteractiveAncestorRole(descendantUiString); } else if (role != null && role != "" && Arrays.binarySearch(INTERACTIVE_ROLES, role) >= 0) { mask = A_BUTTON_MASK; descendantUiString = "An element with the attribute \u201C" + "role=" + role + "\u201D"; checkForInteractiveAncestorRole(descendantUiString); } if (mask != 0) { int maskHit = ancestorMask & mask; if (maskHit != 0) { for (String ancestor : SPECIAL_ANCESTORS) { if ((maskHit & 1) != 0) { err(descendantUiString + " must not appear as a" + " descendant of the \u201C" + ancestor + "\u201D element."); } maskHit >>= 1; } } } if (Arrays.binarySearch(INTERACTIVE_ELEMENTS, localName) >= 0) { checkForInteractiveAncestorRole( "The element \u201C" + localName + "\u201D"); } // Ancestor requirements/restrictions if ("area" == localName && ((ancestorMask & MAP_MASK) == 0)) { err("The \u201Carea\u201D element must have a \u201Cmap\u201D ancestor."); } else if ("img" == localName) { List<String> roles = null; if (role != null) { roles = Arrays.asList(role.trim() .toLowerCase().split("\\s+")); } String titleVal = atts.getValue("", "title"); if (ismap && ((ancestorMask & HREF_MASK) == 0)) { err("The \u201Cimg\u201D element with the " + "\u201Cismap\u201D attribute set must have an " + "\u201Ca\u201D ancestor with the " + "\u201Chref\u201D attribute."); } if (atts.getIndex("", "alt") < 0) { if (role != null) { err("An \u201Cimg\u201D element with no \u201Calt\u201D" + " attribute must not have a" + " \u201Crole\u201D attribute."); } if (hasAriaAttributesOtherThanAriaHidden) { err("An \u201Cimg\u201D element with no \u201Calt\u201D" + " attribute must not have any" + " \u201Caria-*\u201D attributes other than" + " \u201Caria-hidden\u201D."); } if ((titleVal == null || "".equals(titleVal))) { if ((ancestorMask & FIGURE_MASK) == 0) { err("An \u201Cimg\u201D element must have an" + " \u201Calt\u201D attribute, except under" + " certain conditions. For details, consult" + " guidance on providing text alternatives" + " for images."); } else { stack[currentFigurePtr].setFigcaptionNeeded(); stack[currentFigurePtr].addImageLackingAlt( new LocatorImpl(getDocumentLocator())); } } } else if (role != null) { if ("".equals(atts.getValue("", "alt"))) { // img with alt="" and role for (String roleValue : roles) { if (!("none".equals(roleValue)) && !("presentation".equals(roleValue))) { err("An \u201Cimg\u201D element which has an" + " \u201Calt\u201D attribute whose" + " value is the empty string must not" + " have a \u201Crole\u201D attribute" + " with any value other than" + " \u201Cnone\u201D or" + " \u201Cpresentation\u201D"); } } } else { // img with alt="some text" and role for (String roleValue : roles) { if ("none".equals(roleValue) || "presentation".equals(roleValue)) { err("Bad value \u201C" + roleValue + "\u201D" + " for attribute \u201Crole\u201D on" + " element \u201Cimg\u201D"); } } } } } else if ("table" == localName) { if (atts.getIndex("", "summary") >= 0) { errObsoleteAttribute("summary", "table", " Consider describing the structure of the" + " \u201Ctable\u201D in a \u201Ccaption\u201D " + " element or in a \u201Cfigure\u201D element " + " containing the \u201Ctable\u201D; or," + " simplify the structure of the" + " \u201Ctable\u201D so that no description" + " is needed."); } if (atts.getIndex("", "border") > -1) { errObsoleteAttribute("border", "table", " Use CSS instead."); } } else if ("track" == localName && atts.getIndex("", "default") >= 0) { for (Map.Entry<StackNode, TaintableLocatorImpl> entry : openMediaElements.entrySet()) { StackNode node = entry.getKey(); TaintableLocatorImpl locator = entry.getValue(); if (node.isTrackDescendant()) { err("The \u201Cdefault\u201D attribute must not occur" + " on more than one \u201Ctrack\u201D element" + " within the same \u201Caudio\u201D or" + " \u201Cvideo\u201D element."); if (!locator.isTainted()) { warn("\u201Caudio\u201D or \u201Cvideo\u201D element" + " has more than one \u201Ctrack\u201D child" + " element with a \u201Cdefault\u201D attribute.", locator); locator.markTainted(); } } else { node.setTrackDescendants(); } } } else if ("hgroup" == localName) { incrementUseCounter("hgroup-found"); } else if ("main" == localName) { for (int i = 0; i < currentPtr; i++) { String ancestorName = stack[currentPtr - i].getName(); if (ancestorName != null && Arrays.binarySearch(PROHIBITED_MAIN_ANCESTORS, ancestorName) >= 0) { err("The \u201Cmain\u201D element must not appear as a" + " descendant of the \u201C" + ancestorName + "\u201D element."); } } if (atts.getIndex("", "hidden") < 0) { if (hasVisibleMain) { err("A document must not include more than one visible" + " \u201Cmain\u201D element."); } hasVisibleMain = true; } } else if ("h1" == localName) { if (currentSectioningDepth > 1) { warn(h1WarningMessage); } else if (currentSectioningDepth == 1) { secondLevelH1s.add(new LocatorImpl(getDocumentLocator())); } else { hasTopLevelH1 = true; } } // progress else if ("progress" == localName) { double value = getDoubleAttribute(atts, "value"); if (!Double.isNaN(value)) { double max = getDoubleAttribute(atts, "max"); if (Double.isNaN(max)) { if (!(value <= 1.0)) { err("The value of the \u201Cvalue\u201D attribute must be less than or equal to one when the \u201Cmax\u201D attribute is absent."); } } else { if (!(value <= max)) { err("The value of the \u201Cvalue\u201D attribute must be less than or equal to the value of the \u201Cmax\u201D attribute."); } } } } // meter else if ("meter" == localName) { double value = getDoubleAttribute(atts, "value"); double min = getDoubleAttribute(atts, "min"); double max = getDoubleAttribute(atts, "max"); double optimum = getDoubleAttribute(atts, "optimum"); double low = getDoubleAttribute(atts, "low"); double high = getDoubleAttribute(atts, "high"); if (!Double.isNaN(min) && !Double.isNaN(value) && !(min <= value)) { err("The value of the \u201Cmin\u201D attribute must be less than or equal to the value of the \u201Cvalue\u201D attribute."); } if (Double.isNaN(min) && !Double.isNaN(value) && !(0 <= value)) { err("The value of the \u201Cvalue\u201D attribute must be greater than or equal to zero when the \u201Cmin\u201D attribute is absent."); } if (!Double.isNaN(value) && !Double.isNaN(max) && !(value <= max)) { err("The value of the \u201Cvalue\u201D attribute must be less than or equal to the value of the \u201Cmax\u201D attribute."); } if (!Double.isNaN(value) && Double.isNaN(max) && !(value <= 1)) { err("The value of the \u201Cvalue\u201D attribute must be less than or equal to one when the \u201Cmax\u201D attribute is absent."); } if (!Double.isNaN(min) && !Double.isNaN(max) && !(min <= max)) { err("The value of the \u201Cmin\u201D attribute must be less than or equal to the value of the \u201Cmax\u201D attribute."); } if (Double.isNaN(min) && !Double.isNaN(max) && !(0 <= max)) { err("The value of the \u201Cmax\u201D attribute must be greater than or equal to zero when the \u201Cmin\u201D attribute is absent."); } if (!Double.isNaN(min) && Double.isNaN(max) && !(min <= 1)) { err("The value of the \u201Cmin\u201D attribute must be less than or equal to one when the \u201Cmax\u201D attribute is absent."); } if (!Double.isNaN(min) && !Double.isNaN(low) && !(min <= low)) { err("The value of the \u201Cmin\u201D attribute must be less than or equal to the value of the \u201Clow\u201D attribute."); } if (Double.isNaN(min) && !Double.isNaN(low) && !(0 <= low)) { err("The value of the \u201Clow\u201D attribute must be greater than or equal to zero when the \u201Cmin\u201D attribute is absent."); } if (!Double.isNaN(min) && !Double.isNaN(high) && !(min <= high)) { err("The value of the \u201Cmin\u201D attribute must be less than or equal to the value of the \u201Chigh\u201D attribute."); } if (Double.isNaN(min) && !Double.isNaN(high) && !(0 <= high)) { err("The value of the \u201Chigh\u201D attribute must be greater than or equal to zero when the \u201Cmin\u201D attribute is absent."); } if (!Double.isNaN(low) && !Double.isNaN(high) && !(low <= high)) { err("The value of the \u201Clow\u201D attribute must be less than or equal to the value of the \u201Chigh\u201D attribute."); } if (!Double.isNaN(high) && !Double.isNaN(max) && !(high <= max)) { err("The value of the \u201Chigh\u201D attribute must be less than or equal to the value of the \u201Cmax\u201D attribute."); } if (!Double.isNaN(high) && Double.isNaN(max) && !(high <= 1)) { err("The value of the \u201Chigh\u201D attribute must be less than or equal to one when the \u201Cmax\u201D attribute is absent."); } if (!Double.isNaN(low) && !Double.isNaN(max) && !(low <= max)) { err("The value of the \u201Clow\u201D attribute must be less than or equal to the value of the \u201Cmax\u201D attribute."); } if (!Double.isNaN(low) && Double.isNaN(max) && !(low <= 1)) { err("The value of the \u201Clow\u201D attribute must be less than or equal to one when the \u201Cmax\u201D attribute is absent."); } if (!Double.isNaN(min) && !Double.isNaN(optimum) && !(min <= optimum)) { err("The value of the \u201Cmin\u201D attribute must be less than or equal to the value of the \u201Coptimum\u201D attribute."); } if (Double.isNaN(min) && !Double.isNaN(optimum) && !(0 <= optimum)) { err("The value of the \u201Coptimum\u201D attribute must be greater than or equal to zero when the \u201Cmin\u201D attribute is absent."); } if (!Double.isNaN(optimum) && !Double.isNaN(max) && !(optimum <= max)) { err("The value of the \u201Coptimum\u201D attribute must be less than or equal to the value of the \u201Cmax\u201D attribute."); } if (!Double.isNaN(optimum) && Double.isNaN(max) && !(optimum <= 1)) { err("The value of the \u201Coptimum\u201D attribute must be less than or equal to one when the \u201Cmax\u201D attribute is absent."); } } // map required attrs else if ("map" == localName && id != null) { String nameVal = atts.getValue("", "name"); if (nameVal != null && !nameVal.equals(id)) { err("The \u201Cid\u201D attribute on a \u201Cmap\u201D element must have an the same value as the \u201Cname\u201D attribute."); } } else if ("object" == localName) { if (atts.getIndex("", "typemustmatch") >= 0) { if ((atts.getIndex("", "data") < 0) || (atts.getIndex("", "type") < 0)) { { err("Element \u201Cobject\u201D must not have" + " attribute \u201Ctypemustmatch\u201D unless" + " both attribute \u201Cdata\u201D" + " and attribute \u201Ctype\u201D are also specified."); } } } } else if ("form" == localName) { if (atts.getIndex("", "accept-charset") >= 0) { if (!"utf-8".equals( atts.getValue("", "accept-charset").toLowerCase())) { err("The only allowed value for the" + " \u201Caccept-charset\u201D attribute for" + " the \u201Cform\u201D element is" + " \u201Cutf-8\u201D."); } } } // script else if ("script" == localName) { // script language if (languageJavaScript && typeNotTextJavaScript) { err("A \u201Cscript\u201D element with the \u201Clanguage=\"JavaScript\"\u201D attribute set must not have a \u201Ctype\u201D attribute whose value is not \u201Ctext/javascript\u201D."); } if (atts.getIndex("", "charset") >= 0) { warnObsoleteAttribute("charset", "script", ""); if (!"utf-8".equals( atts.getValue("", "charset").toLowerCase())) { err("The only allowed value for the \u201Ccharset\u201D" + " attribute for the \u201Cscript\u201D" + " element is \u201Cutf-8\u201D. (But the" + " attribute is not needed and should be" + " omitted altogether.)"); } } // src-less script if (atts.getIndex("", "src") < 0) { if (atts.getIndex("", "charset") >= 0) { err("Element \u201Cscript\u201D must not have attribute \u201Ccharset\u201D unless attribute \u201Csrc\u201D is also specified."); } if (atts.getIndex("", "defer") >= 0) { err("Element \u201Cscript\u201D must not have attribute \u201Cdefer\u201D unless attribute \u201Csrc\u201D is also specified."); } if (atts.getIndex("", "async") >= 0) { if (!(atts.getIndex("", "type") > -1 && "module".equals(atts.getValue("", "type") .toLowerCase()))) { err("Element \u201Cscript\u201D must not have" + " attribute \u201Casync\u201D unless" + " attribute \u201Csrc\u201D is also" + " specified or unless attribute" + " \u201Ctype\u201D is specified with" + " value \u201Cmodule\u201D."); } } if (atts.getIndex("", "integrity") >= 0) { err("Element \u201Cscript\u201D must not have attribute" + " \u201Cintegrity\u201D unless attribute" + " \u201Csrc\u201D is also specified."); } } if (atts.getIndex("", "type") > -1) { String scriptType = atts.getValue("", "type").toLowerCase(); if (JAVASCRIPT_MIME_TYPES.contains(scriptType) || "".equals(scriptType)) { warn("The \u201Ctype\u201D attribute is unnecessary for" + " JavaScript resources."); } else if ("module".equals(scriptType)) { if (atts.getIndex("", "defer") > -1) { err("A \u201Cscript\u201D element with a" + " \u201Cdefer\u201D attribute must not have a" + " \u201Ctype\u201D attribute with the value" + " \u201Cmodule\u201D."); } if (atts.getIndex("", "nomodule") > -1) { err("A \u201Cscript\u201D element with a" + " \u201Cnomodule\u201D attribute must not have a" + " \u201Ctype\u201D attribute with the value" + " \u201Cmodule\u201D."); } } else if (atts.getIndex("", "src") > -1) { err("A \u201Cscript\u201D element with a" + " \u201Csrc\u201D attribute must not have" + " a \u201Ctype\u201D attribute whose" + " value is anything other than" + " the empty string, a JavaScript MIME" + " type, or \u201Cmodule\u201D."); } } } else if ("style" == localName) { if (atts.getIndex("", "type") > -1) { String styleType = atts.getValue("", "type").toLowerCase(); if ("text/css".equals(styleType)) { warn("The \u201Ctype\u201D attribute for the" + " \u201Cstyle\u201D element is not needed and" + " should be omitted."); } else { err("The only allowed value for the \u201Ctype\u201D" + " attribute for the \u201Cstyle\u201D element" + " is \u201Ctext/css\u201D (with no" + " parameters). (But the attribute is not" + " needed and should be omitted altogether.)"); } } } // bdo required attrs else if ("bdo" == localName && atts.getIndex("", "dir") < 0) { err("Element \u201Cbdo\u201D must have attribute \u201Cdir\u201D."); } // labelable elements if (isLabelableElement(localName, atts)) { for (Map.Entry<StackNode, Locator> entry : openLabels.entrySet()) { StackNode node = entry.getKey(); Locator locator = entry.getValue(); if (node.isLabeledDescendants()) { err("The \u201Clabel\u201D element may contain at most" + " one \u201Cbutton\u201D, \u201Cinput\u201D," + " \u201Cmeter\u201D, \u201Coutput\u201D," + " \u201Cprogress\u201D, \u201Cselect\u201D," + " or \u201Ctextarea\u201D descendant."); warn("\u201Clabel\u201D element with multiple labelable" + " descendants.", locator); } else { node.setLabeledDescendants(); } } if ((ancestorMask & LABEL_FOR_MASK) != 0) { boolean hasMatchingFor = false; for (int i = 0; (stack[currentPtr - i].getAncestorMask() & LABEL_FOR_MASK) != 0; i++) { String forVal = stack[currentPtr - i].getForAttr(); if (forVal != null && forVal.equals(id)) { hasMatchingFor = true; break; } } if (id == null || !hasMatchingFor) { err("Any \u201C" + localName + "\u201D descendant of a \u201Clabel\u201D" + " element with a \u201Cfor\u201D attribute" + " must have an ID value that matches that" + " \u201Cfor\u201D attribute."); } } } // lang and xml:lang for XHTML5 if (lang != null && xmlLang != null && !equalsIgnoreAsciiCase(lang, xmlLang)) { err("When the attribute \u201Clang\u201D in no namespace and the attribute \u201Clang\u201D in the XML namespace are both present, they must have the same value."); } if (role != null && owns != null) { for (Set<String> value : REQUIRED_ROLE_ANCESTOR_BY_DESCENDANT.values()) { if (value.contains(role)) { String[] ownedIds = AttributeUtil.split(owns); for (String ownedId : ownedIds) { Set<String> ownedIdsForThisRole = ariaOwnsIdsByRole.get( role); if (ownedIdsForThisRole == null) { ownedIdsForThisRole = new HashSet<>(); } ownedIdsForThisRole.add(ownedId); ariaOwnsIdsByRole.put(role, ownedIdsForThisRole); } break; } } } if ("datalist" == localName) { listIds.addAll(ids); } // label for if ("label" == localName) { String forVal = atts.getValue("", "for"); if (forVal != null) { formControlReferences.add(new IdrefLocator( new LocatorImpl(getDocumentLocator()), forVal)); } } if ("form" == localName) { formElementIds.addAll(ids); } if (("button" == localName || "input" == localName && !hidden) || "meter" == localName || "output" == localName || "progress" == localName || "select" == localName || "textarea" == localName || isCustomElement) { formControlIds.addAll(ids); } if ("button" == localName || "fieldset" == localName || ("input" == localName && !hidden) || "object" == localName || "output" == localName || "select" == localName || "textarea" == localName) { String formVal = atts.getValue("", "form"); if (formVal != null) { formElementReferences.add(new IdrefLocator( new LocatorImpl(getDocumentLocator()), formVal)); } } // input list if ("input" == localName && list != null) { listReferences.add(new IdrefLocator( new LocatorImpl(getDocumentLocator()), list)); } // input@type=checkbox if ("input" == localName && AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "checkbox", atts.getValue("", "type"))) { if ("button".equals(role) && !"true".equals(atts.getValue("", "aria-pressed"))) { err("An \u201Cinput\u201D element with a \u201Ctype\u201D" + " attribute whose value is \u201Ccheckbox\u201D" + " and with a \u201Crole\u201D attribute whose" + " value is \u201Cbutton\u201D must have an" + " \u201Caria-pressed\u201D attribute whose value" + " is \u201Ctrue\u201D."); } } // input@type=button if ("input" == localName && AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "button", atts.getValue("", "type"))) { if (atts.getValue("", "value") == null || "".equals(atts.getValue("", "value"))) { err("Element \u201Cinput\u201D with attribute \u201Ctype\u201D whose value is \u201Cbutton\u201D must have non-empty attribute \u201Cvalue\u201D."); } } // track if ("track" == localName) { if ("".equals(atts.getValue("", "label"))) { err("Attribute \u201Clabel\u201D for element \u201Ctrack\u201D must have non-empty value."); } } // multiple selected options if ("option" == localName && selected) { for (Map.Entry<StackNode, Locator> entry : openSingleSelects.entrySet()) { StackNode node = entry.getKey(); if (node.isSelectedOptions()) { err("The \u201Cselect\u201D element cannot have more than one selected \u201Coption\u201D descendant unless the \u201Cmultiple\u201D attribute is specified."); } else { node.setSelectedOptions(); } } } if ("meta" == localName) { if (AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "content-language", atts.getValue("", "http-equiv"))) { err("Using the \u201Cmeta\u201D element to specify the" + " document-wide default language is obsolete." + " Consider specifying the language on the root" + " element instead."); } else if (AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "x-ua-compatible", atts.getValue("", "http-equiv")) && !AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "ie=edge", atts.getValue("", "content"))) { err("A \u201Cmeta\u201D element with an" + " \u201Chttp-equiv\u201D attribute whose value is" + " \u201CX-UA-Compatible\u201D" + " must have a" + " \u201Ccontent\u201D attribute with the value" + " \u201CIE=edge\u201D."); } if (atts.getIndex("", "charset") > -1) { if (!"utf-8".equals( atts.getValue("", "charset").toLowerCase())) { err("The only allowed value for the \u201Ccharset\u201D" + " attribute for the \u201Cmeta\u201D" + " element is \u201Cutf-8\u201D."); } if (hasMetaCharset) { err("A document must not include more than one" + " \u201Cmeta\u201D element with a" + " \u201Ccharset\u201D attribute."); } if (hasContentTypePragma) { err("A document must not include both a" + " \u201Cmeta\u201D element with an" + " \u201Chttp-equiv\u201D attribute" + " whose value is \u201Ccontent-type\u201D," + " and a \u201Cmeta\u201D element with a" + " \u201Ccharset\u201D attribute."); } hasMetaCharset = true; } if (atts.getIndex("", "name") > -1) { if ("description".equals(atts.getValue("", "name"))) { if (hasMetaDescription) { err("A document must not include more than one" + " \u201Cmeta\u201D element with its" + " \u201Cname\u201D attribute set to the" + " value \u201Cdescription\u201D."); } hasMetaDescription = true; } if ("viewport".equals(atts.getValue("", "name")) && atts.getIndex("", "content") > -1) { String contentVal = atts.getValue("", "content").toLowerCase(); if (contentVal.contains("user-scalable=no") || contentVal.contains("maximum-scale=1.0")) { warn("Consider avoiding viewport values that" + " prevent users from resizing documents."); } } if ("theme-color".equals(atts.getValue("", "name")) && atts.getIndex("", "content") > -1) { String contentVal = atts.getValue("", "content").toLowerCase(); try { Color.THE_INSTANCE.checkValid(contentVal); } catch (DatatypeException e) { try { if (getErrorHandler() != null) { String msg = e.getMessage(); if (e instanceof Html5DatatypeException) { msg = msg.substring( msg.indexOf(": ") + 2); } VnuBadAttrValueException ex = new VnuBadAttrValueException( localName, uri, "content", contentVal, msg, getDocumentLocator(), Color.class, false); getErrorHandler().error(ex); } } catch (ClassNotFoundException ce) { } } } } if (atts.getIndex("", "http-equiv") > -1 && AttributeUtil.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "content-type", atts.getValue("", "http-equiv"))) { if (hasMetaCharset) { err("A document must not include both a" + " \u201Cmeta\u201D element with an" + " \u201Chttp-equiv\u201D attribute" + " whose value is \u201Ccontent-type\u201D," + " and a \u201Cmeta\u201D element with a" + " \u201Ccharset\u201D attribute."); } if (hasContentTypePragma) { err("A document must not include more than one" + " \u201Cmeta\u201D element with a" + " \u201Chttp-equiv\u201D attribute" + " whose value is \u201Ccontent-type\u201D."); } hasContentTypePragma = true; } } if ("link" == localName) { boolean hasRel = false; List<String> relList = new ArrayList<>(); if (atts.getIndex("", "rel") > -1) { hasRel = true; Collections.addAll(relList, atts.getValue("", "rel") .toLowerCase().split("\\s+")); } if (relList.contains("preload") && atts.getIndex("", "as") < 0) { err("A \u201Clink\u201D element with a" + " \u201Crel\u201D attribute that contains the" + " value \u201Cpreload\u201D must have an" + " \u201Cas\u201D attribute."); } if (atts.getIndex("", "as") > -1 && (!(relList.contains("preload") || relList.contains("modulepreload") || relList.contains("prefetch")) || !hasRel)) { err("A \u201Clink\u201D element with an" + " \u201Cas\u201D attribute must have a" + " \u201Crel\u201D attribute that contains the" + " value \u201Cpreload\u201D or the value" + " \u201Cmodulepreload\u201D or the value" + " \u201Cprefetch\u201D."); } if (atts.getIndex("", "integrity") > -1 && (!(relList.contains("stylesheet") || relList.contains("preload") || relList.contains("modulepreload")) || !hasRel)) { err("A \u201Clink\u201D element with an" + " \u201Cintegrity\u201D attribute must have a" + " \u201Crel\u201D attribute that contains the" + " value \u201Cstylesheet\u201D or the value" + " \u201Cpreload\u201D or the value" + " \u201Cmodulepreload\u201D."); } if (atts.getIndex("", "disabled") > -1 && (!relList.contains("stylesheet") || !hasRel)) { err("A \u201Clink\u201D element with a" + " \u201Cdisabled\u201D attribute must have a" + " \u201Crel\u201D attribute that contains the" + " value \u201Cstylesheet\u201D."); } if (atts.getIndex("", "sizes") > -1 && (!(relList.contains("icon") || relList.contains("apple-touch-icon") || relList.contains( "apple-touch-icon-precomposed")) || !hasRel)) { err("A \u201Clink\u201D element with a" + " \u201Csizes\u201D attribute must have a" + " \u201Crel\u201D attribute that contains the" + " value \u201Cicon\u201D or the value" + " \u201Capple-touch-icon\u201D or the value" + " \u201Capple-touch-icon-precomposed\u201D."); } if (atts.getIndex("", "color") > -1 && (!relList.contains("mask-icon") || !hasRel)) { err("A \u201Clink\u201D element with a" + " \u201Ccolor\u201D attribute must have a" + " \u201Crel\u201D attribute that contains" + " the value \u201Cmask-icon\u201D."); } if (atts.getIndex("", "scope") > -1 && (!relList.contains("serviceworker") || !hasRel)) { err("A \u201Clink\u201D element with a" + " \u201Cscope\u201D attribute must have a" + " \u201Crel\u201D attribute that contains the" + " value \u201Cserviceworker\u201D."); } if (atts.getIndex("", "updateviacache") > -1 && (!relList.contains("serviceworker") || !hasRel)) { err("A \u201Clink\u201D element with an" + " \u201Cupdateviacache\u201D attribute must have a" + " \u201Crel\u201D attribute that contains the" + " value \u201Cserviceworker\u201D."); } if (atts.getIndex("", "workertype") > -1 && (!relList.contains("serviceworker") || !hasRel)) { err("A \u201Clink\u201D element with a" + " \u201Cworkertype\u201D attribute must have a" + " \u201Crel\u201D attribute that contains the" + " value \u201Cserviceworker\u201D."); } if ((ancestorMask & BODY_MASK) != 0 && (relList != null && !(relList.contains("dns-prefetch") || relList.contains("modulepreload") || relList.contains("pingback") || relList.contains("preconnect") || relList.contains("prefetch") || relList.contains("preload") || relList.contains("prerender") || relList.contains("stylesheet"))) && atts.getIndex("", "itemprop") < 0 && atts.getIndex("", "property") < 0) { err("A \u201Clink\u201D element must not appear" + " as a descendant of a \u201Cbody\u201D element" + " unless the \u201Clink\u201D element has an" + " \u201Citemprop\u201D attribute or has a" + " \u201Crel\u201D attribute whose value contains" + " \u201Cdns-prefetch\u201D," + " \u201Cmodulepreload\u201D," + " \u201Cpingback\u201D," + " \u201Cpreconnect\u201D," + " \u201Cprefetch\u201D," + " \u201Cpreload\u201D," + " \u201Cprerender\u201D, or" + " \u201Cstylesheet\u201D."); } } // microdata if (itemid && !(itemscope && itemtype)) { err("The \u201Citemid\u201D attribute must not be specified on elements that do not have both an \u201Citemscope\u201D attribute and an \u201Citemtype\u201D attribute specified."); } if (itemref && !itemscope) { err("The \u201Citemref\u201D attribute must not be specified on elements that do not have an \u201Citemscope\u201D attribute specified."); } if (itemtype && !itemscope) { err("The \u201Citemtype\u201D attribute must not be specified on elements that do not have an \u201Citemscope\u201D attribute specified."); } // Errors for use of ARIA attributes that conflict with native // element semantics. if (atts.getIndex("", "contenteditable") > -1 && "true".equals(atts.getValue("", "aria-readonly"))) { err("The \u201Caria-readonly\u201D attribute must only be" + " specified with a value of \u201Cfalse\u201D" + " on elements that have a \u201Ccontenteditable\u201D" + " attribute."); } if (atts.getIndex("", "aria-placeholder") > -1 && atts.getIndex("", "placeholder") > -1) { err("The \u201Caria-placeholder\u201D attribute must not be" + " specified on elements that have a" + " \u201Cplaceholder\u201D attribute."); } // Warnings for use of ARIA attributes with markup already // having implicit ARIA semantics. if (ELEMENTS_WITH_IMPLICIT_ROLE.containsKey(localName) && ELEMENTS_WITH_IMPLICIT_ROLE.get(localName).equals( role)) { if (!("img".equals(localName) && ("".equals(atts.getValue("", "alt"))))) { warn("The \u201C" + role + "\u201D role is unnecessary for" + " element" + " \u201C" + localName + "\u201D."); } } else if (ELEMENTS_WITH_IMPLICIT_ROLES.containsKey(localName) && role != null && Arrays.binarySearch( ELEMENTS_WITH_IMPLICIT_ROLES.get(localName), role) >= 0) { warn("The \u201C" + role + "\u201D role is unnecessary for" + " element" + " \u201C" + localName + "\u201D."); } else if (ELEMENTS_THAT_NEVER_NEED_ROLE.containsKey(localName) && ELEMENTS_THAT_NEVER_NEED_ROLE.get(localName).equals( role)) { warn("Element \u201C" + localName + "\u201D does not need a" + " \u201Crole\u201D attribute."); } else if ("input" == localName) { inputTypeVal = inputTypeVal == null ? "text" : inputTypeVal; if (INPUT_TYPES_WITH_IMPLICIT_ROLE.containsKey(inputTypeVal) && INPUT_TYPES_WITH_IMPLICIT_ROLE.get( inputTypeVal).equals(role)) { warnExplicitRoleUnnecessaryForType("input", role, inputTypeVal); } else if ("email".equals(inputTypeVal) || "search".equals(inputTypeVal) || "tel".equals(inputTypeVal) || "text".equals(inputTypeVal) || "url".equals(inputTypeVal)) { if (atts.getIndex("", "list") < 0) { if ("textbox".equals(role) && !"search".equals(inputTypeVal)) { warn("The \u201Ctextbox\u201D role is unnecessary" + " for an \u201Cinput\u201D element that" + " has no \u201Clist\u201D attribute and" + " whose type is" + " \u201C" + inputTypeVal + "\u201D."); } if ("searchbox".equals(role) && "search".equals(inputTypeVal)) { warn("The \u201Csearchbox\u201D role is unnecessary" + " for an \u201Cinput\u201D element that" + " has no \u201Clist\u201D attribute and" + " whose type is" + " \u201C" + inputTypeVal + "\u201D."); } } else { if ("combobox".equals(role)) { warn("The \u201Ccombobox\u201D role is unnecessary" + " for an \u201Cinput\u201D element that" + " has a \u201Clist\u201D attribute and" + " whose type is" + " \u201C" + inputTypeVal + "\u201D."); } } } } else if (atts.getIndex("", "href") > -1 && "link".equals(role) && ("a".equals(localName) || "area".equals(localName) || "link".equals(localName))) { warn("The \u201Clink\u201D role is unnecessary for element" + " \u201C" + localName + "\u201D with attribute" + " \u201Chref\u201D."); } else if (atts.getIndex("", "href") > -1 && "link".equals(role) && ("a".equals(localName) || "area".equals(localName) || "link".equals(localName))) { warn("The \u201Clink\u201D role is unnecessary for element" + " \u201C" + localName + "\u201D with attribute" + " \u201Chref\u201D."); } else if (("tbody".equals(localName) || "tfoot".equals(localName) || "thead".equals(localName)) && "rowgroup".equals(role)) { warn("The \u201Crowgroup\u201D role is unnecessary for element" + " \u201C" + localName + "\u201D."); } else if ("th" == localName && ("columnheader".equals(role) || "columnheader".equals(role))) { warn("The \u201C" + role + "\u201D role is unnecessary for" + " element \u201Cth\u201D."); } else if ("li" == localName && "listitem".equals(role) && !"menu".equals(parentName)) { warn("The \u201Clistitem\u201D role is unnecessary for an" + " \u201Cli\u201D element whose parent is" + " an \u201Col\u201D element or a" + " \u201Cul\u201D element."); } else if ("button" == localName && "button".equals(role) && "menu".equals(atts.getValue("", "type"))) { warnExplicitRoleUnnecessaryForType("button", "button", "menu"); } else if ("menu" == localName && "toolbar".equals(role) && "toolbar".equals(atts.getValue("", "type"))) { warnExplicitRoleUnnecessaryForType("menu", "toolbar", "toolbar"); } else if ("li" == localName && "listitem".equals(role) && !"menu".equals(parentName)) { warn("The \u201Clistitem\u201D role is unnecessary for an" + " \u201Cli\u201D element whose parent is" + " an \u201Col\u201D element or a" + " \u201Cul\u201D element."); } } else { int len = atts.getLength(); for (int i = 0; i < len; i++) { if (atts.getType(i) == "ID") { String attVal = atts.getValue(i); if (attVal.length() != 0) { ids.add(attVal); } } String attLocal = atts.getLocalName(i); if (atts.getURI(i).length() == 0) { if ("role" == attLocal) { role = atts.getValue(i); } else if ("aria-activedescendant" == attLocal) { activeDescendant = atts.getValue(i); } else if ("aria-owns" == attLocal) { owns = atts.getValue(i); } } } allIds.addAll(ids); } // ARIA required owner/ancestors Set<String> requiredAncestorRoles = REQUIRED_ROLE_ANCESTOR_BY_DESCENDANT.get( role); if (requiredAncestorRoles != null && !"presentation".equals(parentRole) && !"tbody".equals(localName) && !"tfoot".equals(localName) && !"thead".equals(localName)) { if (!currentElementHasRequiredAncestorRole(requiredAncestorRoles)) { if (atts.getIndex("", "id") > -1 && !"".equals(atts.getValue("", "id"))) { needsAriaOwner.add(new IdrefLocator( new LocatorImpl(getDocumentLocator()), atts.getValue("", "id"), role)); } else { errContainedInOrOwnedBy(role, getDocumentLocator()); } } } // ARIA IDREFS for (String att : MUST_NOT_DANGLE_IDREFS) { String attVal = atts.getValue("", att); if (attVal != null) { String[] tokens = AttributeUtil.split(attVal); for (String token : tokens) { ariaReferences.add( new IdrefLocator(getDocumentLocator(), token, att)); } } } allIds.addAll(ids); if (isAriaLabelMisuse(ariaLabel, localName, role, atts)) { warn("Possible misuse of \u201Caria-label\u201D. (If you disagree" + " with this warning, file an issue report or send e-mail" + " to www-validator@w3.org.)"); incrementUseCounter("aria-label-misuse-found"); String systemId = getDocumentLocator().getSystemId(); if (systemId != null && hasPageEmitterInCallStack()) { log4j.info("aria-label misuse " + systemId); } } // aria-activedescendant accompanied by aria-owns if (activeDescendant != null && !"".equals(activeDescendant)) { // String activeDescendantVal = atts.getValue("", // "aria-activedescendant"); if (owns != null && !"".equals(owns)) { activeDescendantWithAriaOwns = true; // String[] tokens = AttributeUtil.split(owns); // for (int i = 0; i < tokens.length; i++) { // String token = tokens[i]; // if (token.equals(activeDescendantVal)) { // activeDescendantWithAriaOwns = true; // break; } } // activedescendant for (Iterator<Map.Entry<StackNode, Locator>> iterator = openActiveDescendants.entrySet().iterator(); iterator.hasNext();) { Map.Entry<StackNode, Locator> entry = iterator.next(); if (ids.contains(entry.getKey().getActiveDescendant())) { iterator.remove(); } } if ("http: int number = specialAncestorNumber(localName); if (number > -1) { ancestorMask |= (1 << number); } if ("a" == localName && href) { ancestorMask |= HREF_MASK; } StackNode child = new StackNode(ancestorMask, localName, role, activeDescendant, forAttr); if ("style" == localName) { child.setIsCollectingCharacters(true); } if ("script" == localName) { child.setIsCollectingCharacters(true); } if (activeDescendant != null && !activeDescendantWithAriaOwns) { openActiveDescendants.put(child, new LocatorImpl(getDocumentLocator())); } if ("select" == localName && atts.getIndex("", "multiple") == -1) { openSingleSelects.put(child, getDocumentLocator()); } else if ("label" == localName) { openLabels.put(child, new LocatorImpl(getDocumentLocator())); } else if ("video" == localName || "audio" == localName) { openMediaElements.put(child, new TaintableLocatorImpl(getDocumentLocator())); } push(child); if ("article" == localName || "aside" == localName || "nav" == localName || "section" == localName) { if (atts.getIndex("", "aria-label") > -1 && !"".equals(atts.getValue("", "aria-label"))) { child.setHeadingFound(); } } if ("select" == localName) { boolean hasSize = false; boolean sizeIsOne = false; boolean sizeIsGreaterThanOne = false; boolean hasMultiple = atts.getIndex("", "multiple") > -1; if (atts.getIndex("", "aria-multiselectable") > -1) { warn("The \u201Caria-multiselectable\u201D attribute" + " should not be used with the \u201Cselect" + " \u201D element."); } if (atts.getIndex("", "size") > -1) { hasSize = true; String size = trimSpaces(atts.getValue("", "size")); if (!"".equals(size)) { try { if ((size.length() > 1 && size.charAt(0) == '+' && Integer.parseInt(size.substring(1)) == 1) || Integer.parseInt(size) == 1) { sizeIsOne = true; } else if ((size.length() > 1 && size.charAt(0) == '+' && Integer.parseInt(size.substring(1)) > 1) || Integer.parseInt(size) > 1) { sizeIsGreaterThanOne = true; } } catch (NumberFormatException e) { } } } if (sizeIsGreaterThanOne || hasMultiple) { if ("listbox".equals(role)) { warn("The \u201Clistbox\u201D role is unnecessary for" + " element \u201Cselect\u201D with a" + " \u201Cmultiple\u201D attribute or with a" + " \u201Csize\u201D attribute whose value" + " is greater than 1."); } else if (role != null) { err("A \u201Cselect\u201D element with a" + " \u201Cmultiple\u201D attribute or with a" + " \u201Csize\u201D attribute whose value" + " is greater than 1 must not have any" + " \u201Crole\u201D attribute."); } } if (!hasMultiple) { if (!sizeIsGreaterThanOne && role != null) { if ("combobox".equals(role)) { warn("The \u201Ccombobox\u201D role is unnecessary" + " for element \u201Cselect\u201D" + " without a \u201Cmultiple\u201D" + " attribute and without a" + " \u201Csize\u201D attribute whose value" + " is greater than 1."); } else if (!"menu".equals(role)) { err("The \u201C" + role + "\u201D role is not" + " allowed for element \u201Cselect\u201D" + " without a \u201Cmultiple\u201D" + " attribute and without a" + " \u201Csize\u201D attribute whose value" + " is greater than 1."); } } if (atts.getIndex("", "required") > -1) { if (hasSize) { if (sizeIsOne) { child.setOptionNeeded(); } else { // "size" attr specified but isn't 1; do nothing } } else { // "size" unspecified; so browsers default size to 1 child.setOptionNeeded(); } } } else { // ARIA } } } else if ("http://n.validator.nu/custom-elements/" == uri) { err("Element \u201c" + localName + "\u201d from namespace" + " \u201chttp://n.validator.nu/custom-elements/\u201d" + " not allowed."); } else { StackNode child = new StackNode(ancestorMask, null, role, activeDescendant, forAttr); if (activeDescendant != null) { openActiveDescendants.put(child, new LocatorImpl(getDocumentLocator())); } push(child); } stack[currentPtr].setLocator(new LocatorImpl(getDocumentLocator())); } /** * @see nu.validator.checker.Checker#characters(char[], int, int) */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (numberOfTemplatesDeep > 0) { return; } if (stack[currentPtr].getIsCollectingCharacters()) { stack[currentPtr].appendToTextContent(ch, start, length); } StackNode node = peek(); for (int i = start; i < start + length; i++) { char c = ch[i]; switch (c) { case ' ': case '\t': case '\r': case '\n': continue; default: if ("h1".equals(node.name) || "h2".equals(node.name) || "h3".equals(node.name) || "h4".equals(node.name) || "h5".equals(node.name) || "h6".equals(node.name) || (node.ancestorMask & H1_MASK) != 0 || (node.ancestorMask & H2_MASK) != 0 || (node.ancestorMask & H3_MASK) != 0 || (node.ancestorMask & H4_MASK) != 0 || (node.ancestorMask & H5_MASK) != 0 || (node.ancestorMask & H6_MASK) != 0) { stack[currentHeadingPtr].setTextNodeFound(); } else if ("figcaption".equals(node.name) || (node.ancestorMask & FIGCAPTION_MASK) != 0) { if ((node.ancestorMask & FIGURE_MASK) != 0) { stack[currentFigurePtr].setFigcaptionContentFound(); } // for any ancestor figures of the parent figure // of this figcaption, the content of this // figcaption counts as a text node descendant for (int j = 1; j < currentFigurePtr; j++) { if ("figure".equals( stack[currentFigurePtr - j].getName())) { stack[currentFigurePtr - j].setTextNodeFound(); } } } else if ("figure".equals(node.name) || (node.ancestorMask & FIGURE_MASK) != 0) { stack[currentFigurePtr].setTextNodeFound(); // for any ancestor figures of this figure, this // also counts as a text node descendant for (int k = 1; k < currentFigurePtr; k++) { if ("figure".equals( stack[currentFigurePtr - k].getName())) { stack[currentFigurePtr - k].setTextNodeFound(); } } } else if ("option".equals(node.name) && !stack[currentPtr - 1].hasOption() && (!stack[currentPtr - 1].hasEmptyValueOption() || stack[currentPtr - 1].hasNoValueOption()) && stack[currentPtr - 1].nonEmptyOptionLocator() == null) { stack[currentPtr - 1].setNonEmptyOption( (new LocatorImpl(getDocumentLocator()))); } return; // This return can be removed if other code is added // here. But it's here for now because we know we // have at least one non-WS character, and for the // purposes of the current code, that's all we need; // it's a waste to keep checking for more. } } } private CharSequence renderTypeList(String[] types) { StringBuilder sb = new StringBuilder(); int len = types.length; for (int i = 0; i < len; i++) { if (i > 0) { sb.append(", "); } if (i == len - 1) { sb.append("or "); } sb.append("\u201C"); sb.append(types[i]); sb.append('\u201D'); } return sb; } private CharSequence renderRoleSet(Set<String> roles) { boolean first = true; StringBuilder sb = new StringBuilder(); for (String role : roles) { if (first) { first = false; } else { sb.append(" or "); } sb.append("\u201Crole="); sb.append(role); sb.append('\u201D'); } return sb; } }
package com.intellij.ide.ui.laf.intellij; import com.intellij.ide.ui.laf.darcula.ui.DarculaButtonUI; import com.intellij.ui.Gray; import com.intellij.util.ui.IconCache; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.MacUIUtil; import com.intellij.util.ui.UIUtil; import sun.swing.SwingUtilities2; import javax.swing.*; import javax.swing.plaf.ComponentUI; import java.awt.*; import java.awt.geom.Path2D; import java.awt.geom.RoundRectangle2D; import static com.intellij.ide.ui.laf.intellij.MacIntelliJTextBorder.ARC; import static com.intellij.ide.ui.laf.intellij.MacIntelliJTextBorder.LW; import static com.intellij.ide.ui.laf.intellij.MacIntelliJTextBorder.MINIMUM_HEIGHT; /** * @author Konstantin Bulenkov */ public class MacIntelliJButtonUI extends DarculaButtonUI { @SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"}) public static ComponentUI createUI(JComponent c) { return new MacIntelliJButtonUI(); } @Override public void paint(Graphics g, JComponent c) { if (!(c.getBorder() instanceof MacIntelliJButtonBorder)) { super.paint(g, c); return; } int w = c.getWidth(); int h = c.getHeight(); if (UIUtil.isHelpButton(c)) { Icon icon = IconCache.getIcon("helpButton", false, c.hasFocus(), true); int x = (w - icon.getIconWidth()) / 2; int y = (h - icon.getIconHeight()) / 2; icon.paintIcon(c, g, x, y); } else { AbstractButton b = (AbstractButton) c; Graphics2D g2 = (Graphics2D)g.create(); try { g2.translate(0, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, MacUIUtil.USE_QUARTZ ? RenderingHints.VALUE_STROKE_PURE : RenderingHints.VALUE_STROKE_NORMALIZE); float lw = LW(g2); float arc = ARC.getFloat(); Insets i = isSmallComboButton(c) ? JBUI.insets(1) : c.getInsets(); // Draw background Shape outerRect = new RoundRectangle2D.Float(i.left, i.top, w - (i.left + i.right), h - (i.top + i.bottom), arc, arc); g2.setPaint(getBackgroundPaint(c)); g2.fill(outerRect); // Draw outline Path2D outline = new Path2D.Float(Path2D.WIND_EVEN_ODD); outline.append(outerRect, false); outline.append(new RoundRectangle2D.Float(i.left + lw, i.top + lw, w - lw*2 - (i.left + i.right), h - lw*2 - (i.top + i.bottom), arc - lw, arc - lw), false); g2.setPaint(getBorderPaint(c)); g2.fill(outline); paintContents(g2, b); } finally { g2.dispose(); } } } @SuppressWarnings("UseJBColor") private static Paint getBackgroundPaint(JComponent b) { int h = b.getHeight(); Insets i = b.getInsets(); if (!b.isEnabled()) { return Gray.xF1; } else if (isDefaultButton(b)) { return UIUtil.isGraphite() ? new GradientPaint(0, i.top, new Color(0xb2b2b7), 0, h - (i.top + i.bottom), new Color(0x929297)) : new GradientPaint(0, i.top, new Color(0x68b2fa), 0, b.getHeight() - (i.top + i.bottom), new Color(0x0e80ff)); } else { Color backgroundColor = (Color)b.getClientProperty("JButton.backgroundColor"); return backgroundColor != null ? backgroundColor : Gray.xFF; } } @SuppressWarnings("UseJBColor") public static Paint getBorderPaint(JComponent b) { int h = b.getHeight(); Insets i = b.getBorder().getBorderInsets(b); if (!b.isEnabled()) { return new GradientPaint(0, i.top, Gray.xD2, 0, h - (i.top + i.bottom), Gray.xC3); } else if (isDefaultButton(b)) { return UIUtil.isGraphite() ? new GradientPaint(0, i.top, new Color(0xa5a5ab), 0, h - (i.top + i.bottom), new Color(0x7d7d83)) : new GradientPaint(0, i.top, new Color(0x4ba0f8), 0, h - (i.top + i.bottom), new Color(0x095eff)); } else { Color borderColor = (Color)b.getClientProperty("JButton.borderColor"); return borderColor != null ? borderColor : new GradientPaint(0, i.top, Gray.xC9, 0, h - (i.top + i.bottom), Gray.xAC); } } @Override protected Dimension getDarculaButtonSize(JComponent c, Dimension prefSize) { if (UIUtil.isHelpButton(c)) { Icon icon = IconCache.getIcon("helpButton"); return new Dimension(icon.getIconWidth(), icon.getIconHeight()); } else { Insets i = c.getInsets(); return new Dimension(getComboAction(c) != null ? prefSize.width: Math.max(HORIZONTAL_PADDING.get() * 2 + prefSize.width, MINIMUM_BUTTON_WIDTH.get() + i.left + i.right), Math.max(prefSize.height, getMinimumHeight() + i.top + i.bottom)); } } protected int getMinimumHeight() { return MINIMUM_HEIGHT.get(); } @Override protected void paintDisabledText(Graphics g, String text, JComponent c, Rectangle textRect, FontMetrics metrics) { int x = textRect.x + getTextShiftOffset(); int y = textRect.y + metrics.getAscent() + getTextShiftOffset(); if (isDefaultButton(c)) { g.setColor(Gray.xCC); } else { g.setColor(UIManager.getColor("Button.disabledText")); } SwingUtilities2.drawStringUnderlineCharAt(c, g, text, -1, x, y); } }
package gov.nih.nci.camod.service.impl; import gov.nih.nci.camod.Constants; import gov.nih.nci.camod.domain.Agent; import gov.nih.nci.camod.domain.AnimalModel; import gov.nih.nci.camod.domain.Comments; import gov.nih.nci.camod.domain.Log; import gov.nih.nci.camod.domain.Person; import gov.nih.nci.camod.domain.Publication; import gov.nih.nci.camod.util.DrugScreenResult; import gov.nih.nci.camod.webapp.form.SearchData; import gov.nih.nci.common.persistence.Search; import gov.nih.nci.common.persistence.exception.PersistenceException; import gov.nih.nci.common.persistence.hibernate.HQLParameter; import gov.nih.nci.common.persistence.hibernate.HibernateUtil; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; import javax.servlet.http.HttpServletRequest; import org.hibernate.Hibernate; import org.hibernate.Query; /** * Implementation of a wrapper around the HQL/JDBC interface. Used for more * complex instances where QBE does not have sufficient power. */ public class QueryManagerImpl extends BaseManager { /** * Return all NSC numbers * * @return a list of NSC numbers * * @throws PersistenceException */ public List getNSCNumbers() throws PersistenceException { log.debug("Entering QueryManagerImpl.getNSCNumbersAsStrings"); // Format the query HQLParameter[] theParams = new HQLParameter[0]; String theHQLQuery = "select distinct(a.nscNumber) from Agent as a WHERE nsc_number is not null"; List theList = Search.query(theHQLQuery, theParams); log.info("Found matching items: " + theList.size()); log.debug("Exiting QueryManagerImpl.getNSCNumbers"); return theList; } /** * Return the list of animal model names that start with the pattern passed in * * @param inPrefix * the starting characters of the name * * @return a sorted list of unique modelDescriptors * * @throws PersistenceException */ public List getMatchingAnimalModelNames(String inPrefix) throws PersistenceException { log.debug("Entering QueryManagerImpl.getMatchingAnimalModelNames"); // Format the query HQLParameter[] theParams = new HQLParameter[1]; theParams[0] = new HQLParameter(); theParams[0].setName("modelDescriptor"); theParams[0].setValue(inPrefix.toUpperCase() + "%"); theParams[0].setType(Hibernate.STRING); log.info("inPrefix: " + inPrefix); String theHQLQuery = "select distinct am.modelDescriptor from AnimalModel as am where upper(am.modelDescriptor) like :modelDescriptor AND am.state = 'Edited-approved' order by am.modelDescriptor asc "; List theList = Search.query(theHQLQuery, theParams); log.info("Found matching items: " + theList.size()); log.debug("Exiting QueryManagerImpl.getMatchingAnimalModelNames"); return theList; } /** * Return the list of organ object that start with the pattern passed in * * @param inPrefix * the starting characters of the name * * @return a sorted list of unique organ object * * @throws PersistenceException */ public List getMatchingOrgans(String inPrefix) throws PersistenceException { log.debug("Entering QueryManagerImpl.getMatchingOrganNames"); // Format the query HQLParameter[] theParams = new HQLParameter[1]; theParams[0] = new HQLParameter(); theParams[0].setName("name"); theParams[0].setValue(inPrefix.toUpperCase() + "%"); theParams[0].setType(Hibernate.STRING); //HQLParameter[] theParams = new HQLParameter[0]; log.info("inPrefix: " + inPrefix); String theHQLQuery = "select distinct histo.organ from AnimalModel as am left outer join am.histopathologyCollection as histo where am.state = 'Edited-approved' and upper(histo.organ.name) like :name"; List theList = Search.query(theHQLQuery, theParams); log.info("Found matching items: " + theList.size()); log.debug("Exiting QueryManagerImpl.getMatchingOrganNames"); return theList; } /** * Return the list of tumor classification object that start with the pattern passed in * * @param inPrefix * the starting characters of the name * * @return a sorted list of unique tumor classification object * * @throws PersistenceException */ public List getMatchingTumorClassifications(String inPrefix) throws PersistenceException { log.debug("Entering QueryManagerImpl.getMatchingTumorClassificationNames"); // Format the query HQLParameter[] theParams = new HQLParameter[1]; theParams[0] = new HQLParameter(); theParams[0].setName("name"); theParams[0].setValue(inPrefix.toUpperCase() + "%"); theParams[0].setType(Hibernate.STRING); //HQLParameter[] theParams = new HQLParameter[0]; log.info("inPrefix: " + inPrefix); String theHQLQuery = "select distinct histo.disease from AnimalModel as am left outer join am.histopathologyCollection as histo where am.state = 'Edited-approved' and upper(histo.disease.name) like :name"; List theList = Search.query(theHQLQuery, theParams); log.info("Found matching items: " + theList.size()); log.debug("Exiting QueryManagerImpl.getMatchingTumorClassificationNames"); return theList; } /** * Return the list of gene names that start with the pattern passed in * * @param inPrefix * the starting characters of the name * * @return a sorted list of unique gene names * * @throws PersistenceException */ public List getMatchingGeneNames(String inPrefix) throws PersistenceException { log.debug("Entering QueryManagerImpl.getMatchingGeneNames"); // Format the query HQLParameter[] theParams = new HQLParameter[1]; theParams[0] = new HQLParameter(); theParams[0].setName("name"); theParams[0].setValue(inPrefix.toUpperCase() + "%"); theParams[0].setType(Hibernate.STRING); log.info("inPrefix: " + inPrefix); String theHQLQuery = "select distinct genes.name from AnimalModel as am left outer join am.engineeredGeneCollection as genes where upper(genes.name) like :name AND am.state = 'Edited-approved' "; List theList = Search.query(theHQLQuery, theParams); log.info("Found matching items: " + theList.size()); log.debug("Exiting QueryManagerImpl.getMatchingGeneNames"); return theList; } /** * Return the list of environmental factor names * * @param inType * the type of environmental factor * * @return a sorted list of unique environmental factors * @throws PersistenceException */ public List getEnvironmentalFactors(String inType) throws PersistenceException { log.info("Entering QueryManagerImpl.getEnvironmentalFactors"); // Format the query HQLParameter[] theParams = new HQLParameter[1]; theParams[0] = new HQLParameter(); theParams[0].setName("type"); theParams[0].setValue(inType); theParams[0].setType(Hibernate.STRING); log.info("inType: " + inType); String theHQLQuery = "select distinct ef.name from EnvironmentalFactor as ef where ef.type = :type and ef.name is not null order by ef.name asc "; List theList = Search.query(theHQLQuery, theParams); log.info("Found matching items: " + theList.size()); log.info("Exiting QueryManagerImpl.getAdministrativeRoutes"); return theList; } /** * Return the list of environmental factor names * * @param inType * the type of environmental factor * * @return a sorted list of unique environmental factors * @throws PersistenceException */ public List getQueryOnlyEnvironmentalFactors(String inType) throws PersistenceException { log.info("Entering QueryManagerImpl.getQueryOnlyEnvironmentalFactors"); ResultSet theResultSet = null; List<String> theEnvFactors = new ArrayList<String>(); try { // Format the query String theSQLQuery = "SELECT ef.name, ef.name_unctrl_vocab " + "FROM environmental_factor ef " + "WHERE ef.type = ? " + " AND ef.name IS NOT null " + " AND ef.environmental_factor_id IN (SELECT ce.environmental_factor_id " + " FROM carcinogen_exposure ce, abs_cancer_model am " + " WHERE ef.environmental_factor_id = ce.environmental_factor_id " + " AND am.abs_cancer_model_id = ce.abs_cancer_model_id AND am.state = 'Edited-approved') ORDER BY ef.name asc "; Object[] theParams = new Object[1]; theParams[0] = inType; theResultSet = Search.query(theSQLQuery, theParams); while (theResultSet.next()) { String theName = theResultSet.getString(1); String theUncontrolledName = theResultSet.getString(2); if (theName != null && theName.length() > 0 && !theEnvFactors.contains(theName)) { theEnvFactors.add(theName); } else if (theUncontrolledName != null && theUncontrolledName.length() > 0 && !theEnvFactors.contains(theUncontrolledName)) { theEnvFactors.add(theName); } } Collections.sort(theEnvFactors); log.info("Exiting QueryManagerImpl.getQueryOnlyEnvironmentalFactors"); } catch (Exception e) { log.error("Exception in getQueryOnlyEnvironmentalFactors", e); throw new PersistenceException("Exception in getQueryOnlyEnvironmentalFactors: " + e); } finally { if (theResultSet != null) { try { theResultSet.close(); } catch (Exception e) {} } } return theEnvFactors; } /** * Return the list of environmental factor names which were used to induce a * mutation * * @return a sorted list of unique environmental factors * @throws PersistenceException */ public List getQueryOnlyInducedMutationAgents() throws PersistenceException { log.info("Entering QueryManagerImpl.getQueryOnlyInducedMutationAgents"); ResultSet theResultSet = null; List<String> theAgents = new ArrayList<String>(); try { // Format the query String theSQLQuery = "SELECT distinct ef.name FROM environmental_factor ef, engineered_gene eg " + "WHERE ef.name IS NOT null AND ef.environmental_factor_id = eg.environmental_factor_id"; Object[] theParams = new Object[0]; theResultSet = Search.query(theSQLQuery, theParams); while (theResultSet.next()) { theAgents.add(theResultSet.getString(1)); } log.info("Exiting QueryManagerImpl.getQueryOnlyInducedMutationAgents"); } catch (Exception e) { log.error("Exception in getQueryOnlyInducedMutationAgents", e); throw new PersistenceException("Exception in getQueryOnlyInducedMutationAgents: " + e); } finally { if (theResultSet != null) { try { theResultSet.close(); } catch (Exception e) {} } } return theAgents; } /** * Return the list of species associated with animal models * * @return a sorted list of unique species * * @throws PersistenceException */ public List getQueryOnlySpecies(HttpServletRequest inRequest) throws PersistenceException { log.info("Entering QueryManagerImpl.getQueryOnlySpecies"); // Format the query HQLParameter[] theParams = new HQLParameter[0]; String theHQLQuery = "from Species where scientificName is not null order by scientificName asc"; List theList = Search.query(theHQLQuery, theParams); log.info("Found matching items: " + theList.size()); log.info("Exiting QueryManagerImpl.getQueryOnlySpecies"); return theList; } public List getApprovedSpecies(HttpServletRequest inRequest) throws PersistenceException { log.info("Entering QueryManagerImpl.getSpeciesObject"); // Format the query HQLParameter[] theParams = new HQLParameter[0]; String theHQLQuery = "from Species where scientificName is not null order by scientificName asc"; List theList = Search.query(theHQLQuery, theParams); log.info("Found matching items: " + theList.size()); log.info("Exiting QueryManagerImpl.getQueryOnlySpecies"); return theList; } /** * Return the list of PI's sorted by last name * * @return a sorted list of People objects * @throws PersistenceException */ public List getPrincipalInvestigators() throws PersistenceException { log.info("Entering QueryManagerImpl.getPrincipalInvestigators"); // Format the query HQLParameter[] theParams = new HQLParameter[0]; String theHQLQuery = "from Person where is_principal_investigator = 1 order by last_name asc"; List theList = Search.query(theHQLQuery, theParams); log.info("Found matching items: " + theList.size()); log.info("Exiting QueryManagerImpl.getPrincipalInvestigators"); return theList; } /** * Return the list of PI's sorted by last name * * @return a sorted list of People objects * @throws PersistenceException */ public List getPeopleByRole(String inRole) throws PersistenceException { log.info("Entering QueryManagerImpl.getPeopleByRole"); String theHQLQuery = "from Person where username is not null "; if (!inRole.equals(Constants.Admin.Roles.ALL)) { theHQLQuery += " AND party_id in (" + getPartyIdsForRole(inRole) + ") "; } // Complete the query theHQLQuery += " order by last_name asc"; HQLParameter[] theParams = new HQLParameter[0]; List theList = Search.query(theHQLQuery, theParams); log.info("Found matching items: " + theList.size()); log.info("Exiting QueryManagerImpl.getPeopleByRole"); return theList; } /** * Get the model id's for any model that has a histopathology with a parent * histopathology * * @return a list of matching model ids * * @throws PersistenceException */ private String getPartyIdsForRole(String inRole) throws PersistenceException { String theSQLString = "SELECT distinct pr.party_id FROM party_role pr " + "WHERE pr.role_id IN (SELECT role_id FROM role r " + " WHERE r.name = ?)"; Object[] theParams = new Object[1]; theParams[0] = inRole; return getIds(theSQLString, theParams); } /** * Return the list of species associated with animal models * * @return a sorted list of unique species * * @throws PersistenceException */ public List getQueryOnlyPrincipalInvestigators() throws PersistenceException { log.info("Entering QueryManagerImpl.getQueryOnlyPrincipalInvestigators"); // Format the query String theSQLString = "SELECT last_name, first_name " + "FROM party " + "WHERE is_principal_investigator = 1 " + " AND first_name IS NOT NULL " + " AND last_name IS NOT NULL " + " AND party_id IN (SELECT DISTINCT principal_investigator_id FROM abs_cancer_model WHERE state = 'Edited-approved')" + "ORDER BY last_name ASC"; ResultSet theResultSet = null; List<String> thePIList = new ArrayList<String>(); try { log.info("getQueryOnlyPrincipalInvestigators - SQL: " + theSQLString); Object[] params = new Object[0]; theResultSet = Search.query(theSQLString, params); while (theResultSet.next()) { String thePIEntry = theResultSet.getString(1) + ", " + theResultSet.getString(2); thePIList.add(thePIEntry); } } catch (Exception e) { log.error("Exception in getQueryOnlyPrincipalInvestigators", e); throw new PersistenceException("Exception in getQueryOnlyPrincipalInvestigators: " + e); } finally { if (theResultSet != null) { try { theResultSet.close(); } catch (Exception e) {} } } return thePIList; } /** * Return the latest log for an animal model * * @param inModel * the animal model to get the latest log for * * @return the current log for an animal model * @throws PersistenceException */ public Log getCurrentLog(AnimalModel inModel) throws PersistenceException { log.info("Entering QueryManagerImpl.getCurrentLog"); HQLParameter[] theParams = new HQLParameter[1]; theParams[0] = new HQLParameter(); theParams[0].setName("abs_cancer_model_id"); theParams[0].setValue(inModel.getId()); theParams[0].setType(Hibernate.LONG); String theHQLQuery = "from Log where abs_cancer_model_id = :abs_cancer_model_id order by timestamp desc"; log.info("The HQL query: " + theHQLQuery); List theLogs = Search.query(theHQLQuery, theParams); Log theLog = null; if (theLogs != null && theLogs.size() > 0) { theLog = (Log) theLogs.get(0); log.info("Found a matching object: " + theLog.getId()); } else { log.info("No object found."); } log.info("Exiting QueryManagerImpl.getCurrentLog"); return theLog; } /** * Return the latest log for an animal model/user combo * * @param inModel * the animal model to get the latest log for * @param inUser * the user to get the latest log for * * @return the current log for an animal model/user combination * @throws PersistenceException */ public Log getCurrentLogForUser(AnimalModel inModel, Person inUser) throws PersistenceException { log.info("Entering QueryManagerImpl.getCurrentLogForUser"); // Format the query HQLParameter[] theParams = new HQLParameter[2]; theParams[0] = new HQLParameter(); theParams[0].setName("abs_cancer_model_id"); theParams[0].setValue(inModel.getId()); theParams[0].setType(Hibernate.LONG); theParams[1] = new HQLParameter(); theParams[1].setName("party_id"); theParams[1].setValue(inUser.getId()); theParams[1].setType(Hibernate.LONG); String theHQLQuery = "from Log where abs_cancer_model_id = :abs_cancer_model_id and party_id = :party_id " + "and comments_id is null order by timestamp desc"; log.info("the HQL Query: " + theHQLQuery); List theLogs = Search.query(theHQLQuery, theParams); Log theLog = null; if (theLogs != null && theLogs.size() > 0) { theLog = (Log) theLogs.get(0); log.info("Found a matching object: " + theLog.getId()); } else { log.info("No object found."); } log.info("Exiting QueryManagerImpl.getCurrentLogForUser"); return theLog; } /** * Return the latest log for a comment/user combo * * @param inComments * the comments to get the latest log for * @param inUser * the user to get the latest log for * * @return the current log for an comments/user combination * * @throws PersistenceException */ public Log getCurrentLogForUser(Comments inComments, Person inUser) throws PersistenceException { log.info("Entering QueryManagerImpl.getCurrentLogForUser"); // Format the query HQLParameter[] theParams = new HQLParameter[3]; theParams[0] = new HQLParameter(); theParams[0].setName("abs_cancer_model_id"); theParams[0].setValue(inComments.getCancerModel().getId()); theParams[0].setType(Hibernate.LONG); theParams[1] = new HQLParameter(); theParams[1].setName("party_id"); theParams[1].setValue(inUser.getId()); theParams[1].setType(Hibernate.LONG); theParams[2] = new HQLParameter(); theParams[2].setName("comments_id"); theParams[2].setValue(inComments.getId()); theParams[2].setType(Hibernate.LONG); String theHQLQuery = "from Log where abs_cancer_model_id = :abs_cancer_model_id and party_id = :party_id " + "and comments_id = :comments_id order by timestamp desc"; log.info("the HQL Query: " + theHQLQuery); List theLogs = Search.query(theHQLQuery, theParams); Log theLog = null; if (theLogs != null && theLogs.size() > 0) { theLog = (Log) theLogs.get(0); log.info("Found a matching object: " + theLog.getId()); } else { log.info("No object found."); } log.info("Exiting QueryManagerImpl.getCurrentLogForUser"); return theLog; } /** * Return all of the comments associated with a person that match the state * passed in * * @param inState * the state of the comment * * @param inPerson * the person to match * * @return a list of matching comments * * @throws PersistenceException */ public List getCommentsBySection(String inSection, Person inPerson, AnimalModel inModel) throws PersistenceException { log.info("Entering QueryManagerImpl.getCommentsBySectionForPerson"); // If no person, only get approved items // TODO: make the states a constant String theStateHQL = "(c.state = 'Screened-approved'"; if (inPerson == null) { theStateHQL += ") "; } else { theStateHQL += "or c.submitter = :party_id) "; } String theHQLQuery = "from Comments as c where " + theStateHQL + " and c.cancerModel in (" + "from AnimalModel as am where am.id = :abs_cancer_model_id) and c.modelSection in (from ModelSection where name = :name)"; log.info("The HQL query: " + theHQLQuery); Query theQuery = HibernateUtil.getSession().createQuery(theHQLQuery); theQuery.setParameter("abs_cancer_model_id", inModel.getId()); theQuery.setParameter("name", inSection); // Only query for party if the passed in party wasn't null if (inPerson != null) { theQuery.setParameter("party_id", inPerson.getId()); } List theComments = theQuery.list(); if (theComments == null) { theComments = new ArrayList(); } log.info("Exiting QueryManagerImpl.getCommentsByStateForPerson"); return theComments; } /** * Return all of the comments associated with a person that match the state * passed in * * @param inState * the state of the comment * * @param inPerson * the person to match * * @return a list of matching comments * * @throws PersistenceException */ public List getCommentsByStateForPerson(String inState, Person inPerson) throws PersistenceException { log.info("Entering QueryManagerImpl.getCommentsByStateForPerson"); String theHQLQuery = "from Comments as c where c.state = :state and c.id in ("; Query theQuery = null; if (inPerson == null) { theHQLQuery += "select l.comment from Log as l where l.type = :state)"; theQuery = HibernateUtil.getSession().createQuery(theHQLQuery); theQuery.setParameter("state", inState); } else { theHQLQuery += "select l.comment from Log as l where l.submitter = :party_id and l.type = :state)"; theQuery = HibernateUtil.getSession().createQuery(theHQLQuery); theQuery.setParameter("party_id", inPerson.getId()); theQuery.setParameter("state", inState); } log.info("The HQL query: " + theHQLQuery); List theComments = theQuery.list(); if (theComments == null) { theComments = new ArrayList(); } log.info("Exiting QueryManagerImpl.getCommentsByStateForPerson"); return theComments; } /** * Return all of the models associated with a person that match the state * passed in * * @param inState * the state of the comment * * @param inPerson * the person to match * * @return a list of matching models * * @throws PersistenceException */ public List getModelsByStateForPerson(String inState, Person inPerson) throws PersistenceException { log.info("Entering QueryManagerImpl.getCurrentLog"); String theHQLQuery = "from AnimalModel as am where am.state = :state and am.id in ("; Query theQuery = null; if (inPerson == null) { theHQLQuery += "select l.cancerModel from Log as l where l.type = :state)"; theQuery = HibernateUtil.getSession().createQuery(theHQLQuery); theQuery.setParameter("state", inState); } else { theHQLQuery += "select l.cancerModel from Log as l where l.submitter = :party_id and l.type = :state)"; theQuery = HibernateUtil.getSession().createQuery(theHQLQuery); theQuery.setParameter("party_id", inPerson.getId()); theQuery.setParameter("state", inState); } log.info("The HQL query: " + theHQLQuery); List theComments = theQuery.list(); if (theComments == null) { theComments = new ArrayList(); } return theComments; } /** * Return all of the models associated which have the passed in user as * either the submitter _or_ the PI * * @param inUsername * * @return a list of matching models * * @throws PersistenceException */ public List getModelsByUser(String inUsername) throws PersistenceException { log.info("Entering QueryManagerImpl.getModelsByUser"); String theHQLQuery = "from AnimalModel as am where " + " am.submitter in (from Person where username = :username) or" + " am.principalInvestigator in (from Person where username = :username) " + " order by model_descriptor"; log.info("The HQL query: " + theHQLQuery); Query theQuery = HibernateUtil.getSession().createQuery(theHQLQuery); theQuery.setParameter("username", inUsername); log.info("Entering QueryManagerImpl.getModelsByUser here"); List theComments = new ArrayList(); // breaks before this line theComments = theQuery.list(); if (theComments == null) { theComments = new ArrayList(); } return theComments; } /** * Return all of InvivoResult objects with a specific NSC number * * @param inNscNumber * * @return a list of matching InvivoResult objects * * @throws PersistenceException */ public List getInvivoResultCollectionByNSC(String inNSCNumber, String inModelId) throws PersistenceException { log.info("Entering QueryManagerImpl.getInvivoResultCollectionByNSC"); String theHQLQuery = "from InvivoResult as ir where " + " ir.id in (" + getInvivoIdsForNSCNumberAndModel(inNSCNumber, inModelId) + ")"; log.info("The HQL query: " + theHQLQuery); Query theQuery = HibernateUtil.getSession().createQuery(theHQLQuery); List theResults = theQuery.list(); if (theResults == null) { theResults = new ArrayList(); } return theResults; } /** * Get the InvivoResult id's for for a given NSC number and model * * @return a list of matching ids * * @throws PersistenceException */ private String getInvivoIdsForNSCNumberAndModel(String inNSCNumber, String inModelId) throws PersistenceException { String theSQLString = "SELECT distinct xeno_inv.invivo_result_id FROM xenograft_invivo_result xeno_inv " + "WHERE xeno_inv.invivo_result_id IN (SELECT ir.invivo_result_id FROM invivo_result ir, agent ag " + " WHERE ir.agent_id = ag.agent_id and ag.nsc_number = ?) and xeno_inv.abs_cancer_model_id = ?"; Object[] theParams = new Object[2]; theParams[0] = inNSCNumber; theParams[1] = inModelId; return getIds(theSQLString, theParams); } /** * Get yeast screen result data (ave inibition etc.) for a given Agent * (drug) * * @param agent * refers to the compound that was used in the yeast experiment * @param stage * is the stage of the experiment (0, 1, or 2) * * @return the results * @throws PersistenceException */ public DrugScreenResult getYeastScreenResults(Agent agent, String stage, boolean useNscNumber) throws PersistenceException { DrugScreenResult dsr = new DrugScreenResult(); ResultSet theResultSet = null; try { String theSQLString = "select st.name," + "\n" + " t.dosage," + "\n" + " sr.aveinh aveinh," + "\n" + " sr.diffinh diffinh" + "\n" + " from screening_Result sr," + "\n" + " agent ag," + "\n" + " strain st," + "\n" + " YST_MDL_SCRNING_RESULT ymsr," + "\n" + " abs_cancer_model acm," + "\n" + " treatment t," + "\n" + " species sp" + "\n" + " where sr.agent_id = ag.agent_id" + "\n" + " and sr.screening_result_id = ymsr.screening_result_id" + "\n" + " and sr.treatment_id = t.treatment_id" + "\n" + " and ymsr.abs_cancer_model_id = acm.abs_cancer_model_id" + "\n" + " and acm.strain_id = st.strain_id" + "\n" + " and st.species_id = sp.species_id" + "\n" + " and sr.stage = ?" + "\n"; // We query for the agent id on the drug screen search pages and the nsc number on // the theraputic approaches pages Long theParam; if (useNscNumber == true) { theSQLString += " and ag.nsc_number = ?" + "\n"; theParam = agent.getNscNumber(); } else { theSQLString += " and ag.agent_id = ?" + "\n"; theParam = agent.getId(); } theSQLString += " order by st.name, to_number(t.dosage)"; log.info("getYeastScreenResults - SQL: " + theSQLString); Object[] params = new Object[2]; params[0] = stage; params[1] = theParam; theResultSet = Search.query(theSQLString, params); while (theResultSet.next()) { final String strain = theResultSet.getString(1); final String dosage = theResultSet.getString(2); final float aveinh = theResultSet.getFloat(3); final float diffinh = theResultSet.getFloat(4); dsr.addEntry(strain, dosage, aveinh, diffinh); } log.info("Got " + dsr.strainCount + " strains"); } catch (Exception e) { log.error("Exception in getYeastScreenResults", e); throw new PersistenceException("Exception in getYeastScreenResults: " + e); } finally { if (theResultSet != null) { try { theResultSet.close(); } catch (Exception e) {} } } return dsr; } /** * Get the invivo (Xenograft) data (from DTP) for a given Agent.nscNumber * (drug) * * @param agent * refers to the compound that was used in the xenograft * experiment * * @return the results (list of abs_cancer_model_id, model_descriptor, and # * of records * @throws PersistenceException */ //Sima TODO: optimize the extra join for strain_id/species_id public List getInvivoResults(Agent agent, boolean useNscNumber) throws PersistenceException { List<String[]> results = new ArrayList<String[]>(); int cc = 0; ResultSet theResultSet = null; log.info("Env factor_id=" + agent.getId()); try { String theSQLString = "select acm.abs_cancer_model_id," + "\n" + " acm.model_descriptor," + "\n" + " st.name," + "\n" + " acm.administrative_site," + "\n" + " count(*)" + "\n" + " from invivo_Result sr," + "\n" + " agent a," + "\n" + " XENOGRAFT_INVIVO_RESULT ymsr," + "\n" + " abs_cancer_model acm," + "\n" + " treatment t," + "\n" + " strain st," + "\n" + " species sp" + "\n" + " where sr.agent_id = a.agent_id" + "\n" + " and sr.invivo_result_id = ymsr.invivo_result_id" + "\n" + " and sr.treatment_id = t.treatment_id" + "\n" + " and ymsr.abs_cancer_model_id = acm.abs_cancer_model_id" + "\n" + " and acm.strain_id = st.strain_id" + "\n" + " and st.species_id = sp.species_id" + "\n"; Long theParam; if (useNscNumber == true) { theSQLString += " and a.nsc_number = ?" + "\n"; theParam = agent.getNscNumber(); } else { theSQLString += " and a.agent_id = ?" + "\n"; theParam = agent.getId(); } theSQLString += " group by acm.abs_cancer_model_id, acm.model_descriptor, st.name, acm.administrative_site" + "\n" + " order by 3, 2"; log.info("getInvivoResults - SQL: " + theSQLString); Object[] params = new Object[1]; params[0] = theParam; theResultSet = Search.query(theSQLString, params); while (theResultSet.next()) { String[] item = new String[5]; item[0] = theResultSet.getString(1); // the id item[1] = theResultSet.getString(2); // model descriptor item[2] = theResultSet.getString(3); // strain item[3] = theResultSet.getString(4); // administrative site item[4] = theResultSet.getString(5); // record count results.add(item); cc++; } log.info("Got " + cc + " xenograft models"); } catch (Exception e) { log.error("Exception in getYeastScreenResults", e); throw new PersistenceException("Exception in getYeastScreenResults: " + e); } finally { if (theResultSet != null) { try { theResultSet.close(); } catch (Exception e) {} } } return results; } /** * Get the model id's for any model that has a strain associated w/ the species * * @param inSpecies * the species to search for * * @return a list of matching model id * * @throws PersistenceException */ private String getStrainIdsForSpecies(String inSpecies) throws PersistenceException { String theSQLString = "SELECT distinct strain.strain_id FROM strain WHERE strain.species_id IN (SELECT species.species_id FROM species WHERE species.scientific_name like ? or species.scientific_name_unctrl_vocab like ?) "; System.out.println("SQL: " + theSQLString); Object[] theParams = new Object[2]; theParams[0] = inSpecies; theParams[1] = theParams[0]; System.out.println("The params: " + theParams[0]); return getIds(theSQLString, theParams); } /** * Get the model id's for any model that has a histopathology associated * with a specific organ. * * @param inConceptCodes * the concept codes and organ tissue name to search for * * @return a list of matching model id * * @throws PersistenceException */ private String getModelIdsForHistopathologyOrgan(String inConceptCodes, String inOrganTissueName) throws PersistenceException { String theConceptCodeList = ""; // Format the query Object[] theParams = null; String theSQLString = "SELECT distinct hist.abs_cancer_model_id FROM histopathology hist " + "WHERE hist.abs_cancer_model_id IS NOT null " + "AND hist.histopathology_id IN (SELECT h.histopathology_id " + " FROM histopathology h, organ o " + " WHERE h.organ_id = o.organ_id "; if (inOrganTissueName != null && inOrganTissueName.length() > 0 && inConceptCodes == null || inConceptCodes.trim().length() == 0) { theParams = new Object[1]; theParams[0] = "%"+inOrganTissueName.toUpperCase()+ "%"; theSQLString += " AND upper(o.name) like ? )"; } else if (inConceptCodes.trim().length() > 0) { StringTokenizer theTokenizer = new StringTokenizer(inConceptCodes, ","); theParams = new Object[0]; while (theTokenizer.hasMoreElements()) { theConceptCodeList += "'" + theTokenizer.nextToken() + "'"; // Only tack on a , if it's not the last element if (theTokenizer.hasMoreElements()) { theConceptCodeList += ","; } } theSQLString += " AND o.concept_code IN (" + theConceptCodeList + "))"; } return getIds(theSQLString, theParams); } /** * Get the model id's for any model that has a histopathology with a parent * histopathology * * @return a list of matching model ids * * @throws PersistenceException */ private String getModelIdsForHistoMetastasis() throws PersistenceException { String theSQLString = "SELECT distinct hist.abs_cancer_model_id FROM histopathology hist " + "WHERE hist.abs_cancer_model_id IS NOT null " + "AND hist.histopathology_id IN (SELECT h.parent_histopathology_id FROM histopathology h " + " WHERE h.parent_histopathology_id IS NOT NULL)"; Object[] theParams = new Object[0]; return getIds(theSQLString, theParams); } /** * Get the model id's for any model that has a histopathology with a parent * histopathology * * @return a list of matching model ids * * @throws PersistenceException */ private String getModelIdsForXenograft() throws PersistenceException { String theSQLString = "SELECT distinct par_abs_can_model_id FROM abs_cancer_model "; Object[] theParams = new Object[0]; return getIds(theSQLString, theParams); } /** * Get the model id's for any model that has associated microarray data * * @return a list of matching model ids * * @throws PersistenceException */ private String getModelIdsForMicroArrayData() throws PersistenceException { String theSQLString = "SELECT distinct abs_cancer_model_id FROM micro_array_data"; Object[] theParams = new Object[0]; return getIds(theSQLString, theParams); } /** * Get the model id's for any model that has associated transient interface data * * @return a list of matching model ids * * @throws PersistenceException */ private String getModelIdsForTransientInterference() throws PersistenceException { String theSQLString = "SELECT distinct abs_cancer_model_id FROM morpholino"; Object[] theParams = new Object[0]; return getIds(theSQLString, theParams); } /** * Get the model id's for any model that has a cellline w/ a matching name * * @param inCellLineName * the text to search for in the cell-line * * @return a list of matching model id * * @throws PersistenceException */ private String getModelIdsForCellLine(String inCellLineName) throws PersistenceException { String theSQLString = "SELECT distinct cell.abs_cancer_model_id FROM cell_line cell " + "WHERE cell.cell_line_id IN (SELECT c.cell_line_id FROM cell_line c " + " WHERE upper(c.name) LIKE ?)"; Object[] theParams = new Object[1]; theParams[0] = "%" + inCellLineName + "%"; return getIds(theSQLString, theParams); } /** * Get the model id's for any model that has a histopathology associated * with a specific organ. * * @param inDisease * the disease to search for * * @return a list of matching model id * * @throws PersistenceException */ private String getModelIdsForTherapeuticApproach(String inTherapeuticApproach) throws PersistenceException { String theSQLString = "SELECT distinct ther.abs_cancer_model_id " + "FROM therapy ther " + "WHERE ther.therapy_id IN (SELECT t.therapy_id FROM therapy t, agent ag " + " WHERE t.agent_id = ag.agent_id " + " AND upper(ag.name) like ?)"; String theSQLTheraputicApproach = "%"; if (inTherapeuticApproach != null && inTherapeuticApproach.trim().length() > 0) { theSQLTheraputicApproach = "%" + inTherapeuticApproach.trim().toUpperCase() + "%"; } Object[] theParams = new Object[1]; theParams[0] = theSQLTheraputicApproach; return getIds(theSQLString, theParams); } /** * Get the model id's for any model that has a transient interference associated * with a specific organ. * * @param inTransientInterference * the transient interface to search for * * @return a list of matching model id * * @throws PersistenceException */ private String getModelIdsForTransientInterference(String inTransientInterference) throws PersistenceException { String theSQLString = "SELECT distinct m.abs_cancer_model_id " + "FROM morpholino m WHERE upper(m.targeted_region) like ?"; String theSQLTheraputicApproach = "%"; if (inTransientInterference != null && inTransientInterference.trim().length() > 0) { theSQLTheraputicApproach = "%" + inTransientInterference.trim().toUpperCase() + "%"; } Object[] theParams = new Object[1]; theParams[0] = theSQLTheraputicApproach; return getIds(theSQLString, theParams); } /** * Get the model id's for any model that has a histopathology associated * with a specific disease. * * @param inDisease * the concept code and disease name to search for * * @return a list of matching model id * * @throws PersistenceException */ private String getModelIdsForHistopathologyDisease(String inConceptCodes, String inDiseaseName) throws PersistenceException { String theConceptCodeList = ""; // Format the query Object[] theParams = null; String theSQLString = "SELECT distinct hist.abs_cancer_model_id " + "FROM histopathology hist " + "WHERE hist.histopathology_id IS NOT null " + "AND hist.histopathology_id IN (SELECT h.histopathology_id " + " FROM histopathology h, disease d " + " WHERE h.disease_id = d.disease_id "; if (inDiseaseName != null && inDiseaseName.trim().length() > 0 && inConceptCodes == null || inConceptCodes.trim().length() == 0 || inConceptCodes.equalsIgnoreCase("000000") && inConceptCodes.trim().length() > 0) { theParams = new Object[1]; theParams[0] = "%"+inDiseaseName.toUpperCase()+ "%"; theSQLString += " AND upper(d.name) like ? )"; } else if (inConceptCodes.trim().length() > 0) { StringTokenizer theTokenizer = new StringTokenizer(inConceptCodes, ","); theParams = new Object[0]; while (theTokenizer.hasMoreElements()) { theConceptCodeList += "'" + theTokenizer.nextToken() + "'"; // Only tack on a , if it's not the last element if (theTokenizer.hasMoreElements()) { theConceptCodeList += ","; } } theSQLString += " AND d.concept_code IN (" + theConceptCodeList + "))"; } return getIds(theSQLString, theParams); } /** * Get the models with the associated engineered gene * * @param inGeneName * the name of the transgene or targeted modification * * @param isEngineeredTransgene * are we looking for a transgene? * * @param isEngineeredTransgene * are we looking for an induced mutation? * * @param inGenomicSegDesignator * the name of the genomic segment designator * * @param inInducedMutationAgent * the name of Agent which induced the mutation. Exact match. * * @return a list of matching model id * * @throws PersistenceException * */ //Sima TODO: could not test IM since original query returned 0 results in camoddev private String getModelIdsForEngineeredGenes(String inGeneName, boolean isEngineeredTransgene, boolean isTargetedModification, String inGenomicSegDesignator, String inInducedMutationAgent) throws PersistenceException { List<Object> theList = new ArrayList<Object>(); String theSQLString = "SELECT eg.abs_cancer_model_id " + "FROM engineered_gene eg WHERE "; String OR = " "; if (isEngineeredTransgene == true && inGeneName.trim().length() > 0) { theSQLString += OR + " eg.engineered_gene_id IN (SELECT distinct engineered_gene_id " + " FROM engineered_gene WHERE upper(name) LIKE ? AND engineered_gene_type = 'T')"; OR = " OR "; theList.add("%" + inGeneName.trim().toUpperCase() + "%"); } if (isTargetedModification == true && inGeneName.trim().length() > 0) { theSQLString += OR + " eg.engineered_gene_id IN (SELECT distinct engineered_gene_id " + " FROM engineered_gene WHERE upper(name) LIKE ? AND engineered_gene_type = 'TM')"; OR = " OR "; theList.add("%" + inGeneName.trim().toUpperCase() + "%"); } if (inInducedMutationAgent != null && inInducedMutationAgent.trim().length() > 0) { theSQLString += OR + " eg.engineered_gene_id IN (SELECT distinct engineered_gene_id " + " FROM engineered_gene WHERE engineered_gene_id IN (" + " SELECT distinct eg.engineered_gene_id FROM environmental_factor ef, engineered_gene eg " + " WHERE ef.name = ? " + " AND ef.environmental_factor_id = eg.environmental_factor_id) AND engineered_gene_type = 'IM')"; OR = " OR "; theList.add(inInducedMutationAgent.trim()); } if (inGenomicSegDesignator != null && inGenomicSegDesignator.trim().length() > 0) { theSQLString += OR + " eg.engineered_gene_id IN (SELECT distinct engineered_gene_id " + " FROM engineered_gene WHERE upper(clone_designator) LIKE ? AND engineered_gene_type = 'GS')"; theList.add(inGenomicSegDesignator.trim().toUpperCase()); } // Convert the params Object[] theParams = new Object[theList.size()]; for (int i = 0; i < theList.size(); i++) { theParams[i] = theList.get(i); } return getIds(theSQLString, theParams); } /** * Get the models with the associated engineered gene * * @param inKeyword * the keyword to search for * * @return a list of matching model id * * @throws PersistenceException * */ private String getModelIdsForAnyEngineeredGene(String inKeyword) throws PersistenceException { String theSQLString = "SELECT distinct eg.abs_cancer_model_id " + "FROM engineered_gene eg WHERE "; theSQLString += " eg.engineered_gene_id IN (SELECT distinct engineered_gene_id " + " FROM engineered_gene WHERE upper(name) LIKE ?)"; theSQLString += " OR eg.engineered_gene_id IN (SELECT distinct engineered_gene_id " + " FROM engineered_gene WHERE engineered_gene_id IN (" + " SELECT distinct egg.engineered_gene_id FROM environmental_factor ef, engineered_gene egg " + " WHERE upper(ef.name) like ? " + " AND ef.environmental_factor_id = egg.environmental_factor_id) AND engineered_gene_type = 'IM')"; theSQLString += " OR eg.engineered_gene_id IN (SELECT distinct engineered_gene_id " + " FROM engineered_gene WHERE upper(clone_designator) LIKE ? AND engineered_gene_type = 'GS')"; // Convert the params Object[] theParams = new Object[3]; theParams[0] = inKeyword; theParams[1] = inKeyword; theParams[2] = inKeyword; return getIds(theSQLString, theParams); } /** * Get the model id's that have an carcinogen_exposure * * @return a list of matching model id * * @throws PersistenceException */ private String getModelIdsForAnyEnvironmentalFactor() throws PersistenceException { String theSQLString = "SELECT distinct ce.abs_cancer_model_id FROM carcinogen_exposure ce "; Object[] theParams = new Object[0]; return getIds(theSQLString, theParams); } /** * Get the model id's that have a matching environmental factor * * @param inType * the EF type * @param inName * the name to look for * * @return a list of matching model id * * @throws PersistenceException */ private String getModelIdsForEnvironmentalFactor(String inType, String inName) throws PersistenceException { String theSQLString = "SELECT distinct ce.abs_cancer_model_id FROM carcinogen_exposure ce " + "WHERE ce.environmental_factor_id IN (SELECT ef.environmental_factor_id FROM carcinogen_exposure ce, environmental_factor ef" + " WHERE ce.environmental_factor_id = ef.environmental_factor_id AND (ef.name = ? OR ef.name_unctrl_vocab = ?) AND ef.type = ?)"; Object[] theParams = new Object[3]; theParams[0] = inName; theParams[1] = inName; theParams[2] = inType; return getIds(theSQLString, theParams); } /** * Get the model id's for any model has a keyword match in the env factor * * @param inKeyword * the name to look for * * @return a list of matching model id * * @throws PersistenceException */ private String getModelIdsForAnyEnvironmentalFactor(String inKeyword) throws PersistenceException { String theSQLString = "SELECT distinct ce.abs_cancer_model_id FROM carcinogen_exposure ce " + "WHERE ce.environmental_factor_id IN (SELECT ef.environmental_factor_id FROM carcinogen_exposure ce, environmental_factor ef" + " WHERE ce.environmental_factor_id = ef.environmental_factor_id AND upper(ef.name) like ?)"; Object[] theParams = new Object[1]; theParams[0] = inKeyword; return getIds(theSQLString, theParams); } public List searchForAnimalModels(SearchData inSearchData) throws Exception { log.info("Entering searchForAnimalModels"); List theAnimalModels = null; String theFromClause = "from AnimalModel as am where am.state = 'Edited-approved' AND am.availability.releaseDate < sysdate "; String theOrderByClause = " ORDER BY am.modelDescriptor asc"; if (inSearchData.getKeyword() != null && inSearchData.getKeyword().length() > 0) { log.info("Doing a keyword search: " + inSearchData.getKeyword()); theAnimalModels = keywordSearch(theFromClause, theOrderByClause, inSearchData.getKeyword()); } else { log.info("Doing a criteria search"); theAnimalModels = criteriaSearch(theFromClause, theOrderByClause, inSearchData); } log.info("Exiting searchForAnimalModels"); return theAnimalModels; } public int countMatchingAnimalModels(SearchData inSearchData) throws Exception { log.info("Entering countMatchingAnimalModels"); String theFromClause = "select count (am) from AnimalModel as am where am.state = 'Edited-approved' AND am.availability.releaseDate < sysdate "; List theCountResults = null; if (inSearchData.getKeyword() != null && inSearchData.getKeyword().trim().length() > 0) { log.info("Doing a keyword search: " + inSearchData.getKeyword()); String theWhereClause = buildKeywordSearchWhereClause(inSearchData.getKeyword()); try { String theHQLQuery = theFromClause + theWhereClause; log.info("HQL Query: " + theHQLQuery); String theKeyword = "%" + inSearchData.getKeyword().toUpperCase().trim() + "%"; Query theQuery = HibernateUtil.getSession().createQuery(theHQLQuery); theQuery.setParameter("keyword", theKeyword); theCountResults = theQuery.list(); } catch (Exception e) { log.error("Exception occurred searching for models", e); throw e; } } else { log.info("Doing a criteria search"); String theWhereClause = buildCriteriaSearchWhereClause(inSearchData); try { String theHQLQuery = theFromClause + theWhereClause; log.info("HQL Query: " + theHQLQuery); Query theQuery = HibernateUtil.getSession().createQuery(theHQLQuery); theCountResults = theQuery.list(); } catch (Exception e) { log.error("Exception occurred searching for models", e); throw e; } } int theCount = -1; if (theCountResults != null && theCountResults.size() > 0) { Integer theInt = (Integer) theCountResults.get(0); theCount = theInt.intValue(); } log.info("Exiting searchForAnimalModels"); return theCount; } // Build the where clause for the search and the count private String buildKeywordSearchWhereClause(String inKeyword) throws Exception { String theKeyword = "%" + inKeyword.toUpperCase().trim() + "%"; String theWhereClause = ""; theWhereClause += " AND (upper(am.modelDescriptor) like :keyword "; theWhereClause += " OR am.strain IN (" + getStrainIdsForSpecies(inKeyword) + ")"; theWhereClause += " OR abs_cancer_model_id IN (" + getModelIdsForHistopathologyOrgan(theKeyword, "") + ")"; theWhereClause += " OR abs_cancer_model_id IN (" + getModelIdsForHistopathologyDisease(theKeyword, "") + ")"; theWhereClause += " OR abs_cancer_model_id IN (" + getModelIdsForAnyEnvironmentalFactor(inKeyword) + ")"; theWhereClause += " OR abs_cancer_model_id IN (" + getModelIdsForAnyEngineeredGene(inKeyword) + ")"; theWhereClause += " OR am.phenotype IN (from Phenotype as p where upper(p.description) like :keyword )"; theWhereClause += " OR abs_cancer_model_id IN (" + getModelIdsForCellLine(inKeyword) + ")"; theWhereClause += " OR abs_cancer_model_id IN (" + getModelIdsForTherapeuticApproach(inKeyword) + "))"; theWhereClause += " OR abs_cancer_model_id IN (" + getModelIdsForTransientInterference(inKeyword) + "))"; return theWhereClause; } private List keywordSearch(String inFromClause, String inOrderByClause, String inKeyword) throws Exception { String theWhereClause = buildKeywordSearchWhereClause(inKeyword); List theAnimalModels = null; try { String theHQLQuery = inFromClause + theWhereClause + inOrderByClause; log.info("HQL Query: " + theHQLQuery); String theKeyword = "%" + inKeyword.toUpperCase() + "%"; Query theQuery = HibernateUtil.getSession().createQuery(theHQLQuery); theQuery.setParameter("keyword", theKeyword); theAnimalModels = theQuery.list(); } catch (Exception e) { log.error("Exception occurred searching for models", e); throw e; } return theAnimalModels; } private String buildCriteriaSearchWhereClause(SearchData inSearchData) throws Exception { String theWhereClause = ""; // PI criteria if (inSearchData.getPiName() != null && inSearchData.getPiName().length() > 0) { StringTokenizer theTokenizer = new StringTokenizer(inSearchData.getPiName()); String theLastName = theTokenizer.nextToken(",").trim(); String theFirstName = theTokenizer.nextToken().trim(); theWhereClause += " AND am.principalInvestigator IN (from Person as p where p.lastName like '%" + theLastName + "%' AND p.firstName like '%" + theFirstName + "%')"; } // Model descriptor criteria if (inSearchData.getModelDescriptor() != null && inSearchData.getModelDescriptor().trim().length() > 0) { theWhereClause += " AND upper(am.modelDescriptor) like '%" + inSearchData.getModelDescriptor().toUpperCase().trim() + "%'"; } // Species criteria if (inSearchData.getSpecies() != null && inSearchData.getSpecies().length() > 0) { theWhereClause += " AND am.strain IN (" + getStrainIdsForSpecies(inSearchData.getSpecies()) + ")"; } // Search for organ if (inSearchData.getOrganTissueCode() != null && inSearchData.getOrganTissueCode().length() > 0 || inSearchData.getOrgan()!= null && inSearchData.getOrgan().length() > 0) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForHistopathologyOrgan(inSearchData.getOrganTissueCode(),inSearchData.getOrgan() ) + ")"; } // Search for disease if (inSearchData.getDiagnosisCode() != null && inSearchData.getDiagnosisCode().trim().length() > 0 || inSearchData.getTumorClassification()!= null && inSearchData.getTumorClassification().length() > 0 ) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForHistopathologyDisease(inSearchData.getDiagnosisCode(),inSearchData.getTumorClassification() ) + ")"; } // Carcinogenic interventions if (inSearchData.isSearchCarcinogenicInterventions() == true) { log.info("Searching for Carcinogenic Interventions"); boolean searchForSpecificCI = false; // Search for chemical/drug if (inSearchData.getChemicalDrug() != null && inSearchData.getChemicalDrug().trim().length() > 0) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForEnvironmentalFactor("Chemical / Drug", inSearchData.getChemicalDrug().trim()) + ")"; searchForSpecificCI = true; } // Search for Surgery/Other if (inSearchData.getSurgery() != null && inSearchData.getSurgery().length() > 0) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForEnvironmentalFactor("Other", inSearchData.getSurgery()) + ")"; searchForSpecificCI = true; } // Search for Hormone if (inSearchData.getHormone() != null && inSearchData.getHormone().length() > 0) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForEnvironmentalFactor("Hormone", inSearchData.getHormone()) + ")"; searchForSpecificCI = true; } // Search for Growth Factor if (inSearchData.getGrowthFactor() != null && inSearchData.getGrowthFactor().length() > 0) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForEnvironmentalFactor("Growth Factor", inSearchData.getGrowthFactor()) + ")"; searchForSpecificCI = true; } // Search for Radiation if (inSearchData.getRadiation() != null && inSearchData.getRadiation().length() > 0) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForEnvironmentalFactor("Radiation", inSearchData.getRadiation()) + ")"; searchForSpecificCI = true; } // Search for Viral if (inSearchData.getViral() != null && inSearchData.getViral().length() > 0) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForEnvironmentalFactor("Viral", inSearchData.getViral()) + ")"; searchForSpecificCI = true; } // Search for any model w/ a CI if (searchForSpecificCI == false) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForAnyEnvironmentalFactor() + ")"; } } // Only call if some of the data is set : TODO: clean this up if ((inSearchData.getGeneName() != null && inSearchData.getGeneName().trim().length() > 0 && (inSearchData.isEngineeredTransgene() || inSearchData.isTargetedModification())) || (inSearchData.getGenomicSegDesignator() != null && inSearchData.getGenomicSegDesignator().trim().length() > 0) || (inSearchData.getInducedMutationAgent() != null && inSearchData.getInducedMutationAgent().trim().length() > 0)) { // Search for engineered genes theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForEngineeredGenes(inSearchData.getGeneName(), inSearchData.isEngineeredTransgene(), inSearchData.isTargetedModification(), inSearchData.getGenomicSegDesignator(), inSearchData.getInducedMutationAgent()) + ")"; } // Search for phenotype if (inSearchData.getPhenotype() != null && inSearchData.getPhenotype().trim().length() > 0) { theWhereClause += " AND am.phenotype IN (from Phenotype as p where upper(p.description) like '%" + inSearchData.getPhenotype().trim().toUpperCase() + "%')"; } // Search for cellline if (inSearchData.getCellLine() != null && inSearchData.getCellLine().trim().length() > 0) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForCellLine(inSearchData.getCellLine().trim()) + ")"; } // Search for therapeutic approaches if (inSearchData.isSearchTherapeuticApproaches()) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForTherapeuticApproach(inSearchData.getTherapeuticApproach().trim()) + ")"; } // Search for metastasis if (inSearchData.isSearchHistoMetastasis()) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForHistoMetastasis() + ")"; } // Search for microarray data if (inSearchData.isSearchMicroArrayData()) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForMicroArrayData() + ")"; } // Search for microarray data if (inSearchData.isSearchTransientInterference()) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForTransientInterference() + ")"; } // Search for xenograft if (inSearchData.isSearchXenograft()) { theWhereClause += " AND abs_cancer_model_id IN (" + getModelIdsForXenograft() + ")"; } return theWhereClause; } private List criteriaSearch(String inFromClause, String inOrderByClause, SearchData inSearchData) throws Exception { String theWhereClause = buildCriteriaSearchWhereClause(inSearchData); List theAnimalModels = null; try { String theHQLQuery = inFromClause + theWhereClause + inOrderByClause; log.info("HQL Query: " + theHQLQuery); Query theQuery = HibernateUtil.getSession().createQuery(theHQLQuery); theAnimalModels = theQuery.list(); } catch (Exception e) { log.error("Exception occurred searching for models", e); throw e; } return theAnimalModels; } /** * Extract the ID's for an sql query. * * @param inSQLString * the SQL string that returns a set of IDs * @param inParameters * the parameters to bind in the query * * @return a list of matching ids * * @throws PersistenceException */ private String getIds(String inSQLString, Object inParameters[]) throws PersistenceException { log.info("In getIds"); String theModelIds = ""; ResultSet theResultSet = null; try { log.info("getIds - SQL: " + inSQLString); theResultSet = Search.query(inSQLString, inParameters); if (theResultSet.next()) { theModelIds += theResultSet.getString(1); } while (theResultSet.next()) { theModelIds += "," + theResultSet.getString(1); } } catch (Exception e) { log.error("Exception in getIds", e); throw new PersistenceException("Exception in getIds: " + e); } finally { if (theResultSet != null) { try { theResultSet.close(); } catch (Exception e) {} } } if (theModelIds.equals("")) { theModelIds = "-1"; } return theModelIds; } // Sima TODO: optimize query - added extra join for species/strain //no nscNumber in environmental_factor to test if this is correct public List getModelsForThisCompound(Long nscNumber) throws PersistenceException { List<String[]> models = new ArrayList<String[]>(); int cc = 0; ResultSet theResultSet = null; try { String theSQLString = "select acm.abs_cancer_model_id, " + "\n" + " acm.model_descriptor," + "\n" + " sp.common_name," + "\n" + " sp.common_name_unctrl_vocab," + "\n" + " st.name," + "\n" + " st.name_unctrl_vocab" + "\n" + " from abs_cancer_model acm," + "\n" + " therapy t," + "\n" + " strain st," + "\n" + " species sp," + "\n" + " agent a" + "\n" + " where acm.abs_cancer_model_id = t.abs_cancer_model_id" + "\n" + " and acm.abs_cancer_model_type = 'AM'" + "\n" + " and t.agent_id = a.agent_id" + "\n" + " and acm.strain_id = st.strain_id" + "\n" + " and st.species_id = sp.species_id" + "\n" + " and a.nsc_number = ?"; log.info("\n getModelsForThisCompound - SQL: " + theSQLString); Object[] params = new Object[1]; params[0] = nscNumber; theResultSet = Search.query(theSQLString, params); String speciesName = ""; String stainName = ""; while (theResultSet.next()) { String[] item = new String[3]; item[0] = theResultSet.getString(1); // the id item[1] = theResultSet.getString(2); // model descriptor String theSpeciesName = theResultSet.getString(3); // species common name String theSpeciesUnctrlName = theResultSet.getString(4); String theStrainName = theResultSet.getString(5); // strain name String theStrainUnctrlName = theResultSet.getString(6); if (theSpeciesName != null && theSpeciesName.length() > 0 ) { speciesName = theResultSet.getString(3); // species common name } else if (theSpeciesUnctrlName != null && theSpeciesUnctrlName.length() > 0 ) { speciesName = theResultSet.getString(4); // species Unctrl common name } if (theStrainName != null && theStrainName.length() > 0 ) { stainName = theResultSet.getString(5); // strain name } else if (theStrainUnctrlName != null && theStrainUnctrlName.length() > 0 ) { stainName = theResultSet.getString(6); // strain Unctrl name } item[2] = speciesName + " " + stainName; // result of column models.add(item); cc++; } log.info("Got " + cc + " animal models"); } catch (Exception e) { log.error("Exception in getModelsForThisCompound", e); throw new PersistenceException("Exception in getModelsForThisCompound: " + e); } finally { if (theResultSet != null) { try { theResultSet.close(); } catch (Exception e) {} } } return models; } public List getAllPublications(long absCancerModelId) throws PersistenceException { List<Publication> publications = new ArrayList<Publication>(); int cc = 0; ResultSet theResultSet = null; try { String theSQLString = "select publication_id, year, authors" + "\n" + " from publication" + "\n" + " where publication_id in (" + "\n" + " select min(publication_id) publication_id" + "\n" + " from (" + "\n" + " select p.pmid, p.publication_id" + "\n" + " from therapy th," + "\n" + " therapy_publication tp," + "\n" + " publication p" + "\n" + " where th.abs_cancer_model_id = ?" + "\n" + " and th.therapy_id = tp.therapy_id" + "\n" + " and tp.publication_id = p.publication_id" + "\n" + " union" + "\n" + " select p.pmid, p.publication_id" + "\n" + " from cell_line cl," + "\n" + " cell_line_publication cp," + "\n" + " publication p" + "\n" + " where cl.abs_cancer_model_id = ?" + "\n" + " and cl.cell_line_id = cp.cell_line_id" + "\n" + " and cp.publication_id = p.publication_id" + "\n" + " union" + "\n" + " select p.pmid, p.publication_id" + "\n" + " from abs_can_mod_publication acmp," + "\n" + " publication p" + "\n" + " where acmp.abs_cancer_model_id = ?" + "\n" + " and acmp.publication_id = p.publication_id )" + "\n" + " group by pmid )" + "\n" + " order by year desc, authors" + "\n"; log.info("getAllPublications - SQL: " + theSQLString); Object[] params = new Object[3]; params[0] = params[1] = params[2] = String.valueOf(absCancerModelId); theResultSet = Search.query(theSQLString, params); while (theResultSet.next()) { String pid = theResultSet.getString(1); // the publication_id Publication p = (Publication) get(pid, Publication.class); publications.add(p); cc++; } log.info("Got " + cc + " publications"); } catch (Exception e) { log.error("Exception in getAllPublications", e); throw new PersistenceException("Exception in getAllPublications: " + e); } finally { if (theResultSet != null) { try { theResultSet.close(); } catch (Exception e) {} } } return publications; } public List getSavedQueriesByParty(String inUsername) throws PersistenceException { log.trace("Entering QueryManagerImpl.getModelsByUser"); String theHQLQuery = "from SavedQuery as sq where " + " sq.user in (from Person where username = :username) " + " and sq.isSaved = :savedValue " + " order by query_name"; log.debug("The HQL query: " + theHQLQuery); org.hibernate.Query theQuery = HibernateUtil.getSession().createQuery(theHQLQuery); theQuery.setParameter("username", inUsername); theQuery.setParameter("savedValue", "1"); List theSavedQueries = theQuery.list(); if (theSavedQueries == null) { theSavedQueries = new ArrayList(); } return theSavedQueries; } public List getQueriesByParty(String inUsername) throws PersistenceException { log.trace("Entering QueryManagerImpl.getModelsByUser"); String theHQLQuery = "from SavedQuery as sq where " + " sq.user in (from Person where username = :username) " + " and sq.isSaved = :savedValue " + " order by query_execute_timestamp DESC"; log.debug("The HQL query: " + theHQLQuery); org.hibernate.Query theQuery = HibernateUtil.getSession().createQuery(theHQLQuery); theQuery.setParameter("username", inUsername); theQuery.setParameter("savedValue", "0"); List theSavedQueries = theQuery.list(); if (theSavedQueries == null) { theSavedQueries = new ArrayList(); } return theSavedQueries; } public List getResultSettingsByUsername(String inUsername) throws PersistenceException { log.trace("Entering QueryManagerImpl.getResultSettingsByUsername"); String theHQLQuery = "from ResultSettings as sq where sq.user in (from Person where username = :username) "; org.hibernate.Query theQuery = HibernateUtil.getSession().createQuery(theHQLQuery); theQuery.setParameter("username", inUsername); List theResultSettings = theQuery.list(); return theResultSettings; } public static void main(String[] inArgs) { try { List theList = QueryManagerSingleton.instance().getMatchingTumorClassifications("a"); System.out.println("Number matched: " + theList.size()); System.out.println(theList.get(0)); } catch (Exception e) { e.printStackTrace(); } } }
package org.jtrfp.trcl.gui; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.filechooser.FileFilter; import org.jtrfp.jfdt.Parser; import org.jtrfp.jtrfp.FileLoadException; import org.jtrfp.jtrfp.pod.PodFile; import org.jtrfp.trcl.coll.CollectionActionDispatcher; import org.jtrfp.trcl.conf.TRConfigurationFactory.TRConfiguration; import org.jtrfp.trcl.core.Feature; import org.jtrfp.trcl.core.FeatureFactory; import org.jtrfp.trcl.core.Features; import org.jtrfp.trcl.core.GraphStabilizationListener; import org.jtrfp.trcl.core.PODRegistry; import org.jtrfp.trcl.core.TRConfigRootFactory.TRConfigRoot; import org.jtrfp.trcl.core.TRFactory.TR; import org.jtrfp.trcl.file.VOXFile; import org.jtrfp.trcl.snd.SoundSystem; import org.springframework.stereotype.Component; @Component public class ConfigWindowFactory implements FeatureFactory<TR>{ /* public static void main(String [] args){ new ConfigWindow().setVisible(true); }//end main() */ public class ConfigWindow extends JFrame implements GraphStabilizationListener, Feature<TR>{ //private TRConfiguration config; //private JComboBox audioBufferSizeCB; //private JSlider modStereoWidthSlider; private JList podList,missionList; private DefaultListModel podLM=new DefaultListModel(), missionLM=new DefaultListModel(); private boolean needRestart=false; private final JFileChooser fileChooser = new JFileChooser(); private final Collection<ConfigurationTab> tabs; //private final TRConfigRoot cMgr; private final JTabbedPane tabbedPane; private PODRegistry podRegistry; private PodCollectionListener podCollectionListener = new PodCollectionListener(); private TR tr; private TRConfigRoot trConfigRoot; private TRConfiguration trConfiguration; private JLabel lblConfigpath = new JLabel("[config path not set]"); public ConfigWindow(){ this(new ArrayList<ConfigurationTab>()); } public ConfigWindow(Collection<ConfigurationTab> tabs){ setTitle("Settings"); setSize(340,540); final TR tr = getTr(); //this.cMgr = Features.get(tr, TRConfigRoot.class); this.tabs = tabs; //config = Features.get(tr, TRConfiguration.class); tabbedPane = new JTabbedPane(JTabbedPane.TOP); getContentPane().add(tabbedPane, BorderLayout.CENTER); JPanel generalTab = new JPanel(); tabbedPane.addTab("General", new ImageIcon(ConfigWindow.class.getResource("/org/freedesktop/tango/22x22/mimetypes/application-x-executable.png")), generalTab, null); GridBagLayout gbl_generalTab = new GridBagLayout(); gbl_generalTab.columnWidths = new int[]{0, 0}; gbl_generalTab.rowHeights = new int[]{0, 188, 222, 0}; gbl_generalTab.columnWeights = new double[]{1.0, Double.MIN_VALUE}; gbl_generalTab.rowWeights = new double[]{0.0, 1.0, 0.0, Double.MIN_VALUE}; generalTab.setLayout(gbl_generalTab); JPanel settingsLoadSavePanel = new JPanel(); GridBagConstraints gbc_settingsLoadSavePanel = new GridBagConstraints(); gbc_settingsLoadSavePanel.insets = new Insets(0, 0, 5, 0); gbc_settingsLoadSavePanel.anchor = GridBagConstraints.WEST; gbc_settingsLoadSavePanel.gridx = 0; gbc_settingsLoadSavePanel.gridy = 0; generalTab.add(settingsLoadSavePanel, gbc_settingsLoadSavePanel); settingsLoadSavePanel.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Overall Settings", TitledBorder.LEADING, TitledBorder.TOP, null, null)); FlowLayout flowLayout_1 = (FlowLayout) settingsLoadSavePanel.getLayout(); flowLayout_1.setAlignment(FlowLayout.LEFT); JButton btnSave = new JButton("Export..."); btnSave.setToolTipText("Export these settings to an external file"); settingsLoadSavePanel.add(btnSave); btnSave.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { exportSettings(); }}); JButton btnLoad = new JButton("Import..."); btnLoad.setToolTipText("Import an external settings file"); settingsLoadSavePanel.add(btnLoad); btnLoad.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { importSettings(); }}); JButton btnConfigReset = new JButton("Reset"); btnConfigReset.setToolTipText("Reset all settings to defaults"); settingsLoadSavePanel.add(btnConfigReset); btnConfigReset.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { defaultSettings(); }}); JPanel registeredPODsPanel = new JPanel(); registeredPODsPanel.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Registered PODs", TitledBorder.LEFT, TitledBorder.TOP, null, null)); GridBagConstraints gbc_registeredPODsPanel = new GridBagConstraints(); gbc_registeredPODsPanel.insets = new Insets(0, 0, 5, 0); gbc_registeredPODsPanel.fill = GridBagConstraints.BOTH; gbc_registeredPODsPanel.gridx = 0; gbc_registeredPODsPanel.gridy = 1; generalTab.add(registeredPODsPanel, gbc_registeredPODsPanel); GridBagLayout gbl_registeredPODsPanel = new GridBagLayout(); gbl_registeredPODsPanel.columnWidths = new int[]{272, 0}; gbl_registeredPODsPanel.rowHeights = new int[]{76, 0, 0}; gbl_registeredPODsPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE}; gbl_registeredPODsPanel.rowWeights = new double[]{1.0, 1.0, Double.MIN_VALUE}; registeredPODsPanel.setLayout(gbl_registeredPODsPanel); JPanel podListPanel = new JPanel(); GridBagConstraints gbc_podListPanel = new GridBagConstraints(); gbc_podListPanel.insets = new Insets(0, 0, 5, 0); gbc_podListPanel.fill = GridBagConstraints.BOTH; gbc_podListPanel.gridx = 0; gbc_podListPanel.gridy = 0; registeredPODsPanel.add(podListPanel, gbc_podListPanel); podListPanel.setLayout(new BorderLayout(0, 0)); JScrollPane podListScrollPane = new JScrollPane(); podListPanel.add(podListScrollPane, BorderLayout.CENTER); podList = new JList(podLM); podList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); podListScrollPane.setViewportView(podList); JPanel podListOpButtonPanel = new JPanel(); podListOpButtonPanel.setBorder(null); GridBagConstraints gbc_podListOpButtonPanel = new GridBagConstraints(); gbc_podListOpButtonPanel.anchor = GridBagConstraints.NORTH; gbc_podListOpButtonPanel.gridx = 0; gbc_podListOpButtonPanel.gridy = 1; registeredPODsPanel.add(podListOpButtonPanel, gbc_podListOpButtonPanel); FlowLayout flowLayout = (FlowLayout) podListOpButtonPanel.getLayout(); flowLayout.setAlignment(FlowLayout.LEFT); JButton addPodButton = new JButton("Add..."); addPodButton.setIcon(new ImageIcon(ConfigWindow.class.getResource("/org/freedesktop/tango/16x16/actions/list-add.png"))); addPodButton.setToolTipText("Add a POD to the registry to be considered when running a game."); podListOpButtonPanel.add(addPodButton); addPodButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { notifyNeedRestart(); addPOD(); }}); JButton removePodButton = new JButton("Remove"); removePodButton.setIcon(new ImageIcon(ConfigWindow.class.getResource("/org/freedesktop/tango/16x16/actions/list-remove.png"))); removePodButton.setToolTipText("Remove a POD file from being considered when playing a game"); podListOpButtonPanel.add(removePodButton); removePodButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { //podLM.removeElement(podList.getSelectedValue()); notifyNeedRestart(); getPodRegistry().getPodCollection().remove(podList.getSelectedValue()); }}); JButton podEditButton = new JButton("Edit..."); podEditButton.setIcon(null); podEditButton.setToolTipText("Edit the selected POD path"); podListOpButtonPanel.add(podEditButton); podEditButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { notifyNeedRestart(); editPODPath(); }}); JPanel missionPanel = new JPanel(); GridBagConstraints gbc_missionPanel = new GridBagConstraints(); gbc_missionPanel.fill = GridBagConstraints.BOTH; gbc_missionPanel.gridx = 0; gbc_missionPanel.gridy = 2; generalTab.add(missionPanel, gbc_missionPanel); missionPanel.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Missions", TitledBorder.LEADING, TitledBorder.TOP, null, null)); GridBagLayout gbl_missionPanel = new GridBagLayout(); gbl_missionPanel.columnWidths = new int[]{0, 0}; gbl_missionPanel.rowHeights = new int[]{0, 0, 0}; gbl_missionPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE}; gbl_missionPanel.rowWeights = new double[]{1.0, 0.0, Double.MIN_VALUE}; missionPanel.setLayout(gbl_missionPanel); JScrollPane scrollPane = new JScrollPane(); GridBagConstraints gbc_scrollPane = new GridBagConstraints(); gbc_scrollPane.insets = new Insets(0, 0, 5, 0); gbc_scrollPane.fill = GridBagConstraints.BOTH; gbc_scrollPane.gridx = 0; gbc_scrollPane.gridy = 0; missionPanel.add(scrollPane, gbc_scrollPane); missionList = new JList(missionLM); missionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); scrollPane.setViewportView(missionList); JPanel missionListOpButtonPanel = new JPanel(); GridBagConstraints gbc_missionListOpButtonPanel = new GridBagConstraints(); gbc_missionListOpButtonPanel.anchor = GridBagConstraints.NORTH; gbc_missionListOpButtonPanel.gridx = 0; gbc_missionListOpButtonPanel.gridy = 1; missionPanel.add(missionListOpButtonPanel, gbc_missionListOpButtonPanel); JButton addVOXButton = new JButton("Add..."); addVOXButton.setIcon(new ImageIcon(ConfigWindow.class.getResource("/org/freedesktop/tango/16x16/actions/list-add.png"))); addVOXButton.setToolTipText("Add an external VOX file as a mission"); missionListOpButtonPanel.add(addVOXButton); addVOXButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { addVOX(); }}); final JButton removeVOXButton = new JButton("Remove"); removeVOXButton.setIcon(new ImageIcon(ConfigWindow.class.getResource("/org/freedesktop/tango/16x16/actions/list-remove.png"))); removeVOXButton.setToolTipText("Remove the selected mission"); missionListOpButtonPanel.add(removeVOXButton); removeVOXButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { //TODO: missionLM.remove(missionList.getSelectedIndex()); }}); final JButton editVOXButton = new JButton("Edit..."); editVOXButton.setToolTipText("Edit the selected Mission's VOX path"); missionListOpButtonPanel.add(editVOXButton); editVOXButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { editVOXPath(); }}); missionList.addListSelectionListener(new ListSelectionListener(){ @Override public void valueChanged(ListSelectionEvent evt) { final String val = (String)missionList.getSelectedValue(); if(val == null) missionList.setSelectedIndex(0); else if(isBuiltinVOX(val)){ removeVOXButton.setEnabled(false); editVOXButton.setEnabled(false); }else{ removeVOXButton.setEnabled(true); editVOXButton.setEnabled(true); } }}); JPanel okCancelPanel = new JPanel(); getContentPane().add(okCancelPanel, BorderLayout.SOUTH); okCancelPanel.setLayout(new BorderLayout(0, 0)); JButton btnOk = new JButton("OK"); btnOk.setToolTipText("Apply these settings and close the window"); okCancelPanel.add(btnOk, BorderLayout.WEST); btnOk.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { //Keep settings, save to disk try {getTrConfigRoot().saveConfigurations();} catch(Exception e){e.printStackTrace();} applySettingsEDT(); ConfigWindow.this.setVisible(false); } }); JButton btnCancel = new JButton("Cancel"); btnCancel.setToolTipText("Close the window without applying settings"); okCancelPanel.add(btnCancel, BorderLayout.EAST); //final TRConfigRoot cfgRoot = getTrConfigRoot(); //final String cFilePath = cfgRoot.getConfigSaveURI(); //JLabel lblConfigpath = new JLabel(cFilePath); lblConfigpath.setIcon(null); lblConfigpath.setToolTipText("Default config file path"); lblConfigpath.setHorizontalAlignment(SwingConstants.CENTER); lblConfigpath.setFont(new Font("Dialog", Font.BOLD, 6)); okCancelPanel.add(lblConfigpath, BorderLayout.CENTER); btnCancel.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { //dispatchComponentConfigs(); //Revert to original getTrConfigRoot().loadConfigurations(); ConfigWindow.this.setVisible(false); }}); }//end constructor @Override public void setVisible(boolean isVisible){ if(isVisible) try {getTrConfigRoot().saveConfigurations();} catch(Exception e){e.printStackTrace();} super.setVisible(isVisible); }//end setVisible(...) private void applySettingsEDT(){ final TRConfigRoot configRoot = getTrConfigRoot(); final TRConfiguration config = getTrConfiguration(); config.setVoxFile((String)missionList.getSelectedValue()); //config.setModStereoWidth((double)modStereoWidthSlider.getValue()/100.); //config.setAudioLinearFiltering(chckbxLinearInterpolation.isSelected()); //config.setAudioBufferLag(chckbxBufferLag.isSelected()); {HashSet<String>pList=new HashSet<String>(); //for(int i=0; i<podLM.getSize();i++) // pList.add((String)podLM.getElementAt(i)); //podLM.clear();//Clear so we don't get a double-copy when the dispatcher populates it. //final Collection<String> podCollection = getPodRegistry().getPodCollection(); //podCollection.clear(); //for(String pod:pList) //podCollection.add(pod); HashSet<String>vxList=new HashSet<String>(); for(int i=0; i<missionLM.getSize();i++) vxList.add((String)missionLM.getElementAt(i)); config.setMissionList(vxList);} //soundOutputSelectorGUI.applySettings(config); try{configRoot.saveConfigurations();} catch(Exception e){e.printStackTrace();} //writeSettingsTo(cMgr.getConfigFilePath()); if(needRestart) notifyOfRestart(); //final AudioBufferSize abs = (AudioBufferSize)audioBufferSizeCB.getSelectedItem(); //config.setAudioBufferSize(abs.getSizeInFrames()); //Apply the component configs //gatherComponentConfigs(); }//end applySettings() /* private void gatherComponentConfigs(){ Map<String,Object> configs = config.getComponentConfigs(); for(ConfigurationTab tab:tabs){ System.out.println("Putting tab "+tab.getTabName()+" With entries:"); System.out.print("\t"); ControllerConfigTabConf conf = (ControllerConfigTabConf)tab.getConfigBean(); for(Entry ent: conf.getControllerConfigurations().entrySet()){ System.out.print(" "+ent.getKey()); } System.out.println(); configs.put(tab.getConfigBeanClass().getName(), tab.getConfigBean());} }//end gatherComponentConfigs() */ /* private void dispatchComponentConfigs(){ Map<String,Object> configs = config.getComponentConfigs(); for(ConfigurationTab tab:tabs) tab.setConfigBean(configs.get(tab.getConfigBeanClass().getName())); }//end dispatchComponentConfigs() */ private void readSettingsToPanel(){ final TRConfiguration config = getTrConfiguration(); //Initial settings - These do not listen to the config states! final SoundSystem soundSystem = Features.get(getTr(), SoundSystem.class); //modStereoWidthSlider.setValue((int)(config.getModStereoWidth()*100.)); //chckbxLinearInterpolation.setSelected(soundSystem.isLinearFiltering()); //chckbxBufferLag.setSelected(soundSystem.isBufferLag()); /*final int bSize = config.getAudioBufferSize(); for(AudioBufferSize abs:AudioBufferSize.values()) if(abs.getSizeInFrames()==bSize) audioBufferSizeCB.setSelectedItem(abs); */ missionLM.removeAllElements(); for(String vox:config.getMissionList()){ if(isBuiltinVOX(vox)) missionLM.addElement(vox); else if(checkVOX(new File(vox))) missionLM.addElement(vox); }//end for(vox) String missionSelection = config.getVoxFile(); for(int i=0; i<missionLM.getSize(); i++){ if(((String)missionLM.get(i)).contentEquals(missionSelection))missionList.setSelectedIndex(i);} /* podLM.removeAllElements(); final Collection<String> podRegistryCollection = getPodRegistry().getPodCollection(); //final DefaultListModel podList = config.getPodList(); for(String path : podRegistryCollection){ if(path!=null) if(checkPOD(new File(path))) podLM.addElement(path);} */ //soundOutputSelectorGUI.readToPanel(config); //Undo any flags set by the listeners. needRestart=false; }//end readSettings() private boolean isBuiltinVOX(String vox){ return vox.contentEquals(TRConfiguration.AUTO_DETECT) || vox.contentEquals("Fury3") || vox.contentEquals("TV") || vox.contentEquals("FurySE"); }//end isBuiltinVOX private void notifyOfRestart(){ JOptionPane.showMessageDialog(this, "Some changes won't take effect until the program is restarted."); needRestart=false; } private void addPOD(){ fileChooser.setFileFilter(new FileFilter(){ @Override public boolean accept(File file) { return file.getName().toUpperCase().endsWith(".POD")||file.isDirectory(); } @Override public String getDescription() { return "Terminal Reality .POD files"; }}); if(fileChooser.showOpenDialog(this)!=JFileChooser.APPROVE_OPTION) return; final File file = fileChooser.getSelectedFile(); if(!checkPOD(file)) return; //podLM.addElement(file.getAbsolutePath()); getPodRegistry().getPodCollection().add(file.getAbsolutePath()); }//end addPOD() private void addVOX() { fileChooser.setFileFilter(new FileFilter() { @Override public boolean accept(File file) { return file.getName().toUpperCase().endsWith(".VOX")||file.isDirectory(); } @Override public String getDescription() { return "Terminal Reality .VOX files"; } }); if (fileChooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; final File file = fileChooser.getSelectedFile(); if(file!=null) missionLM.addElement(file.getAbsolutePath()); }//end addVOX() private boolean writeSettingsToNormalConf(){ try{ //cMgr.saveConfigurations(f); final TRConfigRoot configRoot = getTrConfigRoot(); //configRoot.setConfigSaveURI(f.getPath()); configRoot.saveConfigurations(); return true; }catch(Exception e){JOptionPane.showMessageDialog( this, "Failed to write the config file.\n" + e.getLocalizedMessage()+"\n"+e.getClass().getName(), "File write failure", JOptionPane.ERROR_MESSAGE); return false;} }//end writeSettings() private boolean writeSettingsTo(File f){ try{/* //cMgr.saveConfigurations(f); final TRConfigRoot configRoot = getTrConfigRoot(); configRoot.setConfigSaveURI(f.getPath()); configRoot.saveConfigurations(); */ getTrConfigRoot().saveConfigurations(f); return true; }catch(Exception e){JOptionPane.showMessageDialog( this, "Failed to write the config file.\n" + e.getLocalizedMessage()+"\n"+e.getClass().getName(), "File write failure", JOptionPane.ERROR_MESSAGE); return false;} }//end writeSettingsTo(...) private void exportSettings(){ fileChooser.setFileFilter(new FileFilter(){ @Override public boolean accept(File file) { return file.getName().toLowerCase().endsWith(".config.trcl.xml")||file.isDirectory(); } @Override public String getDescription() { return "Terminal Recall Config Files"; }}); fileChooser.showSaveDialog(this); File f = fileChooser.getSelectedFile(); if(f==null)return; writeSettingsTo(f); }//end exportSettings() private void editVOXPath(){ JOptionPane.showMessageDialog(this, "Not yet implemented."); //TODO /* final String result = JOptionPane.showInputDialog(this, "Edit VOX Path", missionLM.get(missionList.getSelectedIndex())); if(result==null)// Clicked Cancel return;// Do nothing if(checkVOX(new File(result))) missionLM.set(missionList.getSelectedIndex(), result); */ }//end editVOXPath() private void editPODPath(){ JOptionPane.showMessageDialog(this, "Not yet implemented."); //TODO /* final String result = JOptionPane.showInputDialog(this, "Edit POD Path", podLM.get(missionList.getSelectedIndex())); if(result==null)// Clicked Cancel return;// Do nothing if(checkPOD(new File(result))) podLM.set(podList.getSelectedIndex(), result); */ }//end editPODPath() private boolean readSettingsFromFile(File f){ try{/* FileInputStream is = new FileInputStream(f); XMLDecoder xmlDec = new XMLDecoder(is); xmlDec.setExceptionListener(new ExceptionListener(){ @Override public void exceptionThrown(Exception e) { e.printStackTrace(); }}); TRConfiguration src =(TRConfiguration)xmlDec.readObject(); xmlDec.close(); TRConfiguration config = getTrConfiguration(); */ this.getTrConfigRoot().loadConfigurations(f,0); /*if(config!=null) BeanUtils.copyProperties(config, src); else setTrConfiguration(config = src);*/ }catch(Exception e){JOptionPane.showMessageDialog( this, "Failed to read the specified file:\n" + e.getLocalizedMessage(), "File read failure", JOptionPane.ERROR_MESSAGE);return false;} return true; }//end readSettingsFromFile(...) private void importSettings(){ fileChooser.setFileFilter(new FileFilter(){ @Override public boolean accept(File file) { return file.getName().toLowerCase().endsWith(".config.trcl.xml")||file.isDirectory(); } @Override public String getDescription() { return "Terminal Recall Config Files"; }}); fileChooser.showOpenDialog(this); File f = fileChooser.getSelectedFile(); if(f==null)return; readSettingsFromFile(f); readSettingsToPanel(); }//end exportSettings() private void defaultSettings(){ JOptionPane.showMessageDialog(this, "Not yet implemented."); //TODO /* try{BeanUtils.copyProperties(config, new TRConfiguration());} catch(Exception e){e.printStackTrace();} readSettingsToPanel(); */ } private boolean checkFile(File f){ if(f.exists()) return true; JOptionPane.showMessageDialog(this, "The specified path could not be opened from disk:\n"+f.getAbsolutePath(), "File Not Found", JOptionPane.ERROR_MESSAGE); return false; }//end checkFile private boolean checkPOD(File file){ if(!checkFile(file)) return false; try{new PodFile(file).getData();} catch(FileLoadException e){ JOptionPane.showMessageDialog(this, "Failed to parse the specified POD: \n"+e.getLocalizedMessage(), "POD failed format check.", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); return false;} return true; }//end checkPOD(...) private boolean checkVOX(File file){ if (!checkFile(file)) return false; try { FileInputStream fis = new FileInputStream(file); new Parser().readToNewBean(fis, VOXFile.class); fis.close(); } catch (Exception e) { JOptionPane.showMessageDialog( this, "Failed to parse the specified VOX: \n" + e.getLocalizedMessage(), "VOX failed format check", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); return false; } return true; }//end checkVOX(...) @Override public void apply(TR target) { setPodRegistry(Features.get(target, PODRegistry.class)); final TR tr; setTr (tr = Features.get(Features.getSingleton(), TR.class)); setTrConfigRoot (Features.get(Features.getSingleton(), TRConfigRoot.class )); setTrConfiguration(Features.get(tr, TRConfiguration.class)); final CollectionActionDispatcher<String> podRegistryCollection = getPodRegistry().getPodCollection(); podRegistryCollection.addTarget(podCollectionListener, true); } @Override public void destruct(TR target) { // TODO Auto-generated method stub } public void registerConfigTab(final ConfigurationTab configTab) { final String name = configTab.getTabName(); final ImageIcon icon = configTab.getTabIcon(); final JComponent content = configTab.getContent(); try{ SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { tabbedPane.addTab(name,icon,content); }}); }catch(Exception e){e.printStackTrace();} //dispatchComponentConfigs(); }//end registerConfigTab(...) public PODRegistry getPodRegistry() { return podRegistry; } public void setPodRegistry(PODRegistry podRegistry) { this.podRegistry = podRegistry; } private class PodCollectionListener implements List<String> { @Override public boolean add(final String element) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { podLM.addElement(element); }}); return true;//Meh. } @Override public void add(final int index, final String element) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { podLM.add(index, element); }}); } @Override public boolean addAll(final Collection<? extends String> arg0) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { for(String s : arg0 ) podLM.addElement(s); }}); return true;//Meh. } @Override public boolean addAll(int arg0, Collection<? extends String> arg1) { throw new UnsupportedOperationException(); } @Override public void clear() { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { podLM.clear(); }}); } @Override public boolean contains(Object arg0) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> arg0) { throw new UnsupportedOperationException(); } @Override public String get(int arg0) { throw new UnsupportedOperationException(); } @Override public int indexOf(Object arg0) { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } @Override public Iterator<String> iterator() { throw new UnsupportedOperationException(); } @Override public int lastIndexOf(Object arg0) { throw new UnsupportedOperationException(); } @Override public ListIterator<String> listIterator() { throw new UnsupportedOperationException(); } @Override public ListIterator<String> listIterator(int arg0) { throw new UnsupportedOperationException(); } @Override public boolean remove(final Object elementToRemove) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { podLM.removeElement(elementToRemove); }}); return true; //Meh. } @Override public String remove(final int indexOfElementToRemove) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { podLM.remove(indexOfElementToRemove); }}); return null;//Meh. } @Override public boolean removeAll(final Collection<?> elementsToRemove) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { boolean result = false; for(Object o : elementsToRemove) result |= podLM.removeElement(o); }}); return true;//Meh. } @Override public boolean retainAll(Collection<?> arg0) { throw new UnsupportedOperationException(); } @Override public String set(final int index, final String element) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { podLM.set(index, element); }}); return null;//Meh. } @Override public int size() { return podLM.size(); } @Override public List<String> subList(int arg0, int arg1) { throw new UnsupportedOperationException(); } @Override public Object[] toArray() { throw new UnsupportedOperationException(); } @Override public <T> T[] toArray(T[] arg0) { throw new UnsupportedOperationException(); } }//end PodCollectionListener public TR getTr() { return tr; } public void setTr(TR tr) { this.tr = tr; } public TRConfigRoot getTrConfigRoot() { return trConfigRoot; } public void setTrConfigRoot(TRConfigRoot trConfigRoot) { this.trConfigRoot = trConfigRoot; final String cFilePath = trConfigRoot.getConfigSaveURI(); SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { lblConfigpath.setText(cFilePath); }}); }//end setTrConfigRoot(...) public TRConfiguration getTrConfiguration() { return trConfiguration; } public void setTrConfiguration(TRConfiguration trConfiguration) { this.trConfiguration = trConfiguration; } public void notifyNeedRestart(){ needRestart = true; } @Override public void graphStabilized(Object target) { if(getTrConfiguration() != null) readSettingsToPanel(); } }//end ConfigWindow @Override public Feature<TR> newInstance(TR target) { final ConfigWindow result = new ConfigWindow(); return result; } @Override public Class<TR> getTargetClass() { return TR.class; } @Override public Class<? extends Feature> getFeatureClass() { return ConfigWindow.class; } }//end ConfigWindowFactory
package nu.validator.checker.schematronequiv; import java.util.concurrent.ConcurrentHashMap; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.Arrays; import nu.validator.checker.AttributeUtil; import nu.validator.checker.Checker; import nu.validator.checker.LocatorImpl; import nu.validator.checker.TaintableLocatorImpl; import nu.validator.checker.VnuBadAttrValueException; import nu.validator.datatype.Html5DatatypeException; import nu.validator.datatype.ImageCandidateStringsWidthRequired; import nu.validator.datatype.ImageCandidateStrings; import nu.validator.datatype.ImageCandidateURL; import org.relaxng.datatype.DatatypeException; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; public class Assertions extends Checker { private static boolean followW3Cspec = "1".equals(System.getProperty("nu.validator.servlet.follow-w3c-spec")) ? true : false; private static boolean lowerCaseLiteralEqualsIgnoreAsciiCaseString( String lowerCaseLiteral, String string) { if (string == null) { return false; } if (lowerCaseLiteral.length() != string.length()) { return false; } for (int i = 0; i < lowerCaseLiteral.length(); i++) { char c0 = lowerCaseLiteral.charAt(i); char c1 = string.charAt(i); if (c1 >= 'A' && c1 <= 'Z') { c1 += 0x20; } if (c0 != c1) { return false; } } return true; } private static boolean equalsIgnoreAsciiCase(String one, String other) { if (other == null) { if (one == null) { return true; } else { return false; } } if (one.length() != other.length()) { return false; } for (int i = 0; i < one.length(); i++) { char c0 = one.charAt(i); char c1 = other.charAt(i); if (c0 >= 'A' && c0 <= 'Z') { c0 += 0x20; } if (c1 >= 'A' && c1 <= 'Z') { c1 += 0x20; } if (c0 != c1) { return false; } } return true; } private static final String trimSpaces(String str) { return trimLeadingSpaces(trimTrailingSpaces(str)); } private static final String trimLeadingSpaces(String str) { if (str == null) { return null; } for (int i = str.length(); i > 0; --i) { char c = str.charAt(str.length() - i); if (!(' ' == c || '\t' == c || '\n' == c || '\f' == c || '\r' == c)) { return str.substring(str.length() - i, str.length()); } } return ""; } private static final String trimTrailingSpaces(String str) { if (str == null) { return null; } for (int i = str.length() - 1; i >= 0; --i) { char c = str.charAt(i); if (!(' ' == c || '\t' == c || '\n' == c || '\f' == c || '\r' == c)) { return str.substring(0, i + 1); } } return ""; } private static final Map<String, String> OBSOLETE_ELEMENTS = new HashMap<String, String>(); static { OBSOLETE_ELEMENTS.put("center", "Use CSS instead."); OBSOLETE_ELEMENTS.put("font", "Use CSS instead."); OBSOLETE_ELEMENTS.put("big", "Use CSS instead."); OBSOLETE_ELEMENTS.put("strike", "Use CSS instead."); OBSOLETE_ELEMENTS.put("tt", "Use CSS instead."); OBSOLETE_ELEMENTS.put("acronym", "Use the \u201Cabbr\u201D element instead."); OBSOLETE_ELEMENTS.put("dir", "Use the \u201Cul\u201D element instead."); OBSOLETE_ELEMENTS.put("applet", "Use the \u201Cobject\u201D element instead."); OBSOLETE_ELEMENTS.put("basefont", "Use CSS instead."); OBSOLETE_ELEMENTS.put( "frameset", "Use the \u201Ciframe\u201D element and CSS instead, or use server-side includes."); OBSOLETE_ELEMENTS.put( "noframes", "Use the \u201Ciframe\u201D element and CSS instead, or use server-side includes."); if (followW3Cspec) { OBSOLETE_ELEMENTS.put( "hgroup", "To mark up subheadings, consider either just putting the " + "subheading into a \u201Cp\u201D element after the " + "\u201Ch1\u201D-\u201Ch6\u201D element containing the " + "main heading, or else putting the subheading directly " + "within the \u201Ch1\u201D-\u201Ch6\u201D element " + "containing the main heading, but separated from the main " + "heading by punctuation and/or within, for example, a " + "\u201Cspan class=\"subheading\"\u201D element with " + "differentiated styling. " + "To group headings and subheadings, alternative titles, " + "or taglines, consider using the \u201Cheader\u201D or " + "\u201Cdiv\u201D elements."); } } private static final Map<String, String[]> OBSOLETE_ATTRIBUTES = new HashMap<String, String[]>(); static { OBSOLETE_ATTRIBUTES.put("abbr", new String[] { "td", "th" }); OBSOLETE_ATTRIBUTES.put("archive", new String[] { "object" }); OBSOLETE_ATTRIBUTES.put("axis", new String[] { "td", "th" }); OBSOLETE_ATTRIBUTES.put("charset", new String[] { "link", "a" }); OBSOLETE_ATTRIBUTES.put("classid", new String[] { "object" }); OBSOLETE_ATTRIBUTES.put("code", new String[] { "object" }); OBSOLETE_ATTRIBUTES.put("codebase", new String[] { "object" }); OBSOLETE_ATTRIBUTES.put("codetype", new String[] { "object" }); OBSOLETE_ATTRIBUTES.put("coords", new String[] { "a" }); OBSOLETE_ATTRIBUTES.put("datafld", new String[] { "span", "div", "object", "input", "select", "textarea", "button", "table" }); OBSOLETE_ATTRIBUTES.put("dataformatas", new String[] { "span", "div", "object", "input", "select", "textarea", "button", "table" }); OBSOLETE_ATTRIBUTES.put("datasrc", new String[] { "span", "div", "object", "input", "select", "textarea", "button", "table" }); OBSOLETE_ATTRIBUTES.put("datapagesize", new String[] { "table" }); OBSOLETE_ATTRIBUTES.put("declare", new String[] { "object" }); OBSOLETE_ATTRIBUTES.put("event", new String[] { "script" }); OBSOLETE_ATTRIBUTES.put("for", new String[] { "script" }); OBSOLETE_ATTRIBUTES.put("language", new String[] { "script" }); if (!followW3Cspec) { OBSOLETE_ATTRIBUTES.put("longdesc", new String[] { "img", "iframe" }); } OBSOLETE_ATTRIBUTES.put("methods", new String[] { "link", "a" }); OBSOLETE_ATTRIBUTES.put("name", new String[] { "img", "embed", "option" }); OBSOLETE_ATTRIBUTES.put("nohref", new String[] { "area" }); OBSOLETE_ATTRIBUTES.put("profile", new String[] { "head" }); OBSOLETE_ATTRIBUTES.put("scheme", new String[] { "meta" }); OBSOLETE_ATTRIBUTES.put("scope", new String[] { "td" }); OBSOLETE_ATTRIBUTES.put("shape", new String[] { "a" }); OBSOLETE_ATTRIBUTES.put("standby", new String[] { "object" }); OBSOLETE_ATTRIBUTES.put("target", new String[] { "link" }); OBSOLETE_ATTRIBUTES.put("type", new String[] { "param" }); OBSOLETE_ATTRIBUTES.put("urn", new String[] { "a", "link" }); OBSOLETE_ATTRIBUTES.put("usemap", new String[] { "input" }); OBSOLETE_ATTRIBUTES.put("valuetype", new String[] { "param" }); OBSOLETE_ATTRIBUTES.put("version", new String[] { "html" }); } private static final Map<String, String> OBSOLETE_ATTRIBUTES_MSG = new HashMap<String, String>(); static { OBSOLETE_ATTRIBUTES_MSG.put( "abbr", "Consider instead beginning the cell contents with concise text, followed by further elaboration if needed."); OBSOLETE_ATTRIBUTES_MSG.put( "archive", "Use the \u201Cdata\u201D and \u201Ctype\u201D attributes to invoke plugins. To set a parameter with the name \u201Carchive\u201D, use the \u201Cparam\u201D element."); OBSOLETE_ATTRIBUTES_MSG.put("axis", "Use the \u201Cscope\u201D attribute."); OBSOLETE_ATTRIBUTES_MSG.put("charset", "Use an HTTP Content-Type header on the linked resource instead."); OBSOLETE_ATTRIBUTES_MSG.put( "classid", "Use the \u201Cdata\u201D and \u201Ctype\u201D attributes to invoke plugins. To set a parameter with the name \u201Cclassid\u201D, use the \u201Cparam\u201D element."); OBSOLETE_ATTRIBUTES_MSG.put( "code", "Use the \u201Cdata\u201D and \u201Ctype\u201D attributes to invoke plugins. To set a parameter with the name \u201Ccode\u201D, use the \u201Cparam\u201D element."); OBSOLETE_ATTRIBUTES_MSG.put( "codebase", "Use the \u201Cdata\u201D and \u201Ctype\u201D attributes to invoke plugins. To set a parameter with the name \u201Ccodebase\u201D, use the \u201Cparam\u201D element."); OBSOLETE_ATTRIBUTES_MSG.put( "codetype", "Use the \u201Cdata\u201D and \u201Ctype\u201D attributes to invoke plugins. To set a parameter with the name \u201Ccodetype\u201D, use the \u201Cparam\u201D element."); OBSOLETE_ATTRIBUTES_MSG.put("coords", "Use \u201Carea\u201D instead of \u201Ca\u201D for image maps."); OBSOLETE_ATTRIBUTES_MSG.put("datapagesize", "You can safely omit it."); OBSOLETE_ATTRIBUTES_MSG.put("datafld", "Use script and a mechanism such as XMLHttpRequest to populate the page dynamically"); OBSOLETE_ATTRIBUTES_MSG.put("dataformatas", "Use script and a mechanism such as XMLHttpRequest to populate the page dynamically"); OBSOLETE_ATTRIBUTES_MSG.put("datasrc", "Use script and a mechanism such as XMLHttpRequest to populate the page dynamically"); OBSOLETE_ATTRIBUTES_MSG.put("for", "Use DOM Events mechanisms to register event listeners."); OBSOLETE_ATTRIBUTES_MSG.put("event", "Use DOM Events mechanisms to register event listeners."); OBSOLETE_ATTRIBUTES_MSG.put( "declare", "Repeat the \u201Cobject\u201D element completely each time the resource is to be reused."); OBSOLETE_ATTRIBUTES_MSG.put("language", "Use the \u201Ctype\u201D attribute instead."); if (!followW3Cspec) { OBSOLETE_ATTRIBUTES_MSG.put("longdesc", "Use a regular \u201Ca\u201D element to link to the description."); } OBSOLETE_ATTRIBUTES_MSG.put("methods", "Use the HTTP OPTIONS feature instead."); OBSOLETE_ATTRIBUTES_MSG.put("name", "Use the \u201Cid\u201D attribute instead."); OBSOLETE_ATTRIBUTES_MSG.put("nohref", "Omitting the \u201Chref\u201D attribute is sufficient."); OBSOLETE_ATTRIBUTES_MSG.put( "profile", "To declare which \u201Cmeta\u201D terms are used in the document, instead register the names as meta extensions. To trigger specific UA behaviors, use a \u201Clink\u201D element instead."); OBSOLETE_ATTRIBUTES_MSG.put( "scheme", "Use only one scheme per field, or make the scheme declaration part of the value."); OBSOLETE_ATTRIBUTES_MSG.put("scope", "Use the \u201Cscope\u201D attribute on a \u201Cth\u201D element instead."); OBSOLETE_ATTRIBUTES_MSG.put("shape", "Use \u201Carea\u201D instead of \u201Ca\u201D for image maps."); OBSOLETE_ATTRIBUTES_MSG.put( "standby", "Optimise the linked resource so that it loads quickly or, at least, incrementally."); OBSOLETE_ATTRIBUTES_MSG.put("target", "You can safely omit it."); OBSOLETE_ATTRIBUTES_MSG.put( "type", "Use the \u201Cname\u201D and \u201Cvalue\u201D attributes without declaring value types."); OBSOLETE_ATTRIBUTES_MSG.put( "urn", "Specify the preferred persistent identifier using the \u201Chref\u201D attribute instead."); OBSOLETE_ATTRIBUTES_MSG.put( "usemap", "Use the \u201Cimg\u201D element instead of the \u201Cinput\u201D element for image maps."); OBSOLETE_ATTRIBUTES_MSG.put( "valuetype", "Use the \u201Cname\u201D and \u201Cvalue\u201D attributes without declaring value types."); OBSOLETE_ATTRIBUTES_MSG.put("version", "You can safely omit it."); } private static final Map<String, String[]> OBSOLETE_STYLE_ATTRS = new HashMap<String, String[]>(); static { OBSOLETE_STYLE_ATTRS.put("align", new String[] { "caption", "iframe", "img", "input", "object", "embed", "legend", "table", "hr", "div", "h1", "h2", "h3", "h4", "h5", "h6", "p", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr" }); OBSOLETE_STYLE_ATTRS.put("alink", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("allowtransparency", new String[] { "iframe" }); OBSOLETE_STYLE_ATTRS.put("background", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("bgcolor", new String[] { "table", "tr", "td", "th", "body" }); OBSOLETE_STYLE_ATTRS.put("cellpadding", new String[] { "table" }); OBSOLETE_STYLE_ATTRS.put("cellspacing", new String[] { "table" }); OBSOLETE_STYLE_ATTRS.put("char", new String[] { "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr" }); OBSOLETE_STYLE_ATTRS.put("charoff", new String[] { "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr" }); OBSOLETE_STYLE_ATTRS.put("clear", new String[] { "br" }); OBSOLETE_STYLE_ATTRS.put("color", new String[] { "hr" }); OBSOLETE_STYLE_ATTRS.put("compact", new String[] { "dl", "menu", "ol", "ul" }); OBSOLETE_STYLE_ATTRS.put("frameborder", new String[] { "iframe" }); OBSOLETE_STYLE_ATTRS.put("frame", new String[] { "table" }); OBSOLETE_STYLE_ATTRS.put("height", new String[] { "td", "th" }); OBSOLETE_STYLE_ATTRS.put("hspace", new String[] { "img", "object", "embed" }); OBSOLETE_STYLE_ATTRS.put("link", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("marginbottom", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("marginheight", new String[] { "iframe", "body" }); OBSOLETE_STYLE_ATTRS.put("marginleft", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("marginright", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("margintop", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("marginwidth", new String[] { "iframe", "body" }); OBSOLETE_STYLE_ATTRS.put("noshade", new String[] { "hr" }); OBSOLETE_STYLE_ATTRS.put("nowrap", new String[] { "td", "th" }); OBSOLETE_STYLE_ATTRS.put("rules", new String[] { "table" }); OBSOLETE_STYLE_ATTRS.put("scrolling", new String[] { "iframe" }); OBSOLETE_STYLE_ATTRS.put("size", new String[] { "hr" }); OBSOLETE_STYLE_ATTRS.put("text", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("type", new String[] { "li", "ul" }); OBSOLETE_STYLE_ATTRS.put("valign", new String[] { "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr" }); OBSOLETE_STYLE_ATTRS.put("vlink", new String[] { "body" }); OBSOLETE_STYLE_ATTRS.put("vspace", new String[] { "img", "object", "embed" }); OBSOLETE_STYLE_ATTRS.put("width", new String[] { "hr", "table", "td", "th", "col", "colgroup", "pre" }); } private static final String[] SPECIAL_ANCESTORS = { "a", "address", "button", "caption", "dfn", "dt", "figcaption", "figure", "footer", "form", "header", "label", "map", "noscript", "th", "time", "progress", "meter", "article", "section", "aside", "nav", "h1", "h2", "h3", "h4", "h5", "h6" }; private static int specialAncestorNumber(String name) { for (int i = 0; i < SPECIAL_ANCESTORS.length; i++) { if (name == SPECIAL_ANCESTORS[i]) { return i; } } return -1; } private static Map<String, Integer> ANCESTOR_MASK_BY_DESCENDANT = new HashMap<String, Integer>(); private static void registerProhibitedAncestor(String ancestor, String descendant) { int number = specialAncestorNumber(ancestor); if (number == -1) { throw new IllegalStateException("Ancestor not found in array: " + ancestor); } Integer maskAsObject = ANCESTOR_MASK_BY_DESCENDANT.get(descendant); int mask = 0; if (maskAsObject != null) { mask = maskAsObject.intValue(); } mask |= (1 << number); ANCESTOR_MASK_BY_DESCENDANT.put(descendant, new Integer(mask)); } static { registerProhibitedAncestor("form", "form"); registerProhibitedAncestor("time", "time"); registerProhibitedAncestor("progress", "progress"); registerProhibitedAncestor("meter", "meter"); registerProhibitedAncestor("dfn", "dfn"); registerProhibitedAncestor("noscript", "noscript"); registerProhibitedAncestor("label", "label"); registerProhibitedAncestor("address", "address"); registerProhibitedAncestor("address", "section"); registerProhibitedAncestor("address", "nav"); registerProhibitedAncestor("address", "article"); registerProhibitedAncestor("address", "aside"); registerProhibitedAncestor("header", "header"); registerProhibitedAncestor("footer", "header"); registerProhibitedAncestor("address", "header"); registerProhibitedAncestor("header", "footer"); registerProhibitedAncestor("footer", "footer"); registerProhibitedAncestor("dt", "header"); registerProhibitedAncestor("dt", "footer"); registerProhibitedAncestor("dt", "article"); registerProhibitedAncestor("dt", "aside"); registerProhibitedAncestor("dt", "nav"); registerProhibitedAncestor("dt", "section"); registerProhibitedAncestor("dt", "h1"); registerProhibitedAncestor("dt", "h2"); registerProhibitedAncestor("dt", "h2"); registerProhibitedAncestor("dt", "h3"); registerProhibitedAncestor("dt", "h4"); registerProhibitedAncestor("dt", "h5"); registerProhibitedAncestor("dt", "h6"); registerProhibitedAncestor("dt", "hgroup"); registerProhibitedAncestor("th", "header"); registerProhibitedAncestor("th", "footer"); registerProhibitedAncestor("th", "article"); registerProhibitedAncestor("th", "aside"); registerProhibitedAncestor("th", "nav"); registerProhibitedAncestor("th", "section"); registerProhibitedAncestor("th", "h1"); registerProhibitedAncestor("th", "h2"); registerProhibitedAncestor("th", "h2"); registerProhibitedAncestor("th", "h3"); registerProhibitedAncestor("th", "h4"); registerProhibitedAncestor("th", "h5"); registerProhibitedAncestor("th", "h6"); registerProhibitedAncestor("th", "hgroup"); registerProhibitedAncestor("address", "footer"); registerProhibitedAncestor("address", "h1"); registerProhibitedAncestor("address", "h2"); registerProhibitedAncestor("address", "h3"); registerProhibitedAncestor("address", "h4"); registerProhibitedAncestor("address", "h5"); registerProhibitedAncestor("address", "h6"); registerProhibitedAncestor("a", "a"); registerProhibitedAncestor("button", "a"); registerProhibitedAncestor("a", "details"); registerProhibitedAncestor("button", "details"); registerProhibitedAncestor("a", "button"); registerProhibitedAncestor("button", "button"); registerProhibitedAncestor("a", "textarea"); registerProhibitedAncestor("button", "textarea"); registerProhibitedAncestor("a", "select"); registerProhibitedAncestor("button", "select"); registerProhibitedAncestor("a", "keygen"); registerProhibitedAncestor("button", "keygen"); registerProhibitedAncestor("a", "embed"); registerProhibitedAncestor("button", "embed"); registerProhibitedAncestor("a", "iframe"); registerProhibitedAncestor("button", "iframe"); registerProhibitedAncestor("a", "label"); registerProhibitedAncestor("button", "label"); registerProhibitedAncestor("caption", "table"); registerProhibitedAncestor("article", "main"); registerProhibitedAncestor("aside", "main"); registerProhibitedAncestor("header", "main"); registerProhibitedAncestor("footer", "main"); registerProhibitedAncestor("nav", "main"); } private static final int A_BUTTON_MASK = (1 << specialAncestorNumber("a")) | (1 << specialAncestorNumber("button")); private static final int FIGCAPTION_MASK = (1 << specialAncestorNumber("figcaption")); private static final int FIGURE_MASK = (1 << specialAncestorNumber("figure")); private static final int H1_MASK = (1 << specialAncestorNumber("h1")); private static final int H2_MASK = (1 << specialAncestorNumber("h2")); private static final int H3_MASK = (1 << specialAncestorNumber("h3")); private static final int H4_MASK = (1 << specialAncestorNumber("h4")); private static final int H5_MASK = (1 << specialAncestorNumber("h5")); private static final int H6_MASK = (1 << specialAncestorNumber("h6")); private static final int MAP_MASK = (1 << specialAncestorNumber("map")); private static final int HREF_MASK = (1 << 30); private static final int LABEL_FOR_MASK = (1 << 28); private static final Map<String, Set<String>> REQUIRED_ROLE_ANCESTOR_BY_DESCENDANT = new HashMap<String, Set<String>>(); private static final Map<String, Set<String>> ariaOwnsIdsByRole = new HashMap<String, Set<String>>(); private static void registerRequiredAncestorRole(String parent, String child) { Set<String> parents = REQUIRED_ROLE_ANCESTOR_BY_DESCENDANT.get(child); if (parents == null) { parents = new HashSet<String>(); } parents.add(parent); REQUIRED_ROLE_ANCESTOR_BY_DESCENDANT.put(child, parents); } static { registerRequiredAncestorRole("combobox", "option"); registerRequiredAncestorRole("listbox", "option"); registerRequiredAncestorRole("radiogroup", "option"); registerRequiredAncestorRole("menu", "option"); registerRequiredAncestorRole("menu", "menuitem"); registerRequiredAncestorRole("menu", "menuitemcheckbox"); registerRequiredAncestorRole("menu", "menuitemradio"); registerRequiredAncestorRole("menubar", "menuitem"); registerRequiredAncestorRole("menubar", "menuitemcheckbox"); registerRequiredAncestorRole("menubar", "menuitemradio"); registerRequiredAncestorRole("tablist", "tab"); registerRequiredAncestorRole("tree", "treeitem"); registerRequiredAncestorRole("tree", "option"); registerRequiredAncestorRole("group", "treeitem"); registerRequiredAncestorRole("group", "listitem"); registerRequiredAncestorRole("group", "menuitemradio"); registerRequiredAncestorRole("list", "listitem"); registerRequiredAncestorRole("row", "gridcell"); registerRequiredAncestorRole("row", "columnheader"); registerRequiredAncestorRole("row", "rowheader"); registerRequiredAncestorRole("grid", "row"); registerRequiredAncestorRole("grid", "rowgroup"); registerRequiredAncestorRole("rowgroup", "row"); registerRequiredAncestorRole("treegrid", "row"); } private static final Set<String> MUST_NOT_DANGLE_IDREFS = new HashSet<String>(); static { MUST_NOT_DANGLE_IDREFS.add("aria-controls"); MUST_NOT_DANGLE_IDREFS.add("aria-describedby"); MUST_NOT_DANGLE_IDREFS.add("aria-flowto"); MUST_NOT_DANGLE_IDREFS.add("aria-labelledby"); MUST_NOT_DANGLE_IDREFS.add("aria-owns"); } private static final String h1WarningMessage = "Consider using the" + " \u201Ch1\u201D element as a top-level heading only (all" + " \u201Ch1\u201D elements are treated as top-level headings" + " by many screen readers and other tools)."; private class IdrefLocator { private final Locator locator; private final String idref; private final String additional; /** * @param locator * @param idref */ public IdrefLocator(Locator locator, String idref) { this.locator = new LocatorImpl(locator); this.idref = idref; this.additional = null; } public IdrefLocator(Locator locator, String idref, String additional) { this.locator = new LocatorImpl(locator); this.idref = idref; this.additional = additional; } /** * Returns the locator. * * @return the locator */ public Locator getLocator() { return locator; } /** * Returns the idref. * * @return the idref */ public String getIdref() { return idref; } /** * Returns the additional. * * @return the additional */ public String getAdditional() { return additional; } } private class StackNode { private final int ancestorMask; private final String name; // null if not HTML private final String role; private final String activeDescendant; private final String forAttr; private Set<Locator> imagesLackingAlt = new HashSet<Locator>(); private Locator nonEmptyOption = null; private Locator locator = null; private boolean selectedOptions = false; private boolean labeledDescendants = false; private boolean trackDescendants = false; private boolean textNodeFound = false; private boolean imgFound = false; private boolean embeddedContentFound = false; private boolean figcaptionNeeded = false; private boolean figcaptionContentFound = false; private boolean headingFound = false; private boolean optionNeeded = false; private boolean optionFound = false; private boolean noValueOptionFound = false; private boolean emptyValueOptionFound = false; /** * @param ancestorMask */ public StackNode(int ancestorMask, String name, String role, String activeDescendant, String forAttr) { this.ancestorMask = ancestorMask; this.name = name; this.role = role; this.activeDescendant = activeDescendant; this.forAttr = forAttr; } /** * Returns the ancestorMask. * * @return the ancestorMask */ public int getAncestorMask() { return ancestorMask; } /** * Returns the name. * * @return the name */ public String getName() { return name; } /** * Returns the selectedOptions. * * @return the selectedOptions */ public boolean isSelectedOptions() { return selectedOptions; } /** * Sets the selectedOptions. * * @param selectedOptions * the selectedOptions to set */ public void setSelectedOptions() { this.selectedOptions = true; } /** * Returns the labeledDescendants. * * @return the labeledDescendants */ public boolean isLabeledDescendants() { return labeledDescendants; } /** * Sets the labeledDescendants. * * @param labeledDescendants * the labeledDescendants to set */ public void setLabeledDescendants() { this.labeledDescendants = true; } /** * Returns the trackDescendants. * * @return the trackDescendants */ public boolean isTrackDescendant() { return trackDescendants; } /** * Sets the trackDescendants. * * @param trackDescendants * the trackDescendants to set */ public void setTrackDescendants() { this.trackDescendants = true; } /** * Returns the role. * * @return the role */ public String getRole() { return role; } /** * Returns the activeDescendant. * * @return the activeDescendant */ public String getActiveDescendant() { return activeDescendant; } /** * Returns the forAttr. * * @return the forAttr */ public String getForAttr() { return forAttr; } /** * Returns the textNodeFound. * * @return the textNodeFound */ public boolean hasTextNode() { return textNodeFound; } /** * Sets the textNodeFound. */ public void setTextNodeFound() { this.textNodeFound = true; } /** * Returns the imgFound. * * @return the imgFound */ public boolean hasImg() { return imgFound; } /** * Sets the imgFound. */ public void setImgFound() { this.imgFound = true; } /** * Returns the embeddedContentFound. * * @return the embeddedContentFound */ public boolean hasEmbeddedContent() { return embeddedContentFound; } /** * Sets the embeddedContentFound. */ public void setEmbeddedContentFound() { this.embeddedContentFound = true; } /** * Returns the figcaptionNeeded. * * @return the figcaptionNeeded */ public boolean needsFigcaption() { return figcaptionNeeded; } /** * Sets the figcaptionNeeded. */ public void setFigcaptionNeeded() { this.figcaptionNeeded = true; } /** * Returns the figcaptionContentFound. * * @return the figcaptionContentFound */ public boolean hasFigcaptionContent() { return figcaptionContentFound; } /** * Sets the figcaptionContentFound. */ public void setFigcaptionContentFound() { this.figcaptionContentFound = true; } /** * Returns the headingFound. * * @return the headingFound */ public boolean hasHeading() { return headingFound; } /** * Sets the headingFound. */ public void setHeadingFound() { this.headingFound = true; } /** * Returns the imagesLackingAlt * * @return the imagesLackingAlt */ public Set<Locator> getImagesLackingAlt() { return imagesLackingAlt; } /** * Adds to the imagesLackingAlt */ public void addImageLackingAlt(Locator locator) { this.imagesLackingAlt.add(locator); } /** * Returns the optionNeeded. * * @return the optionNeeded */ public boolean isOptionNeeded() { return optionNeeded; } /** * Sets the optionNeeded. */ public void setOptionNeeded() { this.optionNeeded = true; } /** * Returns the optionFound. * * @return the optionFound */ public boolean hasOption() { return optionFound; } /** * Sets the optionFound. */ public void setOptionFound() { this.optionFound = true; } /** * Returns the noValueOptionFound. * * @return the noValueOptionFound */ public boolean hasNoValueOption() { return noValueOptionFound; } /** * Sets the noValueOptionFound. */ public void setNoValueOptionFound() { this.noValueOptionFound = true; } /** * Returns the emptyValueOptionFound. * * @return the emptyValueOptionFound */ public boolean hasEmptyValueOption() { return emptyValueOptionFound; } /** * Sets the emptyValueOptionFound. */ public void setEmptyValueOptionFound() { this.emptyValueOptionFound = true; } /** * Returns the nonEmptyOption. * * @return the nonEmptyOption */ public Locator nonEmptyOptionLocator() { return nonEmptyOption; } /** * Sets the nonEmptyOption. */ public void setNonEmptyOption(Locator locator) { this.nonEmptyOption = locator; } /** * Returns the locator. * * @return the locator */ public Locator locator() { return locator; } /** * Sets the locator. */ public void setLocator(Locator locator) { this.locator = locator; } } private StackNode[] stack; private int currentPtr; private int currentSectioningDepth; public Assertions() { super(); } private void push(StackNode node) { currentPtr++; if (currentPtr == stack.length) { StackNode[] newStack = new StackNode[stack.length + 64]; System.arraycopy(stack, 0, newStack, 0, stack.length); stack = newStack; } stack[currentPtr] = node; } private StackNode pop() { return stack[currentPtr } private StackNode peek() { return stack[currentPtr]; } private Map<StackNode, Locator> openSingleSelects = new HashMap<StackNode, Locator>(); private Map<StackNode, Locator> openLabels = new HashMap<StackNode, Locator>(); private Map<StackNode, TaintableLocatorImpl> openMediaElements = new HashMap<StackNode, TaintableLocatorImpl>(); private Map<StackNode, Locator> openActiveDescendants = new HashMap<StackNode, Locator>(); private LinkedHashSet<IdrefLocator> contextmenuReferences = new LinkedHashSet<IdrefLocator>(); private Set<String> menuIds = new HashSet<String>(); private LinkedHashSet<IdrefLocator> formControlReferences = new LinkedHashSet<IdrefLocator>(); private LinkedHashSet<IdrefLocator> formElementReferences = new LinkedHashSet<IdrefLocator>(); private LinkedHashSet<IdrefLocator> needsAriaOwner = new LinkedHashSet<IdrefLocator>(); private Set<String> formControlIds = new HashSet<String>(); private Set<String> formElementIds = new HashSet<String>(); private LinkedHashSet<IdrefLocator> listReferences = new LinkedHashSet<IdrefLocator>(); private Set<String> listIds = new HashSet<String>(); private LinkedHashSet<IdrefLocator> ariaReferences = new LinkedHashSet<IdrefLocator>(); private Set<String> allIds = new HashSet<String>(); private int currentFigurePtr; private int currentHeadingPtr; private int currentSectioningElementPtr; private boolean hasMain; private boolean hasTopLevelH1; private Set<Locator> secondLevelH1s = new HashSet<Locator>(); private Map<Locator, Map<String, String>> siblingSources = new ConcurrentHashMap<Locator, Map<String, String>>(); private final void errContainedInOrOwnedBy(String role, Locator locator) throws SAXException { err("An element with \u201Crole=" + role + "\u201D" + " must be contained in, or owned by, an element with " + renderRoleSet(REQUIRED_ROLE_ANCESTOR_BY_DESCENDANT.get(role)) + ".", locator); } private final void errObsoleteAttribute(String attribute, String element, String suggestion) throws SAXException { err("The \u201C" + attribute + "\u201D attribute on the \u201C" + element + "\u201D element is obsolete." + suggestion); } private final void warnPresentationalAttribute(String attribute, String element, String suggestion) throws SAXException { warn("The \u201C" + attribute + "\u201D attribute on the \u201C" + element + "\u201D element is presentational markup." + " Consider using CSS instead." + suggestion); } private boolean currentElementHasRequiredAncestorRole( Set<String> requiredAncestorRoles) { for (String role : requiredAncestorRoles) { for (int i = 0; i < currentPtr; i++) { if (role.equals(stack[currentPtr - i].getRole())) { return true; } } } return false; } /** * @see nu.validator.checker.Checker#endDocument() */ @Override public void endDocument() throws SAXException { // contextmenu for (IdrefLocator idrefLocator : contextmenuReferences) { if (!menuIds.contains(idrefLocator.getIdref())) { err( "The \u201Ccontextmenu\u201D attribute must refer to a \u201Cmenu\u201D element.", idrefLocator.getLocator()); } } // label for for (IdrefLocator idrefLocator : formControlReferences) { if (!formControlIds.contains(idrefLocator.getIdref())) { err( "The \u201Cfor\u201D attribute of the \u201Clabel\u201D element must refer to a form control.", idrefLocator.getLocator()); } } // references to IDs from form attributes for (IdrefLocator idrefLocator : formElementReferences) { if (!formElementIds.contains(idrefLocator.getIdref())) { err("The \u201Cform\u201D attribute must refer to a form element.", idrefLocator.getLocator()); } } // input list for (IdrefLocator idrefLocator : listReferences) { if (!listIds.contains(idrefLocator.getIdref())) { err( "The \u201Clist\u201D attribute of the \u201Cinput\u201D element must refer to a \u201Cdatalist\u201D element.", idrefLocator.getLocator()); } } // ARIA idrefs for (IdrefLocator idrefLocator : ariaReferences) { if (!allIds.contains(idrefLocator.getIdref())) { err( "The \u201C" + idrefLocator.getAdditional() + "\u201D attribute must point to an element in the same document.", idrefLocator.getLocator()); } } // ARIA required owners for (IdrefLocator idrefLocator : needsAriaOwner) { boolean foundOwner = false; String role = idrefLocator.getAdditional(); for (String ownerRole : REQUIRED_ROLE_ANCESTOR_BY_DESCENDANT.get(role)) { if (ariaOwnsIdsByRole.size() != 0 && ariaOwnsIdsByRole.get(ownerRole) != null && ariaOwnsIdsByRole.get(ownerRole).contains( idrefLocator.getIdref())) { foundOwner = true; break; } } if (!foundOwner) { errContainedInOrOwnedBy(role, idrefLocator.getLocator()); } } if (hasTopLevelH1) { for (Locator locator : secondLevelH1s) { warn(h1WarningMessage, locator); } } reset(); stack = null; } private static double getDoubleAttribute(Attributes atts, String name) { String str = atts.getValue("", name); if (str == null) { return Double.NaN; } else { try { return Double.parseDouble(str); } catch (NumberFormatException e) { return Double.NaN; } } } /** * @see nu.validator.checker.Checker#endElement(java.lang.String, * java.lang.String, java.lang.String) */ @Override public void endElement(String uri, String localName, String name) throws SAXException { StackNode node = pop(); Locator locator = null; openSingleSelects.remove(node); openLabels.remove(node); openMediaElements.remove(node); if ("http: if ("figure" == localName) { if ((node.needsFigcaption() && !node.hasFigcaptionContent()) || node.hasTextNode() || node.hasEmbeddedContent()) { for (Locator imgLocator : node.getImagesLackingAlt()) { err("An \u201Cimg\u201D element must have an" + " \u201Calt\u201D attribute, except under" + " certain conditions. For details, consult" + " guidance on providing text alternatives" + " for images.", imgLocator); } } } else if ("picture" == localName) { siblingSources.clear(); } else if ("select" == localName && node.isOptionNeeded()) { if (!node.hasOption()) { err("A \u201Cselect\u201D element with a" + " \u201Crequired\u201D attribute, and without a" + " \u201Cmultiple\u201D attribute, and without a" + " \u201Csize\u201D attribute whose value is" + " greater than" + " \u201C1\u201D, must have a child" + " \u201Coption\u201D element."); } if (node.nonEmptyOptionLocator() != null) { err("The first child \u201Coption\u201D element of a" + " \u201Cselect\u201D element with a" + " \u201Crequired\u201D attribute, and without a" + " \u201Cmultiple\u201D attribute, and without a" + " \u201Csize\u201D attribute whose value is" + " greater than" + " \u201C1\u201D, must have either an empty" + " \u201Cvalue\u201D attribute, or must have no" + " text content." + " Consider either adding a placeholder option" + " label, or adding a" + " \u201Csize\u201D attribute with a value equal" + " to the number of" + " \u201Coption\u201D elements.", node.nonEmptyOptionLocator()); } } else if ("section" == localName && !node.hasHeading()) { warn("Section lacks heading. Consider using" + " \u201ch2\u201d-\u201ch6\u201d elements to add" + " identifying headings to all sections.", node.locator()); } else if ("article" == localName && !node.hasHeading()) { warn("Article lacks heading. Consider using" + " \u201ch2\u201d-\u201ch6\u201d elements to add" + " identifying headings to all articles.", node.locator()); } else if (("h1" == localName || "h2" == localName || "h3" == localName || "h4" == localName || "h5" == localName || "h6" == localName) && !node.hasTextNode() && !node.hasImg()) { warn("Empty heading.", node.locator()); } else if ("option" == localName && !stack[currentPtr].hasOption()) { stack[currentPtr].setOptionFound(); } if ("article" == localName || "aside" == localName || "nav" == localName || "section" == localName) { currentSectioningElementPtr = -1; currentSectioningDepth } } if ((locator = openActiveDescendants.remove(node)) != null) { warn( "Attribute \u201Caria-activedescendant\u201D value should " + "either refer to a descendant element, or should " + "be accompanied by attribute \u201Caria-owns\u201D.", locator); } } /** * @see nu.validator.checker.Checker#startDocument() */ @Override public void startDocument() throws SAXException { reset(); stack = new StackNode[32]; currentPtr = 0; currentFigurePtr = -1; currentHeadingPtr = -1; currentSectioningElementPtr = -1; currentSectioningDepth = 0; stack[0] = null; hasMain = false; hasTopLevelH1 = false; } public void reset() { openSingleSelects.clear(); openLabels.clear(); openMediaElements.clear(); openActiveDescendants.clear(); contextmenuReferences.clear(); menuIds.clear(); ariaOwnsIdsByRole.clear(); needsAriaOwner.clear(); formControlReferences.clear(); formElementReferences.clear(); formControlIds.clear(); formElementIds.clear(); listReferences.clear(); listIds.clear(); ariaReferences.clear(); allIds.clear(); siblingSources.clear(); } /** * @see nu.validator.checker.Checker#startElement(java.lang.String, * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException { Set<String> ids = new HashSet<String>(); String role = null; String activeDescendant = null; String owns = null; String forAttr = null; boolean href = false; boolean activeDescendantWithAriaOwns = false; // see nu.validator.datatype.ImageCandidateStrings System.setProperty("nu.validator.checker.imageCandidateString.hasWidth", "0"); StackNode parent = peek(); int ancestorMask = 0; String parentRole = null; String parentName = null; if (parent != null) { ancestorMask = parent.getAncestorMask(); parentName = parent.getName(); parentRole = parent.getRole(); } if ("http: boolean controls = false; boolean hidden = false; boolean toolbar = false; boolean usemap = false; boolean ismap = false; boolean selected = false; boolean itemid = false; boolean itemref = false; boolean itemscope = false; boolean itemtype = false; boolean languageJavaScript = false; boolean typeNotTextJavaScript = false; String xmlLang = null; String lang = null; String id = null; String contextmenu = null; String list = null; int len = atts.getLength(); for (int i = 0; i < len; i++) { String attUri = atts.getURI(i); if (attUri.length() == 0) { String attLocal = atts.getLocalName(i); if ("href" == attLocal) { href = true; } else if ("controls" == attLocal) { controls = true; } else if ("type" == attLocal && "param" != localName && "ol" != localName && "ul" != localName && "li" != localName) { String attValue = atts.getValue(i); if (lowerCaseLiteralEqualsIgnoreAsciiCaseString( "hidden", attValue)) { hidden = true; } else if (lowerCaseLiteralEqualsIgnoreAsciiCaseString( "toolbar", attValue)) { toolbar = true; } if (!lowerCaseLiteralEqualsIgnoreAsciiCaseString( "text/javascript", attValue)) { typeNotTextJavaScript = true; } } else if ("role" == attLocal) { role = atts.getValue(i); } else if ("aria-activedescendant" == attLocal) { activeDescendant = atts.getValue(i); } else if ("aria-owns" == attLocal) { owns = atts.getValue(i); } else if ("list" == attLocal) { list = atts.getValue(i); } else if ("lang" == attLocal) { lang = atts.getValue(i); } else if ("id" == attLocal) { id = atts.getValue(i); } else if ("for" == attLocal && "label" == localName) { forAttr = atts.getValue(i); ancestorMask |= LABEL_FOR_MASK; } else if ("contextmenu" == attLocal) { contextmenu = atts.getValue(i); } else if ("ismap" == attLocal) { ismap = true; } else if ("selected" == attLocal) { selected = true; } else if ("usemap" == attLocal && "input" != localName) { usemap = true; } else if ("itemid" == attLocal) { itemid = true; } else if ("itemref" == attLocal) { itemref = true; } else if ("itemscope" == attLocal) { itemscope = true; } else if ("itemtype" == attLocal) { itemtype = true; } else if ("language" == attLocal && lowerCaseLiteralEqualsIgnoreAsciiCaseString( "javascript", atts.getValue(i))) { languageJavaScript = true; } else if ("rev" == attLocal && !("1".equals(System.getProperty("nu.validator.schema.rdfa-full")))) { errObsoleteAttribute( "rev", localName, " Use the \u201Crel\u201D attribute instead," + " with a term having the opposite meaning."); } else if (OBSOLETE_ATTRIBUTES.containsKey(attLocal) && "ol" != localName && "ul" != localName && "li" != localName) { String[] elementNames = OBSOLETE_ATTRIBUTES.get(attLocal); Arrays.sort(elementNames); if (Arrays.binarySearch(elementNames, localName) >= 0) { String suggestion = OBSOLETE_ATTRIBUTES_MSG.containsKey(attLocal) ? " " + OBSOLETE_ATTRIBUTES_MSG.get(attLocal) : ""; errObsoleteAttribute(attLocal, localName, suggestion); } } else if (OBSOLETE_STYLE_ATTRS.containsKey(attLocal)) { String[] elementNames = OBSOLETE_STYLE_ATTRS.get(attLocal); Arrays.sort(elementNames); if (Arrays.binarySearch(elementNames, localName) >= 0) { errObsoleteAttribute(attLocal, localName, " Use CSS instead."); } } else if ("dropzone" == attLocal) { String[] tokens = atts.getValue(i).toString().split( "[ \\t\\n\\f\\r]+"); Arrays.sort(tokens); for (int j = 0; j < tokens.length; j++) { String keyword = tokens[j]; if (j > 0 && keyword.equals(tokens[j - 1])) { err("Duplicate keyword " + keyword + ". Each keyword must be unique."); } } } } else if ("http: if ("lang" == atts.getLocalName(i)) { xmlLang = atts.getValue(i); } } if (atts.getType(i) == "ID") { String attVal = atts.getValue(i); if (attVal.length() != 0) { ids.add(attVal); } } } if ("img".equals(localName) || "source".equals(localName)) { if (atts.getIndex("", "srcset") > -1) { String srcsetVal = atts.getValue("", "srcset"); try { if (atts.getIndex("", "sizes") > -1) { ImageCandidateStringsWidthRequired.THE_INSTANCE.checkValid(srcsetVal); } else { ImageCandidateStrings.THE_INSTANCE.checkValid(srcsetVal); } // see nu.validator.datatype.ImageCandidateStrings if ("1".equals(System.getProperty("nu.validator.checker.imageCandidateString.hasWidth"))) { if (atts.getIndex("", "sizes") < 0) { err("When the \u201csrcset\u201d attribute has" + " any image candidate string with a" + " width descriptor, the" + " \u201csizes\u201d attribute" + " must also be present."); } } } catch (DatatypeException e) { Class<?> datatypeClass = ImageCandidateStrings.class; if (atts.getIndex("", "sizes") > -1) { datatypeClass = ImageCandidateStringsWidthRequired.class; } try { if (getErrorHandler() != null) { String msg = e.getMessage(); if (e instanceof Html5DatatypeException) { Html5DatatypeException ex5 = (Html5DatatypeException) e; if (!ex5.getDatatypeClass().equals( ImageCandidateURL.class)) { msg = msg.substring(msg.indexOf(": ") + 2); } } VnuBadAttrValueException ex = new VnuBadAttrValueException( localName, uri, "srcset", srcsetVal, msg, getDocumentLocator(), datatypeClass, false); getErrorHandler().error(ex); } } catch (ClassNotFoundException ce) { } } if ("picture".equals(parentName) && !siblingSources.isEmpty()) { for (Map.Entry<Locator, Map<String, String>> entry : siblingSources.entrySet()) { Locator locator = entry.getKey(); Map<String, String> sourceAtts = entry.getValue(); String media = sourceAtts.get("media"); if (media == null && sourceAtts.get("type") == null) { err("A \u201csource\u201d element that has a" + " following sibling" + " \u201csource\u201d element or" + " \u201cimg\u201d element with a" + " \u201csrcset\u201d attribute" + " must have a" + " \u201cmedia\u201d attribute and/or" + " \u201ctype\u201d attribute.", locator); siblingSources.remove(locator); } else if (media != null && lowerCaseLiteralEqualsIgnoreAsciiCaseString( "all", trimSpaces(media))) { err("Value of \u201cmedia\u201d attribute here" + " must not be \u201call\u201d.", locator); } } } } else if (atts.getIndex("", "sizes") > -1) { err("The \u201csizes\u201d attribute may be specified" + " only if the \u201csrcset\u201d attribute is" + " also present."); } } if ("picture".equals(parentName) && "source".equals(localName)) { Map<String, String> sourceAtts = new HashMap<String, String>(); for (int i = 0; i < atts.getLength(); i++) { sourceAtts.put(atts.getLocalName(i), atts.getValue(i)); } siblingSources.put((new LocatorImpl(getDocumentLocator())), sourceAtts); } if ("figure" == localName) { currentFigurePtr = currentPtr + 1; } if ((ancestorMask & FIGURE_MASK) != 0) { if ("img" == localName) { if (stack[currentFigurePtr].hasImg()) { stack[currentFigurePtr].setEmbeddedContentFound(); } else { stack[currentFigurePtr].setImgFound(); } } else if ("audio" == localName || "canvas" == localName || "embed" == localName || "iframe" == localName || "math" == localName || "object" == localName || "svg" == localName || "video" == localName) { stack[currentFigurePtr].setEmbeddedContentFound(); } } if ("article" == localName || "aside" == localName || "nav" == localName || "section" == localName) { currentSectioningElementPtr = currentPtr + 1; currentSectioningDepth++; } if ("h1" == localName || "h2" == localName || "h3" == localName || "h4" == localName || "h5" == localName || "h6" == localName) { currentHeadingPtr = currentPtr + 1; if (currentSectioningElementPtr > -1) { stack[currentSectioningElementPtr].setHeadingFound(); } } if (((ancestorMask & H1_MASK) != 0 || (ancestorMask & H2_MASK) != 0 || (ancestorMask & H3_MASK) != 0 || (ancestorMask & H4_MASK) != 0 || (ancestorMask & H5_MASK) != 0 || (ancestorMask & H6_MASK) != 0) && "img" == localName && atts.getIndex("", "alt") > -1 && !"".equals(atts.getValue("", "alt"))) { stack[currentHeadingPtr].setImgFound(); } if ("option" == localName && !parent.hasOption()) { if (atts.getIndex("", "value") < 0) { parent.setNoValueOptionFound(); } else if (atts.getIndex("", "value") > -1 && "".equals(atts.getValue("", "value"))) { parent.setEmptyValueOptionFound(); } else { parent.setNonEmptyOption((new LocatorImpl( getDocumentLocator()))); } } // Obsolete elements if (OBSOLETE_ELEMENTS.get(localName) != null) { err("The \u201C" + localName + "\u201D element is obsolete. " + OBSOLETE_ELEMENTS.get(localName)); } // Exclusions Integer maskAsObject; int mask = 0; String descendantUiString = ""; if ((maskAsObject = ANCESTOR_MASK_BY_DESCENDANT.get(localName)) != null) { mask = maskAsObject.intValue(); descendantUiString = localName; } else if ("video" == localName && controls) { mask = A_BUTTON_MASK; descendantUiString = "video\u201D with the attribute \u201Ccontrols"; } else if ("audio" == localName && controls) { mask = A_BUTTON_MASK; descendantUiString = "audio\u201D with the attribute \u201Ccontrols"; } else if ("menu" == localName && toolbar) { mask = A_BUTTON_MASK; descendantUiString = "menu\u201D with the attribute \u201Ctype=toolbar"; } else if ("img" == localName && usemap) { mask = A_BUTTON_MASK; descendantUiString = "img\u201D with the attribute \u201Cusemap"; } else if ("object" == localName && usemap) { mask = A_BUTTON_MASK; descendantUiString = "object\u201D with the attribute \u201Cusemap"; } else if ("input" == localName && !hidden) { mask = A_BUTTON_MASK; descendantUiString = "input"; } if (mask != 0) { int maskHit = ancestorMask & mask; if (maskHit != 0) { for (int j = 0; j < SPECIAL_ANCESTORS.length; j++) { if ((maskHit & 1) != 0) { err("The element \u201C" + descendantUiString + "\u201D must not appear as a descendant of the \u201C" + SPECIAL_ANCESTORS[j] + "\u201D element."); } maskHit >>= 1; } } } // Ancestor requirements/restrictions if ("area" == localName && ((ancestorMask & MAP_MASK) == 0)) { err("The \u201Carea\u201D element must have a \u201Cmap\u201D ancestor."); } else if ("img" == localName) { String titleVal = atts.getValue("", "title"); if (ismap && ((ancestorMask & HREF_MASK) == 0)) { err("The \u201Cimg\u201D element with the " + "\u201Cismap\u201D attribute set must have an " + "\u201Ca\u201D ancestor with the " + "\u201Chref\u201D attribute."); } if (atts.getIndex("", "alt") < 0) { if (followW3Cspec || (titleVal == null || "".equals(titleVal))) { if ((ancestorMask & FIGURE_MASK) == 0) { err("An \u201Cimg\u201D element must have an" + " \u201Calt\u201D attribute, except under" + " certain conditions. For details, consult" + " guidance on providing text alternatives" + " for images."); } else { stack[currentFigurePtr].setFigcaptionNeeded(); stack[currentFigurePtr].addImageLackingAlt(new LocatorImpl( getDocumentLocator())); } } } } else if ("input" == localName || "button" == localName || "select" == localName || "textarea" == localName || "keygen" == localName) { for (Map.Entry<StackNode, Locator> entry : openLabels.entrySet()) { StackNode node = entry.getKey(); Locator locator = entry.getValue(); if (node.isLabeledDescendants()) { err("The \u201Clabel\u201D element may contain at most one \u201Cinput\u201D, \u201Cbutton\u201D, \u201Cselect\u201D, \u201Ctextarea\u201D, or \u201Ckeygen\u201D descendant."); warn( "\u201Clabel\u201D element with multiple labelable descendants.", locator); } else { node.setLabeledDescendants(); } } if ((ancestorMask & LABEL_FOR_MASK) != 0) { boolean hasMatchingFor = false; for (int i = 0; (stack[currentPtr - i].getAncestorMask() & LABEL_FOR_MASK) != 0; i++) { String forVal = stack[currentPtr - i].getForAttr(); if (forVal != null && forVal.equals(id)) { hasMatchingFor = true; break; } } if (id == null || !hasMatchingFor) { err("Any \u201C" + localName + "\u201D descendant of a \u201Clabel\u201D element with a \u201Cfor\u201D attribute must have an ID value that matches that \u201Cfor\u201D attribute."); } } } else if ("table" == localName) { if (atts.getIndex("", "summary") >= 0) { errObsoleteAttribute("summary", "table", " Consider describing the structure of the" + " \u201Ctable\u201D in a \u201Ccaption\u201D " + " element or in a \u201Cfigure\u201D element " + " containing the \u201Ctable\u201D; or," + " simplify the structure of the" + " \u201Ctable\u201D so that no description" + " is needed."); } if (atts.getIndex("", "border") > -1) { if (followW3Cspec) { if (atts.getIndex("", "border") > -1 && (!("".equals(atts.getValue("", "border")) || "1".equals(atts.getValue( "", "border"))))) { errObsoleteAttribute("border", "table", " Use CSS instead."); } else { warnPresentationalAttribute("border", "table", " For example: \u201Ctable, td, th { border: 1px solid gray }\u201D"); } } else { errObsoleteAttribute("border", "table", " Use CSS instead."); } } } else if ("track" == localName && atts.getIndex("", "default") >= 0) { for (Map.Entry<StackNode, TaintableLocatorImpl> entry : openMediaElements.entrySet()) { StackNode node = entry.getKey(); TaintableLocatorImpl locator = entry.getValue(); if (node.isTrackDescendant()) { err("The \u201Cdefault\u201D attribute must not occur" + " on more than one \u201Ctrack\u201D element" + " within the same \u201Caudio\u201D or" + " \u201Cvideo\u201D element."); if (!locator.isTainted()) { warn("\u201Caudio\u201D or \u201Cvideo\u201D element" + " has more than one \u201Ctrack\u201D child" + " element with a \u201Cdefault\u201D attribute.", locator); locator.markTainted(); } } else { node.setTrackDescendants(); } } } else if ("main" == localName) { if (hasMain) { err("A document must not include more than one" + " \u201Cmain\u201D element."); } hasMain = true; } else if ("h1" == localName) { if (currentSectioningDepth > 1) { warn(h1WarningMessage); } else if (currentSectioningDepth == 1) { secondLevelH1s.add(new LocatorImpl(getDocumentLocator())); } else { hasTopLevelH1 = true; } } // progress else if ("progress" == localName) { double value = getDoubleAttribute(atts, "value"); if (!Double.isNaN(value)) { double max = getDoubleAttribute(atts, "max"); if (Double.isNaN(max)) { if (!(value <= 1.0)) { err("The value of the \u201Cvalue\u201D attribute must be less than or equal to one when the \u201Cmax\u201D attribute is absent."); } } else { if (!(value <= max)) { err("The value of the \u201Cvalue\u201D attribute must be less than or equal to the value of the \u201Cmax\u201D attribute."); } } } } // meter else if ("meter" == localName) { double value = getDoubleAttribute(atts, "value"); double min = getDoubleAttribute(atts, "min"); double max = getDoubleAttribute(atts, "max"); double optimum = getDoubleAttribute(atts, "optimum"); double low = getDoubleAttribute(atts, "low"); double high = getDoubleAttribute(atts, "high"); if (!Double.isNaN(min) && !Double.isNaN(value) && !(min <= value)) { err("The value of the \u201Cmin\u201D attribute must be less than or equal to the value of the \u201Cvalue\u201D attribute."); } if (Double.isNaN(min) && !Double.isNaN(value) && !(0 <= value)) { err("The value of the \u201Cvalue\u201D attribute must be greater than or equal to zero when the \u201Cmin\u201D attribute is absent."); } if (!Double.isNaN(value) && !Double.isNaN(max) && !(value <= max)) { err("The value of the \u201Cvalue\u201D attribute must be less than or equal to the value of the \u201Cmax\u201D attribute."); } if (!Double.isNaN(value) && Double.isNaN(max) && !(value <= 1)) { err("The value of the \u201Cvalue\u201D attribute must be less than or equal to one when the \u201Cmax\u201D attribute is absent."); } if (!Double.isNaN(min) && !Double.isNaN(max) && !(min <= max)) { err("The value of the \u201Cmin\u201D attribute must be less than or equal to the value of the \u201Cmax\u201D attribute."); } if (Double.isNaN(min) && !Double.isNaN(max) && !(0 <= max)) { err("The value of the \u201Cmax\u201D attribute must be greater than or equal to zero when the \u201Cmin\u201D attribute is absent."); } if (!Double.isNaN(min) && Double.isNaN(max) && !(min <= 1)) { err("The value of the \u201Cmin\u201D attribute must be less than or equal to one when the \u201Cmax\u201D attribute is absent."); } if (!Double.isNaN(min) && !Double.isNaN(low) && !(min <= low)) { err("The value of the \u201Cmin\u201D attribute must be less than or equal to the value of the \u201Clow\u201D attribute."); } if (Double.isNaN(min) && !Double.isNaN(low) && !(0 <= low)) { err("The value of the \u201Clow\u201D attribute must be greater than or equal to zero when the \u201Cmin\u201D attribute is absent."); } if (!Double.isNaN(min) && !Double.isNaN(high) && !(min <= high)) { err("The value of the \u201Cmin\u201D attribute must be less than or equal to the value of the \u201Chigh\u201D attribute."); } if (Double.isNaN(min) && !Double.isNaN(high) && !(0 <= high)) { err("The value of the \u201Chigh\u201D attribute must be greater than or equal to zero when the \u201Cmin\u201D attribute is absent."); } if (!Double.isNaN(low) && !Double.isNaN(high) && !(low <= high)) { err("The value of the \u201Clow\u201D attribute must be less than or equal to the value of the \u201Chigh\u201D attribute."); } if (!Double.isNaN(high) && !Double.isNaN(max) && !(high <= max)) { err("The value of the \u201Chigh\u201D attribute must be less than or equal to the value of the \u201Cmax\u201D attribute."); } if (!Double.isNaN(high) && Double.isNaN(max) && !(high <= 1)) { err("The value of the \u201Chigh\u201D attribute must be less than or equal to one when the \u201Cmax\u201D attribute is absent."); } if (!Double.isNaN(low) && !Double.isNaN(max) && !(low <= max)) { err("The value of the \u201Clow\u201D attribute must be less than or equal to the value of the \u201Cmax\u201D attribute."); } if (!Double.isNaN(low) && Double.isNaN(max) && !(low <= 1)) { err("The value of the \u201Clow\u201D attribute must be less than or equal to one when the \u201Cmax\u201D attribute is absent."); } if (!Double.isNaN(min) && !Double.isNaN(optimum) && !(min <= optimum)) { err("The value of the \u201Cmin\u201D attribute must be less than or equal to the value of the \u201Coptimum\u201D attribute."); } if (Double.isNaN(min) && !Double.isNaN(optimum) && !(0 <= optimum)) { err("The value of the \u201Coptimum\u201D attribute must be greater than or equal to zero when the \u201Cmin\u201D attribute is absent."); } if (!Double.isNaN(optimum) && !Double.isNaN(max) && !(optimum <= max)) { err("The value of the \u201Coptimum\u201D attribute must be less than or equal to the value of the \u201Cmax\u201D attribute."); } if (!Double.isNaN(optimum) && Double.isNaN(max) && !(optimum <= 1)) { err("The value of the \u201Coptimum\u201D attribute must be less than or equal to one when the \u201Cmax\u201D attribute is absent."); } } // map required attrs else if ("map" == localName && id != null) { String nameVal = atts.getValue("", "name"); if (nameVal != null && !nameVal.equals(id)) { err("The \u201Cid\u201D attribute on a \u201Cmap\u201D element must have an the same value as the \u201Cname\u201D attribute."); } } else if ("object" == localName) { if (atts.getIndex("", "typemustmatch") >= 0) { if ((atts.getIndex("", "data") < 0) || (atts.getIndex("", "type") < 0)) { { err("Element \u201Cobject\u201D must not have" + " attribute \u201Ctypemustmatch\u201D unless" + " both attribute \u201Cdata\u201D" + " and attribute \u201Csrc\u201D are also specified."); } } } } // script else if ("script" == localName) { // script language if (languageJavaScript && typeNotTextJavaScript) { err("A \u201Cscript\u201D element with the \u201Clanguage=\"JavaScript\"\u201D attribute set must not have a \u201Ctype\u201D attribute whose value is not \u201Ctext/javascript\u201D."); } // src-less script if (atts.getIndex("", "src") < 0) { if (atts.getIndex("", "charset") >= 0) { err("Element \u201Cscript\u201D must not have attribute \u201Ccharset\u201D unless attribute \u201Csrc\u201D is also specified."); } if (atts.getIndex("", "defer") >= 0) { err("Element \u201Cscript\u201D must not have attribute \u201Cdefer\u201D unless attribute \u201Csrc\u201D is also specified."); } if (atts.getIndex("", "async") >= 0) { err("Element \u201Cscript\u201D must not have attribute \u201Casync\u201D unless attribute \u201Csrc\u201D is also specified."); } } } // bdo required attrs else if ("bdo" == localName && atts.getIndex("", "dir") < 0) { err("Element \u201Cbdo\u201D must have attribute \u201Cdir\u201D."); } // lang and xml:lang for XHTML5 if (lang != null && xmlLang != null && !equalsIgnoreAsciiCase(lang, xmlLang)) { err("When the attribute \u201Clang\u201D in no namespace and the attribute \u201Clang\u201D in the XML namespace are both present, they must have the same value."); } // contextmenu if (contextmenu != null) { contextmenuReferences.add(new IdrefLocator(new LocatorImpl( getDocumentLocator()), contextmenu)); } if ("menu" == localName) { menuIds.addAll(ids); } if (role != null && owns != null) { for (Set<String> value : REQUIRED_ROLE_ANCESTOR_BY_DESCENDANT.values()) { if (value.contains(role)) { String[] ownedIds = AttributeUtil.split(owns); for (int i = 0; i < ownedIds.length; i++) { Set<String> ownedIdsForThisRole = ariaOwnsIdsByRole.get(role); if (ownedIdsForThisRole == null) { ownedIdsForThisRole = new HashSet<String>(); } ownedIdsForThisRole.add(ownedIds[i]); ariaOwnsIdsByRole.put(role, ownedIdsForThisRole); } break; } } } if ("datalist" == localName) { listIds.addAll(ids); } // label for if ("label" == localName) { String forVal = atts.getValue("", "for"); if (forVal != null) { formControlReferences.add(new IdrefLocator(new LocatorImpl( getDocumentLocator()), forVal)); } } if ("form" == localName) { formElementIds.addAll(ids); } if (("input" == localName && !hidden) || "textarea" == localName || "select" == localName || "button" == localName || "keygen" == localName || "output" == localName) { formControlIds.addAll(ids); } if ("button" == localName || "fieldset" == localName || ("input" == localName && !hidden) || "keygen" == localName || "label" == localName || "object" == localName || "output" == localName || "select" == localName || "textarea" == localName) { String formVal = atts.getValue("", "form"); if (formVal != null) { formElementReferences.add(new IdrefLocator( new LocatorImpl(getDocumentLocator()), formVal)); } } // input list if ("input" == localName && list != null) { listReferences.add(new IdrefLocator(new LocatorImpl( getDocumentLocator()), list)); } // input@type=button if ("input" == localName && lowerCaseLiteralEqualsIgnoreAsciiCaseString("button", atts.getValue("", "type"))) { if (atts.getValue("", "value") == null || "".equals(atts.getValue("", "value"))) { err("Element \u201Cinput\u201D with attribute \u201Ctype\u201D whose value is \u201Cbutton\u201D must have non-empty attribute \u201Cvalue\u201D."); } } // track if ("track" == localName) { if ("".equals(atts.getValue("", "label"))) { err("Attribute \u201Clabel\u201D for element \u201Ctrack\u201D must have non-empty value."); } } // multiple selected options if ("option" == localName && selected) { for (Map.Entry<StackNode, Locator> entry : openSingleSelects.entrySet()) { StackNode node = entry.getKey(); if (node.isSelectedOptions()) { err("The \u201Cselect\u201D element cannot have more than one selected \u201Coption\u201D descendant unless the \u201Cmultiple\u201D attribute is specified."); } else { node.setSelectedOptions(); } } } if ("meta" == localName) { if (lowerCaseLiteralEqualsIgnoreAsciiCaseString( "content-language", atts.getValue("", "http-equiv"))) { err("Using the \u201Cmeta\u201D element to specify the" + " document-wide default language is obsolete." + " Consider specifying the language on the root" + " element instead."); } else if (lowerCaseLiteralEqualsIgnoreAsciiCaseString( "x-ua-compatible", atts.getValue("", "http-equiv")) && !lowerCaseLiteralEqualsIgnoreAsciiCaseString( "ie=edge", atts.getValue("", "content"))) { err("A \u201Cmeta\u201D element with an" + " \u201Chttp-equiv\u201D attribute whose value is" + " \u201CX-UA-Compatible\u201D" + " must have a" + " \u201Ccontent\u201D attribute with the value" + " \u201CIE=edge\u201D."); } } // microdata if (itemid && !(itemscope && itemtype)) { err("The \u201Citemid\u201D attribute must not be specified on elements that do not have both an \u201Citemscope\u201D attribute and an \u201Citemtype\u201D attribute specified."); } if (itemref && !itemscope) { err("The \u201Citemref\u201D attribute must not be specified on elements that do not have an \u201Citemscope\u201D attribute specified."); } if (itemtype && !itemscope) { err("The \u201Citemtype\u201D attribute must not be specified on elements that do not have an \u201Citemscope\u201D attribute specified."); } } else { int len = atts.getLength(); for (int i = 0; i < len; i++) { if (atts.getType(i) == "ID") { String attVal = atts.getValue(i); if (attVal.length() != 0) { ids.add(attVal); } } String attLocal = atts.getLocalName(i); if (atts.getURI(i).length() == 0) { if ("role" == attLocal) { role = atts.getValue(i); } else if ("aria-activedescendant" == attLocal) { activeDescendant = atts.getValue(i); } else if ("aria-owns" == attLocal) { owns = atts.getValue(i); } } } allIds.addAll(ids); } // ARIA required owner/ancestors Set<String> requiredAncestorRoles = REQUIRED_ROLE_ANCESTOR_BY_DESCENDANT.get(role); if (requiredAncestorRoles != null && !"presentation".equals(parentRole) && !"tbody".equals(localName) && !"tfoot".equals(localName) && !"thead".equals(localName)) { if (!currentElementHasRequiredAncestorRole(requiredAncestorRoles)) { if (atts.getIndex("", "id") > -1 && !"".equals(atts.getValue("", "id"))) { needsAriaOwner.add(new IdrefLocator(new LocatorImpl( getDocumentLocator()), atts.getValue("", "id"), role)); } else { errContainedInOrOwnedBy(role, getDocumentLocator()); } } } // ARIA IDREFS for (String att : MUST_NOT_DANGLE_IDREFS) { String attVal = atts.getValue("", att); if (attVal != null) { String[] tokens = AttributeUtil.split(attVal); for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; ariaReferences.add(new IdrefLocator(getDocumentLocator(), token, att)); } } } allIds.addAll(ids); // aria-activedescendant accompanied by aria-owns if (activeDescendant != null && !"".equals(activeDescendant)) { // String activeDescendantVal = atts.getValue("", // "aria-activedescendant"); if (owns != null && !"".equals(owns)) { activeDescendantWithAriaOwns = true; // String[] tokens = AttributeUtil.split(owns); // for (int i = 0; i < tokens.length; i++) { // String token = tokens[i]; // if (token.equals(activeDescendantVal)) { // activeDescendantWithAriaOwns = true; // break; } } // activedescendant for (Iterator<Map.Entry<StackNode, Locator>> iterator = openActiveDescendants.entrySet().iterator(); iterator.hasNext();) { Map.Entry<StackNode, Locator> entry = iterator.next(); if (ids.contains(entry.getKey().getActiveDescendant())) { iterator.remove(); } } if ("http: int number = specialAncestorNumber(localName); if (number > -1) { ancestorMask |= (1 << number); } if ("a" == localName && href) { ancestorMask |= HREF_MASK; } StackNode child = new StackNode(ancestorMask, localName, role, activeDescendant, forAttr); if (activeDescendant != null && !activeDescendantWithAriaOwns) { openActiveDescendants.put(child, new LocatorImpl( getDocumentLocator())); } if ("select" == localName && atts.getIndex("", "multiple") == -1) { openSingleSelects.put(child, getDocumentLocator()); } else if ("label" == localName) { openLabels.put(child, new LocatorImpl(getDocumentLocator())); } else if ("video" == localName || "audio" == localName ) { openMediaElements.put(child, new TaintableLocatorImpl(getDocumentLocator())); } push(child); if ("select" == localName && atts.getIndex("", "required") > -1 && atts.getIndex("", "multiple") < 0) { if (atts.getIndex("", "size") > -1) { String size = trimSpaces(atts.getValue("", "size")); if (!"".equals(size)) { try { if ((size.length() > 1 && size.charAt(0) == '+' && Integer.parseInt(size.substring(1)) == 1) || Integer.parseInt(size) == 1) { child.setOptionNeeded(); } else { // do nothing } } catch (NumberFormatException e) { } } } else { // default size is 1 child.setOptionNeeded(); } } } else { StackNode child = new StackNode(ancestorMask, null, role, activeDescendant, forAttr); if (activeDescendant != null) { openActiveDescendants.put(child, new LocatorImpl( getDocumentLocator())); } push(child); } stack[currentPtr].setLocator(new LocatorImpl( getDocumentLocator())); } /** * @see nu.validator.checker.Checker#characters(char[], int, int) */ @Override public void characters(char[] ch, int start, int length) throws SAXException { StackNode node = peek(); for (int i = start; i < start + length; i++) { char c = ch[i]; switch (c) { case ' ': case '\t': case '\r': case '\n': continue; default: if ("h1".equals(node.name) || "h2".equals(node.name) || "h3".equals(node.name) || "h4".equals(node.name) || "h5".equals(node.name) || "h6".equals(node.name) || (node.ancestorMask & H1_MASK) != 0 || (node.ancestorMask & H2_MASK) != 0 || (node.ancestorMask & H3_MASK) != 0 || (node.ancestorMask & H4_MASK) != 0 || (node.ancestorMask & H5_MASK) != 0 || (node.ancestorMask & H6_MASK) != 0) { stack[currentHeadingPtr].setTextNodeFound(); } else if ("figcaption".equals(node.name) || (node.ancestorMask & FIGCAPTION_MASK) != 0) { if ((node.ancestorMask & FIGURE_MASK) != 0) { stack[currentFigurePtr].setFigcaptionContentFound(); } // for any ancestor figures of the parent figure // of this figcaption, the content of this // figcaption counts as a text node descendant for (int j = 1; j < currentFigurePtr; j++) { if ("figure".equals(stack[currentFigurePtr - j].getName())) { stack[currentFigurePtr - j].setTextNodeFound(); } } } else if ("figure".equals(node.name) || (node.ancestorMask & FIGURE_MASK) != 0) { stack[currentFigurePtr].setTextNodeFound(); // for any ancestor figures of this figure, this // also counts as a text node descendant for (int k = 1; k < currentFigurePtr; k++) { if ("figure".equals(stack[currentFigurePtr - k].getName())) { stack[currentFigurePtr - k].setTextNodeFound(); } } } else if ("option".equals(node.name) && !stack[currentPtr - 1].hasOption() && (!stack[currentPtr - 1].hasEmptyValueOption() || stack[currentPtr - 1].hasNoValueOption()) && stack[currentPtr - 1].nonEmptyOptionLocator() == null) { stack[currentPtr - 1].setNonEmptyOption((new LocatorImpl( getDocumentLocator()))); } return; } } } private CharSequence renderRoleSet(Set<String> roles) { boolean first = true; StringBuilder sb = new StringBuilder(); for (String role : roles) { if (first) { first = false; } else { sb.append(" or "); } sb.append("\u201Crole="); sb.append(role); sb.append('\u201D'); } return sb; } }
package org.komamitsu.fluency.sender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; public class TCPSender extends Sender<TCPSender.Config> { private static final Logger LOG = LoggerFactory.getLogger(TCPSender.class); private static final Charset CHARSET_FOR_ERRORLOG = Charset.forName("UTF-8"); private final AtomicReference<SocketChannel> channel = new AtomicReference<SocketChannel>(); private final byte[] optionBuffer = new byte[256]; private final AckTokenSerDe ackTokenSerDe = new MessagePackAckTokenSerDe(); private final ExecutorService executorService = Executors.newSingleThreadExecutor(); public String getHost() { return config.getHost(); } public int getPort() { return config.getPort(); } public TCPSender(Config config) { super(config); } private SocketChannel getOrOpenChannel() throws IOException { if (channel.get() == null) { SocketChannel socketChannel = SocketChannel.open(); socketChannel.socket().connect(new InetSocketAddress(config.getHost(), config.getPort()), config.getConnectionTimeoutMilli()); socketChannel.socket().setTcpNoDelay(true); socketChannel.socket().setSoTimeout(config.getReadTimeoutMilli()); channel.set(socketChannel); } return channel.get(); } private synchronized void sendBuffers(List<ByteBuffer> dataList) throws IOException { try { LOG.trace("send(): sender.host={}, sender.port={}", getHost(), getPort()); getOrOpenChannel().write(dataList.toArray(new ByteBuffer[dataList.size()])); } catch (IOException e) { close(); throw e; } } @Override protected synchronized void sendInternal(List<ByteBuffer> dataList, byte[] ackToken) throws IOException { ArrayList<ByteBuffer> buffers = new ArrayList<ByteBuffer>(); buffers.addAll(dataList); if (ackToken != null) { buffers.add(ByteBuffer.wrap(ackTokenSerDe.pack(ackToken))); } sendBuffers(buffers); if (ackToken == null) { return; } // For ACK response mode final ByteBuffer byteBuffer = ByteBuffer.wrap(optionBuffer); try { Future<Void> future = executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { getOrOpenChannel().read(byteBuffer); return null; } }); try { future.get(config.getReadTimeoutMilli(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new IOException("InterruptedException occurred", e); } catch (ExecutionException e) { throw new IOException("ExecutionException occurred", e); } catch (TimeoutException e) { throw new SocketTimeoutException("Socket read timeout"); } byte[] unpackedToken = ackTokenSerDe.unpack(optionBuffer); if (!Arrays.equals(ackToken, unpackedToken)) { throw new UnmatchedAckException("Ack tokens don't matched: expected=" + new String(ackToken, CHARSET_FOR_ERRORLOG) + ", got=" + new String(unpackedToken, CHARSET_FOR_ERRORLOG)); } } catch (IOException e) { close(); throw e; } } @Override public synchronized void close() throws IOException { SocketChannel socketChannel; if ((socketChannel = channel.getAndSet(null)) != null) { socketChannel.close(); channel.set(null); } } @Override public String toString() { return "TCPSender{" + "config=" + config + '}'; } public static class UnmatchedAckException extends IOException { public UnmatchedAckException(String message) { super(message); } } public static class Config extends Sender.Config<TCPSender, Config> { private String host = "127.0.0.1"; private int port = 24224; private int connectionTimeoutMilli = 5000; private int readTimeoutMilli = 5000; public String getHost() { return host; } public Config setHost(String host) { this.host = host; return this; } public int getPort() { return port; } public Config setPort(int port) { this.port = port; return this; } public int getConnectionTimeoutMilli() { return connectionTimeoutMilli; } public Config setConnectionTimeoutMilli(int connectionTimeoutMilli) { this.connectionTimeoutMilli = connectionTimeoutMilli; return this; } public int getReadTimeoutMilli() { return readTimeoutMilli; } public Config setReadTimeoutMilli(int readTimeoutMilli) { this.readTimeoutMilli = readTimeoutMilli; return this; } @Override public TCPSender createInstance() { return new TCPSender(this); } @Override public String toString() { return "Config{" + "host='" + host + '\'' + ", port=" + port + ", connectionTimeoutMilli=" + connectionTimeoutMilli + ", readTimeoutMilli=" + readTimeoutMilli + '}'; } } }
package org.kumoricon.view.role; import com.vaadin.data.fieldgroup.BeanFieldGroup; import com.vaadin.data.util.BeanItem; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.server.FontAwesome; import com.vaadin.ui.*; import org.kumoricon.model.role.Right; import org.kumoricon.model.role.Role; import org.kumoricon.presenter.role.RolePresenter; import org.kumoricon.util.FieldFactory; import java.util.List; import java.util.Set; public class RoleEditWindow extends Window { private TextField name = FieldFactory.createTextField("Name"); private TwinColSelect rightsList = new TwinColSelect("Rights"); private Button btnSave = new Button("Save"); private Button btnCancel = new Button("Cancel"); private BeanFieldGroup<Role> roleBeanFieldGroup = new BeanFieldGroup<>(Role.class); private RolePresenter handler; private RoleView parentView; public RoleEditWindow(RoleView parentView, RolePresenter rolePresenter, List<Right> rights) { super("Edit Role"); this.handler = rolePresenter; this.parentView = parentView; setIcon(FontAwesome.GROUP); center(); setModal(true); setResizable(false); setWidth(700, Unit.PIXELS); rightsList.setContainerDataSource(new BeanItemContainer<>(Right.class, rights)); FormLayout form = new FormLayout(); form.setMargin(true); form.setSpacing(true); roleBeanFieldGroup.bind(name, "name"); form.addComponent(name); rightsList.setLeftColumnCaption("Available Rights"); rightsList.setRightColumnCaption("Granted Rights"); rightsList.setImmediate(true); rightsList.setSizeFull(); form.addComponent(rightsList); HorizontalLayout buttons = new HorizontalLayout(); buttons.setSpacing(true); buttons.addComponent(btnSave); buttons.addComponent(btnCancel); form.addComponent(buttons); btnCancel.addClickListener((Button.ClickListener) clickEvent -> handler.cancel(this)); btnSave.addClickListener((Button.ClickListener) clickEvent -> { try { roleBeanFieldGroup.commit(); handler.saveRole(this, getRole()); } catch (Exception e) { parentView.notifyError(e.getMessage()); } }); setContent(form); } public Role getRole() { BeanItem<Role> roleBean = roleBeanFieldGroup.getItemDataSource(); Role role = roleBean.getBean(); role.clearRights(); role.addRights((Set<Right>)rightsList.getValue()); return role; } public void showRole(Role role) { roleBeanFieldGroup.setItemDataSource(role); for (Right r : role.getRights()) { rightsList.select(r); } name.selectAll(); } public RolePresenter getHandler() { return handler; } public void setHandler(RolePresenter handler) { this.handler = handler; } public RoleView getParentView() { return parentView; } }
package it.unitn.disi.smatch.loaders.context; import it.unitn.disi.smatch.components.ConfigurableException; import it.unitn.disi.smatch.data.trees.Context; import it.unitn.disi.smatch.data.trees.IContext; import it.unitn.disi.smatch.data.trees.INode; import it.unitn.disi.smatch.loaders.ILoader; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.semanticweb.HermiT.Reasoner; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.skos.SKOSConcept; import org.semanticweb.skos.SKOSCreationException; import org.semanticweb.skos.SKOSDataset; import org.semanticweb.skos.SKOSLiteral; import org.semanticweb.skos.properties.SKOSAltLabelProperty; import org.semanticweb.skos.properties.SKOSPrefLabelProperty; import org.semanticweb.skosapibinding.SKOSManager; import org.semanticweb.skosapibinding.SKOSReasoner; import java.util.*; /** * Loads a context from a SKOS file using SKOS API (based on OWL API) and HermiT reasoner. * Takes in a preferredLanguage parameter, which defines the language which should be preferred for labels. * If specified, the loader will search for the label in the specified language among preferred labels and then among * alternative labels. * * @author Aliaksandr Autayeu avtaev@gmail.com */ public class SKOSLoader extends BaseContextLoader implements IContextLoader { private static final Logger log = Logger.getLogger(SKOSLoader.class); // which language to load, default "" - load anything private static final String PREFERRED_LANGUAGE_KEY = "preferredLanguage"; private String preferredLanguage = ""; @Override public boolean setProperties(Properties newProperties) throws ConfigurableException { boolean result = super.setProperties(newProperties); if (result) { if (newProperties.containsKey(PREFERRED_LANGUAGE_KEY)) { preferredLanguage = newProperties.getProperty(PREFERRED_LANGUAGE_KEY); } } return result; } public IContext loadContext(String fileName) throws ContextLoaderException { IContext result = new Context(); try { SKOSManager manager = new SKOSManager(); SKOSDataset dataSet = manager.loadDatasetFromPhysicalIRI(IRI.create(fileName)); SKOSReasoner reasoner = new SKOSReasoner(manager, new Reasoner.ReasonerFactory()); reasoner.loadDataset(dataSet); reasoner.classify(); // IRI - INode Map<String, INode> conceptNode = new HashMap<String, INode>(); Set<SKOSConcept> skosConcepts = reasoner.getSKOSConcepts(); if (log.isEnabledFor(Level.INFO)) { log.info("Loaded SKOS concepts: " + skosConcepts.size()); } int unlabeledNodeCount = 0; // create a node for each class for (SKOSConcept concept : skosConcepts) { if (log.isEnabledFor(Level.DEBUG)) { log.debug("Importing: " + concept.getIRI()); } String nodeName = ""; // get a node name from pref labels SKOSPrefLabelProperty prefLabelProperty = manager.getSKOSDataFactory().getSKOSPrefLabelProperty(); for (SKOSLiteral literal : concept.getSKOSRelatedConstantByProperty(dataSet, prefLabelProperty)) { if ("".equals(preferredLanguage)) { nodeName = literal.getLiteral(); break; } else { if (preferredLanguage.equals(literal.getAsSKOSUntypedLiteral().getLang())) { nodeName = literal.getLiteral(); break; } } } // get a node name from alt labels if ("".equals(nodeName)) { SKOSAltLabelProperty altLabelProperty = manager.getSKOSDataFactory().getSKOSAltLabelProperty(); for (SKOSLiteral literal : concept.getSKOSRelatedConstantByProperty(dataSet, altLabelProperty)) { if ("".equals(preferredLanguage)) { nodeName = literal.getLiteral(); break; } else { if (preferredLanguage.equals(literal.getAsSKOSUntypedLiteral().getLang())) { nodeName = literal.getLiteral(); break; } } } } if ("".equals(nodeName)) { unlabeledNodeCount++; if (log.isEnabledFor(Level.WARN)) { log.warn("Label is not found in language " + preferredLanguage + " for a concept: " + concept.getIRI()); log.warn("Creating unlabeled node..."); } } else { if (log.isEnabledFor(Level.DEBUG)) { log.debug("Creating a node: " + nodeName); } } INode node = result.createNode(nodeName); node.getNodeData().setProvenance(concept.getIRI().toString()); node.setUserObject(concept); conceptNode.put(concept.getIRI().toString(), node); nodesParsed++; } if (0 < unlabeledNodeCount) { if (log.isEnabledFor(Level.INFO)) { log.info("Created unlabeled nodes: " + unlabeledNodeCount); } } if (log.isEnabledFor(Level.INFO)) { log.info("Creating hierarchy via BTs..."); } int countBT = 0; int linksCreated = 0; // create hierarchy via BTs for (Map.Entry<String, INode> e : conceptNode.entrySet()) { String conceptIRI = e.getKey(); INode child = e.getValue(); if (log.isEnabledFor(Level.DEBUG)) { log.debug("Creating hierarchy: " + child.getNodeData().getName() + ": " + conceptIRI); } Set<SKOSConcept> parents = reasoner.getSKOSBroaderConcepts(dataSet.getSKOSEntity(conceptIRI).asSKOSConcept()); countBT = countBT + parents.size(); // there can be multiple BTs // either discard, or duplicate the subtree in two places // discard for now all but one if (1 < parents.size()) { if (log.isEnabledFor(Level.WARN)) { log.warn("Multiple BTs are found for the concept: " + conceptIRI); } } if (parents.iterator().hasNext()) { SKOSConcept parentConcept = parents.iterator().next(); INode parentNode = conceptNode.get(parentConcept.getIRI().toString()); if (log.isEnabledFor(Level.DEBUG)) { log.debug("Choosing as a parent BT: " + parentConcept.getIRI()); log.debug(child.getNodeData().getName() + " -> BT -> " + parentNode.getNodeData().getName()); } parentNode.addChild(child); linksCreated++; } } if (log.isEnabledFor(Level.INFO)) { log.info("Encountered BTs: " + countBT); log.info("Parent-child relations established: " + linksCreated); log.info("Creating hierarchy via NTs..."); } int countNT = 0; linksCreated = 0; // create hierarchy via NTs for (Map.Entry<String, INode> e : conceptNode.entrySet()) { String conceptIRI = e.getKey(); INode parent = e.getValue(); if (log.isEnabledFor(Level.DEBUG)) { log.debug("Creating hierarchy: " + parent.getNodeData().getName() + ": " + conceptIRI); } Set<SKOSConcept> children = reasoner.getSKOSNarrowerConcepts(dataSet.getSKOSEntity(conceptIRI).asSKOSConcept()); countNT = countNT + children.size(); for (SKOSConcept childConcept : children) { INode child = conceptNode.get(childConcept.getIRI().toString()); // there can be multiple BTs // either discard, or duplicate the subtree in two places // discard for now all but one if (child.hasParent()) { if (log.isEnabledFor(Level.WARN)) { log.warn("Keeping previously set parent: child: " + child.getNodeData().getName() + " -> parent: " + child.getParent().getNodeData().getName()); log.warn("Multiple BTs are found for the concept: " + conceptIRI); } } else { if (log.isEnabledFor(Level.DEBUG)) { log.debug("Choosing as a parent BT: " + conceptIRI); log.debug(parent.getNodeData().getName() + " -> NT -> " + child.getNodeData().getName()); } int childIndex = parent.getChildIndex(child); if (-1 == childIndex) { parent.addChild(child); linksCreated++; } else { if (log.isEnabledFor(Level.WARN)) { log.warn("Child already exist under this parent: " + parent.getNodeData().getName() + " -> child -> " + child.getNodeData().getName()); log.warn("Duplicated NT or label: " + conceptIRI + " -> NT -> " + childConcept.getIRI()); } } } } } if (log.isEnabledFor(Level.INFO)) { log.info("Encountered NTs: " + countNT); log.info("Parent-child relations established: " + linksCreated); } if (log.isEnabledFor(Level.INFO)) { log.info("Checking multiple roots..."); } // check multiple roots Set<INode> roots = new HashSet<INode>(); for (SKOSConcept concept : skosConcepts) { INode node = conceptNode.get(concept.getIRI().toString()); if (!node.hasParent()) { roots.add(node); } } if (log.isEnabledFor(Level.WARN)) { log.warn("Found root nodes: " + roots.size()); if (log.isEnabledFor(Level.DEBUG)) { for (INode r : roots) { log.debug("Root: " + r.getNodeData().getName()); } } } if (1 < roots.size()) { if (log.isEnabledFor(Level.WARN)) { log.warn("Found multiple roots. Creating artificial root: Top"); } // create artificial Top root INode root = result.createRoot("Top"); // put every other top one under it for (INode r : roots) { root.addChild(r); } } else { if (1 == roots.size()) { result.setRoot(roots.iterator().next()); } else { throw new ContextLoaderException("Cannot find even one root."); } } createIds(result); log.info("Parsed nodes: " + nodesParsed); } catch (SKOSCreationException e) { final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage(); log.error(errMessage, e); throw new ContextLoaderException(errMessage, e); } return result; } public String getDescription() { return ILoader.SKOS_FILES; } public ILoader.LoaderType getType() { return ILoader.LoaderType.FILE; } }
package com.hypirion.beckon; import sun.misc.Signal; import sun.misc.SignalHandler; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.HashSet; import java.util.concurrent.Callable; import clojure.lang.PersistentList; public class SignalRegistererHelper { /** * A set of modified signal handlers. */ private final static Set<String> modifiedHandlers = new HashSet<String>(); /** * Registers the new list of functions to the signal name, and returns the * old SignalHandler. */ private static SignalHandler setHandler(String signame, List fns) { Signal sig = new Signal(signame); SignalFolder folder = new SignalFolder(fns); SignalHandler oldHandler = Signal.handle(sig, folder); return oldHandler; } /** * Registers the signal name to a List of Callables, where each callable * returns an Object. The signal handling is performed as follows: The first * callable is called, and if it returns a value equal to <code>false</code> * or <code>null</code> it will stop. Otherwise it will repeat on the next * callable, until there are no more left. * * @param signame the signal name to register this list of callables on. * @param fns the list of Callables to (potentially) call. */ static synchronized void register(String signame, List fns) { SignalHandler old = setHandler(signame, fns); modifiedHandlers.add(signame); } /** * Resets/reinits the signal to be handled by its original signal handler. * * @param signame the name of the signal to reinit. */ static synchronized void resetDefaultHandler(String signame) { if (modifiedHandlers.contains(signame)) { SignalHandler original = SignalHandler.SIG_DFL; Signal sig = new Signal(signame); Signal.handle(sig, original); modifiedHandlers.remove(sig); SignalAtoms.getSignalAtom(signame).reset(getHandlerList(signame)); } } /** * Resets/reinits all the signals back to their original signal handlers, * discarding all possible changes done to them. */ static synchronized void resetAll() { // To get around the fact that we cannot remove elements from a set // while iterating over it. List<String> signames = new ArrayList<String>(modifiedHandlers); for (String signame : signames) { resetDefaultHandler(signame); } } /** * Returns a list of Callables which is used within the SignalFolder * handling the Signal, or a PersistentList with a Callable SignalHandler if * the SignalHandler is not a SignalFolder. * * @param signame The name of the Signal. * * @return A list with the Callables used in the SignalFolder. */ static synchronized List getHandlerList(String signame) { Signal sig = new Signal(signame); // Urgh, no easy way to get current signal handler. // Double-handle to get current one without issues. SignalHandler current = Signal.handle(sig, SignalHandler.SIG_DFL); Signal.handle(sig, current); if (current instanceof SignalFolder) { return ((SignalFolder)current).originalList; } else { Callable<Boolean> wrappedHandler = new CallableSignalHandler(sig, current); return new PersistentList(wrappedHandler); } } /** * A Callable SignalHandler is simply a Callable which wraps a * SignalHandler. This is used internally to ensure that people can perform * <code>swap!</code> in Clojure programs without worrying that the default * SignalHandler will cause issues as it's not Callable by default. */ private static class CallableSignalHandler implements Callable<Boolean> { private final Signal sig; private final SignalHandler handler; /** * Returns a Callable which will call <code>handler.handle(sig)</code> * whenever called. */ CallableSignalHandler(Signal sig, SignalHandler handler) { this.sig = sig; this.handler = handler; } /** * Calls the SignalHandler with the signal provided at construction, and * returns true if the handler doesn't cast any exception. If the * handler cast an exception, false is returned, and if the handler * casts an error, that error is cast. * * @return true if the handler doesn't throw an exception, false * otherwise. */ @Override public Boolean call() { try { handler.handle(sig); return true; } catch (Exception e) { // Not throwable, will still die on errors. return false; } } } }
package org.mariadb.jdbc; import javax.sql.*; import java.sql.Statement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class MySQLPooledConnection implements PooledConnection{ MySQLConnection connection; List<ConnectionEventListener> connectionEventListeners; List<StatementEventListener> statementEventListeners; public MySQLPooledConnection(MySQLConnection connection) { this.connection = connection; connection.pooledConnection = this; statementEventListeners = new ArrayList<StatementEventListener>(); connectionEventListeners = new ArrayList<ConnectionEventListener>(); } /** * Creates and returns a <code>Connection</code> object that is a handle * for the physical connection that * this <code>PooledConnection</code> object represents. * The connection pool manager calls this method when an application has * called the method <code>DataSource.getConnection</code> and there are * no <code>PooledConnection</code> objects available. See the * {@link javax.sql.PooledConnection interface description} for more information. * * @return a <code>Connection</code> object that is a handle to * this <code>PooledConnection</code> object * @throws java.sql.SQLException if a database access error occurs * if the JDBC driver does not support * this method * @since 1.4 */ public Connection getConnection() throws SQLException { return connection; } /** * Closes the physical connection that this <code>PooledConnection</code> * object represents. An application never calls this method directly; * it is called by the connection pool module, or manager. * <p/> * See the {@link javax.sql.PooledConnection interface description} for more * information. * * @throws java.sql.SQLException if a database access error occurs * if the JDBC driver does not support * this method * @since 1.4 */ public void close() throws SQLException { connection.pooledConnection = null; connection.close(); } /** * Registers the given event listener so that it will be notified * when an event occurs on this <code>PooledConnection</code> object. * * @param listener a component, usually the connection pool manager, * that has implemented the * <code>ConnectionEventListener</code> interface and wants to be * notified when the connection is closed or has an error * @see #removeConnectionEventListener */ public void addConnectionEventListener(ConnectionEventListener listener) { connectionEventListeners.add(listener); } /** * Removes the given event listener from the list of components that * will be notified when an event occurs on this * <code>PooledConnection</code> object. * * @param listener a component, usually the connection pool manager, * that has implemented the * <code>ConnectionEventListener</code> interface and * been registered with this <code>PooledConnection</code> object as * a listener * @see #addConnectionEventListener */ public void removeConnectionEventListener(ConnectionEventListener listener) { connectionEventListeners.remove(listener); } public void addStatementEventListener(StatementEventListener listener) { statementEventListeners.add(listener); } /** * Removes the specified <code>StatementEventListener</code> from the list of * components that will be notified when the driver detects that a * <code>PreparedStatement</code> has been closed or is invalid. * <p/> * * @param listener the component which implements the * <code>StatementEventListener</code> interface that was previously * registered with this <code>PooledConnection</code> object * <p/> * @since 1.6 */ public void removeStatementEventListener(StatementEventListener listener) { statementEventListeners.remove(listener); } public void fireStatementClosed(Statement st) { if (st instanceof PreparedStatement) { StatementEvent event = new StatementEvent(this, (PreparedStatement)st); for(StatementEventListener listener:statementEventListeners) listener.statementClosed(event); } } public void fireStatementErrorOccured(Statement st, SQLException e) { if (st instanceof PreparedStatement) { StatementEvent event = new StatementEvent(this,(PreparedStatement) st,e); for(StatementEventListener listener:statementEventListeners) listener.statementErrorOccurred(event); } } public void fireConnectionClosed() { ConnectionEvent event = new ConnectionEvent(this); CopyOnWriteArrayList<ConnectionEventListener> copyListeners = new CopyOnWriteArrayList<ConnectionEventListener>(connectionEventListeners); for(ConnectionEventListener listener: copyListeners) listener.connectionClosed(event); } public void fireConnectionErrorOccured(SQLException e) { ConnectionEvent event = new ConnectionEvent(this,e); for(ConnectionEventListener listener: connectionEventListeners) listener.connectionErrorOccurred(event); } }
package org.eclipse.oomph.setup.ui; import org.eclipse.oomph.preferences.util.PreferencesUtil; import org.eclipse.oomph.setup.VariableChoice; import org.eclipse.oomph.setup.VariableTask; import org.eclipse.oomph.setup.VariableType; import org.eclipse.oomph.setup.internal.core.SetupCorePlugin; import org.eclipse.oomph.setup.internal.core.util.Authenticator; import org.eclipse.oomph.util.ConcurrentArray; import org.eclipse.oomph.util.StringUtil; import org.eclipse.emf.common.ui.dialogs.WorkspaceResourceDialog; import org.eclipse.emf.ecore.plugin.EcorePlugin; import org.eclipse.core.resources.IContainer; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * @author Eike Stepper */ public abstract class PropertyField { public static final int NUM_COLUMNS = 3; private static final String EMPTY = ""; public static PropertyField createField(final VariableTask variable) { PropertyField field = createField(variable.getType(), variable.getChoices()); String label = variable.getLabel(); if (StringUtil.isEmpty(label)) { label = variable.getName(); } field.setLabelText(label); field.setToolTip(variable.getDescription()); GridData gridData = field.getLabelGridData(); gridData.widthHint = 150; return field; } public static PropertyField createField(VariableType type, List<? extends VariableChoice> choices) { switch (type) { case FOLDER: PropertyField.FileField fileField = new FileField(choices); fileField.setDialogText("Folder Selection"); fileField.setDialogMessage("Select a folder."); return fileField; case CONTAINER: PropertyField.ContainerField containerField = new ContainerField(choices); containerField.setDialogText("Folder Selection"); containerField.setDialogMessage("Select a folder."); return containerField; case TEXT: PropertyField.TextField textField = new TextField(choices) { @Override protected Text createText(Composite parent, int style) { return super.createText(parent, style | SWT.MULTI | SWT.V_SCROLL); } }; textField.getControlGridData().heightHint = 50; return textField; case PASSWORD: return new AuthenticatedField(); } return new TextField(choices); } private final GridData labelGridData = new GridData(SWT.RIGHT, SWT.TOP, false, false); private final GridData controlGridData = new GridData(SWT.FILL, SWT.TOP, true, false); private final GridData helperGridData = new GridData(SWT.FILL, SWT.TOP, false, false); private final ValueListenerArray valueListeners = new ValueListenerArray(); private String value = EMPTY; private String labelText; private String toolTip; private Label label; private Control helper; private boolean enabled = true; public PropertyField() { this(null); } public PropertyField(String labelText) { this.labelText = labelText; setValue(null); } @Override public String toString() { return getClass().getSimpleName() + "[label=" + labelText + ", value=" + value + "]"; } public final String getLabelText() { return labelText; } public final void setLabelText(String labelText) { if (labelText.endsWith(":")) { labelText = labelText.substring(0, labelText.length() - 1); } this.labelText = labelText.trim(); } public final String getToolTip() { return toolTip; } public final void setToolTip(String toolTip) { this.toolTip = toolTip; } public final String getValue() { return value; } public final void setValue(String value) { setValue(value, true); } public final void setValue(String value, boolean notify) { if (value == null) { value = EMPTY; } String oldValue = this.value; if (!oldValue.equals(value)) { this.value = value; String controlValue = getControlValue(); if (!controlValue.equals(value)) { transferValueToControl(value); } if (notify) { notifyValueListeners(oldValue, value); } } } public final void addValueListener(ValueListener listener) { if (listener == null) { throw new IllegalArgumentException("listener is null"); //$NON-NLS-1$ } valueListeners.add(listener); } public final void removeValueListener(ValueListener listener) { if (listener == null) { throw new IllegalArgumentException("listener is null"); //$NON-NLS-1$ } valueListeners.remove(listener); } public final void fill(final Composite parent) { checkParentLayout(parent); label = new Label(parent, SWT.WRAP); label.setLayoutData(labelGridData); if (labelText != null) { label.setText(labelText + ":"); } Control control = createControl(parent); getMainControl().setLayoutData(controlGridData); if (toolTip != null && toolTip.length() != 0) { label.setToolTipText(toolTip); control.setToolTipText(toolTip); getMainControl().setToolTipText(toolTip); } helper = createHelper(parent); if (helper == null) { helper = new Label(parent, SWT.NONE); } else { helper = getMainHelper(); } helper.setLayoutData(helperGridData); setEnabled(enabled); transferValueToControl(value); } public final Label getLabel() { return label; } public final GridData getLabelGridData() { return labelGridData; } public final GridData getControlGridData() { return controlGridData; } public final Control getHelper() { return helper; } public final GridData getHelperGridData() { return helperGridData; } public final void setFocus() { Control control = getControl(); if (control != null) { control.setFocus(); } } public final boolean isEnabled() { return enabled; } public final void setEnabled(boolean enabled) { this.enabled = enabled; if (label != null) { label.setEnabled(enabled); } setControlEnabled(enabled); Control mainHelper = getMainHelper(); if (mainHelper != null) { mainHelper.setEnabled(enabled); } } protected void setControlEnabled(boolean enabled) { Control mainControl = getMainControl(); if (mainControl != null) { mainControl.setEnabled(enabled); } } protected Control getMainControl() { return getControl(); } protected Control getMainHelper() { return helper; } public abstract Control getControl(); protected abstract String getControlValue(); protected abstract void transferValueToControl(String value); protected abstract Control createControl(Composite parent); protected Control createHelper(Composite parent) { return null; } private void checkParentLayout(Composite parent) { Layout layout = parent.getLayout(); if (layout instanceof GridLayout) { GridLayout gridLayout = (GridLayout)layout; if (gridLayout.numColumns == NUM_COLUMNS) { return; } } throw new IllegalArgumentException("Parent must have a GridLayout with 3 columns"); } private void notifyValueListeners(String oldValue, String newValue) { ValueListener[] listeners = valueListeners.get(); if (listeners != null) { for (int i = 0; i < listeners.length; i++) { ValueListener listener = listeners[i]; try { listener.valueChanged(oldValue, newValue); } catch (Exception ex) { SetupUIPlugin.INSTANCE.log(ex); } } } } /** * @author Eike Stepper */ private static final class ValueListenerArray extends ConcurrentArray<ValueListener> { @Override protected ValueListener[] newArray(int length) { return new ValueListener[length]; } } /** * @author Eike Stepper */ public interface ValueListener { public void valueChanged(String oldValue, String newValue) throws Exception; } /** * @author Eike Stepper */ public static class TextField extends PropertyField { private final boolean secret; private PropertyField linkField; private Composite mainControl; private Text text; private ComboViewer comboViewer; private ToolItem linkButton; private boolean linked = true; private List<? extends VariableChoice> choices; public TextField() { this(null, false); } public TextField(boolean secret) { this(null, secret); } public TextField(String labelText) { this(labelText, false); } public TextField(String labelText, boolean secret) { this(labelText, secret, null); } public TextField(List<? extends VariableChoice> choices) { this(null, choices); } public TextField(String labelText, List<? extends VariableChoice> choices) { this(labelText, false, choices); } private TextField(String labelText, boolean secret, List<? extends VariableChoice> choices) { super(labelText); this.secret = secret; this.choices = choices; } public final PropertyField getLinkField() { return linkField; } public final void setLinkField(PropertyField field) { linkField = field; } public final boolean isLinked() { return linked; } public final void setLinked(boolean linked) { this.linked = linked; if (linkButton != null) { String path = linked ? "linked.gif" : "icons/unlinked"; Image image = SetupUIPlugin.INSTANCE.getSWTImage(path); linkButton.setImage(image); linkButton.setSelection(linked); if (linked) { setLinkedValue(linkField.getValue()); } } } public final void setLinkedFromValue() { String thisValue = getValue(); String linkValue = linkField.getValue(); setLinked(thisValue.length() == 0 && linkValue.length() == 0 || thisValue.equals(computeLinkedValue(thisValue, linkValue))); } @Override protected Control getMainControl() { if (mainControl != null) { return mainControl; } return super.getMainControl(); } @Override public Control getControl() { return text != null ? text : comboViewer.getCombo(); } @Override protected String getControlValue() { return text != null ? secret ? PreferencesUtil.encrypt(text.getText()) : text.getText() : comboViewer.getCombo().getText(); } @Override protected void transferValueToControl(String value) { if (text != null) { text.setText(secret ? PreferencesUtil.decrypt(value) : value); } else { comboViewer.getCombo().setText(value); updateToolTip(value); } } private void updateToolTip(String value) { if (!StringUtil.isEmpty(value)) { for (VariableChoice choice : choices) { if (value.equals(choice.getValue())) { comboViewer.getCombo().setToolTipText(choice.getLabel()); return; } } } String toolTip = getToolTip(); comboViewer.getCombo().setToolTipText(toolTip == null ? "" : toolTip); } @Override protected Control createControl(Composite parent) { if (linkField == null) { return createControlHelper(parent); } GridLayout mainLayout = new GridLayout(2, false); mainLayout.marginWidth = 0; mainLayout.marginHeight = 0; mainLayout.horizontalSpacing = 0; mainControl = new Composite(parent, SWT.NULL) { @Override public void setEnabled(boolean enabled) { if (text != null) { text.setEnabled(enabled); } else { super.setEnabled(enabled); Control[] children = getChildren(); for (int i = 0; i < children.length; i++) { Control child = children[i]; child.setEnabled(enabled); } } } }; mainControl.setLayout(mainLayout); Control control = createControlHelper(mainControl); control.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); ToolBar toolBar = new ToolBar(mainControl, SWT.FLAT | SWT.NO_FOCUS); toolBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); linkButton = new ToolItem(toolBar, SWT.PUSH); linkButton.setToolTipText("Link with the '" + linkField.getLabelText() + "' field"); linkButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setLinked(!linked); } }); linkField.addValueListener(new ValueListener() { public void valueChanged(String oldValue, String newValue) throws Exception { if (linked) { setLinkedValue(newValue); } } }); setLinkedFromValue(); return control; } protected String computeLinkedValue(String thisValue, String linkValue) { return linkValue; } private void setLinkedValue(String newValue) { String thisValue = getValue(); String value = computeLinkedValue(thisValue, newValue); setValue(value); } private Control createControlHelper(Composite parent) { return choices == null || choices.isEmpty() ? createText(parent) : createCombo(parent); } private Text createText(Composite parent) { int style = SWT.BORDER; if (secret) { style |= SWT.PASSWORD; } text = createText(parent, style); String toolTip = getToolTip(); if (toolTip != null) { text.setToolTipText(toolTip); } text.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String value = text.getText(); if (secret) { value = PreferencesUtil.encrypt(value); } if (!value.equals(getValue())) { setValue(value); if (linkButton != null && linked) { setLinkedFromValue(); } } } }); return text; } protected Text createText(Composite parent, int style) { return new Text(parent, style); } protected Combo createCombo(Composite parent) { comboViewer = new ComboViewer(parent, SWT.BORDER); final LabelProvider labelProvider = new LabelProvider() { @Override public String getText(Object element) { VariableChoice choice = (VariableChoice)element; return choice.getLabel(); } }; comboViewer.setLabelProvider(labelProvider); comboViewer.setContentProvider(new ArrayContentProvider()); comboViewer.setInput(choices); comboViewer.getCombo().addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String value = comboViewer.getCombo().getText(); setValue(value); updateToolTip(value); } }); comboViewer.getCombo().addVerifyListener(new VerifyListener() { public void verifyText(VerifyEvent e) { if (e.character == 0) { for (VariableChoice choice : choices) { if (labelProvider.getText(choice).equals(e.text)) { e.text = choice.getValue(); break; } } } } }); Combo control = comboViewer.getCombo(); control.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); return control; } } /** * @author Eike Stepper */ public static class TextButtonField extends TextField { private String buttonText; public TextButtonField() { } public TextButtonField(boolean secret) { super(secret); } public TextButtonField(String labelText) { super(labelText); } public TextButtonField(String labelText, boolean secret) { super(labelText, secret); } public TextButtonField(String labelText, List<? extends VariableChoice> choices) { super(labelText, choices); } public final String getButtonText() { return buttonText; } public final void setButtonText(String buttonText) { this.buttonText = buttonText; } @Override protected Button createHelper(Composite parent) { final Button button = new Button(parent, SWT.NONE); if (buttonText != null) { button.setText(buttonText); } button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { helperButtonSelected(e); } }); return button; } protected void helperButtonSelected(SelectionEvent e) { } } /** * @author Eike Stepper */ public static class FileField extends TextButtonField { private String dialogText; private String dialogMessage; public FileField() { this(null, null); } public FileField(String labelText) { this(labelText, null); } public FileField(List<? extends VariableChoice> choices) { this(null, choices); } public FileField(String labelText, List<? extends VariableChoice> choices) { super(labelText, choices); setButtonText("Browse..."); } public final String getDialogText() { return dialogText; } public final void setDialogText(String dialogText) { this.dialogText = dialogText; } public final String getDialogMessage() { return dialogMessage; } public final void setDialogMessage(String dialogMessage) { this.dialogMessage = dialogMessage; } @Override protected void helperButtonSelected(SelectionEvent e) { Shell shell = getHelper().getShell(); DirectoryDialog dialog = new DirectoryDialog(shell); if (dialogText != null) { dialog.setText(dialogText); } if (dialogMessage != null) { dialog.setMessage(dialogMessage); } String value = getValue(); if (value.length() != 0) { dialog.setFilterPath(value); } String dir = dialog.open(); if (dir != null) { transferValueToControl(dir); } } } /** * @author Ed Merks */ public static class ContainerField extends TextButtonField { private String dialogText; private String dialogMessage; public ContainerField() { this(null, null); } public ContainerField(String labelText) { this(labelText, null); } public ContainerField(List<? extends VariableChoice> choices) { this(null, choices); } public ContainerField(String labelText, List<? extends VariableChoice> choices) { super(labelText, choices); setButtonText("Browse..."); } public final String getDialogText() { return dialogText; } public final void setDialogText(String dialogText) { this.dialogText = dialogText; } public final String getDialogMessage() { return dialogMessage; } public final void setDialogMessage(String dialogMessage) { this.dialogMessage = dialogMessage; } @Override protected void helperButtonSelected(SelectionEvent e) { Shell shell = getHelper().getShell(); Object[] initialSelection = getInitialSelection(); IContainer[] folders = WorkspaceResourceDialog.openFolderSelection(shell, getDialogText(), getDialogMessage(), false, initialSelection, null); if (folders.length > 0) { transferValueToControl(folders[0].getFullPath().toString()); } } private Object[] getInitialSelection() { try { String value = getValue(); if (!StringUtil.isEmpty(value)) { Path path = new Path(value); if (!path.isEmpty()) { if (path.segmentCount() == 1) { return new Object[] { EcorePlugin.getWorkspaceRoot().getProject(path.segment(0)) }; } return new Object[] { EcorePlugin.getWorkspaceRoot().getFolder(path) }; } } } catch (Exception ex) { //$FALL-THROUGH$ } return null; } } /** * @author Ed Merks */ public static class AuthenticatedField extends TextButtonField { private Set<Authenticator> authenticators = new LinkedHashSet<Authenticator>(); public AuthenticatedField() { super(true); setButtonText("Authenticate..."); } public void clear() { authenticators.clear(); getHelper().setEnabled(false); } public void addAll(Set<? extends Authenticator> authenticators) { this.authenticators.addAll(authenticators); getHelper().setEnabled(!this.authenticators.isEmpty()); StringBuilder toolTip = new StringBuilder(); for (Authenticator authenticator : this.authenticators) { if (toolTip.length() != 0) { toolTip.append("\n"); } toolTip.append(authenticator.getMessage(IStatus.INFO)); } ((Button)getHelper()).setToolTipText(toolTip.toString()); } @Override protected void helperButtonSelected(SelectionEvent e) { String pluginID = SetupCorePlugin.INSTANCE.getSymbolicName(); MultiStatus status = new MultiStatus(pluginID, 0, "Authentication Status", null); for (Authenticator authenticator : authenticators) { int severity = authenticator.validate(); status.add(new Status(severity == IStatus.OK ? IStatus.INFO : severity, pluginID, authenticator.getMessage(severity))); } IStatus finalStatus = status; switch (status.getSeverity()) { case IStatus.INFO: { status = new MultiStatus(pluginID, 0, "The password is successfully authenticated", null); status.addAll(finalStatus); break; } case IStatus.WARNING: { status = new MultiStatus(pluginID, 0, "The password cannot be authenticated", null); status.addAll(finalStatus); break; } case IStatus.ERROR: { status = new MultiStatus(pluginID, 0, "The password is invalid", null); status.addAll(finalStatus); break; } } ErrorDialog.openError(getHelper().getShell(), "Authentication Status", null, status); } } public void dispose() { Label label = getLabel(); if (label != null) { label.dispose(); } Control mainControl = getMainControl(); if (mainControl != null) { mainControl.dispose(); } Control mainHelper = getMainHelper(); if (mainHelper != null) { mainHelper.dispose(); } } }
package org.TexasTorque.TexasTorque2013.constants; public class Ports { public static int SIDECAR_ONE = 1; public static int SIDECAR_TWO = 2; public static int DRIVE_CONTROLLER_PORT = 1; public static int OPERATOR_CONTROLLER_PORT = 2; public static int FRONT_LEFT_MOTOR_PORT = 1; public static int MIDDLE_LEFT_MOTOR_PORT = 2; public static int REAR_LEFT_MOTOR_PORT = 3; public static int FRONT_RIGHT_MOTOR_PORT = 4; public static int MIDDLE_RIGHT_MOTOR_PORT = 5; public static int REAR_RIGHT_MOTOR_PORT = 6; public static int FRONT_SHOOTER_MOTOR_PORT = 1; public static int REAR_SHOOTER_MOTOR_PORT = 2; public static int SHIFTERS_FORWARD_PORT = 1; public static int SHIFTERS_REVERSE_PORT = 2; public static int PRESSURE_SWITCH_PORT = 1; public static int LEFT_DRIVE_ENCODER_A_PORT = 2; public static int LEFT_DRIVE_ENCODER_B_PORT = 3; public static int RIGHT_DRIVE_ENCODER_A_PORT = 4; public static int RIGHT_DRIVE_ENCODER_B_PORT = 5; public static int COMPRESSOR_RELAY_PORT = 1; }
package com.opensymphony.workflow; import com.opensymphony.module.propertyset.PropertySet; import com.opensymphony.module.propertyset.PropertySetManager; import com.opensymphony.provider.BeanProvider; import com.opensymphony.provider.bean.DefaultBeanProvider; import com.opensymphony.util.TextUtils; import com.opensymphony.workflow.config.ConfigLoader; import com.opensymphony.workflow.loader.*; import com.opensymphony.workflow.query.WorkflowQuery; import com.opensymphony.workflow.spi.*; import com.opensymphony.workflow.util.beanshell.BeanShellCondition; import com.opensymphony.workflow.util.beanshell.BeanShellFunctionProvider; import com.opensymphony.workflow.util.beanshell.BeanShellRegister; import com.opensymphony.workflow.util.beanshell.BeanShellValidator; import com.opensymphony.workflow.util.bsf.BSFCondition; import com.opensymphony.workflow.util.bsf.BSFFunctionProvider; import com.opensymphony.workflow.util.bsf.BSFRegister; import com.opensymphony.workflow.util.bsf.BSFValidator; import com.opensymphony.workflow.util.ejb.local.LocalEJBCondition; import com.opensymphony.workflow.util.ejb.local.LocalEJBFunctionProvider; import com.opensymphony.workflow.util.ejb.local.LocalEJBRegister; import com.opensymphony.workflow.util.ejb.local.LocalEJBValidator; import com.opensymphony.workflow.util.ejb.remote.RemoteEJBCondition; import com.opensymphony.workflow.util.ejb.remote.RemoteEJBFunctionProvider; import com.opensymphony.workflow.util.ejb.remote.RemoteEJBRegister; import com.opensymphony.workflow.util.ejb.remote.RemoteEJBValidator; import com.opensymphony.workflow.util.jndi.JNDICondition; import com.opensymphony.workflow.util.jndi.JNDIFunctionProvider; import com.opensymphony.workflow.util.jndi.JNDIRegister; import com.opensymphony.workflow.util.jndi.JNDIValidator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.InputStream; import java.net.URL; import java.util.*; /** * Abstract workflow instance that serves as the base for specific implementations, such as EJB or SOAP. * * @author <a href="mailto:plightbo@hotmail.com">Pat Lightbody</a> */ public class AbstractWorkflow implements Workflow { //~ Static fields/initializers ///////////////////////////////////////////// // statics public static final String CLASS_NAME = "class.name"; public static final String EJB_LOCATION = "ejb.location"; public static final String JNDI_LOCATION = "jndi.location"; public static final String BSF_LANGUAGE = "language"; public static final String BSF_SOURCE = "source"; public static final String BSF_ROW = "row"; public static final String BSF_COL = "col"; public static final String BSF_SCRIPT = "script"; public static final String BSH_SCRIPT = "script"; private static final Log log = LogFactory.getLog(AbstractWorkflow.class); protected static boolean configLoaded = false; private static BeanProvider beanProvider = new DefaultBeanProvider(); //~ Instance fields //////////////////////////////////////////////////////// protected WorkflowContext context; //~ Constructors /////////////////////////////////////////////////////////// public AbstractWorkflow() { try { loadConfig(null); } catch (FactoryException e) { throw new InternalWorkflowException("Error loading config", (e.getRootCause() != null) ? e.getRootCause() : e); } } //~ Methods //////////////////////////////////////////////////////////////// /** * @ejb.interface-method * @deprecated use {@link #getAvailableActions(long, Map)} with an empty Map instead. */ public int[] getAvailableActions(long id) throws WorkflowException { return getAvailableActions(id, new HashMap()); } public int[] getAvailableActions(long id, Map inputs) throws WorkflowException { WorkflowStore store = getPersistence(); WorkflowEntry entry = store.findEntry(id); if (entry == null) { throw new IllegalArgumentException("No such workflow id " + id); } if (entry.getState() != WorkflowEntry.ACTIVATED) { log.debug("--> state is " + entry.getState()); return new int[0]; } WorkflowDescriptor wf = getWorkflow(entry.getWorkflowName()); if (wf == null) { throw new IllegalArgumentException("No such workflow " + entry.getWorkflowName()); } List l = new ArrayList(); PropertySet ps = store.getPropertySet(id); Map transientVars = (inputs == null) ? new HashMap() : new HashMap(inputs); populateTransientMap(entry, transientVars, wf.getRegisters()); // get global actions List globalActions = wf.getGlobalActions(); for (Iterator iterator = globalActions.iterator(); iterator.hasNext();) { ActionDescriptor action = (ActionDescriptor) iterator.next(); RestrictionDescriptor restriction = action.getRestriction(); String conditionType = null; List conditions = null; if (restriction != null) { conditionType = restriction.getConditionType(); conditions = restriction.getConditions(); } if (passesConditions(conditionType, conditions, transientVars, ps)) { l.add(new Integer(action.getId())); } } // get normal actions Collection currentSteps = store.findCurrentSteps(id); for (Iterator iterator = currentSteps.iterator(); iterator.hasNext();) { Step step = (Step) iterator.next(); l.addAll(getAvailableActionsForStep(wf, step, transientVars, ps)); } int[] actions = new int[l.size()]; for (int i = 0; i < actions.length; i++) { actions[i] = ((Integer) l.get(i)).intValue(); } return actions; } /** * @ejb.interface-method */ public List getCurrentSteps(long id) throws StoreException { WorkflowStore store = getPersistence(); return store.findCurrentSteps(id); } /** * @ejb.interface-method */ public int getEntryState(long id) throws StoreException { WorkflowStore store = getPersistence(); return store.findEntry(id).getState(); } /** * @ejb.interface-method */ public List getHistorySteps(long id) throws StoreException { WorkflowStore store = getPersistence(); return store.findHistorySteps(id); } /** * @ejb.interface-method */ public Properties getPersistenceProperties() { Properties p = new Properties(); Iterator iter = ConfigLoader.persistenceArgs.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); p.setProperty((String) entry.getKey(), (String) entry.getValue()); } return p; } /** * Get the PropertySet for the specified workflow ID * @ejb.interface-method * @param id The workflow ID */ public PropertySet getPropertySet(long id) throws StoreException { PropertySet ps = getPersistence().getPropertySet(id); return ps; } /** * @ejb.interface-method */ public List getSecurityPermissions(long id) throws WorkflowException { WorkflowStore store = getPersistence(); WorkflowEntry entry = store.findEntry(id); WorkflowDescriptor wf = getWorkflow(entry.getWorkflowName()); PropertySet ps = store.getPropertySet(id); Map transientVars = new HashMap(); populateTransientMap(entry, transientVars, wf.getRegisters()); List s = new ArrayList(); Collection currentSteps = store.findCurrentSteps(id); for (Iterator interator = currentSteps.iterator(); interator.hasNext();) { Step step = (Step) interator.next(); int stepId = step.getStepId(); StepDescriptor xmlStep = wf.getStep(stepId); List securities = xmlStep.getPermissions(); for (Iterator iterator2 = securities.iterator(); iterator2.hasNext();) { PermissionDescriptor security = (PermissionDescriptor) iterator2.next(); // securities can't have restrictions based on inputs, so it's null if (passesConditions(security.getRestriction().getConditionType(), security.getRestriction().getConditions(), transientVars, ps)) { s.add(security.getName()); } } } return s; } /** * @ejb.interface-method */ public WorkflowDescriptor getWorkflowDescriptor(String workflowName) throws FactoryException { return getWorkflow(workflowName); } /** * @ejb.interface-method */ public String getWorkflowName(long id) throws StoreException { WorkflowStore store = getPersistence(); WorkflowEntry entry = store.findEntry(id); if (entry != null) { return entry.getWorkflowName(); } else { return null; } } /** * Get a list of workflow names available * @ejb.interface-method * @return String[] an array of workflow names. * @throws UnsupportedOperationException if the underlying workflow factory cannot obtain a list of workflow names. */ public String[] getWorkflowNames() throws FactoryException { return ConfigLoader.getWorkflowNames(); } /** * @ejb.interface-method */ public boolean canInitialize(String workflowName, int initialAction) throws WorkflowException { return canInitialize(workflowName, initialAction, null); } /** * @ejb.interface-method * @param workflowName the name of the workflow to check * @param initialAction The initial action to check * @param inputs the inputs map * @return true if the workflow can be initialized * @throws WorkflowException if an unexpected error happens */ public boolean canInitialize(String workflowName, int initialAction, Map inputs) throws WorkflowException { final String mockWorkflowName = workflowName; WorkflowEntry mockEntry = new WorkflowEntry() { public long getId() { return 0; } public String getWorkflowName() { return mockWorkflowName; } public boolean isInitialized() { return false; } public int getState() { return WorkflowEntry.CREATED; } }; // since no state change happens here, a memory instance is just fine PropertySet ps = PropertySetManager.getInstance("memory", null); Map transientVars = new HashMap(); if (inputs != null) { transientVars.putAll(inputs); } populateTransientMap(mockEntry, transientVars, Collections.EMPTY_LIST); return canInitialize(workflowName, initialAction, transientVars, ps); } /** * @ejb.interface-method */ public boolean canModifyEntryState(long id, int newState) throws WorkflowException { WorkflowStore store = getPersistence(); WorkflowEntry entry = store.findEntry(id); int currentState = entry.getState(); boolean result = false; switch (newState) { case WorkflowEntry.CREATED: result = false; case WorkflowEntry.ACTIVATED: if ((currentState == WorkflowEntry.CREATED) || (currentState == WorkflowEntry.SUSPENDED)) { result = true; } break; case WorkflowEntry.SUSPENDED: if (currentState == WorkflowEntry.ACTIVATED) { result = true; } break; case WorkflowEntry.KILLED: if ((currentState == WorkflowEntry.CREATED) || (currentState == WorkflowEntry.ACTIVATED) || (currentState == WorkflowEntry.SUSPENDED)) { result = true; } break; default: result = false; break; } return result; } public void changeEntryState(long id, int newState) throws WorkflowException { WorkflowStore store = getPersistence(); WorkflowEntry entry = store.findEntry(id); if (canModifyEntryState(id, newState)) { store.setEntryState(id, newState); } else { throw new InvalidEntryStateException("Can't transition workflow instance #" + id + ". Current state is " + entry.getState() + ", requested state is " + newState); } if (log.isDebugEnabled()) { log.debug(entry.getId() + " : State is now : " + entry.getState()); } } public void doAction(long id, int actionId, Map inputs) throws WorkflowException { int[] availableActions = getAvailableActions(id, null); boolean validAction = false; WorkflowStore store = getPersistence(); WorkflowEntry entry = store.findEntry(id); if (entry.getState() != WorkflowEntry.ACTIVATED) { return; } for (int i = 0; i < availableActions.length; i++) { if (availableActions[i] == actionId) { validAction = true; break; } } if (!validAction) { throw new IllegalArgumentException("Action " + actionId + " is invalid"); } WorkflowDescriptor wf = getWorkflow(entry.getWorkflowName()); List currentSteps = store.findCurrentSteps(id); ActionDescriptor action = wf.getAction(actionId); PropertySet ps = store.getPropertySet(id); Map transientVars = new HashMap(); if (inputs != null) { transientVars.putAll(inputs); } populateTransientMap(entry, transientVars, wf.getRegisters()); try { transitionWorkflow(entry, currentSteps, store, wf, action, transientVars, inputs, ps); completeEntry(id); } catch (WorkflowException e) { context.setRollbackOnly(); throw e; } } public void executeTriggerFunction(long id, int triggerId) throws WorkflowException { WorkflowStore store = getPersistence(); WorkflowEntry entry = store.findEntry(id); WorkflowDescriptor wf = getWorkflow(entry.getWorkflowName()); PropertySet ps = store.getPropertySet(id); Map transientVars = new HashMap(); populateTransientMap(entry, transientVars, wf.getRegisters()); executeFunction(wf.getTriggerFunction(triggerId), transientVars, ps); } public long initialize(String workflowName, int initialAction, Map inputs) throws InvalidRoleException, InvalidInputException, WorkflowException { WorkflowDescriptor wf = getWorkflow(workflowName); WorkflowStore store = getPersistence(); WorkflowEntry entry = store.createEntry(workflowName); // start with a memory property set, but clone it after we have an ID PropertySet ps = store.getPropertySet(entry.getId()); Map transientVars = new HashMap(); if (inputs != null) { transientVars.putAll(inputs); } populateTransientMap(entry, transientVars, wf.getRegisters()); if (!canInitialize(workflowName, initialAction, transientVars, ps)) { context.setRollbackOnly(); throw new InvalidRoleException("You are restricted from initializing this workflow"); } ActionDescriptor action = wf.getInitialAction(initialAction); try { transitionWorkflow(entry, Collections.EMPTY_LIST, store, wf, action, transientVars, inputs, ps); } catch (WorkflowException e) { context.setRollbackOnly(); throw e; } long entryId = entry.getId(); // now clone the memory PS to the real PS //PropertySetManager.clone(ps, store.getPropertySet(entryId)); return entryId; } /** * @ejb.interface-method */ public List query(WorkflowQuery query) throws StoreException { return getPersistence().query(query); } /** * @ejb.interface-method */ public boolean saveWorkflowDescriptor(String workflowName, WorkflowDescriptor descriptor, boolean replace) throws FactoryException { boolean success = ConfigLoader.saveWorkflow(workflowName, descriptor, replace); return success; } protected List getAvailableActionsForStep(WorkflowDescriptor wf, Step step, Map transientVars, PropertySet ps) throws WorkflowException { List l = new ArrayList(); StepDescriptor s = wf.getStep(step.getStepId()); if (s == null) { log.warn("getAvailableActionsForStep called for non-existent step Id #" + step.getStepId()); return l; } List actions = s.getActions(); if ((actions == null) || (actions.size() == 0)) { return l; } for (Iterator iterator2 = actions.iterator(); iterator2.hasNext();) { ActionDescriptor action = (ActionDescriptor) iterator2.next(); RestrictionDescriptor restriction = action.getRestriction(); String conditionType = null; List conditions = null; if (restriction != null) { conditionType = restriction.getConditionType(); conditions = restriction.getConditions(); } if (passesConditions(conditionType, conditions, Collections.unmodifiableMap(transientVars), ps)) { l.add(new Integer(action.getId())); } } return l; } protected WorkflowStore getPersistence() throws StoreException { return StoreFactory.getPersistence(context); } /** * Returns a workflow definition object associated with the given name. * * @param name the name of the workflow * @return the object graph that represents a workflow definition */ protected synchronized WorkflowDescriptor getWorkflow(String name) throws FactoryException { return ConfigLoader.getWorkflow(name); } protected void completeEntry(long id) throws WorkflowException { WorkflowStore store = getPersistence(); WorkflowEntry entry = store.findEntry(id); WorkflowDescriptor wf = getWorkflow(entry.getWorkflowName()); Collection currentSteps = store.findCurrentSteps(id); boolean isCompleted = true; for (Iterator iterator = currentSteps.iterator(); iterator.hasNext();) { Step step = (Step) iterator.next(); StepDescriptor stepDes = wf.getStep(step.getStepId()); // if at least on current step have an available action if (stepDes.getActions().size() > 0) { isCompleted = false; } } if (isCompleted == true) { store.setEntryState(id, WorkflowEntry.COMPLETED); } } /** * Load the default configuration from the current context classloader. The search order is: * <li>osworkflow.xml</li> * <li>/osworkflow.xml</li> * <li>META-INF/osworkflow.xml</li> * <li>/META-INF/osworkflow.xml</li> */ protected void loadConfig() throws FactoryException { loadConfig(null); } /** * Loads the configurtion file <b>osworkflow.xml</b> from the thread's class loader if no url is specified. * @param url the URL to first attempt to load the configuration file from. If this url is unavailable, * then the default search mechanism is used (as outlined in {@link #loadConfig}). */ protected void loadConfig(URL url) throws FactoryException { if (configLoaded) { return; } InputStream is = null; if (url != null) { try { is = url.openStream(); } catch (Exception ex) { } } ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (is == null) { try { is = classLoader.getResourceAsStream("osworkflow.xml"); } catch (Exception e) { } } if (is == null) { try { is = classLoader.getResourceAsStream("/osworkflow.xml"); } catch (Exception e) { } } if (is == null) { try { is = classLoader.getResourceAsStream("META-INF/osworkflow.xml"); } catch (Exception e) { } } if (is == null) { try { is = classLoader.getResourceAsStream("/META-INF/osworkflow.xml"); } catch (Exception e) { } } if (is != null) { ConfigLoader.load(is); configLoaded = true; } } protected Object loadObject(String clazz) { try { return Thread.currentThread().getContextClassLoader().loadClass(clazz).newInstance(); } catch (Exception e) { log.error("Could not load object '" + clazz + "'", e); return null; } } protected boolean passesCondition(ConditionDescriptor conditionDesc, Map transientVars, PropertySet ps) throws WorkflowException { String type = conditionDesc.getType(); HashMap args = new HashMap(conditionDesc.getArgs()); for (Iterator iterator = args.entrySet().iterator(); iterator.hasNext();) { Map.Entry mapEntry = (Map.Entry) iterator.next(); mapEntry.setValue(translateVariables((String) mapEntry.getValue(), transientVars, ps)); } String clazz; if ("remote-ejb".equals(type)) { clazz = RemoteEJBCondition.class.getName(); } else if ("local-ejb".equals(type)) { clazz = LocalEJBCondition.class.getName(); } else if ("jndi".equals(type)) { clazz = JNDICondition.class.getName(); } else if ("bsf".equals(type)) { clazz = BSFCondition.class.getName(); } else if ("beanshell".equals(type)) { clazz = BeanShellCondition.class.getName(); } else { clazz = (String) args.get(CLASS_NAME); } Condition condition = (Condition) loadObject(clazz); if (condition == null) { String message = "Could not load Condition: " + clazz; throw new WorkflowException(message); } try { boolean passed = condition.passesCondition(transientVars, args, ps); if (conditionDesc.isNegate()) { passed = !passed; } return passed; } catch (Exception e) { String message = "Unknown exception encountered when trying condition: " + clazz; context.setRollbackOnly(); throw new WorkflowException(message, e); } } protected boolean passesConditions(String conditionType, List conditions, Map transientVars, PropertySet ps) throws WorkflowException { if ((conditions == null) || (conditions.size() == 0)) { return true; } boolean and = "AND".equals(conditionType); boolean or = !and; for (Iterator iterator = conditions.iterator(); iterator.hasNext();) { ConditionDescriptor conditionDescriptor = (ConditionDescriptor) iterator.next(); boolean result = passesCondition(conditionDescriptor, transientVars, ps); if (and && !result) { return false; } else if (or && result) { return true; } } if (and) { return true; } else if (or) { return false; } else { return false; } } protected void populateTransientMap(WorkflowEntry entry, Map transientVars, List registers) throws WorkflowException { transientVars.put("context", context); transientVars.put("entry", entry); transientVars.put("store", getPersistence()); transientVars.put("descriptor", getWorkflow(entry.getWorkflowName())); // now talk to the registers for any extra objects needed in scope for (Iterator iterator = registers.iterator(); iterator.hasNext();) { RegisterDescriptor register = (RegisterDescriptor) iterator.next(); Map args = register.getArgs(); String type = register.getType(); String clazz; if ("remote-ejb".equals(type)) { clazz = RemoteEJBRegister.class.getName(); } else if ("local-ejb".equals(type)) { clazz = LocalEJBRegister.class.getName(); } else if ("jndi".equals(type)) { clazz = JNDIRegister.class.getName(); } else if ("bsf".equals(type)) { clazz = BSFRegister.class.getName(); } else if ("beanshell".equals(type)) { clazz = BeanShellRegister.class.getName(); } else { clazz = (String) args.get(CLASS_NAME); } Register r = (Register) loadObject(clazz); if (r == null) { String message = "Could not load register class: " + clazz; throw new WorkflowException(message); } try { transientVars.put(register.getVariableName(), r.registerVariable(context, entry, args)); } catch (Exception e) { String message = "An unknown exception occured while registering variable using class: " + clazz; context.setRollbackOnly(); throw new WorkflowException(message, e); } } } /** * Validates input against a list of ValidatorDescriptor objects. * * @param entry the workflow instance * @param validators the list of ValidatorDescriptors * @param transientVars the transientVars * @param ps the persistence variables * @throws InvalidInputException if the input is deemed invalid by any validator */ protected void verifyInputs(WorkflowEntry entry, List validators, Map transientVars, PropertySet ps) throws WorkflowException { for (Iterator iterator = validators.iterator(); iterator.hasNext();) { ValidatorDescriptor input = (ValidatorDescriptor) iterator.next(); if (input != null) { String type = input.getType(); HashMap args = new HashMap(input.getArgs()); for (Iterator iterator2 = args.entrySet().iterator(); iterator2.hasNext();) { Map.Entry mapEntry = (Map.Entry) iterator2.next(); mapEntry.setValue(translateVariables((String) mapEntry.getValue(), transientVars, ps)); } String clazz; if ("remote-ejb".equals(type)) { clazz = RemoteEJBValidator.class.getName(); } else if ("local-ejb".equals(type)) { clazz = LocalEJBValidator.class.getName(); } else if ("jndi".equals(type)) { clazz = JNDIValidator.class.getName(); } else if ("bsf".equals(type)) { clazz = BSFValidator.class.getName(); } else if ("beanshell".equals(type)) { clazz = BeanShellValidator.class.getName(); } else { clazz = (String) args.get(CLASS_NAME); } Validator validator = (Validator) loadObject(clazz); if (validator == null) { String message = "Could not load validator class: " + clazz; throw new WorkflowException(message); } try { validator.validate(transientVars, args, ps); } catch (InvalidInputException e) { throw e; } catch (Exception e) { String message = "An unknown exception occured executing Validator: " + clazz; context.setRollbackOnly(); throw new WorkflowException(message, e); } } } } Object getVariableFromMaps(String var, Map transientVars, PropertySet ps) { int firstDot = var.indexOf('.'); String actualVar = var; if (firstDot != -1) { actualVar = var.substring(0, firstDot); } Object o = transientVars.get(actualVar); if (o == null) { o = ps.getAsActualType(actualVar); } if (firstDot != -1) { o = beanProvider.getProperty(o, var.substring(firstDot + 1)); } return o; } /** * Parses a string for instances of "${foo}" and returns a string with all instances replaced * with the string value of the foo object (<b>foo.toString()</b>). If the string being passed * in only refers to a single variable and contains no other characters (for example: ${foo}), * then the actual object is returned instead of converting it to a string. */ Object translateVariables(String s, Map transientVars, PropertySet ps) { String temp = s.trim(); if (temp.startsWith("${") && temp.endsWith("}") && (temp.indexOf('$', 1) == -1)) { // the string is just a variable reference, don't convert it to a string String var = temp.substring(2, temp.length() - 1); return getVariableFromMaps(var, transientVars, ps); } else { // the string passed in contains multiple variables (or none!) and should be treated as a string while (true) { int x = s.indexOf("${"); int y = s.indexOf("}", x); if ((x != -1) && (y != -1)) { String var = s.substring(x + 2, y); String t = null; Object o = getVariableFromMaps(var, transientVars, ps); if (o != null) { t = o.toString(); } if (t != null) { s = s.substring(0, x) + t + s.substring(y + 1); } else { // the variable doesn't exist, so don't display anything s = s.substring(0, x) + s.substring(y + 1); } } else { break; } } return s; } } private Step getCurrentStep(WorkflowDescriptor wfDesc, int actionId, List currentSteps, Map transientVars, PropertySet ps) throws WorkflowException { if (currentSteps.size() == 1) { return (Step) currentSteps.get(0); } for (Iterator iterator = currentSteps.iterator(); iterator.hasNext();) { Step step = (Step) iterator.next(); ActionDescriptor action = wfDesc.getStep(step.getStepId()).getAction(actionId); if (action != null) { List availActions = getAvailableActionsForStep(wfDesc, step, transientVars, ps); if (availActions.contains(new Integer(action.getId()))) { return step; } } } return null; } private boolean canInitialize(String workflowName, int initialAction, Map transientVars, PropertySet ps) throws WorkflowException { WorkflowDescriptor wf = getWorkflow(workflowName); ActionDescriptor actionDescriptor = wf.getInitialAction(initialAction); if (actionDescriptor == null) { throw new WorkflowException("Invalid Initial Action"); } RestrictionDescriptor restriction = actionDescriptor.getRestriction(); String conditionType = null; List conditions = null; if (restriction != null) { conditionType = restriction.getConditionType(); conditions = restriction.getConditions(); } return passesConditions(conditionType, conditions, Collections.unmodifiableMap(transientVars), ps); } private void createNewCurrentStep(ResultDescriptor theResult, WorkflowEntry entry, WorkflowStore store, int actionId, Step currentStep, long[] previousIds, Map transientVars, PropertySet ps) throws StoreException { try { if (log.isDebugEnabled()) { log.debug("Outcome: stepId=" + theResult.getStep() + ", status=" + theResult.getStatus() + ", owner=" + theResult.getOwner() + ", actionId=" + actionId + ", currentStep=" + ((currentStep != null) ? currentStep.getStepId() : 0)); } if (previousIds == null) { previousIds = new long[0]; } String owner = TextUtils.noNull(theResult.getOwner()); if (owner.equals("")) { owner = null; } else { Object o = translateVariables(owner, transientVars, ps); owner = (o != null) ? o.toString() : null; } String oldStatus = theResult.getOldStatus(); oldStatus = translateVariables(oldStatus, transientVars, ps).toString(); String status = theResult.getStatus(); status = translateVariables(status, transientVars, ps).toString(); if (currentStep != null) { store.markFinished(currentStep, actionId, new Date(), oldStatus, context.getCaller()); store.moveToHistory(currentStep); //store.moveToHistory(actionId, new Date(), currentStep, oldStatus, context.getCaller()); } // construct the start date and optional due date Date startDate = new Date(); Date dueDate = null; if ((theResult.getDueDate() != null) && (theResult.getDueDate().length() > 0)) { Object dueDateObject = translateVariables(theResult.getDueDate(), transientVars, ps); if (dueDateObject instanceof Date) { dueDate = (Date) dueDateObject; } else if (dueDateObject instanceof String) { long offset = TextUtils.parseLong((String) dueDateObject); if (offset > 0) { dueDate = new Date(startDate.getTime() + offset); } } else if (dueDateObject instanceof Number) { Number num = (Number) dueDateObject; long offset = num.longValue(); if (offset > 0) { dueDate = new Date(startDate.getTime() + offset); } } } store.createCurrentStep(entry.getId(), theResult.getStep(), owner, startDate, dueDate, status, previousIds); } catch (StoreException e) { context.setRollbackOnly(); throw e; } } /** * Executes a function. * * @param function the function to execute * @param transientVars the transientVars given by the end-user * @param ps the persistence variables */ private void executeFunction(FunctionDescriptor function, Map transientVars, PropertySet ps) throws WorkflowException { if (function != null) { String type = function.getType(); HashMap args = new HashMap(function.getArgs()); for (Iterator iterator = args.entrySet().iterator(); iterator.hasNext();) { Map.Entry mapEntry = (Map.Entry) iterator.next(); mapEntry.setValue(translateVariables((String) mapEntry.getValue(), transientVars, ps)); } String clazz; if ("remote-ejb".equals(type)) { clazz = RemoteEJBFunctionProvider.class.getName(); } else if ("local-ejb".equals(type)) { clazz = LocalEJBFunctionProvider.class.getName(); } else if ("jndi".equals(type)) { clazz = JNDIFunctionProvider.class.getName(); } else if ("bsf".equals(type)) { clazz = BSFFunctionProvider.class.getName(); } else if ("beanshell".equals(type)) { clazz = BeanShellFunctionProvider.class.getName(); } else { clazz = (String) args.get(CLASS_NAME); } FunctionProvider provider = (FunctionProvider) loadObject(clazz); if (provider == null) { String message = "Could not load FunctionProvider class: " + clazz; context.setRollbackOnly(); throw new WorkflowException(message); } try { provider.execute(transientVars, args, ps); } catch (WorkflowException e) { context.setRollbackOnly(); throw e; } } } private void transitionWorkflow(WorkflowEntry entry, List currentSteps, WorkflowStore store, WorkflowDescriptor wf, ActionDescriptor action, Map transientVars, Map inputs, PropertySet ps) throws WorkflowException { Step step = getCurrentStep(wf, action.getId(), currentSteps, transientVars, ps); // validate transientVars (optional) verifyInputs(entry, action.getValidators(), Collections.unmodifiableMap(transientVars), ps); // preFunctions List preFunctions = action.getPreFunctions(); for (Iterator iterator = preFunctions.iterator(); iterator.hasNext();) { FunctionDescriptor function = (FunctionDescriptor) iterator.next(); executeFunction(function, transientVars, ps); } // check each conditional result List conditionalResults = action.getConditionalResults(); List extraPreFunctions = null; List extraPostFunctions = null; ResultDescriptor[] theResults = new ResultDescriptor[1]; for (Iterator iterator = conditionalResults.iterator(); iterator.hasNext();) { ConditionalResultDescriptor conditionalResult = (ConditionalResultDescriptor) iterator.next(); if (passesConditions(conditionalResult.getConditionType(), conditionalResult.getConditions(), Collections.unmodifiableMap(transientVars), ps)) { //if (evaluateExpression(conditionalResult.getCondition(), entry, wf.getRegisters(), null, transientVars)) { theResults[0] = conditionalResult; verifyInputs(entry, conditionalResult.getValidators(), Collections.unmodifiableMap(transientVars), ps); extraPreFunctions = conditionalResult.getPreFunctions(); extraPostFunctions = conditionalResult.getPostFunctions(); break; } } // use unconditional-result if a condition hasn't been met if (theResults[0] == null) { theResults[0] = action.getUnconditionalResult(); verifyInputs(entry, theResults[0].getValidators(), Collections.unmodifiableMap(transientVars), ps); extraPreFunctions = theResults[0].getPreFunctions(); extraPostFunctions = theResults[0].getPostFunctions(); } if (log.isDebugEnabled()) { log.debug("theResult=" + theResults[0].getStep() + " " + theResults[0].getStatus()); } if (extraPreFunctions != null) { // run any extra pre-functions that haven't been run already for (Iterator iterator = extraPreFunctions.iterator(); iterator.hasNext();) { FunctionDescriptor function = (FunctionDescriptor) iterator.next(); executeFunction(function, transientVars, ps); } } // go to next step if (theResults[0].getSplit() != 0) { // the result is a split request, handle it correctly SplitDescriptor splitDesc = wf.getSplit(theResults[0].getSplit()); Collection results = splitDesc.getResults(); List splitPreFunctions = new ArrayList(); List splitPostFunctions = new ArrayList(); for (Iterator iterator = results.iterator(); iterator.hasNext();) { ResultDescriptor resultDescriptor = (ResultDescriptor) iterator.next(); verifyInputs(entry, resultDescriptor.getValidators(), Collections.unmodifiableMap(transientVars), ps); splitPreFunctions.addAll(resultDescriptor.getPreFunctions()); splitPostFunctions.addAll(resultDescriptor.getPostFunctions()); } // now execute the pre-functions for (Iterator iterator = splitPreFunctions.iterator(); iterator.hasNext();) { FunctionDescriptor function = (FunctionDescriptor) iterator.next(); executeFunction(function, transientVars, ps); } // now make these steps... boolean moveFirst = true; theResults = new ResultDescriptor[results.size()]; results.toArray(theResults); for (Iterator iterator = results.iterator(); iterator.hasNext();) { ResultDescriptor resultDescriptor = (ResultDescriptor) iterator.next(); Step moveToHistoryStep = null; if (moveFirst) { moveToHistoryStep = step; } long[] previousIds = null; if (step != null) { previousIds = new long[] {step.getId()}; } createNewCurrentStep(resultDescriptor, entry, store, action.getId(), moveToHistoryStep, previousIds, transientVars, ps); moveFirst = false; } // now execute the post-functions for (Iterator iterator = splitPostFunctions.iterator(); iterator.hasNext();) { FunctionDescriptor function = (FunctionDescriptor) iterator.next(); executeFunction(function, transientVars, ps); } } else if (theResults[0].getJoin() != 0) { // this is a join, finish this step... JoinDescriptor joinDesc = wf.getJoin(theResults[0].getJoin()); step = store.markFinished(step, action.getId(), new Date(), theResults[0].getOldStatus(), context.getCaller()); // ... now check to see if the expression evaluates // (get only current steps that have a result to this join) ArrayList joinSteps = new ArrayList(); joinSteps.add(step); //currentSteps = store.findCurrentSteps(id); // shouldn't need to refresh the list for (Iterator iterator = currentSteps.iterator(); iterator.hasNext();) { Step currentStep = (Step) iterator.next(); if (currentStep.getId() != step.getId()) { StepDescriptor stepDesc = wf.getStep(currentStep.getStepId()); if (stepDesc.resultsInJoin(theResults[0].getJoin())) { joinSteps.add(currentStep); } } } JoinNodes jn = new JoinNodes(joinSteps); transientVars.put("jn", jn); if (passesConditions(joinDesc.getConditionType(), joinDesc.getConditions(), Collections.unmodifiableMap(transientVars), ps)) { // move the rest without creating a new step ... ResultDescriptor joinresult = joinDesc.getResult(); verifyInputs(entry, joinresult.getValidators(), Collections.unmodifiableMap(transientVars), ps); // now execute the pre-functions for (Iterator iterator = joinresult.getPreFunctions().iterator(); iterator.hasNext();) { FunctionDescriptor function = (FunctionDescriptor) iterator.next(); executeFunction(function, transientVars, ps); } long[] previousIds = new long[joinSteps.size()]; int i = 1; for (Iterator iterator = joinSteps.iterator(); iterator.hasNext();) { Step currentStep = (Step) iterator.next(); if (currentStep.getId() != step.getId()) { //store.moveToHistory(currentStep.getActionId(), currentStep.getFinishDate(), currentStep, theResult.getOldStatus(), context.getCaller()); store.moveToHistory(currentStep); previousIds[i] = currentStep.getId(); i++; } } // ... now finish this step normally previousIds[0] = step.getId(); theResults[0] = joinDesc.getResult(); createNewCurrentStep(joinDesc.getResult(), entry, store, action.getId(), step, previousIds, transientVars, ps); // now execute the post-functions for (Iterator iterator = joinresult.getPostFunctions().iterator(); iterator.hasNext();) { FunctionDescriptor function = (FunctionDescriptor) iterator.next(); executeFunction(function, transientVars, ps); } } } else { // normal finish, no splits or joins long[] previousIds = null; if (step != null) { previousIds = new long[] {step.getId()}; } createNewCurrentStep(theResults[0], entry, store, action.getId(), step, previousIds, transientVars, ps); } // postFunctions (BOTH) if (extraPostFunctions != null) { for (Iterator iterator = extraPostFunctions.iterator(); iterator.hasNext();) { FunctionDescriptor function = (FunctionDescriptor) iterator.next(); executeFunction(function, transientVars, ps); } } List postFunctions = action.getPostFunctions(); for (Iterator iterator = postFunctions.iterator(); iterator.hasNext();) { FunctionDescriptor function = (FunctionDescriptor) iterator.next(); executeFunction(function, transientVars, ps); } //if executed action was an initial action then workflow is activated if ((wf.getInitialAction(action.getId()) != null) && (entry.getState() != WorkflowEntry.ACTIVATED)) { changeEntryState(entry.getId(), WorkflowEntry.ACTIVATED); } //we have our results, lets check if we need to autoexec any of them int[] availableActions = getAvailableActions(entry.getId(), null); if (availableActions.length != 0) { for (int i = 0; i < theResults.length; i++) { ResultDescriptor theResult = theResults[i]; StepDescriptor toCheck = wf.getStep(theResult.getStep()); if (toCheck != null) { Iterator iter = toCheck.getActions().iterator(); MAIN: while (iter.hasNext()) { ActionDescriptor descriptor = (ActionDescriptor) iter.next(); if (descriptor.getAutoExecute()) { //check if it's an action we can actually perform for (int j = 0; j < availableActions.length; j++) { if (descriptor.getId() == availableActions[j]) { doAction(entry.getId(), descriptor.getId(), inputs); break MAIN; } } } } } } } } }
package org.minimalj.frontend.page; import java.util.Optional; import org.minimalj.frontend.Frontend.IContent; import org.minimalj.frontend.action.Action; import org.minimalj.security.Subject; public interface PageManager { public abstract void show(Page page); public default void showDetail(Page mainPage, Page detail, boolean horizontalDetailLayout) { showDetail(mainPage, detail); } public default void showDetail(Page mainPage, Page detail) { show(detail); } public default void hideDetail(Page page) { // do nothing } public default boolean isDetailShown(Page page) { return false; } public abstract IDialog showDialog(String title, IContent content, Action saveAction, Action closeAction, Action... actions); public abstract Optional<IDialog> showLogin(IContent content, Action loginAction, Action forgetPasswordAction, Action cancelAction); public abstract void showMessage(String text); public abstract void showError(String text); public abstract void login(Subject subject); }