answer
stringlengths 17
10.2M
|
|---|
package edu.umd.cs.findbugs;
import java.util.*;
import java.io.PrintStream;
import org.apache.bcel.classfile.*;
import java.util.zip.*;
import java.io.*;
import edu.umd.cs.pugh.visitclass.Constants2;
public class FindHEmismatch extends BytecodeScanningDetector implements Constants2 {
String prevClassName = " none ";
boolean firstTime = true;
boolean hasFields = false;
boolean hasHashCode = false;
boolean hasEqualsObject = false;
boolean hasCompareToObject = false;
boolean hasEqualsSelf = false;
boolean hasCompareToSelf = false;
boolean isInterface = false;
boolean extendsObject = false;
private BugReporter bugReporter;
public FindHEmismatch(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
public void report() {
if (!hasEqualsObject && hasEqualsSelf) {
if (extendsObject)
bugReporter.reportBug(new BugInstance("EQ_SELF_USE_OBJECT", NORMAL_PRIORITY).addClass(prevClassName));
else
bugReporter.reportBug(new BugInstance("EQ_SELF_NO_OBJECT", NORMAL_PRIORITY).addClass(prevClassName));
}
if (!hasCompareToObject && hasCompareToSelf) {
if (!extendsObject)
bugReporter.reportBug(new BugInstance("CO_SELF_NO_OBJECT", NORMAL_PRIORITY).addClass(prevClassName));
}
if (!hasFields) return;
if (hasHashCode && !(hasEqualsObject || hasEqualsSelf)) {
if (extendsObject)
bugReporter.reportBug(new BugInstance("HE_HASHCODE_USE_OBJECT_EQUALS", NORMAL_PRIORITY).addClass(prevClassName));
else
bugReporter.reportBug(new BugInstance("HE_HASHCODE_NO_EQUALS", NORMAL_PRIORITY). addClass(prevClassName));
}
if (!hasHashCode && (hasEqualsObject || hasEqualsSelf)) {
if (extendsObject)
bugReporter.reportBug(new BugInstance("HE_EQUALS_USE_HASHCODE", NORMAL_PRIORITY).addClass(prevClassName));
else
bugReporter.reportBug(new BugInstance("HE_EQUALS_NO_HASHCODE", NORMAL_PRIORITY).addClass(prevClassName));
}
}
public void visit(JavaClass obj) {
if (!isInterface && !firstTime) report();
extendsObject = betterSuperclassName.equals("java.lang.Object");
firstTime = false;
prevClassName = betterClassName;
hasFields = false;
hasHashCode = false;
hasCompareToObject = false;
hasCompareToSelf = false;
hasEqualsObject = false;
hasEqualsSelf = false;
int accessFlags = obj.getAccessFlags();
isInterface = ((accessFlags & ACC_INTERFACE) != 0);
}
public void visit(Field obj) {
int accessFlags = obj.getAccessFlags();
if ((accessFlags & ACC_STATIC) != 0) return;
hasFields = true;
}
public void visit(Method obj) {
int accessFlags = obj.getAccessFlags();
if ((accessFlags & ACC_STATIC) != 0) return;
String name = obj.getName();
String sig = obj.getSignature();
if ((accessFlags & ACC_ABSTRACT) != 0) {
if (name.equals("equals")
&& sig.equals("(L"+className+";)Z"))
bugReporter.reportBug(new BugInstance("EQ_ABSTRACT_SELF", NORMAL_PRIORITY).addClass(betterClassName));
else if (name.equals("compareTo")
&& sig.equals("(L"+className+";)I"))
bugReporter.reportBug(new BugInstance("CO_ABSTRACT_SELF", NORMAL_PRIORITY).addClass(betterClassName));
return;
}
boolean sigIsObject = sig.equals("(Ljava/lang/Object;)Z");
if (name.equals("hashCode")) hasHashCode = true;
else if (name.equals("equals")) {
if (sigIsObject) hasEqualsObject = true;
else if (sig.equals("(L"+className+";)Z"))
hasEqualsSelf = true;
}
else if (name.equals("compareTo")) {
if (sig.equals("(Ljava/lang/Object;)I"))
hasCompareToObject = true;
else if (sig.equals("(L"+className+";)I"))
hasCompareToSelf = true;
}
}
}
|
package net.finmath.montecarlo.interestrate;
import java.util.ArrayList;
import java.util.Map;
import net.finmath.exception.CalculationException;
import net.finmath.functions.AnalyticFormulas;
import net.finmath.marketdata.AbstractSwaptionMarketData;
import net.finmath.marketdata.model.AnalyticModelInterface;
import net.finmath.marketdata.model.curves.DiscountCurveFromForwardCurve;
import net.finmath.marketdata.model.curves.DiscountCurveInterface;
import net.finmath.marketdata.model.curves.ForwardCurveInterface;
import net.finmath.marketdata.products.Swap;
import net.finmath.marketdata.products.SwapAnnuity;
import net.finmath.montecarlo.RandomVariable;
import net.finmath.montecarlo.interestrate.modelplugins.AbstractLIBORCovarianceModel;
import net.finmath.montecarlo.interestrate.modelplugins.AbstractLIBORCovarianceModelParametric;
import net.finmath.montecarlo.interestrate.products.AbstractLIBORMonteCarloProduct;
import net.finmath.montecarlo.interestrate.products.SwaptionAnalyticApproximation;
import net.finmath.montecarlo.interestrate.products.SwaptionSimple;
import net.finmath.montecarlo.model.AbstractModel;
import net.finmath.stochastic.ImmutableRandomVariableInterface;
import net.finmath.stochastic.RandomVariableInterface;
import net.finmath.time.TimeDiscretization;
import net.finmath.time.TimeDiscretizationInterface;
/**
* Implements a basic LIBOR market model with some drift approximation methods.
*
* The class implements different measure(drift) / numeraire pairs (terminal and spot).
*
* The model uses an <code>AbstractLIBORCovarianceModel</code> as a covariance model, which has the ability to calibrate to swaptions.
*
* @see AbstractLIBORCovarianceModel
*
* @author Christian Fries
* @version 1.0
*/
public class LIBORMarketModel extends AbstractModel implements LIBORMarketModelInterface {
public enum Driftapproximation { EULER, LINE_INTEGRAL, PREDICTOR_CORRECTOR };
public enum Measure { SPOT, TERMINAL };
private TimeDiscretizationInterface liborPeriodDiscretization;
private String forwardCurveName;
private AnalyticModelInterface curveModel;
private ForwardCurveInterface forwardRateCurve;
private DiscountCurveInterface discountCurve;
private AbstractLIBORCovarianceModel covarianceModel;
private AbstractSwaptionMarketData swaptionMarketData;
private Driftapproximation driftApproximationMethod = Driftapproximation.EULER;
private Measure measure = Measure.SPOT;
// This is a cache of the integrated covariance.
private double[][][] integratedLIBORCovariance;
public static class CalibrationItem {
public AbstractLIBORMonteCarloProduct calibrationProduct;
public double calibrationTargetValue;
public double calibrationWeight;
public CalibrationItem(AbstractLIBORMonteCarloProduct calibrationProduct, double calibrationTargetValue, double calibrationWeight) {
super();
this.calibrationProduct = calibrationProduct;
this.calibrationTargetValue = calibrationTargetValue;
this.calibrationWeight = calibrationWeight;
}
}
/**
* Creates a LIBOR Market Model for given covariance.
*
* @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure).
* @param forwardRateCurve The initial values for the forward rates.
* @param covarianceModel The covariance model to use.
*/
public LIBORMarketModel(
TimeDiscretizationInterface liborPeriodDiscretization,
ForwardCurveInterface forwardRateCurve,
AbstractLIBORCovarianceModel covarianceModel
) {
this.liborPeriodDiscretization = liborPeriodDiscretization;
this.forwardRateCurve = forwardRateCurve;
this.covarianceModel = covarianceModel;
}
/**
* Creates a LIBOR Market Model for given covariance.
*
* @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure).
* @param forwardRateCurve The initial values for the forward rates.
* @param discountCurve The discount curve to use. This will create an LMM model with a deterministic zero-spread discounting adjustment.
* @param covarianceModel The covariance model to use.
*/
public LIBORMarketModel(
TimeDiscretizationInterface liborPeriodDiscretization,
ForwardCurveInterface forwardRateCurve,
DiscountCurveInterface discountCurve,
AbstractLIBORCovarianceModel covarianceModel
) {
this.liborPeriodDiscretization = liborPeriodDiscretization;
this.forwardRateCurve = forwardRateCurve;
this.discountCurve = discountCurve;
this.covarianceModel = covarianceModel;
}
/**
* Creates a LIBOR Market Model for given covariance.
*
* @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure).
* @param forwardRateCurve The initial values for the forward rates.
* @param covarianceModel The covariance model to use.
* @param swaptionMarketData The set of swaption values to calibrate to.
* @throws CalculationException
*/
public LIBORMarketModel(
TimeDiscretizationInterface liborPeriodDiscretization,
ForwardCurveInterface forwardRateCurve,
AbstractLIBORCovarianceModel covarianceModel,
AbstractSwaptionMarketData swaptionMarketData
) throws CalculationException {
this(liborPeriodDiscretization, forwardRateCurve, null, covarianceModel, getCalibrationItems(liborPeriodDiscretization, forwardRateCurve, swaptionMarketData));
}
/**
* Creates a LIBOR Market Model for given covariance.
*
* @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure).
* @param forwardRateCurve The initial values for the forward rates.
* @param discountCurve The discount curve to use. This will create an LMM model with a deterministic zero-spread discounting adjustment.
* @param covarianceModel The covariance model to use.
* @param swaptionMarketData The set of swaption values to calibrate to.
* @throws CalculationException
*/
public LIBORMarketModel(
TimeDiscretizationInterface liborPeriodDiscretization,
ForwardCurveInterface forwardRateCurve,
DiscountCurveInterface discountCurve,
AbstractLIBORCovarianceModel covarianceModel,
AbstractSwaptionMarketData swaptionMarketData
) throws CalculationException {
this(liborPeriodDiscretization, forwardRateCurve, discountCurve, covarianceModel, getCalibrationItems(liborPeriodDiscretization, forwardRateCurve, swaptionMarketData));
}
/**
* Creates a LIBOR Market Model for given covariance.
*
* @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure).
* @param forwardRateCurve The initial values for the forward rates.
* @param discountCurve The discount curve to use. This will create an LMM model with a deterministic zero-spread discounting adjustment.
* @param covarianceModel The covariance model to use.
* @param calibrationItems The vector of calibration items (a union of a product, target value and weight) for the objective function sum weight(i) * (modelValue(i)-targetValue(i).
* @throws CalculationException
*/
public LIBORMarketModel(
TimeDiscretizationInterface liborPeriodDiscretization,
ForwardCurveInterface forwardRateCurve,
DiscountCurveInterface discountCurve,
AbstractLIBORCovarianceModel covarianceModel,
CalibrationItem[] calibrationItems
) throws CalculationException {
this.liborPeriodDiscretization = liborPeriodDiscretization;
double[] times = new double[liborPeriodDiscretization.getNumberOfTimeSteps()];
for(int i=0; i<times.length; i++) times[i] = liborPeriodDiscretization.getTime(i);
AbstractLIBORCovarianceModelParametric covarianceModelParametric = null;
try {
covarianceModelParametric = (AbstractLIBORCovarianceModelParametric)covarianceModel;
}
catch(Exception e) {
throw new ClassCastException("Calibration is currently restricted to parametric covariance models (AbstractLIBORCovarianceModelParametric).");
}
this.forwardRateCurve = forwardRateCurve;
this.discountCurve = discountCurve;
// @TODO Should be more elegant. Convert array for constructor
AbstractLIBORMonteCarloProduct[] calibrationProducts = new AbstractLIBORMonteCarloProduct[calibrationItems.length];
double[] calibrationTargetValues = new double[calibrationItems.length];
double[] calibrationWeights = new double[calibrationItems.length];
for(int i=0; i<calibrationTargetValues.length; i++) {
calibrationProducts[i] = calibrationItems[i].calibrationProduct;
calibrationTargetValues[i] = calibrationItems[i].calibrationTargetValue;
calibrationWeights[i] = calibrationItems[i].calibrationWeight;
}
this.covarianceModel = covarianceModelParametric.getCloneCalibrated(this, calibrationProducts, calibrationTargetValues, calibrationWeights);
}
private static CalibrationItem[] getCalibrationItems(TimeDiscretizationInterface liborPeriodDiscretization, ForwardCurveInterface forwardCurve, AbstractSwaptionMarketData swaptionMarketData) {
TimeDiscretizationInterface optionMaturities = swaptionMarketData.getOptionMaturities();
TimeDiscretizationInterface tenor = swaptionMarketData.getTenor();
double swapPeriodLength = swaptionMarketData.getSwapPeriodLength();
ArrayList<CalibrationItem> calibrationItems = new ArrayList<CalibrationItem>();
for(int exerciseIndex=0; exerciseIndex<=optionMaturities.getNumberOfTimeSteps(); exerciseIndex++) {
for(int tenorIndex=0; tenorIndex<=tenor.getNumberOfTimeSteps()-exerciseIndex; tenorIndex++) {
// Create a swaption
double exerciseDate = optionMaturities.getTime(exerciseIndex);
double swapLength = tenor.getTime(tenorIndex);
if(liborPeriodDiscretization.getTimeIndex(exerciseDate) < 0) continue;
if(liborPeriodDiscretization.getTimeIndex(exerciseDate+swapLength) <= liborPeriodDiscretization.getTimeIndex(exerciseDate)) continue;
int numberOfPeriods = (int)(swapLength / swapPeriodLength);
double[] fixingDates = new double[numberOfPeriods];
double[] paymentDates = new double[numberOfPeriods];
double[] swapTenorTimes = new double[numberOfPeriods+1];
for(int periodStartIndex=0; periodStartIndex<numberOfPeriods; periodStartIndex++) {
fixingDates[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength;
paymentDates[periodStartIndex] = exerciseDate + (periodStartIndex+1) * swapPeriodLength;
swapTenorTimes[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength;
}
swapTenorTimes[numberOfPeriods] = exerciseDate + numberOfPeriods * swapPeriodLength;
// Swaptions swap rate
TimeDiscretizationInterface swapTenor = new TimeDiscretization(swapTenorTimes);
double swaprate = Swap.getForwardSwapRate(swapTenor, swapTenor, forwardCurve, null);
// Set swap rates for each period
double[] swaprates = new double[numberOfPeriods];
for(int periodStartIndex=0; periodStartIndex<numberOfPeriods; periodStartIndex++) {
swaprates[periodStartIndex] = swaprate;
}
boolean isUseAnalyticApproximation = true;
if(isUseAnalyticApproximation) {
AbstractLIBORMonteCarloProduct swaption = new SwaptionAnalyticApproximation(swaprate, swapTenorTimes, SwaptionAnalyticApproximation.ValueUnit.VOLATILITY);
double impliedVolatility = swaptionMarketData.getVolatility(exerciseDate, swapLength, swaptionMarketData.getSwapPeriodLength(), swaprate);
calibrationItems.add(new CalibrationItem(swaption, impliedVolatility, 1.0));
}
else {
AbstractLIBORMonteCarloProduct swaption = new SwaptionSimple(swaprate, swapTenorTimes, SwaptionSimple.ValueUnit.VALUE);
double forwardSwaprate = Swap.getForwardSwapRate(swapTenor, swapTenor, forwardCurve);
double swapAnnuity = SwapAnnuity.getSwapAnnuity(swapTenor, forwardCurve);
double impliedVolatility = swaptionMarketData.getVolatility(exerciseDate, swapLength, swaptionMarketData.getSwapPeriodLength(), swaprate);
double targetValue = AnalyticFormulas.blackModelSwaptionValue(forwardSwaprate, impliedVolatility, exerciseDate, swaprate, swapAnnuity);
calibrationItems.add(new CalibrationItem(swaption, targetValue, 1.0));
}
}
}
return calibrationItems.toArray(new CalibrationItem[0]);
}
/**
* Return the numeraire at a given time.
* Note: The random variable returned is a defensive copy and may be modified.
* <b>
* Note: This method does not interpolate the numeraire if it is requested outside the liborPeriodDiscretization
* </b>
*
* @param time Time time <i>t</i> for which the numeraire should be returned <i>N(t)</i>.
* @return The numeraire at the specified time as <code>RandomVariable</code>
* @throws CalculationException
*/
public RandomVariableInterface getNumeraire(double time) throws CalculationException {
return getNumeraire(getTimeIndex(time));
}
public RandomVariableInterface[] getInitialState() {
double[] liborInitialStates = new double[liborPeriodDiscretization.getNumberOfTimeSteps()];
for(int timeIndex=0; timeIndex<liborPeriodDiscretization.getNumberOfTimeSteps(); timeIndex++) {
double rate = forwardRateCurve.getForward(null, liborPeriodDiscretization.getTime(timeIndex));
liborInitialStates[timeIndex] = Math.log(rate);
}
RandomVariableInterface[] initialStateRandomVariable = new RandomVariableInterface[getNumberOfComponents()];
for(int componentIndex=0; componentIndex<getNumberOfComponents(); componentIndex++) {
initialStateRandomVariable[componentIndex] = new RandomVariable(0.0, liborInitialStates[componentIndex]);
}
return initialStateRandomVariable;
}
/**
* Return the complete vector of the drift for the time index timeIndex, given that current state is realizationAtTimeIndex.
* Note: The random variable returned is a defensive copy and may be modified.
* The drift will be zero for rates being already fixed.
*
* @see LIBORMarketModel#getNumeraire(int) The calculation of the drift is consistent with the calculation of the numeraire in <code>getNumeraire</code>.
*
* @param timeIndex Time index <i>i</i> for which the drift should be returned <i>μ(t<sub>i</sub>)</i>.
* @param realizationAtTimeIndex Time current forward rate vector at time index <i>i</i> which should be used in the calculation.
* @return The drift vector μ(t<sub>i</sub>) as <code>RandomVariable[]</code>
* @throws CalculationException
*/
public RandomVariableInterface[] getDrift(int timeIndex, ImmutableRandomVariableInterface[] realizationAtTimeIndex, ImmutableRandomVariableInterface[] realizationPredictor) {
double time = getTime(timeIndex);
int firstLiborIndex = this.getLiborPeriodIndex(time)+1;
if(firstLiborIndex<0) firstLiborIndex = -firstLiborIndex-1 + 1;
// Allocate drift vector and initialize to zero (will be used to sum up drift components)
RandomVariableInterface[] drift = new RandomVariableInterface[getNumberOfComponents()];
RandomVariableInterface[][] covarianceFactorSums = new RandomVariableInterface[getNumberOfComponents()][getNumberOfFactors()];
for(int componentIndex=firstLiborIndex; componentIndex<getNumberOfComponents(); componentIndex++) {
drift[componentIndex] = new RandomVariable(0.0, 0.0);
}
// Calculate drift for the component componentIndex (starting at firstLiborIndex, others are zero)
for(int componentIndex=firstLiborIndex; componentIndex<getNumberOfComponents(); componentIndex++) {
double periodLength = liborPeriodDiscretization.getTimeStep(componentIndex);
ImmutableRandomVariableInterface libor = realizationAtTimeIndex[componentIndex];
RandomVariableInterface oneStepMeasureTransform = (new RandomVariable(periodLength)).discount(libor, periodLength);
oneStepMeasureTransform.mult(libor);
RandomVariableInterface[] covarianceFactors = getFactorLoading(timeIndex, componentIndex, realizationAtTimeIndex);
for(int factorIndex=0; factorIndex<getNumberOfFactors(); factorIndex++) {
covarianceFactors[factorIndex].mult(oneStepMeasureTransform);
covarianceFactorSums[componentIndex][factorIndex] = covarianceFactors[factorIndex];
if(componentIndex > firstLiborIndex)
covarianceFactorSums[componentIndex][factorIndex].add(covarianceFactorSums[componentIndex-1][factorIndex]);
}
}
// Above is the drift for the spot measure: a simple conversion makes it the drift of the terminal measure.
if(measure == Measure.TERMINAL) {
for(int componentIndex=firstLiborIndex; componentIndex<getNumberOfComponents(); componentIndex++) {
for(int factorIndex=0; factorIndex<getNumberOfFactors(); factorIndex++) {
covarianceFactorSums[componentIndex][factorIndex].sub(covarianceFactorSums[getNumberOfComponents()-1][factorIndex]);
}
}
}
for(int componentIndex=firstLiborIndex; componentIndex<getNumberOfComponents(); componentIndex++) {
RandomVariableInterface[] factorLoading = getFactorLoading(timeIndex, componentIndex, realizationAtTimeIndex);
for(int factorIndex=0; factorIndex<getNumberOfFactors(); factorIndex++) {
drift[componentIndex].addProduct(covarianceFactorSums[componentIndex][factorIndex], factorLoading[factorIndex]);
}
}
// Drift adjustment for log-coordinate in each component
for(int componentIndex=firstLiborIndex; componentIndex<getNumberOfComponents(); componentIndex++) {
RandomVariableInterface variance = covarianceModel.getCovariance(timeIndex, componentIndex, componentIndex, realizationAtTimeIndex);
drift[componentIndex].addProduct(variance, -0.5);
}
return drift;
}
public RandomVariableInterface getDrift(int timeIndex, int componentIndex, ImmutableRandomVariableInterface[] realizationAtTimeIndex, ImmutableRandomVariableInterface[] realizationPredictor) {
// Check if this LIBOR is already fixed
if(getTime(timeIndex) >= this.getLiborPeriod(componentIndex)) {
return null;
}
/*
* We implemented several different methods to calculate the drift
*/
if(driftApproximationMethod == Driftapproximation.PREDICTOR_CORRECTOR && realizationPredictor != null) {
RandomVariableInterface drift = getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex);
RandomVariableInterface driftEulerWithPredictor = getDriftEuler(timeIndex, componentIndex, realizationPredictor);
drift.add(driftEulerWithPredictor).div(2.0);
return drift;
}
else if(driftApproximationMethod == Driftapproximation.LINE_INTEGRAL && realizationPredictor != null) {
return getDriftLineIntegral(timeIndex, componentIndex, realizationAtTimeIndex, realizationPredictor);
}
else {
return getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex);
}
}
public RandomVariableInterface[] getFactorLoading(int timeIndex, int componentIndex, ImmutableRandomVariableInterface[] realizationAtTimeIndex)
{
return covarianceModel.getFactorLoading(timeIndex, componentIndex, realizationAtTimeIndex);
}
@Override
public void applyStateSpaceTransform(int componentIndex, RandomVariableInterface randomVariable) {
randomVariable.exp();
}
/**
* @return Returns the driftApproximationMethod.
*/
public Driftapproximation getDriftApproximationMethod() {
return driftApproximationMethod;
}
/* (non-Javadoc)
* @see net.finmath.montecarlo.interestrate.LIBORMarketModelInterface#getLIBOR(int, int)
*/
@Override
public RandomVariableInterface getLIBOR(int timeIndex, int liborIndex) throws CalculationException
{
// This method is just a psynonym - call getProcessValue of super class
return getProcessValue(timeIndex, liborIndex);
}
/**
* This method is just a synonym to getNumberOfLibors
* @return The number of components
*/
public int getNumberOfComponents() {
return getNumberOfLibors();
}
/* (non-Javadoc)
* @see net.finmath.montecarlo.interestrate.LIBORMarketModelInterface#getNumberOfLibors()
*/
@Override
public int getNumberOfLibors()
{
// This is just a synonym to number of components
return liborPeriodDiscretization.getNumberOfTimeSteps();
}
/* (non-Javadoc)
* @see net.finmath.montecarlo.interestrate.LIBORMarketModelInterface#getLiborPeriod(int)
*/
@Override
public double getLiborPeriod(int timeIndex) {
return liborPeriodDiscretization.getTime(timeIndex);
}
/* (non-Javadoc)
* @see net.finmath.montecarlo.interestrate.LIBORMarketModelInterface#getLiborPeriodIndex(double)
*/
@Override
public int getLiborPeriodIndex(double time) {
return liborPeriodDiscretization.getTimeIndex(time);
}
/* (non-Javadoc)
* @see net.finmath.montecarlo.interestrate.LIBORMarketModelInterface#getLiborPeriodDiscretization()
*/
@Override
public TimeDiscretizationInterface getLiborPeriodDiscretization() {
return liborPeriodDiscretization;
}
protected RandomVariableInterface getDriftEuler(int timeIndex, int componentIndex, ImmutableRandomVariableInterface[] liborVectorStart) {
// The following is the drift of the LIBOR component
double time = getTime(timeIndex);
// Initialize to 0.0
RandomVariableInterface drift = new RandomVariable(time, 0.0);
// Get the start and end of the summation (start is the LIBOR after the current LIBOR component, end is the last LIBOR)
int firstLiborIndex, lastLiborIndex;
switch(measure) {
case SPOT:
// Spot measure
firstLiborIndex = this.getLiborPeriodIndex(time)+1;
if(firstLiborIndex<0) firstLiborIndex = -firstLiborIndex-1 + 1;
lastLiborIndex = componentIndex;
break;
case TERMINAL:
default:
firstLiborIndex = componentIndex+1;
lastLiborIndex = liborPeriodDiscretization.getNumberOfTimeSteps()-1;
break;
}
// The sum
for(int liborIndex = firstLiborIndex; liborIndex<=lastLiborIndex; liborIndex++) {
double periodLength = liborPeriodDiscretization.getTimeStep(liborIndex);
RandomVariableInterface covariance = covarianceModel.getCovariance(timeIndex, componentIndex, liborIndex, null);
ImmutableRandomVariableInterface libor = liborVectorStart[liborIndex];
covariance.mult(periodLength).mult(libor).discount(libor, periodLength);
drift.add(covariance);
}
if(measure == Measure.TERMINAL) {
drift.mult(-1.0);
}
// Drift adjustment for log-coordinate
RandomVariableInterface variance = covarianceModel.getCovariance(timeIndex, componentIndex, componentIndex, null);
drift.addProduct(variance, -0.5);
return drift;
}
private RandomVariableInterface getDriftLineIntegral(int timeIndex, int componentIndex, ImmutableRandomVariableInterface[] liborVectorStart, ImmutableRandomVariableInterface[] liborVectorEnd) {
// The following is the dirft of the LIBOR component
double time = getTime(timeIndex);
// Check if this LIBOR is already fixed
if(getTime(timeIndex) >= this.getLiborPeriod(componentIndex)) {
return null;
}
// Initialize to 0.0
RandomVariable drift = new RandomVariable(time, 0.0);
// Get the start and end of the summation (start is the LIBOR after the current LIBOR component, end is the last LIBOR)
int firstLiborIndex, lastLiborIndex;
switch(measure) {
case SPOT:
// Spot measure
firstLiborIndex = this.getLiborPeriodIndex(time)+1;
if(firstLiborIndex<0) firstLiborIndex = -firstLiborIndex-1 + 1;
lastLiborIndex = componentIndex;
break;
case TERMINAL:
default:
firstLiborIndex = componentIndex+1;
lastLiborIndex = liborPeriodDiscretization.getNumberOfTimeSteps()-1;
break;
}
// The sum
for(int liborIndex = firstLiborIndex; liborIndex<=lastLiborIndex; liborIndex++) {
double periodLength = liborPeriodDiscretization.getTimeStep(liborIndex);
RandomVariableInterface covariance = covarianceModel.getCovariance(timeIndex, componentIndex, liborIndex, null);
/*
* We calcululate
* driftTerm = covariance * log( (1 + periodLength * liborVectorEnd[liborIndex]) / (1 + periodLength * liborVectorStart[liborIndex]) )
* / log(liborVectorEnd[liborIndex] / liborVectorStart[liborIndex])
*/
RandomVariableInterface driftTerm = new RandomVariable(1.0);
driftTerm.accrue(liborVectorEnd[liborIndex], periodLength);
driftTerm.discount(liborVectorStart[liborIndex], periodLength);
driftTerm.log();
driftTerm.mult(covariance);
driftTerm.div(liborVectorEnd[liborIndex].getMutableCopy().div(liborVectorStart[liborIndex]).log());
drift.sub(driftTerm);
}
return drift;
}
/**
* @return Returns the measure.
*/
public Measure getMeasure() {
return measure;
}
/**
* Return the numeraire at a given time index.
* Note: The random variable returned is a defensive copy and may be modified.
* <b>
* Note: This method does not interpolate the numeraire if it is requested outside the liborPeriodDiscretization
* </b>
*
* @param timeIndex Time index <i>i</i> for which the numeraire should be returned <i>N(t<sub>i</sub>)</i>.
* @return The numeraire at the specified time as <code>RandomVariable</code>
* @throws CalculationException
*/
public RandomVariableInterface getNumeraire(int timeIndex) throws CalculationException
{
double time = getTime(timeIndex);
// Get the start of the product
int firstLiborIndex = this.getLiborPeriodIndex(time);
// while(liborPeriodDiscretization[firstLiborIndex] < time) firstLiborIndex++;
// Get the end of the product
int lastLiborIndex = liborPeriodDiscretization.getNumberOfTimeSteps()-1;
if(measure == Measure.SPOT) {
// Spot measure
firstLiborIndex = 0;
lastLiborIndex = this.getLiborPeriodIndex(time)-1;
if(lastLiborIndex < -1) {
System.out.println("Interpolation on Numeraire not supported.");
}
}
/*
* Calculation of the numeraire
*/
// Initialize to 1.0
RandomVariable numeraire = new RandomVariable(time, 1.0);
// The product
for(int liborIndex = firstLiborIndex; liborIndex<=lastLiborIndex; liborIndex++) {
RandomVariableInterface libor = getLIBOR(getTimeIndex(Math.min(time,liborPeriodDiscretization.getTime(liborIndex))), liborIndex);
double periodLength = liborPeriodDiscretization.getTimeStep(liborIndex);
if(measure == Measure.SPOT) {
numeraire.accrue(libor, periodLength);
}
else {
numeraire.discount(libor, periodLength);
}
}
/*
* Adjust for disocunting
*/
if(discountCurve != null) {
DiscountCurveInterface discountcountCurveFromForwardPerformance = new DiscountCurveFromForwardCurve(forwardRateCurve);
double deterministicNumeraireAdjustment = discountcountCurveFromForwardPerformance.getDiscountFactor(time) / discountCurve.getDiscountFactor(time);
numeraire.mult(deterministicNumeraireAdjustment);
}
return numeraire;
}
public synchronized double[][][] getIntegratedLIBORCovariance() {
if(integratedLIBORCovariance != null) return integratedLIBORCovariance;
TimeDiscretizationInterface liborPeriodDiscretization = getLiborPeriodDiscretization();
TimeDiscretizationInterface simulationTimeDiscretization = getTimeDiscretization();
integratedLIBORCovariance = new double[simulationTimeDiscretization.getNumberOfTimeSteps()][liborPeriodDiscretization.getNumberOfTimeSteps()][liborPeriodDiscretization.getNumberOfTimeSteps()];
for(int componentIndex1 = 0; componentIndex1 < liborPeriodDiscretization.getNumberOfTimeSteps(); componentIndex1++) {
// Sum the libor cross terms (use symmetry)
for(int componentIndex2 = componentIndex1; componentIndex2 < liborPeriodDiscretization.getNumberOfTimeSteps(); componentIndex2++) {
double integratedLIBORCovarianceValue = 0.0;
for(int timeIndex = 0; timeIndex < simulationTimeDiscretization.getNumberOfTimeSteps(); timeIndex++) {
double dt = getTime(timeIndex+1) - getTime(timeIndex);
ImmutableRandomVariableInterface[] factorLoadingOfComponent1 = getCovarianceModel().getFactorLoading(timeIndex, componentIndex1, null);
ImmutableRandomVariableInterface[] factorLoadingOfComponent2 = getCovarianceModel().getFactorLoading(timeIndex, componentIndex2, null);
for(int factorIndex = 0; factorIndex < getNumberOfFactors(); factorIndex++) {
integratedLIBORCovarianceValue += factorLoadingOfComponent1[factorIndex].get(0) * factorLoadingOfComponent2[factorIndex].get(0) * dt;
}
integratedLIBORCovariance[timeIndex][componentIndex1][componentIndex2] = integratedLIBORCovarianceValue;
}
}
}
return integratedLIBORCovariance;
}
public Object clone() {
return new LIBORMarketModel(liborPeriodDiscretization, forwardRateCurve, covarianceModel);
}
/**
* @param driftApproximationMethod The driftApproximationMethod to set.
*/
public void setDriftApproximationMethod(Driftapproximation driftApproximationMethod) {
this.driftApproximationMethod = driftApproximationMethod;
}
/**
* @param measure The measure to set.
*/
public void setMeasure(Measure measure) {
this.measure = measure;
}
/* (non-Javadoc)
* @see net.finmath.montecarlo.interestrate.LIBORMarketModelInterface#getForwardRateCurve()
*/
@Override
public ForwardCurveInterface getForwardRateCurve() {
return forwardRateCurve;
}
/**
* Return the swaption market data used for calibration (if any, may be null).
*
* @return The swaption market data used for calibration (if any, may be null).
*/
public AbstractSwaptionMarketData getSwaptionMarketData() {
return swaptionMarketData;
}
/* (non-Javadoc)
* @see net.finmath.montecarlo.interestrate.LIBORMarketModelInterface#getCovarianceModel()
*/
@Override
public AbstractLIBORCovarianceModel getCovarianceModel() {
return covarianceModel;
}
/**
* @param covarianceModel the covarianceModel to set
* @deprecated
*/
public void setCovarianceModel(AbstractLIBORCovarianceModel covarianceModel) {
this.covarianceModel = covarianceModel;
}
/**
* @param covarianceModel A covariance model
* @return A new <code>LIBORMarketModel</code> using the specified covariance model.
*/
public LIBORMarketModel getCloneWithModifiedCovarianceModel(AbstractLIBORCovarianceModel covarianceModel) {
LIBORMarketModel model = (LIBORMarketModel)this.clone();
model.setCovarianceModel(covarianceModel);
return model;
}
public LIBORMarketModel getCloneWithModifiedData(Map<String, Object> dataModified) throws CalculationException {
TimeDiscretizationInterface liborPeriodDiscretization = this.liborPeriodDiscretization;
ForwardCurveInterface forwardRateCurve = this.forwardRateCurve;
AbstractLIBORCovarianceModel covarianceModel = this.covarianceModel;
AbstractSwaptionMarketData swaptionMarketData = null;
if(dataModified.containsKey("liborPeriodDiscretization")) {
liborPeriodDiscretization = (TimeDiscretizationInterface)dataModified.get("liborPeriodDiscretization");
}
if(dataModified.containsKey("forwardRateCurve")) {
forwardRateCurve = (ForwardCurveInterface)dataModified.get("forwardRateCurve");
}
if(dataModified.containsKey("forwardRateShift")) {
forwardRateCurve = (ForwardCurveInterface)dataModified.get("forwardRateCurve");
// throw new RuntimeException("Forward rate shift clone currently disabled.");
}
if(dataModified.containsKey("covarianceModel")) {
covarianceModel = (AbstractLIBORCovarianceModel)dataModified.get("covarianceModel");
}
if(dataModified.containsKey("swaptionMarketData")) {
swaptionMarketData = (AbstractSwaptionMarketData)dataModified.get("covarianceModel");
}
if(swaptionMarketData == null) {
return new LIBORMarketModel(liborPeriodDiscretization, forwardRateCurve, covarianceModel);
}
else {
return new LIBORMarketModel(liborPeriodDiscretization, forwardRateCurve, covarianceModel, swaptionMarketData);
}
}
}
|
package musikerverwaltung.Swing;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.*;
import musikerverwaltung.Database.DBMethods03;
import musikerverwaltung.menschen.*;
public class AnzeigeFormularArtist02 extends JPanel {
// Felder:
// JPanel
private JPanel jpmainleft, jpmainmiddle, jpmainright, jpmainlefttop,
jpmainleftmiddle, jpmainleftbottom, jpmainmiddleinstrument,
jpmainmiddlestueck, jpmainrightreferenz, jpmainrightjb,
jpmainartist, jpdatum, dodjpdatum, jpgeschlechtgruppe,
jpmainleftperson;
// Schriften:
private Font ftfield;
// Labels
private JLabel jlueschrift, jlvorname, jlname, jltitel, jlvorsatz,
jlzusatz, jlgeschlecht, jldob, jldod, jlpseudonym, jlinstrument,
jlsolostueck, jlreferenz, jlfueller;
// JTextField
private JTextField jtfueschrift, jtfvorname, jtfname, jtftitel, jtfvorsatz,
jtfzusatz, jtfgeschlecht, jtfdob, jtfdod, jtfpseudonym,
jtfinstrument, jtfsolostueck, jtfreferenz;
// JComoboxBox
private JComboBox<String> jcbmonat, dodjcbmonat;
private JComboBox<Integer> jcbtag, jcbjahr, dodjcbtag, dodjcbjahr;
// String Array fuer die Monatsnamen
private String[] monatsname = { "Januar", "Februar", "M\u00E4rz", "April",
"Mai", "Juni", "Juli", "August", "September", "Oktober",
"November", "Dezember" };
private String[] dodmonatsname = { "Januar", "Februar", "M\u00E4rz",
"April", "Mai", "Juni", "Juli", "August", "September", "Oktober",
"November", "Dezember" };
// JButton
private JButton jbsubmit, jbdelete;
// JRadioButton
private JRadioButton rbmann, rbfrau, rbkeineahnung, jrblebt;
// Button Group
private ButtonGroup auswahl;
// Instanz der Klasse Musiker erzeugen und Pseudonym uebergeben um
// entsprechenden >SELECT< ausfuehren zu koennen in DB-Methoden
private Musiker01 musiker;
// Border
private BorderSet border;
// DefaultTableModel
private TableModel dtm;
// JTable
private JTable jtinstrument, jtstueck, jtreferenz;
// JScrollPane
private JScrollPane jspinstrument, jspstueck, jspreferenz;
private ListSelectionModel cellSelectionModel;
public JPanel jpmainLeft(Object artist) {
jpmainlefttop = new JPanel(new GridLayout(6, 2, 1, 1));
// JLabels erzeugen
jlvorname = new JLabel("Vorname");
jlname = new JLabel("Name");
jltitel = new JLabel("Titel");
jlvorsatz = new JLabel("Vorsatz");
jlzusatz = new JLabel("Zusatz");
jlgeschlecht = new JLabel("Geschlecht");
// JTextFields erzeugen
jtfvorname = new JTextField();
jtfname = new JTextField();
jtftitel = new JTextField();
jtfvorsatz = new JTextField();
jtfzusatz = new JTextField();
jtfgeschlecht = new JTextField();
jpgeschlechtgruppe = new JPanel();
// Vorname
jpmainlefttop.add(jlvorname);
jpmainlefttop.add(jtfvorname);
// Name
jpmainlefttop.add(jlname);
jpmainlefttop.add(jtfname);
// Titel
jpmainlefttop.add(jltitel);
jpmainlefttop.add(jtftitel);
// Vorsatz
jpmainlefttop.add(jlvorsatz);
jpmainlefttop.add(jtfvorsatz);
// Zusatz
jpmainlefttop.add(jlzusatz);
jpmainlefttop.add(jtfzusatz);
// Geschlecht
jpmainlefttop.add(jlgeschlecht);
jpmainlefttop.add(jpgeschlechtgruppe);
// Instanz eines Musikers erzeugen
musiker = new Musiker01(String.valueOf(artist));
// Texte setzen die aus der MusikerKlasse-DBKlasse kommen
jtfvorname.setText(musiker.getMusikerVorname());
jtfname.setText(musiker.getMusikerName());
jtftitel.setText(musiker.getMusikerTitel());
jtfvorsatz.setText(musiker.getMusikerVorsatz());
jtfzusatz.setText(musiker.getMusikerZusatz());
// Pruefung ob m oder w oder ns
boolean m = false;
boolean w = false;
boolean ns = false;
if (musiker.getMusikerGeschlecht().equals("m"))
m = true;
if (musiker.getMusikerGeschlecht().equals("f"))
w = true;
if (musiker.getMusikerGeschlecht().equals("ns"))
ns = true;
// // JRadioButtons erzeugen und die richtigen RadioButtons
// vorselektieren
rbmann = new JRadioButton("Mann", m);
rbmann.setActionCommand("m");
rbfrau = new JRadioButton("Frau", w);
rbfrau.setActionCommand("f");
rbkeineahnung = new JRadioButton("Keine Ahnung", ns);
rbkeineahnung.setActionCommand("ns");
// JRadioButtons ButtonGroup hinzuf\u00FCgen
auswahl = new ButtonGroup();
auswahl.add(rbmann);
auswahl.add(rbfrau);
auswahl.add(rbkeineahnung);
jpgeschlechtgruppe.add(rbmann);
jpgeschlechtgruppe.add(rbfrau);
jpgeschlechtgruppe.add(rbkeineahnung);
// Border-Instanz erzeugen
border = new BorderSet();
border.setBorder(jpmainlefttop, "Personen-Daten");
//
jpmainleftmiddle = new JPanel();
// JLabel erzeugen
jldob = new JLabel("Geburstdatum");
jldod = new JLabel("Todesdatum");
// JComboBox- Geburtstag - Tag
jcbtag = new JComboBox<Integer>();
for (int t = 1; t < 32; t++)
jcbtag.addItem(new Integer(t));
jcbtag.setSelectedIndex(musiker.getMusikerGTag() - 1);
jcbtag.setEditable(false);
// JComboBox - Geburtstag - Monat
jcbmonat = new JComboBox<String>(monatsname);
jcbmonat.setSelectedIndex(musiker.getMusikerGMonat() - 1);
jcbmonat.setEditable(false);
// JComboBox - Geburtstag - Jahr
jcbjahr = new JComboBox<Integer>();
jcbjahr.setEditable(true);
int aktjahr = (new GregorianCalendar()).get(Calendar.YEAR);
for (int j = 0; j <= 100; j++)
jcbjahr.addItem(new Integer(aktjahr - j));
jcbjahr.setSelectedIndex(aktjahr - musiker.getMusikerGJahr());
// JRadio Button ob Musiker gestorben ist
jrblebt = new JRadioButton("tot");
jrblebt.setActionCommand("n");
// Alles in ein Panel
jpdatum = new JPanel(new GridLayout(1, 3, 2, 2));
jpdatum.add(jcbtag);
jpdatum.add(jcbmonat);
jpdatum.add(jcbjahr);
// JComboBox- Todes - Tag
dodjcbtag = new JComboBox<Integer>();
for (int t = 1; t < 32; t++)
dodjcbtag.addItem(new Integer(t));
if (musiker.getMusikerLebt().equals("n")) {
dodjcbtag.setSelectedIndex(musiker.getMusikerTTag() - 1);
} else {
dodjcbtag.setSelectedIndex(0);
dodjcbtag.setEnabled(false);
}
dodjcbtag.setEditable(false);
// JComboBox - Todes - Monat
dodjcbmonat = new JComboBox<String>(dodmonatsname);
if (musiker.getMusikerLebt().equals("n")) {
dodjcbmonat.setSelectedIndex(musiker.getMusikerTMonat() - 1);
} else {
dodjcbmonat.setSelectedIndex(0);
dodjcbmonat.setEnabled(false);
}
dodjcbmonat.setEditable(false);
// JComboBox - Todes - Monat
dodjcbjahr = new JComboBox<Integer>();
dodjcbjahr.setEditable(true);
int dodaktjahr = (new GregorianCalendar()).get(Calendar.YEAR);
for (int j = 0; j <= 100; j++)
dodjcbjahr.addItem(new Integer(dodaktjahr - j));
if (musiker.getMusikerLebt().equals("n")) {
dodjcbjahr.setSelectedIndex(aktjahr - musiker.getMusikerTJahr());
} else {
dodjcbjahr.setSelectedIndex(0);
dodjcbjahr.setEnabled(false);
}
// in ein JPanel einfuegen
dodjpdatum = new JPanel(new GridLayout(1, 3, 2, 2));
dodjpdatum.add(dodjcbtag);
dodjpdatum.add(dodjcbmonat);
dodjpdatum.add(dodjcbjahr);
// Zuordnung zum mittleren Panel der linken Seite
jpmainleftmiddle.add(jldob);
jpmainleftmiddle.add(jpdatum);
jpmainleftmiddle.add(jldod);
jpmainleftmiddle.add(dodjpdatum);
jpmainleftmiddle.add(jrblebt);
// Border setzen
border.setBorder(jpmainleftmiddle, "Datums-Angaben");
//
jpmainleftbottom = new JPanel(new GridLayout(4, 2, 1, 1));
// JLabel erzeugen
jlpseudonym = new JLabel("Pseudonym");
jlinstrument = new JLabel("Instrument");
jlsolostueck = new JLabel("Stueck");
jlreferenz = new JLabel("Referenz");
// JTextfield erzeugen
jtfpseudonym = new JTextField();
jtfinstrument = new JTextField();
jtfsolostueck = new JTextField();
jtfreferenz = new JTextField();
// Pseudonym
jpmainleftbottom.add(jlpseudonym);
jpmainleftbottom.add(jtfpseudonym);
// Instrument
jpmainleftbottom.add(jlinstrument);
jpmainleftbottom.add(jtfinstrument);
// Solostueck
jpmainleftbottom.add(jlsolostueck);
jpmainleftbottom.add(jtfsolostueck);
// Referenz
jpmainleftbottom.add(jlreferenz);
jpmainleftbottom.add(jtfreferenz);
// Texte setzen
jtfpseudonym.setText(musiker.getMusikerPseudonym());
jtfinstrument.setText(musiker.getMusikerInstrument());
jtfreferenz.setText(musiker.getMusikerReferenz());
jtfsolostueck.setText(musiker.getMusikerStueckSolo());
// Border setzen
border.setBorder(jpmainleftbottom, "Interpreten-Daten");
// ToolTips hinzuf\u00FCgen
rbmann.setToolTipText("Ist ihr Interpret ein Mann?");
rbfrau.setToolTipText("Ist ihr Interpret eine Frau?");
rbkeineahnung
.setToolTipText("Ich habe keine Ahnung welches Geschlecht mein K\u00FCnstler hat");
jcbtag.setToolTipText("W\u00E4hlen Sie den Tag an dem der Interpret geboren wurde!");
jcbmonat.setToolTipText("W\u00E4hlen Sie den Monat an dem der Interpret geboren wurde!");
jcbjahr.setToolTipText("W\u00E4hlen Sie das Jahr in dem der Interpret geboren wurde?");
dodjcbtag
.setToolTipText("W\u00E4hlen Sie den Tag an dem der Interpret gestorben ist!");
dodjcbmonat
.setToolTipText("W\u00E4hlen Sie den Monat an dem der Interpret gestorben ist!");
dodjcbjahr
.setToolTipText("W\u00E4hlen Sie das Jahr in dem der Interpret gestorben ist!");
jtfname.setToolTipText("Tragen Sie hier bitte den Nachnamen ein");
jtfvorname.setToolTipText("Tragen Sie hier bitte den Vornamen ein");
jtftitel.setToolTipText("Tragen Sie hier bitte den Titel ein");
jtfvorsatz.setToolTipText("Tragen Sie hier bitte den Vorsatz ein");
jtfzusatz.setToolTipText("Tragen Sie hier bitte den Zusatz ein");
jtfpseudonym
.setToolTipText("Tragen Sie hier bitte das Pseudonym/ den K\u00FCnstlernamen ein");
jtfinstrument
.setToolTipText("Tragen Sie hier bitte das Instrument ein");
jtfsolostueck
.setToolTipText("Tragen Sie hier bitte ein Solost\u00FCck ein");
jtfreferenz
.setToolTipText("Hier k\u00F6nnen Sie eine Referenz zu einem K\u00FCnstler eintragen");
// Hauptpanel fuer die Linke Seite erzeugen
jpmainleft = new JPanel(new GridLayout(3, 1, 1, 1));
// Zurordnen der beiden JPanel jl und jtf
jpmainleft.add(jpmainlefttop);
jpmainleft.add(jpmainleftmiddle);
jpmainleft.add(jpmainleftbottom);
// Border setzen
border.setBorder(jpmainleft, "Info's zum Interpreten");
return jpmainleft;
}
// Rueckgabe-Methode fuer das Mittlere JPanel
public JPanel jpmainMiddle(Object artist) {
jpmainmiddleinstrument = new JPanel(new GridLayout(1, 1, 1, 0));
// Instanz des TablesModels erzeugen
dtm = new TableModel();
// Erzeugung der Tabelle mit DefaultTableModel
jtinstrument = new JTable(dtm.dtm(1, 2,
DBMethods03.COLUMN_IDENTIFIERSINSTRUMENT, musiker.dbSelect()));
// Spalten nicht mehr verschiebbar
jtinstrument.getTableHeader().setReorderingAllowed(false);
jtinstrument.setCellSelectionEnabled(true);
// Nur auswahl einer Zeile moeglich
cellSelectionModel = jtinstrument.getSelectionModel();
cellSelectionModel
.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// JTable der JScrollPane hinzufuegen
jspinstrument = new JScrollPane(jtinstrument);
// Groesse der Tabelle festlegen, das sonst keinen Scrollen vorhanden
// ist, auerdem schoener:) //860 , 600
jspinstrument.setPreferredSize(new Dimension(300, 500));
// Viewport setzen
jspinstrument.setViewportView(jtinstrument);
// JSP mit Mitgliedern und JLabel dem JPanel hinzufuegen
jpmainmiddleinstrument.add(jspinstrument);
// Border setzen
border.setBorder(jpmainmiddleinstrument, "Instrumenten-Liste");
//
jpmainmiddlestueck = new JPanel(new GridLayout(1, 1, 1, 0));
// Erzeugung der Tabelle mit DefaultTableModel
jtstueck = new JTable(dtm.dtm(1, 2,
DBMethods03.COLUMN_IDENTIFIERSTITLES, musiker.dbSelect()));
// Spalten nicht mehr verschiebbar
jtstueck.getTableHeader().setReorderingAllowed(false);
jtstueck.setCellSelectionEnabled(true);
// Nur auswahl einer Zeile moeglich
cellSelectionModel = jtstueck.getSelectionModel();
cellSelectionModel
.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// JTable der JScrollPane hinzufuegen
jspstueck = new JScrollPane(jtstueck);
// Groesse der Tabelle festlegen, das sonst keinen Scrollen vorhanden
// ist, auerdem schoener:) //860 , 600
jspstueck.setPreferredSize(new Dimension(300, 500));
// Viewport setzen
jspstueck.setViewportView(jtstueck);
// JSP mit Mitgliedern und JLabel dem JPanel hinzufuegen
jpmainmiddlestueck.add(jspstueck);
// Border dem JPanel hinzufuegen
border.setBorder(jpmainmiddlestueck, "Titel-Liste");
// HauptPanel fuer die Mitte erzeugen
jpmainmiddle = new JPanel(new GridLayout(2, 1, 1, 1));
// Dem Hauptpanel die JSP zuordnen
jpmainmiddle.add(jpmainmiddleinstrument);
jpmainmiddle.add(jpmainmiddlestueck);
return jpmainmiddle;
}
public JPanel jpmainRight() {
jpmainrightreferenz = new JPanel(new GridLayout(1, 1, 1, 0));
// Erzeugung der Tabelle mit DefaultTableModel
jtreferenz = new JTable(dtm.dtm(1, 2,
DBMethods03.COLUMN_IDENTIFIERSREFERENCES, musiker.dbSelect()));
// Spalten nicht mehr verschiebbar
jtreferenz.getTableHeader().setReorderingAllowed(false);
jtreferenz.setCellSelectionEnabled(true);
// Nur auswahl einer Zeile moeglich
cellSelectionModel = jtreferenz.getSelectionModel();
cellSelectionModel
.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// JTable der JScrollPane hinzufuegen
jspreferenz = new JScrollPane(jtreferenz);
// Groesse der Tabelle festlegen, das sonst keinen Scrollen vorhanden
// ist, auerdem schoener:) //860 , 600
jspreferenz.setPreferredSize(new Dimension(300, 500));
// Viewport setzen
jspreferenz.setViewportView(jtreferenz);
// JSP mit Mitgliedern und JLabel dem JPanel hinzufuegen
jpmainrightreferenz.add(jspreferenz);
// Border dem JPanel hinzufuegen
border.setBorder(jpmainrightreferenz, "Referenzen-Liste");
//
// JPanel erzeugen
jpmainrightjb = new JPanel(new GridLayout(5, 1, 1, 10));
// L\u00FCenf\u00FCller einf\u00FCgen
for (int i = 0; i < 3; i++) {
jlfueller = new JLabel("");
jpmainrightjb.add(jlfueller);
}
// JButtons
jbsubmit = new JButton("Bearbeiten");
jbdelete = new JButton("Lschen");
// In Arbeit => Groesse des Eintragen-Buttons setzen
jbsubmit.setPreferredSize(new Dimension(50, 100));
// JButton dem JPanel hinzuf\u00FCgen
jpmainrightjb.add(jbdelete);
jpmainrightjb.add(jbsubmit);
// ToolTip hinzuf\u00FCgen
jbsubmit.setToolTipText("Hier klicken, um den Interpreten zu editieren");
// HauptPanel fuer die linke Seite erzeugen
jpmainright = new JPanel(new GridLayout(2, 1, 1, 1));
jpmainright.add(jpmainrightreferenz);
jpmainright.add(jpmainrightjb);
return jpmainright;
}
// Methode, die die drei JPanels zusammenfuehrt
public JPanel jpmainArtist(Object artist) {
// JPanel erzeugen, dem drei JPanels hinzugefuegt werden
jpmainartist = new JPanel(new GridLayout(1, 3, 4, 4));
// hinzufuegen der JPanels
jpmainartist.add(jpmainLeft(artist));
jpmainartist.add(jpmainMiddle(artist));
jpmainartist.add(jpmainRight());
// Listener hinzufuegen
actionListenerJButton();
return jpmainartist;
}
private void actionListenerJButton() {
jrblebt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
// Wenn JRB ausgewaehlt, ist lebt != null
Object lebt = jrblebt.getSelectedObjects();
if (lebt != null) {
dodjcbtag.setEnabled(true);
dodjcbmonat.setEnabled(true);
dodjcbjahr.setEnabled(true);
} else {
dodjcbtag.setEnabled(false);
dodjcbmonat.setEnabled(false);
dodjcbjahr.setEnabled(false);
}
}
});
// Speicher-Button
jbsubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Arrays erzeugen
String[] instrument = new String[10];
instrument[0] = jtfinstrument.getText();
String[] solostueck = new String[10];
solostueck[0] = jtfsolostueck.getText();
String[] referenz = new String[10];
referenz[0] = jtfreferenz.getText();
int todestag = musiker.getMusikerTTag();
int todesmonat = musiker.getMusikerTMonat();
int todesjahr = musiker.getMusikerTJahr();
if (jrblebt.getActionCommand() == "n") {
todestag = Integer.parseInt(String.valueOf(dodjcbtag
.getSelectedItem()));
todesmonat = Helfer01.monatUmwandlung(dodjcbmonat
.getSelectedItem().toString());
todesjahr = Integer.parseInt(String.valueOf(dodjcbjahr
.getSelectedItem()));
}
// Instanzvar erzeugen - Uebergabe der Parameter/ jrblebt
Musiker01 musikerbearbeiten = new Musiker01(jtftitel.getText(),
jtfvorsatz.getText(), jtfvorname.getText(), jtfzusatz
.getText(), jtfname.getText(), Integer
.parseInt(String.valueOf(jcbtag
.getSelectedItem())), Helfer01
.monatUmwandlung(jcbmonat.getSelectedItem()
.toString()), Integer.parseInt(String
.valueOf(jcbjahr.getSelectedItem())), todestag,
todesmonat, todesjahr, auswahl.getSelection()
.getActionCommand(),
jrblebt.getActionCommand(), jtfpseudonym.getText(),
instrument, solostueck, referenz);
// Insert-Methode aufrufen
musikerbearbeiten.updateArtist(musiker.getMusikerID());
}
});
}
}
|
package net.finmath.montecarlo.interestrate;
import java.util.ArrayList;
import java.util.Map;
import net.finmath.exception.CalculationException;
import net.finmath.functions.AnalyticFormulas;
import net.finmath.marketdata.AbstractSwaptionMarketData;
import net.finmath.marketdata.model.AnalyticModelInterface;
import net.finmath.marketdata.model.curves.DiscountCurveFromForwardCurve;
import net.finmath.marketdata.model.curves.DiscountCurveInterface;
import net.finmath.marketdata.model.curves.ForwardCurveInterface;
import net.finmath.marketdata.products.Swap;
import net.finmath.marketdata.products.SwapAnnuity;
import net.finmath.montecarlo.RandomVariable;
import net.finmath.montecarlo.interestrate.modelplugins.AbstractLIBORCovarianceModel;
import net.finmath.montecarlo.interestrate.modelplugins.AbstractLIBORCovarianceModelParametric;
import net.finmath.montecarlo.interestrate.products.AbstractLIBORMonteCarloProduct;
import net.finmath.montecarlo.interestrate.products.SwaptionAnalyticApproximation;
import net.finmath.montecarlo.interestrate.products.SwaptionSimple;
import net.finmath.montecarlo.model.AbstractModel;
import net.finmath.stochastic.RandomVariableInterface;
import net.finmath.time.TimeDiscretization;
import net.finmath.time.TimeDiscretizationInterface;
/**
* Implements a basic LIBOR market model with some drift approximation methods.
*
* The class implements different measure(drift) / numeraire pairs (terminal and spot).
*
* The model uses an <code>AbstractLIBORCovarianceModel</code> as a covariance model, which has the ability to calibrate to swaptions.
*
* @see net.finmath.montecarlo.interestrate.modelplugins.AbstractLIBORCovarianceModel
*
* @author Christian Fries
* @version 1.0
*/
public class LIBORMarketModel extends AbstractModel implements LIBORMarketModelInterface {
public enum Driftapproximation { EULER, LINE_INTEGRAL, PREDICTOR_CORRECTOR }
public enum Measure { SPOT, TERMINAL }
private final TimeDiscretizationInterface liborPeriodDiscretization;
private String forwardCurveName;
private AnalyticModelInterface curveModel;
private ForwardCurveInterface forwardRateCurve;
private DiscountCurveInterface discountCurve;
private AbstractLIBORCovarianceModel covarianceModel;
private AbstractSwaptionMarketData swaptionMarketData;
private Driftapproximation driftApproximationMethod = Driftapproximation.EULER;
private Measure measure = Measure.SPOT;
// This is a cache of the integrated covariance.
private double[][][] integratedLIBORCovariance;
public static class CalibrationItem {
public final AbstractLIBORMonteCarloProduct calibrationProduct;
public final double calibrationTargetValue;
public final double calibrationWeight;
public CalibrationItem(AbstractLIBORMonteCarloProduct calibrationProduct, double calibrationTargetValue, double calibrationWeight) {
super();
this.calibrationProduct = calibrationProduct;
this.calibrationTargetValue = calibrationTargetValue;
this.calibrationWeight = calibrationWeight;
}
}
/**
* Creates a LIBOR Market Model for given covariance.
*
* @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure).
* @param forwardRateCurve The initial values for the forward rates.
* @param covarianceModel The covariance model to use.
*/
public LIBORMarketModel(
TimeDiscretizationInterface liborPeriodDiscretization,
ForwardCurveInterface forwardRateCurve,
AbstractLIBORCovarianceModel covarianceModel
) {
this.liborPeriodDiscretization = liborPeriodDiscretization;
this.forwardRateCurve = forwardRateCurve;
this.covarianceModel = covarianceModel;
}
/**
* Creates a LIBOR Market Model for given covariance.
*
* @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure).
* @param forwardRateCurve The initial values for the forward rates.
* @param discountCurve The discount curve to use. This will create an LMM model with a deterministic zero-spread discounting adjustment.
* @param covarianceModel The covariance model to use.
*/
public LIBORMarketModel(
TimeDiscretizationInterface liborPeriodDiscretization,
ForwardCurveInterface forwardRateCurve,
DiscountCurveInterface discountCurve,
AbstractLIBORCovarianceModel covarianceModel
) {
this.liborPeriodDiscretization = liborPeriodDiscretization;
this.forwardRateCurve = forwardRateCurve;
this.discountCurve = discountCurve;
this.covarianceModel = covarianceModel;
}
/**
* Creates a LIBOR Market Model for given covariance.
*
* @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure).
* @param forwardRateCurve The initial values for the forward rates.
* @param covarianceModel The covariance model to use.
* @param swaptionMarketData The set of swaption values to calibrate to.
* @throws net.finmath.exception.CalculationException
*/
public LIBORMarketModel(
TimeDiscretizationInterface liborPeriodDiscretization,
ForwardCurveInterface forwardRateCurve,
AbstractLIBORCovarianceModel covarianceModel,
AbstractSwaptionMarketData swaptionMarketData
) throws CalculationException {
this(liborPeriodDiscretization, forwardRateCurve, null, covarianceModel, getCalibrationItems(liborPeriodDiscretization, forwardRateCurve, swaptionMarketData));
}
/**
* Creates a LIBOR Market Model for given covariance.
*
* @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure).
* @param forwardRateCurve The initial values for the forward rates.
* @param discountCurve The discount curve to use. This will create an LMM model with a deterministic zero-spread discounting adjustment.
* @param covarianceModel The covariance model to use.
* @param swaptionMarketData The set of swaption values to calibrate to.
* @throws net.finmath.exception.CalculationException
*/
public LIBORMarketModel(
TimeDiscretizationInterface liborPeriodDiscretization,
ForwardCurveInterface forwardRateCurve,
DiscountCurveInterface discountCurve,
AbstractLIBORCovarianceModel covarianceModel,
AbstractSwaptionMarketData swaptionMarketData
) throws CalculationException {
this(liborPeriodDiscretization, forwardRateCurve, discountCurve, covarianceModel, getCalibrationItems(liborPeriodDiscretization, forwardRateCurve, swaptionMarketData));
}
/**
* Creates a LIBOR Market Model for given covariance.
*
* @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure).
* @param forwardRateCurve The initial values for the forward rates.
* @param discountCurve The discount curve to use. This will create an LMM model with a deterministic zero-spread discounting adjustment.
* @param covarianceModel The covariance model to use.
* @param calibrationItems The vector of calibration items (a union of a product, target value and weight) for the objective function sum weight(i) * (modelValue(i)-targetValue(i).
* @throws net.finmath.exception.CalculationException
*/
public LIBORMarketModel(
TimeDiscretizationInterface liborPeriodDiscretization,
ForwardCurveInterface forwardRateCurve,
DiscountCurveInterface discountCurve,
AbstractLIBORCovarianceModel covarianceModel,
CalibrationItem[] calibrationItems
) throws CalculationException {
this.liborPeriodDiscretization = liborPeriodDiscretization;
double[] times = new double[liborPeriodDiscretization.getNumberOfTimeSteps()];
for(int i=0; i<times.length; i++) times[i] = liborPeriodDiscretization.getTime(i);
AbstractLIBORCovarianceModelParametric covarianceModelParametric = null;
try {
covarianceModelParametric = (AbstractLIBORCovarianceModelParametric)covarianceModel;
}
catch(Exception e) {
throw new ClassCastException("Calibration is currently restricted to parametric covariance models (AbstractLIBORCovarianceModelParametric).");
}
this.forwardRateCurve = forwardRateCurve;
this.discountCurve = discountCurve;
// @TODO Should be more elegant. Convert array for constructor
AbstractLIBORMonteCarloProduct[] calibrationProducts = new AbstractLIBORMonteCarloProduct[calibrationItems.length];
double[] calibrationTargetValues = new double[calibrationItems.length];
double[] calibrationWeights = new double[calibrationItems.length];
for(int i=0; i<calibrationTargetValues.length; i++) {
calibrationProducts[i] = calibrationItems[i].calibrationProduct;
calibrationTargetValues[i] = calibrationItems[i].calibrationTargetValue;
calibrationWeights[i] = calibrationItems[i].calibrationWeight;
}
this.covarianceModel = covarianceModelParametric.getCloneCalibrated(this, calibrationProducts, calibrationTargetValues, calibrationWeights);
}
private static CalibrationItem[] getCalibrationItems(TimeDiscretizationInterface liborPeriodDiscretization, ForwardCurveInterface forwardCurve, AbstractSwaptionMarketData swaptionMarketData) {
TimeDiscretizationInterface optionMaturities = swaptionMarketData.getOptionMaturities();
TimeDiscretizationInterface tenor = swaptionMarketData.getTenor();
double swapPeriodLength = swaptionMarketData.getSwapPeriodLength();
ArrayList<CalibrationItem> calibrationItems = new ArrayList<CalibrationItem>();
for(int exerciseIndex=0; exerciseIndex<=optionMaturities.getNumberOfTimeSteps(); exerciseIndex++) {
for(int tenorIndex=0; tenorIndex<=tenor.getNumberOfTimeSteps()-exerciseIndex; tenorIndex++) {
// Create a swaption
double exerciseDate = optionMaturities.getTime(exerciseIndex);
double swapLength = tenor.getTime(tenorIndex);
if(liborPeriodDiscretization.getTimeIndex(exerciseDate) < 0) continue;
if(liborPeriodDiscretization.getTimeIndex(exerciseDate+swapLength) <= liborPeriodDiscretization.getTimeIndex(exerciseDate)) continue;
int numberOfPeriods = (int)(swapLength / swapPeriodLength);
double[] fixingDates = new double[numberOfPeriods];
double[] paymentDates = new double[numberOfPeriods];
double[] swapTenorTimes = new double[numberOfPeriods+1];
for(int periodStartIndex=0; periodStartIndex<numberOfPeriods; periodStartIndex++) {
fixingDates[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength;
paymentDates[periodStartIndex] = exerciseDate + (periodStartIndex+1) * swapPeriodLength;
swapTenorTimes[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength;
}
swapTenorTimes[numberOfPeriods] = exerciseDate + numberOfPeriods * swapPeriodLength;
// Swaptions swap rate
TimeDiscretizationInterface swapTenor = new TimeDiscretization(swapTenorTimes);
double swaprate = Swap.getForwardSwapRate(swapTenor, swapTenor, forwardCurve, null);
// Set swap rates for each period
double[] swaprates = new double[numberOfPeriods];
for(int periodStartIndex=0; periodStartIndex<numberOfPeriods; periodStartIndex++) {
swaprates[periodStartIndex] = swaprate;
}
boolean isUseAnalyticApproximation = true;
if(isUseAnalyticApproximation) {
AbstractLIBORMonteCarloProduct swaption = new SwaptionAnalyticApproximation(swaprate, swapTenorTimes, SwaptionAnalyticApproximation.ValueUnit.VOLATILITY);
double impliedVolatility = swaptionMarketData.getVolatility(exerciseDate, swapLength, swaptionMarketData.getSwapPeriodLength(), swaprate);
calibrationItems.add(new CalibrationItem(swaption, impliedVolatility, 1.0));
}
else {
AbstractLIBORMonteCarloProduct swaption = new SwaptionSimple(swaprate, swapTenorTimes, SwaptionSimple.ValueUnit.VALUE);
double forwardSwaprate = Swap.getForwardSwapRate(swapTenor, swapTenor, forwardCurve);
double swapAnnuity = SwapAnnuity.getSwapAnnuity(swapTenor, forwardCurve);
double impliedVolatility = swaptionMarketData.getVolatility(exerciseDate, swapLength, swaptionMarketData.getSwapPeriodLength(), swaprate);
double targetValue = AnalyticFormulas.blackModelSwaptionValue(forwardSwaprate, impliedVolatility, exerciseDate, swaprate, swapAnnuity);
calibrationItems.add(new CalibrationItem(swaption, targetValue, 1.0));
}
}
}
return calibrationItems.toArray(new CalibrationItem[calibrationItems.size()]);
}
/**
* Return the numeraire at a given time.
* Note: The random variable returned is a defensive copy and may be modified.
* <b>
* Note: This method does not interpolate the numeraire if it is requested outside the liborPeriodDiscretization
* </b>
*
* @param time Time time <i>t</i> for which the numeraire should be returned <i>N(t)</i>.
* @return The numeraire at the specified time as <code>RandomVariable</code>
* @throws net.finmath.exception.CalculationException
*/
@Override
public RandomVariableInterface getNumeraire(double time) throws CalculationException {
return getNumeraire(getTimeIndex(time));
}
@Override
public RandomVariableInterface[] getInitialState() {
double[] liborInitialStates = new double[liborPeriodDiscretization.getNumberOfTimeSteps()];
for(int timeIndex=0; timeIndex<liborPeriodDiscretization.getNumberOfTimeSteps(); timeIndex++) {
double rate = forwardRateCurve.getForward(null, liborPeriodDiscretization.getTime(timeIndex));
liborInitialStates[timeIndex] = Math.log(rate);
}
RandomVariableInterface[] initialStateRandomVariable = new RandomVariableInterface[getNumberOfComponents()];
for(int componentIndex=0; componentIndex<getNumberOfComponents(); componentIndex++) {
initialStateRandomVariable[componentIndex] = new RandomVariable(0.0, liborInitialStates[componentIndex]);
}
return initialStateRandomVariable;
}
/**
* Return the complete vector of the drift for the time index timeIndex, given that current state is realizationAtTimeIndex.
* Note: The random variable returned is a defensive copy and may be modified.
* The drift will be zero for rates being already fixed.
*
* @see net.finmath.montecarlo.interestrate.LIBORMarketModel#getNumeraire(int) The calculation of the drift is consistent with the calculation of the numeraire in <code>getNumeraire</code>.
*
* @param timeIndex Time index <i>i</i> for which the drift should be returned <i>μ(t<sub>i</sub>)</i>.
* @param realizationAtTimeIndex Time current forward rate vector at time index <i>i</i> which should be used in the calculation.
* @return The drift vector μ(t<sub>i</sub>) as <code>RandomVariable[]</code>
* @throws net.finmath.exception.CalculationException
*/
@Override
public RandomVariableInterface[] getDrift(int timeIndex, RandomVariableInterface[] realizationAtTimeIndex, RandomVariableInterface[] realizationPredictor) {
double time = getTime(timeIndex);
int firstLiborIndex = this.getLiborPeriodIndex(time)+1;
if(firstLiborIndex<0) firstLiborIndex = -firstLiborIndex-1 + 1;
// Allocate drift vector and initialize to zero (will be used to sum up drift components)
RandomVariableInterface[] drift = new RandomVariableInterface[getNumberOfComponents()];
RandomVariableInterface[][] covarianceFactorSums = new RandomVariableInterface[getNumberOfComponents()][getNumberOfFactors()];
for(int componentIndex=firstLiborIndex; componentIndex<getNumberOfComponents(); componentIndex++) {
drift[componentIndex] = new RandomVariable(0.0, 0.0);
}
// Calculate drift for the component componentIndex (starting at firstLiborIndex, others are zero)
for(int componentIndex=firstLiborIndex; componentIndex<getNumberOfComponents(); componentIndex++) {
double periodLength = liborPeriodDiscretization.getTimeStep(componentIndex);
RandomVariableInterface libor = realizationAtTimeIndex[componentIndex];
RandomVariableInterface oneStepMeasureTransform = libor.getMutableCopy().discount(libor, periodLength).mult(periodLength);
//oneStepMeasureTransform = oneStepMeasureTransform.mult(libor);
RandomVariableInterface[] factorLoading = getFactorLoading(timeIndex, componentIndex, realizationAtTimeIndex);
RandomVariableInterface[] covarianceFactors = new RandomVariableInterface[getNumberOfFactors()];
for(int factorIndex=0; factorIndex<getNumberOfFactors(); factorIndex++) {
covarianceFactors[factorIndex] = factorLoading[factorIndex].getMutableCopy().mult(oneStepMeasureTransform);
covarianceFactorSums[componentIndex][factorIndex] = covarianceFactors[factorIndex];
if(componentIndex > firstLiborIndex)
covarianceFactorSums[componentIndex][factorIndex] = covarianceFactorSums[componentIndex][factorIndex].add(covarianceFactorSums[componentIndex-1][factorIndex]);
}
for(int factorIndex=0; factorIndex<getNumberOfFactors(); factorIndex++) {
drift[componentIndex] = drift[componentIndex].addProduct(covarianceFactorSums[componentIndex][factorIndex], factorLoading[factorIndex]);
}
}
// Above is the drift for the spot measure: a simple conversion makes it the drift of the terminal measure.
if(measure == Measure.TERMINAL) {
for(int componentIndex=firstLiborIndex; componentIndex<getNumberOfComponents(); componentIndex++) {
drift[componentIndex] = drift[componentIndex].sub(drift[getNumberOfComponents()-1]);
}
}
// Drift adjustment for log-coordinate in each component
for(int componentIndex=firstLiborIndex; componentIndex<getNumberOfComponents(); componentIndex++) {
RandomVariableInterface variance = covarianceModel.getCovariance(timeIndex, componentIndex, componentIndex, realizationAtTimeIndex);
drift[componentIndex] = drift[componentIndex].addProduct(variance, -0.5);
}
return drift;
}
@Override
public RandomVariableInterface getDrift(int timeIndex, int componentIndex, RandomVariableInterface[] realizationAtTimeIndex, RandomVariableInterface[] realizationPredictor) {
// Check if this LIBOR is already fixed
if(getTime(timeIndex) >= this.getLiborPeriod(componentIndex)) {
return null;
}
/*
* We implemented several different methods to calculate the drift
*/
if(driftApproximationMethod == Driftapproximation.PREDICTOR_CORRECTOR && realizationPredictor != null) {
RandomVariableInterface drift = getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex);
RandomVariableInterface driftEulerWithPredictor = getDriftEuler(timeIndex, componentIndex, realizationPredictor);
drift = drift.add(driftEulerWithPredictor).div(2.0);
return drift;
}
else if(driftApproximationMethod == Driftapproximation.LINE_INTEGRAL && realizationPredictor != null) {
return getDriftLineIntegral(timeIndex, componentIndex, realizationAtTimeIndex, realizationPredictor);
}
else {
return getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex);
}
}
@Override
public RandomVariableInterface[] getFactorLoading(int timeIndex, int componentIndex, RandomVariableInterface[] realizationAtTimeIndex)
{
return covarianceModel.getFactorLoading(timeIndex, componentIndex, realizationAtTimeIndex);
}
@Override
public RandomVariableInterface applyStateSpaceTransform(int componentIndex, RandomVariableInterface randomVariable) {
return randomVariable.exp();
}
/**
* @return Returns the driftApproximationMethod.
*/
public Driftapproximation getDriftApproximationMethod() {
return driftApproximationMethod;
}
/* (non-Javadoc)
* @see net.finmath.montecarlo.interestrate.LIBORMarketModelInterface#getLIBOR(int, int)
*/
@Override
public RandomVariableInterface getLIBOR(int timeIndex, int liborIndex) throws CalculationException
{
// This method is just a psynonym - call getProcessValue of super class
return getProcessValue(timeIndex, liborIndex);
}
/**
* This method is just a synonym to getNumberOfLibors
* @return The number of components
*/
@Override
public int getNumberOfComponents() {
return getNumberOfLibors();
}
/* (non-Javadoc)
* @see net.finmath.montecarlo.interestrate.LIBORMarketModelInterface#getNumberOfLibors()
*/
@Override
public int getNumberOfLibors()
{
// This is just a synonym to number of components
return liborPeriodDiscretization.getNumberOfTimeSteps();
}
/* (non-Javadoc)
* @see net.finmath.montecarlo.interestrate.LIBORMarketModelInterface#getLiborPeriod(int)
*/
@Override
public double getLiborPeriod(int timeIndex) {
return liborPeriodDiscretization.getTime(timeIndex);
}
/* (non-Javadoc)
* @see net.finmath.montecarlo.interestrate.LIBORMarketModelInterface#getLiborPeriodIndex(double)
*/
@Override
public int getLiborPeriodIndex(double time) {
return liborPeriodDiscretization.getTimeIndex(time);
}
/* (non-Javadoc)
* @see net.finmath.montecarlo.interestrate.LIBORMarketModelInterface#getLiborPeriodDiscretization()
*/
@Override
public TimeDiscretizationInterface getLiborPeriodDiscretization() {
return liborPeriodDiscretization;
}
protected RandomVariableInterface getDriftEuler(int timeIndex, int componentIndex, RandomVariableInterface[] liborVectorStart) {
// The following is the drift of the LIBOR component
double time = getTime(timeIndex);
// Initialize to 0.0
RandomVariableInterface drift = new RandomVariable(time, 0.0);
// Get the start and end of the summation (start is the LIBOR after the current LIBOR component, end is the last LIBOR)
int firstLiborIndex, lastLiborIndex;
switch(measure) {
case SPOT:
// Spot measure
firstLiborIndex = this.getLiborPeriodIndex(time)+1;
if(firstLiborIndex<0) firstLiborIndex = -firstLiborIndex-1 + 1;
lastLiborIndex = componentIndex;
break;
case TERMINAL:
default:
firstLiborIndex = componentIndex+1;
lastLiborIndex = liborPeriodDiscretization.getNumberOfTimeSteps()-1;
break;
}
// The sum
for(int liborIndex = firstLiborIndex; liborIndex<=lastLiborIndex; liborIndex++) {
double periodLength = liborPeriodDiscretization.getTimeStep(liborIndex);
RandomVariableInterface covariance = covarianceModel.getCovariance(timeIndex, componentIndex, liborIndex, null);
RandomVariableInterface libor = liborVectorStart[liborIndex];
covariance = covariance.mult(periodLength).mult(libor).discount(libor, periodLength);
drift = drift.add(covariance);
}
if(measure == Measure.TERMINAL) {
drift = drift.mult(-1.0);
}
// Drift adjustment for log-coordinate
RandomVariableInterface variance = covarianceModel.getCovariance(timeIndex, componentIndex, componentIndex, null);
drift = drift.addProduct(variance, -0.5);
return drift;
}
private RandomVariableInterface getDriftLineIntegral(int timeIndex, int componentIndex, RandomVariableInterface[] liborVectorStart, RandomVariableInterface[] liborVectorEnd) {
// The following is the dirft of the LIBOR component
double time = getTime(timeIndex);
// Check if this LIBOR is already fixed
if(getTime(timeIndex) >= this.getLiborPeriod(componentIndex)) {
return null;
}
// Initialize to 0.0
RandomVariableInterface drift = new RandomVariable(time, 0.0);
// Get the start and end of the summation (start is the LIBOR after the current LIBOR component, end is the last LIBOR)
int firstLiborIndex, lastLiborIndex;
switch(measure) {
case SPOT:
// Spot measure
firstLiborIndex = this.getLiborPeriodIndex(time)+1;
if(firstLiborIndex<0) firstLiborIndex = -firstLiborIndex-1 + 1;
lastLiborIndex = componentIndex;
break;
case TERMINAL:
default:
firstLiborIndex = componentIndex+1;
lastLiborIndex = liborPeriodDiscretization.getNumberOfTimeSteps()-1;
break;
}
// The sum
for(int liborIndex = firstLiborIndex; liborIndex<=lastLiborIndex; liborIndex++) {
double periodLength = liborPeriodDiscretization.getTimeStep(liborIndex);
RandomVariableInterface covariance = covarianceModel.getCovariance(timeIndex, componentIndex, liborIndex, null);
/*
* We calcululate
* driftTerm = covariance * log( (1 + periodLength * liborVectorEnd[liborIndex]) / (1 + periodLength * liborVectorStart[liborIndex]) )
* / log(liborVectorEnd[liborIndex] / liborVectorStart[liborIndex])
*/
RandomVariableInterface driftTerm = new RandomVariable(1.0);
driftTerm = driftTerm.accrue(liborVectorEnd[liborIndex], periodLength);
driftTerm = driftTerm.discount(liborVectorStart[liborIndex], periodLength);
driftTerm = driftTerm.log();
driftTerm = driftTerm.mult(covariance);
driftTerm = driftTerm.div(liborVectorEnd[liborIndex].getMutableCopy().div(liborVectorStart[liborIndex]).log());
drift = drift.sub(driftTerm);
}
return drift;
}
/**
* @return Returns the measure.
*/
public Measure getMeasure() {
return measure;
}
/**
* Return the numeraire at a given time index.
* Note: The random variable returned is a defensive copy and may be modified.
* <b>
* Note: This method does not interpolate the numeraire if it is requested outside the liborPeriodDiscretization
* </b>
*
* @param timeIndex Time index <i>i</i> for which the numeraire should be returned <i>N(t<sub>i</sub>)</i>.
* @return The numeraire at the specified time as <code>RandomVariable</code>
* @throws net.finmath.exception.CalculationException
*/
public RandomVariableInterface getNumeraire(int timeIndex) throws CalculationException
{
double time = getTime(timeIndex);
// Get the start of the product
int firstLiborIndex = this.getLiborPeriodIndex(time);
// while(liborPeriodDiscretization[firstLiborIndex] < time) firstLiborIndex++;
// Get the end of the product
int lastLiborIndex = liborPeriodDiscretization.getNumberOfTimeSteps()-1;
if(measure == Measure.SPOT) {
// Spot measure
firstLiborIndex = 0;
lastLiborIndex = this.getLiborPeriodIndex(time)-1;
if(lastLiborIndex < -1) {
System.out.println("Interpolation on Numeraire not supported.");
}
}
/*
* Calculation of the numeraire
*/
// Initialize to 1.0
RandomVariableInterface numeraire = new RandomVariable(time, 1.0);
// The product
for(int liborIndex = firstLiborIndex; liborIndex<=lastLiborIndex; liborIndex++) {
RandomVariableInterface libor = getLIBOR(getTimeIndex(Math.min(time,liborPeriodDiscretization.getTime(liborIndex))), liborIndex);
double periodLength = liborPeriodDiscretization.getTimeStep(liborIndex);
if(measure == Measure.SPOT) {
numeraire = numeraire.accrue(libor, periodLength);
}
else {
numeraire = numeraire.discount(libor, periodLength);
}
}
/*
* Adjust for disocunting
*/
if(discountCurve != null) {
DiscountCurveInterface discountcountCurveFromForwardPerformance = new DiscountCurveFromForwardCurve(forwardRateCurve);
double deterministicNumeraireAdjustment = discountcountCurveFromForwardPerformance.getDiscountFactor(time) / discountCurve.getDiscountFactor(time);
numeraire = numeraire.mult(deterministicNumeraireAdjustment);
}
return numeraire;
}
@Override
public synchronized double[][][] getIntegratedLIBORCovariance() {
if(integratedLIBORCovariance != null) return integratedLIBORCovariance;
TimeDiscretizationInterface liborPeriodDiscretization = getLiborPeriodDiscretization();
TimeDiscretizationInterface simulationTimeDiscretization = getTimeDiscretization();
integratedLIBORCovariance = new double[simulationTimeDiscretization.getNumberOfTimeSteps()][liborPeriodDiscretization.getNumberOfTimeSteps()][liborPeriodDiscretization.getNumberOfTimeSteps()];
for(int componentIndex1 = 0; componentIndex1 < liborPeriodDiscretization.getNumberOfTimeSteps(); componentIndex1++) {
// Sum the libor cross terms (use symmetry)
for(int componentIndex2 = componentIndex1; componentIndex2 < liborPeriodDiscretization.getNumberOfTimeSteps(); componentIndex2++) {
double integratedLIBORCovarianceValue = 0.0;
for(int timeIndex = 0; timeIndex < simulationTimeDiscretization.getNumberOfTimeSteps(); timeIndex++) {
double dt = getTime(timeIndex+1) - getTime(timeIndex);
RandomVariableInterface[] factorLoadingOfComponent1 = getCovarianceModel().getFactorLoading(timeIndex, componentIndex1, null);
RandomVariableInterface[] factorLoadingOfComponent2 = getCovarianceModel().getFactorLoading(timeIndex, componentIndex2, null);
for(int factorIndex = 0; factorIndex < getNumberOfFactors(); factorIndex++) {
integratedLIBORCovarianceValue += factorLoadingOfComponent1[factorIndex].get(0) * factorLoadingOfComponent2[factorIndex].get(0) * dt;
}
integratedLIBORCovariance[timeIndex][componentIndex1][componentIndex2] = integratedLIBORCovarianceValue;
}
}
}
return integratedLIBORCovariance;
}
@Override
public Object clone() {
return new LIBORMarketModel(liborPeriodDiscretization, forwardRateCurve, covarianceModel);
}
/**
* @param driftApproximationMethod The driftApproximationMethod to set.
*/
public void setDriftApproximationMethod(Driftapproximation driftApproximationMethod) {
this.driftApproximationMethod = driftApproximationMethod;
}
/**
* @param measure The measure to set.
*/
public void setMeasure(Measure measure) {
this.measure = measure;
}
/* (non-Javadoc)
* @see net.finmath.montecarlo.interestrate.LIBORMarketModelInterface#getForwardRateCurve()
*/
@Override
public ForwardCurveInterface getForwardRateCurve() {
return forwardRateCurve;
}
/**
* Return the swaption market data used for calibration (if any, may be null).
*
* @return The swaption market data used for calibration (if any, may be null).
*/
public AbstractSwaptionMarketData getSwaptionMarketData() {
return swaptionMarketData;
}
/* (non-Javadoc)
* @see net.finmath.montecarlo.interestrate.LIBORMarketModelInterface#getCovarianceModel()
*/
@Override
public AbstractLIBORCovarianceModel getCovarianceModel() {
return covarianceModel;
}
/**
* @param covarianceModel the covarianceModel to set
* @deprecated
*/
@Deprecated
public void setCovarianceModel(AbstractLIBORCovarianceModel covarianceModel) {
this.covarianceModel = covarianceModel;
}
/**
* @param covarianceModel A covariance model
* @return A new <code>LIBORMarketModel</code> using the specified covariance model.
*/
@Override
public LIBORMarketModel getCloneWithModifiedCovarianceModel(AbstractLIBORCovarianceModel covarianceModel) {
LIBORMarketModel model = (LIBORMarketModel)this.clone();
model.setCovarianceModel(covarianceModel);
return model;
}
@Override
public LIBORMarketModel getCloneWithModifiedData(Map<String, Object> dataModified) throws CalculationException {
TimeDiscretizationInterface liborPeriodDiscretization = this.liborPeriodDiscretization;
ForwardCurveInterface forwardRateCurve = this.forwardRateCurve;
AbstractLIBORCovarianceModel covarianceModel = this.covarianceModel;
AbstractSwaptionMarketData swaptionMarketData = null;
if(dataModified.containsKey("liborPeriodDiscretization")) {
liborPeriodDiscretization = (TimeDiscretizationInterface)dataModified.get("liborPeriodDiscretization");
}
if(dataModified.containsKey("forwardRateCurve")) {
forwardRateCurve = (ForwardCurveInterface)dataModified.get("forwardRateCurve");
}
if(dataModified.containsKey("forwardRateShift")) {
forwardRateCurve = (ForwardCurveInterface)dataModified.get("forwardRateCurve");
// throw new RuntimeException("Forward rate shift clone currently disabled.");
}
if(dataModified.containsKey("covarianceModel")) {
covarianceModel = (AbstractLIBORCovarianceModel)dataModified.get("covarianceModel");
}
if(dataModified.containsKey("swaptionMarketData")) {
swaptionMarketData = (AbstractSwaptionMarketData)dataModified.get("covarianceModel");
}
if(swaptionMarketData == null) {
return new LIBORMarketModel(liborPeriodDiscretization, forwardRateCurve, covarianceModel);
}
else {
return new LIBORMarketModel(liborPeriodDiscretization, forwardRateCurve, covarianceModel, swaptionMarketData);
}
}
}
|
package br.com.redesocial.modelo.dao;
import br.com.redesocial.modelo.dto.Cidade;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
/**
*
* @author Ronneesley Moura Teles, Ianka,
* @since 08/08/2017
*/
public class CidadeDAO extends DAOCRUDBase<Cidade> {
@Override
public void inserir(Cidade dto) throws Exception {
Connection conexao = getConexao();
if (dto.getNome().trim().equals("")){
throw new Exception("O campo estado não pode estar vazio.");
}
if (dto.getEstado() == null){
throw new Exception("O campo nome não pode estar vazio.");
}
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("insert into cidades(nome, estado) values(?, ?)");
pstmt.setString(1, dto.getNome());
pstmt.setInt(2, dto.getEstado().getId());
pstmt.executeUpdate();
dto.setId(getId(pstmt));
}
@Override
public void alterar(Cidade dto) throws Exception {
Connection conexao = getConexao();
}
@Override
public Cidade selecionar(int id) throws Exception {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List listar() throws Exception {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void excluir(int id) throws Exception {
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("delete from cidades where id = ?");
pstmt.setInt(1, id);
pstmt.executeUpdate();
}
}
|
package com.essiembre.eclipse.rbe.ui.editor.i18n;
import java.util.Iterator;
import java.util.Locale;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
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.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.texteditor.ITextEditor;
import com.essiembre.eclipse.rbe.model.bundle.BundleEntry;
import com.essiembre.eclipse.rbe.model.bundle.BundleGroup;
import com.essiembre.eclipse.rbe.model.bundle.visitors.DuplicateValuesVisitor;
import com.essiembre.eclipse.rbe.ui.RBEPlugin;
import com.essiembre.eclipse.rbe.ui.UIUtils;
import com.essiembre.eclipse.rbe.ui.editor.ResourceBundleEditor;
import com.essiembre.eclipse.rbe.ui.editor.resources.ResourceManager;
import com.essiembre.eclipse.rbe.ui.editor.resources.SourceEditor;
import com.essiembre.eclipse.rbe.ui.preferences.RBEPreferences;
/**
* Represents a data entry section for a bundle entry.
* @author Pascal Essiembre (essiembre@users.sourceforge.net)
* @version $Author$ $Revision$ $Date$
*/
public class BundleEntryComposite extends Composite {
private final ResourceManager resourceManager;
private final Locale locale;
private final Font boldFont;
private final Font smallFont;
private final Color yellowColor = UIUtils.getSystemColor(SWT.COLOR_YELLOW);
private ImageRegistry imageRegistry = new ImageRegistry();
private Text textBox;
private Button commentedCheckbox;
private Button gotoButton;
private Button duplButton;
private Button simButton;
private String activeKey;
private String textBeforeUpdate;
private DuplicateValuesVisitor duplVisitor;
/**
* Constructor.
*/
public BundleEntryComposite(
final Composite parent,
final ResourceManager resourceManager,
final Locale locale) {
super(parent, SWT.NONE);
this.resourceManager = resourceManager;
this.locale = locale;
this.boldFont = UIUtils.createFont(this, SWT.BOLD, 0);
this.smallFont = UIUtils.createFont(SWT.NONE, -1);
GridLayout gridLayout = new GridLayout(1, false);
gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 2;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
setLayout(gridLayout);
setLayoutData(new GridData(GridData.FILL_BOTH));
createLabelRow();
createTextRow();
}
/**
* Update bundles if the value of the active key changed.
*/
public void updateBundleOnChanges(){
if (activeKey != null) {
BundleGroup bundleGroup = resourceManager.getBundleGroup();
BundleEntry entry = bundleGroup.getBundleEntry(locale, activeKey);
boolean commentedSelected = commentedCheckbox.getSelection();
if (entry == null || !textBox.getText().equals(entry.getValue())
|| entry.isCommented() != commentedSelected) {
String comment = null;
if (entry != null) {
comment = entry.getComment();
}
bundleGroup.addBundleEntry(locale, new BundleEntry(
activeKey,
textBox.getText(),
comment,
commentedSelected));
}
}
}
/**
* @see org.eclipse.swt.widgets.Widget#dispose()
*/
public void dispose() {
super.dispose();
boldFont.dispose();
smallFont.dispose();
}
/**
* Refreshes the text field value with value matching given key.
* @param key key used to grab value
*/
public void refresh(String key) {
activeKey = key;
BundleGroup bundleGroup = resourceManager.getBundleGroup();
if (key != null && bundleGroup.isKey(key)) {
BundleEntry bundleEntry = bundleGroup.getBundleEntry(locale, key);
SourceEditor sourceEditor = resourceManager.getSourceEditor(locale);
if (bundleEntry == null) {
textBox.setText("");
commentedCheckbox.setSelection(false);
} else {
commentedCheckbox.setSelection(bundleEntry.isCommented());
textBox.setText(bundleEntry.getValue());
}
commentedCheckbox.setEnabled(!sourceEditor.isReadOnly());
textBox.setEnabled(!sourceEditor.isReadOnly());
gotoButton.setEnabled(true);
if (RBEPreferences.getReportDuplicateValues()) {
findDuplicates(bundleEntry);
}
if (RBEPreferences.getReportSimilarValues()) {
if (RBEPreferences.getReportSimilarValuesLevensthein()) {
} else {
}
}
} else {
commentedCheckbox.setSelection(false);
commentedCheckbox.setEnabled(false);
textBox.setText("");
textBox.setEnabled(false);
gotoButton.setEnabled(false);
duplButton.setVisible(false);
simButton.setVisible(false);
}
resetCommented();
}
private void findDuplicates(BundleEntry bundleEntry) {
BundleGroup bundleGroup = resourceManager.getBundleGroup();
if (duplVisitor == null) {
duplVisitor = new DuplicateValuesVisitor();
}
duplVisitor.clear();
bundleGroup.getBundle(locale).accept(duplVisitor, bundleEntry);
duplButton.setVisible(duplVisitor.getDuplicates().size() > 0);
}
/**
* Creates the text field label, icon, and commented check box.
*/
private void createLabelRow() {
Composite labelComposite = new Composite(this, SWT.NONE);
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 6;
gridLayout.horizontalSpacing = 5;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
labelComposite.setLayout(gridLayout);
labelComposite.setLayoutData(
new GridData(GridData.FILL_HORIZONTAL));
// Locale text
Label txtLabel = new Label(labelComposite, SWT.NONE);
txtLabel.setText(" " + UIUtils.getDisplayName(locale) + " ");
txtLabel.setFont(boldFont);
GridData gridData = new GridData();
// Similar button
gridData = new GridData();
gridData.horizontalAlignment = GridData.END;
simButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT);
simButton.setImage(RBEPlugin.getImageDescriptor("similar.gif").createImage());
simButton.setLayoutData(gridData);
simButton.setVisible(false);
simButton.setToolTipText(
"Similar value(s) found. Click for details");
// Duplicate button
gridData.horizontalAlignment = GridData.END;
gridData.grabExcessHorizontalSpace = true;
duplButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT);
duplButton.setImage(RBEPlugin.getImageDescriptor("duplicate.gif").createImage());
duplButton.setLayoutData(gridData);
duplButton.setVisible(false);
duplButton.setToolTipText(
"Duplicate value(s) found. Click for details");
duplButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
String msg = "Below are keys having the same value has key \""
+ activeKey + "\" within the locale \""
+ locale.getDisplayName() + "\":\n\n";
for (Iterator iter = duplVisitor.getDuplicates().iterator();
iter.hasNext();) {
msg += " " + ((BundleEntry) iter.next()).getKey()
+ "\n";
}
MessageDialog.openInformation(
getShell(), "Duplicate value(s) found.", msg);
}
});
// Commented checkbox
gridData = new GridData();
gridData.horizontalAlignment = GridData.END;
//gridData.grabExcessHorizontalSpace = true;
commentedCheckbox = new Button(
labelComposite, SWT.CHECK);
commentedCheckbox.setText("#");//TODO translate
commentedCheckbox.setFont(smallFont);
commentedCheckbox.setLayoutData(gridData);
commentedCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
resetCommented();
updateBundleOnChanges();
}
});
commentedCheckbox.setEnabled(false);
// Country flag
gridData = new GridData();
gridData.horizontalAlignment = GridData.END;
Label imgLabel = new Label(labelComposite, SWT.NONE);
imgLabel.setLayoutData(gridData);
imgLabel.setImage(loadCountryIcon(locale));
// Goto button
gridData = new GridData();
gridData.horizontalAlignment = GridData.END;
gotoButton = new Button(
labelComposite, SWT.ARROW | SWT.RIGHT);
gotoButton.setToolTipText(
"Click to go to corresponding properties file");
gotoButton.setEnabled(false);
gotoButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
ITextEditor editor = resourceManager.getSourceEditor(
locale).getEditor();
Object activeEditor =
editor.getSite().getPage().getActiveEditor();
if (activeEditor instanceof ResourceBundleEditor) {
((ResourceBundleEditor) activeEditor).setActivePage(locale);
}
}
});
gotoButton.setLayoutData(gridData);
}
/**
* Creates the text row.
*/
private void createTextRow() {
textBox = new Text(this, SWT.MULTI | SWT.WRAP |
SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
textBox.setEnabled(false);
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.FILL;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
textBox.setLayoutData(gridData);
textBox.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent event) {
textBeforeUpdate = textBox.getText();
}
public void focusLost(FocusEvent event) {
updateBundleOnChanges();
}
});
//TODO add a preference property listener and add/remove this listener
textBox.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent event) {
if (!RBEPreferences.getFieldTabInserts()
&& event.character == SWT.TAB) {
event.doit = true;
}
}
});
textBox.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
Text textBox = (Text) event.widget;
final ITextEditor editor = resourceManager.getSourceEditor(
locale).getEditor();
// Text field has changed: make editor dirty if not already
if (textBeforeUpdate != null
&& !textBeforeUpdate.equals(textBox.getText())) {
// Make the editor dirty if not already. If it is,
// we wait until field focus lost (or save) to
// update it completely.
if (!editor.isDirty()) {
int caretPosition = textBox.getCaretPosition();
updateBundleOnChanges();
textBox.setSelection(caretPosition);
}
// Text field is the same as original (make non-dirty)
} else {
if (editor.isDirty()) {
getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
editor.doRevertToSaved();
}
});
}
}
}
});
}
/**
* Loads country icon based on locale country.
* @param locale the locale on which to grab the country
* @return an image, or <code>null</code> if no match could be made
*/
private Image loadCountryIcon(Locale locale) {
Image image = null;
String countryCode = null;
if (locale != null && locale.getCountry() != null) {
countryCode = locale.getCountry().toLowerCase();
}
if (countryCode != null && countryCode.length() > 0) {
String imageName =
"countries/" + countryCode.toLowerCase() + ".gif";
image = imageRegistry.get(imageName);
if (image == null) {
image = RBEPlugin.getImageDescriptor(imageName).createImage();
imageRegistry.put(imageName, image);
}
}
if (image == null) {
image = imageRegistry.get("countries/blank.gif");
if (image == null) {
String imageName = "countries/blank.gif";
image = RBEPlugin.getImageDescriptor(imageName).createImage();
imageRegistry.put(imageName, image);
}
}
return image;
}
private void resetCommented() {
if (commentedCheckbox.getSelection()) {
commentedCheckbox.setToolTipText(
"Uncheck to uncomment this entry.");
textBox.setForeground(
getDisplay().getSystemColor(SWT.COLOR_GRAY));
} else {
commentedCheckbox.setToolTipText(
"Check to comment this entry.");
textBox.setForeground(null);
}
}
}
|
package net.java.sip.communicator.service.httputil;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.swing.*;
import org.apache.http.*;
import org.apache.http.Header;
import org.apache.http.auth.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.client.params.*;
import org.apache.http.client.utils.*;
import org.apache.http.conn.scheme.*;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.*;
import org.apache.http.entity.mime.*;
import org.apache.http.entity.mime.content.*;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.*;
import org.apache.http.message.*;
import org.apache.http.params.*;
import org.apache.http.protocol.*;
import org.apache.http.util.*;
import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.*;
import java.util.*;
/**
* Common http utils querying http locations, handling redirects, self-signed
* certificates, host verify on certificates, password protection and storing
* and reusing credentials for password protected sites.
*
* @author Damian Minkov
*/
public class HttpUtils
{
/**
* The <tt>Logger</tt> used by the <tt>HttpUtils</tt> class for logging
* output.
*/
private static final Logger logger = Logger.getLogger(HttpUtils.class);
/**
* The prefix used when storing credentials for sites when no property
* is provided.
*/
private static final String HTTP_CREDENTIALS_PREFIX =
"net.java.sip.communicator.util.http.credential.";
/**
* Maximum number of http redirects (301, 302, 303).
*/
private static final int MAX_REDIRECTS = 10;
/**
* Opens a connection to the <tt>address</tt>.
* @param address the address to contact.
* @return the result if any or null if connection was not possible
* or canceled by user.
*/
public static HTTPResponseResult openURLConnection(String address)
{
return openURLConnection(address, null, null, null, null);
}
/**
* Opens a connection to the <tt>address</tt>.
* @param address the address to contact.
* @param headerParamNames additional header name to include
* @param headerParamValues corresponding header value to include
* @return the result if any or null if connection was not possible
* or canceled by user.
*/
public static HTTPResponseResult openURLConnection(String address,
String[] headerParamNames,
String[] headerParamValues)
{
return openURLConnection(address, null, null, headerParamNames,
headerParamValues);
}
/**
* Opens a connection to the <tt>address</tt>.
* @param address the address to contact.
* @param usernamePropertyName the property to use to retrieve/store
* username value if protected site is hit, for username
* ConfigurationService service is used.
* @param passwordPropertyName the property to use to retrieve/store
* password value if protected site is hit, for password
* CredentialsStorageService service is used.
* @param headerParamNames additional header name to include
* @param headerParamValues corresponding header value to include
* @return the result if any or null if connection was not possible
* or canceled by user.
*/
public static HTTPResponseResult openURLConnection(String address,
String usernamePropertyName,
String passwordPropertyName,
String[] headerParamNames,
String[] headerParamValues)
{
try
{
HttpGet httpGet = new HttpGet(address);
DefaultHttpClient httpClient = getHttpClient(
usernamePropertyName, passwordPropertyName,
httpGet.getURI().getHost(), null);
/* add additional HTTP header */
if(headerParamNames != null && headerParamValues != null)
{
for(int i = 0 ; i < headerParamNames.length ; i++)
{
httpGet.addHeader(new BasicHeader(headerParamNames[i],
headerParamValues[i]));
}
}
HttpEntity result = executeMethod(httpClient, httpGet);
if(result == null)
return null;
return new HTTPResponseResult(result, httpClient);
}
catch(Throwable t)
{
logger.error("Cannot open connection to:" + address, t);
}
return null;
}
/**
* Executes the method and return the result. Handle ask for password
* when hitting password protected site.
* Keep asking for password till user clicks cancel or enters correct
* password. When 'remember password' is checked password is saved, if this
* password and username are not correct clear them, if there are correct
* they stay saved.
* @param httpClient the configured http client to use.
* @param req the request for now it is get or post.
* @return the result http entity.
*/
private static HttpEntity executeMethod(DefaultHttpClient httpClient,
HttpRequestBase req)
throws Throwable
{
// do it when response (first execution) or till we are unauthorized
HttpResponse response = null;
int redirects = 0;
while(response == null
|| response.getStatusLine().getStatusCode()
== HttpStatus.SC_UNAUTHORIZED
|| response.getStatusLine().getStatusCode()
== HttpStatus.SC_FORBIDDEN)
{
// if we were unauthorized, lets clear the method and recreate it
// for new connection with new credentials.
if(response != null
&& (response.getStatusLine().getStatusCode()
== HttpStatus.SC_UNAUTHORIZED
|| response.getStatusLine().getStatusCode()
== HttpStatus.SC_FORBIDDEN))
{
if(logger.isDebugEnabled())
logger.debug("Will retry http connect and " +
"credentials input as latest are not correct!");
throw new AuthenticationException("Authorization needed");
}
else
response = httpClient.execute(req);
// if user click cancel no need to retry, stop trying
if(!((HTTPCredentialsProvider)httpClient
.getCredentialsProvider()).retry())
{
if(logger.isDebugEnabled())
logger.debug("User canceled credentials input.");
break;
}
// check for post redirect as post redirects are not handled
// automatically
// RFC2616 (10.3 Redirection 3xx).
// The second request (forwarded method) can only be a GET or HEAD.
Header locationHeader = response.getFirstHeader("location");
if(locationHeader != null
&& req instanceof HttpPost
&& (response.getStatusLine().getStatusCode()
== HttpStatus.SC_MOVED_PERMANENTLY
|| response.getStatusLine().getStatusCode()
== HttpStatus.SC_MOVED_TEMPORARILY
|| response.getStatusLine().getStatusCode()
== HttpStatus.SC_SEE_OTHER)
&& redirects < MAX_REDIRECTS)
{
HttpRequestBase oldreq = req;
oldreq.abort();
String newLocation = locationHeader.getValue();
// append query string if any
HttpEntity en = ((HttpPost) oldreq).getEntity();
if(en != null && en instanceof StringEntity)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
en.writeTo(out);
newLocation += "?" + out.toString("UTF-8");
}
req = new HttpGet(newLocation);
req.setParams(oldreq.getParams());
req.setHeaders(oldreq.getAllHeaders());
redirects++;
response = httpClient.execute(req);
}
}
// if we finally managed to login return the result.
if(response != null
&& response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
return response.getEntity();
}
// is user has canceled no result needed.
return null;
}
/**
* Posts a <tt>file</tt> to the <tt>address</tt>.
* @param address the address to post the form to.
* @param fileParamName the name of the param for the file.
* @param file the file we will send.
* @return the result or null if send was not possible or
* credentials ask if any was canceled.
*/
public static HTTPResponseResult postFile(String address,
String fileParamName,
File file)
{
return postFile(address, fileParamName, file, null, null);
}
/**
* Posts a <tt>file</tt> to the <tt>address</tt>.
* @param address the address to post the form to.
* @param fileParamName the name of the param for the file.
* @param file the file we will send.
* @param usernamePropertyName the property to use to retrieve/store
* username value if protected site is hit, for username
* ConfigurationService service is used.
* @param passwordPropertyName the property to use to retrieve/store
* password value if protected site is hit, for password
* CredentialsStorageService service is used.
* @return the result or null if send was not possible or
* credentials ask if any was canceled.
*/
public static HTTPResponseResult postFile(String address,
String fileParamName,
File file,
String usernamePropertyName,
String passwordPropertyName)
{
DefaultHttpClient httpClient = null;
try
{
HttpPost postMethod = new HttpPost(address);
httpClient = getHttpClient(
usernamePropertyName, passwordPropertyName,
postMethod.getURI().getHost(), null);
String mimeType = URLConnection.guessContentTypeFromName(
file.getPath());
if(mimeType == null)
mimeType = "application/octet-stream";
FileBody bin = new FileBody(file, mimeType);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart(fileParamName, bin);
postMethod.setEntity(reqEntity);
HttpEntity resEntity = executeMethod(httpClient, postMethod);
if(resEntity == null)
return null;
return new HTTPResponseResult(resEntity, httpClient);
}
catch(Throwable e)
{
logger.error("Cannot post file to:" + address, e);
}
return null;
}
/**
* Posting form to <tt>address</tt>. For submission we use POST method
* which is "application/x-www-form-urlencoded" encoded.
* @param address HTTP address.
* @param usernamePropertyName the property to use to retrieve/store
* username value if protected site is hit, for username
* ConfigurationService service is used.
* @param passwordPropertyName the property to use to retrieve/store
* password value if protected site is hit, for password
* CredentialsStorageService service is used.
* @param formParamNames the parameter names to include in post.
* @param formParamValues the corresponding parameter values to use.
* @param usernameParamIx the index of the username parameter in the
* <tt>formParamNames</tt> and <tt>formParamValues</tt>
* if any, otherwise -1.
* @param passwordParamIx the index of the password parameter in the
* <tt>formParamNames</tt> and <tt>formParamValues</tt>
* if any, otherwise -1.
* @return the result or null if send was not possible or
* credentials ask if any was canceled.
*/
public static HTTPResponseResult postForm(String address,
String usernamePropertyName,
String passwordPropertyName,
String[] formParamNames,
String[] formParamValues,
int usernameParamIx,
int passwordParamIx)
{
DefaultHttpClient httpClient;
HttpPost postMethod;
HttpEntity resEntity = null;
try
{
// if any authentication exception rise while executing
// will retry
AuthenticationException authEx;
HTTPCredentialsProvider credentialsProvider = null;
do
{
postMethod = new HttpPost(address);
httpClient = getHttpClient(
usernamePropertyName, passwordPropertyName,
postMethod.getURI().getHost(), credentialsProvider);
try
{
// execute post
resEntity = postForm(
httpClient,
postMethod,
address,
usernamePropertyName,
passwordPropertyName,
formParamNames,
formParamValues,
usernameParamIx,
passwordParamIx);
authEx = null;
}
catch(AuthenticationException ex)
{
authEx = ex;
// lets reuse credentialsProvider
credentialsProvider = (HTTPCredentialsProvider)
httpClient.getCredentialsProvider();
String userName = credentialsProvider.authUsername;
// clear
credentialsProvider.clear();
// lets show the same username
credentialsProvider.authUsername = userName;
credentialsProvider.errorMessage =
HttpUtilActivator.getResources().getI18NString(
"service.gui.AUTHENTICATION_FAILED",
new String[]
{credentialsProvider.usedScope.getHost()});
}
}
while(authEx != null);
// canceled or no result
if(resEntity == null)
return null;
return new HTTPResponseResult(resEntity, httpClient);
}
catch(Throwable e)
{
logger.error("Error posting form", e);
}
return null;
}
/**
* Posting form to <tt>address</tt>. For submission we use POST method
* which is "application/x-www-form-urlencoded" encoded.
* @param httpClient the http client
* @param postMethod the post method
* @param address HTTP address.
* @param usernamePropertyName the property to use to retrieve/store
* username value if protected site is hit, for username
* ConfigurationService service is used.
* @param passwordPropertyName the property to use to retrieve/store
* password value if protected site is hit, for password
* CredentialsStorageService service is used.
* @param formParamNames the parameter names to include in post.
* @param formParamValues the corresponding parameter values to use.
* @param usernameParamIx the index of the username parameter in the
* <tt>formParamNames</tt> and <tt>formParamValues</tt>
* if any, otherwise -1.
* @param passwordParamIx the index of the password parameter in the
* <tt>formParamNames</tt> and <tt>formParamValues</tt>
* if any, otherwise -1.
* @return the result or null if send was not possible or
* credentials ask if any was canceled.
*/
private static HttpEntity postForm(
DefaultHttpClient httpClient,
HttpPost postMethod,
String address,
String usernamePropertyName,
String passwordPropertyName,
String[] formParamNames,
String[] formParamValues,
int usernameParamIx,
int passwordParamIx)
throws Throwable
{
// if we have username and password in the parameters, lets
// retrieve their values
Credentials creds = null;
if(usernameParamIx != -1
&& usernameParamIx < formParamNames.length
&& passwordParamIx != -1
&& passwordParamIx < formParamNames.length)
{
URL url = new URL(address);
HTTPCredentialsProvider prov = (HTTPCredentialsProvider)
httpClient.getCredentialsProvider();
// don't allow empty username
while(creds == null
|| creds.getUserPrincipal() == null
|| StringUtils.isNullOrEmpty(
creds.getUserPrincipal().getName()))
{
creds = prov.getCredentials(
new AuthScope(url.getHost(), url.getPort()));
// it was user canceled lets stop processing
if(creds == null && !prov.retry())
{
return null;
}
}
}
// construct the name value pairs we will be sending
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
// there can be no params
if(formParamNames != null)
{
for(int i = 0; i < formParamNames.length; i++)
{
// we are on the username index, insert retrieved username value
if(i == usernameParamIx && creds != null)
{
parameters.add(new BasicNameValuePair(
formParamNames[i], creds.getUserPrincipal().getName()));
}// we are on the password index, insert retrieved password val
else if(i == passwordParamIx && creds != null)
{
parameters.add(new BasicNameValuePair(
formParamNames[i], creds.getPassword()));
}
else // common name value pair, all info is present
{
parameters.add(new BasicNameValuePair(
formParamNames[i], formParamValues[i]));
}
}
}
String s = URLEncodedUtils.format(parameters, HTTP.UTF_8);
StringEntity entity = new StringEntity(s, HTTP.UTF_8);
// set content type to "application/x-www-form-urlencoded"
entity.setContentType(URLEncodedUtils.CONTENT_TYPE);
// insert post values encoded.
postMethod.setEntity(entity);
// execute post
return executeMethod(httpClient, postMethod);
}
/**
* Returns the preconfigured http client,
* using CertificateVerificationService, timeouts, user-agent,
* hostname verifier, proxy settings are used from global java settings,
* if protected site is hit asks for credentials
* using util.swing.AuthenticationWindow.
* @param usernamePropertyName the property to use to retrieve/store
* username value if protected site is hit, for username
* ConfigurationService service is used.
* @param passwordPropertyName the property to use to retrieve/store
* password value if protected site is hit, for password
* CredentialsStorageService service is used.
* @param credentialsProvider if not null provider will bre reused
* in the new client
* @param address the address we will be connecting to
*/
private static DefaultHttpClient getHttpClient(
String usernamePropertyName,
String passwordPropertyName,
final String address,
HTTPCredentialsProvider credentialsProvider)
throws IOException
{
HttpParams params = new BasicHttpParams();
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
params.setParameter(ClientPNames.MAX_REDIRECTS, MAX_REDIRECTS);
DefaultHttpClient httpClient = new DefaultHttpClient(params);
HttpProtocolParams.setUserAgent(httpClient.getParams(),
System.getProperty("sip-communicator.application.name")
+ "/"
+ System.getProperty("sip-communicator.version"));
SSLContext sslCtx;
try
{
sslCtx = HttpUtilActivator.getCertificateVerificationService()
.getSSLContext(
HttpUtilActivator.getCertificateVerificationService()
.getTrustManager(address));
}
catch (GeneralSecurityException e)
{
throw new IOException(e.getMessage());
}
Scheme sch =
new Scheme("https", 443, new SSLSocketFactory(sslCtx,
SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER));
httpClient.getConnectionManager().getSchemeRegistry().register(sch);
//TODO: wrap the SSLSocketFactory to use our own DNS resolution
//TODO: register socketfactory for http to use our own DNS resolution
// set proxy from default jre settings
ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
httpClient.getConnectionManager().getSchemeRegistry(),
ProxySelector.getDefault());
httpClient.setRoutePlanner(routePlanner);
if(credentialsProvider == null)
credentialsProvider =
new HTTPCredentialsProvider(
usernamePropertyName, passwordPropertyName);
httpClient.setCredentialsProvider(credentialsProvider);
return httpClient;
}
/**
* The provider asking for password that is inserted into httpclient.
*/
private static class HTTPCredentialsProvider
implements CredentialsProvider
{
/**
* Should we continue retrying, this is set when user hits cancel.
*/
private boolean retry = true;
/**
* The last scope we have used, no problem overriding cause
* we use new HTTPCredentialsProvider instance for every
* httpclient/request.
*/
private AuthScope usedScope = null;
/**
* The property to use to retrieve/store
* username value if protected site is hit, for username
* ConfigurationService service is used.
*/
private String usernamePropertyName = null;
/**
* The property to use to retrieve/store
* password value if protected site is hit, for password
* CredentialsStorageService service is used.
*/
private String passwordPropertyName = null;
/**
* Authentication username if any.
*/
private String authUsername = null;
/**
* Authentication password if any.
*/
private String authPassword = null;
/**
* Error message.
*/
private String errorMessage = null;
/**
* Creates HTTPCredentialsProvider.
* @param usernamePropertyName the property to use to retrieve/store
* username value if protected site is hit, for username
* ConfigurationService service is used.
* @param passwordPropertyName the property to use to retrieve/store
* password value if protected site is hit, for password
* CredentialsStorageService service is used.
*/
HTTPCredentialsProvider(String usernamePropertyName,
String passwordPropertyName)
{
this.usernamePropertyName = usernamePropertyName;
this.passwordPropertyName = passwordPropertyName;
}
/**
* Not used.
*/
public void setCredentials(AuthScope authscope, Credentials credentials)
{}
/**
* Get the {@link org.apache.http.auth.Credentials credentials} for the
* given authentication scope.
*
* @param authscope the {@link org.apache.http.auth.AuthScope
* authentication scope}
* @return the credentials
* @see #setCredentials(org.apache.http.auth.AuthScope,
* org.apache.http.auth.Credentials)
*/
public Credentials getCredentials(AuthScope authscope)
{
this.usedScope = authscope;
// if we have specified password and username property will use them
// if not create one from the scope/site we are connecting to.
if(passwordPropertyName == null)
passwordPropertyName = getCredentialProperty(authscope);
if(usernamePropertyName == null)
usernamePropertyName = getCredentialProperty(authscope);
// load the password
String pass =
HttpUtilActivator.getCredentialsService().loadPassword(
passwordPropertyName);
// if password is not saved ask user for credentials
if(pass == null)
{
AuthenticationWindow authWindow =
new AuthenticationWindow(
authUsername, null,
authscope.getHost(), true, null, errorMessage);
authWindow.setVisible(true);
if(!authWindow.isCanceled())
{
Credentials cred = new UsernamePasswordCredentials(
authWindow.getUserName(),
new String(authWindow.getPassword())
);
authUsername = authWindow.getUserName();
authPassword = new String(authWindow.getPassword());
// if password remember is checked lets save passwords,
// if they seem not correct later will be removed.
if(authWindow.isRememberPassword())
{
HttpUtilActivator.getConfigurationService().setProperty(
usernamePropertyName,
authWindow.getUserName());
HttpUtilActivator.getCredentialsService().storePassword(
passwordPropertyName,
new String(authWindow.getPassword())
);
}
return cred;
}
// well user canceled credentials input stop retry asking him
// if credentials are not correct
retry = false;
}
else
{
// we have saved values lets return them
authUsername =
HttpUtilActivator.getConfigurationService().getString(
usernamePropertyName);
authPassword = pass;
return new UsernamePasswordCredentials(
HttpUtilActivator.getConfigurationService().getString(
usernamePropertyName),
pass);
}
return null;
}
/**
* Clear saved password. Used when we are in situation that
* saved username and password are no longer valid.
*/
public void clear()
{
if(usedScope != null)
{
if(passwordPropertyName == null)
passwordPropertyName = getCredentialProperty(usedScope);
if(usernamePropertyName == null)
usernamePropertyName = getCredentialProperty(usedScope);
HttpUtilActivator.getConfigurationService().removeProperty(
usernamePropertyName);
HttpUtilActivator.getCredentialsService().removePassword(
passwordPropertyName);
}
authUsername = null;
authPassword = null;
errorMessage = null;
}
/**
* Constructs property name for save if one is not specified.
* Its in the form
* HTTP_CREDENTIALS_PREFIX.host.realm.port
* @param authscope the scope, holds host,realm, port info about
* the host we are reaching.
* @return return the constructed property.
*/
private static String getCredentialProperty(AuthScope authscope)
{
StringBuilder pref = new StringBuilder();
pref.append(HTTP_CREDENTIALS_PREFIX).append(authscope.getHost())
.append(".").append(authscope.getRealm())
.append(".").append(authscope.getPort());
return pref.toString();
}
/**
* Whether we need to continue retrying.
* @return whether we need to continue retrying.
*/
boolean retry()
{
return retry;
}
/**
* Returns authentication username if any
* @return authentication username or null
*/
public String getAuthenticationUsername()
{
return authUsername;
}
/**
* Returns authentication password if any
* @return authentication password or null
*/
public String getAuthenticationPassword()
{
return authPassword;
}
}
/**
* Input stream wrapper which handles closing the httpclient when
* everything is retrieved.
*/
private static class HttpClientInputStream
extends InputStream
{
/**
* The original input stream.
*/
InputStream in;
/**
* The http client to close.
*/
HttpClient httpClient;
/**
* Creates HttpClientInputStream.
* @param in the original input stream.
* @param httpClient the http client to close.
*/
HttpClientInputStream(InputStream in, HttpClient httpClient)
{
this.in = in;
this.httpClient = httpClient;
}
/**
* Uses parent InputStream read method.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
* @throws java.io.IOException if an I/O error occurs.
*/
@Override
public int read()
throws IOException
{
return in.read();
}
/**
* Closes this input stream and releases any system resources associated
* with the stream. Releases httpclient connections.
*
* <p> The <code>close</code> method of <code>InputStream</code> does
* nothing.
*
* @exception IOException if an I/O error occurs.
*/
public void close()
throws IOException
{
super.close();
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate de-allocation of all system resources
httpClient.getConnectionManager().shutdown();
}
}
/**
* Utility class wraps the http requests result and some utility methods
* for retrieving info and content for the result.
*/
public static class HTTPResponseResult
{
/**
* The httpclient entity.
*/
HttpEntity entity;
/**
* The httpclient.
*/
DefaultHttpClient httpClient;
/**
* Creates HTTPResponseResult.
* @param entity the httpclient entity.
* @param httpClient the httpclient.
*/
HTTPResponseResult(HttpEntity entity, DefaultHttpClient httpClient)
{
this.entity = entity;
this.httpClient = httpClient;
}
/**
* Tells the length of the content, if known.
*
* @return the number of bytes of the content, or
* a negative number if unknown. If the content length is known
* but exceeds {@link java.lang.Long#MAX_VALUE Long.MAX_VALUE},
* a negative number is returned.
*/
public long getContentLength()
{
return entity.getContentLength();
}
public InputStream getContent()
throws IOException, IllegalStateException
{
return new HttpClientInputStream(entity.getContent(), httpClient);
}
/**
* Returns a content string of the entity.
*
* @return content string of the entity.
*
* @throws IOException if the stream could not be created
*/
public String getContentString()
throws IOException
{
try
{
return EntityUtils.toString(entity);
}
finally
{
if(httpClient != null)
httpClient.getConnectionManager().shutdown();
}
}
/**
* Get the credentials used by the request.
*
* @return the credentials (login at index 0 and password at index 1)
*/
public String[] getCredentials()
{
String cred[] = new String[2];
if(httpClient != null)
{
HTTPCredentialsProvider prov = (HTTPCredentialsProvider)
httpClient.getCredentialsProvider();
cred[0] = prov.getAuthenticationUsername();
cred[1] = prov.getAuthenticationPassword();
}
return cred;
}
}
}
|
package org.opencms.ade.configuration;
import org.opencms.ade.configuration.formatters.CmsFormatterChangeSet;
import org.opencms.ade.configuration.formatters.CmsFormatterConfigurationCacheState;
import org.opencms.ade.detailpage.CmsDetailPageInfo;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.xml.containerpage.CmsFormatterConfiguration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A configuration data class whose parent can be set directly for test purposes.<p>
*/
public class CmsTestConfigData extends CmsADEConfigData {
/** The parent configuration object. */
public CmsADEConfigData m_parent;
/** CmsObject for testing. */
private CmsObject m_cms2;
/** The formatter cache state can be set directly for the test configuration data. */
private CmsFormatterConfigurationCacheState m_formatters;
/** The schema formatters can be set directly for the test configuration data. */
private Map<Integer, CmsFormatterConfiguration> m_schemaFormatterConfiguration = new HashMap<Integer, CmsFormatterConfiguration>();
/**
* Creates a new configuration data object.<p>
*
* @param basePath the base path
* @param resourceTypeConfig the resource type configuration
* @param propertyConfig the property configuration
* @param detailPageInfos the detail page configuration
* @param modelPages the model page configuration
*/
public CmsTestConfigData(
String basePath,
List<CmsResourceTypeConfig> resourceTypeConfig,
List<CmsPropertyConfig> propertyConfig,
List<CmsDetailPageInfo> detailPageInfos,
List<CmsModelPageConfig> modelPages) {
super(new CmsADEConfigDataInternal(
null,
false,
basePath,
resourceTypeConfig,
false,
propertyConfig,
false,
detailPageInfos,
modelPages,
new ArrayList<CmsFunctionReference>(),
false,
false,
false,
new CmsFormatterChangeSet()), null);
}
/**
* @see org.opencms.ade.configuration.CmsADEConfigData#getCachedFormatters()
*/
@Override
public CmsFormatterConfigurationCacheState getCachedFormatters() {
if (m_formatters != null) {
return m_formatters;
} else {
return super.getCachedFormatters();
}
}
/**
* Sets the CmsObject for testing.<p>
*
* @param cms the CmsObject for testing
*/
public void initialize(CmsObject cms) {
m_cms2 = cms;
}
/**
* @see org.opencms.ade.configuration.CmsADEConfigData#parent()
*/
@Override
public CmsADEConfigData parent() {
return m_parent;
}
/**
* Registers a schema formatter which will be returned from getSchemaFormatters if a resource with the matching type is passed in.<p>
*
* @param typeId the resource type id
* @param formatters the formatters for the resource type
*/
public void registerSchemaFormatters(int typeId, CmsFormatterConfiguration formatters) {
m_schemaFormatterConfiguration.put(new Integer(typeId), formatters);
}
/**
* Sets the "create contents locally" flag.<p>
*
* @param createContentsLocally the flag to control whether contents from inherited resource types are stored in the local .content folder
*/
public void setCreateContentsLocally(boolean createContentsLocally) {
m_data.m_createContentsLocally = createContentsLocally;
}
/**
* Sets the "discard inherited model pages" flag.<p>
*
* @param discardInheritedModelPages the flag to control whether inherited model pages are discarded
*/
public void setDiscardInheritedModelPages(boolean discardInheritedModelPages) {
m_data.m_discardInheritedModelPages = discardInheritedModelPages;
}
/**
* Sets the "discard inherited properties" flag.<p>
*
* @param discardInheritedProperties the flag to control whether inherited properties are discarded
*/
public void setDiscardInheritedProperties(boolean discardInheritedProperties) {
m_data.m_discardInheritedProperties = discardInheritedProperties;
}
/**
* Sets the formatter change set.<p>
*
* @param changeSet the formatter change set
*/
public void setFormatterChangeSet(CmsFormatterChangeSet changeSet) {
m_data.m_formatterChangeSet = changeSet;
}
/**
* Sets the formatter cache state.<p>
*
* @param formatters the formatter cache state
*/
public void setFormatters(CmsFormatterConfigurationCacheState formatters) {
m_formatters = formatters;
}
/**
* Sets the "discard inherited types" flag.<p>
*
* @param discardInheritedTypes the flag to control whether inherited types are discarded
*/
public void setIsDiscardInheritedTypes(boolean discardInheritedTypes) {
m_data.m_discardInheritedTypes = discardInheritedTypes;
}
/**
* Marks this as a module configuration or normal sitemap configuration.<p>
*
* @param isModuleConfig true if this is a module configuration
*/
public void setIsModuleConfig(boolean isModuleConfig) {
m_data.m_isModuleConfig = isModuleConfig;
}
/**
* Sets the parent configuration object.<p>
*
* @param parent the parent configuration object
*/
public void setParent(CmsADEConfigData parent) {
m_parent = parent;
}
/**
* @see org.opencms.ade.configuration.CmsADEConfigData#getCms()
*/
@Override
protected CmsObject getCms() {
return m_cms2;
}
/**
* @see org.opencms.ade.configuration.CmsADEConfigData#getFormattersFromSchema(org.opencms.file.CmsObject, org.opencms.file.CmsResource)
*/
@Override
protected CmsFormatterConfiguration getFormattersFromSchema(CmsObject cms, CmsResource res) {
Integer key = new Integer(res.getTypeId());
CmsFormatterConfiguration result = m_schemaFormatterConfiguration.get(key);
if (result == null) {
result = super.getFormattersFromSchema(cms, res);
}
return result;
}
}
|
package net.frapu.code.visualization.domainModel;
import java.util.LinkedList;
import java.util.List;
import net.frapu.code.visualization.ProcessModel;
import net.frapu.code.visualization.ProcessNode;
import net.frapu.code.visualization.ProcessEdge;
import net.frapu.code.visualization.general.ColoredFrame;
/**
*
* @author frank
*/
public class DomainModel extends ProcessModel {
public final static String PROP_SOURCE = "#source";
public final static String PROP_DATA = "#data";
public final static String PROP_NAMESPACE_PREFIX = "namespacePrefix";
public final static String PROP_NAMESPACE_URI = "namespaceUri";
public DomainModel() {
this(null);
}
public DomainModel(String name) {
super(name);
processUtils = new DomainUtils();
setProperty(PROP_SOURCE, "");
setProperty(PROP_DATA, "");
setProperty(PROP_NAMESPACE_PREFIX, "");
setProperty(PROP_NAMESPACE_URI, "");
}
public String getDescription() {
return "Domain Model";
}
@Override
public List<Class<? extends ProcessNode>> getSupportedNodeClasses() {
List<Class<? extends ProcessNode>> result = new LinkedList<Class<? extends ProcessNode>>();
result.add(DomainClass.class);
//result.add(DomainClassReference.class);
result.add(Comment.class);
result.add(ColoredFrame.class);
return result;
}
@Override
public List<Class<? extends ProcessEdge>> getSupportedEdgeClasses() {
List<Class<? extends ProcessEdge>> result = new LinkedList<Class<? extends ProcessEdge>>();
result.add(Association.class);
result.add(Aggregation.class);
// result.add(Inheritance.class);
return result;
}
/**
* Returns the first root instance of the DomainModel (if any exists)
* @return
*/
public DomainClass getRootInstance() {
DomainClass root = null;
for (ProcessNode node: getNodes()) {
if (node instanceof DomainClass && node.getStereotype().equals("root_instance"))
return (DomainClass)node;
}
return root;
}
@Override
public String toString() {
return this.getProcessName() + " (Domain Model)";
}
}
|
package br.com.redesocial.modelo.dao;
import br.com.redesocial.modelo.dto.Estado;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class EstadoDAO extends DAOBase {
public List listar() throws Exception {
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("select * from estados order by nome");
ResultSet rs;
rs = pstmt.executeQuery();
List lista;
lista = new ArrayList();
//PaisDAO paisDAO = new PaisDAO();
while (rs.next()){
Estado e = new Estado();
e.setId(rs.getInt("id"));
e.setNome(rs.getString("nome"));
//e.setPais(paisDAO.selecionar(rs.getInt("pais")));
lista.add(e);
}
return lista;
}
}
|
package com.jetdrone.vertx.yoke;
import com.jetdrone.vertx.yoke.core.Context;
import com.jetdrone.vertx.yoke.core.MountedMiddleware;
import com.jetdrone.vertx.yoke.core.RequestWrapper;
import com.jetdrone.vertx.yoke.core.impl.DefaultRequestWrapper;
import com.jetdrone.vertx.yoke.jmx.ContextMBean;
import com.jetdrone.vertx.yoke.jmx.MiddlewareMBean;
import com.jetdrone.vertx.yoke.middleware.YokeRequest;
import com.jetdrone.vertx.yoke.security.YokeKeyStoreSecurity;
import com.jetdrone.vertx.yoke.security.YokeSecurity;
import com.jetdrone.vertx.yoke.store.SessionStore;
import com.jetdrone.vertx.yoke.store.SharedDataSessionStore;
import com.jetdrone.vertx.yoke.core.YokeException;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.vertx.java.core.AsyncResult;
import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.http.HttpServer;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.http.HttpServerResponse;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonElement;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.platform.Container;
import org.vertx.java.platform.Verticle;
import org.jetbrains.annotations.*;
import javax.management.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.*;
/**
* # Yoke
*
* Yoke is a chain executor of middleware for Vert.x 2.x. The goal of this library is not to provide a web application
* framework but the backbone that helps the creation of web applications.
*
* Yoke works in a similar way to Connect middleware. Users start by declaring which middleware components want to use
* and then start an http server either managed by Yoke or provided by the user (say when you need https).
*
* Yoke has no extra dependencies than Vert.x itself so it is self contained.
*/
public class Yoke {
//Get the MBean server
private final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
/**
* Vert.x instance
*/
private final Vertx vertx;
/**
* Vert.x container
*/
private final Container container;
/**
* request wrapper in use
*/
private final RequestWrapper requestWrapper;
/**
* default context used by all requests
*
* <pre>
* {
* title: "Yoke",
* x-powered-by: true,
* trust-proxy: true
* }
* </pre>
*/
protected final Map<String, Object> defaultContext = new HashMap<>();
/**
* The internal registry of [render engines](Engine.html)
*/
private final Map<String, Engine> engineMap = new HashMap<>();
/**
* Creates a Yoke instance.
*
* This constructor should be called from a verticle and pass a valid Vertx instance. This instance will be shared
* with all registered middleware. The reason behind this is to allow middleware to use Vertx features such as file
* system and timers.
*
* <pre>
* public class MyVerticle extends Verticle {
* public void start() {
* final Yoke yoke = new Yoke(this);
* ...
* }
* }
* </pre>
*
* @param verticle the main verticle
*/
public Yoke(@NotNull Verticle verticle) {
this(verticle.getVertx(), verticle.getContainer(), new DefaultRequestWrapper());
}
/**
* Creates a Yoke instance.
*
* This constructor should be called from a verticle and pass a valid Vertx instance and a Logger. This instance
* will be shared with all registered middleware. The reason behind this is to allow middleware to use Vertx
* features such as file system and timers.
*
* <pre>
* public class MyVerticle extends Verticle {
* public void start() {
* final Yoke yoke = new Yoke(getVertx());
* ...
* }
* }
* </pre>
*
* @param vertx
*/
public Yoke(@NotNull Vertx vertx) {
this(vertx, null, new DefaultRequestWrapper());
}
/**
* Creates a Yoke instance.
*
* This constructor should be called from a verticle and pass a valid Vertx instance and a Container. This instance
* will be shared with all registered middleware. The reason behind this is to allow middleware to use Vertx
* features such as file system and timers.
*
* <pre>
* public class MyVerticle extends Verticle {
* public void start() {
* final Yoke yoke = new Yoke(getVertx());
* ...
* }
* }
* </pre>
*
* @param vertx
*/
public Yoke(@NotNull Vertx vertx, Container container) {
this(vertx, container, new DefaultRequestWrapper());
}
/**
* Creates a Yoke instance.
*
* This constructor should be called internally or from other language bindings.
*
* <pre>
* public class MyVerticle extends Verticle {
* public void start() {
* final Yoke yoke = new Yoke(getVertx(),
* getContainer(),
* new RequestWrapper() {...});
* ...
* }
* }
* </pre>
*
* @param vertx
* @param container
* @param requestWrapper
*/
public Yoke(@NotNull Vertx vertx, @Nullable Container container, @NotNull RequestWrapper requestWrapper) {
this.vertx = vertx;
this.container = container;
this.requestWrapper = requestWrapper;
defaultContext.put("title", "Yoke");
defaultContext.put("x-powered-by", true);
defaultContext.put("trust-proxy", true);
store = new SharedDataSessionStore(vertx, "yoke.sessiondata");
// register on JMX
try {
mbs.registerMBean(new ContextMBean(defaultContext), new ObjectName("com.jetdrone.yoke:instance=@" + hashCode() + ",type=DefaultContext@" + defaultContext.hashCode()));
} catch (InstanceAlreadyExistsException e) {
// ignore
} catch (MalformedObjectNameException | MBeanRegistrationException | NotCompliantMBeanException e) {
throw new RuntimeException(e);
}
}
public Vertx vertx() {
return vertx;
}
/**
* Ordered list of mounted middleware in the chain
*/
private final List<MountedMiddleware> middlewareList = new ArrayList<>();
/**
* Special middleware used for error handling
*/
private Middleware errorHandler;
/**
* Adds a Middleware to the chain. If the middleware is an Error Handler Middleware then it is
* treated differently and only the last error handler is kept.
*
* You might want to add a middleware that is only supposed to run on a specific route (path prefix).
* In this case if the request path does not match the prefix the middleware is skipped automatically.
*
* <pre>
* yoke.use("/login", new CustomLoginMiddleware());
* </pre>
*
* @param route The route prefix for the middleware
* @param middleware The middleware add to the chain
*/
public Yoke use(@NotNull String route, @NotNull Middleware... middleware) {
for (Middleware m : middleware) {
// when the type of middleware is error handler then the route is ignored and
// the middleware is extracted from the execution chain into a special placeholder
// for error handling
if (m.isErrorHandler()) {
errorHandler = m;
} else {
MountedMiddleware mm = new MountedMiddleware(route, m);
middlewareList.add(mm);
// register on JMX
try {
mbs.registerMBean(new MiddlewareMBean(mm), new ObjectName("com.jetdrone.yoke:type=Middleware@" + hashCode() + ",order=" + middlewareList.size()));
} catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
throw new RuntimeException(e);
}
}
// initialize the middleware with the current Vert.x and Logger
m.init(this, route);
}
return this;
}
/**
* Adds a middleware to the chain with the prefix "/".
*
* @param middleware The middleware add to the chain
*/
public Yoke use(@NotNull Middleware... middleware) {
return use("/", middleware);
}
/**
* Adds a Handler to a route. The behaviour is similar to the middleware, however this
* will be a terminal point in the execution chain. In this case any middleware added
* after will not be executed. However you should care about the route which may lead
* to skip this middleware.
*
* The idea to user a Handler is to keep the API familiar with the rest of the Vert.x
* API.
*
* <pre>
* yoke.use("/login", new Handler<YokeRequest>() {
* public void handle(YokeRequest request) {
* request.response.end("Hello");
* }
* });
* </pre>
*
* @param route The route prefix for the middleware
* @param handler The Handler to add
*/
public Yoke use(@NotNull String route, final @NotNull Handler<YokeRequest> handler) {
middlewareList.add(new MountedMiddleware(route, new Middleware() {
@Override
public void handle(YokeRequest request, Handler<Object> next) {
handler.handle(request);
}
}));
return this;
}
/**
* Adds a Handler to a route.
*
* <pre>
* yoke.use("/login", new Handler<YokeRequest>() {
* public void handle(YokeRequest request) {
* request.response.end("Hello");
* }
* });
* </pre>
* @param handler The Handler to add
*/
public Yoke use(@NotNull Handler<YokeRequest> handler) {
return use("/", handler);
}
/**
* Adds a Render Engine to the library. Render Engines are Template engines you
* might want to use to speed the development of your application. Once they are
* registered you can use the method render in the YokeResponse to
* render a template.
*
* @param engine The implementation of the engine
*/
public Yoke engine(@NotNull Engine engine) {
engine.setVertx(vertx);
engineMap.put(engine.extension(), engine);
return this;
}
/**
* Special store engine used for accessing session data
*/
protected SessionStore store;
public Yoke store(@NotNull SessionStore store) {
this.store = store;
return this;
}
protected YokeSecurity security = new YokeSecurity();
public Yoke keyStore(@NotNull String fileName, @NotNull String keyStorePassword) {
String storeType;
int idx = fileName.lastIndexOf('.');
if (idx == -1) {
storeType = KeyStore.getDefaultType();
} else {
storeType = fileName.substring(idx + 1);
}
try {
KeyStore ks = KeyStore.getInstance(storeType);
try (InputStream in = getClass().getResourceAsStream(fileName)) {
if (in == null) {
throw new FileNotFoundException(fileName);
}
ks.load(in, keyStorePassword.toCharArray());
}
this.security = new YokeKeyStoreSecurity(ks);
} catch (KeyStoreException | IOException | CertificateException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
return this;
}
public YokeSecurity security() {
return this.security;
}
/**
* When you need to share global properties with your requests you can add them
* to Yoke and on every request they will be available as request.get(String)
*
* @param key unique identifier
* @param value Any non null value, nulls are not saved
*/
public Yoke set(@NotNull String key, Object value) {
if (value == null) {
defaultContext.remove(key);
} else {
defaultContext.put(key, value);
}
return this;
}
/**
* Starts the server listening at a given port bind to all available interfaces.
*
* @param port the server TCP port
* @return {Yoke}
*/
public Yoke listen(int port) {
return listen(port, "0.0.0.0", null);
}
/**
* Starts the server listening at a given port bind to all available interfaces.
*
* @param port the server TCP port
* @param handler for asynchronous result of the listen operation
* @return {Yoke}
*/
public Yoke listen(int port, @NotNull Handler<Boolean> handler) {
return listen(port, "0.0.0.0", handler);
}
/**
* Starts the server listening at a given port and given address.
*
* @param port the server TCP port
* @return {Yoke}
*/
public Yoke listen(int port, @NotNull String address) {
return listen(port, address, null);
}
/**
* Starts the server listening at a given port and given address.
*
* @param port the server TCP port
* @param handler for asynchronous result of the listen operation
* @return {Yoke}
*/
public Yoke listen(int port, @NotNull String address, final Handler<Boolean> handler) {
HttpServer server = vertx.createHttpServer();
listen(server);
if (handler != null) {
server.listen(port, address, new Handler<AsyncResult<HttpServer>>() {
@Override
public void handle(AsyncResult<HttpServer> listen) {
handler.handle(listen.succeeded());
}
});
} else {
server.listen(port, address);
}
return this;
}
/**
* Starts listening at a already created server.
*
* @param server
* @return {Yoke}
*/
public Yoke listen(final @NotNull HttpServer server) {
// is this server HTTPS?
final boolean secure = server.isSSL();
server.requestHandler(new Handler<HttpServerRequest>() {
@Override
public void handle(HttpServerRequest req) {
// the context map is shared with all middlewares
final YokeRequest request = requestWrapper.wrap(req, secure, new Context(defaultContext), engineMap, store);
// add x-powered-by header is enabled
Boolean poweredBy = request.get("x-powered-by");
if (poweredBy != null && poweredBy) {
request.response().putHeader("x-powered-by", "yoke");
}
new Handler<Object>() {
int currentMiddleware = -1;
@Override
public void handle(Object error) {
if (error == null) {
currentMiddleware++;
if (currentMiddleware < middlewareList.size()) {
MountedMiddleware mountedMiddleware = middlewareList.get(currentMiddleware);
if (!mountedMiddleware.enabled) {
// the middleware is disabled
handle(null);
} else {
if (request.path().startsWith(mountedMiddleware.mount)) {
Middleware middlewareItem = mountedMiddleware.middleware;
middlewareItem.handle(request, this);
} else {
// the middleware was not mounted on this uri, skip to the next entry
handle(null);
}
}
} else {
HttpServerResponse response = request.response();
// reached the end and no handler was able to answer the request
response.setStatusCode(404);
response.setStatusMessage(HttpResponseStatus.valueOf(404).reasonPhrase());
if (errorHandler != null) {
errorHandler.handle(request, null);
} else {
response.end(HttpResponseStatus.valueOf(404).reasonPhrase());
}
}
} else {
request.put("error", error);
if (errorHandler != null) {
errorHandler.handle(request, null);
} else {
HttpServerResponse response = request.response();
int errorCode;
// if the error was set on the response use it
if (response.getStatusCode() >= 400) {
errorCode = response.getStatusCode();
} else {
// if it was set as the error object use it
if (error instanceof Number) {
errorCode = ((Number) error).intValue();
} else if (error instanceof YokeException) {
errorCode = ((YokeException) error).getErrorCode().intValue();
} else {
// default error code
errorCode = 500;
}
}
response.setStatusCode(errorCode);
response.setStatusMessage(HttpResponseStatus.valueOf(errorCode).reasonPhrase());
response.end(HttpResponseStatus.valueOf(errorCode).reasonPhrase());
}
}
}
}.handle(null);
}
});
return this;
}
/**
* Deploys required middleware from a config json element.
*
* The current format for the config is either a single item or an array:
* <pre>
* {
* module: String, // the name of the module
* verticle: String, // the name of the verticle (either verticle or module must be present)
* instances: Number, // how many instances, default 1
* worker: Boolean, // is it a worker verticle? default false
* multiThreaded: Boolean, // is it a multiThreaded verticle? default false
* config: JsonObject // any config you need to pass to the module/verticle
* }
* </pre>
*
* @param config either a json object or a json array.
*/
public Yoke deploy(@NotNull JsonElement config) {
return deploy(config, null);
}
/**
* Deploys required middleware from a config json element. The handler is only called once all middleware is
* deployed or in error. The order of deployment is not guaranteed since all deploy functions are called
* concurrently and do not wait for the previous result before deploying the next item.
*
* The current format for the config is either a single item or an array:
* <pre>
* {
* module: String, // the name of the module
* verticle: String, // the name of the verticle (either verticle or module must be present)
* instances: Number, // how many instances, default 1
* worker: Boolean, // is it a worker verticle? default false
* multiThreaded: Boolean, // is it a multiThreaded verticle? default false
* config: JsonObject // any config you need to pass to the module/verticle
* }
* </pre>
*
* @param config either a json object or a json array.
* @param handler A handler that is called once all middleware is deployed or on error.
*/
public Yoke deploy(final @NotNull JsonElement config, final Handler<Object> handler) {
if (config.isArray() && config.asArray().size() == 0) {
if (handler == null) {
return this;
} else {
handler.handle(null);
return this;
}
}
if (config.isObject()) {
return deploy(new JsonArray().addObject(config.asObject()), handler);
}
// wait for all deployments before calling the real handler
Handler<AsyncResult<String>> waitFor = new Handler<AsyncResult<String>>() {
private int latch = config.asArray().size();
private boolean handled = false;
@Override
public void handle(AsyncResult<String> event) {
latch
if (handler != null) {
if (!handled && (event.failed() || latch == 0)) {
handled = true;
handler.handle(event.failed() ? event.cause() : null);
}
}
}
};
for (Object o : config.asArray()) {
JsonObject mod = (JsonObject) o;
if (mod.getString("module") != null) {
deploy(mod.getString("module"), true, false, false, mod.getInteger("instances", 1), mod.getObject("config", new JsonObject()), waitFor);
} else {
deploy(mod.getString("verticle"), false, mod.getBoolean("worker", false), mod.getBoolean("multiThreaded", false), mod.getInteger("instances", 1), mod.getObject("config", new JsonObject()), waitFor);
}
}
return this;
}
private void deploy(String name, boolean module, boolean worker, boolean multiThreaded, int instances, JsonObject config, Handler<AsyncResult<String>> handler) {
if (module) {
if (handler != null) {
container.deployModule(name, config, instances, handler);
} else {
container.deployModule(name, config, instances);
}
} else {
if (worker) {
if (handler != null) {
container.deployWorkerVerticle(name, config, instances, multiThreaded, handler);
} else {
container.deployWorkerVerticle(name, config, instances, multiThreaded);
}
} else {
if (handler != null) {
container.deployVerticle(name, config, instances, handler);
} else {
container.deployVerticle(name, config, instances);
}
}
}
}
}
|
package net.sf.jaer.eventprocessing.filter;
import com.google.common.collect.EvictingQueue;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.util.gl2.GLUT;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.OutputEventIterator;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventio.AEInputStream;
import static net.sf.jaer.eventprocessing.EventFilter.log;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.util.RemoteControlCommand;
import net.sf.jaer.util.RemoteControlled;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.graphics.DavisRenderer;
/**
* Filter for testing noise filters
*
* @author tobid/shasah
*/
@Description("Tests noise filters by injecting known noise and measuring how much signal and noise is filtered")
@DevelopmentStatus(DevelopmentStatus.Status.Stable)
public class NoiseTesterFilter extends AbstractNoiseFilter implements FrameAnnotater, RemoteControlled {
FilterChain chain;
private float shotNoiseRateHz = getFloat("shotNoiseRateHz", .1f);
private float leakNoiseRateHz = getFloat("leakNoiseRateHz", .1f);
private float poissonDtUs = 1;
float shotOffThresholdProb; // bounds for samppling Poisson noise, factor 0.5 so total rate is shotNoiseRateHz
float shotOnThresholdProb; // for shot noise sample both sides, for leak events just generate ON events
float leakOnThresholdProb; // bounds for samppling Poisson noise
private static String DEFAULT_CSV_FILENAME_BASE = "NoiseTesterFilter";
private String csvFileName = getString("csvFileName", DEFAULT_CSV_FILENAME_BASE);
private File csvFile = null;
private BufferedWriter csvWriter = null;
// chip size values, set in initFilter()
private int sx = 0;
private int sy = 0;
private Integer lastTimestampPreviousPacket = null; // use Integer Object so it can be null to signify no value yet
private float TPR = 0;
private float TPO = 0;
private float TNR = 0;
private float accuracy = 0;
private float BR = 0;
float inSignalRateHz = 0, inNoiseRateHz = 0, outSignalRateHz = 0, outNoiseRateHz = 0;
// private EventPacket<ApsDvsEvent> signalAndNoisePacket = null;
private EventPacket<BasicEvent> signalAndNoisePacket = null;
// private EventList<BasicEvent> noiseList = new EventList();
private Random random = new Random();
private AbstractNoiseFilter[] noiseFilters = null;
private AbstractNoiseFilter selectedFilter = null;
protected boolean resetCalled = true; // flag to reset on next event
public static final float RATE_LIMIT_HZ = 25; //per pixel, separately for leak and shot rates
private float annotateAlpha = getFloat("annotateAlpha", 0.5f);
private DavisRenderer renderer = null;
private boolean overlayClassifications = getBoolean("overlayClassifications", false);
private boolean overlayInput = getBoolean("overlayInput", false);
private int rocHistory = getInt("rocHistory", 1);
private EvictingQueue<Point2D.Float> rocHistoryList = EvictingQueue.create(rocHistory);
private ArrayList<BasicEvent> tpList = null, fnList = null, fpList = null, tnList = null; // output of classification
public enum NoiseFilterEnum {
BackgroundActivityFilter, SpatioTemporalCorrelationFilter, SequenceBasedFilter, OrderNBackgroundActivityFilter
}
private NoiseFilterEnum selectedNoiseFilterEnum = NoiseFilterEnum.valueOf(getString("selectedNoiseFilter", NoiseFilterEnum.BackgroundActivityFilter.toString())); //default is BAF
private float correlationTimeS = getFloat("correlationTimeS", 20e-3f);
// float BR = 2 * TPR * TPO / (TPR + TPO); // wish to norm to 1. if both TPR and TPO is 1. the value is 1
public NoiseTesterFilter(AEChip chip) {
super(chip);
String ann = "Filtering Annotation";
setPropertyTooltip("shotNoiseRateHz", "rate per pixel of shot noise events");
setPropertyTooltip("leakNoiseRateHz", "rate per pixel of leak noise events");
setPropertyTooltip("csvFileName", "Enter a filename base here to open CSV output file (appending to it if it already exists)");
setPropertyTooltip("selectedNoiseFilterEnum", "Choose a noise filter to test");
setPropertyTooltip(ann, "annotateAlpha", "Sets the transparency for the annotated pixels. Only works for Davis renderer.");
setPropertyTooltip(ann, "overlayClassifications", "Overlay the signal and noise classifications of events in green and red.");
setPropertyTooltip(ann, "overlayInput", "<html><p>If selected, overlay all input events as signal (green) and noise (red). <p>If not selected, overlay true positives as green (signal in output) and false positives as red (noise in output).");
setPropertyTooltip(ann, "rocHistory", "Number of samples of ROC point to show.");
if (chip.getRemoteControl() != null) {
log.info("adding RemoteControlCommand listener to AEChip\n");
chip.getRemoteControl().addCommandListener(this, "setNoiseFilterParameters", "set correlation time or distance.");
}
}
@Override
public synchronized void setFilterEnabled(boolean yes) {
filterEnabled = yes;
if (yes) {
for (EventFilter2D f : chain) {
if (selectedFilter != null && selectedFilter == f) {
f.setFilterEnabled(yes);
}
}
} else {
for (EventFilter2D f : chain) {
f.setFilterEnabled(false);
}
}
}
public void doCloseCsvFile() {
if (csvFile != null) {
try {
log.info("closing statistics output file" + csvFile);
csvWriter.close();
} catch (IOException e) {
log.warning("could not close " + csvFile + ": caught " + e.toString());
} finally {
csvFile = null;
csvWriter = null;
}
}
}
private void openCvsFiile() {
String fn = csvFileName + ".csv";
csvFile = new File(fn);
log.info(String.format("opening %s for output", fn));
try {
csvWriter = new BufferedWriter(new FileWriter(csvFile, true));
if (!csvFile.exists()) { // write header
log.info("file did not exist, so writing header");
csvWriter.write(String.format("TP,TN,FP,FN,TPR,TNR,BR,firstE.timestamp,"
+ "inSignalRateHz,inNoiseRateHz,outSignalRateHz,outNoiseRateHz\n"));
}
} catch (IOException ex) {
log.warning(String.format("could not open %s for output; caught %s", fn, ex.toString()));
}
}
@Override
synchronized public void annotate(GLAutoDrawable drawable) {
int L;
float x, y;
if (!showFilteringStatistics) {
return;
}
findUnusedDawingY();
GL2 gl = drawable.getGL().getGL2();
gl.glPushMatrix();
L = 3;
gl.glColor3f(.2f, .2f, .8f); // must set color before raster position (raster position is like glVertex)
for (Point2D.Float p : rocHistoryList) {
gl.glBegin(GL.GL_LINES);
x = (1 - p.y) * sx;
y = p.x * sy;
gl.glVertex2f(x - L, y - L);
gl.glVertex2f(x + L, y + L);
gl.glVertex2f(x - L, y + L);
gl.glVertex2f(x + L, y - L);
gl.glEnd();
}
gl.glColor3f(.8f, .8f, .2f); // must set color before raster position (raster position is like glVertex)
L = 6;
// draw X at TPR / TNR point
gl.glLineWidth(4);
gl.glBegin(GL.GL_LINES);
x = (1 - TNR) * sx;
y = TPR * sy;
gl.glVertex2f(x - L, y - L);
gl.glVertex2f(x + L, y + L);
gl.glVertex2f(x - L, y + L);
gl.glVertex2f(x + L, y - L);
gl.glEnd();
gl.glLineWidth(3);
gl.glColor3f(.2f, .2f, .8f); // must set color before raster position (raster position is like glVertex)
final GLUT glut = new GLUT();
gl.glRasterPos3f(0, statisticsDrawingPosition, 0);
String s = String.format("TPR=%6.1f%% TNR=%6.1f%% TPO=%6.1f%%, BR=%6.1f%% dT=%.2fus", 100 * TPR, 100 * TNR, 100 * TPO, 100 * BR, poissonDtUs);
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
gl.glRasterPos3f(0, statisticsDrawingPosition + 10, 0);
String s2 = String.format("In sigRate=%s noiseRate=%s, Out sigRate=%s noiseRate=%s Hz", eng.format(inSignalRateHz), eng.format(inNoiseRateHz), eng.format(outSignalRateHz), eng.format(outNoiseRateHz));
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s2);
gl.glPopMatrix();
}
private void annotateNoiseFilteringEvents(ArrayList<BasicEvent> outSig, ArrayList<BasicEvent> outNoise) {
if (renderer == null) {
return;
}
renderer.clearAnnotationMap();
final int offset = 1;
final float a = getAnnotateAlpha();
final float[] noiseColor = {1f, 0, 0, 1}, sigColor = {0, 1f, 0, 1};
for (BasicEvent e : outSig) {
renderer.setAnnotateColorRGBA(e.x + 2 >= sx ? e.x : e.x + offset, e.y - 2 < 0 ? e.y : e.y - offset, sigColor);
}
for (BasicEvent e : outNoise) {
renderer.setAnnotateColorRGBA(e.x + 2 >= sx ? e.x : e.x + offset, e.y - 2 < 0 ? e.y : e.y - offset, noiseColor);
// renderer.setAnnotateColorRGBA(e.x+2, e.y-2, noiseColor);
}
}
// final private class TimeStampComparator<E extends BasicEvent> implements Comparator<E> {
// // NOTE this hack so that sorted event EventSet does not lose elements with identical timestamps
// @Override
// public int compare(final E e1, final E e2) {
// int diff = e1.timestamp - e2.timestamp;
// return diff;
// private TimeStampComparator timestampComparator = new TimeStampComparator<BasicEvent>();
private ArrayList<BasicEvent> createEventList() {
return new ArrayList<BasicEvent>();
}
private class BackwardsTimestampException extends Exception {
public BackwardsTimestampException(String string) {
super(string);
}
}
private ArrayList<BasicEvent> createEventList(EventPacket<BasicEvent> p) throws BackwardsTimestampException {
ArrayList<BasicEvent> l = new ArrayList(p.getSize());
BasicEvent pe = null;
for (BasicEvent e : p) {
if (pe != null && (e.timestamp < pe.timestamp )) {
throw new BackwardsTimestampException(String.format("timestamp %d is earlier than previous %d", e.timestamp, pe.timestamp));
}
l.add(e);
pe = e;
}
return l;
}
private ArrayList<BasicEvent> createEventList(List<BasicEvent> p) throws BackwardsTimestampException {
ArrayList<BasicEvent> l = new ArrayList(p.size());
BasicEvent pe = null;
for (BasicEvent e : p) {
if (pe != null && (e.timestamp < pe.timestamp )) {
throw new BackwardsTimestampException(String.format("timestamp %d is earlier than previous %d", e.timestamp, pe.timestamp));
}
l.add(e);
pe = e;
}
return l;
}
/**
* Finds the intersection of events in a that are in b. Assumes packets are
* non-monotonic in timestamp ordering.
*
*
* @param a ArrayList<BasicEvent> of a
* @param b likewise
* @return ArrayList of intersection
*/
private ArrayList<BasicEvent> countIntersect(ArrayList<BasicEvent> a, ArrayList<BasicEvent> b) {
ArrayList<BasicEvent> intersect = new ArrayList(a.size() > b.size() ? a.size() : b.size());
int count = 0;
if (a.isEmpty() || b.isEmpty()) {
return new ArrayList();
}
// TODO test case
// a = new ArrayList();
// b = new ArrayList();
// a.add(new BasicEvent(4, (short) 0, (short) 0));
// a.add(new BasicEvent(4, (short) 0, (short) 0));
// a.add(new BasicEvent(4, (short) 1, (short) 0));
// a.add(new BasicEvent(4, (short) 2, (short) 0));
//// a.add(new BasicEvent(2, (short) 0, (short) 0));
//// a.add(new BasicEvent(10, (short) 0, (short) 0));
// b.add(new BasicEvent(2, (short) 0, (short) 0));
// b.add(new BasicEvent(2, (short) 0, (short) 0));
// b.add(new BasicEvent(4, (short) 0, (short) 0));
// b.add(new BasicEvent(4, (short) 0, (short) 0));
// b.add(new BasicEvent(4, (short) 1, (short) 0));
// b.add(new BasicEvent(10, (short) 0, (short) 0));
int i = 0, j = 0;
int na = a.size(), nb = b.size();
while (i < na && j < nb) {
if (a.get(i).timestamp < b.get(j).timestamp) {
i++;
} else if (b.get(j).timestamp < a.get(i).timestamp) {
j++;
} else {
// If timestamps equal, it mmight be identical events or maybe not
// and there might be several events with identical timestamps.
// We MUST match all a with all b.
// We don't want to increment both pointers or we can miss matches.
// We do an inner double loop for exhaustive matching as long as the timestamps
// are identical.
int i1 = i, j1 = j;
while (i1 < na && j1 < nb && a.get(i1).timestamp == b.get(j1).timestamp) {
boolean match = false;
while (j1 < nb && i1 < na && a.get(i1).timestamp == b.get(j1).timestamp) {
if (a.get(i1).equals(b.get(j1))) {
count++;
intersect.add(b.get(j1)); // TODO debug
// we have a match, so use up the a element
i1++;
match = true;
}
j1++;
}
if (!match) {
i1++;
}
j1 = j; // reset j to start of matching ts region
}
i = i1; // when done, timestamps are different or we reached end of either or both arrays
j = j1;
}
}
// System.out.println("%%%%%%%%%%%%%%");
// printarr(a, "a");
// printarr(b, "b");
// printarr(intersect, "intsct");
return intersect;
}
// TODO test case
void printarr(ArrayList<BasicEvent> a, String n) {
final int MAX = 30;
if (a.size() > MAX) {
System.out.printf("
return;
}
System.out.printf("%s[%d]
for (int i = 0; i < a.size(); i++) {
BasicEvent e = a.get(i);
System.out.printf("%s[%d]=[%d %d %d %d]\n", n, i, e.timestamp, e.x, e.y, (e instanceof PolarityEvent) ? ((PolarityEvent) e).getPolaritySignum() : 0);
}
}
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
totalEventCount = 0; // from super, to measure filtering
filteredOutEventCount = 0;
int TP = 0; // filter take real events as real events. the number of events
int TN = 0; // filter take noise events as noise events
int FP = 0; // filter take noise events as real events
int FN = 0; // filter take real events as noise events
if (in == null || in.isEmpty()) {
log.warning("empty packet, cannot inject noise");
return in;
}
BasicEvent firstE = in.getFirstEvent();
if (resetCalled) {
resetCalled = false;
int ts = in.getLastTimestamp(); // we use getLastTimestamp because getFirstTimestamp contains event from BEFORE the rewind :-(
// initialize filters with lastTimesMap to Poisson waiting times
log.info("initializing timestamp maps with Poisson process waiting times");
for (AbstractNoiseFilter f : noiseFilters) {
int[][] map = f.getLastTimesMap();
if (map != null) {
initializeLastTimesMapForNoiseRate(map, shotNoiseRateHz + leakNoiseRateHz, ts);
}
}
}
// copy input events to inList
ArrayList<BasicEvent> signalList;
try {
signalList = createEventList((EventPacket<BasicEvent>) in);
} catch (BackwardsTimestampException ex) {
log.warning(String.format("%s: skipping nonmonotonic packet [%s]", ex, in));
return in;
}
assert signalList.size() == in.getSizeNotFilteredOut() : String.format("signalList size (%d) != in.getSizeNotFilteredOut() (%d)", signalList.size(), in.getSizeNotFilteredOut());
// add noise into signalList to get the outputPacketWithNoiseAdded, track noise in noiseList
ArrayList<BasicEvent> noiseList = createEventList(); //List.create(tim);
addNoise(in, signalAndNoisePacket, noiseList, shotNoiseRateHz, leakNoiseRateHz);
// we need to copy the augmented event packet to a HashSet for use with Collections
ArrayList<BasicEvent> signalAndNoiseList;
try {
signalAndNoiseList = createEventList((EventPacket<BasicEvent>) signalAndNoisePacket);
// filter the augmented packet
EventPacket<BasicEvent> passedSignalAndNoisePacket = (EventPacket<BasicEvent>) getEnclosedFilterChain().filterPacket(signalAndNoisePacket);
ArrayList<BasicEvent> filteredOutList = selectedFilter.getFilteredOutEvents();
// make a list of the output packet, which has noise filtered out by selected filter
ArrayList<BasicEvent> passedSignalAndNoiseList = createEventList(passedSignalAndNoisePacket);
assert (signalList.size() + noiseList.size() == signalAndNoiseList.size());
// now we sort out the mess
tpList = countIntersect(signalList, passedSignalAndNoiseList); // True positives: Signal that was correctly retained by filtering
TP = tpList.size();
fnList = countIntersect(signalList, filteredOutList); // False negatives: Signal that was incorrectly removed by filter.
FN = fnList.size();
fpList = countIntersect(noiseList, passedSignalAndNoiseList); // False positives: Noise that is incorrectly passed by filter
FP = fpList.size();
tnList = countIntersect(noiseList, filteredOutList); // True negatives: Noise that was correctly removed by filter
TN = tnList.size();
// if (TN + FP != noiseList.size()) {
// System.err.println(String.format("TN (%d) + FP (%d) = %d != noiseList (%d)", TN, FP, TN + FP, noiseList.size()));
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
assert (TN + FP == noiseList.size()) : String.format("TN (%d) + FP (%d) = %d != noiseList (%d)", TN, FP, TN + FP, noiseList.size());
totalEventCount = signalAndNoiseList.size();
int outputEventCount = passedSignalAndNoiseList.size();
filteredOutEventCount = totalEventCount - outputEventCount;
// if (TP + FP != outputEventCount) {
// System.err.printf("@@@@@@@@@ TP (%d) + FP (%d) = %d != outputEventCount (%d)", TP, FP, TP + FP, outputEventCount);
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
assert TP + FP == outputEventCount : String.format("TP (%d) + FP (%d) = %d != outputEventCount (%d)", TP, FP, TP + FP, outputEventCount);
// if (TP + TN + FP + FN != totalEventCount) {
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
assert TP + TN + FP + FN == totalEventCount : String.format("TP (%d) + TN (%d) + FP (%d) + FN (%d) = %d != totalEventCount (%d)", TP, TN, FP, FN, TP + TN + FP + FN, totalEventCount);
assert TN + FN == filteredOutEventCount : String.format("TN (%d) + FN (%d) = %d != filteredOutEventCount (%d)", TN, FN, TN + FN, filteredOutEventCount);
// System.out.printf("every packet is: %d %d %d %d %d, %d %d %d: %d %d %d %d\n", inList.size(), newInList.size(), outList.size(), outRealList.size(), outNoiseList.size(), outInitList.size(), outInitRealList.size(), outInitNoiseList.size(), TP, TN, FP, FN);
TPR = TP + FN == 0 ? 0f : (float) (TP * 1.0 / (TP + FN)); // percentage of true positive events. that's output real events out of all real events
TPO = TP + FP == 0 ? 0f : (float) (TP * 1.0 / (TP + FP)); // percentage of real events in the filter's output
TNR = TN + FP == 0 ? 0f : (float) (TN * 1.0 / (TN + FP));
accuracy = (float) ((TP + TN) * 1.0 / (TP + TN + FP + FN));
BR = TPR + TPO == 0 ? 0f : (float) (2 * TPR * TPO / (TPR + TPO)); // wish to norm to 1. if both TPR and TPO is 1. the value is 1
// System.out.printf("shotNoiseRateHz and leakNoiseRateHz is %.2f and %.2f\n", shotNoiseRateHz, leakNoiseRateHz);
if (lastTimestampPreviousPacket != null) {
int deltaTime = in.getLastTimestamp() - lastTimestampPreviousPacket;
inSignalRateHz = (1e6f * in.getSize()) / deltaTime;
inNoiseRateHz = (1e6f * noiseList.size()) / deltaTime;
outSignalRateHz = (1e6f * TP) / deltaTime;
outNoiseRateHz = (1e6f * FP) / deltaTime;
}
if (csvWriter != null) {
try {
csvWriter.write(String.format("%d,%d,%d,%d,%f,%f,%f,%d,%f,%f,%f,%f\n",
TP, TN, FP, FN, TPR, TNR, BR, firstE.timestamp,
inSignalRateHz, inNoiseRateHz, outSignalRateHz, outNoiseRateHz));
} catch (IOException e) {
doCloseCsvFile();
}
}
if (overlayClassifications) {
if (overlayInput) {
annotateNoiseFilteringEvents(signalList, noiseList);
} else {
annotateNoiseFilteringEvents(tpList, fpList);
}
}
Point2D.Float p = new Point2D.Float(TPR, TNR);
rocHistoryList.add(p);
// if (rocHistoryList.size() > rocHistory) {
// rocHistoryList.removeFirst();
lastTimestampPreviousPacket = in.getLastTimestamp();
return passedSignalAndNoisePacket;
} catch (BackwardsTimestampException ex) {
Logger.getLogger(NoiseTesterFilter.class.getName()).log(Level.SEVERE, null, ex);
return in;
}
}
@Override
synchronized public void resetFilter() {
lastTimestampPreviousPacket = null;
resetCalled = true;
getEnclosedFilterChain().reset();
rocHistoryList.clear();
}
private void computeProbs() {
// the rate per pixel results in overall noise rate for entire sensor that is product of pixel rate and number of pixels.
// we compute this overall noise rate to determine the Poisson sample interval that is much smaller than this to enable simple Poisson noise sampling.
// Compute time step that is 10X less than the overall mean interval for noise
// dt is the time interval such that if we sample a random value 0-1 every dt us, the the overall noise rate will be correct.
int npix = (chip.getSizeX() * chip.getSizeY());
float tmp = (float) (1.0 / ((leakNoiseRateHz + shotNoiseRateHz) * npix)); // this value is very small
poissonDtUs = ((tmp / 10) * 1000000); // 1s = 1000000 us // TODO document why 10 here. It is to ensure that prob(>1 event per sample is low)
if (poissonDtUs < 1) {
log.warning(String.format("Poisson sampling rate is less than 1us which is timestep resolution, could be slow"));
}
shotOffThresholdProb = 0.5f * (poissonDtUs * 1e-6f * npix) * shotNoiseRateHz; // bounds for samppling Poisson noise, factor 0.5 so total rate is shotNoiseRateHz
shotOnThresholdProb = 1 - shotOffThresholdProb; // for shot noise sample both sides, for leak events just generate ON events
leakOnThresholdProb = (poissonDtUs * 1e-6f * npix) * leakNoiseRateHz; // bounds for samppling Poisson noise
}
@Override
public void initFilter() {
chain = new FilterChain(chip);
noiseFilters = new AbstractNoiseFilter[]{new BackgroundActivityFilter(chip), new SpatioTemporalCorrelationFilter(chip), new SequenceBasedFilter(chip), new OrderNBackgroundActivityFilter((chip))};
for (AbstractNoiseFilter n : noiseFilters) {
n.initFilter();
chain.add(n);
}
setEnclosedFilterChain(chain);
sx = chip.getSizeX() - 1;
sy = chip.getSizeY() - 1;
signalAndNoisePacket = new EventPacket<>(ApsDvsEvent.class);
if (chip.getAeViewer() != null) {
chip.getAeViewer().getSupport().addPropertyChangeListener(AEInputStream.EVENT_REWOUND, this);
chip.getAeViewer().getSupport().addPropertyChangeListener(AEViewer.EVENT_CHIP, this);
}
setSelectedNoiseFilterEnum(selectedNoiseFilterEnum);
computeProbs();
if (chip.getRenderer() instanceof DavisRenderer) {
renderer = (DavisRenderer) chip.getRenderer();
}
setAnnotateAlpha(annotateAlpha);
}
/**
* @return the shotNoiseRateHz
*/
public float getShotNoiseRateHz() {
return shotNoiseRateHz;
}
@Override
public int[][] getLastTimesMap() {
return null;
}
/**
* @param shotNoiseRateHz the shotNoiseRateHz to set
*/
synchronized public void setShotNoiseRateHz(float shotNoiseRateHz) {
if (shotNoiseRateHz < 0) {
shotNoiseRateHz = 0;
}
if (shotNoiseRateHz > RATE_LIMIT_HZ) {
log.warning("high leak rates will hang the filter and consume all memory");
shotNoiseRateHz = RATE_LIMIT_HZ;
}
putFloat("shotNoiseRateHz", shotNoiseRateHz);
getSupport().firePropertyChange("shotNoiseRateHz", this.shotNoiseRateHz, shotNoiseRateHz);
this.shotNoiseRateHz = shotNoiseRateHz;
computeProbs();
}
/**
* @return the leakNoiseRateHz
*/
public float getLeakNoiseRateHz() {
return leakNoiseRateHz;
}
/**
* @param leakNoiseRateHz the leakNoiseRateHz to set
*/
synchronized public void setLeakNoiseRateHz(float leakNoiseRateHz) {
if (leakNoiseRateHz < 0) {
leakNoiseRateHz = 0;
}
if (leakNoiseRateHz > RATE_LIMIT_HZ) {
log.warning("high leak rates will hang the filter and consume all memory");
leakNoiseRateHz = RATE_LIMIT_HZ;
}
putFloat("leakNoiseRateHz", leakNoiseRateHz);
getSupport().firePropertyChange("leakNoiseRateHz", this.leakNoiseRateHz, leakNoiseRateHz);
this.leakNoiseRateHz = leakNoiseRateHz;
computeProbs();
}
/**
* @return the csvFileName
*/
public String getCsvFilename() {
return csvFileName;
}
/**
* @param csvFileName the csvFileName to set
*/
public void setCsvFilename(String csvFileName) {
if (csvFileName.toLowerCase().endsWith(".csv")) {
csvFileName = csvFileName.substring(0, csvFileName.length() - 4);
}
putString("csvFileName", csvFileName);
getSupport().firePropertyChange("csvFileName", this.csvFileName, csvFileName);
this.csvFileName = csvFileName;
openCvsFiile();
}
private void addNoise(EventPacket<? extends BasicEvent> in, EventPacket<? extends BasicEvent> augmentedPacket, List<BasicEvent> generatedNoise, float shotNoiseRateHz, float leakNoiseRateHz) {
// we need at least 1 event to be able to inject noise before it
if ((in.isEmpty())) {
log.warning("no input events in this packet, cannot inject noise because there is no end event");
return;
}
// save input packet
augmentedPacket.clear();
generatedNoise.clear();
// make the itertor to save events with added noise events
OutputEventIterator<ApsDvsEvent> outItr = (OutputEventIterator<ApsDvsEvent>) augmentedPacket.outputIterator();
if (leakNoiseRateHz == 0 && shotNoiseRateHz == 0) {
for (BasicEvent ie : in) {
outItr.nextOutput().copyFrom(ie);
}
return; // no noise, just return which returns the copy from filterPacket
}
int firstTsThisPacket = in.getFirstTimestamp();
// insert noise between last event of last packet and first event of current packet
// but only if there waa a previous packet and we are monotonic
if (lastTimestampPreviousPacket != null) {
if (firstTsThisPacket < lastTimestampPreviousPacket) {
log.warning(String.format("non-monotonic timestamp: Resetting filter. (first event %d is smaller than previous event %d by %d)",
firstTsThisPacket, lastTimestampPreviousPacket, firstTsThisPacket - lastTimestampPreviousPacket));
resetFilter();
return;
}
// we had some previous event
int lastPacketTs = lastTimestampPreviousPacket + 1; // 1us more than timestamp of the last event in the last packet
insertNoiseEvents(lastPacketTs, firstTsThisPacket, outItr, generatedNoise);
}
// insert noise between events of this packet after the first event, record their timestamp
int preEts = 0;
int lastEventTs = in.getFirstTimestamp();
for (BasicEvent ie : in) {
// if it is the first event or any with first event timestamp then just copy them
if (ie.timestamp == firstTsThisPacket) {
outItr.nextOutput().copyFrom(ie);
continue;
}
// save the previous timestamp and get the next one, and then inject noise between them
preEts = lastEventTs;
lastEventTs = ie.timestamp;
insertNoiseEvents(preEts, lastEventTs, outItr, generatedNoise);
outItr.nextOutput().copyFrom(ie);
}
}
private void insertNoiseEvents(int lastPacketTs, int firstTsThisPacket, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> generatedNoise) {
for (double ts = lastPacketTs; ts < firstTsThisPacket; ts += poissonDtUs) {
// note that poissonDtUs is float but we truncate the actual timestamp to int us value here.
// It's OK if there are events with duplicate timestamps (there are plenty in input already).
sampleNoiseEvent((int)ts, outItr, generatedNoise, shotOffThresholdProb, shotOnThresholdProb, leakOnThresholdProb); // note noise injection updates ts to make sure monotonic
}
}
private int sampleNoiseEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> noiseList, float shotOffThresholdProb, float shotOnThresholdProb, float leakOnThresholdProb) {
float randomnum = random.nextFloat();
if (randomnum < shotOffThresholdProb) {
injectOffEvent(ts, outItr, noiseList);
} else if (randomnum > shotOnThresholdProb) {
injectOnEvent(ts, outItr, noiseList);
}
if (random.nextFloat() < leakOnThresholdProb) {
injectOnEvent(ts, outItr, noiseList);
}
return ts; // we make sure ts increment and return the new one, which updates loop param
}
private void injectOnEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> noiseList) {
ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput();
e.setSpecial(false);
e.polarity = PolarityEvent.Polarity.On;
int x = (short) random.nextInt(sx);
int y = (short) random.nextInt(sy);
e.x = (short) (x);
e.y = (short) (y);
e.timestamp = ts;
noiseList.add(e);
}
private void injectOffEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> noiseList) {
ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput();
e.setSpecial(false);
e.polarity = PolarityEvent.Polarity.Off;
int x = (short) random.nextInt(sx);
int y = (short) random.nextInt(sy);
e.x = (short) (x);
e.y = (short) (y);
e.timestamp = ts;
noiseList.add(e);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
super.propertyChange(evt); //To change body of generated methods, choose Tools | Templates.
if (evt.getPropertyName() == AEInputStream.EVENT_REWOUND) {
log.info(String.format("got rewound event %s, setting reset on next packet flat", evt));
resetCalled = true;
}
}
/**
* @return the selectedNoiseFilter
*/
public NoiseFilterEnum getSelectedNoiseFilterEnum() {
return selectedNoiseFilterEnum;
}
/**
* @param selectedNoiseFilter the selectedNoiseFilter to set
*/
synchronized public void setSelectedNoiseFilterEnum(NoiseFilterEnum selectedNoiseFilter) {
this.selectedNoiseFilterEnum = selectedNoiseFilter;
putString("selectedNoiseFilter", selectedNoiseFilter.toString());
for (AbstractNoiseFilter n : noiseFilters) {
if (n.getClass().getSimpleName().equals(selectedNoiseFilter.toString())) {
n.initFilter();
n.setFilterEnabled(true);
selectedFilter = n;
} else {
n.setFilterEnabled(false);
}
}
resetCalled = true; // make sure we iniitialize the timestamp maps on next packet for new filter
}
private String USAGE = "Need at least 2 arguments: noisefilter <command> <args>\nCommands are: setNoiseFilterParameters <csvFilename> xx <shotNoiseRateHz> xx <leakNoiseRateHz> xx and specific to the filter\n";
@Override
public String processRemoteControlCommand(RemoteControlCommand command, String input) {
// parse command and set parameters of NoiseTesterFilter, and pass command to specific filter for further processing
// setNoiseFilterParameters csvFilename 10msBAFdot_500m_0m_300num0 shotNoiseRateHz 0.5 leakNoiseRateHz 0 dt 300 num 0
String[] tok = input.split("\\s");
if (tok.length < 2) {
return USAGE;
} else {
for (int i = 1; i < tok.length; i++) {
if (tok[i].equals("csvFileName")) {
setCsvFilename(tok[i + 1]);
} else if (tok[i].equals("shotNoiseRateHz")) {
setShotNoiseRateHz(Float.parseFloat(tok[i + 1]));
log.info(String.format("setShotNoiseRateHz %f", shotNoiseRateHz));
} else if (tok[i].equals("leakNoiseRateHz")) {
setLeakNoiseRateHz(Float.parseFloat(tok[i + 1]));
log.info(String.format("setLeakNoiseRateHz %f", leakNoiseRateHz));
}
}
log.info("Received Command:" + input);
String out = selectedFilter.setParameters(command, input);
log.info("Execute Command:" + input);
return out;
}
}
/**
* Fills lastTimesMap with waiting times drawn from Poisson process with
* rate noiseRateHz
*
* @param lastTimesMap map
* @param noiseRateHz rate in Hz
* @param lastTimestampUs the last timestamp; waiting times are created
* before this time
*/
protected void initializeLastTimesMapForNoiseRate(int[][] lastTimesMap, float noiseRateHz, int lastTimestampUs) {
for (final int[] arrayRow : lastTimesMap) {
for (int i = 0; i < arrayRow.length; i++) {
final float p = random.nextFloat();
final double t = -noiseRateHz * Math.log(1 - p);
final int tUs = (int) (1000000 * t);
arrayRow[i] = lastTimestampUs - tUs;
}
}
}
@Override
public float getCorrelationTimeS() {
return this.correlationTimeS;
}
@Override
public void setCorrelationTimeS(float dtS) {
if (dtS > 1e-6f * MAX_DT) {
dtS = 1e-6f * MAX_DT;
} else if (dtS < 1e-6f * MIN_DT) {
dtS = 1e-6f * MIN_DT;
}
this.correlationTimeS = dtS;
for (AbstractNoiseFilter f : noiseFilters) {
f.setCorrelationTimeS(dtS);
}
putFloat("correlationTimeS", this.correlationTimeS);
}
/**
* @return the annotateAlpha
*/
public float getAnnotateAlpha() {
return annotateAlpha;
}
/**
* @param annotateAlpha the annotateAlpha to set
*/
public void setAnnotateAlpha(float annotateAlpha) {
if (annotateAlpha > 1.0) {
annotateAlpha = 1.0f;
}
if (annotateAlpha < 0.0) {
annotateAlpha = 0.0f;
}
this.annotateAlpha = annotateAlpha;
if (renderer != null) {
renderer.setAnnotateAlpha(annotateAlpha);
}
}
/**
* @return the overlayClassifications
*/
public boolean isOverlayClassifications() {
return overlayClassifications;
}
/**
* @param overlayClassifications the overlayClassifications to set
*/
public void setOverlayClassifications(boolean overlayClassifications) {
this.overlayClassifications = overlayClassifications;
putBoolean("overlayClassifications", overlayClassifications);
if (renderer != null) {
renderer.setDisplayAnnotation(overlayClassifications);
}
}
/**
* @return the overlayInput
*/
public boolean isOverlayInput() {
return overlayInput;
}
/**
* @param overlayInput the overlayInput to set
*/
public void setOverlayInput(boolean overlayInput) {
this.overlayInput = overlayInput;
putBoolean("overlayInput", overlayInput);
}
/**
* @return the rocHistory
*/
public int getRocHistory() {
return rocHistory;
}
/**
* @param rocHistory the rocHistory to set
*/
synchronized public void setRocHistory(int rocHistory) {
if (rocHistory > 10000) {
rocHistory = 10000;
}
this.rocHistory = rocHistory;
putInt("rocHistory", rocHistory);
rocHistoryList=EvictingQueue.create(rocHistory);
}
}
|
package pt.fccn.mobile.arquivo.tests;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.junit.Test;
import pt.fccn.mobile.arquivo.pages.IndexMobilePage;
import pt.fccn.saw.selenium.Retry;
import pt.fccn.saw.selenium.WebDriverTestBaseParalell;
import pt.fccn.sobre.arquivo.pages.IndexSobrePage;
public class FullTextSearchTest extends WebDriverTestBaseParalell {
public FullTextSearchTest(String os, String version, String browser, String deviceName, String deviceOrientation) {
super( os, version, browser, deviceName, deviceOrientation );
}
@Test
//@Retry
public void searchingTest( ) {
System.out.print( "[Mobile] Running SearchTest Test. \n");
//IndexMobilePage index = null;
//index = new IndexMobilePage( driver );
//Ispre_prod = index.setPreProd( pre_prod );
//index.testPrint( );
/*** Portuguese version ***/
//assertTrue("Failed The Search Test in Portuguese", index.checkSearch( "PT" ) );
System.out.println( "Success The Search Test in Portuguese" );
assertTrue( "ola".equals( "ola" ) );
/*** English version ***/
//assertTrue("Failed The Search Test in English", search.checkSearch( "EN" ) );
//System.out.println( "Success The Search Test in English" );
}
}
|
package hudson.slaves;
import com.gargoylesoftware.htmlunit.xml.XmlPage;
import hudson.Util;
import hudson.model.Computer;
import hudson.model.Node;
import hudson.model.Slave;
import jenkins.model.Jenkins;
import org.dom4j.Document;
import org.dom4j.io.DOMReader;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.FlagRule;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.LoggerRule;
import org.jvnet.hudson.test.MockAuthorizationStrategy;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Tests of {@link JNLPLauncher} using a custom inbound agent url.
*/
public class AgentInboundUrlTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Rule
public LoggerRule logging = new LoggerRule().record(Slave.class, Level.FINE);
// Override the inbound agent url
private static final String customInboundUrl = "http://localhost:8080/jenkins";
@Rule
public final FlagRule<String> customInboundUrlRule = FlagRule.systemProperty(JNLPLauncher.CUSTOM_INBOUND_URL_PROPERTY, customInboundUrl);
@Issue("JENKINS-63222")
@Test
public void testInboundAgentUrlOverride() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
MockAuthorizationStrategy authorizationStrategy = new MockAuthorizationStrategy();
authorizationStrategy.grant(Jenkins.ADMINISTER).everywhere().toEveryone();
j.jenkins.setAuthorizationStrategy(authorizationStrategy);
// Create an agent
addTestAgent();
// parse the JNLP page into DOM to inspect the jnlp url argument.
JenkinsRule.WebClient agent = j.createWebClient();
XmlPage jnlp = (XmlPage) agent.goTo("computer/test/jenkins-agent.jnlp", "application/x-java-jnlp-file");
Document dom = new DOMReader().read(jnlp.getXmlDocument());
Object arg = dom.selectSingleNode("//application-desc/argument[3]/following-sibling::argument[1]");
String val = ((org.dom4j.Element) arg).getText();
assertEquals(customInboundUrl, val);
}
/**
* Adds an Inbound TCP agent to the system and returns it.
*/
private void addTestAgent() throws Exception {
addTestAgent(new JNLPLauncher(false));
}
/**
* Adds an Inbound TCP agent to the system and returns it.
*/
private void addTestAgent(ComputerLauncher launcher) throws Exception {
List<Node> agents = new ArrayList<>(j.jenkins.getNodes());
File dir = Util.createTempDir();
agents.add(new DumbSlave("test", "dummy", dir.getAbsolutePath(), "1", Node.Mode.NORMAL, "",
launcher, RetentionStrategy.INSTANCE, new ArrayList<>()));
j.jenkins.setNodes(agents);
Computer c = j.jenkins.getComputer("test");
assertNotNull(c);
}
}
|
package org.spine3.testdata;
import com.google.common.base.Enums;
import com.google.common.base.Optional;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor.JavaType;
import com.google.protobuf.Descriptors.FieldDescriptor.Type;
import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.Message;
import com.google.protobuf.Timestamp;
import org.spine3.protobuf.AnyPacker;
import org.spine3.protobuf.KnownTypes;
import org.spine3.protobuf.TypeUrl;
import org.spine3.server.aggregate.storage.AggregateStorageRecord;
import org.spine3.server.event.storage.EventStorageRecord;
import org.spine3.type.ClassName;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.SecureRandom;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
/**
* Utility for creating simple stubs for generated messages.
*
* @author Dmytro Dashenkov
*/
public class Sample {
private Sample() {
}
/**
* Utility class for stubbing the {@link EventStorageRecord} instances.
*
* @see Sample
*/
public static class EventRecord {
private EventRecord() {
}
public static EventStorageRecord withRandomFields() {
return Sample.messageOfType(EventStorageRecord.class);
}
public static EventStorageRecord with(Timestamp timestamp) {
final EventStorageRecord.Builder builder = Sample.builderForType(EventStorageRecord.class);
builder.setTimestamp(timestamp);
return builder.build();
}
public static EventStorageRecord with(String eventId) {
final EventStorageRecord.Builder builder = Sample.builderForType(EventStorageRecord.class);
builder.setEventId(eventId);
return builder.build();
}
public static EventStorageRecord with(String eventId, Timestamp timestamp) {
final EventStorageRecord.Builder builder = Sample.builderForType(EventStorageRecord.class);
builder.setEventId(eventId)
.setTimestamp(timestamp);
return builder.build();
}
}
/**
* Utility class for stubbing the {@link AggregateStorageRecord} instances.
*
* @see Sample
*/
public static class AggregateRecord {
private AggregateRecord() {
}
public static AggregateStorageRecord withRandomFields() {
return Sample.messageOfType(AggregateStorageRecord.class);
}
}
/**
* Generates a new stub {@link Message.Builder builder} with all the fields set to {@link Random random} values.
*
* <p> All the fields are guaranteed to be not {@code null} and not default. Number and {@code boolean} fields
* may or may not have their default values ({@code 0} and {@code false}).
*
* @param clazz Java class of the stub message
* @param <M> type of the required message
* @param <B> type of the {@link Message.Builder builder} for the message
* @return new instance of the {@link Message.Builder} for given type
* @see #valueFor(FieldDescriptor)
*/
public static <M extends Message, B extends Message.Builder> B builderForType(Class<M> clazz) {
checkClass(clazz);
final B builder = builderFor(clazz);
final Descriptor builderDescriptor = builder.getDescriptorForType();
final Collection<FieldDescriptor> fields = builderDescriptor.getFields();
for (FieldDescriptor field : fields) {
final Object value = valueFor(field);
if (field.isRepeated()) {
builder.addRepeatedField(field, value);
} else {
builder.setField(field, value);
}
}
return builder;
}
/**
* Generates a new stub {@link Message} with all the fields set to {@link Random random} values.
*
* <p> All the fields are guaranteed to be not {@code null} and not default. Number and {@code boolean} fields
* may or may not have their default values ({@code 0} and {@code false}).
*
* <p>If the required type is {@link Any}, an instance of an empty {@link Any} wrapped into another {@link Any}
* is returned. See {@link AnyPacker}.
*
* @param clazz Java class of the required stub message
* @param <M> type of the required message
* @return new instance of the given {@link Message} type with random fields
* @see #builderForType(Class)
*/
public static <M extends Message> M messageOfType(Class<M> clazz) {
checkClass(clazz);
if (Any.class.equals(clazz)) {
final Any any = Any.getDefaultInstance();
@SuppressWarnings("unchecked")
final M result = (M) AnyPacker.pack(any);
return result;
}
final M.Builder builder = builderForType(clazz);
@SuppressWarnings("unchecked") // Checked cast
final M result = (M) builder.build();
return result;
}
private static void checkClass(Class<? extends Message> clazz) {
checkNotNull(clazz);
// Support only generated protobuf messages
checkArgument(clazz.isAssignableFrom(GeneratedMessageV3.class));
}
/**
* Generates a non-default value for the given message field.
*
* <p>All the protobuf types are supported including nested {@link Message}s and the {@code enum}s.
*
* @param field {@link FieldDescriptor} to take the type info from
* @return a non-default generated value of type of the given field
*/
private static Object valueFor(FieldDescriptor field) {
final Type type = field.getType();
final JavaType javaType = type.getJavaType();
final Random random = new SecureRandom();
switch (javaType) {
case INT:
return random.nextInt();
case LONG:
return random.nextLong();
case FLOAT:
return random.nextFloat();
case DOUBLE:
return random.nextDouble();
case BOOLEAN:
return random.nextBoolean();
case STRING:
final byte[] bytes = new byte[8];
random.nextBytes(bytes);
return new String(bytes);
case BYTE_STRING:
final byte[] bytesPrimitive = new byte[8];
random.nextBytes(bytesPrimitive);
return ByteString.copyFrom(bytesPrimitive);
case ENUM:
return enumValueFor(field, random);
case MESSAGE:
return messageValueFor(field);
default:
throw new IllegalArgumentException(format("Field type %s is not supported.", type));
}
}
private static Enum enumValueFor(FieldDescriptor field, Random random) {
final Descriptors.EnumDescriptor descriptor = field.getEnumType();
final List<Descriptors.EnumValueDescriptor> enumValues = descriptor.getValues();
if (enumValues.isEmpty()) {
return null;
}
// Value under index 0 is usually used to store `undefined` option
// Use values with indexes from 1 to n
final int index = random.nextInt(enumValues.size() - 1) + 1;
final Descriptors.EnumValueDescriptor enumValue = descriptor.findValueByNumber(index);
final String enumValueName = enumValue.getName();
final TypeUrl enumType = TypeUrl.from(descriptor);
final Class<? extends Enum> enumClass = classFor(enumType);
final Optional<? extends Enum> enumField = Enums.getIfPresent(enumClass, enumValueName);
checkState(enumField.isPresent());
return enumField.get();
}
private static Message messageValueFor(FieldDescriptor field) {
final TypeUrl messageType = TypeUrl.from(field.getMessageType());
final Class<? extends Message> javaClass = classFor(messageType);
final Message fieldValue = Sample.messageOfType(javaClass);
return fieldValue;
}
@SuppressWarnings("unchecked") // Reflective class definition retrieving
private static <M extends Message> Class<M> classFor(TypeUrl type) {
final ClassName className = KnownTypes.getClassName(type);
final Class<M> javaClass;
try {
javaClass = (Class<M>) Class.forName(className.value());
return javaClass;
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
}
private static <B extends Message.Builder> B builderFor(Class<? extends Message> clazz) {
try {
final Method factoryMethod = clazz.getDeclaredMethod("newBuilder");
@SuppressWarnings("unchecked")
final B result = (B) factoryMethod.invoke(null);
return result;
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException(
format("Class %s must be a generated proto message",
clazz.getCanonicalName()),
e);
}
}
}
|
package net.maizegenetics.pal.alignment.io;
import net.maizegenetics.pal.alignment.*;
import net.maizegenetics.pal.alignment.genotype.Genotype;
import net.maizegenetics.pal.alignment.genotype.GenotypeBuilder;
import net.maizegenetics.pal.site.*;
import net.maizegenetics.pal.taxa.Taxon;
import net.maizegenetics.pal.taxa.TaxaList;
import net.maizegenetics.pal.taxa.TaxaListBuilder;
import net.maizegenetics.util.Utils;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
/**
* Create an alignment based on HapMap format file (either .txt or compressed). Alleles are set as global major and
* global minor.
* e.g. code <p></p>
* {@code
* Alignment a=BuilderFromHapMap.getBuilder(infileName).build();
* }
* <p></p>
* TODO: Add filtering while reading, provide an option to define the alleles as reference and alternate
*
* @author Ed Buckler
*/
public class BuilderFromHapMap {
private static final Logger myLogger = Logger.getLogger(BuilderFromHapMap.class);
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s");
private static final int NUM_HAPMAP_NON_TAXA_HEADERS = 11;
private final String infile;
private BuilderFromHapMap(String infile) {
this.infile = infile;
}
public static BuilderFromHapMap getBuilder(String infile) {
return new BuilderFromHapMap(infile);
}
//TODO provide options on caching to use, read only some sites, etc.
public Alignment build() {
long time = System.nanoTime();
Alignment result = null;
try {
int numThreads = Runtime.getRuntime().availableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(numThreads);
BufferedReader r = Utils.getBufferedReader(infile, -1);
TaxaList taxaList = processTaxa(r.readLine());
String currLine;
int linesAtTime = 1 << 12; //this is a critical lines with 20% or more swings. Needs to be optimized with transposing
// int linesAtTime=1<<8; //better for with lots of taxa.
ArrayList<String> txtLines = new ArrayList<>(linesAtTime);
ArrayList<ProcessHapMapBlock> pbs = new ArrayList<>();
int lines = 0;
while ((currLine = r.readLine()) != null) {
txtLines.add(currLine);
lines++;
if (lines % linesAtTime == 0) {
ProcessHapMapBlock pb = ProcessHapMapBlock.getInstance(pbs.size(), taxaList.getTaxaCount(), txtLines);
pbs.add(pb);
// pb.run();
pool.execute(pb);
txtLines = new ArrayList<>(linesAtTime);
}
}
r.close();
if (txtLines.size() > 0) {
ProcessHapMapBlock pb = ProcessHapMapBlock.getInstance(pbs.size(), taxaList.getTaxaCount(), txtLines);
pbs.add(pb);
pool.execute(pb);
}
pool.shutdown();
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
throw new IllegalStateException("BuilderFromHapMap: processing threads timed out.");
}
int currentSite = 0;
PositionArrayList.Builder posBuild = new PositionArrayList.Builder();
GenotypeBuilder gb = GenotypeBuilder.getUnphasedNucleotideGenotypeBuilder(taxaList.getTaxaCount(), lines);
for (ProcessHapMapBlock pb : pbs) {
posBuild.addAll(pb.getBlkPosList());
byte[][] bgTS = pb.getGenoTS();
for (int t = 0; t < bgTS.length; t++) {
gb.setBaseRangeForTaxon(t, currentSite, bgTS[t]);
}
currentSite += pb.getSiteNumber();
}
if (posBuild.validateOrdering() == false) {
throw new IllegalStateException("BuilderFromHapMap: Ordering incorrect HapMap must be ordered by position");
}
Genotype g = gb.build();
result = AlignmentBuilder.getInstance(g, posBuild.build(), taxaList);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
long totalTime = System.nanoTime() - time;
System.out.printf("BuilderFromHapMap data timing %gs %n", totalTime / 1e9);
return result;
}
private static TaxaList processTaxa(String readLn) {
String[] header = WHITESPACE_PATTERN.split(readLn);
int numTaxa = header.length - NUM_HAPMAP_NON_TAXA_HEADERS;
TaxaListBuilder tlb = new TaxaListBuilder();
for (int i = 0; i < numTaxa; i++) {
Taxon at = new Taxon.Builder(header[i + NUM_HAPMAP_NON_TAXA_HEADERS])
.build();
tlb.add(at);
}
return tlb.build();
}
}
class ProcessHapMapBlock implements Runnable {
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s");
private static final Pattern SLASH_PATTERN = Pattern.compile("/");
private static final int NUM_HAPMAP_NON_TAXA_HEADERS = 11;
private static final int GENOIDX = NUM_HAPMAP_NON_TAXA_HEADERS;
private static final int SNPID_INDEX = 0;
private static final int VARIANT_INDEX = 1;
private static final int CHROMOSOME_INDEX = 2;
private static final int POSITION_INDEX = 3;
private final int order;
private final int taxaN;
private final int siteN;
private ArrayList<String> txtL;
private byte[][] gTS;
private final ArrayList<Position> blkPosList;
private final byte[] convert;
private final boolean isOneLetter; //true e.g. A,R, false=AA,CT
private ProcessHapMapBlock(int order, int taxaN, ArrayList<String> txtL) {
this.order = order;
this.taxaN = taxaN;
this.siteN = txtL.size();
this.txtL = txtL;
blkPosList = new ArrayList<>(siteN);
String[] tokens = WHITESPACE_PATTERN.split(txtL.get(0), NUM_HAPMAP_NON_TAXA_HEADERS + 1);
double avg = (double) (tokens[GENOIDX].length() + 1) / (double) taxaN;
if ((avg > 1.99) && (avg < 2.01)) {
isOneLetter = true;
} else if ((avg > 2.99) && (avg < 3.01)) {
isOneLetter = false;
} else {
throw new IllegalStateException("ProcessHapMapBlock: Genotype coded wrong use one or 2 letters per genotype");
}
//todo Move to Nucleotide constants if best way
convert = new byte[128];
for (int i = 0; i < convert.length; i++) {
try {
convert[i] = NucleotideAlignmentConstants.getNucleotideDiploidByte((char) i);
} catch (IllegalArgumentException e) {
convert[i] = Alignment.UNKNOWN_DIPLOID_ALLELE;
}
}
}
public static ProcessHapMapBlock getInstance(int order, int taxaN, ArrayList<String> txtL) {
return new ProcessHapMapBlock(order, taxaN, txtL);
}
//@Override
public void run() {
Map<String, Chromosome> chromosomeLookup = new HashMap<>();
gTS = new byte[taxaN][siteN];
for (int s = 0; s < siteN; s++) {
String input = txtL.get(s);
int[] tabPos = new int[NUM_HAPMAP_NON_TAXA_HEADERS];
int tabIndex = 0;
int len = input.length();
for (int i = 0; (tabIndex < NUM_HAPMAP_NON_TAXA_HEADERS) && (i < len); i++) {
if (input.charAt(i) == '\t') {
tabPos[tabIndex++] = i;
}
}
String chrName = input.substring(tabPos[CHROMOSOME_INDEX - 1] + 1, tabPos[CHROMOSOME_INDEX]);
Chromosome currChr = chromosomeLookup.get(chrName);
if (currChr == null) {
currChr = new Chromosome(new String(chrName));
chromosomeLookup.put(chrName, currChr);
}
String variants = input.substring(tabPos[VARIANT_INDEX - 1] + 1, tabPos[VARIANT_INDEX]);
GeneralPosition.Builder apb = new GeneralPosition.Builder(currChr,
Integer.parseInt(input.substring(tabPos[POSITION_INDEX - 1] + 1, tabPos[POSITION_INDEX])))
.snpName(input.substring(0, tabPos[SNPID_INDEX]))
.knownVariants(variants) //TODO strand, variants,
;
try {
byte glbMajor = convert[variants.charAt(0)];
apb.allele(Position.Allele.GLBMAJ, glbMajor);
if (variants.length() == 3) {
byte glbMinor = convert[variants.charAt(2)];
apb.allele(Position.Allele.GLBMIN, glbMinor);
}
} catch (IllegalArgumentException e) {
//for the indels that cannot be converted correctly now
// System.out.println("Error Parsing this variant"+Arrays.toString(variants));
}
blkPosList.add(apb.build());
int offset = tabPos[NUM_HAPMAP_NON_TAXA_HEADERS - 1] + 1;
if (isOneLetter) {
for (int i = offset; i < len; i += 2) {
gTS[(i - offset) / 2][s] = convert[input.charAt(i)];
}
} else {
for (int i = offset; i < len; i += 3) {
//System.out.println(i+":"+input.charAt(i+1)+input.charAt(i));
//there is a phasing conflict with the existing import approach
gTS[(i - offset) / 3][s] = AlignmentUtils.getDiploidValue(convert[input.charAt(i + 1)], convert[input.charAt(i)]);
}
}
}
txtL = null;
}
int getSiteNumber() {
return siteN;
}
byte[][] getGenoTS() {
return gTS;
}
ArrayList<Position> getBlkPosList() {
return blkPosList;
}
}
|
package net.wisedog.android.whooing.activity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import net.wisedog.android.whooing.Define;
import net.wisedog.android.whooing.R;
import net.wisedog.android.whooing.db.AccountsEntity;
import net.wisedog.android.whooing.engine.DataRepository;
import net.wisedog.android.whooing.engine.DataRepository.OnBsChangeListener;
import net.wisedog.android.whooing.engine.GeneralProcessor;
import net.wisedog.android.whooing.utils.FragmentUtil;
import net.wisedog.android.whooing.utils.WhooingCurrency;
import net.wisedog.android.whooing.widget.WiTextView;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import com.actionbarsherlock.app.SherlockFragment;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
/**
* @author Wisedog(me@wisedog.net)
*
*/
public class BalanceFragment extends SherlockFragment implements OnBsChangeListener{
public static BalanceFragment newInstance() {
BalanceFragment fragment = new BalanceFragment();
return fragment;
}
private Activity mActivity;
private AdView adView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.balance_fragment, null);
// adView
adView = new AdView(getSherlockActivity(), AdSize.SMART_BANNER, "a15147cd53daa26");
LinearLayout layout = (LinearLayout)view.findViewById(R.id.balance_ads);
// LinearLayout adView
layout.addView(adView);
AdRequest adRequest = new AdRequest();
if(Define.DEBUG){
adRequest.addTestDevice("65E3B8CB214707370B559D98093D74AA");
}
adView.loadAd(adRequest);
return view;
}
@Override
public void onResume() {
TableLayout tl = (TableLayout) mActivity
.findViewById(R.id.balance_asset_table);
if(tl.getChildCount() <= 2){
DataRepository repository = DataRepository.getInstance();
if(repository.getBsValue() != null){
showBalance(repository.getBsValue());
}
else{
repository.refreshBsValue(getSherlockActivity());
repository.registerObserver(this, DataRepository.BS_MODE);
}
}
super.onResume();
}
@Override
public void onAttach(Activity activity) {
mActivity = activity;
super.onAttach(activity);
}
@Override
public void onDestroyView() {
DataRepository repository = DataRepository.getInstance();
repository.removeObserver(this, DataRepository.BS_MODE);
adView.destroy();
super.onDestroyView();
}
/**
* Show Balance
* @param obj JSON formatted balance data
* */
public void showBalance(JSONObject obj) {
WiTextView labelTotalAssetValue = (WiTextView)mActivity.findViewById(R.id.balance_total_asset_value);
TableLayout tl = (TableLayout) mActivity
.findViewById(R.id.balance_asset_table);
DisplayMetrics metrics = new DisplayMetrics();
mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
final int secondColumnWidth = (int) (metrics.widthPixels * 0.6);
Resources r = getResources();
final int valueWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 95,
r.getDisplayMetrics());
final int viewHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14,
r.getDisplayMetrics());
final int rightMargin4Dip = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
r.getDisplayMetrics());
try {
JSONObject objResult = obj.getJSONObject("results");
JSONObject objAssets = objResult.getJSONObject("assets");
double totalAssetValue = objAssets.getDouble("total");
if (labelTotalAssetValue != null) {
double totalAssetValue1 = objAssets.getDouble("total");
labelTotalAssetValue.setText(WhooingCurrency.getFormattedValue(totalAssetValue1));
View bar = (View) mActivity.findViewById(R.id.bar_total_asset);
int barWidth = FragmentUtil.getBarWidth(objAssets.getInt("total"), totalAssetValue,
secondColumnWidth, valueWidth);
android.widget.LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(
barWidth, viewHeight);
lParams.setMargins(0, 0, rightMargin4Dip, 0);
lParams.gravity = Gravity.CENTER_VERTICAL;
bar.setLayoutParams(lParams);
}
JSONArray objAssetAccounts = objAssets.getJSONArray("accounts");
showBalanceEntities(objAssetAccounts, totalAssetValue, secondColumnWidth,
valueWidth, tl, 0xFFC36FBC);
JSONObject objLiabilities = objResult.getJSONObject("liabilities");
JSONArray objLiabilitiesAccounts = objLiabilities.getJSONArray("accounts");
TableLayout tableLiabilites = (TableLayout) mActivity
.findViewById(R.id.balance_liabilities_table);
WiTextView labelTotalLiabilitiesValue = (WiTextView)mActivity.findViewById(R.id.balance_total_liabilities_value);
if(labelTotalLiabilitiesValue != null){
double totalLiabilities = objLiabilities.getDouble("total");
labelTotalLiabilitiesValue.setText(WhooingCurrency.getFormattedValue(totalLiabilities));
View bar = (View)mActivity.findViewById(R.id.bar_total_liabilities);
int barWidth = FragmentUtil.getBarWidth(objLiabilities.getInt("total"), totalAssetValue,
secondColumnWidth, valueWidth);
android.widget.LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(
barWidth, viewHeight);
lParams.setMargins(0, 0, rightMargin4Dip, 0);
lParams.gravity = Gravity.CENTER_VERTICAL;
bar.setLayoutParams(lParams);
}
showBalanceEntities(objLiabilitiesAccounts, totalAssetValue, secondColumnWidth,
valueWidth, tableLiabilites, 0xFF5294FF);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showBalanceEntities(JSONArray accounts, double totalAssetValue,
int secondColumnWidth, int labelWidth, TableLayout tl, int color) throws JSONException{
if(accounts == null){
return;
}
GeneralProcessor genericProcessor = new GeneralProcessor(mActivity);
for(int i = 0; i < accounts.length(); i++){
JSONObject accountItem = (JSONObject) accounts.get(i);
/* Create a new row to be added. */
TableRow tr = new TableRow(mActivity);
tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
tr.setWeightSum(1.0f);
WiTextView accountText = new WiTextView(mActivity);
AccountsEntity entity = genericProcessor.findAccountById(accountItem.getString("account_id"));
accountText.setText(entity.title);
accountText.setLayoutParams(new LayoutParams(
0, LayoutParams.WRAP_CONTENT, 0.4f));
tr.addView(accountText);
LinearLayout amountLayout = new LinearLayout(mActivity);
amountLayout.setLayoutParams(new TableRow.LayoutParams(
0,
LayoutParams.WRAP_CONTENT,0.6f));
int barWidth = FragmentUtil.getBarWidth(accountItem.getDouble("money"), totalAssetValue,
secondColumnWidth, labelWidth);
Resources r = getResources();
int px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14, r.getDisplayMetrics());
android.widget.LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(
barWidth, px);
//set up view for horizontally bar graph
View barView = new View(mActivity);
barView.setBackgroundColor(color);
int rightMargin = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, r.getDisplayMetrics());
lParams.setMargins(0, 0, rightMargin, 0);
lParams.gravity = Gravity.CENTER_VERTICAL;
barView.setLayoutParams(lParams);
//set up textview for showing amount
WiTextView amountText = new WiTextView(mActivity);
double money = accountItem.getDouble("money");
amountText.setText(WhooingCurrency.getFormattedValue(money));
amountLayout.addView(barView);
amountLayout.addView(amountText);
tr.addView(amountLayout);
/* Add row to TableLayout. */
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
}
}
/* (non-Javadoc)
* @see net.wisedog.android.whooing.engine.DataRepository.OnBsChangeListener#onBsUpdate(org.json.JSONObject)
*/
public void onBsUpdate(JSONObject obj) {
showBalance(obj);
}
}
|
package net.sf.jaer.eventprocessing.filter;
import ch.unizh.ini.jaer.projects.util.ColorHelper;
import com.google.common.collect.EvictingQueue;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLException;
import com.jogamp.opengl.util.gl2.GLUT;
import java.beans.PropertyChangeEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.OutputEventIterator;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventio.AEInputStream;
import static net.sf.jaer.eventprocessing.EventFilter.log;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.util.RemoteControlCommand;
import net.sf.jaer.util.RemoteControlled;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import net.sf.jaer.aemonitor.AEPacketRaw;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket.InItr;
import net.sf.jaer.eventio.AEFileInputStream;
import net.sf.jaer.graphics.ChipDataFilePreview;
import net.sf.jaer.graphics.DavisRenderer;
import net.sf.jaer.util.DATFileFilter;
import net.sf.jaer.util.DrawGL;
/**
* Filter for testing noise filters
*
* @author tobid/shasah
*/
@Description("Tests noise filters by injecting known noise and measuring how much signal and noise is filtered")
@DevelopmentStatus(DevelopmentStatus.Status.Stable)
public class NoiseTesterFilter extends AbstractNoiseFilter implements FrameAnnotater, RemoteControlled {
public static final int MAX_NUM_RECORDED_EVENTS = 10_0000_0000;
public static final float MAX_TOTAL_NOISE_RATE_HZ = 50e6f;
public static final float RATE_LIMIT_HZ = 25; //per pixel, separately for leak and shot rates
private FilterChain chain;
private float shotNoiseRateHz = getFloat("shotNoiseRateHz", .1f);
private float leakNoiseRateHz = getFloat("leakNoiseRateHz", .1f);
private float poissonDtUs = 1;
private float shotOffThresholdProb; // bounds for samppling Poisson noise, factor 0.5 so total rate is shotNoiseRateHz
private float shotOnThresholdProb; // for shot noise sample both sides, for leak events just generate ON events
private float leakOnThresholdProb; // bounds for samppling Poisson noise
private PrerecordedNoise prerecordedNoise = null;
private static String DEFAULT_CSV_FILENAME_BASE = "NoiseTesterFilter";
private String csvFileName = getString("csvFileName", DEFAULT_CSV_FILENAME_BASE);
private File csvFile = null;
private BufferedWriter csvWriter = null;
// chip size values, set in initFilter()
private int sx = 0;
private int sy = 0;
private Integer lastTimestampPreviousPacket = null, firstSignalTimestmap = null; // use Integer Object so it can be null to signify no value yet
private float TPR = 0;
private float TPO = 0;
private float TNR = 0;
private float accuracy = 0;
private float BR = 0;
float inSignalRateHz = 0, inNoiseRateHz = 0, outSignalRateHz = 0, outNoiseRateHz = 0;
// private EventPacket<ApsDvsEvent> signalAndNoisePacket = null;
private Random random = new Random();
private EventPacket<BasicEvent> signalAndNoisePacket = null;
// private EventList<BasicEvent> noiseList = new EventList();
private AbstractNoiseFilter[] noiseFilters = null;
private AbstractNoiseFilter selectedFilter = null;
protected boolean resetCalled = true; // flag to reset on next event
private float annotateAlpha = getFloat("annotateAlpha", 0.5f);
private DavisRenderer renderer = null;
private boolean overlayClassifications = getBoolean("overlayClassifications", false);
private boolean overlayInput = getBoolean("overlayInput", false);
private int rocHistory = getInt("rocHistory", 1);
private EvictingQueue<ROCSample> rocHistoryList = EvictingQueue.create(rocHistory);
private ArrayList<BasicEvent> tpList = null, fnList = null, fpList = null, tnList = null; // output of classification
public enum NoiseFilterEnum {
BackgroundActivityFilter, SpatioTemporalCorrelationFilter, SequenceBasedFilter, OrderNBackgroundActivityFilter
}
private NoiseFilterEnum selectedNoiseFilterEnum = NoiseFilterEnum.valueOf(getString("selectedNoiseFilter", NoiseFilterEnum.BackgroundActivityFilter.toString())); //default is BAF
private float correlationTimeS = getFloat("correlationTimeS", 20e-3f);
private class ROCSample {
float x, y, tau;
boolean labeled = false;
public ROCSample(float x, float y, float tau) {
this.x = x;
this.y = y;
this.tau = tau;
}
}
// recorded noise to be used as input
private class PrerecordedNoise {
EventPacket<BasicEvent> recordedNoiseFileNoisePacket = null;
int firstTs;
Iterator<BasicEvent> itr = null;
BasicEvent firstEvent, nextEvent;
private PrerecordedNoise(File chosenPrerecordedNoiseFilePath) throws IOException {
AEFileInputStream recordedNoiseAeFileInputStream = new AEFileInputStream(chosenPrerecordedNoiseFilePath, getChip());
AEPacketRaw rawPacket = recordedNoiseAeFileInputStream.readPacketByNumber(MAX_NUM_RECORDED_EVENTS);
recordedNoiseAeFileInputStream.close();
EventPacket<BasicEvent> inpack = getChip().getEventExtractor().extractPacket(rawPacket);
EventPacket<BasicEvent> recordedNoiseFileNoisePacket = new EventPacket(PolarityEvent.class);
OutputEventIterator outItr = recordedNoiseFileNoisePacket.outputIterator();
for (BasicEvent p : inpack) {
outItr.nextOutput().copyFrom(p);
}
this.recordedNoiseFileNoisePacket = recordedNoiseFileNoisePacket;
itr = recordedNoiseFileNoisePacket.inputIterator();
firstEvent = recordedNoiseFileNoisePacket.getFirstEvent();
firstTs = recordedNoiseFileNoisePacket.getFirstTimestamp();
this.nextEvent = this.firstEvent;
computeProbs(); // set noise sample rate via poissonDtUs
log.info(String.format("Loaded %s pre-recorded events with duration %ss from %s", eng.format(recordedNoiseFileNoisePacket.getSize()), eng.format(1e-6f * recordedNoiseAeFileInputStream.getDurationUs()), chosenPrerecordedNoiseFilePath));
}
BasicEvent nextEventInRange(Integer signalFirstTs, int ts, float dT) {
if (signalFirstTs == null) {
return null;
}
if (nextEvent.timestamp - firstTs < ts - signalFirstTs + dT) {
BasicEvent rtn = nextEvent;
if (itr.hasNext()) {
nextEvent = itr.next();
} else {
itr = recordedNoiseFileNoisePacket.inputIterator();
firstTs += recordedNoiseFileNoisePacket.getDurationUs();
nextEvent = itr.next();
log.info(String.format("restart noise input from file after %d us", recordedNoiseFileNoisePacket.getDurationUs()));
}
return rtn;
}
return null;
}
private void rewind() {
this.itr = recordedNoiseFileNoisePacket.inputIterator();
nextEvent = firstEvent;
}
}
public NoiseTesterFilter(AEChip chip) {
super(chip);
String ann = "Filtering Annotation";
String roc = "ROC display";
String out = "Output";
String noise = "Noise";
String filt = "Filtering control";
setPropertyTooltip(noise, "shotNoiseRateHz", "rate per pixel of shot noise events");
setPropertyTooltip(noise, "leakNoiseRateHz", "rate per pixel of leak noise events");
setPropertyTooltip(noise, "openNoiseSourceRecording", "Open a pre-recorded AEDAT file as noise source.");
setPropertyTooltip(noise, "closeNoiseSourceRecording", "Closes the pre-recorded noise input.");
setPropertyTooltip(noise, "closeCsvFile", "Closes the output spreadsheet data file.");
setPropertyTooltip(out, "csvFileName", "Enter a filename base here to open CSV output file (appending to it if it already exists)");
setPropertyTooltip(filt, "selectedNoiseFilterEnum", "Choose a noise filter to test");
setPropertyTooltip(ann, "annotateAlpha", "Sets the transparency for the annotated pixels. Only works for Davis renderer.");
setPropertyTooltip(ann, "overlayClassifications", "Overlay the signal and noise classifications of events in green and red.");
setPropertyTooltip(ann, "overlayInput", "<html><p>If selected, overlay all input events as signal (green) and noise (red). <p>If not selected, overlay true positives as green (signal in output) and false positives as red (noise in output).");
setPropertyTooltip(roc, "rocHistory", "Number of samples of ROC point to show.");
setPropertyTooltip(roc, "clearROCHistory", "Clears samples from display.");
if (chip.getRemoteControl() != null) {
log.info("adding RemoteControlCommand listener to AEChip\n");
chip.getRemoteControl().addCommandListener(this, "setNoiseFilterParameters", "set correlation time or distance.");
}
}
@Override
public synchronized void setFilterEnabled(boolean yes) {
filterEnabled = yes;
if (yes) {
for (EventFilter2D f : chain) {
if (selectedFilter != null && selectedFilter == f) {
f.setFilterEnabled(yes);
}
}
} else {
for (EventFilter2D f : chain) {
f.setFilterEnabled(false);
}
}
}
private int rocSampleCounter = 0;
private final int ROC_LABEL_TAU_INTERVAL = 30;
@Override
synchronized public void annotate(GLAutoDrawable drawable) {
int L;
float x, y;
if (!showFilteringStatistics) {
return;
}
final GLUT glut = new GLUT();
findUnusedDawingY();
GL2 gl = drawable.getGL().getGL2();
L = 5;
gl.glLineWidth(2);
for (ROCSample rocSample : rocHistoryList) {
float hue = (float) Math.log10(100 * rocSample.tau); //. hue is 1 for tau=100ms and is 0 for tau = 1ms
float[] colors = ColorHelper.HSVtoRGB(hue, 1.0f, 1.0f);
gl.glColor3f(colors[0], colors[1], colors[2]); // must set color before raster position (raster position is like glVertex)
gl.glLineWidth(2);
x = (1 - rocSample.y) * sx;
y = rocSample.x * sy;
// compute area of box propto the tau
// final float l = L * (float) Math.sqrt(1e2 * p.tau); // 10ms tau will produce box of dimension L
final float l = L; // 10ms tau will produce box of dimension L
gl.glPushMatrix();
DrawGL.drawBox(gl, x, y, l, l, 0);
gl.glPopMatrix();
if (rocSample.labeled) {
gl.glPushMatrix();
gl.glRasterPos3f(x + 5 * L, y - 3 * L, 0);
// gl.glColor3f(.5f, .5f, .8f); // must set color before raster position (raster position is like glVertex)
String s = String.format("%ss", eng.format(rocSample.tau));
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
gl.glPopMatrix();
}
}
// draw X at TPR / TNR point
gl.glPushMatrix();
gl.glColor3f(.8f, .8f, .2f); // must set color before raster position (raster position is like glVertex)
L = 12;
gl.glLineWidth(4);
x = (1 - TNR) * sx;
y = TPR * sy;
DrawGL.drawCross(gl, x, y, L, 0);
gl.glPopMatrix();
gl.glPushMatrix();
gl.glColor3f(.2f, .2f, .8f); // must set color before raster position (raster position is like glVertex)
gl.glRasterPos3f(0, statisticsDrawingPosition, 0);
String s = String.format("TPR=%6.1f%% TNR=%6.1f%% TPO=%6.1f%%, BR=%6.1f%% dT=%.2fus", 100 * TPR, 100 * TNR, 100 * TPO, 100 * BR, poissonDtUs);
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
gl.glRasterPos3f(0, statisticsDrawingPosition + 10, 0);
String s2 = String.format("In sigRate=%s noiseRate=%s, Out sigRate=%s noiseRate=%s Hz", eng.format(inSignalRateHz), eng.format(inNoiseRateHz), eng.format(outSignalRateHz), eng.format(outNoiseRateHz));
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s2);
gl.glPopMatrix();
}
private void annotateNoiseFilteringEvents(ArrayList<BasicEvent> outSig, ArrayList<BasicEvent> outNoise) {
if (renderer == null) {
return;
}
renderer.clearAnnotationMap();
final int offset = 1;
final float a = getAnnotateAlpha();
final float[] noiseColor = {1f, 0, 0, 1}, sigColor = {0, 1f, 0, 1};
for (BasicEvent e : outSig) {
renderer.setAnnotateColorRGBA(e.x + 2 >= sx ? e.x : e.x + offset, e.y - 2 < 0 ? e.y : e.y - offset, sigColor);
}
for (BasicEvent e : outNoise) {
renderer.setAnnotateColorRGBA(e.x + 2 >= sx ? e.x : e.x + offset, e.y - 2 < 0 ? e.y : e.y - offset, noiseColor);
// renderer.setAnnotateColorRGBA(e.x+2, e.y-2, noiseColor);
}
}
// final private class TimeStampComparator<E extends BasicEvent> implements Comparator<E> {
// // NOTE this hack so that sorted event EventSet does not lose elements with identical timestamps
// @Override
// public int compare(final E e1, final E e2) {
// int diff = e1.timestamp - e2.timestamp;
// return diff;
// private TimeStampComparator timestampComparator = new TimeStampComparator<BasicEvent>();
private ArrayList<BasicEvent> createEventList() {
return new ArrayList<BasicEvent>();
}
private class BackwardsTimestampException extends Exception {
public BackwardsTimestampException(String string) {
super(string);
}
}
private ArrayList<BasicEvent> createEventList(EventPacket<BasicEvent> p) throws BackwardsTimestampException {
ArrayList<BasicEvent> l = new ArrayList(p.getSize());
BasicEvent pe = null;
for (BasicEvent e : p) {
if (pe != null && (e.timestamp < pe.timestamp)) {
throw new BackwardsTimestampException(String.format("timestamp %d is earlier than previous %d", e.timestamp, pe.timestamp));
}
l.add(e);
pe = e;
}
return l;
}
private ArrayList<BasicEvent> createEventList(List<BasicEvent> p) throws BackwardsTimestampException {
ArrayList<BasicEvent> l = new ArrayList(p.size());
BasicEvent pe = null;
for (BasicEvent e : p) {
if (pe != null && (e.timestamp < pe.timestamp)) {
throw new BackwardsTimestampException(String.format("timestamp %d is earlier than previous %d", e.timestamp, pe.timestamp));
}
l.add(e);
pe = e;
}
return l;
}
/**
* Finds the intersection of events in a that are in b. Assumes packets are
* non-monotonic in timestamp ordering.
*
*
* @param a ArrayList<BasicEvent> of a
* @param b likewise
* @return ArrayList of intersection
*/
private ArrayList<BasicEvent> countIntersect(ArrayList<BasicEvent> a, ArrayList<BasicEvent> b) {
ArrayList<BasicEvent> intersect = new ArrayList(a.size() > b.size() ? a.size() : b.size());
int count = 0;
if (a.isEmpty() || b.isEmpty()) {
return new ArrayList();
}
// TODO test case
// a = new ArrayList();
// b = new ArrayList();
// a.add(new BasicEvent(4, (short) 0, (short) 0));
// a.add(new BasicEvent(4, (short) 0, (short) 0));
// a.add(new BasicEvent(4, (short) 1, (short) 0));
// a.add(new BasicEvent(4, (short) 2, (short) 0));
//// a.add(new BasicEvent(2, (short) 0, (short) 0));
//// a.add(new BasicEvent(10, (short) 0, (short) 0));
// b.add(new BasicEvent(2, (short) 0, (short) 0));
// b.add(new BasicEvent(2, (short) 0, (short) 0));
// b.add(new BasicEvent(4, (short) 0, (short) 0));
// b.add(new BasicEvent(4, (short) 0, (short) 0));
// b.add(new BasicEvent(4, (short) 1, (short) 0));
// b.add(new BasicEvent(10, (short) 0, (short) 0));
int i = 0, j = 0;
int na = a.size(), nb = b.size();
while (i < na && j < nb) {
if (a.get(i).timestamp < b.get(j).timestamp) {
i++;
} else if (b.get(j).timestamp < a.get(i).timestamp) {
j++;
} else {
// If timestamps equal, it mmight be identical events or maybe not
// and there might be several events with identical timestamps.
// We MUST match all a with all b.
// We don't want to increment both pointers or we can miss matches.
// We do an inner double loop for exhaustive matching as long as the timestamps
// are identical.
int i1 = i, j1 = j;
while (i1 < na && j1 < nb && a.get(i1).timestamp == b.get(j1).timestamp) {
boolean match = false;
while (j1 < nb && i1 < na && a.get(i1).timestamp == b.get(j1).timestamp) {
if (a.get(i1).equals(b.get(j1))) {
count++;
intersect.add(b.get(j1)); // TODO debug
// we have a match, so use up the a element
i1++;
match = true;
}
j1++;
}
if (!match) {
i1++;
}
j1 = j; // reset j to start of matching ts region
}
i = i1; // when done, timestamps are different or we reached end of either or both arrays
j = j1;
}
}
// System.out.println("%%%%%%%%%%%%%%");
// printarr(a, "a");
// printarr(b, "b");
// printarr(intersect, "intsct");
return intersect;
}
// TODO test case
private void printarr(ArrayList<BasicEvent> a, String n) {
final int MAX = 30;
if (a.size() > MAX) {
System.out.printf("
return;
}
System.out.printf("%s[%d]
for (int i = 0; i < a.size(); i++) {
BasicEvent e = a.get(i);
System.out.printf("%s[%d]=[%d %d %d %d]\n", n, i, e.timestamp, e.x, e.y, (e instanceof PolarityEvent) ? ((PolarityEvent) e).getPolaritySignum() : 0);
}
}
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
totalEventCount = 0; // from super, to measure filtering
filteredOutEventCount = 0;
int TP = 0; // filter take real events as real events. the number of events
int TN = 0; // filter take noise events as noise events
int FP = 0; // filter take noise events as real events
int FN = 0; // filter take real events as noise events
if (in == null || in.isEmpty()) {
log.warning("empty packet, cannot inject noise");
return in;
}
BasicEvent firstE = in.getFirstEvent();
if (firstSignalTimestmap == null) {
firstSignalTimestmap = firstE.timestamp;
}
if (resetCalled) {
resetCalled = false;
int ts = in.getLastTimestamp(); // we use getLastTimestamp because getFirstTimestamp contains event from BEFORE the rewind :-(
// initialize filters with lastTimesMap to Poisson waiting times
log.info("initializing timestamp maps with Poisson process waiting times");
for (AbstractNoiseFilter f : noiseFilters) {
int[][] map = f.getLastTimesMap();
if (map != null) {
initializeLastTimesMapForNoiseRate(map, shotNoiseRateHz + leakNoiseRateHz, ts);
}
}
}
// copy input events to inList
ArrayList<BasicEvent> signalList;
try {
signalList = createEventList((EventPacket<BasicEvent>) in);
} catch (BackwardsTimestampException ex) {
log.warning(String.format("%s: skipping nonmonotonic packet [%s]", ex, in));
return in;
}
assert signalList.size() == in.getSizeNotFilteredOut() : String.format("signalList size (%d) != in.getSizeNotFilteredOut() (%d)", signalList.size(), in.getSizeNotFilteredOut());
// add noise into signalList to get the outputPacketWithNoiseAdded, track noise in noiseList
ArrayList<BasicEvent> noiseList = createEventList(); //List.create(tim);
addNoise(in, signalAndNoisePacket, noiseList, shotNoiseRateHz, leakNoiseRateHz);
// we need to copy the augmented event packet to a HashSet for use with Collections
ArrayList<BasicEvent> signalAndNoiseList;
try {
signalAndNoiseList = createEventList((EventPacket<BasicEvent>) signalAndNoisePacket);
// filter the augmented packet
for (EventFilter2D f : getEnclosedFilterChain()) {
((AbstractNoiseFilter) f).setRecordFilteredOutEvents(true); // make sure to record events, turned off by default for normal use
}
EventPacket<BasicEvent> passedSignalAndNoisePacket = (EventPacket<BasicEvent>) getEnclosedFilterChain().filterPacket(signalAndNoisePacket);
ArrayList<BasicEvent> filteredOutList = selectedFilter.getFilteredOutEvents();
// make a list of the output packet, which has noise filtered out by selected filter
ArrayList<BasicEvent> passedSignalAndNoiseList = createEventList(passedSignalAndNoisePacket);
assert (signalList.size() + noiseList.size() == signalAndNoiseList.size());
// now we sort out the mess
tpList = countIntersect(signalList, passedSignalAndNoiseList); // True positives: Signal that was correctly retained by filtering
TP = tpList.size();
fnList = countIntersect(signalList, filteredOutList); // False negatives: Signal that was incorrectly removed by filter.
FN = fnList.size();
fpList = countIntersect(noiseList, passedSignalAndNoiseList); // False positives: Noise that is incorrectly passed by filter
FP = fpList.size();
tnList = countIntersect(noiseList, filteredOutList); // True negatives: Noise that was correctly removed by filter
TN = tnList.size();
// if (TN + FP != noiseList.size()) {
// System.err.println(String.format("TN (%d) + FP (%d) = %d != noiseList (%d)", TN, FP, TN + FP, noiseList.size()));
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
assert (TN + FP == noiseList.size()) : String.format("TN (%d) + FP (%d) = %d != noiseList (%d)", TN, FP, TN + FP, noiseList.size());
totalEventCount = signalAndNoiseList.size();
int outputEventCount = passedSignalAndNoiseList.size();
filteredOutEventCount = totalEventCount - outputEventCount;
// if (TP + FP != outputEventCount) {
// System.err.printf("@@@@@@@@@ TP (%d) + FP (%d) = %d != outputEventCount (%d)", TP, FP, TP + FP, outputEventCount);
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
assert TP + FP == outputEventCount : String.format("TP (%d) + FP (%d) = %d != outputEventCount (%d)", TP, FP, TP + FP, outputEventCount);
// if (TP + TN + FP + FN != totalEventCount) {
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
assert TP + TN + FP + FN == totalEventCount : String.format("TP (%d) + TN (%d) + FP (%d) + FN (%d) = %d != totalEventCount (%d)", TP, TN, FP, FN, TP + TN + FP + FN, totalEventCount);
assert TN + FN == filteredOutEventCount : String.format("TN (%d) + FN (%d) = %d != filteredOutEventCount (%d)", TN, FN, TN + FN, filteredOutEventCount);
// System.out.printf("every packet is: %d %d %d %d %d, %d %d %d: %d %d %d %d\n", inList.size(), newInList.size(), outList.size(), outRealList.size(), outNoiseList.size(), outInitList.size(), outInitRealList.size(), outInitNoiseList.size(), TP, TN, FP, FN);
TPR = TP + FN == 0 ? 0f : (float) (TP * 1.0 / (TP + FN)); // percentage of true positive events. that's output real events out of all real events
TPO = TP + FP == 0 ? 0f : (float) (TP * 1.0 / (TP + FP)); // percentage of real events in the filter's output
TNR = TN + FP == 0 ? 0f : (float) (TN * 1.0 / (TN + FP));
accuracy = (float) ((TP + TN) * 1.0 / (TP + TN + FP + FN));
BR = TPR + TPO == 0 ? 0f : (float) (2 * TPR * TPO / (TPR + TPO)); // wish to norm to 1. if both TPR and TPO is 1. the value is 1
// System.out.printf("shotNoiseRateHz and leakNoiseRateHz is %.2f and %.2f\n", shotNoiseRateHz, leakNoiseRateHz);
if (lastTimestampPreviousPacket != null) {
int deltaTime = in.getLastTimestamp() - lastTimestampPreviousPacket;
inSignalRateHz = (1e6f * in.getSize()) / deltaTime;
inNoiseRateHz = (1e6f * noiseList.size()) / deltaTime;
outSignalRateHz = (1e6f * TP) / deltaTime;
outNoiseRateHz = (1e6f * FP) / deltaTime;
}
if (csvWriter != null) {
try {
csvWriter.write(String.format("%d,%d,%d,%d,%f,%f,%f,%d,%f,%f,%f,%f\n",
TP, TN, FP, FN, TPR, TNR, BR, firstE.timestamp,
inSignalRateHz, inNoiseRateHz, outSignalRateHz, outNoiseRateHz));
} catch (IOException e) {
doCloseCsvFile();
}
}
if (overlayClassifications) {
if (overlayInput) {
annotateNoiseFilteringEvents(signalList, noiseList);
} else {
annotateNoiseFilteringEvents(tpList, fpList);
}
}
ROCSample p = new ROCSample(TPR, TNR, getCorrelationTimeS());
if (rocSampleCounter++ % ROC_LABEL_TAU_INTERVAL == 0) {
p.labeled = true; // only label every so many to avoid cluttering
}
rocHistoryList.add(p);
lastTimestampPreviousPacket = in.getLastTimestamp();
return passedSignalAndNoisePacket;
} catch (BackwardsTimestampException ex) {
Logger.getLogger(NoiseTesterFilter.class.getName()).log(Level.SEVERE, null, ex);
return in;
}
}
private void addNoise(EventPacket<? extends BasicEvent> in, EventPacket<? extends BasicEvent> augmentedPacket, List<BasicEvent> generatedNoise, float shotNoiseRateHz, float leakNoiseRateHz) {
// we need at least 1 event to be able to inject noise before it
if ((in.isEmpty())) {
log.warning("no input events in this packet, cannot inject noise because there is no end event");
return;
}
// save input packet
augmentedPacket.clear();
generatedNoise.clear();
// make the itertor to save events with added noise events
OutputEventIterator<ApsDvsEvent> outItr = (OutputEventIterator<ApsDvsEvent>) augmentedPacket.outputIterator();
if (prerecordedNoise == null && leakNoiseRateHz == 0 && shotNoiseRateHz == 0) {
for (BasicEvent ie : in) {
outItr.nextOutput().copyFrom(ie);
}
return; // no noise, just return which returns the copy from filterPacket
}
int firstTsThisPacket = in.getFirstTimestamp();
// insert noise between last event of last packet and first event of current packet
// but only if there waa a previous packet and we are monotonic
if (lastTimestampPreviousPacket != null) {
if (firstTsThisPacket < lastTimestampPreviousPacket) {
log.warning(String.format("non-monotonic timestamp: Resetting filter. (first event %d is smaller than previous event %d by %d)",
firstTsThisPacket, lastTimestampPreviousPacket, firstTsThisPacket - lastTimestampPreviousPacket));
resetFilter();
return;
}
// we had some previous event
int lastPacketTs = lastTimestampPreviousPacket + 1; // 1us more than timestamp of the last event in the last packet
insertNoiseEvents(lastPacketTs, firstTsThisPacket, outItr, generatedNoise);
}
// insert noise between events of this packet after the first event, record their timestamp
int preEts = 0;
int lastEventTs = in.getFirstTimestamp();
for (BasicEvent ie : in) {
// if it is the first event or any with first event timestamp then just copy them
if (ie.timestamp == firstTsThisPacket) {
outItr.nextOutput().copyFrom(ie);
continue;
}
// save the previous timestamp and get the next one, and then inject noise between them
preEts = lastEventTs;
lastEventTs = ie.timestamp;
insertNoiseEvents(preEts, lastEventTs, outItr, generatedNoise);
outItr.nextOutput().copyFrom(ie);
}
}
private void insertNoiseEvents(int lastPacketTs, int firstTsThisPacket, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> generatedNoise) {
for (double ts = lastPacketTs; ts < firstTsThisPacket; ts += poissonDtUs) {
// note that poissonDtUs is float but we truncate the actual timestamp to int us value here.
// It's OK if there are events with duplicate timestamps (there are plenty in input already).
sampleNoiseEvent((int) ts, outItr, generatedNoise, shotOffThresholdProb, shotOnThresholdProb, leakOnThresholdProb); // note noise injection updates ts to make sure monotonic
}
}
private int sampleNoiseEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> noiseList, float shotOffThresholdProb, float shotOnThresholdProb, float leakOnThresholdProb) {
if (prerecordedNoise == null) {
float randomnum = random.nextFloat();
if (randomnum < shotOffThresholdProb) {
injectOffEvent(ts, outItr, noiseList);
} else if (randomnum > shotOnThresholdProb) {
injectOnEvent(ts, outItr, noiseList);
}
if (random.nextFloat() < leakOnThresholdProb) {
injectOnEvent(ts, outItr, noiseList);
}
return ts;
} else {
BasicEvent e = prerecordedNoise.nextEventInRange(this.firstSignalTimestmap, ts, poissonDtUs);
if (e != null) {
PolarityEvent pe = (PolarityEvent) e;
if (pe.polarity == PolarityEvent.Polarity.On) {
injectOnEvent(ts, outItr, noiseList);
} else {
injectOffEvent(ts, outItr, noiseList);
}
}
return ts;
}
}
private void injectOnEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> noiseList) {
int x = (short) random.nextInt(sx);
int y = (short) random.nextInt(sy);
ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput();
e.setSpecial(false);
e.x = (short) (x);
e.y = (short) (y);
e.timestamp = ts;
e.polarity = PolarityEvent.Polarity.On;
noiseList.add(e);
}
private void injectOffEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> noiseList) {
int x = (short) random.nextInt(sx);
int y = (short) random.nextInt(sy);
ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput();
e.setSpecial(false);
e.x = (short) (x);
e.y = (short) (y);
e.timestamp = ts;
e.polarity = PolarityEvent.Polarity.Off;
noiseList.add(e);
}
@Override
synchronized public void resetFilter() {
lastTimestampPreviousPacket = null;
firstSignalTimestmap = null;
resetCalled = true;
getEnclosedFilterChain().reset();
if (prerecordedNoise != null) {
prerecordedNoise.rewind();
}
// rocHistoryList.clear(); // done by doClearROCHistory to preserve
}
private void computeProbs() {
// the rate per pixel results in overall noise rate for entire sensor that is product of pixel rate and number of pixels.
// we compute this overall noise rate to determine the Poisson sample interval that is much smaller than this to enable simple Poisson noise sampling.
// Compute time step that is 10X less than the overall mean interval for noise
// dt is the time interval such that if we sample a random value 0-1 every dt us, the the overall noise rate will be correct.
int npix = (chip.getSizeX() * chip.getSizeY());
float tmp = (float) (1.0 / ((leakNoiseRateHz + shotNoiseRateHz) * npix)); // this value is very small
poissonDtUs = ((tmp / 10) * 1000000); // 1s = 1000000 us // TODO document why 10 here. It is to ensure that prob(>1 event per sample is low)
final float minPoissonDtUs = 1f / (1e-6f * MAX_TOTAL_NOISE_RATE_HZ);
if (prerecordedNoise != null) {
log.info("Prerecoded noise input: clipping max noise rate to MAX_TOTAL_NOISE_RATE_HZ=" + eng.format(MAX_TOTAL_NOISE_RATE_HZ) + "Hz");
poissonDtUs = minPoissonDtUs;
} else if (poissonDtUs < minPoissonDtUs) {
log.info("clipping max noise rate to MAX_TOTAL_NOISE_RATE_HZ=" + eng.format(MAX_TOTAL_NOISE_RATE_HZ) + "Hz");
poissonDtUs = minPoissonDtUs;
} else // if (poissonDtUs < 1) {
// log.warning(String.format("Poisson sampling rate is less than 1us which is timestep resolution, could be slow"));
{
shotOffThresholdProb = 0.5f * (poissonDtUs * 1e-6f * npix) * shotNoiseRateHz; // bounds for samppling Poisson noise, factor 0.5 so total rate is shotNoiseRateHz
}
shotOnThresholdProb = 1 - shotOffThresholdProb; // for shot noise sample both sides, for leak events just generate ON events
leakOnThresholdProb = (poissonDtUs * 1e-6f * npix) * leakNoiseRateHz; // bounds for samppling Poisson noise
}
@Override
public void initFilter() {
chain = new FilterChain(chip);
noiseFilters = new AbstractNoiseFilter[]{new BackgroundActivityFilter(chip), new SpatioTemporalCorrelationFilter(chip), new SequenceBasedFilter(chip), new OrderNBackgroundActivityFilter((chip))};
for (AbstractNoiseFilter n : noiseFilters) {
n.initFilter();
chain.add(n);
}
setEnclosedFilterChain(chain);
sx = chip.getSizeX() - 1;
sy = chip.getSizeY() - 1;
signalAndNoisePacket = new EventPacket<>(ApsDvsEvent.class);
if (chip.getAeViewer() != null) {
chip.getAeViewer().getSupport().addPropertyChangeListener(AEInputStream.EVENT_REWOUND, this);
chip.getAeViewer().getSupport().addPropertyChangeListener(AEViewer.EVENT_CHIP, this);
}
setSelectedNoiseFilterEnum(selectedNoiseFilterEnum);
computeProbs();
if (chip.getRenderer() instanceof DavisRenderer) {
renderer = (DavisRenderer) chip.getRenderer();
}
setAnnotateAlpha(annotateAlpha);
setOverlayClassifications(overlayClassifications); // make sure renderer is properly set up.
setOverlayInput(overlayInput);
}
/**
* @return the shotNoiseRateHz
*/
public float getShotNoiseRateHz() {
return shotNoiseRateHz;
}
@Override
public int[][] getLastTimesMap() {
return null;
}
/**
* @param shotNoiseRateHz the shotNoiseRateHz to set
*/
synchronized public void setShotNoiseRateHz(float shotNoiseRateHz) {
if (shotNoiseRateHz < 0) {
shotNoiseRateHz = 0;
}
if (shotNoiseRateHz > RATE_LIMIT_HZ) {
log.warning("high leak rates will hang the filter and consume all memory");
shotNoiseRateHz = RATE_LIMIT_HZ;
}
putFloat("shotNoiseRateHz", shotNoiseRateHz);
getSupport().firePropertyChange("shotNoiseRateHz", this.shotNoiseRateHz, shotNoiseRateHz);
this.shotNoiseRateHz = shotNoiseRateHz;
computeProbs();
}
/**
* @return the leakNoiseRateHz
*/
public float getLeakNoiseRateHz() {
return leakNoiseRateHz;
}
/**
* @param leakNoiseRateHz the leakNoiseRateHz to set
*/
synchronized public void setLeakNoiseRateHz(float leakNoiseRateHz) {
if (leakNoiseRateHz < 0) {
leakNoiseRateHz = 0;
}
if (leakNoiseRateHz > RATE_LIMIT_HZ) {
log.warning("high leak rates will hang the filter and consume all memory");
leakNoiseRateHz = RATE_LIMIT_HZ;
}
putFloat("leakNoiseRateHz", leakNoiseRateHz);
getSupport().firePropertyChange("leakNoiseRateHz", this.leakNoiseRateHz, leakNoiseRateHz);
this.leakNoiseRateHz = leakNoiseRateHz;
computeProbs();
}
/**
* @return the csvFileName
*/
public String getCsvFilename() {
return csvFileName;
}
/**
* @param csvFileName the csvFileName to set
*/
public void setCsvFilename(String csvFileName) {
if (csvFileName.toLowerCase().endsWith(".csv")) {
csvFileName = csvFileName.substring(0, csvFileName.length() - 4);
}
putString("csvFileName", csvFileName);
getSupport().firePropertyChange("csvFileName", this.csvFileName, csvFileName);
this.csvFileName = csvFileName;
openCvsFiile();
}
public void doCloseCsvFile() {
if (csvFile != null) {
try {
log.info("closing statistics output file" + csvFile);
csvWriter.close();
} catch (IOException e) {
log.warning("could not close " + csvFile + ": caught " + e.toString());
} finally {
csvFile = null;
csvWriter = null;
}
}
}
private void openCvsFiile() {
String fn = csvFileName + ".csv";
csvFile = new File(fn);
log.info(String.format("opening %s for output", fn));
try {
csvWriter = new BufferedWriter(new FileWriter(csvFile, true));
if (!csvFile.exists()) { // write header
log.info("file did not exist, so writing header");
csvWriter.write(String.format("TP,TN,FP,FN,TPR,TNR,BR,firstE.timestamp,"
+ "inSignalRateHz,inNoiseRateHz,outSignalRateHz,outNoiseRateHz\n"));
}
} catch (IOException ex) {
log.warning(String.format("could not open %s for output; caught %s", fn, ex.toString()));
}
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
super.propertyChange(evt); //To change body of generated methods, choose Tools | Templates.
if (evt.getPropertyName() == AEInputStream.EVENT_REWOUND) {
log.info(String.format("got rewound event %s, setting reset on next packet flat", evt));
resetCalled = true;
}
}
/**
* @return the selectedNoiseFilter
*/
public NoiseFilterEnum getSelectedNoiseFilterEnum() {
return selectedNoiseFilterEnum;
}
/**
* @param selectedNoiseFilter the selectedNoiseFilter to set
*/
synchronized public void setSelectedNoiseFilterEnum(NoiseFilterEnum selectedNoiseFilter) {
this.selectedNoiseFilterEnum = selectedNoiseFilter;
putString("selectedNoiseFilter", selectedNoiseFilter.toString());
for (AbstractNoiseFilter n : noiseFilters) {
if (n.getClass().getSimpleName().equals(selectedNoiseFilter.toString())) {
n.initFilter();
n.setFilterEnabled(true);
selectedFilter = n;
} else {
n.setFilterEnabled(false);
}
}
resetCalled = true; // make sure we iniitialize the timestamp maps on next packet for new filter
}
private String USAGE = "Need at least 2 arguments: noisefilter <command> <args>\nCommands are: setNoiseFilterParameters <csvFilename> xx <shotNoiseRateHz> xx <leakNoiseRateHz> xx and specific to the filter\n";
@Override
public String processRemoteControlCommand(RemoteControlCommand command, String input) {
// parse command and set parameters of NoiseTesterFilter, and pass command to specific filter for further processing
// setNoiseFilterParameters csvFilename 10msBAFdot_500m_0m_300num0 shotNoiseRateHz 0.5 leakNoiseRateHz 0 dt 300 num 0
String[] tok = input.split("\\s");
if (tok.length < 2) {
return USAGE;
} else {
for (int i = 1; i < tok.length; i++) {
if (tok[i].equals("csvFileName")) {
setCsvFilename(tok[i + 1]);
} else if (tok[i].equals("shotNoiseRateHz")) {
setShotNoiseRateHz(Float.parseFloat(tok[i + 1]));
log.info(String.format("setShotNoiseRateHz %f", shotNoiseRateHz));
} else if (tok[i].equals("leakNoiseRateHz")) {
setLeakNoiseRateHz(Float.parseFloat(tok[i + 1]));
log.info(String.format("setLeakNoiseRateHz %f", leakNoiseRateHz));
}
}
log.info("Received Command:" + input);
String out = selectedFilter.setParameters(command, input);
log.info("Execute Command:" + input);
return out;
}
}
/**
* Fills lastTimesMap with waiting times drawn from Poisson process with
* rate noiseRateHz
*
* @param lastTimesMap map
* @param noiseRateHz rate in Hz
* @param lastTimestampUs the last timestamp; waiting times are created
* before this time
*/
protected void initializeLastTimesMapForNoiseRate(int[][] lastTimesMap, float noiseRateHz, int lastTimestampUs) {
for (final int[] arrayRow : lastTimesMap) {
for (int i = 0; i < arrayRow.length; i++) {
final float p = random.nextFloat();
final double t = -noiseRateHz * Math.log(1 - p);
final int tUs = (int) (1000000 * t);
arrayRow[i] = lastTimestampUs - tUs;
}
}
}
@Override
public float getCorrelationTimeS() {
return this.correlationTimeS;
}
@Override
public void setCorrelationTimeS(float dtS) {
if (dtS > 1e-6f * MAX_DT) {
dtS = 1e-6f * MAX_DT;
} else if (dtS < 1e-6f * MIN_DT) {
dtS = 1e-6f * MIN_DT;
}
this.correlationTimeS = dtS;
for (AbstractNoiseFilter f : noiseFilters) {
f.setCorrelationTimeS(dtS);
}
putFloat("correlationTimeS", this.correlationTimeS);
}
/**
* @return the annotateAlpha
*/
public float getAnnotateAlpha() {
return annotateAlpha;
}
/**
* @param annotateAlpha the annotateAlpha to set
*/
public void setAnnotateAlpha(float annotateAlpha) {
if (annotateAlpha > 1.0) {
annotateAlpha = 1.0f;
}
if (annotateAlpha < 0.0) {
annotateAlpha = 0.0f;
}
this.annotateAlpha = annotateAlpha;
if (renderer != null) {
renderer.setAnnotateAlpha(annotateAlpha);
}
}
/**
* @return the overlayClassifications
*/
public boolean isOverlayClassifications() {
return overlayClassifications;
}
/**
* @param overlayClassifications the overlayClassifications to set
*/
public void setOverlayClassifications(boolean overlayClassifications) {
this.overlayClassifications = overlayClassifications;
putBoolean("overlayClassifications", overlayClassifications);
if (renderer != null) {
renderer.setDisplayAnnotation(overlayClassifications);
}
}
/**
* @return the overlayInput
*/
public boolean isOverlayInput() {
return overlayInput;
}
/**
* @param overlayInput the overlayInput to set
*/
public void setOverlayInput(boolean overlayInput) {
this.overlayInput = overlayInput;
putBoolean("overlayInput", overlayInput);
}
/**
* @return the rocHistory
*/
public int getRocHistory() {
return rocHistory;
}
/**
* @param rocHistory the rocHistory to set
*/
synchronized public void setRocHistory(int rocHistory) {
if (rocHistory > 10000) {
rocHistory = 10000;
}
this.rocHistory = rocHistory;
putInt("rocHistory", rocHistory);
rocHistoryList = EvictingQueue.create(rocHistory);
}
synchronized public void doClearROCHistory() {
rocHistoryList.clear();
}
synchronized public void doCloseNoiseSourceRecording() {
if (prerecordedNoise != null) {
log.info("clearing recoerded noise input data");
prerecordedNoise = null;
}
}
synchronized public void doOpenNoiseSourceRecording() {
JFileChooser fileChooser = new JFileChooser();
ChipDataFilePreview preview = new ChipDataFilePreview(fileChooser, getChip());
// from book swing hacks
fileChooser.addPropertyChangeListener(preview);
fileChooser.setAccessory(preview);
String chosenPrerecordedNoiseFilePath = getString("chosenPrerecordedNoiseFilePath", "");
// get the last folder
DATFileFilter datFileFilter = new DATFileFilter();
fileChooser.addChoosableFileFilter(datFileFilter);
fileChooser.setCurrentDirectory(new File(chosenPrerecordedNoiseFilePath));
// sets the working directory of the chooser
// boolean wasPaused=isPaused();
try {
int retValue = fileChooser.showOpenDialog(getChip().getAeViewer().getFilterFrame());
if (retValue == JFileChooser.APPROVE_OPTION) {
chosenPrerecordedNoiseFilePath = fileChooser.getSelectedFile().toString();
putString("chosenPrerecordedNoiseFilePath", chosenPrerecordedNoiseFilePath);
try {
prerecordedNoise = new PrerecordedNoise(fileChooser.getSelectedFile());
computeProbs(); // set poissonDtUs after we construct prerecordedNoise so it is set properly
} catch (IOException ex) {
log.warning(String.format("Exception trying to open data file: " + ex));
}
} else {
preview.showFile(null);
}
} catch (GLException e) {
log.warning(e.toString());
preview.showFile(null);
}
}
}
|
package org.appwork.app.gui.copycutpaste;
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.MouseEvent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPopupMenu;
import javax.swing.MenuSelectionManager;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;
public class CopyCutPasteHandler extends EventQueue {
private static final CopyCutPasteHandler INSTANCE = new CopyCutPasteHandler();
public static CopyCutPasteHandler getInstance() {
return INSTANCE;
}
private long startupTime = System.currentTimeMillis();
public long getStartupTime() {
return startupTime;
}
private long lastMouseEvent = -1;
public long getLastMouseEvent() {
return lastMouseEvent;
}
private CopyCutPasteHandler() {
super();
}
@Override
protected void dispatchEvent(AWTEvent event) {
super.dispatchEvent(event);
if (!(event instanceof MouseEvent)) return;
lastMouseEvent = System.currentTimeMillis();
MouseEvent mouseEvent = (MouseEvent) event;
if (!mouseEvent.isPopupTrigger() && mouseEvent.getButton() != MouseEvent.BUTTON3) return;
if (mouseEvent.getComponent() == null) return;
// get deepest component
// Component c = null;
Point point = mouseEvent.getPoint();
Component c;
if (mouseEvent.getSource() instanceof JDialog) {
c = SwingUtilities.getDeepestComponentAt((JDialog) mouseEvent.getSource(), (int) point.getX(), (int) point.getY());
} else if (mouseEvent.getSource() instanceof JFrame) {
Component source = ((JFrame) mouseEvent.getSource()).getContentPane();
point.x -= (source.getLocationOnScreen().x - ((JFrame) mouseEvent.getSource()).getLocationOnScreen().x);
point.y -= (source.getLocationOnScreen().y - ((JFrame) mouseEvent.getSource()).getLocationOnScreen().y);
c = SwingUtilities.getDeepestComponentAt(source, (int) point.getX(), (int) point.getY());
} else {
return;
}
// Check if deepest component is a textcomponent
if (!(c instanceof JTextComponent) && !(c instanceof ContextMenuAdapter)) return;
if (MenuSelectionManager.defaultManager().getSelectedPath().length > 0) return;
JPopupMenu menu;
final JTextComponent t = (JTextComponent) c;
if (c instanceof ContextMenuAdapter) {
menu = ((ContextMenuAdapter) c).getPopupMenu(new CutAction(t), new CopyAction(t), new PasteAction(t), new DeleteAction(t), new SelectAction(t));
if (menu == null) return;
} else {
// create menu
menu = new JPopupMenu();
menu.add(new CutAction(t));
menu.add(new CopyAction(t));
menu.add(new PasteAction(t));
menu.add(new DeleteAction(t));
menu.add(new SelectAction(t));
}
Point pt = SwingUtilities.convertPoint(mouseEvent.getComponent(), mouseEvent.getPoint(), c);
menu.show(c, pt.x, pt.y);
}
}
|
package net.sf.jaer.eventprocessing.tracking;
//import ch.unizh.ini.caviar.aemonitor.AEConstants;
import net.sf.jaer.chip.*;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.event.*;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.graphics.*;
import java.awt.*;
//import ch.unizh.ini.caviar.util.PreferencesEditor;
import java.awt.geom.*;
import java.io.*;
import java.util.*;
import java.util.prefs.*;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import net.sf.jaer.util.TobiLogger;
/**
* Tracks particles using a particle filter.
*
* @author Philipp <hafliger@ifi.uio.no>
*/
public class ParticleTracker extends EventFilter2D implements FrameAnnotater,Observer{
public static String getDescription (){
return "Tracks multiple objects using a particle filter approach.";
}
private java.util.List<Cluster> clusters = new LinkedList<Cluster>();
private int[][] lastCluster = new int[ 128 ][ 128 ];
private int[][] lastEvent = new int[ 128 ][ 128 ];
private int next_cluster_id = 1;
protected Random random = new Random();
private PrintStream logStream = null;
//Variables that will be set by the tracker parameter pop-up window:
//private final int CLUSTER_UNSUPPORTED_LIFETIME=50000;
int surround = 2;//neighbourhood that is searched for recent events that are considered to belong to the same cluster
int clusterUnsupportedLifetime = getPrefs().getInt("ParticleTracker.clusterUnsupportedLifetime",50000);
//private final int CLUSTER_MINLIFEFORCE_4_DISPLAY=10;
float clusterMinMass4Display = getPrefs().getFloat("ParticleTracker.clusterMinMass4Display",10);
boolean onPolarityOnly = getPrefs().getBoolean("ParticleTracker.onPolarityOnly",false);
float displayVelocityScaling = getPrefs().getFloat("ParticleTracker.DisplayVelocityScaling",1000.0f);
int logFrameIntervalUs = getPrefs().getInt("Particletracker.logFrameIntervalUs",0);
int logFrameNumber = 0;
private int maxClusters = getPrefs().getInt("Particletracker.maxClusters",9);
protected boolean logDataEnabled = false;
/** Creates a new instance of ParticleTracker */
public ParticleTracker (AEChip chip){
super(chip);
this.chip = chip;
chip.addObserver(this);
initFilter();
setPropertyTooltip("maxClusters","max number of clusters");
setPropertyTooltip("clusterMinMass4Display","minimum mass of cluster for display or logging");
setPropertyTooltip("logFrameIntervalUs","Interval in us for logging data to file about clusters");
setPropertyTooltip("displayVelocityScaling","velocity vector scaling of velocity in pixels/timestamp tick");
setPropertyTooltip("onPolarityOnly","use ON polarity events only");
setPropertyTooltip("clusterUnsupportedLifetime","prune clusters that don't get events for this long in ticks; also time constant of effect of event - decrease to move clusters more rapidly to new events");
setPropertyTooltip("logDataEnabled","enable to open log file for clusters; logging interval set by logFrameIntervalUs");
}
// All callback functions for the tracker parameter pop-up:
public void setDisplayVelocityScaling (float x){
this.displayVelocityScaling = x;
getPrefs().putFloat("ParticleTracker.displayVelocityScaling",displayVelocityScaling);
}
public final float getDisplayVelocityScaling (){
return ( displayVelocityScaling );
}
public void setLogFrameIntervalUs (int x){
// if ( x > 0 ){
// openLog();
// } else{
// closeLog();
this.logFrameIntervalUs = x;
getPrefs().putInt("ParticleTracker.logFrameIntervalUs",logFrameIntervalUs);
}
public final int getLogFrameIntervalUs (){
return ( logFrameIntervalUs );
}
public void setClusterUnsupportedLifetime (int x){
this.clusterUnsupportedLifetime = x;
getPrefs().putInt("ParticleTracker.clusterUnsupportedLifetime",clusterUnsupportedLifetime);
}
public final int getClusterUnsupportedLifetime (){
return ( clusterUnsupportedLifetime );
}
public void setOnPolarityOnly (boolean b){
this.onPolarityOnly = b;
getPrefs().putBoolean("ParticleTracker.onPolarityOnly",onPolarityOnly);
}
public final boolean isOnPolarityOnly (){
return ( onPolarityOnly );
}
public void setClusterMinMass4Display (float x){
this.clusterMinMass4Display = x;
getPrefs().putFloat("ParticleTracker.clusterMinMass4Display",clusterMinMass4Display);
}
public final float getClusterMinMass4Display (){
return ( clusterMinMass4Display );
}
@Override
synchronized public void setFilterEnabled (boolean enabled){
super.setFilterEnabled(enabled);
initFilter();
if ( !enabled ){
closeLog();
}
}
// all default values for the tracker parameter pop-up
private void initDefaults (){
initDefault("ParticleTracker.clusterUnsupportedLifetime","50000");
initDefault("ParticleTracker.ParticleTracker.clusterMinMass4Display","10");
initDefault("ParticleTracker.displayVelocityScaling","1000.0f");
initDefault("ParticleTracker.OnPolarityOnly","false");
initDefault("ParticleTracker.LogFrameRate","0");
}
private void initDefault (String key,String value){
if ( getPrefs().get(key,null) == null ){
getPrefs().put(key,value);
}
}
private void closeLog (){
if ( logStream != null ){
log.info("closing data logging file");
logStream.println("otherwise");
logStream.println("particles=[];");
//logStream.println("cla;");
//logStream.println("set(gca,'xlim',xlim,'ylim',ylim)");
logStream.println("end; %switch");
logStream.flush();
logStream.close();
logStream = null;
}
}
private void openLog (){
if ( logStream == null ){
log.info("creating data logging file ParticleTrackerLog.m");
try{
logStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("ParticleTrackerLog.m"))));
//logStream.println("function [particles]=ParticleTrackerLog(frameN,time_shift,xshift,yshift,xscaling,yscaling,xlim,ylim)");
logStream.println("function [particles]=ParticleTrackerLog(frameN)");
logStream.println("% lasttimestamp x y u v");
//logStream.println("switch (frameN+time_shift)");
logStream.println("switch (frameN)");
} catch ( Exception e ){
e.printStackTrace();
}
}
}
private void printClusterLog (PrintStream log,LinkedList<Cluster> cl,int frameNumber,int now){
ListIterator listScanner = cl.listIterator();
Cluster c = null;
int time_limit;
if ( logStream == null ){
openLog();
}
time_limit = now - clusterUnsupportedLifetime;
logStream.println(String.format("case %d",frameNumber));
logStream.println(String.format("particles=["));
while ( listScanner.hasNext() ){
c = (Cluster)listScanner.next();
if ( ( c.last < time_limit ) || ( c.last > now ) ){ //check if cluster is dead or if time has moved backwards
listScanner.remove();
} else{
if ( ( c.mass * weighEvent((float)c.last,(float)now) ) > clusterMinMass4Display ){
logStream.println(String.format("%d %e %e %e %e",c.last,c.location.x,c.location.y,c.velocity.x,c.velocity.y));
}
}
}
logStream.println("];");
//logStream.println("if (~isempty(particles))");
//logStream.println("plot(xscaling*particles(:,2)-xshift,yscaling*particles(:,3)-yshift,'o')");
//logStream.println("set(gca,'xlim',xlim,'ylim',ylim)");
//logStream.println("end; %if");
}
public float weighEvent (float t_ev,float now){
float result;
result = (float)Math.exp(-( now - t_ev ) / (float)clusterUnsupportedLifetime);
//result=1f-(now-t_ev)/(float)clusterUnsupportedLifetime;
return ( result );
}
// the method that actually does the tracking
synchronized private void track (EventPacket<BasicEvent> ae){
int n = ae.getSize();
//int surround=2;
if ( n == 0 ){
return;
}
int l, k, i, ir, il, j, jr, jl;
//int most_recent;
//LinkedList<Cluster> pruneList=new LinkedList<Cluster>();
int[] cluster_ids = new int[ maxClusters ];
Cluster thisCluster = null;
ListIterator listScanner;
Cluster c = null;
int sx = chip.getSizeX() - 1, sy = chip.getSizeY() - 1;
//int maxNumClusters=getMaxNumClusters();
// for each event, see which cluster it is closest to and add it to this cluster.
// if its too far from any cluster, make a new cluster if we can
// for(int i=0;i<n;i++){
for ( BasicEvent ev:ae ){
// check for if off-polarity is to be ignored
if ( !( onPolarityOnly && ( ev instanceof TypedEvent ) && ( ( (TypedEvent)ev ).type == 0 ) ) ){
if ( logDataEnabled && logFrameIntervalUs > 0 ){
if ( ( ev.timestamp / logFrameIntervalUs ) > logFrameNumber ){
logFrameNumber = ev.timestamp / logFrameIntervalUs;
printClusterLog(logStream,(LinkedList<Cluster>)clusters,logFrameNumber,ev.timestamp);
}
}
// check if any neigbours are assigned to a cluster already
il = -surround;
if ( ( ev.x + il ) < 0 ){
il = il - ( ev.x + il );
}
ir = surround;
if ( ( ev.x + ir ) > sx ){
ir = ir - ( ev.x + ir - sx );
}
jl = -surround;
if ( ( ev.y + jl ) < 0 ){
jl = jl - ( ev.y + jl );
}
jr = surround;
if ( ( ev.y + jr ) > sy ){
jr = jr - ( ev.y + jr - sy );
}
//if (ev.x==0){il=0;}else{il=-1;}
//if (ev.x==sx){ir=0;}else{ir=1;}
//if (ev.y==0){jl=0;}else{jl=-1;}
//if (ev.y==sy){jr=0;}else{jr=1;}
//most_recent=-1;
k = 0;
search:
for ( i = il ; i <= ir ; i++ ){
for ( j = jl ; j <= jr ; j++ ){
if ( lastEvent[ev.x + i][ev.y + j] != -1 ){
//if (lastEvent[ev.x+i][ev.y+j]>most_recent){
//most_recent=lastEvent[ev.x+i][ev.y+j];
//lastCluster[ev.x][ev.y]=lastCluster[ev.x+i][ev.y+j];
if ( lastEvent[ev.x + i][ev.y + j] >= ev.timestamp - clusterUnsupportedLifetime ){
lastCluster[ev.x][ev.y] = lastCluster[ev.x + i][ev.y + j];
cluster_ids[k] = lastCluster[ev.x + i][ev.y + j]; // an existing cluster id at or around the event
k++;
if ( k >= maxClusters ){
break search;
}
for ( l = 0 ; l < ( k - 1 ) ; l++ ){ // checking if its a doublicate
if ( cluster_ids[k - 1] == cluster_ids[l] ){
k
break;
}
}
}
}
}
}
lastEvent[ev.x][ev.y] = ev.timestamp;
if ( k == 0 ){// new cluster
//if (next_cluster_id<200){
lastCluster[ev.x][ev.y] = next_cluster_id;
thisCluster = new Cluster(ev.x,ev.y,ev.timestamp);
clusters.add(thisCluster);
} else{// existing cluster: new event of one or several existing cluster
listScanner = clusters.listIterator();
while ( listScanner.hasNext() ){ // add new event to cluster
c = (Cluster)listScanner.next();
if ( ( c.last < ev.timestamp - clusterUnsupportedLifetime ) || ( c.last > ev.timestamp ) ){ //check if cluster is dead or if time has moved backwards
listScanner.remove();
} else{ //if cluster is still alive
for ( l = 0 ; l < c.id.length ; l++ ){
if ( c.id[l] == lastCluster[ev.x][ev.y] ){// check if this event belongs to this cluster
c.addEvent(ev);
thisCluster = c;
//break;
}
}
}
}
if ( k > 1 ){ //merge clusters if there has been more alive clusters in neighbourhood
if ( thisCluster == null ){
log.warning("null thisCluster before mergeClusters");
} else{
mergeClusters(thisCluster,cluster_ids,k,ev.timestamp);
}
}
//clusters.removeAll(pruneList);
//pruneList.clear();
}
}
}
}
public int mergeClusters (Cluster thisCluster,int[] cluster_ids,int n_ids,int now){
ListIterator listScanner;
Cluster c = null;
int i, j, l;
int c_count = 1;
int[] merged_ids;
float thisClusterWeight, thatClusterWeight;
if ( thisCluster != null ){
listScanner = clusters.listIterator();
while ( listScanner.hasNext() ){ // look for the clusters to be merged
c = (Cluster)listScanner.next();
if ( c != thisCluster ){
for ( i = 0 ; i < c.id.length ; i++ ){
for ( j = 0 ; j < n_ids ; j++ ){
if ( c.id[i] == cluster_ids[j] ){
c_count++;
merged_ids = new int[ c.id.length + thisCluster.id.length ];
for ( l = 0 ; l < thisCluster.id.length ; l++ ){
merged_ids[l] = thisCluster.id[l];
}
for ( l = 0 ; l < ( c.id.length ) ; l++ ){
merged_ids[l + thisCluster.id.length] = c.id[l];
}
//for (l=0;l<(c.id.length+ thisCluster.id.length);l++){
//System.out.print(" "+merged_ids[l]);
//System.out.println();
thisCluster.id = merged_ids;
c.mass = c.mass * weighEvent((float)c.last,(float)now);
c.lifeForce = c.lifeForce * (float)Math.exp(-(float)( now - c.last ) / clusterUnsupportedLifetime);
thisClusterWeight = thisCluster.mass / ( thisCluster.mass + c.mass );
thatClusterWeight = 1 - thisClusterWeight;
thisCluster.location.x = thisClusterWeight * thisCluster.location.x + thatClusterWeight * c.location.x;
thisCluster.location.y = thisClusterWeight * thisCluster.location.y + thatClusterWeight * c.location.y;
thisCluster.velocity.x = thisClusterWeight * thisCluster.velocity.x + thatClusterWeight * c.velocity.x;
thisCluster.velocity.y = thisClusterWeight * thisCluster.velocity.y + thatClusterWeight * c.velocity.y;
if ( thisCluster.mass < c.mass ){
thisCluster.color = c.color;
}
thisCluster.mass = thisCluster.mass + c.mass;
thisCluster.lifeForce = thisCluster.lifeForce + c.lifeForce;
j = n_ids;
i = c.id.length;
listScanner.remove();
}
}
}
}
}
} else{
log.warning("null thisCluster in ParticleTracker.mergeClusters");
}
return ( c_count );
}
/**
* @return the maxClusters
*/
public int getMaxClusters (){
return maxClusters;
}
/**
* @param maxClusters the maxClusters to set
*/
public void setMaxClusters (int maxClusters){
this.maxClusters = maxClusters;
getPrefs().putInt("ParticleTracker.maxClusters",maxClusters);
}
public class DiffusedCluster{
int t;
Point2D.Float location = new Point2D.Float();
int n = 0;
float mass = 0;
public DiffusedCluster (){
}
public DiffusedCluster (int x,int y,int ti){
t = ti;
location.x = x;
location.y = y;
n = 0;
mass = 0;
}
}
public DiffusedCluster diffuseCluster (int x,int y,int id,int time_limit,int lowest_id,DiffusedCluster c){
int i, j, t, most_recent;
float new_event_weight;
//int surround=2;
if ( ( x >= 0 ) && ( x < 128 ) && ( y >= 0 ) && ( y < 128 ) && ( lastCluster[x][y] < lowest_id ) && ( lastEvent[x][y] >= time_limit ) ){
if ( c == null ){
c = new DiffusedCluster(0,0,lastEvent[x][y]);
}
lastCluster[x][y] = id;
c.n++;
//new_event_weight = (float)Math.exp( ((float)(lastEvent[x][y]-time_limit)) / (float)clusterUnsupportedLifetime - 1f);
new_event_weight = weighEvent((float)lastEvent[x][y],(float)( time_limit + clusterUnsupportedLifetime ));
c.location.x = ( c.location.x * c.mass + x * new_event_weight ) / ( c.mass + new_event_weight );
c.location.y = ( c.location.y * c.mass + y * new_event_weight ) / ( c.mass + new_event_weight );
c.mass = c.mass + new_event_weight;
if ( c.t < lastEvent[x][y] ){
c.t = lastEvent[x][y];
}
for ( i = -surround ; i <= surround ; i++ ){
for ( j = -surround ; j <= surround ; j++ ){
c = diffuseCluster(x + i,y + j,id,time_limit,lowest_id,c);
}
}
}
return ( c );
}
public int splitClusters (){
int split_count = 0;
float max_new_mass = 0f;
int local_split_count = 0;
ListIterator clusterScanner, old_new_id_scanner;
Cluster c, new_c;
int now = -1;
int new_clusters_from;
DiffusedCluster dc = null;
int x, y, time_limit, i/*,new_id*/, old_id;
float first_x = 0;
float first_y = 0;
//int[] old_cluster_id = new int[1];
int[] old_ids;
//int[] new_ids;
class OldNewId{
int o;
int n;
DiffusedCluster c; //last event timestamp in this cluster, estimated location and mass
}
java.util.List<OldNewId> old_new_id_list = new java.util.LinkedList<OldNewId>();
OldNewId old_new_id;
int this_pixel_old_id;
boolean position_correction_necessary = false;
float old_mass;
clusterScanner = clusters.listIterator();
while ( clusterScanner.hasNext() ){ // check for the most recent event timestamp
c = (Cluster)clusterScanner.next();
if ( c.last > now ){
now = c.last;
}
}
time_limit = now - clusterUnsupportedLifetime;
if ( time_limit < 0 ){
time_limit = 0;
}
new_clusters_from = next_cluster_id;
// the next foor loop builds up a list of clusters based on all connected alive events in the pixels
// and assignes new cluster ids in the lastCluster array. This new id, the old id and the cluster are stored ina temporary list
for ( x = 0 ; x < 128 ; x++ ){
for ( y = 0 ; y < 128 ; y++ ){
this_pixel_old_id = lastCluster[x][y];
try{
dc = diffuseCluster(x,y,next_cluster_id,time_limit,new_clusters_from,null);
} catch ( java.lang.StackOverflowError e ){
log.warning(e.getMessage());
log.warning("Probably a stack overflow: resetting ParticleTracker");
dc = null;
initFilter();
}
if ( dc != null ){
//dc.mass = dc.mass * (float)Math.exp((float)(now-dc.t)/clusterUnsupportedLifetime);
// the above is not necessary since already right from the difuseCluster function
old_new_id = new OldNewId();
old_new_id.o = this_pixel_old_id;
old_new_id.n = next_cluster_id;
old_new_id.c = dc;
old_new_id_list.add(old_new_id);
next_cluster_id++;
} else{
//lastCluster[x][y]=-1;
}
}
}
clusterScanner = clusters.listIterator();
while ( clusterScanner.hasNext() ){ // get all old clusters, assign new ids and split if necessary
c = (Cluster)clusterScanner.next();
if ( ( c.last < time_limit ) || ( c.last > now ) ){ //check if cluster is dead or if time has moved backwards
clusterScanner.remove();
} else{
old_mass = c.mass;
old_ids = c.id;
max_new_mass = 0;
local_split_count = 0;
//new_id=new_clusters_from;
first_x = -1; // dummy initialization : this variable should always be initialized in if (local_split_count >0){}else{...}
first_y = -1;
old_new_id_scanner = old_new_id_list.listIterator();
while ( old_new_id_scanner.hasNext() ){ // checking for all new clusters if they have been part of this old cluster
old_new_id = (OldNewId)old_new_id_scanner.next();
for ( i = 0 ; i < old_ids.length ; i++ ){
if ( old_ids[i] == old_new_id.o ){
//position_correction_necessary=
//(old_mass > 1000*old_new_id.c.mass);
// //((Math.abs(old_new_id.c.location.x-c.location.x) > 10)||
// //(Math.abs(old_new_id.c.location.y-c.location.y)>10 ));
if ( local_split_count > 0 ){// cluster has been split
new_c = new Cluster(old_new_id.n,c.location.x,c.location.y,c.velocity.x,c.velocity.y,old_new_id.c.t);
if ( old_new_id.c.mass > max_new_mass ){
max_new_mass = old_new_id.c.mass;
c.mass = 0f;
new_c.mass = old_mass;
} else{
new_c.mass = 0f;
}
//new_c.mass = old_new_id.c.mass; // not so good this, since various events in the same pixel can have contributed
new_c.color = c.color;
clusterScanner.add(new_c);
} else{ // found first old cluster and assigning the new id
max_new_mass = old_new_id.c.mass;
c.id = new int[ 1 ];
c.id[0] = old_new_id.n;
c.last = old_new_id.c.t;
new_c = c;
}
//if (position_correction_necessary){
// //System.out.println("correcting position"
// // +" "+(old_new_id.c.location.x-new_c.location.x)
// // +" "+(old_new_id.c.location.y-new_c.location.y)
// // +" "+(old_mass)
// // +" "+(old_new_id.c.mass)
//new_c.location.x= old_new_id.c.location.x;
//new_c.location.y= old_new_id.c.location.y;
//new_c.mass=0;
local_split_count++;
}
}
}
if ( local_split_count < 1 ){
log.warning("could not associate an existing cluster with one of the still valid diffused clusters");
clusterScanner.remove();
}
split_count += ( local_split_count - 1 );
}
}
return ( split_count );
}
public class Cluster{
public Point2D.Float location = new Point2D.Float(); // location in chip pixels
public Point2D.Float lastPixel = new Point2D.Float(); // location of last active pixel belonging to cluster
/** velocity of cluster in pixels/tick, where tick is timestamp tick (usually microseconds) */
public Point2D.Float velocity = new Point2D.Float(); // velocity in chip pixels/sec
//protected float distanceToLastEvent=Float.POSITIVE_INFINITY;
public int[] id = null;
int last = -1;
public float mass = (float)0;
public float lifeForce = 0f;
public Color color = null;
public boolean em = false; //emphazise when drawing;
// public Cluster(){
// location.x=(float)20.5;
// location.y=(float)10.9;
// id=-1;
public Cluster (float x,float y,int first_event_time){
location.x = x;
location.y = y;
lastPixel.x = x;
lastPixel.y = y;
id = new int[ 1 ];
id[0] = next_cluster_id++;
last = first_event_time;
velocity.x = (float)0.0;
velocity.y = (float)0.0;
lifeForce = 1;
mass = 1;
//float hue=random.nextFloat();
color = Color.getHSBColor(random.nextFloat(),1f,1f);
}
public Cluster (int identity,float x,float y,float vx,float vy,int first_event_time){
location.x = x;
location.y = y;
id = new int[ 1 ];
id[0] = identity;
last = first_event_time;
velocity.x = vx;
velocity.y = vy;
lifeForce = 1;
mass = 1;
//float hue=random.nextFloat();
color = Color.getHSBColor(random.nextFloat(),1f,1f);
}
public void addEvent (BasicEvent ev){
int interval;
interval = ev.timestamp - this.last;
if ( interval == 0 ){
interval = 1;
}
this.last = ev.timestamp;
this.lastPixel.x = ev.x;
this.lastPixel.y = ev.y;
this.lifeForce = this.lifeForce * (float)Math.exp(-(float)interval / clusterUnsupportedLifetime) + 1;
//this.mass= this.mass * (float)Math.exp(-(float)interval/clusterUnsupportedLifetime) +1;
this.mass = this.mass * weighEvent(this.last - interval,this.last) + 1;
//float event_weight=(float)interval/clusterUnsupportedLifetime;
//if (event_weight>1) event_weight=1;
//float event_weight=(float)1/(this.mass);
float predicted_x = this.location.x + this.velocity.x * ( interval );
float predicted_y = this.location.y + this.velocity.y * ( interval );
//float new_x=(1-event_weight)*predicted_x + event_weight*ev.x ;
//float new_x=(1-1/(this.mass))*predicted_x + 1/(this.mass)*ev.x ;
float new_x = ( 1 - 1 / ( this.mass ) ) * this.location.x + 1 / ( this.mass ) * ev.x;
//float new_y=(1-event_weight)*predicted_y + event_weight*ev.y ;
//float new_y=(1-1/(this.mass))*predicted_y + 1/(this.mass)*ev.y ;
float new_y = ( 1 - 1 / ( this.mass ) ) * this.location.y + 1 / ( this.mass ) * ev.y;
//this.velocity.x= (1-event_weight)*this.velocity.x + event_weight*(new_x - this.location.x)/interval;
this.velocity.x = ( 1 - 1 / ( this.mass ) ) * this.velocity.x + 1 / ( this.mass ) * ( new_x - this.location.x ) / (float)interval;
//this.velocity.x= (new_x - this.location.x)/interval;
//this.velocity.y= (1-event_weight)*this.velocity.y + event_weight*(new_y - this.location.y)/interval;
this.velocity.y = ( 1 - 1 / ( this.mass ) ) * this.velocity.y + 1 / ( this.mass ) * ( new_y - this.location.y ) / (float)interval;
//this.velocity.y= (new_y - this.location.y)/interval;
this.location.x = new_x;
this.location.y = new_y;
}
public Point2D.Float getLocation (){
return location;
}
public void setLocation (Point2D.Float l){
this.location = l;
}
}
public java.util.List<ParticleTracker.Cluster> getClusters (){
return this.clusters;
}
// private LinkedList<ParticleTracker.Cluster> getPruneList(){
// return this.pruneList;
private final void drawCluster (final Cluster c,float[][][] fr){
int x = (int)c.getLocation().x;
int y = (int)c.getLocation().y;
int i;
if ( y < 0 || y > fr.length - 1 || x < 0 || x > fr[0].length - 1 ){
return;
}
// for (x=20;x<(fr[0].length-20);x++){
// for(y=20;y<(fr[1].length-20);y++){
fr[x][y][0] = (float)0.2;
fr[x][y][1] = (float)1.0;
fr[x][y][2] = (float)1.0;
}
public void initFilter (){
initDefaults();
resetFilter();
// defaultClusterRadius=(int)Math.max(chip.getSizeX(),chip.getSizeY())*getClusterSize();
if ( logDataEnabled && ( logStream == null ) ){
openLog();
}
}
synchronized public void resetFilter (){
int i, j;
clusters.clear();
next_cluster_id = 1;
for ( i = 0 ; i < 128 ; i++ ){
for ( j = 0 ; j < 128 ; j++ ){
lastCluster[i][j] = -1;
lastEvent[i][j] = -1;
}
}
logFrameNumber=Integer.MIN_VALUE;
}
public Object getFilterState (){
return null;
}
private boolean isGeneratingFilter (){
return false;
}
synchronized public EventPacket filterPacket (EventPacket in){
if ( in == null ){
return null;
}
if ( !filterEnabled ){
return in;
}
if ( enclosedFilter != null ){
in = enclosedFilter.filterPacket(in);
}
track(in);
return in;
}
public void update (Observable o,Object arg){
initFilter();
}
public void annotate (Graphics2D g){
}
protected void drawBox (GL gl,int x,int y,int sx,int sy){
gl.glBegin(GL.GL_LINE_LOOP);
{
gl.glVertex2i(x - sx,y - sy);
gl.glVertex2i(x + sx,y - sy);
gl.glVertex2i(x + sx,y + sy);
gl.glVertex2i(x - sx,y + sy);
}
gl.glEnd();
}
synchronized public void annotate (GLAutoDrawable drawable){
final float BOX_LINE_WIDTH = 5f; // in pixels
final float PATH_LINE_WIDTH = 3f;
float[] rgb;
int sx, sy;
if ( !isFilterEnabled() ){
return;
}
GL gl = drawable.getGL(); // when we get this we are already set up with scale 1=1 pixel, at LL corner
if ( gl == null ){
log.warning("null GL in ClassTracker.annotate");
return;
}
gl.glPushMatrix();
splitClusters();
for ( Cluster c:clusters ){
rgb = c.color.getRGBComponents(null);
if ( c.mass > clusterMinMass4Display ){
sx = 4;
sy = 4;
if ( c.em ){
gl.glLineWidth((float)2);
} else{
gl.glLineWidth((float)1);
}
gl.glColor3fv(rgb,0);
//gl.glColor3f(.5f,.7f,.1f);
} else{
sx = (int)( 4.0 * c.mass / clusterMinMass4Display );
sy = (int)( 4.0 * c.mass / clusterMinMass4Display );
gl.glLineWidth((float).2);
//gl.glColor3fv(rgb,0);
gl.glColor3f(.1f,.2f,.1f);
}
drawBox(gl,(int)c.location.x,(int)c.location.y,sx,sy);
gl.glBegin(GL.GL_LINES);
{
gl.glVertex2i((int)c.location.x,(int)c.location.y);
gl.glVertex2f((int)( c.location.x + c.velocity.x * displayVelocityScaling ),(int)( c.location.y + c.velocity.y * displayVelocityScaling ));
}
gl.glEnd();
}
gl.glPopMatrix();
}
/** annotate the rendered retina frame to show locations of clusters */
synchronized public void annotate (float[][][] frame){
if ( !isFilterEnabled() ){
return;
}
// disable for now TODO
if ( chip.getCanvas().isOpenGLEnabled() ){
return; // done by open gl annotator
}
for ( Cluster c:clusters ){
// if(c.isVisible()){
drawCluster(c,frame);
}
}
/**
* Get the value of logDataEnabled
*
* @return the value of logDataEnabled
*/
public boolean isLogDataEnabled (){
return logDataEnabled;
}
/**
* Set the value of logDataEnabled
*
* @param logDataEnabled new value of logDataEnabled
*/
synchronized public void setLogDataEnabled (boolean logDataEnabled){
this.logDataEnabled = logDataEnabled;
if ( logDataEnabled ){
openLog();
} else{
closeLog();
}
}
}
|
package org.appwork.swing.components.pathchooser;
import java.awt.event.ActionEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.util.List;
import java.util.Locale;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileFilter;
import net.miginfocom.swing.MigLayout;
import org.appwork.app.gui.copycutpaste.CopyAction;
import org.appwork.app.gui.copycutpaste.CutAction;
import org.appwork.app.gui.copycutpaste.DeleteAction;
import org.appwork.app.gui.copycutpaste.PasteAction;
import org.appwork.app.gui.copycutpaste.SelectAction;
import org.appwork.storage.JSonStorage;
import org.appwork.swing.MigPanel;
import org.appwork.swing.components.ExtButton;
import org.appwork.swing.components.ExtTextField;
import org.appwork.swing.components.searchcombo.SearchComboBox;
import org.appwork.utils.StringUtils;
import org.appwork.utils.locale._AWU;
import org.appwork.utils.os.CrossSystem;
import org.appwork.utils.swing.dialog.Dialog;
import org.appwork.utils.swing.dialog.DialogCanceledException;
import org.appwork.utils.swing.dialog.DialogClosedException;
import org.appwork.utils.swing.dialog.ExtFileChooserDialog;
import org.appwork.utils.swing.dialog.FileChooserSelectionMode;
import org.appwork.utils.swing.dialog.FileChooserType;
public class PathChooser extends MigPanel {
private class BrowseAction extends AbstractAction {
private static final long serialVersionUID = -4350861121298607806L;
BrowseAction() {
putValue(Action.NAME, getBrowseLabel());
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent
* )
*/
@Override
public void actionPerformed(final ActionEvent e) {
final File file = doFileChooser();
if (file == null) { return; }
setFile(file);
}
}
private static final long serialVersionUID = -3651657642011425583L;
protected ExtTextField txt;
protected ExtButton bt;
private String id;
protected SearchComboBox<String> destination;
public PathChooser(final String id) {
this(id, false);
}
public PathChooser(final String id, final boolean useQuickLIst) {
super("ins 0", "[grow,fill][]", "[grow,fill]");
this.id = id;
setOpaque(false);
txt = new ExtTextField() {
private static final long serialVersionUID = 3243788323043431841L;
@Override
public JPopupMenu getPopupMenu(final CutAction cutAction, final CopyAction copyAction, final PasteAction pasteAction, final DeleteAction deleteAction, final SelectAction selectAction) {
final JPopupMenu self = PathChooser.this.getPopupMenu(txt, cutAction, copyAction, pasteAction, deleteAction, selectAction);
if (self == null) { return super.getPopupMenu(cutAction, copyAction, pasteAction, deleteAction, selectAction); }
return self;
}
};
txt.setHelpText(getHelpText());
bt = new ExtButton(new BrowseAction());
if (useQuickLIst) {
destination = new SearchComboBox<String>() {
@Override
public JTextField createTextField() {
return txt;
}
@Override
protected Icon getIconForValue(final String value) {
return null;
}
@Override
protected String getTextForValue(final String value) {
return value;
}
@Override
public boolean isAutoCompletionEnabled() {
return false;
}
@Override
public void onChanged() {
PathChooser.this.onChanged(txt);
}
};
// this code makes enter leave the dialog.
destination.getTextField().getInputMap().put(KeyStroke.getKeyStroke("pressed TAB"), "auto");
destination.getTextField().setFocusTraversalKeysEnabled(false);
destination.getTextField().getActionMap().put("auto", new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
PathChooser.this.auto(txt);
}
});
destination.setUnkownTextInputAllowed(true);
destination.setBadColor(null);
destination.setSelectedItem(null);
this.add(destination);
} else {
this.add(txt);
}
this.add(bt);
final String preSelection = JSonStorage.getStorage(Dialog.FILECHOOSER).get(Dialog.LASTSELECTION + id, getDefaultPreSelection());
if (preSelection != null) {
setFile(new File(preSelection));
}
}
@Override
public synchronized void addMouseListener(final MouseListener l) {
txt.addMouseListener(l);
bt.addMouseListener(l);
super.addMouseListener(l);
}
protected void auto(final JTextField oldTextField) {
final String txt = oldTextField.getText();
final int selstart = oldTextField.getSelectionStart();
final int selend = oldTextField.getSelectionEnd();
if (selend != txt.length()) { return; }
final String sel = txt.substring(selstart, selend);
final String bef = txt.substring(0, selstart);
final String name = bef.endsWith("/") || bef.endsWith("\\") ? "" : new File(bef).getName();
final String findName = txt.endsWith("/") || txt.endsWith("\\") ? "" : new File(txt).getName();
boolean found = sel.length() == 0;
File root = new File(bef);
while (!root.exists() && root != null) {
if (root.getParentFile() == root) { return; }
root = root.getParentFile();
}
for (final File f : root.listFiles()) {
if (f.isFile()) {
continue;
}
if (f.isHidden()) {
continue;
}
if (this.equals(f.getName(), findName)) {
found = true;
continue;
}
if (found && startsWith(f.getName(), name)) {
oldTextField.setText(f.getAbsolutePath());
oldTextField.setSelectionStart(selstart);
oldTextField.setSelectionEnd(oldTextField.getText().length());
return;
}
}
oldTextField.setText(bef);
}
/**
* @return
*/
public File doFileChooser() {
final ExtFileChooserDialog d = new ExtFileChooserDialog(0, getDialogTitle(), null, null);
d.setStorageID(getID());
d.setFileSelectionMode(getSelectionMode());
d.setFileFilter(getFileFilter());
d.setType(getType());
d.setMultiSelection(false);
d.setPreSelection(getFile());
try {
Dialog.I().showDialog(d);
} catch (final DialogClosedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final DialogCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return d.getSelectedFile();
}
/**
* @param name
* @param findName
* @return
*/
private boolean equals(final String name, final String findName) {
if (CrossSystem.isWindows()) { return name.equalsIgnoreCase(findName); }
return name.equals(findName);
}
/**
* @param file2
* @return
*/
protected String fileToText(final File file2) {
return file2.getAbsolutePath();
}
/**
* @return
*/
public String getBrowseLabel() {
return _AWU.T.pathchooser_browselabel();
}
/**
* removes the button from the component to place it externaly
*
* @return
*/
public JButton getButton() {
this.remove(bt);
setLayout(new MigLayout("ins 0", "[grow,fill]", "[grow,fill]"));
return bt;
}
/**
* @return
*/
protected String getDefaultPreSelection() {
// TODO Auto-generated method stub
return null;
}
/**
* @return
*/
public String getDialogTitle() {
// TODO Auto-generated method stub
return _AWU.T.pathchooser_dialog_title();
}
/**
* @return
*/
public File getFile() {
if (StringUtils.isEmpty(txt.getText())) { return null; }
return textToFile(txt.getText());
}
/**
* @return
*/
public FileFilter getFileFilter() {
return null;
}
/**
* @return
*/
protected String getHelpText() {
return _AWU.T.pathchooser_helptext();
}
/**
* @return
*/
public String getID() {
return id;
}
/**
* @return
*/
public String getPath() {
return txt.getText();
}
public JPopupMenu getPopupMenu(final ExtTextField txt, final CutAction cutAction, final CopyAction copyAction, final PasteAction pasteAction, final DeleteAction deleteAction, final SelectAction selectAction) {
return null;
}
/**
* @return
*/
public FileChooserSelectionMode getSelectionMode() {
return FileChooserSelectionMode.DIRECTORIES_ONLY;
}
/**
* @return
*/
public FileChooserType getType() {
return FileChooserType.SAVE_DIALOG;
}
/**
* @param txt2
*/
protected void onChanged(final ExtTextField txt2) {
// TODO Auto-generated method stub
}
@Override
public synchronized void removeMouseListener(final MouseListener l) {
txt.removeMouseListener(l);
bt.removeMouseListener(l);
super.removeMouseListener(l);
}
@Override
public void setEnabled(final boolean b) {
txt.setEnabled(b);
bt.setEnabled(b);
if (destination != null) {
destination.setEnabled(b);
}
}
public void setFile(final File file) {
txt.setText(fileToText(file));
}
/**
* @param packagizerFilterRuleDialog_layoutDialogContent_dest_help
*/
public void setHelpText(final String helpText) {
txt.setHelpText(helpText);
}
/**
* @param downloadDestination
*/
public void setPath(final String downloadDestination) {
txt.setText(downloadDestination);
}
public void setQuickSelectionList(final List<String> quickSelectionList) {
destination.setList(quickSelectionList);
}
/**
* @param name
* @param name2
* @return
*/
private boolean startsWith(final String name, final String name2) {
if (CrossSystem.isWindows()) {
return name.toLowerCase(Locale.ENGLISH).startsWith(name2.toLowerCase(Locale.ENGLISH));
}
return name.startsWith(name2);
}
/**
* @param text
* @return
*/
protected File textToFile(final String text) {
return new File(text);
}
}
|
package net.sourceforge.pebble.web.action;
import net.sourceforge.pebble.Constants;
import net.sourceforge.pebble.domain.BlogEntry;
import net.sourceforge.pebble.domain.BlogException;
import net.sourceforge.pebble.domain.Blog;
import net.sourceforge.pebble.web.view.ForwardView;
import net.sourceforge.pebble.web.view.View;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Removes one or more existing draft blog entries.
*
* @author Simon Brown
*/
public class RemoveDraftsAction extends SecureAction {
/**
* Peforms the processing associated with this action.
*
* @param request the HttpServletRequest instance
* @param response the HttpServletResponse instance
* @return the name of the next view
*/
public View process(HttpServletRequest request, HttpServletResponse response) throws ServletException {
Blog blog = (Blog)getModel().get(Constants.BLOG_KEY);
String ids[] = request.getParameterValues("entry");
if (ids != null) {
for (String id : ids) {
BlogEntry blogEntry = blog.getDraftBlogEntry(id);
if (blogEntry != null) {
try {
blogEntry.remove();
} catch (BlogException be) {
throw new ServletException(be);
}
}
}
}
return new ForwardView("/viewDrafts.secureaction");
}
/**
* Gets a list of all roles that are allowed to access this action.
*
* @return an array of Strings representing role names
* @param request
*/
public String[] getRoles(HttpServletRequest request) {
return new String[]{Constants.BLOG_CONTRIBUTOR_ROLE};
}
}
|
package org.bouncycastle.jce.provider;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.cryptopro.GOST3410PublicKeyAlgParameters;
import org.bouncycastle.asn1.oiw.ElGamalParameter;
import org.bouncycastle.asn1.pkcs.DHParameter;
import org.bouncycastle.asn1.pkcs.PKCS12PBEParams;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.RC2CBCParameter;
import org.bouncycastle.asn1.pkcs.RSAESOAEPparams;
import org.bouncycastle.asn1.pkcs.RSASSAPSSparams;
import org.bouncycastle.asn1.pkcs.PBKDF2Params;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.DSAParameter;
import org.bouncycastle.jce.spec.ElGamalParameterSpec;
import org.bouncycastle.jce.spec.GOST3410ParameterSpec;
import org.bouncycastle.jce.spec.GOST3410PublicKeyParameterSetSpec;
import org.bouncycastle.jce.spec.IESParameterSpec;
import org.bouncycastle.util.Arrays;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.PSource;
import javax.crypto.spec.RC2ParameterSpec;
import java.io.IOException;
import java.security.AlgorithmParametersSpi;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.DSAParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec;
public abstract class JDKAlgorithmParameters
extends AlgorithmParametersSpi
{
protected boolean isASN1FormatString(String format)
{
return format == null || format.equals("ASN.1");
}
protected AlgorithmParameterSpec engineGetParameterSpec(
Class paramSpec)
throws InvalidParameterSpecException
{
if (paramSpec == null)
{
throw new NullPointerException("argument to getParameterSpec must not be null");
}
return localEngineGetParameterSpec(paramSpec);
}
protected abstract AlgorithmParameterSpec localEngineGetParameterSpec(Class paramSpec)
throws InvalidParameterSpecException;
public static class IVAlgorithmParameters
extends JDKAlgorithmParameters
{
private byte[] iv;
protected byte[] engineGetEncoded()
throws IOException
{
return engineGetEncoded("ASN.1");
}
protected byte[] engineGetEncoded(
String format)
throws IOException
{
if (isASN1FormatString(format))
{
return new DEROctetString(engineGetEncoded("RAW")).getEncoded();
}
if (format.equals("RAW"))
{
return Arrays.clone(iv);
}
return null;
}
protected AlgorithmParameterSpec localEngineGetParameterSpec(
Class paramSpec)
throws InvalidParameterSpecException
{
if (paramSpec == IvParameterSpec.class)
{
return new IvParameterSpec(iv);
}
throw new InvalidParameterSpecException("unknown parameter spec passed to IV parameters object.");
}
protected void engineInit(
AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (!(paramSpec instanceof IvParameterSpec))
{
throw new InvalidParameterSpecException("IvParameterSpec required to initialise a IV parameters algorithm parameters object");
}
this.iv = ((IvParameterSpec)paramSpec).getIV();
}
protected void engineInit(
byte[] params)
throws IOException
{
// check that we don't have a DER encoded octet string
if ((params.length % 8) != 0
&& params[0] == 0x04 && params[1] == params.length - 2)
{
ASN1OctetString oct = (ASN1OctetString)ASN1Object.fromByteArray(params);
params = oct.getOctets();
}
this.iv = Arrays.clone(params);
}
protected void engineInit(
byte[] params,
String format)
throws IOException
{
if (isASN1FormatString(format))
{
try
{
ASN1OctetString oct = (ASN1OctetString)ASN1Object.fromByteArray(params);
engineInit(oct.getOctets());
}
catch (Exception e)
{
throw new IOException("Exception decoding: " + e);
}
return;
}
if (format.equals("RAW"))
{
engineInit(params);
return;
}
throw new IOException("Unknown parameters format in IV parameters object");
}
protected String engineToString()
{
return "IV Parameters";
}
}
public static class RC2AlgorithmParameters
extends JDKAlgorithmParameters
{
private short[] table = {
0xbd, 0x56, 0xea, 0xf2, 0xa2, 0xf1, 0xac, 0x2a, 0xb0, 0x93, 0xd1, 0x9c, 0x1b, 0x33, 0xfd, 0xd0,
0x30, 0x04, 0xb6, 0xdc, 0x7d, 0xdf, 0x32, 0x4b, 0xf7, 0xcb, 0x45, 0x9b, 0x31, 0xbb, 0x21, 0x5a,
0x41, 0x9f, 0xe1, 0xd9, 0x4a, 0x4d, 0x9e, 0xda, 0xa0, 0x68, 0x2c, 0xc3, 0x27, 0x5f, 0x80, 0x36,
0x3e, 0xee, 0xfb, 0x95, 0x1a, 0xfe, 0xce, 0xa8, 0x34, 0xa9, 0x13, 0xf0, 0xa6, 0x3f, 0xd8, 0x0c,
0x78, 0x24, 0xaf, 0x23, 0x52, 0xc1, 0x67, 0x17, 0xf5, 0x66, 0x90, 0xe7, 0xe8, 0x07, 0xb8, 0x60,
0x48, 0xe6, 0x1e, 0x53, 0xf3, 0x92, 0xa4, 0x72, 0x8c, 0x08, 0x15, 0x6e, 0x86, 0x00, 0x84, 0xfa,
0xf4, 0x7f, 0x8a, 0x42, 0x19, 0xf6, 0xdb, 0xcd, 0x14, 0x8d, 0x50, 0x12, 0xba, 0x3c, 0x06, 0x4e,
0xec, 0xb3, 0x35, 0x11, 0xa1, 0x88, 0x8e, 0x2b, 0x94, 0x99, 0xb7, 0x71, 0x74, 0xd3, 0xe4, 0xbf,
0x3a, 0xde, 0x96, 0x0e, 0xbc, 0x0a, 0xed, 0x77, 0xfc, 0x37, 0x6b, 0x03, 0x79, 0x89, 0x62, 0xc6,
0xd7, 0xc0, 0xd2, 0x7c, 0x6a, 0x8b, 0x22, 0xa3, 0x5b, 0x05, 0x5d, 0x02, 0x75, 0xd5, 0x61, 0xe3,
0x18, 0x8f, 0x55, 0x51, 0xad, 0x1f, 0x0b, 0x5e, 0x85, 0xe5, 0xc2, 0x57, 0x63, 0xca, 0x3d, 0x6c,
0xb4, 0xc5, 0xcc, 0x70, 0xb2, 0x91, 0x59, 0x0d, 0x47, 0x20, 0xc8, 0x4f, 0x58, 0xe0, 0x01, 0xe2,
0x16, 0x38, 0xc4, 0x6f, 0x3b, 0x0f, 0x65, 0x46, 0xbe, 0x7e, 0x2d, 0x7b, 0x82, 0xf9, 0x40, 0xb5,
0x1d, 0x73, 0xf8, 0xeb, 0x26, 0xc7, 0x87, 0x97, 0x25, 0x54, 0xb1, 0x28, 0xaa, 0x98, 0x9d, 0xa5,
0x64, 0x6d, 0x7a, 0xd4, 0x10, 0x81, 0x44, 0xef, 0x49, 0xd6, 0xae, 0x2e, 0xdd, 0x76, 0x5c, 0x2f,
0xa7, 0x1c, 0xc9, 0x09, 0x69, 0x9a, 0x83, 0xcf, 0x29, 0x39, 0xb9, 0xe9, 0x4c, 0xff, 0x43, 0xab
};
private short[] ekb = {
0x5d, 0xbe, 0x9b, 0x8b, 0x11, 0x99, 0x6e, 0x4d, 0x59, 0xf3, 0x85, 0xa6, 0x3f, 0xb7, 0x83, 0xc5,
0xe4, 0x73, 0x6b, 0x3a, 0x68, 0x5a, 0xc0, 0x47, 0xa0, 0x64, 0x34, 0x0c, 0xf1, 0xd0, 0x52, 0xa5,
0xb9, 0x1e, 0x96, 0x43, 0x41, 0xd8, 0xd4, 0x2c, 0xdb, 0xf8, 0x07, 0x77, 0x2a, 0xca, 0xeb, 0xef,
0x10, 0x1c, 0x16, 0x0d, 0x38, 0x72, 0x2f, 0x89, 0xc1, 0xf9, 0x80, 0xc4, 0x6d, 0xae, 0x30, 0x3d,
0xce, 0x20, 0x63, 0xfe, 0xe6, 0x1a, 0xc7, 0xb8, 0x50, 0xe8, 0x24, 0x17, 0xfc, 0x25, 0x6f, 0xbb,
0x6a, 0xa3, 0x44, 0x53, 0xd9, 0xa2, 0x01, 0xab, 0xbc, 0xb6, 0x1f, 0x98, 0xee, 0x9a, 0xa7, 0x2d,
0x4f, 0x9e, 0x8e, 0xac, 0xe0, 0xc6, 0x49, 0x46, 0x29, 0xf4, 0x94, 0x8a, 0xaf, 0xe1, 0x5b, 0xc3,
0xb3, 0x7b, 0x57, 0xd1, 0x7c, 0x9c, 0xed, 0x87, 0x40, 0x8c, 0xe2, 0xcb, 0x93, 0x14, 0xc9, 0x61,
0x2e, 0xe5, 0xcc, 0xf6, 0x5e, 0xa8, 0x5c, 0xd6, 0x75, 0x8d, 0x62, 0x95, 0x58, 0x69, 0x76, 0xa1,
0x4a, 0xb5, 0x55, 0x09, 0x78, 0x33, 0x82, 0xd7, 0xdd, 0x79, 0xf5, 0x1b, 0x0b, 0xde, 0x26, 0x21,
0x28, 0x74, 0x04, 0x97, 0x56, 0xdf, 0x3c, 0xf0, 0x37, 0x39, 0xdc, 0xff, 0x06, 0xa4, 0xea, 0x42,
0x08, 0xda, 0xb4, 0x71, 0xb0, 0xcf, 0x12, 0x7a, 0x4e, 0xfa, 0x6c, 0x1d, 0x84, 0x00, 0xc8, 0x7f,
0x91, 0x45, 0xaa, 0x2b, 0xc2, 0xb1, 0x8f, 0xd5, 0xba, 0xf2, 0xad, 0x19, 0xb2, 0x67, 0x36, 0xf7,
0x0f, 0x0a, 0x92, 0x7d, 0xe3, 0x9d, 0xe9, 0x90, 0x3e, 0x23, 0x27, 0x66, 0x13, 0xec, 0x81, 0x15,
0xbd, 0x22, 0xbf, 0x9f, 0x7e, 0xa9, 0x51, 0x4b, 0x4c, 0xfb, 0x02, 0xd3, 0x70, 0x86, 0x31, 0xe7,
0x3b, 0x05, 0x03, 0x54, 0x60, 0x48, 0x65, 0x18, 0xd2, 0xcd, 0x5f, 0x32, 0x88, 0x0e, 0x35, 0xfd
};
private byte[] iv;
private int parameterVersion = 58;
protected byte[] engineGetEncoded()
{
return Arrays.clone(iv);
}
protected byte[] engineGetEncoded(
String format)
throws IOException
{
if (isASN1FormatString(format))
{
if (parameterVersion == -1)
{
return new RC2CBCParameter(engineGetEncoded()).getEncoded();
}
else
{
return new RC2CBCParameter(parameterVersion, engineGetEncoded()).getEncoded();
}
}
if (format.equals("RAW"))
{
return engineGetEncoded();
}
return null;
}
protected AlgorithmParameterSpec localEngineGetParameterSpec(
Class paramSpec)
throws InvalidParameterSpecException
{
if (paramSpec == RC2ParameterSpec.class)
{
if (parameterVersion != -1)
{
if (parameterVersion < 256)
{
return new RC2ParameterSpec(ekb[parameterVersion], iv);
}
else
{
return new RC2ParameterSpec(parameterVersion, iv);
}
}
}
if (paramSpec == IvParameterSpec.class)
{
return new IvParameterSpec(iv);
}
throw new InvalidParameterSpecException("unknown parameter spec passed to RC2 parameters object.");
}
protected void engineInit(
AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (paramSpec instanceof IvParameterSpec)
{
this.iv = ((IvParameterSpec)paramSpec).getIV();
}
else if (paramSpec instanceof RC2ParameterSpec)
{
int effKeyBits = ((RC2ParameterSpec)paramSpec).getEffectiveKeyBits();
if (effKeyBits != -1)
{
if (effKeyBits < 256)
{
parameterVersion = table[effKeyBits];
}
else
{
parameterVersion = effKeyBits;
}
}
this.iv = ((RC2ParameterSpec)paramSpec).getIV();
}
else
{
throw new InvalidParameterSpecException("IvParameterSpec or RC2ParameterSpec required to initialise a RC2 parameters algorithm parameters object");
}
}
protected void engineInit(
byte[] params)
throws IOException
{
this.iv = Arrays.clone(params);
}
protected void engineInit(
byte[] params,
String format)
throws IOException
{
if (isASN1FormatString(format))
{
RC2CBCParameter p = RC2CBCParameter.getInstance(ASN1Object.fromByteArray(params));
if (p.getRC2ParameterVersion() != null)
{
parameterVersion = p.getRC2ParameterVersion().intValue();
}
iv = p.getIV();
return;
}
if (format.equals("RAW"))
{
engineInit(params);
return;
}
throw new IOException("Unknown parameters format in IV parameters object");
}
protected String engineToString()
{
return "RC2 Parameters";
}
}
public static class PBKDF2
extends JDKAlgorithmParameters
{
PBKDF2Params params;
protected byte[] engineGetEncoded()
{
try
{
return params.getEncoded(ASN1Encodable.DER);
}
catch (IOException e)
{
throw new RuntimeException("Oooops! " + e.toString());
}
}
protected byte[] engineGetEncoded(
String format)
{
if (isASN1FormatString(format))
{
return engineGetEncoded();
}
return null;
}
protected AlgorithmParameterSpec localEngineGetParameterSpec(
Class paramSpec)
throws InvalidParameterSpecException
{
if (paramSpec == PBEParameterSpec.class)
{
return new PBEParameterSpec(params.getSalt(),
params.getIterationCount().intValue());
}
throw new InvalidParameterSpecException("unknown parameter spec passed to PKCS12 PBE parameters object.");
}
protected void engineInit(
AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (!(paramSpec instanceof PBEParameterSpec))
{
throw new InvalidParameterSpecException("PBEParameterSpec required to initialise a PKCS12 PBE parameters algorithm parameters object");
}
PBEParameterSpec pbeSpec = (PBEParameterSpec)paramSpec;
this.params = new PBKDF2Params(pbeSpec.getSalt(),
pbeSpec.getIterationCount());
}
protected void engineInit(
byte[] params)
throws IOException
{
this.params = PBKDF2Params.getInstance(ASN1Object.fromByteArray(params));
}
protected void engineInit(
byte[] params,
String format)
throws IOException
{
if (isASN1FormatString(format))
{
engineInit(params);
return;
}
throw new IOException("Unknown parameters format in PWRIKEK parameters object");
}
protected String engineToString()
{
return "PBKDF2 Parameters";
}
}
public static class PKCS12PBE
extends JDKAlgorithmParameters
{
PKCS12PBEParams params;
protected byte[] engineGetEncoded()
{
try
{
return params.getEncoded(ASN1Encodable.DER);
}
catch (IOException e)
{
throw new RuntimeException("Oooops! " + e.toString());
}
}
protected byte[] engineGetEncoded(
String format)
{
if (isASN1FormatString(format))
{
return engineGetEncoded();
}
return null;
}
protected AlgorithmParameterSpec localEngineGetParameterSpec(
Class paramSpec)
throws InvalidParameterSpecException
{
if (paramSpec == PBEParameterSpec.class)
{
return new PBEParameterSpec(params.getIV(),
params.getIterations().intValue());
}
throw new InvalidParameterSpecException("unknown parameter spec passed to PKCS12 PBE parameters object.");
}
protected void engineInit(
AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (!(paramSpec instanceof PBEParameterSpec))
{
throw new InvalidParameterSpecException("PBEParameterSpec required to initialise a PKCS12 PBE parameters algorithm parameters object");
}
PBEParameterSpec pbeSpec = (PBEParameterSpec)paramSpec;
this.params = new PKCS12PBEParams(pbeSpec.getSalt(),
pbeSpec.getIterationCount());
}
protected void engineInit(
byte[] params)
throws IOException
{
this.params = PKCS12PBEParams.getInstance(ASN1Object.fromByteArray(params));
}
protected void engineInit(
byte[] params,
String format)
throws IOException
{
if (isASN1FormatString(format))
{
engineInit(params);
return;
}
throw new IOException("Unknown parameters format in PKCS12 PBE parameters object");
}
protected String engineToString()
{
return "PKCS12 PBE Parameters";
}
}
public static class DH
extends JDKAlgorithmParameters
{
DHParameterSpec currentSpec;
/**
* Return the PKCS#3 ASN.1 structure DHParameter.
* <p>
* <pre>
* DHParameter ::= SEQUENCE {
* prime INTEGER, -- p
* base INTEGER, -- g
* privateValueLength INTEGER OPTIONAL}
* </pre>
*/
protected byte[] engineGetEncoded()
{
DHParameter dhP = new DHParameter(currentSpec.getP(), currentSpec.getG(), currentSpec.getL());
try
{
return dhP.getEncoded(ASN1Encodable.DER);
}
catch (IOException e)
{
throw new RuntimeException("Error encoding DHParameters");
}
}
protected byte[] engineGetEncoded(
String format)
{
if (isASN1FormatString(format))
{
return engineGetEncoded();
}
return null;
}
protected AlgorithmParameterSpec localEngineGetParameterSpec(
Class paramSpec)
throws InvalidParameterSpecException
{
if (paramSpec == DHParameterSpec.class)
{
return currentSpec;
}
throw new InvalidParameterSpecException("unknown parameter spec passed to DH parameters object.");
}
protected void engineInit(
AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (!(paramSpec instanceof DHParameterSpec))
{
throw new InvalidParameterSpecException("DHParameterSpec required to initialise a Diffie-Hellman algorithm parameters object");
}
this.currentSpec = (DHParameterSpec)paramSpec;
}
protected void engineInit(
byte[] params)
throws IOException
{
try
{
DHParameter dhP = new DHParameter((ASN1Sequence)ASN1Object.fromByteArray(params));
if (dhP.getL() != null)
{
currentSpec = new DHParameterSpec(dhP.getP(), dhP.getG(), dhP.getL().intValue());
}
else
{
currentSpec = new DHParameterSpec(dhP.getP(), dhP.getG());
}
}
catch (ClassCastException e)
{
throw new IOException("Not a valid DH Parameter encoding.");
}
catch (ArrayIndexOutOfBoundsException e)
{
throw new IOException("Not a valid DH Parameter encoding.");
}
}
protected void engineInit(
byte[] params,
String format)
throws IOException
{
if (isASN1FormatString(format))
{
engineInit(params);
}
else
{
throw new IOException("Unknown parameter format " + format);
}
}
protected String engineToString()
{
return "Diffie-Hellman Parameters";
}
}
public static class DSA
extends JDKAlgorithmParameters
{
DSAParameterSpec currentSpec;
/**
* Return the X.509 ASN.1 structure DSAParameter.
* <p>
* <pre>
* DSAParameter ::= SEQUENCE {
* prime INTEGER, -- p
* subprime INTEGER, -- q
* base INTEGER, -- g}
* </pre>
*/
protected byte[] engineGetEncoded()
{
DSAParameter dsaP = new DSAParameter(currentSpec.getP(), currentSpec.getQ(), currentSpec.getG());
try
{
return dsaP.getEncoded(ASN1Encodable.DER);
}
catch (IOException e)
{
throw new RuntimeException("Error encoding DSAParameters");
}
}
protected byte[] engineGetEncoded(
String format)
{
if (isASN1FormatString(format))
{
return engineGetEncoded();
}
return null;
}
protected AlgorithmParameterSpec localEngineGetParameterSpec(
Class paramSpec)
throws InvalidParameterSpecException
{
if (paramSpec == DSAParameterSpec.class)
{
return currentSpec;
}
throw new InvalidParameterSpecException("unknown parameter spec passed to DSA parameters object.");
}
protected void engineInit(
AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (!(paramSpec instanceof DSAParameterSpec))
{
throw new InvalidParameterSpecException("DSAParameterSpec required to initialise a DSA algorithm parameters object");
}
this.currentSpec = (DSAParameterSpec)paramSpec;
}
protected void engineInit(
byte[] params)
throws IOException
{
try
{
DSAParameter dsaP = new DSAParameter((ASN1Sequence)ASN1Object.fromByteArray(params));
currentSpec = new DSAParameterSpec(dsaP.getP(), dsaP.getQ(), dsaP.getG());
}
catch (ClassCastException e)
{
throw new IOException("Not a valid DSA Parameter encoding.");
}
catch (ArrayIndexOutOfBoundsException e)
{
throw new IOException("Not a valid DSA Parameter encoding.");
}
}
protected void engineInit(
byte[] params,
String format)
throws IOException
{
if (isASN1FormatString(format) || format.equalsIgnoreCase("X.509"))
{
engineInit(params);
}
else
{
throw new IOException("Unknown parameter format " + format);
}
}
protected String engineToString()
{
return "DSA Parameters";
}
}
public static class GOST3410
extends JDKAlgorithmParameters
{
GOST3410ParameterSpec currentSpec;
/**
* Return the X.509 ASN.1 structure GOST3410Parameter.
* <p>
* <pre>
* GOST3410Parameter ::= SEQUENCE {
* prime INTEGER, -- p
* subprime INTEGER, -- q
* base INTEGER, -- a}
* </pre>
*/
protected byte[] engineGetEncoded()
{
GOST3410PublicKeyAlgParameters gost3410P = new GOST3410PublicKeyAlgParameters(new DERObjectIdentifier(currentSpec.getPublicKeyParamSetOID()), new DERObjectIdentifier(currentSpec.getDigestParamSetOID()), new DERObjectIdentifier(currentSpec.getEncryptionParamSetOID()));
try
{
return gost3410P.getEncoded(ASN1Encodable.DER);
}
catch (IOException e)
{
throw new RuntimeException("Error encoding GOST3410Parameters");
}
}
protected byte[] engineGetEncoded(
String format)
{
if (isASN1FormatString(format) || format.equalsIgnoreCase("X.509"))
{
return engineGetEncoded();
}
return null;
}
protected AlgorithmParameterSpec localEngineGetParameterSpec(
Class paramSpec)
throws InvalidParameterSpecException
{
if (paramSpec == GOST3410PublicKeyParameterSetSpec.class)
{
return currentSpec;
}
throw new InvalidParameterSpecException("unknown parameter spec passed to GOST3410 parameters object.");
}
protected void engineInit(
AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (!(paramSpec instanceof GOST3410ParameterSpec))
{
throw new InvalidParameterSpecException("GOST3410ParameterSpec required to initialise a GOST3410 algorithm parameters object");
}
this.currentSpec = (GOST3410ParameterSpec)paramSpec;
}
protected void engineInit(
byte[] params)
throws IOException
{
try
{
ASN1Sequence seq = (ASN1Sequence) ASN1Object.fromByteArray(params);
this.currentSpec = GOST3410ParameterSpec.fromPublicKeyAlg(
new GOST3410PublicKeyAlgParameters(seq));
}
catch (ClassCastException e)
{
throw new IOException("Not a valid GOST3410 Parameter encoding.");
}
catch (ArrayIndexOutOfBoundsException e)
{
throw new IOException("Not a valid GOST3410 Parameter encoding.");
}
}
protected void engineInit(
byte[] params,
String format)
throws IOException
{
if (isASN1FormatString(format) || format.equalsIgnoreCase("X.509"))
{
engineInit(params);
}
else
{
throw new IOException("Unknown parameter format " + format);
}
}
protected String engineToString()
{
return "GOST3410 Parameters";
}
}
public static class ElGamal
extends JDKAlgorithmParameters
{
ElGamalParameterSpec currentSpec;
/**
* Return the X.509 ASN.1 structure ElGamalParameter.
* <p>
* <pre>
* ElGamalParameter ::= SEQUENCE {
* prime INTEGER, -- p
* base INTEGER, -- g}
* </pre>
*/
protected byte[] engineGetEncoded()
{
ElGamalParameter elP = new ElGamalParameter(currentSpec.getP(), currentSpec.getG());
try
{
return elP.getEncoded(ASN1Encodable.DER);
}
catch (IOException e)
{
throw new RuntimeException("Error encoding ElGamalParameters");
}
}
protected byte[] engineGetEncoded(
String format)
{
if (isASN1FormatString(format) || format.equalsIgnoreCase("X.509"))
{
return engineGetEncoded();
}
return null;
}
protected AlgorithmParameterSpec localEngineGetParameterSpec(
Class paramSpec)
throws InvalidParameterSpecException
{
if (paramSpec == ElGamalParameterSpec.class)
{
return currentSpec;
}
else if (paramSpec == DHParameterSpec.class)
{
return new DHParameterSpec(currentSpec.getP(), currentSpec.getG());
}
throw new InvalidParameterSpecException("unknown parameter spec passed to ElGamal parameters object.");
}
protected void engineInit(
AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (!(paramSpec instanceof ElGamalParameterSpec) && !(paramSpec instanceof DHParameterSpec))
{
throw new InvalidParameterSpecException("DHParameterSpec required to initialise a ElGamal algorithm parameters object");
}
if (paramSpec instanceof ElGamalParameterSpec)
{
this.currentSpec = (ElGamalParameterSpec)paramSpec;
}
else
{
DHParameterSpec s = (DHParameterSpec)paramSpec;
this.currentSpec = new ElGamalParameterSpec(s.getP(), s.getG());
}
}
protected void engineInit(
byte[] params)
throws IOException
{
try
{
ElGamalParameter elP = new ElGamalParameter((ASN1Sequence)ASN1Object.fromByteArray(params));
currentSpec = new ElGamalParameterSpec(elP.getP(), elP.getG());
}
catch (ClassCastException e)
{
throw new IOException("Not a valid ElGamal Parameter encoding.");
}
catch (ArrayIndexOutOfBoundsException e)
{
throw new IOException("Not a valid ElGamal Parameter encoding.");
}
}
protected void engineInit(
byte[] params,
String format)
throws IOException
{
if (isASN1FormatString(format) || format.equalsIgnoreCase("X.509"))
{
engineInit(params);
}
else
{
throw new IOException("Unknown parameter format " + format);
}
}
protected String engineToString()
{
return "ElGamal Parameters";
}
}
public static class IES
extends JDKAlgorithmParameters
{
IESParameterSpec currentSpec;
/**
* in the absence of a standard way of doing it this will do for
* now...
*/
protected byte[] engineGetEncoded()
{
try
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DEROctetString(currentSpec.getDerivationV()));
v.add(new DEROctetString(currentSpec.getEncodingV()));
v.add(new DERInteger(currentSpec.getMacKeySize()));
return new DERSequence(v).getEncoded(ASN1Encodable.DER);
}
catch (IOException e)
{
throw new RuntimeException("Error encoding IESParameters");
}
}
protected byte[] engineGetEncoded(
String format)
{
if (isASN1FormatString(format) || format.equalsIgnoreCase("X.509"))
{
return engineGetEncoded();
}
return null;
}
protected AlgorithmParameterSpec localEngineGetParameterSpec(
Class paramSpec)
throws InvalidParameterSpecException
{
if (paramSpec == IESParameterSpec.class)
{
return currentSpec;
}
throw new InvalidParameterSpecException("unknown parameter spec passed to ElGamal parameters object.");
}
protected void engineInit(
AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (!(paramSpec instanceof IESParameterSpec))
{
throw new InvalidParameterSpecException("IESParameterSpec required to initialise a IES algorithm parameters object");
}
this.currentSpec = (IESParameterSpec)paramSpec;
}
protected void engineInit(
byte[] params)
throws IOException
{
try
{
ASN1Sequence s = (ASN1Sequence)ASN1Object.fromByteArray(params);
this.currentSpec = new IESParameterSpec(
((ASN1OctetString)s.getObjectAt(0)).getOctets(),
((ASN1OctetString)s.getObjectAt(0)).getOctets(),
((DERInteger)s.getObjectAt(0)).getValue().intValue());
}
catch (ClassCastException e)
{
throw new IOException("Not a valid IES Parameter encoding.");
}
catch (ArrayIndexOutOfBoundsException e)
{
throw new IOException("Not a valid IES Parameter encoding.");
}
}
protected void engineInit(
byte[] params,
String format)
throws IOException
{
if (isASN1FormatString(format) || format.equalsIgnoreCase("X.509"))
{
engineInit(params);
}
else
{
throw new IOException("Unknown parameter format " + format);
}
}
protected String engineToString()
{
return "IES Parameters";
}
}
public static class OAEP
extends JDKAlgorithmParameters
{
OAEPParameterSpec currentSpec;
/**
* Return the PKCS#1 ASN.1 structure RSAES-OAEP-params.
*/
protected byte[] engineGetEncoded()
{
AlgorithmIdentifier hashAlgorithm = new AlgorithmIdentifier(
JCEDigestUtil.getOID(currentSpec.getDigestAlgorithm()),
new DERNull());
MGF1ParameterSpec mgfSpec = (MGF1ParameterSpec)currentSpec.getMGFParameters();
AlgorithmIdentifier maskGenAlgorithm = new AlgorithmIdentifier(
PKCSObjectIdentifiers.id_mgf1,
new AlgorithmIdentifier(JCEDigestUtil.getOID(mgfSpec.getDigestAlgorithm()), new DERNull()));
PSource.PSpecified pSource = (PSource.PSpecified)currentSpec.getPSource();
AlgorithmIdentifier pSourceAlgorithm = new AlgorithmIdentifier(
PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(pSource.getValue()));
RSAESOAEPparams oaepP = new RSAESOAEPparams(hashAlgorithm, maskGenAlgorithm, pSourceAlgorithm);
try
{
return oaepP.getEncoded(ASN1Encodable.DER);
}
catch (IOException e)
{
throw new RuntimeException("Error encoding OAEPParameters");
}
}
protected byte[] engineGetEncoded(
String format)
{
if (isASN1FormatString(format) || format.equalsIgnoreCase("X.509"))
{
return engineGetEncoded();
}
return null;
}
protected AlgorithmParameterSpec localEngineGetParameterSpec(
Class paramSpec)
throws InvalidParameterSpecException
{
if (paramSpec == OAEPParameterSpec.class && currentSpec != null)
{
return currentSpec;
}
throw new InvalidParameterSpecException("unknown parameter spec passed to OAEP parameters object.");
}
protected void engineInit(
AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (!(paramSpec instanceof OAEPParameterSpec))
{
throw new InvalidParameterSpecException("OAEPParameterSpec required to initialise an OAEP algorithm parameters object");
}
this.currentSpec = (OAEPParameterSpec)paramSpec;
}
protected void engineInit(
byte[] params)
throws IOException
{
try
{
RSAESOAEPparams oaepP = new RSAESOAEPparams((ASN1Sequence)ASN1Object.fromByteArray(params));
currentSpec = new OAEPParameterSpec(
oaepP.getHashAlgorithm().getObjectId().getId(),
oaepP.getMaskGenAlgorithm().getObjectId().getId(),
new MGF1ParameterSpec(AlgorithmIdentifier.getInstance(oaepP.getMaskGenAlgorithm().getParameters()).getObjectId().getId()),
new PSource.PSpecified(ASN1OctetString.getInstance(oaepP.getPSourceAlgorithm().getParameters()).getOctets()));
}
catch (ClassCastException e)
{
throw new IOException("Not a valid OAEP Parameter encoding.");
}
catch (ArrayIndexOutOfBoundsException e)
{
throw new IOException("Not a valid OAEP Parameter encoding.");
}
}
protected void engineInit(
byte[] params,
String format)
throws IOException
{
if (format.equalsIgnoreCase("X.509")
|| format.equalsIgnoreCase("ASN.1"))
{
engineInit(params);
}
else
{
throw new IOException("Unknown parameter format " + format);
}
}
protected String engineToString()
{
return "OAEP Parameters";
}
}
public static class PSS
extends JDKAlgorithmParameters
{
PSSParameterSpec currentSpec;
/**
* Return the PKCS#1 ASN.1 structure RSASSA-PSS-params.
*/
protected byte[] engineGetEncoded()
throws IOException
{
PSSParameterSpec pssSpec = currentSpec;
AlgorithmIdentifier hashAlgorithm = new AlgorithmIdentifier(
JCEDigestUtil.getOID(pssSpec.getDigestAlgorithm()),
new DERNull());
MGF1ParameterSpec mgfSpec = (MGF1ParameterSpec)pssSpec.getMGFParameters();
AlgorithmIdentifier maskGenAlgorithm = new AlgorithmIdentifier(
PKCSObjectIdentifiers.id_mgf1,
new AlgorithmIdentifier(JCEDigestUtil.getOID(mgfSpec.getDigestAlgorithm()), new DERNull()));
RSASSAPSSparams pssP = new RSASSAPSSparams(hashAlgorithm, maskGenAlgorithm, new DERInteger(pssSpec.getSaltLength()), new DERInteger(pssSpec.getTrailerField()));
return pssP.getEncoded("DER");
}
protected byte[] engineGetEncoded(
String format)
throws IOException
{
if (format.equalsIgnoreCase("X.509")
|| format.equalsIgnoreCase("ASN.1"))
{
return engineGetEncoded();
}
return null;
}
protected AlgorithmParameterSpec localEngineGetParameterSpec(
Class paramSpec)
throws InvalidParameterSpecException
{
if (paramSpec == PSSParameterSpec.class && currentSpec != null)
{
return currentSpec;
}
throw new InvalidParameterSpecException("unknown parameter spec passed to PSS parameters object.");
}
protected void engineInit(
AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (!(paramSpec instanceof PSSParameterSpec))
{
throw new InvalidParameterSpecException("PSSParameterSpec required to initialise an PSS algorithm parameters object");
}
this.currentSpec = (PSSParameterSpec)paramSpec;
}
protected void engineInit(
byte[] params)
throws IOException
{
try
{
RSASSAPSSparams pssP = new RSASSAPSSparams((ASN1Sequence)ASN1Object.fromByteArray(params));
currentSpec = new PSSParameterSpec(
pssP.getHashAlgorithm().getObjectId().getId(),
pssP.getMaskGenAlgorithm().getObjectId().getId(),
new MGF1ParameterSpec(AlgorithmIdentifier.getInstance(pssP.getMaskGenAlgorithm().getParameters()).getObjectId().getId()),
pssP.getSaltLength().getValue().intValue(),
pssP.getTrailerField().getValue().intValue());
}
catch (ClassCastException e)
{
throw new IOException("Not a valid PSS Parameter encoding.");
}
catch (ArrayIndexOutOfBoundsException e)
{
throw new IOException("Not a valid PSS Parameter encoding.");
}
}
protected void engineInit(
byte[] params,
String format)
throws IOException
{
if (isASN1FormatString(format) || format.equalsIgnoreCase("X.509"))
{
engineInit(params);
}
else
{
throw new IOException("Unknown parameter format " + format);
}
}
protected String engineToString()
{
return "PSS Parameters";
}
}
}
|
package org.usfirst.frc.team3335.robot.subsystems;
import java.util.ArrayList;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import edu.wpi.cscore.CvSource;
import edu.wpi.cscore.UsbCamera;
import edu.wpi.first.wpilibj.CameraServer;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.Relay.Direction;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.vision.VisionThread;
public class VisionTest extends Subsystem implements LoggableSubsystem{
private static final int IMG_WIDTH = 320;
private static final int IMG_HEIGHT = 240;
private VisionThread visionThread;
private double centerX = 0.0;
private double targetDistance;
private double targetAzimuth;
private final Object imgLock = new Object();
public VisionTest() {
UsbCamera camera = CameraServer.getInstance().startAutomaticCapture();
camera.setResolution(IMG_WIDTH, IMG_HEIGHT);
// CvSource cs= CameraServer.getInstance().putVideo("name", IMG_WIDTH, IMG_HEIGHT);
visionThread = new VisionThread(camera, new GripPipeline(), pipeline -> {
Mat IMG_MOD = pipeline.hslThresholdOutput();
if (!pipeline.filterContoursOutput().isEmpty()) {
//Rect recCombine = Imgproc.boundingRect(pipeline.filterContoursOutput().get(0));
Rect recCombine = computeBoundingRectangle(pipeline.filterContoursOutput());
if (recCombine == null) return;
computeCoords(recCombine);
synchronized (imgLock) {
centerX = recCombine.x + (recCombine.width / 2);
}
Imgproc.rectangle(IMG_MOD, new Point(recCombine.x, recCombine.y),new Point(recCombine.x + recCombine.width,recCombine.y + recCombine.height), new Scalar(255, 20, 0), 5);
}
// cs.putFrame(IMG_MOD);
});
visionThread.start();
Relay relay = new Relay(0,Direction.kForward);
relay.set(Relay.Value.kOn);
//this.processImage();
}
/*public void processImage() {
cs.putFrame()
}*/
private Rect computeBoundingRectangle(ArrayList<MatOfPoint> contours) {
if(contours.size() == 2){
MatOfPoint mop1 = contours.get(0);
Rect rec1 = Imgproc.boundingRect(mop1);
MatOfPoint mop2 = contours.get(1);
Rect rec2 = Imgproc.boundingRect(mop2);
int x = Math.min(rec1.x, rec2.x);
int y = Math.min(rec1.y, rec2.y);
int width = Math.max(rec1.x + rec1.width, rec2.x + rec2.width)-x;
int height = Math.max(rec1.y + rec1.height, rec2.y + rec2.height)-y;
Rect recCombine = new Rect(x, y, width, height);
return recCombine;
}
return null;
}
@Override
protected void initDefaultCommand() {
// TODO Auto-generated method stub
}
private void computeCoords(Rect rec) {
double pixelFOV = IMG_WIDTH;
//double targetFeet = 20.0 / 12.0; // Stronghold target width / 12 in
//double targetFeet = 10.25 / 12.0; // Steamworks target width / 12 in
double targetFeet = 10.25; // FEET!!!! // Steamworks target width / 12 in
double diagonalFOVDegrees = 68.5; // Field-Of-View angle in degress for Microsoft LifeCam HD-3000(?)
double distance = targetFeet * pixelFOV / (2 * rec.width * Math.tan(Math.toRadians(diagonalFOVDegrees / 2)));
distance *= 1.47; // Fudge factor [equal to 1/tan(68.5/2)]
double targetCx = rec.x + rec.width / 2;
double width = (targetCx - pixelFOV / 2) * targetFeet / rec.width;
double azimuth = Math.toDegrees(Math.atan2(width, distance));
targetDistance = distance;
targetAzimuth = azimuth;
}
@Override
public void log() {
double cx = centerX;
SmartDashboard.putNumber("Vision: Center Value", cx);
SmartDashboard.putNumber("Vision: Target Distance", targetDistance);
SmartDashboard.putNumber("Vision: Target Azimuth", targetAzimuth);
}
}
|
package org.usfirst.frc.team4795.robot.subsystems;
import org.usfirst.frc.team4795.robot.RobotMap;
import edu.wpi.first.wpilibj.CANTalon;
import edu.wpi.first.wpilibj.CANTalon.TalonControlMode;
import edu.wpi.first.wpilibj.command.Subsystem;
public class Drivetrain extends Subsystem {
public static final double WHEEL_DIAMETER_IN = 6.0;
public static final int ENCODER_TICKS_PER_REV = 2048;
public static final double ENCODER_TICKS_PER_FT = (ENCODER_TICKS_PER_REV * 48) / (Math.PI * WHEEL_DIAMETER_IN);
public static final double WHEEL_SEPARATION_IN = 26.797;
private final CANTalon leftMotor1;
private final CANTalon leftMotor2;
private final CANTalon rightMotor1;
private final CANTalon rightMotor2;
private boolean closedLoopMode = false;
public Drivetrain() {
leftMotor1 = new CANTalon(RobotMap.LEFT_MOTOR_1.value);
leftMotor2 = new CANTalon(RobotMap.LEFT_MOTOR_2.value);
rightMotor1 = new CANTalon(RobotMap.RIGHT_MOTOR_1.value);
rightMotor2 = new CANTalon(RobotMap.RIGHT_MOTOR_2.value);
disableControl();
leftMotor1.configEncoderCodesPerRev(ENCODER_TICKS_PER_REV);
rightMotor1.configEncoderCodesPerRev(ENCODER_TICKS_PER_REV);
leftMotor1.ConfigFwdLimitSwitchNormallyOpen(true);
leftMotor1.ConfigRevLimitSwitchNormallyOpen(true);
leftMotor2.ConfigFwdLimitSwitchNormallyOpen(true);
leftMotor2.ConfigRevLimitSwitchNormallyOpen(true);
rightMotor1.ConfigFwdLimitSwitchNormallyOpen(true);
rightMotor1.ConfigRevLimitSwitchNormallyOpen(true);
rightMotor2.ConfigFwdLimitSwitchNormallyOpen(true);
rightMotor2.ConfigRevLimitSwitchNormallyOpen(true);
leftMotor1.configMaxOutputVoltage(12);
leftMotor2.configMaxOutputVoltage(12);
rightMotor1.configMaxOutputVoltage(12);
rightMotor2.configMaxOutputVoltage(12);
}
public void disableControl() {
leftMotor1.disableControl();
leftMotor2.disableControl();
rightMotor1.disableControl();
rightMotor2.disableControl();
}
public void enableControl() {
leftMotor1.enableControl();
leftMotor2.enableControl();
rightMotor1.enableControl();
rightMotor2.enableControl();
}
public void changeControlMode(TalonControlMode mode) {
disableControl();
leftMotor1.changeControlMode(mode);
rightMotor1.changeControlMode(mode);
if(mode != TalonControlMode.Position && mode != TalonControlMode.Speed) {
leftMotor2.changeControlMode(mode);
rightMotor2.changeControlMode(mode);
closedLoopMode = false;
} else {
leftMotor2.changeControlMode(TalonControlMode.Follower);
leftMotor2.set(RobotMap.LEFT_MOTOR_1.value);
rightMotor2.changeControlMode(TalonControlMode.Follower);
rightMotor2.set(RobotMap.RIGHT_MOTOR_1.value);
closedLoopMode = true;
}
enableControl();
}
public void setRaw(double left, double right) {
leftMotor1.set(left);
rightMotor1.set(right);
if(!closedLoopMode) {
leftMotor2.set(left);
rightMotor1.set(right);
}
}
public void setPID(double P, double I, double D) {
leftMotor1.setPID(P, I, D);
rightMotor1.setPID(P, I, D);
}
public void drive(double left, double right) {
changeControlMode(TalonControlMode.PercentVbus);
setRaw(left, right);
}
public void drive(double distance, double P, double I, double D) {
changeControlMode(TalonControlMode.Position);
setPID(P, I, D);
double distanceTicks = distance * ENCODER_TICKS_PER_FT;
setRaw(leftMotor1.getPosition()+distanceTicks, rightMotor1.getPosition()+distanceTicks);
}
public void rotateRadians(double angle, double P, double I, double D) {
changeControlMode(TalonControlMode.Position);
setPID(P, I, D);
double distanceTicks = (angle * WHEEL_SEPARATION_IN * ENCODER_TICKS_PER_FT) / 24;
setRaw(leftMotor1.getPosition()-distanceTicks, rightMotor1.getPosition()+distanceTicks);
}
public void rotateDegrees(double angle, double P, double I, double D) {
rotateRadians(Math.toRadians(angle), P, I, D);
}
public double getLeftError() {
return leftMotor1.getError();
}
public double getRightError() {
return rightMotor1.getError();
}
@Override
protected void initDefaultCommand() {}
}
|
package org.vitrivr.cineast.core.run;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.vitrivr.cineast.core.data.MediaType;
import org.vitrivr.cineast.core.data.entities.MultimediaMetadataDescriptor;
import org.vitrivr.cineast.core.data.entities.MultimediaObjectDescriptor;
/**
* An {@link ExtractionItemContainer} contains all information for ONE item which is supposed to be
* extracted. A container MUST contain a {@link #path} linking to the item to be extracted. The
* corresponding {@link #object} MUST contain the {@link MultimediaObjectDescriptor#getMediatype()}
* so an item can be handed out to different extractionhandlers.
*
* @author silvan on 06.04.18.
*/
public class ExtractionItemContainer {
private MultimediaObjectDescriptor object;
private MultimediaMetadataDescriptor[] metadata;
@JsonIgnore
private Path path;
/**
* If a path has been specified directly, returns the path. If no path has been specified, tries
* to construct a path from the path of the underlying {@link MultimediaObjectDescriptor}
*/
public Path getPathForExtraction() {
if (path == null) {
return Paths.get(object.getPath());
}
return path;
}
public void setObject(MultimediaObjectDescriptor object) {
this.object = object;
}
public void setMetadata(
MultimediaMetadataDescriptor[] metadata) {
this.metadata = metadata;
}
public MultimediaObjectDescriptor getObject() {
return object;
}
public MultimediaMetadataDescriptor[] getMetadata() {
return metadata;
}
@Override
public String toString() {
return "ExtractionItemContainer{" +
"object=" + object +
", metadata=" + Arrays.toString(metadata) +
", path=" + path +
'}';
}
/**
* Json-Creator, only takes strings or json-compatible objects.
*
* @param uri used to create a path
*/
@JsonCreator
public ExtractionItemContainer(@JsonProperty("object") MultimediaObjectDescriptor object,
@JsonProperty("metadata") MultimediaMetadataDescriptor[] metadata,
@JsonProperty("uri") String uri)
throws URISyntaxException {
this(object, metadata, Paths.get(new URI(uri)));
}
public ExtractionItemContainer(
MultimediaObjectDescriptor object,
MultimediaMetadataDescriptor[] metadata, Path path) {
this.object = object;
this.metadata = metadata == null ? new MultimediaMetadataDescriptor[0] : metadata;
this.path = path;
if (this.path == null) {
throw new RuntimeException("Path was null for object " + object);
}
}
}
|
// This file is part of the OpenNMS(R) Application.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// Modifications:
// 2005 Jan 11: Added a check to insure V2 traps had TIMTICKS varbind.
// 2003 Aug 21: Modifications to support ScriptD.
// 2003 Feb 28: Small fix for null terminated strings in traps.
// 2003 Jan 31: Cleaned up some unused imports.
// 2003 Jan 08: Added code to associate IP addresses from traps with nodes.
// 2002 Nov 29: Fixed a small bug in trap handler. Bug #676.
// 2002 Jul 18: Added a check for bad varbind from Extreme traps.
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
// Tab Size = 8
package org.opennms.netmgt.trapd;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import org.apache.log4j.Category;
import org.opennms.core.fiber.PausableFiber;
import org.opennms.core.queue.FifoQueue;
import org.opennms.core.queue.FifoQueueException;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.eventd.EventConfigurationManager;
import org.opennms.netmgt.eventd.EventIpcManager;
import org.opennms.netmgt.xml.event.Event;
import org.opennms.netmgt.xml.event.Parm;
import org.opennms.netmgt.xml.event.Parms;
import org.opennms.netmgt.xml.event.Snmp;
import org.opennms.netmgt.xml.event.Value;
import org.opennms.netmgt.xml.eventconf.Logmsg;
import org.opennms.protocols.ip.IPv4Address;
import org.opennms.protocols.snmp.SnmpCounter32;
import org.opennms.protocols.snmp.SnmpCounter64;
import org.opennms.protocols.snmp.SnmpGauge32;
import org.opennms.protocols.snmp.SnmpIPAddress;
import org.opennms.protocols.snmp.SnmpInt32;
import org.opennms.protocols.snmp.SnmpNull;
import org.opennms.protocols.snmp.SnmpObjectId;
import org.opennms.protocols.snmp.SnmpOctetString;
import org.opennms.protocols.snmp.SnmpOpaque;
import org.opennms.protocols.snmp.SnmpPduPacket;
import org.opennms.protocols.snmp.SnmpPduTrap;
import org.opennms.protocols.snmp.SnmpSMI;
import org.opennms.protocols.snmp.SnmpSyntax;
import org.opennms.protocols.snmp.SnmpTimeTicks;
class TrapQueueProcessor implements Runnable, PausableFiber {
/**
* The sysUpTimeOID, which should be the first varbind in a V2 trap
*/
private static final String SNMP_SYSUPTIME_OID = ".1.3.6.1.2.1.1.3.0";
/**
* The sysUpTimeOID, which should be the first varbind in a V2 trap, but in
* the case of Extreme Networks only mostly
*/
private static final String EXTREME_SNMP_SYSUPTIME_OID = ".1.3.6.1.2.1.1.3";
/**
* The snmpTrapOID, which should be the second varbind in a V2 trap
*/
private static final String SNMP_TRAP_OID = ".1.3.6.1.6.3.1.1.4.1.0";
/**
* The snmp trap enterprise OID, which if present in a V2 trap is the last
* varbind.
*
* ref - book 'SNMP, SNMPv2, SNMPv3..' by William Stallings, third edition,
* section 13.1.3
*/
private static final String SNMP_TRAP_ENTERPRISE_ID = ".1.3.6.1.6.3.1.1.4.3.0";
/**
* The snmpTraps value to be used in case a standard trap comes in without
* the SNMP_TRAP_ENTERPRISE_ID as the last varbind.
*/
private static final String SNMP_TRAPS = ".1.3.6.1.6.3.1.1.5";
/**
* The standard traps list
*/
private static final ArrayList GENERIC_TRAPS;
/**
* The snmp sysUpTime OID is the first varbind
*/
private static final int SNMP_SYSUPTIME_OID_INDEX = 0;
/**
* The snmp trap OID is the second varbind
*/
private static final int SNMP_TRAP_OID_INDEX = 1;
/**
* The dot separator in an OID
*/
private static final char DOT_CHAR = '.';
/**
* The input queue
*/
private FifoQueue m_backlogQ;
/**
* The name of the local host.
*/
private String m_localAddr;
/**
* Current status of the fiber
*/
private int m_status;
/**
* The thread that is executing the <code>run</code> method on behalf of
* the fiber.
*/
private Thread m_worker;
/**
* Whether or not a newSuspect event should be generated with a trap from an
* unknown IP address
*/
private boolean m_newSuspect;
private EventIpcManager m_eventMgr;
private SyntaxToEvent[] m_syntaxToEvents;
/**
* Create the standard traps list - used in v2 processing
*/
static {
GENERIC_TRAPS = new ArrayList();
GENERIC_TRAPS.add(new SnmpObjectId("1.3.6.1.6.3.1.1.5.1")); // coldStart
GENERIC_TRAPS.add(new SnmpObjectId("1.3.6.1.6.3.1.1.5.2")); // warmStart
GENERIC_TRAPS.add(new SnmpObjectId("1.3.6.1.6.3.1.1.5.3")); // linkDown
GENERIC_TRAPS.add(new SnmpObjectId("1.3.6.1.6.3.1.1.5.4")); // linkUp
GENERIC_TRAPS.add(new SnmpObjectId("1.3.6.1.6.3.1.1.5.5")); // authenticationFailure
GENERIC_TRAPS.add(new SnmpObjectId("1.3.6.1.6.3.1.1.5.6")); // egpNeighborLoss
}
private void process(V2TrapInformation info) {
Category log = ThreadCategory.getInstance(getClass());
SnmpPduPacket pdu = info.getPdu();
InetAddress agent = info.getAgent();
// verify the type
if (pdu.typeId() != (byte) (SnmpPduPacket.V2TRAP)) {
// if not V2 trap, do nothing
log.warn("Received not SNMPv2 Trap from host "
+ agent.getHostAddress());
log.warn("PDU Type = " + pdu.getCommand());
return;
}
// get the address converted
IPv4Address addr = new IPv4Address(agent);
String trapInterface = addr.toString();
Event event = new Event();
event.setSource("trapd");
event.setHost(trapInterface);
event.setSnmphost(trapInterface);
event.setInterface(trapInterface);
event.setTime(org.opennms.netmgt.EventConstants
.formatToString(new java.util.Date()));
String ipNodeId = TrapdIPMgr.getNodeId(trapInterface);
if (ipNodeId != null) {
int intNodeId = Integer.parseInt(ipNodeId);
event.setNodeid((long) intNodeId);
}
if (log.isDebugEnabled()) {
log.debug("V2 trap - trapInterface: " + trapInterface);
}
// set the information
int numVars = pdu.getLength();
if (log.isDebugEnabled()) {
log.debug("V2 trap numVars or pdu length: " + numVars);
}
if (numVars < 2) // check number of varbinds
{
log.info("V2 trap from " + trapInterface +
" IGNORED due to not having the required varbinds. Have " +
numVars + ", needed 2");
return;
}
// The first varbind has the sysUpTime
// Modify the sysUpTime varbind to add the trailing 0 if it is
// missing
// The second varbind has the snmpTrapOID
// Confirm that these two are present
String varBindName0 = pdu.getVarBindAt(0).getName().toString();
String varBindName1 = pdu.getVarBindAt(1).getName().toString();
if (varBindName0.equals(EXTREME_SNMP_SYSUPTIME_OID)) {
log
.info("V2 trap from "
+ trapInterface
+ " has been corrected due to the sysUptime.0 varbind not having been sent with a trailing 0.\n\tVarbinds received are : "
+ varBindName0 + " and " + varBindName1);
varBindName0 = SNMP_SYSUPTIME_OID;
}
if ((!(varBindName0.equals(SNMP_SYSUPTIME_OID)))
|| (!(varBindName1.equals(SNMP_TRAP_OID)))) {
log
.info("V2 trap from "
+ trapInterface
+ " IGNORED due to not having the required varbinds.\n\tThe first varbind must be sysUpTime.0 and the second snmpTrapOID.0\n\tVarbinds received are : "
+ varBindName0 + " and " + varBindName1);
return;
}
Snmp snmpInfo = new Snmp();
if (log.isDebugEnabled()) {
log.debug("V2 trap first varbind value: "
+ pdu.getVarBindAt(0).getValue().toString());
}
// time-stamp
long timeVal;
switch (pdu.getVarBindAt(SNMP_SYSUPTIME_OID_INDEX).getValue().typeId()) {
case SnmpSMI.SMI_TIMETICKS:
timeVal = ((SnmpTimeTicks) pdu.getVarBindAt(
SNMP_SYSUPTIME_OID_INDEX).getValue()).getValue();
log.debug("V2 trap first varbind value is of type TIMETICKS (correct)");
break;
case SnmpSMI.SMI_INTEGER:
timeVal = ((SnmpInt32) pdu.getVarBindAt(
SNMP_SYSUPTIME_OID_INDEX).getValue()).getValue();
log.debug("V2 trap first varbind value is of type INTEGER, casting to TIMETICKS");
break;
default:
log.info("V2 trap does not have the required first varbind as TIMETICKS - cannot process trap");
return;
}
snmpInfo.setTimeStamp(timeVal);
// Get the value for the snmpTrapOID
SnmpObjectId snmpTrapOid = (SnmpObjectId)
pdu.getVarBindAt(SNMP_TRAP_OID_INDEX).getValue();
String snmpTrapOidValue = snmpTrapOid.toString();
// Force leading "." (dot) if not present
if (!snmpTrapOidValue.startsWith(".")) {
snmpTrapOidValue = "." + snmpTrapOidValue;
}
if (log.isDebugEnabled()) {
log.debug("snmpTrapOID: " + snmpTrapOidValue);
}
// get the last subid
int length = snmpTrapOidValue.length();
int lastIndex = snmpTrapOidValue.lastIndexOf(DOT_CHAR);
String lastSubIdStr = snmpTrapOidValue.substring(lastIndex + 1);
int lastSubId = -1;
try {
lastSubId = Integer.parseInt(lastSubIdStr);
} catch (NumberFormatException nfe) {
lastSubId = -1;
}
// Check if standard trap
if (GENERIC_TRAPS.contains(snmpTrapOid)) {
// set generic
snmpInfo.setGeneric(lastSubId - 1);
// set specific to zero
snmpInfo.setSpecific(0);
// if present, the 'snmpTrapEnterprise' OID occurs as
// the last OID
// Check the last varbind to see if it is the enterprise ID
String varBindName = pdu.getVarBindAt(numVars - 1).getName()
.toString();
if (varBindName.equals(SNMP_TRAP_ENTERPRISE_ID)) {
// if present, set the value of the varbind as the
// enterprise id
snmpInfo.setId(pdu.getVarBindAt(numVars - 1).getValue()
.toString());
} else {
// if not present, set the value of the varbind as the
// snmpTraps value defined as in RFC 1907
snmpInfo.setId(SNMP_TRAPS
+ "."
+ snmpTrapOidValue
.charAt(snmpTrapOidValue.length() - 1));
}
} else // not standard trap
{
// set generic to 6
snmpInfo.setGeneric(6);
// set specific to lastsubid
snmpInfo.setSpecific(lastSubId);
// get the next to last subid
int nextToLastIndex = snmpTrapOidValue.lastIndexOf(DOT_CHAR,
lastIndex - 1);
// check if value is zero
String nextToLastSubIdStr = snmpTrapOidValue.substring(
nextToLastIndex + 1, lastIndex);
if (nextToLastSubIdStr.equals("0")) {
// set enterprise value to trap oid minus the
// the last two subids
snmpInfo.setId(snmpTrapOidValue.substring(0,
nextToLastIndex));
} else {
snmpInfo.setId(snmpTrapOidValue.substring(0, lastIndex));
}
}
if (log.isDebugEnabled()) {
log.debug("snmp specific/generic/eid: "
+ snmpInfo.getSpecific() + "/" + snmpInfo.getGeneric()
+ "/" + snmpInfo.getId());
}
// version
snmpInfo.setVersion("v2");
// community
snmpInfo.setCommunity(new String(info.getCommunity().getString()));
event.setSnmp(snmpInfo);
Parms parms = new Parms();
for (int i = 0; i < pdu.getLength(); i++) {
String name = pdu.getVarBindAt(i).getName().toString();
SnmpSyntax obj = pdu.getVarBindAt(i).getValue();
parms.addParm(processSyntax(name, obj));
} // end for loop
event.setParms(parms);
processTrapEvent(event, trapInterface, ipNodeId);
}
/**
* Process a V1 trap and convert it to an event. Once the event is
* formatted, send it to eventd.
*
* @param info
* V1 trap
*/
private void process(V1TrapInformation info) {
Category log = ThreadCategory.getInstance(getClass());
SnmpPduTrap pdu = info.getPdu();
InetAddress agent = info.getAgent();
IPv4Address addr = new IPv4Address(agent);
// XXX Why do we get the trapInterface from the PDU here, whereas for V2, we get it from
// the agent address?
String trapInterface = pdu.getAgentAddress().toString();
// I've changed it to match the way that we do things in V2 so that my test for V1 succeeds.
//String trapInterface = addr.toString();
Event event = new Event();
event.setSource("trapd");
event.setHost(addr.toString());
event.setSnmphost(trapInterface);
event.setInterface(trapInterface);
event.setTime(org.opennms.netmgt.EventConstants
.formatToString(new java.util.Date()));
String ipNodeId = TrapdIPMgr.getNodeId(trapInterface);
if (ipNodeId != null) {
int intNodeId = Integer.parseInt(ipNodeId);
event.setNodeid((long) intNodeId);
}
if (log.isDebugEnabled()) {
log.debug("V1 trap - trapInterface: " + trapInterface);
}
// set the snmp information
Snmp snmpInfo = new Snmp();
// NOTE: Force leading "." (dot) on all id's
String entId = pdu.getEnterprise().toString();
if (!entId.startsWith(".")) {
entId = "." + entId;
}
snmpInfo.setId(entId);
// version
snmpInfo.setVersion("v1");
// specific
snmpInfo.setSpecific(pdu.getSpecific());
// generic
snmpInfo.setGeneric(pdu.getGeneric());
// community
snmpInfo.setCommunity(new String(info.getCommunity().getString()));
// time-stamp
snmpInfo.setTimeStamp(pdu.getTimeStamp());
event.setSnmp(snmpInfo);
Parms parms = new Parms();
for (int i = 0; i < pdu.getLength(); i++) {
String name = pdu.getVarBindAt(i).getName().toString();
SnmpSyntax obj = pdu.getVarBindAt(i).getValue();
parms.addParm(processSyntax(name, obj));
} // end for loop
event.setParms(parms);
processTrapEvent(event, trapInterface, ipNodeId);
}
public Parm processSyntax(String name, SnmpSyntax obj) {
Category log = ThreadCategory.getInstance(getClass());
Value val = new Value();
if (obj instanceof SnmpOctetString) {
// check for non-printable characters. If they
// exist then print the string out as hexidecimal
boolean asHex = false;
byte[] data = ((SnmpOctetString) obj).getString();
for (int x = 0; x < data.length; x++) {
byte b = data[x];
if ((b < 32 && b != 9 && b != 10 && b != 13 && b != 0) || b == 127) {
asHex = true;
break;
}
}
data = null;
String encoding = asHex ? EventConstants.XML_ENCODING_BASE64
: EventConstants.XML_ENCODING_TEXT;
val.setType(EventConstants.TYPE_SNMP_OCTET_STRING);
val.setEncoding(encoding);
val.setContent(EventConstants.toString(encoding, obj));
// DEBUG
if (!asHex && log.isDebugEnabled()) {
log.debug("snmpReceivedTrap: string varbind: "
+ (((SnmpOctetString) obj).toString()));
}
} else {
boolean found = false;
for (int i = 0; i < m_syntaxToEvents.length; i++) {
if (m_syntaxToEvents[i].getClassMatch() == null ||
m_syntaxToEvents[i].m_classMatch.isInstance(obj)) {
val.setType(m_syntaxToEvents[i].getType());
val.setEncoding(m_syntaxToEvents[i].getEncoding());
val.setContent(EventConstants.toString(
m_syntaxToEvents[i].getType(), obj));
found = true;
break;
}
}
if (!found) {
throw new IllegalStateException("Internal error: fell through the " +
"bottom of the loop. The syntax-to-events array might not have a " +
"catch-all for Object");
}
}
Parm parm = new Parm();
parm.setParmName(name);
parm.setValue(val);
return parm;
}
public void processTrapEvent(Event event, String trapInterface, String ipNodeId) {
Category log = ThreadCategory.getInstance(getClass());
org.opennms.netmgt.xml.eventconf.Event econf = EventConfigurationManager.get(event);
if (econf == null || econf.getUei() == null) {
event.setUei("uei.opennms.org/default/trap");
} else {
event.setUei(econf.getUei());
}
if (econf != null) {
Logmsg logmsg = econf.getLogmsg();
if (logmsg != null) {
String dest = logmsg.getDest();
if ("discardtraps".equals(dest)) {
log.debug("Trap discarded due to matching event having logmsg dest == discardtraps");
return;
}
}
}
// send the event to eventd
m_eventMgr.sendNow(event);
log.debug("Trap successfully converted and sent to eventd");
if (ipNodeId == null && m_newSuspect) {
sendNewSuspectEvent(trapInterface);
if (log.isDebugEnabled()) {
log.debug("Sent newSuspectEvent for interface: "
+ trapInterface);
}
}
}
/**
* Send a newSuspect event for the interface
*
* @param trapInterface
* The interface for which the newSuspect event is to be
* generated
*/
private void sendNewSuspectEvent(String trapInterface) {
// construct event with 'trapd' as source
Event event = new Event();
event.setSource("trapd");
event
.setUei(org.opennms.netmgt.EventConstants.NEW_SUSPECT_INTERFACE_EVENT_UEI);
event.setHost(m_localAddr);
event.setInterface(trapInterface);
event.setTime(org.opennms.netmgt.EventConstants
.formatToString(new java.util.Date()));
// send the event to eventd
m_eventMgr.sendNow(event);
}
/**
* Returns true if the status is ok and the thread should continue running.
* If the status returend is false then the thread should exit.
*
*/
private synchronized boolean statusOK() {
Category log = ThreadCategory.getInstance(getClass());
// Loop until there is a new client or we are shutdown
boolean exitThread = false;
boolean exitCheck = false;
while (!exitCheck) {
// check the child thread!
if (m_worker.isAlive() == false && m_status != STOP_PENDING) {
log.warn(getName() + " terminated abnormally");
m_status = STOP_PENDING;
}
// do normal status checks now
if (m_status == STOP_PENDING) {
exitCheck = true;
exitThread = true;
m_status = STOPPED;
} else if (m_status == PAUSE_PENDING) {
pause();
} else if (m_status == RESUME_PENDING) {
resume();
} else if (m_status == PAUSED) {
try {
wait();
} catch (InterruptedException e) {
m_status = STOP_PENDING;
}
} else if (m_status == RUNNING) {
exitCheck = true;
}
} // end !exit check
return !exitThread;
} // statusOK
/**
* The constructor
*/
TrapQueueProcessor(FifoQueue backlog, boolean newSuspect,
EventIpcManager eventMgr) {
m_backlogQ = backlog;
m_newSuspect = newSuspect;
m_eventMgr = eventMgr;
try {
m_localAddr = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException uhE) {
Category log = ThreadCategory.getInstance(getClass());
m_localAddr = "localhost";
log.error("<ctor>: Error looking up local hostname", uhE);
}
m_syntaxToEvents = new SyntaxToEvent[] {
new SyntaxToEvent(SnmpInt32.class, EventConstants.TYPE_SNMP_INT32,
EventConstants.XML_ENCODING_TEXT),
new SyntaxToEvent(SnmpNull.class, EventConstants.TYPE_SNMP_NULL,
EventConstants.XML_ENCODING_TEXT),
new SyntaxToEvent(SnmpObjectId.class, EventConstants.TYPE_SNMP_OBJECT_IDENTIFIER,
EventConstants.XML_ENCODING_TEXT),
new SyntaxToEvent(SnmpIPAddress.class, EventConstants.TYPE_SNMP_IPADDRESS,
EventConstants.XML_ENCODING_TEXT),
new SyntaxToEvent(SnmpTimeTicks.class, EventConstants.TYPE_SNMP_TIMETICKS,
EventConstants.XML_ENCODING_TEXT),
new SyntaxToEvent(SnmpCounter32.class, EventConstants.TYPE_SNMP_COUNTER32,
EventConstants.XML_ENCODING_TEXT),
new SyntaxToEvent(SnmpGauge32.class, EventConstants.TYPE_SNMP_GAUGE32,
EventConstants.XML_ENCODING_TEXT),
new SyntaxToEvent(SnmpOpaque.class, EventConstants.TYPE_SNMP_OPAQUE,
EventConstants.XML_ENCODING_BASE64),
new SyntaxToEvent(SnmpCounter64.class, EventConstants.TYPE_SNMP_COUNTER64,
EventConstants.XML_ENCODING_TEXT),
new SyntaxToEvent(Object.class, EventConstants.TYPE_STRING,
EventConstants.XML_ENCODING_TEXT)
};
}
public synchronized void start() {
Category log = ThreadCategory.getInstance(getClass());
if (m_worker != null)
throw new IllegalStateException(
"The fiber is running or has already run");
m_status = STARTING;
m_worker = new Thread(this, getName());
m_worker.start();
if (log.isDebugEnabled()) {
log.debug(getName() + " started");
}
}
/**
* Pauses the current fiber.
*/
public synchronized void pause() {
if (m_worker == null || m_worker.isAlive() == false)
throw new IllegalStateException("The fiber is not running");
m_status = PAUSED;
notifyAll();
}
/**
* Resumes the currently paused fiber.
*/
public synchronized void resume() {
if (m_worker == null || m_worker.isAlive() == false)
throw new IllegalStateException("The fiber is not running");
m_status = RUNNING;
notifyAll();
}
public synchronized void stop() {
if (m_worker == null)
throw new IllegalStateException("The fiber has never run");
m_status = STOP_PENDING;
m_worker.interrupt();
notifyAll();
}
/**
* Returns the name of the fiber.
*
* @return The name of the Fiber.
*/
public String getName() {
return "TrapQueueProcessor";
}
/**
* Returns the current status of the fiber
*
* @return The status of the Fiber.
*/
public synchronized int getStatus() {
if (m_worker != null && !m_worker.isAlive())
m_status = STOPPED;
return m_status;
}
/**
* Reads off of the input queue and depending on the type (V1 or V2 trap) of
* object read, process the traps to convert them to events and send them
* out
*/
public void run() {
Category log = ThreadCategory.getInstance(getClass());
synchronized (this) {
m_status = RUNNING;
}
while (statusOK()) {
Object o = null;
try {
o = m_backlogQ.remove(1000);
} catch (InterruptedException iE) {
log.debug("Trapd.QueueProcessor: caught interrupted exception");
o = null;
m_status = STOP_PENDING;
} catch (FifoQueueException qE) {
log.debug("Trapd.QueueProcessor: caught fifo queue exception");
log.debug(qE.getLocalizedMessage(), qE);
o = null;
m_status = STOP_PENDING;
}
if (o != null && statusOK()) {
if (o instanceof V1TrapInformation) {
V1TrapInformation v1 = (V1TrapInformation) o;
try {
process(v1);
} catch (Throwable t) {
log.error("Unexpected error processing V1 trap", t);
}
} else {
V2TrapInformation v2 = (V2TrapInformation) o;
try {
process(v2);
} catch (Throwable t) {
log.error("Unexpected error processing V2 trap", t);
}
}
}
}
}
public class SyntaxToEvent {
private Class m_classMatch;
private String m_type;
private String m_encoding;
public SyntaxToEvent(Class classMatch, String type, String encoding) {
m_classMatch = classMatch;
m_type = type;
m_encoding = encoding;
}
public Class getClassMatch() {
return m_classMatch;
}
public String getType() {
return m_type;
}
public String getEncoding() {
return m_encoding;
}
}
}
|
package org.jruby.ext.thread_safe;
import org.jruby.*;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.ext.thread_safe.jsr166e.ConcurrentHashMap;
import org.jruby.ext.thread_safe.jsr166e.ConcurrentHashMapV8;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.load.Library;
import java.io.IOException;
import java.util.Map;
import static org.jruby.runtime.Visibility.PRIVATE;
/**
* Native Java implementation to avoid the JI overhead.
*
* @author thedarkone
*/
public class JRubyCacheBackendLibrary implements Library {
public void load(Ruby runtime, boolean wrap) throws IOException {
RubyClass jrubyRefClass = runtime.defineClassUnder("JRubyCacheBackend", runtime.getObject(), BACKEND_ALLOCATOR, runtime.getModule("ThreadSafe"));
jrubyRefClass.setAllocator(BACKEND_ALLOCATOR);
jrubyRefClass.defineAnnotatedMethods(JRubyCacheBackend.class);
}
private static final ObjectAllocator BACKEND_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
return new JRubyCacheBackend(runtime, klazz);
}
};
@JRubyClass(name="JRubyCacheBackend", parent="Object")
public static class JRubyCacheBackend extends RubyObject {
// Defaults used by the CHM
static final int DEFAULT_INITIAL_CAPACITY = 16;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
private ConcurrentHashMap<IRubyObject, IRubyObject> map;
private static ConcurrentHashMap<IRubyObject, IRubyObject> newCHM(int initialCapacity, float loadFactor) {
return new ConcurrentHashMapV8<IRubyObject, IRubyObject>(initialCapacity, loadFactor);
}
private static ConcurrentHashMap<IRubyObject, IRubyObject> newCHM() {
return newCHM(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
public JRubyCacheBackend(Ruby runtime, RubyClass klass) {
super(runtime, klass);
}
@JRubyMethod
public IRubyObject initialize(ThreadContext context) {
map = newCHM();
return context.getRuntime().getNil();
}
@JRubyMethod
public IRubyObject initialize(ThreadContext context, IRubyObject options) {
map = toCHM(context, options);
return context.getRuntime().getNil();
}
private ConcurrentHashMap<IRubyObject, IRubyObject> toCHM(ThreadContext context, IRubyObject options) {
Ruby runtime = context.getRuntime();
if (!options.isNil() && options.respondsTo("[]")) {
IRubyObject rInitialCapacity = options.callMethod(context, "[]", runtime.newSymbol("initial_capacity"));
IRubyObject rLoadFactor = options.callMethod(context, "[]", runtime.newSymbol("load_factor"));
int initialCapacity = !rInitialCapacity.isNil() ? RubyNumeric.num2int(rInitialCapacity.convertToInteger()) : DEFAULT_INITIAL_CAPACITY;
float loadFactor = !rLoadFactor.isNil() ? (float)RubyNumeric.num2dbl(rLoadFactor.convertToFloat()) : DEFAULT_LOAD_FACTOR;
return newCHM(initialCapacity, loadFactor);
} else {
return newCHM();
}
}
@JRubyMethod(name = "[]", required = 1)
public IRubyObject op_aref(ThreadContext context, IRubyObject key) {
IRubyObject value;
return ((value = map.get(key)) == null) ? context.getRuntime().getNil() : value;
}
@JRubyMethod(name = {"[]="}, required = 2)
public IRubyObject op_aset(IRubyObject key, IRubyObject value) {
map.put(key, value);
return value;
}
@JRubyMethod
public IRubyObject put_if_absent(IRubyObject key, IRubyObject value) {
IRubyObject result = map.putIfAbsent(key, value);
return result == null ? getRuntime().getNil() : result;
}
@JRubyMethod
public IRubyObject compute_if_absent(final ThreadContext context, final IRubyObject key, final Block block) {
return map.computeIfAbsent(key, new ConcurrentHashMap.Fun<IRubyObject, IRubyObject>() {
@Override
public IRubyObject apply(IRubyObject key) {
return block.yieldSpecific(context);
}
});
}
@JRubyMethod
public IRubyObject compute_if_present(final ThreadContext context, final IRubyObject key, final Block block) {
IRubyObject result = map.computeIfPresent(key, new ConcurrentHashMap.BiFun<IRubyObject, IRubyObject, IRubyObject>() {
@Override
public IRubyObject apply(IRubyObject key, IRubyObject oldValue) {
IRubyObject result = block.yieldSpecific(context, oldValue);
return result.isNil() ? null : result;
}
});
return result == null ? context.getRuntime().getNil() : result;
}
@JRubyMethod
public IRubyObject compute(final ThreadContext context, final IRubyObject key, final Block block) {
IRubyObject result = map.compute(key, new ConcurrentHashMap.BiFun<IRubyObject, IRubyObject, IRubyObject>() {
@Override
public IRubyObject apply(IRubyObject key, IRubyObject oldValue) {
IRubyObject result = block.yieldSpecific(context, oldValue);
return result.isNil() ? null : result;
}
});
return result == null ? context.getRuntime().getNil() : result;
}
@JRubyMethod
public IRubyObject merge_pair(final ThreadContext context, final IRubyObject key, final IRubyObject value, final Block block) {
IRubyObject result = map.merge(key, value, new ConcurrentHashMap.BiFun<IRubyObject, IRubyObject, IRubyObject>() {
@Override
public IRubyObject apply(IRubyObject oldValue, IRubyObject newValue) {
IRubyObject result = block.yieldSpecific(context, oldValue);
return result.isNil() ? null : result;
}
});
return result == null ? context.getRuntime().getNil() : result;
}
@JRubyMethod
public RubyBoolean replace_pair(IRubyObject key, IRubyObject oldValue, IRubyObject newValue) {
return getRuntime().newBoolean(map.replace(key, oldValue, newValue));
}
@JRubyMethod(name = {"key?"}, required = 1)
public RubyBoolean has_key_p(IRubyObject key) {
return map.containsKey(key) ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod
public IRubyObject replace_if_exists(IRubyObject key, IRubyObject value) {
IRubyObject result = map.replace(key, value);
return result == null ? getRuntime().getNil() : result;
}
@JRubyMethod
public IRubyObject get_and_set(IRubyObject key, IRubyObject value) {
IRubyObject result = map.put(key, value);
return result == null ? getRuntime().getNil() : result;
}
@JRubyMethod
public IRubyObject delete(IRubyObject key) {
IRubyObject result = map.remove(key);
return result == null ? getRuntime().getNil() : result;
}
@JRubyMethod
public RubyBoolean delete_pair(IRubyObject key, IRubyObject value) {
return getRuntime().newBoolean(map.remove(key, value));
}
@JRubyMethod
public IRubyObject clear() {
map.clear();
return this;
}
@JRubyMethod
public IRubyObject each_pair(ThreadContext context, Block block) {
for (Map.Entry<IRubyObject,IRubyObject> entry : map.entrySet()) {
block.yieldSpecific(context, entry.getKey(), entry.getValue());
}
return this;
}
@JRubyMethod
public RubyFixnum size(ThreadContext context) {
return context.getRuntime().newFixnum(map.size());
}
@JRubyMethod
public IRubyObject get_or_default(IRubyObject key, IRubyObject defaultValue) {
return map.getValueOrDefault(key, defaultValue);
}
@JRubyMethod(visibility = PRIVATE)
public JRubyCacheBackend initialize_copy(ThreadContext context, IRubyObject other) {
map = newCHM();
return this;
}
}
}
|
package org.jruby.ext.thread_safe;
import org.jruby.*;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.ext.thread_safe.jsr166e.ConcurrentHashMapV8;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.load.Library;
import java.io.IOException;
import java.util.Map;
import static org.jruby.runtime.Visibility.PRIVATE;
/**
* Native Java implementation to avoid the JI overhead.
*
* @author thedarkone
*/
public class JRubyCacheBackendLibrary implements Library {
public void load(Ruby runtime, boolean wrap) throws IOException {
RubyClass jrubyRefClass = runtime.defineClassUnder("JRubyCacheBackend", runtime.getObject(), BACKEND_ALLOCATOR, runtime.getModule("ThreadSafe"));
jrubyRefClass.setAllocator(BACKEND_ALLOCATOR);
jrubyRefClass.defineAnnotatedMethods(JRubyCacheBackend.class);
}
private static final ObjectAllocator BACKEND_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
return new JRubyCacheBackend(runtime, klazz);
}
};
@JRubyClass(name="JRubyCacheBackend", parent="Object")
public static class JRubyCacheBackend extends RubyObject {
// Defaults used by the CHM
static final int DEFAULT_INITIAL_CAPACITY = 16;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int DEFAULT_CONCURRENCY_LEVEL = 16;
private ConcurrentHashMapV8<IRubyObject, IRubyObject> map;
public JRubyCacheBackend(Ruby runtime, RubyClass klass) {
super(runtime, klass);
}
@JRubyMethod
public IRubyObject initialize(ThreadContext context) {
map = new ConcurrentHashMapV8<IRubyObject, IRubyObject>();
return context.getRuntime().getNil();
}
@JRubyMethod
public IRubyObject initialize(ThreadContext context, IRubyObject options) {
map = toCHM(context, options);
return context.getRuntime().getNil();
}
private ConcurrentHashMapV8<IRubyObject, IRubyObject> toCHM(ThreadContext context, IRubyObject options) {
Ruby runtime = context.getRuntime();
if (!options.isNil() && options.respondsTo("[]")) {
IRubyObject rInitialCapacity = options.callMethod(context, "[]", runtime.newSymbol("initial_capacity"));
IRubyObject rLoadFactor = options.callMethod(context, "[]", runtime.newSymbol("load_factor"));
IRubyObject rConcurrencyLevel = options.callMethod(context, "[]", runtime.newSymbol("concurrency_level"));
int initialCapacity = !rInitialCapacity.isNil() ? RubyNumeric.num2int(rInitialCapacity.convertToInteger()) : DEFAULT_INITIAL_CAPACITY;
float loadFactor = !rLoadFactor.isNil() ? (float)RubyNumeric.num2dbl(rLoadFactor.convertToFloat()) : DEFAULT_LOAD_FACTOR;
int concurrencyLevel = !rConcurrencyLevel.isNil() ? RubyNumeric.num2int(rConcurrencyLevel.convertToInteger()) : DEFAULT_CONCURRENCY_LEVEL;
return new ConcurrentHashMapV8<IRubyObject, IRubyObject>(initialCapacity, loadFactor, concurrencyLevel);
} else {
return new ConcurrentHashMapV8<IRubyObject, IRubyObject>();
}
}
@JRubyMethod(name = "[]", required = 1)
public IRubyObject op_aref(ThreadContext context, IRubyObject key) {
IRubyObject value;
return ((value = map.get(key)) == null) ? context.getRuntime().getNil() : value;
}
@JRubyMethod(name = {"[]="}, required = 2)
public IRubyObject op_aset(IRubyObject key, IRubyObject value) {
map.put(key, value);
return value;
}
@JRubyMethod
public IRubyObject put_if_absent(IRubyObject key, IRubyObject value) {
IRubyObject result = map.putIfAbsent(key, value);
return result == null ? getRuntime().getNil() : result;
}
@JRubyMethod
public IRubyObject compute_if_absent(final ThreadContext context, final IRubyObject key, final Block block) {
return map.computeIfAbsent(key, new ConcurrentHashMapV8.Fun<IRubyObject, IRubyObject>() {
@Override
public IRubyObject apply(IRubyObject key) {
return block.yieldSpecific(context);
}
});
}
@JRubyMethod
public RubyBoolean replace_pair(IRubyObject key, IRubyObject oldValue, IRubyObject newValue) {
return getRuntime().newBoolean(map.replace(key, oldValue, newValue));
}
@JRubyMethod(name = {"key?"}, required = 1)
public RubyBoolean has_key_p(IRubyObject key) {
return map.containsKey(key) ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod
public IRubyObject replace_if_exists(IRubyObject key, IRubyObject value) {
IRubyObject result = map.replace(key, value);
return result == null ? getRuntime().getNil() : result;
}
@JRubyMethod
public IRubyObject get_and_set(IRubyObject key, IRubyObject value) {
return map.put(key, value);
}
@JRubyMethod
public IRubyObject delete(IRubyObject key) {
IRubyObject result = map.remove(key);
return result == null ? getRuntime().getNil() : result;
}
@JRubyMethod
public RubyBoolean delete_pair(IRubyObject key, IRubyObject value) {
return getRuntime().newBoolean(map.remove(key, value));
}
@JRubyMethod
public IRubyObject clear() {
map.clear();
return this;
}
@JRubyMethod
public IRubyObject each_pair(ThreadContext context, Block block) {
for (Map.Entry<IRubyObject,IRubyObject> entry : map.entrySet()) {
block.yieldSpecific(context, entry.getKey(), entry.getValue());
}
return this;
}
@JRubyMethod
public RubyFixnum size(ThreadContext context) {
return context.getRuntime().newFixnum(map.size());
}
@JRubyMethod(visibility = PRIVATE)
public JRubyCacheBackend initialize_copy(ThreadContext context, IRubyObject other) {
this.map = new ConcurrentHashMapV8<IRubyObject, IRubyObject>();
return this;
}
}
}
|
package br.edu.horus.javabasico2015;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashSet;
import org.junit.Before;
import org.junit.Test;
public class ReflectionTest {
Pedido pedido = new Pedido();
Item item = new Item("polenta", 4.9d);
@Before
public void setUp(){
pedido.limpar();
pedido.adicionar(item);
}
@Test
public void testRecuperarMetodos() throws Exception{
Class<?>[] parametros = new Class<?>[]{Item.class};
Class<?> tipo = Class.forName("br.edu.horus.javabasico2015.Pedido");
Method method = tipo.getMethod("remover", parametros);
method.invoke(pedido, item);
}
@Test
public void testConstruir() throws Exception{
Class<?> tipo = Class.forName("br.edu.horus.javabasico2015.Pedido");
Constructor<?> constructor = tipo.getConstructor();
Object pedido = constructor.newInstance();
Class<?>[] parametros = new Class<?>[]{Item.class};
Method method = tipo.getMethod("remover", parametros);
@SuppressWarnings("unused")
Object retorno = method.invoke(pedido, item);
}
@Test
public void testSetPorReflection() throws Exception{
Field field = pedido.getClass().getDeclaredField("items");
field.setAccessible(true);
Collection<Item> value = new HashSet<>();
field.set(pedido, value);
}
@Test
public void testString(){
String nome = "abc";
foo(nome);
System.out.println(nome);
}
public void foo(String nome){
nome = "def";
}
}
|
package com.axxessio.oauth2.server;
import static org.junit.Assert.*;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.InvalidKeySpecException;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@IntegrationTest({"server.port=0"})
@WebAppConfiguration
public class ApplicationTest {
private static final Logger logger = Logger.getLogger("ApplicationTest");
private static CloseableHttpClient httpclient;
private static TokenHandler th;
private static UsernamePasswordCredentials creds;
@Value("${local.server.port}")
private int port;
@Before
public void setUp() throws AuthenticationException, ClientProtocolException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, URISyntaxException, IOException {
creds = new UsernamePasswordCredentials("system", "system");
httpclient = HttpClients.createDefault();
th = new TokenHandler("http://localhost:" + port, "system", "system");
th.setLogger(logger);
}
@Test
public void test() {
testCreateToken();
testCheckToken();
testRefreshToken();
testDeleteToken();
}
void testCreateToken() {
HttpPost httpPost = new HttpPost("http://localhost:" + port + "/services/oauth2/token");
CloseableHttpResponse response = null;
HttpEntity requestBody;
HttpEntity responseBody;
try {
httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
requestBody = new ByteArrayEntity("grant_type=password&username=admin&password=d033e22ae348aeb5660fc2140aec35850c4da997&scope=~customer~order".getBytes("UTF-8"));
httpPost.setEntity(requestBody);
response = httpclient.execute(httpPost);
responseBody = response.getEntity();
// set token via body
th.setToken(responseBody.getContent());
// set token via header parameter
th.setToken(response.getFirstHeader("Token-Value").getValue());
// check signature is valid
assertTrue(th.isValid(response.getFirstHeader("Signature-Value").getValue()));
// check timestamp is valid, otherwise refresh token must be called
assertTrue(th.isValid());
EntityUtils.consume(responseBody);
assertTrue(th.hasRight("customer", 'c'));
assertTrue(th.hasRight("customer", 'r'));
assertTrue(th.hasRight("customer", 'u'));
assertTrue(th.hasRight("customer", 'd'));
assertTrue(th.hasRight("order", 'c'));
assertTrue(th.hasRight("order", 'r'));
assertTrue(th.hasRight("order", 'u'));
assertTrue(th.hasRight("order", 'd'));
} catch (AuthenticationException | IOException xcptn) {
logger.severe(xcptn.toString());
} finally {
if (response != null) {
try {
response.close();
} catch (IOException ioxcptn) {
logger.severe(ioxcptn.toString());
}
}
}
}
void testCheckToken() {
HttpGet httpGet = new HttpGet("http://localhost:" + port + "/services/oauth2/token?access_token=" + th.getAccessToken());
CloseableHttpResponse response = null;
try {
httpGet.addHeader(new BasicScheme().authenticate(creds, httpGet, null));
httpGet.addHeader("Accept", "application/json");
response = httpclient.execute(httpGet);
StatusLine sl = response.getStatusLine();
// Status must be 200 OK
assertTrue (sl.getStatusCode() == 200);
} catch (AuthenticationException | IOException xcptn) {
logger.severe(xcptn.toString());
} finally {
if (response != null) {
try {
response.close();
} catch (IOException ioxcptn) {
logger.severe(ioxcptn.toString());
}
}
}
}
void testRefreshToken() {
//grant_type=refresh_token&refresh_token=
HttpPost httpPost = new HttpPost("http://localhost:" + port + "/services/oauth2/token");
CloseableHttpResponse response = null;
HttpEntity requestBody;
HttpEntity responseBody;
String oldAccessToken = th.getAccessToken();
String oldRefreshToken = th.getRefreshToken();
try {
httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
requestBody = new ByteArrayEntity(("grant_type=refresh_token&refresh_token=" + th.getRefreshToken()).getBytes("UTF-8"));
httpPost.setEntity(requestBody);
response = httpclient.execute(httpPost);
responseBody = response.getEntity();
th.setToken(responseBody.getContent());
// check signature is valid
assertTrue(oldRefreshToken.equals(th.getRefreshToken()));
assertTrue(!oldAccessToken.equals(th.getAccessToken()));
EntityUtils.consume(responseBody);
} catch (AuthenticationException | IOException xcptn) {
logger.severe(xcptn.toString());
} finally {
if (response != null) {
try {
response.close();
} catch (IOException ioxcptn) {
logger.severe(ioxcptn.toString());
}
}
}
}
void testDeleteToken() {
HttpDelete httpDelete = new HttpDelete("http://localhost:" + port + "/services/oauth2/token?refresh_token&" + th.getRefreshToken());
CloseableHttpResponse response = null;
try {
httpDelete.addHeader(new BasicScheme().authenticate(creds, httpDelete, null));
httpDelete.addHeader("Accept", "application/json");
response = httpclient.execute(httpDelete);
StatusLine sl = response.getStatusLine();
// Status must be 200 OK
assertTrue (sl.getStatusCode() == 200);
} catch (AuthenticationException | IOException xcptn) {
logger.severe(xcptn.toString());
} finally {
if (response != null) {
try {
response.close();
} catch (IOException ioxcptn) {
logger.severe(ioxcptn.toString());
}
}
}
}
}
|
package com.doctorwho.com.refection;
import static org.junit.Assert.*;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import javax.naming.InitialContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.doctorwho.com.refection.domain.BetGroupPlan;
import com.doctorwho.com.refection.domain.BetOrder;
import com.doctorwho.com.refection.domain.BetPlan;
import com.doctorwho.com.refection.domain.Empty;
public class MethodUtilTest {
private Class<?> classt;
private Class<?> betGroupPlanClass;
BeanInfo beanInfo ;
private PropertyDescriptor[] propertyDescriptors;
private String propertyName;
private Method writeMethod;
@Before
public void init() throws Throwable{
classt = BetPlan.class;
betGroupPlanClass = BetGroupPlan.class;
beanInfo = Introspector.getBeanInfo(classt);
propertyDescriptors = beanInfo.getPropertyDescriptors();
propertyName = "";
writeMethod = null;
}
@Test
public void testGetReadMethod() {
String propertyName = "";
Method readMethod = MethodUtil.getReadMethod(classt, propertyName);
assertNull(readMethod);
propertyName = "planNo";
readMethod = null;
readMethod = MethodUtil.getReadMethod(classt, propertyName);
assertNotNull(readMethod);
assertEquals(0, readMethod.getParameterTypes().length);
assertEquals(String.class, readMethod.getReturnType());
propertyName = "OrderId";
readMethod = null;
readMethod = MethodUtil.getReadMethod(classt, propertyName);
assertNull(readMethod);
propertyName = "orderId";
readMethod = null;
readMethod = MethodUtil.getReadMethod(classt, propertyName);
assertNull(readMethod);
propertyName = "orderId";
readMethod = null;
readMethod = MethodUtil.getReadMethod(betGroupPlanClass, propertyName);
assertNull(readMethod);
propertyName = "planNo";
readMethod = null;
readMethod = MethodUtil.getReadMethod(betGroupPlanClass, propertyName);
assertNotNull(readMethod);
assertEquals(0, readMethod.getParameterTypes().length);
assertEquals(String.class, readMethod.getReturnType());
propertyName = "title";
readMethod = null;
readMethod = MethodUtil.getReadMethod(betGroupPlanClass, propertyName);
assertNotNull(readMethod);
assertEquals(0, readMethod.getParameterTypes().length);
assertEquals(String.class, readMethod.getReturnType());
propertyName = "perAmount";
readMethod = null;
readMethod = MethodUtil.getReadMethod(betGroupPlanClass, propertyName);
assertNotNull(readMethod);
assertEquals(0, readMethod.getParameterTypes().length);
assertEquals(BigDecimal.class, readMethod.getReturnType());
propertyName = "joinEndTime";
readMethod = null;
readMethod = MethodUtil.getReadMethod(betGroupPlanClass, propertyName);
assertNotNull(readMethod);
assertEquals(0, readMethod.getParameterTypes().length);
assertEquals(Calendar.class, readMethod.getReturnType());
}
@Test
public void GetWriteMethods() {
String propertyName = "";
List<Method> list = MethodUtil.getWriteMethods(classt, propertyName);
assertEquals(0, list.size());
propertyName = "order";
list.clear();
list = MethodUtil.getWriteMethods(classt, propertyName);
assertEquals(3, list.size());
propertyName = "orderId";
list.clear();
list = MethodUtil.getWriteMethods(classt, propertyName);
assertEquals(1, list.size());
Method method = list.get(0);
assertEquals(1, method.getParameterTypes().length);
assertEquals(Long.class.getName(), method.getParameterTypes()[0].getName());
propertyName = "orderId";
list.clear();
list = MethodUtil.getWriteMethods(betGroupPlanClass, propertyName);
assertEquals(1, list.size());
method = null;
method = list.get(0);
assertEquals(1, method.getParameterTypes().length);
assertEquals(Long.class.getName(), method.getParameterTypes()[0].getName());
propertyName = "joinEndTime";
list.clear();
list = MethodUtil.getWriteMethods(betGroupPlanClass, propertyName);
assertEquals(1, list.size());
method = null;
method = list.get(0);
assertEquals(1, method.getParameterTypes().length);
assertEquals(Calendar.class.getName(), method.getParameterTypes()[0].getName());
propertyName = "order";
list.clear();
list = MethodUtil.getWriteMethods(betGroupPlanClass, propertyName);
assertEquals(3, list.size());
}
@Test
public void GetWriteMethodByNoPrimParam(){
String propertyName = "order";
Method writeMethod = MethodUtil.getWriteMethodByNoPrimParam(classt, propertyName);
assertNotNull(writeMethod);
assertEquals(BetOrder.class.getName(), writeMethod.getParameterTypes()[0].getName());
propertyName = "betCount";
writeMethod = null;
writeMethod = MethodUtil.getWriteMethodByNoPrimParam(classt, propertyName);
assertNull(writeMethod);
propertyName = "orderId";
writeMethod = null;
writeMethod = MethodUtil.getWriteMethodByNoPrimParam(classt, propertyName);
assertNull(writeMethod);
propertyName = "orderId";
writeMethod = null;
writeMethod = MethodUtil.getWriteMethodByNoPrimParam(betGroupPlanClass, propertyName);
assertNull(writeMethod);
propertyName = "betCount";
writeMethod = null;
writeMethod = MethodUtil.getWriteMethodByNoPrimParam(betGroupPlanClass, propertyName);
assertNull(writeMethod);
propertyName = "order";
writeMethod = null;
writeMethod = MethodUtil.getWriteMethodByNoPrimParam(betGroupPlanClass, propertyName);
assertNotNull(writeMethod);
assertEquals(BetOrder.class.getName(),writeMethod.getParameterTypes()[0].getName());
assertEquals("setOrder", writeMethod.getName());
}
@Test
public void GetWriteMethodByPrimitiveParam(){
propertyName = "order";
writeMethod = null;
writeMethod = MethodUtil.getWriteMethodByPrimitiveParam(classt, propertyName);
assertNotNull(writeMethod);
assertEquals(long.class.getName(), writeMethod.getParameterTypes()[0].getName());
}
@Test
public void GetWriteMethodByWrapperTypeParam(){
propertyName = "order";
writeMethod = null;
writeMethod = MethodUtil.getWriteMethodByWrapperTypeParam(classt, propertyName);
assertNotNull(writeMethod);
assertEquals(Long.class.getName(), writeMethod.getParameterTypes()[0].getName());
}
@Test
public void GetWriteMethod(){
String propertyName = "order";
Method writeMethod = MethodUtil.getWriteMethod(classt, propertyName,long.class);
assertNotNull(writeMethod);
assertEquals(long.class.getName(), writeMethod.getParameterTypes()[0].getName());
propertyName = "order";
writeMethod = null;
writeMethod = MethodUtil.getWriteMethod(classt, propertyName,Long.class);
assertNotNull(writeMethod);
assertEquals(Long.class.getName(), writeMethod.getParameterTypes()[0].getName());
propertyName = "order";
writeMethod = null;
writeMethod = MethodUtil.getWriteMethod(classt, propertyName,BetOrder.class);
assertNotNull(writeMethod);
assertEquals(BetOrder.class.getName(), writeMethod.getParameterTypes()[0].getName());
}
@Test
public void testGetPropertyDescriptors(){
PropertyDescriptor[] descriptors = MethodUtil.getPropertyDescriptors(BetOrder.class);
assertEquals(7, descriptors.length);
descriptors = MethodUtil.getPropertyDescriptors(BetPlan.class);
assertEquals(10, descriptors.length);
descriptors = MethodUtil.getPropertyDescriptors(BetGroupPlan.class);
assertEquals(18, descriptors.length);
descriptors = MethodUtil.getPropertyDescriptors(Empty.class);
assertEquals(0, descriptors.length);
}
@Test
public void testGetPropertyDescriptor() {
String propertyName = "";
PropertyDescriptor p = MethodUtil.getPropertyDescriptor(propertyDescriptors, propertyName);
assertNull(p);
propertyName = "planNo";
p = null;
p = MethodUtil.getPropertyDescriptor(propertyDescriptors, propertyName);
assertNotNull(p);
propertyName = "OrderId";
p = null;
p = MethodUtil.getPropertyDescriptor(propertyDescriptors, propertyName);
assertNull(p);
propertyName = "orderId";
p = null;
p = MethodUtil.getPropertyDescriptor(propertyDescriptors, propertyName);
assertNotNull(p);
propertyName = "orderId";
p = null;
p = MethodUtil.getPropertyDescriptor(MethodUtil.getPropertyDescriptors(BetGroupPlan.class), propertyName);
assertNotNull(p);
}
@Test
public void testGetMethodsByMethodName() {
String methodName = "";
List<Method> list = MethodUtil.getMethodsByMethodName(classt.getDeclaredMethods(), methodName);
Assert.assertEquals(0, list.size());
methodName = "setOrder";
list.clear();
list = MethodUtil.getMethodsByMethodName(classt.getDeclaredMethods(), methodName);
Assert.assertEquals(3, list.size());
methodName = "setOrderId";
list.clear();
list = MethodUtil.getMethodsByMethodName(classt.getDeclaredMethods(), methodName);
Assert.assertEquals(1, list.size());
methodName = "getMultiple";
list.clear();
list = MethodUtil.getMethodsByMethodName(classt.getDeclaredMethods(), methodName);
Assert.assertEquals(1, list.size());
methodName = "setOrder";
list.clear();
list = MethodUtil.getMethodsByMethodName(betGroupPlanClass.getDeclaredMethods(), methodName);
Assert.assertEquals(0, list.size());
methodName = "setOrder";
List<Method> methodlList = new ArrayList<Method>();
methodlList.addAll(Arrays.asList(betGroupPlanClass.getDeclaredMethods()));
Class<?> supClass = betGroupPlanClass.getSuperclass();
while (null != supClass) {
methodlList.addAll(Arrays.asList(supClass.getDeclaredMethods()));
supClass = supClass.getSuperclass();
}
list = MethodUtil.getMethodsByMethodName(methodlList.toArray(new Method[methodlList.size()]), methodName);
Assert.assertEquals(3, list.size());
}
@Test
public void InvokeWriteMethod() throws Throwable{
BetPlan betPlan = new BetPlan();
propertyName = "";
Object object = MethodUtil.invokeWriteMethod(betPlan, propertyName, 1);
assertNull(object);
propertyName = "id";
object = null;
object = MethodUtil.invokeWriteMethod(betPlan, propertyName, 1L);
assertNull(object);
propertyName = "orderId";
object = null;
object = MethodUtil.invokeWriteMethod(betPlan, propertyName, 1L);
assertNull(object);
propertyName = "order";
Object newInstance = classt.newInstance();
MethodUtil.invokeWriteMethod(newInstance, propertyName, new Object[]{2L});
BetPlan plan = (BetPlan) newInstance;
assertEquals(2L, plan.getOrder().getId().longValue());
BetOrder order = new BetOrder();
order.setId(5L);
newInstance = classt.newInstance();
MethodUtil.invokeWriteMethod(newInstance, propertyName, new Object[]{order});
plan = null;
plan = (BetPlan) newInstance;
assertEquals(order.getId(), plan.getOrder().getId());
Object betGroupPlan = betGroupPlanClass.newInstance();
BetGroupPlan before = (BetGroupPlan) betGroupPlan;
BetGroupPlan after = new BetGroupPlan();
after.setPlanNo("d1111");
after.setTitle("title");
BetOrder bOrder = new BetOrder();
bOrder.setId(135L);
bOrder.setSellChannel(166L);
after.setOrder(bOrder);
Object aObject = JSON.toJSON(after);
System.out.println(aObject);
propertyName = "planNo";
MethodUtil.invokeWriteMethod(before, propertyName, new Object[]{"d1111"});
MethodUtil.invokeWriteMethod(before, "title", new Object[]{"title"});
MethodUtil.invokeWriteMethod(before, "order", new Object[]{bOrder});
Object fObject = JSON.toJSON(before);
assertEquals(aObject, fObject);
System.out.println(fObject);
}
}
|
package com.github.fakemongo;
import com.github.fakemongo.junit.FongoRule;
import com.mongodb.AggregationOutput;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import org.assertj.core.util.Lists;
import static org.junit.Assert.assertEquals;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
/**
* User: gdepourtales
* 2015/06/15
*/
public class FongoAggregateOutTest {
public final FongoRule fongoRule = new FongoRule(false);
public final ExpectedException exception = ExpectedException.none();
@Rule
public TestRule rules = RuleChain.outerRule(exception).around(fongoRule);
@Test
public void testOut() {
DBCollection coll = fongoRule.newCollection();
DBCollection secondCollection = fongoRule.newCollection();
String data = "[{ _id: 1, sec: \"dessert\", category: \"pie\", type: \"apple\" },\n" +
"{ _id: 2, sec: \"dessert\", category: \"pie\", type: \"cherry\" },\n" +
"{ _id: 3, sec: \"main\", category: \"pie\", type: \"shepherd's\" },\n" +
"{ _id: 4, sec: \"main\", category: \"pie\", type: \"chicken pot\" }]";
fongoRule.insertJSON(coll, data);
DBObject project = fongoRule.parseDBObject(
"{ $out: \"" + secondCollection.getName() + "\"}"
);
AggregationOutput output = coll.aggregate(Arrays.asList(project));
List<DBObject> resultAggregate = Lists.newArrayList(output.results());
assertThat(resultAggregate).isEqualTo(fongoRule.parse(data));
assertEquals(4, secondCollection.count());
assertEquals("apple", secondCollection.find(fongoRule.parseDBObject("{_id:1}")).next().get("type"));
assertEquals("pie", secondCollection.find(fongoRule.parseDBObject("{_id:1}")).next().get("category"));
assertEquals("chicken pot", secondCollection.find(fongoRule.parseDBObject("{_id:4}")).next().get("type"));
}
@Test
public void testOutWithEmptyCollection() {
DBCollection coll = fongoRule.newCollection();
DBCollection secondCollection = fongoRule.newCollection();
String data = "[]";
fongoRule.insertJSON(coll, data);
DBObject project = fongoRule.parseDBObject(
"{ $out: \"" + secondCollection.getName() + "\"}"
);
AggregationOutput output = coll.aggregate(Arrays.asList(project));
List<DBObject> resultAggregate = Lists.newArrayList(output.results());
assertThat(resultAggregate).isEqualTo(fongoRule.parse(data));
assertEquals(0, secondCollection.count());
}
@Test
public void testOutWithNonExistentCollection() {
DBCollection coll = fongoRule.newCollection();
String data = "[{ _id: 1, sec: \"dessert\", category: \"pie\", type: \"apple\" },\n" +
"{ _id: 2, sec: \"dessert\", category: \"pie\", type: \"cherry\" },\n" +
"{ _id: 3, sec: \"main\", category: \"pie\", type: \"shepherd's\" } ,\n" +
"{ _id: 4, sec: \"main\", category: \"pie\", type: \"chicken pot\" }]";
fongoRule.insertJSON(coll, data);
String newCollectionName = "new_collection";
DBObject project = fongoRule.parseDBObject(
"{ $out: \"" + newCollectionName + "\"}"
);
AggregationOutput output = coll.aggregate(Arrays.asList(project));
List<DBObject> resultAggregate = Lists.newArrayList(output.results());
assertThat(resultAggregate).isEqualTo(fongoRule.parse(data));
DBCollection newCollection = fongoRule.getDB().getCollection("new_collection");
assertEquals(4, newCollection.count());
assertEquals("apple", newCollection.find(fongoRule.parseDBObject("{_id:1}")).next().get("type"));
assertEquals("pie", newCollection.find(fongoRule.parseDBObject("{_id:1}")).next().get("category"));
assertEquals("chicken pot", newCollection.find(fongoRule.parseDBObject("{_id:4}")).next().get("type"));
}
}
|
package fr.xevents.spikes;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
public class ScheduledTaskRegistrarIT {
private static final Logger log = LoggerFactory.getLogger(ScheduledTaskRegistrarIT.class);
private final ScheduledTaskRegistrar registrar = new ScheduledTaskRegistrar();
private final CountDownLatch latch = new CountDownLatch(10);
@Test
@Ignore
public void registerAScheduledTaskWithRegistrar() throws Exception {
CountDownTask task = new CountDownTask();
Map<Runnable, Long> fixedDelayTasks = new HashMap<Runnable, Long>();
fixedDelayTasks.put(task, new Long(100));
registrar.setFixedDelayTasks(fixedDelayTasks);
registrar.afterPropertiesSet();
latch.await(2000, TimeUnit.MILLISECONDS);
assertThat(latch.getCount(), equalTo((long) 0));
}
public class CountDownTask implements Runnable {
@Override
public void run() {
latch.countDown();
log.debug("DummyTask has been triggered, CountDownLatch is decreased.");
}
}
}
|
package io.leonard.maven.plugins.jspc;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.maven.plugin.testing.MojoRule;
import org.junit.Rule;
import org.junit.Test;
/**
* Test {@link JspcMojo}
*/
public class TestJspcMojo {
@Rule
public MojoRule rule = new MojoRule();
@Test
public void should_return_one_compiled_jsp_when_executeMojo_on_project_one_jsp_with_no_options() throws Exception {
// Given
File oneJspProject = new File("target/test-classes/unit/project_one_jsp");
// When
rule.executeMojo(oneJspProject, "compile");
// Then
Path indexJspPath = Paths.get("target/test-classes/unit/project_one_jsp/target/classes/jsp/jsp/index_jsp.class");
assertThat(indexJspPath).isNotNull();
}
@Test
public void should_return_webfrag_equal_to_reference_when_executeMojo_on_project_one_jsp_with_no_options() throws Exception {
// Given
File oneJspProject = new File("target/test-classes/unit/project_one_jsp");
Path expectedWebfrag = Paths.get("target/test-classes/unit/project_one_jsp/src/assert/webfrag.xml");
// When
rule.executeMojo(oneJspProject, "compile");
// Then
Path webfrag = Paths.get("target/test-classes/unit/project_one_jsp/target/webfrag.xml");
byte[] actualWebfrag = Files.readAllBytes(webfrag);
byte[] expectedWebFrag = Files.readAllBytes(expectedWebfrag);
// String actualWebFragStr = new String(actualWebfrag).replaceAll("\n", "\r\n");
// String expectedWebFragStr = new String(expectedWebFrag);
assertThat(actualWebfrag).isEqualTo(expectedWebFrag);
// assertThat(actualWebFragStr).isEqualTo(expectedWebFragStr);
}
}
|
package og.github.antennae.cfs;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
//@SpringBootTest
@RunWith(SpringRunner.class)
public class CfsApplicationTests {
@Test
public void contextLoads() {
}
}
|
package org.chocosolver.solver.variables;
import org.chocosolver.solver.*;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.constraints.nary.sum.PropScalar;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.search.strategy.SearchStrategyFactory;
import org.chocosolver.util.iterators.DisposableValueIterator;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import static org.chocosolver.solver.constraints.Operator.EQ;
import static org.chocosolver.solver.constraints.ternary.Max.var;
import static org.chocosolver.solver.search.strategy.SearchStrategyFactory.*;
import static org.chocosolver.solver.search.strategy.selectors.ValSelectorFactory.randomIntBound;
import static org.chocosolver.solver.search.strategy.selectors.VarSelectorFactory.randomVar;
import static org.testng.Assert.*;
/**
* <br/>
*
* @author Charles Prud'homme
* @since 25/08/11
*/
public class ViewsTest {
public static void check(Model ref, Model model, long seed, boolean strict, boolean solveAll) {
if (solveAll) {
while (ref.solve()) ;
while (model.solve()) ;
} else {
ref.solve();
model.solve();
}
Assert.assertEquals(model.getSolver().getSolutionCount(),
ref.getSolver().getSolutionCount(), "solutions (" + seed + ")");
if (strict) {
Assert.assertEquals(model.getSolver().getNodeCount(), ref.getSolver().getNodeCount(), "nodes (" + seed + ")");
} else {
Assert.assertTrue(ref.getSolver().getNodeCount() >=
model.getSolver().getNodeCount(), seed + "");
}
}
@Test(groups="10s", timeOut=60000)
public void test1() {
// Z = X + Y
// int seed = 5;
for (int seed = 0; seed < 9999; seed++) {
Model ref = new Model();
Model model = new Model();
model.set(new Settings() {
@Override
public boolean enableACOnTernarySum() {
return true;
}
});
{
IntVar x = ref.intVar("x", 0, 2, false);
IntVar y = ref.intVar("y", 0, 2, false);
IntVar z = ref.intVar("z", 0, 4, false);
new Constraint("SP", new PropScalar(new IntVar[]{x, y, z}, new int[]{1, 1, -1}, 2, EQ, 0)).post();
ref.getSolver().set(randomSearch(new IntVar[]{x, y, z}, seed));
}
{
IntVar x = model.intVar("x", 0, 2, false);
IntVar y = model.intVar("y", 0, 2, false);
IntVar z = model.intVar("Z", 0, 200, false);
model.sum(new IntVar[]{x, y}, "=", z).post();
model.getSolver().set(randomSearch(new IntVar[]{x, y, z}, seed));
}
check(ref, model, seed, false, true);
}
}
@Test(groups="10s", timeOut=60000)
public void test1a() {
// Z = X + Y (bounded)
for (int seed = 0; seed < 9999; seed++) {
Model ref = new Model();
Model model = new Model();
{
IntVar x = ref.intVar("x", 0, 2, true);
IntVar y = ref.intVar("y", 0, 2, true);
IntVar z = ref.intVar("z", 0, 4, true);
new Constraint("SP", new PropScalar(new IntVar[]{x, y, z}, new int[]{1, 1, -1}, 2, EQ, 0)).post();
ref.getSolver().set(randomSearch(new IntVar[]{x, y, z}, seed));
}
{
IntVar x = model.intVar("x", 0, 2, true);
IntVar y = model.intVar("y", 0, 2, true);
IntVar z = model.intVar("Z", 0, 200, false);
model.sum(new IntVar[]{x, y}, "=", z).post();
model.getSolver().set(randomSearch(new IntVar[]{x, y, z}, seed));
}
check(ref, model, seed, true, true);
}
}
@Test(groups="10s", timeOut=60000)
public void testa() {
// Z = max(X + Y)
for (int seed = 0; seed < 9999; seed += 1) {
Model ref = new Model();
Model model = new Model();
{
IntVar x = ref.intVar("x", 0, 2, false);
IntVar y = ref.intVar("y", 0, 2, false);
IntVar z = ref.intVar("z", 0, 2, true);
ref.max(z, x, y).post();
ref.getSolver().set(randomSearch(new IntVar[]{x, y, z}, seed));
}
{
IntVar x = model.intVar("x", 0, 2, false);
IntVar y = model.intVar("y", 0, 2, false);
IntVar z = var(x, y);
model.getSolver().set(randomSearch(new IntVar[]{x, y, z}, seed));
}
check(ref, model, seed, false, true);
}
}
@Test(groups="10s", timeOut=60000)
public void test1b() {
// Z = |X|
for (int seed = 0; seed < 9999; seed++) {
Model ref = new Model();
Model model = new Model();
{
IntVar x = ref.intVar("x", -2, 2, false);
IntVar z = ref.intVar("z", 0, 2, false);
ref.absolute(z, x).post();
ref.getSolver().set(randomSearch(new IntVar[]{x, z}, seed));
}
{
IntVar x = model.intVar("x", -2, 2, false);
IntVar z = model.intAbsView(x);
model.getSolver().set(randomSearch(new IntVar[]{x, z}, seed));
}
check(ref, model, seed, true, true);
}
}
@Test(groups="10s", timeOut=60000)
public void test1bb() {
// Z = X + c
for (int seed = 0; seed < 9999; seed++) {
Model ref = new Model();
Model model = new Model();
{
IntVar x = ref.intVar("x", -2, 2, false);
IntVar z = ref.intVar("z", -1, 3, false);
ref.arithm(z, "=", x, "+", 1).post();
ref.getSolver().set(randomSearch(new IntVar[]{x, z}, seed));
}
{
IntVar x = model.intVar("x", -2, 2, false);
IntVar z = model.intOffsetView(x, 1);
Solver r = model.getSolver();
r.set(randomSearch(new IntVar[]{x, z}, seed));
}
check(ref, model, seed, true, true);
}
}
@Test(groups="10s", timeOut=60000)
public void test1bbb() {
// Z = X * c
for (int seed = 0; seed < 9999; seed++) {
Model ref = new Model();
Model model = new Model();
{
IntVar x = ref.intVar("x", -2, 2, false);
IntVar z = ref.intVar("z", -4, 4, false);
ref.times(x, ref.intVar(2), z).post();
ref.getSolver().set(randomSearch(new IntVar[]{x, z}, seed));
}
{
IntVar x = model.intVar("x", -2, 2, false);
IntVar z = model.intScaleView(x, 2);
Solver r = model.getSolver();
r.set(randomSearch(new IntVar[]{x, z}, seed));
}
check(ref, model, seed, false, true);
}
}
@Test(groups="10s", timeOut=60000)
public void test1c() {
// Z = -X
for (int seed = 0; seed < 9999; seed++) {
Model ref = new Model();
Model model = new Model();
{
IntVar x = ref.intVar("x", 0, 2, false);
IntVar z = ref.intVar("z", -2, 0, false);
ref.arithm(z, "+", x, "=", 0).post();
ref.getSolver().set(randomSearch(new IntVar[]{x, z}, seed));
}
{
IntVar x = model.intVar("x", 0, 2, false);
IntVar z = model.intMinusView(x);
Solver r = model.getSolver();
r.set(randomSearch(new IntVar[]{x, z}, seed));
}
check(ref, model, seed, true, true);
}
}
@DataProvider(name = "1d")
public Object[][] data1D(){
List<Object[]> elt = new ArrayList<>();
for (int seed = 2; seed < 9; seed += 1) {
elt.add(new Object[]{seed});
}
return elt.toArray(new Object[elt.size()][1]);
}
@Test(groups="5m", timeOut=300000, dataProvider = "1d")
public void test1d(int seed) {
// Z = X + Y + ...
Model ref = new Model();
Model model = new Model();
int n = seed * 2;
{
IntVar[] x = ref.intVarArray("x", n, 0, 2, false);
ref.sum(x, "=", n).post();
ref.getSolver().set(minDomLBSearch(x));
}
{
IntVar[] x = model.intVarArray("x", n, 0, 2, false);
IntVar[] y = new IntVar[seed];
for (int i = 0; i < seed; i++) {
y[i] = model.intVar("Z", 0, 200, false);
model.sum(new IntVar[]{x[i], x[i + seed]}, "=", y[i]).post();
}
model.sum(y, "=", n).post();
model.getSolver().set(minDomLBSearch(x));
}
check(ref, model, seed, true, true);
}
@Test(groups="1s", timeOut=60000)
public void test1f() {
// Z = MAX(X,Y)
Model ref = new Model();
Model model = new Model();
{
IntVar x = ref.intVar("x", 160, 187, false);
IntVar y = ref.intVar("y", -999, 999, false);
IntVar z = ref.intVar("z", -9999, 9999, false);
ref.arithm(z, "+", x, "=", 180).post();
ref.max(y, ref.intVar(0), z).post();
}
{
IntVar x = model.intVar("x", 160, 187, false);
IntVar y = model.intVar("y", -999, 999, false);
IntVar z = model.intOffsetView(model.intMinusView(x), 180);
model.max(y, model.intVar(0), z).post();
check(ref, model, 0, false, true);
}
}
@Test(groups="10s", timeOut=60000)
public void test2() {
// Z = X - Y
for (int seed = 0; seed < 9999; seed++) {
Model ref = new Model();
Model model = new Model();
model.set(new Settings() {
@Override
public boolean enableACOnTernarySum() {
return true;
}
});
{
IntVar x = ref.intVar("x", 0, 2, false);
IntVar y = ref.intVar("y", 0, 2, false);
IntVar z = ref.intVar("z", -2, 2, false);
new Constraint("SP", new PropScalar(new IntVar[]{x, y, z}, new int[]{1, -1, -1}, 1, EQ, 0)).post();
// System.out.println(cstr);
ref.getSolver().set(randomSearch(new IntVar[]{x, y, z}, seed));
}
{
IntVar x = model.intVar("x", 0, 2, false);
IntVar y = model.intVar("y", 0, 2, false);
IntVar z = model.intVar("Z", -200, 200, false);
Constraint cstr = model.sum(new IntVar[]{z, y}, "=", x);
cstr.post();
// System.out.println(cstr);
model.getSolver().set(randomSearch(new IntVar[]{x, y, z}, seed));
}
check(ref, model, seed, false, true);
}
}
@Test(groups="1s", timeOut=60000)
public void testTernArithmBC() {
// note did not pass because PropXplusYeqZ did not reach a fix point
Model model = new Model();
model.set(new Settings() {
@Override
public boolean enableACOnTernarySum() {
return true;
}
});
IntVar x = model.intVar("x", 0, 2, false);
IntVar y = model.intVar("y", 0, 2, false);
IntVar z = model.intVar("Z", -2, 2, false);
IntVar absZ = model.intVar("|Z|", 0, 2, false);
model.absolute(absZ,z).post();
System.out.println(model.arithm(x,"-",y, "=", z));
model.arithm(x,"-",y, "=", z).post(); // test passes if added twice
model.arithm(absZ,"=",1).post();
model.arithm(y,"=",0).post();
try {
model.getSolver().propagate();
} catch (ContradictionException e) {
e.printStackTrace();
}
System.out.println("x - y = z");
System.out.println(x);
System.out.println(y);
System.out.println(z);
Assert.assertTrue(x.isInstantiatedTo(1));
}
@Test(groups="1s", timeOut=60000)
public void testTernArithmAC() {
// note did not pass because PropXplusYeqZ did not reach a fix point
Model model = new Model();
IntVar x = model.intVar("x", 0, 2, false);
IntVar y = model.intVar("y", 0, 2, false);
IntVar z = model.intVar("Z", -2, 2, false);
IntVar absZ = model.intVar("|Z|", 0, 2, false);
model.absolute(absZ,z).post();
System.out.println(model.arithm(x,"-",y, "=", z));
model.arithm(x,"-",y, "=", z).post(); // test passes if added twice
model.arithm(absZ,"=",1).post();
model.arithm(y,"=",0).post();
try {
model.getSolver().propagate();
} catch (ContradictionException e) {
e.printStackTrace();
}
System.out.println("x - y = z");
System.out.println(x);
System.out.println(y);
System.out.println(z);
Assert.assertTrue(x.isInstantiatedTo(1));
}
@Test(groups="10s", timeOut=60000)
public void test3() {
// Z = |X - Y|
for (int seed = 0; seed < 999; seed++) {
Model ref = new Model();
{
IntVar x = ref.intVar("x", 0, 2, false);
IntVar y = ref.intVar("y", 0, 2, false);
IntVar z = ref.intVar("z", -2, 2, false);
ref.arithm(x,"-",y, "=", z).post();
IntVar az = ref.intVar("az", 0, 2, false);
ref.absolute(az, z).post();
ref.getSolver().set(intVarSearch(randomVar(seed), randomIntBound(seed),x, y, az));
}
Model model = new Model();
{
IntVar x = model.intVar("x", 0, 2, false);
IntVar y = model.intVar("y", 0, 2, false);
IntVar z = model.intVar("Z", -2, 2, false);
model.arithm(x,"-",y, "=", z).post();
IntVar az = model.intAbsView(z);
model.getSolver().set(intVarSearch(randomVar(seed), randomIntBound(seed),x, y, az));
}
check(ref, model, seed, true, true);
}
}
@Test(groups="10s", timeOut=60000)
public void test4() {
// Z = |X - Y| + AllDiff
for (int seed = 0; seed < 999; seed++) {
Model ref = new Model();
Model model = new Model();
{
IntVar x = ref.intVar("x", 0, 2, false);
IntVar y = ref.intVar("y", 0, 2, false);
IntVar z = ref.intVar("z", -2, 2, false);
IntVar az = ref.intVar("az", 0, 2, false);
new Constraint("SP", new PropScalar(new IntVar[]{x, y, z}, new int[]{1, -1, -1}, 1, EQ, 0)).post();
ref.absolute(az, z).post();
ref.allDifferent(new IntVar[]{x, y, az}, "BC").post();
ref.getSolver().set(randomSearch(new IntVar[]{x, y, az}, seed));
}
{
IntVar x = model.intVar("x", 0, 2, false);
IntVar y = model.intVar("y", 0, 2, false);
IntVar z = model.intVar("z", -2, 2, false);
new Constraint("SP", new PropScalar(new IntVar[]{x, y, z}, new int[]{1, -1, -1}, 1, EQ, 0)).post();
IntVar az = model.intAbsView(z);
model.allDifferent(new IntVar[]{x, y, az}, "BC").post();
model.getSolver().set(randomSearch(new IntVar[]{x, y, az}, seed));
}
check(ref, model, seed, true, true);
}
}
@Test(groups="10s", timeOut=60000)
public void test5() {
// ~all-interval series
int k = 5;
for (int seed = 0; seed < 99; seed++) {
Model ref = new Model();
Model model = new Model();
{
IntVar[] x = ref.intVarArray("x", k, 0, k - 1, false);
IntVar[] y = ref.intVarArray("y", k - 1, -(k - 1), k - 1, false);
IntVar[] t = ref.intVarArray("t", k - 1, 0, k - 1, false);
for (int i = 0; i < k - 1; i++) {
new Constraint("SP", new PropScalar(new IntVar[]{x[i + 1], x[i], y[i]}, new int[]{1, -1, -1}, 1, EQ, 0)).post();
ref.absolute(t[i], y[i]).post();
}
ref.allDifferent(x, "BC").post();
ref.allDifferent(t, "BC").post();
ref.arithm(x[1], ">", x[0]).post();
ref.arithm(t[0], ">", t[k - 2]).post();
ref.getSolver().set(randomSearch(x, seed));
}
{
IntVar[] x = model.intVarArray("x", k, 0, k - 1, false);
IntVar[] t = new IntVar[k - 1];
for (int i = 0; i < k - 1; i++) {
IntVar z = model.intVar("Z", -200, 200, false);
new Constraint("SP", new PropScalar(new IntVar[]{x[i + 1], x[i], z}, new int[]{1, -1, -1}, 1, EQ, 0)).post();
t[i] = model.intAbsView(z);
}
model.allDifferent(x, "BC").post();
model.allDifferent(t, "BC").post();
model.arithm(x[1], ">", x[0]).post();
model.arithm(t[0], ">", t[k - 2]).post();
model.getSolver().set(randomSearch(x, seed));
}
check(ref, model, k, true, true);
}
}
@Test(groups="10s", timeOut=60000)
public void test6() throws ContradictionException {
Model model = new Model();
IntVar x = model.intVar("x", 0, 10, false);
IntVar y = model.intAbsView(x);
IntVar z = model.intAbsView(model.intAbsView(x));
for (int j = 0; j < 200; j++) {
// long t = -System.nanoTime();
for (int i = 0; i < 999999; i++) {
if (y.getLB() == x.getUB()) {
y.updateLowerBound(0, Cause.Null);
}
}
// t += System.nanoTime();
// System.out.printf("%.2fms vs. ", t / 1000 / 1000f);
// t = -System.nanoTime();
for (int i = 0; i < 999999; i++) {
if (z.getLB() == x.getUB()) {
z.updateLowerBound(0, Cause.Null);
}
}
// t += System.nanoTime();
// System.out.printf("%.2fms\n", t / 1000 / 1000f);
}
}
@Test(groups="1s", timeOut=60000)
public void testJL1() throws ContradictionException {
Model s = new Model();
IntVar v1 = s.intVar("v1", -2, 2, false);
IntVar v2 = s.intMinusView(s.intMinusView(s.intVar("v2", -2, 2, false)));
s.arithm(v1, "=", v2).post();
s.arithm(v2, "!=", 1).post();
s.getSolver().propagate();
assertFalse(v1.contains(1));
}
@Test(groups="1s", timeOut=60000)
public void testJL2() {
Model model = new Model();
SetVar v1 = model.setVar("{0,1}", new int[]{0, 1});
SetVar v2 = model.setVar("v2", new int[]{}, new int[]{0, 1, 2, 3});
model.subsetEq(new SetVar[]{v1, v2}).post();
while (model.solve()) ;
assertEquals(model.getSolver().getSolutionCount(), 4);
}
@Test(groups="1s", timeOut=60000)
public void testJL3() {
Model model = new Model();
model.arithm(
model.intVar("int", -3, 3, false),
"=",
model.intMinusView(model.boolVar("bool"))).post();
while (model.solve()) ;
assertEquals(model.getSolver().getSolutionCount(), 2);
}
@Test(groups="1s", timeOut=60000)
public void testJL4() throws ContradictionException {
Model s = new Model();
BoolVar bool = s.boolVar("bool");
SetVar set = s.setVar("set", new int[]{}, new int[]{0, 1});
// 17/03/16 : seems not idempotent when multiple occurrence of same var
// possible fix : split propagator in two ways
s.setBoolsChanneling(new BoolVar[]{bool, bool}, set, 0).post();
s.member(s.ONE(), set).post();
Solver r = s.getSolver();
r.set(minDomUBSearch(bool));
while (s.solve()) ;
assertEquals(s.getSolver().getSolutionCount(), 1);
}
@Test(groups="1s", timeOut=60000)
public void testJG() throws ContradictionException {
Model s = new Model();
BoolVar bool = s.boolVar("bool");
BoolVar view = bool;
IntVar sum = s.intVar("sum", 0, 6, true);
s.scalar(new IntVar[]{view, bool}, new int[]{1, 5}, "=", sum).post();
s.arithm(sum, ">", 2).post();
s.getSolver().propagate();
assertEquals(sum.isInstantiated(), true);
}
@Test(groups="1s", timeOut=60000)
public void testJG2() throws ContradictionException {
Model s = new Model();
BoolVar bool = s.boolVar("bool");
BoolVar view = s.boolNotView(bool);
IntVar sum = s.intVar("sum", 0, 6, true);
s.scalar(new IntVar[]{view, bool}, new int[]{1, 5}, "=", sum).post();
s.arithm(sum, ">", 2).post();
s.getSolver().propagate();
assertEquals(sum.isInstantiated(), true);
}
@Test(groups="1s", timeOut=60000)
public void testJG3() throws ContradictionException {
Model s = new Model();
IntVar var = s.intVar("int", 0, 2, true);
IntVar view = var;
IntVar sum = s.intVar("sum", 0, 6, true);
s.scalar(new IntVar[]{view, var}, new int[]{1, 5}, "=", sum).post();
s.arithm(sum, ">", 2).post();
s.getSolver().propagate();
assertEquals(sum.isInstantiated(), true);
}
@Test(groups="1s", timeOut=60000)
public void testJG4() throws ContradictionException {
Model s = new Model();
IntVar var = s.intVar("int", 0, 2, true);
IntVar view = s.intMinusView(var);
IntVar sum = s.intVar("sum", 0, 6, true);
s.scalar(new IntVar[]{view, var}, new int[]{1, 5}, "=", sum).post();
s.arithm(sum, ">", 2).post();
s.getSolver().propagate();
assertEquals(sum.isInstantiated(), true);
}
@Test(groups="1s", timeOut=60000)
public void testvanH() {
Model model = new Model();
BoolVar x1 = model.boolVar("x1");
BoolVar x2 = model.boolNotView(x1);
BoolVar x3 = model.boolVar("x3");
IntVar[] av = new IntVar[]{x1, x2, x3};
int[] coef = new int[]{5, 3, 2};
model.scalar(av, coef, ">=", 7).post();
try {
model.getSolver().propagate();
} catch (Exception ignored) {
}
assertTrue(x3.isInstantiated());
assertEquals(x3.getValue(), 1);
}
@Test(groups="10s", timeOut=60000)
public void testScale(){
int n = 9;
Model viewModel = makeModel(true);
scale(viewModel,n);
Model noViewModel = makeModel(false);
scale(noViewModel,n);
testModels(viewModel,noViewModel);
}
@Test(groups="10s", timeOut=60000)
public void testOffset(){
int n = 9;
Model viewModel = makeModel(true);
offset(viewModel,n);
Model noViewModel = makeModel(false);
offset(noViewModel,n);
testModels(viewModel,noViewModel);
}
@Test(groups="10s", timeOut=60000)
public void testMinus(){
int n = 9;
Model viewModel = makeModel(true);
minus(viewModel,n);
Model noViewModel = makeModel(false);
minus(noViewModel,n);
testModels(viewModel,noViewModel);
}
@Test(groups="10s", timeOut=60000)
public void testBoolNot(){
int n = 23;
Model viewModel = makeModel(true);
boolNot(viewModel,n);
Model noViewModel = makeModel(false);
boolNot(noViewModel,n);
testModels(viewModel,noViewModel);
}
@Test(groups = "10s", timeOut=60000)
public void testBoolNotNot() {
int n = 20;
Model viewModel = makeModel(true);
boolNotNot(viewModel, n);
Model noViewModel = makeModel(false);
boolNotNot(noViewModel, n);
testModels(viewModel, noViewModel);
}
private static Model makeModel(final boolean withViews){
Model m = new Model("with"+(withViews?"":"out")+" views");
m.set(new Settings() {
@Override
public boolean enableViews() {
return withViews;
}
});
return m;
}
private static void offset(Model model, int n){
IntVar[] x = model.intVarArray(n,0,n-1);
IntVar[] y = new IntVar[n];
for(int i=0;i<n;i++){
y[i] = model.intOffsetView(x[i],42);
}
checkDomains(true, x, y);
model.allDifferent(x).post();
model.sum(y, "<", n*2).post();
model.getSolver().set(SearchStrategyFactory.randomSearch(y,0));
}
private static void scale(Model model, int n){
IntVar[] x = model.intVarArray(n,0,n-1);
IntVar[] y = new IntVar[n];
for(int i=0;i<n;i++){
y[i] = model.intScaleView(x[i],42);
}
checkDomains(false, x, y);
model.allDifferent(x).post();
model.sum(y, "<", n*2).post();
model.getSolver().set(SearchStrategyFactory.randomSearch(y,0));
}
private static void minus(Model model, int n){
IntVar[] x = model.intVarArray(n,0,n-1);
IntVar[] y = new IntVar[n];
for(int i=0;i<n;i++){
y[i] = model.intMinusView(x[i]);
}
checkDomains(true, x, y);
model.allDifferent(x).post();
model.sum(y, "<", n*2).post();
model.getSolver().set(SearchStrategyFactory.randomSearch(y,0));
}
private static void boolNot(Model model, int n){
BoolVar[] x = model.boolVarArray(n);
BoolVar[] y = new BoolVar[n];
for(int i=0;i<n;i++){
y[i] = model.boolNotView(x[i]);
}
checkDomains(true, x, y);
model.sum(x,"=",n/2).post();
model.getSolver().set(SearchStrategyFactory.randomSearch(y,0));
}
public static void boolNotNot(Model model, int n) {
BoolVar[] x = model.boolVarArray(n);
BoolVar[] y = new BoolVar[n];
for (int i = 0; i < x.length; i++) {
y[i] = model.boolNotView(x[i]);
}
BoolVar[] z = new BoolVar[n];
for (int i = 0; i < y.length; i++) {
z[i] = model.boolNotView(y[i]);
Assert.assertTrue(z[i]==x[i]);
}
checkDomains(true, x, y, z);
model.sum(x, "=", n/2).post();
model.getSolver().set(SearchStrategyFactory.randomSearch(z, 0));
}
private static <T extends IntVar> void checkDomains(boolean noHoles, T[] ... vars) {
assert vars.length > 0;
for (T[] varArray : vars) {
for (T var : varArray) {
// Not in the domain
int prev = -1;
DisposableValueIterator it = var.getValueIterator(true);
for(int i = var.getLB(); i != Integer.MAX_VALUE; i = var.nextValue(i)) {
assertTrue(it.hasNext());
if(prev != -1) {
if(noHoles) {
assertEquals(var.nextValueOut(i), var.getUB()+1);
assertEquals(var.previousValueOut(i), var.getLB()-1);
}
assertTrue(it.hasPrevious());
// assertEquals(it.previous(), prev);
assertEquals(var.previousValue(i), prev);
}
prev = i;
assertEquals(it.next(), i);
}
}
}
}
private static void testModels(Model... models) {
IntVar[][] vars = new IntVar[models.length][];
for(int i=0;i<models.length;i++){
Assert.assertEquals(models[0].getResolutionPolicy(),models[i].getResolutionPolicy());
vars[i] = models[i].retrieveIntVars(true);
Assert.assertEquals(vars[i].length,vars[0].length);
}
long t;
long[] time = new long[models.length];
boolean bc;
int nbSols=0;
do {
t = System.currentTimeMillis();
bc = models[0].solve();
time[0] += System.currentTimeMillis() - t;
if(bc) nbSols++;
for(int k=1;k<models.length;k++) {
t = System.currentTimeMillis();
Assert.assertEquals(bc, models[k].solve());
time[k] += System.currentTimeMillis() - t;
Assert.assertEquals(
models[k].getSolver().getBackTrackCount(),
models[0].getSolver().getBackTrackCount());
Assert.assertEquals(
models[k].getSolver().getCurrentDepth(),
models[0].getSolver().getCurrentDepth());
Assert.assertEquals(
models[k].getSolver().getMaxDepth(),
models[0].getSolver().getMaxDepth());
Assert.assertEquals(
models[k].getSolver().getFailCount(),
models[0].getSolver().getFailCount());
if(models[0].getResolutionPolicy()!= ResolutionPolicy.SATISFACTION)
Assert.assertEquals(
models[k].getSolver().getBestSolutionValue(),
models[0].getSolver().getBestSolutionValue());
if (bc) {
for (int i = 0; i < vars[k].length; i++) {
Assert.assertEquals(vars[0][i].getValue(), vars[0][i].getValue());
}
}
}
}while (bc);
System.out.println(nbSols+" solutions");
for(int i=0;i<models.length;i++){
System.out.println(models[i].getName()+" solved in "+time[i]+" ms");
}
}
}
|
package org.minperf.bloom;
import java.util.Random;
import org.minperf.hem.RandomGenerator;
public class ProbabilityOfMappingStep {
private static final int HASHES = 3;
public static void main(String... args) {
int seed = 0;
int testCount = 1000;
for(int add = 2; add < 128; add *= 2) {
System.out.println("with arraySize = 1.23 * size + " + add + " ============");
for (int size = 1; size < 65536; size *= 2) {
long[] list = new long[size];
int arrayLength = 0;
int totalRetries = 0;
for(int test = 0; test < testCount; test++) {
RandomGenerator.createRandomUniqueListFast(list, seed);
seed += list.length;
arrayLength = (int) ((size * 1.23) + add) / 3 * 3;
int retryCount = getRetryCount(list, arrayLength, 0);
totalRetries += retryCount;
}
System.out.println("size " + size + ": " + (double) (testCount - totalRetries) / testCount);
if (totalRetries == 0 && size > 100) {
break;
}
}
}
}
public static void mainAdd(String... args) {
int seed = 0;
for (int size = 1; size < 10000000; size *= 2) {
long[] list = new long[size];
for (int add = 2;; add *= 2) {
int totalRetries = 0;
int arrayLength = 0;
for (int test = 0; test < 1000; test++) {
RandomGenerator.createRandomUniqueListFast(list, seed);
seed += list.length;
arrayLength = (int) ((size * 1.23) + add) / 3 * 3;
int retryCount = getRetryCount(list, arrayLength, 0);
totalRetries += retryCount;
if (totalRetries > 0) {
break;
}
}
// System.out.println(" size " + size + " add " + add + " totalRetries " + totalRetries);
if (totalRetries == 0) {
System.out.println("size " + size + ": " + ((double) arrayLength / size) + " * size = arrayLength (1.23 * size + " + add + ")");
if (add == 2 && size > 1000) {
System.out.println("done");
return;
}
break;
}
}
}
}
public static int getRetryCount(long[] keys, int arrayLength, int maxRetries) {
int size = keys.length;
int blockLength = arrayLength / HASHES;
int m = arrayLength;
int retryCount = 0;
Random random = new Random(1);
while (true) {
int seed = random.nextInt();
byte[] t2count = new byte[m];
long[] t2 = new long[m];
for (long k : keys) {
for (int hi = 0; hi < HASHES; hi++) {
int h = getHash(k, seed, hi, blockLength);
t2[h] ^= k;
if (t2count[h] > 120) {
// probably something wrong with the hash function
throw new IllegalArgumentException();
}
t2count[h]++;
}
}
int reverseOrderPos = 0;
int[][] alone = new int[HASHES][blockLength];
int[] alonePos = new int[HASHES];
for (int nextAlone = 0; nextAlone < HASHES; nextAlone++) {
for (int i = 0; i < blockLength; i++) {
if (t2count[nextAlone * blockLength + i] == 1) {
alone[nextAlone][alonePos[nextAlone]++] = nextAlone * blockLength + i;
}
}
}
int found = -1;
while (true) {
int i = -1;
for (int hi = 0; hi < HASHES; hi++) {
if (alonePos[hi] > 0) {
i = alone[hi][--alonePos[hi]];
found = hi;
break;
}
}
if (i == -1) {
// no entry found
break;
}
if (t2count[i] <= 0) {
continue;
}
long k = t2[i];
if (t2count[i] != 1) {
throw new AssertionError();
}
--t2count[i];
// which index (0, 1, 2) the entry was found
for (int hi = 0; hi < HASHES; hi++) {
if (hi != found) {
int h = getHash(k, seed, hi, blockLength);
int newCount = --t2count[h];
if (newCount == 1) {
// we found a key that is _now_ alone
alone[hi][alonePos[hi]++] = h;
}
// remove this key from the t2 table, using xor
t2[h] ^= k;
}
}
reverseOrderPos++;
}
// this means there was no cycle
if (reverseOrderPos == size) {
break;
}
retryCount++;
if (retryCount > maxRetries) {
break;
}
}
return retryCount;
}
private static int getHash(long key, long seed, int index, int blockLength) {
long hash = hash(key, seed);
int r;
switch (index) {
case 0:
r = (int) (hash);
break;
case 1:
r = (int) Long.rotateLeft(hash, 21);
break;
default:
r = (int) Long.rotateLeft(hash, 42);
break;
}
r = reduce((int) r, blockLength);
r = r + index * blockLength;
return (int) r;
}
static long hash(long key, long seed) {
long h = key + seed;
h ^= h >>> 33;
h *= 0xff51afd7ed558ccdL;
h ^= h >>> 33;
h *= 0xc4ceb9fe1a85ec53L;
h ^= h >>> 33;
return h;
}
private static int reduce(int hash, int n) {
return (int) (((hash & 0xffffffffL) * n) >>> 32);
}
}
|
package org.sorenle.partitioner;
import com.google.common.hash.Hashing;
import org.junit.Test;
import static org.junit.Assert.*;
public class Murmur3BuilderTest {
@Test
public void test128BitPartitioner(){
Murmur3Partitioner murmur3Partitioner = Murmur3Builder.create128BitHasher();
long hashExpected = Hashing.murmur3_128().newHasher().putInt(0).hash().padToLong();
long hash = murmur3Partitioner.getHash(0);
assertEquals(hash,hashExpected);
}
@Test
public void test32BitPartitioner(){
Murmur3Partitioner murmur3Partitioner = Murmur3Builder.create32BitHasher();
long hashExpected = Hashing.murmur3_32().newHasher().putInt(0).hash().padToLong();
long hash = murmur3Partitioner.getHash(0);
assertEquals(hash,hashExpected);
}
}
|
package org.zalando.nakadi.service;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.zalando.nakadi.domain.ConsumedEvent;
import org.zalando.nakadi.domain.NakadiCursor;
import org.zalando.nakadi.domain.Timeline;
import org.zalando.nakadi.exceptions.NakadiException;
import org.zalando.nakadi.exceptions.runtime.AccessDeniedException;
import org.zalando.nakadi.repository.db.EventTypeCache;
import org.zalando.nakadi.repository.kafka.KafkaCursor;
import org.zalando.nakadi.repository.kafka.NakadiKafkaConsumer;
import org.zalando.nakadi.security.Client;
import org.zalando.nakadi.service.converter.CursorConverterImpl;
import org.zalando.nakadi.service.timeline.TimelineService;
import org.zalando.nakadi.utils.TestUtils;
import org.zalando.nakadi.view.Cursor;
import org.zalando.nakadi.view.SubscriptionCursor;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.nCopies;
import static java.util.Optional.empty;
import static junit.framework.TestCase.assertSame;
import static junit.framework.TestCase.fail;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.zalando.nakadi.service.EventStreamWriter.BATCH_SEPARATOR;
import static org.zalando.nakadi.utils.TestUtils.buildTimelineWithTopic;
import static org.zalando.nakadi.utils.TestUtils.waitFor;
import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs;
public class EventStreamTest {
private static final String TOPIC = UUID.randomUUID().toString();
private static final byte[] DUMMY = "DUMMY".getBytes(UTF_8);
private static final Meter BYTES_FLUSHED_METER = new MetricRegistry().meter("mock");
private static final Timeline TIMELINE = buildTimelineWithTopic(TOPIC);
private static CursorConverter cursorConverter;
private static EventStreamWriterProvider writerProvider;
private final NakadiKpiPublisher kpiPublisher = mock(NakadiKpiPublisher.class);
private final String kpiEventType = "nakadi.data.streamed";
private final long kpiFrequencyMs = 100l;
@BeforeClass
public static void setupMocks() {
final TimelineService timelineService = mock(TimelineService.class);
final EventTypeCache eventTypeCache = mock(EventTypeCache.class);
cursorConverter = new CursorConverterImpl(eventTypeCache, timelineService);
writerProvider = mock(EventStreamWriterProvider.class);
}
@Before
public void setupWriter() {
when(writerProvider.getWriter()).thenReturn(createWriter());
}
protected EventStreamWriter createWriter() {
return new EventStreamWriterBinary();
}
@Test(timeout = 15000)
public void whenIOExceptionThenStreamIsClosed() throws NakadiException, InterruptedException, IOException {
final EventStreamConfig config = EventStreamConfig
.builder()
.withCursors(ImmutableList.of(NakadiCursor.of(TIMELINE, "0", "0")))
.withBatchLimit(1)
.withBatchTimeout(1)
.withConsumingClient(mock(Client.class))
.build();
final OutputStream outputStreamMock = mock(OutputStream.class);
final EventStream eventStream = new EventStream(
emptyConsumer(), outputStreamMock, config, mock(BlacklistService.class), cursorConverter,
BYTES_FLUSHED_METER, writerProvider, kpiPublisher, kpiEventType, kpiFrequencyMs);
final Thread thread = new Thread(() -> eventStream.streamEvents(new AtomicBoolean(true), () -> {
}));
thread.start();
TestUtils.waitFor(() -> assertThat("Thread should be running", thread.isAlive(), is(true)), 5000);
// simulation of client closing the connection: this will end the eventStream
doThrow(new IOException()).when(outputStreamMock).flush();
TestUtils.waitFor(
() -> assertThat("The thread should be dead now, as we simulated that client closed connection",
thread.isAlive(), is(false)), 10000);
thread.join();
}
@Test(timeout = 10000)
public void whenCrutchWorkedThenStreamIsClosed() throws NakadiException, InterruptedException, IOException {
final EventStreamConfig config = EventStreamConfig
.builder()
.withCursors(ImmutableList.of(NakadiCursor.of(TIMELINE, "0", "0")))
.withBatchLimit(1)
.withBatchTimeout(1)
.withConsumingClient(mock(Client.class))
.build();
final EventStream eventStream = new EventStream(
emptyConsumer(), mock(OutputStream.class), config, mock(BlacklistService.class), cursorConverter,
BYTES_FLUSHED_METER, writerProvider, kpiPublisher, kpiEventType, kpiFrequencyMs);
final AtomicBoolean streamOpen = new AtomicBoolean(true);
final Thread thread = new Thread(() -> eventStream.streamEvents(streamOpen, () -> {
}));
thread.start();
waitFor(() -> Assert.assertTrue(thread.isAlive()));
// simulation of client closing the connection using crutch
streamOpen.set(false);
waitFor(() -> Assert.assertFalse(thread.isAlive()), TimeUnit.SECONDS.toMillis(3));
assertThat("The thread should be dead now, as we simulated that client closed connection",
thread.isAlive(), is(false));
thread.join();
}
@Test(timeout = 10000)
public void whenAuthorizationChangedStreamClosed() throws NakadiException, InterruptedException, IOException {
final EventStreamConfig config = EventStreamConfig
.builder()
.withCursors(ImmutableList.of(NakadiCursor.of(TIMELINE, "0", "0")))
.withBatchLimit(1)
.withBatchTimeout(1)
.withConsumingClient(mock(Client.class))
.build();
final EventStream eventStream = new EventStream(
emptyConsumer(), mock(OutputStream.class), config, mock(BlacklistService.class), cursorConverter,
BYTES_FLUSHED_METER, writerProvider, kpiPublisher, kpiEventType, kpiFrequencyMs);
final AtomicBoolean triggerAuthChange = new AtomicBoolean(false);
final AtomicBoolean accessDeniedTriggered = new AtomicBoolean(false);
final Thread thread = new Thread(() -> {
try {
eventStream.streamEvents(new AtomicBoolean(true), () -> {
if (triggerAuthChange.getAndSet(false)) {
throw new AccessDeniedException(null, null);
}
});
} catch (final AccessDeniedException ex) {
accessDeniedTriggered.set(true);
}
});
thread.start();
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
waitFor(() -> Assert.assertTrue(thread.isAlive()));
// simulation of accessDenied
triggerAuthChange.set(true);
waitFor(() -> Assert.assertFalse(triggerAuthChange.get()), TimeUnit.SECONDS.toMillis(3));
triggerAuthChange.set(true);
waitFor(() -> Assert.assertFalse(thread.isAlive()), TimeUnit.SECONDS.toMillis(3));
assertThat("The thread should be dead now, as we simulated that client closed connection",
thread.isAlive(), is(false));
thread.join();
assertThat("Exception caught", accessDeniedTriggered.get());
assertThat("Threre should be only one call to check accessDenied", triggerAuthChange.get());
}
@Test(timeout = 5000)
public void whenStreamTimeoutIsSetThenStreamIsClosed() throws NakadiException, IOException, InterruptedException {
final EventStreamConfig config = EventStreamConfig
.builder()
.withBatchLimit(1)
.withStreamTimeout(1)
.withBatchTimeout(1)
.withCursors(new ArrayList<>())
.withConsumingClient(mock(Client.class))
.build();
final EventStream eventStream = new EventStream(
emptyConsumer(), mock(OutputStream.class), config, mock(BlacklistService.class), cursorConverter,
BYTES_FLUSHED_METER, writerProvider, kpiPublisher, kpiEventType, kpiFrequencyMs);
eventStream.streamEvents(new AtomicBoolean(true), () -> {
});
// if something goes wrong - the test should fail with a timeout
}
@Test(timeout = 3000)
public void whenStreamLimitIsSetThenStreamIsClosed() throws NakadiException, IOException, InterruptedException {
final EventStreamConfig config = EventStreamConfig
.builder()
.withCursors(ImmutableList.of(NakadiCursor.of(TIMELINE, "0", "0")))
.withBatchLimit(1)
.withStreamLimit(1)
.withConsumingClient(mock(Client.class))
.build();
final EventStream eventStream = new EventStream(endlessDummyConsumer(), mock(OutputStream.class), config,
mock(BlacklistService.class), cursorConverter, BYTES_FLUSHED_METER, writerProvider, kpiPublisher,
kpiEventType, kpiFrequencyMs);
eventStream.streamEvents(new AtomicBoolean(true), () -> {
});
// if something goes wrong - the test should fail with a timeout
}
@Test(timeout = 5000)
public void whenKeepAliveLimitIsSetThenStreamIsClosed() throws NakadiException, IOException, InterruptedException {
final EventStreamConfig config = EventStreamConfig
.builder()
.withCursors(ImmutableList.of(NakadiCursor.of(TIMELINE, "0", "0")))
.withBatchLimit(1)
.withBatchTimeout(1)
.withStreamKeepAliveLimit(1)
.withConsumingClient(mock(Client.class))
.build();
final EventStream eventStream = new EventStream(
emptyConsumer(), mock(OutputStream.class), config, mock(BlacklistService.class), cursorConverter,
BYTES_FLUSHED_METER, writerProvider, kpiPublisher, kpiEventType, kpiFrequencyMs);
eventStream.streamEvents(new AtomicBoolean(true), () -> {
});
// if something goes wrong - the test should fail with a timeout
}
@Test(timeout = 15000)
public void whenNoEventsToReadThenKeepAliveIsSent() throws NakadiException, IOException, InterruptedException {
final EventStreamConfig config = EventStreamConfig
.builder()
.withCursors(ImmutableList.of(NakadiCursor.of(TIMELINE, "0", "000000000000000000")))
.withBatchLimit(1)
.withBatchTimeout(1)
.withStreamTimeout(2)
.withConsumingClient(mock(Client.class))
.build();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final EventStream eventStream = new EventStream(
emptyConsumer(), out, config, mock(BlacklistService.class), cursorConverter, BYTES_FLUSHED_METER,
writerProvider, kpiPublisher, kpiEventType, kpiFrequencyMs);
eventStream.streamEvents(new AtomicBoolean(true), () -> {
});
final String[] batches = out.toString().split(BATCH_SEPARATOR);
Arrays
.stream(batches)
.forEach(batch ->
assertThat(batch, sameJSONAs(jsonBatch("0", "001-0000-000000000000000000", empty()))));
}
@Test(timeout = 10000)
public void whenBatchSizeIsSetThenGetEventsInBatches() throws NakadiException, IOException, InterruptedException {
final EventStreamConfig config = EventStreamConfig
.builder()
.withCursors(ImmutableList.of(NakadiCursor.of(TIMELINE, "0", String.format("%18d", 0))))
.withBatchLimit(5)
.withBatchTimeout(1)
.withStreamTimeout(1)
.withConsumingClient(mock(Client.class))
.build();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final EventStream eventStream = new EventStream(
nCountDummyConsumerForPartition(12, "0"), out, config, mock(BlacklistService.class),
cursorConverter, BYTES_FLUSHED_METER, writerProvider, kpiPublisher, kpiEventType, kpiFrequencyMs);
eventStream.streamEvents(new AtomicBoolean(true), () -> {
});
final String[] batches = out.toString().split(BATCH_SEPARATOR);
assertThat(batches, arrayWithSize(3));
assertThat(batches[0], sameJSONAs(jsonBatch("0", "001-0000-000000000000000000",
Optional.of(nCopies(5, new String(DUMMY))))));
assertThat(batches[1], sameJSONAs(jsonBatch("0", "001-0000-000000000000000000",
Optional.of(nCopies(5, new String(DUMMY))))));
assertThat(batches[2], sameJSONAs(jsonBatch("0", "001-0000-000000000000000000",
Optional.of(nCopies(2, new String(DUMMY))))));
}
@Test(timeout = 10000)
public void whenReadingEventsTheOrderIsCorrect() throws NakadiException, IOException, InterruptedException {
final EventStreamConfig config = EventStreamConfig
.builder()
.withCursors(ImmutableList.of(NakadiCursor.of(TIMELINE, "0", "0")))
.withBatchLimit(1)
.withStreamLimit(4)
.withConsumingClient(mock(Client.class))
.build();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final int eventNum = 4;
final LinkedList<ConsumedEvent> events = new LinkedList<>(IntStream
.range(0, eventNum)
.boxed()
.map(index -> new ConsumedEvent(
("event" + index).getBytes(UTF_8), NakadiCursor.of(TIMELINE, "0",
KafkaCursor.toNakadiOffset(index))))
.collect(Collectors.toList()));
final EventStream eventStream =
new EventStream(predefinedConsumer(events), out, config, mock(BlacklistService.class), cursorConverter,
BYTES_FLUSHED_METER, writerProvider, kpiPublisher, kpiEventType, kpiFrequencyMs);
eventStream.streamEvents(new AtomicBoolean(true), () -> {
});
final String[] batches = out.toString().split(BATCH_SEPARATOR);
assertThat(batches, arrayWithSize(eventNum));
IntStream
.range(0, eventNum)
.boxed()
.forEach(index -> assertThat(
batches[index],
sameJSONAs(jsonBatch(
"0", String.format("001-0000-%018d", index), Optional.of(nCopies(1, "event" + index))))
));
}
@Test(timeout = 10000)
public void whenReadFromMultiplePartitionsThenGroupedInBatchesAccordingToPartition()
throws NakadiException, IOException, InterruptedException {
final EventStreamConfig config = EventStreamConfig
.builder()
.withCursors(ImmutableList.of(
NakadiCursor.of(TIMELINE, "0", "000000000000000000"),
NakadiCursor.of(TIMELINE, "1", "000000000000000000"),
NakadiCursor.of(TIMELINE, "2", "000000000000000000")))
.withBatchLimit(2)
.withStreamLimit(6)
.withBatchTimeout(30)
.withConsumingClient(mock(Client.class))
.build();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final LinkedList<ConsumedEvent> events = new LinkedList<>();
events.add(new ConsumedEvent(DUMMY, NakadiCursor.of(TIMELINE, "0", "000000000000000000")));
events.add(new ConsumedEvent(DUMMY, NakadiCursor.of(TIMELINE, "1", "000000000000000000")));
events.add(new ConsumedEvent(DUMMY, NakadiCursor.of(TIMELINE, "2", "000000000000000000")));
events.add(new ConsumedEvent(DUMMY, NakadiCursor.of(TIMELINE, "0", "000000000000000000")));
events.add(new ConsumedEvent(DUMMY, NakadiCursor.of(TIMELINE, "1", "000000000000000000")));
events.add(new ConsumedEvent(DUMMY, NakadiCursor.of(TIMELINE, "2", "000000000000000000")));
final EventStream eventStream =
new EventStream(predefinedConsumer(events), out, config, mock(BlacklistService.class), cursorConverter,
BYTES_FLUSHED_METER, writerProvider, kpiPublisher, kpiEventType, kpiFrequencyMs);
eventStream.streamEvents(new AtomicBoolean(true), () -> {
});
final String[] batches = out.toString().split(BATCH_SEPARATOR);
assertThat(batches, arrayWithSize(3));
assertThat(batches[0], sameJSONAs(jsonBatch("0", "001-0000-000000000000000000",
Optional.of(nCopies(2, new String(DUMMY))))));
assertThat(batches[1], sameJSONAs(jsonBatch("1", "001-0000-000000000000000000",
Optional.of(nCopies(2, new String(DUMMY))))));
assertThat(batches[2], sameJSONAs(jsonBatch("2", "001-0000-000000000000000000",
Optional.of(nCopies(2, new String(DUMMY))))));
}
private static NakadiKafkaConsumer emptyConsumer() throws NakadiException {
final NakadiKafkaConsumer nakadiKafkaConsumer = mock(NakadiKafkaConsumer.class);
when(nakadiKafkaConsumer.readEvents()).thenReturn(Collections.emptyList());
return nakadiKafkaConsumer;
}
private static NakadiKafkaConsumer endlessDummyConsumerForPartition(final String partition) throws NakadiException {
final NakadiKafkaConsumer nakadiKafkaConsumer = mock(NakadiKafkaConsumer.class);
when(nakadiKafkaConsumer.readEvents())
.thenReturn(Collections.singletonList(
new ConsumedEvent(DUMMY, NakadiCursor.of(TIMELINE, partition, "0"))));
return nakadiKafkaConsumer;
}
private static NakadiKafkaConsumer nCountDummyConsumerForPartition(final int eventNum, final String partition)
throws NakadiException {
final NakadiKafkaConsumer nakadiKafkaConsumer = mock(NakadiKafkaConsumer.class);
final AtomicInteger eventsToCreate = new AtomicInteger(eventNum);
when(nakadiKafkaConsumer.readEvents()).thenAnswer(invocation -> {
if (eventsToCreate.get() > 0) {
eventsToCreate.set(eventsToCreate.get() - 1);
return Collections.singletonList(
new ConsumedEvent(DUMMY, NakadiCursor.of(TIMELINE, partition, "000000000000000000")));
} else {
return Collections.emptyList();
}
});
return nakadiKafkaConsumer;
}
private static NakadiKafkaConsumer predefinedConsumer(final List<ConsumedEvent> events)
throws NakadiException {
final NakadiKafkaConsumer nakadiKafkaConsumer = mock(NakadiKafkaConsumer.class);
final AtomicBoolean sent = new AtomicBoolean(false);
when(nakadiKafkaConsumer.readEvents()).thenAnswer(invocation -> {
if (sent.get()) {
return Collections.emptyList();
} else {
sent.set(true);
return events;
}
});
return nakadiKafkaConsumer;
}
private static NakadiKafkaConsumer endlessDummyConsumer() throws NakadiException {
return endlessDummyConsumerForPartition("0");
}
private static String jsonBatch(final String partition, final String offset,
final Optional<List<String>> eventsOrNone) {
return jsonBatch(partition, offset, eventsOrNone, Optional.empty());
}
private static String jsonBatch(final String partition, final String offset,
final Optional<List<String>> eventsOrNone, final Optional<String> metadata) {
final String eventsStr = eventsOrNone
.map(events -> {
final StringBuilder builder = new StringBuilder(",\"events\":[");
events.forEach(event -> builder.append("\"").append(event).append("\","));
builder.deleteCharAt(builder.length() - 1).append("]");
return builder.toString();
})
.orElse("");
final String metadataStr = metadata.map(m -> ",\"metadata\":{\"debug\":\"" + m + "\"}").orElse("");
return String.format("{\"cursor\":{\"partition\":\"%s\",\"offset\":\"%s\"}%s%s}", partition, offset, eventsStr,
metadataStr);
}
@SuppressWarnings("unchecked")
@Test
public void testWriteStreamEvent() {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final Cursor cursor = new Cursor("22", "000000000000000023");
final ArrayList<byte[]> events = Lists.newArrayList(
"{\"a\":\"b\"}".getBytes(),
"{\"c\":\"d\"}".getBytes(),
"{\"e\":\"f\"}".getBytes());
try {
writerProvider.getWriter().writeBatch(baos, cursor, events);
final Map<String, Object> batch =
TestUtils.OBJECT_MAPPER.readValue(baos.toString(), new TypeReference<Map<String, Object>>() {
});
final Map<String, String> cursorM = (Map<String, String>) batch.get("cursor");
assertEquals("22", cursorM.get("partition"));
assertEquals("000000000000000023", cursorM.get("offset"));
final List<Map<String, String>> eventsM = (List<Map<String, String>>) batch.get("events");
assertSame(eventsM.size(), 3);
// check the order is preserved as well as the data via get
assertEquals("b", eventsM.get(0).get("a"));
assertEquals("d", eventsM.get(1).get("c"));
assertEquals("f", eventsM.get(2).get("e"));
} catch (final IOException e) {
fail(e.getMessage());
}
}
@SuppressWarnings("unchecked")
@Test
public void testWriteStreamEventEmptyBatchProducesNoEventArray() {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final Cursor cursor = new Cursor("11", "000000000000000012");
final ArrayList<byte[]> events = Lists.newArrayList();
try {
writerProvider.getWriter().writeBatch(baos, cursor, events);
final String json = baos.toString();
assertEquals("{\"cursor\":{\"partition\":\"11\",\"offset\":\"000000000000000012\"}}\n", json);
final Map<String, Object> batch =
TestUtils.OBJECT_MAPPER.readValue(json, new TypeReference<Map<String, Object>>() {
});
final Map<String, String> cursorM = (Map<String, String>) batch.get("cursor");
assertEquals("11", cursorM.get("partition"));
assertEquals("000000000000000012", cursorM.get("offset"));
final List<Map<String, String>> eventsM = (List<Map<String, String>>) batch.get("events");
// expecting events not to be written as an empty array
assertNull(eventsM);
} catch (final IOException e) {
fail(e.getMessage());
}
}
@Test
public void testWriteStreamInfoWhenPresent() {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final SubscriptionCursor cursor = new SubscriptionCursor("11", "000000000000000012", "event-type", "token-id");
final ArrayList<ConsumedEvent> events = Lists.newArrayList(
new ConsumedEvent("{\"a\":\"b\"}".getBytes(), mock(NakadiCursor.class)));
try {
writerProvider.getWriter().writeSubscriptionBatch(baos, cursor, events, Optional.of("something"));
final JSONObject batch = new JSONObject(baos.toString());
final JSONObject cursorM = batch.getJSONObject("cursor");
assertEquals("11", cursorM.getString("partition"));
assertEquals("000000000000000012", cursorM.getString("offset"));
assertEquals("event-type", cursorM.getString("event_type"));
assertEquals("token-id", cursorM.getString("cursor_token"));
final JSONArray eventsM = batch.getJSONArray("events");
assertSame(eventsM.length(), 1);
assertEquals("something", batch.getJSONObject("info").getString("debug"));
} catch (final IOException e) {
fail(e.getMessage());
}
}
}
|
package uk.co.eluinhost.UltraHardcore.util;
import org.bukkit.Bukkit;
import org.bukkit.block.BlockFace;
public enum BlockFace2DVector{
NORTH(BlockFace.NORTH),
EAST(BlockFace.EAST),
SOUTH(BlockFace.SOUTH),
WEST(BlockFace.WEST),
NORTH_EAST(BlockFace.NORTH_EAST),
NORTH_NORTH_EAST(BlockFace.NORTH_NORTH_EAST),
EAST_NORTH_EAST(BlockFace.EAST_NORTH_EAST),
NORTH_WEST(BlockFace.NORTH_WEST),
NORTH_NORTH_WEST(BlockFace.NORTH_NORTH_WEST),
WEST_NORTH_WEST(BlockFace.WEST_NORTH_WEST),
SOUTH_EAST(BlockFace.SOUTH_EAST),
SOUTH_SOUTH_EAST(BlockFace.SOUTH_SOUTH_EAST),
EAST_SOUTH_EAST(BlockFace.EAST_SOUTH_EAST),
SOUTH_WEST(BlockFace.SOUTH_WEST),
SOUTH_SOUTH_WEST(BlockFace.SOUTH_SOUTH_WEST),
WEST_SOUTH_WEST(BlockFace.WEST_SOUTH_WEST);
private BlockFace bf;
private BlockFace2DVector(BlockFace bf) {
this.bf = bf;
}
public int getX() {
return -bf.getModX();
}
public int getZ() {
return bf.getModZ();
}
public BlockFace getBlockFace(){
return bf;
}
public double getAngle(){
return Math.atan2(this.getX(), this.getZ());
}
public static BlockFace getClosest(double look_angle){
Bukkit.getLogger().severe(""+look_angle);
BlockFace2DVector[] vectors = BlockFace2DVector.values();
BlockFace2DVector best = vectors[0];
double angle = Math.abs(best.getAngle());
for(BlockFace2DVector bfv : BlockFace2DVector.values()){
double a = look_angle-bfv.getAngle();
Bukkit.getLogger().severe(bfv.getBlockFace().toString()+" - "+a);
if(Math.abs(a) < angle){
best = bfv;
angle = Math.abs(a);
}
}
return best.getBlockFace();
}
}
|
package us.kbase.narrativejobservice.sdkjobs;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.WriteConcernException;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import us.kbase.auth.AuthConfig;
import us.kbase.auth.AuthException;
import us.kbase.auth.AuthToken;
import us.kbase.auth.ConfigurableAuthService;
import us.kbase.catalog.CatalogClient;
import us.kbase.catalog.ClientGroupConfig;
import us.kbase.catalog.ClientGroupFilter;
import us.kbase.catalog.LogExecStatsParams;
import us.kbase.catalog.ModuleVersion;
import us.kbase.catalog.SelectModuleVersion;
import us.kbase.common.executionengine.JobRunnerConstants;
import us.kbase.common.service.*;
import us.kbase.common.utils.AweUtils;
import us.kbase.common.utils.CondorUtils;
import us.kbase.common.utils.CountingOutputStream;
import us.kbase.narrativejobservice.CancelJobParams;
import us.kbase.narrativejobservice.CheckJobCanceledResult;
import us.kbase.narrativejobservice.CheckJobsParams;
import us.kbase.narrativejobservice.CheckJobsResults;
import us.kbase.narrativejobservice.FinishJobParams;
import us.kbase.narrativejobservice.GetJobLogsResults;
import us.kbase.narrativejobservice.JobState;
import us.kbase.narrativejobservice.JsonRpcError;
import us.kbase.narrativejobservice.LogLine;
import us.kbase.narrativejobservice.NarrativeJobServiceServer;
import us.kbase.narrativejobservice.RunJobParams;
import us.kbase.narrativejobservice.UpdateJobParams;
import us.kbase.narrativejobservice.db.ExecEngineMongoDb;
import us.kbase.narrativejobservice.db.ExecLog;
import us.kbase.narrativejobservice.db.ExecLogLine;
import us.kbase.narrativejobservice.db.ExecTask;
import us.kbase.narrativejobservice.db.SanitizeMongoObject;
import us.kbase.userandjobstate.*;
import us.kbase.workspace.GetObjectInfoNewParams;
import us.kbase.workspace.ObjectSpecification;
import us.kbase.workspace.WorkspaceClient;
public class SDKMethodRunner {
private final static DateTimeFormatter DATE_FORMATTER =
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZoneUTC();
public static final String APP_STATE_QUEUED = "queued";
public static final String APP_STATE_STARTED = "in-progress";
public static final String APP_STATE_DONE = "completed";
public static final String APP_STATE_ERROR = "suspend";
public static final String APP_STATE_CANCELLED = "cancelled";
public static final String APP_STATE_CANCELED = "canceled";
public static final String RELEASE = JobRunnerConstants.RELEASE;
public static final Set<String> RELEASE_TAGS =
JobRunnerConstants.RELEASE_TAGS;
public static final int MAX_LOG_LINE_LENGTH = 1000;
public static final String REQ_REL = "requested_release";
private static final int MAX_IO_BYTE_SIZE = JobRunnerConstants.MAX_IO_BYTE_SIZE;
private static AuthToken cachedCatalogAdminAuth = null;
private static AuthToken cachedAweAdminAuth = null;
private static ExecEngineMongoDb db = null;
public static String requestClientGroups(Map<String, String> config, String srvMethod)
throws UnauthorizedException, IOException, AuthException, JsonClientException {
String aweClientGroups = null;
String[] modMeth = srvMethod.split(Pattern.quote("."));
if (modMeth.length == 2) {
CatalogClient catCl = getCatalogClient(config, false);
List<ClientGroupConfig> ret = catCl.listClientGroupConfigs(
new ClientGroupFilter().withModuleName(modMeth[0]).withFunctionName(modMeth[1]));
if (ret != null && ret.size() == 1) {
ClientGroupConfig cgc = ret.get(0);
List<String> groupList = cgc.getClientGroups();
StringBuilder sb = new StringBuilder();
for (String group : groupList) {
if (sb.length() > 0)
sb.append(",");
sb.append(group);
}
aweClientGroups = sb.toString();
}
}
return aweClientGroups;
}
public static String runJob(RunJobParams params, AuthToken authPart,
String appJobId, Map<String, String> config, String aweClientGroups) throws Exception {
//perform sanity checks before creating job
checkWSObjects(authPart, config, params.getSourceWsObjects());
//need to update the params before transforming to a Map
checkModuleAndUpdateRunJobParams(params, config);
@SuppressWarnings("unchecked") final Map<String, Object> jobInput =
UObject.transformObjectToObject(params, Map.class);
checkObjectLength(jobInput, MAX_IO_BYTE_SIZE, "Input", null);
String kbaseEndpoint = config.get(NarrativeJobServiceServer.CFG_PROP_KBASE_ENDPOINT);
if (kbaseEndpoint == null) {
String wsUrl = config.get(NarrativeJobServiceServer.CFG_PROP_WORKSPACE_SRV_URL);
if (!wsUrl.endsWith("/ws"))
throw new IllegalStateException("Parameter " +
NarrativeJobServiceServer.CFG_PROP_KBASE_ENDPOINT +
" is not defined in configuration");
kbaseEndpoint = wsUrl.replace("/ws", "");
}
final UserAndJobStateClient ujsClient = getUjsClient(authPart, config);
final CreateJobParams cjp = new CreateJobParams()
.withMeta(params.getMeta());
if (params.getWsid() != null) {
cjp.withAuthstrat("kbaseworkspace")
.withAuthparam("" + params.getWsid());
}
String ujsJobId = ujsClient.createJob2(cjp);
// final String ujsJobId = ujsClient.createJob2(cjp);
String selfExternalUrl = config.get(NarrativeJobServiceServer.CFG_PROP_SELF_EXTERNAL_URL);
if (selfExternalUrl == null)
selfExternalUrl = kbaseEndpoint + "/njs_wrapper";
if (aweClientGroups == null || aweClientGroups.isEmpty())
aweClientGroups = config.get(NarrativeJobServiceServer.CFG_PROP_DEFAULT_AWE_CLIENT_GROUPS);
if (aweClientGroups == null || aweClientGroups.equals("*"))
aweClientGroups = "";
// Config switch to switch to calling new Condor Utils method submitToCondor
if (config.get(NarrativeJobServiceServer.CFG_PROP_CONDOR_MODE).equals("1")) {
System.out.println("UJS JOB ID FOR SUBMITTED JOB IS:" + ujsJobId);
HashMap<String, String> optClassAds = new HashMap<String, String>();
String[] modNameFuncName = params.getMethod().split(Pattern.quote("."));
optClassAds.put("kb_parent_job_id", params.getParentJobId());
optClassAds.put("kb_module_name", modNameFuncName[0]);
optClassAds.put("kb_function_name", modNameFuncName[0]);
optClassAds.put("kb_app_id", params.getAppId());
if (params.getWsid() != null) {
optClassAds.put("kb_wsid", "" + params.getWsid());
}
String baseDir = String.format("%s/%s/", config.get(NarrativeJobServiceServer.CFG_PROP_CONDOR_JOB_DATA_DIR), authPart.getUserName());
String newExternalURL = config.get(NarrativeJobServiceServer.CFG_PROP_SELF_EXTERNAL_URL);
String parentJobId = params.getParentJobId();
String schedulerType = "condor";
try {
String condorId = CondorUtils.submitToCondorCLI(ujsJobId, authPart, aweClientGroups, newExternalURL, baseDir, optClassAds, getCatalogAdminAuth(config));
saveTask(ujsJobId, condorId, jobInput, appJobId, schedulerType, parentJobId, config);
//Start job in UJS to become available in ujs.list_jobs2(ws)
try {
ujsClient.startJob(ujsJobId, authPart.getToken(),
APP_STATE_QUEUED,
APP_STATE_QUEUED, new InitProgress().withPtype("none"),
null);
} catch (ServerException se) {
// ignore and continue if the job was just started
}
} catch (Exception e) {
throw new IllegalStateException("Couldn't submit condor job: " + e);
}
} else {
String aweJobId = AweUtils.runTask(getAweServerURL(config), "ExecutionEngine", params.getMethod(), ujsJobId + " " + selfExternalUrl, NarrativeJobServiceServer.AWE_CLIENT_SCRIPT_NAME, authPart, aweClientGroups, getCatalogAdminAuth(config));
if (appJobId != null && appJobId.isEmpty()) appJobId = ujsJobId;
addAweTaskDescription(ujsJobId, aweJobId, jobInput, appJobId, config);
//CALL THIS AND LOOK INSIDE OF THE DOCUMENT
}
return ujsJobId;
}
private static AuthToken getCatalogAdminAuth(Map<String, String> config)
throws IOException, AuthException {
if (cachedCatalogAdminAuth == null) {
String adminUser = config.get(NarrativeJobServiceServer.CFG_PROP_CATALOG_ADMIN_USER);
if (adminUser != null && adminUser.trim().isEmpty()) {
adminUser = null;
}
String adminPwd = config.get(NarrativeJobServiceServer.CFG_PROP_CATALOG_ADMIN_PWD);
String adminToken = config.get(NarrativeJobServiceServer.CFG_PROP_CATALOG_ADMIN_TOKEN);
if (adminToken != null && adminToken.trim().isEmpty()) {
adminToken = null;
}
if (adminToken == null && adminUser == null) {
throw new IllegalStateException("Catalog admin credentials are not defined in " +
"configuration");
}
if (adminToken == null) {
cachedCatalogAdminAuth = getAuth(config).login(adminUser,
adminPwd == null ? "" : adminPwd).getToken();
} else {
cachedCatalogAdminAuth = getAuth(config).validateToken(adminToken);
}
}
return cachedCatalogAdminAuth;
}
private static void checkModuleAndUpdateRunJobParams(
final RunJobParams params,
final Map<String, String> config)
throws IOException, JsonClientException,
AuthException {
final String[] modMeth = params.getMethod().split("\\.");
if (modMeth.length != 2) {
throw new IllegalStateException("Illegal method name: " +
params.getMethod());
}
final String moduleName = modMeth[0];
CatalogClient catClient = getCatalogClient(config, false);
final String servVer;
if (params.getServiceVer() == null ||
params.getServiceVer().isEmpty()) {
servVer = RELEASE;
} else {
servVer = params.getServiceVer();
}
final ModuleVersion mv;
try {
mv = catClient.getModuleVersion(new SelectModuleVersion()
.withModuleName(moduleName)
.withVersion(servVer));
} catch (ServerException se) {
throw new IllegalArgumentException(String.format(
"Error looking up module %s with version %s: %s",
moduleName, servVer, se.getLocalizedMessage()));
}
params.setServiceVer(mv.getGitCommitHash());
params.setAdditionalProperties(REQ_REL,
RELEASE_TAGS.contains(servVer) ? servVer : null);
}
private static void checkWSObjects(
final AuthToken token,
final Map<String, String> config,
final List<String> objrefs)
throws UnauthorizedException, IOException, JsonClientException {
if (objrefs == null || objrefs.isEmpty()) {
return;
}
final String wsUrlstr = config.get(
NarrativeJobServiceServer.CFG_PROP_WORKSPACE_SRV_URL);
if (wsUrlstr == null || wsUrlstr.isEmpty())
throw new IllegalStateException("Parameter " +
NarrativeJobServiceServer.CFG_PROP_WORKSPACE_SRV_URL +
" is not defined in configuration");
final URL wsURL;
try {
wsURL = new URL(wsUrlstr);
} catch (MalformedURLException mue) {
throw new IllegalStateException("Config parameter " +
NarrativeJobServiceServer.CFG_PROP_WORKSPACE_SRV_URL +
" is invalid: " + wsUrlstr);
}
final WorkspaceClient wscli = new WorkspaceClient(wsURL, token);
final List<ObjectSpecification> ois =
new LinkedList<ObjectSpecification>();
for (final String obj : objrefs) {
ois.add(new ObjectSpecification().withRef(obj));
}
final List<Tuple11<Long, String, String, String, Long, String, Long,
String, String, Long, Map<String, String>>> objinfo;
try {
objinfo = wscli.getObjectInfoNew(new GetObjectInfoNewParams()
.withObjects(ois).withIgnoreErrors(1L));
} catch (ServerException se) {
if (se.getLocalizedMessage().indexOf(
"Error on ObjectIdentity") != -1) {
throw new ServerException(se.getLocalizedMessage().replace(
"ObjectIdentity", "workspace reference"),
se.getCode(), se.getName(), se.getData());
} else {
throw se;
}
}
final Set<String> inaccessible = new LinkedHashSet<String>();
for (int i = 0; i < objinfo.size(); i++) {
if (objinfo.get(i) == null) {
inaccessible.add(objrefs.get(i));
}
}
if (!inaccessible.isEmpty()) {
throw new IllegalArgumentException(String.format(
"The workspace objects %s either don't exist or were " +
"inaccessible to the user %s.",
inaccessible, token.getUserName()));
}
}
public static RunJobParams getJobInputParams(String ujsJobId, AuthToken auth,
Map<String, String> config, Map<String, String> resultConfig) throws Exception {
UserAndJobStateClient ujsClient = getUjsClient(auth, config);
ujsClient.getJobStatus(ujsJobId);
final RunJobParams input = getJobInput(ujsJobId, config);
if (resultConfig != null) {
String[] propsToSend = {
NarrativeJobServiceServer.CFG_PROP_WORKSPACE_SRV_URL,
NarrativeJobServiceServer.CFG_PROP_JOBSTATUS_SRV_URL,
NarrativeJobServiceServer.CFG_PROP_AWE_CLIENT_SCRATCH,
NarrativeJobServiceServer.CFG_PROP_DOCKER_REGISTRY_URL,
NarrativeJobServiceServer.CFG_PROP_AWE_CLIENT_DOCKER_URI,
NarrativeJobServiceServer.CFG_PROP_CATALOG_SRV_URL,
NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE,
NarrativeJobServiceServer.CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS,
NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL,
NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL_V2,
NarrativeJobServiceServer.CFG_PROP_TIME_BEFORE_EXPIRATION,
NarrativeJobServiceServer.CFG_PROP_JOB_TIMEOUT_MINUTES,
NarrativeJobServiceServer.CFG_PROP_DOCKER_JOB_TIMEOUT_SECONDS,
};
for (String key : propsToSend) {
String value = config.get(key);
if (value != null)
resultConfig.put(key, value);
}
String kbaseEndpoint = config.get(NarrativeJobServiceServer.CFG_PROP_KBASE_ENDPOINT);
if (kbaseEndpoint == null) {
String wsUrl = config.get(NarrativeJobServiceServer.CFG_PROP_WORKSPACE_SRV_URL);
if (!wsUrl.endsWith("/ws"))
throw new IllegalStateException("Parameter " +
NarrativeJobServiceServer.CFG_PROP_KBASE_ENDPOINT +
" is not defined in configuration");
kbaseEndpoint = wsUrl.replace("/ws", "");
}
resultConfig.put(NarrativeJobServiceServer.CFG_PROP_KBASE_ENDPOINT, kbaseEndpoint);
propagateConfigUrl(config, NarrativeJobServiceServer.CFG_PROP_SELF_EXTERNAL_URL,
resultConfig, kbaseEndpoint, "njs_wrapper");
propagateConfigUrl(config, NarrativeJobServiceServer.CFG_PROP_SHOCK_URL,
resultConfig, kbaseEndpoint, "shock-api");
propagateConfigUrl(config, NarrativeJobServiceServer.CFG_PROP_HANDLE_SRV_URL,
resultConfig, kbaseEndpoint, "handle_service");
propagateConfigUrl(config, NarrativeJobServiceServer.CFG_PROP_SRV_WIZ_URL,
resultConfig, kbaseEndpoint, "service_wizard");
resultConfig.put(JobRunnerConstants.CFG_PROP_EE_SERVER_VERSION,
NarrativeJobServiceServer.VERSION);
String authNotSecure = config.get(
NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM);
resultConfig.put(
NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM,
String.valueOf("true".equals(authNotSecure)));
}
return input;
}
private static void propagateConfigUrl(Map<String, String> config, String paramName,
Map<String, String> resultConfig, String endpointUrl, String optionalSuffix) {
String paramUrl = config.get(paramName);
if (paramUrl == null)
paramUrl = endpointUrl + "/" + optionalSuffix;
resultConfig.put(paramName, paramUrl);
}
public static List<String> updateJob(UpdateJobParams params, AuthToken auth,
Map<String, String> config) throws Exception {
String ujsJobId = params.getJobId();
UserAndJobStateClient ujsClient = getUjsClient(auth, config);
String jobOwner = ujsClient.getJobOwner(ujsJobId);
if (auth == null || !jobOwner.equals(auth.getUserName()))
throw new IllegalStateException("Only owner of the job can update it");
Tuple7<String, String, String, Long, String, Long, Long> jobStatus =
ujsClient.getJobStatus(ujsJobId);
if (params.getIsStarted() == null || params.getIsStarted() != 1L)
throw new IllegalStateException("Method is currently supported only for " +
"switching jobs into stated state");
List<String> ret = new ArrayList<String>();
final RunJobParams input = getJobInput(ujsJobId, config);
final String jobstage = jobStatus.getE2();
if ("started".equals(jobstage)) {
String message = String.format(
"Updating job status for %s from 'queued' to 'in-progress'",
ujsJobId);
ret.add(message);
List<LogLine> lines = new ArrayList<>();
lines.add(new LogLine().withLine(message).withIsError(0L));
addJobLogs(ujsJobId, lines, auth, config);
String tomorrow = DATE_FORMATTER.print(new DateTime().plusDays(1));
ujsClient.updateJob(ujsJobId, auth.getToken(), "in-progress", null);
//is this the fix???
updateTaskExecTime(ujsJobId, config, false);
return ret;
}
try {
ujsClient.startJob(ujsJobId, auth.getToken(), "in-progress",
"Execution engine job for " + input.getMethod(),
new InitProgress().withPtype("none"), null);
} catch (ServerException se) {
throw new IllegalStateException(String.format(
"Job %s couldn't be started and is in state " +
"%s. Server stacktrace:\n%s",
ujsJobId, jobstage, se.getData()), se);
}
updateTaskExecTime(ujsJobId, config, false);
return ret;
}
public static void finishJob(
final String ujsJobId,
final FinishJobParams params,
final AuthToken auth,
final ErrorLogger log,
final Map<String, String> config)
throws Exception {
if (params.getIsCanceled() == null && params.getIsCancelled() != null) {
params.setIsCanceled(params.getIsCancelled());
}
final UserAndJobStateClient ujsClient = getUjsClient(auth, config);
final Tuple7<String, String, String, Long, String, Long,
Long> jobStatus = ujsClient.getJobStatus(ujsJobId);
if (jobStatus.getE6() != null && jobStatus.getE6() == 1L) {
// Job was already done
final List<LogLine> lines = new ArrayList<LogLine>();
lines.add(new LogLine().withLine(
"Attempt to finish already completed job")
.withIsError(1L));
addJobLogs(ujsJobId, lines, auth, config);
return;
}
@SuppressWarnings("unchecked") final Map<String, Object> jobOutput =
UObject.transformObjectToObject(params, Map.class);
//should never trigger since the local method runner limits uploads to
//15k
checkObjectLength(jobOutput, MAX_IO_BYTE_SIZE, "Output", ujsJobId);
SanitizeMongoObject.sanitize(jobOutput);
// Updating UJS job state
if (params.getIsCanceled() != null &&
params.getIsCanceled() == 1L) {
// will throw an error here if user doesn't have rights to cancel
ujsClient.cancelJob(ujsJobId, "canceled by user");
getDb(config).addExecTaskResult(ujsJobId, jobOutput);
updateTaskExecTime(ujsJobId, config, true);
return;
}
final String jobOwner = ujsClient.getJobOwner(ujsJobId);
if (auth == null || !jobOwner.equals(auth.getUserName())) {
throw new IllegalStateException(
"Only the owner of a job can complete it");
}
getDb(config).addExecTaskResult(ujsJobId, jobOutput);
updateTaskExecTime(ujsJobId, config, true);
if (jobStatus.getE2().equals("created")) {
// job hasn't started yet. Need to put it in started state to
// complete it
try {
ujsClient.startJob(ujsJobId, auth.getToken(),
"starting job so that it can be finished",
"as state", new InitProgress().withPtype("none"),
null);
} catch (ServerException se) {
// ignore and continue if the job was just started
}
}
if (params.getError() != null) {
String status = params.getError().getMessage();
if (status == null)
status = "Unknown error";
if (status.length() > 200)
status = status.substring(0, 197) + "...";
ujsClient.completeJob(ujsJobId, auth.getToken(), status,
params.getError().getError(), null);
} else {
ujsClient.completeJob(ujsJobId, auth.getToken(), "done", null,
new Results());
}
// let's make a call to catalog sending execution stats
try {
final AppInfo info = getAppInfo(ujsJobId, config);
final RunJobParams input = getJobInput(ujsJobId, config);
String[] parts = input.getMethod().split(Pattern.quote("."));
String funcModuleName = parts.length > 1 ? parts[0] : null;
String funcName = parts.length > 1 ? parts[1] : parts[0];
String gitCommitHash = input.getServiceVer();
Long[] execTimes = getTaskExecTimes(ujsJobId, config);
long creationTime = execTimes[0];
long execStartTime = execTimes[1];
long finishTime = execTimes[2];
boolean isError = params.getError() != null;
String errorMessage = null;
try {
sendExecStatsToCatalog(auth.getUserName(), info.uiModuleName,
info.methodSpecId, funcModuleName, funcName,
gitCommitHash, creationTime, execStartTime, finishTime,
isError, ujsJobId, config);
} catch (ServerException ex) {
errorMessage = ex.getData();
if (errorMessage == null)
errorMessage = ex.getMessage();
if (errorMessage == null)
errorMessage = "Unknown server error";
} catch (Exception ex) {
errorMessage = ex.getMessage();
if (errorMessage == null)
errorMessage = "Unknown error";
}
if (errorMessage != null) {
String message = "Error sending execution stats to catalog (" +
auth.getUserName() + ", " + info.uiModuleName + ", " + info.methodSpecId +
", " + funcModuleName + ", " + funcName + ", " + gitCommitHash + ", " +
creationTime + ", " + execStartTime + ", " + finishTime + ", " + isError +
"): " + errorMessage;
System.err.println(message);
if (log != null)
log.logErr(message);
}
} catch (Exception ex) {
ex.printStackTrace();
if (log != null)
log.logErr(ex);
}
}
private static void sendExecStatsToCatalog(String userId, String uiModuleName,
String methodSpecId, String funcModuleName, String funcName, String gitCommitHash,
long creationTime, long execStartTime, long finishTime, boolean isError,
String jobId, Map<String, String> config) throws Exception {
CatalogClient catCl = getCatalogClient(config, true);
catCl.logExecStats(new LogExecStatsParams().withUserId(userId)
.withAppModuleName(uiModuleName).withAppId(methodSpecId)
.withFuncModuleName(funcModuleName).withFuncName(funcName)
.withGitCommitHash(gitCommitHash).withCreationTime(creationTime / 1000.0)
.withExecStartTime(execStartTime / 1000.0).withFinishTime(finishTime / 1000.0)
.withIsError(isError ? 1L : 0L).withJobId(jobId));
}
public static int addJobLogs(String ujsJobId, List<LogLine> lines,
AuthToken authPart, Map<String, String> config) throws Exception {
UserAndJobStateClient ujsClient = getUjsClient(authPart, config);
ujsClient.getJobStatus(ujsJobId);
ExecEngineMongoDb db = getDb(config);
ExecLog dbLog = db.getExecLog(ujsJobId);
if (dbLog == null) {
dbLog = new ExecLog();
dbLog.setUjsJobId(ujsJobId);
dbLog.setOriginalLineCount(0);
dbLog.setStoredLineCount(0);
dbLog.setLines(new ArrayList<ExecLogLine>());
db.insertExecLog(dbLog);
}
if (dbLog.getOriginalLineCount() > dbLog.getStoredLineCount()) {
// Error with out of space happened previously. So we just update line count.
db.updateExecLogOriginalLineCount(ujsJobId, dbLog.getOriginalLineCount() + lines.size());
return dbLog.getStoredLineCount();
}
int linePos = dbLog.getOriginalLineCount();
try {
int partSize = 1000;
int partCount = (lines.size() + partSize - 1) / partSize;
for (int i = 0; i < partCount; i++) {
int newLineCount = Math.min((i + 1) * partSize, lines.size());
List<ExecLogLine> dbLines = new ArrayList<ExecLogLine>();
for (int j = i * partSize; j < newLineCount; j++) {
LogLine line = lines.get(j);
String text = line.getLine();
if (text.length() > MAX_LOG_LINE_LENGTH)
text = text.substring(0, MAX_LOG_LINE_LENGTH - 3) + "...";
ExecLogLine dbLine = new ExecLogLine();
dbLine.setLinePos(linePos);
dbLine.setLine(text);
dbLine.setIsError((long) line.getIsError() == 1L);
dbLines.add(dbLine);
linePos++;
}
db.updateExecLogLines(ujsJobId, linePos, dbLines);
}
return linePos;
} catch (WriteConcernException ex) {
ex.getCode();
db.updateExecLogOriginalLineCount(ujsJobId, dbLog.getOriginalLineCount() + lines.size());
return dbLog.getStoredLineCount();
}
}
public static GetJobLogsResults getJobLogs(String ujsJobId, Long skipLines,
AuthToken authPart, Set<String> admins, Map<String, String> config) throws Exception {
boolean isAdmin = admins != null && admins.contains(authPart.getUserName());
if (!isAdmin) {
UserAndJobStateClient ujsClient = getUjsClient(authPart, config);
ujsClient.getJobStatus(ujsJobId);
}
ExecEngineMongoDb db = getDb(config);
ExecLog dbLog = db.getExecLog(ujsJobId);
List<LogLine> lines;
if (dbLog == null || (skipLines != null && dbLog.getStoredLineCount() <= skipLines)) {
lines = Collections.<LogLine>emptyList();
} else {
lines = new ArrayList<LogLine>();
int from = skipLines == null ? 0 : (int) (long) skipLines;
int count = dbLog.getStoredLineCount() - from;
for (ExecLogLine dbLine : db.getExecLogLines(ujsJobId, from, count)) {
lines.add(new LogLine().withLine(dbLine.getLine())
.withIsError(dbLine.getIsError() ? 1L : 0L));
}
}
return new GetJobLogsResults().withLines(lines)
.withLastLineNumber((long) lines.size() + (skipLines == null ? 0L : skipLines));
}
private static ConfigurableAuthService getAuth(Map<String, String> config)
throws IOException, AuthException {
String authUrl = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL);
String authAllowInsecure = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM);
try {
final AuthConfig c = new AuthConfig().withKBaseAuthServerURL(new URL(authUrl));
if ("true".equals(authAllowInsecure)) {
c.withAllowInsecureURLs(true);
}
return new ConfigurableAuthService(c);
} catch (URISyntaxException ex) {
throw new AuthException(ex.getMessage(), ex);
}
}
private static AuthToken getAweAdminAuth(Map<String, String> config)
throws IOException, AuthException {
if (cachedAweAdminAuth == null) {
String aweAdminUser = config.get(NarrativeJobServiceServer.CFG_PROP_AWE_READONLY_ADMIN_USER);
if (aweAdminUser != null && aweAdminUser.trim().isEmpty()) {
aweAdminUser = null;
}
String aweAdminPwd = config.get(NarrativeJobServiceServer.CFG_PROP_AWE_READONLY_ADMIN_PWD);
String aweAdminToken = config.get(NarrativeJobServiceServer.CFG_PROP_AWE_READONLY_ADMIN_TOKEN);
if (aweAdminToken != null && aweAdminToken.trim().isEmpty()) {
aweAdminToken = null;
}
if (aweAdminToken == null && aweAdminUser == null) {
throw new IllegalStateException("AWE admin creadentials are not defined in configuration");
}
// Use the config token if provided, otherwise generate one
// userid/password may be deprecated in the future
if (aweAdminToken == null) {
cachedAweAdminAuth = getAuth(config).login(aweAdminUser,
aweAdminPwd == null ? "" : aweAdminPwd).getToken();
} else {
cachedAweAdminAuth = getAuth(config).validateToken(aweAdminToken);
}
}
return cachedAweAdminAuth;
}
public static CheckJobCanceledResult checkJobCanceled(
final CancelJobParams params,
final AuthToken authPart,
final Map<String, String> config) throws Exception {
final String ujsUrl = config.get(NarrativeJobServiceServer.CFG_PROP_JOBSTATUS_SRV_URL);
if (params == null) {
throw new NullPointerException("No parameters supplied to method");
}
final String jobId = params.getJobId();
if (jobId == null || jobId.trim().isEmpty()) {
throw new IllegalArgumentException("No job id supplied");
}
final UserAndJobStateClient ujsClient = getUjsClient(authPart, config);
final Tuple7<String, String, String, Long, String, Long, Long> jobStatus =
ujsClient.getJobStatus(jobId);
return new CheckJobCanceledResult().withJobId(jobId).withUjsUrl(ujsUrl)
// null if job not started yet
.withFinished(jobStatus.getE6() == null ? 0 : jobStatus.getE6())
.withCanceled(APP_STATE_CANCELED.equals(jobStatus.getE2()) ? 1L : 0L);
}
public static String getJobState(String ujsJobId) throws Exception {
String jobState = CondorUtils.getJobState(ujsJobId);
int retries = 10;
if (jobState == null) {
while (retries > 0 && jobState == null) {
retries
jobState = CondorUtils.getJobState(ujsJobId);
}
}
if (jobState == null) {
return "unavailable";
}
switch (jobState) {
case "0":
return APP_STATE_QUEUED; //Maybe need to return a new state here?
case "1":
return APP_STATE_QUEUED; //Maybe need to return a new state here?
case "2":
return APP_STATE_STARTED;
case "3":
return APP_STATE_CANCELED;
case "4":
return APP_STATE_DONE;
case "5":
return APP_STATE_QUEUED; //Maybe need to return a new state here?
default:
return APP_STATE_ERROR;
}
}
@SuppressWarnings("unchecked")
public static JobState checkJob(String jobId, AuthToken authPart,
Map<String, String> config) throws Exception {
if (config.get(NarrativeJobServiceServer.CFG_PROP_CONDOR_MODE).equals("1")) {
return checkJobCondor(jobId, authPart, config);
} else {
return checkJobAwe(jobId, authPart, config);
}
}
@SuppressWarnings("unchecked")
public static List<JobState> listStatusByWorkspace(String workspace, AuthToken authPart,
Map<String, String> config) throws Exception {
List<JobState> js = new ArrayList<>();
UserAndJobStateClient ujsClient = getUjsClient(authPart, config);
List<String> authParams = new ArrayList<>();
authParams.add(workspace);
for (Tuple13<String, Tuple2<String, String>, String, String, String,
Tuple3<String, String, String>, Tuple3<Long, Long, String>,
Long, Long, Tuple2<String, String>, Map<String, String>,
String, Results> j : ujsClient.listJobs2(new ListJobsParams().withAuthstrat("kbaseworkspace").withAuthparams(authParams))) {
String jobId = j.getE1();
JobState njsJobState = checkJobCondor(jobId, authPart, config);
js.add(njsJobState);
}
return js;
}
@SuppressWarnings("unchecked")
public static JobState checkJobAwe(String jobId, AuthToken authPart,
Map<String, String> config) throws Exception {
String ujsUrl = config.get(NarrativeJobServiceServer.CFG_PROP_JOBSTATUS_SRV_URL);
JobState returnVal = new JobState().withJobId(jobId).withUjsUrl(ujsUrl);
String aweJobId = getAweTaskAweJobId(jobId, config);
returnVal.getAdditionalProperties().put("awe_job_id", aweJobId);
UserAndJobStateClient ujsClient = getUjsClient(authPart, config);
Tuple7<String, String, String, Long, String, Long, Long> jobStatus =
ujsClient.getJobStatus(jobId);
returnVal.setStatus(new UObject(jobStatus));
boolean complete = jobStatus.getE6() != null && jobStatus.getE6() == 1L;
FinishJobParams params = null;
if (complete) {
params = getJobOutput(jobId, authPart, config);
}
if (params == null) {
// We should consult AWE for case the job was killed or gone with no reason.
AuthToken aweAdminToken = getAweAdminAuth(config);
Map<String, Object> aweData = null;
String aweState = null;
String aweServerUrl = getAweServerURL(config);
try {
Map<String, Object> aweJob = AweUtils.getAweJobDescr(aweServerUrl, aweJobId,
aweAdminToken);
aweData = (Map<String, Object>) aweJob.get("data");
if (aweData != null) {
aweState = (String) aweData.get("state");
}
} catch (Exception ex) {
throw new IllegalStateException("Error checking AWE job (id=" + aweJobId + ") " +
"for ujs-id=" + jobId + " (" + ex.getMessage() + ")", ex);
}
if (aweState == null) {
final String aweDataStr = new ObjectMapper().writeValueAsString(aweData);
throw new IllegalStateException("Error checking AWE job (id=" + aweJobId + ") " +
"for ujs-id=" + jobId + " - state is null. AWE returned:\n " + aweDataStr);
}
if ((!aweState.equals("init")) && (!aweState.equals("queued")) &&
(!aweState.equals("in-progress"))) {
// Let's double-check, what if UJS job was marked as complete while we checked AWE?
jobStatus = ujsClient.getJobStatus(jobId);
complete = jobStatus.getE6() != null && jobStatus.getE6() == 1L;
if (complete) { // Yes, we are switching to "complete" scenario
returnVal.setStatus(new UObject(jobStatus));
params = getJobOutput(jobId, authPart, config);
} else {
if (aweState.equals("suspend")) {
throw new IllegalStateException("FATAL error in AWE job (" + aweState +
" for id=" + aweJobId + ")" + (jobStatus.getE2().equals("created") ?
" whereas job script wasn't started at all" : ""));
}
throw new IllegalStateException(String.format(
"Unexpected AWE job state: %s. Job id: %s. Awe job id: %s.",
aweState, jobId, aweJobId));
}
}
if (!complete) {
returnVal.getAdditionalProperties().put("awe_job_state", aweState);
returnVal.setFinished(0L);
String stage = jobStatus.getE2();
if (stage != null && stage.equals("started")) {
returnVal.setJobState(APP_STATE_STARTED);
} else {
returnVal.setJobState(APP_STATE_QUEUED);
try {
Map<String, Object> aweResp = AweUtils.getAweJobPosition(aweServerUrl,
aweJobId, aweAdminToken);
Map<String, Object> posData = (Map<String, Object>) aweResp.get("data");
if (posData != null && posData.containsKey("position"))
returnVal.setPosition(UObject.transformObjectToObject(posData.get("position"), Long.class));
} catch (Exception ignore) {
}
}
}
}
if (complete) {
boolean isCanceled = params.getIsCanceled() == null ? false :
(params.getIsCanceled() == 1L);
returnVal.setFinished(1L);
returnVal.setCanceled(isCanceled ? 1L : 0L);
// Next line is here for backward compatibility:
returnVal.setCancelled(isCanceled ? 1L : 0L);
returnVal.setResult(params.getResult());
returnVal.setError(params.getError());
if (params.getError() != null) {
returnVal.setJobState(APP_STATE_ERROR);
} else if (isCanceled) {
returnVal.setJobState(APP_STATE_CANCELLED);
} else {
returnVal.setJobState(APP_STATE_DONE);
}
}
Long[] execTimes = getTaskExecTimes(jobId, config);
if (execTimes != null) {
if (execTimes[0] != null)
returnVal.withCreationTime(execTimes[0]);
if (execTimes[1] != null)
returnVal.withExecStartTime(execTimes[1]);
if (execTimes[2] != null)
returnVal.withFinishTime(execTimes[2]);
}
return returnVal;
}
// public static List<JobState> checkWorkspaceJobs(String workspaceId, AuthToken authPart,
// Map<String, String> config) throws Exception{
// List<JobState> states = new ArrayList<>();
// UserAndJobStateClient ujsClient = getUjsClient(authPart, config);
// ListJobsParams p = new ListJobsParams().withAuthstrat("kbaseworkspace").withAuthparams();
// ujsClient.listJobs2()
// nar_jobs = clients.get('user_and_job_state').list_jobs2({
// 'authstrat': 'kbaseworkspace',
// 'authparams': [str(ws_id)]
@SuppressWarnings("unchecked")
public static JobState checkJobCondor(String jobId, AuthToken authPart,
Map<String, String> config) throws Exception {
String ujsUrl = config.get(NarrativeJobServiceServer.CFG_PROP_JOBSTATUS_SRV_URL);
JobState returnVal = new JobState().withJobId(jobId).withUjsUrl(ujsUrl);
UserAndJobStateClient ujsClient = getUjsClient(authPart, config);
Tuple7<String, String, String, Long, String, Long, Long> jobStatus =
ujsClient.getJobStatus(jobId);
// (1) parameter "last_update" of original type "timestamp" (A time in the format YYYY-MM-DDThh:mm:ssZ, where Z is the difference in time to UTC in the format +/-HHMM, eg: 2012-12-17T23:24:06-0500 (EST time) 2013-04-03T08:56:32+0000 (UTC time)),
// (2) parameter "stage" of original type "job_stage" (A string that describes the stage of processing of the job. One of 'created', 'started', 'completed', 'canceled' or 'error'.),
// (3) parameter "status" of original type "job_status" (A job status string supplied by the reporting service. No more than 200 characters.),
// (4) parameter "progress" of original type "total_progress" (The total progress of a job.),
// (5) parameter "est_complete" of original type "timestamp" (A time in the format YYYY-MM-DDThh:mm:ssZ, where Z is the difference in time to UTC in the format +/-HHMM, eg: 2012-12-17T23:24:06-0500 (EST time) 2013-04-03T08:56:32+0000 (UTC time)),
// (6) parameter "complete" of original type "boolean" (A boolean. 0 = false, other = true.),
// (7) parameter "error" of original type "boolean" (A boolean. 0 = false, other = true.)
String[] subJobs = getDb(config).getSubJobIds(jobId);
returnVal.getAdditionalProperties().put("sub_jobs", subJobs);
boolean complete = jobStatus.getE6() != null && jobStatus.getE6() == 1L;
FinishJobParams params = null;
if (complete) {
params = getJobOutput(jobId, authPart, config);
boolean isCanceled = params.getIsCanceled() == null ? false :
(params.getIsCanceled() == 1L);
returnVal.setFinished(1L);
returnVal.setCanceled(isCanceled ? 1L : 0L);
// Next line is here for backward compatibility:
returnVal.setCancelled(isCanceled ? 1L : 0L);
returnVal.setResult(params.getResult());
returnVal.setError(params.getError());
if (params.getError() != null) {
returnVal.setJobState(APP_STATE_ERROR);
} else if (isCanceled) {
returnVal.setJobState(APP_STATE_CANCELLED);
} else {
returnVal.setJobState(APP_STATE_DONE);
}
} else {
returnVal.setFinished(0L);
// (A string that describes the stage of processing of the job.
// One of 'created', 'started', 'completed', 'canceled' or 'error'.),
String currentStage = jobStatus.getE2();
//parameter "status" of original type "job_status"
// (A job status string supplied by the reporting service. No more than 200 characters.)
String currentStatus = jobStatus.getE3();
if (currentStatus.equals("running") || currentStatus.equals("in-progress")) {
returnVal.setJobState("in-progress");
returnVal.getAdditionalProperties().put("awe_job_state", "in-progress");
returnVal.getAdditionalProperties().put("job_state", "in-progress");
} else {
returnVal.setJobState(APP_STATE_QUEUED);
returnVal.getAdditionalProperties().put("awe_job_state", APP_STATE_QUEUED);
returnVal.getAdditionalProperties().put("job_state", APP_STATE_QUEUED);
}
}
// String stage = jobStatus.getE2();
// if (stage != null && stage.equals("started")) {
// returnVal.setJobState(APP_STATE_STARTED);
// returnVal.getAdditionalProperties().put("awe_job_state", APP_STATE_STARTED);
// } else {
// returnVal.setJobState(APP_STATE_QUEUED);
// returnVal.getAdditionalProperties().put("awe_job_state", APP_STATE_QUEUED);
// // Check job postion for queued jobs only
// returnVal.setPosition(UObject.transformObjectToObject(posData.get("position"), Long.class));
returnVal.setStatus(new UObject(jobStatus));
Long[] execTimes = getTaskExecTimes(jobId, config);
if (execTimes != null) {
if (execTimes[0] != null)
returnVal.withCreationTime(execTimes[0]);
if (execTimes[1] != null)
returnVal.withExecStartTime(execTimes[1]);
if (execTimes[2] != null)
returnVal.withFinishTime(execTimes[2]);
}
return returnVal;
}
public static CheckJobsResults checkJobs(CheckJobsParams params, AuthToken auth,
Map<String, String> config) throws Exception {
if (params.getJobIds() == null) {
throw new IllegalStateException("Input parameters should include 'job_ids' property");
}
boolean withJobParams = params.getWithJobParams() != null &&
params.getWithJobParams() == 1L;
Map<String, RunJobParams> jobParams = new LinkedHashMap<String, RunJobParams>();
Map<String, JsonRpcError> checkError = new LinkedHashMap<String, JsonRpcError>();
CheckJobsResults ret = new CheckJobsResults().withJobStates(
new LinkedHashMap<String, JobState>()).withCheckError(checkError);
for (String jobId : params.getJobIds()) {
try {
ret.getJobStates().put(jobId, checkJob(jobId, auth, config));
if (withJobParams) {
jobParams.put(jobId, getJobInputParams(jobId, auth, config, null));
}
} catch (Exception ex) {
JsonRpcError error = null;
if (ex instanceof ServerException) {
ServerException se = (ServerException)ex;
error = new JsonRpcError().withCode((long)se.getCode()).withName(se.getName())
.withMessage(se.getMessage()).withError(se.getData());
} else {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.close();
error = new JsonRpcError().withCode(-32603L)
.withName(ex.getClass().getSimpleName()).withMessage(ex.getMessage())
.withError(sw.toString());
}
checkError.put(jobId, error);
}
}
if (withJobParams) {
ret.withJobParams(jobParams);
}
return ret;
}
public static void cancelJob(CancelJobParams params, AuthToken auth,
Map<String, String> config) throws Exception {
FinishJobParams finishParams = new FinishJobParams().withIsCanceled(1L);
// Next line is here for backward compatibility:
finishParams.setIsCancelled(1L);
finishJob(params.getJobId(), finishParams, auth, null, config);
CondorUtils.condorRemoveJobRangeAsync(params.getJobId());
}
private static UserAndJobStateClient getUjsClient(AuthToken auth,
Map<String, String> config) throws Exception {
String jobSrvUrl = config.get(NarrativeJobServiceServer.CFG_PROP_JOBSTATUS_SRV_URL);
if (jobSrvUrl == null)
throw new IllegalStateException("Parameter '" +
NarrativeJobServiceServer.CFG_PROP_JOBSTATUS_SRV_URL +
"' is not defined in configuration");
UserAndJobStateClient ret = new UserAndJobStateClient(new URL(jobSrvUrl), auth);
ret.setIsInsecureHttpConnectionAllowed(true);
ret.setAllSSLCertificatesTrusted(true);
return ret;
}
private static String getAweServerURL(Map<String, String> config) throws Exception {
String aweUrl = config.get(NarrativeJobServiceServer.CFG_PROP_AWE_SRV_URL);
if (aweUrl == null)
throw new IllegalStateException("Parameter '" +
NarrativeJobServiceServer.CFG_PROP_AWE_SRV_URL +
"' is not defined in configuration");
return aweUrl;
}
public static CatalogClient getCatalogClient(Map<String, String> config,
boolean asAdmin)
throws UnauthorizedException, IOException,
AuthException {
final String catalogUrl = getRequiredConfigParam(config,
NarrativeJobServiceServer.CFG_PROP_CATALOG_SRV_URL);
final CatalogClient ret;
final URL catURL;
try {
catURL = new URL(catalogUrl);
} catch (MalformedURLException mue) {
throw new IllegalStateException("Config parameter " +
NarrativeJobServiceServer.CFG_PROP_CATALOG_SRV_URL +
" is invalid: " + catalogUrl);
}
if (asAdmin) {
ret = new CatalogClient(catURL, getCatalogAdminAuth(config));
} else {
ret = new CatalogClient(catURL);
}
ret.setIsInsecureHttpConnectionAllowed(true);
ret.setAllSSLCertificatesTrusted(true);
return ret;
}
private static String getRequiredConfigParam(Map<String, String> config, String param) {
String ret = config.get(param);
if (ret == null)
throw new IllegalStateException("Parameter '" + param +
"' is not defined in configuration");
return ret;
}
public static ExecEngineMongoDb getDb(Map<String, String> config) throws Exception {
if (db == null)
db = NarrativeJobServiceServer.getMongoDb(config);
return db;
}
private static void addAweTaskDescription(
final String ujsJobId,
final String aweJobId,
final Map<String, Object> jobInput,
final String appJobId,
final Map<String, String> config) throws Exception {
SanitizeMongoObject.sanitize(jobInput);
ExecEngineMongoDb db = getDb(config);
ExecTask dbTask = new ExecTask();
dbTask.setUjsJobId(ujsJobId);
dbTask.setAweJobId(aweJobId);
dbTask.setJobInput(jobInput);
dbTask.setCreationTime(System.currentTimeMillis());
dbTask.setAppJobId(appJobId);
db.insertExecTask(dbTask);
}
/**
* Saves state in mongodb to allow the job to communicate its status
* @param ujsJobId (UJS ID)
* @param jobId (Scheduler ID, such as condor job range)
* @param jobInput (Runjob Params)
* @param appJobId
* @param schedulerType (Scheduler Type, such as Condor or Awe)
* @param parentJobId (ID of Parent Job)
* @param config (Configuration File)
* @throws Exception
*/
private static void saveTask(
final String ujsJobId,
final String jobId,
final Map<String, Object> jobInput,
final String appJobId,
final String schedulerType,
final String parentJobId,
final Map<String, String> config) throws Exception {
SanitizeMongoObject.sanitize(jobInput);
ExecEngineMongoDb db = getDb(config);
ExecTask dbTask = new ExecTask();
dbTask.setUjsJobId(ujsJobId);
dbTask.setJobInput(jobInput);
dbTask.setCreationTime(System.currentTimeMillis());
dbTask.setAppJobId(appJobId);
dbTask.setSchdulerType(schedulerType);
dbTask.setTaskId(jobId);
dbTask.setParentJobId(parentJobId);
db.insertExecTask(dbTask);
}
private static ExecTask getTaskDescription(String ujsJobId, Map<String, String> config) throws Exception {
ExecEngineMongoDb db = getDb(config);
ExecTask dbTask = db.getExecTask(ujsJobId);
if (dbTask == null)
throw new IllegalStateException("AWE task wasn't found in DB for jobid=" + ujsJobId);
return dbTask;
}
private static String getAweTaskAweJobId(String ujsJobId, Map<String, String> config) throws Exception {
return getTaskDescription(ujsJobId, config).getAweJobId();
}
private static void updateTaskExecTime(String ujsJobId, Map<String, String> config, boolean finishTime) throws Exception {
ExecEngineMongoDb db = getDb(config);
ExecTask dbTask = db.getExecTask(ujsJobId);
Long prevTime = finishTime ? dbTask.getFinishTime() : dbTask.getExecStartTime();
if (prevTime == null)
db.updateExecTaskTime(ujsJobId, finishTime, System.currentTimeMillis());
}
private static Long[] getTaskExecTimes(String ujsJobId, Map<String, String> config) throws Exception {
ExecEngineMongoDb db = getDb(config);
ExecTask dbTask = db.getExecTask(ujsJobId);
if (dbTask == null)
return null;
return new Long[] {dbTask.getCreationTime(), dbTask.getExecStartTime(), dbTask.getFinishTime()};
}
private static void checkObjectLength(
final Map<String, Object> o,
final int max,
final String type,
final String jobId) {
final CountingOutputStream cos = new CountingOutputStream();
try {
//writes in UTF8
new ObjectMapper().writeValue(cos, o);
} catch (IOException ioe) {
throw new RuntimeException("something's broken", ioe);
} finally {
try {
cos.close();
} catch (IOException ioe) {
throw new RuntimeException("something's broken", ioe);
}
}
if (cos.getSize() > max) {
throw new IllegalArgumentException(String.format(
"%s parameters%s are above %sB maximum: %s",
type, jobId != null ? " for job ID " + jobId : "", max,
cos.getSize()));
}
}
private static RunJobParams getJobInput(
final String ujsJobId,
final Map<String, String> config)
throws Exception {
return getJobInput(getTaskDescription(ujsJobId, config));
}
private static RunJobParams getJobInput(
final ExecTask task)
throws Exception {
if (task.getJobInput() != null) {
SanitizeMongoObject.befoul(task.getJobInput());
return UObject.transformObjectToObject(task.getJobInput(),
RunJobParams.class);
}
throw new IllegalStateException("According to the database, the " +
"impossible occurred and a job was started without parameters");
}
private static FinishJobParams getJobOutput(
final String ujsJobId,
final AuthToken token,
final Map<String, String> config) throws Exception {
final ExecTask task = getTaskDescription(ujsJobId, config);
if (task.getJobOutput() != null) {
SanitizeMongoObject.befoul(task.getJobOutput());
FinishJobParams ret = UObject.transformObjectToObject(task.getJobOutput(),
FinishJobParams.class);
if (ret.getIsCanceled() == null && ret.getIsCancelled() != null) {
ret.setIsCanceled(ret.getIsCancelled());
}
return ret;
}
return null;
}
private static AppInfo getAppInfo(
final String ujsJobId,
final Map<String, String> config)
throws Exception {
ExecTask task = getTaskDescription(ujsJobId, config);
RunJobParams params = getJobInput(task);
String methodSpecId = params.getAppId();
String uiModuleName = null;
if (methodSpecId != null) {
String[] parts = methodSpecId.split("/");
if (parts.length > 1) {
uiModuleName = parts[0];
methodSpecId = parts[1];
}
}
return new AppInfo(uiModuleName, methodSpecId);
}
private static class AppInfo {
public final String uiModuleName;
public final String methodSpecId;
private AppInfo(String uiModuleName, String methodSpecId) {
this.uiModuleName = uiModuleName;
this.methodSpecId = methodSpecId;
}
}
}
|
package cgeo.geocaching.connector.gc;
import java.util.Locale;
import java.util.regex.Pattern;
public final class GCConstants {
static final String GC_URL = "http:
static final String GC_TILE_URL = "http://tiles.geocaching.com/";
/** Live Map */
public final static String URL_LIVE_MAP = GC_URL + "map/default.aspx";
/** Live Map pop-up */
public final static String URL_LIVE_MAP_DETAILS = GC_TILE_URL + "map.details";
/** Caches in a tile */
public final static String URL_MAP_INFO = GC_TILE_URL + "map.info";
/** Tile itself */
public final static String URL_MAP_TILE = GC_TILE_URL + "map.png";
/**
* Patterns for parsing the result of a (detailed) search
*/
public final static Pattern PATTERN_HINT = Pattern.compile("<div id=\"div_hint\"[^>]*>(.*?)</div>");
public final static Pattern PATTERN_DESC = Pattern.compile("<span id=\"ctl00_ContentBody_LongDescription\">(.*?)</span>\\s*</div>\\s*<p>\\s*</p>\\s*<p id=\"ctl00_ContentBody_hints\">");
public final static Pattern PATTERN_SHORTDESC = Pattern.compile("<span id=\"ctl00_ContentBody_ShortDescription\">(.*?)</span>\\s*</div>");
public final static Pattern PATTERN_GEOCODE = Pattern.compile("class=\"CoordInfoCode\">(GC[0-9A-Z]+)</span>");
public final static Pattern PATTERN_CACHEID = Pattern.compile("/seek/log\\.aspx\\?ID=(\\d+)");
public final static Pattern PATTERN_GUID = Pattern.compile(Pattern.quote("&wid=") + "([0-9a-z\\-]+)" + Pattern.quote("&"));
public final static Pattern PATTERN_SIZE = Pattern.compile("<div id=\"ctl00_ContentBody_size\" class=\"CacheSize[^\"]*\">[^<]*<p[^>]*>[^S]*Size[^:]*:[^<]*<span[^>]*>[^<]*<img src=\"[^\"]*/icons/container/[a-z_]+\\.gif\" alt=\"\\w+: ([^\"]+)\"[^>]*>[^<]*<small>[^<]*</small>[^<]*</span>[^<]*</p>");
public final static Pattern PATTERN_LATLON = Pattern.compile("<span id=\"uxLatLon\"[^>]*>(.*?)</span>");
public final static Pattern PATTERN_LATLON_ORIG = Pattern.compile("\\{\"isUserDefined\":true[^}]+?\"oldLatLngDisplay\":\"([^\"]+)\"\\}");
public final static Pattern PATTERN_LOCATION = Pattern.compile(Pattern.quote("<span id=\"ctl00_ContentBody_Location\">In ") + "(?:<a href=[^>]*>)?(.*?)<");
public final static Pattern PATTERN_PERSONALNOTE = Pattern.compile("<span id=\"cache_note\"[^>]*>(.*?)</span>", Pattern.DOTALL);
public final static Pattern PATTERN_NAME = Pattern.compile("<span id=\"ctl00_ContentBody_CacheName\">(.*?)</span>");
public final static Pattern PATTERN_DIFFICULTY = Pattern.compile("<span id=\"ctl00_ContentBody_uxLegendScale\"[^>]*>[^<]*<img src=\"[^\"]*/images/stars/stars([0-9_]+)\\.gif\"");
public final static Pattern PATTERN_TERRAIN = Pattern.compile("<span id=\"ctl00_ContentBody_Localize[\\d]+\"[^>]*>[^<]*<img src=\"[^\"]*/images/stars/stars([0-9_]+)\\.gif\"");
public final static Pattern PATTERN_OWNER_USERID = Pattern.compile("other caches <a href=\"/seek/nearest\\.aspx\\?u=(.*?)\">hidden</a> or");
public final static Pattern PATTERN_FOUND = Pattern.compile("ctl00_ContentBody_GeoNav_logText\">(Found It|Attended)");
public final static Pattern PATTERN_FOUND_ALTERNATIVE = Pattern.compile("<div class=\"StatusInformationWidget FavoriteWidget\"");
public final static Pattern PATTERN_FOUND_DATE = Pattern.compile(">Logged on: ([^<]+?)<");
public final static Pattern PATTERN_OWNER_DISPLAYNAME = Pattern.compile("<div id=\"ctl00_ContentBody_mcd1\">[^<]+<a href=\"[^\"]+\">([^<]+)</a>");
public final static Pattern PATTERN_TYPE = Pattern.compile("<img src=\"[^\"]*/WptTypes/\\d+\\.gif\" alt=\"([^\"]+?)\"[^>]*>");
public final static Pattern PATTERN_HIDDEN = Pattern.compile("<div id=\"ctl00_ContentBody_mcd2\">\\W*Hidden[\\s:]*([^<]+?)</div>");
public final static Pattern PATTERN_HIDDENEVENT = Pattern.compile("Event\\s*Date\\s*:\\s*([^<]+)<div id=\"calLinks\">", Pattern.DOTALL);
public final static Pattern PATTERN_FAVORITE = Pattern.compile("<div id=\"pnlFavoriteCache\">"); // without 'class="hideMe"' inside the tag !
public final static Pattern PATTERN_FAVORITECOUNT = Pattern.compile("<span class=\"favorite-value\">\\D*([0-9]+?)\\D*</span>");
public final static Pattern PATTERN_COUNTLOGS = Pattern.compile("<span id=\"ctl00_ContentBody_lblFindCounts\"><p(.+?)</p></span>");
public final static Pattern PATTERN_LOGBOOK = Pattern.compile("initalLogs = (\\{.+\\});"); // The "inital" typo really comes from gc.com site
/** Two groups ! */
public final static Pattern PATTERN_COUNTLOG = Pattern.compile("<img src=\"/images/logtypes/([0-9]+)\\.png\"[^>]+> (\\d*[,.]?\\d+)");
public static final Pattern PATTERN_PREMIUMMEMBERS = Pattern.compile("<p class=\"Warning NoBottomSpacing\">This is a Premium Member Only cache.</p>");
public final static Pattern PATTERN_ATTRIBUTES = Pattern.compile("Attributes\\s*</h3>[^<]*<div class=\"WidgetBody\">((?:[^<]*<img src=\"[^\"]+\" alt=\"[^\"]+\"[^>]*>)+?)[^<]*<p");
/** Two groups ! */
public final static Pattern PATTERN_ATTRIBUTESINSIDE = Pattern.compile("[^<]*<img src=\"([^\"]+)\" alt=\"([^\"]+?)\"");
public final static Pattern PATTERN_SPOILER_IMAGE = Pattern.compile("<a href=\"(http://imgcdn\\.geocaching\\.com[^.]+\\.(jpg|jpeg|png|gif))\"[^>]+>([^<]+)</a>(?:<br />([^<]+)<br /><br />)?");
public final static Pattern PATTERN_INVENTORY = Pattern.compile("<span id=\"ctl00_ContentBody_uxTravelBugList_uxInventoryLabel\">\\W*Inventory[^<]*</span>[^<]*</h3>[^<]*<div class=\"WidgetBody\">([^<]*<ul>(([^<]*<li>[^<]*<a href=\"[^\"]+\"[^>]*>[^<]*<img src=\"[^\"]+\"[^>]*>[^<]*<span>[^<]+<\\/span>[^<]*<\\/a>[^<]*<\\/li>)+)[^<]*<\\/ul>)?");
public final static Pattern PATTERN_INVENTORYINSIDE = Pattern.compile("[^<]*<li>[^<]*<a href=\"[a-z0-9\\-\\_\\.\\?\\/\\:\\@]*\\/track\\/details\\.aspx\\?guid=([0-9a-z\\-]+)[^\"]*\"[^>]*>[^<]*<img src=\"[^\"]+\"[^>]*>[^<]*<span>([^<]+)<\\/span>[^<]*<\\/a>[^<]*<\\/li>");
public final static Pattern PATTERN_WATCHLIST = Pattern.compile(Pattern.quote("watchlist.aspx") + ".{1,50}" + Pattern.quote("action=rem"));
// Info box top-right
public static final Pattern PATTERN_LOGIN_NAME = Pattern.compile("\"SignedInProfileLink\">([^<]+)</a>");
public static final Pattern PATTERN_MEMBER_STATUS = Pattern.compile("<span id=\"ctl00_litPMLevel\">([^<]+)</span>");
public static final String MEMBER_STATUS_RENEW = "<a id=\"ctl00_hlRenew";
public static final String MEMBER_STATUS_PM = "Premium Member";
/** Use replaceAll("[,.]","") on the resulting string before converting to an int */
public static final Pattern PATTERN_CACHES_FOUND = Pattern.compile("<strong[^>]*>.*?([\\d,.]+) Caches? Found", Pattern.DOTALL);
public static final Pattern PATTERN_AVATAR_IMAGE_PROFILE_PAGE = Pattern.compile("<img src=\"(http://img.geocaching.com/user/avatar/[0-9a-f-]+\\.jpg)\"[^>]*\\salt=\"Avatar\"");
public static final Pattern PATTERN_LOGIN_NAME_LOGIN_PAGE = Pattern.compile("ctl00_ContentBody_lbUsername\">.*<strong>(.*)</strong>");
public static final Pattern PATTERN_CUSTOMDATE = Pattern.compile("<option selected=\"selected\" value=\"([ /Mdy-]+)\">");
/**
* Patterns for parsing trackables
*/
public final static Pattern PATTERN_TRACKABLE_GUID = Pattern.compile("<a id=\"ctl00_ContentBody_lnkPrint\" title=\"[^\"]*\" href=\".*sheet\\.aspx\\?guid=([a-z0-9\\-]+)\"[^>]*>[^<]*</a>");
public final static Pattern PATTERN_TRACKABLE_GEOCODE = Pattern.compile("<strong>(TB[0-9A-Z]+)[^<]*</strong> to reference this item.");
// multiple error codes, depending on the search term for the trackable code
public final static String ERROR_TB_DOES_NOT_EXIST = "does not exist in the system";
public final static String ERROR_TB_ELEMENT_EXCEPTION = "ElementNotFound Exception";
public final static String ERROR_TB_ARITHMETIC_OVERFLOW = "operation resulted in an overflow";
public final static String ERROR_TB_NOT_ACTIVATED = "hasn't been activated";
/**
* some parts of the webpage don't correctly encode the name, therefore this pattern must be checked with a
* trackable name that needs HTML encoding
*/
public final static Pattern PATTERN_TRACKABLE_NAME = Pattern.compile("name=\"og:title\" content=\"([^\"]+)\"");
/** Two groups ! */
public final static Pattern PATTERN_TRACKABLE_OWNER = Pattern.compile("<dt>\\W*Owner:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugOwner\" title=\"[^\"]*\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">([^<]+)<\\/a>[^<]*</dd>");
public final static Pattern PATTERN_TRACKABLE_RELEASES = Pattern.compile("<dt>\\W*Released:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugReleaseDate\">([^<]+)<\\/span>[^<]*</dd>");
public final static Pattern PATTERN_TRACKABLE_ORIGIN = Pattern.compile("<dt>\\W*Origin:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugOrigin\">([^<]+)<\\/span>[^<]*</dd>");
/** Two groups ! */
public final static Pattern PATTERN_TRACKABLE_SPOTTEDCACHE = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" title=\"[^\"]*\" href=\"[^\"]*/seek/cache_details.aspx\\?guid=([a-z0-9\\-]+)\">In ([^<]+)</a>[^<]*</dd>");
/** Two groups ! */
public final static Pattern PATTERN_TRACKABLE_SPOTTEDUSER = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">In the hands of ([^<]+).</a>[^<]*</dd>");
public final static Pattern PATTERN_TRACKABLE_SPOTTEDUNKNOWN = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">Unknown Location[^<]*</a>[^<]*</dd>");
public final static Pattern PATTERN_TRACKABLE_SPOTTEDOWNER = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">In the hands of the owner[^<]*</a>[^<]*</dd>");
public final static Pattern PATTERN_TRACKABLE_GOAL = Pattern.compile("<div id=\"TrackableGoal\">[^<]*<p>(.*?)</p>[^<]*</div>", Pattern.DOTALL);
/** Four groups */
public final static Pattern PATTERN_TRACKABLE_DETAILSIMAGE = Pattern.compile("<h3>\\W*About This Item[^<]*</h3>[^<]*<div id=\"TrackableDetails\">([^<]*<p>([^<]*<img id=\"ctl00_ContentBody_BugDetails_BugImage\" class=\"[^\"]+\" src=\"([^\"]+)\"[^>]*>)?[^<]*</p>)?[^<]*<p[^>]*>(.*)</p>[^<]*</div> <div id=\"ctl00_ContentBody_BugDetails_uxAbuseReport\">");
public final static Pattern PATTERN_TRACKABLE_ICON = Pattern.compile("<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"([^\"]+)\"[^>]*>");
public final static Pattern PATTERN_TRACKABLE_TYPE = Pattern.compile("<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"[^\"]+\" alt=\"([^\"]+)\"[^>]*>");
public final static Pattern PATTERN_TRACKABLE_DISTANCE = Pattern.compile("<h4[^>]*\\W*Tracking History \\(([0-9.,]+(km|mi))[^\\)]*\\)");
public final static Pattern PATTERN_TRACKABLE_LOG = Pattern.compile("<tr class=\"Data BorderTop .+?/images/logtypes/([^.]+)\\.png[^>]+> ([^<]+)</td>.+?guid.+?>([^<]+)</a>.+?(?:guid=([^\"]+)\">(<span[^>]+>)?([^<]+)</.+?)?<td colspan=\"4\">\\s*<div>(.*?)</div>\\s*(?:<ul.+?ul>)?\\s*</td>\\s*</tr>");
public final static Pattern PATTERN_TRACKABLE_LOG_IMAGES = Pattern.compile("<li><a href=\"([^\"]+)\".+?LogImgTitle.+?>([^<]+)</");
/**
* Patterns for parsing the result of a search (next)
*/
public final static Pattern PATTERN_SEARCH_TYPE = Pattern.compile("<td class=\"Merge\">.*?<img src=\"[^\"]*/images/wpttypes/[^.]+\\.gif\" alt=\"([^\"]+)\" title=\"[^\"]+\"[^>]*>[^<]*</a>");
public final static Pattern PATTERN_SEARCH_GUIDANDDISABLED = Pattern.compile("SearchResultsWptType.*?<a href=\"[^\"]*\" class=\"lnk ([^\"]*)\"><span>([^<]*)</span>[^|]*[|][^|]*[|]([^<]*)<");
/** Two groups **/
public final static Pattern PATTERN_SEARCH_TRACKABLES = Pattern.compile("<a id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxTravelBugList\" class=\"tblist\" data-tbcount=\"([0-9]+)\" data-id=\"[^\"]*\"[^>]*>(.*)</a>");
/** Second group used */
public final static Pattern PATTERN_SEARCH_TRACKABLESINSIDE = Pattern.compile("(<img src=\"[^\"]+\" alt=\"([^\"]+)\" title=\"[^\"]*\" />[^<]*)");
public final static Pattern PATTERN_SEARCH_DIRECTION_DISTANCE = Pattern.compile("<img src=\"/images/icons/compass/([^\\.]+)\\.gif\"[^>]*>[^<]*<br />([^<]+)</span>");
public final static Pattern PATTERN_SEARCH_DIFFICULTY_TERRAIN = Pattern.compile("<span class=\"small\">([0-5]([\\.,]5)?)/([0-5]([\\.,]5)?)</span><br />");
public final static Pattern PATTERN_SEARCH_CONTAINER = Pattern.compile("<img src=\"/images/icons/container/([^\\.]+)\\.gif\"");
public final static Pattern PATTERN_SEARCH_GEOCODE = Pattern.compile("\\|\\W*(GC[0-9A-Z]+)[^\\|]*\\|");
public final static Pattern PATTERN_SEARCH_ID = Pattern.compile("name=\"CID\"[^v]*value=\"(\\d+)\"");
public final static Pattern PATTERN_SEARCH_FAVORITE = Pattern.compile("favorite-rank\">([0-9,.]+)</span>");
public final static Pattern PATTERN_SEARCH_TOTALCOUNT = Pattern.compile("<span>Total Records\\D*(\\d+)<");
public final static Pattern PATTERN_SEARCH_RECAPTCHA = Pattern.compile("<script[^>]*src=\"[^\"]*/recaptcha/api/challenge\\?k=([^\"]+)\"[^>]*>");
public final static Pattern PATTERN_SEARCH_RECAPTCHACHALLENGE = Pattern.compile("challenge : '([^']+)'");
public final static Pattern PATTERN_SEARCH_HIDDEN_DATE = Pattern.compile("<td valign=\"top\"[^<]+<span class=\"small\">([^<]+)</span>");
/**
* Patterns for waypoints
*/
public final static Pattern PATTERN_WPTYPE = Pattern.compile("\\/wpttypes\\/sm\\/(.+)\\.jpg");
public final static Pattern PATTERN_WPPREFIXORLOOKUPORLATLON = Pattern.compile(">([^<]*<[^>]+>)?([^<]+)(<[^>]+>[^<]*)?<\\/td>");
public final static Pattern PATTERN_WPNAME = Pattern.compile(">[^<]*<a[^>]+>([^<]*)<\\/a>");
public final static Pattern PATTERN_WPNOTE = Pattern.compile("colspan=\"6\">(.*)<\\/td>");
/**
* Patterns for different purposes
*/
/** replace linebreak and paragraph tags */
public final static Pattern PATTERN_LINEBREAK = Pattern.compile("<(br|p)[^>]*>");
public final static Pattern PATTERN_TYPEBOX = Pattern.compile("<select name=\"ctl00\\$ContentBody\\$LogBookPanel1\\$ddLogType\" id=\"ctl00_ContentBody_LogBookPanel1_ddLogType\"[^>]*>"
+ "(([^<]*<option[^>]*>[^<]+</option>)+)[^<]*</select>", Pattern.CASE_INSENSITIVE);
public final static Pattern PATTERN_TYPE2 = Pattern.compile("<option( selected=\"selected\")? value=\"(\\d+)\">[^<]+</option>", Pattern.CASE_INSENSITIVE);
// FIXME: pattern is over specified
public final static Pattern PATTERN_TRACKABLE = Pattern.compile("<tr id=\"ctl00_ContentBody_LogBookPanel1_uxTrackables_repTravelBugs_ctl[0-9]+_row\"[^>]*>"
+ "[^<]*<td>[^<]*<a href=\"[^\"]+\">([A-Z0-9]+)</a>[^<]*</td>[^<]*<td>([^<]+)</td>[^<]*<td>"
+ "[^<]*<select name=\"ctl00\\$ContentBody\\$LogBookPanel1\\$uxTrackables\\$repTravelBugs\\$ctl([0-9]+)\\$ddlAction\"[^>]*>"
+ "([^<]*<option value=\"([0-9]+)(_[a-z]+)?\">[^<]+</option>)+"
+ "[^<]*</select>[^<]*</td>[^<]*</tr>", Pattern.CASE_INSENSITIVE);
public final static Pattern PATTERN_MAINTENANCE = Pattern.compile("<span id=\"ctl00_ContentBody_LogBookPanel1_lbConfirm\"[^>]*>([^<]*<font[^>]*>)?([^<]+)(</font>[^<]*)?</span>", Pattern.CASE_INSENSITIVE);
public final static Pattern PATTERN_OK1 = Pattern.compile("<h2[^>]*>[^<]*<span id=\"ctl00_ContentBody_lbHeading\"[^>]*>[^<]*</span>[^<]*</h2>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
public final static Pattern PATTERN_OK2 = Pattern.compile("<div id=[\"|']ctl00_ContentBody_LogBookPanel1_ViewLogPanel[\"|']>", Pattern.CASE_INSENSITIVE);
public final static Pattern PATTERN_IMAGE_UPLOAD_URL = Pattern.compile("title=\"Click for Larger Image\"\\s*src=\"(.*?)\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
public final static Pattern PATTERN_VIEWSTATEFIELDCOUNT = Pattern.compile("id=\"__VIEWSTATEFIELDCOUNT\"[^(value)]+value=\"(\\d+)\"[^>]+>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
public final static Pattern PATTERN_VIEWSTATES = Pattern.compile("id=\"__VIEWSTATE(\\d*)\"[^(value)]+value=\"([^\"]+)\"[^>]+>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
public final static Pattern PATTERN_USERTOKEN = Pattern.compile("userToken\\s*=\\s*'([^']+)'");
/** Live Map since 14.02.2012 */
public final static Pattern PATTERN_USERSESSION = Pattern.compile("UserSession\\('([^']+)'");
public final static Pattern PATTERN_SESSIONTOKEN = Pattern.compile("sessionToken:'([^']+)'");
public final static Pattern PATTERN_LOG_IMAGE_UPLOAD = Pattern.compile("/seek/upload\\.aspx\\?LID=(\\d+)", Pattern.CASE_INSENSITIVE);
public final static String STRING_PREMIUMONLY_2 = "Sorry, the owner of this listing has made it viewable to Premium Members only.";
public final static String STRING_PREMIUMONLY_1 = "has chosen to make this cache listing visible to Premium Members only.";
public final static String STRING_UNPUBLISHED_OWNER = "cache has not been published yet";
public final static String STRING_UNPUBLISHED_OTHER = "you cannot view this cache listing until it has been published";
public final static String STRING_UNPUBLISHED_FROM_SEARCH = "UnpublishedCacheSearchWidget";
public final static String STRING_UNKNOWN_ERROR = "An Error Has Occurred";
public final static String STRING_DISABLED = "<li>This cache is temporarily unavailable.";
public final static String STRING_ARCHIVED = "<li>This cache has been archived,";
public final static String STRING_CACHEDETAILS = "id=\"cacheDetails\"";
/** Number of logs to retrieve from GC.com */
public final static int NUMBER_OF_LOGS = 35;
private final static String SEQUENCE_GCID = "0123456789ABCDEFGHJKMNPQRTVWXYZ";
private final static long GC_BASE31 = 31;
private final static long GC_BASE16 = 16;
public static long gccodeToGCId(final String gccode) {
long base = GC_BASE31;
final String geocodeWO = gccode.substring(2).toUpperCase(Locale.US);
if ((geocodeWO.length() < 4) || (geocodeWO.length() == 4 && SEQUENCE_GCID.indexOf(geocodeWO.charAt(0)) < 16)) {
base = GC_BASE16;
}
long gcid = 0;
for (int p = 0; p < geocodeWO.length(); p++) {
gcid = base * gcid + SEQUENCE_GCID.indexOf(geocodeWO.charAt(p));
}
if (base == GC_BASE31) {
gcid += Math.pow(16, 4) - 16 * Math.pow(31, 3);
}
return gcid;
}
private GCConstants() {
// this class shall not have instances
}
}
|
package cgeo.geocaching.connector.gc;
import cgeo.geocaching.Geocache;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.settings.Settings;
import android.graphics.Bitmap;
/**
* icon decoder for cache icons
*
*/
final class IconDecoder {
private static final int CT_TRADITIONAL = 0;
private static final int CT_MULTI = 1;
private static final int CT_MYSTERY = 2;
private static final int CT_EVENT = 3;
private static final int CT_EARTH = 4;
private static final int CT_FOUND = 5;
private static final int CT_OWN = 6;
private static final int CT_MEGAEVENT = 7;
private static final int CT_CITO = 8;
private static final int CT_WEBCAM = 9;
private static final int CT_WHERIGO = 10;
private static final int CT_VIRTUAL = 11;
private static final int CT_LETTERBOX = 12;
private IconDecoder() {
throw new IllegalStateException("utility class");
}
static boolean parseMapPNG(final Geocache cache, final Bitmap bitmap, final UTFGridPosition xy, final int zoomlevel) {
final int topX = xy.getX() * 4;
final int topY = xy.getY() * 4;
final int bitmapWidth = bitmap.getWidth();
final int bitmapHeight = bitmap.getHeight();
if ((topX < 0) || (topY < 0) || (topX + 4 > bitmapWidth) || (topY + 4 > bitmapHeight)) {
return false; //out of image position
}
int numberOfDetections = 7; //for level 12 and 13
if (zoomlevel < 12) {
numberOfDetections = 5;
}
if (zoomlevel > 13) {
numberOfDetections = 13;
}
final int[] pngType = new int[numberOfDetections];
for (int x = topX; x < topX + 4; x++) {
for (int y = topY; y < topY + 4; y++) {
final int color = bitmap.getPixel(x, y);
if ((color >>> 24) != 255) {
continue; //transparent pixels (or semi_transparent) are only shadows of border
}
final int r = (color & 0xFF0000) >> 16;
final int g = (color & 0xFF00) >> 8;
final int b = color & 0xFF;
if (isPixelDuplicated(r, g, b, zoomlevel)) {
continue;
}
final int type;
if (zoomlevel < 12) {
type = getCacheTypeFromPixel11(r, g, b);
} else {
if (zoomlevel > 13) {
type = getCacheTypeFromPixel14(r, g, b);
} else {
type = getCacheTypeFromPixel13(r, g, b);
}
}
pngType[type]++;
}
}
int type = -1;
int count = 0;
for (int x = 0; x < pngType.length; x++) {
if (pngType[x] > count) {
count = pngType[x];
type = x;
}
}
if (count > 1) { // 2 pixels need to detect same type and we say good to go
switch (type) {
case CT_TRADITIONAL:
cache.setType(CacheType.TRADITIONAL, zoomlevel);
return true;
case CT_MULTI:
cache.setType(CacheType.MULTI, zoomlevel);
return true;
case CT_MYSTERY:
cache.setType(CacheType.MYSTERY, zoomlevel);
return true;
case CT_EVENT:
cache.setType(CacheType.EVENT, zoomlevel);
return true;
case CT_EARTH:
cache.setType(CacheType.EARTH, zoomlevel);
return true;
case CT_FOUND:
cache.setFound(true);
return true;
case CT_OWN:
cache.setOwnerUserId(Settings.getUsername());
return true;
case CT_MEGAEVENT:
cache.setType(CacheType.MEGA_EVENT, zoomlevel);
return true;
case CT_CITO:
cache.setType(CacheType.CITO, zoomlevel);
return true;
case CT_WEBCAM:
cache.setType(CacheType.WEBCAM, zoomlevel);
return true;
case CT_WHERIGO:
cache.setType(CacheType.WHERIGO, zoomlevel);
return true;
case CT_VIRTUAL:
cache.setType(CacheType.VIRTUAL, zoomlevel);
return true;
case CT_LETTERBOX:
cache.setType(CacheType.LETTERBOX, zoomlevel);
return true;
}
}
return false;
}
/**
* A method that returns true if pixel color appears on more then one cache type and shall be excluded from parsing
*
* @param r
* red value
* @param g
* green value
* @param b
* blue value
* @param zoomlevel
* zoom level of map
* @return true if parsing should not be performed
*/
private static boolean isPixelDuplicated(final int r, final int g, final int b, final int zoomlevel) {
if (zoomlevel < 12) {
if (((r == g) && (g == b)) || ((r == 233) && (g == 233) && (b == 234))) {
return true;
}
return false;
}
if (zoomlevel > 13) {
if ((r == g) && (g == b)) {
if ((r == 119) || (r == 231) || (r == 5) || (r == 230) || (r == 244) || (r == 93) || (r == 238) || (r == 73) || (r == 9) || (r == 225) || (r == 162) || (r == 153) || (r == 32) ||
(r == 50) || (r == 20) || (r == 232) || (r == 224) || (r == 192) || (r == 248) || (r == 152) || (r == 128) || (r == 176) || (r == 184) || (r == 200)) {
return false;
}
return true;
}
if ((r == 44) && (b == 44) && (g == 17) ||
(r == 228) && (b == 228) && (g == 255) ||
(r == 236) && (b == 236) && (g == 255) ||
(r == 252) && (b == 225) && (g == 83) ||
(r == 252) && (b == 221) && (g == 81) ||
(r == 252) && (b == 216) && (g == 79) ||
(r == 252) && (b == 211) && (g == 77) ||
(r == 251) && (b == 206) && (g == 75) ||
(r == 251) && (b == 201) && (g == 73) ||
(r == 251) && (b == 196) && (g == 71) ||
(r == 251) && (b == 191) && (g == 69) ||
(r == 243) && (b == 153) && (g == 36)) {
return true;
}
return false;
}
//zoom level 12, 13
if ((r == 95) && (g == 95) && (b == 95)) {
return true;
}
return false;
}
private static int getCacheTypeFromPixel13(final int r, final int g, final int b) {
if (b < 130) {
if (r < 41) {
return CT_MYSTERY;
}
if (g < 74) {
return CT_EVENT;
}
if (r < 130) {
return CT_TRADITIONAL;
}
if (b < 31) {
return CT_MULTI;
}
if (b < 101) {
if (g < 99) {
return r < 178 ? CT_FOUND : CT_EVENT;
}
if (b < 58) {
if (g < 174) {
return CT_FOUND;
}
if (r < 224) {
return CT_OWN;
}
if (b < 49) {
return g < 210 ? CT_FOUND : CT_OWN;
}
if (g < 205) {
return g < 202 ? CT_FOUND : CT_OWN;
}
return CT_FOUND;
}
if (r < 255) {
return CT_FOUND;
}
return g < 236 ? CT_MULTI : CT_FOUND;
}
return g < 182 ? CT_EVENT : CT_MULTI;
}
if (r < 136) {
return CT_MYSTERY;
}
if (b < 168) {
return g < 174 ? CT_EARTH : CT_TRADITIONAL;
}
return CT_EARTH;
}
private static int getCacheTypeFromPixel14(final int r, final int g, final int b) {
if (b < 128) {
if (r < 214) {
if (b < 37) {
if (g < 50) {
if (b < 19) {
if (g < 16) {
if (b < 4) {
return CT_FOUND;
}
return r < 8 ? CT_VIRTUAL : CT_WEBCAM;
}
return CT_FOUND;
}
return CT_WEBCAM;
}
if (b < 24) {
if (b < 18) {
return CT_EARTH;
}
return r < 127 ? CT_TRADITIONAL : CT_EARTH;
}
return CT_FOUND;
}
if (r < 142) {
if (r < 63) {
if (r < 26) {
return CT_CITO;
}
return r < 51 ? CT_WEBCAM : CT_CITO;
}
return g < 107 ? CT_WEBCAM : CT_MULTI;
}
if (g < 138) {
return r < 178 ? CT_MEGAEVENT : CT_EVENT;
}
return b < 71 ? CT_FOUND : CT_EARTH;
}
if (b < 77) {
if (g < 166) {
if (r < 238) {
return g < 120 ? CT_MULTI : CT_OWN;
}
if (b < 57) {
if (r < 254) {
if (b < 39) {
if (r < 239) {
return CT_OWN;
}
if (b < 36) {
if (g < 150) {
if (b < 24) {
return b < 22 ? CT_FOUND : CT_OWN;
}
if (g < 138) {
return b < 25 ? CT_FOUND : CT_OWN;
}
return CT_FOUND;
}
return CT_OWN;
}
if (b < 38) {
if (b < 37) {
if (g < 153) {
return r < 242 ? CT_OWN : CT_FOUND;
}
return CT_OWN;
}
return CT_FOUND;
}
return CT_OWN;
}
if (g < 148) {
return CT_OWN;
}
if (r < 244) {
return CT_FOUND;
}
if (b < 45) {
if (b < 42) {
return CT_FOUND;
}
if (g < 162) {
return r < 245 ? CT_OWN : CT_FOUND;
}
return CT_OWN;
}
return CT_FOUND;
}
return g < 3 ? CT_FOUND : CT_VIRTUAL;
}
return CT_OWN;
}
if (b < 51) {
if (r < 251) {
return CT_OWN;
}
return g < 208 ? CT_EARTH : CT_MULTI;
}
if (b < 63) {
if (r < 247) {
return CT_FOUND;
}
if (r < 250) {
if (g < 169) {
return CT_FOUND;
}
if (g < 192) {
if (b < 54) {
return CT_OWN;
}
if (r < 248) {
return g < 180 ? CT_FOUND : CT_OWN;
}
return CT_OWN;
}
return g < 193 ? CT_FOUND : CT_OWN;
}
return CT_FOUND;
}
return CT_FOUND;
}
if (g < 177) {
return CT_OWN;
}
if (r < 239) {
return CT_FOUND;
}
if (g < 207) {
return CT_OWN;
}
return r < 254 ? CT_FOUND : CT_EARTH;
}
if (r < 203) {
if (b < 218) {
if (g < 158) {
if (g < 71) {
return CT_MYSTERY;
}
return r < 153 ? CT_WHERIGO : CT_WEBCAM;
}
if (b < 167) {
return r < 157 ? CT_TRADITIONAL : CT_WEBCAM;
}
return CT_WHERIGO;
}
if (g < 199) {
if (r < 142) {
return CT_LETTERBOX;
}
return r < 175 ? CT_CITO : CT_LETTERBOX;
}
if (g < 207) {
return r < 167 ? CT_MEGAEVENT : CT_CITO;
}
return CT_EARTH;
}
if (b < 224) {
if (g < 235) {
if (b < 163) {
if (r < 249) {
return b < 133 ? CT_FOUND : CT_OWN;
}
return CT_FOUND;
}
if (r < 235) {
if (r < 213) {
if (r < 207) {
return CT_FOUND;
}
if (g < 206) {
return CT_OWN;
}
return g < 207 ? CT_FOUND : CT_OWN;
}
return g < 194 ? CT_OWN : CT_FOUND;
}
if (g < 230) {
return CT_OWN;
}
return b < 205 ? CT_FOUND : CT_OWN;
}
if (r < 238) {
return CT_CITO;
}
return b < 170 ? CT_EVENT : CT_FOUND;
}
if (r < 251) {
if (r < 210) {
return CT_MYSTERY;
}
if (b < 252) {
if (r < 243) {
if (r < 225) {
return CT_WHERIGO;
}
if (b < 232) {
if (g < 228) {
return CT_WEBCAM;
}
return r < 231 ? CT_VIRTUAL : CT_TRADITIONAL;
}
if (r < 236) {
return CT_WHERIGO;
}
return r < 240 ? CT_WEBCAM : CT_WHERIGO;
}
if (g < 247) {
return r < 245 ? CT_WEBCAM : CT_FOUND;
}
return CT_WHERIGO;
}
return CT_LETTERBOX;
}
if (r < 255) {
return CT_OWN;
}
return g < 254 ? CT_FOUND : CT_OWN;
}
private static int getCacheTypeFromPixel11(final int r, final int g, final int b) {
if (g < 136) {
if (r < 90) {
return g < 111 ? CT_MYSTERY : CT_TRADITIONAL;
}
return b < 176 ? CT_EVENT : CT_MYSTERY;
}
if (r < 197) {
return CT_TRADITIONAL;
}
return b < 155 ? CT_MULTI : CT_EARTH;
}
}
|
package fr.free.nrw.commons.upload;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.android.volley.Cache;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
public class MwVolleyApi {
private static RequestQueue REQUEST_QUEUE;
private static final Gson GSON = new GsonBuilder().create();
private Context context;
protected static HashSet<String> categorySet;
public MwVolleyApi(Context context) {
this.context = context;
categorySet = new HashSet<String>();
}
public void request(String coords) {
String apiUrl = buildUrl(coords);
Log.d("Image", "URL: " + apiUrl);
JsonRequest<QueryResponse> request = new QueryRequest(apiUrl,
new LogResponseListener<QueryResponse>(), new LogResponseErrorListener());
getQueue().add(request);
}
private String buildUrl (String coords){
Uri.Builder builder = Uri.parse("https://commons.wikimedia.org/").buildUpon();
builder.appendPath("w")
.appendPath("api.php")
.appendQueryParameter("action", "query")
.appendQueryParameter("prop", "categories|coordinates|pageprops")
.appendQueryParameter("format", "json")
.appendQueryParameter("clshow", "!hidden")
.appendQueryParameter("coprop", "type|name|dim|country|region|globe")
.appendQueryParameter("codistancefrompoint", coords)
.appendQueryParameter("generator", "geosearch")
.appendQueryParameter("ggscoord", coords)
.appendQueryParameter("ggsradius", "100")
.appendQueryParameter("ggslimit", "10")
.appendQueryParameter("ggsnamespace", "6")
.appendQueryParameter("ggsprop", "type|name|dim|country|region|globe")
.appendQueryParameter("ggsprimary", "all")
.appendQueryParameter("formatversion", "2");
return builder.toString();
}
private synchronized RequestQueue getQueue() {
return getQueue(context);
}
private static RequestQueue getQueue(Context context) {
if (REQUEST_QUEUE == null) {
REQUEST_QUEUE = Volley.newRequestQueue(context.getApplicationContext());
}
return REQUEST_QUEUE;
}
private static class LogResponseListener<T> implements Response.Listener<T> {
private static final String TAG = LogResponseListener.class.getName();
@Override
public void onResponse(T response) {
Log.d(TAG, response.toString());
}
}
private static class LogResponseErrorListener implements Response.ErrorListener {
private static final String TAG = LogResponseErrorListener.class.getName();
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.toString());
}
}
private static class QueryRequest extends JsonRequest<QueryResponse> {
private static final String TAG = QueryRequest.class.getName();
public QueryRequest(String url,
Response.Listener<QueryResponse> listener,
Response.ErrorListener errorListener) {
super(Request.Method.GET, url, null, listener, errorListener);
}
@Override
protected Response<QueryResponse> parseNetworkResponse(NetworkResponse response) {
String json = parseString(response);
//Log.d(TAG, "json=" + json);
QueryResponse queryResponse = GSON.fromJson(json, QueryResponse.class);
return Response.success(queryResponse, cacheEntry(response));
}
private Cache.Entry cacheEntry(NetworkResponse response) {
return HttpHeaderParser.parseCacheHeaders(response);
}
private String parseString(NetworkResponse response) {
try {
return new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
return new String(response.data);
}
}
}
private static class QueryResponse {
private Query query = new Query();
private Page page;
private String printSet() {
if (categorySet == null || categorySet.isEmpty()) {
return "No collection of categories";
}
else {
return "CATEGORIES FOUND" + categorySet.toString();
}
}
@Override
public String toString() {
return "query=" + query.toString() + "\n" + printSet();
}
}
private static class Query {
private Page [] pages;
@Override
public String toString() {
StringBuilder builder = new StringBuilder("pages=" + "\n");
for (Page page : pages) {
builder.append(page.toString());
builder.append("\n");
}
builder.replace(builder.length() - 1, builder.length(), "");
return builder.toString();
}
}
private static class Page {
private int pageid;
private int ns;
private String title;
private Category[] categories;
private Category category;
@Override
public String toString() {
StringBuilder builder = new StringBuilder("PAGEID=" + pageid + " ns=" + ns + " title=" + title + "\n" + " CATEGORIES= ");
if (categories == null || categories.length == 0) {
builder.append("no categories exist\n");
}
else {
for (Category category : categories) {
builder.append(category.toString());
builder.append("\n");
if (category != null) {
String categoryString = category.toString().replace("Category:", "");
categorySet.add(categoryString);
//Log.d("Set", "category added: " + category.toString());
//Log.d("Set", "Current category Set" + categorySet.toString());
}
}
}
builder.replace(builder.length() - 1, builder.length(), "");
return builder.toString();
}
}
private static class Category {
private String title;
@Override
public String toString() {
return title;
}
}
}
|
package org.jfree.chart.event;
import org.jfree.chart.JFreeChart;
/**
* An event that contains information about the drawing progress of a chart.
*
*/
public class ChartProgressEvent extends java.util.EventObject {
/** Indicates drawing has started. */
public static final int DRAWING_STARTED = 1;
/** Indicates drawing has finished. */
public static final int DRAWING_FINISHED = 2;
/** The type of event. */
private int type;
/** The percentage of completion. */
private int percent;
/** The chart that generated the event. */
private JFreeChart chart;
/**
* Creates a new chart change event.
*
* @param source the source of the event (could be the chart, a title, an
* axis etc.)
* @param chart the chart that generated the event.
* @param type the type of event.
* @param percent the percentage of completion.
*/
public ChartProgressEvent(Object source, JFreeChart chart, int type,
int percent) {
super(source);
this.chart = chart;
this.type = type;
this.percent = percent;
}
/**
* Returns the chart that generated the change event.
*
* @return The chart that generated the change event.
*/
public JFreeChart getChart() {
return this.chart;
}
/**
* Sets the chart that generated the change event.
*
* @param chart the chart that generated the event.
*/
public void setChart(JFreeChart chart) {
this.chart = chart;
}
/**
* Returns the event type.
*
* @return The event type.
*/
public int getType() {
return this.type;
}
/**
* Sets the event type.
*
* @param type the event type.
*/
public void setType(int type) {
this.type = type;
}
/**
* Returns the percentage complete.
*
* @return The percentage complete.
*/
public int getPercent() {
return this.percent;
}
/**
* Sets the percentage complete.
*
* @param percent the percentage.
*/
public void setPercent(int percent) {
this.percent = percent;
}
}
|
package com.sun.jna.platform.win32;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.WString;
import com.sun.jna.platform.win32.WinBase.FILETIME;
import com.sun.jna.platform.win32.WinNT.ACCESS_ACEStructure;
import com.sun.jna.platform.win32.WinNT.ACL;
import com.sun.jna.platform.win32.WinNT.EVENTLOGRECORD;
import com.sun.jna.platform.win32.WinNT.HANDLE;
import com.sun.jna.platform.win32.WinNT.HANDLEByReference;
import com.sun.jna.platform.win32.WinNT.PSID;
import com.sun.jna.platform.win32.WinNT.PSIDByReference;
import com.sun.jna.platform.win32.WinNT.SECURITY_DESCRIPTOR_RELATIVE;
import com.sun.jna.platform.win32.WinNT.SID_AND_ATTRIBUTES;
import com.sun.jna.platform.win32.WinNT.SID_NAME_USE;
import com.sun.jna.platform.win32.WinReg.HKEY;
import com.sun.jna.platform.win32.WinReg.HKEYByReference;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.LongByReference;
import com.sun.jna.ptr.PointerByReference;
/**
* Advapi32 utility API.
*
* @author dblock[at]dblock.org
*/
public abstract class Advapi32Util {
/**
* An account.
*/
public static class Account {
/**
* Account name.
*/
public String name;
/**
* Account domain.
*/
public String domain;
/**
* Account SID.
*/
public byte[] sid;
/**
* String representation of the account SID.
*/
public String sidString;
/**
* Account type, one of SID_NAME_USE.
*/
public int accountType;
/**
* Fully qualified account name.
*/
public String fqn;
}
/**
* Retrieves the name of the user associated with the current thread.
*
* @return A user name.
*/
public static String getUserName() {
char[] buffer = new char[128];
IntByReference len = new IntByReference(buffer.length);
boolean result = Advapi32.INSTANCE.GetUserNameW(buffer, len);
if (!result) {
switch (Kernel32.INSTANCE.GetLastError()) {
case W32Errors.ERROR_INSUFFICIENT_BUFFER:
buffer = new char[len.getValue()];
break;
default:
throw new Win32Exception(Native.getLastError());
}
result = Advapi32.INSTANCE.GetUserNameW(buffer, len);
}
if (!result) {
throw new Win32Exception(Native.getLastError());
}
return Native.toString(buffer);
}
/**
* Retrieves a security identifier (SID) for the account on the current
* system.
*
* @param accountName
* Specifies the account name.
* @return A structure containing the account SID;
*/
public static Account getAccountByName(String accountName) {
return getAccountByName(null, accountName);
}
/**
* Retrieves a security identifier (SID) for a given account.
*
* @param systemName
* Name of the system.
* @param accountName
* Account name.
* @return A structure containing the account SID.
*/
public static Account getAccountByName(String systemName, String accountName) {
IntByReference pSid = new IntByReference(0);
IntByReference cchDomainName = new IntByReference(0);
PointerByReference peUse = new PointerByReference();
if (Advapi32.INSTANCE.LookupAccountName(systemName, accountName, null,
pSid, null, cchDomainName, peUse)) {
throw new RuntimeException(
"LookupAccountNameW was expected to fail with ERROR_INSUFFICIENT_BUFFER");
}
int rc = Kernel32.INSTANCE.GetLastError();
if (pSid.getValue() == 0 || rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
Memory sidMemory = new Memory(pSid.getValue());
PSID result = new PSID(sidMemory);
char[] referencedDomainName = new char[cchDomainName.getValue() + 1];
if (!Advapi32.INSTANCE.LookupAccountName(systemName, accountName,
result, pSid, referencedDomainName, cchDomainName, peUse)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
Account account = new Account();
account.accountType = peUse.getPointer().getInt(0);
account.name = accountName;
String[] accountNamePartsBs = accountName.split("\\\\", 2);
String[] accountNamePartsAt = accountName.split("@", 2);
if (accountNamePartsBs.length == 2) {
account.name = accountNamePartsBs[1];
} else if (accountNamePartsAt.length == 2) {
account.name = accountNamePartsAt[0];
} else {
account.name = accountName;
}
if (cchDomainName.getValue() > 0) {
account.domain = Native.toString(referencedDomainName);
account.fqn = account.domain + "\\" + account.name;
} else {
account.fqn = account.name;
}
account.sid = result.getBytes();
account.sidString = convertSidToStringSid(new PSID(account.sid));
return account;
}
/**
* Get the account by SID on the local system.
*
* @param sid
* SID.
* @return Account.
*/
public static Account getAccountBySid(PSID sid) {
return getAccountBySid(null, sid);
}
/**
* Get the account by SID.
*
* @param systemName
* Name of the system.
* @param sid
* SID.
* @return Account.
*/
public static Account getAccountBySid(String systemName, PSID sid) {
IntByReference cchName = new IntByReference();
IntByReference cchDomainName = new IntByReference();
PointerByReference peUse = new PointerByReference();
if (Advapi32.INSTANCE.LookupAccountSid(null, sid, null, cchName, null,
cchDomainName, peUse)) {
throw new RuntimeException(
"LookupAccountSidW was expected to fail with ERROR_INSUFFICIENT_BUFFER");
}
int rc = Kernel32.INSTANCE.GetLastError();
if (cchName.getValue() == 0
|| rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
char[] domainName = new char[cchDomainName.getValue()];
char[] name = new char[cchName.getValue()];
if (!Advapi32.INSTANCE.LookupAccountSid(null, sid, name, cchName,
domainName, cchDomainName, peUse)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
Account account = new Account();
account.accountType = peUse.getPointer().getInt(0);
account.name = Native.toString(name);
if (cchDomainName.getValue() > 0) {
account.domain = Native.toString(domainName);
account.fqn = account.domain + "\\" + account.name;
} else {
account.fqn = account.name;
}
account.sid = sid.getBytes();
account.sidString = convertSidToStringSid(sid);
return account;
}
/**
* Convert a security identifier (SID) to a string format suitable for
* display, storage, or transmission.
*
* @param sid
* SID bytes.
* @return String SID.
*/
public static String convertSidToStringSid(PSID sid) {
PointerByReference stringSid = new PointerByReference();
if (!Advapi32.INSTANCE.ConvertSidToStringSid(sid, stringSid)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
String result = stringSid.getValue().getString(0, true);
Kernel32.INSTANCE.LocalFree(stringSid.getValue());
return result;
}
/**
* Convert a string representation of a security identifier (SID) to a
* binary format.
*
* @param sidString
* String SID.
* @return SID bytes.
*/
public static byte[] convertStringSidToSid(String sidString) {
PSIDByReference pSID = new PSIDByReference();
if (!Advapi32.INSTANCE.ConvertStringSidToSid(sidString, pSID)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
return pSID.getValue().getBytes();
}
/**
* Compares a SID to a well known SID and returns TRUE if they match.
*
* @param sidString
* String representation of a SID.
* @param wellKnownSidType
* Member of the WELL_KNOWN_SID_TYPE enumeration to compare with
* the SID at pSid.
* @return True if the SID is of the well-known type, false otherwise.
*/
public static boolean isWellKnownSid(String sidString, int wellKnownSidType) {
PSIDByReference pSID = new PSIDByReference();
if (!Advapi32.INSTANCE.ConvertStringSidToSid(sidString, pSID)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
return Advapi32.INSTANCE.IsWellKnownSid(pSID.getValue(),
wellKnownSidType);
}
/**
* Compares a SID to a well known SID and returns TRUE if they match.
*
* @param sidBytes
* Byte representation of a SID.
* @param wellKnownSidType
* Member of the WELL_KNOWN_SID_TYPE enumeration to compare with
* the SID at pSid.
* @return True if the SID is of the well-known type, false otherwise.
*/
public static boolean isWellKnownSid(byte[] sidBytes, int wellKnownSidType) {
PSID pSID = new PSID(sidBytes);
return Advapi32.INSTANCE.IsWellKnownSid(pSID, wellKnownSidType);
}
/**
* Get an account name from a string SID on the local machine.
*
* @param sidString
* SID.
* @return Account.
*/
public static Account getAccountBySid(String sidString) {
return getAccountBySid(null, sidString);
}
/**
* Get an account name from a string SID.
*
* @param systemName
* System name.
* @param sidString
* SID.
* @return Account.
*/
public static Account getAccountBySid(String systemName, String sidString) {
return getAccountBySid(systemName, new PSID(
convertStringSidToSid(sidString)));
}
/**
* This function returns the groups associated with a security token, such
* as a user token.
*
* @param hToken
* Token.
* @return Token groups.
*/
public static Account[] getTokenGroups(HANDLE hToken) {
// get token group information size
IntByReference tokenInformationLength = new IntByReference();
if (Advapi32.INSTANCE.GetTokenInformation(hToken,
WinNT.TOKEN_INFORMATION_CLASS.TokenGroups, null, 0,
tokenInformationLength)) {
throw new RuntimeException(
"Expected GetTokenInformation to fail with ERROR_INSUFFICIENT_BUFFER");
}
int rc = Kernel32.INSTANCE.GetLastError();
if (rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
// get token group information
WinNT.TOKEN_GROUPS groups = new WinNT.TOKEN_GROUPS(
tokenInformationLength.getValue());
if (!Advapi32.INSTANCE.GetTokenInformation(hToken,
WinNT.TOKEN_INFORMATION_CLASS.TokenGroups, groups,
tokenInformationLength.getValue(), tokenInformationLength)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
ArrayList<Account> userGroups = new ArrayList<Account>();
// make array of names
for (SID_AND_ATTRIBUTES sidAndAttribute : groups.getGroups()) {
Account group = null;
try {
group = Advapi32Util.getAccountBySid(sidAndAttribute.Sid);
} catch (Exception e) {
group = new Account();
group.sid = sidAndAttribute.Sid.getBytes();
group.sidString = Advapi32Util
.convertSidToStringSid(sidAndAttribute.Sid);
group.name = group.sidString;
group.fqn = group.sidString;
group.accountType = SID_NAME_USE.SidTypeGroup;
}
userGroups.add(group);
}
return userGroups.toArray(new Account[0]);
}
/**
* This function returns the information about the user who owns a security
* token,
*
* @param hToken
* Token.
* @return Token user.
*/
public static Account getTokenAccount(HANDLE hToken) {
// get token group information size
IntByReference tokenInformationLength = new IntByReference();
if (Advapi32.INSTANCE.GetTokenInformation(hToken,
WinNT.TOKEN_INFORMATION_CLASS.TokenUser, null, 0,
tokenInformationLength)) {
throw new RuntimeException(
"Expected GetTokenInformation to fail with ERROR_INSUFFICIENT_BUFFER");
}
int rc = Kernel32.INSTANCE.GetLastError();
if (rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
// get token user information
WinNT.TOKEN_USER user = new WinNT.TOKEN_USER(
tokenInformationLength.getValue());
if (!Advapi32.INSTANCE.GetTokenInformation(hToken,
WinNT.TOKEN_INFORMATION_CLASS.TokenUser, user,
tokenInformationLength.getValue(), tokenInformationLength)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
return getAccountBySid(user.User.Sid);
}
/**
* Return the group memberships of the currently logged on user.
*
* @return An array of groups.
*/
public static Account[] getCurrentUserGroups() {
HANDLEByReference phToken = new HANDLEByReference();
try {
// open thread or process token
HANDLE threadHandle = Kernel32.INSTANCE.GetCurrentThread();
if (!Advapi32.INSTANCE.OpenThreadToken(threadHandle,
WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, true, phToken)) {
if (W32Errors.ERROR_NO_TOKEN != Kernel32.INSTANCE
.GetLastError()) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess();
if (!Advapi32.INSTANCE.OpenProcessToken(processHandle,
WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
}
return getTokenGroups(phToken.getValue());
} finally {
if (phToken.getValue() != WinBase.INVALID_HANDLE_VALUE) {
if (!Kernel32.INSTANCE.CloseHandle(phToken.getValue())) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
}
}
}
/**
* Checks whether a registry key exists.
*
* @param root
* HKEY_LOCAL_MACHINE, etc.
* @param key
* Path to the registry key.
* @return True if the key exists.
*/
public static boolean registryKeyExists(HKEY root, String key) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ,
phkKey);
switch (rc) {
case W32Errors.ERROR_SUCCESS:
Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
return true;
case W32Errors.ERROR_FILE_NOT_FOUND:
return false;
default:
throw new Win32Exception(rc);
}
}
/**
* Checks whether a registry value exists.
*
* @param root
* HKEY_LOCAL_MACHINE, etc.
* @param key
* Registry key path.
* @param value
* Value name.
* @return True if the value exists.
*/
public static boolean registryValueExists(HKEY root, String key,
String value) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ,
phkKey);
try {
switch (rc) {
case W32Errors.ERROR_SUCCESS:
break;
case W32Errors.ERROR_FILE_NOT_FOUND:
return false;
default:
throw new Win32Exception(rc);
}
IntByReference lpcbData = new IntByReference();
IntByReference lpType = new IntByReference();
rc = Advapi32.INSTANCE.RegQueryValueEx(phkKey.getValue(), value, 0,
lpType, (char[]) null, lpcbData);
switch (rc) {
case W32Errors.ERROR_SUCCESS:
case W32Errors.ERROR_MORE_DATA:
case W32Errors.ERROR_INSUFFICIENT_BUFFER:
return true;
case W32Errors.ERROR_FILE_NOT_FOUND:
return false;
default:
throw new Win32Exception(rc);
}
} finally {
if (phkKey.getValue() != WinBase.INVALID_HANDLE_VALUE) {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
}
/**
* Get a registry REG_SZ value.
*
* @param root
* Root key.
* @param key
* Registry path.
* @param value
* Name of the value to retrieve.
* @return String value.
*/
public static String registryGetStringValue(HKEY root, String key,
String value) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ,
phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
return registryGetStringValue(phkKey.getValue(), value);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Get a registry REG_SZ value.
*
* @param hKey
* Parent Key.
* @param value
* Name of the value to retrieve.
* @return String value.
*/
public static String registryGetStringValue(HKEY hKey, String value) {
IntByReference lpcbData = new IntByReference();
IntByReference lpType = new IntByReference();
int rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, (char[]) null, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
if (lpType.getValue() != WinNT.REG_SZ
&& lpType.getValue() != WinNT.REG_EXPAND_SZ) {
throw new RuntimeException("Unexpected registry type "
+ lpType.getValue()
+ ", expected REG_SZ or REG_EXPAND_SZ");
}
char[] data = new char[lpcbData.getValue()];
rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, data, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
return Native.toString(data);
}
/**
* Get a registry REG_EXPAND_SZ value.
*
* @param root
* Root key.
* @param key
* Registry path.
* @param value
* Name of the value to retrieve.
* @return String value.
*/
public static String registryGetExpandableStringValue(HKEY root,
String key, String value) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ,
phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
return registryGetExpandableStringValue(phkKey.getValue(), value);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Get a registry REG_EXPAND_SZ value.
*
* @param hKey
* Parent Key.
* @param value
* Name of the value to retrieve.
* @return String value.
*/
public static String registryGetExpandableStringValue(HKEY hKey, String value) {
IntByReference lpcbData = new IntByReference();
IntByReference lpType = new IntByReference();
int rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, (char[]) null, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
if (lpType.getValue() != WinNT.REG_EXPAND_SZ) {
throw new RuntimeException("Unexpected registry type "
+ lpType.getValue() + ", expected REG_SZ");
}
char[] data = new char[lpcbData.getValue()];
rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, data, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
return Native.toString(data);
}
/**
* Get a registry REG_MULTI_SZ value.
*
* @param root
* Root key.
* @param key
* Registry path.
* @param value
* Name of the value to retrieve.
* @return String value.
*/
public static String[] registryGetStringArray(HKEY root, String key,
String value) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ,
phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
return registryGetStringArray(phkKey.getValue(), value);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Get a registry REG_MULTI_SZ value.
*
* @param hKey
* Parent Key.
* @param value
* Name of the value to retrieve.
* @return String value.
*/
public static String[] registryGetStringArray(HKEY hKey, String value) {
IntByReference lpcbData = new IntByReference();
IntByReference lpType = new IntByReference();
int rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, (char[]) null, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
if (lpType.getValue() != WinNT.REG_MULTI_SZ) {
throw new RuntimeException("Unexpected registry type "
+ lpType.getValue() + ", expected REG_SZ");
}
Memory data = new Memory(lpcbData.getValue());
rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, data, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
ArrayList<String> result = new ArrayList<String>();
int offset = 0;
while (offset < data.size()) {
String s = data.getString(offset, true);
offset += s.length() * Native.WCHAR_SIZE;
offset += Native.WCHAR_SIZE;
if (s.length() == 0 && offset == data.size()) {
// skip the final NULL
} else {
result.add(s);
}
}
return result.toArray(new String[0]);
}
/**
* Get a registry REG_BINARY value.
*
* @param root
* Root key.
* @param key
* Registry path.
* @param value
* Name of the value to retrieve.
* @return String value.
*/
public static byte[] registryGetBinaryValue(HKEY root, String key,
String value) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ,
phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
return registryGetBinaryValue(phkKey.getValue(), value);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Get a registry REG_BINARY value.
*
* @param hKey
* Parent Key.
* @param value
* Name of the value to retrieve.
* @return String value.
*/
public static byte[] registryGetBinaryValue(HKEY hKey, String value) {
IntByReference lpcbData = new IntByReference();
IntByReference lpType = new IntByReference();
int rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, (char[]) null, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
if (lpType.getValue() != WinNT.REG_BINARY) {
throw new RuntimeException("Unexpected registry type "
+ lpType.getValue() + ", expected REG_BINARY");
}
byte[] data = new byte[lpcbData.getValue()];
rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, data, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
return data;
}
/**
* Get a registry DWORD value.
*
* @param root
* Root key.
* @param key
* Registry key path.
* @param value
* Name of the value to retrieve.
* @return Integer value.
*/
public static int registryGetIntValue(HKEY root, String key, String value) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ,
phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
return registryGetIntValue(phkKey.getValue(), value);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Get a registry DWORD value.
*
* @param hKey
* Parent key.
* @param value
* Name of the value to retrieve.
* @return Integer value.
*/
public static int registryGetIntValue(HKEY hKey, String value) {
IntByReference lpcbData = new IntByReference();
IntByReference lpType = new IntByReference();
int rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, (char[]) null, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
if (lpType.getValue() != WinNT.REG_DWORD) {
throw new RuntimeException("Unexpected registry type "
+ lpType.getValue() + ", expected REG_DWORD");
}
IntByReference data = new IntByReference();
rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, data, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
return data.getValue();
}
/**
* Get a registry QWORD value.
*
* @param root
* Root key.
* @param key
* Registry key path.
* @param value
* Name of the value to retrieve.
* @return Integer value.
*/
public static long registryGetLongValue(HKEY root, String key, String value) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ,
phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
return registryGetLongValue(phkKey.getValue(), value);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Get a registry QWORD value.
*
* @param hKey
* Parent key.
* @param value
* Name of the value to retrieve.
* @return Integer value.
*/
public static long registryGetLongValue(HKEY hKey, String value) {
IntByReference lpcbData = new IntByReference();
IntByReference lpType = new IntByReference();
int rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, (char[]) null, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
if (lpType.getValue() != WinNT.REG_QWORD) {
throw new RuntimeException("Unexpected registry type "
+ lpType.getValue() + ", expected REG_QWORD");
}
LongByReference data = new LongByReference();
rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, data, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
return data.getValue();
}
/**
* Get a registry value and returns a java object depending on the value
* type.
*
* @param hkKey
* Root key.
* @param subKey
* Registry key path.
* @param lpValueName
* Name of the value to retrieve or null for the default value.
* @return Object value.
*/
public static Object registryGetValue(HKEY hkKey, String subKey,
String lpValueName) {
Object result = null;
IntByReference lpType = new IntByReference();
byte[] lpData = new byte[Advapi32.MAX_VALUE_NAME];
IntByReference lpcbData = new IntByReference(Advapi32.MAX_VALUE_NAME);
int rc = Advapi32.INSTANCE.RegGetValue(hkKey, subKey, lpValueName,
Advapi32.RRF_RT_ANY, lpType, lpData, lpcbData);
// if lpType == 0 then the value is empty (REG_NONE)!
if (lpType.getValue() == WinNT.REG_NONE)
return null;
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
Memory byteData = new Memory(lpcbData.getValue());
byteData.write(0, lpData, 0, lpcbData.getValue());
if (lpType.getValue() == WinNT.REG_DWORD) {
result = new Integer(byteData.getInt(0));
} else if (lpType.getValue() == WinNT.REG_QWORD) {
result = new Long(byteData.getLong(0));
} else if (lpType.getValue() == WinNT.REG_BINARY) {
result = byteData.getByteArray(0, lpcbData.getValue());
} else if ((lpType.getValue() == WinNT.REG_SZ)
|| (lpType.getValue() == WinNT.REG_EXPAND_SZ)) {
result = byteData.getString(0, true);
}
return result;
}
/**
* Create a registry key.
*
* @param hKey
* Parent key.
* @param keyName
* Key name.
* @return True if the key was created, false otherwise.
*/
public static boolean registryCreateKey(HKEY hKey, String keyName) {
HKEYByReference phkResult = new HKEYByReference();
IntByReference lpdwDisposition = new IntByReference();
int rc = Advapi32.INSTANCE.RegCreateKeyEx(hKey, keyName, 0, null,
WinNT.REG_OPTION_NON_VOLATILE, WinNT.KEY_READ, null, phkResult,
lpdwDisposition);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
rc = Advapi32.INSTANCE.RegCloseKey(phkResult.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
return WinNT.REG_CREATED_NEW_KEY == lpdwDisposition.getValue();
}
/**
* Create a registry key.
*
* @param root
* Root key.
* @param parentPath
* Path to an existing registry key.
* @param keyName
* Key name.
* @return True if the key was created, false otherwise.
*/
public static boolean registryCreateKey(HKEY root, String parentPath,
String keyName) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, parentPath, 0,
WinNT.KEY_CREATE_SUB_KEY, phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
return registryCreateKey(phkKey.getValue(), keyName);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Set an integer value in registry.
*
* @param hKey
* Parent key.
* @param name
* Value name.
* @param value
* Value to write to registry.
*/
public static void registrySetIntValue(HKEY hKey, String name, int value) {
byte[] data = new byte[4];
data[0] = (byte) (value & 0xff);
data[1] = (byte) ((value >> 8) & 0xff);
data[2] = (byte) ((value >> 16) & 0xff);
data[3] = (byte) ((value >> 24) & 0xff);
int rc = Advapi32.INSTANCE.RegSetValueEx(hKey, name, 0,
WinNT.REG_DWORD, data, 4);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
/**
* Set an integer value in registry.
*
* @param root
* Root key.
* @param keyPath
* Path to an existing registry key.
* @param name
* Value name.
* @param value
* Value to write to registry.
*/
public static void registrySetIntValue(HKEY root, String keyPath,
String name, int value) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, keyPath, 0,
WinNT.KEY_READ | WinNT.KEY_WRITE, phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
registrySetIntValue(phkKey.getValue(), name, value);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Set a long value in registry.
*
* @param hKey
* Parent key.
* @param name
* Value name.
* @param value
* Value to write to registry.
*/
public static void registrySetLongValue(HKEY hKey, String name, long value) {
byte[] data = new byte[8];
data[0] = (byte) (value & 0xff);
data[1] = (byte) ((value >> 8) & 0xff);
data[2] = (byte) ((value >> 16) & 0xff);
data[3] = (byte) ((value >> 24) & 0xff);
data[4] = (byte) ((value >> 32) & 0xff);
data[5] = (byte) ((value >> 40) & 0xff);
data[6] = (byte) ((value >> 48) & 0xff);
data[7] = (byte) ((value >> 56) & 0xff);
int rc = Advapi32.INSTANCE.RegSetValueEx(hKey, name, 0,
WinNT.REG_QWORD, data, 8);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
/**
* Set a long value in registry.
*
* @param root
* Root key.
* @param keyPath
* Path to an existing registry key.
* @param name
* Value name.
* @param value
* Value to write to registry.
*/
public static void registrySetLongValue(HKEY root, String keyPath,
String name, long value) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, keyPath, 0,
WinNT.KEY_READ | WinNT.KEY_WRITE, phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
registrySetLongValue(phkKey.getValue(), name, value);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Set a string value in registry.
*
* @param hKey
* Parent key.
* @param name
* Value name.
* @param value
* Value to write to registry.
*/
public static void registrySetStringValue(HKEY hKey, String name,
String value) {
char[] data = Native.toCharArray(value);
int rc = Advapi32.INSTANCE.RegSetValueEx(hKey, name, 0, WinNT.REG_SZ,
data, data.length * Native.WCHAR_SIZE);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
/**
* Set a string value in registry.
*
* @param root
* Root key.
* @param keyPath
* Path to an existing registry key.
* @param name
* Value name.
* @param value
* Value to write to registry.
*/
public static void registrySetStringValue(HKEY root, String keyPath,
String name, String value) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, keyPath, 0,
WinNT.KEY_READ | WinNT.KEY_WRITE, phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
registrySetStringValue(phkKey.getValue(), name, value);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Set an expandable string value in registry.
*
* @param hKey
* Parent key.
* @param name
* Value name.
* @param value
* Value to write to registry.
*/
public static void registrySetExpandableStringValue(HKEY hKey, String name,
String value) {
char[] data = Native.toCharArray(value);
int rc = Advapi32.INSTANCE.RegSetValueEx(hKey, name, 0,
WinNT.REG_EXPAND_SZ, data, data.length * Native.WCHAR_SIZE);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
/**
* Set a string value in registry.
*
* @param root
* Root key.
* @param keyPath
* Path to an existing registry key.
* @param name
* Value name.
* @param value
* Value to write to registry.
*/
public static void registrySetExpandableStringValue(HKEY root,
String keyPath, String name, String value) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, keyPath, 0,
WinNT.KEY_READ | WinNT.KEY_WRITE, phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
registrySetExpandableStringValue(phkKey.getValue(), name, value);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Set a string array value in registry.
*
* @param hKey
* Parent key.
* @param name
* Name.
* @param arr
* Array of strings to write to registry.
*/
public static void registrySetStringArray(HKEY hKey, String name,
String[] arr) {
int size = 0;
for (String s : arr) {
size += s.length() * Native.WCHAR_SIZE;
size += Native.WCHAR_SIZE;
}
size += Native.WCHAR_SIZE;
int offset = 0;
Memory data = new Memory(size);
for (String s : arr) {
data.setString(offset, s, true);
offset += s.length() * Native.WCHAR_SIZE;
offset += Native.WCHAR_SIZE;
}
for (int i = 0; i < Native.WCHAR_SIZE; i++) {
data.setByte(offset++, (byte) 0);
}
int rc = Advapi32.INSTANCE.RegSetValueEx(hKey, name, 0,
WinNT.REG_MULTI_SZ, data.getByteArray(0, size), size);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
/**
* Set a string array value in registry.
*
* @param root
* Root key.
* @param keyPath
* Path to an existing registry key.
* @param name
* Value name.
* @param arr
* Array of strings to write to registry.
*/
public static void registrySetStringArray(HKEY root, String keyPath,
String name, String[] arr) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, keyPath, 0,
WinNT.KEY_READ | WinNT.KEY_WRITE, phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
registrySetStringArray(phkKey.getValue(), name, arr);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Set a binary value in registry.
*
* @param hKey
* Parent key.
* @param name
* Value name.
* @param data
* Data to write to registry.
*/
public static void registrySetBinaryValue(HKEY hKey, String name,
byte[] data) {
int rc = Advapi32.INSTANCE.RegSetValueEx(hKey, name, 0,
WinNT.REG_BINARY, data, data.length);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
/**
* Set a binary value in registry.
*
* @param root
* Root key.
* @param keyPath
* Path to an existing registry key.
* @param name
* Value name.
* @param data
* Data to write to registry.
*/
public static void registrySetBinaryValue(HKEY root, String keyPath,
String name, byte[] data) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, keyPath, 0,
WinNT.KEY_READ | WinNT.KEY_WRITE, phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
registrySetBinaryValue(phkKey.getValue(), name, data);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Delete a registry key.
*
* @param hKey
* Parent key.
* @param keyName
* Name of the key to delete.
*/
public static void registryDeleteKey(HKEY hKey, String keyName) {
int rc = Advapi32.INSTANCE.RegDeleteKey(hKey, keyName);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
/**
* Delete a registry key.
*
* @param root
* Root key.
* @param keyPath
* Path to an existing registry key.
* @param keyName
* Name of the key to delete.
*/
public static void registryDeleteKey(HKEY root, String keyPath,
String keyName) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, keyPath, 0,
WinNT.KEY_READ | WinNT.KEY_WRITE, phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
registryDeleteKey(phkKey.getValue(), keyName);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Delete a registry value.
*
* @param hKey
* Parent key.
* @param valueName
* Name of the value to delete.
*/
public static void registryDeleteValue(HKEY hKey, String valueName) {
int rc = Advapi32.INSTANCE.RegDeleteValue(hKey, valueName);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
/**
* Delete a registry value.
*
* @param root
* Root key.
* @param keyPath
* Path to an existing registry key.
* @param valueName
* Name of the value to delete.
*/
public static void registryDeleteValue(HKEY root, String keyPath,
String valueName) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, keyPath, 0,
WinNT.KEY_READ | WinNT.KEY_WRITE, phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
registryDeleteValue(phkKey.getValue(), valueName);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Get names of the registry key's sub-keys.
*
* @param hKey
* Registry key.
* @return Array of registry key names.
*/
public static String[] registryGetKeys(HKEY hKey) {
IntByReference lpcSubKeys = new IntByReference();
IntByReference lpcMaxSubKeyLen = new IntByReference();
int rc = Advapi32.INSTANCE
.RegQueryInfoKey(hKey, null, null, null, lpcSubKeys,
lpcMaxSubKeyLen, null, null, null, null, null, null);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
ArrayList<String> keys = new ArrayList<String>(lpcSubKeys.getValue());
char[] name = new char[lpcMaxSubKeyLen.getValue() + 1];
for (int i = 0; i < lpcSubKeys.getValue(); i++) {
IntByReference lpcchValueName = new IntByReference(
lpcMaxSubKeyLen.getValue() + 1);
rc = Advapi32.INSTANCE.RegEnumKeyEx(hKey, i, name, lpcchValueName,
null, null, null, null);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
keys.add(Native.toString(name));
}
return keys.toArray(new String[0]);
}
/**
* Get names of the registry key's sub-keys.
*
* @param root
* Root key.
* @param keyPath
* Path to a registry key.
* @return Array of registry key names.
*/
public static String[] registryGetKeys(HKEY root, String keyPath) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, keyPath, 0,
WinNT.KEY_READ, phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
return registryGetKeys(phkKey.getValue());
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Get a registry key, the caller is responsible to close the key after use.
*
* @param root
* Root key.
* @param keyPath
* Path to a registry key.
*
* @param samDesired
* Access level (e.g. WinNT.KEY_READ)
*
* @return HKEYByReference.
*/
public static HKEYByReference registryGetKey(HKEY root, String keyPath,
int samDesired) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, keyPath, 0, samDesired,
phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
return phkKey;
}
/**
* Close the registry key
*
* @param hKey
* Registry key.
*/
public static void registryCloseKey(HKEY hKey) {
int rc = Advapi32.INSTANCE.RegCloseKey(hKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
/**
* Get a table of registry values.
*
* @param hKey
* Registry key.
* @return Table of values.
*/
public static TreeMap<String, Object> registryGetValues(HKEY hKey) {
IntByReference lpcValues = new IntByReference();
IntByReference lpcMaxValueNameLen = new IntByReference();
IntByReference lpcMaxValueLen = new IntByReference();
int rc = Advapi32.INSTANCE.RegQueryInfoKey(hKey, null, null, null,
null, null, null, lpcValues, lpcMaxValueNameLen,
lpcMaxValueLen, null, null);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
TreeMap<String, Object> keyValues = new TreeMap<String, Object>();
char[] name = new char[lpcMaxValueNameLen.getValue() + 1];
byte[] data = new byte[lpcMaxValueLen.getValue()];
for (int i = 0; i < lpcValues.getValue(); i++) {
IntByReference lpcchValueName = new IntByReference(
lpcMaxValueNameLen.getValue() + 1);
IntByReference lpcbData = new IntByReference(
lpcMaxValueLen.getValue());
IntByReference lpType = new IntByReference();
rc = Advapi32.INSTANCE.RegEnumValue(hKey, i, name, lpcchValueName,
null, lpType, data, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
String nameString = Native.toString(name);
if (lpcbData.getValue() == 0) {
switch (lpType.getValue()) {
case WinNT.REG_BINARY: {
keyValues.put(nameString, new byte[0]);
break;
}
case WinNT.REG_SZ:
case WinNT.REG_EXPAND_SZ: {
keyValues.put(nameString, new char[0]);
break;
}
case WinNT.REG_MULTI_SZ: {
keyValues.put(nameString, new String[0]);
break;
}
case WinNT.REG_NONE: {
keyValues.put(nameString, null);
break;
}
default:
throw new RuntimeException("Unsupported empty type: "
+ lpType.getValue());
}
continue;
}
Memory byteData = new Memory(lpcbData.getValue());
byteData.write(0, data, 0, lpcbData.getValue());
switch (lpType.getValue()) {
case WinNT.REG_QWORD: {
keyValues.put(nameString, byteData.getLong(0));
break;
}
case WinNT.REG_DWORD: {
keyValues.put(nameString, byteData.getInt(0));
break;
}
case WinNT.REG_SZ:
case WinNT.REG_EXPAND_SZ: {
keyValues.put(nameString, byteData.getString(0, true));
break;
}
case WinNT.REG_BINARY: {
keyValues.put(nameString,
byteData.getByteArray(0, lpcbData.getValue()));
break;
}
case WinNT.REG_MULTI_SZ: {
Memory stringData = new Memory(lpcbData.getValue());
stringData.write(0, data, 0, lpcbData.getValue());
ArrayList<String> result = new ArrayList<String>();
int offset = 0;
while (offset < stringData.size()) {
String s = stringData.getString(offset, true);
offset += s.length() * Native.WCHAR_SIZE;
offset += Native.WCHAR_SIZE;
if (s.length() == 0 && offset == stringData.size()) {
// skip the final NULL
} else {
result.add(s);
}
}
keyValues.put(nameString, result.toArray(new String[0]));
break;
}
default:
throw new RuntimeException("Unsupported type: "
+ lpType.getValue());
}
}
return keyValues;
}
/**
* Get a table of registry values.
*
* @param root
* Registry root.
* @param keyPath
* Regitry key path.
* @return Table of values.
*/
public static TreeMap<String, Object> registryGetValues(HKEY root,
String keyPath) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, keyPath, 0,
WinNT.KEY_READ, phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
return registryGetValues(phkKey.getValue());
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Queries the information about a specified key.
*
* @param hKey
* Current registry key.
*
* @return A InfoKey value object.
*/
public static InfoKey registryQueryInfoKey(HKEY hKey,
int lpcbSecurityDescriptor) {
InfoKey infoKey = new InfoKey(hKey, lpcbSecurityDescriptor);
int rc = Advapi32.INSTANCE.RegQueryInfoKey(hKey, infoKey.lpClass,
infoKey.lpcClass, null, infoKey.lpcSubKeys,
infoKey.lpcMaxSubKeyLen, infoKey.lpcMaxClassLen,
infoKey.lpcValues, infoKey.lpcMaxValueNameLen,
infoKey.lpcMaxValueLen, infoKey.lpcbSecurityDescriptor,
infoKey.lpftLastWriteTime);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
return infoKey;
}
public static class InfoKey {
public HKEY hKey;
public char[] lpClass = new char[WinNT.MAX_PATH];
public IntByReference lpcClass = new IntByReference(WinNT.MAX_PATH);
public IntByReference lpcSubKeys = new IntByReference();
public IntByReference lpcMaxSubKeyLen = new IntByReference();
public IntByReference lpcMaxClassLen = new IntByReference();
public IntByReference lpcValues = new IntByReference();
public IntByReference lpcMaxValueNameLen = new IntByReference();
public IntByReference lpcMaxValueLen = new IntByReference();
public IntByReference lpcbSecurityDescriptor = new IntByReference();
public FILETIME lpftLastWriteTime = new FILETIME();
public InfoKey() {
}
public InfoKey(HKEY hKey, int securityDescriptor) {
this.hKey = hKey;
this.lpcbSecurityDescriptor = new IntByReference(securityDescriptor);
}
}
/**
* Queries the information about a specified key.
*
* @param hKey
* Current registry key.
*
* @return A InfoKey value object.
*/
public static EnumKey registryRegEnumKey(HKEY hKey, int dwIndex) {
EnumKey enumKey = new EnumKey(hKey, dwIndex);
int rc = Advapi32.INSTANCE.RegEnumKeyEx(hKey, enumKey.dwIndex,
enumKey.lpName, enumKey.lpcName, null, enumKey.lpClass,
enumKey.lpcbClass, enumKey.lpftLastWriteTime);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
return enumKey;
}
public static class EnumKey {
public HKEY hKey;
public int dwIndex = 0;
public char[] lpName = new char[Advapi32.MAX_KEY_LENGTH];
public IntByReference lpcName = new IntByReference(
Advapi32.MAX_KEY_LENGTH);
public char[] lpClass = new char[Advapi32.MAX_KEY_LENGTH];
public IntByReference lpcbClass = new IntByReference(
Advapi32.MAX_KEY_LENGTH);
public FILETIME lpftLastWriteTime = new FILETIME();
public EnumKey() {
}
public EnumKey(HKEY hKey, int dwIndex) {
this.hKey = hKey;
this.dwIndex = dwIndex;
}
}
/**
* Converts a map of environment variables to an environment block suitable
* for {@link Advapi32#CreateProcessAsUser}. This environment block consists
* of null-terminated blocks of null-terminated strings. Each string is in
* the following form: name=value\0
*
* @param environment
* Environment variables
* @return A environment block
*/
public static String getEnvironmentBlock(Map<String, String> environment) {
StringBuffer out = new StringBuffer();
for (Entry<String, String> entry : environment.entrySet()) {
if (entry.getValue() != null) {
out.append(entry.getKey() + "=" + entry.getValue() + "\0");
}
}
return out.toString() + "\0";
}
/**
* Event log types.
*/
public static enum EventLogType {
Error, Warning, Informational, AuditSuccess, AuditFailure
}
/**
* An event log record.
*/
public static class EventLogRecord {
private EVENTLOGRECORD _record = null;
private String _source;
private byte[] _data;
private String[] _strings;
/**
* Raw record data.
*
* @return EVENTLOGRECORD.
*/
public EVENTLOGRECORD getRecord() {
return _record;
}
/**
* Event Id.
*
* @return Integer.
*/
public int getEventId() {
return _record.EventID.intValue();
}
/**
* Event source.
*
* @return String.
*/
public String getSource() {
return _source;
}
/**
* Status code for the facility, part of the Event ID.
*
* @return Status code.
*/
public int getStatusCode() {
return _record.EventID.intValue() & 0xFFFF;
}
/**
* Record number of the record. This value can be used with the
* EVENTLOG_SEEK_READ flag in the ReadEventLog function to begin reading
* at a specified record.
*
* @return Integer.
*/
public int getRecordNumber() {
return _record.RecordNumber.intValue();
}
/**
* Record length, with data.
*
* @return Number of bytes in the record including data.
*/
public int getLength() {
return _record.Length.intValue();
}
/**
* Strings associated with this event.
*
* @return Array of strings or null.
*/
public String[] getStrings() {
return _strings;
}
/**
* Event log type.
*
* @return Event log type.
*/
public EventLogType getType() {
switch (_record.EventType.intValue()) {
case WinNT.EVENTLOG_SUCCESS:
case WinNT.EVENTLOG_INFORMATION_TYPE:
return EventLogType.Informational;
case WinNT.EVENTLOG_AUDIT_FAILURE:
return EventLogType.AuditFailure;
case WinNT.EVENTLOG_AUDIT_SUCCESS:
return EventLogType.AuditSuccess;
case WinNT.EVENTLOG_ERROR_TYPE:
return EventLogType.Error;
case WinNT.EVENTLOG_WARNING_TYPE:
return EventLogType.Warning;
default:
throw new RuntimeException("Invalid type: "
+ _record.EventType.intValue());
}
}
/**
* Raw data associated with the record.
*
* @return Array of bytes or null.
*/
public byte[] getData() {
return _data;
}
public EventLogRecord(Pointer pevlr) {
_record = new EVENTLOGRECORD(pevlr);
_source = pevlr.getString(_record.size(), true);
// data
if (_record.DataLength.intValue() > 0) {
_data = pevlr.getByteArray(_record.DataOffset.intValue(),
_record.DataLength.intValue());
}
// strings
if (_record.NumStrings.intValue() > 0) {
ArrayList<String> strings = new ArrayList<String>();
int count = _record.NumStrings.intValue();
long offset = _record.StringOffset.intValue();
while (count > 0) {
String s = pevlr.getString(offset, true);
strings.add(s);
offset += s.length() * Native.WCHAR_SIZE;
offset += Native.WCHAR_SIZE;
count
}
_strings = strings.toArray(new String[0]);
}
}
}
/**
* An iterator for Event Log entries.
*/
public static class EventLogIterator implements Iterable<EventLogRecord>,
Iterator<EventLogRecord> {
private HANDLE _h = null;
private Memory _buffer = new Memory(1024 * 64); // memory buffer to
// store events
private boolean _done = false; // no more events
private int _dwRead = 0; // number of bytes remaining in the current
// buffer
private Pointer _pevlr = null; // pointer to the current record
private int _flags = WinNT.EVENTLOG_FORWARDS_READ;
public EventLogIterator(String sourceName) {
this(null, sourceName, WinNT.EVENTLOG_FORWARDS_READ);
}
public EventLogIterator(String serverName, String sourceName, int flags) {
_flags = flags;
_h = Advapi32.INSTANCE.OpenEventLog(serverName, sourceName);
if (_h == null) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
}
private boolean read() {
// finished or bytes remain, don't read any new data
if (_done || _dwRead > 0) {
return false;
}
IntByReference pnBytesRead = new IntByReference();
IntByReference pnMinNumberOfBytesNeeded = new IntByReference();
if (!Advapi32.INSTANCE
.ReadEventLog(_h, WinNT.EVENTLOG_SEQUENTIAL_READ | _flags,
0, _buffer, (int) _buffer.size(), pnBytesRead,
pnMinNumberOfBytesNeeded)) {
int rc = Kernel32.INSTANCE.GetLastError();
// not enough bytes in the buffer, resize
if (rc == W32Errors.ERROR_INSUFFICIENT_BUFFER) {
_buffer = new Memory(pnMinNumberOfBytesNeeded.getValue());
if (!Advapi32.INSTANCE.ReadEventLog(_h,
WinNT.EVENTLOG_SEQUENTIAL_READ | _flags, 0,
_buffer, (int) _buffer.size(), pnBytesRead,
pnMinNumberOfBytesNeeded)) {
throw new Win32Exception(
Kernel32.INSTANCE.GetLastError());
}
} else {
// read failed, no more entries or error
close();
if (rc != W32Errors.ERROR_HANDLE_EOF) {
throw new Win32Exception(rc);
}
return false;
}
}
_dwRead = pnBytesRead.getValue();
_pevlr = _buffer;
return true;
}
/**
* Call close() in the case when the caller needs to abandon the
* iterator before the iteration completes.
*/
public void close() {
_done = true;
if (_h != null) {
if (!Advapi32.INSTANCE.CloseEventLog(_h)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
_h = null;
}
}
// @Override - @todo restore Override annotation after we move to source
// level 1.6
public Iterator<EventLogRecord> iterator() {
return this;
}
// @Override - @todo restore Override annotation after we move to source
// level 1.6
public boolean hasNext() {
read();
return !_done;
}
// @Override - @todo restore Override annotation after we move to source
// level 1.6
public EventLogRecord next() {
read();
EventLogRecord record = new EventLogRecord(_pevlr);
_dwRead -= record.getLength();
_pevlr = _pevlr.share(record.getLength());
return record;
}
// @Override - @todo restore Override annotation after we move to source
// level 1.6
public void remove() {
}
}
public static ACCESS_ACEStructure[] getFileSecurity(String fileName,
boolean compact) {
int infoType = WinNT.DACL_SECURITY_INFORMATION;
int nLength = 1024;
boolean repeat = false;
Memory memory = null;
do {
repeat = false;
memory = new Memory(nLength);
IntByReference lpnSize = new IntByReference();
boolean succeded = Advapi32.INSTANCE.GetFileSecurity(new WString(
fileName), infoType, memory, nLength, lpnSize);
if (!succeded) {
int lastError = Kernel32.INSTANCE.GetLastError();
memory.clear();
if (W32Errors.ERROR_INSUFFICIENT_BUFFER != lastError) {
throw new Win32Exception(lastError);
}
}
int lengthNeeded = lpnSize.getValue();
if (nLength < lengthNeeded) {
repeat = true;
nLength = lengthNeeded;
memory.clear();
}
} while (repeat);
SECURITY_DESCRIPTOR_RELATIVE sdr = new WinNT.SECURITY_DESCRIPTOR_RELATIVE(
memory);
memory.clear();
ACL dacl = sdr.getDiscretionaryACL();
ACCESS_ACEStructure[] aceStructures = dacl.getACEStructures();
if (compact) {
Map<String, ACCESS_ACEStructure> aceMap = new HashMap<String, ACCESS_ACEStructure>();
for (ACCESS_ACEStructure aceStructure : aceStructures) {
boolean inherted = ((aceStructure.AceFlags & WinNT.VALID_INHERIT_FLAGS) != 0);
String key = aceStructure.getSidString() + "/" + inherted + "/"
+ aceStructure.getClass().getName();
ACCESS_ACEStructure aceStructure2 = aceMap.get(key);
if (aceStructure2 != null) {
int accessMask = aceStructure2.Mask;
accessMask = accessMask | aceStructure.Mask;
aceStructure2.Mask = accessMask;
} else {
aceMap.put(key, aceStructure);
}
}
return aceMap.values().toArray(
new ACCESS_ACEStructure[aceMap.size()]);
}
return aceStructures;
}
}
|
package alluxio.resource;
import java.io.Closeable;
/**
* A {@code CloseableResource<T>} is a wrapper around a resource of type {@code T} which must do
* some sort of cleanup when it is no longer in use.
*
* @param <T> the type of the wrapped resource
*/
public abstract class CloseableResource<T> implements Closeable {
private T mResource;
/**
* Creates a {@link CloseableResource<T>} wrapper around the given resource. This resource will
* be returned by the {@link CloseableResource#get()} method.
*
* @param resource the resource to wrap
*/
public CloseableResource(T resource) {
mResource = resource;
}
/**
* @return the resource
*/
public T get() {
return mResource;
}
/**
* Performs any cleanup operations necessary when the resource is no longer in use.
*/
@Override
public abstract void close();
}
|
package com.gentics.mesh.core.data.impl;
import static com.gentics.mesh.core.data.relationship.GraphPermission.READ_PERM;
import static com.gentics.mesh.core.data.relationship.GraphRelationships.ASSIGNED_TO_ROLE;
import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_CREATOR;
import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_EDITOR;
import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_ROLE;
import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_USER;
import static com.gentics.mesh.core.rest.MeshEvent.GROUP_ROLE_ASSIGNED;
import static com.gentics.mesh.core.rest.MeshEvent.GROUP_ROLE_UNASSIGNED;
import static com.gentics.mesh.core.rest.MeshEvent.GROUP_USER_ASSIGNED;
import static com.gentics.mesh.core.rest.MeshEvent.GROUP_USER_UNASSIGNED;
import static com.gentics.mesh.core.rest.error.Errors.conflict;
import static com.gentics.mesh.core.rest.error.Errors.error;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import java.util.Set;
import java.util.stream.Collectors;
import com.gentics.mesh.cli.BootstrapInitializer;
import com.gentics.mesh.context.BulkActionContext;
import com.gentics.mesh.context.InternalActionContext;
import com.gentics.mesh.core.cache.PermissionStore;
import com.gentics.mesh.core.data.Group;
import com.gentics.mesh.core.data.MeshAuthUser;
import com.gentics.mesh.core.data.Role;
import com.gentics.mesh.core.data.User;
import com.gentics.mesh.core.data.generic.AbstractMeshCoreVertex;
import com.gentics.mesh.core.data.generic.MeshVertexImpl;
import com.gentics.mesh.core.data.page.TransformablePage;
import com.gentics.mesh.core.data.page.impl.DynamicTransformablePageImpl;
import com.gentics.mesh.core.data.relationship.GraphPermission;
import com.gentics.mesh.core.rest.event.group.GroupRoleAssignModel;
import com.gentics.mesh.core.rest.event.group.GroupUserAssignModel;
import com.gentics.mesh.core.rest.group.GroupReference;
import com.gentics.mesh.core.rest.group.GroupResponse;
import com.gentics.mesh.core.rest.group.GroupUpdateRequest;
import com.gentics.mesh.dagger.DB;
import com.gentics.mesh.dagger.MeshInternal;
import com.gentics.mesh.event.Assignment;
import com.gentics.mesh.event.EventQueueBatch;
import com.gentics.mesh.graphdb.spi.Database;
import com.gentics.mesh.graphdb.spi.FieldType;
import com.gentics.mesh.madlmigration.TraversalResult;
import com.gentics.mesh.parameter.GenericParameters;
import com.gentics.mesh.parameter.PagingParameters;
import com.gentics.mesh.parameter.value.FieldsSet;
import com.gentics.mesh.util.ETag;
import com.syncleus.ferma.traversals.VertexTraversal;
import io.reactivex.Single;
/**
* @see Group
*/
public class GroupImpl extends AbstractMeshCoreVertex<GroupResponse, Group> implements Group {
public static void init(Database database) {
database.addVertexType(GroupImpl.class, MeshVertexImpl.class);
database.addVertexIndex(GroupImpl.class, true, "name", FieldType.STRING);
}
@Override
public GroupReference transformToReference() {
return new GroupReference().setName(getName()).setUuid(getUuid());
}
@Override
public String getName() {
return property("name");
}
@Override
public void setName(String name) {
property("name", name);
}
@Override
public TraversalResult<? extends User> getUsers() {
return new TraversalResult<>(in(HAS_USER).frameExplicit(UserImpl.class));
}
@Override
public void addUser(User user) {
setUniqueLinkInTo(user, HAS_USER);
// Add shortcut edge from user to roles of this group
for (Role role : getRoles()) {
user.setUniqueLinkOutTo(role, ASSIGNED_TO_ROLE);
}
}
@Override
public void removeUser(User user) {
unlinkIn(user, HAS_USER);
// The user does no longer belong to the group so lets update the shortcut edges
user.updateShortcutEdges();
PermissionStore.invalidate();
}
@Override
public TraversalResult<? extends Role> getRoles() {
return new TraversalResult<>(in(HAS_ROLE).frameExplicit(RoleImpl.class));
}
@Override
public void addRole(Role role) {
setUniqueLinkInTo(role, HAS_ROLE);
// Add shortcut edges from role to users of this group
for (User user : getUsers()) {
user.setUniqueLinkOutTo(role, ASSIGNED_TO_ROLE);
}
}
@Override
public void removeRole(Role role) {
unlinkIn(role, HAS_ROLE);
// Update the shortcut edges since the role does no longer belong to the group
for (User user : getUsers()) {
user.updateShortcutEdges();
}
PermissionStore.invalidate();
}
@Override
public boolean hasRole(Role role) {
return in(HAS_ROLE).retain(role).hasNext();
}
@Override
public boolean hasUser(User user) {
return in(HAS_USER).retain(user).hasNext();
}
@Override
public TransformablePage<? extends User> getVisibleUsers(MeshAuthUser user, PagingParameters pagingInfo) {
VertexTraversal<?, ?, ?> traversal = in(HAS_USER);
return new DynamicTransformablePageImpl<User>(user, traversal, pagingInfo, READ_PERM, UserImpl.class);
}
@Override
public TransformablePage<? extends Role> getRoles(User user, PagingParameters pagingInfo) {
VertexTraversal<?, ?, ?> traversal = in(HAS_ROLE);
return new DynamicTransformablePageImpl<Role>(user, traversal, pagingInfo, READ_PERM, RoleImpl.class);
}
@Override
public GroupResponse transformToRestSync(InternalActionContext ac, int level, String... languageTags) {
GenericParameters generic = ac.getGenericParameters();
FieldsSet fields = generic.getFields();
GroupResponse restGroup = new GroupResponse();
if (fields.has("name")) {
restGroup.setName(getName());
}
if (fields.has("roles")) {
setRoles(ac, restGroup);
}
fillCommonRestFields(ac, fields, restGroup);
setRolePermissions(ac, restGroup);
return restGroup;
}
/**
* Load the roles that are assigned to this group and add the transformed references to the rest model.
*
* @param ac
* @param restGroup
*/
private void setRoles(InternalActionContext ac, GroupResponse restGroup) {
for (Role role : getRoles()) {
String name = role.getName();
if (name != null) {
restGroup.getRoles().add(role.transformToReference());
}
}
}
@Override
public void delete(BulkActionContext bac) {
// TODO don't allow deletion of the admin group
bac.batch().add(onDeleted());
Set<? extends User> affectedUsers = getUsers().stream().collect(Collectors.toSet());
getElement().remove();
for (User user : affectedUsers) {
user.updateShortcutEdges();
bac.add(user.onUpdated());
bac.inc();
}
bac.process();
PermissionStore.invalidate();
}
@Override
public boolean update(InternalActionContext ac, EventQueueBatch batch) {
BootstrapInitializer boot = MeshInternal.get().boot();
GroupUpdateRequest requestModel = ac.fromJson(GroupUpdateRequest.class);
if (isEmpty(requestModel.getName())) {
throw error(BAD_REQUEST, "error_name_must_be_set");
}
if (shouldUpdate(requestModel.getName(), getName())) {
Group groupWithSameName = boot.groupRoot().findByName(requestModel.getName());
if (groupWithSameName != null && !groupWithSameName.getUuid().equals(getUuid())) {
throw conflict(groupWithSameName.getUuid(), requestModel.getName(), "group_conflicting_name", requestModel.getName());
}
setName(requestModel.getName());
batch.add(onUpdated());
return true;
}
return false;
}
@Override
public void applyPermissions(EventQueueBatch batch, Role role, boolean recursive, Set<GraphPermission> permissionsToGrant,
Set<GraphPermission> permissionsToRevoke) {
if (recursive) {
for (User user : getUsers()) {
user.applyPermissions(batch, role, false, permissionsToGrant, permissionsToRevoke);
}
}
super.applyPermissions(batch, role, recursive, permissionsToGrant, permissionsToRevoke);
}
@Override
public String getETag(InternalActionContext ac) {
StringBuilder keyBuilder = new StringBuilder();
keyBuilder.append(super.getETag(ac));
keyBuilder.append(getLastEditedTimestamp());
return ETag.hash(keyBuilder);
}
@Override
public String getAPIPath(InternalActionContext ac) {
return "/api/v1/groups/" + getUuid();
}
@Override
public User getCreator() {
return out(HAS_CREATOR).nextOrDefault(UserImpl.class, null);
}
@Override
public User getEditor() {
return out(HAS_EDITOR).nextOrDefaultExplicit(UserImpl.class, null);
}
@Override
public Single<GroupResponse> transformToRest(InternalActionContext ac, int level, String... languageTags) {
return DB.get().asyncTx(() -> {
return Single.just(transformToRestSync(ac, level, languageTags));
});
}
@Override
public GroupRoleAssignModel createRoleAssignmentEvent(Role role, Assignment assignment) {
GroupRoleAssignModel model = new GroupRoleAssignModel();
model.setGroup(transformToReference());
model.setRole(role.transformToReference());
switch (assignment) {
case ASSIGNED:
model.setEvent(GROUP_ROLE_ASSIGNED);
break;
case UNASSIGNED:
model.setEvent(GROUP_ROLE_UNASSIGNED);
break;
}
return model;
}
@Override
public GroupUserAssignModel createUserAssignmentEvent(User user, Assignment assignment) {
GroupUserAssignModel model = new GroupUserAssignModel();
model.setGroup(transformToReference());
model.setUser(user.transformToReference());
switch (assignment) {
case ASSIGNED:
model.setEvent(GROUP_USER_ASSIGNED);
break;
case UNASSIGNED:
model.setEvent(GROUP_USER_UNASSIGNED);
break;
}
return model;
}
}
|
package com.zyeeda.framework.ws;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import org.apache.commons.lang.StringUtils;
import com.zyeeda.framework.entities.Department;
import com.zyeeda.framework.entities.Role;
import com.zyeeda.framework.entities.User;
import com.zyeeda.framework.ldap.LdapService;
import com.zyeeda.framework.managers.RoleManager;
import com.zyeeda.framework.managers.UserManager;
import com.zyeeda.framework.managers.UserPersistException;
import com.zyeeda.framework.managers.internal.DefaultRoleManager;
import com.zyeeda.framework.managers.internal.LdapDepartmentManager;
import com.zyeeda.framework.managers.internal.LdapUserManager;
import com.zyeeda.framework.viewmodels.DepartmentVo;
import com.zyeeda.framework.viewmodels.OrganizationNodeVo;
import com.zyeeda.framework.viewmodels.UserVo;
import com.zyeeda.framework.ws.base.ResourceService;
@Path("/depts")
public class DepartmentService extends ResourceService {
public DepartmentService(@Context ServletContext ctx) {
super(ctx);
}
@POST
@Path("/{parent}")
@Produces("application/json")
public Department persist(@FormParam("") Department dept,
@PathParam("parent") String parent)
throws UserPersistException {
LdapService ldapSvc = this.getLdapService();
LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
if (deptMgr.findByName(dept.getName()) != null &&
deptMgr.findByName(dept.getName()).size() > 0) {
throw new RuntimeException("");
} else {
dept.setParent(parent);
dept.setId("ou=" + dept.getName() + "," + dept.getParent());
dept.setDeptFullPath("ou=" + dept.getName() + "," + dept.getParent());
deptMgr.persist(dept);
return deptMgr.findById(dept.getId());
}
}
@DELETE
@Path("/{id}")
@Produces("application/json")
public String remove(@PathParam("id") String id,
@FormParam("cascade") String cascade)
throws UserPersistException {
LdapService ldapSvc = this.getLdapService();
LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
LdapUserManager userManager = new LdapUserManager(ldapSvc);
if (cascade != null) {
deptMgr.remove(id);
return "{\"success\": \"true\"}";
} else {
Integer deptCount = deptMgr.getChildrenCountById(id, "(objectclass=*)");
Integer userCount = userManager.getChildrenCountById(id, "(objectclass=*)");
if (userCount > 0 || deptCount > 0) {
return "{\"success\": \"false\"}";
} else {
deptMgr.remove(id);
return "{\"success\": \"true\"}";
}
}
}
@PUT
@Path("/{id}")
@Produces("application/json")
public Department update(@FormParam("") Department dept,
@PathParam("id") String id)
throws UserPersistException {
LdapService ldapSvc = this.getLdapService();
LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
dept.setId(id);
deptMgr.update(dept);
return deptMgr.findById(id);
}
@GET
@Path("/{id}")
@Produces("application/json")
public Department findById(@PathParam("id") String id) throws UserPersistException {
LdapService ldapSvc = this.getLdapService();
LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
return deptMgr.findById(id);
}
@GET
@Path("/search/{name}")
@Produces("application/json")
public List<DepartmentVo> findByName(@PathParam("name") String name) throws UserPersistException {
LdapService ldapSvc = this.getLdapService();
LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
return DepartmentService.fillPropertiesToVo(deptMgr.findByName(name));
}
@GET
@Path("/search")
@Produces("application/json")
public String search(@FormParam("name") String name) throws UserPersistException {
LdapService ldapSvc = this.getLdapService();
LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
List<Department> deptList = deptMgr.search(name);
StringBuffer buffer = new StringBuffer("{");
buffer.append("\"totalRecords\":").append(deptList.size())
.append(",").append("\"startIndex\":").append(0)
.append(",").append("\"pageSize\":").append(13)
.append(",").append("\"records\":[");
for (Department department : deptList) {
buffer.append("{\"name\":").append("\"").append(department.getId()).append("\"").append(",")
.append("\"parent\":").append("\"").append(department.getParent() == null ? "" : department.getParent()).append("\"").append(",")
.append("\"fullpath\":").append("\"").append(department.getDeptFullPath() == null ? "" : department.getDeptFullPath()).append("\"").append(",")
.append("\"description\":").append("\"").append(department.getDescription() == null ? "" : department.getDescription()).append("\"").append("},");
}
if (buffer.lastIndexOf(",") != -1 && deptList.size() > 0) {
buffer.deleteCharAt(buffer.lastIndexOf(","));
}
buffer.append("]}");
return buffer.toString();
}
@GET
@Path("/search/{parent}/{name}")
@Produces("application/json")
public List<DepartmentVo> findByName(@PathParam("parent") String parent,
@PathParam("name") String name)
throws UserPersistException {
LdapService ldapSvc = this.getLdapService();
LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
return DepartmentService.fillPropertiesToVo(deptMgr.findByName(parent, name));
}
@GET
@Path("/{id}/children")
@Produces("application/json")
public List<OrganizationNodeVo> getChildrenById(@Context HttpServletRequest request,
@PathParam("id") String id)
throws UserPersistException {
LdapService ldapSvc = this.getLdapService();
LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
LdapUserManager userMgr = new LdapUserManager(ldapSvc);
List<DepartmentVo> deptVoList = null;
List<UserVo> userVoList = null;
String type = request.getParameter("type");
if (StringUtils.isNotBlank(type) && "task".equals(type)) {
deptVoList = DepartmentService.fillPropertiesToVo(deptMgr.getChildrenById(id), type);
userVoList = UserService.fillUserListPropertiesToVo(userMgr.findByDepartmentId(id), type);
} else {
deptVoList = DepartmentService.fillPropertiesToVo(deptMgr.getChildrenById(id));
userVoList = UserService.fillUserListPropertiesToVo(userMgr.findByDepartmentId(id));
}
List<OrganizationNodeVo> orgList = this.mergeDepartmentVoAndUserVo(deptVoList, userVoList);
return orgList;
}
private List<OrganizationNodeVo> mergeDepartmentVoAndUserVo(List<DepartmentVo> deptVoList,
List<UserVo> userVoList) {
List<OrganizationNodeVo> orgNodeVoList = new ArrayList<OrganizationNodeVo>();
for (DepartmentVo deptVo: deptVoList) {
OrganizationNodeVo orgNodeVo = new OrganizationNodeVo();
orgNodeVo.setId(deptVo.getId());
orgNodeVo.setCheckName(deptVo.getCheckName());
orgNodeVo.setIo(deptVo.getIo());
orgNodeVo.setLabel(deptVo.getLabel());
orgNodeVo.setType(deptVo.getType());
orgNodeVo.setFullPath(deptVo.getDeptFullPath());
orgNodeVo.setKind(deptVo.getKind());
orgNodeVoList.add(orgNodeVo);
}
for (UserVo userVo: userVoList) {
OrganizationNodeVo orgNodeVo = new OrganizationNodeVo();
orgNodeVo.setId(userVo.getDeptFullPath());
orgNodeVo.setCheckName(userVo.getCheckName());
orgNodeVo.setIo(userVo.getId());
orgNodeVo.setLabel(userVo.getLabel());
orgNodeVo.setType(userVo.getType());
orgNodeVo.setLeaf(userVo.isLeaf());
orgNodeVo.setFullPath(userVo.getDeptFullPath());
orgNodeVo.setKind(userVo.getKind());
orgNodeVoList.add(orgNodeVo);
}
return orgNodeVoList;
}
public static DepartmentVo fillPropertiesToVo(Department dept) {
DepartmentVo deptVo = new DepartmentVo();
deptVo.setType("io");
deptVo.setLabel(dept.getName());
deptVo.setCheckName(dept.getId());
deptVo.setLeaf(false);
if (StringUtils.isBlank(dept.getParent())) {
deptVo.setDeptFullPath("o=" + dept.getId());
} else {
deptVo.setDeptFullPath("ou=" + dept.getId() + "," + dept.getParent());
}
if (StringUtils.isBlank(deptVo.getDeptFullPath())) {
deptVo.setIo("/rest/depts/root/children");
} else {
deptVo.setIo("/rest/depts/" + deptVo.getDeptFullPath() + "/children");
}
deptVo.setKind("dept");
return deptVo;
}
public static List<DepartmentVo> fillPropertiesToVo(List<Department> deptList,
String type) {
List<DepartmentVo> deptVoList = new ArrayList<DepartmentVo>(deptList.size());
DepartmentVo deptVo = null;
for (Department dept : deptList) {
deptVo = DepartmentService.fillPropertiesToVo(dept);
deptVo.setId(dept.getId());
deptVo.setIo(deptVo.getIo() + "?type=task");
deptVo.setType(type);
deptVoList.add(deptVo);
}
return deptVoList;
}
public static List<DepartmentVo> fillPropertiesToVo(List<Department> deptList) {
List<DepartmentVo> deptVoList = new ArrayList<DepartmentVo>(deptList.size());
DepartmentVo deptVo = null;
for (Department dept : deptList) {
deptVo = DepartmentService.fillPropertiesToVo(dept);
deptVoList.add(deptVo);
}
return deptVoList;
}
@GET
@Path("root_and_second_level_dept")
@Produces("application/json")
public List<Department> getRootAndSecondLevelDepartment() throws UserPersistException {
List<Department> deptList = null;
LdapService ldapSvc = this.getLdapService();
LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
deptList = deptMgr.getRootAndSecondLevelDepartment();
//List<DepartmentVo> deptVoList = DepartmentService.fillPropertiesToVo(deptList);
return deptList;
}
@GET
@Path("second_level_dept")
@Produces("application/json")
public List<Department> getSecondLevelDepartment() throws UserPersistException {
List<Department> deptList = null;
LdapService ldapSvc = this.getLdapService();
LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
deptList = deptMgr.getChildrenById("o=");
return deptList;
}
@GET
@Path("/children/{id}")
@Produces("application/json")
public List<OrganizationNodeVo> getChindren(@PathParam("id") String id) throws UserPersistException {
List<Department> deptList = null;
LdapService ldapSvc = this.getLdapService();
LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
deptList = deptMgr.getChildrenById(id);
return this.mergeDepartmentVoAndUserVo(fillPropertiesToVo(deptList, "task"), new ArrayList<UserVo>());
}
@GET
@Path("second_level_dept_role")
@Produces("application/json")
public List<DepartmentVo> getSecondLevelDepartmentAndRole() throws UserPersistException {
List<Department> deptList = null;
LdapService ldapSvc = this.getLdapService();
LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
deptList = deptMgr.getChildrenById("o=");
List<DepartmentVo> deptVoList = DepartmentService.fillPropertiesToVoAndRoles(deptList);
return deptVoList;
}
public static List<DepartmentVo> fillPropertiesToVoAndRoles(List<Department> deptList) {
List<DepartmentVo> deptVoList = new ArrayList<DepartmentVo>(deptList.size());
DepartmentVo deptVo = null;
for (Department dept : deptList) {
deptVo = DepartmentService.fillPropertiesToVoAndRole(dept);
deptVoList.add(deptVo);
}
return deptVoList;
}
public static DepartmentVo fillPropertiesToVoAndRole(Department dept) {
DepartmentVo deptVo = new DepartmentVo();
deptVo.setType("io");
deptVo.setLabel(dept.getName());
deptVo.setId(dept.getDeptFullPath());
deptVo.setCheckName(dept.getId());
deptVo.setLeaf(false);
if (StringUtils.isNotBlank(dept.getDeptFullPath())) {
deptVo.setIo("/rest/roles/dept/" + dept.getDeptFullPath());
}
deptVo.setKind("dept");
return deptVo;
}
/**
*
* @param userId
* @return
* @throws UserPersistException
*/
@GET
@Path("eliminating_team")
@Produces("application/json")
public List<Department> getDepartmentListByUserId() throws UserPersistException {
List<Department> deptList = null;
LdapService ldapSvc = this.getLdapService();
LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
UserManager userManager = new LdapUserManager(this.getLdapService());
String currentUser = this.getSecurityService().getCurrentUser();
List<User> userList = userManager.findByName(currentUser);
User user = null;
if (userList != null && userList.size() > 0) {
user = userList.get(0);
if (user != null && StringUtils.isNotBlank(user.getDeptFullPath())) {
String deptFullPath = StringUtils.substring(user.getDeptFullPath(),
user.getDeptFullPath().indexOf(",") + 1,
user.getDeptFullPath().length());
if (deptFullPath.indexOf(",") != -1) {
deptFullPath = StringUtils.substring(deptFullPath,
deptFullPath.indexOf(",") + 1,
deptFullPath.length());
}
deptList = deptMgr.getDepartmentListByUserId(deptFullPath);
}
}
return deptList;
}
@GET
@Path("/{id}/children/{roleId}")
@Produces("application/json")
public List<OrganizationNodeVo> getChildrenNodesByDepartmentIdAndRoleId(@Context HttpServletRequest request,
@PathParam("id") String id,
@PathParam("roleId") String roleId)
throws UserPersistException {
LdapService ldapSvc = this.getLdapService();
RoleManager roleMgr = new DefaultRoleManager(this.getPersistenceService());
Role role = roleMgr.find(roleId);
Set<String> roleByUser = new HashSet<String>();
if(role != null) {
roleByUser = role.getSubjects();
}
LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
LdapUserManager userMgr = new LdapUserManager(ldapSvc);
List<DepartmentVo> deptVoList = null;
List<UserVo> userVoList = null;
String type = request.getParameter("type");
if (StringUtils.isNotBlank(type) && "task".equals(type)) {
deptVoList = DepartmentService.fillDepartmentListPropertiesToVoByRoleId(deptMgr.getChildrenById(id), type, roleId);
} else {
deptVoList = DepartmentService.fillPropertiesToVo(deptMgr.getChildrenById(id));
}
userVoList = UserService.fillUserListPropertiesToVo(userMgr.findByDepartmentId(id));
List<OrganizationNodeVo> orgList = this.mergeDepartmentVoAndUserVoCheckUser(deptVoList, userVoList, roleByUser);
return orgList;
}
private List<OrganizationNodeVo> mergeDepartmentVoAndUserVoCheckUser(List<DepartmentVo> deptVoList,
List<UserVo> userVoList,
Set<String> userId) {
List<OrganizationNodeVo> orgNodeVoList = new ArrayList<OrganizationNodeVo>();
for (DepartmentVo deptVo: deptVoList) {
OrganizationNodeVo orgNodeVo = new OrganizationNodeVo();
orgNodeVo.setId(deptVo.getId());
orgNodeVo.setCheckName(deptVo.getCheckName());
orgNodeVo.setIo(deptVo.getIo());
orgNodeVo.setLabel(deptVo.getLabel());
orgNodeVo.setType(deptVo.getType());
orgNodeVo.setFullPath(deptVo.getId());
orgNodeVo.setKind(deptVo.getKind());
orgNodeVoList.add(orgNodeVo);
}
for (UserVo userVo: userVoList) {
OrganizationNodeVo orgNodeVo = new OrganizationNodeVo();
orgNodeVo.setId(userVo.getCheckName());
orgNodeVo.setCheckName(userVo.getCheckName());
orgNodeVo.setIo(userVo.getId());
for(String id:userId){
if(id.equals(userVo.getId())){
orgNodeVo.setChecked(true);
}
}
orgNodeVo.setLabel(userVo.getLabel());
orgNodeVo.setType("task");
orgNodeVo.setLeaf(userVo.isLeaf());
orgNodeVo.setFullPath("uid=" + userVo.getId() + "," + userVo.getDeptFullPath());
orgNodeVo.setKind(userVo.getKind());
orgNodeVoList.add(orgNodeVo);
}
return orgNodeVoList;
}
public static DepartmentVo fillDepartmentPropertiesToVoByRole(Department dept, String roleId) {
DepartmentVo deptVo = new DepartmentVo();
deptVo.setId(dept.getId());
deptVo.setType("io");
deptVo.setLabel(dept.getName());
deptVo.setCheckName(dept.getId());
deptVo.setLeaf(false);
if (StringUtils.isBlank(dept.getParent())) {
deptVo.setDeptFullPath("o=" + dept.getId());
} else {
deptVo.setDeptFullPath("ou=" + dept.getId() + "," + dept.getParent());
}
if (StringUtils.isBlank(deptVo.getDeptFullPath())) {
deptVo.setIo("/rest/depts/root/children");
} else {
deptVo.setIo("/rest/depts/" + deptVo.getDeptFullPath() + "/children/"+roleId);
}
deptVo.setKind("dept");
return deptVo;
}
public static List<DepartmentVo> fillDepartmentListPropertiesToVoByRoleId(List<Department> deptList,
String type,
String roleId) {
List<DepartmentVo> deptVoList = new ArrayList<DepartmentVo>(deptList.size());
DepartmentVo deptVo = null;
for (Department dept : deptList) {
deptVo = DepartmentService.fillDepartmentPropertiesToVoByRole(dept, roleId);
deptVo.setIo(deptVo.getIo() + "?type=task");
deptVo.setType(type);
deptVoList.add(deptVo);
}
return deptVoList;
}
// @GET
// @Path("/get_children/{id}")
// @Produces("application/json")
// public List<Department> getChindren(@PathParam("id") String id) throws UserPersistException {
// List<Department> deptList = null;
// LdapService ldapSvc = this.getLdapService();
// LdapDepartmentManager deptMgr = new LdapDepartmentManager(ldapSvc);
// deptList = deptMgr.getChildrenById(id);
// return deptList;
}
|
package de.gurkenlabs.litiengine.gui;
import de.gurkenlabs.litiengine.Align;
import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.Valign;
import de.gurkenlabs.litiengine.graphics.IRenderable;
import de.gurkenlabs.litiengine.graphics.ShapeRenderer;
import de.gurkenlabs.litiengine.graphics.TextRenderer;
import de.gurkenlabs.litiengine.input.Input;
import de.gurkenlabs.litiengine.resources.Resources;
import de.gurkenlabs.litiengine.sound.Sound;
import de.gurkenlabs.litiengine.tweening.TweenType;
import de.gurkenlabs.litiengine.tweening.Tweenable;
import de.gurkenlabs.litiengine.util.ColorHelper;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RectangularShape;
import java.awt.geom.RoundRectangle2D;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
/**
* The abstract Class GuiComponent provides all properties and methods needed for screens, built-in, and custom GUI
* components such as buttons, sliders, etc... It includes mouse event handling, different hovering states and
* appearances, and texts to be rendered.
*/
public abstract class GuiComponent
implements MouseListener, MouseMotionListener, MouseWheelListener, IRenderable, Tweenable {
protected static final Font ICON_FONT;
private static int id = 0;
static {
final Font icon = Resources.fonts().get("fontello.ttf");
ICON_FONT = icon != null ? icon.deriveFont(16f) : null;
}
private final List<Consumer<ComponentMouseEvent>> clickConsumer;
private final List<Consumer<ComponentMouseEvent>> mouseDraggedConsumer;
private final List<Consumer<ComponentMouseEvent>> mouseEnterConsumer;
private final List<Consumer<ComponentMouseEvent>> mouseLeaveConsumer;
private final List<Consumer<ComponentMouseEvent>> mouseMovedConsumer;
private final List<Consumer<ComponentMouseEvent>> mousePressedConsumer;
private final List<Consumer<ComponentMouseEvent>> mouseReleasedConsumer;
private final List<Consumer<ComponentMouseWheelEvent>> mouseWheelConsumer;
private final List<Consumer<ComponentMouseEvent>> hoverConsumer;
private final List<Consumer<String>> textChangedConsumer;
private final Collection<ComponentRenderListener> renderListeners = ConcurrentHashMap.newKeySet();
private final Collection<ComponentRenderedListener> renderedListeners = ConcurrentHashMap.newKeySet();
private final int componentId;
private final Appearance appearance;
private final Appearance hoveredAppearance;
private final List<GuiComponent> components;
private final Appearance disabledAppearance;
private boolean enabled;
private Font font;
private boolean forwardMouseEvents = true;
private double width;
private double height;
private Sound hoverSound;
private boolean textAntialiasing;
private boolean textShadow;
private Color textShadowColor;
private float textShadowRadius;
private boolean isHovered;
private boolean isPressed;
private boolean isSelected;
private String name;
private boolean suspended;
private Object tag;
private String text;
private Align textAlign;
private Valign textValign;
private boolean automaticLineBreaks;
private int textAngle = 0;
private double textX;
private double textY;
private boolean visible;
private Point2D location;
private Rectangle2D boundingBox;
/**
* Instantiates a new gui component with the dimension (0,0) at the given location.
*
* @param x
* the x
* @param y
* the y
*/
protected GuiComponent(final double x, final double y) {
this(x, y, 0, 0);
}
/**
* Instantiates a new gui component at the point (x,y) with the dimension (width,height).
*
* @param x
* the x
* @param y
* the y
* @param width
* the width
* @param height
* the height
*/
protected GuiComponent(final double x, final double y, final double width, final double height) {
this.components = new CopyOnWriteArrayList<>();
this.clickConsumer = new CopyOnWriteArrayList<>();
this.hoverConsumer = new CopyOnWriteArrayList<>();
this.mousePressedConsumer = new CopyOnWriteArrayList<>();
this.mouseDraggedConsumer = new CopyOnWriteArrayList<>();
this.mouseEnterConsumer = new CopyOnWriteArrayList<>();
this.mouseLeaveConsumer = new CopyOnWriteArrayList<>();
this.mouseReleasedConsumer = new CopyOnWriteArrayList<>();
this.mouseWheelConsumer = new CopyOnWriteArrayList<>();
this.mouseMovedConsumer = new CopyOnWriteArrayList<>();
this.textChangedConsumer = new CopyOnWriteArrayList<>();
this.appearance = new Appearance();
this.appearance.update(GuiProperties.getDefaultAppearance());
this.appearance.onChange(
app -> {
for (final GuiComponent child : this.getComponents()) {
child.getAppearance().update(this.getAppearance());
}
});
this.hoveredAppearance = new Appearance();
this.hoveredAppearance.update(GuiProperties.getDefaultAppearanceHovered());
this.hoveredAppearance.onChange(
app -> {
for (final GuiComponent child : this.getComponents()) {
child.getAppearanceHovered().update(this.getAppearanceHovered());
}
});
this.disabledAppearance = new Appearance();
this.disabledAppearance.update(GuiProperties.getDefaultAppearanceDisabled());
this.disabledAppearance.onChange(
app -> {
for (final GuiComponent child : this.getComponents()) {
child.getAppearanceDisabled().update(this.getAppearanceDisabled());
}
});
setTextAlign(GuiProperties.getDefaultTextAlign());
setTextValign(GuiProperties.getDefaultTextValign());
setTextAntialiasing(GuiProperties.getDefaultTextAntialiasing());
setTextShadow(GuiProperties.getDefaultTextShadow());
setTextShadowColor(GuiProperties.getDefaultTextShadowColor());
setTextShadowRadius(GuiProperties.getDefaultTextShadowRadius());
this.componentId = ++id;
setLocation(x, y);
setDimension(width, height);
setFont(GuiProperties.getDefaultFont());
setSelected(false);
setEnabled(true);
initializeComponents();
}
/**
* Gets the default appearance object for this GuiComponent.
*
* @return the appearance
*/
public Appearance getAppearance() {
return this.appearance;
}
/**
* Gets the appearance object for this GuiComponent while disabled.
*
* @return the appearance disabled
*/
public Appearance getAppearanceDisabled() {
return this.disabledAppearance;
}
/**
* Gets the appearance object for this GuiComponent while hovered.
*
* @return the hovered appearance
*/
public Appearance getAppearanceHovered() {
return this.hoveredAppearance;
}
/**
* Gets the bounding box of this GuiComponent.
*
* @return the bounding box
*/
public Rectangle2D getBoundingBox() {
if (boundingBox != null) {
return boundingBox;
}
this.boundingBox = new Rectangle2D.Double(getX(), getY(), getWidth(), getHeight());
return boundingBox;
}
/**
* Gets the component id of this GuiComponent.
*
* @return the component id
*/
public int getComponentId() {
return this.componentId;
}
/**
* Gets the child components of this GuiComponent.
*
* @return the child components
*/
public List<GuiComponent> getComponents() {
return this.components;
}
/**
* Gets the font of this GuiComponent's text.
*
* @return the GuiComponent's font
*/
public Font getFont() {
return this.font;
}
/**
* Gets the height of this GuiComponent.
*
* @return the height
*/
public double getHeight() {
return this.height;
}
/**
* Gets the sound that is played when hovering the GuiComponent.
*
* @return the hover sound
*/
public Sound getHoverSound() {
return this.hoverSound;
}
/**
* Gets the screen location of this GuiComponent.
*
* @return the screen location
*/
public Point2D getLocation() {
return location;
}
/**
* Gets the name of this GuiComponent.
*
* @return the name
*/
public String getName() {
return this.name;
}
/**
* Gets the tag.
*
* @return the tag
*/
public Object getTag() {
return this.tag;
}
/**
* Gets the entire Text associated with this GuiComponent. Parts of the Text may get cropped and can therefore be
* invisible. To retrieve only the visible part of the text, use {@code
* GuiComponent.getTextToRender(Graphics2D g)}.
*
* @return the entire text on this GuiComponent
*/
public String getText() {
return this.text;
}
/**
* Gets the horizontal text alignment.
*
* @return the horizontal text alignment
*/
public Align getTextAlign() {
return this.textAlign;
}
/**
* Gets the vertical text alignment.
*
* @return the vertical text alignment
*/
public Valign getTextValign() {
return this.textValign;
}
/**
* Gets the text angle.
*
* @return the text angle
*/
public int getTextAngle() {
return this.textAngle;
}
/**
* Check whether text antialiasing is activated.
*
* @return true, if this GuiComponent is currently configured to draw its text with antialiasing.
*/
public boolean hasTextAntialiasing() {
return this.textAntialiasing;
}
/**
* Check whether text shadow is activated.
*
* @return true, if this GuiComponent is currently configured to draw a shadow below its text.
*/
public boolean hasTextShadow() {
return this.textShadow;
}
public Color getTextShadowColor() {
return textShadowColor;
}
public void setTextShadowColor(Color textShadowColor) {
this.textShadowColor = textShadowColor;
}
public float getTextShadowRadius() {
return textShadowRadius;
}
public void setTextShadowRadius(float textShadowRadius) {
this.textShadowRadius = textShadowRadius;
}
public boolean hasAutomaticLineBreaks() {
return this.automaticLineBreaks;
}
/**
* Gets only the non-cropped bits of Text visible on this GuiComponent.m To retrieve only the entire text associated
* with this GuiComponent, use {@code GuiComponent.getText()}.
*
* @param g
* The graphics object to render on.
* @return the text to render
*/
public String getTextToRender(final Graphics2D g) {
if (this.getText() == null) {
return "";
} else if (hasAutomaticLineBreaks()) {
return getText();
}
final FontMetrics fm = g.getFontMetrics();
String newText = getText();
while (newText.length() > 1 && fm.stringWidth(newText) >= getWidth()) {
newText = newText.substring(1);
}
return newText;
}
/**
* Gets the text X coordinate.
*
* @return the text X
*/
public double getTextX() {
return textX;
}
/**
* Gets the text Y coordinate.
*
* @return the text Y
*/
public double getTextY() {
return textY;
}
/**
* Gets the width of this GuiComponent.
*
* @return the width
*/
public double getWidth() {
return width;
}
/**
* Gets the x coordinate of this GuiComponent.
*
* @return the x coordinate
*/
public double getX() {
return getLocation().getX();
}
/**
* Gets the y coordinate of this GuiComponent.
*
* @return the y coordinate
*/
public double getY() {
return getLocation().getY();
}
/**
* Checks if the GuiComponent is enabled.
*
* @return true, if is enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* Checks if mouse events are being forwarded by this GuiComponent.
*
* @return true, the GuiComponent forwards mouse events
*/
public boolean isForwardMouseEvents() {
return forwardMouseEvents;
}
/**
* Checks if the cursor bounding box intersects with this GuiComponent's bounding box.
*
* @return true, if the GuiComponent is hovered
*/
public boolean isHovered() {
return isHovered;
}
/**
* Checks if the mouse button is currently being pressed on this GuiComponent.
*
* @return true, if the mouse is currently pressed on the GuiComponent
*/
public boolean isPressed() {
return isPressed;
}
/**
* Checks if the GuiComponent is currently selected.
*
* @return true, if the GuiComponent is selected
*/
public boolean isSelected() {
return isSelected;
}
/**
* Checks if the GuiComponent is currently suspended.
*
* @return true, if the GuiComponent is suspended
*/
public boolean isSuspended() {
return suspended;
}
/**
* Checks if the GuiComponent is currently visible.
*
* @return true, if the GuiComponent is visible
*/
public boolean isVisible() {
return visible;
}
@Override
public void mouseClicked(final MouseEvent e) {
if (!this.mouseEventShouldBeForwarded(e)) {
return;
}
if (this.isPressed) {
final ComponentMouseEvent event = new ComponentMouseEvent(e, this);
this.getClickConsumer().forEach(consumer -> consumer.accept(event));
this.isPressed = false;
}
}
@Override
public void mouseDragged(final MouseEvent e) {
if (!this.mouseEventShouldBeForwarded(e)) {
return;
}
final ComponentMouseEvent event = new ComponentMouseEvent(e, this);
this.getMouseDraggedConsumer().forEach(consumer -> consumer.accept(event));
}
@Override
public void mouseEntered(final MouseEvent e) {
if (!isForwardMouseEvents()) {
return;
}
if (!mouseEventShouldBeForwarded(e)) {
this.isHovered = false;
return;
}
this.isHovered = true;
final ComponentMouseEvent event = new ComponentMouseEvent(e, this);
getHoverConsumer().forEach(consumer -> consumer.accept(event));
if (getHoverSound() != null) {
Game.audio().playSound(getHoverSound());
}
this.getMouseEnterConsumer().forEach(consumer -> consumer.accept(event));
}
@Override
public void mouseExited(final MouseEvent e) {
if (!isForwardMouseEvents()) {
return;
}
this.isHovered = false;
this.isPressed = false;
final ComponentMouseEvent event = new ComponentMouseEvent(e, this);
getMouseLeaveConsumer().forEach(consumer -> consumer.accept(event));
}
@Override
public void mouseMoved(final MouseEvent e) {
if (!mouseEventShouldBeForwarded(e) && isHovered()) {
mouseExited(e);
return;
}
// also throw enter event if the mouse did not hover the component
// before
if (!isHovered()) {
mouseEntered(e);
}
final ComponentMouseEvent event = new ComponentMouseEvent(e, this);
getMouseMovedConsumer().forEach(consumer -> consumer.accept(event));
}
@Override
public void mousePressed(final MouseEvent e) {
if (!mouseEventShouldBeForwarded(e)) {
return;
}
this.isPressed = true;
final ComponentMouseEvent event = new ComponentMouseEvent(e, this);
getMousePressedConsumer().forEach(consumer -> consumer.accept(event));
}
@Override
public void mouseReleased(final MouseEvent e) {
if (!mouseEventShouldBeForwarded(e)) {
return;
}
this.isPressed = false;
final ComponentMouseEvent event = new ComponentMouseEvent(e, this);
// TODO: check if this should really call the clicked consumers...
getClickConsumer().forEach(consumer -> consumer.accept(event));
getMouseReleasedConsumer().forEach(consumer -> consumer.accept(event));
}
@Override
public void mouseWheelMoved(final MouseWheelEvent e) {
getMouseWheelConsumer().forEach(consumer -> consumer.accept(new ComponentMouseWheelEvent(e, this)));
}
/**
* Add a callback that is being executed if this GuiComponent is clicked once.
*
* @param callback
* the callback
*/
public void onClicked(final Consumer<ComponentMouseEvent> callback) {
if (!getClickConsumer().contains(callback)) {
getClickConsumer().add(callback);
}
}
/**
* Add a callback that is being executed if this GuiComponent is hovered with the mouse.
*
* @param callback
* the callback
*/
public void onHovered(final Consumer<ComponentMouseEvent> callback) {
if (!getHoverConsumer().contains(callback)) {
getHoverConsumer().add(callback);
}
}
/**
* Add a callback that is being executed if the mouse is pressed and moving around while within the bounds of this
* GuiComponent.
*
* @param callback
* the callback
*/
public void onMouseDragged(final Consumer<ComponentMouseEvent> callback) {
if (!getMouseDraggedConsumer().contains(callback)) {
getMouseDraggedConsumer().add(callback);
}
}
/**
* Add a callback that is being executed if the mouse enters the bounds of this GuiComponent.
*
* @param callback
* the callback
*/
public void onMouseEnter(final Consumer<ComponentMouseEvent> callback) {
if (!this.getMouseEnterConsumer().contains(callback)) {
this.getMouseEnterConsumer().add(callback);
}
}
/**
* Add a callback that is being executed if the mouse leaves the bounds of this GuiComponent.
*
* @param callback
* the callback
*/
public void onMouseLeave(final Consumer<ComponentMouseEvent> callback) {
if (!getMouseLeaveConsumer().contains(callback)) {
getMouseLeaveConsumer().add(callback);
}
}
/**
* Add a callback that is being executed if the mouse is moving around while within the bounds of this GuiComponent.
*
* @param callback
* the callback
*/
public void onMouseMoved(final Consumer<ComponentMouseEvent> callback) {
if (!getMouseMovedConsumer().contains(callback)) {
getMouseMovedConsumer().add(callback);
}
}
/**
* Add a callback that is being executed if the mouse is continually pressed while within the bounds of this
* GuiComponent.
*
* @param callback
* the callback
*/
public void onMousePressed(final Consumer<ComponentMouseEvent> callback) {
if (!getMousePressedConsumer().contains(callback)) {
getMousePressedConsumer().add(callback);
}
}
/**
* Add a callback that is being executed if the mouse button is released while within the bounds of this GuiComponent.
*
* @param callback
* the callback
*/
public void onMouseReleased(final Consumer<ComponentMouseEvent> callback) {
if (!getMouseReleasedConsumer().contains(callback)) {
getMouseReleasedConsumer().add(callback);
}
}
/**
* Add a callback that is being executed if the mouse wheel is scrolled while within the bounds of this GuiComponent.
*
* @param callback
* the callback
*/
public void onMouseWheelScrolled(final Consumer<ComponentMouseWheelEvent> callback) {
if (!getMouseWheelConsumer().contains(callback)) {
getMouseWheelConsumer().add(callback);
}
}
/**
* Add a callback that is being executed if the text on this GuiComponent changes.
*
* @param cons
* the cons
*/
public void onTextChanged(final Consumer<String> cons) {
this.textChangedConsumer.add(cons);
}
public void addRenderListener(final ComponentRenderListener listener) {
this.renderListeners.add(listener);
}
public void removeListener(final ComponentRenderListener listener) {
this.renderListeners.remove(listener);
}
public void addRenderedListener(final ComponentRenderedListener listener) {
this.renderedListeners.add(listener);
}
public void removeListener(final ComponentRenderedListener listener) {
this.renderedListeners.remove(listener);
}
/**
* Prepare the GuiComponent and all its child Components (Makes the GuiComponent visible and adds mouse listeners.).
* This is, for example, done right before switching to a new screen.
*/
public void prepare() {
this.suspended = false;
this.visible = true;
Input.mouse().addMouseListener(this);
Input.mouse().onWheelMoved(this);
Input.mouse().addMouseMotionListener(this);
for (final GuiComponent component : this.getComponents()) {
component.prepare();
}
}
/**
* Note: If you override this and are modifying swing components, be sure you are in the AWT thread when you do so!
*/
@Override
public void render(final Graphics2D g) {
if (this.isSuspended() || !this.isVisible()) {
return;
}
for (ComponentRenderListener listener : this.renderListeners) {
if (!listener.canRender(this)) {
return;
}
}
final ComponentRenderEvent event = new ComponentRenderEvent(g, this);
for (ComponentRenderListener listener : this.renderListeners) {
listener.rendering(event);
}
Shape clip = g.getClip();
g.clip(this.getShape());
if (!getCurrentAppearance().isTransparentBackground()) {
g.setPaint(getCurrentAppearance().getBackgroundPaint(this.getWidth(), this.getHeight()));
ShapeRenderer.render(g, getBoundingBox());
}
g.setColor(getCurrentAppearance().getForeColor());
g.setFont(this.getFont());
this.renderText(g);
g.setClip(clip);
if (getCurrentAppearance().getBorderColor() != null
&& getCurrentAppearance().getBorderStyle() != null) {
g.setColor(getCurrentAppearance().getBorderColor());
ShapeRenderer.renderOutline(g, getBoundingBox(), getCurrentAppearance().getBorderStyle());
}
for (final GuiComponent component : this.getComponents()) {
if (!component.isVisible() || component.isSuspended()) {
continue;
}
component.render(g);
}
for (ComponentRenderListener listener : this.renderListeners) {
listener.rendered(event);
}
for (ComponentRenderedListener listener : this.renderedListeners) {
listener.rendered(event);
}
if (Game.config().debug().renderGuiComponentBoundingBoxes()) {
g.setColor(Color.RED);
ShapeRenderer.renderOutline(g, getBoundingBox());
}
}
@Override
public float[] getTweenValues(TweenType tweenType) {
switch (tweenType) {
case POSITION_X:
return new float[] {(float) this.getX()};
case POSITION_Y:
return new float[] {(float) this.getY()};
case POSITION_XY:
return new float[] {(float) this.getX(), (float) this.getY()};
case SIZE_WIDTH:
return new float[] {(float) this.getWidth()};
case SIZE_HEIGHT:
return new float[] {(float) this.getHeight()};
case SIZE_BOTH:
return new float[] {(float) this.getWidth(), (float) this.getHeight()};
case ANGLE:
return new float[] {this.getTextAngle()};
case FONTSIZE:
return new float[] {this.getFont().getSize2D()};
case OPACITY:
Color bg1 = this.getCurrentAppearance().getBackgroundColor1();
Color bg2 = this.getCurrentAppearance().getBackgroundColor2();
Color fore = this.getCurrentAppearance().getForeColor();
Color shadow = this.getTextShadowColor();
Color border = this.getCurrentAppearance().getBorderColor();
return new float[] {
bg1 == null ? 0 : bg1.getAlpha(),
bg2 == null ? 0 : bg2.getAlpha(),
fore == null ? 0 : fore.getAlpha(),
shadow == null ? 0 : shadow.getAlpha(),
border == null ? 0 : border.getAlpha()
};
default:
return Tweenable.super.getTweenValues(tweenType);
}
}
@Override
public void setTweenValues(TweenType tweenType, float[] newValues) {
switch (tweenType) {
case POSITION_X -> this.setX(newValues[0]);
case POSITION_Y -> this.setY(newValues[0]);
case POSITION_XY -> {
this.setX(newValues[0]);
this.setY(newValues[1]);
}
case SIZE_WIDTH -> this.setWidth(newValues[0]);
case SIZE_HEIGHT -> this.setHeight(newValues[0]);
case SIZE_BOTH -> {
this.setWidth(newValues[0]);
this.setHeight(newValues[1]);
}
case ANGLE -> this.setTextAngle(Math.round(newValues[0]));
case FONTSIZE -> this.setFontSize(newValues[0]);
case OPACITY -> {
Color bg1 = this.getCurrentAppearance().getBackgroundColor1();
Color bg2 = this.getCurrentAppearance().getBackgroundColor2();
Color fore = this.getCurrentAppearance().getForeColor();
Color border = this.getCurrentAppearance().getBorderColor();
getCurrentAppearance()
.setBackgroundColor1(
bg1 == null ? null : ColorHelper.getTransparentVariant(bg1, (int) newValues[0]));
getCurrentAppearance()
.setBackgroundColor2(
bg2 == null ? null : ColorHelper.getTransparentVariant(bg2, (int) newValues[1]));
getCurrentAppearance()
.setForeColor(
fore == null ? null : ColorHelper.getTransparentVariant(fore, (int) newValues[2]));
setTextShadowColor(
getTextShadowColor() == null
? null
: ColorHelper.getTransparentVariant(getTextShadowColor(), (int) newValues[3]));
getCurrentAppearance()
.setBorderColor(
border == null
? null
: ColorHelper.getTransparentVariant(border, (int) newValues[4]));
}
default -> Tweenable.super.setTweenValues(tweenType, newValues);
}
}
public RectangularShape getShape() {
float radius = this.getCurrentAppearance().getBorderRadius();
if (radius == 0f) {
return this.getBoundingBox();
}
return new RoundRectangle2D.Double(
this.getX(),
this.getY(),
this.getWidth(),
this.getHeight(),
this.getCurrentAppearance().getBorderRadius(),
this.getCurrentAppearance().getBorderRadius());
}
/**
* Sets the width and height of this GuiComponent.
*
* @param width
* the width
* @param height
* the height
*/
public void setDimension(final double width, final double height) {
setWidth(width);
setHeight(height);
}
/**
* Sets the "enabled" property on this GuiComponent and its child components.
*
* @param enabled
* the new enabled property
*/
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
for (final GuiComponent comp : this.getComponents()) {
comp.setEnabled(this.isEnabled());
}
}
/**
* Sets the font for this GuiComponent's text.
*
* @param font
* the new font
*/
public void setFont(final Font font) {
this.font = font;
}
/**
* Sets the font size for this GuiComponent's text.
*
* @param size
* the new font size
*/
public void setFontSize(final float size) {
if (this.font == null) {
return;
}
this.font = this.font.deriveFont(size);
}
/**
* Enable or disable forwarding mouse events by this GuiComponent.
*
* @param forwardMouseEvents
* the new forward mouse events
*/
public void setForwardMouseEvents(final boolean forwardMouseEvents) {
this.forwardMouseEvents = forwardMouseEvents;
}
/**
* Sets the GuiComponent's height.
*
* @param height
* the new height
*/
public void setHeight(final double height) {
this.height = height;
this.boundingBox = null; // trigger recreation in next boundingBox getter call
}
/**
* Sets the "hovered" property on this GuiComponent.
*
* @param hovered
* the new hovered
*/
public void setHovered(final boolean hovered) {
this.isHovered = hovered;
}
/**
* Sets the hover sound.
*
* @param hoverSound
* the new hover sound
*/
public void setHoverSound(final Sound hoverSound) {
this.hoverSound = hoverSound;
}
/**
* Sets this GuiComponent's location.
*
* @param x
* the new x coordinate
* @param y
* the new y coordinate
*/
public void setLocation(final double x, final double y) {
setLocation(new Point2D.Double(x, y));
}
/**
* Sets this GuiComponent's location.
*
* @param location
* the new location
*/
public void setLocation(final Point2D location) {
this.location = location;
this.boundingBox = null; // trigger recreation in next boundingBox getter call
final double deltaX = location.getX() - getX();
final double deltaY = location.getY() - getY();
for (final GuiComponent component : getComponents()) {
component.setLocation(new Point2D.Double(component.getX() + deltaX, component.getY() + deltaY));
}
}
/**
* Sets this GuiComponent's name.
*
* @param name
* the new name
*/
public void setName(final String name) {
this.name = name;
}
/**
* Sets the "selected" property on this GuiComponent.
*
* @param bool
* the new selected
*/
public void setSelected(final boolean bool) {
this.isSelected = bool;
}
/**
* Sets the tag.
*
* @param tag
* the new tag
*/
public void setTag(final Object tag) {
this.tag = tag;
}
/**
* Sets the text.
*
* @param text
* the new text
*/
public void setText(final String text) {
this.text = text;
for (final Consumer<String> cons : this.textChangedConsumer) {
cons.accept(this.getText());
}
}
/**
* Sets the {@link RenderingHints#KEY_TEXT_ANTIALIASING} settings for the rendered text.
*
* @param antialiasing
* Either {@link RenderingHints#VALUE_TEXT_ANTIALIAS_ON} or {@link RenderingHints#VALUE_TEXT_ANTIALIAS_OFF}
*/
public void setTextAntialiasing(boolean antialiasing) {
this.textAntialiasing = antialiasing;
}
public void setAutomaticLineBreaks(boolean automaticLineBreaks) {
this.automaticLineBreaks = automaticLineBreaks;
}
/**
* Sets the horizontal text alignment.
*
* @param textAlign
* the new text align
*/
public void setTextAlign(final Align textAlign) {
this.textAlign = textAlign;
}
/**
* Sets the vertical text alignment.
*
* @param textValign
* the new text align
*/
public void setTextValign(final Valign textValign) {
this.textValign = textValign;
}
/**
* Sets the text angle in degrees.
*
* @param textAngle
* the new text angle in degrees
*/
public void setTextAngle(final int textAngle) {
this.textAngle = textAngle;
}
/**
* Enable or disable the shadow being drawn below the text
*
* @param drawTextShadow
* the boolean determining if a text shadow should be drawn
*/
public void setTextShadow(final boolean drawTextShadow) {
this.textShadow = drawTextShadow;
for (final GuiComponent comp : this.getComponents()) {
comp.setTextShadow(drawTextShadow);
}
}
/**
* Sets the text X coordinate.
*
* @param x
* the new text X
*/
public void setTextX(final double x) {
this.textX = x;
}
/**
* Sets the text Y coordinate.
*
* @param y
* the new text Y
*/
public void setTextY(final double y) {
this.textY = y;
}
/**
* Sets the "visible" property on this GuiComponent.
*
* @param visible
* the new visible
*/
public void setVisible(final boolean visible) {
this.visible = visible;
for (final GuiComponent component : this.getComponents()) {
component.setVisible(visible);
}
}
/**
* Sets the GuiComponent's width.
*
* @param width
* the new width
*/
public void setWidth(final double width) {
this.width = width;
this.boundingBox = null; // trigger recreation in next boundingBox getter call
}
/**
* Sets the GuiComponent's x coordinate.
*
* @param x
* the new x coordinate
*/
public void setX(final double x) {
final double delta = x - getX();
setLocation(x, getY());
for (final GuiComponent component : getComponents()) {
component.setX(component.getX() + delta);
}
}
/**
* Sets the GuiComponent's y coordinate.
*
* @param y
* the new y coordinate
*/
public void setY(final double y) {
final double delta = y - getY();
setLocation(getX(), y);
for (final GuiComponent component : getComponents()) {
component.setY(component.getY() + delta);
}
}
/**
* Suspend the GuiComponent and all its child Components (Makes the GuiComponent invisible and removes mouse
* listeners.).
*/
public void suspend() {
Input.mouse().removeMouseListener(this);
Input.mouse().removeMouseWheelListener(this);
Input.mouse().removeMouseMotionListener(this);
this.suspended = true;
this.visible = false;
for (final GuiComponent childComp : this.getComponents()) {
childComp.suspend();
}
}
/**
* Toggle this GuiComponent's selection.
*/
public void toggleSelection() {
this.setSelected(!this.isSelected);
}
/**
* Toggle this GuiComponent's suspension state. If it's suspended, prepare it. If it's prepared, suspend it.
*/
public void toggleSuspension() {
if (!this.isSuspended()) {
this.suspend();
} else {
this.prepare();
}
}
public Appearance getCurrentAppearance() {
if (!this.isEnabled()) {
return this.getAppearanceDisabled();
}
return this.isHovered() ? this.getAppearanceHovered() : this.getAppearance();
}
/**
* Gets the click consumer list.
*
* @return the click consumer list
*/
protected List<Consumer<ComponentMouseEvent>> getClickConsumer() {
return this.clickConsumer;
}
/**
* Gets the hover consumer list.
*
* @return the hover consumer list
*/
protected List<Consumer<ComponentMouseEvent>> getHoverConsumer() {
return this.hoverConsumer;
}
/**
* Gets the mouse dragged consumer list.
*
* @return the mouse dragged consumer list
*/
protected List<Consumer<ComponentMouseEvent>> getMouseDraggedConsumer() {
return this.mouseDraggedConsumer;
}
/**
* Gets the mouse enter consumer list.
*
* @return the mouse enter consumer list
*/
protected List<Consumer<ComponentMouseEvent>> getMouseEnterConsumer() {
return this.mouseEnterConsumer;
}
/**
* Gets the mouse leave consumer list.
*
* @return the mouse leave consumer list
*/
protected List<Consumer<ComponentMouseEvent>> getMouseLeaveConsumer() {
return this.mouseLeaveConsumer;
}
/**
* Gets the mouse moved consumer list.
*
* @return the mouse moved consumer list
*/
protected List<Consumer<ComponentMouseEvent>> getMouseMovedConsumer() {
return this.mouseMovedConsumer;
}
/**
* Gets the mouse pressed consumer list.
*
* @return the mouse pressed consumer list
*/
protected List<Consumer<ComponentMouseEvent>> getMousePressedConsumer() {
return this.mousePressedConsumer;
}
/**
* Gets the mouse released consumer list.
*
* @return the mouse released consumer list
*/
protected List<Consumer<ComponentMouseEvent>> getMouseReleasedConsumer() {
return this.mouseReleasedConsumer;
}
/**
* Gets the mouse wheel consumer list.
*
* @return the mouse wheel consumer list
*/
protected List<Consumer<ComponentMouseWheelEvent>> getMouseWheelConsumer() {
return this.mouseWheelConsumer;
}
/**
* Initialize child components.
*/
protected void initializeComponents() {
// nothing to do in the base class
}
/**
* Check if a Mouse event should be forwarded.
*
* @param e
* the mouse event
* @return true, if the Mouse event should be forwarded
*/
protected boolean mouseEventShouldBeForwarded(final MouseEvent e) {
return this.isForwardMouseEvents()
&& this.isVisible()
&& this.isEnabled()
&& !this.isSuspended()
&& e != null
&& this.getBoundingBox().contains(e.getPoint());
}
/**
* Render this GuiComponent's text.
*
* @param g
* the {@code Graphics2D} object used for drawing
*/
private void renderText(final Graphics2D g) {
if (this.getText() == null || this.getText().isEmpty()) {
return;
}
final FontMetrics fm = g.getFontMetrics();
double textWidth = fm.stringWidth(this.getTextToRender(g));
double textHeight = (double) fm.getAscent() + fm.getDescent();
double xCoord =
this.getTextAlign() != null
? this.getX() + this.getTextAlign().getLocation(this.getWidth(), textWidth)
: this.getTextX();
double yCoord =
this.getTextValign() != null
? this.getY() + this.getTextValign().getLocation(this.getHeight(), textHeight)
: this.getTextY();
if (this.getTextAngle() == 0) {
if (this.hasTextShadow()) {
TextRenderer.renderWithOutline(
g,
this.getTextToRender(g),
this.getX(),
this.getY(),
this.getWidth(),
this.getHeight(),
this.getTextShadowColor(),
this.getTextShadowRadius(),
this.getTextAlign(),
this.getTextValign(),
this.hasTextAntialiasing());
} else {
TextRenderer.renderWithLinebreaks(
g,
this.getTextToRender(g),
this.getTextAlign(),
this.getTextValign(),
this.getX(),
this.getY(),
this.getWidth(),
this.getHeight(),
this.hasTextAntialiasing());
}
} else if (this.getTextAngle() == 90) {
TextRenderer.renderRotated(
g,
this.getTextToRender(g),
xCoord,
yCoord - fm.stringWidth(this.getTextToRender(g)),
this.getTextAngle(),
this.hasTextAntialiasing());
} else {
TextRenderer.renderRotated(
g,
this.getTextToRender(g),
xCoord,
yCoord,
this.getTextAngle(),
this.hasTextAntialiasing());
}
}
}
|
package org.mini2Dx.core.engine.geom;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.mini2Dx.core.engine.PositionChangeListener;
import org.mini2Dx.core.engine.Positionable;
import org.mini2Dx.core.engine.SizeChangeListener;
import org.mini2Dx.core.engine.Sizeable;
import org.mini2Dx.core.game.GameContainer;
import org.mini2Dx.core.geom.Point;
import org.mini2Dx.core.geom.Rectangle;
import org.mini2Dx.core.geom.Shape;
import org.mini2Dx.core.graphics.Graphics;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
/**
* An implementation of {@link Rectangle} that allows for interpolation. Game
* objects can use this class to move around the game world and retrieve the
* appropriate rendering coordinates after interpolating between the previous
* and current position.
*/
public class CollisionBox extends Rectangle implements CollisionShape {
private static final long serialVersionUID = -8217730724587578266L;
private final int id;
private final ReentrantReadWriteLock positionChangeListenerLock;
private final ReentrantReadWriteLock sizeChangeListenerLock;
private final Vector2 tmpSourceVector = new Vector2();
private final Vector2 tmpTargetVector = new Vector2();
private final Rectangle previousRectangle;
private final Rectangle renderRectangle;
private List<PositionChangeListener> positionChangeListeners;
private List<SizeChangeListener> sizeChangeListeners;
private int renderX, renderY, renderWidth, renderHeight;
private boolean interpolate = false;
public CollisionBox() {
this(0f, 0f, 1f, 1f);
}
public CollisionBox(int id) {
this(id, 0f, 0f, 1f, 1f);
}
public CollisionBox(float x, float y, float width, float height) {
this(CollisionIdSequence.nextId(), x, y, width, height);
}
public CollisionBox(int id, float x, float y, float width, float height) {
super(x, y, width, height);
this.id = id;
positionChangeListenerLock = new ReentrantReadWriteLock();
sizeChangeListenerLock = new ReentrantReadWriteLock();
previousRectangle = new Rectangle(x, y, width, height);
renderRectangle = new Rectangle(x, y, width, height);
storeRenderCoordinates();
}
private void storeRenderCoordinates() {
renderX = MathUtils.round(renderRectangle.getX());
renderY = MathUtils.round(renderRectangle.getY());
renderWidth = MathUtils.round(renderRectangle.getWidth());
renderHeight = MathUtils.round(renderRectangle.getHeight());
}
@Override
public void preUpdate() {
previousRectangle.set(this);
}
@Override
public void update(GameContainer gc, float delta) {
}
@Override
public void interpolate(GameContainer gc, float alpha) {
if(!interpolate) {
return;
}
renderRectangle.set(previousRectangle.lerp(this, alpha));
storeRenderCoordinates();
if(renderX != MathUtils.round(this.getX())) {
return;
}
if(renderY != MathUtils.round(this.getY())) {
return;
}
if(renderWidth != MathUtils.round(this.getWidth())) {
return;
}
if(renderHeight != MathUtils.round(this.getHeight())) {
return;
}
interpolate = false;
}
@Override
public void draw(Graphics g) {
renderRectangle.draw(g);
}
@Override
public void fill(Graphics g) {
renderRectangle.fill(g);
}
/**
* @see Positionable#addPostionChangeListener(PositionChangeListener)
*/
@Override
public <T extends Positionable> void addPostionChangeListener(
PositionChangeListener<T> listener) {
positionChangeListenerLock.writeLock().lock();
if (positionChangeListeners == null) {
positionChangeListeners = new ArrayList<PositionChangeListener>(1);
}
positionChangeListeners.add(listener);
positionChangeListenerLock.writeLock().unlock();
}
/**
* @see Positionable#removePositionChangeListener(PositionChangeListener)
*/
@Override
public <T extends Positionable> void removePositionChangeListener(
PositionChangeListener<T> listener) {
positionChangeListenerLock.readLock().lock();
if (positionChangeListeners == null) {
positionChangeListenerLock.readLock().unlock();
return;
}
positionChangeListenerLock.readLock().unlock();
positionChangeListenerLock.writeLock().lock();
positionChangeListeners.remove(listener);
positionChangeListenerLock.writeLock().unlock();
}
private void notifyPositionChangeListeners() {
positionChangeListenerLock.readLock().lock();
if (positionChangeListeners == null) {
positionChangeListenerLock.readLock().unlock();
return;
}
for (int i = positionChangeListeners.size() - 1; i >= 0; i
if(i >= positionChangeListeners.size()) {
i = positionChangeListeners.size() - 1;
}
PositionChangeListener listener = positionChangeListeners.get(i);
positionChangeListenerLock.readLock().unlock();
listener.positionChanged(this);
positionChangeListenerLock.readLock().lock();
}
positionChangeListenerLock.readLock().unlock();
}
@Override
public <T extends Sizeable> void addSizeChangeListener(SizeChangeListener<T> listener) {
sizeChangeListenerLock.writeLock().lock();
if (sizeChangeListeners == null) {
sizeChangeListeners = new ArrayList<SizeChangeListener>(1);
}
sizeChangeListeners.add(listener);
sizeChangeListenerLock.writeLock().unlock();
}
@Override
public <T extends Sizeable> void removeSizeChangeListener(SizeChangeListener<T> listener) {
sizeChangeListenerLock.readLock().lock();
if (sizeChangeListeners == null) {
sizeChangeListenerLock.readLock().unlock();
return;
}
sizeChangeListenerLock.readLock().unlock();
sizeChangeListenerLock.writeLock().lock();
sizeChangeListeners.remove(listener);
sizeChangeListenerLock.writeLock().unlock();
}
private void notifySizeChangeListeners() {
sizeChangeListenerLock.readLock().lock();
if (sizeChangeListeners == null) {
sizeChangeListenerLock.readLock().unlock();
return;
}
for (int i = sizeChangeListeners.size() - 1; i >= 0; i
if(i >= sizeChangeListeners.size()) {
i = sizeChangeListeners.size() - 1;
}
SizeChangeListener listener = sizeChangeListeners.get(i);
sizeChangeListenerLock.readLock().unlock();
listener.sizeChanged(this);
sizeChangeListenerLock.readLock().lock();
}
sizeChangeListenerLock.readLock().unlock();
}
@Override
public void setRotation(float degrees) {
if(degrees == getRotation()) {
return;
}
super.setRotation(degrees);
notifyPositionChangeListeners();
}
@Override
public void rotate(float degrees) {
if(degrees == 0f) {
return;
}
super.rotate(degrees);
notifyPositionChangeListeners();
}
@Override
public void rotateAround(float centerX, float centerY, float degrees) {
if(degrees == 0f) {
return;
}
super.rotateAround(centerX, centerY, degrees);
notifyPositionChangeListeners();
}
@Override
public void setRotationAround(Point center, float degrees) {
if(center.x == getX() && center.y == getY() && degrees == getRotation()) {
return;
}
super.setRotationAround(center, degrees);
notifyPositionChangeListeners();
}
@Override
public void setRotationAround(float centerX, float centerY, float degrees) {
if(centerX == getX() && centerY == getY() && degrees == getRotation()) {
return;
}
super.setRotationAround(centerX, centerY, degrees);
notifyPositionChangeListeners();
}
@Override
public float getDistanceTo(Positionable positionable) {
return getDistanceTo(positionable.getX(), positionable.getY());
}
@Override
public void forceTo(float x, float y) {
forceTo(x, y, getWidth(), getHeight());
}
/**
* Sets the current bounds to the specified bounds and force updates the
* rendering bounds to match
*
* @param x
* The x coordinate to set
* @param y
* The y coordinate to set
* @param width
* The width to set
* @param height
* The height to set
*/
public void forceTo(float x, float y, float width, float height) {
boolean notifyPositionListeners = x != getX() || y != getY();
boolean notifySizeListeners = width != getWidth() || height != getHeight();
super.set(x, y, width, height);
previousRectangle.set(x, y, width, height);
renderRectangle.set(previousRectangle);
storeRenderCoordinates();
interpolate = false;
if(notifyPositionListeners) {
notifyPositionChangeListeners();
}
if(notifySizeListeners) {
notifySizeChangeListeners();
}
}
public void forceTo(Rectangle rectangle) {
forceTo(rectangle.getX(), rectangle.getY(), rectangle.getWidth(), rectangle.getHeight());
}
/**
* Sets the current width to the specified width and force updates the
* rendering bounds to match
*
* @param width
* The width to set
*/
public void forceToWidth(float width) {
super.setWidth(width);
previousRectangle.set(this);
renderRectangle.set(this);
storeRenderCoordinates();
notifySizeChangeListeners();
}
/**
* Sets the current height to the specified height and force updates the
* rendering bounds to match
*
* @param height
* The height to set
*/
public void forceToHeight(float height) {
super.setHeight(height);
previousRectangle.set(this);
renderRectangle.set(this);
storeRenderCoordinates();
notifySizeChangeListeners();
}
@Override
public void moveTowards(float x, float y, float speed) {
tmpSourceVector.set(getX(), getY());
tmpTargetVector.set(x, y);
Vector2 direction = tmpTargetVector.sub(tmpSourceVector).nor();
float xComponent = speed * MathUtils.cosDeg(direction.angle());
float yComponent = speed * MathUtils.sinDeg(direction.angle());
tmpSourceVector.add(xComponent, yComponent);
set(tmpSourceVector.x, tmpSourceVector.y);
}
@Override
public void moveTowards(Positionable positionable, float speed) {
moveTowards(positionable.getX(), positionable.getY(), speed);
}
@Override
public void add(float x, float y) {
super.add(x, y);
interpolate = true;
notifyPositionChangeListeners();
}
@Override
public void subtract(float x, float y) {
super.subtract(x, y);
interpolate = true;
notifyPositionChangeListeners();
}
@Override
public Rectangle set(float x, float y, float width, float height) {
boolean notifyPositionListeners = x != getX() || y != getY();
boolean notifySizeListeners = width != getWidth() || height != getHeight();
if(notifyPositionListeners || notifySizeListeners) {
super.set(x, y, width, height);
interpolate = true;
}
if(notifyPositionListeners) {
notifyPositionChangeListeners();
}
if(notifySizeListeners) {
notifySizeChangeListeners();
}
return this;
}
public void set(Rectangle rectangle) {
boolean notifyPositionListeners = rectangle.getX() != getX() || rectangle.getY() != getY();
boolean notifySizeListeners = rectangle.getWidth() != getWidth() || rectangle.getHeight() != getHeight();
if(notifyPositionListeners || notifySizeListeners) {
super.set(rectangle);
interpolate = true;
}
if(notifyPositionListeners) {
notifyPositionChangeListeners();
}
if(notifySizeListeners) {
notifySizeChangeListeners();
}
}
@Override
public void set(float x, float y) {
if(x == getX() && y == getY()) {
return;
}
super.set(x, y);
interpolate = true;
notifyPositionChangeListeners();
}
@Override
public void set(Vector2 position) {
if(getX() == position.x && getY() == position.y) {
return;
}
super.set(position);
interpolate = true;
notifyPositionChangeListeners();
}
@Override
public void setX(float x) {
if(x == getX()) {
return;
}
super.setX(x);
interpolate = true;
notifyPositionChangeListeners();
}
@Override
public void setY(float y) {
if(y == getY()) {
return;
}
super.setY(y);
interpolate = true;
notifyPositionChangeListeners();
}
@Override
public Rectangle setWidth(float width) {
if(width == getWidth()) {
return this;
}
super.setWidth(width);
interpolate = true;
notifySizeChangeListeners();
return this;
}
@Override
public Rectangle setHeight(float height) {
if(height == getHeight()) {
return this;
}
super.setHeight(height);
interpolate = true;
notifySizeChangeListeners();
return this;
}
@Override
public Rectangle setSize(float width, float height) {
if(width == getWidth() && height == getHeight()) {
return this;
}
super.setSize(width, height);
interpolate = true;
notifySizeChangeListeners();
return this;
}
@Override
public Rectangle setSize(float sizeXY) {
if(getWidth() == sizeXY && getHeight() == sizeXY) {
return this;
}
super.setSize(sizeXY);
interpolate = true;
notifySizeChangeListeners();
return this;
}
@Override
public void setRadius(float radius) {
super.setRadius(radius);
interpolate = true;
notifySizeChangeListeners();
}
@Override
public void scale(float scale) {
super.scale(scale);
interpolate = true;
notifySizeChangeListeners();
}
public int getRenderX() {
return renderX;
}
public int getRenderY() {
return renderY;
}
public int getRenderWidth() {
return renderWidth;
}
public int getRenderHeight() {
return renderHeight;
}
public float getRenderRotation() {
return renderRectangle.getRotation();
}
public int getId() {
return id;
}
@Override
public Shape getShape() {
return this;
}
@Override
public String toString() {
return "CollisionBox [id=" + id + ", x=" + getX() + ", y=" + getY() + ", width="
+ getWidth() + ", height=" + getHeight() + ", getRotation()=" + getRotation() + ", renderRectangle=" + renderRectangle + "]";
}
}
|
package org.yggard.brokkgui.control;
import org.yggard.brokkgui.event.ActionEvent;
import org.yggard.hermod.EventHandler;
public abstract class GuiButtonBase extends GuiLabeled
{
private EventHandler<ActionEvent> onActionEvent;
public GuiButtonBase(final String text)
{
super(text);
}
public GuiButtonBase()
{
this("");
}
public void activate()
{
this.getEventDispatcher().dispatchEvent(ActionEvent.TYPE, new ActionEvent(this));
}
// EVENTS HANDLING //
public void setOnActionEvent(final EventHandler<ActionEvent> onActionEvent)
{
this.getEventDispatcher().removeHandler(ActionEvent.TYPE, this.onActionEvent);
this.onActionEvent = onActionEvent;
this.getEventDispatcher().addHandler(ActionEvent.TYPE, this.onActionEvent);
}
}
|
package imagej.ui.viewer;
import imagej.data.Dataset;
import imagej.data.display.ImageDisplay;
import imagej.data.display.ImageDisplayService;
import imagej.display.Display;
import imagej.display.event.DisplayActivatedEvent;
import imagej.display.event.DisplayCreatedEvent;
import imagej.display.event.DisplayDeletedEvent;
import imagej.display.event.DisplayUpdatedEvent;
import imagej.display.event.DisplayUpdatedEvent.DisplayUpdateLevel;
import net.imglib2.img.Img;
import net.imglib2.img.cell.AbstractCellImg;
import org.scijava.event.EventHandler;
import org.scijava.event.EventService;
import org.scijava.plugin.SortablePlugin;
/**
* The AbstractDisplayViewer provides some basic generic implementations for a
* DisplayViewer such as storing and providing the display, window and panel for
* a DisplayViewer.
*
* @author Lee Kamentsky
* @author Curtis Rueden
*/
public abstract class AbstractDisplayViewer<T> extends SortablePlugin implements
DisplayViewer<T>
{
private Display<T> display;
private DisplayWindow window;
private DisplayPanel panel;
@Override
public void view(final DisplayWindow w, final Display<?> d) {
if (!canView(d)) {
throw new IllegalArgumentException("Incompatible display: " + d);
}
@SuppressWarnings("unchecked")
final Display<T> typedDisplay = (Display<T>) d;
display = typedDisplay;
window = w;
}
@Override
public Display<T> getDisplay() {
return display;
}
@Override
public DisplayWindow getWindow() {
return window;
}
@Override
public void setPanel(final DisplayPanel panel) {
this.panel = panel;
}
@Override
public DisplayPanel getPanel() {
return panel;
}
@Override
public void onDisplayDeletedEvent(final DisplayDeletedEvent e) {
getPanel().getWindow().close();
}
@Override
public void onDisplayUpdatedEvent(final DisplayUpdatedEvent e) {
if (e.getLevel() == DisplayUpdateLevel.REBUILD) {
getPanel().redoLayout();
}
getPanel().redraw();
}
@Override
public void onDisplayActivatedEvent(final DisplayActivatedEvent e) {
getPanel().getWindow().requestFocus();
}
// -- Disposable methods --
@Override
public void dispose() {
final DisplayWindow w = getWindow();
if (w != null) w.close();
}
// -- Internal AbstractDisplayViewer methods --
/** Convenience method to obtain the appropriate {@link EventService}. */
protected EventService getEventService() {
return getContext().getService(EventService.class);
}
protected void updateTitle() {
String trailer = "";
if (display instanceof ImageDisplay) {
ImageDisplayService src =
getContext().getService(ImageDisplayService.class);
if (src != null) {
Dataset ds = src.getActiveDataset((ImageDisplay) display);
Img<?> img = ds.getImgPlus().getImg();
if (AbstractCellImg.class.isAssignableFrom(img.getClass()))
{
trailer = " (V)";
}
}
}
getWindow().setTitle(getDisplay().getName() + trailer);
}
// -- Event handlers --
@EventHandler
protected void onEvent(final DisplayCreatedEvent event) {
if (event.getObject() != getDisplay()) return;
updateTitle();
}
@EventHandler
protected void onEvent(final DisplayUpdatedEvent event) {
if (event.getDisplay() != getDisplay()) return;
updateTitle();
}
}
|
package imagej.updater.core;
import imagej.updater.core.Conflicts.Conflict;
import imagej.updater.util.Progress;
import imagej.updater.util.StderrProgress;
import imagej.updater.util.UpdaterUserInterface;
import imagej.updater.util.Util;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.scijava.Context;
import org.scijava.log.LogService;
/**
* This class is responsible for writing updates to server, upon given the
* updated file records.
* <p>
* Note: Files are uploaded differently:
* </p>
* <ul>
* <li>Local-only files & new file versions will have files AND details uploaded
* </li>
* <li>Uninstalled & up-to-date files will ONLY have their details uploaded
* (i.e.: XML file)</li>
* </ul>
*
* @author Johannes Schindelin
*/
public class FilesUploader {
private FilesCollection files;
private Uploader uploader;
private String siteName;
private UpdateSite site;
private List<Uploadable> uploadables;
private String compressed;
private boolean loggedIn;
private static UploaderService createUploaderService() {
setClassLoaderIfNecessary();
final Context context = new Context(UploaderService.class);
return context.getService(UploaderService.class);
}
/**
* Sets the context class loader if necessary.
*
* If the current class cannot be found by the current Thread's context
* class loader, we should tell the Thread about the class loader that
* loaded this class.
*/
private static void setClassLoaderIfNecessary() {
ClassLoader thisLoader = FilesUploader.class.getClassLoader();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
for (; loader != null; loader = loader.getParent()) {
if (thisLoader == loader) return;
}
Thread.currentThread().setContextClassLoader(thisLoader);
}
/**
* @deprecated use {@link #FilesUploader(UploaderService, files, updateSite, progress)} instead
*/
public FilesUploader(final FilesCollection files, final String updateSite) {
this(createUploaderService(), files, updateSite);
}
/**
* @deprecated use {@link #FilesUploader(UploaderService, files, updateSite, progress)} instead
*/
public FilesUploader(final UploaderService uploaderService,
final FilesCollection files, final String updateSite) {
this(uploaderService, files, updateSite, null);
}
public FilesUploader(UploaderService uploaderService,
final FilesCollection files, final String updateSite,
final Progress progress) {
if (uploaderService == null) uploaderService = createUploaderService();
this.files = files;
siteName = updateSite;
site = files.getUpdateSite(updateSite, false);
compressed = Util.XML_COMPRESSED;
final String protocol = site.getUploadProtocol();
uploader = uploaderService.installUploader(protocol, files,
progress == null ? new StderrProgress() : progress);
if (uploader == null) {
throw new IllegalArgumentException(
"No uploader found for protocol " + protocol);
}
}
public boolean hasUploader() {
return uploader != null;
}
public FilesCollection getFilesCollection() {
return files;
}
public String getSiteName() {
return siteName;
}
public String getDefaultUsername() {
String host = site.getHost();
if (host.startsWith("sftp:")) host = host.substring(5);
final int at = host.indexOf('@');
if (at > 0) return host.substring(0, at);
final String name = UpdaterUserInterface.get().getPref(Util.PREFS_USER);
if (name == null) return "";
return name;
}
public String getUploadHost() {
String host = site.getHost();
if (uploader != null) {
final String protocol = uploader.getProtocol();
if (protocol != null && host.startsWith(protocol + ":")) {
host = host.substring(protocol.length() + 1);
}
}
return host.substring(host.indexOf('@') + 1);
}
public String getUploadDirectory() {
return site.getUploadDirectory();
}
protected class DbXmlFile implements Uploadable {
public byte[] bytes;
@Override
public String getFilename() {
return compressed + ".lock";
}
@Override
public String getPermissions() {
return "C0444";
}
@Override
public long getFilesize() {
return bytes.length;
}
@Override
public InputStream getInputStream() {
return new ByteArrayInputStream(bytes);
}
@Override
public String toString() {
return compressed;
}
}
public void upload(final Progress progress) throws Exception {
if (uploader == null) throw new RuntimeException("No uploader set for " +
site.getHost());
if (!loggedIn) throw new RuntimeException("Not logged in!");
final Iterable<Conflict> conflicts = new Conflicts(files).getConflicts(true);
if (Conflicts.needsFeedback(conflicts)) {
throw new RuntimeException("Unresolved upload conflicts!\n\n"
+ Util.join("\n", conflicts));
}
uploader.addProgress(progress);
uploader.addProgress(new VerifyTimestamp());
uploadables = new ArrayList<Uploadable>();
final List<String> locks = new ArrayList<String>();
uploadables.add(new DbXmlFile());
for (final FileObject file : files.toUpload(siteName)) {
// remove obsolete/invalid dependencies
for (Iterator<Dependency> iter = file.getDependencies().iterator(); iter.hasNext(); ) {
final String filename = iter.next().filename;
final FileObject other = files.get(filename);
if (other == null || other.isObsolete()) {
files.log.warn("Removed obsolete dependency " + filename + " of " + file.filename);
iter.remove();
}
}
uploadables.add(new UploadableFile(files, file));
}
// must be last lock
locks.add(Util.XML_COMPRESSED);
// verify that the files have not changed in the meantime
final long[] timestamps = new long[uploadables.size()];
int counter = 0;
for (final Uploadable uploadable : uploadables) {
if (uploadable instanceof UploadableFile) {
final UploadableFile file = (UploadableFile) uploadable;
timestamps[counter] = Util.getTimestamp(file.source);
}
verifyUnchanged(uploadable, true);
counter++;
}
uploader.upload(uploadables, locks);
// verify that the files have not changed in the meantime
counter = 0;
for (final Uploadable uploadable : uploadables) {
if (uploadable instanceof UploadableFile) {
final UploadableFile file = (UploadableFile) uploadable;
if (timestamps[counter] != Util.getTimestamp(file.source)) throw new RuntimeException(
"Timestamp of " + file.getFilename() +
"changed since being checksummed (was " + timestamps[counter] +
" but is " + Util.getTimestamp(file.source) + "!)");
}
counter++;
}
site.setLastModified(getCurrentLastModified());
}
protected void verifyUnchanged(final Uploadable file,
final boolean checkTimestamp)
{
if (!(file instanceof UploadableFile)) return;
final UploadableFile uploadable = (UploadableFile) file;
final long size = uploadable.source.length();
if (uploadable.filesize != size) throw new RuntimeException(
"File size of " + uploadable.file.filename +
" changed since being checksummed (was " + uploadable.filesize +
" but is " + size + ")!");
if (checkTimestamp) {
final long stored =
uploadable.file.getStatus() == FileObject.Status.LOCAL_ONLY
? uploadable.file.current.timestamp : uploadable.file.localTimestamp;
if (stored != Util.getTimestamp(uploadable.source)) throw new RuntimeException(
"Timestamp of " + uploadable.file.filename +
" changed since being checksummed (was " + stored + " but is " +
Util.getTimestamp(uploadable.source) + ")!");
}
}
protected void updateUploadTimestamp(final long timestamp) throws Exception {
for (final Uploadable f : uploadables) {
if (!(f instanceof UploadableFile)) continue;
final UploadableFile uploadable = (UploadableFile) f;
final FileObject file = uploadable.file;
if (file == null) continue;
file.filesize = uploadable.filesize = uploadable.source.length();
file.localTimestamp = timestamp;
uploadable.filename = file.filename + "-" + timestamp;
if (file.getStatus() == FileObject.Status.LOCAL_ONLY) {
file.setStatus(FileObject.Status.INSTALLED);
file.current.timestamp = timestamp;
}
}
final XMLFileWriter writer =
new XMLFileWriter(files.clone(files.forUpdateSite(siteName, true)));
if (files.size() > 0) writer.validate(false);
((DbXmlFile) uploadables.get(0)).bytes =
writer.toCompressedByteArray(false);
uploader.calculateTotalSize(uploadables);
}
/*
* This class serves two purposes:
*
* - after locking, it ensures that the timestamp of db.xml.gz is the
* same as when it was last downloaded, to prevent race-conditions
*
* - it takes the timestamp of the lock file and updates the timestamps
* of all files to be uploaded, so that local time skews do not
* harm
*/
protected class VerifyTimestamp implements Progress {
@Override
public void addItem(final Object item) {
if (item != uploadables.get(0)) return;
verifyTimestamp();
}
@Override
public void setTitle(final String string) {
try {
updateUploadTimestamp(uploader.getTimestamp());
}
catch (final Exception e) {
files.log.error(e);
throw new RuntimeException("Could not update "
+ "the timestamps in db.xml.gz");
}
}
@Override
public void itemDone(final Object item) {
if (item instanceof UploadableFile) verifyUnchanged(
(UploadableFile) item, false);
}
@Override
public void setCount(final int count, final int total) {}
@Override
public void setItemCount(final int count, final int total) {}
@Override
public void done() {}
}
protected long getCurrentLastModified() {
try {
URLConnection connection;
try {
connection = files.util.openConnection(new URL(site.getURL() + Util.XML_COMPRESSED));
}
catch (final FileNotFoundException e) {
files.log.error(e);
Thread.sleep(500);
connection = files.util.openConnection(new URL(site.getURL() + Util.XML_COMPRESSED));
}
connection.setUseCaches(false);
final long lastModified = connection.getLastModified();
connection.getInputStream().close();
UpdaterUserInterface.get().debug(
"got last modified " + lastModified + " = timestamp " +
Util.timestamp(lastModified));
return lastModified;
}
catch (final Exception e) {
UpdaterUserInterface.get().debug(e.getMessage());
if (files.size() == 0) return -1; // assume initial upload
files.log.error(e);
return 0;
}
}
protected void verifyTimestamp() {
if (site.getTimestamp() == 0) return;
final long lastModified = getCurrentLastModified();
if (!site.isLastModified(lastModified)) throw new RuntimeException(
"db.xml.gz was " + "changed in the meantime (was " + site.getTimestamp() +
" but now is " + Util.timestamp(lastModified) + ")");
}
public boolean login() {
if (loggedIn) return loggedIn;
loggedIn = uploader.login(this);
return loggedIn;
}
public void logout() {
if (uploader != null)
uploader.logout();
}
@Deprecated
public static FilesUploader initialUpload(final String url,
final String sshHost, final String uploadDirectory)
{
return initialUploader(null, url, sshHost, uploadDirectory, null);
}
public static FilesUploader initialUploader(
final UploaderService uploaderService, final String url,
final String sshHost, final String uploadDirectory, final Progress progress)
{
final String updateSiteName = "Dummy";
final FilesCollection files = new FilesCollection(null);
files.addUpdateSite(updateSiteName, url, sshHost, uploadDirectory, Long
.parseLong(Util.timestamp(-1)));
return new FilesUploader(uploaderService, files, updateSiteName, progress);
}
public LogService getLog() {
return files.log;
}
}
|
package de.uni.freiburg.iig.telematik.sewol.parser.mxml;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import de.invation.code.toval.parser.ParserException;
import de.invation.code.toval.validate.ParameterException;
import de.invation.code.toval.validate.Validate;
import de.uni.freiburg.iig.telematik.sewol.format.MXMLLogFormat;
import de.uni.freiburg.iig.telematik.sewol.log.EventType;
import de.uni.freiburg.iig.telematik.sewol.log.LockingException;
import de.uni.freiburg.iig.telematik.sewol.log.LogEntry;
import de.uni.freiburg.iig.telematik.sewol.log.LogSummary;
import de.uni.freiburg.iig.telematik.sewol.log.LogTrace;
import de.uni.freiburg.iig.telematik.sewol.parser.AbstractLogParser;
import de.uni.freiburg.iig.telematik.sewol.parser.ParserFileFormat;
import de.uni.freiburg.iig.telematik.sewol.parser.ParsingMode;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/**
* <p>
* A parser class for MXML files for the SEWOL log classes.
* </p>
*
* @author Adrian Lange
*/
public class MXMLLogParser extends AbstractLogParser {
/**
* Parses the specified log file path and returns a collection of
* processes.
*
* @param filePath Path to file to parse
* @param parsingMode
* @return Collection of processes, which consist of a collection of
* instances, which again consist of a collection of {@link LogTrace}
* objects.
* @throws ParameterException Gets thrown if there's a discrepancy in
* how the file should be interpreted.
* @throws ParserException Gets thrown if the file under the given path
* can't be read, is a directory, or doesn't exist.
*/
public List<List<LogTrace<LogEntry>>> parse(String filePath, ParsingMode parsingMode) throws ParameterException, ParserException {
Validate.notNull(filePath);
return parse(new File(filePath), parsingMode);
}
/**
* Parses the specified log file and returns a collection of processes.
*
* @param inputStream {@link InputStream} to parse
* @param parsingMode
* @param fileFormat Format of the {@link InputStream} as it can't be
* determined automatically
* @return Collection of processes, which consist of a collection of
* instances, which again consist of a collection of {@link LogTrace}
* objects.
* @throws ParameterException Gets thrown if there's a discrepancy in
* how the file should be interpreted.
* @throws ParserException Gets thrown if the given file can't be read,
* is a directory, or doesn't exist.
*/
public List<List<LogTrace<LogEntry>>> parse(InputStream inputStream, ParsingMode parsingMode, ParserFileFormat fileFormat) throws ParameterException, ParserException {
try {
inputStream.available();
} catch (IOException e) {
throw new ParameterException("Unable to read input file: " + e.getMessage());
}
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
MXMLSAXHandler handler = new MXMLSAXHandler();
parser.parse(inputStream, handler);
summaries.addAll(handler.summaries);
parsedLogFiles = handler.logs;
return parsedLogFiles;
} catch (ParserConfigurationException | SAXException | IOException ex) {
throw new ParserException(ex);
}
}
/**
* Parses the specified log file and returns a collection of processes.
*
* @param file File to parse
* @param parsingMode
* @return Collection of processes, which consist of a collection of
* instances, which again consist of a collection of {@link LogTrace}
* objects.
* @throws ParameterException Gets thrown if there's a discrepancy in
* how the file should be interpreted.
* @throws ParserException Gets thrown if the given file can't be read,
* is a directory, or doesn't exist.
*/
@Override
public List<List<LogTrace<LogEntry>>> parse(File file, ParsingMode parsingMode) throws ParameterException, ParserException {
Validate.noDirectory(file);
if (!file.canRead()) {
throw new ParameterException("Unable to read input file!");
}
try {
try {
InputStream is = new FileInputStream(file);
return parse(is, parsingMode, ParserFileFormat.getFileFormat(file));
} catch (FileNotFoundException | ParameterException | ParserException e) {
throw new ParserException("Exception while parsing with OpenXES: " + e.getMessage());
}
} catch (Exception e) {
throw new ParserException("Error while parsing log with OpenXES-Parser: " + e.getMessage());
}
}
// TODO remove
public static void main(String[] args) throws ParameterException, ParserException {
new MXMLLogParser().parse("/home/alange/validLogExample.mxml", ParsingMode.COMPLETE);
}
private static class MXMLSAXHandler extends DefaultHandler {
private final List<List<LogTrace<LogEntry>>> logs = new ArrayList<>();
private final List<LogSummary<LogEntry>> summaries = new ArrayList<>();
private List<LogTrace<LogEntry>> currentLog = null;
private LogTrace<LogEntry> currentTrace = null;
private LogEntry currentEntry = null;
private LogSummary<LogEntry> currentSummary = null;
private final StringBuilder lastCharacters = new StringBuilder();
private boolean recordCharacters = false;
private static final Pattern INT_PATTERN = Pattern.compile("^(\\d+)$");
private static final Pattern NON_INT_PATTERN = Pattern.compile("(\\D+)");
@Override
public void startDocument() throws SAXException {
}
@Override
public void endDocument() throws SAXException {
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
switch (qName) {
case MXMLLogFormat.ELEMENT_LOG:
currentLog = new ArrayList<>();
currentSummary = new LogSummary<>();
break;
case MXMLLogFormat.ELEMENT_TRACE:
if (attributes.getIndex(MXMLLogFormat.ATTRIBUTE_ID) >= 0) {
String idString = attributes.getValue(attributes.getIndex(MXMLLogFormat.ATTRIBUTE_ID));
currentTrace = new LogTrace<>(idStrToInt(idString));
} else {
currentTrace = new LogTrace<>();
}
break;
case MXMLLogFormat.ELEMENT_ENTRY:
currentEntry = new LogEntry();
break;
case MXMLLogFormat.ELEMENT_ACTIVITY:
case MXMLLogFormat.ELEMENT_TYPE:
case MXMLLogFormat.ELEMENT_TIME:
case MXMLLogFormat.ELEMENT_ORIGINATOR:
case MXMLLogFormat.ELEMENT_DATA:
lastCharacters.setLength(0);
recordCharacters = true;
break;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
{
try {
switch (qName) {
case MXMLLogFormat.ELEMENT_LOG:
summaries.add(currentSummary);
logs.add(currentLog);
break;
case MXMLLogFormat.ELEMENT_TRACE:
currentLog.add(currentTrace);
currentSummary.addTrace(currentTrace);
break;
case MXMLLogFormat.ELEMENT_ENTRY:
currentTrace.addEntry(currentEntry);
break;
case MXMLLogFormat.ELEMENT_ACTIVITY:
currentEntry.setActivity(lastCharacters.toString());
recordCharacters = false;
break;
case MXMLLogFormat.ELEMENT_TYPE:
currentEntry.setEventType(EventType.parse(lastCharacters.toString()));
recordCharacters = false;
break;
case MXMLLogFormat.ELEMENT_TIME:
String dateStr = lastCharacters.toString();
// TODO parse date
//currentEntry.setEventType(EventType.parse(lastCharacters.toString()));
recordCharacters = false;
break;
case MXMLLogFormat.ELEMENT_ORIGINATOR:
currentEntry.setOriginator(lastCharacters.toString());
recordCharacters = false;
break;
case MXMLLogFormat.ELEMENT_DATA:
// TODO
recordCharacters = false;
break;
}
} catch (LockingException ex) {
throw new RuntimeException(ex);
}
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (recordCharacters) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < length; i++) {
str.append(ch[start + i]);
}
lastCharacters.append(str);
}
}
@Override
public void error(SAXParseException e) throws SAXException {
throw e;
}
@Override
public void warning(SAXParseException e) throws SAXException {
throw e;
}
private static int idStrToInt(String idString) {
if (idString.matches(INT_PATTERN.pattern())) {
return Integer.parseInt(idString);
} else if (idString.replaceAll(NON_INT_PATTERN.pattern(), "").matches(INT_PATTERN.pattern())) {
return Integer.parseInt(idString.replaceAll(NON_INT_PATTERN.pattern(), ""));
} else {
return idString.hashCode();
}
}
}
}
|
package edu.psu.compbio.seqcode.gse.projects.readdb;
import java.io.*;
import java.util.*;
import org.apache.commons.cli.*;
import net.sf.samtools.*;
import net.sf.samtools.util.CloseableIterator;
/**
* Reads two files of SAM or BAM data and produces output on stdout in the
* format expected by ImportHits. Both files must be sorted in the *same order*.
* Note that Bowtie (perhaps others) DOES NOT preserve input order perfectly if
* it's using multiple processors, so you can only use one processor if you're
* going to use this program to pair the reads up (you can however split the
* input file and run a separate bowtie on each part).
*
* Only reads present in both files will be included in the output (on stdout).
*
* The matching of reads between files is done by stripping "/\d" from the end of the
* read name, as reads usually end in /1 or /2.
*
* Usage:
* java PairedSAMToReadDB --left leftreads.bam --right rightreads.bam
*
*
* Options: --nosuboptimal (flag to only take the hits with the minimum number of mismatches)
* --uniquehits (flag to only print 1:1 read to hit mappings)
*
* nosuboptimal is applied before uniquehits
*
* Output columns are
* 1) left chromname
* 2) left position
* 3) left strand
* 4) left readlen
* 5) right chromname
* 6) right position
* 7) right strand
* 8) right length
* 9) weight
* 10) paircode
*/
public class PairedSAMToReadDB {
public static boolean uniqueOnly, filterSubOpt, debug;
public static int chunksize = 2000;
public static ArrayList<SAMRecord> leftbuffer, rightbuffer;
public static CloseableIterator<SAMRecord> leftiter, rightiter;
public static void dumpRecords(Collection<SAMRecord> lefts,
Collection<SAMRecord> rights) {
if (filterSubOpt) {
lefts = filterSubOpt(filterNoChrom(lefts));
rights = filterSubOpt(filterNoChrom(rights));
} else {
lefts = filterNoChrom(lefts);
rights = filterNoChrom(rights);
}
int mapcount = lefts.size() * rights.size();
if (mapcount == 0) {
return;
}
if (uniqueOnly && mapcount > 1) {
return;
}
float weight = 1 / ((float)mapcount);
for (SAMRecord left : lefts) {
for (SAMRecord right : rights) {
System.out.println(String.format("%s\t%d\t%s\t%d\t%s\t%d\t%s\t%d\t%f\t%d",
left.getReferenceName(),
left.getReadNegativeStrandFlag() ?
left.getAlignmentEnd() :
left.getAlignmentStart(),
left.getReadNegativeStrandFlag() ? "-" : "+",
left.getReadLength(),
right.getReferenceName(),
right.getReadNegativeStrandFlag() ?
right.getAlignmentEnd() :
right.getAlignmentStart(),
right.getReadNegativeStrandFlag() ? "-" : "+",
right.getReadLength(),
weight,
1));
}
}
}
public static Collection<SAMRecord> filterNoChrom(Collection<SAMRecord> input) {
if (input.size() == 0) {
return input;
}
Collection<SAMRecord> output = new ArrayList<SAMRecord>();
for (SAMRecord r : input) {
if (!r.getReferenceName().equals("*")) {
output.add(r);
}
}
return output;
}
public static Collection<SAMRecord> filterSubOpt(Collection<SAMRecord> input) {
if (input == null || input.size() < 2) {
return input;
}
int maxqual = SAMRecord.NO_MAPPING_QUALITY;
for (SAMRecord r : input) {
if (r.getMappingQuality() > maxqual) {
maxqual = r.getMappingQuality();
}
}
Collection<SAMRecord> output = new ArrayList<SAMRecord>();
for (SAMRecord r : input) {
if (maxqual == r.getMappingQuality()) {
if(!uniqueOnly || r.getMappingQuality()!=0) //For BWA
output.add(r);
}
}
return output;
}
public static boolean fillLeft(int n) {
boolean filled = false;
for (int i = 0; i < n; i++) {
if (leftiter.hasNext()) {
SAMRecord r = leftiter.next();
r.setReadName(r.getReadName().replaceAll("/\\d$",""));
leftbuffer.add(r);
filled = true;
}
}
return filled;
}
public static boolean fillRight(int n) {
boolean filled = false;
for (int i = 0; i < n; i++) {
if (rightiter.hasNext()) {
SAMRecord r = rightiter.next();
r.setReadName(r.getReadName().replaceAll("/\\d$",""));
rightbuffer.add(r);
filled = true;
}
}
return filled;
}
public static boolean fill(int n) {
return fillLeft(n) && fillRight(n);
}
public static void makePairs() {
ArrayList<SAMRecord> leftrecords = new ArrayList<SAMRecord>();
ArrayList<SAMRecord> rightrecords = new ArrayList<SAMRecord>();
while (fill(chunksize) || leftbuffer.size() > 0) {
int clearL = 0, clearR = 0;
int lbs = Math.min(leftbuffer.size(),10000);
for (int i = 0; i < lbs; i++) {
String readname = leftbuffer.get(i).getReadName();
String nextreadname = i < leftbuffer.size() - 1 ? leftbuffer.get(i+1).getReadName() : null;
int j = clearR;
while (j < rightbuffer.size()) {
if (readname.equals(rightbuffer.get(j).getReadName())) {
/* having found a match, find the rest of the reads with that ID and output */
int k = i;
int l = j;
/* make sure we'll be able to find all reads with this name */
while (readname.equals(leftbuffer.get(leftbuffer.size()-1).getReadName()) &&
fillLeft(chunksize)) {
}
while (readname.equals(rightbuffer.get(rightbuffer.size()-1).getReadName()) &&
fillRight(chunksize)) {
}
do {
leftrecords.add(leftbuffer.get(k++));
} while (k < leftbuffer.size() && readname.equals(leftbuffer.get(k).getReadName()));
do {
rightrecords.add(rightbuffer.get(l++));
} while (l < rightbuffer.size() && readname.equals(rightbuffer.get(l).getReadName()));
dumpRecords(leftrecords, rightrecords);
leftrecords.clear();
rightrecords.clear();
clearL = k;
clearR = l;
i = k-1;
break;
} else if (nextreadname != null && nextreadname.equals(rightbuffer.get(j).getReadName())) {
clearR = j;
break;
}
j++;
}
}
if (rightiter.hasNext()) {
leftbuffer.subList(0,clearL).clear();
rightbuffer.subList(0,clearR).clear();
} else {
leftbuffer.clear();
}
//System.err.println(String.format("loop %d, left %d, right %d", loop++, leftbuffer.size(), rightbuffer.size()));
}
}
public static void main(String args[]) throws IOException, ParseException {
Options options = new Options();
options.addOption("l","left",true,"filename of left side of read");
options.addOption("r","right",true,"filename of right side of read");
options.addOption("u","uniquehits",false,"only output hits with a single mapping");
options.addOption("s","nosuboptimal",false,"do not include hits whose score is not equal to the best score for the read");
options.addOption("D","debug",false,"enable debugging spew?");
CommandLineParser parser = new GnuParser();
CommandLine cl = parser.parse( options, args, false );
uniqueOnly = cl.hasOption("uniquehits");
filterSubOpt = cl.hasOption("nosuboptimal");
debug = cl.hasOption("debug");
String leftfile = cl.getOptionValue("left");
String rightfile = cl.getOptionValue("right");
SAMFileReader leftreader = new SAMFileReader(new FileInputStream(leftfile));
SAMFileReader rightreader = new SAMFileReader(new FileInputStream(rightfile));
leftiter = leftreader.iterator();
rightiter = rightreader.iterator();
leftbuffer = new ArrayList<SAMRecord>();
rightbuffer = new ArrayList<SAMRecord>();
makePairs();
}
}
|
package edu.washington.escience.myria.operator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import javax.annotation.Nullable;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang.BooleanUtils;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.Floats;
import edu.washington.escience.myria.DbException;
import edu.washington.escience.myria.MyriaConstants;
import edu.washington.escience.myria.Schema;
import edu.washington.escience.myria.io.AmazonS3Source;
import edu.washington.escience.myria.io.DataSource;
import edu.washington.escience.myria.io.FileSource;
import edu.washington.escience.myria.storage.TupleBatch;
import edu.washington.escience.myria.storage.TupleBatchBuffer;
import edu.washington.escience.myria.util.DateTimeUtils;
public class CSVFragmentTupleSource extends LeafOperator {
/** The Schema of the relation stored in this file. */
private final Schema schema;
/** Scanner used to parse the file. */
private transient CSVParser parser = null;
/** Iterator over CSV records. */
private transient Iterator<CSVRecord> iterator = null;
/** A user-provided file delimiter; if null, the system uses the default comma as delimiter. */
private final Character delimiter;
/** A user-provided quotation mark, if null, the system uses '"'. */
private final Character quote;
/** A user-provided escape character to escape quote and itself, if null, the system uses '/'. */
private final Character escape;
/** The data source that will generate the input stream to be read at initialization. */
private final AmazonS3Source source;
/** Number of skipped lines on the head. */
private final Integer numberOfSkippedLines;
/** Holds the tuples that are ready for release. */
private transient TupleBatchBuffer buffer;
/** Which line of the file the scanner is currently on. */
private long lineNumber = 0;
private long byteOverlap = MyriaConstants.PARALLEL_INGEST_BYTE_OVERLAP;
private static final String truncatedQuoteErrorMessage =
"EOF reached before encapsulated token finished";
private boolean isLastWorker;
private final long maxByteRange;
private long partitionStartByteRange;
private long partitionEndByteRange;
private long adjustedStartByteRange;
private int byteOffsetFromTruncatedRowAtStart = 0;
private InputStream partitionInputStream;
private CSVRecord record;
private boolean onLastRow;
private boolean finishedReadingLastRow;
private boolean flagAsIncomplete;
private boolean flagAsRangeSelected;
private int[] workerIds;
/** Required for Java serialization. */
private static final long serialVersionUID = 1L;
/**
* The logger for debug, trace, etc. messages in this class.
*/
private static final org.slf4j.Logger LOGGER =
org.slf4j.LoggerFactory.getLogger(CSVFragmentTupleSource.class);
public CSVFragmentTupleSource(
final String filename,
final Schema schema,
final long startByteRange,
final long endByteRange,
final boolean isLastWorker) {
this(filename, schema, startByteRange, endByteRange, isLastWorker, null, null, null, null);
}
public CSVFragmentTupleSource(
final DataSource source,
final Schema schema,
final long startByteRange,
final long endByteRange,
final boolean isLastWorker) {
this(source, schema, startByteRange, endByteRange, isLastWorker, null, null, null, null);
}
public CSVFragmentTupleSource(
final String filename,
final Schema schema,
final long startByteRange,
final long endByteRange,
final boolean isLastWorker,
final Character delimiter) {
this(
new FileSource(filename),
schema,
startByteRange,
endByteRange,
isLastWorker,
delimiter,
null,
null,
null);
}
public CSVFragmentTupleSource(
final DataSource source,
final Schema schema,
final long startByteRange,
final long endByteRange,
final boolean isLastWorker,
final Character delimiter) {
this(source, schema, startByteRange, endByteRange, isLastWorker, delimiter, null, null, null);
}
public CSVFragmentTupleSource(
final String filename,
final Schema schema,
final long startByteRange,
final long endByteRange,
final boolean isLastWorker,
@Nullable final Character delimiter,
@Nullable final Character quote,
@Nullable final Character escape,
@Nullable final Integer numberOfSkippedLines) {
this(
new FileSource(filename),
schema,
startByteRange,
endByteRange,
isLastWorker,
delimiter,
quote,
escape,
numberOfSkippedLines);
}
public CSVFragmentTupleSource(
final DataSource source,
final Schema schema,
final long partitionStartByteRange,
final long partitionEndByteRange,
final boolean isLastWorker,
@Nullable final Character delimiter,
@Nullable final Character quote,
@Nullable final Character escape,
@Nullable final Integer numberOfSkippedLines) {
this.source = (AmazonS3Source) Preconditions.checkNotNull(source, "source");
this.schema = Preconditions.checkNotNull(schema, "schema");
this.delimiter = MoreObjects.firstNonNull(delimiter, CSVFormat.DEFAULT.getDelimiter());
this.quote = MoreObjects.firstNonNull(quote, CSVFormat.DEFAULT.getQuoteCharacter());
this.escape = escape;
this.numberOfSkippedLines = MoreObjects.firstNonNull(numberOfSkippedLines, 0);
this.partitionStartByteRange = partitionStartByteRange;
this.partitionEndByteRange = partitionEndByteRange;
this.isLastWorker = isLastWorker;
maxByteRange = ((AmazonS3Source) source).getFileSize();
onLastRow = false;
finishedReadingLastRow = false;
flagAsIncomplete = false;
flagAsRangeSelected = true;
}
public CSVFragmentTupleSource(
final AmazonS3Source source,
final Schema schema,
final int[] workerIds,
@Nullable final Character delimiter,
@Nullable final Character quote,
@Nullable final Character escape,
@Nullable final Integer numberOfSkippedLines) {
this.source = Preconditions.checkNotNull(source, "source");
this.schema = Preconditions.checkNotNull(schema, "schema");
this.workerIds = workerIds;
this.delimiter = MoreObjects.firstNonNull(delimiter, CSVFormat.DEFAULT.getDelimiter());
this.quote = MoreObjects.firstNonNull(quote, CSVFormat.DEFAULT.getQuoteCharacter());
this.escape = escape;
this.numberOfSkippedLines = MoreObjects.firstNonNull(numberOfSkippedLines, 0);
maxByteRange = source.getFileSize();
onLastRow = false;
finishedReadingLastRow = false;
flagAsIncomplete = false;
flagAsRangeSelected = false;
}
@Override
protected TupleBatch fetchNextReady() throws IOException, DbException {
long lineNumberBegin = lineNumber;
boolean nextRecordTruncated = false;
while ((buffer.numTuples() < buffer.getBatchSize()) && !flagAsIncomplete) {
lineNumber++;
if (parser.isClosed()) {
break;
}
if (nextRecordTruncated) {
onLastRow = true;
}
try {
if (!onLastRow) {
record = iterator.next();
}
} catch (Exception e) {
/*
* FIX ME: If we hit an exception for a malformed row (in case of quotes for example), we mark this as the last
* row
*/
if (e.getMessage() != null && e.getMessage().contains(truncatedQuoteErrorMessage)) {
onLastRow = true;
} else {
throw e;
}
}
try {
if (!iterator.hasNext()) {
onLastRow = true;
}
} catch (Exception e) {
/*
* FIX ME: If we hit an exception for a malformed row (in case of quotes for example), we mark
* nextRecordTruncated as true
*/
if (e.getMessage() != null && e.getMessage().contains(truncatedQuoteErrorMessage)) {
nextRecordTruncated = true;
} else {
throw e;
}
}
/*
* Here, if we are on the last row, we make sure to read the entire row until we either hit a new line or until we
* have read the entire file (this is for the case where a single worker might be reading a single large row that
* was split among other workers). If we're at the last row and the last worker is reading, we just mark this
* final line as finished.
*/
if (onLastRow && !finishedReadingLastRow && !isLastWorker) {
long trailingStartByte = partitionEndByteRange + 1;
long trailingEndByte = trailingStartByte + byteOverlap - 1;
long finalBytePositionFound = trailingStartByte;
boolean finalLineFound = false;
while (!finalLineFound) {
/*
* If we are within the max byte range, then keep checking for a new line. Otherwise, if we've reached the end
* of the file, mark finalLineFound as true.
*/
if (trailingEndByte < maxByteRange) {
InputStream trailingEndInputStream =
source.getInputStream(trailingStartByte, trailingEndByte);
int dataChar = trailingEndInputStream.read();
while (dataChar != -1) {
char currentChar = (char) dataChar;
if (currentChar == '\n' || currentChar == '\r') {
finalLineFound = true;
break;
}
dataChar = trailingEndInputStream.read();
finalBytePositionFound++;
}
trailingEndInputStream.close();
} else {
finalLineFound = true;
finalBytePositionFound = maxByteRange;
}
/*
* If we found the new line, then reset the parser for this line. Otherwise, increase the byte overlap and the
* trailing range.
*/
if (finalLineFound) {
long characterPositionAtBeginningOfRecord =
(record == null) ? 0 : record.getCharacterPosition();
InputStream completePartitionStream =
source.getInputStream(
adjustedStartByteRange + byteOffsetFromTruncatedRowAtStart,
finalBytePositionFound);
BufferedReader reader =
new BufferedReader(new InputStreamReader(completePartitionStream));
reader.skip(characterPositionAtBeginningOfRecord);
parser =
new CSVParser(
reader,
CSVFormat.newFormat(delimiter).withQuote(quote).withEscape(escape),
0,
0);
iterator = parser.iterator();
record = iterator.next();
if (nextRecordTruncated) {
record = iterator.next();
}
finishedReadingLastRow = true;
} else {
trailingStartByte += byteOverlap;
byteOverlap *= 2;
trailingEndByte += byteOverlap;
}
}
} else if (record.size() == schema.numColumns() && onLastRow && isLastWorker) {
finishedReadingLastRow = true;
}
/*
* If we're on the last row, we check if we've finished reading the row completely.
*/
if (!onLastRow || (onLastRow && finishedReadingLastRow)) {
for (int column = 0; column < schema.numColumns(); ++column) {
String cell = record.get(column);
try {
switch (schema.getColumnType(column)) {
case BOOLEAN_TYPE:
if (Floats.tryParse(cell) != null) {
buffer.putBoolean(column, Floats.tryParse(cell) != 0);
} else if (BooleanUtils.toBoolean(cell)) {
buffer.putBoolean(column, Boolean.parseBoolean(cell));
}
break;
case DOUBLE_TYPE:
buffer.putDouble(column, Double.parseDouble(cell));
break;
case FLOAT_TYPE:
buffer.putFloat(column, Float.parseFloat(cell));
break;
case INT_TYPE:
buffer.putInt(column, Integer.parseInt(cell));
break;
case LONG_TYPE:
buffer.putLong(column, Long.parseLong(cell));
break;
case STRING_TYPE:
buffer.putString(column, cell);
break;
case DATETIME_TYPE:
buffer.putDateTime(column, DateTimeUtils.parse(cell));
break;
case BLOB_TYPE:
throw new DbException(
"Ingesting BLOB via csv isn't supported. Use DownloadBlob expression.");
}
} catch (final IllegalArgumentException e) {
throw new DbException(
"Error parsing column "
+ column
+ " of row "
+ lineNumber
+ ", expected type: "
+ schema.getColumnType(column)
+ ", scanned value: "
+ cell,
e);
}
}
/*
* Once we finish reading the last row, we close the parser
*/
if (onLastRow) {
parser.close();
}
}
LOGGER.debug("Scanned {} input lines", lineNumber - lineNumberBegin);
}
return buffer.popAny();
}
@Override
public void cleanup() throws IOException {
parser = null;
while (buffer.numTuples() > 0) {
buffer.popAny();
}
}
@Override
protected Schema generateSchema() {
return schema;
}
@Override
protected void init(final ImmutableMap<String, Object> execEnvVars) throws DbException {
buffer = new TupleBatchBuffer(getSchema());
if (!flagAsRangeSelected) {
int workerID = getNodeID();
long fileSize = source.getFileSize();
long currentPartitionSize = fileSize / workerIds.length;
int workerIndex = -1;
for (int i = 0; i < workerIds.length; i++) {
if (workerID == workerIds[i]) {
workerIndex = i;
}
}
if (workerIndex >= 0) {
boolean isLastWorker = (workerIndex == workerIds.length - 1);
long startByteRange = currentPartitionSize * workerIndex;
long endByteRange;
if (isLastWorker) {
endByteRange = fileSize - 1;
} else {
endByteRange = (currentPartitionSize * (workerIndex + 1)) - 1;
}
this.partitionStartByteRange = startByteRange;
this.partitionEndByteRange = endByteRange;
this.isLastWorker = isLastWorker;
} else {
flagAsIncomplete = true;
}
}
try {
adjustedStartByteRange = partitionStartByteRange;
/* Optimization */
if (partitionStartByteRange != 0) {
adjustedStartByteRange -= 1;
}
partitionInputStream = source.getInputStream(adjustedStartByteRange, partitionEndByteRange);
/* If the file is empty, mark the partition as incomplete */
if (maxByteRange == 0) {
flagAsIncomplete = true;
}
/*
* If this is not the first worker, we make sure to read until we hit a new line character. We do this to skip
* partial rows at the beginning of the partition.
*/
if (partitionStartByteRange != 0) {
int firstChar = partitionInputStream.read();
byteOffsetFromTruncatedRowAtStart = 1;
if (firstChar != '\n' && firstChar != '\r') {
boolean newLineFound = false;
while (!newLineFound) {
int currentChar = partitionInputStream.read();
byteOffsetFromTruncatedRowAtStart++;
if (currentChar == '\n' || currentChar == '\r' || currentChar == -1) {
newLineFound = true;
/*
* If we never reach a new line (this could happen for a partial row at the last worker), mark as
* incomplete
*/
if (currentChar == -1) {
flagAsIncomplete = true;
} else if (currentChar == '\r') {
currentChar = partitionInputStream.read();
byteOffsetFromTruncatedRowAtStart++;
if (currentChar != '\n') {
byteOffsetFromTruncatedRowAtStart
partitionInputStream =
source.getInputStream(
adjustedStartByteRange + byteOffsetFromTruncatedRowAtStart,
partitionEndByteRange);
}
}
}
}
} else if (firstChar == '\r') {
int currentChar = partitionInputStream.read();
byteOffsetFromTruncatedRowAtStart++;
if (currentChar != '\n') {
byteOffsetFromTruncatedRowAtStart
partitionInputStream =
source.getInputStream(
adjustedStartByteRange + byteOffsetFromTruncatedRowAtStart,
partitionEndByteRange);
}
}
}
/* If we hit the end of the partition then mark it as incomplete.*/
if (adjustedStartByteRange + byteOffsetFromTruncatedRowAtStart - 1 == partitionEndByteRange) {
flagAsIncomplete = true;
}
/* If the partition is incomplete, do not instantiate the parser */
if (!flagAsIncomplete) {
parser =
new CSVParser(
new BufferedReader(new InputStreamReader(partitionInputStream)),
CSVFormat.newFormat(delimiter).withQuote(quote).withEscape(escape));
iterator = parser.iterator();
/* FIX ME: For now, we only support cases where all skipped lines are contained within the first partition. */
if (partitionStartByteRange == 0) {
for (int i = 0; i < numberOfSkippedLines; i++) {
iterator.next();
}
}
}
} catch (IOException e) {
throw new DbException(e);
}
}
}
|
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class CallbackVerifier {
private boolean verify(HttpServletRequest request, String authyApiKey)
throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String forwardedProtocol = request.getHeader("X-Forwarded-Proto");
String protocol = forwardedProtocol != null ? forwardedProtocol :
request.getScheme();
String url = String.format("%s://%s%s", protocol,
request.getServerName(), request.getServletPath());
// Fetch Json body
String body = IOUtils.toString(request.getReader());
Map<String, Object> bodyJson = objectMapper.readValue(body,
new TypeReference<Map<String, Object>>() {
});
// Flatten and sort JSON elements
String flattenJson = bodyJson.entrySet()
.stream()
.flatMap(FlatMap::flatten)
.map(e -> e.getKey() + "=" + e.getValue())
.sorted()
.collect(Collectors.joining("&"));
// Read the nonce from the request
String nonce = request.getHeader("X-Authy-Signature-Nonce");
// Join all the request bits using '|'
String data = String.format("%s|%s|%s|%s",
nonce,
request.getMethod(),
url,
flattenJson);
try {
// Compute the signature
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(authyApiKey.getBytes(),
"HmacSHA256");
sha256_HMAC.init(secret_key);
String hash = Base64
.getEncoder()
.encodeToString(sha256_HMAC.doFinal(data.getBytes()));
// Extract the actual request signature
String signature = request.getHeader("X-Authy-Signature");
// Compare the request signature with your computed signature
return hash.equals(signature);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace();
return false;
}
}
}
class FlatMap {
private static String openBracket;
private static String closeBracket;
static {
try {
openBracket = encode("[", "UTF-8");
closeBracket = encode("]", "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private static String prependKeyName(String keyName, String prefix) {
StringBuffer result = new StringBuffer();
result.append(prefix);
int indexOfOpenBracket = keyName.indexOf(openBracket);
if(indexOfOpenBracket == -1) {
indexOfOpenBracket = keyName.length();
}
result.append(openBracket);
result.append(keyName.substring(0, indexOfOpenBracket));
result.append(closeBracket);
result.append(keyName.substring(indexOfOpenBracket));
return result.toString();
}
public static Stream<Map.Entry<?, ?>> flatten(Map.Entry<?, ?> e) {
Object value = e.getValue();
if (value instanceof Map<?, ?>) {
return ((Map<?, ?>) value).entrySet()
.stream()
.flatMap(FlatMap::flatten)
.map(el -> {
String newKeyName = FlatMap.prependKeyName(
(String) el.getKey(), (String) e.getKey());
return new AbstractMap.SimpleEntry<>(newKeyName, el.getValue());
});
} else if(value == null) {
return Stream.of(new AbstractMap.SimpleEntry<>(e.getKey(), ""));
} else if(value instanceof String) {
try {
String encodedValue = URLEncoder.encode((String) value, "UTF-8");
return Stream.of(new AbstractMap.SimpleEntry<>(e.getKey(),
encodedValue.replace(" ", "+")));
} catch (UnsupportedEncodingException exception) {
throw new RuntimeException(exception);
}
}
return Stream.of(e);
}
}
|
package org.objectweb.asm.commons;
import org.objectweb.asm.AnnotationVisitor;
/**
* An <code>AnnotationVisitor</code> adapter for type remapping.
*
* @author Eugene Kuleshov
*/
public class RemappingAnnotationAdapter implements AnnotationVisitor {
private final AnnotationVisitor av;
private final Remapper renamer;
public RemappingAnnotationAdapter(AnnotationVisitor av, Remapper renamer) {
this.av = av;
this.renamer = renamer;
}
public void visit(String name, Object value) {
av.visit(name, renamer.mapValue(value));
}
public void visitEnum(String name, String desc, String value) {
av.visitEnum(name, renamer.mapType(desc), value);
}
public AnnotationVisitor visitAnnotation(String name, String desc) {
AnnotationVisitor v = av.visitAnnotation(name, renamer.mapType(desc));
return v == av ? this : new RemappingAnnotationAdapter(v, renamer);
}
public AnnotationVisitor visitArray(String name) {
AnnotationVisitor v = av.visitArray(name);
return v == av ? this : new RemappingAnnotationAdapter(v, renamer);
}
public void visitEnd() {
av.visitEnd();
}
}
|
package org.springframework.web.servlet.view.tiles;
import java.io.IOException;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.tiles.ComponentContext;
import org.apache.struts.tiles.ComponentDefinition;
import org.apache.struts.tiles.Controller;
import org.apache.struts.tiles.DefinitionsFactory;
import org.apache.struts.tiles.DefinitionsFactoryException;
import org.apache.struts.tiles.TilesUtilImpl;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.servlet.view.InternalResourceView;
/**
* TilesView retrieves a Tiles definition.
* The "url" property is interpreted as name of a Tiles definition.
*
* <p>TilesJstlView with JSTL support is a separate class,
* mainly to avoid JSTL dependencies in this class.
*
* <p>A component controller specified in the Tiles definition will receive
* a reference to the current Spring ApplicationContext if it implements
* ApplicationContextAware. The ComponentControllerSupport class provides
* a convenient base class for such Spring-aware component controllers.
*
* @author Alef Arendsen
* @author Juergen Hoeller
* @see #setUrl
* @see TilesConfigurer
* @see TilesJstlView
* @see ComponentControllerSupport
* @see org.springframework.context.ApplicationContextAware
*/
public class TilesView extends InternalResourceView {
/**
* The actual rendering of the Tiles definition.
*/
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (!response.isCommitted()) {
response.setContentType(getContentType());
}
try {
// get definitions factory
DefinitionsFactory factory = (DefinitionsFactory)
getWebApplicationContext().getServletContext().
getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY);
if (factory == null) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Tiles definitions factory not found: TilesConfigurer not defined?");
}
// get component definition
ComponentDefinition definition = factory.getDefinition(getUrl(), request, getServletContext());
if (definition == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND,
"Tile with name '" + getName() + "' not found");
return;
}
exposeModelsAsRequestAttributes(model, request);
// get current tile context
ComponentContext tileContext = ComponentContext.getContext(request);
if (tileContext == null) {
tileContext = new ComponentContext(definition.getAttributes());
ComponentContext.setContext(tileContext, request);
}
else {
tileContext.addMissing(definition.getAttributes());
}
// execute controller associated to definition, if any
Controller controller = definition.getOrCreateController();
System.out.println("Executing controller " + controller);
if (controller instanceof ApplicationContextAware) {
System.out.println("Setting applcation context " + getApplicationContext());
((ApplicationContextAware) controller).setApplicationContext(getApplicationContext());
}
if (controller != null) {
System.out.println("Executing controller " + controller + " now");
controller.perform(tileContext, request, response, getServletContext());
}
// process the definition
RequestDispatcher rd = request.getRequestDispatcher(definition.getPath());
if (rd == null) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
rd.include(request, response);
}
catch (DefinitionsFactoryException ex) {
throw new ServletException(ex.getMessage(), ex);
}
catch (InstantiationException ex) {
throw new ServletException(ex.getMessage(), ex);
}
}
}
|
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc2619.PlyBot2017.subsystems;
import org.usfirst.frc2619.PlyBot2017.MathUtil;
import org.usfirst.frc2619.PlyBot2017.Robot;
import org.usfirst.frc2619.PlyBot2017.RobotMap;
import org.usfirst.frc2619.PlyBot2017.commands.*;
import com.ctre.CANTalon;
import com.kauailabs.navx.frc.AHRS;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class DriveTrain extends Subsystem {
private final double TICKS_PER_FOOT = 4273;
private double Destination = 0;
private double numFeet = 0;
public boolean isReversed = false;
public int DELIN_POW = 3;
public double DEADBAND_X = 0.2;
public double DEADBAND_Y = 0.1;
public double DEADBAND_TWIST = 0.2;
public double TURN_OUTER_SPEED = 0.5;
public double TURN_INNER_SPEED = -0.5;
private static final String DELIN_POW_KEY = "DELIN_POW";
private static final String DEADBAND_X_KEY = "DEADBAND_X";
private static final String DEADBAND_Y_KEY = "DEADBAND_Y";
private static final String DEADBAND_TWIST_KEY = "DEADBAND_TWIST";
private static final String TURN_OUTER_SPEED_KEY = "TURN_OUTER_SPEED";
private static final String TURN_INNER_SPEED_KEY = "TURN_INNER_SPEED";
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
private final CANTalon leftFrontMotor = RobotMap.driveTrainLeftFrontMotor;
private final CANTalon rightFrontMotor = RobotMap.driveTrainRightFrontMotor;
private final CANTalon rightRearMotor = RobotMap.driveTrainRightRearMotor;
private final CANTalon leftRearMotor = RobotMap.driveTrainLeftRearMotor;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
private final AHRS ahrs = RobotMap.driveTrainAHRS;
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void writeDefaultValues() {
SmartDashboard.putNumber(DELIN_POW_KEY, DELIN_POW);
SmartDashboard.putNumber(DEADBAND_X_KEY, DEADBAND_X);
SmartDashboard.putNumber(DEADBAND_Y_KEY, DEADBAND_Y);
SmartDashboard.putNumber(DEADBAND_TWIST_KEY, DEADBAND_TWIST);
SmartDashboard.putNumber(TURN_OUTER_SPEED_KEY, TURN_OUTER_SPEED);
SmartDashboard.putNumber(TURN_INNER_SPEED_KEY, TURN_INNER_SPEED);
}
public void readControlValues() {
DELIN_POW = SmartDashboard.getInt(DELIN_POW_KEY);
DEADBAND_X = SmartDashboard.getNumber(DEADBAND_X_KEY);
DEADBAND_Y = SmartDashboard.getNumber(DEADBAND_Y_KEY);
DEADBAND_TWIST = SmartDashboard.getNumber(DEADBAND_TWIST_KEY);
TURN_OUTER_SPEED = SmartDashboard.getNumber(TURN_OUTER_SPEED_KEY);
TURN_INNER_SPEED = SmartDashboard.getNumber(TURN_INNER_SPEED_KEY);
}
public void writeDebugValues(){
SmartDashboard.putNumber("IMU_TotalYaw", ahrs.getAngle());
SmartDashboard.putNumber("IMU_YawRateDPS", ahrs.getRate());
SmartDashboard.putBoolean("IMU_Connected", ahrs.isConnected());
SmartDashboard.putBoolean("IMU_IsCalibrating", ahrs.isCalibrating());
SmartDashboard.putNumber("IMU_Yaw", ahrs.getYaw());
SmartDashboard.putNumber("IMU_Pitch", ahrs.getPitch());
SmartDashboard.putNumber("IMU_Roll", ahrs.getRoll());
// Connectivity Debugging Support
SmartDashboard.putNumber( "IMU_Byte_Count", ahrs.getByteCount());
SmartDashboard.putNumber( "IMU_Update_Count", ahrs.getUpdateCount());
}
public void run(double leftSpeed, double rightSpeed){
writeDebugValues();
SmartDashboard.putNumber("LeftSpeed", leftSpeed);
SmartDashboard.putNumber("RightSpeed", rightSpeed);
if(!isReversed) {
leftFrontMotor.set(leftSpeed);
rightFrontMotor.set(rightSpeed);
}
else {
leftFrontMotor.set(-1*rightSpeed);
rightFrontMotor.set(-1*leftSpeed);
}
}
public double getFeet() {
return (leftFrontMotor.getEncPosition()) / TICKS_PER_FOOT; // Gives the number of ticks the left front motor is currently at in feet.
}
public double getTicks() {
return (leftFrontMotor.getEncPosition()); // Gives the number of ticks the left front motor is currently at.
}
public void sendFeet(double f) {
Destination = 0;
numFeet = f;
Destination = getTicks() + (((numFeet * 1.017) - (12.147 / 12)) * TICKS_PER_FOOT);
SmartDashboard.putNumber("Destination", Destination);
}
public boolean isAtDestination() {
SmartDashboard.putNumber("getTicks()", getTicks());
if (numFeet > 0)
{
return getTicks() >= Destination;
}
else {
return getTicks() <= Destination;
}
}
public void stop() {
Robot.driveTrain.run(0, 0);
}
public double getDegrees(){
return ahrs.getAngle();
}
public double getYaw(){
return ahrs.getYaw();
}
public void relTurn(double turnTo, double speed){
double leftSpeed =0, rightSpeed = 0;
double direction = MathUtil.calcDirection(getDegrees(), turnTo);
if(direction >= 0){
leftSpeed = speed;
rightSpeed = 0;
//run(speed, -speed);
SmartDashboard.putString("Direction", "right");
}
else if(direction < 0){
leftSpeed = 0;
rightSpeed = speed;
//run(-speed, speed);
SmartDashboard.putString("Direction", "left");
}
else{
leftSpeed = 0;
rightSpeed = 0;
//run(0,0);
SmartDashboard.putString("Direction", "none");
}
run(leftSpeed,rightSpeed);
}
public void absTurn(double degreeChange, double speed){
double leftSpeed = 0, rightSpeed = 0;
if (degreeChange > 0){
leftSpeed = TURN_OUTER_SPEED;
rightSpeed = -1 * TURN_INNER_SPEED;
}
else if (degreeChange < 0){
rightSpeed = TURN_OUTER_SPEED;
leftSpeed = -1 * TURN_INNER_SPEED;
}
run(leftSpeed,rightSpeed);
}
public void initDefaultCommand() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
setDefaultCommand(new TankDrive());
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// Set the default command for a subsystem here.
// setDefaultCommand(new MySpecialCommand());
}
}
|
package soot.jimple.toolkits.pointer;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import org.omg.CORBA.UNKNOWN;
import soot.Local;
import soot.RefLikeType;
import soot.Unit;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.CastExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.InvokeExpr;
import soot.jimple.NewExpr;
import soot.jimple.ParameterRef;
import soot.jimple.Stmt;
import soot.jimple.ThisRef;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ForwardFlowAnalysis;
/** LocalMustAliasAnalysis attempts to determine if two local
* variables (at two potentially different program points) must point
* to the same object.
*
* The underlying abstraction is based on global value numbering.
*
* @author Patrick Lam
* @author Eric Bodden
* */
public class LocalMustAliasAnalysis extends ForwardFlowAnalysis<Unit,HashMap<Local,Object>>
{
public static final String UNKNOWN_LABEL = "UNKNOWN";
protected static final Object UNKNOWN = new Object() {
public String toString() { return UNKNOWN_LABEL; }
};
protected static final Object NOTHING = new Object() {
public String toString() { return "NOTHING"; }
};
protected List<Local> locals;
protected int nextNumber = 1;
public LocalMustAliasAnalysis(UnitGraph g)
{
super(g);
this.locals = new LinkedList<Local>();
for (Local l : (Collection<Local>) g.getBody().getLocals()) {
if (l.getType() instanceof RefLikeType)
this.locals.add(l);
}
doAnalysis();
}
protected void merge(HashMap<Local,Object> inMap1, HashMap<Local,Object> inMap2, HashMap<Local,Object> outMap)
{
for (Local l : locals) {
Object i1 = inMap1.get(l), i2 = inMap2.get(l);
if (i1.equals(i2))
outMap.put(l, i1);
else if (i1 == NOTHING)
outMap.put(l, i2);
else if (i2 == NOTHING)
outMap.put(l, i1);
else
outMap.put(l, UNKNOWN);
}
}
protected void flowThrough(HashMap<Local,Object> in, Unit u, HashMap<Local,Object> out) {
Stmt s = (Stmt)u;
out.clear();
out.putAll(in);
if (s instanceof DefinitionStmt) {
DefinitionStmt ds = (DefinitionStmt) s;
Value lhs = ds.getLeftOp();
Value rhs = ds.getRightOp();
if (rhs instanceof CastExpr) {
CastExpr castExpr = (CastExpr) rhs;
rhs = castExpr.getOp();
}
if (lhs instanceof Local && lhs.getType() instanceof RefLikeType) {
if (rhs instanceof NewExpr ||
rhs instanceof InvokeExpr ||
rhs instanceof ParameterRef ||
rhs instanceof FieldRef ||
rhs instanceof ThisRef ||
rhs instanceof ArrayRef) {
//expression could have changed, hence assign a fresh number
//(thisref and parameterref cannot actually change but whatever...)
out.put((Local) lhs, nextNumber++);
} else if (rhs instanceof Local) {
out.put((Local) lhs, in.get(rhs));
} else out.put((Local) lhs, UNKNOWN);
}
}
}
protected void copy(HashMap<Local,Object> sourceMap, HashMap<Local,Object> destMap)
{
for (Local l : (Collection<Local>) locals) {
destMap.put (l, sourceMap.get(l));
}
}
/** Initial most conservative value: has to be {@link UNKNOWN} (top). */
protected HashMap<Local,Object> entryInitialFlow()
{
HashMap<Local,Object> m = new HashMap<Local,Object>();
for (Local l : (Collection<Local>) locals) {
m.put(l, UNKNOWN);
}
return m;
}
/** Initial bottom value: objects have no definitions. */
protected HashMap<Local,Object> newInitialFlow()
{
HashMap<Local,Object> m = new HashMap<Local,Object>();
for (Local l : (Collection<Local>) locals) {
m.put(l, NOTHING);
}
return m;
}
/**
* Returns a string (natural number) representation of the instance key associated with l
* at statement s or <code>null</code> if there is no such key associated or <code>UNKNOWN</code> if
* the value of l at s is {@link #UNKNOWN}.
* @param l any local of the associated method
* @param s the statement at which to check
*/
public String instanceKeyString(Local l, Stmt s) {
Object ln = getFlowBefore(s).get(l);
if(ln==null) {
return null;
} else if(ln==UNKNOWN) {
return UNKNOWN.toString();
}
return ln.toString();
}
/**
* Returns true if this analysis has any information about local l
* at statement s (i.e. it is not {@link #UNKNOWN}).
* In particular, it is safe to pass in locals/statements that are not
* even part of the right method. In those cases <code>false</code>
* will be returned.
* Permits s to be <code>null</code>, in which case <code>false</code> will be returned.
*/
public boolean hasInfoOn(Local l, Stmt s) {
HashMap<Local,Object> flowBefore = getFlowBefore(s);
if(flowBefore==null) {
return false;
} else {
Object info = flowBefore.get(l);
return info!=null && info!=UNKNOWN;
}
}
/**
* @return true if values of l1 (at s1) and l2 (at s2) have the
* exact same object IDs, i.e. at statement s1 the variable l1 must point to the same object
* as l2 at s2.
*/
public boolean mustAlias(Local l1, Stmt s1, Local l2, Stmt s2) {
Object l1n = getFlowBefore(s1).get(l1);
Object l2n = getFlowBefore(s2).get(l2);
if (l1n == UNKNOWN || l2n == UNKNOWN)
return false;
return l1n == l2n;
}
}
|
package org.craft.atom.nio;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.craft.atom.io.ChannelEventType;
import org.craft.atom.io.IoHandler;
import org.craft.atom.io.IoProtocol;
import org.craft.atom.nio.spi.NioChannelEventDispatcher;
import org.craft.atom.util.NamedThreadFactory;
/**
* Processor process actual I/O operations.
* It abstracts Java NIO to simplify transport implementations.
*
* @author mindwind
* @version 1.0, Feb 22, 2013
*/
public class NioProcessor extends NioReactor {
private static final Log LOG = LogFactory.getLog(NioProcessor.class);
/** Flush spin count */
private static final long FLUSH_SPIN_COUNT = 256;
/** A channel queue containing the newly created channel */
private final Queue<NioByteChannel> newChannels = new ConcurrentLinkedQueue<NioByteChannel>();
/** A queue used to store the channel to be flushed */
private final Queue<NioByteChannel> flushingChannels= new ConcurrentLinkedQueue<NioByteChannel>();
/** A queue used to store the channel to be closed */
private final Queue<NioByteChannel> closingChannels = new ConcurrentLinkedQueue<NioByteChannel>();
/** UDP channel holders */
private final Map<String, NioByteChannel> udpChannels = new ConcurrentHashMap<String, NioByteChannel>();
private final Executor executor;
private final NioConfig config;
private final AtomicReference<ProcessThread> processThreadRef = new AtomicReference<ProcessThread>();
private final NioByteBufferAllocator allocator = new NioByteBufferAllocator();
private final AtomicBoolean wakeupCalled = new AtomicBoolean(false);
private final NioChannelIdleTimer idleTimer = NioChannelIdleTimer.getInstance();
private IoProtocol protocol;
private volatile Selector selector;
private volatile boolean shutdown = false;
NioProcessor(NioConfig config, IoHandler handler, NioChannelEventDispatcher dispatcher) {
this.config = config;
this.handler = handler;
this.dispatcher = dispatcher;
this.executor = Executors.newCachedThreadPool(new NamedThreadFactory("craft-atom-nio-processor"));
try {
selector = Selector.open();
} catch (IOException e) {
throw new RuntimeException("Fail to startup a processor", e);
}
}
/**
* Adds a nio channel to processor's new channel queue, so that processor can process I/O operations associated this channel.
*
* @param channel
*/
public void add(NioByteChannel channel) {
if (this.shutdown) {
throw new IllegalStateException("The processor already shutdown!");
}
if (channel == null) {
LOG.warn("Add null, return!");
return;
}
newChannels.add(channel);
startup();
wakeup();
}
private void startup() {
ProcessThread pt = processThreadRef.get();
if (pt == null) {
pt = new ProcessThread();
if (processThreadRef.compareAndSet(null, pt)) {
executor.execute(pt);
}
}
}
private void wakeup() {
wakeupCalled.getAndSet(true);
selector.wakeup();
}
/**
* shutdown the processor, stop the process thread and close all the channel within this processor
*/
public void shutdown() {
this.shutdown = true;
wakeup();
}
private void shutdown0() throws IOException {
// close all the channel within this processor
this.closingChannels.addAll(newChannels);
newChannels.clear();
this.closingChannels.addAll(flushingChannels);
flushingChannels.clear();
close();
// close processor selector
this.selector.close();
if (LOG.isDebugEnabled()) { LOG.debug("shutdown processor successful!"); }
}
private void close() throws IOException {
for (NioByteChannel channel = closingChannels.poll(); channel != null; channel = closingChannels.poll()) {
if (channel.isClosed()) {
if (LOG.isDebugEnabled()) { LOG.debug("Skip closes channel=" + channel); }
continue;
}
channel.setClosing();
if (LOG.isDebugEnabled()) { LOG.debug("Closing channel=" + channel); }
close(channel);
channel.setClosed();
idleTimer.remove(channel);
// fire channel closed event
fireChannelClosed(channel);
if (LOG.isDebugEnabled()) { LOG.debug("Closed channel=" + channel); }
}
}
private void close(NioByteChannel channel) throws IOException {
channel.close0();
if (protocol == IoProtocol.UDP) {
String key = udpChannelKey(channel.getLocalAddress(), channel.getRemoteAddress());
udpChannels.remove(key);
}
}
private int select() throws IOException {
int selected = selector.select();
if ((selected == 0) && !wakeupCalled.get()) {
// the select() may have been interrupted because we have had an closed channel.
if (isBrokenConnection()) {
LOG.warn("Broken connection wakeup");
} else {
LOG.warn("Create a new selector. Selected is 0");
registerNewSelector();
}
// Set back the flag to false and continue the loop
wakeupCalled.getAndSet(false);
}
return selected;
}
private void registerNewSelector() throws IOException {
synchronized (this) {
Set<SelectionKey> keys = selector.keys();
// Open a new selector
Selector newSelector = Selector.open();
// Loop on all the registered keys, and register them on the new selector
for (SelectionKey key : keys) {
SelectableChannel ch = key.channel();
// Don't forget to attache the channel, and back !
NioByteChannel channel = (NioByteChannel) key.attachment();
ch.register(newSelector, key.interestOps(), channel);
}
// Now we can close the old selector and switch it
selector.close();
selector = newSelector;
}
}
private boolean isBrokenConnection() throws IOException {
boolean brokenSession = false;
synchronized (selector) {
Set<SelectionKey> keys = selector.keys();
for (SelectionKey key : keys) {
SelectableChannel channel = key.channel();
if (!((SocketChannel) channel).isConnected()) {
// The channel is not connected anymore. Cancel the associated key.
key.cancel();
brokenSession = true;
}
}
}
return brokenSession;
}
private void register() throws ClosedChannelException {
for (NioByteChannel channel = newChannels.poll(); channel != null; channel = newChannels.poll()) {
SelectableChannel sc = channel.innerChannel();
SelectionKey key = sc.register(selector, SelectionKey.OP_READ, channel);
channel.setSelectionKey(key);
idleTimer.add(channel);
// fire channel opened event
fireChannelOpened(channel);
}
}
private void process() {
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
NioByteChannel channel = (NioByteChannel) it.next().attachment();
if (channel.isValid()) {
process0(channel);
} else {
LOG.warn("Channel is invalid, but some event trigger to process! channel=" + channel);
}
it.remove();
}
}
private void process0(NioByteChannel channel) {
// set last IO time
channel.setLastIoTime(System.currentTimeMillis());
// Process reads
if (channel.isReadable()) {
if (LOG.isDebugEnabled()) { LOG.debug("Read event process on channel=" + channel); }
read(channel);
}
// Process writes
if (channel.isWritable()) {
if (LOG.isDebugEnabled()) { LOG.debug("Write event process on channel=" + channel); }
asyWrite(channel);
}
}
private void read(NioByteChannel channel) {
int bufferSize = channel.getPredictor().next();
ByteBuffer buf = allocator.allocate(bufferSize);
if (LOG.isDebugEnabled()) { LOG.debug("Predict buffer size=" + bufferSize + ", allocate buffer=" + buf); }
int readBytes = 0;
try {
if (protocol.equals(IoProtocol.TCP)) {
readBytes = readTcp(channel, buf);
} else if (protocol.equals(IoProtocol.UDP)) {
readBytes = readUdp(channel, buf);
}
} catch (Throwable t) {
LOG.warn("Catch read exception and fire it, channel=" + channel, t);
// fire exception caught event
fireChannelThrown(channel, t);
// if it is IO exception close channel avoid infinite loop.
if (t instanceof IOException) {
asyClose(channel);
}
} finally {
if (readBytes > 0) { buf.clear(); }
}
}
private int readTcp(NioByteChannel channel, ByteBuffer buf) throws IOException {
int readBytes = 0;
int ret;
while ((ret = channel.readTcp(buf)) > 0) {
readBytes += ret;
if (!buf.hasRemaining()) {
break;
}
}
if (readBytes > 0) {
channel.getPredictor().previous(readBytes);
fireChannelRead(channel, buf, readBytes);
if (LOG.isDebugEnabled()) { LOG.debug("Actual read=" + readBytes); }
}
// read end-of-stream, remote peer may close channel so close channel.
if (ret < 0) {
asyClose(channel);
}
return readBytes;
}
private void asyClose(NioByteChannel channel) {
if (channel.isClosing() || channel.isClosed()) {
return;
}
closingChannels.add(channel);
}
private int readUdp(NioByteChannel channel, ByteBuffer buf) throws IOException {
SocketAddress remoteAddress = channel.readUdp(buf);
if (remoteAddress == null) {
// no datagram was immediately available
return 0;
}
int readBytes = buf.position();
String key = udpChannelKey(channel.getLocalAddress(), remoteAddress);
if (!udpChannels.containsKey(key)) {
// handle first datagram with current channel
channel.setRemoteAddress(remoteAddress);
udpChannels.put(key, channel);
}
channel.setLastIoTime(System.currentTimeMillis());
fireChannelRead(channel, buf, buf.position());
return readBytes;
}
private String udpChannelKey(SocketAddress localAddress, SocketAddress remoteAddress) {
return localAddress.toString() + "-" + remoteAddress.toString();
}
/**
* Add the channel to the processor's flushing channel queue, and notify processor flush it immediately.
*
* @param channel
*/
public void flush(NioByteChannel channel) {
if (this.shutdown) {
throw new IllegalStateException("The processor is already shutdown!");
}
if (channel == null) {
return;
}
asyWrite(channel);
wakeup();
}
private void asyWrite(NioByteChannel channel) {
// Add channel to flushing queue, soon after it will be flushed in the same select loop.
flushingChannels.add(channel);
}
private void flush() {
int c = 0;
while (!flushingChannels.isEmpty() && c < FLUSH_SPIN_COUNT) {
NioByteChannel channel = flushingChannels.poll();
if (channel == null) {
// Just in case ... It should not happen.
break;
}
try {
if (channel.isClosed() || channel.isClosing()) {
if (LOG.isDebugEnabled()) { LOG.debug("Channel=" + channel + ", flushing channel size=" + flushingChannels.size()); }
continue;
} else {
// spin counter avoid infinite loop in this method.
c++;
flush0(channel);
}
} catch (Throwable t) {
LOG.warn("Catch flush exception and fire it", t);
// fire channel thrown event
fireChannelThrown(channel, t);
// if it is IO exception close channel avoid infinite loop.
if (t instanceof IOException) {
asyClose(channel);
}
}
}
}
private void flush0(NioByteChannel channel) throws IOException {
if (LOG.isDebugEnabled()) { LOG.debug("Flushing channel=" + channel); }
Queue<ByteBuffer> writeQueue = channel.getWriteBufferQueue();
// First set not be interested to write event
setInterestedInWrite(channel, false);
// flush by mode
if (config.isReadWritefair()) {
fairFlush0(channel, writeQueue);
} else {
oneOffFlush0(channel, writeQueue);
}
// The write buffer queue is not empty, we re-interest in writing and later flush it.
if (!writeQueue.isEmpty()) {
setInterestedInWrite(channel, true);
flushingChannels.add(channel);
}
}
private void oneOffFlush0(NioByteChannel channel, Queue<ByteBuffer> writeQueue) throws IOException {
ByteBuffer buf = writeQueue.peek();
if (buf == null) {
return;
}
// fire channel flush event
fireChannelFlush(channel, buf);
write(channel, buf, buf.remaining());
if (buf.hasRemaining()) {
setInterestedInWrite(channel, true);
flushingChannels.add(channel);
return;
} else {
writeQueue.remove();
// fire channel written event
fireChannelWritten(channel, buf);
}
}
private void fairFlush0(NioByteChannel channel, Queue<ByteBuffer> writeQueue) throws IOException {
ByteBuffer buf = null;
int writtenBytes = 0;
final int maxWrittenBytes = channel.getMaxWriteBufferSize();
if (LOG.isDebugEnabled()) { LOG.debug("Max write byte size=" + maxWrittenBytes); }
do {
if (buf == null) {
buf = writeQueue.peek();
if (buf == null) {
return;
} else {
// fire channel flush event
fireChannelFlush(channel, buf);
}
}
int qota = maxWrittenBytes - writtenBytes;
int localWrittenBytes = write(channel, buf, qota);
if (LOG.isDebugEnabled()) { LOG.debug("Flush buffer=" + new String(buf.array()) + " channel=" + channel + " written-bytes=" + localWrittenBytes + " buf-bytes=" + buf.array().length + " qota=" + qota + " buf-remaining=" + buf.hasRemaining()); }
writtenBytes += localWrittenBytes;
// The buffer is all flushed, remove it from write queue
if (!buf.hasRemaining()) {
if (LOG.isDebugEnabled()) { LOG.debug("The buffer is all flushed, remove it from write queue"); }
writeQueue.remove();
// fire channel written event
fireChannelWritten(channel, buf);
// set buf=null and the next loop if no byte buffer to write then break the loop.
buf = null;
continue;
}
// 0 byte be written, maybe kernel buffer is full so we re-interest in writing and later flush it.
if (localWrittenBytes == 0) {
if (LOG.isDebugEnabled()) { LOG.debug("Zero byte be written, maybe kernel buffer is full so we re-interest in writing and later flush it, channel=" + channel); }
setInterestedInWrite(channel, true);
flushingChannels.add(channel);
return;
}
// The buffer isn't empty(bytes to flush more than max bytes), we re-interest in writing and later flush it.
if (localWrittenBytes > 0 && buf.hasRemaining()) {
if (LOG.isDebugEnabled()) { LOG.debug("The buffer isn't empty(bytes to flush more than max bytes), we re-interest in writing and later flush it, channel=" + channel); }
setInterestedInWrite(channel, true);
flushingChannels.add(channel);
return;
}
// Wrote too much, so we re-interest in writing and later flush other bytes.
if (writtenBytes >= maxWrittenBytes && buf.hasRemaining()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Wrote too much, so we re-interest in writing and later flush other bytes, channel=" + channel);
}
setInterestedInWrite(channel, true);
flushingChannels.add(channel);
return;
}
} while (writtenBytes < maxWrittenBytes);
}
private void setInterestedInWrite(NioByteChannel channel, boolean isInterested) {
SelectionKey key = channel.getSelectionKey();
if (key == null || !key.isValid()) {
return;
}
int oldInterestOps = key.interestOps();
int newInterestOps = oldInterestOps;
if (isInterested) {
newInterestOps |= SelectionKey.OP_WRITE;
} else {
newInterestOps &= ~SelectionKey.OP_WRITE;
}
if (oldInterestOps != newInterestOps) {
key.interestOps(newInterestOps);
}
}
private int write(NioByteChannel channel, ByteBuffer buf, int maxLength) throws IOException {
int writtenBytes = 0;
if (LOG.isDebugEnabled()) { LOG.debug("Allow write max len=" + maxLength + ", Waiting write byte buffer=" + buf); }
if (buf.hasRemaining()) {
int length = Math.min(buf.remaining(), maxLength);
if (protocol.equals(IoProtocol.TCP)) {
writtenBytes = writeTcp(channel, buf, length);
} else if (protocol.equals(IoProtocol.UDP)) {
writtenBytes = writeUdp(channel, buf, length);
}
}
if (LOG.isDebugEnabled()) { LOG.debug("Actual written byte size=" + writtenBytes); }
return writtenBytes;
}
private int writeTcp(NioByteChannel channel, ByteBuffer buf, int length) throws IOException {
if (buf.remaining() <= length) {
return channel.writeTcp(buf);
}
int oldLimit = buf.limit();
buf.limit(buf.position() + length);
try {
return channel.writeTcp(buf);
} finally {
buf.limit(oldLimit);
}
}
private int writeUdp(NioByteChannel channel, ByteBuffer buf, int length) throws IOException {
if (buf.remaining() <= length) {
return channel.writeUdp(buf, channel.getRemoteAddress());
}
int oldLimit = buf.limit();
buf.limit(buf.position() + length);
try {
return channel.writeUdp(buf, channel.getRemoteAddress());
} finally {
buf.limit(oldLimit);
}
}
/**
* Removes and closes the specified channel from the processor,
* so that processor closes the channel and releases any other related resources.
*
* @param channel
*/
void remove(NioByteChannel channel) {
if (this.shutdown) {
throw new IllegalStateException("The processor is already shutdown!");
}
if (channel == null) {
return;
}
asyClose(channel);
wakeup();
}
private void fireChannelOpened(NioByteChannel channel) {
dispatcher.dispatch(new NioByteChannelEvent(ChannelEventType.CHANNEL_OPENED, channel, handler));
}
private void fireChannelRead(NioByteChannel channel, ByteBuffer buf, int length) {
// fire channel received event, here we copy buffer bytes to a new byte array to avoid handler expose <code>ByteBuffer</code> to end user.
byte[] barr = new byte[length];
System.arraycopy(buf.array(), 0, barr, 0, length);
dispatcher.dispatch(new NioByteChannelEvent(ChannelEventType.CHANNEL_READ, channel, handler, barr));
}
private void fireChannelFlush(NioByteChannel channel, ByteBuffer buf) {
dispatcher.dispatch(new NioByteChannelEvent(ChannelEventType.CHANNEL_FLUSH, channel, handler, buf.array()));
}
private void fireChannelWritten(NioByteChannel channel, ByteBuffer buf) {
dispatcher.dispatch(new NioByteChannelEvent(ChannelEventType.CHANNEL_WRITTEN, channel, handler, buf.array()));
}
private void fireChannelThrown(NioByteChannel channel, Throwable t) {
dispatcher.dispatch(new NioByteChannelEvent(ChannelEventType.CHANNEL_THROWN, channel, handler, t));
}
private void fireChannelClosed(NioByteChannel channel) {
dispatcher.dispatch(new NioByteChannelEvent(ChannelEventType.CHANNEL_CLOSED, channel, handler));
}
private class ProcessThread implements Runnable {
public void run() {
while (!shutdown) {
try {
int selected = select();
// flush channels
flush();
// register new channels
register();
if (selected > 0) { process(); }
// close channels
close();
} catch (Exception e) {
LOG.error("Unexpected exception caught while process", e);
}
}
// if shutdown == true, we shutdown the processor
if (shutdown) {
try {
shutdown0();
} catch (Exception e) {
LOG.error("Unexpected exception caught while shutdown", e);
}
}
}
}
public void setProtocol(IoProtocol protocol) {
this.protocol = protocol;
}
}
|
package test.dr.inference.distribution;
import dr.inference.distribution.DirichletProcessLikelihood;
import dr.inference.model.*;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* A test suit for the Dirichlet Process likelihood.
*
* @author Andrew Rambaut
* @author Trevor Bedford
* @version $Id: BinomialLikelihood.java,v 1.5 2005/05/24 20:25:59 rambaut Exp $
*/
public class DirichletProcessTest extends TestCase {
public DirichletProcessTest(String name) {
super(name);
}
public void setUp() throws Exception {
super.setUp();
}
public void testDirichletProcess() {
// these are expected results calculated manually...
testDirichletProcess(new double[] {1, 1, 1}, 1.0, -Math.log(6.0)); // log 1/6
testDirichletProcess(new double[] {2, 1}, 1.0, -Math.log(6.0)); // log 1/6
testDirichletProcess(new double[] {3}, 1.0, -Math.log(3.0)); // log 1/3
// check the unoccupied groups are not counted
testDirichletProcess(new double[] {2, 1, 0}, 1.0, -Math.log(6.0)); // log 1/6
testDirichletProcess(new double[] {3, 0, 0}, 1.0, -Math.log(3.0)); // log 1/3
// these are results calculated by the method but confirmed against an independent implementation...
testDirichletProcess(new double[] {1, 1, 1, 1, 1}, 0.5, -6.851184927493743);
testDirichletProcess(new double[] {2, 1, 1, 1, 0}, 0.5, -6.158037746933798);
testDirichletProcess(new double[] {3, 1, 1, 0, 0}, 0.5, -4.771743385813907);
testDirichletProcess(new double[] {4, 1, 0, 0, 0}, 0.5, -2.9799839165858524);
testDirichletProcess(new double[] {5, 0, 0, 0, 0}, 0.5, -0.9005423749060166);
testDirichletProcess(new double[] {1, 1, 1, 1, 1}, 1.0, -4.787491742782046);
testDirichletProcess(new double[] {2, 1, 1, 1, 0}, 1.0, -4.787491742782046);
testDirichletProcess(new double[] {3, 1, 1, 0, 0}, 1.0, -4.0943445622221);
testDirichletProcess(new double[] {4, 1, 0, 0, 0}, 1.0, -2.995732273553991);
testDirichletProcess(new double[] {5, 0, 0, 0, 0}, 1.0, -1.6094379124341005);
testDirichletProcess(new double[] {1, 1, 1, 1, 1}, 2.0, -3.1135153092103747);
testDirichletProcess(new double[] {2, 1, 1, 1, 0}, 2.0, -3.80666248977032);
testDirichletProcess(new double[] {3, 1, 1, 0, 0}, 2.0, -3.80666248977032);
testDirichletProcess(new double[] {4, 1, 0, 0, 0}, 2.0, -3.401197381662156);
testDirichletProcess(new double[] {5, 0, 0, 0, 0}, 2.0, -2.7080502011022105);
testDirichletProcess(new double[] {1, 1, 1, 1, 1}, 5.0, -1.5765840875630222);
testDirichletProcess(new double[] {2, 1, 1, 1, 0}, 5.0, -3.1860219999971227);
testDirichletProcess(new double[] {3, 1, 1, 0, 0}, 5.0, -4.102312731871278);
testDirichletProcess(new double[] {4, 1, 0, 0, 0}, 5.0, -4.613138355637268);
testDirichletProcess(new double[] {5, 0, 0, 0, 0}, 5.0, -4.836281906951478);
}
private void testDirichletProcess(double[] eta, double chi, double expectedLogL) {
Parameter etaParameter = new Parameter.Default("eta", eta);
Parameter chiParameter = new Parameter.Default("chi", chi, 0.0, Double.MAX_VALUE);
DirichletProcessLikelihood dirichlet = new DirichletProcessLikelihood(etaParameter, chiParameter);
assertEquals(expectedLogL, dirichlet.getLogLikelihood(), 1E-10);
}
public static Test suite() {
return new TestSuite(DirichletProcessTest.class);
}
}
|
package org.craft.atom.nio;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import lombok.ToString;
import org.craft.atom.io.Channel;
import org.craft.atom.io.ChannelEventType;
import org.craft.atom.io.IoHandler;
import org.craft.atom.io.IoProcessor;
import org.craft.atom.io.IoProcessorX;
import org.craft.atom.io.IoProtocol;
import org.craft.atom.nio.spi.NioChannelEventDispatcher;
import org.craft.atom.util.NamedThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Processor process actual I/O operations.
* It abstracts Java NIO to simplify transport implementations.
*
* @author mindwind
* @version 1.0, Feb 22, 2013
*/
@ToString(callSuper = true, of = { "config", "newChannels", "flushingChannels", "closingChannels", "udpChannels" })
public class NioProcessor extends NioReactor implements IoProcessor {
private static final Logger LOG = LoggerFactory.getLogger(NioProcessor.class);
private static final long FLUSH_SPIN_COUNT = 256 ;
private static final long SELECT_TIMEOUT = 1000L ;
private final Queue<NioByteChannel> newChannels = new ConcurrentLinkedQueue<NioByteChannel>() ;
private final Queue<NioByteChannel> flushingChannels = new ConcurrentLinkedQueue<NioByteChannel>() ;
private final Queue<NioByteChannel> closingChannels = new ConcurrentLinkedQueue<NioByteChannel>() ;
private final Map<String, NioByteChannel> udpChannels = new ConcurrentHashMap<String, NioByteChannel>();
private final AtomicReference<ProcessThread> processThreadRef = new AtomicReference<ProcessThread>() ;
private final NioByteBufferAllocator allocator = new NioByteBufferAllocator() ;
private final AtomicBoolean wakeupCalled = new AtomicBoolean(false) ;
private final NioChannelIdleTimer idleTimer ;
private final NioConfig config ;
private final Executor executor ;
private IoProtocol protocol ;
private volatile Selector selector ;
private volatile boolean shutdown = false ;
NioProcessor(NioConfig config, IoHandler handler, NioChannelEventDispatcher dispatcher, NioChannelIdleTimer idleTimer) {
this.config = config;
this.handler = handler;
this.dispatcher = dispatcher;
this.idleTimer = idleTimer;
this.executor = Executors.newCachedThreadPool(new NamedThreadFactory("craft-atom-nio-processor"));
try {
selector = Selector.open();
} catch (IOException e) {
throw new RuntimeException("Fail to startup a processor", e);
}
}
/**
* Adds a nio channel to processor's new channel queue, so that processor can process I/O operations associated this channel.
*
* @param channel
*/
public void add(NioByteChannel channel) {
if (this.shutdown) {
throw new IllegalStateException("The processor already shutdown!");
}
if (channel == null) {
LOG.debug("[CRAFT-ATOM-NIO] Add channel is null, return");
return;
}
newChannels.add(channel);
startup();
wakeup();
}
private void startup() {
ProcessThread pt = processThreadRef.get();
if (pt == null) {
pt = new ProcessThread();
if (processThreadRef.compareAndSet(null, pt)) {
executor.execute(pt);
}
}
}
private void wakeup() {
wakeupCalled.getAndSet(true);
selector.wakeup();
}
/**
* shutdown the processor, stop the process thread and close all the channel within this processor
*/
public void shutdown() {
this.shutdown = true;
wakeup();
}
private void shutdown0() throws IOException {
// close all the channel within this processor
this.closingChannels.addAll(newChannels);
newChannels.clear();
this.closingChannels.addAll(flushingChannels);
flushingChannels.clear();
close();
// close processor selector
this.selector.close();
LOG.debug("[CRAFT-ATOM-NIO] Shutdown processor successful");
}
private void close() throws IOException {
for (NioByteChannel channel = closingChannels.poll(); channel != null; channel = closingChannels.poll()) {
idleTimer.remove(channel);
if (channel.isClosed()) {
LOG.debug("[CRAFT-ATOM-NIO] Skip close because it is already closed, |channel={}|", channel);
continue;
}
channel.setClosing();
LOG.debug("[CRAFT-ATOM-NIO] Closing |channel={}|", channel);
close(channel);
channel.setClosed();
// fire channel closed event
fireChannelClosed(channel);
LOG.debug("[CRAFT-ATOM-NIO] Closed |channel={}|" + channel);
}
}
private void close(NioByteChannel channel) throws IOException {
try {
channel.close0();
if (protocol == IoProtocol.UDP) {
String key = udpChannelKey(channel.getLocalAddress(), channel.getRemoteAddress());
udpChannels.remove(key);
}
} catch (Exception e) {
LOG.warn("[CRAFT-ATOM-NIO] Catch close exception and fire it, |channel={}|", channel, e);
fireChannelThrown(channel, e);
}
}
private int select() throws IOException {
long t0 = System.currentTimeMillis();
int selected = selector.select(SELECT_TIMEOUT);
long t1 = System.currentTimeMillis();
long delta = (t1 - t0);
if ((selected == 0) && !wakeupCalled.get() && (delta < 100)) {
// the select() may have been interrupted because we have had an closed channel.
if (isBrokenConnection()) {
LOG.debug("[CRAFT-ATOM-NIO] Broken connection wakeup");
} else {
LOG.debug("[CRAFT-ATOM-NIO] Create a new selector, |selected={}, delta={}|", selected, delta);
registerNewSelector();
}
// Set back the flag to false and continue the loop
wakeupCalled.getAndSet(false);
}
return selected;
}
private void registerNewSelector() throws IOException {
synchronized (this) {
Set<SelectionKey> keys = selector.keys();
// Open a new selector
Selector newSelector = Selector.open();
// Loop on all the registered keys, and register them on the new selector
for (SelectionKey key : keys) {
SelectableChannel ch = key.channel();
// Don't forget to attache the channel, and back !
NioByteChannel channel = (NioByteChannel) key.attachment();
ch.register(newSelector, key.interestOps(), channel);
}
// Now we can close the old selector and switch it
selector.close();
selector = newSelector;
}
}
private boolean isBrokenConnection() throws IOException {
boolean broken = false;
synchronized (selector) {
Set<SelectionKey> keys = selector.keys();
for (SelectionKey key : keys) {
SelectableChannel channel = key.channel();
if (!((SocketChannel) channel).isConnected()) {
// The channel is not connected anymore. Cancel the associated key.
key.cancel();
broken = true;
}
}
}
return broken;
}
private void register() throws ClosedChannelException {
for (NioByteChannel channel = newChannels.poll(); channel != null; channel = newChannels.poll()) {
SelectableChannel sc = channel.innerChannel();
SelectionKey key = sc.register(selector, SelectionKey.OP_READ, channel);
channel.setSelectionKey(key);
idleTimer.add(channel);
// fire channel opened event
fireChannelOpened(channel);
}
}
private void process() {
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
NioByteChannel channel = (NioByteChannel) it.next().attachment();
if (channel.isValid()) {
process0(channel);
} else {
LOG.debug("[CRAFT-ATOM-NIO] Channel is invalid, |channel={}|", channel);
}
it.remove();
}
}
private void process0(NioByteChannel channel) {
// set last IO time
channel.setLastIoTime(System.currentTimeMillis());
// Process reads
if (channel.isReadable()) {
LOG.debug("[CRAFT-ATOM-NIO] Read event process on |channel={}|", channel);
read(channel);
}
// Process writes
if (channel.isWritable()) {
LOG.debug("[CRAFT-ATOM-NIO] Write event process on |channel={}|", channel);
scheduleFlush(channel);
}
}
private void read(NioByteChannel channel) {
int bufferSize = channel.getPredictor().next();
ByteBuffer buf = allocator.allocate(bufferSize);
LOG.debug("[CRAFT-ATOM-NIO] Predict buffer |size={}, buffer={}|", bufferSize, buf);
int readBytes = 0;
try {
if (protocol.equals(IoProtocol.TCP)) {
readBytes = readTcp(channel, buf);
} else if (protocol.equals(IoProtocol.UDP)) {
readBytes = readUdp(channel, buf);
}
} catch (Exception e) {
LOG.debug("[CRAFT-ATOM-NIO] Catch read exception and fire it, |channel={}|", channel, e);
// fire exception caught event
fireChannelThrown(channel, e);
// if it is IO exception close channel avoid infinite loop.
if (e instanceof IOException) {
scheduleClose(channel);
}
} finally {
if (readBytes > 0) { buf.clear(); }
}
}
private int readTcp(NioByteChannel channel, ByteBuffer buf) throws IOException {
int readBytes = 0;
int ret;
while ((ret = channel.readTcp(buf)) > 0) {
readBytes += ret;
if (!buf.hasRemaining()) {
break;
}
}
if (readBytes > 0) {
channel.getPredictor().previous(readBytes);
fireChannelRead(channel, buf, readBytes);
LOG.debug("[CRAFT-ATOM-NIO] Actual |readBytes={}|", readBytes);
}
// read end-of-stream, remote peer may close channel so close channel.
if (ret < 0) {
scheduleClose(channel);
}
return readBytes;
}
private void scheduleClose(NioByteChannel channel) {
if (channel.isClosing() || channel.isClosed()) {
return;
}
closingChannels.add(channel);
}
private int readUdp(NioByteChannel channel, ByteBuffer buf) throws IOException {
SocketAddress remoteAddress = channel.readUdp(buf);
if (remoteAddress == null) {
// no datagram was immediately available
return 0;
}
int readBytes = buf.position();
String key = udpChannelKey(channel.getLocalAddress(), remoteAddress);
if (!udpChannels.containsKey(key)) {
// handle first datagram with current channel
channel.setRemoteAddress(remoteAddress);
udpChannels.put(key, channel);
}
channel.setLastIoTime(System.currentTimeMillis());
fireChannelRead(channel, buf, buf.position());
return readBytes;
}
private String udpChannelKey(SocketAddress localAddress, SocketAddress remoteAddress) {
return localAddress.toString() + "-" + remoteAddress.toString();
}
/**
* Add the channel to the processor's flushing channel queue, and notify processor flush it immediately.
*
* @param channel
*/
public void flush(NioByteChannel channel) {
if (this.shutdown) {
throw new IllegalStateException("The processor is already shutdown!");
}
if (channel == null) {
return;
}
scheduleFlush(channel);
wakeup();
}
private void scheduleFlush(NioByteChannel channel) {
// Add channel to flushing queue if it's not already in the queue, soon after it will be flushed in the same select loop.
if (channel.setScheduleFlush(true)) {
flushingChannels.add(channel);
}
}
private void flush() {
int c = 0;
while (!flushingChannels.isEmpty() && c < FLUSH_SPIN_COUNT) {
NioByteChannel channel = flushingChannels.poll();
if (channel == null) {
// Just in case ... It should not happen.
break;
}
// Reset the schedule for flush flag to this channel, as we are flushing it now
channel.unsetScheduleFlush();
try {
if (channel.isClosed() || channel.isClosing()) {
LOG.debug("[CRAFT-ATOM-NIO] Channel is closing or closed, |Channel={}, flushing-channel-size={}|", channel, flushingChannels.size());
continue;
} else {
// spin counter avoid infinite loop in this method.
c++;
flush0(channel);
}
} catch (Exception e) {
LOG.debug("[CRAFT-ATOM-NIO] Catch flush exception and fire it", e);
// fire channel thrown event
fireChannelThrown(channel, e);
// if it is IO exception close channel avoid infinite loop.
if (e instanceof IOException) {
scheduleClose(channel);
}
}
}
}
private void flush0(NioByteChannel channel) throws IOException {
LOG.debug("[CRAFT-ATOM-NIO] Flushing |channel={}|", channel);
Queue<ByteBuffer> writeQueue = channel.getWriteBufferQueue();
// First set not be interested to write event
setInterestedInWrite(channel, false);
// flush by mode
if (config.isReadWritefair()) {
fairFlush0(channel, writeQueue);
} else {
oneOffFlush0(channel, writeQueue);
}
// The write buffer queue is not empty, we re-interest in writing and later flush it.
if (!writeQueue.isEmpty()) {
setInterestedInWrite(channel, true);
scheduleFlush(channel);
}
}
private void oneOffFlush0(NioByteChannel channel, Queue<ByteBuffer> writeQueue) throws IOException {
ByteBuffer buf = writeQueue.peek();
if (buf == null) {
return;
}
// fire channel flush event
fireChannelFlush(channel, buf);
write(channel, buf, buf.remaining());
if (buf.hasRemaining()) {
setInterestedInWrite(channel, true);
scheduleFlush(channel);
return;
} else {
writeQueue.remove();
// fire channel written event
fireChannelWritten(channel, buf);
}
}
private void fairFlush0(NioByteChannel channel, Queue<ByteBuffer> writeQueue) throws IOException {
ByteBuffer buf = null;
int writtenBytes = 0;
final int maxWriteBytes = channel.getMaxWriteBufferSize();
LOG.debug("[CRAFT-ATOM-NIO] Max write byte size, |maxWriteBytes={}|", maxWriteBytes);
do {
if (buf == null) {
buf = writeQueue.peek();
if (buf == null) {
return;
} else {
// fire channel flush event
fireChannelFlush(channel, buf);
}
}
int qota = maxWriteBytes - writtenBytes;
int localWrittenBytes = write(channel, buf, qota);
LOG.debug("[CRAFT-ATOM-NIO] Flush |buffer={}, channel={}, bytes={}, size={}, qota={}, remaining={}|", new String(buf.array()), channel, localWrittenBytes, buf.array().length, qota, buf.remaining());
writtenBytes += localWrittenBytes;
// The buffer is all flushed, remove it from write queue
if (!buf.hasRemaining()) {
LOG.debug("[CRAFT-ATOM-NIO] The buffer is all flushed, remove it from write queue");
writeQueue.remove();
// fire channel written event
fireChannelWritten(channel, buf);
// set buf=null and the next loop if no byte buffer to write then break the loop.
buf = null;
continue;
}
// 0 byte be written, maybe kernel buffer is full so we re-interest in writing and later flush it.
if (localWrittenBytes == 0) {
LOG.debug("[CRAFT-ATOM-NIO] Zero byte be written, maybe kernel buffer is full so we re-interest in writing and later flush it, |channel={}|", channel);
setInterestedInWrite(channel, true);
scheduleFlush(channel);
return;
}
// The buffer isn't empty(bytes to flush more than max bytes), we re-interest in writing and later flush it.
if (localWrittenBytes > 0 && buf.hasRemaining()) {
LOG.debug("[CRAFT-ATOM-NIO] The buffer isn't empty, bytes to flush more than max bytes, we re-interest in writing and later flush it, |channel={}|", channel);
setInterestedInWrite(channel, true);
scheduleFlush(channel);
return;
}
// Wrote too much, so we re-interest in writing and later flush other bytes.
if (writtenBytes >= maxWriteBytes && buf.hasRemaining()) {
LOG.debug("[CRAFT-ATOM-NIO] Wrote too much, so we re-interest in writing and later flush other bytes, |channel={}|", channel);
setInterestedInWrite(channel, true);
scheduleFlush(channel);
return;
}
} while (writtenBytes < maxWriteBytes);
}
private void setInterestedInWrite(NioByteChannel channel, boolean isInterested) {
SelectionKey key = channel.getSelectionKey();
if (key == null || !key.isValid()) {
return;
}
int oldInterestOps = key.interestOps();
int newInterestOps = oldInterestOps;
if (isInterested) {
newInterestOps |= SelectionKey.OP_WRITE;
} else {
newInterestOps &= ~SelectionKey.OP_WRITE;
}
if (oldInterestOps != newInterestOps) {
key.interestOps(newInterestOps);
}
}
private int write(NioByteChannel channel, ByteBuffer buf, int maxLength) throws IOException {
int writtenBytes = 0;
LOG.debug("[CRAFT-ATOM-NIO] Allow write max len={}, Waiting write byte buffer={}", maxLength, buf);
if (buf.hasRemaining()) {
int length = Math.min(buf.remaining(), maxLength);
if (protocol.equals(IoProtocol.TCP)) {
writtenBytes = writeTcp(channel, buf, length);
} else if (protocol.equals(IoProtocol.UDP)) {
writtenBytes = writeUdp(channel, buf, length);
}
}
LOG.debug("[CRAFT-ATOM-NIO] Actual written byte size, |writtenBytes={}|", writtenBytes);
return writtenBytes;
}
private int writeTcp(NioByteChannel channel, ByteBuffer buf, int length) throws IOException {
if (buf.remaining() <= length) {
return channel.writeTcp(buf);
}
int oldLimit = buf.limit();
buf.limit(buf.position() + length);
try {
return channel.writeTcp(buf);
} finally {
buf.limit(oldLimit);
}
}
private int writeUdp(NioByteChannel channel, ByteBuffer buf, int length) throws IOException {
if (buf.remaining() <= length) {
return channel.writeUdp(buf, channel.getRemoteAddress());
}
int oldLimit = buf.limit();
buf.limit(buf.position() + length);
try {
return channel.writeUdp(buf, channel.getRemoteAddress());
} finally {
buf.limit(oldLimit);
}
}
/**
* Removes and closes the specified channel from the processor,
* so that processor closes the channel and releases any other related resources.
*
* @param channel
*/
void remove(NioByteChannel channel) {
if (this.shutdown) {
throw new IllegalStateException("The processor is already shutdown!");
}
if (channel == null) {
return;
}
scheduleClose(channel);
wakeup();
}
private void fireChannelOpened(NioByteChannel channel) {
dispatcher.dispatch(new NioByteChannelEvent(ChannelEventType.CHANNEL_OPENED, channel, handler));
}
private void fireChannelRead(NioByteChannel channel, ByteBuffer buf, int length) {
// fire channel received event, here we copy buffer bytes to a new byte array to avoid handler expose <code>ByteBuffer</code> to end user.
byte[] barr = new byte[length];
System.arraycopy(buf.array(), 0, barr, 0, length);
dispatcher.dispatch(new NioByteChannelEvent(ChannelEventType.CHANNEL_READ, channel, handler, barr));
}
private void fireChannelFlush(NioByteChannel channel, ByteBuffer buf) {
dispatcher.dispatch(new NioByteChannelEvent(ChannelEventType.CHANNEL_FLUSH, channel, handler, buf.array()));
}
private void fireChannelWritten(NioByteChannel channel, ByteBuffer buf) {
dispatcher.dispatch(new NioByteChannelEvent(ChannelEventType.CHANNEL_WRITTEN, channel, handler, buf.array()));
}
private void fireChannelThrown(NioByteChannel channel, Exception e) {
dispatcher.dispatch(new NioByteChannelEvent(ChannelEventType.CHANNEL_THROWN, channel, handler, e));
}
private void fireChannelClosed(NioByteChannel channel) {
dispatcher.dispatch(new NioByteChannelEvent(ChannelEventType.CHANNEL_CLOSED, channel, handler));
}
private class ProcessThread implements Runnable {
public void run() {
while (!shutdown) {
try {
int selected = select();
// flush channels
flush();
// register new channels
register();
if (selected > 0) { process(); }
// close channels
close();
} catch (Exception e) {
LOG.error("[CRAFT-ATOM-NIO] Process exception", e);
}
}
// if shutdown == true, we shutdown the processor
if (shutdown) {
try {
shutdown0();
} catch (Exception e) {
LOG.error("[CRAFT-ATOM-NIO] Shutdown exception", e);
}
}
}
}
public void setProtocol(IoProtocol protocol) {
this.protocol = protocol;
}
public IoProcessorX x() {
IoProcessorX ipx = new IoProcessorX();
ipx.setNewChannels(new HashSet<Channel<byte[]>>(newChannels));
ipx.setFlushingChannels(new HashSet<Channel<byte[]>>(flushingChannels));
ipx.setClosingChannels(new HashSet<Channel<byte[]>>(closingChannels));
return ipx;
}
}
|
package com.simplifiedlogic.nitro.jlink.impl;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import java.util.regex.Pattern;
import com.ptc.cipjava.jxthrowable;
import com.ptc.pfc.pfcBase.DatumSide;
import com.ptc.pfc.pfcBase.UnitType;
import com.ptc.pfc.pfcComponentFeat.ComponentConstraintType;
import com.ptc.pfc.pfcExceptions.XToolkitCantOpen;
import com.ptc.pfc.pfcExceptions.XToolkitInUse;
import com.ptc.pfc.pfcExceptions.XToolkitUserAbort;
import com.ptc.pfc.pfcFeature.FeatureStatus;
import com.ptc.pfc.pfcFeature.FeatureType;
import com.ptc.pfc.pfcModel.ModelType;
import com.ptc.pfc.pfcModelItem.ModelItemType;
import com.ptc.pfc.pfcUnits.UnitDimensionConversion;
import com.simplifiedlogic.nitro.jlink.calls.assembly.CallAssembly;
import com.simplifiedlogic.nitro.jlink.calls.assembly.CallComponentPath;
import com.simplifiedlogic.nitro.jlink.calls.base.CallTransform3D;
import com.simplifiedlogic.nitro.jlink.calls.componentfeat.CallComponentConstraint;
import com.simplifiedlogic.nitro.jlink.calls.componentfeat.CallComponentConstraints;
import com.simplifiedlogic.nitro.jlink.calls.componentfeat.CallComponentFeat;
import com.simplifiedlogic.nitro.jlink.calls.family.CallFamilyTableRow;
import com.simplifiedlogic.nitro.jlink.calls.family.CallFamilyTableRows;
import com.simplifiedlogic.nitro.jlink.calls.feature.CallFeature;
import com.simplifiedlogic.nitro.jlink.calls.feature.CallFeatureOperations;
import com.simplifiedlogic.nitro.jlink.calls.feature.CallFeatures;
import com.simplifiedlogic.nitro.jlink.calls.feature.CallSuppressOperation;
import com.simplifiedlogic.nitro.jlink.calls.geometry.CallCoordSystem;
import com.simplifiedlogic.nitro.jlink.calls.mfg.CallMFG;
import com.simplifiedlogic.nitro.jlink.calls.model.CallModel;
import com.simplifiedlogic.nitro.jlink.calls.model.CallModelDescriptor;
import com.simplifiedlogic.nitro.jlink.calls.model2d.CallModel2D;
import com.simplifiedlogic.nitro.jlink.calls.modelitem.CallModelItem;
import com.simplifiedlogic.nitro.jlink.calls.modelitem.CallModelItems;
import com.simplifiedlogic.nitro.jlink.calls.select.CallSelection;
import com.simplifiedlogic.nitro.jlink.calls.seq.CallIntSeq;
import com.simplifiedlogic.nitro.jlink.calls.seq.CallStringSeq;
import com.simplifiedlogic.nitro.jlink.calls.session.CallSession;
import com.simplifiedlogic.nitro.jlink.calls.solid.CallMassProperty;
import com.simplifiedlogic.nitro.jlink.calls.solid.CallRegenInstructions;
import com.simplifiedlogic.nitro.jlink.calls.solid.CallSolid;
import com.simplifiedlogic.nitro.jlink.calls.units.CallUnit;
import com.simplifiedlogic.nitro.jlink.calls.units.CallUnitConversionOptions;
import com.simplifiedlogic.nitro.jlink.calls.units.CallUnitSystem;
import com.simplifiedlogic.nitro.jlink.calls.units.CallUnitSystems;
import com.simplifiedlogic.nitro.jlink.calls.window.CallWindow;
import com.simplifiedlogic.nitro.jlink.data.AbstractJLISession;
import com.simplifiedlogic.nitro.jlink.data.AssembleInstructions;
import com.simplifiedlogic.nitro.jlink.data.FileAssembleResults;
import com.simplifiedlogic.nitro.jlink.data.FileInfoResults;
import com.simplifiedlogic.nitro.jlink.data.FileListInstancesResults;
import com.simplifiedlogic.nitro.jlink.data.FileOpenResults;
import com.simplifiedlogic.nitro.jlink.data.JLConstraint;
import com.simplifiedlogic.nitro.jlink.data.JLConstraintInput;
import com.simplifiedlogic.nitro.jlink.data.JLMatrix;
import com.simplifiedlogic.nitro.jlink.data.JLTransform;
import com.simplifiedlogic.nitro.jlink.data.MasspropsData;
import com.simplifiedlogic.nitro.jlink.intf.DebugLogging;
import com.simplifiedlogic.nitro.jlink.intf.IJLFile;
import com.simplifiedlogic.nitro.rpc.JLIException;
import com.simplifiedlogic.nitro.rpc.JLISession;
import com.simplifiedlogic.nitro.util.FileListFilter;
import com.simplifiedlogic.nitro.util.JLConnectionUtil;
import com.simplifiedlogic.nitro.util.JLMatrixMaker;
import com.simplifiedlogic.nitro.util.ModelItemLooper;
import com.simplifiedlogic.nitro.util.ModelLooper;
/**
* @author Adam Andrews
*
*/
public class JLFile implements IJLFile {
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.impl.IJLFile#open(java.lang.String, java.lang.String, java.util.List, java.lang.String, boolean, boolean, boolean, boolean, java.lang.String)
*/
public FileOpenResults open(
String dirname,
String filename,
List<String> filenames,
String genericname,
boolean display,
boolean activate,
boolean newwin,
boolean forceRegen,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return open(dirname, filename, filenames, genericname, display, activate, newwin, forceRegen, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.impl.IJLFile#open(java.lang.String, java.lang.String, java.util.List, java.lang.String, boolean, boolean, boolean, boolean, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public FileOpenResults open(
String dirname,
String filename,
List<String> filenames,
String genericname,
boolean display,
boolean activate,
boolean newwin,
boolean forceRegen,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.open: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return null;
if ("*.*".equals(filename) || "*".equals(filename))
throw new JLIException("Not allowed to open all files in a directory");
dirname = JlinkUtils.resolveRelativePath(session, dirname);
String savedir = session.getCurrentDirectory();
if (dirname==null)
dirname = savedir;
FileOpenResults out = new FileOpenResults();
int fileRevision=0;
if (filenames!=null ||
NitroUtils.isPattern(filename) ||
(filename!=null && filename.indexOf(' ')!=-1)) {
// special handling for lists
FileOpenResults tmpResults = new FileOpenResults();
String[] found_names = null;
if (dirname != null && !dirname.equals(savedir)) {
JlinkUtils.changeDirectory(session, dirname);
}
try {
Vector<String> out_files = new Vector<String>();
FileListFilter filter = new FileListFilter();
if (filenames!=null)
filter.setNameList(filenames);
else if (filename==null)
filter.setNamePattern(null);
else
filter.setNamePattern(filename);
filter.setListDirs(false);
filter.setListFiles(true);
if (filter.getNameList()!=null && !filter.getIsNamePattern()) {
// get each specific file
String[] namelist = filter.getNameList();
int len = namelist.length;
for (int i=0; i<len; i++) {
tmpResults = new FileOpenResults();
try {
CallModel m = doFileOpen(session, tmpResults, false,
dirname, null, namelist[i], null,
false, false, false, false);
if (m!=null && len==1) {
CallModelDescriptor descr = m.getDescr();
fileRevision = descr.getFileVersion();
}
}
catch (JLIException e) {
//ignore file not found exception
}
found_names = tmpResults.getFilenames();
if (found_names!=null && found_names.length>0)
out_files.add(namelist[i]);
}
}
else {
// normal pattern matching
File dir = new File(dirname);
if (!dir.exists() || !dir.isDirectory())
throw new JLIException("Directory '" + dirname + "' does not exist");
File[] files = dir.listFiles(filter);
int numfiles = files.length;
if (numfiles>0) {
String last_subname = null;
String subname = null;
for (int i=0; i<numfiles; i++) {
subname = NitroUtils.removeNumericExtension(files[i].getName());
if (last_subname==null || !subname.equalsIgnoreCase(last_subname)) {
tmpResults = new FileOpenResults();
try {
CallModel m = doFileOpen(session, tmpResults, false,
dirname, null, subname, null,
false, false, false, false);
if (m!=null && numfiles==1) {
CallModelDescriptor descr = m.getDescr();
fileRevision = descr.getFileVersion();
}
}
catch (JLIException e) {
//ignore file not found exception
}
found_names = tmpResults.getFilenames();
if (found_names!=null && found_names.length>0)
out_files.add(subname);
}
last_subname = subname;
}
}
}
out.setDirname(dirname.replace('\\', '/'));
if (found_names==null)
found_names=new String[0];
out.setFilenames((String[])out_files.toArray(found_names));
if (fileRevision>0)
out.setFileRevision(fileRevision);
}
finally {
if (dirname != null && !dirname.equals(savedir)) {
JlinkUtils.changeDirectory(session, savedir);
}
}
return out;
}
CallModel m = doFileOpen(session, out, true,
dirname, savedir, filename, genericname,
display, newwin, activate, forceRegen);
if (m!=null) {
CallModelDescriptor descr = null;
try {
descr = m.getDescr();
}
catch (XToolkitCantOpen e) {
JlinkUtils.resolveGenerics(session, m);
descr = m.getDescr();
}
if (descr!=null)
fileRevision = descr.getFileVersion();
}
if (fileRevision>0)
out.setFileRevision(fileRevision);
return out;
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.open,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/**
* Perform a file open. Utility method that may be called from multiple places in the code.
* @param session The Creo session
* @param out The results of the file-open, to be returned to the user
* @param change_dir Whether to change Creo's working directory
* @param dirname Directory name for the file
* @param savedir Creo's original working directory before this operation
* @param filename File name
* @param generic The generic instance for the file
* @param display Whether to display the model after opening it
* @param newwin Whether to display the model in a new window (false will open the model in the currently active window)
* @param activate Whether to make the model the active model
* @param regen_force Whether to force regeneration after opening the file
* @return The Model object that was opened
* @throws JLIException
* @throws jxthrowable
*/
private CallModel doFileOpen(CallSession session, FileOpenResults out, boolean change_dir,
String dirname, String savedir, String filename, String generic,
boolean display, boolean newwin, boolean activate, boolean regen_force) throws JLIException,jxthrowable {
CallModel m = JlinkUtils.getFile(session, dirname, filename);
if (m!=null) {
// TODO: check path?
if (display) {
if (newwin) {
CallWindow win = session.createModelWindow(m);
if (win!=null) win.activate();
}
JlinkUtils.displayModel(session, m, activate);
}
if (m instanceof CallSolid && regen_force) {
CallSolid solid = (CallSolid)m;
CallRegenInstructions reginst = CallRegenInstructions.create(Boolean.FALSE, Boolean.TRUE, null);
JlinkUtils.regenerate(session, new RegenerateModel(solid, reginst), true);
CallWindow win = session.getModelWindow(solid);
if (win!=null)
win.refresh();
}
String path = JlinkUtils.getPath(m);
if (path!=null)
out.setDirname(path.replace('\\', '/'));
else
out.setDirname("");
out.setFilenames(new String[] {m.getFullName() + "." + m.getDescr().getExtension()});
}
else {
if (change_dir && dirname != null && !dirname.equals(savedir)) {
JlinkUtils.changeDirectory(session, dirname);
}
try {
CallModelDescriptor descr = CallModelDescriptor.createFromFileName(filename);
// note that SetPath is ignored by RetrieveModel call...
// but it _is_ used by RetrieveModelWithOpts
descr.setPath(session.getCurrentDirectory());
String topGeneric = generic;
if (generic!=null) {
if (topGeneric!=null && topGeneric.indexOf('<')>=0)
topGeneric = JlinkUtils.extractTopGeneric(topGeneric);
descr.setGenericName(topGeneric);
}
try {
m = session.retrieveModel(descr);
}
catch (jxthrowable jxe) {
if (generic!=null && generic.indexOf('<')>=0)
generic = JlinkUtils.extractInstance(generic);
filename = JlinkUtils.instGenericToFilename(filename, generic);
throw new JLIException("Could not open file '" + filename + "' in directory " + session.getCurrentDirectory(), jxe);
}
if (display) {
if (newwin) {
CallWindow win = session.createModelWindow(m);
if (win!=null) win.activate();
}
JlinkUtils.displayModel(session, m, activate);
}
if (m instanceof CallSolid && regen_force) {
CallSolid solid = (CallSolid)m;
CallRegenInstructions reginst = CallRegenInstructions.create(Boolean.FALSE, Boolean.TRUE, null);
JlinkUtils.regenerate(session, new RegenerateModel(solid, reginst), true);
CallWindow win = session.getModelWindow(solid);
if (win!=null)
win.refresh();
}
String path = JlinkUtils.getPath(m);
if (path!=null)
out.setDirname(path.replace('\\', '/'));
else
out.setDirname(dirname.replace('\\', '/'));
out.setFilenames(new String[] {m.getFullName() + "." + m.getDescr().getExtension()});
}
finally {
if (change_dir && dirname != null && !dirname.equals(savedir)) {
JlinkUtils.changeDirectory(session, savedir);
}
}
}
return m;
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#openErrors(java.lang.String, java.lang.String)
*/
public boolean openErrors(
String filename,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return openErrors(filename, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#openErrors(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public boolean openErrors(
String filename,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.open_errors: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
if (NitroUtils.isPattern(filename))
throw new JLIException("Name patterns are not supported for this command");
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return false;
CallSolid solid = JlinkUtils.getModelSolid(session, filename);
return solid.hasRetrievalErrors();
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.open_errors,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#rename(java.lang.String, java.lang.String, boolean, java.lang.String)
*/
public String rename(
String filename,
String newname,
boolean onlyInSession,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return rename(filename, newname, onlyInSession, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#rename(java.lang.String, java.lang.String, boolean, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public String rename(
String filename,
String newname,
boolean onlyInSession,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.rename: " + filename + " to " + newname, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
if (newname==null || newname.trim().length()==0)
throw new JLIException("No new-name parameter given");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
if (NitroUtils.isPattern(filename))
throw new JLIException("Name patterns are not supported for this command");
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return null;
int extpos = NitroUtils.findFileExtension(newname);
String sub_name = (extpos==-1 ? newname : newname.substring(0, extpos));
CallModel m = JlinkUtils.getFile(session, filename, true);
String modelname = m.getFileName();
int extpos2 = NitroUtils.findFileExtension(modelname);
String sub_name2 = (extpos2==-1 ? modelname : modelname.substring(0, extpos2));
if (sub_name.equals(sub_name2)) {
return null;
}
String pathdir = JlinkUtils.getPath(m);
// all this change-directory stuff is to get round the fact that a) the
// RenameFilesToo flag on Rename() isn't implemented, and b) it will
// rename the disk file if and only if the file is in the current directory
boolean changedir=false;
String curdir = session.getCurrentDirectory();
if (onlyInSession) {
JlinkUtils.changeDirectory(session, System.getProperty("java.io.tmpdir"));
changedir=true;
}
else {
if (!NitroUtils.compareDirNames(curdir, pathdir)) {
JlinkUtils.changeDirectory(session, pathdir);
changedir=true;
}
}
try {
m.rename(sub_name, new Boolean(onlyInSession));
return m.getFileName();
}
catch (jxthrowable e) {
throw new JLIException("Error renaming model; check to see there isn't another model in memory with the same name.");
}
finally {
if (changedir)
JlinkUtils.changeDirectory(session, curdir);
}
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.rename,"+filename+","+newname, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#save(java.lang.String, java.util.List, java.lang.String)
*/
public void save(
String filename,
List<String> filenames,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
save(filename, filenames, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#save(java.lang.String, java.util.List, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public void save(
String filename,
List<String> filenames,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.save: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return;
SaveLooper looper = new SaveLooper();
if (filenames!=null)
looper.setNameList(filenames);
else
looper.setNamePattern(filename);
looper.setDefaultToActive(true);
looper.setSession(session);
looper.loop();
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.save,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#backup(java.lang.String, java.lang.String, java.lang.String)
*/
public void backup(
String filename,
String targetdir,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
backup(filename, targetdir, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#backup(java.lang.String, java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public void backup(
String filename,
String targetdir,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.backup: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
if (filename==null || filename.trim().length()==0)
throw new JLIException("No file name parameter given");
if (targetdir==null || targetdir.trim().length()==0)
throw new JLIException("No target directory parameter given");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return;
String savedir = session.getCurrentDirectory();
if (targetdir==null)
targetdir = savedir;
else
targetdir = JlinkUtils.resolveRelativePath(session, targetdir);
NitroUtils.validateDirFile(targetdir, filename, true);
CallModel m = JlinkUtils.getFile(session, targetdir, filename);
if (m!=null) {
CallModelDescriptor descr = m.getDescr();
String savepath = descr.getPath();
descr.setPath(targetdir);
m.backup(descr);
// m.copy(filename, null); // alternate way to do it
descr = m.getDescr();
descr.setPath(savepath); // does not appear to affect the model's actual descr
descr = m.getDescr();
}
else {
throw new JLIException("File '" + filename + "' was not open.");
}
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.backup,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/*
public void copy(
String filename,
String targetdir,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
copy(filename, targetdir, sess);
}
public void copy(
String filename,
String targetdir,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.copy: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
Session session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return;
String olddir = session.GetCurrentDirectory();
if (targetdir==null)
targetdir = olddir;
else
targetdir = JlinkUtils.resolveRelativePath(session, targetdir);
NitroUtils.validateDirFile(targetdir, filename, true);
Model m = JlinkUtils.getFile(session, targetdir, filename);
if (m!=null) {
if (targetdir != null && !targetdir.equals(olddir)) {
JlinkUtils.changeDirectory(session, targetdir);
try {
System.out.println("current dir: " + session.GetCurrentDirectory());
m.Copy(filename, null);
}
finally {
JlinkUtils.changeDirectory(session, olddir);
}
}
else {
m.Copy(filename, null);
}
}
else {
throw new JLIException("File '" + filename + "' was not open.");
}
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.copy,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
*/
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#erase(java.lang.String, java.util.List, boolean, java.lang.String)
*/
public void erase(
String filename,
List<String> filenames,
boolean eraseChildren,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
erase(filename, filenames, eraseChildren, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#erase(java.lang.String, java.util.List, boolean, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public void erase(
String filename,
List<String> filenames,
boolean eraseChildren,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.erase: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return;
// do it this way because after using EraseWithDependencies, some items in the
// list will no longer be valid (and ignoring that exception seems to cause Pro/E to crash)
EraseLooper looper = new EraseLooper();
if (filenames!=null)
looper.setNameList(filenames);
else
looper.setNamePattern(filename);
looper.setDefaultToActive(false);
looper.eraseChildren = eraseChildren;
// loop until the list is empty or we've gone through the list without erasing anything
looper.erasedSomething = true;
while (looper.erasedSomething) {
looper.erasedSomething = false;
looper.setSession(session);
looper.loop();
if (looper.singleOp)
break;
}
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.erase,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#eraseNotDisplayed(java.lang.String)
*/
public void eraseNotDisplayed(
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
eraseNotDisplayed(sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#eraseNotDisplayed(com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public void eraseNotDisplayed(
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.erase_not_displayed", NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return;
session.eraseUndisplayedModels();
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.erase_not_displayed", start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#regenerate(java.lang.String, java.util.List, boolean, java.lang.String)
*/
public void regenerate(
String filename,
List<String> filenames,
boolean display,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
regenerate(filename, filenames, display, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#regenerate(java.lang.String, java.util.List, boolean, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public void regenerate(
String filename,
List<String> filenames,
boolean display,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.regenerate: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return;
// Things that can regenerate:
// Model2D
// SheetOwner
// View2D
// Solid
// XSection
// ComponentFeat
// required for WF5 and higher
boolean resolveMode = JlinkUtils.prefixResolveModeFix(session, NitroConstants.DEBUG_REGEN_KEY);
try {
RegenerateLooper looper = new RegenerateLooper();
if (filenames!=null)
looper.setNameList(filenames);
else
looper.setNamePattern(filename);
looper.display = display;
looper.session = session;
looper.setDefaultToActive(true);
looper.setSession(session);
looper.setDebugKey(NitroConstants.DEBUG_REGEN_KEY);
looper.loop();
}
finally {
JlinkUtils.postfixResolveModeFix(session, resolveMode, NitroConstants.DEBUG_REGEN_KEY);
}
}
catch (jxthrowable e) {
System.err.println("Error regenerating: " + e.getMessage());
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.regenerate,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.impl.IJLFile#getActive(java.lang.String)
*/
public FileOpenResults getActive(
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return getActive(sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.impl.IJLFile#getActive(com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public FileOpenResults getActive(
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.get_active", NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return null;
FileOpenResults out = new FileOpenResults();
CallModel m;
m = session.getCurrentModel();
String dirname = "";
String filename = "";
String mfgName=null;
if (m==null) {
//throw new JLIException("No current model");
dirname = session.getCurrentDirectory();
}
else {
filename = m.getFileName();
int mtype = m.getType();
if (mtype==ModelType._MDL_MFG) {
CallModel m2 = JlinkUtils.getMfgModel(session, (CallMFG)m);
mfgName = m2.getFileName();
// filename = m2.getFileName();
}
dirname = JlinkUtils.getPath(m);
}
out.setDirname(dirname.replace('\\', '/'));
if (mfgName==null)
out.setFilenames(new String[] {filename});
else
out.setFilenames(new String[] {filename, mfgName});
return out;
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.get_active", start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#list(java.lang.String, java.util.List, java.lang.String)
*/
public List<String> list(
String filename,
List<String> filenames,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return list(filename, filenames, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#list(java.lang.String, java.util.List, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public List<String> list(
String filename,
List<String> filenames,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.list: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return null;
ListLooper looper = new ListLooper();
if (filenames!=null)
looper.setNameList(filenames);
else
looper.setNamePattern(filename);
looper.setDefaultToActive(false);
looper.setSession(session);
looper.loop();
if (looper.output==null)
return new Vector<String>();
else
return looper.output;
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.list,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#exists(java.lang.String, java.lang.String)
*/
public boolean exists(
String filename,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return exists(filename, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#exists(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public boolean exists(
String filename,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.exists: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
if (filename==null || filename.trim().length()==0)
throw new JLIException("No file name parameter given");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
if (NitroUtils.isPattern(filename))
throw new JLIException("Name patterns are not supported for this command");
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return false;
CallModel m = JlinkUtils.getFile(session, filename, false);
if (m!=null) {
return true;
}
else {
return false;
}
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.exists,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#getFileinfo(java.lang.String, java.lang.String)
*/
public FileInfoResults getFileinfo(
String filename,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return getFileinfo(filename, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#getFileinfo(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public FileInfoResults getFileinfo(
String filename,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.get_fileinfo: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
if (NitroUtils.isPattern(filename))
throw new JLIException("Name patterns are not supported for this command");
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return null;
CallModel m = JlinkUtils.getFile(session, filename, false);
if (m!=null) {
FileInfoResults result = new FileInfoResults();
CallModelDescriptor descr = m.getDescr();
result.setFilename(m.getFileName());
result.setFileRevision(descr.getFileVersion());
result.setDirname(JlinkUtils.getPath(m));
return result;
}
else {
return null;
}
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.get_fileinfo,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#hasInstances(java.lang.String, java.lang.String)
*/
public boolean hasInstances(
String filename,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return hasInstances(filename, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#hasInstances(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public boolean hasInstances(
String filename,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.has_instances: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
if (NitroUtils.isPattern(filename))
throw new JLIException("Name patterns are not supported for this command");
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return false;
CallModel m = JlinkUtils.getFile(session, filename, true);
if (!(m instanceof CallSolid)) {
return false;
}
CallSolid solid = (CallSolid)m;
CallFamilyTableRows rows = null;
try {
rows = solid.listRows();
}
catch (Exception e) {
// fall through
}
if (rows!=null && rows.getarraysize()>0) {
return true;
}
return false;
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.has_instances,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#listInstances(java.lang.String, java.lang.String)
*/
@Override
public FileListInstancesResults listInstances(String filename, String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return listInstances(filename, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#listInstances(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
@Override
public FileListInstancesResults listInstances(String filename, AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.list_instances: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
if (NitroUtils.isPattern(filename))
throw new JLIException("Name patterns are not supported for this command");
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return null;
CallModel m = JlinkUtils.getFile(session, filename, true);
if (!(m instanceof CallSolid))
throw new JLIException("File '" + m.getFileName() + "' must be a solid");
CallSolid solid = (CallSolid)m;
if (filename==null)
filename = solid.getFileName();
int extpos = NitroUtils.findFileExtension(filename);
String generic = (extpos==-1 ? filename : filename.substring(0, extpos));
String ext = (extpos==-1 ? "" : filename.substring(extpos));
CallFamilyTableRows rows = solid.listRows();
FileListInstancesResults results = new FileListInstancesResults();
results.setDirname(JlinkUtils.getPath(solid).replace('\\', '/'));
results.setGeneric(generic);
CallFamilyTableRow onerow;
int len = rows.getarraysize();
for (int i=0; i<len; i++) {
try {
onerow = rows.get(i);
results.addInstance(onerow.getInstanceName() + ext);
}
catch (jxthrowable jxe) {
throw new JLIException(JlinkUtils.ptcError(jxe, "A PTC error has occurred when retrieving instance " + i));
}
}
return results;
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.list_instances,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#massprops(java.lang.String, java.lang.String)
*/
@Override
public MasspropsData massprops(String filename, String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return massprops(filename, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#massprops(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
@Override
public MasspropsData massprops(String filename, AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.massprops: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return null;
CallModel m = JlinkUtils.getFile(session, filename, true);
if (!(m instanceof CallSolid))
throw new JLIException("File '" + m.getFileName() + "' must be a solid");
CallSolid solid = (CallSolid)m;
CallMassProperty prop = solid.getMassProperty(null);
if (prop==null)
throw new JLIException("No mass properties found for part");
MasspropsData ret = new MasspropsData();
ret.setVolume(prop.getVolume());
ret.setMass(prop.getMass());
ret.setDensity(prop.getDensity());
ret.setSurfaceArea(prop.getSurfaceArea());
return ret;
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.massprops,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#getMassUnits(java.lang.String, java.lang.String)
*/
@Override
public String getMassUnits(String filename, String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return getMassUnits(filename, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#getMassUnits(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
@Override
public String getMassUnits(String filename, AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.get_mass_units: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return null;
CallModel m = JlinkUtils.getFile(session, filename, true);
if (!(m instanceof CallSolid))
throw new JLIException("File '" + m.getFileName() + "' must be a solid");
CallSolid solid = (CallSolid)m;
CallUnitSystem system = solid.getPrincipalUnits();
if (system==null)
throw new JLIException("No Unit System found for part");
CallUnit unit = system.getUnit(UnitType.UNIT_MASS);
if (unit==null)
throw new JLIException("No Mass Unit found for part");
String ret = unit.getName();
return ret;
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.get_mass_units,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#setMassUnits(java.lang.String, java.lang.String, boolean, java.lang.String)
*/
@Override
public void setMassUnits(String filename, String units, boolean convert, String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
setMassUnits(filename, units, convert, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#setMassUnits(java.lang.String, java.lang.String, boolean, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
@Override
public void setMassUnits(String filename, String units, boolean convert, AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.set_mass_units: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
if (units==null || units.trim().length()==0)
throw new JLIException("No units parameter given");
units = units.toLowerCase();
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return;
CallModel m = JlinkUtils.getFile(session, filename, true);
if (!(m instanceof CallSolid))
throw new JLIException("File '" + m.getFileName() + "' must be a solid");
CallSolid solid = (CallSolid)m;
CallUnitSystem system = solid.getPrincipalUnits();
if (system!=null) {
CallUnit unit = system.getUnit(UnitType.UNIT_MASS);
if (unit!=null && unit.getName().equals(units))
return;
}
CallUnitSystems systems = solid.listUnitSystems();
boolean found=false;
if (systems!=null) {
int len = systems.getarraysize();
for (int i=0; i<len; i++) {
system = systems.get(i);
CallUnit unit = system.getUnit(UnitType.UNIT_MASS);
if (unit==null)
continue;
if (unit.getName().equals(units)) {
UnitDimensionConversion convertOpt;
if (convert)
convertOpt = UnitDimensionConversion.UNITCONVERT_SAME_SIZE;
else
convertOpt = UnitDimensionConversion.UNITCONVERT_SAME_DIMS;
CallUnitConversionOptions opts = CallUnitConversionOptions.create(convertOpt);
opts.setDimensionOption(convertOpt);
solid.setPrincipalUnits(system, opts);
found=true;
break;
}
}
}
if (!found)
throw new JLIException("No mass unit '" + units + "' was found.");
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.set_mass_units,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#getLengthUnits(java.lang.String, java.lang.String)
*/
@Override
public String getLengthUnits(String filename, String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return getLengthUnits(filename, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#getLengthUnits(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
@Override
public String getLengthUnits(String filename, AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.get_length_units: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return null;
CallModel m = JlinkUtils.getFile(session, filename, true);
if (!(m instanceof CallSolid))
throw new JLIException("File '" + m.getFileName() + "' must be a solid");
CallSolid solid = (CallSolid)m;
CallUnitSystem system = solid.getPrincipalUnits();
if (system==null)
throw new JLIException("No Unit System found for part");
CallUnit unit = system.getUnit(UnitType.UNIT_LENGTH);
if (unit==null)
throw new JLIException("No Length Unit found for part");
String ret = unit.getName();
return ret;
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.get_length_units,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#setLengthUnits(java.lang.String, java.lang.String, boolean, java.lang.String)
*/
@Override
public void setLengthUnits(String filename, String units, boolean convert, String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
setLengthUnits(filename, units, convert, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#setLengthUnits(java.lang.String, java.lang.String, boolean, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
@Override
public void setLengthUnits(String filename, String units, boolean convert, AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.set_length_units: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
if (units==null || units.trim().length()==0)
throw new JLIException("No units parameter given");
units = units.toLowerCase();
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return;
CallModel m = JlinkUtils.getFile(session, filename, true);
if (!(m instanceof CallSolid))
throw new JLIException("File '" + m.getFileName() + "' must be a solid");
CallSolid solid = (CallSolid)m;
CallUnitSystem system = solid.getPrincipalUnits();
if (system!=null) {
CallUnit unit = system.getUnit(UnitType.UNIT_LENGTH);
if (unit!=null && unit.getName().equals(units))
return;
}
CallUnitSystems systems = solid.listUnitSystems();
boolean found=false;
if (systems!=null) {
int len = systems.getarraysize();
for (int i=0; i<len; i++) {
system = systems.get(i);
CallUnit unit = system.getUnit(UnitType.UNIT_LENGTH);
if (unit==null)
continue;
if (unit.getName().equals(units)) {
UnitDimensionConversion convertOpt;
if (convert)
convertOpt = UnitDimensionConversion.UNITCONVERT_SAME_SIZE;
else
convertOpt = UnitDimensionConversion.UNITCONVERT_SAME_DIMS;
CallUnitConversionOptions opts = CallUnitConversionOptions.create(convertOpt);
opts.setDimensionOption(convertOpt);
solid.setPrincipalUnits(system, opts);
found=true;
break;
}
}
}
if (!found)
throw new JLIException("No length unit '" + units + "' was found.");
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.set_length_units,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#getRelations(java.lang.String, java.lang.String)
*/
public List<String> getRelations(
String filename,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return getRelations(filename, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#getRelations(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public List<String> getRelations(
String filename,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.relations_get: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return null;
CallModel m;
m = JlinkUtils.getFile(session, filename, true);
CallStringSeq lines = m.getRelations();
if (lines==null)
return null;
int sz = lines.getarraysize();
if (sz==0)
return null;
List<String> result = new ArrayList<String>();
for (int i=0; i<sz; i++) {
result.add(lines.get(i));
}
return result;
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.relations_get,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#setRelations(java.lang.String, java.util.List, java.lang.String)
*/
public void setRelations(
String filename,
List<String> relations,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
setRelations(filename, relations, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#setRelations(java.lang.String, java.util.List, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public void setRelations(
String filename,
List<String> relations,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.relations_set: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return;
CallModel m;
m = JlinkUtils.getFile(session, filename, true);
if (relations==null || relations.size()==0)
m.deleteRelations();
else {
CallStringSeq lines = CallStringSeq.create();
int len = relations.size();
for (int i=0; i<len; i++)
lines.append(relations.get(i));
m.setRelations(lines);
}
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.relations_set,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#getPostRegenRelations(java.lang.String, java.lang.String)
*/
public List<String> getPostRegenRelations(
String filename,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return getPostRegenRelations(filename, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#getPostRegenRelations(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public List<String> getPostRegenRelations(
String filename,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.postregen_relations_get: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return null;
CallModel m;
m = JlinkUtils.getFile(session, filename, true);
CallStringSeq lines = m.getPostRegenerationRelations();
if (lines==null)
return null;
int sz = lines.getarraysize();
if (sz==0)
return null;
List<String> result = new ArrayList<String>();
for (int i=0; i<sz; i++) {
result.add(lines.get(i));
}
return result;
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.postregen_relations_get,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#setPostRegenRelations(java.lang.String, java.util.List, java.lang.String)
*/
public void setPostRegenRelations(
String filename,
List<String> relations,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
setPostRegenRelations(filename, relations, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#setPostRegenRelations(java.lang.String, java.util.List, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public void setPostRegenRelations(
String filename,
List<String> relations,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.postregen_relations_set: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return;
CallModel m;
m = JlinkUtils.getFile(session, filename, true);
Object[] inputs = new Object[] {
m,
relations
};
JlinkUtils.callCreoFunction("com.simplifiedlogic.nitro.jshell.creo.SetPostRegenRelations", inputs);
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.postregen_relations_set,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#assemble(com.simplifiedlogic.nitro.jlink.data.AssembleInstructions, java.lang.String)
*/
public FileAssembleResults assemble(AssembleInstructions instro, String sessionId) throws JLIException {
return assemble(
instro.getDirname(),
instro.getFilename(),
instro.getGenericName(),
instro.getIntoAsm(),
instro.getComponentPath(),
instro.getTransData(),
instro.getConstraints(),
instro.isPackageAssembly(),
instro.getRefModel(),
instro.isWalkChildren(),
instro.isAssembleToRoot(),
instro.isSuppress(),
sessionId);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#assemble(com.simplifiedlogic.nitro.jlink.data.AssembleInstructions, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public FileAssembleResults assemble(AssembleInstructions instro, AbstractJLISession sess) throws JLIException {
return assemble(
instro.getDirname(),
instro.getFilename(),
instro.getGenericName(),
instro.getIntoAsm(),
instro.getComponentPath(),
instro.getTransData(),
instro.getConstraints(),
instro.isPackageAssembly(),
instro.getRefModel(),
instro.isWalkChildren(),
instro.isAssembleToRoot(),
instro.isSuppress(),
sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#assemble(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.List, com.simplifiedlogic.nitro.jlink.data.JLTransform, java.util.List, boolean, java.lang.String, boolean, boolean, java.lang.String)
*/
public FileAssembleResults assemble(
String dirname,
String filename,
String genericName,
String intoAsm,
List<Integer> componentPath,
JLTransform transData,
List<JLConstraintInput> constraints,
boolean packageAssembly,
String refModel,
boolean walkChildren,
boolean assembleToRoot,
boolean suppress,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return assemble(dirname, filename, genericName, intoAsm, componentPath, transData, constraints, packageAssembly, refModel, walkChildren, assembleToRoot, suppress, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#assemble(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.List, com.simplifiedlogic.nitro.jlink.data.JLTransform, java.util.List, boolean, java.lang.String, boolean, boolean, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public FileAssembleResults assemble(
String dirname,
String filename,
String genericName,
String intoAsm,
List<Integer> componentPath,
JLTransform transData,
List<JLConstraintInput> constraintsInput,
boolean packageAssembly,
String refModel,
boolean walkChildren,
boolean assembleToRoot,
boolean suppress,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.assemble: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
if (filename==null || filename.trim().length()==0)
throw new JLIException("No file name parameter given");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return null;
JLMatrix initMatrix = JLMatrixMaker.create(transData);
// translate constraints
List<JLConstraint> constraints = null;
if (constraintsInput!=null) {
constraints = new ArrayList<JLConstraint>();
for (JLConstraintInput in : constraintsInput)
constraints.add(new JLConstraint(in));
}
// resolve directory
dirname = JlinkUtils.resolveRelativePath(session, dirname);
FileAssembleResults out = new FileAssembleResults();
// get component
String savedir = session.getCurrentDirectory();
if (dirname==null)
dirname = savedir;
CallModel m = doFileOpen(session, out, true,
dirname, savedir, filename, genericName,
false, false, false, false);
// validate assembly
CallModel assemblyModel = JlinkUtils.getFile(session, intoAsm, false);
if (assemblyModel==null) {
if (intoAsm==null)
throw new JLIException("No active assembly to assemble into");
else
throw new JLIException("Assembly " + intoAsm + " was not open");
}
if (!(assemblyModel instanceof CallAssembly))
throw new JLIException("The model " + (intoAsm==null?assemblyModel.getFileName():intoAsm) + " is not an assembly");
CallAssembly assembly = (CallAssembly)assemblyModel;
String assemblyName = assembly.getFileName();
// if path given, get sub-component of assembly
CallModel subComponent = null;
Pattern subComponentPattern = null;
CallComponentPath compPath = null;
CallIntSeq ids = CallIntSeq.create();
if (componentPath!=null) {
CallFeature f = JlinkUtils.getFeatureForPath(session, assembly, componentPath);
if (!(f instanceof CallComponentFeat))
throw new JLIException("Component path does not point to a component feature");
subComponent = session.getModelFromDescr(((CallComponentFeat)f).getModelDescr());
// create pro/e component path
int len = componentPath.size();
for (int i=0; i<len; i++) {
ids.append(((Integer)componentPath.get(i)).intValue());
}
}
else if (refModel!=null) {
if (NitroUtils.isPattern(refModel))
subComponentPattern = Pattern.compile(NitroUtils.transformPattern(refModel.toUpperCase()));
else
subComponent = JlinkUtils.getFile(session, refModel, true);
}
else
subComponent = assembly;
compPath = CallComponentPath.create(assembly, ids);
CallModelDescriptor descr = m.getDescr();
out.setFileRevision(descr.getFileVersion());
// this is really only needed when suppress=true
// required for WF5 and higher
boolean resolveMode = JlinkUtils.prefixResolveModeFix(session);
try {
if (((CallSolid)m).getIsSkeleton()) {
try {
assembly.assembleSkeleton((CallSolid)m);
}
catch (jxthrowable e) {
throw new JLIException("Creo does not allow you to assemble more than one skeleton into an assembly");
}
CallSolid skel = assembly.getSkeleton();
if (skel!=null) {
CallFeatures featList = assembly.listFeaturesByType(true, FeatureType.FEATTYPE_COMPONENT);
if (featList!=null) {
int len = featList.getarraysize();
CallComponentFeat compFeat;
for (int i=0; i<len; i++) {
compFeat = (CallComponentFeat)featList.get(i);
String fname = compFeat.getModelDescr().getFileName();
if (fname.equalsIgnoreCase(filename)) {
out.setFeatureId(compFeat.getId());
if (suppress) {
suppressNewFeature(session, assembly, compFeat);
}
break;
}
}
}
}
}
else {
List<WalkResult> subpaths = new Vector<WalkResult>();
if (walkChildren || (componentPath==null && refModel!=null)) {
if (subComponent==assembly)
subpaths.add(new WalkResult(compPath, assembly, assembly));
else if (subComponentPattern!=null && subComponentPattern.matcher(assemblyName.toUpperCase()).matches()) //assemblyName.matches(subComponentPattern))
subpaths.add(new WalkResult(compPath, assembly, assembly));
ArrayList<Integer> curPath = new ArrayList<Integer>();
ArrayList<String> assembliesProcessed = new ArrayList<String>();
walkAssemble(session, assembly, assembly, "root", curPath, 0, (subComponent!=null ? subComponent.getFileName() : null), subComponentPattern, subpaths,
assembliesProcessed, !walkChildren, assembleToRoot);
if (subpaths.size()==0) {
throw new JLIException("File '" + subComponent.getFileName() + "' does not exist in assembly");
}
}
else {
if (subComponent!=null)
subpaths.add(new WalkResult(compPath, assembly, subComponent));
}
// assemble component
CallTransform3D transform = CallTransform3D.create(JLMatrixMaker.export(initMatrix));
// add constraints
int len = 0;
if (constraints!=null)
len = constraints.size();
WalkResult res;
if (len>0) {
int cntAssembled = 0;
JLConstraint csys_con = getCsysConstraint(constraints);
String asmrefCsys=null;
if (csys_con!=null && csys_con.asmref!=null)
asmrefCsys = csys_con.asmref;
int num_comps = subpaths.size();
for (int i=0; i<num_comps; i++) {
res = (WalkResult)subpaths.get(i);
compPath = res.compPath;
assembly = assembleToRoot ? (CallAssembly)assemblyModel : res.parent;
subComponent = res.item;
if (asmrefCsys!=null && asmrefCsys.indexOf('*')>=0) {
List<JLConstraint> other_con = getNonCsysConstraint(constraints);
//AssembleLooper looper = new AssembleLooper(assembly, subComponent, m, compPath, transform, csys_con, other_con);
AssembleLooper2 looper = new AssembleLooper2();
looper.setNamePattern(asmrefCsys);
looper.loop(subComponent);
if (looper.items!=null && looper.items.size()>0) {
Collections.sort(looper.items);
int num_items = looper.items.size();
ModelItemEntry entry;
for (int k=0; k<num_items; k++) {
entry = (ModelItemEntry)looper.items.get(k);
assembleItem(session, assembly, subComponent, m, compPath, transform, csys_con, other_con, entry.item, suppress);
}
looper.items.clear();
cntAssembled += num_items;
}
}
else {
CallComponentConstraints constrs = null;
try {
constrs = makeConstraints(subComponent, m, compPath, constraints);
}
catch (JLIException e) {
// constraints are ANDed together, so if one of them fails then the whole set of constraints does
// if this fails, then fall through and let the check at the end throw an error
continue;
}
CallComponentFeat newfeat = (CallComponentFeat)assembly.assembleComponent((CallSolid)m, transform);
if (constrs!=null)
newfeat.setConstraints(constrs, null);
if (suppress) {
suppressNewFeature(session, assembly, newfeat);
}
cntAssembled++;
}
}
if (asmrefCsys!=null && cntAssembled==0)
throw new JLIException("No Coord Systems matching '" + asmrefCsys + "' were found in the assembly component");
}
else if (!packageAssembly) {
try {
CallComponentFeat newfeat = (CallComponentFeat)assembly.assembleComponent((CallSolid)m, transform);
int cid = newfeat.getId();
out.setFeatureId(cid);
newfeat.redefineThroughUI();
if (suppress) {
suppressNewFeature(session, assembly, newfeat);
}
}
catch (XToolkitUserAbort e) {
// ignore user aborts
}
}
}
}
finally {
// this is really only needed when suppress=true
JlinkUtils.postfixResolveModeFix(session, resolveMode);
}
return out;
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.assemble,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/**
* Get the CSYS constraint (if any) from a list of input constraints
* @param constraints A list of input constraints
* @return The CSYS constraint from the list
* @throws JLIException
* @throws jxthrowable
*/
private JLConstraint getCsysConstraint(List<JLConstraint> constraints) throws JLIException, jxthrowable {
int len = constraints.size();
JLConstraint con;
JLConstraint ccon=null;
for (int i=0; i<len; i++) {
con = (JLConstraint)constraints.get(i);
if (con.type!=ComponentConstraintType._ASM_CONSTRAINT_CSYS)
continue;
if (ccon!=null)
throw new JLIException("Not allowed to have more than one CSYS constraint");
ccon = con;
}
return ccon;
}
/**
* Get the non-CSYS constraints (if any) from a list of input constraints
* @param constraints A list of input constraints
* @return The non-CSYS constraint from the list
* @throws jxthrowable
*/
private List<JLConstraint> getNonCsysConstraint(List<JLConstraint> constraints) throws jxthrowable {
int len = constraints.size();
JLConstraint con;
List<JLConstraint> newcons = new Vector<JLConstraint>();
for (int i=0; i<len; i++) {
con = (JLConstraint)constraints.get(i);
if (con.type==ComponentConstraintType._ASM_CONSTRAINT_CSYS)
continue;
newcons.add(con);
}
if (newcons.size()==0)
return null;
return newcons;
}
/**
* Make a set of Creo constraints from inputs. Calls makeConstraint() to make each individual constraint.
* @param subComponent The assembly the component will be assembled to
* @param m The component being assembled
* @param compPath The component path of the component that the new item will be constrained to
* @param constraints The list of input constraint data
* @return A set of Creo constraints
* @throws JLIException
* @throws jxthrowable
*/
public CallComponentConstraints makeConstraints(CallModel subComponent, CallModel m, CallComponentPath compPath, List<JLConstraint> constraints) throws JLIException, jxthrowable {
if (constraints==null)
return null;
int len = constraints.size();
JLConstraint con;
CallComponentConstraints constrs = CallComponentConstraints.create();
for (int i=0; i<len; i++) {
con = (JLConstraint)constraints.get(i);
CallComponentConstraint ctrt = makeConstraint(subComponent, m, compPath, con);
constrs.append(ctrt);
}
return constrs;
}
/**
* Create a Creo constraint from input constraint data
* @param subComponent The assembly the component will be assembled to
* @param m The component being assembled
* @param compPath The component path of the component that the new item will be constrained to
* @param con Input constraint data
* @return The new Creo constraint
* @throws JLIException
* @throws jxthrowable
*/
protected CallComponentConstraint makeConstraint(CallModel subComponent, CallModel m, CallComponentPath compPath, JLConstraint con) throws JLIException, jxthrowable {
CallModelItem asmItem, compItem;
asmItem = null;
compItem = null;
if (con.type==ComponentConstraintType._ASM_CONSTRAINT_CSYS) {
if (con.asmref!=null) {
// set the assembly reference
asmItem = subComponent.getItemByName(ModelItemType.ITEM_COORD_SYS, con.asmref);
if (asmItem==null)
throw new JLIException("Coord System '" + con.asmref + "' was not found in the assembly component");
}
if (con.compref!=null) {
// set the component reference
compItem = m.getItemByName(ModelItemType.ITEM_COORD_SYS, con.compref);
if (compItem==null)
throw new JLIException("Coord System '" + con.compref + "' was not found in the new component");
}
}
CallComponentConstraint ctrt = CallComponentConstraint.create(ComponentConstraintType.FromInt(con.type));
if (asmItem!=null) {
CallSelection compConstrain = CallSelection.createModelItemSelection(asmItem, compPath);
ctrt.setAssemblyReference(compConstrain);
}
if (compItem!=null) {
CallSelection compSel = CallSelection.createModelItemSelection(compItem, null);
ctrt.setComponentReference(compSel);
}
if (con.offset!=null) {
ctrt.setOffset(con.offset);
}
if (con.asmDatum!=DatumSide._DATUM_SIDE_NONE) {
ctrt.setAssemblyDatumSide(DatumSide.FromInt(con.asmDatum));
}
if (con.compDatum!=DatumSide._DATUM_SIDE_NONE) {
ctrt.setComponentDatumSide(DatumSide.FromInt(con.asmDatum));
}
return ctrt;
}
/**
* Assemble a component into an assembly
* @param assembly The assembly to receive the component
* @param subComponent
* @param part
* @param compPath
* @param transform The 3D transform to apply to the component
* @param csys_con A CSYS-type constraint
* @param other_con Other constraints
* @param item
* @throws JLIException
* @throws jxthrowable
*/
private void assembleItem(
CallSession session,
CallAssembly assembly,
CallModel subComponent,
CallModel part,
CallComponentPath compPath,
CallTransform3D transform,
JLConstraint csys_con,
List<JLConstraint> other_con,
CallModelItem item,
boolean suppress
) throws JLIException, jxthrowable {
CallComponentConstraints constrs = makeConstraints(subComponent, part, compPath, other_con);
if (csys_con!=null) {
JLConstraint clone = csys_con.copy();
clone.asmref = item.getName();
CallComponentConstraint ctrt = makeConstraint(subComponent, part, compPath, clone);
if (ctrt!=null) {
if (constrs==null)
constrs = CallComponentConstraints.create();
constrs.append(ctrt);
}
}
CallComponentFeat newfeat = (CallComponentFeat)assembly.assembleComponent((CallSolid)part, transform);
if (constrs!=null)
newfeat.setConstraints(constrs, null);
if (suppress) {
suppressNewFeature(session, assembly, newfeat);
}
}
private void suppressNewFeature(CallSession session, CallAssembly assembly, CallFeature newfeat) throws jxthrowable {
//System.out.println("Suppressing new feature: "+newfeat.getId());
CallFeatureOperations featOps = CallFeatureOperations.create();
CallSuppressOperation supop = newfeat.createSuppressOp();
supop.setClip(true);
featOps.append(supop);
assembly.executeFeatureOps(featOps, null);
// JlinkUtils.regenerate(session, new RegenerateFeatureOps(assembly, featOps), true);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#refresh(java.lang.String, java.lang.String)
*/
public void refresh(
String filename,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
refresh(filename, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#refresh(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public void refresh(
String filename,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.refresh: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return;
CallModel m = JlinkUtils.getFile(session, filename, true);
CallWindow win = null;
if (m!=null && m instanceof CallSolid) {
// get window for part
win = session.getModelWindow((CallSolid)m);
}
if (win==null) {
// get default window
win = session.getCurrentWindow();
}
if (win!=null)
win.refresh();
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.refresh,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#repaint(java.lang.String, java.lang.String)
*/
public void repaint(
String filename,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
repaint(filename, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#repaint(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public void repaint(
String filename,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.repaint: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return;
CallModel m = JlinkUtils.getFile(session, filename, true);
CallWindow win = null;
if (m!=null && m instanceof CallSolid) {
// get window for part
win = session.getModelWindow((CallSolid)m);
}
if (win==null) {
// get default window
win = session.getCurrentWindow();
}
if (win!=null)
win.repaint();
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.repaint,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#getTransform(java.lang.String, java.util.List, java.lang.String, java.lang.String)
*/
public JLTransform getTransform(
String asm,
List<Integer> path,
String csys,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return getTransform(asm, path, csys, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#getTransform(java.lang.String, java.util.List, java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public JLTransform getTransform(
String asm,
List<Integer> path,
String csys,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.get_transform", NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return null;
CallModel assemblyModel = JlinkUtils.getFile(session, asm, false);
if (!(assemblyModel instanceof CallAssembly))
throw new JLIException("The model " + (asm==null?assemblyModel.getFileName():asm) + " is not an assembly");
CallAssembly assembly = (CallAssembly)assemblyModel;
// if path given, get sub-component of assembly
CallModel subComponent;
CallComponentPath compPath = null;
CallIntSeq ids = CallIntSeq.create ();
if (path!=null) {
CallFeature f = JlinkUtils.getFeatureForPath(session, assembly, path);
if (!(f instanceof CallComponentFeat))
throw new JLIException("Component path does not point to a component feature");
subComponent = session.getModelFromDescr(((CallComponentFeat)f).getModelDescr());
// create pro/e component path
int len = path.size();
for (int i=0; i<len; i++) {
ids.append(((Integer)path.get(i)).intValue());
}
}
else
subComponent = assemblyModel;
CallCoordSystem partSys = null;
if (csys!=null) {
partSys = (CallCoordSystem)subComponent.getItemByName(ModelItemType.ITEM_COORD_SYS, csys);
if (partSys==null)
throw new JLIException("Coord System '" + csys + "' was not found.");
}
else {
CallModelItems itemList = subComponent.listItems(ModelItemType.ITEM_COORD_SYS);
if (itemList!=null && itemList.getarraysize()>0) {
partSys = (CallCoordSystem)itemList.get(0);
}
}
if (partSys==null) {
throw new JLIException("No Coord System found.");
}
compPath = CallComponentPath.create(assembly, ids);
CallTransform3D featTrans = compPath.getTransform(true);
JLMatrix mat1 = JLMatrixMaker.create(featTrans.getMatrix());
CallTransform3D partTransform = partSys.getCoordSys();
JLMatrix mat2 = JLMatrixMaker.create(partTransform.getMatrix());
JLMatrixMaker.dot(mat1, mat2);
JLTransform out = JLMatrixMaker.writeTransformTable(mat1);
return out;
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.get_transform", start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#isActive(java.lang.String, java.lang.String)
*/
public boolean isActive(
String filename,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return isActive(filename, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#isActive(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public boolean isActive(
String filename,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.is_active: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
if (filename==null || filename.trim().length()==0)
throw new JLIException("No file name parameter given");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return false;
CallModel m = JlinkUtils.getFile(session, filename, false);
if (m!=null) {
return JlinkUtils.isModelActive(session, m);
}
else {
return false;
}
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.is_active,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#display(java.lang.String, boolean, java.lang.String)
*/
public void display(
String filename,
boolean activate,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
display(filename, activate, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#display(java.lang.String, boolean, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public void display(
String filename,
boolean activate,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.display: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
if (filename==null || filename.trim().length()==0)
throw new JLIException("No file name parameter given");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return;
CallModel m = JlinkUtils.getFile(session, filename, true);
if (m!=null) {
JlinkUtils.displayModel(session, m, activate);
}
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.display,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#closeWindow(java.lang.String, java.lang.String)
*/
public void closeWindow(
String filename,
String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
closeWindow(filename, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#closeWindow(java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
public void closeWindow(
String filename,
AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.close_window: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return;
if (filename!=null && filename.trim().length()>0) {
CallModel m = JlinkUtils.getFile(session, filename, true);
if (m!=null) {
CallWindow win = session.getModelWindow(m);
if (win!=null)
win.close();
}
}
else {
CallWindow win = session.getCurrentWindow();
if (win!=null)
win.close();
}
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.close_window,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#listSimpReps(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public List<String> listSimpReps(String filename, String name, String sessionId) throws JLIException {
JLISession sess = JLISession.getSession(sessionId);
return listSimpReps(filename, name, sess);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.intf.IJLFile#listSimpReps(java.lang.String, java.lang.String, com.simplifiedlogic.nitro.jlink.data.AbstractJLISession)
*/
@Override
public List<String> listSimpReps(String filename, String name, AbstractJLISession sess) throws JLIException {
DebugLogging.sendDebugMessage("file.list_simp_reps: " + filename, NitroConstants.DEBUG_KEY);
if (sess==null)
throw new JLIException("No session found");
long start = 0;
if (NitroConstants.TIME_TASKS)
start = System.currentTimeMillis();
try {
if (NitroUtils.isPattern(filename))
throw new JLIException("Name patterns are not supported for this command");
JLGlobal.loadLibrary();
CallSession session = JLConnectionUtil.getJLSession(sess.getConnectionId());
if (session == null)
return null;
CallModel m = JlinkUtils.getFile(session, filename, true);
ListSimpRepLooper looper = new ListSimpRepLooper();
looper.setNamePattern(name);
looper.loop(m);
return looper.output;
}
catch (jxthrowable e) {
throw JlinkUtils.createException(e);
}
finally {
if (NitroConstants.TIME_TASKS) {
DebugLogging.sendTimerMessage("file.list_simp_reps,"+filename, start, NitroConstants.DEBUG_KEY);
}
}
}
/**
* Walk the hierarchy of an assembly to find a list of sub-components to assemble a new component to
*
* @param session
* @param baseAssembly
* @param wrapping_solid
* @param base_seq
* @param curPath
* @param pathlen
* @param searchName
* @param searchPattern
* @param results An output list of results from the walk
* @param assembliesProcessed
* @param onelevel
* @param assembleToRoot
* @throws JLIException
* @throws jxthrowable
*/
private void walkAssemble(CallSession session, CallAssembly baseAssembly, CallSolid wrapping_solid, String base_seq, List<Integer> curPath, int pathlen, String searchName, Pattern searchPattern, List<WalkResult> results, List<String> assembliesProcessed, boolean onelevel, boolean assembleToRoot) throws JLIException, jxthrowable {
CallFeatures components = wrapping_solid.listFeaturesByType(Boolean.FALSE, FeatureType.FEATTYPE_COMPONENT);
if (components==null)
return;
int len = components.getarraysize();
if (len==0) return;
CallComponentFeat component;
CallModelDescriptor desc = null;
int type;
String newseq;
CallModel child;
String filename;
int id=0;
int seq=0;
for (int i=0; i<len; i++) {
component = (CallComponentFeat)components.get(i);
try {
if (component.getStatus()!=FeatureStatus._FEAT_ACTIVE)
continue;
// try {
desc = component.getModelDescr();
// catch (XToolkitCantOpen e) {
/*
* Note: From Pro/ENGINEER Wildfire 4.0 onwards, the
methods pfcModel.Model.GetFullName,
pfcModel.Model.GetGenericName, and
pfcModel.Model.GetDescr throw an exception
pfcExceptions.XtoolkitCantOpen if called on a
model instance whose immediate generic is not in
session. Handle this exception and typecast the model
as pfcSolid.Solid, which in turn can be typecast as
pfcFamily.FamilyMember, and use the method
pfcFamily.FamilyMember.GetImmediateGenericI
nfo to get the model descriptor of the immediate generic
model. The model descriptor can be used to derive the
full name or generic name of the model. If you wish to
switch off this behavior and continue to run legacy
applications in the pre-Wildfire 4.0 mode, set the
configuration option
retrieve_instance_dependencies to
"instance_and_generic_deps"
*/
child = null;
type = desc.getType();
newseq = base_seq + '.' + ++seq;
id = component.getId();
if (curPath.size()>pathlen)
curPath.set(pathlen, new Integer(id));
else
curPath.add(new Integer(id));
filename = desc.getFileName();
if ((searchName!=null && filename.equalsIgnoreCase(searchName)) ||
(searchPattern!=null && searchPattern.matcher(filename.toUpperCase()).matches())) {
CallIntSeq ids = CallIntSeq.create();
for (int k=0; k<pathlen+1; k++) {
ids.append(((Integer)curPath.get(k)).intValue());
}
if (child==null)
child = session.getModelFromDescr(desc);
WalkResult res = new WalkResult(CallComponentPath.create(baseAssembly, ids), (CallAssembly)wrapping_solid, child);
results.add(res);
}
if (!onelevel) {
// recurse into the child components
if (type==ModelType._MDL_ASSEMBLY) {
// don't need to assemble into the same assembly more than once, so skip dups
if (!assembleToRoot) {
if (assembliesProcessed.contains(filename))
continue;
assembliesProcessed.add(filename);
}
if (child==null)
child = session.getModelFromDescr(desc);
if (child!=null && child instanceof CallSolid) {
// System.out.println(indent + "checking children for " + instname);
walkAssemble(session, baseAssembly, (CallSolid)child, newseq, curPath, pathlen+1, searchName, searchPattern, results, assembliesProcessed, onelevel, assembleToRoot);
}
}
}
}
catch (jxthrowable jxe) {
throw new JLIException(JlinkUtils.ptcError(jxe, "A PTC error has occurred when retrieving component " + component.getModelDescr().getFileName()));
}
}
}
/**
* @author Adam Andrews
*
*/
private class WalkResult {
CallComponentPath compPath;
CallAssembly parent;
CallModel item;
/**
* @param compPath
* @param parent
* @param item
*/
public WalkResult(CallComponentPath compPath, CallAssembly parent, CallModel item) {
this.compPath = compPath;
this.parent = parent;
this.item = item;
}
}
/**
* An implementation of ModelLooper which gets a list of open model names
* @author Adam Andrews
*
*/
private static class ListLooper extends ModelLooper {
/**
* An output list of model names
*/
public List<String> output = null;
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.util.ModelLooper#loopAction(com.simplifiedlogic.nitro.jlink.calls.model.CallModel)
*/
public boolean loopAction(CallModel m) throws JLIException,jxthrowable {
String name = null;
try {
name = m.getFileName();
}
catch (XToolkitCantOpen e) {
JlinkUtils.resolveGenerics(getSession(), m);
name = m.getFileName();
}
if (currentName==null)
currentName = name;
if (output==null)
output = new Vector<String>();
output.add(currentName);
return false;
}
}
/**
* An implementation of ModelLooper which saves a list of models
* @author Adam Andrews
*
*/
private static class SaveLooper extends ModelLooper {
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.util.ModelLooper#loopAction(com.simplifiedlogic.nitro.jlink.calls.model.CallModel)
*/
public boolean loopAction(CallModel m) throws JLIException,jxthrowable {
m.save();
return false;
}
}
/**
* An implementation of ModelLooper which regenerates a list of models
* @author Adam Andrews
*
*/
private static class RegenerateLooper extends ModelLooper {
/**
* Whether to display each model before regenerating
*/
public boolean display = false;
/**
* The Creo session
*/
public CallSession session = null;
public boolean loopAction(CallModel m) throws JLIException, jxthrowable {
if (display) {
JlinkUtils.displayModel(getSession(), m, true);
}
// Things that can regenerate:
// Model2D
// SheetOwner
// View2D
// Solid
// XSection
// ComponentFeat
if (m instanceof CallSolid) {
CallSolid solid = (CallSolid)m;
CallRegenInstructions reginst = CallRegenInstructions.create(Boolean.FALSE, null, null);
JlinkUtils.regenerate(session, new RegenerateModel(solid, reginst), false, NitroConstants.DEBUG_REGEN_KEY);
}
else if (m instanceof CallModel2D) {
if (!display) {
// Window win = getSession().GetModelWindow(m);
// if (win!=null) // can cause a general toolkit error the second time around
JlinkUtils.displayModel(getSession(), m, true);
}
CallModel2D m2d = (CallModel2D)m;
JlinkUtils.regenerate(session, new JLDrawing.RegenerateDrawing(m2d), false, NitroConstants.DEBUG_REGEN_KEY);
}
CallWindow win = getSession().getModelWindow(m);
if (win!=null) {
long start = System.currentTimeMillis();
win.refresh();
DebugLogging.sendTimerMessage("jlink.Refresh", start, NitroConstants.DEBUG_REGEN_KEY);
}
return false;
}
}
/**
* An implenetation of ModelLooper which erases a list of models
* @author Adam Andrews
*
*/
private static class EraseLooper extends ModelLooper {
/**
* Output field which indicates whether anything was erased in this call
*/
public boolean erasedSomething = true;
/**
* Whether to also erase children of the model(s)
*/
public boolean eraseChildren = true;
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.util.ModelLooper#loopAction(com.simplifiedlogic.nitro.jlink.calls.model.CallModel)
*/
public boolean loopAction(CallModel m) throws JLIException, jxthrowable {
// loop until the list is empty or we've gone through the list without erasing anything
if (m!=null) {
try {
if (eraseChildren)
m.eraseWithDependencies();
else
m.erase();
erasedSomething = true;
return true; // as soon as we erase anything, break out of the loop so we can get a new list
}
catch (XToolkitInUse e) { // caused when erasing a model that's a dependency of another
if (getNamePattern()!=null || getNameList()!=null) {
if (currentName==null)
currentName = m.getFileName();
throw new JLIException("File '" + currentName + "' could not be erased because it was still in use");
}
}
//catch (XToolkitBadInputs e) {} // caused when erasing a model that's already been erased
}
return false;
}
}
/**
* An implementation of ModelItemLooper which returns a list of coordinate systems on a model
* @author Adam Andrews
*
*/
private class AssembleLooper2 extends ModelItemLooper {
/**
* Output list of corodinate systems
*/
List<ModelItemEntry> items = new Vector<ModelItemEntry>();
/**
* Constructor needed to initialize model item type
*/
public AssembleLooper2() {
setSearchType(ModelItemType.ITEM_COORD_SYS);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.util.ModelItemLooper#loopAction(com.simplifiedlogic.nitro.jlink.calls.modelitem.CallModelItem)
*/
public boolean loopAction(CallModelItem item) throws JLIException, jxthrowable {
if (currentName==null)
currentName = item.getName();
ModelItemEntry entry = new ModelItemEntry();
entry.name = item.getName();
entry.item = item;
items.add(entry);
return false;
}
}
/**
* Implementation of ModelItemLooper which loops over Simplified Reps and
* outputs a list of names
* @author Adam Andrews
*
*/
private class ListSimpRepLooper extends ModelItemLooper {
/**
* The output list of dimension data
*/
public Vector<String> output = null;
/**
* Default constructor which sets the search type.
*/
public ListSimpRepLooper() {
setSearchType(ModelItemType.ITEM_SIMPREP);
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.util.ModelItemLooper#loopAction(com.simplifiedlogic.nitro.jlink.calls.modelitem.CallModelItem)
*/
public boolean loopAction(CallModelItem item) throws JLIException, jxthrowable {
try {
if (currentName==null)
currentName = item.getName();
if (output==null)
output = new Vector<String>();
output.add(item.getName());
}
catch (jxthrowable e) {
// e.printStackTrace();
System.err.println("Error looping through Simplified Reps: " + e.getMessage());
}
return false;
}
}
/**
* Implentation of java.lang.Comparable which allows model items to be sorted by name
* @author Adam Andrews
*
*/
private class ModelItemEntry implements Comparable<ModelItemEntry> {
/**
* Name of thd model item object, stored separately to save on JNI calls
*/
public String name;
/**
* The model item object
*/
public CallModelItem item;
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(ModelItemEntry arg0) {
String argname = ((ModelItemEntry)arg0).name;
return name.compareTo(argname);
}
}
/**
* Implementation of Regenerator which will regenerate a Model
* @author Adam Andrews
*
*/
private static class RegenerateModel implements JlinkUtils.Regenerator {
/**
* The model to be regenerated
*/
private CallSolid solid;
/**
* The regenerate instructions
*/
private CallRegenInstructions reginst;
/**
* Default constructor
* @param solid The model to be regenerated
* @param reginst The regenerate instructions
*/
public RegenerateModel(CallSolid solid, CallRegenInstructions reginst) {
this.solid = solid;
this.reginst = reginst;
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.impl.JlinkUtils.Regenerator#regenerate()
*/
@Override
public void regenerate() throws jxthrowable {
solid.regenerate(reginst);
}
}
/**
* Implementation of Regenerator which will execute feature operations.
* This was set up as a Regenerator because a regenerate is forced.
* @author Adam Andrews
*
*/
private static class RegenerateFeatureOps implements JlinkUtils.Regenerator {
/**
* The model containing the features
*/
private CallSolid solid;
/**
* The feature operations to execute
*/
private CallFeatureOperations featOps;
/**
* Default constructor
* @param solid The model containing the features
* @param featOps The list of feature operations to execute
*/
public RegenerateFeatureOps(CallSolid solid, CallFeatureOperations featOps) {
this.solid = solid;
this.featOps = featOps;
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jlink.impl.JlinkUtils.Regenerator#regenerate()
*/
@Override
public void regenerate() throws jxthrowable {
CallRegenInstructions inst = CallRegenInstructions.create(Boolean.FALSE, null, null);
solid.executeFeatureOps(featOps, inst);
}
}
}
|
package com.egf.db.services.impl;
import static org.junit.Assert.*;
import org.apache.log4j.Logger;
import org.junit.Test;
import com.egf.db.core.sql.template.Generate;
/**
* @author fangj
* @version $Revision: 1.0 $
* @since 1.0
*/
public class GenerateImplTest {
Logger logger=Logger.getLogger(GenerateImplTest.class);
Generate generate =new GenerateImpl();
/**
* Test method for {@link com.egf.db.services.impl.GenerateImpl#AddConstraint(java.lang.String, java.lang.String, java.lang.String, java.lang.String[])}.
*/
@Test
public void testAddConstraint() {
String sql=generate.addConstraint("dtxx.test", "aa", "unique", "cl1","cl2");
assertEquals("alter table dtxx.test add constraint aa unique (cl1,cl2);", sql);
String sql2=generate.addConstraint("test", "aa", "unique", "cl1");
assertEquals("alter table test add constraint aa unique (cl1);", sql2);
}
/**
* Test method for {@link com.egf.db.services.impl.GenerateImpl#addIndex(java.lang.String, java.lang.String, java.lang.String[])}.
*/
@Test
public void testAddIndexStringStringStringArray() {
String sql=generate.addIndex("zdry.zdryqbxx", "test", new String[]{"cl1","cl2"});
assertEquals("create index test on zdry.zdryqbxx (cl1,cl2);", sql);
String sql2=generate.addIndex("zdry.zdryqbxx", "test", new String[]{"cl1"});
assertEquals("create index test on zdry.zdryqbxx (cl1);", sql2);
}
/**
* Test method for {@link com.egf.db.services.impl.GenerateImpl#addIndex(java.lang.String, java.lang.String, java.lang.String, java.lang.String[])}.
*/
@Test
public void testAddIndexStringStringStringStringArray() {
String sql=generate.addIndex("zdry.zdryqbxx", "test", "unique", new String[]{"cl1","cl2"});
assertEquals("create unique index test on zdry.zdryqbxx (cl1,cl2);", sql);
}
/**
* Test method for {@link com.egf.db.services.impl.GenerateImpl#AddColumn(java.lang.String, java.lang.String, java.lang.String)}.
*/
@Test
public void testAddColumnStringStringString() {
String sql=generate.addColumn("test", "cl1", "varchar2(10)");
assertEquals("alter table test add cl1 varchar2(10);", sql);
}
/**
* Test method for {@link com.egf.db.services.impl.GenerateImpl#AddColumn(java.lang.String, java.lang.String, java.lang.String, java.lang.String)}.
*/
@Test
public void testAddColumnStringStringStringString() {
String sql=generate.addColumn("test", "cl1", "number", "not null");
assertEquals("alter table test add cl1 number not null;", sql);
String sql2=generate.addColumn("test", "cl1", "number");
assertEquals("alter table test add cl1 number;", sql2);
}
/**
* Test method for {@link com.egf.db.services.impl.GenerateImpl#addComment(java.lang.String, java.lang.String, java.lang.String)}.
*/
@Test
public void testAddComment() {
String sql=generate.addComment("test", "cl1", "");
assertEquals("comment on column test.cl1 is '';", sql);
}
/**
* Test method for {@link com.egf.db.services.impl.GenerateImpl#dropColumn(java.lang.String, java.lang.String)}.
*/
@Test
public void testDropColumn() {
String sql=generate.dropColumn("test", "cl1");
assertEquals("alter table test drop column cl1;", sql);
}
/**
* Test method for {@link com.egf.db.services.impl.GenerateImpl#dropIndex(java.lang.String)}.
*/
@Test
public void testDropIndex() {
String sql=generate.dropIndex("tt");
assertEquals("drop index tt;", sql);
}
/**
* Test method for {@link com.egf.db.services.impl.GenerateImpl#dropTalbe(java.lang.String)}.
*/
@Test
public void testDropTalbe() {
String sql=generate.dropTalbe("tt");
assertEquals("drop table tt;", sql);
}
/**
* Test method for {@link com.egf.db.services.impl.GenerateImpl#dropConstraint(java.lang.String, java.lang.String)}.
*/
@Test
public void testDropConstraint() {
String sql=generate.dropConstraint("test", "test");
assertEquals("alter table test drop constraint test;", sql);
}
}
|
package com.github.arteam.jgcompare;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.junit.Test;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
public class IterablesTest {
Iterable<String> source = Lists.newArrayList("as", "q", "def");
Stream<String> stream = Stream.of("as", "q", "def");
@Test
public void testAll() {
assertThat(Iterables.all(source, it -> !it.isEmpty())).isTrue();
assertThat(stream.allMatch(it -> !it.isEmpty())).isTrue();
}
@Test
public void testAny() {
assertThat(Iterables.any(source, it -> it.length() > 2)).isTrue();
assertThat(stream.anyMatch(it -> it.length() > 2)).isTrue();
}
@Test
public void testConcat() {
List<String> addition = ImmutableList.of("ger", "d", "fm");
List<String> result = ImmutableList.of("as", "q", "def", "ger", "d", "fm");
assertThat(ImmutableList.copyOf(Iterables.concat(source, addition))).isEqualTo(result);
assertThat(Stream.concat(stream, addition.stream()).collect(Collectors.toList())).isEqualTo(result);
}
@Test
public void testContains() {
assertThat(Iterables.contains(source, "q")).isTrue();
assertThat(stream.anyMatch(s -> s.equals("q"))).isTrue();
}
@Test
public void testCycle() {
ImmutableList<String> expected = ImmutableList.of("as", "q", "def", "as", "q", "def", "as", "q", "def", "as");
Iterator<String> iterator = Iterables.cycle(source).iterator();
List<String> cycled = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
cycled.add(iterator.next());
}
assertThat(expected).isEqualTo(cycled);
String[] streamAsArray = stream.toArray(String[]::new);
assertThat(expected).isEqualTo(IntStream.iterate(0, i -> (i + 1) % 3)
.mapToObj(i -> streamAsArray[i])
.limit(10)
.collect(Collectors.toList()));
}
@Test
public void testFilter() {
Iterable<String> result = Iterables.filter(Iterables.filter(source, s -> s.length() > 1),
s -> s.startsWith("d"));
assertThat(ImmutableList.copyOf(result)).isEqualTo(ImmutableList.of("def"));
assertThat(stream
.filter(s -> s.length() > 1)
.filter(s -> s.startsWith("d"))
.collect(Collectors.toList())).isEqualTo(ImmutableList.of("def"));
}
@Test
public void testFind() {
assertThat(Iterables.find(source, it -> it.length() == 1)).isEqualTo("q");
assertThat(stream.filter(it -> it.length() == 1).findAny().get()).isEqualTo("q");
}
@Test
public void testFindDefaultValue() {
assertThat(Iterables.find(source, it -> it.length() == 4, "abcd")).isEqualTo("abcd");
assertThat(stream.filter(it -> it.length() == 4).findAny().orElse("abcd")).isEqualTo("abcd");
}
@Test
public void testFrequency() {
List<String> source = ImmutableList.<String>builder()
.addAll(this.source)
.add("def")
.add("try")
.add("q")
.add("def")
.build();
Stream<String> stream = source.stream();
assertThat(Iterables.frequency(source, "def")).isEqualTo(3);
assertThat(stream
.filter(s -> s.equals("def"))
.count()).isEqualTo(3);
}
@Test
public void testGetFirst() {
assertThat(Iterables.getFirst(source, "")).isEqualTo("as");
assertThat(stream.findFirst().orElse("")).isEqualTo("as");
}
@Test
public void testGetLast() {
assertThat(Iterables.getLast(source, "")).isEqualTo("def");
assertThat(stream.reduce((l, r) -> r).get()).isEqualTo("def");
}
@Test
public void testGetOnlyElement() {
assertThat(Iterables.getOnlyElement(Iterables.filter(source, s -> s.length() == 3))).isEqualTo("def");
assertThat(stream.filter(s -> s.length() == 3).findFirst().get()).isEqualTo("def");
}
@Test
public void testGetOnlyElementWithDefault() {
assertThat(Iterables.getOnlyElement(Iterables.filter(source, s -> s.length() == 4), "mann")).isEqualTo("mann");
assertThat(stream.filter(s -> s.length() == 4).findFirst().orElse("mann")).isEqualTo("mann");
}
@Test
public void testIndexOf() {
assertThat(Iterables.indexOf(source, it -> it.length() == 1)).isEqualTo(1);
// Rather tricky way
assertThat(StreamUtils.withIndex(stream)
.filter(e -> e.getElement().length() == 1)
.map(e -> e.getIndex())
.findFirst()
.get())
.isEqualTo(1);
}
@Test
public void testIsEmpty() {
assertThat(Iterables.isEmpty(source)).isEqualTo(false);
assertThat(stream.noneMatch(s -> true)).isEqualTo(false);
}
@Test
public void testLimit() {
assertThat(Lists.newArrayList(Iterables.limit(source, 2))).isEqualTo(Arrays.asList("as", "q"));
assertThat(stream.limit(2).collect(Collectors.toList())).isEqualTo(Arrays.asList("as", "q"));
}
@Test
@SuppressWarnings("unchecked")
public void testPartition() {
List<String> source = ImmutableList.of("trash", "talk", "arg", "loose", "fade", "cross", "dump", "bust");
assertThat(Iterables.partition(source, 3)).containsExactly(
ImmutableList.of("trash", "talk", "arg"),
ImmutableList.of("loose", "fade", "cross"),
ImmutableList.of("dump", "bust"));
int partitionSize = 3;
List<List<String>> partitions = StreamUtils.withIndex(source.stream())
.collect(ArrayList::new, (lists, el) -> {
int place = el.getIndex() % partitionSize;
List<String> part;
if (place == 0) {
part = new ArrayList<>();
lists.add(part);
} else {
part = lists.get(lists.size() - 1);
}
part.add(el.getElement());
}, ArrayList::addAll);
assertThat(partitions).containsExactly(
ImmutableList.of("trash", "talk", "arg"),
ImmutableList.of("loose", "fade", "cross"),
ImmutableList.of("dump", "bust"));
}
@Test
@SuppressWarnings("unchecked")
public void testPartitionClumsy() {
List<String> source = ImmutableList.of("trash", "talk", "arg", "loose", "fade", "cross", "dump", "bust");
int partitionSize = 3;
List<List<String>> partitions = StreamUtils.withIndex(source.stream())
.collect(new Collector<StreamUtils.ElementIndex<String>, List<List<String>>, List<List<String>>>() {
@Override
public Supplier<List<List<String>>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<List<String>>, StreamUtils.ElementIndex<String>> accumulator() {
return (lists, el) -> {
int place = el.getIndex() % partitionSize;
List<String> part;
if (place == 0) {
part = new ArrayList<>();
lists.add(part);
} else {
part = lists.get(lists.size() - 1);
}
part.add(el.getElement());
};
}
@Override
public BinaryOperator<List<List<String>>> combiner() {
return (first, second) -> {
first.addAll(second);
return first;
};
}
@Override
public Function<List<List<String>>, List<List<String>>> finisher() {
return Function.identity();
}
@Override
public Set<Characteristics> characteristics() {
return EnumSet.of(Characteristics.CONCURRENT, Characteristics.UNORDERED);
}
}
);
assertThat(partitions).containsExactly(
ImmutableList.of("trash", "talk", "arg"),
ImmutableList.of("loose", "fade", "cross"),
ImmutableList.of("dump", "bust"));
}
@Test
public void testRemoveAll() {
List<String> removed = ImmutableList.of("q", "d");
Iterables.removeAll(source, removed);
assertThat(source).containsExactly("as", "def");
assertThat(stream.filter(s -> !removed.contains(s))
.collect(Collectors.toList())).containsExactly("as", "def");
}
@Test
public void testRemoveIf() {
Iterables.removeIf(source, it -> it.length() < 3);
assertThat(Arrays.asList("def")).isEqualTo(source);
List<String> removed = stream
.filter(((Predicate<String>) it -> it.length() < 3).negate())
.collect(Collectors.toList());
assertThat(Arrays.asList("def")).isEqualTo(removed);
}
@Test
public void testRetainAll() {
List<String> removed = ImmutableList.of("q", "d");
Iterables.retainAll(source, removed);
assertThat(source).containsExactly("q");
assertThat(stream.filter(s -> removed.contains(s))
.collect(Collectors.toList())).containsExactly("q");
}
@Test
public void testSize() {
assertThat(Iterables.size(source)).isEqualTo(3);
assertThat(stream.count()).isEqualTo(3);
}
@Test
public void testSkip() {
assertThat(Iterables.skip(source, 2)).containsOnly("def");
assertThat(stream.skip(2).collect(Collectors.toList())).containsOnly("def");
}
@Test
public void testToArray() {
assertThat(Iterables.toArray(source, String.class)).isEqualTo(new String[]{"as", "q", "def"});
assertThat(stream.toArray(String[]::new)).isEqualTo(new String[]{"as", "q", "def"});
}
@Test
public void testTransform() {
assertThat(Lists.newArrayList(Iterables.transform(source, String::length))).isEqualTo(Arrays.asList(2, 1, 3));
assertThat(stream.map(String::length).collect(Collectors.toList())).isEqualTo(Arrays.asList(2, 1, 3));
}
@Test
public void testTryFind() {
assertThat(Iterables.tryFind(source, it -> it.length() == 4).or("abcd")).isEqualTo("abcd");
assertThat(stream.filter(it -> it.length() == 4).findAny().orElse("abcd")).isEqualTo("abcd");
}
}
|
package com.github.kratorius.cuckoohash;
import junit.framework.TestCase;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/**
* Tests for entrySet(), keySet() and values().
*/
public class ViewsTest extends TestCase {
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
public void testEmptyEntrySet() {
CuckooHashMap<String, Integer> m = new CuckooHashMap<>();
assertTrue(m.entrySet().isEmpty());
}
public void testSimpleEntrySet() {
CuckooHashMap<String, Integer> m = new CuckooHashMap<>();
m.put("key1", 1);
assertEquals(1, m.entrySet().size());
Map.Entry<String, Integer> item = m.entrySet().iterator().next();
assertEquals(1, (int) item.getValue());
}
public void testLargeEntrySet() {
final int size = 1024;
CuckooHashMap<String, Integer> m = new CuckooHashMap<>();
for (int i = 0; i < size; i++){
m.put("key-" + i, 100);
}
Set<Map.Entry<String, Integer>> entrySet = m.entrySet();
assertEquals(size, entrySet.size());
assertEquals(size, m.size());
for (int i = 0; i < size; i++) {
assertTrue(entrySet.contains(new AbstractMap.SimpleEntry<>("key-" + i, 100)));
}
}
public void testKeySet() {
final int size = 1024;
CuckooHashMap<String, Integer> m = new CuckooHashMap<>();
for (int i = 0; i < size; i++){
m.put("key-" + i, i);
}
// keySet() returns a set and therefore there's no guarantee on the ordering of the keys.
Set<String> keys = m.keySet();
assertEquals(size, keys.size());
for (int i = 0; i < size; i++){
assertTrue(keys.contains("key-" + i));
}
// Override a key.
m.put("key-123", 2134);
keys = m.keySet();
assertEquals(size, keys.size());
for (int i = 0; i < size; i++){
assertTrue(keys.contains("key-" + i));
}
}
public void testValues_unique() {
final int size = 1024;
CuckooHashMap<String, Integer> m = new CuckooHashMap<>();
for (int i = 0; i < size; i++){
m.put("key-" + i, i);
}
Collection<Integer> values = m.values();
assertEquals(size, values.size());
for (int i = 0; i < size; i++){
assertTrue(values.contains(i));
}
}
public void testValues_duplicates() {
final int size = 1024;
CuckooHashMap<String, Integer> m = new CuckooHashMap<>();
for (int i = 0; i < size; i++){
m.put("key-" + i, i / 2);
}
Collection<Integer> values = m.values();
assertEquals(size, values.size());
for (int i = 0; i < size; i++){
assertTrue(values.contains(i / 2));
}
}
}
|
package com.ociweb.hazelcast.stage;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.ociweb.pronghorn.pipe.Pipe;
import com.ociweb.pronghorn.pipe.PipeConfig;
import com.ociweb.pronghorn.pipe.RawDataSchema;
import com.ociweb.pronghorn.stage.PronghornStage;
import com.ociweb.pronghorn.stage.scheduling.GraphManager;
import com.ociweb.pronghorn.stage.scheduling.ThreadPerStageScheduler;
import com.ociweb.pronghorn.stage.test.PipeCleanerStage;
public class ConnectionTest {
private static HazelcastInstance memberInstance;
@BeforeClass
public static void statupClusterMember() {
Config config = new Config();
config.getNetworkConfig().getJoin().getTcpIpConfig().addMember("127.0.0.1");
memberInstance = Hazelcast.newHazelcastInstance(config);
if (0==memberInstance.getAtomicLong("MyLock").getAndIncrement()) {
System.out.println("Starting Connection Tets");
}
}
@AfterClass
public static void shutdownClusterMember() {
System.out.println("shutting down cluster");
memberInstance.shutdown();
}
@Test
public void simpleAuthTest() {
GraphManager gm = new GraphManager();
PipeConfig<RawDataSchema> inputConfig = new PipeConfig(RawDataSchema.instance);
PipeConfig<RequestResponseSchema> outputConfig = new PipeConfig(RequestResponseSchema.instance);;
Pipe<RawDataSchema> input = new Pipe<>(inputConfig);
Pipe<RequestResponseSchema> output = new Pipe<>(outputConfig);
HazelcastConfigurator conf = new HazelcastConfigurator();
ConnectionStage cs = new TestConnectionStageWrapper(gm, input, output, conf, true);
GeneratorStage gs = new GeneratorStage(gm, input);
PipeCleanerStage pc = new PipeCleanerStage(gm, output);
ThreadPerStageScheduler scheduler = new ThreadPerStageScheduler(gm);
scheduler.startup();
scheduler.awaitTermination(3,TimeUnit.SECONDS);
}
public class TestConnectionStageWrapper extends ConnectionStage {
private final boolean shutDownAfterAuth;
protected TestConnectionStageWrapper(GraphManager graphManager,
Pipe<RawDataSchema> input,
Pipe<RequestResponseSchema> output,
HazelcastConfigurator conf, boolean shutDownAfterAuth) {
super(graphManager,input,output,conf);
this.shutDownAfterAuth = shutDownAfterAuth;
}
@Override
public void run() {
super.run();
if (shutDownAfterAuth && isAuthenticated) {
Assert.assertTrue(authUUIDLen>10);
System.out.println("IP & GUID:"+authResponse);
requestShutdown();
}
}
}
public class GeneratorStage extends PronghornStage {
protected GeneratorStage(GraphManager graphManager, Pipe output) {
super(graphManager, NONE, output);
GraphManager.addNota(graphManager,GraphManager.PRODUCER,GraphManager.PRODUCER, this);
}
@Override
public void run() {
}
}
}
|
package com.versionone.om.tests;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import sun.net.www.protocol.http.AuthCacheImpl;
import sun.net.www.protocol.http.AuthCacheValue;
import com.versionone.apiclient.ConnectionException;
import com.versionone.om.Effort;
import com.versionone.om.Project;
import com.versionone.om.Story;
import com.versionone.om.Task;
import com.versionone.om.V1Instance;
public class AssetsStateTester extends BaseSDKTester {
private final static int port = 8080;
private V1Instance proxyInstance;
@Test
public void effortAssetStateTest() {
TestServer testServer = new TestServer(port, null, 100);
runServer(testServer);
String storyName = "story name 13";
String taskName = "task name 123";
Double effortTime = 11D;
Project rootProject = getProxyInstance().get().projectByID(SCOPE_ZERO);
Story story = rootProject.createStory(storyName);
Task task = story.createTask(taskName);
Effort effort = task.createEffort(effortTime);
resetInstance();
effort = getProxyInstance().get().effortByID(effort.getID());
resetInstance();
effort = getProxyInstance().get().effortByID(effort.getID());
testServer.stopServer();
List<String> urls = testServer.getUrls();
Assert.assertFalse(urls.contains("meta.v1/Actual/AssetState"));
}
protected V1Instance getProxyInstance() {
if (proxyInstance == null) {
proxyInstance = new V1Instance("http://localhost/VersionOne.SDK.Java.ObjectModel.Tests/", "admin", "admin");
proxyInstance.validate();
}
return proxyInstance;
}
private void runServer(TestServer server) {
new Thread(server).start();
// waiting till server is started
int count = 0;
while (server.isNotRun && count < 50) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
// JIC
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class TestServer extends Thread {
public volatile boolean isNotRun = true;
final String HTTP = "HTTP/1.0 ";
private final List<String> cookies = new LinkedList<String>();
private final int port;
private ServerSocket serverSocket;
private final int requestNumbers;
private static final String UTF8 = "UTF-8";
private final List<String> urls = new ArrayList<String>();
public TestServer(int port, String urlPart, int requestNumbers) {
if (cookies != null) {
this.cookies.addAll(cookies);
}
this.port = port;
this.requestNumbers = requestNumbers;
}
public void run() {
serverSocket = null;
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Could not listen on port: " + port + ". "
+ e.getMessage());
System.exit(-1);
}
isNotRun = false;
try {
for (int i = 0; i < requestNumbers; i++) {
clientSocket = null;
out = null;
in = null;
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket
.getInputStream()));
HttpURLConnection connection = makeRequestToRealV1(in);
String responce;
responce = createResponce(connection);
out.write(responce);
out.flush();
out.close();
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
if (out != null) {
out.close();
}
try {
if (in != null) {
in.close();
}
if (clientSocket != null) {
clientSocket.close();
}
} catch (Exception ex) {
}
stopServer();
}
}
private String createResponce(HttpURLConnection connection) throws IOException {
BufferedReader in= null;
String result = "";
try {
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
String header = connection.getHeaderField( 0 );
result += header + "\n";
int i = 1;
while ( ( header = connection.getHeaderField(i) ) != null ) {
String key = connection.getHeaderFieldKey(i);
result += key + ": " + header + "\n";
i++;
}
result += "\n";
int numByte = Integer.valueOf(connection.getHeaderField("Content-Length"));
for (int k = 0; k < numByte; k++) {
char data = (char)in.read();
result += data;
}
return result;
}
private HttpURLConnection makeRequestToRealV1(BufferedReader in)
throws ConnectionException {
//get URL and request method
V1RequestInfo urlAndType = getHeaderFirstLineData(in);
String path = getApplicationPath() + urlAndType.url;
HttpURLConnection request;
AuthCacheValue.setAuthCache(new AuthCacheImpl());
Authenticator.setDefault(new Credentials(getUsername(), getPassword()));
Map<String, String> customHttpHeaders = null;
try {
customHttpHeaders = getHeaderParams(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
URL url = new URL(path);
request = (HttpURLConnection) url.openConnection();
request.setDoOutput(true);
addHeaders(request, customHttpHeaders);
if (urlAndType.method.equals("POST")) {
addPostData(in, request, customHttpHeaders);
}
} catch (MalformedURLException e) {
throw new ConnectionException("Invalid URL", e);
} catch (IOException e) {
throw new ConnectionException("Error Opening Connection", e);
}
return request;
}
private void addPostData(BufferedReader in, HttpURLConnection request,
Map<String, String> customHttpHeaders)
throws UnsupportedEncodingException, IOException {
OutputStreamWriter stream = new OutputStreamWriter(request.getOutputStream(), UTF8);
int numByte = Integer.parseInt(customHttpHeaders.get("Content-Length"));
String test = "";
for (int i = 0; i < numByte; i++) {
char data = (char)in.read();
stream.write(data);
test += data;
}
stream.flush();
}
private void addHeaders(HttpURLConnection request, Map<String, String> customHttpHeaders) {
if (customHttpHeaders == null) {
return;
}
for (String key : customHttpHeaders.keySet()) {
request.setRequestProperty(key, customHttpHeaders.get(key));
}
}
private Map<String, String> getHeaderParams(BufferedReader in)
throws IOException {
Map<String, String> headers = new HashMap<String, String>();
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.equals("")) {
break;
} else if (!inputLine.contains(": ")) {
continue;
}
String[] data = inputLine.split(": ");
if (data.length > 1) {
String value = data[1].replace("localhost:" + port, getHostName());
headers.put(data[0], value);
}
}
return headers;
}
private String getHostName() {
String domen = getApplicationPath();
URL url = null;
try {
url = new URL(domen);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return url != null ? url.getHost() : "";
}
private V1RequestInfo getHeaderFirstLineData(BufferedReader in) {
String url = "";
try {
url = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] tmp = url.split(" ");
url = tmp[1].substring(1, tmp[1].length());
urls.add(url);
return new V1RequestInfo(url, tmp[0]);
}
public void stopServer() {
try {
if (serverSocket != null) {
serverSocket.close();
}
} catch (Exception ex) {
}
}
public List<String> getUrls() {
return urls;
}
private class V1RequestInfo {
public String url;
public String method;
public V1RequestInfo(String url, String method) {
this.url = url;
this.method = method;
}
}
}
private class Credentials extends Authenticator {
PasswordAuthentication _value;
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return _value;
}
Credentials(String userName, String password) {
if (null == password) {
_value = new PasswordAuthentication(userName, null);
} else {
_value = new PasswordAuthentication(userName, password
.toCharArray());
}
}
@Override
public String toString() {
return _value.getUserName() + ":"
+ String.valueOf(_value.getPassword());
}
}
}
|
package edu.ufl.cise.cnt5106c.log;
import static org.junit.Assert.*;
public class EventLoggerTest {
public EventLoggerTest(){
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of peerConnection method, of class EventLogger.
*/
@Test
public void testPeerConnection(){
}
/**
* Test of chokeMessage method, of class EventLogger.
*/
@Test
public void testChokeMessage(){
}
/**
* Test of unchokeMessage method, of class EventLogger.
*/
@Test
public void testUnchokeMessage(){
}
/**
* Test of haveMessage method, of class EventLogger.
*/
@Test
public void testHaveMessage(){
}
/**
* Test of interestedMessage method, of class EventLogger.
*/
@Test
public void testInterestedMessage(){
}
/**
* Test of notInterestedMessage method, of class EventLogger.
*/
@Test
public void testNotInterestedMessage(){
}
/**
* Test of pieceDownloadedMessage method, of class EventLogger.
*/
@Test
public void testPieceDownloadedMessage(){
}
/**
* Test of fileDownloadedMessage method, of class EventLogger.
*/
@Test
public void testFileDownloadedMessage(){
}
/**
* Test of getLogMsgHeader method, of class EventLogger.
*/
@Test
public void testGetLogMsgHeader(){
}
}
|
package net.emaze.dysfunctional.options;
import net.emaze.dysfunctional.dispatching.delegates.ConstantProvider;
import net.emaze.dysfunctional.dispatching.delegates.Delegate;
import net.emaze.dysfunctional.dispatching.delegates.Identity;
import net.emaze.dysfunctional.testing.O;
import org.junit.Assert;
import org.junit.Test;
/**
*
* @author rferranti
*/
public class MaybeTest {
@Test
public void justHasValue() {
final Maybe<Integer> maybeInt = Maybe.just(1);
Assert.assertTrue(maybeInt.hasValue());
}
@Test(expected = IllegalStateException.class)
public void fetchingValueFromNothingYieldException() {
Maybe.nothing().value();
}
@Test
public void canFetchValueFromJust() {
int got = Maybe.just(1).value();
Assert.assertEquals(1, got);
}
@Test
public void fmapWithJustYieldsJustDelegateResult() {
final Maybe<Integer> expected = Maybe.just(1);
final Maybe<Integer> got = expected.fmap(new Identity<Integer>());
Assert.assertEquals(expected, got);
}
@Test
public void fmapWithJustNothingYieldsNothing() {
final Maybe<Integer> source = Maybe.nothing();
final Maybe<Integer> got = source.fmap(new Identity<Integer>());
Assert.assertFalse(got.hasValue());
}
@Test(expected = IllegalArgumentException.class)
public void fmapWithNullDelegateYieldsException() {
final Delegate<?, Integer> delegate = null;
Maybe.just(1).fmap(delegate);
}
@Test
public void maybeAndUnidentifiedObjectAreNotEquals() {
Assert.assertFalse(Maybe.just(1).equals(new Object()));
}
@Test
public void maybeWithSameValuesAreEquals() {
Assert.assertTrue(Maybe.just(1).equals(Maybe.just(1)));
}
@Test
public void maybeWithSameValuesHaveSameHashcode() {
Assert.assertEquals(Maybe.just(1).hashCode(), Maybe.just(1).hashCode());
}
@Test
public void toStringOfNothingIsNothing() {
Assert.assertEquals("Nothing", Maybe.nothing().toString());
}
@Test
public void toStringOfJustReflectsValue() {
Assert.assertEquals("Just 1", Maybe.just(1).toString());
}
@Test
public void transformingNothingToEitherYieldsLeft() {
final int marker = 0;
final Either<Integer, Object> either = Maybe.nothing().either(new ConstantProvider<Integer>(marker));
final Maybe<Integer> perform = new MaybeLeft<Integer, Object>().perform(either);
Assert.assertEquals(marker, perform.value().intValue());
}
@Test
public void transformingJustSomethingToEitherYieldsRight() {
final int left = 0;
final int right = 1;
final Either<Integer, Integer> either = Maybe.just(right).either(new ConstantProvider<Integer>(left));
final Maybe<Integer> perform = new MaybeRight<Integer, Integer>().perform(either);
Assert.assertEquals(right, perform.value().intValue());
}
@Test
public void callingOrElseOnJustYieldsJustValue() {
final O got = Maybe.just(O.ONE).orElse(O.ANOTHER);
Assert.assertEquals(O.ONE, got);
}
@Test
public void callingOrElseOnNothingYieldsParameter() {
final O got = Maybe.<O>nothing().orElse(O.ANOTHER);
Assert.assertEquals(O.ANOTHER, got);
}
@Test
public void nothingYieldsEmptyIterator() {
Assert.assertFalse(Maybe.nothing().iterator().hasNext());
}
@Test
public void justYieldsSingletonIterator() {
Assert.assertTrue(Maybe.just(O.ONE).iterator().hasNext());
}
}
|
package nom.bdezonia.zorbage.algorithm;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import nom.bdezonia.zorbage.groups.G;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorageFloat64;
/**
*
* @author Barry DeZonia
*
*/
public class TestMedian {
@Test
public void test() {
Float64Member value = new Float64Member();
ArrayStorageFloat64<Float64Member> storage = new ArrayStorageFloat64<Float64Member>(10, value);
// build the initial test data
for (int i = 0; i < storage.size(); i++) {
value.setV(i);
storage.set(i, value);
}
Float64Member result = new Float64Member();
Median.compute(G.DBL, storage, result);
assertEquals(4.5, result.v(), 0);
}
}
|
package org.cactoos.scalar;
import java.io.IOException;
import java.util.IllegalFormatException;
import java.util.IllegalFormatWidthException;
import org.cactoos.iterable.IterableOf;
import org.cactoos.matchers.ScalarHasValue;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
/**
* Test case for {@link ScalarWithFallback}.
*
* @author Roman Proshin (roman@proshin.org)
* @version $Id$
* @since 0.31
* @checkstyle JavadocMethodCheck (500 lines)
*/
@SuppressWarnings("unchecked")
public final class ScalarWithFallbackTest {
@Test
public void usesMainFunc() throws Exception {
final String message = "Main function's result
MatcherAssert.assertThat(
"Can't use the main function if no exception",
new ScalarWithFallback<>(
() -> message,
new IterableOf<>(
new FallbackFrom<>(
new IterableOf<>(IOException.class),
Throwable::getMessage
)),
input -> input
),
new ScalarHasValue<>(message)
);
}
@Test
public void usesFollowUpFunc() throws Exception {
final String message = "There was follow up function";
MatcherAssert.assertThat(
"Can't use the follow up function if no exception",
new ScalarWithFallback<>(
() -> "Main function's result
new IterableOf<>(
new FallbackFrom<>(
new IterableOf<>(IOException.class),
Throwable::getMessage
)),
input -> message
),
new ScalarHasValue<>(message)
);
}
@Test
public void usesFallback() throws Exception {
final String message = "Fallback from IOException";
MatcherAssert.assertThat(
"Can't use a single fallback in case of exception",
new ScalarWithFallback<>(
() -> {
throw new IOException("Failure with IOException");
},
new IterableOf<>(
new FallbackFrom<>(
new IterableOf<>(IOException.class),
exp -> message
)),
input -> input
),
new ScalarHasValue<>(message)
);
}
@Test
public void usesFallbackOfInterruptedException() throws Exception {
final String message = "Fallback from InterruptedException";
MatcherAssert.assertThat(
"Can't use a fallback from Interrupted in case of exception",
new ScalarWithFallback<>(
() -> {
throw new InterruptedException(
"Failure with InterruptedException"
);
},
new IterableOf<>(
new FallbackFrom<>(
new IterableOf<>(InterruptedException.class),
exp -> message
)),
input -> input
),
new ScalarHasValue<>(message)
);
}
@Test
public void usesTheClosestFallback() throws Exception {
final String expected = "Fallback from IllegalFormatException";
MatcherAssert.assertThat(
"Can't find the closest fallback",
new ScalarWithFallback<>(
() -> {
throw new IllegalFormatWidthException(1);
},
new IterableOf<>(
new FallbackFrom<>(
new IterableOf<>(IllegalArgumentException.class),
exp -> "Fallback from IllegalArgumentException"
),
new FallbackFrom<>(
new IterableOf<>(IllegalFormatException.class),
exp -> expected
)),
input -> input
),
new ScalarHasValue<>(expected)
);
}
@Test(expected = Exception.class)
public void noFallbackIsProvided() throws Exception {
new ScalarWithFallback<>(
() -> {
throw new IllegalFormatWidthException(1);
},
new IterableOf<>(),
input -> input
).value();
}
}
|
package org.cojen.tupl.repl;
import java.io.File;
import java.net.ServerSocket;
import java.util.Arrays;
import java.util.Random;
import org.junit.*;
import static org.junit.Assert.*;
import org.cojen.tupl.TestUtils;
import static org.cojen.tupl.repl.MessageReplicator.*;
/**
*
*
* @author Brian S O'Neill
*/
public class MessageReplicatorTest {
public static void main(String[] args) throws Exception {
org.junit.runner.JUnitCore.main(MessageReplicatorTest.class.getName());
}
private static final long COMMIT_TIMEOUT_NANOS = 10_000_000_000L;
@Before
public void setup() throws Exception {
}
@After
public void teardown() throws Exception {
if (mReplicators != null) {
for (Replicator repl : mReplicators) {
if (repl != null) {
repl.close();
}
}
}
TestUtils.deleteTempFiles(getClass());
}
private File[] mReplBaseFiles;
private int[] mReplPorts;
private ReplicatorConfig[] mConfigs;
private MessageReplicator[] mReplicators;
/**
* @return first is the leader
*/
private MessageReplicator[] startGroup(int members) throws Exception {
return startGroup(members, Role.OBSERVER, true);
}
/**
* @return first is the leader
*/
private MessageReplicator[] startGroup(int members, Role replicaRole, boolean waitToJoin)
throws Exception
{
if (members < 1) {
throw new IllegalArgumentException();
}
ServerSocket[] sockets = new ServerSocket[members];
for (int i=0; i<members; i++) {
sockets[i] = new ServerSocket(0);
}
mReplBaseFiles = new File[members];
mReplPorts = new int[members];
mConfigs = new ReplicatorConfig[members];
mReplicators = new MessageReplicator[members];
for (int i=0; i<members; i++) {
mReplBaseFiles[i] = TestUtils.newTempBaseFile(getClass());
mReplPorts[i] = sockets[i].getLocalPort();
mConfigs[i] = new ReplicatorConfig()
.baseFile(mReplBaseFiles[i])
.groupToken(1)
.localSocket(sockets[i]);
if (i > 0) {
mConfigs[i].addSeed(sockets[0].getLocalSocketAddress());
mConfigs[i].localRole(replicaRole);
}
MessageReplicator repl = MessageReplicator.open(mConfigs[i]);
mReplicators[i] = repl;
repl.start();
readyCheck: {
for (int trial=0; trial<100; trial++) {
Thread.sleep(100);
if (i == 0) {
// Wait to become leader.
Reader reader = repl.newReader(0, false);
if (reader == null) {
break readyCheck;
}
reader.close();
} else if (waitToJoin) {
// Wait to join the group.
Reader reader = repl.newReader(0, true);
reader.close();
if (reader.term() > 0) {
break readyCheck;
}
} else {
break readyCheck;
}
}
throw new AssertionError(i == 0 ? "No leader" : "Not joined");
}
}
return mReplicators;
}
@Test
public void oneMember() throws Exception {
MessageReplicator[] repls = startGroup(1);
assertTrue(repls.length == 1);
MessageReplicator repl = repls[0];
Reader reader = repl.newReader(0, false);
assertNull(reader);
reader = repl.newReader(0, true);
assertNotNull(reader);
Writer writer = repl.newWriter(0);
assertNotNull(writer);
long term = writer.term();
assertEquals(1, term);
assertEquals(term, reader.term());
assertEquals(0, writer.termStartIndex());
assertEquals(0, reader.termStartIndex());
assertEquals(Long.MAX_VALUE, writer.termEndIndex());
assertEquals(Long.MAX_VALUE, reader.termEndIndex());
byte[] message = "hello".getBytes();
assertTrue(writer.writeMessage(message));
assertEquals(writer.index(), writer.waitForCommit(writer.index(), 0));
TestUtils.fastAssertArrayEquals(message, reader.readMessage());
}
@Test
public void twoMembers() throws Exception {
MessageReplicator[] repls = startGroup(2);
assertTrue(repls.length == 2);
MessageReplicator repl = repls[0];
Reader reader = repl.newReader(0, false);
assertNull(reader);
reader = repl.newReader(0, true);
assertNotNull(reader);
Writer writer = repl.newWriter();
assertNotNull(writer);
Reader replica = repls[1].newReader(0, false);
assertNotNull(replica);
long term = writer.term();
assertTrue(term > 0);
assertEquals(term, reader.term());
assertEquals(term, replica.term());
assertEquals(0, writer.termStartIndex());
assertEquals(0, reader.termStartIndex());
assertEquals(0, replica.termStartIndex());
assertEquals(Long.MAX_VALUE, writer.termEndIndex());
assertEquals(Long.MAX_VALUE, reader.termEndIndex());
assertEquals(Long.MAX_VALUE, replica.termEndIndex());
byte[] message = "hello".getBytes();
assertTrue(writer.writeMessage(message));
long highIndex = writer.index();
assertEquals(highIndex, writer.waitForCommit(highIndex, COMMIT_TIMEOUT_NANOS));
TestUtils.fastAssertArrayEquals(message, reader.readMessage());
TestUtils.fastAssertArrayEquals(message, replica.readMessage());
message = "world!".getBytes();
assertTrue(writer.writeMessage(message));
highIndex = writer.index();
assertEquals(highIndex, writer.waitForCommit(highIndex, COMMIT_TIMEOUT_NANOS));
TestUtils.fastAssertArrayEquals(message, reader.readMessage());
TestUtils.fastAssertArrayEquals(message, replica.readMessage());
}
@Test
public void threeMembers() throws Exception {
MessageReplicator[] repls = startGroup(3);
assertTrue(repls.length == 3);
Writer writer = repls[0].newWriter();
Reader r0 = repls[0].newReader(0, true);
Reader r1 = repls[1].newReader(0, true);
Reader r2 = repls[2].newReader(0, true);
byte[][] messages = {"hello".getBytes(), "world!".getBytes()};
for (byte[] message : messages) {
assertTrue(writer.writeMessage(message));
long highIndex = writer.index();
assertTrue(highIndex <= writer.waitForCommit(highIndex, COMMIT_TIMEOUT_NANOS));
TestUtils.fastAssertArrayEquals(message, r0.readMessage());
TestUtils.fastAssertArrayEquals(message, r1.readMessage());
TestUtils.fastAssertArrayEquals(message, r2.readMessage());
}
}
@Test
public void variableMessageSizes() throws Exception {
variableMessageSizes(false);
}
@Test
public void variableMessageSizesPartial() throws Exception {
variableMessageSizes(true);
}
private void variableMessageSizes(boolean partial) throws Exception {
MessageReplicator[] repls = startGroup(3);
int[] sizes = {
0, 1, 10, 100, 127,
128, 129, 1000, 8190, 8191, 8192, 8193, 10000, 16383, 16384, 16385, 16510, 16511,
16512, 16513, 20000, 100_000
};
final long seed = 9823745;
Random rnd = new Random(seed);
Writer writer = repls[0].newWriter();
for (int size : sizes) {
byte[] message = TestUtils.randomStr(rnd, size);
assertTrue(writer.writeMessage(message));
}
long highIndex = writer.index();
assertEquals(highIndex, writer.waitForCommit(highIndex, COMMIT_TIMEOUT_NANOS));
byte[] buf = new byte[1001];
for (MessageReplicator repl : repls) {
rnd = new Random(seed);
Reader reader = repl.newReader(0, true);
for (int size : sizes) {
byte[] expected = TestUtils.randomStr(rnd, size);
byte[] actual;
if (!partial) {
actual = reader.readMessage();
} else {
int result = reader.readMessage(buf, 1, 1000);
if (result >= 0) {
actual = Arrays.copyOfRange(buf, 1, 1 + result);
} else {
try {
reader.readMessage();
fail();
} catch (IllegalStateException e) {
// Cannot read next message when partial exists.
}
assertNotEquals(-1, result);
actual = new byte[1000 + ~result];
System.arraycopy(buf, 1, actual, 0, 1000);
reader.readMessage(actual, 1000, ~result);
}
}
TestUtils.fastAssertArrayEquals(expected, actual);
}
reader.close();
}
}
@Test
public void largeGroupNoWaitToJoin() throws Exception {
final int count = 10;
MessageReplicator[] repls = startGroup(count, Role.STANDBY, false);
Writer writer = repls[0].newWriter();
Reader[] readers = new Reader[count];
for (int i=0; i<count; i++) {
readers[i] = repls[i].newReader(0, true);
}
for (int q=0; q<20; q++) {
byte[] message = ("hello-" + q).getBytes();
assertTrue(writer.writeMessage(message));
long highIndex = writer.index();
// Note: Actual commit index might be higher, because of control messages which
// were sent by the replication system for membership changes.
long commitIndex = writer.waitForCommit(highIndex, COMMIT_TIMEOUT_NANOS);
assertTrue("highIndex: " + highIndex + ", commitIndex: " + commitIndex,
commitIndex >= highIndex);
for (int j=0; j<readers.length; j++) {
Reader reader = readers[j];
byte[] actual;
while ((actual = reader.readMessage()) == null) {
// Reader was created at false term of 0. Move to the correct one.
reader.close();
reader = repls[j].newReader(reader.index(), true);
readers[j] = reader;
}
TestUtils.fastAssertArrayEquals(message, actual);
}
}
}
}
|
package org.myrobotlab.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import org.myrobotlab.arduino.BoardInfo;
import org.myrobotlab.arduino.Msg;
import org.myrobotlab.arduino.VirtualMsg;
import org.myrobotlab.arduino.virtual.Device;
import org.myrobotlab.arduino.virtual.MrlServo;
import org.myrobotlab.framework.QueueStats;
import org.myrobotlab.framework.Service;
import org.myrobotlab.sensor.EncoderData;
import org.myrobotlab.service.data.PinData;
import org.myrobotlab.service.data.SerialRelayData;
import org.myrobotlab.service.interfaces.MrlCommPublisher;
import org.myrobotlab.service.interfaces.SerialDataListener;
// @Ignore
public class VirtualArduinoTest extends AbstractServiceTest implements MrlCommPublisher, SerialDataListener {
private Msg msg = new Msg(this, null);
String testPort = "testPort";
Serial serial = (Serial)Runtime.start("dteSerial", "Serial");
@Override
public Service createService() {
// Runtime.setLogLevel("info");
VirtualArduino service = (VirtualArduino)Runtime.start("virtualArduino", "VirtualArduino");
return service;
}
@Override
public void testService() throws Exception {
// our local msg handle that parses the stream from the virtual arduino
// skip invoking in unit tests, instead directly call the callbacks to make unit tests easier.
msg.setInvoke(false);
// our service to test
VirtualArduino va = (VirtualArduino)service;
// connect to the test uart/DCE port
va.connect(testPort);
// virtual arduino listens on virtual port + .UART as the DCE side of the interface.
assertEquals(testPort + ".UART", va.getPortName());
// some basic validation stuff on the va..
assertNotNull(va.getPinList());
assertNotNull(va.board);
Serial serial = (Serial)Runtime.start("serial", "Serial");
// attach our test as a byte listener for the onBytes call.
serial.addByteListener(this);
// connect to the actual DTE side of the virtual serial port.
serial.connect(testPort);
Thread.sleep(100);
// TODO: We should probably wait for the begin message to be seen from the virtual arduino here before proceeding.
// servo attach method being written to the DTE side of the virtual port
serial.write(msg.servoAttach(0, 7, 180, -1, "s1"));
// TODO: there's a race condition here.. we seem to fail without a small sleep here!!!!
// we need to let the virtual arduinos catch up and actually add the device.
Thread.sleep(50);
// get a handle to the virtual device that we just attached.
Device d = va.getDevice(0);
// validate the device exists.
assertNotNull(d);
// make sure the device is actually a servo
assertEquals(Msg.DEVICE_TYPE_SERVO, d.type);
serial.write(msg.servoMoveToMicroseconds(0, 1500));
MrlServo s = (MrlServo)d;
// TODO: there's a race condition here. it takes a moment for the virtual device to respond.
Thread.sleep(50);
assertEquals(s.targetPosUs, 1500);
serial.write(msg.servoSetVelocity(0, 22));
Thread.sleep(50);
assertEquals(s.velocity, 22);
// other Servo methods to test.
serial.write(msg.servoAttachPin(0, 11));
Thread.sleep(50);
assertEquals(11, s.pin);
serial.write(msg.servoDetachPin(0));
Thread.sleep(50);
assertFalse(s.enabled);
va.disconnect();
Thread.sleep(50);
assertFalse(va.isConnected());
// TODO: we could test other virtual devices.
// what else can we do?
}
// These are all of the messages that the MrlComm/MrlCommIno can publish back to the arduino service.
// none of these will get called unlesss this test gets the onBytes called that passes the returned stream down to the Msg.java onBytes.
@Override
public BoardInfo publishBoardInfo(Integer version, Integer boardTypeId, Integer microsPerLoop, Integer sram, Integer activePins, int[] deviceSummary) {
return null;
}
@Override
public void publishAck(Integer function) {
log.info("Publish Ack for function {}", VirtualMsg.methodToString(function));
}
@Override
public int[] publishCustomMsg(int[] msg) {
log.info("Publish Custom Msg: {}", msg);
return msg;
}
@Override
public String publishDebug(String debugMsg) {
log.info("Publish Debug Message {}", debugMsg);
return debugMsg;
}
@Override
public void publishEcho(float myFloat, int myByte, float secondFloat) {
log.info("Publish Echo myFloat:{} myByte:{} secondFloat:{}", myFloat, myByte, secondFloat);
}
@Override
public EncoderData publishEncoderData(Integer deviceId, Integer position) {
// mocked out encoder data to publish.
log.info("Device ID:{} Position:{}", deviceId, position);
EncoderData data = new EncoderData("Test-" + deviceId, null, new Double(position), new Double(position));
return data;
}
@Override
public void publishI2cData(Integer deviceId, int[] data) {
log.info("Publish I2C - Device ID: {} Data: {}", deviceId, data);
}
@Override
public SerialRelayData publishSerialData(Integer deviceId, int[] data) {
log.info("Publish Serial Data: {} {}", deviceId, data);
SerialRelayData srd = new SerialRelayData(deviceId, data);
return srd;
}
@Override
public Integer publishServoEvent(Integer deviceId, Integer eventType, Integer currentPos, Integer targetPos) {
log.info("Publish Servo Event - DeviceId:{} EventType:{} CurrentPos:{} TargetPos:{}", deviceId, eventType, currentPos, targetPos);
return currentPos;
}
@Override
public void publishMrlCommBegin(Integer version) {
assertEquals(VirtualMsg.MRLCOMM_VERSION, version.intValue());
}
@Override
public String publishMRLCommError(String errorMsg) {
log.warn("MRL Comm Error : {}", errorMsg);
return errorMsg;
}
@Override
public PinData[] publishPinArray(int[] data) {
log.info("Publish Pin Array: {}", data);
// TODO: this has some complex logic in Arduino to replicate/test here.
return null;
}
@Override
public Integer publishUltrasonicSensorData(Integer deviceId, Integer echoTime) {
log.info("Publish Ultrasonice Sensor Data: {} {}", deviceId, echoTime);
return echoTime;
}
@Override
public void onBytes(byte[] data) {
// It's the responsibility of the MrlCommPublisher to relay serial bytes / events to the msg.java class
msg.onBytes(data);
}
@Override
public QueueStats publishStats(QueueStats stats) {
// TODO NoOp in the unit test for now.
return stats;
}
@Override
public void updateStats(QueueStats stats) {
// TODO: NoOp in the unit test for now.
}
@Override
public void onConnect(String portName) {
// TODO: should we test this? it's the responsibility of the MrlCommPublisher to pass serial events to the msg class.
msg.onConnect(portName);
}
@Override
public void onDisconnect(String portName) {
// TODO: should we test this? it's the responsibility of the MrlCommPublisher to pass serial events to the msg class.
msg.onDisconnect(portName);
}
@Override
public void ackTimeout() {
// TODO: validate something...
log.warn("Ack Timeout was seen!!!!");
}
@Override
public Object invoke(String method, Object... params) {
log.warn("Don't invoke in a unit test!!!!!!");
return null;
}
}
|
package ru.redcraft.pinterest4j;
import java.io.File;
import java.io.FileInputStream;
import java.net.URISyntaxException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.log4j.Logger;
import ru.redcraft.pinterest4j.core.PinterestImpl;
import ru.redcraft.pinterest4j.exceptions.PinterestAuthException;
public class PinterestTestBase {
protected static TestUserInfo id1, id2, idAutherror;
protected static Pinterest pinterest1, pinterest2;
protected static String imageLink;
protected static String pinterest1Twitter;
protected static String pinterest1Facebook;
protected static File imageFile;
protected static String webLink;
private static final String BUNDLE_NAME = "test";
private static final Logger log = Logger.getLogger(PinterestTestBase.class);
protected static class TestUserInfo {
private final String login;
private final String password;
TestUserInfo(String login, String password) {
this.login = login;
this.password = password;
log.trace(String.format("Loaded config for user: ", this));
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
@Override
public String toString() {
return "TestUserInfo [login=" + login + ", password=" + password
+ "]";
}
}
static {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
public X509Certificate[] getAcceptedIssuers(){return null;}
public void checkClientTrusted(X509Certificate[] certs, String authType){}
public void checkServerTrusted(X509Certificate[] certs, String authType){}
}};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
;
}
ResourceBundle rb = null;
try {
rb = new PropertyResourceBundle(new FileInputStream("/opt/redcraft/pinterest4j.properties"));
} catch (Exception e) {
rb = ResourceBundle.getBundle(BUNDLE_NAME);
}
id1 = getTestUserForPrefix(rb, "pinterest1");
id2 = getTestUserForPrefix(rb, "pinterest2");
idAutherror = getTestUserForPrefix(rb, "autherror");
try {
pinterest1 = new PinterestImpl(id1.getLogin(), id1.getPassword());
pinterest2 = new PinterestImpl(id2.getLogin(), id2.getPassword());
} catch (PinterestAuthException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
pinterest1Twitter = rb.getString("pinterest1.twitter");
pinterest1Facebook = rb.getString("pinterest1.facebook");
imageLink = rb.getString("pin.image.link");
webLink = rb.getString("pin.link");
try {
imageFile = new File(ClassLoader.getSystemResource("pin_image.jpg").toURI());
} catch(URISyntaxException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
clean();
}
private static TestUserInfo getTestUserForPrefix(ResourceBundle rb, String prefix) {
String login = rb.getString(prefix + ".login");
String password = rb.getString(prefix + ".password");
return new TestUserInfo(login, password);
}
private static void clean() {
cleanAccount(pinterest1);
cleanAccount(pinterest2);
pinterest1.getUser().refresh();
pinterest2.getUser().refresh();
}
private static void cleanAccount(Pinterest pinterest) {
for(Board board : pinterest.getUser().getBoards()) {
pinterest.deleteBoard(board);
}
for(Pin pin : pinterest.getUser().getLikes()) {
pinterest.unlikePin(pin);
}
for(User user : pinterest.getUser().getFollowing()) {
pinterest.unfollowUser(user);
}
}
}
|
package com.mysema.query.apt;
import com.mysema.query.apt.util.TypeInfo;
import com.sun.mirror.declaration.FieldDeclaration;
/**
* FieldDecl represents a field / property in a query domain type.
*
* @author tiwe
* @version $Id$
*/
public class Field implements Comparable<Field> {
/**
* The Enum Type.
*/
public enum Type {
BOOLEAN,
COMPARABLE,
ENTITY,
ENTITYLIST,
ENTITYCOLLECTION,
ENTITYMAP,
NUMERIC,
SIMPLE,
SIMPLELIST,
SIMPLECOLLECTION,
SIMPLEMAP,
STRING
}
private final Type fieldType;
private String name, realName, keyTypeName, typeName, typePackage, simpleTypeName;
/**
* Construct a Field instance from the given FieldDeclaration instance
* @param field
*/
public Field(FieldDeclaration field) {
TypeInfo typeInfo = new TypeInfo(field.getType());
this.name = javaSafe(field.getSimpleName());
this.realName = realName(name);
this.keyTypeName = typeInfo.getKeyTypeName();
this.typeName = typeInfo.getFullName();
this.typePackage = typeInfo.getPackageName();
this.simpleTypeName = typeInfo.getSimpleName();
this.fieldType = typeInfo.getFieldType();
}
/**
* Construct a new Field instance
* @param name normalized field name
* @param realName real fieldName
* @param keyTypeName key type name for Map types
* @param typeName full type name (with package)
* @param simpleTypeName simple type name (local)
* @param fieldType
*/
public Field(String name, String realName, String keyTypeName, String typeName,
String simpleTypeName, Type fieldType){
this.name = javaSafe(name);
this.realName = realName(realName);
this.keyTypeName = keyTypeName;
this.typeName = typeName;
this.simpleTypeName = simpleTypeName;
this.fieldType = fieldType;
}
private static String javaSafe(String name){
// TODO : improve this
if (name.equals("private")){
return "prvate";
}else if (name.equals("public")){
return "pblic";
}else{
return name;
}
}
private static String realName(String name){
// TODO : improve this
if (name.equals("prvate")){
return "private";
}else if (name.equals("pblic")){
return "public";
}else{
return name;
}
}
public int compareTo(Field o) {
return name.compareTo(o.name);
}
public boolean equals(Object o) {
return o instanceof Field && name.equals(((Field) o).name);
}
public Type getFieldType() {
return fieldType;
}
/**
* Returns the type name of key element for Map fields
* @return
*/
public String getKeyTypeName() {
return keyTypeName;
}
public String getName() {
return name;
}
public String getRealName(){
return realName;
}
/**
* Returns the simple name of the field type
* @return
*/
public String getSimpleTypeName() {
return simpleTypeName;
}
/**
* Returns the full name of the field type
* @return
*/
public String getTypeName() {
return typeName;
}
public String getTypePackage(){
return typePackage;
}
public int hashCode() {
return name.hashCode();
}
}
|
package com.chadimasri.tests.helpers;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class H2Helper {
private static final int MAX_RECONNECTION_ATTEMPTS = 20;
public static Connection getH2Connection(String host, int port) throws SQLException {
int retries = 0;
while (true) {
try {
return DriverManager.getConnection("jdbc:h2:tcp://" + host + ":" + port + "/mem:db;DB_CLOSE_DELAY=-1");
} catch (SQLException e) {
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
}
retries++;
if (retries > MAX_RECONNECTION_ATTEMPTS) {
throw e;
}
}
}
}
public static void insertNames(Connection connection, List<String> names) throws SQLException {
try (Statement stat = connection.createStatement()) {
stat.execute("CREATE TABLE NAMES(ID INT AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(255))");
}
try (PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO NAMES(NAME) VALUES(?)")) {
for (String name : names) {
preparedStatement.setString(1, name);
preparedStatement.execute();
}
}
}
public static List<String> readNames(Connection connection) throws SQLException {
List<String> names = new ArrayList<>();
try (Statement stat = connection.createStatement();
ResultSet rs = stat.executeQuery("SELECT NAME FROM NAMES")) {
while (rs.next()) {
names.add(rs.getString("NAME"));
}
}
return names;
}
}
|
package com.exedio.cope.pattern;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import com.exedio.cope.BooleanField;
import com.exedio.cope.Cope;
import com.exedio.cope.DataField;
import com.exedio.cope.DateField;
import com.exedio.cope.Item;
import com.exedio.cope.ItemField;
import com.exedio.cope.LongField;
import com.exedio.cope.Model;
import com.exedio.cope.Pattern;
import com.exedio.cope.Query;
import com.exedio.cope.SetValue;
import com.exedio.cope.Type;
import com.exedio.cope.instrument.Wrapper;
import com.exedio.cope.util.ReactivationConstructorDummy;
public final class Dispatcher extends Pattern
{
private static final String ENCODING = "utf8";
private final int failureLimit;
private final int searchSize;
private final BooleanField pending = new BooleanField().defaultTo(true);
private final DateField successDate = new DateField().optional();
private final LongField successElapsed = new LongField().optional();
ItemField<?> failureParent = null;
PartOf<?> failureFailures = null;
final DateField failureDate = new DateField().toFinal();
final LongField failureElapsed = new LongField();
final DataField failureCause = new DataField().toFinal();
Type<Failure> failureType = null;
public Dispatcher()
{
this(5, 100);
}
public Dispatcher(final int failureLimit, final int searchSize)
{
this.failureLimit = failureLimit;
this.searchSize = searchSize;
if(failureLimit<1)
throw new IllegalArgumentException("failureLimit must be greater zero, but was " + failureLimit + ".");
if(searchSize<1)
throw new IllegalArgumentException("searchSize must be greater zero, but was " + searchSize + ".");
addSource(pending, "Pending");
addSource(successDate, "SuccessDate");
addSource(successElapsed, "SuccessElapsed");
}
@Override
protected void initialize()
{
final Type<?> type = getType();
if(!Dispatchable.class.isAssignableFrom(type.getJavaClass()))
throw new ClassCastException(
"type of " + getID() + " must implement " + Dispatchable.class +
", but was " + type.getJavaClass().getName());
failureParent = type.newItemField(ItemField.DeletePolicy.CASCADE).toFinal();
failureFailures = PartOf.newPartOf(failureParent);
final LinkedHashMap<String, com.exedio.cope.Feature> features = new LinkedHashMap<String, com.exedio.cope.Feature>();
features.put("parent", failureParent);
features.put("failures", failureFailures);
features.put("date", failureDate);
features.put("elapsed", failureElapsed);
features.put("cause", failureCause);
failureType = newSourceType(Failure.class, features, "Failure");
}
public int getFailureLimit()
{
return failureLimit;
}
public int getSearchSize()
{
return searchSize;
}
public BooleanField getPending()
{
return pending;
}
public DateField getSuccessDate()
{
return successDate;
}
public LongField getSuccessElapsed()
{
return successElapsed;
}
public <P extends Item> ItemField<P> getFailureParent(final Class<P> parentClass)
{
assert failureParent!=null;
return failureParent.as(parentClass);
}
public PartOf getFailureFailures()
{
return failureFailures;
}
public DateField getFailureDate()
{
return failureDate;
}
public LongField getFailureElapsed()
{
return failureElapsed;
}
public DataField getFailureCause()
{
return failureCause;
}
public Type<Failure> getFailureType()
{
assert failureType!=null;
return failureType;
}
public interface Interrupter
{
boolean isRequested();
}
@Override
public List<Wrapper> getWrappers()
{
final ArrayList<Wrapper> result = new ArrayList<Wrapper>();
result.addAll(super.getWrappers());
result.add(
new Wrapper("dispatch").
addComment("Dispatch by {0}.").
setReturn(int.class, "the number of successfully dispatched items").
addParameter(Interrupter.class, "interrupter").
setStatic());
result.add(
new Wrapper("isPending").
addComment("Returns, whether this item is yet to be dispatched by {0}.").
setReturn(boolean.class));
result.add(
new Wrapper("getSuccessDate").
addComment("Returns the date, this item was successfully dispatched by {0}.").
setReturn(Date.class));
result.add(
new Wrapper("getSuccessElapsed").
addComment("Returns the milliseconds, this item needed to be successfully dispatched by {0}.").
setReturn(Long.class));
result.add(
new Wrapper("getFailures").
addComment("Returns the failed attempts to dispatch this item by {0}.").
setReturn(Wrapper.generic(List.class, Failure.class)));
result.add(
new Wrapper("getFailureParent").
addComment("Returns the parent field of the failure type of {0}.").
setReturn(Wrapper.generic(ItemField.class, Wrapper.ClassVariable.class)).
setMethodWrapperPattern("{1}FailureParent").
setStatic());
return Collections.unmodifiableList(result);
}
/**
* @return the number of successfully dispatched items
*/
public <P extends Item> int dispatch(final Class<P> parentClass, final Interrupter interrupter)
{
final Type<P> type = getType().castType(parentClass);
final Type.This<P> typeThis = type.getThis();
final Model model = type.getModel();
final String id = getID();
P lastDispatched = null;
int result = 0;
while(true)
{
final List<P> toDispatch;
try
{
model.startTransaction(id + " search");
final Query<P> q = type.newQuery(pending.equal(true));
if(lastDispatched!=null)
q.narrow(typeThis.greater(lastDispatched));
q.setOrderBy(typeThis, true);
q.setLimit(0, searchSize);
toDispatch = q.search();
model.commit();
}
finally
{
model.rollbackIfNotCommitted();
}
if(toDispatch.isEmpty())
break;
for(final P item : toDispatch)
{
if(interrupter!=null && interrupter.isRequested())
return result;
lastDispatched = item;
final String itemID = item.getCopeID();
try
{
model.startTransaction(id + " dispatch " + itemID);
if(!isPending(item))
{
System.out.println("Already dispatched " + itemID + " by " + id + ", probably due to concurrent dispatching.");
continue;
}
final long start = System.currentTimeMillis();
try
{
((Dispatchable)item).dispatch(this);
final long elapsed = System.currentTimeMillis() - start;
item.set(
pending.map(false),
successDate.map(new Date(start)),
successElapsed.map(elapsed));
model.commit();
result++;
}
catch(Exception cause)
{
final long elapsed = System.currentTimeMillis() - start;
model.rollbackIfNotCommitted();
model.startTransaction(id + " register failure " + itemID);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream out;
try
{
out = new PrintStream(baos, false, ENCODING);
}
catch(UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
cause.printStackTrace(out);
out.close();
final ItemField<P> failureParent = this.failureParent.as(parentClass);
failureType.newItem(
failureParent.map(item),
failureDate.map(new Date(start)),
failureElapsed.map(elapsed),
failureCause.map(baos.toByteArray()));
final boolean done = failureType.newQuery(failureParent.equal(item)).total()>=failureLimit;
if(done)
pending.set(item, false);
model.commit();
if(done)
((Dispatchable)item).notifyFinalFailure(this, cause);
}
}
finally
{
model.rollbackIfNotCommitted();
}
}
}
return result;
}
public boolean isPending(final Item item)
{
return pending.getMandatory(item);
}
public Date getSuccessDate(final Item item)
{
return successDate.get(item);
}
public Long getSuccessElapsed(final Item item)
{
return successElapsed.get(item);
}
public List<Failure> getFailures(final Item item)
{
return failureType.search(Cope.equalAndCast(failureParent, item), failureType.getThis(), true);
}
public static final class Failure extends Item
{
private static final long serialVersionUID = 1l;
Failure(final SetValue[] setValues, final Type<? extends Item> type)
{
super(setValues, type);
assert type!=null;
}
Failure(final ReactivationConstructorDummy reactivationDummy, final int pk, final Type<? extends Item> type)
{
super(reactivationDummy, pk, type);
}
public Dispatcher getPattern()
{
return (Dispatcher)getCopeType().getPattern();
}
public Item getParent()
{
return getPattern().failureParent.get(this);
}
public Date getDate()
{
return getPattern().failureDate.get(this);
}
public long getElapsed()
{
return getPattern().failureElapsed.getMandatory(this);
}
public String getCause()
{
try
{
return new String(getPattern().failureCause.get(this).asArray(), ENCODING);
}
catch(UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
}
}
}
|
package cgeo.geocaching;
import cgeo.geocaching.geopoint.Geopoint;
import android.test.AndroidTestCase;
import junit.framework.Assert;
@SuppressWarnings("static-method")
public class cgBaseTest extends AndroidTestCase {
public void testReplaceWhitespaces() {
Assert.assertEquals("foo bar baz ", cgBase.replaceWhitespace(new String(" foo\n\tbar \r baz ")));
}
public void testElevation() {
Assert.assertEquals(125.663703918457, cgBase.getElevation(new Geopoint(48.0, 2.0)), 0.1);
}
}
|
package nl.mpi.kinnate.ui.menu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import nl.mpi.kinnate.ui.window.AbstractDiagramManager;
public class DocumentNewMenu extends JMenu implements ActionListener {
AbstractDiagramManager diagramWindowManager;
public enum DocumentType {
Freeform("Freeform Diagram"),
KinTerms("Kin Terms Diagram"),
Query("Kin Type String Query"),
ArchiveLinker("Archive Data Linker"),
EntitySearch("Entity Search"),
CustomQuery("Custom Metadata"),
Simple("Standard Diagram");
private String displayName;
private DocumentType(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
}
public DocumentNewMenu(AbstractDiagramManager diagramWindowManager) {
this.diagramWindowManager = diagramWindowManager;
for (DocumentType documentType : DocumentType.values()) {
JMenuItem menuItem = new JMenuItem(documentType.getDisplayName());
menuItem.setActionCommand(documentType.name());
menuItem.addActionListener(this);
this.add(menuItem);
}
}
public void actionPerformed(ActionEvent e) {
DocumentType documentType = DocumentType.valueOf(e.getActionCommand());
diagramWindowManager.newDiagram(documentType);
}
}
|
package org.intermine.api.bag;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.InterMineException;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.model.InterMineObject;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsBatches;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.api.template.ApiTemplate;
import org.intermine.api.template.TemplateManager;
import org.intermine.util.CollectionUtil;
import org.intermine.util.TypeUtil;
/**
* For a given list of input strings search for objects using default and configured queries for a
* particular type.
*
* @author Richard Smith
*/
public class BagQueryRunner
{
private static final Logger LOG = Logger.getLogger(BagQueryRunner.class);
private ObjectStore os;
private Model model;
private Map<String, List<FieldDescriptor>> classKeys;
private BagQueryConfig bagQueryConfig;
private TemplateManager templateManager;
private static final boolean MATCHES_ARE_ISSUES_DEFAULT = true;
/**
* Construct with configured bag queries and a map of type -> key fields.
*
* @param os the ObjectStore to run queries on
* @param classKeys the class keys Map
* @param bagQueryConfig the configuration for running queries
* @param templateManager the InterMine template manager to access conversion templates a list
* of template queries to be used when type converting results
*/
public BagQueryRunner(ObjectStore os, Map<String, List<FieldDescriptor>> classKeys,
BagQueryConfig bagQueryConfig, TemplateManager templateManager) {
this.model = os.getModel();
this.os = os;
this.classKeys = classKeys;
this.bagQueryConfig = bagQueryConfig;
this.templateManager = templateManager;
}
/**
* Given an input list of string identifiers search for corresponding objects. First run a
* default query then any queries configured for the specified type.
*
* @param type an unqualified class name to search for objects
* @param input a list of strings to query
* @param extraFieldValue the value used when adding an extra constraint to the bag query,
* configured in BagQueryConfig (e.g. if connectField is "organism", the extraClassName is
* "Organism" and the constrainField is "name", the extraFieldValue might be "Drosophila
* melanogaster")
* @param doWildcards true if the strings should be evaluated as wildcards
* @return the matches, issues and unresolved input
* @throws ClassNotFoundException if the type isn't in the model
* @throws InterMineException if there is any other exception
*/
public BagQueryResult searchForBag(String type, List<String> input, String extraFieldValue,
boolean doWildcards) throws ClassNotFoundException, InterMineException {
return search(type, input, extraFieldValue, doWildcards, false);
}
/**
* Given an input list of string identifiers search for corresponding objects. First run a
* default query then any queries configured for the specified type.
*
* @param type an unqualified class name to search for objects
* @param input a list of strings to query
* @param extraFieldValue the value used when adding an extra constraint to the bag query,
* configured in BagQueryConfig (e.g. if connectField is "organism", the extraClassName is
* "Organism" and the constrainField is "name", the extraFieldValue might be "Drosophila
* melanogaster")
* @param doWildcards true if the strings should be evaluated as wildcards
* @param caseSensitive true if the strings have to match case too
* @return the matches, issues and unresolved input
* @throws ClassNotFoundException if the type isn't in the model
* @throws InterMineException if there is any other exception
*/
public BagQueryResult search(String type, List<String> input, String extraFieldValue,
boolean doWildcards, boolean caseSensitive)
throws ClassNotFoundException, InterMineException {
Map<String, String> lowerCaseInput = new HashMap<String, String>();
List<String> cleanInput = new ArrayList<String>();
List<String> wildcardInput = new ArrayList<String>();
Map<String, Pattern> patterns = new HashMap<String, Pattern>();
for (String inputString : input) {
if (StringUtils.isNotEmpty(inputString)) {
// no wildcards OR single * (if single *, treat like a string)
if (inputString.indexOf('*') == -1 || !doWildcards || inputString.equals("*")) {
if (!lowerCaseInput.containsKey(inputString.toLowerCase())) {
cleanInput.add(inputString);
lowerCaseInput.put(inputString.toLowerCase(), inputString);
}
// wildcard + a string
} else {
wildcardInput.add(inputString);
patterns.put(inputString, Pattern.compile(inputString.toLowerCase()
.replaceAll("\\*", "\\.\\*")));
}
}
}
// TODO tidy up using type String and Class
// TODO BagQueryResult.getUnresolved() needs to return a map from input
// to null (if not found) or a set of objects.
// or just leave as a list of identifiers and objects of the qrong type
// CollectionUtil.groupByClass will sort out the strings and types
Class<?> typeCls = Class.forName(model.getPackageName() + "." + type);
List<BagQuery> queries = getBagQueriesForType(bagQueryConfig, typeCls.getName());
Set<String> unresolved = new LinkedHashSet<String>(cleanInput);
Set<String> wildcardUnresolved = new LinkedHashSet<String>(wildcardInput);
// unmodified list of identifiers uploaded
Set<String> unresolvedOriginal = new LinkedHashSet<String>(cleanInput);
Set<String> wildcardUnresolvedOriginal = new LinkedHashSet<String>(wildcardInput);
BagQueryResult bqr = new BagQueryResult();
// return first record ONLY for identifier. otherwise, run all queries and return all
boolean matchOnFirst = bagQueryConfig.getMatchOnFirst();
for (BagQuery bq : queries) {
// run the next query on identifiers not yet resolved
// OR all identifiers if matchOnFirst = FALSE
if (!unresolved.isEmpty() || !matchOnFirst) {
Map<String, Set<Integer>> resMap = new HashMap<String, Set<Integer>>();
Query q = null;
try {
if (matchOnFirst) {
q = bq.getQuery(unresolved, extraFieldValue);
} else {
q = bq.getQuery(unresolvedOriginal, extraFieldValue);
}
Results res = os.execute(q, 10000, true, true, false);
for (Object rowObj : res) {
ResultsRow<?> row = (ResultsRow<?>) rowObj;
Integer id = (Integer) row.get(0);
for (int i = 1; i < row.size(); i++) {
Object fieldObject = row.get(i);
if (fieldObject != null) {
if (!(fieldObject instanceof String)) {
fieldObject = fieldObject.toString();
}
String field = (String) fieldObject;
String lowerField = field.toLowerCase();
if (caseSensitive) {
if (cleanInput.contains(field)) {
processMatch(resMap, unresolved, id, field);
}
} else if (lowerCaseInput.containsKey(lowerField)) {
// because we are converting to lower case we need to match
// to original input so that 'h' matches 'H' and 'h' becomes
// a duplicate.
String originalInput = lowerCaseInput.get(lowerField);
processMatch(resMap, unresolved, id, originalInput);
}
}
}
}
} catch (IllegalArgumentException e) {
// Query couldn't handle extra value
}
addResults(resMap, unresolved, bqr, bq.getMessage(), typeCls, false,
matchOnFirst, bq.matchesAreIssues());
}
if (!wildcardInput.isEmpty()) {
Map<String, Set<Integer>> resMap = new HashMap<String, Set<Integer>>();
try {
Query q = bq.getQueryForWildcards(wildcardInput, extraFieldValue);
Results res = os.execute(q, ResultsBatches.DEFAULT_BATCH_SIZE, true, true,
false);
for (Object rowObj : res) {
ResultsRow<?> row = (ResultsRow<?>) rowObj;
Integer id = (Integer) row.get(0);
for (int i = 1; i < row.size(); i++) {
String field = "" + row.get(i);
String lowerField = field.toLowerCase();
for (String wildcard : wildcardInput) {
Pattern pattern = patterns.get(wildcard);
if (pattern.matcher(lowerField).matches()) {
Set<Integer> ids = resMap.get(wildcard);
if (ids == null) {
ids = new LinkedHashSet<Integer>();
resMap.put(wildcard, ids);
}
ids.add(id);
// we have matched at least once with wildcard
wildcardUnresolved.remove(wildcard);
}
}
}
}
for (Map.Entry<String, Set<Integer>> entry : resMap.entrySet()) {
// This is a dummy issue just to give a message when running queries
bqr.addIssue(BagQueryResult.WILDCARD, bq.getMessage(),
entry.getKey(), new ArrayList<Object>(entry.getValue()));
if (matchOnFirst) {
addResults(resMap, wildcardUnresolved, bqr, bq.getMessage(),
typeCls, true, matchOnFirst, bq.matchesAreIssues());
} else {
addResults(resMap, wildcardUnresolvedOriginal, bqr, bq.getMessage(),
typeCls, true, matchOnFirst, bq.matchesAreIssues());
}
}
} catch (IllegalArgumentException e) {
LOG.error("Error running bag query lookup: ", e);
// Query couldn't handle extra value
}
}
}
unresolved.addAll(wildcardUnresolved);
Map<String, ?> unresolvedMap = new HashMap<String, Object>();
for (String unresolvedStr : unresolved) {
unresolvedMap.put(unresolvedStr, null);
}
bqr.getUnresolved().putAll(unresolvedMap);
return bqr;
}
private void processMatch(Map<String, Set<Integer>> resMap, Set<String> unresolved,
Integer id, String field) {
Set<Integer> ids = resMap.get(field);
if (ids == null) {
ids = new LinkedHashSet<Integer>();
resMap.put(field, ids);
}
ids.add(id);
unresolved.remove(field);
}
/**
* Add results from resMap to a a BagQueryResults object.
*
* @throws InterMineException
*/
private void addResults(Map<String, Set<Integer>> resMap, Set<String> unresolved,
BagQueryResult bqr, String msg, Class<?> type, boolean areWildcards,
boolean matchOnFirst, boolean matchesAreIssues) throws InterMineException {
Map<String, Set<Object>> objsOfWrongType = new HashMap<String, Set<Object>>();
// Gather together all the id lookups and perform them in one.
Map<Integer, InterMineObject> fetchedObjects = new HashMap<Integer, InterMineObject>();
Set<Integer> idsToFetch = new HashSet<Integer>();
try {
for (Map.Entry<String, Set<Integer>> resEntry : resMap.entrySet()) {
if (matchesAreIssues || (resEntry.getValue().size() > 1)) {
idsToFetch.addAll(resEntry.getValue());
}
}
List<InterMineObject> idsFetched = os.getObjectsByIds(idsToFetch);
for (InterMineObject fetchedObject : idsFetched) {
fetchedObjects.put(fetchedObject.getId(), fetchedObject);
}
} catch (ObjectStoreException e) {
throw new InterMineException("can't fetch: " + idsToFetch, e);
}
for (Map.Entry<String, Set<Integer>> entry : resMap.entrySet()) {
String input = entry.getKey();
Set<Integer> ids = entry.getValue();
boolean resolved = true;
if (!matchesAreIssues) {
// if matches are not issues then each entry will be a match or a duplicate
if (ids.size() == 1) {
bqr.addMatch(input, ids.iterator().next());
} else if (!areWildcards) {
List<Object> objs = new ArrayList<Object>();
for (Integer objectId : ids) {
Object obj = fetchedObjects.get(objectId);
if (obj == null) {
throw new NullPointerException("Could not find object with ID "
+ objectId);
}
objs.add(obj);
}
bqr.addIssue(BagQueryResult.DUPLICATE, msg, entry.getKey(), objs);
}
} else {
List<Object> objs = new ArrayList<Object>();
Set<Object> localObjsOfWrongType = new HashSet<Object>();
// we have a list of objects that result from some query, divide into any that
// match the type of the bag to be created and candidates for conversion
for (Integer objectId : ids) {
InterMineObject obj = fetchedObjects.get(objectId);
if (obj == null) {
throw new NullPointerException("Could not find object with ID " + objectId);
}
if (type.isInstance(obj)) {
objs.add(obj);
} else {
localObjsOfWrongType.add(obj);
}
}
if (!objs.isEmpty()) {
// we have a list of objects, if any match the type then add to bqr as an issue
// discard objects that matched a different type
if (objs.size() == 1) {
bqr.addIssue(BagQueryResult.OTHER, msg, input, objs);
} else if (!areWildcards) {
bqr.addIssue(BagQueryResult.DUPLICATE, msg, input, objs);
}
} else {
// all wrong, allow conversion attempts
resolved = false;
objsOfWrongType.put(input, localObjsOfWrongType);
}
}
if (resolved && matchOnFirst) {
unresolved.remove(input);
}
}
// now objsOfWrongType contains all wrong types found for this query, try converting
convertObjects(bqr, msg, type, objsOfWrongType);
bqr.getUnresolved().putAll(objsOfWrongType);
}
/**
* Find any objects in the objsOfWrongType Map that can be converted to the destination type,
* add them to bqr as TYPE_CONVERTED issues and remove them from objsOfWrongType.
*/
private void convertObjects(BagQueryResult bqr, String msg, Class<?> type,
Map<String, Set<Object>> objsOfWrongType)
throws InterMineException {
if (!objsOfWrongType.isEmpty()) {
// group objects by class
Map<InterMineObject, Set<String>> objectToInput =
new HashMap<InterMineObject, Set<String>>();
for (Map.Entry<String, Set<Object>> entry : objsOfWrongType.entrySet()) {
String input = entry.getKey();
for (Object o : entry.getValue()) {
InterMineObject imo = (InterMineObject) o;
Set<String> inputSet = objectToInput.get(imo);
if (inputSet == null) {
inputSet = new HashSet<String>();
objectToInput.put(imo, inputSet);
}
inputSet.add(input);
}
}
Map<Class<?>, List<InterMineObject>> objTypes =
CollectionUtil.groupByClass(objectToInput.keySet(), true);
for (Class<?> fromClass : objTypes.keySet()) {
List<InterMineObject> candidateObjs = objTypes.get(fromClass);
// we may have already converted some of these types, remove any that have been.
List<Integer> idsToConvert = new ArrayList<Integer>();
for (InterMineObject candidate : candidateObjs) {
if (objectToInput.containsKey(candidate)) {
idsToConvert.add(candidate.getId());
}
}
// there was nothing to convert for this class
if (idsToConvert.isEmpty()) {
continue;
}
// try to convert objects to target type
Map<InterMineObject, List<InterMineObject>> convertedObjsMap =
TypeConverter.getConvertedObjectMap(getConversionTemplates(),
fromClass, type, idsToConvert, os);
if (convertedObjsMap == null) {
// no conversion found
continue;
}
// loop over the old objects
for (InterMineObject origObj : convertedObjsMap.keySet()) {
boolean toRemove = false;
// then for each new object ...
for (InterMineObject convertedObj : convertedObjsMap.get(origObj)) {
ConvertedObjectPair convertedPair = new ConvertedObjectPair(origObj,
convertedObj);
List<Object> objPairList = new ArrayList<Object>();
objPairList.add(convertedPair);
// remove this object so we don't try to convert it again
toRemove = true;
// make an issue for each input identifier that matched the objects in
// this old/new pair
for (String origInputString : objectToInput.get(origObj)) {
bqr.addIssue(BagQueryResult.TYPE_CONVERTED,
msg + " found by converting from x",
origInputString, objPairList);
objsOfWrongType.remove(origInputString);
}
}
if (toRemove) {
objectToInput.remove(origObj);
}
}
}
}
}
// temporary method - will be replaced by BagQueryHelper method
private List<BagQuery> getBagQueriesForType(BagQueryConfig config, String type) {
List<BagQuery> queries = new ArrayList<BagQuery>();
// some queries should run before the default
queries.addAll(config.getPreDefaultBagQueries(TypeUtil.unqualifiedName(type)));
// create the default query and put it first in the list
queries.add(new BagQuery(config, model, classKeys, type));
// add any queries that are configured for this type
queries.addAll(config.getBagQueries(TypeUtil.unqualifiedName(type)));
return queries;
}
/**
* Fetch conversion template queries from the template manager. This is in a separate method
* so we can override and easily use a custom list of templates for testing.
* @return a list of conversion templates
*/
protected List<ApiTemplate> getConversionTemplates() {
return templateManager.getConversionTemplates();
}
}
|
package org.flymine.web;
import servletunit.struts.MockStrutsTestCase;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.HashMap;
import org.flymine.metadata.Model;
import org.flymine.metadata.presentation.DisplayModel;
public class RestartQueryActionTest extends MockStrutsTestCase {
protected Model model;
public RestartQueryActionTest(String testName) {
super(testName);
}
public void setUp() throws Exception {
super.setUp();
model = Model.getInstanceByName("testmodel");
}
public void tearDown() throws Exception {
super.tearDown();
}
public void testRestart() throws Exception {
HttpSession session = getSession();
setRequestPathInfo("/query");
addRequestParameter("action", "Reset query");
String anAlias = "ClassAlias_0";
Map queryClasses = new HashMap();
DisplayQueryClass displayQueryClass = new DisplayQueryClass();
displayQueryClass.setType("org.flymine.model.testmodel.Department");
queryClasses.put(anAlias, displayQueryClass);
session.setAttribute("queryClasses", queryClasses);
session.setAttribute("editingAlias", anAlias);
session.setAttribute("model", new DisplayModel(model));
actionPerform();
verifyForward("buildquery");
assertNull(session.getAttribute("queryClasses"));
assertNull(session.getAttribute("editingAlias"));
assertNotNull(session.getAttribute("model"));
}
}
|
package qora.web;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONObject;
import qora.account.Account;
import qora.crypto.Crypto;
import qora.naming.Name;
import utils.NameUtils;
import utils.NameUtils.NameResult;
import utils.Pair;
import utils.Qorakeys;
import controller.Controller;
import database.DBSet;
/**
* Used to determine which names or accounts are allowed to post in a blog
* @author Skerberus
*
*/
public class BlogBlackWhiteList {
/**
*
* @param blogname the blog to check for white/blacklist
* @return An object containing all names or accounts that are allowed/forbidden the blogowner is always part of the whitelist
*/
public static BlogBlackWhiteList getBlogBlackWhiteList(String blogname)
{
if(blogname == null)
{
return new BlogBlackWhiteList(false, new ArrayList<String>(), null);
}
Name blognameName = DBSet.getInstance().getNameMap().get(blogname);
//Name not registered, --> Default = Whitelist
if(blognameName == null)
{
return new BlogBlackWhiteList(true, new ArrayList<String>(), blogname);
}
JSONObject jsonForNameOpt = NameUtils.getJsonForNameOpt(blognameName);
//No Json or no keys -> --> Default = Whitelist
if(jsonForNameOpt != null)
{
if(jsonForNameOpt.containsKey(Qorakeys.BLOGWHITELIST.toString()))
{
String whitelist = (String) jsonForNameOpt.get(Qorakeys.BLOGWHITELIST.toString());
String[] whiteListEntries = StringUtils.split(whitelist, ",");
List<String> result = new ArrayList<String>(Arrays.asList(whiteListEntries));
return new BlogBlackWhiteList(true, result , blogname);
}
if(jsonForNameOpt.containsKey(Qorakeys.BLOGBLACKLIST.toString()))
{
String blackList = (String) jsonForNameOpt.get(Qorakeys.BLOGBLACKLIST.toString());
String[] blackListEntries = StringUtils.split(blackList, ",");
return new BlogBlackWhiteList(false, Arrays.asList(blackListEntries), blogname);
}
}
return new BlogBlackWhiteList(true, new ArrayList<String>(), blogname);
}
private final boolean whitelist;
private final List<String> blackwhiteList;
private final String blogname;
private BlogBlackWhiteList(boolean isWhiteList, List<String> blackwhiteList, String blogname) {
whitelist = isWhiteList;
this.blackwhiteList = blackwhiteList;
this.blogname = blogname;
}
public List<String> getBlackwhiteList() {
return Collections.unmodifiableList(blackwhiteList);
}
public boolean isWhitelist() {
return whitelist;
}
public boolean isBlacklist() {
return !whitelist;
}
public String getBlogname() {
return blogname;
}
/**
* Checks if post is allowed in blog.
* @param accountOrName name if post by name, creator else
* @param creator the creator of that post
* @return true if post is allowed, false else
*/
public boolean isAllowedPost(String accountOrName, String creator)
{
Pair<Account, NameResult> nameToAdress = NameUtils.nameToAdress(accountOrName);
if(nameToAdress.getB() == NameResult.OK)
{
String address = nameToAdress.getA().getAddress();
//Name is not matching creator, maybe name sold or someone tried to fake a post.
if(!address.equals(creator))
{
return false;
}
//blogowner can always post
if(accountOrName.equals(blogname))
{
return true;
}
}
if(isWhitelist())
{
return (blackwhiteList.contains(accountOrName));
}else
{
return !blackwhiteList.contains(accountOrName);
}
}
/**
*
* @return a pair containing every account and every name that current user owns and that is allowed to post in the blog.
* In case of a whitelist the blogowner is always part of that
*/
public Pair<List<Account>, List<Name>> getOwnAllowedElements(boolean removeZeroBalance)
{
List<Name> resultingNames = new CopyOnWriteArrayList<Name>();
List<Account> resultingAccounts = new CopyOnWriteArrayList<Account>();
List<Account> myaccounts = new ArrayList<Account>(Controller
.getInstance().getAccounts());
List<Name> myNames = new ArrayList<Name>(Controller
.getInstance().getNamesAsList());
if(isWhitelist())
{
for (String accountOrName : blackwhiteList) {
Pair<Account, NameResult> nameToAdress = NameUtils.nameToAdress(accountOrName);
if(nameToAdress.getB() == NameResult.OK)
{
//DO I OWN THAT NAME?
Name name = Controller.getInstance().getName(accountOrName);
if(myNames.contains(name))
{
if(!resultingNames.contains(name))
{
//YOU CAN ONLY POST BY NAME IF PROFILE IS ENABLED
if(Profile.getProfile(name).isProfileEnabled())
{
resultingNames.add(name);
}
}
}
}else if(!Crypto.getInstance().isValidAddress(accountOrName))
{
Account accountByAddress = Controller.getInstance().getAccountByAddress(accountOrName);
//DO I OWN THAT ADDRESS?
if(accountByAddress != null)
{
if(!resultingAccounts.contains(accountByAddress))
{
resultingAccounts.add(accountByAddress);
}
}
}
}
//IF IT IS MY OWN BLOG, MY NAME WILL BE OF COURSE PART OF THE WHITELIST
Name blogName = Controller.getInstance().getName(blogname);
if(myNames.contains(blogName))
{
if(!resultingNames.contains(blogName))
{
resultingNames.add(blogName);
}
}
}else
{
List<Profile> activeProfiles = Profile.getActiveProfiles();
for (Profile profile : activeProfiles) {
if(profile.isProfileEnabled())
{
resultingNames.add(profile.getName());
}
}
resultingAccounts.addAll(myaccounts);
for (String accountOrName : blackwhiteList) {
Pair<Account, NameResult> nameToAdress = NameUtils.nameToAdress(accountOrName);
if(nameToAdress.getB() == NameResult.OK)
{
//DO I OWN THAT NAME?
Name name = Controller.getInstance().getName(accountOrName);
if(myNames.contains(name))
{
resultingNames.remove(name);
}
}else if(!Crypto.getInstance().isValidAddress(accountOrName))
{
Account accountByAddress = Controller.getInstance().getAccountByAddress(accountOrName);
//DO I OWN THAT ADDRESS?
if(accountByAddress != null)
{
resultingAccounts.remove(accountByAddress);
}
}
}
}
if(removeZeroBalance)
{
for (Name name : resultingNames) {
//No balance account not shown
if(name.getOwner().getBalance(0).compareTo(BigDecimal.ZERO) <= 0)
{
resultingNames.remove(name);
}
}
for (Account account : resultingAccounts) {
if(account.getBalance(0).compareTo(BigDecimal.ZERO) <= 0)
{
resultingAccounts.remove(account);
}
}
}
return new Pair<List<Account>, List<Name>>(resultingAccounts, resultingNames);
}
}
|
package com.vk.api.sdk.callback;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.vk.api.sdk.callback.objects.CallbackConfirmation;
import com.vk.api.sdk.callback.objects.board.CallbackBoardPostDelete;
import com.vk.api.sdk.callback.objects.group.CallbackGroupChangePhoto;
import com.vk.api.sdk.callback.objects.group.CallbackGroupChangeSettings;
import com.vk.api.sdk.callback.objects.group.CallbackGroupJoin;
import com.vk.api.sdk.callback.objects.group.CallbackGroupLeave;
import com.vk.api.sdk.callback.objects.group.CallbackGroupOfficersEdit;
import com.vk.api.sdk.callback.objects.market.CallbackMarketComment;
import com.vk.api.sdk.callback.objects.market.CallbackMarketCommentDelete;
import com.vk.api.sdk.callback.objects.messages.CallbackMessage;
import com.vk.api.sdk.callback.objects.messages.CallbackMessageAllow;
import com.vk.api.sdk.callback.objects.messages.CallbackMessageDeny;
import com.vk.api.sdk.callback.objects.photo.CallbackPhotoComment;
import com.vk.api.sdk.callback.objects.photo.CallbackPhotoCommentDelete;
import com.vk.api.sdk.callback.objects.poll.CallbackPollVoteNew;
import com.vk.api.sdk.callback.objects.user.CallbackUserBlock;
import com.vk.api.sdk.callback.objects.user.CallbackUserUnblock;
import com.vk.api.sdk.callback.objects.video.CallbackVideoComment;
import com.vk.api.sdk.callback.objects.video.CallbackVideoCommentDelete;
import com.vk.api.sdk.callback.objects.wall.CallbackWallComment;
import com.vk.api.sdk.callback.objects.wall.CallbackWallCommentDelete;
import com.vk.api.sdk.objects.audio.Audio;
import com.vk.api.sdk.objects.board.TopicComment;
import com.vk.api.sdk.objects.messages.Message;
import com.vk.api.sdk.objects.photos.Photo;
import com.vk.api.sdk.objects.video.Video;
import com.vk.api.sdk.objects.wall.WallPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class CallbackApi {
private static final Logger LOG = LoggerFactory.getLogger(CallbackApi.class);
private static final String CALLBACK_EVENT_MESSAGE_NEW = "message_new";
private static final String CALLBACK_EVENT_MESSAGE_REPLY = "message_reply";
private static final String CALLBACK_EVENT_MESSAGE_ALLOW = "message_allow";
private static final String CALLBACK_EVENT_MESSAGE_DENY = "message_deny";
private static final String CALLBACK_EVENT_PHOTO_NEW = "photo_new";
private static final String CALLBACK_EVENT_PHOTO_COMMENT_NEW = "photo_comment_new";
private static final String CALLBACK_EVENT_PHOTO_COMMENT_EDIT = "photo_comment_edit";
private static final String CALLBACK_EVENT_PHOTO_COMMENT_RESTORE = "photo_comment_restore";
private static final String CALLBACK_EVENT_PHOTO_COMMENT_DELETE = "photo_comment_delete";
private static final String CALLBACK_EVENT_AUDIO_NEW = "audio_new";
private static final String CALLBACK_EVENT_VIDEO_NEW = "video_new";
private static final String CALLBACK_EVENT_VIDEO_COMMENT_NEW = "video_comment_new";
private static final String CALLBACK_EVENT_VIDEO_COMMENT_EDIT = "video_comment_edit";
private static final String CALLBACK_EVENT_VIDEO_COMMENT_RESTORE = "video_comment_restore";
private static final String CALLBACK_EVENT_VIDEO_COMMENT_DELETE = "video_comment_delete";
private static final String CALLBACK_EVENT_WALL_POST_NEW = "wall_post_new";
private static final String CALLBACK_EVENT_WALL_REPOST = "wall_repost";
private static final String CALLBACK_EVENT_WALL_REPLY_NEW = "wall_reply_new";
private static final String CALLBACK_EVENT_WALL_REPLY_EDIT = "wall_reply_edit";
private static final String CALLBACK_EVENT_WALL_REPLY_RESTORE = "wall_reply_restore";
private static final String CALLBACK_EVENT_WALL_REPLY_DELETE = "wall_reply_delete";
private static final String CALLBACK_EVENT_BOARD_POST_NEW = "board_post_new";
private static final String CALLBACK_EVENT_BOARD_POST_EDIT = "board_post_edit";
private static final String CALLBACK_EVENT_BOARD_POST_RESTORE = "board_post_restore";
private static final String CALLBACK_EVENT_BOARD_POST_DELETE = "board_post_delete";
private static final String CALLBACK_EVENT_MARKET_COMMENT_NEW = "market_comment_new";
private static final String CALLBACK_EVENT_MARKET_COMMENT_EDIT = "market_comment_edit";
private static final String CALLBACK_EVENT_MARKET_COMMENT_RESTORE = "market_comment_restore";
private static final String CALLBACK_EVENT_MARKET_COMMENT_DELETE = "market_comment_delete";
private static final String CALLBACK_EVENT_GROUP_LEAVE = "group_leave";
private static final String CALLBACK_EVENT_GROUP_JOIN = "group_join";
private static final String CALLBACK_EVENT_GROUP_CHANGE_SETTINGS = "group_change_settings";
private static final String CALLBACK_EVENT_GROUP_CHANGE_PHOTO = "group_change_photo";
private static final String CALLBACK_EVENT_GROUP_OFFICERS_EDIT = "group_officers_edit";
private static final String CALLBACK_EVENT_POLL_VOTE_NEW = "poll_vote_new";
private static final String CALLBACK_EVENT_USER_BLOCK = "user_block";
private static final String CALLBACK_EVENT_USER_UNBLOCK = "user_unblock";
private static final String CALLBACK_EVENT_CONFIRMATION = "confirmation";
private final static Map<String, Type> CALLBACK_TYPES;
static {
Map<String, Type> types = new HashMap<>();
types.put(CALLBACK_EVENT_MESSAGE_NEW, new TypeToken<CallbackMessage<Message>>() {
}.getType());
types.put(CALLBACK_EVENT_MESSAGE_REPLY, new TypeToken<CallbackMessage<Message>>() {
}.getType());
types.put(CALLBACK_EVENT_MESSAGE_ALLOW, new TypeToken<CallbackMessage<CallbackMessageAllow>>() {
}.getType());
types.put(CALLBACK_EVENT_MESSAGE_DENY, new TypeToken<CallbackMessage<CallbackMessageDeny>>() {
}.getType());
types.put(CALLBACK_EVENT_PHOTO_NEW, new TypeToken<CallbackMessage<Photo>>() {
}.getType());
types.put(CALLBACK_EVENT_PHOTO_COMMENT_NEW, new TypeToken<CallbackMessage<CallbackPhotoComment>>() {
}.getType());
types.put(CALLBACK_EVENT_PHOTO_COMMENT_EDIT, new TypeToken<CallbackMessage<CallbackPhotoComment>>() {
}.getType());
types.put(CALLBACK_EVENT_PHOTO_COMMENT_RESTORE, new TypeToken<CallbackMessage<CallbackPhotoComment>>() {
}.getType());
types.put(CALLBACK_EVENT_PHOTO_COMMENT_DELETE, new TypeToken<CallbackMessage<CallbackPhotoCommentDelete>>() {
}.getType());
types.put(CALLBACK_EVENT_AUDIO_NEW, new TypeToken<CallbackMessage<Audio>>() {
}.getType());
types.put(CALLBACK_EVENT_VIDEO_NEW, new TypeToken<CallbackMessage<Video>>() {
}.getType());
types.put(CALLBACK_EVENT_VIDEO_COMMENT_NEW, new TypeToken<CallbackMessage<CallbackVideoComment>>() {
}.getType());
types.put(CALLBACK_EVENT_VIDEO_COMMENT_EDIT, new TypeToken<CallbackMessage<CallbackVideoComment>>() {
}.getType());
types.put(CALLBACK_EVENT_VIDEO_COMMENT_RESTORE, new TypeToken<CallbackMessage<CallbackVideoComment>>() {
}.getType());
types.put(CALLBACK_EVENT_VIDEO_COMMENT_DELETE, new TypeToken<CallbackMessage<CallbackVideoCommentDelete>>() {
}.getType());
types.put(CALLBACK_EVENT_WALL_POST_NEW, new TypeToken<CallbackMessage<WallPost>>() {
}.getType());
types.put(CALLBACK_EVENT_WALL_REPOST, new TypeToken<CallbackMessage<WallPost>>() {
}.getType());
types.put(CALLBACK_EVENT_WALL_REPLY_NEW, new TypeToken<CallbackMessage<CallbackWallComment>>() {
}.getType());
types.put(CALLBACK_EVENT_WALL_REPLY_EDIT, new TypeToken<CallbackMessage<CallbackWallComment>>() {
}.getType());
types.put(CALLBACK_EVENT_WALL_REPLY_RESTORE, new TypeToken<CallbackMessage<CallbackWallComment>>() {
}.getType());
types.put(CALLBACK_EVENT_WALL_REPLY_DELETE, new TypeToken<CallbackMessage<CallbackWallCommentDelete>>() {
}.getType());
types.put(CALLBACK_EVENT_BOARD_POST_NEW, new TypeToken<CallbackMessage<TopicComment>>() {
}.getType());
types.put(CALLBACK_EVENT_BOARD_POST_EDIT, new TypeToken<CallbackMessage<TopicComment>>() {
}.getType());
types.put(CALLBACK_EVENT_BOARD_POST_RESTORE, new TypeToken<CallbackMessage<TopicComment>>() {
}.getType());
types.put(CALLBACK_EVENT_BOARD_POST_DELETE, new TypeToken<CallbackMessage<CallbackBoardPostDelete>>() {
}.getType());
types.put(CALLBACK_EVENT_MARKET_COMMENT_NEW, new TypeToken<CallbackMessage<CallbackMarketComment>>() {
}.getType());
types.put(CALLBACK_EVENT_MARKET_COMMENT_EDIT, new TypeToken<CallbackMessage<CallbackMarketComment>>() {
}.getType());
types.put(CALLBACK_EVENT_MARKET_COMMENT_RESTORE, new TypeToken<CallbackMessage<CallbackMarketComment>>() {
}.getType());
types.put(CALLBACK_EVENT_MARKET_COMMENT_DELETE, new TypeToken<CallbackMessage<CallbackMarketCommentDelete>>() {
}.getType());
types.put(CALLBACK_EVENT_GROUP_LEAVE, new TypeToken<CallbackMessage<CallbackGroupLeave>>() {
}.getType());
types.put(CALLBACK_EVENT_GROUP_JOIN, new TypeToken<CallbackMessage<CallbackGroupJoin>>() {
}.getType());
types.put(CALLBACK_EVENT_GROUP_CHANGE_SETTINGS, new TypeToken<CallbackMessage<CallbackGroupChangeSettings>>() {
}.getType());
types.put(CALLBACK_EVENT_GROUP_CHANGE_PHOTO, new TypeToken<CallbackMessage<CallbackGroupChangePhoto>>() {
}.getType());
types.put(CALLBACK_EVENT_GROUP_OFFICERS_EDIT, new TypeToken<CallbackMessage<CallbackGroupOfficersEdit>>() {
}.getType());
types.put(CALLBACK_EVENT_USER_BLOCK, new TypeToken<CallbackMessage<CallbackUserBlock>>() {
}.getType());
types.put(CALLBACK_EVENT_USER_UNBLOCK, new TypeToken<CallbackMessage<CallbackUserUnblock>>() {
}.getType());
types.put(CALLBACK_EVENT_POLL_VOTE_NEW, new TypeToken<CallbackMessage<CallbackPollVoteNew>>() {
}.getType());
types.put(CALLBACK_EVENT_CONFIRMATION, new TypeToken<CallbackMessage<CallbackConfirmation>>() {
}.getType());
CALLBACK_TYPES = Collections.unmodifiableMap(types);
}
private final Gson gson;
public CallbackApi() {
gson = new Gson();
}
public void messageNew(Integer groupId, Message message) {
}
public void messageNew(Integer groupId, String secret, Message message) {
messageNew(groupId, message);
}
public void messageReply(Integer groupId, Message message) {
}
public void messageReply(Integer groupId, String secret, Message message) {
messageReply(groupId, message);
}
public void messageAllow(Integer groupId, CallbackMessageAllow message) {
}
public void messageAllow(Integer groupId, String secret, CallbackMessageAllow message) {
messageAllow(groupId, message);
}
public void messageDeny(Integer groupId, CallbackMessageDeny message) {
}
public void messageDeny(Integer groupId, String secret, CallbackMessageDeny message) {
messageDeny(groupId, message);
}
public void photoNew(Integer groupId, Photo message) {
}
public void photoNew(Integer groupId, String secret, Photo message) {
photoNew(groupId, message);
}
public void photoCommentNew(Integer groupId, CallbackPhotoComment message) {
}
public void photoCommentNew(Integer groupId, String secret, CallbackPhotoComment message) {
photoCommentNew(groupId, message);
}
public void photoCommentEdit(Integer groupId, CallbackPhotoComment message) {
}
public void photoCommentEdit(Integer groupId, String secret, CallbackPhotoComment message) {
photoCommentEdit(groupId, message);
}
public void photoCommentRestore(Integer groupId, CallbackPhotoComment message) {
}
public void photoCommentRestore(Integer groupId, String secret, CallbackPhotoComment message) {
photoCommentRestore(groupId, message);
}
public void photoCommentDelete(Integer groupId, CallbackPhotoCommentDelete message) {
}
public void photoCommentDelete(Integer groupId, String secret, CallbackPhotoCommentDelete message) {
photoCommentDelete(groupId, message);
}
public void audioNew(Integer groupId, Audio message) {
}
public void audioNew(Integer groupId, String secret, Audio message) {
audioNew(groupId, message);
}
public void videoNew(Integer groupId, Video message) {
}
public void videoNew(Integer groupId, String secret, Video message) {
videoNew(groupId, message);
}
public void videoCommentNew(Integer groupId, CallbackVideoComment message) {
}
public void videoCommentNew(Integer groupId, String secret, CallbackVideoComment message) {
videoCommentNew(groupId, message);
}
public void videoCommentEdit(Integer groupId, CallbackVideoComment message) {
}
public void videoCommentEdit(Integer groupId, String secret, CallbackVideoComment message) {
videoCommentEdit(groupId, message);
}
public void videoCommentRestore(Integer groupId, CallbackVideoComment message) {
}
public void videoCommentRestore(Integer groupId, String secret, CallbackVideoComment message) {
videoCommentRestore(groupId, message);
}
public void videoCommentDelete(Integer groupId, CallbackVideoCommentDelete message) {
}
public void videoCommentDelete(Integer groupId, String secret, CallbackVideoCommentDelete message) {
videoCommentDelete(groupId, message);
}
public void wallPostNew(Integer groupId, WallPost message) {
}
public void wallPostNew(Integer groupId, String secret, WallPost message) {
wallPostNew(groupId, message);
}
public void wallRepost(Integer groupId, WallPost message) {
}
public void wallRepost(Integer groupId, String secret, WallPost message) {
wallRepost(groupId, message);
}
public void wallReplyNew(Integer groupId, CallbackWallComment object) {
}
public void wallReplyNew(Integer groupId, String secret, CallbackWallComment object) {
wallReplyNew(groupId, object);
}
public void wallReplyEdit(Integer groupId, CallbackWallComment message) {
}
public void wallReplyEdit(Integer groupId, String secret, CallbackWallComment message) {
wallReplyEdit(groupId, message);
}
public void wallReplyRestore(Integer groupId, CallbackWallComment message) {
}
public void wallReplyRestore(Integer groupId, String secret, CallbackWallComment message) {
wallReplyRestore(groupId, message);
}
public void wallReplyDelete(Integer groupId, CallbackWallCommentDelete message) {
}
public void wallReplyDelete(Integer groupId, String secret, CallbackWallCommentDelete message) {
wallReplyDelete(groupId, message);
}
public void boardPostNew(Integer groupId, TopicComment message) {
}
public void boardPostNew(Integer groupId, String secret, TopicComment message) {
boardPostNew(groupId, message);
}
public void boardPostEdit(Integer groupId, TopicComment message) {
}
public void boardPostEdit(Integer groupId, String secret, TopicComment message) {
boardPostEdit(groupId, message);
}
public void boardPostRestore(Integer groupId, TopicComment message) {
}
public void boardPostRestore(Integer groupId, String secret, TopicComment message) {
boardPostRestore(groupId, message);
}
public void boardPostDelete(Integer groupId, CallbackBoardPostDelete message) {
}
public void boardPostDelete(Integer groupId, String secret, CallbackBoardPostDelete message) {
boardPostDelete(groupId, message);
}
public void marketCommentNew(Integer groupId, CallbackMarketComment message) {
}
public void marketCommentNew(Integer groupId, String secret, CallbackMarketComment message) {
marketCommentNew(groupId, message);
}
public void marketCommentEdit(Integer groupId, CallbackMarketComment message) {
}
public void marketCommentEdit(Integer groupId, String secret, CallbackMarketComment message) {
marketCommentEdit(groupId, message);
}
public void marketCommentRestore(Integer groupId, CallbackMarketComment message) {
}
public void marketCommentRestore(Integer groupId, String secret, CallbackMarketComment message) {
marketCommentRestore(groupId, message);
}
public void marketCommentDelete(Integer groupId, CallbackMarketCommentDelete message) {
}
public void marketCommentDelete(Integer groupId, String secret, CallbackMarketCommentDelete message) {
marketCommentDelete(groupId, message);
}
public void groupLeave(Integer groupId, CallbackGroupLeave message) {
}
public void groupLeave(Integer groupId, String secret, CallbackGroupLeave message) {
groupLeave(groupId, message);
}
public void groupJoin(Integer groupId, CallbackGroupJoin message) {
}
public void groupJoin(Integer groupId, String secret, CallbackGroupJoin message) {
groupJoin(groupId, message);
}
public void groupChangeSettings(Integer groupId, CallbackGroupChangeSettings message) {
}
public void groupChangeSettings(Integer groupId, String secret, CallbackGroupChangeSettings message) {
groupChangeSettings(groupId, message);
}
public void groupChangePhoto(Integer groupId, CallbackGroupChangePhoto message) {
}
public void groupChangePhoto(Integer groupId, String secret, CallbackGroupChangePhoto message) {
groupChangePhoto(groupId, message);
}
public void groupOfficersEdit(Integer groupId, CallbackGroupOfficersEdit message) {
}
public void groupOfficersEdit(Integer groupId, String secret, CallbackGroupOfficersEdit message) {
groupOfficersEdit(groupId, message);
}
public void pollVoteNew(Integer groupId, CallbackPollVoteNew message) {
}
public void pollVoteNew(Integer groupId, String secret, CallbackPollVoteNew message) {
pollVoteNew(groupId, message);
}
public void userBlock(Integer groupId, CallbackUserBlock message) {
}
public void userBlock(Integer groupId, String secret, CallbackUserBlock message) {
userBlock(groupId, message);
}
public void userUnblock(Integer groupId, CallbackUserUnblock message) {
}
public void userUnblock(Integer groupId, String secret, CallbackUserUnblock message) {
userUnblock(groupId, message);
}
public void confirmation(Integer groupId, CallbackConfirmation message) {
}
public void confirmation(Integer groupId, String secret, CallbackConfirmation message) {
confirmation(groupId, message);
}
public boolean parse(String json) {
JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
return parse(jsonObject);
}
public boolean parse(JsonObject json) {
String type = json.get("type").getAsString();
Type typeOfClass = CALLBACK_TYPES.get(type);
if (typeOfClass == null) {
LOG.warn("Unsupported callback event", type);
return false;
}
CallbackMessage message = gson.fromJson(json, typeOfClass);
switch (type) {
case CALLBACK_EVENT_MESSAGE_NEW:
messageNew(message.getGroupId(), message.getSecret(), (Message) message.getObject());
break;
case CALLBACK_EVENT_MESSAGE_REPLY:
messageReply(message.getGroupId(), message.getSecret(), (Message) message.getObject());
break;
case CALLBACK_EVENT_MESSAGE_ALLOW:
messageAllow(message.getGroupId(), message.getSecret(), (CallbackMessageAllow) message.getObject());
break;
case CALLBACK_EVENT_MESSAGE_DENY:
messageDeny(message.getGroupId(), message.getSecret(), (CallbackMessageDeny) message.getObject());
break;
case CALLBACK_EVENT_PHOTO_NEW:
photoNew(message.getGroupId(), message.getSecret(), (Photo) message.getObject());
break;
case CALLBACK_EVENT_PHOTO_COMMENT_NEW:
photoCommentNew(message.getGroupId(), message.getSecret(), (CallbackPhotoComment) message.getObject());
break;
case CALLBACK_EVENT_PHOTO_COMMENT_EDIT:
photoCommentEdit(message.getGroupId(), message.getSecret(), (CallbackPhotoComment) message.getObject());
break;
case CALLBACK_EVENT_PHOTO_COMMENT_RESTORE:
photoCommentRestore(message.getGroupId(), message.getSecret(), (CallbackPhotoComment) message.getObject());
break;
case CALLBACK_EVENT_PHOTO_COMMENT_DELETE:
photoCommentDelete(message.getGroupId(), message.getSecret(), (CallbackPhotoCommentDelete) message.getObject());
break;
case CALLBACK_EVENT_AUDIO_NEW:
audioNew(message.getGroupId(), message.getSecret(), (Audio) message.getObject());
break;
case CALLBACK_EVENT_VIDEO_NEW:
videoNew(message.getGroupId(), message.getSecret(), (Video) message.getObject());
break;
case CALLBACK_EVENT_VIDEO_COMMENT_NEW:
videoCommentNew(message.getGroupId(), message.getSecret(), (CallbackVideoComment) message.getObject());
break;
case CALLBACK_EVENT_VIDEO_COMMENT_EDIT:
videoCommentEdit(message.getGroupId(), message.getSecret(), (CallbackVideoComment) message.getObject());
break;
case CALLBACK_EVENT_VIDEO_COMMENT_RESTORE:
videoCommentRestore(message.getGroupId(), message.getSecret(), (CallbackVideoComment) message.getObject());
break;
case CALLBACK_EVENT_VIDEO_COMMENT_DELETE:
videoCommentDelete(message.getGroupId(), message.getSecret(), (CallbackVideoCommentDelete) message.getObject());
break;
case CALLBACK_EVENT_WALL_POST_NEW:
wallPostNew(message.getGroupId(), message.getSecret(), (WallPost) message.getObject());
break;
case CALLBACK_EVENT_WALL_REPOST:
wallRepost(message.getGroupId(), message.getSecret(), (WallPost) message.getObject());
break;
case CALLBACK_EVENT_WALL_REPLY_NEW:
wallReplyNew(message.getGroupId(), message.getSecret(), (CallbackWallComment) message.getObject());
break;
case CALLBACK_EVENT_WALL_REPLY_EDIT:
wallReplyEdit(message.getGroupId(), message.getSecret(), (CallbackWallComment) message.getObject());
break;
case CALLBACK_EVENT_WALL_REPLY_RESTORE:
wallReplyRestore(message.getGroupId(), message.getSecret(), (CallbackWallComment) message.getObject());
break;
case CALLBACK_EVENT_WALL_REPLY_DELETE:
wallReplyDelete(message.getGroupId(), message.getSecret(), (CallbackWallCommentDelete) message.getObject());
break;
case CALLBACK_EVENT_BOARD_POST_NEW:
boardPostNew(message.getGroupId(), message.getSecret(), (TopicComment) message.getObject());
break;
case CALLBACK_EVENT_BOARD_POST_EDIT:
boardPostEdit(message.getGroupId(), message.getSecret(), (TopicComment) message.getObject());
break;
case CALLBACK_EVENT_BOARD_POST_RESTORE:
boardPostRestore(message.getGroupId(), message.getSecret(), (TopicComment) message.getObject());
break;
case CALLBACK_EVENT_BOARD_POST_DELETE:
boardPostDelete(message.getGroupId(), message.getSecret(), (CallbackBoardPostDelete) message.getObject());
break;
case CALLBACK_EVENT_MARKET_COMMENT_NEW:
marketCommentNew(message.getGroupId(), message.getSecret(), (CallbackMarketComment) message.getObject());
break;
case CALLBACK_EVENT_MARKET_COMMENT_EDIT:
marketCommentEdit(message.getGroupId(), message.getSecret(), (CallbackMarketComment) message.getObject());
break;
case CALLBACK_EVENT_MARKET_COMMENT_RESTORE:
marketCommentRestore(message.getGroupId(), message.getSecret(), (CallbackMarketComment) message.getObject());
break;
case CALLBACK_EVENT_MARKET_COMMENT_DELETE:
marketCommentDelete(message.getGroupId(), message.getSecret(), (CallbackMarketCommentDelete) message.getObject());
break;
case CALLBACK_EVENT_GROUP_LEAVE:
groupLeave(message.getGroupId(), message.getSecret(), (CallbackGroupLeave) message.getObject());
break;
case CALLBACK_EVENT_GROUP_JOIN:
groupJoin(message.getGroupId(), message.getSecret(), (CallbackGroupJoin) message.getObject());
break;
case CALLBACK_EVENT_GROUP_CHANGE_SETTINGS:
groupChangeSettings(message.getGroupId(), message.getSecret(), (CallbackGroupChangeSettings) message.getObject());
break;
case CALLBACK_EVENT_GROUP_CHANGE_PHOTO:
groupChangePhoto(message.getGroupId(), message.getSecret(), (CallbackGroupChangePhoto) message.getObject());
break;
case CALLBACK_EVENT_GROUP_OFFICERS_EDIT:
groupOfficersEdit(message.getGroupId(), message.getSecret(), (CallbackGroupOfficersEdit) message.getObject());
break;
case CALLBACK_EVENT_USER_BLOCK:
userBlock(message.getGroupId(), message.getSecret(), (CallbackUserBlock) message.getObject());
break;
case CALLBACK_EVENT_USER_UNBLOCK:
userUnblock(message.getGroupId(), message.getSecret(), (CallbackUserUnblock) message.getObject());
break;
case CALLBACK_EVENT_POLL_VOTE_NEW:
pollVoteNew(message.getGroupId(), message.getSecret(), (CallbackPollVoteNew) message.getObject());
break;
case CALLBACK_EVENT_CONFIRMATION:
confirmation(message.getGroupId(), message.getSecret(), (CallbackConfirmation) message.getObject());
default:
LOG.warn("Unsupported callback event", type);
return false;
}
return true;
}
}
|
package org.openntf.domino.utils;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.annotation.Nonnull;
import lotus.domino.DateTime;
import lotus.domino.Name;
import lotus.domino.NotesException;
import org.openntf.domino.DateRange;
import org.openntf.domino.Document;
import org.openntf.domino.Item;
import org.openntf.domino.MIMEEntity;
import org.openntf.domino.Session;
import org.openntf.domino.big.NoteCoordinate;
import org.openntf.domino.exceptions.DataNotCompatibleException;
import org.openntf.domino.exceptions.Domino32KLimitException;
import org.openntf.domino.exceptions.ItemNotFoundException;
import org.openntf.domino.exceptions.UnimplementedException;
import org.openntf.domino.ext.Formula;
import org.openntf.domino.impl.ImplUtils;
import org.openntf.domino.types.AuthorsList;
import org.openntf.domino.types.BigString;
import org.openntf.domino.types.Encapsulated;
import org.openntf.domino.types.NamesList;
import org.openntf.domino.types.ReadersList;
import com.google.common.collect.ImmutableList;
import com.ibm.commons.util.StringUtil;
import com.ibm.icu.math.BigDecimal;
import com.ibm.icu.text.DateFormat;
import com.ibm.icu.text.SimpleDateFormat;
/**
* @author nfreeman
*
*/
public enum TypeUtils {
;
public static final String[] DEFAULT_STR_ARRAY = { "" };
protected static final List<CustomConverter> converterList_ = new ArrayList<CustomConverter>();
// protected static final List<Class<?>> converterFromList_ = new ArrayList<Class<?>>();
private static final ThreadLocal<SimpleDateFormat> DEFAULT_FORMAT = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
}
};
public static interface CustomConverter {
public Object convert(Object from);
public Object get(Document doc, String itemName);
public Object put(Document doc, String itemName, Object from);
public Class<?> getFrom();
public Class<?> getTo();
public boolean isCompatible(@Nonnull final Class<?> fromClass);
}
public static abstract class AbstractConverter implements CustomConverter {
protected Class<?> fromClass_;
protected Class<?> toClass_;
@Override
public Class<?> getFrom() {
return fromClass_;
}
@Override
public Class<?> getTo() {
return toClass_;
}
@Override
public boolean isCompatible(@Nonnull final Class<?> fromClass) {
return fromClass_.isAssignableFrom(fromClass);
}
}
public static synchronized void addCustomConverter(final CustomConverter converter) {
converterList_.add(converter);
// System.out.println("TEMP DEBUG added custom converter");
// converterFromList_.add(converter.getFrom());
}
public static synchronized void removeCustomConverter(final CustomConverter converter) {
converterList_.remove(converter);
}
public static List<CustomConverter> getConverterList() {
return ImmutableList.copyOf(converterList_);
}
protected static CustomConverter findCustomConverter(final Class<?> fromClass) {
for (CustomConverter converter : getConverterList()) {
if (converter.isCompatible(fromClass)) {
// System.out.println("TEMP DEBUG found custom converter");
return converter;
}
}
return null;
}
@SuppressWarnings("unchecked")
public static <T> T getDefaultInstance(final Class<T> type) {
if (type.isArray()) {
if (type.getComponentType() == String.class) {
return (T) DEFAULT_STR_ARRAY.clone();
} else {
return (T) Array.newInstance(type.getComponentType(), 0);
}
}
if (Boolean.class.equals(type) || Boolean.TYPE.equals(type)) {
return (T) Boolean.FALSE;
}
if (Integer.class.equals(type) || Integer.TYPE.equals(type)) {
return (T) Integer.valueOf(0);
}
if (Long.class.equals(type) || Long.TYPE.equals(type)) {
return (T) Long.valueOf(0l);
}
if (Short.class.equals(type) || Short.TYPE.equals(type)) {
return (T) Short.valueOf("0");
}
if (Double.class.equals(type) || Double.TYPE.equals(type)) {
return (T) Double.valueOf(0d);
}
if (Float.class.equals(type) || Float.TYPE.equals(type)) {
return (T) Float.valueOf(0f);
}
if (String.class.equals(type)) {
return (T) "";
}
try {
return type.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// RPr: This method is implemented wrong, you MUST NOT pass null as "recycleThis" argument, because it may created
// dangling DateTimes that will crash the server (if you have created too much)
// ==>commented out and implemented stampAll method correctly
// @Deprecated
// public static Map<String, Object> toStampableMap(final Map<String, Object> rawMap, final org.openntf.domino.Base<?> context)
// Map<String, Object> result = new LinkedHashMap<String, Object>();
// synchronized (rawMap) {
// for (Map.Entry<String, Object> entry : rawMap.entrySet()) {
// Object lValue = Base.toItemFriendly(entry.getValue(), context, null);
// result.put(entry.getKey(), lValue);
// return Collections.unmodifiableMap(result);
@SuppressWarnings("unchecked")
public static <T> T itemValueToClass(final Document doc, final String itemName, final Class<T> type) {
String noteid = doc.getMetaversalID();
boolean hasItem = doc.hasItem(itemName);
if (!hasItem) {
// System.out.println("Item " + itemName + " doesn't exist in document " + doc.getNoteID() + " in "
// + doc.getAncestorDatabase().getFilePath() + " so we can't return a " + T.getName());
Class<?> CType = null;
if (type.isArray()) {
CType = type.getComponentType();
if (CType.isPrimitive()) {
throw new ItemNotFoundException("Item " + itemName + " was not found on document " + noteid
+ " so we cannot return an array of " + CType.getName());
} else {
return null;
}
} else if (type.isPrimitive()) {
throw new ItemNotFoundException(
"Item " + itemName + " was not found on document " + noteid + " so we cannot return a " + type.getName());
} else if (type.equals(String.class)) {
return (T) "";
} else {
return null;
}
}
Object result = itemValueToClass(doc.getFirstItem(itemName), type);
if (result != null && !type.isAssignableFrom(result.getClass())) {
if (type.isPrimitive()) {
if (Integer.TYPE.equals(type) && result instanceof Integer) {
return (T) result;
}
if (Long.TYPE.equals(type) && result instanceof Long) {
return (T) result;
}
if (Boolean.TYPE.equals(type) && result instanceof Boolean) {
return (T) result;
}
if (Double.TYPE.equals(type) && result instanceof Double) {
return (T) result;
}
} else {
if (java.sql.Date.class.equals(type) && result instanceof Date) {
Date dt = (Date) result;
return (T) new java.sql.Date(dt.getTime());
}
if (java.sql.Time.class.equals(type) && result instanceof Date) {
Date dt = (Date) result;
return (T) new java.sql.Time(dt.getTime());
}
log_.log(Level.WARNING, "Auto-boxing requested a " + type.getName() + " but is returning a " + result.getClass().getName()
+ " in item " + itemName + " for document id " + noteid);
}
}
return (T) result;
}
@SuppressWarnings("rawtypes")
public static <T> T itemValueToClass(final Item item, final Class<T> type) {
// Object o = item.getAncestorDocument().getItemValue(item.getName());
if (Item.Type.USERDATA.equals(item.getTypeEx())) {
return null;
}
Vector v = item.getValues();
if (v == null) {
log_.log(Level.WARNING, "Got a null for the value of item " + item.getName());
}
if (java.lang.Object.class.equals(type) & v.size() > 1) {
return (T) v;
}
Session session = item.getAncestorSession();
T result = null;
try {
result = collectionToClass(v, type, session);
//FIXME: implement NamesList variations
} catch (DataNotCompatibleException e) {
String noteid = item.getAncestorDocument().getNoteID();
throw new DataNotCompatibleException(e.getMessage() + " for field " + item.getName() + " in document " + noteid, e);
} catch (UnimplementedException e) {
String noteid = item.getAncestorDocument().getNoteID();
throw new UnimplementedException(e.getMessage() + ", so cannot auto-box for field " + item.getName() + " in document " + noteid,
e);
}
// if ("form".equalsIgnoreCase(item.getName())) {
// System.out.println("TEMP DEBUG Form value is '" + (String) result + "'");
return result;
}
public static boolean isNumerical(final Object rawObject) {
boolean result = true;
if (rawObject == null || rawObject instanceof String) {
return false; //NTF: we know this is going to be true a LOT, so we'll have a fast out
}
if (rawObject instanceof Collection) {
for (Object obj : (Collection<?>) rawObject) {
if (!isNumerical(obj)) {
result = false;
break;
}
}
} else {
if (rawObject instanceof Number || Integer.TYPE.isInstance(rawObject) || Double.TYPE.isInstance(rawObject)
|| Byte.TYPE.isInstance(rawObject) || Short.TYPE.isInstance(rawObject) || Long.TYPE.isInstance(rawObject)
|| Float.TYPE.isInstance(rawObject)) {
} else {
result = false;
}
}
return result;
}
public static boolean isCalendrical(final Object rawObject) {
boolean result = true;
if (rawObject == null || rawObject instanceof String) {
return false; //NTF: we know this is going to be true a LOT, so we'll have a fast out
}
if (rawObject instanceof Collection) {
for (Object obj : (Collection<?>) rawObject) {
if (!isCalendrical(obj)) {
result = false;
break;
}
}
} else {
if (rawObject instanceof DateTime || rawObject instanceof Date) {
} else {
result = false;
}
}
return result;
}
public static boolean isNameish(final Object rawObject) {
boolean result = true;
if (rawObject == null) {
return false; //NTF: we know this is going to be true a LOT, so we'll have a fast out
}
if (rawObject instanceof Collection) {
for (Object obj : (Collection<?>) rawObject) {
if (!isNameish(obj)) {
result = false;
break;
}
}
} else {
if (rawObject instanceof String) {
result = DominoUtils.isHierarchicalName((String) rawObject);
} else {
result = false;
}
}
return result;
}
public static <T> T objectToClass(final Object o, final Class<T> type, final Session session) {
return convertToTarget(o, type, session);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T convertToTarget(final Object o, final Class<T> type, final Session session) {
if (o == null) {
return null;
}
Object result = null;
if (type.isAssignableFrom(o.getClass())) {
return (T) o;
}
if (o instanceof Collection) {
result = collectionToClass((Collection) o, type, session);
}
if (type.isEnum() && o instanceof String) {
result = toEnum(o, type);
}
Class<?> CType = null;
if (type.equals(String[].class)) {
result = toStrings(o);
return (T) result;
}
if (type.isArray()) {
if (String[].class.equals(type)) {
// System.out.println("Shallow route to string array");
result = toStrings(o);
} else {
CType = type.getComponentType();
if (CType.isPrimitive()) {
try {
result = toPrimitiveArray(o, CType);
} catch (DataNotCompatibleException e) {
throw e;
}
} else if (Number.class.isAssignableFrom(CType)) {
result = toNumberArray(o, CType);
} else {
if (CType == String.class) {
// System.out.println("Deep route to string array");
result = toStrings(o);
} else if (CType == BigString.class) {
result = toBigStrings(o);
} else if (CType == Pattern.class) {
result = toPatterns(o);
} else if (CType == java.lang.Enum.class || CType.isEnum()) {
result = toEnums(o);
} else if (Class.class.isAssignableFrom(CType)) {
result = toClasses(o);
} else if (Formula.class.isAssignableFrom(CType)) {
result = toFormulas(o);
} else if (CType == Date.class) {
result = toDates(o);
} else if (DateTime.class.isAssignableFrom(CType)) {
result = toDateTimes(o, session);
} else if (DateRange.class.isAssignableFrom(CType)) {
result = toDateRanges(o, session);
} else if (Name.class.isAssignableFrom(CType)) {
result = toNames(o, session);
} else if (CType == Boolean.class) {
result = toBooleans(o);
} else if (CType == java.lang.Object.class) {
result = toObjects(o);
} else {
throw new UnimplementedException("Arrays for " + CType.getName() + " not yet implemented");
}
}
}
} else if (type.isPrimitive()) {
try {
result = toPrimitive(o, type);
} catch (DataNotCompatibleException e) {
throw e;
}
} else {
if (type == String.class) {
result = String.valueOf(o);
} else if (Enum.class.isAssignableFrom(type)) {
String str = String.valueOf(o);
result = toEnum(str);
} else if (BigString.class.isAssignableFrom(type)) {
result = new BigString(String.valueOf(o));
} else if (Pattern.class.isAssignableFrom(type)) {
result = Pattern.compile(String.valueOf(o));
} else if (Class.class.isAssignableFrom(type)) {
String cn = String.valueOf(o);
Class<?> cls = DominoUtils.getClass(cn);
result = cls;
} else if (Formula.class.isAssignableFrom(type)) {
Formula formula = new org.openntf.domino.helpers.Formula(String.valueOf(o));
result = formula;
} else if (java.util.Collection.class.equals(type)) {
result = new ArrayList();
((ArrayList) result).add(o);
} else if (java.util.Collection.class.isAssignableFrom(type)) {
try {
result = type.newInstance();
Collection coll = (Collection) result;
coll.addAll(toSerializables(o));
} catch (IllegalAccessException e) {
DominoUtils.handleException(e);
} catch (InstantiationException e) {
DominoUtils.handleException(e);
}
} else if (Date.class.isAssignableFrom(type)) {
result = toDate(o);
} else if (java.util.Calendar.class.isAssignableFrom(type)) {
Date tmpDate = toDate(o);
if (null == tmpDate) {
result = null;
} else {
Calendar tmp = Calendar.getInstance();
tmp.setTime(tmpDate);
result = tmp;
}
} else if (org.openntf.domino.DateTime.class.isAssignableFrom(type)) {
if (session != null) {
result = session.createDateTime(toDate(o));
} else {
throw new IllegalArgumentException(
"Cannont convert a " + o.getClass().getName() + " to DateTime without a valid Session object");
}
} else if (org.openntf.domino.DateRange.class.isAssignableFrom(type)) {
if (session != null) {
Date[] dates = toDates(o);
result = session.createDateRange(dates[0], dates[1]);
} else {
throw new IllegalArgumentException(
"Cannont convert a " + o.getClass().getName() + " to DateRange without a valid Session object");
}
} else if (org.openntf.domino.Name.class.isAssignableFrom(type)) {
if (session != null) {
result = session.createName(String.valueOf(o));
} else {
throw new IllegalArgumentException(
"Cannont convert a " + o.getClass().getName() + " to Name without a valid Session object");
}
} else if (Boolean.class.equals(type)) {
result = toBoolean(o);
} else if (Number.class.isAssignableFrom(type)) {
result = toNumber(o, type);
} else {
result = type.cast(o);
}
}
if (result != null && !type.isAssignableFrom(result.getClass())) {
if (type.isPrimitive()) {
if (Integer.TYPE.equals(type) && result instanceof Integer) {
return (T) result;
}
if (Long.TYPE.equals(type) && result instanceof Long) {
return (T) result;
}
if (Boolean.TYPE.equals(type) && result instanceof Boolean) {
return (T) result;
}
if (Double.TYPE.equals(type) && result instanceof Double) {
return (T) result;
}
} else {
log_.log(Level.WARNING, "Auto-boxing requested a " + type.getName() + " but is returning a " + result.getClass().getName());
}
}
return (T) result;
}
public static Comparable toComparable(final Object value) {
if (value == null) {
return null;
}
return (Comparable) toSerializable(value);
}
public static Serializable toSerializable(final Object value) {
if (value == null) {
return null;
}
Serializable result = null;
if (value instanceof org.openntf.domino.DateTime) {
Date date = null;
org.openntf.domino.DateTime dt = (org.openntf.domino.DateTime) value;
result = dt.toJavaDate();
} else if (value instanceof org.openntf.domino.Name) {
result = DominoUtils.toNameString((org.openntf.domino.Name) value);
} else if (value instanceof String) {
result = (String) value;
} else if (value instanceof Number) {
result = (Number) value;
}
return result;
}
public static Collection<Serializable> toSerializables(final Object value) {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return DominoUtils.toSerializable((Collection<?>) value);
} else if (value.getClass().isArray()) {
return DominoUtils.toSerializable(Arrays.asList(value));
} else {
Collection<Serializable> result = new ArrayList<Serializable>();
if (value instanceof org.openntf.domino.DateTime) {
Date date = null;
org.openntf.domino.DateTime dt = (org.openntf.domino.DateTime) value;
date = dt.toJavaDate();
result.add(date);
} else if (value instanceof org.openntf.domino.Name) {
result.add(DominoUtils.toNameString((org.openntf.domino.Name) value));
} else if (value instanceof String) {
result.add((String) value);
} else if (value instanceof Number) {
result.add((Number) value);
}
return result;
}
}
public static <T> T vectorToClass(final Collection<?> v, final Class<T> type, final Session session) {
return collectionToClass(v, type, session);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T collectionToClass(final Collection v, final Class<T> type, final Session session) {
if (v == null) {
return null;
}
Object result = null;
Class<?> CType = null;
if (type.equals(String[].class)) {
result = toStrings(v);
return (T) result;
}
if (type.isArray()) {
if (type == String[].class) {
// System.out.println("Shallow route to string array");
result = toStrings(v);
} else {
CType = type.getComponentType();
if (CType.isPrimitive()) {
try {
result = toPrimitiveArray(v, CType);
} catch (DataNotCompatibleException e) {
throw e;
}
} else if (Number.class.isAssignableFrom(CType)) {
result = toNumberArray(v, CType);
} else {
if (CType == String.class) {
// System.out.println("Deep route to string array");
result = toStrings(v);
} else if (CType == BigString.class) {
result = toBigStrings(v);
} else if (CType == Pattern.class) {
result = toPatterns(v);
} else if (CType == java.lang.Enum.class || CType.isEnum()) {
result = toEnums(v);
} else if (Class.class.isAssignableFrom(CType)) {
result = toClasses(v);
} else if (Formula.class.isAssignableFrom(CType)) {
result = toFormulas(v);
} else if (CType == Date.class) {
result = toDates(v);
} else if (DateTime.class.isAssignableFrom(CType)) {
result = toDateTimes(v, session);
} else if (DateRange.class.isAssignableFrom(CType)) {
result = toDateRanges(v, session);
} else if (Name.class.isAssignableFrom(CType)) {
result = toNames(v, session);
} else if (CType == Boolean.class) {
result = toBooleans(v);
} else if (CType == java.lang.Object.class) {
result = toObjects(v);
} else {
throw new UnimplementedException("Arrays for " + CType.getName() + " not yet implemented");
}
}
}
} else if (type.isPrimitive()) {
try {
result = toPrimitive(v, type);
} catch (DataNotCompatibleException e) {
throw e;
}
} else {
if (type == String.class) {
result = join(v);
} else if (Enum.class.isAssignableFrom(type)) {
String str = join(v);
// System.out.println("Attempting to convert string " + str + " to Enum");
result = toEnum(str);
// System.out.println("result was " + (result == null ? "null" : result.getClass().getName()));
} else if (BigString.class.isAssignableFrom(type)) {
result = new BigString(join(v));
} else if (Pattern.class.isAssignableFrom(type)) {
result = Pattern.compile(join(v));
} else if (Class.class.isAssignableFrom(type)) {
String cn = join(v);
Class<?> cls = DominoUtils.getClass(cn);
result = cls;
} else if (Formula.class.isAssignableFrom(type)) {
Formula formula = new org.openntf.domino.helpers.Formula(join(v));
result = formula;
} else if (type == java.util.Collection.class) {
result = new ArrayList();
if (v != null) {
((ArrayList) result).addAll(v);
}
} else if (java.util.Collection.class.isAssignableFrom(type)) {
try {
// Support some known concrete implementations of collection interfaces
if (List.class.equals(type)) {
result = new ArrayList<Object>();
} else if (Set.class.equals(type)) {
result = new HashSet<Object>();
} else {
result = type.newInstance();
}
Collection coll = (Collection) result;
coll.addAll(DominoUtils.toSerializable(v));
} catch (IllegalAccessException e) {
DominoUtils.handleException(e);
} catch (InstantiationException e) {
DominoUtils.handleException(e);
}
} else if (java.sql.Date.class.isAssignableFrom(type) || java.sql.Time.class.isAssignableFrom(type)) {
Date tmpDate = toDate(v);
if (null == tmpDate) {
result = null;
} else {
if (java.sql.Date.class.isAssignableFrom(type)) {
result = new java.sql.Date(tmpDate.getTime());
} else {
result = new java.sql.Time(tmpDate.getTime());
}
}
} else if (Date.class.isAssignableFrom(type)) {
result = toDate(v);
} else if (java.util.Calendar.class.isAssignableFrom(type)) {
Date tmpDate = toDate(v);
if (null == tmpDate) {
result = null;
} else {
Calendar tmp = Calendar.getInstance();
tmp.setTime(tmpDate);
result = tmp;
}
} else if (org.openntf.domino.DateTime.class.isAssignableFrom(type)) {
if (session != null) {
result = session.createDateTime(toDate(v));
} else {
throw new IllegalArgumentException("Cannont convert a Vector to DateTime without a valid Session object");
}
} else if (org.openntf.domino.Name.class.isAssignableFrom(type)) {
if (session != null) {
if (v.isEmpty()) {
result = session.createName("");
} else {
Iterator it = v.iterator();
result = session.createName(String.valueOf(it.next()));
}
} else {
throw new IllegalArgumentException("Cannont convert a Vector to Name without a valid Session object");
}
} else if (type == Boolean.class) {
if (v.isEmpty()) {
result = Boolean.FALSE;
} else {
Iterator it = v.iterator();
result = toBoolean(it.next());
}
} else {
if (!v.isEmpty()) {
if (Number.class.isAssignableFrom(type)) {
result = toNumber(v, type);
} else {
Iterator it = v.iterator();
result = it.next();
}
}
}
}
if (result != null && !type.isAssignableFrom(result.getClass())) {
if (type.isPrimitive()) {
if (Integer.TYPE.equals(type) && result instanceof Integer) {
return (T) result;
}
if (Long.TYPE.equals(type) && result instanceof Long) {
return (T) result;
}
if (Boolean.TYPE.equals(type) && result instanceof Boolean) {
return (T) result;
}
if (Double.TYPE.equals(type) && result instanceof Double) {
return (T) result;
}
} else {
log_.log(Level.WARNING, "Auto-boxing requested a " + type.getName() + " but is returning a " + result.getClass().getName());
}
}
return (T) result;
}
private static final Logger log_ = Logger.getLogger(TypeUtils.class.getName());
@SuppressWarnings("unchecked")
public static <T> T toNumberArray(final Object value, final Class<T> type) {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToNumberArray((Collection<Object>) value, type);
} else if (value.getClass().isArray()) {
Object[] arr = (Object[]) value;
Object[] result = (Object[]) Array.newInstance(type, arr.length);
for (int i = 0; i < arr.length; i++) {
result[i++] = toNumber(arr[i], type);
}
return (T) result;
} else {
Object[] result = (Object[]) Array.newInstance(type, 1);
result[0] = toNumber(value, type);
return (T) result;
}
}
@SuppressWarnings("unchecked")
public static <T> T collectionToNumberArray(final Collection<Object> value, final Class<T> type) {
int size = value.size();
Object[] result = (Object[]) Array.newInstance(type, size);
int i = 0;
Iterator<Object> it = value.iterator();
while (it.hasNext()) {
result[i++] = toNumber(it.next(), type);
}
return (T) result;
}
@SuppressWarnings("unchecked")
public static <T> T toNumber(final Object value, final Class<T> type) throws DataNotCompatibleException {
// System.out.println("Starting toNumber to get type " + T.getName() + " from a value of type " + value.getClass().getName());
if (value == null) {
return null;
}
if (value instanceof Vector && (((Vector<?>) value).isEmpty())) {
return null;
}
T result = null;
Object localValue = value;
if (value instanceof Collection) {
localValue = ((Collection<?>) value).iterator().next();
}
// System.out.println("LocalValue is type " + localValue.getClass().getName() + ": " + String.valueOf(localValue));
if (type == Integer.class) {
if (localValue instanceof String) {
result = (T) Integer.valueOf((String) localValue);
} else if (localValue instanceof Double) {
result = (T) Integer.valueOf(((Double) localValue).intValue());
} else if (localValue instanceof Integer) {
result = (T) localValue;
} else if (localValue instanceof Long) {
result = (T) Integer.valueOf(((Long) localValue).intValue());
} else {
throw new DataNotCompatibleException("Cannot create a " + type.getName() + " from a " + localValue.getClass().getName());
}
} else if (type == Long.class) {
if (localValue instanceof String) {
result = (T) Long.valueOf((String) localValue);
} else if (localValue instanceof Double) {
result = (T) Long.valueOf(((Double) localValue).longValue());
} else {
throw new DataNotCompatibleException("Cannot create a " + type.getName() + " from a " + localValue.getClass().getName());
}
} else if (type == Double.class) {
if (localValue instanceof String) {
result = (T) Double.valueOf((String) localValue);
} else if (localValue instanceof Double) {
result = (T) localValue;
} else if (localValue instanceof Integer) {
result = (T) Double.valueOf(((Integer) localValue).doubleValue());
} else if (localValue instanceof Short) {
result = (T) Double.valueOf(((Short) localValue).doubleValue());
} else if (localValue instanceof Float) {
result = (T) Double.valueOf(((Float) localValue).doubleValue());
} else {
throw new DataNotCompatibleException("Cannot create a " + type.getName() + " from a " + localValue.getClass().getName());
}
} else if (type == Short.class) {
if (localValue instanceof String) {
result = (T) Short.valueOf((String) localValue);
} else if (localValue instanceof Double) {
result = (T) Short.valueOf(((Double) localValue).shortValue());
} else {
throw new DataNotCompatibleException("Cannot create a " + type.getName() + " from a " + localValue.getClass().getName());
}
} else if (type == Byte.class) {
if (localValue instanceof String) {
result = (T) Byte.valueOf((String) localValue);
} else if (localValue instanceof Double) {
result = (T) Byte.valueOf(((Double) localValue).byteValue());
} else {
throw new DataNotCompatibleException("Cannot create a " + type.getName() + " from a " + localValue.getClass().getName());
}
} else if (type == Float.class) {
if (localValue instanceof String) {
result = (T) Float.valueOf((String) localValue);
} else if (localValue instanceof Double) {
result = (T) Float.valueOf(((Double) localValue).floatValue());
} else {
throw new DataNotCompatibleException("Cannot create a " + type.getName() + " from a " + localValue.getClass().getName());
}
} else if (type == java.math.BigDecimal.class) {
// Creating a BigDecimal from a Double is not recommended
if (localValue instanceof Double || localValue instanceof String) {
result = (T) new java.math.BigDecimal(localValue.toString());
} else {
throw new DataNotCompatibleException("Cannot create a " + type.getName() + " from a " + localValue.getClass().getName());
}
} else if (type == BigDecimal.class) {
if (localValue instanceof String) {
result = (T) new BigDecimal((String) localValue);
} else if (localValue instanceof Double) {
result = (T) new BigDecimal((Double) localValue);
} else {
throw new DataNotCompatibleException("Cannot create a " + type.getName() + " from a " + localValue.getClass().getName());
}
} else if (type == BigInteger.class) {
if (localValue instanceof String) {
result = (T) new BigInteger((String) localValue);
} else {
throw new DataNotCompatibleException("Cannot create a " + type.getName() + " from a " + localValue.getClass().getName());
}
} else if (type == AtomicInteger.class) {
if (localValue instanceof String) {
result = (T) new AtomicInteger(Integer.valueOf((String) localValue));
} else if (localValue instanceof Double) {
result = (T) new AtomicInteger(Integer.valueOf(((Double) localValue).intValue()));
} else {
throw new DataNotCompatibleException("Cannot create a " + type.getName() + " from a " + localValue.getClass().getName());
}
} else if (type == AtomicLong.class) {
if (localValue instanceof String) {
result = (T) new AtomicLong(Long.valueOf((String) localValue));
} else if (localValue instanceof Double) {
result = (T) new AtomicLong(Long.valueOf(((Double) localValue).longValue()));
} else {
throw new DataNotCompatibleException("Cannot create a " + type.getName() + " from a " + localValue.getClass().getName());
}
}
return result;
}
@SuppressWarnings("unchecked")
public static Boolean[] toBooleans(final Object value) {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToBooleans((Collection<Object>) value);
} else if (value.getClass().isArray()) {
return collectionToBooleans(Arrays.asList(value));
} else {
Boolean[] result = new Boolean[1];
result[0] = toBoolean(value);
return result;
}
}
public static Boolean[] collectionToBooleans(final Collection<Object> vector) {
if (vector == null || vector.isEmpty()) {
return new Boolean[0];
}
Boolean[] bools = new Boolean[vector.size()];
int i = 0;
for (Object o : vector) {
bools[i++] = toBoolean(o);
}
return bools;
}
public static boolean toBoolean(final Object value) {
if (value instanceof String) {
char[] c = ((String) value).toCharArray();
if (c.length > 1 || c.length == 0) {
return false;
} else {
return c[0] == '1';
}
} else if (value instanceof Double) {
if (((Double) value).intValue() == 0) {
return false;
} else {
return true;
}
} else if (value instanceof Vector) {
int size = ((Vector) value).size();
if (size == 0) {
return false;
} else if (size == 1) {
return toBoolean(((Vector) value).get(0));
} else {
System.err.println("Vector conversion failed because vector was size " + size);
}
} else if (value instanceof Boolean) {
return ((Boolean) value).booleanValue();
}
throw new DataNotCompatibleException("Cannot convert a " + value.getClass().getName() + " to boolean primitive.");
}
public static int toInt(final Object value) {
if (value instanceof Integer) {
return ((Integer) value).intValue();
} else if (value instanceof Double) {
return ((Double) value).intValue();
} else if (value instanceof CharSequence) {
String t = ((CharSequence) value).toString();
return Integer.parseInt(t.length() > 0 ? t : "0");
} else {
throw new DataNotCompatibleException("Cannot convert a " + value.getClass().getName() + " to int primitive.");
}
}
public static double toDouble(final Object value) {
if (value instanceof Integer) {
return ((Integer) value).doubleValue();
} else if (value instanceof Double) {
return ((Double) value).doubleValue();
} else if (value instanceof CharSequence) {
String t = ((CharSequence) value).toString();
return Double.parseDouble(t.length() > 0 ? t : "0");
} else {
throw new DataNotCompatibleException("Cannot convert a " + value.getClass().getName() + " to double primitive.");
}
}
public static long toLong(final Object value) {
if (value instanceof Integer) {
return ((Integer) value).longValue();
} else if (value instanceof Double) {
return ((Double) value).longValue();
} else if (value instanceof CharSequence) {
String t = ((CharSequence) value).toString();
return Long.parseLong(t.length() > 0 ? t : "0");
} else {
throw new DataNotCompatibleException("Cannot convert a " + value.getClass().getName() + " to long primitive.");
}
}
public static short toShort(final Object value) {
if (value instanceof Integer) {
return ((Integer) value).shortValue();
} else if (value instanceof Double) {
return ((Double) value).shortValue();
} else {
throw new DataNotCompatibleException("Cannot convert a " + value.getClass().getName() + " to short primitive.");
}
}
public static float toFloat(final Object value) {
if (value instanceof Integer) {
return ((Integer) value).floatValue();
} else if (value instanceof Double) {
return ((Double) value).floatValue();
} else {
throw new DataNotCompatibleException("Cannot convert a " + value.getClass().getName() + " to float primitive.");
}
}
@SuppressWarnings("unchecked")
public static Object toPrimitive(final Object value, final Class<?> ctype) {
if (value instanceof Collection) {
return toPrimitive((Collection<Object>) value, ctype);
} else {
if (ctype == Boolean.TYPE) {
return toBoolean(value);
}
if (ctype == Integer.TYPE) {
return toInt(value);
}
if (ctype == Short.TYPE) {
return toShort(value);
}
if (ctype == Long.TYPE) {
return toLong(value);
}
if (ctype == Float.TYPE) {
return toFloat(value);
}
if (ctype == Double.TYPE) {
return toDouble(value);
}
if (ctype == Byte.TYPE) {
throw new UnimplementedException("Primitive conversion for byte not yet defined");
}
if (ctype == Character.TYPE) {
throw new UnimplementedException("Primitive conversion for char not yet defined");
}
if (ctype == com.ibm.icu.lang.UCharacter.class) {
throw new UnimplementedException("Primitive conversion for char not yet defined");
}
throw new DataNotCompatibleException("");
}
}
public static Object toPrimitive(final Collection<Object> values, final Class<?> ctype) {
if (!ctype.isPrimitive()) {
throw new DataNotCompatibleException(ctype.getName() + " is not a primitive type.");
}
if (values.size() > 1) {
throw new DataNotCompatibleException("Cannot create a primitive " + ctype + " from data because we have a multiple values.");
}
if (values.isEmpty()) {
throw new DataNotCompatibleException("Cannot create a primitive " + ctype + " from data because we don't have any values.");
}
Iterator<Object> it = values.iterator();
if (ctype == Boolean.TYPE) {
return toBoolean(it.next());
}
if (ctype == Integer.TYPE) {
return toInt(it.next());
}
if (ctype == Short.TYPE) {
return toShort(it.next());
}
if (ctype == Long.TYPE) {
return toLong(it.next());
}
if (ctype == Float.TYPE) {
return toFloat(it.next());
}
if (ctype == Double.TYPE) {
return toDouble(it.next());
}
if (ctype == Byte.TYPE) {
throw new UnimplementedException("Primitive conversion for byte not yet defined");
}
if (ctype == Character.TYPE) {
throw new UnimplementedException("Primitive conversion for char not yet defined");
}
if (ctype == com.ibm.icu.lang.UCharacter.class) {
throw new UnimplementedException("Primitive conversion for char not yet defined");
}
throw new DataNotCompatibleException("");
}
public static String join(final Object[] values, final String separator) {
if (values == null || values.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (Object val : values) {
if (!isFirst) {
sb.append(separator);
}
sb.append(String.valueOf(val));
isFirst = false;
}
return sb.toString();
}
public static String join(final Collection<?> values, final String separator) {
if (values == null || values.isEmpty()) {
return "";
}
StringBuilder sb = new StringBuilder();
Iterator<?> it = values.iterator();
while (it.hasNext()) {
sb.append(StringUtil.toString(it.next()));
if (it.hasNext()) {
sb.append(separator);
}
}
return sb.toString();
}
public static String join(final Collection<?> values) {
return join(values, ", ");
}
public static String join(final Object[] values) {
return join(values, ", ");
}
@SuppressWarnings("unchecked")
public static Object toPrimitiveArray(final Object value, final Class<?> ctype) throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToPrimitiveArray((Collection<Object>) value, ctype);
} else if (value.getClass().isArray()) {
//TODO NTF this could be better, but I'm tired
return collectionToPrimitiveArray(Arrays.asList(value), ctype);
} else {
Object result = null;
if (ctype == Boolean.TYPE) {
boolean[] outcome = new boolean[1];
// TODO NTF - should allow for String fields that are binary sequences: "1001001" (SOS)
outcome[0] = toBoolean(value);
result = outcome;
} else if (ctype == Byte.TYPE) {
byte[] outcome = new byte[1];
// TODO
result = outcome;
} else if (ctype == Character.TYPE) {
char[] outcome = new char[0];
// TODO How should this work? Just concatenate the char arrays for each String?
result = outcome;
} else if (ctype == Short.TYPE) {
short[] outcome = new short[1];
outcome[0] = toShort(value);
result = outcome;
} else if (ctype == Integer.TYPE) {
int[] outcome = new int[1];
outcome[0] = toInt(value);
result = outcome;
} else if (ctype == Long.TYPE) {
long[] outcome = new long[1];
outcome[0] = toLong(value);
result = outcome;
} else if (ctype == Float.TYPE) {
float[] outcome = new float[1];
outcome[0] = toFloat(value);
result = outcome;
} else if (ctype == Double.TYPE) {
double[] outcome = new double[1];
outcome[0] = toDouble(value);
result = outcome;
}
return result;
}
}
public static Object collectionToPrimitiveArray(final Collection<Object> values, final Class<?> ctype)
throws DataNotCompatibleException {
Object result = null;
int size = values.size();
Iterator<Object> it = values.iterator();
int i = 0;
if (ctype == Boolean.TYPE) {
boolean[] outcome = new boolean[size];
// TODO NTF - should allow for String fields that are binary sequences: "1001001" (SOS)
while (it.hasNext()) {
outcome[i++] = toBoolean(it.next());
}
result = outcome;
} else if (ctype == Byte.TYPE) {
byte[] outcome = new byte[size];
// TODO
result = outcome;
} else if (ctype == Character.TYPE) {
char[] outcome = new char[size];
// TODO How should this work? Just concatenate the char arrays for each String?
result = outcome;
} else if (ctype == Short.TYPE) {
short[] outcome = new short[size];
while (it.hasNext()) {
outcome[i++] = toShort(it.next());
}
result = outcome;
} else if (ctype == Integer.TYPE) {
int[] outcome = new int[size];
while (it.hasNext()) {
outcome[i++] = toInt(it.next());
}
result = outcome;
} else if (ctype == Long.TYPE) {
long[] outcome = new long[size];
while (it.hasNext()) {
outcome[i++] = toLong(it.next());
}
result = outcome;
} else if (ctype == Float.TYPE) {
float[] outcome = new float[size];
while (it.hasNext()) {
outcome[i++] = toFloat(it.next());
}
result = outcome;
} else if (ctype == Double.TYPE) {
double[] outcome = new double[size];
while (it.hasNext()) {
outcome[i++] = toDouble(it.next());
}
result = outcome;
}
return result;
}
public static Date toDate(Object value) throws DataNotCompatibleException {
if (value instanceof Date) {
return (Date) value;
}
if (value == null) {
return null;
}
if (value instanceof Vector && (((Vector<?>) value).isEmpty())) {
return null;
}
if (value instanceof Vector) {
value = ((Vector<?>) value).get(0);
}
if (value instanceof Long) {
return new Date(((Long) value).longValue());
} else if (value instanceof String) {
// TODO finish
DateFormat df = DEFAULT_FORMAT.get();
String str = (String) value;
if (str.length() < 1) {
return null;
}
try {
synchronized (DEFAULT_FORMAT) {
return df.parse(str);
}
} catch (ParseException e) {
throw new DataNotCompatibleException("Cannot create a Date from String value " + (String) value);
}
} else if (value instanceof lotus.domino.DateTime) {
return DominoUtils.toJavaDateSafe((lotus.domino.DateTime) value);
} else if (value instanceof Date) {
return (Date) value;
} else {
throw new DataNotCompatibleException("Cannot create a Date from a " + value.getClass().getName());
}
}
@SuppressWarnings("unchecked")
public static Date[] toDates(final Object value) throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToDates((Collection<Object>) value);
} else if (value.getClass().isArray()) {
return collectionToDates(Arrays.asList(value));
} else if (value instanceof String) {
String valStr = (String) value;
if (valStr.contains("-")) {
String startStr = valStr.substring(0, valStr.indexOf('-') - 1).trim();
String endStr = valStr.substring(valStr.indexOf('-') + 1).trim();
Date[] result = new Date[2];
result[0] = toDate(startStr);
result[1] = toDate(endStr);
return result;
} else {
Date[] result = new Date[1];
result[0] = toDate(value);
return result;
}
} else {
Date[] result = new Date[1];
result[0] = toDate(value);
return result;
}
}
public static Date[] collectionToDates(final Collection<Object> vector) throws DataNotCompatibleException {
if (vector == null || vector.isEmpty()) {
return new Date[0];
}
Date[] result = new Date[vector.size()];
int i = 0;
for (Object o : vector) {
result[i++] = toDate(o);
}
return result;
}
@SuppressWarnings("unchecked")
public static org.openntf.domino.DateTime[] toDateTimes(final Object value, final org.openntf.domino.Session session)
throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToDateTimes((Collection<Object>) value, session);
} else if (value.getClass().isArray()) {
return collectionToDateTimes(Arrays.asList(value), session);
} else {
org.openntf.domino.DateTime[] result = new org.openntf.domino.DateTime[1];
result[0] = session.createDateTime(toDate(value));
;
return result;
}
}
@SuppressWarnings("unchecked")
public static org.openntf.domino.DateRange[] toDateRanges(final Object value, final org.openntf.domino.Session session)
throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToDateRanges((Collection<Object>) value, session);
} else if (value.getClass().isArray()) {
return collectionToDateRanges(Arrays.asList(value), session);
} else {
org.openntf.domino.DateRange[] result = new org.openntf.domino.DateRange[1];
Date[] dates = toDates(value);
result[0] = session.createDateRange(dates[0], dates[1]);
return result;
}
}
public static org.openntf.domino.DateTime[] collectionToDateTimes(final Collection<Object> vector,
final org.openntf.domino.Session session) throws DataNotCompatibleException {
if (vector == null || vector.isEmpty()) {
return new org.openntf.domino.DateTime[0];
}
org.openntf.domino.DateTime[] result = new org.openntf.domino.DateTime[vector.size()];
if (session != null) {
int i = 0;
for (Object o : vector) {
result[i++] = session.createDateTime(toDate(o));
}
return result;
} else {
throw new IllegalArgumentException("Cannont convert to DateTime without a valid Session object");
}
}
public static org.openntf.domino.DateTime toDateTime(final Object raw, final org.openntf.domino.Session session)
throws DataNotCompatibleException {
if (raw == null) {
return null;
}
if (session != null) {
return session.createDateTime(toDate(raw));
} else {
throw new IllegalArgumentException("Cannont convert to DateTime without a valid Session object");
}
}
public static org.openntf.domino.DateRange toDateRange(final Object raw, final org.openntf.domino.Session session)
throws DataNotCompatibleException {
if (raw == null) {
return null;
}
if (session != null) {
if (raw instanceof Vector && ((Vector) raw).size() == 2) {
System.out.println("TEMP DEBUG processing a size 2 vector to DateRange");
Object startRaw = ((Vector) raw).get(0);
Object endRaw = ((Vector) raw).get(1);
if (startRaw instanceof DateTime && endRaw instanceof DateTime) {
System.out.println("TEMP DEBUG processing a DateTime pair into a DateRange");
return session.createDateRange((DateTime) startRaw, (DateTime) endRaw);
} else {
throw new IllegalArgumentException("Can't convert a Vector to DateRange where the elements are "
+ startRaw.getClass().getName() + " and " + endRaw.getClass().getName());
}
} else {
Date[] dates = toDates(raw);
return session.createDateRange(dates[0], dates[1]);
}
} else {
throw new IllegalArgumentException("Cannont convert to DateTime without a valid Session object");
}
}
public static org.openntf.domino.DateRange[] collectionToDateRanges(final Collection<Object> vector,
final org.openntf.domino.Session session) throws DataNotCompatibleException {
if (vector == null || vector.isEmpty()) {
return new org.openntf.domino.DateRange[0];
}
org.openntf.domino.DateRange[] result = new org.openntf.domino.DateRange[vector.size()];
if (session != null) {
int i = 0;
for (Object o : vector) {
Date[] dates = toDates(o);
result[i++] = session.createDateRange(dates[0], dates[1]);
}
return result;
} else {
throw new IllegalArgumentException("Cannont convert to DateRange without a valid Session object");
}
}
@SuppressWarnings("unchecked")
public static org.openntf.domino.Name[] toNames(final Object value, final org.openntf.domino.Session session)
throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToNames((Collection<Object>) value, session);
} else if (value.getClass().isArray()) {
return collectionToNames(Arrays.asList(value), session);
} else {
org.openntf.domino.Name[] result = new org.openntf.domino.Name[1];
result[0] = session.createName(String.valueOf(value));
return result;
}
}
public static org.openntf.domino.Name[] collectionToNames(final Collection<Object> vector, final org.openntf.domino.Session session)
throws DataNotCompatibleException {
if (vector == null || vector.isEmpty()) {
return new org.openntf.domino.Name[0];
}
org.openntf.domino.Name[] result = new org.openntf.domino.Name[vector.size()];
if (session != null) {
int i = 0;
for (Object o : vector) {
result[i++] = session.createName(String.valueOf(o));
}
return result;
} else {
throw new IllegalArgumentException("Cannont convert to Name without a valid Session object");
}
}
@SuppressWarnings("unchecked")
public static String[] toStrings(final Object value) throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToStrings((Collection<Object>) value);
} else if (value.getClass().isArray()) {
Object[] arr = (Object[]) value;
String[] result = new String[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = String.valueOf(arr[i]);
}
return result;
} else {
String[] result = new String[1];
result[0] = String.valueOf(value);
return result;
}
}
public static String[] collectionToStrings(final Collection<Object> vector) throws DataNotCompatibleException {
if (vector == null || vector.isEmpty()) {
return new String[0];
}
String[] strings = new String[vector.size()];
int i = 0;
// strings = vector.toArray(new String[0]);
for (Object o : vector) {
if (o instanceof org.openntf.domino.DateTime) {
strings[i++] = ((org.openntf.domino.DateTime) o).getGMTTime();
} else {
strings[i++] = String.valueOf(o);
}
}
return strings;
}
public static String toString(final java.lang.Object object) throws DataNotCompatibleException {
if (object == null) {
return null;
}
if (object instanceof String) {
String result = (String) object;
// System.out.println("Object is a String: '" + result + "'");
return result;
} else if (object instanceof Collection) {
return join((Collection<?>) object);
} else if (object.getClass().isArray()) {
return join((Object[]) object);
} else {
// System.out.println("Converting a " + object.getClass().getName() + " to a String");
return String.valueOf(object);
}
}
@SuppressWarnings("unchecked")
public static Pattern[] toPatterns(final Object value) throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToPatterns((Collection<Object>) value);
} else if (value.getClass().isArray()) {
return collectionToPatterns(Arrays.asList(value));
} else {
Pattern[] result = new Pattern[1];
result[0] = Pattern.compile(String.valueOf(value));
return result;
}
}
public static Pattern[] collectionToPatterns(final Collection<Object> vector) throws DataNotCompatibleException {
if (vector == null || vector.isEmpty()) {
return new Pattern[0];
}
Pattern[] patterns = new Pattern[vector.size()];
int i = 0;
for (Object o : vector) {
patterns[i++] = Pattern.compile(String.valueOf(o));
}
return patterns;
}
@SuppressWarnings("unchecked")
public static java.lang.Object[] toObjects(final Object value) throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToObjects((Collection<Object>) value);
} else if (value.getClass().isArray()) {
return collectionToObjects(Arrays.asList(value));
} else {
java.lang.Object[] result = new java.lang.Object[1];
result[0] = value;
return result;
}
}
public static java.lang.Object[] collectionToObjects(final Collection<Object> vector) throws DataNotCompatibleException {
if (vector == null || vector.isEmpty()) {
return new Object[0];
}
Object[] patterns = new Object[vector.size()];
int i = 0;
for (Object o : vector) {
patterns[i++] = o;
}
return patterns;
}
@SuppressWarnings("unchecked")
public static Class<?>[] toClasses(final Object value) throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToClasses((Collection<Object>) value);
} else if (value.getClass().isArray()) {
return collectionToClasses(Arrays.asList(value));
} else {
Class<?>[] classes = new Class[1];
String cn = String.valueOf(value);
Class<?> cls = DominoUtils.getClass(cn);
classes[0] = cls;
return classes;
}
}
public static Class<?>[] collectionToClasses(final Collection<Object> vector) throws DataNotCompatibleException {
if (vector == null || vector.isEmpty()) {
return new Class[0];
}
@SuppressWarnings("unused")
ClassLoader cl = Factory.getClassLoader();
Class<?>[] classes = new Class[vector.size()];
int i = 0;
for (Object o : vector) {
int pos = i++;
String cn = String.valueOf(o);
Class<?> cls = DominoUtils.getClass(cn);
classes[pos] = cls;
}
return classes;
}
public static NoteCoordinate[] collectionToNoteCoordinates(final Collection<Object> vector) throws DataNotCompatibleException {
if (vector == null || vector.isEmpty()) {
return new NoteCoordinate[0];
}
NoteCoordinate[] results = new NoteCoordinate[vector.size()];
int i = 0;
for (Object o : vector) {
int pos = i++;
if (o instanceof NoteCoordinate) {
results[pos] = (NoteCoordinate) o;
} else {
String cn = String.valueOf(o);
results[pos] = toNoteCoordinate(cn);
}
}
return results;
}
public static Enum<?> toEnum(final Object value, final Class<?> enumClass) throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Vector && (((Vector<?>) value).isEmpty())) {
return null;
}
if (enumClass == null) {
return null;
}
Enum<?> result = null;
String ename = String.valueOf(value);
if (ename.contains(" ")) {
ename = String.valueOf(value).substring(ename.indexOf(' ') + 1).trim();
}
Object[] objs = enumClass.getEnumConstants();
if (objs.length > 0) {
for (Object obj : objs) {
if (obj instanceof Enum) {
if (((Enum<?>) obj).name().equals(ename)) {
result = (Enum<?>) obj;
break;
}
}
}
}
if (result == null) {
throw new DataNotCompatibleException("Unable to discover an Enum by the name of " + ename + " in class " + enumClass);
}
return result;
}
public static NoteCoordinate toNoteCoordinate(final Object value) throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof CharSequence) {
return NoteCoordinate.Utils.getNoteCoordinate((CharSequence) value);
} else if (value instanceof NoteCoordinate) {
return (NoteCoordinate) value;
} else {
throw new IllegalArgumentException("Cannont convert a " + value.getClass().getName() + " to NoteCoordinate");
}
}
public static NoteCoordinate[] toNoteCoordinates(final Object value) throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToNoteCoordinates((Collection<Object>) value);
} else if (value.getClass().isArray()) {
return collectionToNoteCoordinates(Arrays.asList(value));
} else {
NoteCoordinate[] results = new NoteCoordinate[1];
results[0] = toNoteCoordinate(value);
return results;
}
}
public static Enum<?> toEnum(final Object value) throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Vector && (((Vector<?>) value).isEmpty())) {
return null;
}
Enum<?> result = null;
String en = String.valueOf(value);
String ename = null;
String cn = null;
if (en.indexOf(' ') > 0) {
cn = String.valueOf(value).substring(0, en.indexOf(' ')).trim();
ename = String.valueOf(value).substring(en.indexOf(' ') + 1).trim();
}
if (cn == null || ename == null) {
// System.out.println("ALERT! This isn't going to work. cn is " + String.valueOf(cn) + " and ename is " + String.valueOf(ename));
} else {
try {
Class<?> cls = DominoUtils.getClass(cn);
if (cls == null) {
Factory.println("Unable to load class " + cn);
} else {
result = toEnum(ename, cls);
}
} catch (Exception e) {
DominoUtils.handleException(e);
}
}
return result;
}
@SuppressWarnings("unchecked")
public static Enum<?>[] toEnums(final Object value) throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToEnums((Collection<Object>) value);
} else if (value.getClass().isArray()) {
return collectionToEnums(Arrays.asList(value));
} else {
Enum<?>[] classes = new Enum[1];
classes[0] = toEnum(value);
return classes;
}
}
public static Enum<?>[] collectionToEnums(final Collection<Object> vector) throws DataNotCompatibleException {
if (vector == null || vector.isEmpty()) {
return new Enum[0];
}
ClassLoader cl = Factory.getClassLoader();
Enum<?>[] classes = new Enum[vector.size()];
int i = 0;
for (Object o : vector) {
int pos = i++;
String en = String.valueOf(o);
String ename = null;
String cn = null;
if (en.indexOf(' ') > 0) {
cn = String.valueOf(o).substring(0, en.indexOf(' ')).trim();
ename = String.valueOf(o).substring(en.indexOf(' ') + 1).trim();
}
try {
Class<?> cls = Class.forName(cn, false, cl);
for (Object obj : cls.getEnumConstants()) {
if (obj instanceof Enum) {
if (((Enum<?>) obj).name().equals(ename)) {
classes[pos] = (Enum<?>) obj;
}
}
}
} catch (ClassNotFoundException e) {
System.out.println("Failed to find class " + cn + " using a classloader of type " + cl.getClass().getName());
DominoUtils.handleException(e);
classes[pos] = null;
}
}
return classes;
}
@SuppressWarnings("unchecked")
public static Formula[] toFormulas(final Object value) throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToFormulas((Collection<Object>) value);
} else if (value.getClass().isArray()) {
return collectionToFormulas(Arrays.asList(value));
} else {
Formula[] strings = new Formula[1];
strings[0] = new org.openntf.domino.helpers.Formula(String.valueOf(value));
return strings;
}
}
public static Formula[] collectionToFormulas(final Collection<Object> vector) throws DataNotCompatibleException {
if (vector == null || vector.isEmpty()) {
return new Formula[0];
}
Formula[] formulas = new Formula[vector.size()];
int i = 0;
for (Object o : vector) {
Formula formula = new org.openntf.domino.helpers.Formula(String.valueOf(o));
formulas[i++] = formula;
}
return formulas;
}
@SuppressWarnings("unchecked")
public static BigString[] toBigStrings(final Object value) throws DataNotCompatibleException {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToBigStrings((Collection<Object>) value);
} else if (value.getClass().isArray()) {
return collectionToBigStrings(Arrays.asList(value));
} else {
BigString[] strings = new BigString[1];
strings[0] = new BigString(String.valueOf(value));
return strings;
}
}
public static BigString[] collectionToBigStrings(final Collection<Object> vector) throws DataNotCompatibleException {
if (vector == null || vector.isEmpty()) {
return new BigString[0];
}
BigString[] strings = new BigString[vector.size()];
int i = 0;
for (Object o : vector) {
if (o instanceof org.openntf.domino.DateTime) {
strings[i++] = new BigString(((org.openntf.domino.DateTime) o).getGMTTime());
} else {
strings[i++] = new BigString(String.valueOf(o));
}
}
return strings;
}
@SuppressWarnings("unchecked")
public static int[] toIntArray(final Object value) {
if (value == null) {
return null;
}
if (value instanceof Collection) {
return collectionToIntArray((Collection<Integer>) value);
} else if (value.getClass().isArray()) {
if (value instanceof int[]) {
return (int[]) value;
}
throw new DataNotCompatibleException("Can't convert an array of " + value.getClass().getName() + " to an int[] yet");
} else {
int[] ret = new int[1];
ret[0] = toInt(value);
return ret;
}
}
public static int[] collectionToIntArray(final Collection<Integer> coll) {
int[] ret = new int[coll.size()];
Iterator<Integer> iterator = coll.iterator();
for (int i = 0; i < ret.length; i++) {
ret[i] = iterator.next().intValue();
}
return ret;
}
public static short[] collectionToShortArray(final Collection<Short> coll) {
short[] ret = new short[coll.size()];
Iterator<Short> iterator = coll.iterator();
for (int i = 0; i < ret.length; i++) {
Short s = iterator.next();
ret[i] = s.shortValue();
}
return ret;
}
public static long[] collectionToLongArray(final Collection<Long> coll) {
long[] ret = new long[coll.size()];
Iterator<Long> iterator = coll.iterator();
for (int i = 0; i < ret.length; i++) {
ret[i] = iterator.next().longValue();
}
return ret;
}
public static byte[] collectionToByteArray(final Collection<Byte> coll) {
byte[] ret = new byte[coll.size()];
Iterator<Byte> iterator = coll.iterator();
for (int i = 0; i < ret.length; i++) {
ret[i] = iterator.next().byteValue();
}
return ret;
}
public static boolean isFriendlyVector(final Object value) {
if (!(value instanceof Vector)) {
return false;
}
for (Object v : (Vector<?>) value) {
if (v instanceof String || v instanceof Integer || v instanceof Double) {
} else {
return false;
}
}
return true;
}
/**
* returns the payload that the Object o needs when it is written into an item
*
* @param o
* @param c
* @return
*/
public static int getLotusPayload(final Object o, final Class<?> c) {
if (c.isAssignableFrom(o.getClass())) {
if (o instanceof String) {
return ((String) o).length(); // LMBCS investigation will be done later (in general not necessary)
}
if (o instanceof lotus.domino.DateRange) {
return 16;
} else {
return 8; // Number + DateTime has 8 bytes payload
}
}
throw new DataNotCompatibleException("Got a " + o.getClass() + " but " + c + " expected");
}
public static Item writeToItem(@Nonnull final org.openntf.domino.Document doc, @Nonnull final String itemName, @Nonnull Object value,
final Boolean isSummary) throws Domino32KLimitException {
Class<?> fromClass = value.getClass();
CustomConverter converter = findCustomConverter(fromClass);
if (converter != null) {
//look for customConverter
Class<?> toClass = converter.getTo();
if (MIMEEntity.class.isAssignableFrom(toClass) || Item.class.isAssignableFrom(toClass)) {
converter.put(doc, itemName, value);
return doc.getAncestorSession().getFactory().create(Item.SCHEMA, doc, itemName);
} else {
value = converter.convert(value);
}
}
Vector<Object> dominoFriendlyVec = null;
Object dominoFriendlyObj = null;
List<lotus.domino.Base> recycleThis = null;
boolean isNonSummary = false;
boolean isNames = false;
lotus.domino.Item result;
try {
// first step: Make it domino friendly and put all converted objects into "dominoFriendly"
if (value instanceof String || value instanceof Integer || value instanceof Double) {
dominoFriendlyObj = value;
} else if (value instanceof Collection) {
if (isFriendlyVector(value)) {
recycleThis = null;
dominoFriendlyVec = (Vector<Object>) value;
} else {
recycleThis = new ArrayList<lotus.domino.Base>();
Collection<?> coll = (Collection<?>) value;
dominoFriendlyVec = new Vector<Object>(coll.size());
for (Object valNode : coll) {
if (valNode != null) { // CHECKME: Should NULL values discarded?
if (valNode instanceof BigString) {
isNonSummary = true;
}
if (valNode instanceof Name) {
isNames = true;
}
dominoFriendlyVec.add(toItemFriendly(valNode, doc.getAncestorSession(), recycleThis));
}
}
}
} else if (value.getClass().isArray()) {
recycleThis = new ArrayList<lotus.domino.Base>();
int lh = Array.getLength(value);
if (lh > org.openntf.domino.Document.MAX_NATIVE_FIELD_SIZE) { // Then skip making dominoFriendly if it's a primitive
String cn = value.getClass().getName();
if (cn.length() == 2) { // It is primitive
throw new Domino32KLimitException();
}
}
dominoFriendlyVec = new Vector<Object>(lh);
for (int i = 0; i < lh; i++) {
Object o = Array.get(value, i);
if (o != null) { // CHECKME: Should NULL values be discarded?
if (o instanceof BigString) {
isNonSummary = true;
}
if (o instanceof Name) {
isNames = true;
}
dominoFriendlyVec.add(toItemFriendly(o, doc.getAncestorSession(), recycleThis));
}
}
} else { // Scalar
recycleThis = new ArrayList<lotus.domino.Base>();
if (value instanceof BigString) {
isNonSummary = true;
}
if (value instanceof Name) {
isNames = true;
}
dominoFriendlyObj = toItemFriendly(value, doc.getAncestorSession(), recycleThis);
}
Object firstElement = null;
// empty vectors are treated as "null"
if (dominoFriendlyObj == null) {
if (dominoFriendlyVec == null || dominoFriendlyVec.size() == 0) {
return ((org.openntf.domino.impl.Document) doc).replaceItemValueLotus(itemName, null, isSummary, true);
} else {
firstElement = dominoFriendlyVec.get(0);
}
} else {
firstElement = dominoFriendlyObj;
}
int payloadOverhead = 0;
if (dominoFriendlyVec != null && dominoFriendlyVec.size() > 1) { // compute overhead first for multi values
// String lists have an global overhead of 2 bytes (maybe the count of values) + 2 bytes for the length of value
if (firstElement instanceof String) {
payloadOverhead = 2 + 2 * dominoFriendlyVec.size();
} else {
payloadOverhead = 4;
}
}
// Next step: Type checking + length computation
// Remark: The special case of a String consisting of only ONE @NewLine (i.e.
// if (s.equals("\n") || s.equals("\r") || s.equals("\r\n"))
// where Domino is a bit ailing) won't be extra considered any longer.
// Neither serialization nor throwing an exception would be reasonable here.
int payload = payloadOverhead;
Class<?> firstElementClass;
if (firstElement instanceof String) {
firstElementClass = String.class;
} else if (firstElement instanceof Number) {
firstElementClass = Number.class;
} else if (firstElement instanceof lotus.domino.DateTime) {
firstElementClass = lotus.domino.DateTime.class;
} else if (firstElement instanceof lotus.domino.DateRange) {
firstElementClass = lotus.domino.DateRange.class;
// Remark: Domino Java API doesn't accept any Vector of DateRanges (cf. DateRange.java), so the implementation
// here will work only with Vectors of size 1 (or Vectors of size >= 2000, when Mime Beaning is enabled).
} else {
throw new DataNotCompatibleException(firstElement.getClass() + " is not a supported data type");
}
if (dominoFriendlyVec != null) {
for (Object o : dominoFriendlyVec) {
payload += getLotusPayload(o, firstElementClass);
}
} else {
payload += getLotusPayload(dominoFriendlyObj, firstElementClass);
}
if (payload > org.openntf.domino.Document.MAX_NATIVE_FIELD_SIZE) {
// the datatype is OK, but there's no way to store the data in the Document
throw new Domino32KLimitException();
}
if (firstElementClass == String.class) { // Strings have to be further inspected, because
// each sign may demand up to 3 bytes in LMBCS
int calc = ((payload - payloadOverhead) * 3) + payloadOverhead;
if (calc >= org.openntf.domino.Document.MAX_NATIVE_FIELD_SIZE) {
if (dominoFriendlyVec != null) {
payload = payloadOverhead + LMBCSUtils.getPayload(dominoFriendlyVec);
} else {
payload = payloadOverhead + LMBCSUtils.getPayload((String) dominoFriendlyObj);
}
if (payload > org.openntf.domino.Document.MAX_NATIVE_FIELD_SIZE) {
throw new Domino32KLimitException();
}
}
}
if (payload > org.openntf.domino.Document.MAX_NATIVE_FIELD_SIZE) {
isNonSummary = true;
}
MIMEEntity mimeChk = doc.getMIMEEntity(itemName);
if (mimeChk != null) {
try {
mimeChk.remove();
} finally {
doc.closeMIMEEntities(true, itemName);
}
}
((org.openntf.domino.impl.Document) doc).beginEdit();
if (dominoFriendlyVec == null || dominoFriendlyVec.size() == 1) {
result = ((lotus.domino.Document) ImplUtils.getLotus(doc)).replaceItemValue(itemName, firstElement);
} else {
result = ((lotus.domino.Document) ImplUtils.getLotus(doc)).replaceItemValue(itemName, dominoFriendlyVec);
}
((org.openntf.domino.impl.Document) doc).markDirty(itemName, true);
if (isSummary == null) {
if (isNonSummary) {
result.setSummary(false);
}
} else {
result.setSummary(isSummary.booleanValue());
}
if (value instanceof ReadersList) {
result.setReaders(true);
} else if (value instanceof AuthorsList) {
result.setAuthors(true);
} else if (value instanceof NamesList || isNames) {
result.setNames(true);
}
ImplUtils.recycle(result);
} catch (NotesException ex) {
DominoUtils.handleException(ex, doc, "Item=" + itemName);
} finally {
ImplUtils.recycle(recycleThis);
}
return doc.getAncestorSession().getFactory().create(Item.SCHEMA, doc, itemName);
}
public static Object toItemFriendly(final Object value, final Session session, final Collection<lotus.domino.Base> recycleThis)
throws IllegalArgumentException {
if (value == null) {
return null;
}
if (value instanceof lotus.domino.Base) {
if (value instanceof lotus.domino.Name) {
// Names are written as canonical
try {
return ((lotus.domino.Name) value).getCanonical();
} catch (NotesException e) {
DominoUtils.handleException(e);
}
} else if (value instanceof org.openntf.formula.DateTime) {
return javaToDominoFriendly(value, session, recycleThis);
} else if (value instanceof org.openntf.domino.DateTime || value instanceof org.openntf.domino.DateRange) {
// according to documentation, these datatypes should be compatible to write to a field ... but DateRanges make problems
return toLotus((org.openntf.domino.Base<?>) value, recycleThis);
} else if (value instanceof lotus.domino.DateTime || value instanceof lotus.domino.DateRange) {
return value;
}
throw new IllegalArgumentException("Cannot convert to Domino friendly from type " + value.getClass().getName());
} else {
return javaToDominoFriendly(value, session, recycleThis);
}
}
public static java.util.Vector<Object> toDominoFriendly(final Collection<?> values, final Session session,
final Collection<lotus.domino.Base> recycleThis) throws IllegalArgumentException {
java.util.Vector<Object> result = new java.util.Vector<Object>();
for (Object value : values) {
result.add(toDominoFriendly(value, session, recycleThis));
}
return result;
}
@SuppressWarnings("rawtypes")
public static Object toDominoFriendly(final Object value, final Session session, final Collection<lotus.domino.Base> recycleThis)
throws IllegalArgumentException {
if (value == null) {
return null;
}
//Extended in order to deal with Arrays
if (value.getClass().isArray()) {
int i = Array.getLength(value);
java.util.Vector<Object> result = new java.util.Vector<Object>(i);
for (int k = 0; k < i; ++k) {
Object o = Array.get(value, k);
result.add(toDominoFriendly(o, session, recycleThis));
}
return result;
}
if (value instanceof Collection) {
java.util.Vector<Object> result = new java.util.Vector<Object>();
Collection<?> coll = (Collection) value;
for (Object o : coll) {
result.add(toDominoFriendly(o, session, recycleThis));
}
return result;
}
if (value instanceof org.openntf.domino.Base) {
// this is a wrapper
return toLotus((org.openntf.domino.Base) value, recycleThis);
} else if (value instanceof lotus.domino.Base) {
// this is already domino friendly
return value;
} else {
return javaToDominoFriendly(value, session, recycleThis);
}
}
/**
* converts a lot of java types to domino-friendly types
*
* @param value
* @param context
* @param recycleThis
* @return
*/
public static Object javaToDominoFriendly(final Object value, final Session session, final Collection<lotus.domino.Base> recycleThis) {
//FIXME NTF This stuff should really defer to TypeUtils. We should do ALL type coercion in that utility class
if (value instanceof Integer || value instanceof Double) {
return value;
} else if (value instanceof String) {
return value;
} else if (value.getClass().isPrimitive()) {
//FIXME: NTF IS A COMPLETE HACK!!!! (but we just want to know if it'll fix PWithers' problem)
Class<?> cl = value.getClass();
if (cl == Boolean.TYPE) {
if ((Boolean) value) {
return "1";
} else {
return "0";
}
}
} else if (value instanceof Boolean) {
if ((Boolean) value) {
return "1";
} else {
return "0";
}
} else if (value instanceof Character) {
return value.toString();
}
if (value instanceof Number) {
// TODO Check if this is greater than what Domino can handle and serialize if so
// CHECKME: Is "doubleValue" really needed. (according to help.nsf only Integer and Double is supported, so keep it)
return ((Number) value).doubleValue();
} else if (value instanceof java.util.Date || value instanceof java.sql.Date || value instanceof java.util.Calendar
|| value instanceof org.openntf.formula.DateTime) {
lotus.domino.Session lsess = toLotus(session);
try {
lotus.domino.DateTime dt = null;
if (value instanceof java.sql.Time) {
dt = lsess.createDateTime((java.sql.Time) value);
dt.setAnyDate();
} else if (value instanceof java.sql.Date) {
dt = lsess.createDateTime((java.sql.Date) value);
dt.setAnyTime();
} else if (value instanceof java.util.Date) {
dt = lsess.createDateTime((java.util.Date) value);
} else if (value instanceof org.openntf.formula.DateTime) {
org.openntf.formula.DateTime fdt = (org.openntf.formula.DateTime) value;
dt = lsess.createDateTime(fdt.toJavaDate());
if (fdt.isAnyDate()) {
dt.setAnyDate();
}
if (fdt.isAnyTime()) {
dt.setAnyTime();
}
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Calendar intermediate = (java.util.Calendar) value;
dt = lsess.createDateTime(sdf.format(intermediate.getTime()) + " " + intermediate.getTimeZone().getID());
}
if (recycleThis != null) {
recycleThis.add(dt);
}
return dt;
} catch (Throwable t) {
DominoUtils.handleException(t);
return null;
}
} else if (value instanceof CharSequence) {
return value.toString();
} else if (value instanceof Pattern) {
return ((Pattern) value).pattern();
} else if (value instanceof Class<?>) {
return ((Class<?>) value).getName();
} else if (value instanceof Enum<?>) {
return ((Enum<?>) value).getDeclaringClass().getName() + " " + ((Enum<?>) value).name();
} else if (value instanceof Formula) {
return ((Formula) value).getExpression();
} else if (value instanceof NoteCoordinate) {
return ((NoteCoordinate) value).toString();
}
throw new IllegalArgumentException("Cannot convert to Domino friendly from type " + value.getClass().getName());
}
/**
* gets the delegate
*
* @param wrapper
* the wrapper
* @param recycleThis
* adds the delegate to the list, if it has to be recycled.
* @return the delegate
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T extends lotus.domino.Base> T toLotus(final T wrapper, final Collection recycleThis) {
if (wrapper instanceof org.openntf.domino.impl.Base) {
lotus.domino.Base ret = ImplUtils.getLotus((org.openntf.domino.Base) wrapper);
if (wrapper instanceof Encapsulated && recycleThis != null) {
recycleThis.add(ret);
}
return (T) ret;
}
return wrapper;
}
/**
* Gets the delegate.
*
* @param wrapper
* the wrapper
* @return the delegate
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T extends lotus.domino.Base> T toLotus(final T wrapper) {
if (wrapper instanceof org.openntf.domino.impl.Base) {
return (T) ImplUtils.getLotus((org.openntf.domino.Base) wrapper);
}
return wrapper;
}
/**
* To lotus.
*
* @param values
* the values
* @return the java.util. vector
*/
public static java.util.Vector<Object> toLotus(final Collection<?> values) {
if (values == null) {
return null;
} else {
java.util.Vector<Object> result = new java.util.Vector<Object>(values.size());
for (Object value : values) {
if (value instanceof lotus.domino.Base) {
result.add(toLotus((lotus.domino.Base) value));
} else {
result.add(value);
}
}
return result;
}
}
}
|
package BeanBagger;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
import java.util.Set;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.management.*;
import javax.management.ObjectInstance;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
/**
*
* @author s.ostenberg
*/
public class BeanBagger {
private static final String CONNECTOR_ADDRESS_PROPERTY = "com.sun.management.jmxremote.localConnectorAddress";
public static VirtualMachineDescriptor TARGETDESCRIPTOR ;
static JMXConnector myJMXconnector = null;
//replace these with MBean
// public static String TargetJVM = "";
//public static String TARGETBEAN = "";
// public static boolean ExactMatchRequired = false; // ALlows matching TargetVM process based on substring
// public static String OUTFILE = "//tmp//output.yml";
// public static boolean suppresscomplex=true;
// public static boolean ignoreunreadable=false;
// public static boolean supressSun=false;
// public static String JSONFile = "";//The file we will output to.
// public static boolean outJSON=false;//Turn on JSON output
// public static boolean prettyprint=false;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
//Get the MBean server
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
//register the MBean
BBConfig mBean = new BBConfig();
ObjectName name = new ObjectName("com.stiv.jmx:type=SystemConfig");
mbs.registerMBean(mBean, name);
for(int x =0;x<args.length;x++)
{
String disarg = args[x];
switch(disarg)
{
case "-p":
if(x==args.length && !args[x+1].startsWith("-"))Usage();
mBean.setTargetJVM(args[x+1]);
x++;
break;
case "-ppj" :
mBean.setoutJSON(true);
mBean.setprettyprint(true);
break;
case "-j":
mBean.setoutJSON(true);
if(args.length-1>x && !args[x+1].startsWith("-"))//If next item on line exists and is not an option
{
mBean.setJSONFile(args[x+1]);
x++;
}
break;
case "-b":
if(args.length-1>x && !args[x+1].startsWith("-"))
{
mBean.setTARGETBEAN(args[x+1]);
x++;
}
break;
case "-r":
mBean.setignoreunreadable(true);
break;
case "-q":
mBean.setsuppresscomplex(false);
break;
case "-m":
mBean.setsupressSun(true);
break;
case "-x":
mBean.setExactMatchRequired(true);
break;
case "-l":
mBean.setLoop(true);
if(args.length-1>x && !args[x+1].startsWith("-"))
{
try{
mBean.setLoopDelaySeconds(Integer.parseInt(args[x+1]));}
catch(Exception ex){
System.out.println("You call " + args[x+1] + " an integer" +mBean.getInsult()+"?");
Usage();
}
x++;
}
else{mBean.setLoopDelaySeconds(30); }
break;
case "-c":
mBean.setLoop(true);
if(args.length-1>x && !args[x+1].startsWith("-"))
{
try{
mBean.setIterations(Integer.parseInt(args[x+1]));}
catch(Exception ex){
System.out.println("You call " + args[x+1] + " an integer" +mBean.getInsult()+"?");
Usage();
}
x++;
}
else{mBean.setIterations(5);}
break;
default:
Usage();
}//End switch
}
//Variables have been set. We are done with intitial config
Boolean loopagain=false;
do { //Here we go, into da loop
try {
Map<String, VirtualMachine> result = new HashMap<>();
List<VirtualMachineDescriptor> list = VirtualMachine.list();
List<VirtualMachineDescriptor> MATCHINGLIST = new ArrayList<VirtualMachineDescriptor>();
Boolean gotit = false;
String listofjvs = "";
System.out.println("Searching for matching VM instances");
for (VirtualMachineDescriptor vmd : list) {
String desc = vmd.toString();
try {
result.put(desc, VirtualMachine.attach(vmd));
String DN = vmd.displayName();
if (DN.contains(mBean.getTargetJVM()) || mBean.getTargetJVM().equalsIgnoreCase("*")) {
if (DN.equals("")) {
System.out.println(" Skipping unnamed JVM");
} //else if(!TargetJVM.startsWith("BeanBagger") && DN.contains("BeanBagger")){ System.out.println(" Skipping BeanBagger JVM"); }
else {
System.out.println(" Matching JVM instance found: " + DN);
TARGETDESCRIPTOR = vmd;
gotit = true;
MATCHINGLIST.add(vmd);
}
} else {
listofjvs += DN + " \n";
}
} catch (IOException | AttachNotSupportedException e) {
}
}
if (!gotit)//If we dont find the instance.
{
System.out.println("No JVM Processes matching " + mBean.getTargetJVM() + " were found.");
System.out.println("Found instances: " + listofjvs);
System.exit(1);
}
System.out.println("");
org.json.JSONObject Jinfrascan = new org.json.JSONObject();//Contains Hosts
org.json.JSONArray Hosts = new org.json.JSONArray();
org.json.JSONObject Host = new org.json.JSONObject();
org.json.JSONArray JVMs = new org.json.JSONArray();//JVMs on host
for (VirtualMachineDescriptor avmd : MATCHINGLIST) {
myJMXconnector = getLocalConnection(VirtualMachine.attach(avmd));// Connects to the process containing our beans
MBeanServerConnection myJMXConnection = myJMXconnector.getMBeanServerConnection(); //Connects to the MBean server for that process.
System.out.println("Number of beans found in " + avmd.displayName() + ":" + myJMXConnection.getMBeanCount());
String getDefaultDomain = myJMXConnection.getDefaultDomain();
String[] getDomains = myJMXConnection.getDomains();
Set<ObjectInstance> beans = myJMXConnection.queryMBeans(null, null);
org.json.JSONObject JVM = new org.json.JSONObject();
org.json.JSONArray JBeans = new org.json.JSONArray();
for (ObjectInstance instance : beans) {
String daclassname = instance.getClassName();
if (mBean.getsupressSun() & (daclassname.startsWith("sun.") | daclassname.startsWith("com.sun."))) {
continue;
}
if (daclassname.contains(mBean.getTARGETBEAN()) || mBean.getTARGETBEAN().contentEquals("*")) {
MBeanAttributeInfo[] myAttributeArray = null;
org.json.JSONObject Beanboy = new org.json.JSONObject();
org.json.JSONArray BeanieButes = new org.json.JSONArray();
try {
MBeanInfo info = myJMXConnection.getMBeanInfo(instance.getObjectName());
myAttributeArray = info.getAttributes();
System.out.println(" Processing me a bean: " + daclassname);
} catch (UnsupportedOperationException | RuntimeMBeanException | IllegalStateException ex) {
System.out.println(" Error processing bean: " + daclassname);
}
for (MBeanAttributeInfo thisAttributeInfo : myAttributeArray) {
String attvalue = "";
String myname = "";
String mytype = "";
String mydesc = "";
boolean myread = false;
boolean mywrite = false;
try {
myname = thisAttributeInfo.getName();
mydesc = thisAttributeInfo.getDescription();
mytype = thisAttributeInfo.getType();
myread = thisAttributeInfo.isReadable();
mywrite = thisAttributeInfo.isWritable();
if (myread) {
switch (mytype) {
case "String":
attvalue = (String) myJMXConnection.getAttribute(instance.getObjectName(), myname);
break;
case "java.lang.String":
attvalue = (String) myJMXConnection.getAttribute(instance.getObjectName(), myname);
break;
case "boolean":
attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString();
break;
case "int":
attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString();
break;
case "long":
attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString();
break;
case "double":
attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString();
break;
default:
attvalue = "*-Unsupported: complex type-*";
break;
}//end switch
}//end if
else {
attvalue = "";
}
} catch (Exception ex) {
attvalue = "*-Exception accessing value-*";
}
//THis section is where we determine if we are going to record the value or not.
boolean dooutput = false;
if (mBean.getsuppresscomplex()) {
dooutput = true;
} else {
try {
if (!attvalue.startsWith("*-")) {
dooutput = true;
}
} catch (Exception ex)//For attributes with no values.
{
attvalue = "*-No value-*";
dooutput = true;
}
}
if (mBean.getignoreunreadable() && !myread) {
dooutput = false;
}
if (dooutput) {
org.json.JSONObject AtDatas = new org.json.JSONObject();// Create the list of attributes and values into an object.
AtDatas.put("Name", myname);
AtDatas.put("Type", mytype);
if (myread) {
AtDatas.put("Value", attvalue);
System.out.println(" Name:" + myname + " Type:" + mytype + " Value:" + attvalue + " Writeable:" + mywrite);
} else {
System.out.println(" Name:" + myname + " Type:" + mytype + " Readable:" + myread + " Writeable:" + mywrite);
AtDatas.put("Readable", myread);
}
AtDatas.put("Desc", mydesc);
if (mywrite) {
AtDatas.put("Writable", mywrite);
}
BeanieButes.put(AtDatas);
}
}//End processing Bean Attributes, add attributes to bean array.
Beanboy.put(daclassname, BeanieButes);//add attributes to the bean
JBeans.put(Beanboy);//add bean to VM
}//End if this bean was skipped.
}//End of process JVM instance beans
JVM.put(avmd.displayName(), JBeans);
JVMs.put(JVM);
}//End JVM iteration
java.net.InetAddress addr = java.net.InetAddress.getLocalHost();
String mename = addr.getHostName();
Host.put(mename, JVMs);
//add vms to host
Hosts.put(Host);
//add server(s) to infra
String time = String.valueOf(System.currentTimeMillis());
Jinfrascan.put(time, Hosts);
// OK. How do I dump the JSON?
if (mBean.getoutJSON()) {
if (!mBean.getJSONFile().equals("")) {
try {
PrintWriter writer = new PrintWriter(mBean.getJSONFile(), "UTF-8");
if (mBean.getprettyprint()) {
writer.println(Jinfrascan.toString(4));
} else {
writer.println(Jinfrascan);
}
writer.close();
} catch (Exception ex) {
System.out.print("Error processing file!");
System.out.print(ex);
}
} else {
System.out.println("JSON Output:");
if (mBean.getprettyprint()) {
System.out.print(Jinfrascan.toString(4));
} else {
System.out.print(Jinfrascan);
}
}
}
} catch (Exception exception) {
//Error handling to come.
}
loopagain=false;
if(mBean.getLoop())loopagain=true;
if( mBean.getIterations()>0 && mBean.getIterationsCount() < mBean.getIterations()){
loopagain=true;
}
if(!mBean.getLoop())loopagain=false;
if(loopagain){
mBean.setIterationsCount(mBean.getIterationsCount() + 1);
System.out.print("Sleeping " + mBean.getLoopDelaySeconds() + " seconds. This was run " + mBean.getIterationsCount());
TimeUnit.SECONDS.sleep(mBean.getLoopDelaySeconds());
}
} while (loopagain);
System.out.println("");
System.out.println("Stiv's Beanbagger Finished");
}
public static void Usage()
{
System.out.println("java -jar Beanbagger [-p {process}] [-b {bean}] -q -m [-j {filename}] -ppj");
System.out.println(" -p {process}: Optional, VM Process Name or substring of process to try to connect to. Defaults to all");
System.out.println(" -b {bean}: Optional , restrict data to just one bean. Default is all beans ");
System.out.println(" -j {optionalfilename}: Optional: Output results to filename in JSON format, or to console if no file specified.");
System.out.println(" -x :Requires exact match of VM Process Name");
System.out.println(" -q :Filter. Suppresses output of unsupported types or operations.");
System.out.println(" -m :Filter. Suppresses iteration of Sun beans (sun.* and com.sun.*");
System.out.println(" -r :Filter. Suppresses logging of unreadable attributes");
System.out.println(" -l {seconds} :Loop continously. After completion, the dump will rerun in x seconds, default is 30");
System.out.println(" -c {iterations} :Count number of times to run. -c with no options sets to 5. Automatically sets -l");
System.out.println(" -ppj : Prettyprint JSON output, sets -j but not j- filename." );
System.out.println("\nProcesses found:");
List<VirtualMachineDescriptor> list = VirtualMachine.list();
for (VirtualMachineDescriptor vmd: list)
{
if(vmd.displayName().equals(""))
{
System.out.println(" {Unamed Instance}");
}
else
{
System.out.println(" "+ vmd.displayName());
}
}
System.out.println("");
System.exit(1);
}
static JMXConnector getLocalConnection(VirtualMachine vm) throws Exception {
Properties props = vm.getAgentProperties();
String connectorAddress = props.getProperty(CONNECTOR_ADDRESS_PROPERTY);
if (connectorAddress == null) {
props = vm.getSystemProperties();
String home = props.getProperty("java.home");
String agent = home + File.separator + "lib" + File.separator + "management-agent.jar";
vm.loadAgent(agent);
props = vm.getAgentProperties();
connectorAddress = props.getProperty(CONNECTOR_ADDRESS_PROPERTY);
}
JMXServiceURL url = new JMXServiceURL(connectorAddress);
return JMXConnectorFactory.connect(url);
}
}
|
package org.dspace.curate;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.identifier.IdentifierService;
import org.dspace.identifier.IdentifierNotFoundException;
import org.dspace.identifier.IdentifierNotResolvableException;
import org.dspace.utils.DSpace;
import org.dspace.authority.orcid.xml.XMLtoBio;
import org.dspace.authority.orcid.model.Bio;
import org.dspace.authority.orcid.model.BioName;
import org.apache.log4j.Logger;
/**
* OdinsHamr helps users reconcile author metadata with metadata stored in ORCID.
*
* Input: a single DSpace item OR a collection
* Output: CSV file that maps author names in the DSpace item to author names in ORCID.
* @author Ryan Scherle
*/
@Suspendable
public class OdinsHamr extends AbstractCurationTask {
private static final String ORCID_QUERY_BASE = "http://pub.orcid.org/search/orcid-bio?q=digital-object-ids:";
private static final double MATCH_THRESHHOLD = 0.5;
private static Logger log = Logger.getLogger(OdinsHamr.class);
private IdentifierService identifierService = null;
DocumentBuilderFactory dbf = null;
DocumentBuilder docb = null;
static long total = 0;
private Context context;
@Override
public void init(Curator curator, String taskId) throws IOException {
super.init(curator, taskId);
identifierService = new DSpace().getSingletonService(IdentifierService.class);
// init xml processing
try {
dbf = DocumentBuilderFactory.newInstance();
docb = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new IOException("unable to initiate xml processor", e);
}
}
/**
* Perform the curation task upon passed DSO
*
* input: an item
* output: several lines of authors, can show all or only identified matches
*
* @param dso the DSpace object
* @throws IOException
*/
@Override
public int perform(DSpaceObject dso) throws IOException {
log.info("performing ODIN's Hamr task " + total++ );
String handle = "\"[no handle found]\"";
String itemDOI = "\"[no item DOI found]\"";
String articleDOI = "";
try {
context = new Context();
} catch (SQLException e) {
log.fatal("Unable to open database connection", e);
return Curator.CURATE_FAIL;
}
if (dso.getType() == Constants.COLLECTION) {
report("itemDOI, articleDOI, orcidID, orcidName, dspaceORCID, dspaceName");
} else if (dso.getType() == Constants.ITEM) {
Item item = (Item)dso;
try {
handle = item.getHandle();
log.info("handle = " + handle);
if (handle == null) {
// this item is still in workflow - no handle assigned
context.abort();
return Curator.CURATE_SKIP;
}
// item DOI
DCValue[] vals = item.getMetadata("dc.identifier");
if (vals.length == 0) {
setResult("Object has no dc.identifier available " + handle);
log.error("Skipping -- no dc.identifier available for " + handle);
context.abort();
return Curator.CURATE_SKIP;
} else {
for(int i = 0; i < vals.length; i++) {
if (vals[i].value.startsWith("doi:")) {
itemDOI = vals[i].value;
}
}
}
log.debug("itemDOI = " + itemDOI);
// article DOI
vals = item.getMetadata("dc.relation.isreferencedby");
if (vals.length == 0) {
log.debug("Object has no articleDOI (dc.relation.isreferencedby) " + handle);
articleDOI = "";
} else {
articleDOI = vals[0].value;
}
log.debug("articleDOI = " + articleDOI);
// DSpace names
List<DCValue> dspaceBios = new ArrayList<DCValue>();
vals = item.getMetadata("dc.contributor.author");
if (vals.length == 0) {
log.error("Object has no dc.contributor.author available in DSpace" + handle);
} else {
for(int i = 0; i < vals.length; i++) {
dspaceBios.add(vals[i]);
}
}
// ORCID names
List<Bio> orcidBios = retrieveOrcids(itemDOI);
if(articleDOI != null && articleDOI.length() > 0) {
List<Bio> articleBios = retrieveOrcids(articleDOI);
for(Bio bio : articleBios) {
if(!containsName(orcidBios, bio)) {
orcidBios.add(bio);
}
}
}
// reconcile names between DSpace and ORCID
HashMap<DCValue,Bio> mappedNames = doHamrMatch(dspaceBios, orcidBios);
// output the resultant mappings
Iterator nameIt = mappedNames.entrySet().iterator();
while(nameIt.hasNext()) {
Map.Entry pairs = (Map.Entry)nameIt.next();
Bio mappedOrcidEntry = (Bio)pairs.getValue();
DCValue mappedDSpaceDCVal = (DCValue)pairs.getKey();
Bio mappedDSpaceEntry = createBio("", mappedDSpaceDCVal.value);
report(itemDOI + ", " + articleDOI + ", " + mappedOrcidEntry.getOrcid() + ", \"" + getName(mappedOrcidEntry) + "\", " +
mappedDSpaceEntry.getOrcid() + ", \"" + getName(mappedDSpaceEntry) + "\", " + hamrScore(mappedDSpaceEntry,mappedOrcidEntry));
setResult("Last processed item = " + handle + " -- " + itemDOI);
}
log.info(handle + " done.");
} catch (Exception e) {
log.fatal("Skipping -- Exception in processing " + handle, e);
setResult("Object has a fatal error: " + handle + "\n" + e.getMessage());
report("Object has a fatal error: " + handle + "\n" + e.getMessage());
context.abort();
return Curator.CURATE_SKIP;
}
} else {
log.info("Skipping -- non-item DSpace object");
setResult("Object skipped (not an item)");
context.abort();
return Curator.CURATE_SKIP;
}
try {
context.complete();
} catch (SQLException e) {
log.fatal("Unable to close database connection", e);
}
log.info("ODIN's Hamr complete");
return Curator.CURATE_SUCCESS;
}
/**
Computes a minimum between three integers.
**/
private static int minimum(int a, int b, int c) {
return Math.min(Math.min(a, b), c);
}
public static int computeLevenshteinDistance(CharSequence str1, CharSequence str2) {
int[][] distance = new int[str1.length() + 1][str2.length() + 1];
for (int i = 0; i <= str1.length(); i++)
distance[i][0] = i;
for (int j = 1; j <= str2.length(); j++)
distance[0][j] = j;
for (int i = 1; i <= str1.length(); i++)
for (int j = 1; j <= str2.length(); j++)
distance[i][j] = minimum(
distance[i - 1][j] + 1,
distance[i][j - 1] + 1,
distance[i - 1][j - 1] + ((str1.charAt(i - 1) == str2.charAt(j - 1)) ? 0 : 1));
return distance[str1.length()][str2.length()];
}
/**
Scores the correspondence between two author names.
**/
private double hamrScore(Bio bio1, Bio bio2) {
// if the orcid ID's match, the names are a perfect match
if(bio1.getOrcid() != null && bio1.getOrcid().equals(bio2.getOrcid())) {
return 1.0;
}
int maxlen = Math.max(getName(bio1).length(), getName(bio2).length());
int editlen = computeLevenshteinDistance(getName(bio1), getName(bio2));
return (double)(maxlen-editlen)/(double)maxlen;
}
/**
Matches two lists of Orcid names using the Hamr algorithm.
**/
private HashMap<DCValue,Bio> doHamrMatch(List<DCValue>dspaceBios, List<Bio>orcidBios) {
HashMap<DCValue,Bio> matchedNames = new HashMap<DCValue,Bio>();
// for each dspaceName, find the best possible match in the orcidBios list, provided the score is over the threshhold
for(DCValue dspaceData:dspaceBios) {
Bio dspaceBio = createBio("",dspaceData.value);
double currentScore = 0.0;
Bio currentMatch = null;
for(Bio orcidBio:orcidBios) {
double strength = hamrScore(dspaceBio, orcidBio);
if(strength > currentScore && strength > MATCH_THRESHHOLD) {
currentScore = strength;
currentMatch = orcidBio;
}
}
if(currentScore > 0.0) {
matchedNames.put(dspaceData, currentMatch);
}
}
return matchedNames;
}
/**
Reports whether a given targetName appears in a list of Orcid Bios.
**/
private boolean containsName(List<Bio> bioList, Bio targetBio) {
if(bioList != null) {
for(Bio bio:bioList) {
if(getName(bio).equals(getName(targetBio))) {
return true;
}
}
}
return false;
}
private Bio createBio (String orcid, String dryadName) {
Bio bio = new Bio();
bio.setOrcid(orcid);
// Create a Pattern object
Pattern lastfirst = Pattern.compile("(.*),\\s*(.*)");
// Now create matcher object.
Matcher m = lastfirst.matcher(dryadName);
if (m.find()) {
bio.setName(new BioName(m.group(2), m.group(1), "", null));
} else {
log.error("Name " + dryadName + " is not in lastname, firstname format.");
}
return bio;
}
/**
Retrieve a list of names associated with this DOI in ORCID.
The DOI may represent a Dryad item, or any other work.
**/
private List<Bio> retrieveOrcids(String aDOI) {
List<Bio> orcidBios = new ArrayList<Bio>();
if(aDOI.startsWith("doi:")) {
aDOI = aDOI.substring("doi:".length());
}
try {
URL orcidQuery = new URL(ORCID_QUERY_BASE + "%22" + aDOI + "%22");
Document orcidDoc = docb.parse(orcidQuery.openStream());
XMLtoBio converter = new XMLtoBio();
return orcidBios = converter.convert(orcidDoc);
} catch (MalformedURLException e) {
log.error("cannot make a valid URL for aDOI=" + aDOI, e);
} catch (IOException e) {
log.error("IO problem for aDOI=" + aDOI, e);
} catch (SAXException e) {
log.error("error processing XML for aDOI=" + aDOI, e);
}
return orcidBios;
}
private String getName(Bio bio) {
return bio.getName().getFamilyName() + ", " + bio.getName().getGivenNames();
}
}
|
package com.custardsource.parfait.dxm;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.GregorianCalendar;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.measure.unit.NonSI;
import javax.measure.unit.SI;
import javax.measure.unit.Unit;
import com.custardsource.parfait.dxm.semantics.Semantics;
import com.custardsource.parfait.dxm.semantics.UnitMapping;
import com.custardsource.parfait.dxm.types.AbstractTypeHandler;
import com.custardsource.parfait.dxm.types.DefaultTypeHandlers;
import com.custardsource.parfait.dxm.types.MmvMetricType;
import com.custardsource.parfait.dxm.types.TypeHandler;
import com.google.common.base.Preconditions;
public class PcpMmvWriter extends BasePcpWriter {
private static enum TocType {
INSTANCE_DOMAINS(1),
INSTANCES(2),
METRICS(3),
VALUES(4),
STRINGS(5);
private final int identifier;
private TocType(int identifier) {
this.identifier = identifier;
}
}
public static enum MmvFlag {
MMV_FLAG_NOPREFIX(1),
MMV_FLAG_PROCESS(2);
private final int bitmask;
MmvFlag(int bitmask) {
this.bitmask = bitmask;
}
public int getBitmask() {
return bitmask;
}
}
public static final Set<MmvFlag> DEFAULT_FLAGS = Collections.unmodifiableSet(EnumSet.of(
MmvFlag.MMV_FLAG_NOPREFIX, MmvFlag.MMV_FLAG_PROCESS));
/**
* The maximum length of a metric name able to be exported to the MMV agent. Note that this is
* relative to {@link #PCP_CHARSET} (it's a measure of the maximum number of bytes, not the Java
* String length)
*/
public static final int METRIC_NAME_LIMIT = 63;
/**
* The maximum length of an instance name able to be exported to the MMV agent. Note that this
* is relative to {@link #PCP_CHARSET} (it's a measure of the maximum number of bytes, not the
* Java String length)
*/
public static final int INSTANCE_NAME_LIMIT = 63;
private static final int HEADER_LENGTH = 40;
private static final int TOC_LENGTH = 16;
private static final int METRIC_LENGTH = 104;
private static final int VALUE_LENGTH = 32;
private static final int DEFAULT_INSTANCE_DOMAIN_ID = -1;
private static final int INSTANCE_LENGTH = 80;
private static final int INSTANCE_DOMAIN_LENGTH = 32;
private static final int STRING_BLOCK_LENGTH = 256;
/**
* The charset used for PCP metrics names and String values.
*/
public static final Charset PCP_CHARSET = Charset.forName("US-ASCII");
private static final byte[] TAG = "MMV\0".getBytes(PCP_CHARSET);
private static final int MMV_FORMAT_VERSION = 1;
private static final int DATA_VALUE_LENGTH = 16;
private static final TypeHandler<String> MMV_STRING_HANDLER = new AbstractTypeHandler<String>(
MmvMetricType.STRING, STRING_BLOCK_LENGTH) {
@Override
public boolean requiresLargeStorage() {
return true;
}
@Override
public void putBytes(ByteBuffer buffer, String value) {
byte[] bytes = value.getBytes(PCP_CHARSET);
int length = Math.min(bytes.length, STRING_BLOCK_LENGTH - 1);
buffer.put(bytes, 0, length);
buffer.put((byte) 0);
}
};
private volatile int clusterIdentifier = 0;
private volatile Set<MmvFlag> flags = DEFAULT_FLAGS;
/**
* A new PcpMmvWriter using a simple default {@link IdentifierSourceSet}.
*
* @see #PcpMmvWriter(File, IdentifierSourceSet)
* @deprecated should pass in an explicit IdentifierSourceSet
*/
@Deprecated
public PcpMmvWriter(File file) {
this(file, IdentifierSourceSet.DEFAULT_SET);
}
/**
* Creates a new PcpMmvWriter writing to the underlying file, which will be created + opened as a
* memory-mapped file. Uses the provided architecture to determine whether to write 32- or
* 64-bit longs for some key header fields.
*
* @param file
* the file to map
* @param identifierSources
* the sources to use for coming up with identifiers for new metrics etc.
*/
public PcpMmvWriter(File file, IdentifierSourceSet identifierSources) {
this(new FileByteBufferFactory(file), identifierSources);
}
public PcpMmvWriter(ByteBufferFactory byteBufferFactory, IdentifierSourceSet identifierSources) {
super(byteBufferFactory, identifierSources);
registerType(String.class, MMV_STRING_HANDLER);
}
/**
* Creates a new PcpMmvWriter writing to the underlying file, which will be created + opened as a
* memory-mapped file. This is the constructor most people should use, unless you have a really
* good reason not to. It automatically handles all (incl. cross-platform) file location issues.
*
* @param name
* logical name of instrumented subsystem (e.g. "hadoop")
* @param identifierSources
* the sources to use for coming up with identifiers for new metrics etc.
*/
public PcpMmvWriter(String name, IdentifierSourceSet identifierSources) {
this(mmvFileFromName(name), identifierSources);
}
private static File mmvFileFromName(String name) {
Preconditions.checkArgument(!name.contains(File.separator), "MMV logical name must not contain path separators");
File tmpDir = null;
PcpConfig pcp = new PcpConfig();
String pcpTemp = pcp.getValue("PCP_TMP_DIR");
if (pcpTemp == null) {
// PCP not installed, so create mapping in tmpdir
tmpDir = new File(System.getProperty("java.io.tmpdir"));
} else {
tmpDir = new File(pcp.getRoot(), pcpTemp);
}
File mmvDir = new File(tmpDir, "mmv");
return new File(mmvDir, name);
}
public void setClusterIdentifier(int clusterIdentifier) {
this.clusterIdentifier = clusterIdentifier;
}
public void setFlags(Set<MmvFlag> flags) {
this.flags = EnumSet.copyOf(flags);
}
@Override
protected void populateDataBuffer(ByteBuffer dataFileBuffer, Collection<PcpValueInfo> valueInfos)
throws IOException {
dataFileBuffer.position(0);
dataFileBuffer.put(TAG);
dataFileBuffer.putInt(MMV_FORMAT_VERSION);
long generation = System.currentTimeMillis() / 1000;
dataFileBuffer.putLong(generation);
int gen2Offset = dataFileBuffer.position();
// Generation 2 will be filled in later, once the file's ready
dataFileBuffer.putLong(0);
// 2 TOC blocks, 3 if there are instances
dataFileBuffer.putInt(tocCount());
dataFileBuffer.putInt(getFlagMask());
dataFileBuffer.putInt(getPid());
dataFileBuffer.putInt(clusterIdentifier);
Collection<InstanceDomain> instanceDomains = getInstanceDomains();
Collection<Instance> instances = getInstances();
Collection<PcpMetricInfo> metrics = getMetricInfos();
Collection<PcpString> strings = getStrings();
int tocBlockIndex = 0;
if (!instanceDomains.isEmpty()) {
dataFileBuffer.position(getTocOffset(tocBlockIndex++));
writeToc(dataFileBuffer, TocType.INSTANCE_DOMAINS, instanceDomains.size(),
instanceDomains.iterator().next().getOffset());
}
if (!instances.isEmpty()) {
dataFileBuffer.position(getTocOffset(tocBlockIndex++));
writeToc(dataFileBuffer, TocType.INSTANCES, instances.size(), instances.iterator()
.next().getOffset());
}
dataFileBuffer.position(getTocOffset(tocBlockIndex++));
int metricsFirstEntryOffset = metrics.isEmpty() ? 0 : metrics.iterator().next().getOffset();
int valuesFirstEntryOffset = valueInfos.isEmpty() ? 0 : valueInfos.iterator().next().getOffset();
writeToc(dataFileBuffer, TocType.METRICS, metrics.size(), metricsFirstEntryOffset);
dataFileBuffer.position(getTocOffset(tocBlockIndex++));
writeToc(dataFileBuffer, TocType.VALUES, valueInfos.size(), valuesFirstEntryOffset);
if (!getStrings().isEmpty()) {
dataFileBuffer.position(getTocOffset(tocBlockIndex++));
writeToc(dataFileBuffer, TocType.STRINGS, strings.size(),
strings.iterator().next().getOffset());
}
for (InstanceDomain instanceDomain : instanceDomains) {
dataFileBuffer.position(instanceDomain.getOffset());
writeInstanceDomainSection(dataFileBuffer, instanceDomain);
for (Instance instance : instanceDomain.getInstances()) {
dataFileBuffer.position(instance.getOffset());
writeInstanceSection(dataFileBuffer, instance);
}
}
for (PcpMetricInfo info : metrics) {
dataFileBuffer.position(info.getOffset());
writeMetricsSection(dataFileBuffer, info, info.getTypeHandler().getMetricType());
}
for (PcpValueInfo info : valueInfos) {
dataFileBuffer.position(info.getOffset());
writeValueSection(dataFileBuffer, info);
}
for (PcpString string : strings) {
dataFileBuffer.position(string.getOffset());
writeStringSection(dataFileBuffer, string.getInitialValue());
}
// Once it's set up, let the agent know
dataFileBuffer.position(gen2Offset);
dataFileBuffer.putLong(generation);
}
private int getFlagMask() {
int flagMask = 0;
for (MmvFlag flag : flags) {
flagMask |= flag.bitmask;
}
return flagMask;
}
private void writeStringSection(ByteBuffer dataFileBuffer, String value) {
byte[] bytes = value.getBytes(PCP_CHARSET);
Preconditions.checkArgument(bytes.length < STRING_BLOCK_LENGTH);
dataFileBuffer.put(bytes);
dataFileBuffer.put((byte) 0);
}
@Override
protected int getDataLength() {
int instanceDomainCount = getInstanceDomains().size();
int metricCount = getMetricInfos().size();
int instanceCount = getInstances().size();
int valueCount = getValueInfos().size();
int tocCount = tocCount();
int stringCount = getStrings().size();
return HEADER_LENGTH + (TOC_LENGTH * tocCount)
+ (INSTANCE_DOMAIN_LENGTH * instanceDomainCount)
+ (INSTANCE_LENGTH * instanceCount) + (METRIC_LENGTH * metricCount)
+ (VALUE_LENGTH * valueCount) + (STRING_BLOCK_LENGTH * stringCount);
}
/**
* Writes out a PCP MMV table-of-contents block.
*
* @param dataFileBuffer
* ByteBuffer positioned at the correct offset in the file for the block
* @param tocType
* the type of TOC block to write
* @param entryCount
* the number of blocks of type tocType to be found in the file
* @param firstEntryOffset
* the offset of the first tocType block, relative to start of the file
*/
private void writeToc(ByteBuffer dataFileBuffer, TocType tocType, int entryCount,
int firstEntryOffset) {
dataFileBuffer.putInt(tocType.identifier);
dataFileBuffer.putInt(entryCount);
dataFileBuffer.putLong(firstEntryOffset);
}
/**
* Writes the descriptor block for an individual metric to the file.
*
* @param dataFileBuffer
* ByteBuffer positioned at the correct offset in the file for the block
* @param info
* the info of the metric (name must be ≤ {@link #METRIC_NAME_LIMIT} characters,
* and must be convertible to {@link #PCP_CHARSET})
* @param metricType
* the type of the metric
*/
private void writeMetricsSection(ByteBuffer dataFileBuffer, PcpMetricInfo info,
MmvMetricType metricType) {
int originalPosition = dataFileBuffer.position();
dataFileBuffer.put(info.getMetricName().getBytes(PCP_CHARSET));
dataFileBuffer.put((byte) 0);
dataFileBuffer.position(originalPosition + METRIC_NAME_LIMIT + 1);
dataFileBuffer.putInt(info.getId());
dataFileBuffer.putInt(metricType.getIdentifier());
dataFileBuffer.putInt(info.getSemantics().getPcpValue());
dataFileBuffer.putInt(UnitMapping.getDimensions(info.getUnit(), info.getMetricName()));
if (info.getInstanceDomain() != null) {
dataFileBuffer.putInt(info.getInstanceDomain().getId());
} else {
dataFileBuffer.putInt(DEFAULT_INSTANCE_DOMAIN_ID);
}
// Just padding
dataFileBuffer.putInt(0);
dataFileBuffer.putLong(getStringOffset(info.getShortHelpText()));
dataFileBuffer.putLong(getStringOffset(info.getLongHelpText()));
}
/**
* Writes the value block for an individual metric to the file.
*
* @param dataFileBuffer
* ByteBuffer positioned at the correct offset in the file for the block
* @param value
* the PcpValueInfo to be written to the file
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private void writeValueSection(ByteBuffer dataFileBuffer, PcpValueInfo info) {
int originalPosition = dataFileBuffer.position();
TypeHandler rawHandler = info.getTypeHandler();
if (rawHandler.requiresLargeStorage()) {
// API requires the length here but it's currently unused -- write out the maximum
// possible length
dataFileBuffer.putLong(STRING_BLOCK_LENGTH - 1);
dataFileBuffer.putLong(info.getLargeValue().getOffset());
dataFileBuffer.position(info.getLargeValue().getOffset());
}
rawHandler.putBytes(dataFileBuffer, info.getInitialValue());
dataFileBuffer.position(originalPosition + DATA_VALUE_LENGTH);
dataFileBuffer.putLong(info.getDescriptorOffset());
dataFileBuffer.putLong(info.getInstanceOffset());
}
private void writeInstanceSection(ByteBuffer dataFileBuffer, Instance instance) {
dataFileBuffer.putLong(instance.getInstanceDomain().getOffset());
dataFileBuffer.putInt(0);
dataFileBuffer.putInt(instance.getId());
dataFileBuffer.put(instance.getName().getBytes(PCP_CHARSET));
}
private void writeInstanceDomainSection(ByteBuffer dataFileBuffer, InstanceDomain instanceDomain) {
dataFileBuffer.putInt(instanceDomain.getId());
dataFileBuffer.putInt(instanceDomain.getInstanceCount());
dataFileBuffer.putLong(instanceDomain.getFirstInstanceOffset());
dataFileBuffer.putLong(getStringOffset(instanceDomain.getShortHelpText()));
dataFileBuffer.putLong(getStringOffset(instanceDomain.getLongHelpText()));
}
private long getStringOffset(PcpString text) {
if (text == null) {
return 0;
}
return text.getOffset();
}
/**
* Calculates the file offset of a given PCP MMV TOC block
*
* @param tocIndex
* the 0-based index of the TOC block to be written
* @return the file offset used to store that TOC block (32-bit regardless of architecture)
*/
private final int getTocOffset(int tocIndex) {
return HEADER_LENGTH + (tocIndex * TOC_LENGTH);
}
@Override
protected Charset getCharset() {
return PCP_CHARSET;
}
@Override
protected int getMetricNameLimit() {
return METRIC_NAME_LIMIT;
}
@Override
protected int getInstanceNameLimit() {
return INSTANCE_NAME_LIMIT;
}
// TODO there's lots of synchronization points we need to properly think out here, including the PcpMonitorBridge
@Override
protected synchronized void initialiseOffsets() {
int nextOffset = HEADER_LENGTH + (TOC_LENGTH * tocCount());
nextOffset = initializeOffsets(getInstanceDomains(), nextOffset, INSTANCE_DOMAIN_LENGTH);
nextOffset = initializeOffsets(getInstances(), nextOffset, INSTANCE_LENGTH);
nextOffset = initializeOffsets(getMetricInfos(), nextOffset, METRIC_LENGTH);
nextOffset = initializeOffsets(getValueInfos(), nextOffset, VALUE_LENGTH);
initializeOffsets(getStrings(), nextOffset, STRING_BLOCK_LENGTH);
}
private int initializeOffsets(Collection<? extends PcpOffset> offsettables,
int nextOffset, int blockLength) {
for (PcpOffset offsettable : offsettables) {
offsettable.setOffset(nextOffset);
nextOffset += blockLength;
}
return nextOffset;
}
private int tocCount() {
int tocCount = 2; // metrics + values
if (!getInstances().isEmpty()) {
tocCount += 2;
}
if (!getStrings().isEmpty()) {
tocCount++;
}
return tocCount;
}
/**
* @return the PID of the current running Java Process
*/
private int getPid() {
String processIdentifier = ManagementFactory.getRuntimeMXBean().getName();
return Integer.valueOf(processIdentifier.split("@")[0]);
}
public static void main(String[] args) throws IOException {
PcpMmvWriter bridge;
if (args.length == 0) {
// use $PCP_PMDAS_DIR/mmv/mmvdump (no args) as diagnostic tool
bridge = new PcpMmvWriter("test", IdentifierSourceSet.DEFAULT_SET);
}
else {
bridge = new PcpMmvWriter(new File(args[0]), IdentifierSourceSet.DEFAULT_SET);
}
// Automatically uses default int handler
bridge.addMetric(MetricName.parse("sheep[baabaablack].bagsfull.count"), Semantics.COUNTER,
Unit.ONE.times(1000), 3);
// Automatically uses default boolean-to-int handler
bridge.addMetric(MetricName.parse("sheep[baabaablack].bagsfull.haveany"),
Semantics.INSTANT, null, new AtomicBoolean(true));
bridge.addMetric(MetricName.parse("sheep[limpy].bagsfull.haveany"), Semantics.INSTANT,
null, new AtomicBoolean(false));
// Automatically uses default long handler
bridge.addMetric(MetricName.parse("sheep[insomniac].jumps"), Semantics.COUNTER, Unit.ONE,
12345678901234L);
// Automatically uses default double handler
bridge.addMetric(MetricName.parse("sheep[limpy].legs.available"), Semantics.DISCRETE,
Unit.ONE, 0.75);
// Uses this class' custom String handler
bridge.addMetric(MetricName.parse("sheep[limpy].jumpitem"), Semantics.DISCRETE, null,
"fence");
// addMetric(GregorianCalendar) would fail, as there's no handler registered by default for
// GregorianCalendars; use a custom one which puts the year as an int
bridge.addMetric(MetricName.parse("sheep[insomniac].lastjumped"), Semantics.INSTANT, null,
new GregorianCalendar(), new AbstractTypeHandler<GregorianCalendar>(
MmvMetricType.I32, 4) {
public void putBytes(ByteBuffer buffer, GregorianCalendar value) {
buffer.putInt(value.get(GregorianCalendar.YEAR));
}
});
// addMetric(Date) would fail, as there's no handler registered; register one for all date
// types from now on
bridge.registerType(Date.class, new AbstractTypeHandler<Date>(MmvMetricType.I64, 8) {
public void putBytes(ByteBuffer buffer, Date value) {
buffer.putLong(value.getTime());
}
});
// These will both use the handler we just registered
bridge.addMetric(MetricName.parse("cow.how.now"), Semantics.INSTANT, null, new Date());
bridge.addMetric(MetricName.parse("cow.how.then"), Semantics.INSTANT, null,
new GregorianCalendar(1990, 1, 1, 12, 34, 56).getTime());
// Uses units
bridge.addMetric(MetricName.parse("cow.launch.velocity"), Semantics.INSTANT, NonSI.MILE
.divide(SI.SECOND), new Date());
bridge.addMetric(MetricName.parse("cow.bytes.total"), Semantics.COUNTER, NonSI.BYTE,
10000001);
bridge.addMetric(MetricName.parse("cow.bytes.rate"), Semantics.INSTANT, NonSI.BYTE.times(
1024).divide(SI.SECOND), new Date());
bridge.addMetric(MetricName.parse("cow.bytes.chewtime"), Semantics.INSTANT, NonSI.HOUR
.divide(NonSI.BYTE), 7);
bridge.addMetric(MetricName.parse("cow.bytes.jawmotion"), Semantics.INSTANT, SI
.KILO(SI.HERTZ), 0.5);
// Set up some help text
bridge.setInstanceDomainHelpText(
"sheep",
"sheep in the paddock",
"List of all the sheep in the paddock. Includes 'baabaablack', 'insomniac' (who likes to jump fences), and 'limpy' the three-legged wonder sheep.");
bridge.setMetricHelpText("sheep.jumps", "# of jumps done",
"Number of times the sheep has jumped over its jumpitem");
// All the metrics are added; write the file
bridge.start();
// Metrics are visible to the agent from this point on
// Sold a bag! Better update the count
bridge.updateMetric(MetricName.parse("sheep[baabaablack].bagsfull.count"), 2);
// The fence broke! Need something new to jump over
bridge.updateMetric(MetricName.parse("sheep[limpy].jumpitem"), "Honda Civic");
// Values will be reflected in the agent immediately
}
}
|
package de.tobject.findbugs.view.explorer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPersistable;
public class Grouping implements IPersistable {
private final LinkedList<GroupType> groupOrder;
private Grouping(List<GroupType> types){
groupOrder = new LinkedList<GroupType>(types);
// at least marker should be shown
if(!groupOrder.contains(GroupType.Marker)){
groupOrder.add(GroupType.Marker);
}
}
private static Grouping createDefault(){
List<GroupType> order = new ArrayList<GroupType>();
order.add(GroupType.Project);
order.add(GroupType.Pattern);
order.add(GroupType.Marker);
return createFrom(order);
}
public static Grouping createFrom(List<GroupType> types){
return new Grouping(types);
}
public List<GroupType> asList(){
return new LinkedList<GroupType>(groupOrder);
}
void setGroupOrder(List<GroupType> groupOrder) {
this.groupOrder.clear();
this.groupOrder.addAll(groupOrder);
}
public GroupType getFirstType(){
return groupOrder.size() > 0? groupOrder.getFirst() : GroupType.Undefined;
}
public GroupType getLastType() {
return groupOrder.size() > 0 ? groupOrder.getLast() : GroupType.Undefined;
}
public GroupType getChildType(GroupType parent) {
if (parent == GroupType.Marker) {
return parent;
}
for (int i = 0; i < groupOrder.size(); i++) {
if (groupOrder.get(i) == parent) {
return i + 1 < groupOrder.size() ? groupOrder.get(i + 1)
: GroupType.Marker;
}
}
return GroupType.Marker;
}
Iterator<GroupType> iterator(){
return groupOrder.iterator();
}
public GroupType getParentType(GroupType child) {
for (int i = 0; i < groupOrder.size(); i++) {
if (groupOrder.get(i) == child) {
return i - 1 >= 0 ? groupOrder.get(i - 1) : GroupType.Undefined;
}
}
return GroupType.Undefined;
}
public void saveState(IMemento memento) {
memento.putString("Grouping", groupOrder.toString());
}
static Grouping restoreFrom(IMemento memento) {
if(memento == null){
return createDefault();
}
String string = memento.getString("Grouping");
return restoreFrom(string);
}
static Grouping restoreFrom(String saved) {
if(saved == null || saved.length() == 0){
return createDefault();
}
StringTokenizer st = new StringTokenizer(saved, "[] ,", false);
List<GroupType> types = new ArrayList<GroupType>();
while(st.hasMoreTokens()){
GroupType type = GroupType.valueOf(st.nextToken());
types.add(type);
}
if(types.isEmpty()){
return createDefault();
}
return createFrom(types);
}
public boolean contains(GroupType type) {
return groupOrder.contains(type);
}
int compare(GroupType g1, GroupType g2){
return groupOrder.indexOf(g1) - groupOrder.indexOf(g2);
}
@Override
public String toString() {
return groupOrder.toString();
}
}
|
package org.openqa.selenium.testing;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.openqa.selenium.Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.environment.GlobalTestEnvironment;
import org.openqa.selenium.environment.InProcessTestEnvironment;
import org.openqa.selenium.environment.TestEnvironment;
import org.openqa.selenium.environment.webserver.AppServer;
import org.openqa.selenium.testing.drivers.WebDriverBuilder;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsNot.not;
@RunWith(SeleniumTestRunner.class)
public abstract class JUnit4TestBase {
protected TestEnvironment environment;
protected AppServer appServer;
protected Pages pages;
protected static WebDriver driver;
@Before
public void prepareEnvironment() throws Exception {
environment = GlobalTestEnvironment.get();
appServer = environment.getAppServer();
pages = new Pages(appServer);
String hostName = environment.getAppServer().getHostName();
String alternateHostName = environment.getAppServer().getAlternateHostName();
assertThat(hostName, is(not(equalTo(alternateHostName))));
}
@Before
public void createDriver() throws Exception {
if (driver != null) {
return;
}
driver = new WebDriverBuilder().get();
}
@Before
public void createEnvironment() {
environment = GlobalTestEnvironment.get(InProcessTestEnvironment.class);
}
@AfterClass
public static void removeDriver() {
if (driver == null) {
return;
}
try {
driver.quit();
} catch (RuntimeException ignored) {
// Fall through
}
driver = null;
}
protected boolean isIeDriverTimedOutException(IllegalStateException e) {
// The IE driver may throw a timed out exception
return e.getClass().getName().contains("TimedOutException");
}
}
|
package com.jme3.audio.lwjgl;
import com.jme3.audio.ListenerParam;
import com.jme3.audio.AudioParam;
import com.jme3.audio.AudioBuffer;
import com.jme3.audio.AudioData;
import com.jme3.audio.AudioRenderer;
import com.jme3.audio.AudioNode;
import com.jme3.audio.AudioNode.Status;
import com.jme3.audio.AudioStream;
import com.jme3.audio.Environment;
import com.jme3.audio.Filter;
import com.jme3.audio.Listener;
import com.jme3.audio.LowPassFilter;
import com.jme3.math.Vector3f;
import com.jme3.util.BufferUtils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lwjgl.LWJGLException;
import org.lwjgl.openal.AL;
import org.lwjgl.openal.AL11;
import org.lwjgl.openal.ALC10;
import org.lwjgl.openal.ALCdevice;
import org.lwjgl.openal.EFX10;
import org.lwjgl.openal.OpenALException;
import static org.lwjgl.openal.AL10.*;
public class LwjglAudioRenderer implements AudioRenderer, Runnable {
private static final Logger logger = Logger.getLogger(LwjglAudioRenderer.class.getName());
// When multiplied by STREAMING_BUFFER_COUNT, will equal 44100 * 2 * 2
// which is exactly 1 second of audio.
private static final int BUFFER_SIZE = 35280;
private static final int STREAMING_BUFFER_COUNT = 5;
private final static int MAX_NUM_CHANNELS = 64;
private IntBuffer ib = BufferUtils.createIntBuffer(1);
private final FloatBuffer fb = BufferUtils.createVector3Buffer(2);
private final ByteBuffer nativeBuf = ByteBuffer.allocateDirect(BUFFER_SIZE);
private final byte[] arrayBuf = new byte[BUFFER_SIZE];
private int[] channels;
private AudioNode[] chanSrcs;
private int nextChan = 0;
private ArrayList<Integer> freeChans = new ArrayList<Integer>();
private Listener listener;
private boolean audioDisabled = false;
private boolean supportEfx = false;
private int auxSends = 0;
private int reverbFx = -1;
private int reverbFxSlot = -1;
// Update audio 20 times per second
private static final float UPDATE_RATE = 0.05f;
private final Thread audioThread = new Thread(this, "jME3 Audio Thread");
private final AtomicBoolean threadLock = new AtomicBoolean(false);
public LwjglAudioRenderer(){
nativeBuf.order(ByteOrder.nativeOrder());
}
public void initialize(){
if (!audioThread.isAlive()){
audioThread.setDaemon(true);
audioThread.setPriority(Thread.NORM_PRIORITY+1);
audioThread.start();
}else{
throw new IllegalStateException("Initialize already called");
}
}
private void checkDead(){
if (audioThread.getState() == Thread.State.TERMINATED)
throw new IllegalStateException("Audio thread is terminated");
}
public void run(){
initInThread();
synchronized (threadLock){
threadLock.set(true);
threadLock.notifyAll();
}
long updateRateNanos = (long) (UPDATE_RATE * 1000000000);
mainloop: while (true){
long startTime = System.nanoTime();
if (Thread.interrupted())
break;
synchronized (threadLock){
updateInThread(UPDATE_RATE);
}
long endTime = System.nanoTime();
long diffTime = endTime - startTime;
if (diffTime < updateRateNanos){
long desiredEndTime = startTime + updateRateNanos;
while (System.nanoTime() < desiredEndTime){
try{
Thread.sleep(1);
}catch (InterruptedException ex){
break mainloop;
}
}
}
}
synchronized (threadLock){
cleanupInThread();
}
}
public void initInThread(){
try{
if (!AL.isCreated()){
AL.create();
}
}catch (OpenALException ex){
logger.log(Level.SEVERE, "Failed to load audio library", ex);
audioDisabled = true;
return;
}catch (LWJGLException ex){
logger.log(Level.SEVERE, "Failed to load audio library", ex);
audioDisabled = true;
return;
}
ALCdevice device = AL.getDevice();
String deviceName = ALC10.alcGetString(device, ALC10.ALC_DEVICE_SPECIFIER);
logger.log(Level.FINER, "Audio Device: {0}", deviceName);
logger.log(Level.FINER, "Audio Vendor: {0}", alGetString(AL_VENDOR));
logger.log(Level.FINER, "Audio Renderer: {0}", alGetString(AL_RENDERER));
logger.log(Level.FINER, "Audio Version: {0}", alGetString(AL_VERSION));
// Find maximum # of sources supported by this implementation
ArrayList<Integer> channelList = new ArrayList<Integer>();
for (int i = 0; i < MAX_NUM_CHANNELS; i++){
int chan = alGenSources();
if (alGetError() != 0){
break;
}else{
channelList.add(chan);
}
}
channels = new int[channelList.size()];
for (int i = 0; i < channels.length; i++){
channels[i] = channelList.get(i);
}
ib = BufferUtils.createIntBuffer(channels.length);
chanSrcs = new AudioNode[channels.length];
logger.log(Level.INFO, "AudioRenderer supports {0} channels", channels.length);
supportEfx = ALC10.alcIsExtensionPresent(device, "ALC_EXT_EFX");
logger.log(Level.FINER, "Audio EFX support: {0}", supportEfx);
if (supportEfx){
ib.position(0).limit(1);
ALC10.alcGetInteger(device, EFX10.ALC_EFX_MAJOR_VERSION, ib);
int major = ib.get(0);
ib.position(0).limit(1);
ALC10.alcGetInteger(device, EFX10.ALC_EFX_MINOR_VERSION, ib);
int minor = ib.get(0);
logger.log(Level.INFO, "Audio effect extension version: {0}.{1}", new Object[]{major, minor});
ALC10.alcGetInteger(device, EFX10.ALC_MAX_AUXILIARY_SENDS, ib);
auxSends = ib.get(0);
logger.log(Level.INFO, "Audio max auxilary sends: {0}", auxSends);
// create slot
ib.position(0).limit(1);
EFX10.alGenAuxiliaryEffectSlots(ib);
reverbFxSlot = ib.get(0);
// create effect
ib.position(0).limit(1);
EFX10.alGenEffects(ib);
reverbFx = ib.get(0);
EFX10.alEffecti(reverbFx, EFX10.AL_EFFECT_TYPE, EFX10.AL_EFFECT_REVERB);
// attach reverb effect to effect slot
// EFX10.alAuxiliaryEffectSloti(reverbFxSlot, EFX10.AL_EFFECTSLOT_EFFECT, reverbFx);
}
}
public void cleanupInThread(){
if (audioDisabled){
AL.destroy();
return;
}
// delete channel-based sources
ib.clear();
ib.put(channels);
ib.flip();
alDeleteSources(ib);
if (supportEfx){
ib.position(0).limit(1);
ib.put(0, reverbFx);
EFX10.alDeleteEffects(ib);
ib.position(0).limit(1);
ib.put(0, reverbFxSlot);
EFX10.alDeleteAuxiliaryEffectSlots(ib);
}
// XXX: Delete other buffers/sources
AL.destroy();
}
public void cleanup(){
// kill audio thread
if (audioThread.isAlive()){
audioThread.interrupt();
}
}
private void updateFilter(Filter f){
int id = f.getId();
if (id == -1){
ib.position(0).limit(1);
EFX10.alGenFilters(ib);
id = ib.get(0);
f.setId(id);
}
if (f instanceof LowPassFilter){
LowPassFilter lpf = (LowPassFilter) f;
EFX10.alFilteri(id, EFX10.AL_FILTER_TYPE, EFX10.AL_FILTER_LOWPASS);
EFX10.alFilterf(id, EFX10.AL_LOWPASS_GAIN, lpf.getVolume());
EFX10.alFilterf(id, EFX10.AL_LOWPASS_GAINHF, lpf.getHighFreqVolume());
}else{
throw new UnsupportedOperationException("Filter type unsupported: "+
f.getClass().getName());
}
f.clearUpdateNeeded();
}
public void updateSourceParam(AudioNode src, AudioParam param){
checkDead();
synchronized (threadLock){
while (!threadLock.get()){
try {
threadLock.wait();
} catch (InterruptedException ex) {
}
}
if (audioDisabled)
return;
assert src.getChannel() >= 0;
int id = channels[src.getChannel()];
switch (param){
case Position:
if (!src.isPositional())
return;
Vector3f pos = src.getWorldTranslation();
alSource3f(id, AL_POSITION, pos.x, pos.y, pos.z);
break;
case Velocity:
if (!src.isPositional())
return;
Vector3f vel = src.getVelocity();
alSource3f(id, AL_VELOCITY, vel.x, vel.y, vel.z);
break;
case MaxDistance:
if (!src.isPositional())
return;
alSourcef(id, AL_MAX_DISTANCE, src.getMaxDistance());
break;
case RefDistance:
if (!src.isPositional())
return;
alSourcef(id, AL_REFERENCE_DISTANCE, src.getRefDistance());
break;
case ReverbFilter:
if (!src.isPositional() || !src.isReverbEnabled())
return;
int filter = EFX10.AL_FILTER_NULL;
if (src.getReverbFilter() != null){
Filter f = src.getReverbFilter();
if (f.isUpdateNeeded()){
updateFilter(f);
}
filter = f.getId();
}
AL11.alSource3i(id, EFX10.AL_AUXILIARY_SEND_FILTER, reverbFxSlot, 0, filter);
break;
case ReverbEnabled:
if (!src.isPositional())
return;
if (src.isReverbEnabled()){
updateSourceParam(src, AudioParam.ReverbFilter);
}else{
AL11.alSource3i(id, EFX10.AL_AUXILIARY_SEND_FILTER, 0, 0, EFX10.AL_FILTER_NULL);
}
break;
case IsPositional:
if (!src.isPositional()){
// play in headspace
alSourcei(id, AL_SOURCE_RELATIVE, AL_TRUE);
alSource3f(id, AL_POSITION, 0,0,0);
alSource3f(id, AL_VELOCITY, 0,0,0);
}else{
alSourcei(id, AL_SOURCE_RELATIVE, AL_FALSE);
updateSourceParam(src, AudioParam.Position);
updateSourceParam(src, AudioParam.Velocity);
updateSourceParam(src, AudioParam.MaxDistance);
updateSourceParam(src, AudioParam.RefDistance);
updateSourceParam(src, AudioParam.ReverbEnabled);
}
break;
case Direction:
if (!src.isDirectional())
return;
Vector3f dir = src.getDirection();
alSource3f(id, AL_DIRECTION, dir.x, dir.y, dir.z);
break;
case InnerAngle:
if (!src.isDirectional())
return;
alSourcef(id, AL_CONE_INNER_ANGLE, src.getInnerAngle());
break;
case OuterAngle:
if (!src.isDirectional())
return;
alSourcef(id, AL_CONE_OUTER_ANGLE, src.getOuterAngle());
break;
case IsDirectional:
if (src.isDirectional()){
updateSourceParam(src, AudioParam.Direction);
updateSourceParam(src, AudioParam.InnerAngle);
updateSourceParam(src, AudioParam.OuterAngle);
alSourcef(id, AL_CONE_OUTER_GAIN, 0);
}else{
alSourcef(id, AL_CONE_INNER_ANGLE, 360);
alSourcef(id, AL_CONE_OUTER_ANGLE, 360);
alSourcef(id, AL_CONE_OUTER_GAIN, 1f);
}
break;
case DryFilter:
if (src.getDryFilter() != null){
Filter f = src.getDryFilter();
if (f.isUpdateNeeded()){
updateFilter(f);
// NOTE: must re-attach filter for changes to apply.
alSourcei(id, EFX10.AL_DIRECT_FILTER, f.getId());
}
}else{
alSourcei(id, EFX10.AL_DIRECT_FILTER, EFX10.AL_FILTER_NULL);
}
break;
case Looping:
if (src.isLooping()){
if (!(src.getAudioData() instanceof AudioStream)){
alSourcei(id, AL_LOOPING, AL_TRUE);
}
}else{
alSourcei(id, AL_LOOPING, AL_FALSE);
}
break;
case Volume:
alSourcef(id, AL_GAIN, src.getVolume());
break;
case Pitch:
alSourcef(id, AL_PITCH, src.getPitch());
break;
}
}
}
private void setSourceParams(int id, AudioNode src, boolean forceNonLoop){
if (src.isPositional()){
Vector3f pos = src.getWorldTranslation();
Vector3f vel = src.getVelocity();
alSource3f(id, AL_POSITION, pos.x, pos.y, pos.z);
alSource3f(id, AL_VELOCITY, vel.x, vel.y, vel.z);
alSourcef(id, AL_MAX_DISTANCE, src.getMaxDistance());
alSourcef(id, AL_REFERENCE_DISTANCE, src.getRefDistance());
alSourcei(id, AL_SOURCE_RELATIVE, AL_FALSE);
if (src.isReverbEnabled()){
int filter = EFX10.AL_FILTER_NULL;
if (src.getReverbFilter() != null){
Filter f = src.getReverbFilter();
if (f.isUpdateNeeded()){
updateFilter(f);
}
filter = f.getId();
}
AL11.alSource3i(id, EFX10.AL_AUXILIARY_SEND_FILTER, reverbFxSlot, 0, filter);
}
}else{
// play in headspace
alSourcei(id, AL_SOURCE_RELATIVE, AL_TRUE);
alSource3f(id, AL_POSITION, 0,0,0);
alSource3f(id, AL_VELOCITY, 0,0,0);
}
if (src.getDryFilter() != null){
Filter f = src.getDryFilter();
if (f.isUpdateNeeded()){
updateFilter(f);
// NOTE: must re-attach filter for changes to apply.
alSourcei(id, EFX10.AL_DIRECT_FILTER, f.getId());
}
}
if (forceNonLoop){
alSourcei(id, AL_LOOPING, AL_FALSE);
}else{
alSourcei(id, AL_LOOPING, src.isLooping() ? AL_TRUE : AL_FALSE);
}
alSourcef(id, AL_GAIN, src.getVolume());
alSourcef(id, AL_PITCH, src.getPitch());
alSourcef(id, AL11.AL_SEC_OFFSET, src.getTimeOffset());
if (src.isDirectional()){
Vector3f dir = src.getDirection();
alSource3f(id, AL_DIRECTION, dir.x, dir.y, dir.z);
alSourcef(id, AL_CONE_INNER_ANGLE, src.getInnerAngle());
alSourcef(id, AL_CONE_OUTER_ANGLE, src.getOuterAngle());
alSourcef(id, AL_CONE_OUTER_GAIN, 0);
}else{
alSourcef(id, AL_CONE_INNER_ANGLE, 360);
alSourcef(id, AL_CONE_OUTER_ANGLE, 360);
alSourcef(id, AL_CONE_OUTER_GAIN, 1f);
}
}
public void updateListenerParam(Listener listener, ListenerParam param){
checkDead();
synchronized (threadLock){
while (!threadLock.get()){
try {
threadLock.wait();
} catch (InterruptedException ex) {
}
}
if (audioDisabled)
return;
switch (param){
case Position:
Vector3f pos = listener.getLocation();
alListener3f(AL_POSITION, pos.x, pos.y, pos.z);
break;
case Rotation:
Vector3f dir = listener.getDirection();
Vector3f up = listener.getUp();
fb.rewind();
fb.put(dir.x).put(dir.y).put(dir.z);
fb.put(up.x).put(up.y).put(up.z);
fb.flip();
alListener(AL_ORIENTATION, fb);
break;
case Velocity:
Vector3f vel = listener.getVelocity();
alListener3f(AL_VELOCITY, vel.x, vel.y, vel.z);
break;
case Volume:
alListenerf(AL_GAIN, listener.getVolume());
break;
}
}
}
private void setListenerParams(Listener listener){
Vector3f pos = listener.getLocation();
Vector3f vel = listener.getVelocity();
Vector3f dir = listener.getDirection();
Vector3f up = listener.getUp();
alListener3f(AL_POSITION, pos.x, pos.y, pos.z);
alListener3f(AL_VELOCITY, vel.x, vel.y, vel.z);
fb.rewind();
fb.put(dir.x).put(dir.y).put(dir.z);
fb.put(up.x).put(up.y).put(up.z);
fb.flip();
alListener(AL_ORIENTATION, fb);
alListenerf(AL_GAIN, listener.getVolume());
}
private int newChannel(){
if (freeChans.size() > 0)
return freeChans.remove(0);
else if (nextChan < channels.length){
return nextChan++;
}else{
return -1;
}
}
private void freeChannel(int index){
if (index == nextChan-1){
nextChan
} else{
freeChans.add(index);
}
}
public void setEnvironment(Environment env){
checkDead();
synchronized (threadLock){
while (!threadLock.get()){
try {
threadLock.wait();
} catch (InterruptedException ex) {
}
}
if (audioDisabled)
return;
EFX10.alEffectf(reverbFx, EFX10.AL_REVERB_DENSITY, env.getDensity());
EFX10.alEffectf(reverbFx, EFX10.AL_REVERB_DIFFUSION, env.getDiffusion());
EFX10.alEffectf(reverbFx, EFX10.AL_REVERB_GAIN, env.getGain());
EFX10.alEffectf(reverbFx, EFX10.AL_REVERB_GAINHF, env.getGainHf());
EFX10.alEffectf(reverbFx, EFX10.AL_REVERB_DECAY_TIME, env.getDecayTime());
EFX10.alEffectf(reverbFx, EFX10.AL_REVERB_DECAY_HFRATIO, env.getDecayHFRatio());
EFX10.alEffectf(reverbFx, EFX10.AL_REVERB_REFLECTIONS_GAIN, env.getReflectGain());
EFX10.alEffectf(reverbFx, EFX10.AL_REVERB_REFLECTIONS_DELAY, env.getReflectDelay());
EFX10.alEffectf(reverbFx, EFX10.AL_REVERB_LATE_REVERB_GAIN, env.getLateReverbGain());
EFX10.alEffectf(reverbFx, EFX10.AL_REVERB_LATE_REVERB_DELAY, env.getLateReverbDelay());
EFX10.alEffectf(reverbFx, EFX10.AL_REVERB_AIR_ABSORPTION_GAINHF, env.getAirAbsorbGainHf());
EFX10.alEffectf(reverbFx, EFX10.AL_REVERB_ROOM_ROLLOFF_FACTOR, env.getRoomRolloffFactor());
// attach effect to slot
EFX10.alAuxiliaryEffectSloti(reverbFxSlot, EFX10.AL_EFFECTSLOT_EFFECT, reverbFx);
}
}
private boolean fillBuffer(AudioStream stream, int id){
int size = 0;
int result;
while (size < arrayBuf.length){
result = stream.readSamples(arrayBuf, size, arrayBuf.length - size);
if(result > 0){
size += result;
}else{
break;
}
}
if(size == 0)
return false;
nativeBuf.clear();
nativeBuf.put(arrayBuf, 0, size);
nativeBuf.flip();
alBufferData(id, convertFormat(stream), nativeBuf, stream.getSampleRate());
return true;
}
private boolean fillStreamingSource(int sourceId, AudioStream stream){
if (!stream.isOpen())
return false;
boolean active = true;
int processed = alGetSourcei(sourceId, AL_BUFFERS_PROCESSED);
// while((processed--) != 0){
if (processed > 0){
int buffer;
ib.position(0).limit(1);
alSourceUnqueueBuffers(sourceId, ib);
buffer = ib.get(0);
active = fillBuffer(stream, buffer);
ib.position(0).limit(1);
ib.put(0, buffer);
alSourceQueueBuffers(sourceId, ib);
}
if (!active && stream.isOpen())
stream.close();
return active;
}
private boolean attachStreamToSource(int sourceId, AudioStream stream){
boolean active = true;
for (int id : stream.getIds()){
active = fillBuffer(stream, id);
ib.position(0).limit(1);
ib.put(id).flip();
alSourceQueueBuffers(sourceId, ib);
}
return active;
}
private boolean attachBufferToSource(int sourceId, AudioBuffer buffer){
alSourcei(sourceId, AL_BUFFER, buffer.getId());
return true;
}
private boolean attachAudioToSource(int sourceId, AudioData data){
if (data instanceof AudioBuffer){
return attachBufferToSource(sourceId, (AudioBuffer) data);
}else if (data instanceof AudioStream){
return attachStreamToSource(sourceId, (AudioStream) data);
}
throw new UnsupportedOperationException();
}
private void clearChannel(int index){
// make room at this channel
if (chanSrcs[index] != null){
AudioNode src = chanSrcs[index];
int sourceId = channels[index];
alSourceStop(sourceId);
if (src.getAudioData() instanceof AudioStream){
AudioStream str = (AudioStream) src.getAudioData();
ib.position(0).limit(STREAMING_BUFFER_COUNT);
ib.put(str.getIds()).flip();
alSourceUnqueueBuffers(sourceId, ib);
}else if (src.getAudioData() instanceof AudioBuffer){
alSourcei(sourceId, AL_BUFFER, 0);
}
if (src.getDryFilter() != null){
// detach filter
alSourcei(sourceId, EFX10.AL_DIRECT_FILTER, EFX10.AL_FILTER_NULL);
}
if (src.isPositional()){
AudioNode pas = (AudioNode) src;
if (pas.isReverbEnabled()) {
AL11.alSource3i(sourceId, EFX10.AL_AUXILIARY_SEND_FILTER, 0, 0, EFX10.AL_FILTER_NULL);
}
}
chanSrcs[index] = null;
}
}
public void update(float tpf){
// does nothing
}
public void updateInThread(float tpf){
if (audioDisabled)
return;
for (int i = 0; i < channels.length; i++){
AudioNode src = chanSrcs[i];
if (src == null)
continue;
int sourceId = channels[i];
// is the source bound to this channel
// if false, it's an instanced playback
boolean boundSource = i == src.getChannel();
// source's data is streaming
boolean streaming = src.getAudioData() instanceof AudioStream;
// only buffered sources can be bound
assert (boundSource && streaming) || (!streaming);
int state = alGetSourcei(sourceId, AL_SOURCE_STATE);
boolean wantPlaying = src.getStatus() == Status.Playing;
boolean stopped = state == AL_STOPPED;
if (streaming && wantPlaying){
AudioStream stream = (AudioStream) src.getAudioData();
if (stream.isOpen()){
fillStreamingSource(sourceId, stream);
if (stopped)
alSourcePlay(sourceId);
}else{
if (stopped){
// became inactive
src.setStatus(Status.Stopped);
src.setChannel(-1);
clearChannel(i);
freeChannel(i);
}
}
}else if (!streaming){
boolean paused = state == AL_PAUSED;
// make sure OAL pause state & source state coincide
assert (src.getStatus() == Status.Paused && paused) || (!paused);
if (stopped){
if (boundSource){
src.setStatus(Status.Stopped);
src.setChannel(-1);
}
clearChannel(i);
freeChannel(i);
}
}
}
}
public void setListener(Listener listener) {
checkDead();
synchronized (threadLock){
while (!threadLock.get()){
try {
threadLock.wait();
} catch (InterruptedException ex) {
}
}
if (audioDisabled)
return;
if (this.listener != null){
// previous listener no longer associated with current
// renderer
this.listener.setRenderer(null);
}
this.listener = listener;
this.listener.setRenderer(this);
setListenerParams(listener);
}
}
public void playSourceInstance(AudioNode src){
checkDead();
synchronized (threadLock){
while (!threadLock.get()){
try {
threadLock.wait();
} catch (InterruptedException ex) {
}
}
if (audioDisabled)
return;
if (src.getAudioData() instanceof AudioStream)
throw new UnsupportedOperationException(
"Cannot play instances " +
"of audio streams. Use playSource() instead.");
if (src.getAudioData().isUpdateNeeded()){
updateAudioData(src.getAudioData());
}
// create a new index for an audio-channel
int index = newChannel();
if (index == -1)
return;
int sourceId = channels[index];
clearChannel(index);
// set parameters, like position and max distance
setSourceParams(sourceId, src, true);
attachAudioToSource(sourceId, src.getAudioData());
chanSrcs[index] = src;
// play the channel
alSourcePlay(sourceId);
}
}
public void playSource(AudioNode src) {
checkDead();
synchronized (threadLock){
while (!threadLock.get()){
try {
threadLock.wait();
} catch (InterruptedException ex) {
}
}
if (audioDisabled)
return;
//assert src.getStatus() == Status.Stopped || src.getChannel() == -1;
if (src.getStatus() == Status.Playing){
return;
}else if (src.getStatus() == Status.Stopped){
// allocate channel to this source
int index = newChannel();
if (index == -1) {
logger.log(Level.WARNING, "No channel available to play {0}", src);
return;
}
clearChannel(index);
src.setChannel(index);
AudioData data = src.getAudioData();
if (data.isUpdateNeeded())
updateAudioData(data);
chanSrcs[index] = src;
setSourceParams(channels[index], src, false);
attachAudioToSource(channels[index], data);
}
alSourcePlay(channels[src.getChannel()]);
src.setStatus(Status.Playing);
}
}
public void pauseSource(AudioNode src) {
checkDead();
synchronized (threadLock){
while (!threadLock.get()){
try {
threadLock.wait();
} catch (InterruptedException ex) {
}
}
if (audioDisabled)
return;
if (src.getStatus() == Status.Playing){
assert src.getChannel() != -1;
alSourcePause(channels[src.getChannel()]);
src.setStatus(Status.Paused);
}
}
}
public void stopSource(AudioNode src) {
synchronized (threadLock){
while (!threadLock.get()){
try {
threadLock.wait();
} catch (InterruptedException ex) {
}
}
if (audioDisabled)
return;
if (src.getStatus() != Status.Stopped){
int chan = src.getChannel();
assert chan != -1; // if it's not stopped, must have id
src.setStatus(Status.Stopped);
src.setChannel(-1);
clearChannel(chan);
freeChannel(chan);
}
}
}
private int convertFormat(AudioData ad){
switch (ad.getBitsPerSample()){
case 8:
if (ad.getChannels() == 1)
return AL_FORMAT_MONO8;
else if (ad.getChannels() == 2)
return AL_FORMAT_STEREO8;
break;
case 16:
if (ad.getChannels() == 1)
return AL_FORMAT_MONO16;
else
return AL_FORMAT_STEREO16;
}
throw new UnsupportedOperationException("Unsupported channels/bits combination: "+
"bits="+ad.getBitsPerSample()+", channels="+ad.getChannels());
}
private void updateAudioBuffer(AudioBuffer ab){
int id = ab.getId();
if (ab.getId() == -1){
ib.position(0).limit(1);
alGenBuffers(ib);
id = ib.get(0);
ab.setId(id);
}
ab.getData().clear();
alBufferData(id, convertFormat(ab), ab.getData(), ab.getSampleRate());
ab.clearUpdateNeeded();
}
private void updateAudioStream(AudioStream as){
if (as.getIds() != null){
deleteAudioData(as);
}
int[] ids = new int[STREAMING_BUFFER_COUNT];
ib.position(0).limit(STREAMING_BUFFER_COUNT);
alGenBuffers(ib);
ib.position(0).limit(STREAMING_BUFFER_COUNT);
ib.get(ids);
as.setIds(ids);
as.clearUpdateNeeded();
}
private void updateAudioData(AudioData ad){
if (ad instanceof AudioBuffer){
updateAudioBuffer((AudioBuffer) ad);
}else if (ad instanceof AudioStream){
updateAudioStream((AudioStream) ad);
}
}
public void deleteAudioData(AudioData ad){
if (audioDisabled)
return;
if (ad instanceof AudioBuffer){
AudioBuffer ab = (AudioBuffer) ad;
int id = ab.getId();
if (id != -1){
ib.put(0,id);
ib.position(0).limit(1);
alDeleteBuffers(ib);
ab.resetObject();
}
}else if (ad instanceof AudioStream){
AudioStream as = (AudioStream) ad;
int[] ids = as.getIds();
if (ids != null){
ib.clear();
ib.put(ids).flip();
alDeleteBuffers(ib);
as.resetObject();
}
}
}
}
|
package com.datatorrent.stram.client;
import com.datatorrent.stram.client.StramAppLauncher.AppFactory;
import com.datatorrent.stram.plan.logical.LogicalPlan;
import java.io.*;
import java.util.*;
import java.util.jar.*;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* AppPackage class.</p>
*
* @author David Yan <david@datatorrent.com>
* @since 1.0.3
*/
public class AppPackage extends JarFile implements Closeable
{
public static final String ATTRIBUTE_DT_ENGINE_VERSION = "DT-Engine-Version";
public static final String ATTRIBUTE_DT_APP_PACKAGE_NAME = "DT-App-Package-Name";
public static final String ATTRIBUTE_DT_APP_PACKAGE_VERSION = "DT-App-Package-Version";
public static final String ATTRIBUTE_CLASS_PATH = "Class-Path";
public static final String ATTRIBUTE_DT_APP_PACKAGE_DISPLAY_NAME = "DT-App-Package-Display-Name";
public static final String ATTRIBUTE_DT_APP_PACKAGE_DESCRIPTION = "DT-App-Package-Description";
private final String appPackageName;
private final String appPackageVersion;
private final String dtEngineVersion;
private final String appPackageDescription;
private final String appPackageDisplayName;
private final ArrayList<String> classPath = new ArrayList<String>();
private final String directory;
private final List<AppInfo> applications = new ArrayList<AppInfo>();
private final List<String> appJars = new ArrayList<String>();
private final List<String> appJsonFiles = new ArrayList<String>();
private final List<String> appPropertiesFiles = new ArrayList<String>();
private final Set<String> requiredProperties = new TreeSet<String>();
private final Map<String, String> defaultProperties = new TreeMap<String, String>();
private final Set<String> configs = new TreeSet<String>();
public static class AppInfo
{
public final String name;
public final String file;
public final String type;
public LogicalPlan dag;
public String error;
public AppInfo(String name, String file, String type)
{
this.name = name;
this.file = file;
this.type = type;
}
}
public AppPackage(File file) throws IOException, ZipException
{
this(file, false);
}
/**
* Creates an App Package object.
*
* If app directory is to be processed, there may be resource leak in the class loader. Only pass true for short-lived applications
*
* @param file
* @param processAppDirectory
* @throws java.io.IOException
* @throws net.lingala.zip4j.exception.ZipException
*/
public AppPackage(File file, boolean processAppDirectory) throws IOException, ZipException
{
super(file);
Manifest manifest = getManifest();
if (manifest == null) {
throw new IOException("Not a valid app package. MANIFEST.MF is not present.");
}
Attributes attr = manifest.getMainAttributes();
appPackageName = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_NAME);
appPackageVersion = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_VERSION);
dtEngineVersion = attr.getValue(ATTRIBUTE_DT_ENGINE_VERSION);
appPackageDisplayName = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_DISPLAY_NAME);
appPackageDescription = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_DESCRIPTION);
String classPathString = attr.getValue(ATTRIBUTE_CLASS_PATH);
if (appPackageName == null || appPackageVersion == null || classPathString == null) {
throw new IOException("Not a valid app package. Class-Path is missing from MANIFEST.MF");
}
classPath.addAll(Arrays.asList(StringUtils.split(classPathString, " ")));
ZipFile zipFile = new ZipFile(file);
if (zipFile.isEncrypted()) {
throw new ZipException("Encrypted app package not supported yet");
}
File newDirectory = new File("/tmp/dt-appPackage-" + System.currentTimeMillis());
newDirectory.mkdirs();
directory = newDirectory.getAbsolutePath();
zipFile.extractAll(directory);
if (processAppDirectory) {
processAppDirectory(new File(newDirectory, "app"));
}
File confDirectory = new File(newDirectory, "conf");
if (confDirectory.exists()) {
processConfDirectory(confDirectory);
}
File propertiesXml = new File(newDirectory, "META-INF/properties.xml");
if (propertiesXml.exists()) {
processPropertiesXml(propertiesXml);
}
}
public String tempDirectory()
{
return directory;
}
@Override
public void close() throws IOException
{
super.close();
FileUtils.deleteDirectory(new File(directory));
}
public String getAppPackageName()
{
return appPackageName;
}
public String getAppPackageVersion()
{
return appPackageVersion;
}
public String getAppPackageDescription()
{
return appPackageDescription;
}
public String getAppPackageDisplayName()
{
return appPackageDisplayName;
}
public String getDtEngineVersion()
{
return dtEngineVersion;
}
public List<String> getClassPath()
{
return Collections.unmodifiableList(classPath);
}
public Collection<String> getConfigs()
{
return Collections.unmodifiableCollection(configs);
}
public List<AppInfo> getApplications()
{
return Collections.unmodifiableList(applications);
}
public List<String> getAppJars()
{
return Collections.unmodifiableList(appJars);
}
public List<String> getAppJsonFiles()
{
return Collections.unmodifiableList(appJsonFiles);
}
public List<String> getAppPropertiesFiles()
{
return Collections.unmodifiableList(appPropertiesFiles);
}
public Set<String> getRequiredProperties()
{
return Collections.unmodifiableSet(requiredProperties);
}
public Map<String, String> getDefaultProperties()
{
return Collections.unmodifiableMap(defaultProperties);
}
private void processAppDirectory(File dir)
{
Iterator<File> it = FileUtils.iterateFiles(dir, null, false);
Configuration config = new Configuration();
List<String> absClassPath = new ArrayList<String>(classPath);
for (int i = 0; i < absClassPath.size(); i++) {
String path = absClassPath.get(i);
if (!path.startsWith("/")) {
absClassPath.set(i, directory + "/" + path);
}
}
config.set(StramAppLauncher.LIBJARS_CONF_KEY_NAME, StringUtils.join(absClassPath, ','));
while (it.hasNext()) {
File entry = it.next();
if (entry.getName().endsWith(".jar")) {
appJars.add(entry.getName());
try {
StramAppLauncher stramAppLauncher = new StramAppLauncher(entry, config);
stramAppLauncher.loadDependencies();
List<AppFactory> appFactories = stramAppLauncher.getBundledTopologies();
for (AppFactory appFactory : appFactories) {
String appName = stramAppLauncher.getLogicalPlanConfiguration().getAppAlias(appFactory.getName());
if (appName == null) {
appName = appFactory.getName();
}
AppInfo appInfo = new AppInfo(appName, entry.getName(), "class");
appInfo.dag = stramAppLauncher.prepareDAG(appFactory);
try {
appInfo.dag.validate();
}
catch (Exception ex) {
appInfo.error = ex.getMessage();
}
applications.add(appInfo);
}
}
catch (Exception ex) {
LOG.error("Caught exception trying to process {}", entry.getName(), ex);
}
}
}
it = FileUtils.iterateFiles(dir, null, false);
// this is for the properties and json files to be able to depend on the app jars,
// since it's possible for users to implement the operators as part of the app package
for (String appJar : appJars) {
absClassPath.add(new File(dir, appJar).getAbsolutePath());
}
config.set(StramAppLauncher.LIBJARS_CONF_KEY_NAME, StringUtils.join(absClassPath, ','));
while (it.hasNext()) {
File entry = it.next();
if (entry.getName().endsWith(".json")) {
appJsonFiles.add(entry.getName());
try {
AppFactory appFactory = new StramAppLauncher.JsonFileAppFactory(entry);
StramAppLauncher stramAppLauncher = new StramAppLauncher(entry.getName(), config);
stramAppLauncher.loadDependencies();
AppInfo appInfo = new AppInfo(appFactory.getName(), entry.getName(), "json");
appInfo.dag = stramAppLauncher.prepareDAG(appFactory);
try {
appInfo.dag.validate();
}
catch (Exception ex) {
appInfo.error = ex.getMessage();
}
applications.add(appInfo);
}
catch (Exception ex) {
LOG.error("Caught exceptions trying to process {}", entry.getName(), ex);
}
}
else if (entry.getName().endsWith(".properties")) {
appPropertiesFiles.add(entry.getName());
try {
AppFactory appFactory = new StramAppLauncher.PropertyFileAppFactory(entry);
StramAppLauncher stramAppLauncher = new StramAppLauncher(entry.getName(), config);
stramAppLauncher.loadDependencies();
AppInfo appInfo = new AppInfo(appFactory.getName(), entry.getName(), "properties");
try {
appInfo.dag = stramAppLauncher.prepareDAG(appFactory);
}
catch (Throwable t) {
appInfo.error = t.getMessage();
}
applications.add(appInfo);
}
catch (Exception ex) {
LOG.error("Caught exceptions trying to process {}", entry.getName(), ex);
}
}
else {
LOG.warn("Ignoring file {} with unknown extension in app directory", entry.getName());
}
}
}
private void processConfDirectory(File dir)
{
Iterator<File> it = FileUtils.iterateFiles(dir, null, false);
while (it.hasNext()) {
File entry = it.next();
if (entry.getName().endsWith(".xml")) {
configs.add(entry.getName());
}
}
}
private void processPropertiesXml(File file)
{
DTConfiguration config = new DTConfiguration();
try {
config.loadFile(file);
for (Map.Entry<String, String> entry : config) {
String key = entry.getKey();
String value = entry.getValue();
if (value == null) {
requiredProperties.add(key);
}
else {
defaultProperties.put(key, value);
}
}
}
catch (Exception ex) {
LOG.warn("Ignoring META_INF/properties.xml because of error", ex);
}
}
private static final Logger LOG = LoggerFactory.getLogger(AppPackage.class);
}
|
package org.broadinstitute.sting.gatk.refdata;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.GenomeLocParser;
import org.broadinstitute.sting.utils.Utils;
import org.broadinstitute.sting.utils.text.XReadLines;
public class AnnotatorROD extends TabularROD {
private static Logger logger = Logger.getLogger(AnnotatorROD.class);
/** Special column names */
public static final String CHRPOS_COLUMN = "chrpos";
public static final String HAPLOTYPE_REFERENCE_COLUMN = "haplotypeReference";
public static final String HAPLOTYPE_ALTERNATE_COLUMN = "haplotypeAlternate";
public static final String HAPLOTYPE_STRAND_COLUMN = "haplotypeStrand";
private static int parsedRecords = 0;
// Temporary attributes were added to make it easier to implement certain
// optimizations for RODs that span an interval. For example, if a Walker
// needs to do a time-consuming computation on data from a ROD, it would normally
// have to repeat this computation every time its map(..) method is called.
// If a ROD spans an interval, the Walker's map(..) method will be called for every position in ROD.
// However, many computations (including validation and parsing) are done per ROD rather than
// per position. Therefore, substantial optimizations are possible if the result
// of the first computation is cached and reused on subsequent map(..) calls.
// Temporary attributes provide a convenient place to store these results,
// freeing the Walkers from having to maintain their own ROD -> result hashmaps.
private Map<Object, Object> temporaryAttributes;
/**
* Constructor.
*
* @param name The binding name provided as the first in the list of -B args.
*/
public AnnotatorROD(String name) {
super(name, new ArrayList<String>());
setDelimiter("\t", "\\t");
}
/**
* Walks through the source files looking for the header line, which it
* returns as a list of strings.
*
* @param source
* @return
*/
public Object initialize(final File source) throws FileNotFoundException {
ArrayList<String> header = AnnotatorROD.readHeader(source);
return header;
}
/**
* Finds and parses the header string in the file.
* @param source The source file.
* @return A List of the column names parsed out of the header.
* @throws FileNotFoundException
*/
public static ArrayList<String> readHeader(final File source) throws FileNotFoundException {
ArrayList<String> header = null;
XReadLines reader = new XReadLines(source);
//find the 1st line that's non-empty and not a comment
for ( String line : reader ) {
line = line.trim();
if ( line.isEmpty() || line.startsWith("
continue;
}
header = new ArrayList<String>(Arrays.asList(line.split(DELIMITER_REGEX)));
break;
}
// check that we found the header
if ( header == null ) {
throw new RuntimeException("No header in " + source + ". All lines are either comments or empty.");
}
logger.info(String.format("Found header line containing %d columns:\n[%s]", header.size(), Utils.join("\t", header)));
try {
reader.close();
} catch ( IOException e ) {
throw new RuntimeException(e);
}
return header;
}
/**
* Used by ROD management system to set the data in this ROD associated with a line in a rod
*
* @param headerObj
* @param parts
* @return
* @throws IOException
*/
public boolean parseLine(final Object headerObj, final String[] parts) throws IOException {
ArrayList<String> header = (ArrayList<String>)(headerObj);
//save the header in the super-class
getHeader().addAll(header);
if ( parts.length == 0 || parts[0].startsWith("#") || header.get(0).equals(parts[0]) /* Skip the header line */ )
return false;
if ( header.size() < parts.length) {
throw new IOException(String.format("Encountered line with more columns than have names in the header. Header has %d columns, this line has %d columns.", header.size(), parts.length));
}
for ( int i = 0; i < parts.length; i++ ) {
put(header.get(i), parts[i]);
}
if ( printRecordsParsed ) System.out.printf("Parsed %d records %s%n", ++parsedRecords, this);
return true;
}
// ROD accessors
public GenomeLoc getLocation() {
if ( loc == null ) {
String s = get(getHeader().get(0));
if(s == null) {
throw new RuntimeException("Location not set.."); //this should never happen unless the line in the file is empty
}
loc = GenomeLocParser.parseGenomeLoc(s);
}
return loc;
}
/**
* Checks whether an attribute has been set for the given key.
*
* Temporary attributes make it easier to implement certain
* optimizations for RODs that span an interval. For example, if a Walker
* needs to do a time-consuming computation on data from a ROD, it would normally
* have to repeat this computation every time its map(..) method is called.
* If a ROD spans an interval, the Walker's map(..) method will be called for every position in ROD.
* However, many computations (including validation and parsing) are done per ROD rather than
* per position. Therefore, substantial optimizations are possible if the result
* of the first computation is cached and reused on subsequent map(..) calls.
* Temporary attributes provide a convenient place to store these results,
* freeing the Walkers from having to maintain their own ROD -> result hashmaps.
*
* @param key key
* @return True if an attribute has been set for this key.
*/
public boolean containsTemporaryAttribute(Object key) {
if(temporaryAttributes != null) {
return temporaryAttributes.containsKey(key);
}
return false;
}
/**
* Sets the key to the given value, replacing any previous value. The previous
* value is returned.
*
* Temporary attributes make it easier to implement certain
* optimizations for RODs that span an interval. For example, if a Walker
* needs to do a time-consuming computation on data from a ROD, it would normally
* have to repeat this computation every time its map(..) method is called.
* If a ROD spans an interval, the Walker's map(..) method will be called for every position in ROD.
* However, many computations (including validation and parsing) are done per ROD rather than
* per position. Therefore, substantial optimizations are possible if the result
* of the first computation is cached and reused on subsequent map(..) calls.
* Temporary attributes provide a convenient place to store these results,
* freeing the Walkers from having to maintain their own ROD -> result hashmaps.
*
* @param key key
* @param value value
* @return attribute
*/
public Object setTemporaryAttribute(Object key, Object value) {
if(temporaryAttributes == null) {
temporaryAttributes = new HashMap<Object, Object>();
}
return temporaryAttributes.put(key, value);
}
/**
* Looks up the value associated with the given key.
*
* Temporary attributes make it easier to implement certain
* optimizations for RODs that span an interval. For example, if a Walker
* needs to do a time-consuming computation on data from a ROD, it would normally
* have to repeat this computation every time its map(..) method is called.
* If a ROD spans an interval, the Walker's map(..) method will be called for every position in ROD.
* However, many computations (including validation and parsing) are done per ROD rather than
* per position. Therefore, substantial optimizations are possible if the result
* of the first computation is cached and reused on subsequent map(..) calls.
* Temporary attributes provide a convenient place to store these results,
* freeing the Walkers from having to maintain their own ROD -> result hashmaps.
*
* @param key key
* @return The value, or null.
*/
public Object getTemporaryAttribute(Object key) {
if(temporaryAttributes != null) {
return temporaryAttributes.get(key);
}
return null;
}
/**
* Removes the attribute that has the given key.
*
* Temporary attributes make it easier to implement certain
* optimizations for RODs that span an interval. For example, if a Walker
* needs to do a time-consuming computation on data from a ROD, it would normally
* have to repeat this computation every time its map(..) method is called.
* If a ROD spans an interval, the Walker's map(..) method will be called for every position in ROD.
* However, many computations (including validation and parsing) are done per ROD rather than
* per position. Therefore, substantial optimizations are possible if the result
* of the first computation is cached and reused on subsequent map(..) calls.
* Temporary attributes provide a convenient place to store these results,
* freeing the Walkers from having to maintain their own ROD -> result hashmaps.
*
* @param key key
* @return The value that was associated with this key, or null.
*/
public Object removeTemporaryAttribute(Object key) {
if(temporaryAttributes != null) {
return temporaryAttributes.remove(key);
}
return null;
}
}
|
package com.kii.thingif.utils;
import com.kii.thingif.clause.trigger.AndClauseInTrigger;
import com.kii.thingif.clause.trigger.EqualsClauseInTrigger;
import com.kii.thingif.clause.trigger.NotEqualsClauseInTrigger;
import com.kii.thingif.clause.trigger.OrClauseInTrigger;
import com.kii.thingif.clause.trigger.RangeClauseInTrigger;
import com.kii.thingif.clause.trigger.TriggerClause;
import com.kii.thingif.trigger.Predicate;
import com.kii.thingif.trigger.ScheduleOncePredicate;
import com.kii.thingif.trigger.SchedulePredicate;
import com.kii.thingif.trigger.ServerCode;
import com.kii.thingif.trigger.StatePredicate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonUtil {
public static JSONObject triggerClauseToJson(TriggerClause clause) {
try {
if (clause instanceof EqualsClauseInTrigger) {
JSONObject json = new JSONObject();
EqualsClauseInTrigger eq = (EqualsClauseInTrigger)clause;
json.put("type", "eq");
json.put("alias", eq.getAlias());
json.put("field", eq.getField());
json.put("value", eq.getValue());
return json;
} else if(clause instanceof NotEqualsClauseInTrigger) {
return new JSONObject()
.put("type", "not")
.put("clause", triggerClauseToJson(((NotEqualsClauseInTrigger) clause).getEquals()));
} else if (clause instanceof RangeClauseInTrigger) {
JSONObject rangeJson = new JSONObject();
RangeClauseInTrigger range = (RangeClauseInTrigger) clause;
rangeJson.put("type", "range");
rangeJson.put("alias", range.getAlias());
rangeJson.put("field", range.getField());
rangeJson.putOpt("lowerIncluded", range.getLowerIncluded());
rangeJson.putOpt("lowerLimit", range.getLowerLimit());
rangeJson.putOpt("upperIncluded", range.getUpperIncluded());
rangeJson.putOpt("upperLimit", range.getUpperLimit());
return rangeJson;
} else if (clause instanceof AndClauseInTrigger) {
JSONArray clauses = new JSONArray();
for (TriggerClause subClause : ((AndClauseInTrigger)clause).getClauses()) {
clauses.put(triggerClauseToJson(subClause));
}
return new JSONObject()
.put("type", "and")
.put("clauses", clauses);
} else if (clause instanceof OrClauseInTrigger) {
JSONArray clauses = new JSONArray();
for (TriggerClause subClause : ((OrClauseInTrigger) clause).getClauses()) {
clauses.put(triggerClauseToJson(subClause));
}
return new JSONObject()
.put("type", "or")
.put("clauses", clauses);
}else{
throw new RuntimeException("not support trigger clause");
}
}catch (JSONException ex) {
throw new RuntimeException(ex);
}
}
public static JSONObject predicateToJson(Predicate predicate) {
try {
JSONObject predicateJson = new JSONObject().put(
"eventSource",
predicate.getEventSource().name());
if (predicate instanceof StatePredicate) {
return predicateJson
.put("triggersWhen",
((StatePredicate) predicate).getTriggersWhen().name())
.put("condition",
triggerClauseToJson(((StatePredicate) predicate).getCondition().getClause()));
} else if (predicate instanceof ScheduleOncePredicate) {
return predicateJson.put(
"scheduleAt",
((ScheduleOncePredicate) predicate).getScheduleAt());
} else if (predicate instanceof SchedulePredicate) {
return predicateJson.put(
"schedule",
((SchedulePredicate) predicate).getSchedule());
} else {
throw new RuntimeException("not support predicate");
}
}catch (JSONException e) {
throw new RuntimeException(e);
}
}
public static JSONObject serverCodeToJson(ServerCode serverCode) {
JSONObject ret = new JSONObject();
try {
ret.put("endPoint", serverCode.getEndpoint());
ret.putOpt("executorAccessToken", serverCode.getExecutorAccessToken());
ret.putOpt("targetAppID", serverCode.getTargetAppID());
ret.putOpt("parameters", serverCode.getParameters());
return ret;
}catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
|
package org.neo4j.com;
import java.io.IOException;
import org.neo4j.helpers.collection.Visitor;
import org.neo4j.kernel.impl.transaction.xaframework.CommittedTransactionRepresentation;
public interface TransactionStream
{
void accept( Visitor<CommittedTransactionRepresentation, IOException> visitor ) throws IOException;
public static final TransactionStream EMPTY = new TransactionStream()
{
@Override
public void accept( Visitor<CommittedTransactionRepresentation, IOException> visitor ) throws IOException
{
}
};
}
|
package org.ethereum.vm.program;
import org.ethereum.config.CommonConfig;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.Repository;
import org.ethereum.core.Transaction;
import org.ethereum.crypto.HashUtil;
import org.ethereum.db.ContractDetails;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.FastByteComparisons;
import org.ethereum.util.Utils;
import org.ethereum.vm.*;
import org.ethereum.vm.MessageCall.MsgType;
import org.ethereum.vm.PrecompiledContracts.PrecompiledContract;
import org.ethereum.vm.program.invoke.ProgramInvoke;
import org.ethereum.vm.program.invoke.ProgramInvokeFactory;
import org.ethereum.vm.program.invoke.ProgramInvokeFactoryImpl;
import org.ethereum.vm.program.listener.CompositeProgramListener;
import org.ethereum.vm.program.listener.ProgramListenerAware;
import org.ethereum.vm.program.listener.ProgramStorageChangeListener;
import org.ethereum.vm.trace.ProgramTraceListener;
import org.ethereum.vm.trace.ProgramTrace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.util.*;
import static java.lang.StrictMath.min;
import static java.lang.String.format;
import static java.math.BigInteger.ZERO;
import static java.math.BigInteger.valueOf;
import static org.apache.commons.lang3.ArrayUtils.*;
import static org.ethereum.util.BIUtil.*;
import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY;
/**
* @author Roman Mandeleil
* @since 01.06.2014
*/
public class Program {
private static final Logger logger = LoggerFactory.getLogger("VM");
/**
* This attribute defines the number of recursive calls allowed in the EVM
* Note: For the JVM to reach this level without a StackOverflow exception,
* ethereumj may need to be started with a JVM argument to increase
* the stack size. For example: -Xss10m
*/
private static final int MAX_DEPTH = 1024;
//Max size for stack checks
private static final int MAX_STACKSIZE = 1024;
private Transaction transaction;
private ProgramInvoke invoke;
private ProgramInvokeFactory programInvokeFactory = new ProgramInvokeFactoryImpl();
private ProgramOutListener listener;
private ProgramTraceListener traceListener;
private ProgramStorageChangeListener storageDiffListener = new ProgramStorageChangeListener();
private CompositeProgramListener programListener = new CompositeProgramListener();
private Stack stack;
private Memory memory;
private Storage storage;
private ProgramResult result = new ProgramResult();
private ProgramTrace trace = new ProgramTrace();
private byte[] ops;
private int pc;
private byte lastOp;
private byte previouslyExecutedOp;
private boolean stopped;
private Set<Integer> jumpdest = new HashSet<>();
@Autowired
CommonConfig commonConfig = CommonConfig.getDefault();
private final SystemProperties config;
public Program(byte[] ops, ProgramInvoke programInvoke) {
this(ops, programInvoke, null);
}
public Program(byte[] ops, ProgramInvoke programInvoke, Transaction transaction) {
this(ops, programInvoke, transaction, SystemProperties.getDefault());
}
public Program(byte[] ops, ProgramInvoke programInvoke, Transaction transaction, SystemProperties config) {
this.config = config;
this.invoke = programInvoke;
this.transaction = transaction;
this.ops = nullToEmpty(ops);
traceListener = new ProgramTraceListener(config.vmTrace());
this.memory = setupProgramListener(new Memory());
this.stack = setupProgramListener(new Stack());
this.storage = setupProgramListener(new Storage(programInvoke));
this.trace = new ProgramTrace(config, programInvoke);
precompile();
}
public int getCallDeep() {
return invoke.getCallDeep();
}
private InternalTransaction addInternalTx(byte[] nonce, DataWord gasLimit, byte[] senderAddress, byte[] receiveAddress,
BigInteger value, byte[] data, String note) {
InternalTransaction result = null;
if (transaction != null) {
byte[] senderNonce = isEmpty(nonce) ? getStorage().getNonce(senderAddress).toByteArray() : nonce;
result = getResult().addInternalTransaction(transaction.getHash(), getCallDeep(), senderNonce,
getGasPrice(), gasLimit, senderAddress, receiveAddress, value.toByteArray(), data, note);
}
return result;
}
private <T extends ProgramListenerAware> T setupProgramListener(T programListenerAware) {
if (programListener.isEmpty()) {
programListener.addListener(traceListener);
programListener.addListener(storageDiffListener);
}
programListenerAware.setProgramListener(programListener);
return programListenerAware;
}
public Map<DataWord, DataWord> getStorageDiff() {
return storageDiffListener.getDiff();
}
public byte getOp(int pc) {
return (getLength(ops) <= pc) ? 0 : ops[pc];
}
public byte getCurrentOp() {
return isEmpty(ops) ? 0 : ops[pc];
}
/**
* Last Op can only be set publicly (no getLastOp method), is used for logging.
*/
public void setLastOp(byte op) {
this.lastOp = op;
}
/**
* Should be set only after the OP is fully executed.
*/
public void setPreviouslyExecutedOp(byte op) {
this.previouslyExecutedOp = op;
}
/**
* Returns the last fully executed OP.
*/
public byte getPreviouslyExecutedOp() {
return this.previouslyExecutedOp;
}
public void stackPush(byte[] data) {
stackPush(new DataWord(data));
}
public void stackPushZero() {
stackPush(new DataWord(0));
}
public void stackPushOne() {
DataWord stackWord = new DataWord(1);
stackPush(stackWord);
}
public void stackPush(DataWord stackWord) {
verifyStackOverflow(0, 1); //Sanity Check
stack.push(stackWord);
}
public Stack getStack() {
return this.stack;
}
public int getPC() {
return pc;
}
public void setPC(DataWord pc) {
this.setPC(pc.intValue());
}
public void setPC(int pc) {
this.pc = pc;
if (this.pc >= ops.length) {
stop();
}
}
public boolean isStopped() {
return stopped;
}
public void stop() {
stopped = true;
}
public void setHReturn(byte[] buff) {
getResult().setHReturn(buff);
}
public void step() {
setPC(pc + 1);
}
public byte[] sweep(int n) {
if (pc + n > ops.length)
stop();
byte[] data = Arrays.copyOfRange(ops, pc, pc + n);
pc += n;
if (pc >= ops.length) stop();
return data;
}
public DataWord stackPop() {
return stack.pop();
}
/**
* Verifies that the stack is at least <code>stackSize</code>
*
* @param stackSize int
* @throws StackTooSmallException If the stack is
* smaller than <code>stackSize</code>
*/
public void verifyStackSize(int stackSize) {
if (stack.size() < stackSize) {
throw Program.Exception.tooSmallStack(stackSize, stack.size());
}
}
public void verifyStackOverflow(int argsReqs, int returnReqs) {
if ((stack.size() - argsReqs + returnReqs) > MAX_STACKSIZE) {
throw new StackTooLargeException("Expected: overflow " + MAX_STACKSIZE + " elements stack limit");
}
}
public int getMemSize() {
return memory.size();
}
public void memorySave(DataWord addrB, DataWord value) {
memory.write(addrB.intValue(), value.getData(), value.getData().length, false);
}
public void memorySaveLimited(int addr, byte[] data, int dataSize) {
memory.write(addr, data, dataSize, true);
}
public void memorySave(int addr, byte[] value) {
memory.write(addr, value, value.length, false);
}
public void memoryExpand(DataWord outDataOffs, DataWord outDataSize) {
if (!outDataSize.isZero()) {
memory.extend(outDataOffs.intValue(), outDataSize.intValue());
}
}
/**
* Allocates a piece of memory and stores value at given offset address
*
* @param addr is the offset address
* @param allocSize size of memory needed to write
* @param value the data to write to memory
*/
public void memorySave(int addr, int allocSize, byte[] value) {
memory.extendAndWrite(addr, allocSize, value);
}
public DataWord memoryLoad(DataWord addr) {
return memory.readWord(addr.intValue());
}
public DataWord memoryLoad(int address) {
return memory.readWord(address);
}
public byte[] memoryChunk(int offset, int size) {
return memory.read(offset, size);
}
/**
* Allocates extra memory in the program for
* a specified size, calculated from a given offset
*
* @param offset the memory address offset
* @param size the number of bytes to allocate
*/
public void allocateMemory(int offset, int size) {
memory.extend(offset, size);
}
public void suicide(DataWord obtainerAddress) {
byte[] owner = getOwnerAddress().getLast20Bytes();
byte[] obtainer = obtainerAddress.getLast20Bytes();
BigInteger balance = getStorage().getBalance(owner);
if (logger.isInfoEnabled())
logger.info("Transfer to: [{}] heritage: [{}]",
Hex.toHexString(obtainer),
balance);
addInternalTx(null, null, owner, obtainer, balance, null, "suicide");
if (FastByteComparisons.compareTo(owner, 0, 20, obtainer, 0, 20) == 0) {
// if owner == obtainer just zeroing account according to Yellow Paper
getStorage().addBalance(owner, balance.negate());
} else {
transfer(getStorage(), owner, obtainer, balance);
}
getResult().addDeleteAccount(this.getOwnerAddress());
}
public Repository getStorage() {
return this.storage;
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public void createContract(DataWord value, DataWord memStart, DataWord memSize) {
if (getCallDeep() == MAX_DEPTH) {
stackPushZero();
return;
}
byte[] senderAddress = this.getOwnerAddress().getLast20Bytes();
BigInteger endowment = value.value();
if (isNotCovers(getStorage().getBalance(senderAddress), endowment)) {
stackPushZero();
return;
}
// [1] FETCH THE CODE FROM THE MEMORY
byte[] programCode = memoryChunk(memStart.intValue(), memSize.intValue());
if (logger.isInfoEnabled())
logger.info("creating a new contract inside contract run: [{}]", Hex.toHexString(senderAddress));
// actual gas subtract
DataWord gasLimit = getGas();
spendGas(gasLimit.longValue(), "internal call");
// [2] CREATE THE CONTRACT ADDRESS
byte[] nonce = getStorage().getNonce(senderAddress).toByteArray();
byte[] newAddress = HashUtil.calcNewAddr(getOwnerAddress().getLast20Bytes(), nonce);
if (byTestingSuite()) {
// This keeps track of the contracts created for a test
getResult().addCallCreate(programCode, EMPTY_BYTE_ARRAY,
gasLimit.getNoLeadZeroesData(),
value.getNoLeadZeroesData());
}
// [3] UPDATE THE NONCE
// (THIS STAGE IS NOT REVERTED BY ANY EXCEPTION)
if (!byTestingSuite()) {
getStorage().increaseNonce(senderAddress);
}
Repository track = getStorage().startTracking();
//In case of hashing collisions, check for any balance before createAccount()
if (track.isExist(newAddress)) {
BigInteger oldBalance = track.getBalance(newAddress);
track.createAccount(newAddress);
track.addBalance(newAddress, oldBalance);
} else
track.createAccount(newAddress);
// [4] TRANSFER THE BALANCE
track.addBalance(senderAddress, endowment.negate());
BigInteger newBalance = ZERO;
if (!byTestingSuite()) {
newBalance = track.addBalance(newAddress, endowment);
}
// [5] COOK THE INVOKE AND EXECUTE
InternalTransaction internalTx = addInternalTx(nonce, getGasLimit(), senderAddress, null, endowment, programCode, "create");
ProgramInvoke programInvoke = programInvokeFactory.createProgramInvoke(
this, new DataWord(newAddress), getOwnerAddress(), value, gasLimit,
newBalance, null, track, this.invoke.getBlockStore(), byTestingSuite());
ProgramResult result = ProgramResult.empty();
if (isNotEmpty(programCode)) {
VM vm = commonConfig.vm();
Program program = commonConfig.program(programCode, programInvoke, internalTx);
vm.play(program);
result = program.getResult();
getResult().merge(result);
}
// 4. CREATE THE CONTRACT OUT OF RETURN
byte[] code = result.getHReturn();
long storageCost = getLength(code) * GasCost.CREATE_DATA;
long afterSpend = programInvoke.getGas().longValue() - storageCost - result.getGasUsed();
if (afterSpend < 0) {
if (!config.getBlockchainConfig().getConfigForBlock(getNumber().longValue()).getConstants().createEmptyContractOnOOG()) {
result.setException(Program.Exception.notEnoughSpendingGas("No gas to return just created contract",
storageCost, this));
} else {
track.saveCode(newAddress, EMPTY_BYTE_ARRAY);
}
} else {
result.spendGas(storageCost);
track.saveCode(newAddress, code);
}
if (result.getException() != null) {
logger.debug("contract run halted by Exception: contract: [{}], exception: [{}]",
Hex.toHexString(newAddress),
result.getException());
internalTx.reject();
result.rejectInternalTransactions();
track.rollback();
stackPushZero();
return;
}
track.commit();
getResult().addDeleteAccounts(result.getDeleteAccounts());
// IN SUCCESS PUSH THE ADDRESS INTO THE STACK
stackPush(new DataWord(newAddress));
// 5. REFUND THE REMAIN GAS
long refundGas = gasLimit.longValue() - result.getGasUsed();
if (refundGas > 0) {
refundGas(refundGas, "remain gas from the internal call");
if (logger.isInfoEnabled()) {
logger.info("The remaining gas is refunded, account: [{}], gas: [{}] ",
Hex.toHexString(getOwnerAddress().getLast20Bytes()),
refundGas);
}
}
}
/**
* That method is for internal code invocations
* <p/>
* - Normal calls invoke a specified contract which updates itself
* - Stateless calls invoke code from another contract, within the context of the caller
*
* @param msg is the message call object
*/
public void callToAddress(MessageCall msg) {
if (getCallDeep() == MAX_DEPTH) {
stackPushZero();
refundGas(msg.getGas().longValue(), " call deep limit reach");
return;
}
byte[] data = memoryChunk(msg.getInDataOffs().intValue(), msg.getInDataSize().intValue());
// FETCH THE SAVED STORAGE
byte[] codeAddress = msg.getCodeAddress().getLast20Bytes();
byte[] senderAddress = getOwnerAddress().getLast20Bytes();
byte[] contextAddress = msg.getType().isStateless() ? senderAddress : codeAddress;
if (logger.isInfoEnabled())
logger.info(msg.getType().name() + " for existing contract: address: [{}], outDataOffs: [{}], outDataSize: [{}] ",
Hex.toHexString(contextAddress), msg.getOutDataOffs().longValue(), msg.getOutDataSize().longValue());
Repository track = getStorage().startTracking();
// 2.1 PERFORM THE VALUE (endowment) PART
BigInteger endowment = msg.getEndowment().value();
BigInteger senderBalance = track.getBalance(senderAddress);
if (isNotCovers(senderBalance, endowment)) {
stackPushZero();
refundGas(msg.getGas().longValue(), "refund gas from message call");
return;
}
// FETCH THE CODE
byte[] programCode = getStorage().isExist(codeAddress) ? getStorage().getCode(codeAddress) : EMPTY_BYTE_ARRAY;
track.addBalance(senderAddress, endowment.negate());
BigInteger contextBalance = ZERO;
if (byTestingSuite()) {
// This keeps track of the calls created for a test
getResult().addCallCreate(data, contextAddress,
msg.getGas().getNoLeadZeroesData(),
msg.getEndowment().getNoLeadZeroesData());
} else {
contextBalance = track.addBalance(contextAddress, endowment);
}
// CREATE CALL INTERNAL TRANSACTION
InternalTransaction internalTx = addInternalTx(null, getGasLimit(), senderAddress, contextAddress, endowment, programCode, "call");
ProgramResult result = null;
if (isNotEmpty(programCode)) {
ProgramInvoke programInvoke = programInvokeFactory.createProgramInvoke(
this, new DataWord(contextAddress),
msg.getType() == MsgType.DELEGATECALL ? getCallerAddress() : getOwnerAddress(),
msg.getType() == MsgType.DELEGATECALL ? getCallValue() : msg.getEndowment(),
msg.getGas(), contextBalance, data, track, this.invoke.getBlockStore(), byTestingSuite());
VM vm = commonConfig.vm();
Program program = commonConfig.program(programCode, programInvoke, internalTx);
vm.play(program);
result = program.getResult();
getTrace().merge(program.getTrace());
getResult().merge(result);
if (result.getException() != null) {
logger.debug("contract run halted by Exception: contract: [{}], exception: [{}]",
Hex.toHexString(contextAddress),
result.getException());
internalTx.reject();
result.rejectInternalTransactions();
// In this case we should reject LogInfo's too
result.rejectLogInfos();
track.rollback();
stackPushZero();
return;
} else if (Arrays.equals(transaction.getReceiveAddress(), internalTx.getReceiveAddress())) {
storageDiffListener.merge(program.getStorageDiff());
}
}
// 3. APPLY RESULTS: result.getHReturn() into out_memory allocated
if (result != null) {
byte[] buffer = result.getHReturn();
int offset = msg.getOutDataOffs().intValue();
int size = msg.getOutDataSize().intValue();
memorySaveLimited(offset, buffer, size);
}
// 4. THE FLAG OF SUCCESS IS ONE PUSHED INTO THE STACK
track.commit();
stackPushOne();
// 5. REFUND THE REMAIN GAS
if (result != null) {
BigInteger refundGas = msg.getGas().value().subtract(toBI(result.getGasUsed()));
if (isPositive(refundGas)) {
refundGas(refundGas.longValue(), "remaining gas from the internal call");
if (logger.isInfoEnabled())
logger.info("The remaining gas refunded, account: [{}], gas: [{}] ",
Hex.toHexString(senderAddress),
refundGas.toString());
}
} else {
refundGas(msg.getGas().longValue(), "remaining gas from the internal call");
}
}
public void spendGas(long gasValue, String cause) {
logger.debug("[{}] Spent for cause: [{}], gas: [{}]", invoke.hashCode(), cause, gasValue);
if (getGas().longValue() < gasValue) {
throw Program.Exception.notEnoughSpendingGas(cause, gasValue, this);
}
getResult().spendGas(gasValue);
}
public void spendAllGas() {
spendGas(getGas().longValue(), "Spending all remaining");
}
public void refundGas(long gasValue, String cause) {
logger.info("[{}] Refund for cause: [{}], gas: [{}]", invoke.hashCode(), cause, gasValue);
getResult().refundGas(gasValue);
}
public void futureRefundGas(long gasValue) {
logger.info("Future refund added: [{}]", gasValue);
getResult().addFutureRefund(gasValue);
}
public void resetFutureRefund() {
getResult().resetFutureRefund();
}
public void storageSave(DataWord word1, DataWord word2) {
storageSave(word1.getData(), word2.getData());
}
public void storageSave(byte[] key, byte[] val) {
DataWord keyWord = new DataWord(key);
DataWord valWord = new DataWord(val);
getStorage().addStorageRow(getOwnerAddress().getLast20Bytes(), keyWord, valWord);
}
public byte[] getCode() {
return ops;
}
public byte[] getCodeAt(DataWord address) {
byte[] code = invoke.getRepository().getCode(address.getLast20Bytes());
return nullToEmpty(code);
}
public DataWord getOwnerAddress() {
return invoke.getOwnerAddress().clone();
}
public DataWord getBlockHash(int index) {
return index < this.getNumber().longValue() && index >= Math.max(256, this.getNumber().intValue()) - 256 ?
new DataWord(this.invoke.getBlockStore().getBlockHashByNumber(index, getPrevHash().getData())) :
DataWord.ZERO.clone();
}
public DataWord getBalance(DataWord address) {
BigInteger balance = getStorage().getBalance(address.getLast20Bytes());
return new DataWord(balance.toByteArray());
}
public DataWord getOriginAddress() {
return invoke.getOriginAddress().clone();
}
public DataWord getCallerAddress() {
return invoke.getCallerAddress().clone();
}
public DataWord getGasPrice() {
return invoke.getMinGasPrice().clone();
}
public DataWord getGas() {
return new DataWord(invoke.getGasLong() - getResult().getGasUsed());
}
public DataWord getCallValue() {
return invoke.getCallValue().clone();
}
public DataWord getDataSize() {
return invoke.getDataSize().clone();
}
public DataWord getDataValue(DataWord index) {
return invoke.getDataValue(index);
}
public byte[] getDataCopy(DataWord offset, DataWord length) {
return invoke.getDataCopy(offset, length);
}
public DataWord storageLoad(DataWord key) {
DataWord ret = getStorage().getStorageValue(getOwnerAddress().getLast20Bytes(), key);
return ret == null ? null : ret.clone();
}
public DataWord getPrevHash() {
return invoke.getPrevHash().clone();
}
public DataWord getCoinbase() {
return invoke.getCoinbase().clone();
}
public DataWord getTimestamp() {
return invoke.getTimestamp().clone();
}
public DataWord getNumber() {
return invoke.getNumber().clone();
}
public DataWord getDifficulty() {
return invoke.getDifficulty().clone();
}
public DataWord getGasLimit() {
return invoke.getGaslimit().clone();
}
public ProgramResult getResult() {
return result;
}
public void setRuntimeFailure(RuntimeException e) {
getResult().setException(e);
}
public String memoryToString() {
return memory.toString();
}
public void fullTrace() {
if (logger.isTraceEnabled() || listener != null) {
StringBuilder stackData = new StringBuilder();
for (int i = 0; i < stack.size(); ++i) {
stackData.append(" ").append(stack.get(i));
if (i < stack.size() - 1) stackData.append("\n");
}
if (stackData.length() > 0) stackData.insert(0, "\n");
ContractDetails contractDetails = getStorage().
getContractDetails(getOwnerAddress().getLast20Bytes());
StringBuilder storageData = new StringBuilder();
if (contractDetails != null) {
List<DataWord> storageKeys = new ArrayList<>(contractDetails.getStorage().keySet());
Collections.sort(storageKeys);
for (DataWord key : storageKeys) {
storageData.append(" ").append(key).append(" -> ").
append(contractDetails.getStorage().get(key)).append("\n");
}
if (storageData.length() > 0) storageData.insert(0, "\n");
}
StringBuilder memoryData = new StringBuilder();
StringBuilder oneLine = new StringBuilder();
if (memory.size() > 320)
memoryData.append("... Memory Folded.... ")
.append("(")
.append(memory.size())
.append(") bytes");
else
for (int i = 0; i < memory.size(); ++i) {
byte value = memory.readByte(i);
oneLine.append(ByteUtil.oneByteToHexString(value)).append(" ");
if ((i + 1) % 16 == 0) {
String tmp = format("[%4s]-[%4s]", Integer.toString(i - 15, 16),
Integer.toString(i, 16)).replace(" ", "0");
memoryData.append("").append(tmp).append(" ");
memoryData.append(oneLine);
if (i < memory.size()) memoryData.append("\n");
oneLine.setLength(0);
}
}
if (memoryData.length() > 0) memoryData.insert(0, "\n");
StringBuilder opsString = new StringBuilder();
for (int i = 0; i < ops.length; ++i) {
String tmpString = Integer.toString(ops[i] & 0xFF, 16);
tmpString = tmpString.length() == 1 ? "0" + tmpString : tmpString;
if (i != pc)
opsString.append(tmpString);
else
opsString.append(" >>").append(tmpString).append("");
}
if (pc >= ops.length) opsString.append(" >>");
if (opsString.length() > 0) opsString.insert(0, "\n ");
logger.trace(" -- OPS -- {}", opsString);
logger.trace(" -- STACK -- {}", stackData);
logger.trace(" -- MEMORY -- {}", memoryData);
logger.trace(" -- STORAGE -- {}\n", storageData);
logger.trace("\n Spent Gas: [{}]/[{}]\n Left Gas: [{}]\n",
getResult().getGasUsed(),
invoke.getGas().longValue(),
getGas().longValue());
StringBuilder globalOutput = new StringBuilder("\n");
if (stackData.length() > 0) stackData.append("\n");
if (pc != 0)
globalOutput.append("[Op: ").append(OpCode.code(lastOp).name()).append("]\n");
globalOutput.append(" -- OPS -- ").append(opsString).append("\n");
globalOutput.append(" -- STACK -- ").append(stackData).append("\n");
globalOutput.append(" -- MEMORY -- ").append(memoryData).append("\n");
globalOutput.append(" -- STORAGE -- ").append(storageData).append("\n");
if (getResult().getHReturn() != null)
globalOutput.append("\n HReturn: ").append(
Hex.toHexString(getResult().getHReturn()));
// sophisticated assumption that msg.data != codedata
// means we are calling the contract not creating it
byte[] txData = invoke.getDataCopy(DataWord.ZERO, getDataSize());
if (!Arrays.equals(txData, ops))
globalOutput.append("\n msg.data: ").append(Hex.toHexString(txData));
globalOutput.append("\n\n Spent Gas: ").append(getResult().getGasUsed());
if (listener != null)
listener.output(globalOutput.toString());
}
}
public void saveOpTrace() {
if (this.pc < ops.length) {
trace.addOp(ops[pc], pc, getCallDeep(), getGas(), traceListener.resetActions());
}
}
public ProgramTrace getTrace() {
return trace;
}
public void precompile() {
for (int i = 0; i < ops.length; ++i) {
OpCode op = OpCode.code(ops[i]);
if (op == null) continue;
if (op.equals(OpCode.JUMPDEST)) jumpdest.add(i);
if (op.asInt() >= OpCode.PUSH1.asInt() && op.asInt() <= OpCode.PUSH32.asInt()) {
i += op.asInt() - OpCode.PUSH1.asInt() + 1;
}
}
}
static String formatBinData(byte[] binData, int startPC) {
StringBuilder ret = new StringBuilder();
for (int i = 0; i < binData.length; i += 16) {
ret.append(Utils.align("" + Integer.toHexString(startPC + (i)) + ":", ' ', 8, false));
ret.append(Hex.toHexString(binData, i, min(16, binData.length - i))).append('\n');
}
return ret.toString();
}
public static String stringifyMultiline(byte[] code) {
int index = 0;
StringBuilder sb = new StringBuilder();
BitSet mask = buildReachableBytecodesMask(code);
ByteArrayOutputStream binData = new ByteArrayOutputStream();
int binDataStartPC = -1;
while (index < code.length) {
final byte opCode = code[index];
OpCode op = OpCode.code(opCode);
if (!mask.get(index)) {
if (binDataStartPC == -1) {
binDataStartPC = index;
}
binData.write(code[index]);
index++;
if (index < code.length) continue;
}
if (binDataStartPC != -1) {
sb.append(formatBinData(binData.toByteArray(), binDataStartPC));
binDataStartPC = -1;
binData = new ByteArrayOutputStream();
if (index == code.length) continue;
}
sb.append(Utils.align("" + Integer.toHexString(index) + ":", ' ', 8, false));
if (op == null) {
sb.append("<UNKNOWN>: ").append(0xFF & opCode).append("\n");
index++;
continue;
}
if (op.name().startsWith("PUSH")) {
sb.append(' ').append(op.name()).append(' ');
int nPush = op.val() - OpCode.PUSH1.val() + 1;
byte[] data = Arrays.copyOfRange(code, index + 1, index + nPush + 1);
BigInteger bi = new BigInteger(1, data);
sb.append("0x").append(bi.toString(16));
if (bi.bitLength() <= 32) {
sb.append(" (").append(new BigInteger(1, data).toString()).append(") ");
}
index += nPush + 1;
} else {
sb.append(' ').append(op.name());
index++;
}
sb.append('\n');
}
return sb.toString();
}
static class ByteCodeIterator {
byte[] code;
int pc;
public ByteCodeIterator(byte[] code) {
this.code = code;
}
public void setPC(int pc) {
this.pc = pc;
}
public int getPC() {
return pc;
}
public OpCode getCurOpcode() {
return pc < code.length ? OpCode.code(code[pc]) : null;
}
public boolean isPush() {
return getCurOpcode() != null ? getCurOpcode().name().startsWith("PUSH") : false;
}
public byte[] getCurOpcodeArg() {
if (isPush()) {
int nPush = getCurOpcode().val() - OpCode.PUSH1.val() + 1;
byte[] data = Arrays.copyOfRange(code, pc + 1, pc + nPush + 1);
return data;
} else {
return new byte[0];
}
}
public boolean next() {
pc += 1 + getCurOpcodeArg().length;
return pc < code.length;
}
}
static BitSet buildReachableBytecodesMask(byte[] code) {
NavigableSet<Integer> gotos = new TreeSet<>();
ByteCodeIterator it = new ByteCodeIterator(code);
BitSet ret = new BitSet(code.length);
int lastPush = 0;
int lastPushPC = 0;
do {
ret.set(it.getPC()); // reachable bytecode
if (it.isPush()) {
lastPush = new BigInteger(1, it.getCurOpcodeArg()).intValue();
lastPushPC = it.getPC();
}
if (it.getCurOpcode() == OpCode.JUMP || it.getCurOpcode() == OpCode.JUMPI) {
if (it.getPC() != lastPushPC + 1) {
// some PC arithmetic we totally can't deal with
// assuming all bytecodes are reachable as a fallback
ret.set(0, code.length);
return ret;
}
int jumpPC = lastPush;
if (!ret.get(jumpPC)) {
// code was not explored yet
gotos.add(jumpPC);
}
}
if (it.getCurOpcode() == OpCode.JUMP || it.getCurOpcode() == OpCode.RETURN ||
it.getCurOpcode() == OpCode.STOP) {
if (gotos.isEmpty()) break;
it.setPC(gotos.pollFirst());
}
} while (it.next());
return ret;
}
public static String stringify(byte[] code) {
int index = 0;
StringBuilder sb = new StringBuilder();
BitSet mask = buildReachableBytecodesMask(code);
String binData = "";
while (index < code.length) {
final byte opCode = code[index];
OpCode op = OpCode.code(opCode);
if (op == null) {
sb.append(" <UNKNOWN>: ").append(0xFF & opCode).append(" ");
index++;
continue;
}
if (op.name().startsWith("PUSH")) {
sb.append(' ').append(op.name()).append(' ');
int nPush = op.val() - OpCode.PUSH1.val() + 1;
byte[] data = Arrays.copyOfRange(code, index + 1, index + nPush + 1);
BigInteger bi = new BigInteger(1, data);
sb.append("0x").append(bi.toString(16)).append(" ");
index += nPush + 1;
} else {
sb.append(' ').append(op.name());
index++;
}
}
return sb.toString();
}
public void addListener(ProgramOutListener listener) {
this.listener = listener;
}
public int verifyJumpDest(DataWord nextPC) {
if (nextPC.bytesOccupied() > 4) {
throw Program.Exception.badJumpDestination(-1);
}
int ret = nextPC.intValue();
if (!jumpdest.contains(ret)) {
throw Program.Exception.badJumpDestination(ret);
}
return ret;
}
public void callToPrecompiledAddress(MessageCall msg, PrecompiledContract contract) {
if (getCallDeep() == MAX_DEPTH) {
stackPushZero();
this.refundGas(msg.getGas().longValue(), " call deep limit reach");
return;
}
Repository track = getStorage().startTracking();
byte[] senderAddress = this.getOwnerAddress().getLast20Bytes();
byte[] codeAddress = msg.getCodeAddress().getLast20Bytes();
byte[] contextAddress = msg.getType().isStateless() ? senderAddress : codeAddress;
BigInteger endowment = msg.getEndowment().value();
BigInteger senderBalance = track.getBalance(senderAddress);
if (senderBalance.compareTo(endowment) < 0) {
stackPushZero();
this.refundGas(msg.getGas().longValue(), "refund gas from message call");
return;
}
byte[] data = this.memoryChunk(msg.getInDataOffs().intValue(),
msg.getInDataSize().intValue());
// Charge for endowment - is not reversible by rollback
transfer(track, senderAddress, contextAddress, msg.getEndowment().value());
if (byTestingSuite()) {
// This keeps track of the calls created for a test
this.getResult().addCallCreate(data,
msg.getCodeAddress().getLast20Bytes(),
msg.getGas().getNoLeadZeroesData(),
msg.getEndowment().getNoLeadZeroesData());
stackPushOne();
return;
}
long requiredGas = contract.getGasForData(data);
if (requiredGas > msg.getGas().longValue()) {
this.refundGas(0, "call pre-compiled"); //matches cpp logic
this.stackPushZero();
track.rollback();
} else {
this.refundGas(msg.getGas().longValue() - requiredGas, "call pre-compiled");
byte[] out = contract.execute(data);
this.memorySave(msg.getOutDataOffs().intValue(), out);
this.stackPushOne();
track.commit();
}
}
public boolean byTestingSuite() {
return invoke.byTestingSuite();
}
public interface ProgramOutListener {
void output(String out);
}
/**
* Denotes problem when executing Ethereum bytecode.
* From blockchain and peer perspective this is quite normal situation
* and doesn't mean exceptional situation in terms of the program execution
*/
@SuppressWarnings("serial")
public static class BytecodeExecutionException extends RuntimeException {
public BytecodeExecutionException(String message) {
super(message);
}
}
@SuppressWarnings("serial")
public static class OutOfGasException extends BytecodeExecutionException {
public OutOfGasException(String message, Object... args) {
super(format(message, args));
}
}
@SuppressWarnings("serial")
public static class IllegalOperationException extends BytecodeExecutionException {
public IllegalOperationException(String message, Object... args) {
super(format(message, args));
}
}
@SuppressWarnings("serial")
public static class BadJumpDestinationException extends BytecodeExecutionException {
public BadJumpDestinationException(String message, Object... args) {
super(format(message, args));
}
}
@SuppressWarnings("serial")
public static class StackTooSmallException extends BytecodeExecutionException {
public StackTooSmallException(String message, Object... args) {
super(format(message, args));
}
}
public static class Exception {
public static OutOfGasException notEnoughOpGas(OpCode op, long opGas, long programGas) {
return new OutOfGasException("Not enough gas for '%s' operation executing: opGas[%d], programGas[%d];", op, opGas, programGas);
}
public static OutOfGasException notEnoughOpGas(OpCode op, DataWord opGas, DataWord programGas) {
return notEnoughOpGas(op, opGas.longValue(), programGas.longValue());
}
public static OutOfGasException notEnoughOpGas(OpCode op, BigInteger opGas, BigInteger programGas) {
return notEnoughOpGas(op, opGas.longValue(), programGas.longValue());
}
public static OutOfGasException notEnoughSpendingGas(String cause, long gasValue, Program program) {
return new OutOfGasException("Not enough gas for '%s' cause spending: invokeGas[%d], gas[%d], usedGas[%d];",
cause, program.invoke.getGas().longValue(), gasValue, program.getResult().getGasUsed());
}
public static OutOfGasException gasOverflow(BigInteger actualGas, BigInteger gasLimit) {
return new OutOfGasException("Gas value overflow: actualGas[%d], gasLimit[%d];", actualGas.longValue(), gasLimit.longValue());
}
public static IllegalOperationException invalidOpCode(byte... opCode) {
return new IllegalOperationException("Invalid operation code: opCode[%s];", Hex.toHexString(opCode, 0, 1));
}
public static BadJumpDestinationException badJumpDestination(int pc) {
return new BadJumpDestinationException("Operation with pc isn't 'JUMPDEST': PC[%d];", pc);
}
public static StackTooSmallException tooSmallStack(int expectedSize, int actualSize) {
return new StackTooSmallException("Expected stack size %d but actual %d;", expectedSize, actualSize);
}
}
@SuppressWarnings("serial")
public class StackTooLargeException extends BytecodeExecutionException {
public StackTooLargeException(String message) {
super(message);
}
}
/**
* used mostly for testing reasons
*/
public byte[] getMemory() {
return memory.read(0, memory.size());
}
/**
* used mostly for testing reasons
*/
public void initMem(byte[] data) {
this.memory.write(0, data, data.length, false);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.