answer
stringlengths
17
10.2M
package dr.evomodel.antigenic; import dr.evolution.util.*; import dr.inference.model.*; import dr.math.MathUtils; import dr.math.distributions.NormalDistribution; import dr.util.*; import dr.xml.*; import java.io.*; import java.util.*; import java.util.logging.Logger; /** * @author Andrew Rambaut * @author Trevor Bedford * @author Marc Suchard * @version $Id$ */ public class AntigenicLikelihood extends AbstractModelLikelihood implements Citable { public final static String ANTIGENIC_LIKELIHOOD = "antigenicLikelihood"; // column indices in table private static final int COLUMN_LABEL = 0; private static final int SERUM_STRAIN = 2; private static final int ROW_LABEL = 1; private static final int VIRUS_STRAIN = 3; private static final int SERUM_DATE = 4; private static final int VIRUS_DATE = 5; private static final int RAW_TITRE = 6; private static final int MIN_TITRE = 7; private static final int MAX_TITRE = 8; public enum MeasurementType { INTERVAL, POINT, UPPER_BOUND, LOWER_BOUND, MISSING } public AntigenicLikelihood( int mdsDimension, Parameter mdsPrecisionParameter, TaxonList strainTaxa, MatrixParameter locationsParameter, Parameter datesParameter, Parameter columnParameter, Parameter rowParameter, DataTable<String[]> dataTable, List<String> virusLocationStatisticList) { super(ANTIGENIC_LIKELIHOOD); List<String> strainNames = new ArrayList<String>(); Map<String, Double> strainDateMap = new HashMap<String, Double>(); for (int i = 0; i < dataTable.getRowCount(); i++) { String[] values = dataTable.getRow(i); int column = columnLabels.indexOf(values[COLUMN_LABEL]); if (column == -1) { columnLabels.add(values[0]); column = columnLabels.size() - 1; } int columnStrain = -1; if (strainTaxa != null) { columnStrain = strainTaxa.getTaxonIndex(values[SERUM_STRAIN]); } else { columnStrain = strainNames.indexOf(values[SERUM_STRAIN]); if (columnStrain == -1) { strainNames.add(values[SERUM_STRAIN]); Double date = Double.parseDouble(values[VIRUS_DATE]); strainDateMap.put(values[VIRUS_STRAIN], date); columnStrain = strainNames.size() - 1; } } if (columnStrain == -1) { throw new IllegalArgumentException("Error reading data table: Unrecognized serum strain name, " + values[SERUM_STRAIN] + ", in row " + (i+1)); } int row = rowLabels.indexOf(values[ROW_LABEL]); if (row == -1) { rowLabels.add(values[ROW_LABEL]); row = rowLabels.size() - 1; } int rowStrain = -1; if (strainTaxa != null) { rowStrain = strainTaxa.getTaxonIndex(values[VIRUS_STRAIN]); } else { rowStrain = strainNames.indexOf(values[VIRUS_STRAIN]); if (rowStrain == -1) { strainNames.add(values[VIRUS_STRAIN]); Double date = Double.parseDouble(values[VIRUS_DATE]); strainDateMap.put(values[VIRUS_STRAIN], date); rowStrain = strainNames.size() - 1; } } if (rowStrain == -1) { throw new IllegalArgumentException("Error reading data table: Unrecognized virus strain name, " + values[VIRUS_STRAIN] + ", in row " + (i+1)); } double minTitre = Double.NaN; if (values[MIN_TITRE].length() > 0) { try { minTitre = Double.parseDouble(values[MIN_TITRE]); } catch (NumberFormatException nfe) { // do nothing } } double maxTitre = Double.NaN; if (values[MAX_TITRE].length() > 0) { try { maxTitre = Double.parseDouble(values[MAX_TITRE]); } catch (NumberFormatException nfe) { // do nothing } } MeasurementType type = MeasurementType.INTERVAL; if (minTitre == maxTitre) { type = MeasurementType.POINT; } if (Double.isNaN(minTitre) || minTitre == 0.0) { if (Double.isNaN(maxTitre)) { throw new IllegalArgumentException("Error in measurement: both min and max titre are at bounds in row " + (i+1)); } type = MeasurementType.UPPER_BOUND; } else if (Double.isNaN(maxTitre)) { type = MeasurementType.LOWER_BOUND; } Measurement measurement = new Measurement(column, columnStrain, row, rowStrain, type, minTitre, maxTitre); measurements.add(measurement); } double[] maxColumnTitre = new double[columnLabels.size()]; double[] maxRowTitre = new double[rowLabels.size()]; for (Measurement measurement : measurements) { double titre = measurement.maxTitre; if (Double.isNaN(titre)) { titre = measurement.minTitre; } if (titre > maxColumnTitre[measurement.column]) { maxColumnTitre[measurement.column] = titre; } if (titre > maxRowTitre[measurement.row]) { maxRowTitre[measurement.row] = titre; } } if (strainTaxa != null) { this.strains = strainTaxa; // fill in the strain name array for local use for (int i = 0; i < strains.getTaxonCount(); i++) { strainNames.add(strains.getTaxon(i).getId()); } } else { Taxa taxa = new Taxa(); for (String strain : strainNames) { taxa.addTaxon(new Taxon(strain)); } this.strains = taxa; } this.mdsDimension = mdsDimension; this.mdsPrecisionParameter = mdsPrecisionParameter; addVariable(mdsPrecisionParameter); this.locationsParameter = locationsParameter; setupLocationsParameter(this.locationsParameter, strainNames); addVariable(this.locationsParameter); if (datesParameter != null) { // this parameter is not used in this class but is setup to be used in other classes datesParameter.setDimension(strainNames.size()); ((Parameter.Abstract)datesParameter).setDimensionNames((String[])strainNames.toArray()); for (int i = 0; i < strainNames.size(); i++) { double date = strainDateMap.get(strainNames.get(i)); datesParameter.setParameterValue(i, date); } } if (columnParameter == null) { this.columnEffectsParameter = new Parameter.Default("columnEffects"); } else { this.columnEffectsParameter = columnParameter; } this.columnEffectsParameter.setDimension(columnLabels.size()); addVariable(this.columnEffectsParameter); String[] labelArray = new String[columnLabels.size()]; columnLabels.toArray(labelArray); ((Parameter.Abstract)this.columnEffectsParameter).setDimensionNames(labelArray); for (int i = 0; i < maxColumnTitre.length; i++) { this.columnEffectsParameter.setParameterValueQuietly(i, maxColumnTitre[i]); } if (rowParameter == null) { this.rowEffectsParameter = new Parameter.Default("rowEffects"); } else { this.rowEffectsParameter = rowParameter; } this.rowEffectsParameter.setDimension(rowLabels.size()); addVariable(this.rowEffectsParameter); labelArray = new String[rowLabels.size()]; rowLabels.toArray(labelArray); ((Parameter.Abstract)this.rowEffectsParameter).setDimensionNames(labelArray); for (int i = 0; i < maxRowTitre.length; i++) { this.rowEffectsParameter.setParameterValueQuietly(i, maxRowTitre[i]); } StringBuilder sb = new StringBuilder(); sb.append("\tAntigenicLikelihood:\n"); sb.append("\t\t" + this.strains.getTaxonCount() + " strains\n"); sb.append("\t\t" + columnLabels.size() + " unique columns\n"); sb.append("\t\t" + rowLabels.size() + " unique rows\n"); sb.append("\t\t" + measurements.size() + " assay measurements\n"); Logger.getLogger("dr.evomodel").info(sb.toString()); // some random initial locations for (int i = 0; i < locationsParameter.getParameterCount(); i++) { for (int j = 0; j < mdsDimension; j++) { // double r = MathUtils.nextGaussian(); double r = 0.0; if (j == 0) { r = (double) i * 0.05; } else { r = MathUtils.nextGaussian(); } locationsParameter.getParameter(i).setParameterValueQuietly(j, r); } } locationChanged = new boolean[this.locationsParameter.getRowDimension()]; logLikelihoods = new double[measurements.size()]; storedLogLikelihoods = new double[measurements.size()]; makeDirty(); } protected void setupLocationsParameter(MatrixParameter locationsParameter, List<String> strains) { locationsParameter.setColumnDimension(mdsDimension); locationsParameter.setRowDimension(strains.size()); for (int i = 0; i < strains.size(); i++) { locationsParameter.getParameter(i).setId(strains.get(i)); } } @Override protected void handleModelChangedEvent(Model model, Object object, int index) { } @Override protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) { if (variable == locationsParameter) { locationChanged[index / mdsDimension] = true; } else if (variable == mdsPrecisionParameter) { setLocationChangedFlags(true); } else if (variable == columnEffectsParameter) { setLocationChangedFlags(true); } else if (variable == rowEffectsParameter) { setLocationChangedFlags(true); } else { // could be a derived class's parameter } likelihoodKnown = false; } @Override protected void storeState() { System.arraycopy(logLikelihoods, 0, storedLogLikelihoods, 0, logLikelihoods.length); } @Override protected void restoreState() { double[] tmp = logLikelihoods; logLikelihoods = storedLogLikelihoods; storedLogLikelihoods = tmp; likelihoodKnown = false; } @Override protected void acceptState() { } @Override public Model getModel() { return this; } @Override public double getLogLikelihood() { if (!likelihoodKnown) { logLikelihood = computeLogLikelihood(); } return logLikelihood; } // This function can be overwritten to implement other sampling densities, i.e. discrete ranks private double computeLogLikelihood() { double precision = mdsPrecisionParameter.getParameterValue(0); double sd = 1.0 / Math.sqrt(precision); logLikelihood = 0.0; int i = 0; for (Measurement measurement : measurements) { if (locationChanged[measurement.rowStrain] || locationChanged[measurement.columnStrain]) { double distance = computeDistance(measurement.rowStrain, measurement.columnStrain); double logNormalization = calculateTruncationNormalization(distance, sd); switch (measurement.type) { case INTERVAL: { double minTitre = transformTitre(measurement.minTitre, measurement.column, measurement.row, distance, sd); double maxTitre = transformTitre(measurement.maxTitre, measurement.column, measurement.row, distance, sd); logLikelihoods[i] = computeMeasurementIntervalLikelihood(minTitre, maxTitre) - logNormalization; } break; case POINT: { double titre = transformTitre(measurement.minTitre, measurement.column, measurement.row, distance, sd); logLikelihoods[i] = computeMeasurementLikelihood(titre) - logNormalization; } break; case LOWER_BOUND: { double minTitre = transformTitre(measurement.minTitre, measurement.column, measurement.row, distance, sd); logLikelihoods[i] = computeMeasurementLowerBoundLikelihood(minTitre) - logNormalization; } break; case UPPER_BOUND: { double maxTitre = transformTitre(measurement.maxTitre, measurement.column, measurement.row, distance, sd); logLikelihoods[i] = computeMeasurementUpperBoundLikelihood(maxTitre) - logNormalization; } break; case MISSING: break; } } logLikelihood += logLikelihoods[i]; i++; } likelihoodKnown = true; setLocationChangedFlags(false); return logLikelihood; } private void setLocationChangedFlags(boolean flag) { for (int i = 0; i < locationChanged.length; i++) { locationChanged[i] = flag; } } protected double computeDistance(int rowStrain, int columnStrain) { if (rowStrain == columnStrain) { return 0.0; } Parameter X = locationsParameter.getParameter(rowStrain); Parameter Y = locationsParameter.getParameter(columnStrain); double sum = 0.0; for (int i = 0; i < mdsDimension; i++) { double difference = X.getParameterValue(i) - Y.getParameterValue(i); sum += difference * difference; } return Math.sqrt(sum); } /** * Transforms a titre into log2 space and normalizes it with respect to a unit normal * @param titre * @param column * @param row * @param mean * @param sd * @return */ private double transformTitre(double titre, int column, int row, double mean, double sd) { double rowEffect = rowEffectsParameter.getParameterValue(row); double columnEffect = columnEffectsParameter.getParameterValue(column); double t = ((rowEffect + columnEffect) * 0.5) - titre; return (t - mean) / sd; } private double computeMeasurementIntervalLikelihood(double minTitre, double maxTitre) { double cdf1 = NormalDistribution.standardCDF(minTitre, false); double cdf2 = NormalDistribution.standardCDF(maxTitre, false); double lnL = Math.log(cdf1 - cdf2); if (cdf1 == cdf2) { lnL = Math.log(cdf1); } if (Double.isNaN(lnL) || Double.isInfinite(lnL)) { throw new RuntimeException("infinite"); } return lnL; } private double computeMeasurementLikelihood(double titre) { double lnL = Math.log(NormalDistribution.pdf(titre, 0.0, 1.0)); if (Double.isNaN(lnL) || Double.isInfinite(lnL)) { throw new RuntimeException("infinite"); } return lnL; } private double computeMeasurementLowerBoundLikelihood(double transformedMinTitre) { // a lower bound in non-transformed titre so the bottom tail of the distribution double cdf = NormalDistribution.standardTail(transformedMinTitre, true); double lnL = Math.log(cdf); if (Double.isNaN(lnL) || Double.isInfinite(lnL)) { throw new RuntimeException("infinite"); } return lnL; } private double computeMeasurementUpperBoundLikelihood(double transformedMaxTitre) { // a upper bound in non-transformed titre so the upper tail of the distribution // using special tail function of NormalDistribution (see main() in NormalDistribution for test) double tail = NormalDistribution.standardTail(transformedMaxTitre, false); double lnL = Math.log(tail); if (Double.isNaN(lnL) || Double.isInfinite(lnL)) { throw new RuntimeException("infinite"); } return lnL; } private double calculateTruncationNormalization(double distance, double sd) { return NormalDistribution.cdf(distance, 0.0, sd, true); } @Override public void makeDirty() { likelihoodKnown = false; setLocationChangedFlags(true); } private class Measurement { private Measurement(final int column, final int columnStrain, final int row, final int rowStrain, final MeasurementType type, final double minTitre, final double maxTitre) { this.column = column; this.columnStrain = columnStrain; this.row = row; this.rowStrain = rowStrain; this.type = type; this.minTitre = Math.log(minTitre) / Math.log(2); this.maxTitre = Math.log(maxTitre) / Math.log(2); } final int column; final int row; final int columnStrain; final int rowStrain; final MeasurementType type; final double minTitre; final double maxTitre; }; private final List<Measurement> measurements = new ArrayList<Measurement>(); private final List<String> columnLabels = new ArrayList<String>(); private final List<String> rowLabels = new ArrayList<String>(); private final int mdsDimension; private final Parameter mdsPrecisionParameter; private final MatrixParameter locationsParameter; private final TaxonList strains; // private final CompoundParameter tipTraitParameter; private final Parameter columnEffectsParameter; private final Parameter rowEffectsParameter; private double logLikelihood = 0.0; private boolean likelihoodKnown = false; private final boolean[] locationChanged; private double[] logLikelihoods; private double[] storedLogLikelihoods; // XMLObjectParser public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public final static String FILE_NAME = "fileName"; public final static String TIP_TRAIT = "tipTrait"; public final static String LOCATIONS = "locations"; public final static String DATES = "dates"; public static final String MDS_DIMENSION = "mdsDimension"; public static final String MDS_PRECISION = "mdsPrecision"; public static final String COLUMN_EFFECTS = "columnEffects"; public static final String ROW_EFFECTS = "rowEffects"; public static final String STRAINS = "strains"; public String getParserName() { return ANTIGENIC_LIKELIHOOD; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { String fileName = xo.getStringAttribute(FILE_NAME); DataTable<String[]> assayTable; try { assayTable = DataTable.Text.parse(new FileReader(fileName), true, false); } catch (IOException e) { throw new XMLParseException("Unable to read assay data from file: " + e.getMessage()); } int mdsDimension = xo.getIntegerAttribute(MDS_DIMENSION); // CompoundParameter tipTraitParameter = null; // if (xo.hasChildNamed(TIP_TRAIT)) { // tipTraitParameter = (CompoundParameter) xo.getElementFirstChild(TIP_TRAIT); TaxonList strains = null; if (xo.hasChildNamed(STRAINS)) { strains = (TaxonList) xo.getElementFirstChild(STRAINS); } MatrixParameter locationsParameter = (MatrixParameter) xo.getElementFirstChild(LOCATIONS); Parameter datesParameter = null; if (xo.hasChildNamed(STRAINS)) { datesParameter = (Parameter) xo.getElementFirstChild(DATES); } Parameter mdsPrecision = (Parameter) xo.getElementFirstChild(MDS_PRECISION); Parameter columnEffectsParameter = (Parameter) xo.getElementFirstChild(COLUMN_EFFECTS); Parameter rowEffectsParameter = (Parameter) xo.getElementFirstChild(ROW_EFFECTS); AntigenicLikelihood AGL = new AntigenicLikelihood( mdsDimension, mdsPrecision, strains, locationsParameter, datesParameter, columnEffectsParameter, rowEffectsParameter, assayTable, null); Logger.getLogger("dr.evomodel").info("Using EvolutionaryCartography model. Please cite:\n" + Utils.getCitationString(AGL)); return AGL; }
package dr.evomodel.treelikelihood; import dr.evolution.alignment.PatternList; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.util.TaxonList; import dr.evolution.datatype.DataType; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.branchratemodel.DefaultBranchRateModel; import dr.evomodel.sitemodel.SiteModel; import dr.evomodel.substmodel.FrequencyModel; import dr.evomodel.tree.TreeModel; import dr.inference.model.Likelihood; import dr.inference.model.Model; import dr.xml.*; import java.util.logging.Logger; /** * TreeLikelihoodModel - implements a Likelihood Function for sequences on a tree. * * @author Andrew Rambaut * @author Alexei Drummond * * @version $Id: TreeLikelihood.java,v 1.31 2006/08/30 16:02:42 rambaut Exp $ */ public class TreeLikelihood extends AbstractTreeLikelihood { public static final String TREE_LIKELIHOOD = "treeLikelihood"; public static final String USE_AMBIGUITIES = "useAmbiguities"; public static final String STORE_PARTIALS = "storePartials"; public static final String USE_SCALING = "useScaling"; /** * Constructor. */ public TreeLikelihood( PatternList patternList, TreeModel treeModel, SiteModel siteModel, BranchRateModel branchRateModel, TipPartialsModel tipPartialsModel, boolean useAmbiguities, boolean storePartials, boolean useScaling) { super(TREE_LIKELIHOOD, patternList, treeModel); this.storePartials = storePartials; try { this.siteModel = siteModel; addModel(siteModel); this.frequencyModel = siteModel.getFrequencyModel(); addModel(frequencyModel); this.tipPartialsModel = tipPartialsModel; integrateAcrossCategories = siteModel.integrateAcrossCategories(); this.categoryCount = siteModel.getCategoryCount(); final Logger logger = Logger.getLogger("dr.evomodel"); String coreName = "Java general"; if (integrateAcrossCategories) { final DataType dataType = patternList.getDataType(); if (dataType instanceof dr.evolution.datatype.Nucleotides) { if (NativeNucleotideLikelihoodCore.isAvailable()) { coreName = "native nucleotide"; likelihoodCore = new NativeNucleotideLikelihoodCore(); } else { coreName = "Java nucleotide"; likelihoodCore = new NucleotideLikelihoodCore(); } } else if (dataType instanceof dr.evolution.datatype.AminoAcids) { coreName = "Java amino acid"; likelihoodCore = new AminoAcidLikelihoodCore(); } else if (dataType instanceof dr.evolution.datatype.Codons) { coreName = "Java codon"; likelihoodCore = new CodonLikelihoodCore(patternList.getStateCount()); useAmbiguities = true; } else { likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); } } else { likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); } logger.info("TreeLikelihood using" + coreName + " likelihood core"); logger.info( " " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood."); logger.info(" Partial likelihood scaling " + (useScaling ? "on." : "off.")); if (branchRateModel != null) { this.branchRateModel = branchRateModel; logger.info("Branch rate model used: " + branchRateModel.getModelName()); } else { this.branchRateModel = new DefaultBranchRateModel(); } addModel(this.branchRateModel); probabilities = new double[stateCount * stateCount]; likelihoodCore.initialize(nodeCount, patternCount, categoryCount, integrateAcrossCategories, useScaling); int extNodeCount = treeModel.getExternalNodeCount(); int intNodeCount = treeModel.getInternalNodeCount(); if (tipPartialsModel != null) { for (int i = 0; i < extNodeCount; i++) { // Find the id of tip i in the patternList String id = treeModel.getTaxonId(i); int index = patternList.getTaxonIndex(id); if (index == -1) { throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() + ", is not found in patternList, " + patternList.getId()); } tipPartialsModel.setStates(patternList, index, i); } addModel(tipPartialsModel); updateTipPartials(); useAmbiguities = true; } else { for (int i = 0; i < extNodeCount; i++) { // Find the id of tip i in the patternList String id = treeModel.getTaxonId(i); int index = patternList.getTaxonIndex(id); if (index == -1) { throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() + ", is not found in patternList, " + patternList.getId()); } if (useAmbiguities) { setPartials(likelihoodCore, patternList, categoryCount, index, i); } else { setStates(likelihoodCore, patternList, index, i); } } } for (int i = 0; i < intNodeCount; i++) { likelihoodCore.createNodePartials(extNodeCount + i); } } catch (TaxonList.MissingTaxonException mte) { throw new RuntimeException(mte.toString()); } } // ModelListener IMPLEMENTATION /** * Handles model changed events from the submodels. */ protected void handleModelChangedEvent(Model model, Object object, int index) { if (model == treeModel) { if (object instanceof TreeModel.TreeChangedEvent) { if (((TreeModel.TreeChangedEvent)object).isNodeChanged()) { // If a node event occurs the node and its two child nodes // are flagged for updating (this will result in everything // above being updated as well. Node events occur when a node // is added to a branch, removed from a branch or its height or // rate changes. updateNodeAndChildren(((TreeModel.TreeChangedEvent)object).getNode()); } else if (((TreeModel.TreeChangedEvent)object).isTreeChanged()) { // Full tree events result in a complete updating of the tree likelihood // Currently this event type is not used. System.err.println("Full tree update event - these events currently aren't used\n" + "so either this is in error or a new feature is using them so remove this message."); updateAllNodes(); } else { // Other event types are ignored (probably trait changes). //System.err.println("Another tree event has occured (possibly a trait change)."); } } } else if (model == branchRateModel) { if (index == -1) { updateAllNodes(); } else { updateNode(treeModel.getNode(index)); } } else if (model == frequencyModel) { updateAllNodes(); } else if (model == tipPartialsModel) { updateTipPartials(); } else if (model instanceof SiteModel) { updateAllNodes(); } else { throw new RuntimeException("Unknown componentChangedEvent"); } super.handleModelChangedEvent(model, object, index); } private void updateTipPartials() { int extNodeCount = treeModel.getExternalNodeCount(); for (int index = 0; index < extNodeCount; index++) { double[] partials = tipPartialsModel.getTipPartials(index); likelihoodCore.setNodePartials(index, partials); } updateAllNodes(); } // Model IMPLEMENTATION /** * Stores the additional state other than model components */ protected void storeState() { if (storePartials) { likelihoodCore.storeState(); } super.storeState(); } /** * Restore the additional stored state */ protected void restoreState() { if (storePartials) { likelihoodCore.restoreState(); } else { updateAllNodes(); } super.restoreState(); } // Likelihood IMPLEMENTATION /** * Calculate the log likelihood of the current state. * @return the log likelihood. */ protected double calculateLogLikelihood() { if (patternLogLikelihoods == null) { patternLogLikelihoods = new double[patternCount]; } if (!integrateAcrossCategories) { if (siteCategories == null) { siteCategories = new int[patternCount]; } for (int i = 0; i < patternCount; i++) { siteCategories[i] = siteModel.getCategoryOfSite(i); } } final NodeRef root = treeModel.getRoot(); traverse(treeModel, root); /** * Traverse the tree calculating partial likelihoods. * @return whether the partials for this node were recalculated. */ private boolean traverse(Tree tree, NodeRef node) { boolean update = false; int nodeNum = node.getNumber(); NodeRef parent = tree.getParent(node); // First update the transition probability matrix(ices) for this branch if (parent != null && updateNode[nodeNum]) { final double branchRate = branchRateModel.getBranchRate(tree, node); // Get the operational time of the branch final double branchTime = branchRate * ( tree.getNodeHeight(parent) - tree.getNodeHeight(node) ); if (branchTime < 0.0) { throw new RuntimeException("Negative branch length: " + branchTime); } likelihoodCore.setNodeMatrixForUpdate(nodeNum); for (int i = 0; i < categoryCount; i++) { siteModel.getTransitionProbabilitiesForCategory(i, branchTime, probabilities); likelihoodCore.setNodeMatrix(nodeNum, i, probabilities); } update = true; } // If the node is internal, update the partial likelihoods. if (!tree.isExternal(node)) { // int nodeCount = tree.getChildCount(node); // if (nodeCount != 2) // throw new RuntimeException("binary trees only!"); // Traverse down the two child nodes NodeRef child1 = tree.getChild(node, 0); final boolean update1 = traverse(tree, child1); NodeRef child2 = tree.getChild(node, 1); final boolean update2 = traverse(tree, child2); // If either child node was updated then update this node too if (update1 || update2) { final int childNum1 = child1.getNumber(); final int childNum2 = child2.getNumber(); likelihoodCore.setNodePartialsForUpdate(nodeNum); if (integrateAcrossCategories) { likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum); } else { likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum, siteCategories); } if (parent == null) { // No parent this is the root of the tree - // calculate the pattern likelihoods double[] frequencies = frequencyModel.getFrequencies(); double[] partials = getRootPartials(); likelihoodCore.calculateLogLikelihoods(partials, frequencies, patternLogLikelihoods); } update = true; } } return update; } public final double[] getRootPartials() { if (rootPartials == null) { rootPartials = new double[patternCount * stateCount]; } int nodeNum = treeModel.getRoot().getNumber(); if (integrateAcrossCategories) { // moved this call to here, because non-integrating siteModels don't need to support it - AD double[] proportions = siteModel.getCategoryProportions(); likelihoodCore.integratePartials(nodeNum, proportions, rootPartials); } else { likelihoodCore.getPartials(nodeNum, rootPartials); } return rootPartials; } /** the root partial likelihoods (a temporary array that is used * to fetch the partials - it should not be examined directly - * use getRootPartials() instead). */ private double[] rootPartials = null; /** * The XML parser */ public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return TREE_LIKELIHOOD; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { boolean useAmbiguities = false; boolean storePartials = true; boolean useScaling = false; if (xo.hasAttribute(USE_AMBIGUITIES)) { useAmbiguities = xo.getBooleanAttribute(USE_AMBIGUITIES); } if (xo.hasAttribute(STORE_PARTIALS)) { storePartials = xo.getBooleanAttribute(STORE_PARTIALS); } if (xo.hasAttribute(USE_SCALING)) { useScaling = xo.getBooleanAttribute(USE_SCALING); } PatternList patternList = (PatternList)xo.getChild(PatternList.class); TreeModel treeModel = (TreeModel)xo.getChild(TreeModel.class); SiteModel siteModel = (SiteModel)xo.getChild(SiteModel.class); BranchRateModel branchRateModel = (BranchRateModel)xo.getChild(BranchRateModel.class); TipPartialsModel tipPartialsModel = (TipPartialsModel)xo.getChild(TipPartialsModel.class); return new TreeLikelihood(patternList, treeModel, siteModel, branchRateModel, tipPartialsModel, useAmbiguities, storePartials, useScaling); } /** the frequency model for these sites */ /** the site model for these sites */ /** the branch rate model */ /** the tip partials model */ /** the categories for each site */ /** the pattern likelihoods */ /** the number of rate categories */ /** an array used to store transition probabilities */ /** the LikelihoodCore */
package edu.grinnell.callaway; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class ParseExceptionsTest { JSONParser parser = new JSONParser(); @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void noJasonTest1() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("\nJSON ERROR: no json values found in input"); parser.parseFromSource(""); } @Test public void noJasonTest2() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("\nJSON ERROR: no json values found in input"); parser.parseFromSource(" \t \n \r \b \f "); } @Test public void invalidCharTest1() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("\nJSON ERROR(L1:C0): Invalid input character a\na\n^"); parser.parseFromSource("a"); } @Test public void invalidCharTest2() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("\nJSON ERROR(L1:C0): Invalid input character @\n@\n^"); parser.parseFromSource("@"); } @Test public void invalidCharTest3() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("\nJSON ERROR(L1:C0): Invalid input character }\n}\n^"); parser.parseFromSource("}"); } @Test public void numberTest1() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("\nJSON NUMBER ERROR(L1:C0): invalid number 15-\n15-\n^"); parser.parseFromSource("15-"); } @Test public void numberTest2() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("\nJSON NUMBER ERROR(L1:C0): invalid number 13+\n13+\n^"); parser.parseFromSource("13+"); } @Test public void booleanTrueTest() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("\nJSON BOOLEAN ERROR(L1:C4): expected input \"true\"\ntruqqqqqq\n ^"); parser.parseFromSource("truqqqqqq"); } @Test public void booleanFalseTest() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("\nJSON BOOLEAN ERROR(L1:C3): expected input \"false\"\nfake\n ^"); parser.parseFromSource("fake"); } @Test public void nullTest() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("\nJSON NULL ERROR(L1:C3): expected input \"null\"\nnunya\n ^"); parser.parseFromSource("nunya"); } @Test public void stringTest1() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("\nJSON STRING ERROR(L1:C8): no closing \" before end of input\n\"string\\\n ^"); parser.parseFromSource("\"string\\"); } }
package edu.iu.grid.oim.view; import java.io.IOException; import java.io.PrintWriter; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import javax.security.auth.x500.X500Principal; import org.apache.commons.lang.StringEscapeUtils; import org.bouncycastle.cms.CMSException; import edu.iu.grid.oim.lib.Authorization; import edu.iu.grid.oim.lib.StaticConfig; import edu.iu.grid.oim.model.UserContext; import edu.iu.grid.oim.model.cert.CertificateManager; import edu.iu.grid.oim.model.db.CertificateRequestHostModel; import edu.iu.grid.oim.model.db.CertificateRequestUserModel; import edu.iu.grid.oim.model.db.VOModel; import edu.iu.grid.oim.model.db.record.CertificateRequestHostRecord; import edu.iu.grid.oim.model.db.record.CertificateRequestUserRecord; import edu.iu.grid.oim.model.db.record.ContactRecord; import edu.iu.grid.oim.model.db.record.VORecord; import edu.iu.grid.oim.model.exceptions.CertificateRequestException; public class HostCertificateTable implements IView { ArrayList<CertificateRequestHostRecord> recs; UserContext context; boolean search_result; public HostCertificateTable(UserContext context, ArrayList<CertificateRequestHostRecord> recs, boolean search_result) { this.context = context; this.recs = recs; this.search_result = search_result; } public void render(PrintWriter out) { out.write("<table class=\"table table-hover certificate\">"); out.write("<thead><tr><th width=\"40px\">ID</th><th width=\"100px\">Status</th><th width=\"120px\">Request Date</th><th width=\"250px\">FQDNs</th><th>VO</th><th>Grid Admins</th><th>Signer</th></tr></thead>"); out.write("<tbody>"); CertificateRequestHostModel model = new CertificateRequestHostModel(context); final Authorization auth = context.getAuthorization(); final SimpleDateFormat dformat = new SimpleDateFormat("MM/dd/yyyy"); dformat.setTimeZone(auth.getTimeZone()); VOModel vomodel = new VOModel(context); for(CertificateRequestHostRecord rec : recs) { String url = "certificatehost?id="+rec.id; if(search_result) { url += "&search"; } out.write("<tr onclick=\"document.location='"+url+"';\">"); out.write("<td>"+rec.id+"</td>"); out.write("<td>"+rec.status+"</td>"); //out.write("<td><a target=\"_blank\" href=\""+StaticConfig.conf.getProperty("url.gocticket")+"/"+rec.goc_ticket_id+"\">"+rec.goc_ticket_id+"</a></td>"); out.write("<td>"+dformat.format(rec.request_time)+"</td>"); //fqdns String[] cns = rec.getCNs(); int idx = 0; out.write("<td><ul>"); for(String cn : cns) { out.write("<li>"+cn+"</li>"); idx++; if(idx > 5) { out.write("<li>... <span class=\"badge badge-info\">Total "+cns.length+"</span></li>"); break; } } out.write("</ul></td>"); //voname String voname = "<span class=\"muted\">N/A</span>"; if(rec.approver_vo_id != null) { try { VORecord vorec = vomodel.get(rec.approver_vo_id); if(vorec != null) { voname = vorec.name; } } catch (SQLException e) { System.out.println("Failed to find voname for request id:"+rec.id); } } out.write("<td>"+voname+"</td>"); try { ArrayList<ContactRecord> gas = model.findGridAdmin(rec); out.write("<td>"); boolean first = true; for(ContactRecord ga : gas) { if(first) { first = false; } else { out.write(" | "); } out.write(StringEscapeUtils.escapeHtml(ga.name)); } out.write("</td>"); } catch (CertificateRequestException ce) { out.write("<td><span class=\"label label-important\">No GridAdmin</span></td>"); } String issuer_dn = ""; //by default ArrayList<Certificate> chain = null; try { if (rec.getPKCS7s()[0] != null) { chain = CertificateManager.parsePKCS7(rec.getPKCS7s()[0]); X509Certificate c0 = CertificateManager.getIssuedX509Cert(chain); X500Principal issuer = c0.getIssuerX500Principal(); issuer_dn = CertificateManager.X500Principal_to_ApacheDN(issuer); } } catch (CertificateException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (CMSException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (IOException e2) { // TODO Auto-generated catch block //e2.printStackTrace(); -this will error for cilogon } if(issuer_dn.contains("DigiCert")) { out.write("<td>Digicert</td>"); } else if (issuer_dn.contains("CILogon")){ out.write("<td>CILogon</td>"); } else { out.write("<td>Not Issued</td>"); } out.write("</tr>"); } out.write("</tbody>"); out.write("</table>"); } }
package org.mozartoz.truffle.nodes.builtins; import static org.mozartoz.truffle.nodes.builtins.Builtin.ALL; import java.io.File; import org.mozartoz.truffle.nodes.OzNode; import org.mozartoz.truffle.nodes.builtins.VirtualStringBuiltins.ToAtomNode; import org.mozartoz.truffle.nodes.builtins.VirtualStringBuiltinsFactory.ToAtomNodeFactory; import org.mozartoz.truffle.runtime.OzVar; import org.mozartoz.truffle.translator.Loader; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.NodeChildren; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.source.Source; public abstract class OSBuiltins { @Builtin(deref = ALL) @GenerateNodeFactory @NodeChild("url") public static abstract class BootURLLoadNode extends OzNode { @Child ToAtomNode toAtomNode = ToAtomNodeFactory.create(null); @Specialization Object bootURLLoad(Object urlVS) { String url = toAtomNode.executeToAtom(urlVS); assert url.startsWith("x-oz://system/"); assert url.endsWith(".ozf"); String name = url.substring("x-oz://system/".length(), url.length() - 1); String path = null; for (String systemFunctor : Loader.SYSTEM_FUNCTORS) { if (new File(systemFunctor).getName().equals(name)) { path = systemFunctor; } } System.out.println("Reading " + path); assert new File(path).exists(); Source source = Loader.createSource(path); Loader loader = Loader.getInstance(); return loader.execute(loader.parseFunctor(source)); } } @GenerateNodeFactory public static abstract class RandNode extends OzNode { @Specialization Object rand() { return unimplemented(); } } @Builtin(proc = true) @GenerateNodeFactory @NodeChild("seed") public static abstract class SrandNode extends OzNode { @Specialization Object srand(Object seed) { return unimplemented(); } } @GenerateNodeFactory @NodeChild("min") public static abstract class RandLimitsNode extends OzNode { @Specialization Object randLimits(OzVar min) { return unimplemented(); } } @Builtin(deref = ALL) @GenerateNodeFactory @NodeChild("var") public static abstract class GetEnvNode extends OzNode { @Specialization Object getEnv(String var) { String value = System.getenv(var); if (value != null) { return value.intern(); } else { return false; } } } @Builtin(proc = true) @GenerateNodeFactory @NodeChildren({ @NodeChild("var"), @NodeChild("value") }) public static abstract class PutEnvNode extends OzNode { @Specialization Object putEnv(Object var, Object value) { return unimplemented(); } } @GenerateNodeFactory @NodeChild("directory") public static abstract class GetDirNode extends OzNode { @Specialization Object getDir(Object directory) { return unimplemented(); } } @GenerateNodeFactory public static abstract class GetCWDNode extends OzNode { @Specialization String getCWD() { return System.getProperty("user.dir").intern(); } } @Builtin(proc = true) @GenerateNodeFactory @NodeChild("dir") public static abstract class ChDirNode extends OzNode { @Specialization Object chDir(Object dir) { return unimplemented(); } } @GenerateNodeFactory public static abstract class TmpnamNode extends OzNode { @Specialization Object tmpnam() { return unimplemented(); } } @GenerateNodeFactory @NodeChildren({ @NodeChild("fileName"), @NodeChild("mode") }) public static abstract class FopenNode extends OzNode { @Specialization Object fopen(Object fileName, Object mode) { return unimplemented(); } } @GenerateNodeFactory @NodeChildren({ @NodeChild("fileNode"), @NodeChild("count"), @NodeChild("end"), @NodeChild("actualCount") }) public static abstract class FreadNode extends OzNode { @Specialization Object fread(Object fileNode, Object count, Object end, OzVar actualCount) { return unimplemented(); } } @GenerateNodeFactory @NodeChildren({ @NodeChild("fileNode"), @NodeChild("data") }) public static abstract class FwriteNode extends OzNode { @Specialization Object fwrite(Object fileNode, Object data) { return unimplemented(); } } @GenerateNodeFactory @NodeChildren({ @NodeChild("fileNode"), @NodeChild("offset"), @NodeChild("whence") }) public static abstract class FseekNode extends OzNode { @Specialization Object fseek(Object fileNode, Object offset, Object whence) { return unimplemented(); } } @Builtin(proc = true) @GenerateNodeFactory @NodeChild("fileNode") public static abstract class FcloseNode extends OzNode { @Specialization Object fclose(Object fileNode) { return unimplemented(); } } @GenerateNodeFactory public static abstract class StdinNode extends OzNode { @Specialization Object stdin() { return System.in; } } @GenerateNodeFactory public static abstract class StdoutNode extends OzNode { @Specialization Object stdout() { return System.out; } } @GenerateNodeFactory public static abstract class StderrNode extends OzNode { @Specialization Object stderr() { return System.err; } } @GenerateNodeFactory @NodeChild("cmd") public static abstract class SystemNode extends OzNode { @Specialization Object system(Object cmd) { return unimplemented(); } } @GenerateNodeFactory @NodeChildren({ @NodeChild("ipVersion"), @NodeChild("port") }) public static abstract class TcpAcceptorCreateNode extends OzNode { @Specialization Object tcpAcceptorCreate(Object ipVersion, Object port) { return unimplemented(); } } @GenerateNodeFactory @NodeChild("acceptor") public static abstract class TcpAcceptNode extends OzNode { @Specialization Object tcpAccept(Object acceptor) { return unimplemented(); } } @Builtin(proc = true) @GenerateNodeFactory @NodeChild("acceptor") public static abstract class TcpCancelAcceptNode extends OzNode { @Specialization Object tcpCancelAccept(Object acceptor) { return unimplemented(); } } @Builtin(proc = true) @GenerateNodeFactory @NodeChild("acceptor") public static abstract class TcpAcceptorCloseNode extends OzNode { @Specialization Object tcpAcceptorClose(Object acceptor) { return unimplemented(); } } @GenerateNodeFactory @NodeChildren({ @NodeChild("host"), @NodeChild("service") }) public static abstract class TcpConnectNode extends OzNode { @Specialization Object tcpConnect(Object host, Object service) { return unimplemented(); } } @GenerateNodeFactory @NodeChildren({ @NodeChild("connection"), @NodeChild("count"), @NodeChild("tail") }) public static abstract class TcpConnectionReadNode extends OzNode { @Specialization Object tcpConnectionRead(Object connection, Object count, Object tail) { return unimplemented(); } } @GenerateNodeFactory @NodeChildren({ @NodeChild("connection"), @NodeChild("data") }) public static abstract class TcpConnectionWriteNode extends OzNode { @Specialization Object tcpConnectionWrite(Object connection, Object data) { return unimplemented(); } } @Builtin(proc = true) @GenerateNodeFactory @NodeChildren({ @NodeChild("connection"), @NodeChild("what") }) public static abstract class TcpConnectionShutdownNode extends OzNode { @Specialization Object tcpConnectionShutdown(Object connection, Object what) { return unimplemented(); } } @Builtin(proc = true) @GenerateNodeFactory @NodeChild("connection") public static abstract class TcpConnectionCloseNode extends OzNode { @Specialization Object tcpConnectionClose(Object connection) { return unimplemented(); } } @GenerateNodeFactory @NodeChildren({ @NodeChild("inExecutable"), @NodeChild("inArgv"), @NodeChild("inDoKill") }) public static abstract class ExecNode extends OzNode { @Specialization Object exec(Object inExecutable, Object inArgv, Object inDoKill) { return unimplemented(); } } @GenerateNodeFactory @NodeChildren({ @NodeChild("inExecutable"), @NodeChild("inArgv"), @NodeChild("outPid") }) public static abstract class PipeNode extends OzNode { @Specialization Object pipe(Object inExecutable, Object inArgv, OzVar outPid) { return unimplemented(); } } @GenerateNodeFactory @NodeChildren({ @NodeChild("connection"), @NodeChild("count"), @NodeChild("tail") }) public static abstract class PipeConnectionReadNode extends OzNode { @Specialization Object pipeConnectionRead(Object connection, Object count, Object tail) { return unimplemented(); } } @GenerateNodeFactory @NodeChildren({ @NodeChild("connection"), @NodeChild("data") }) public static abstract class PipeConnectionWriteNode extends OzNode { @Specialization Object pipeConnectionWrite(Object connection, Object data) { return unimplemented(); } } @Builtin(proc = true) @GenerateNodeFactory @NodeChildren({ @NodeChild("connection"), @NodeChild("what") }) public static abstract class PipeConnectionShutdownNode extends OzNode { @Specialization Object pipeConnectionShutdown(Object connection, Object what) { return unimplemented(); } } @Builtin(proc = true) @GenerateNodeFactory @NodeChild("connection") public static abstract class PipeConnectionCloseNode extends OzNode { @Specialization Object pipeConnectionClose(Object connection) { return unimplemented(); } } @GenerateNodeFactory public static abstract class GetPIDNode extends OzNode { @Specialization Object getPID() { return unimplemented(); } } @GenerateNodeFactory @NodeChild("name") public static abstract class GetHostByNameNode extends OzNode { @Specialization Object getHostByName(Object name) { return unimplemented(); } } @GenerateNodeFactory public static abstract class UNameNode extends OzNode { @Specialization Object uName() { return unimplemented(); } } }
package org.jboss.as.web; import org.jboss.as.controller.persistence.SubsystemMarshallingContext; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.staxmapper.XMLElementReader; import org.jboss.staxmapper.XMLElementWriter; import org.jboss.staxmapper.XMLExtendedStreamReader; import org.jboss.staxmapper.XMLExtendedStreamWriter; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import java.util.Collections; import java.util.List; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.parsing.ParseUtils.missingRequired; import static org.jboss.as.controller.parsing.ParseUtils.readStringAttributeElement; import static org.jboss.as.controller.parsing.ParseUtils.requireAttributes; import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent; import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute; import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute; import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement; import static org.jboss.as.web.Constants.ACCESS_LOG; import static org.jboss.as.web.Constants.ALIAS; import static org.jboss.as.web.Constants.CA_CERTIFICATE_FILE; import static org.jboss.as.web.Constants.CA_REVOCATION_URL; import static org.jboss.as.web.Constants.CERTIFICATE_FILE; import static org.jboss.as.web.Constants.CERTIFICATE_KEY_FILE; import static org.jboss.as.web.Constants.CIPHER_SUITE; import static org.jboss.as.web.Constants.CONDITION; import static org.jboss.as.web.Constants.CONNECTOR; import static org.jboss.as.web.Constants.CONTAINER_CONFIG; import static org.jboss.as.web.Constants.DEFAULT_WEB_MODULE; import static org.jboss.as.web.Constants.DIRECTORY; import static org.jboss.as.web.Constants.DISABLED; import static org.jboss.as.web.Constants.ENABLED; import static org.jboss.as.web.Constants.ENABLE_LOOKUPS; import static org.jboss.as.web.Constants.ENABLE_WELCOME_ROOT; import static org.jboss.as.web.Constants.EXECUTOR; import static org.jboss.as.web.Constants.EXTENDED; import static org.jboss.as.web.Constants.FILE_ENCONDING; import static org.jboss.as.web.Constants.FLAGS; import static org.jboss.as.web.Constants.JSP_CONFIGURATION; import static org.jboss.as.web.Constants.KEY_ALIAS; import static org.jboss.as.web.Constants.LISTINGS; import static org.jboss.as.web.Constants.MAX_CONNECTIONS; import static org.jboss.as.web.Constants.MAX_DEPTH; import static org.jboss.as.web.Constants.MAX_POST_SIZE; import static org.jboss.as.web.Constants.MAX_SAVE_POST_SIZE; import static org.jboss.as.web.Constants.MIME_MAPPING; import static org.jboss.as.web.Constants.NAME; import static org.jboss.as.web.Constants.PASSWORD; import static org.jboss.as.web.Constants.PATH; import static org.jboss.as.web.Constants.PATTERN; import static org.jboss.as.web.Constants.PREFIX; import static org.jboss.as.web.Constants.PROTOCOL; import static org.jboss.as.web.Constants.PROXY_NAME; import static org.jboss.as.web.Constants.PROXY_PORT; import static org.jboss.as.web.Constants.READ_ONLY; import static org.jboss.as.web.Constants.REDIRECT_PORT; import static org.jboss.as.web.Constants.RELATIVE_TO; import static org.jboss.as.web.Constants.RESOLVE_HOSTS; import static org.jboss.as.web.Constants.REWRITE; import static org.jboss.as.web.Constants.ROTATE; import static org.jboss.as.web.Constants.SCHEME; import static org.jboss.as.web.Constants.SECRET; import static org.jboss.as.web.Constants.SECURE; import static org.jboss.as.web.Constants.SENDFILE; import static org.jboss.as.web.Constants.SESSION_CACHE_SIZE; import static org.jboss.as.web.Constants.SESSION_TIMEOUT; import static org.jboss.as.web.Constants.SOCKET_BINDING; import static org.jboss.as.web.Constants.SSL; import static org.jboss.as.web.Constants.SSO; import static org.jboss.as.web.Constants.STATIC_RESOURCES; import static org.jboss.as.web.Constants.SUBSTITUTION; import static org.jboss.as.web.Constants.TEST; import static org.jboss.as.web.Constants.VERIFY_CLIENT; import static org.jboss.as.web.Constants.VERIFY_DEPTH; import static org.jboss.as.web.Constants.VIRTUAL_SERVER; import static org.jboss.as.web.Constants.WEBDAV; import static org.jboss.as.web.Constants.WELCOME_FILE; /** * The web subsystem parser. * * @author Emanuel Muckenhuber * @author Brian Stansberry */ class WebSubsystemParser implements XMLStreamConstants, XMLElementReader<List<ModelNode>>, XMLElementWriter<SubsystemMarshallingContext> { private static final WebSubsystemParser INSTANCE = new WebSubsystemParser(); static WebSubsystemParser getInstance() { return INSTANCE; } /** {@inheritDoc} */ @Override public void writeContent(XMLExtendedStreamWriter writer, SubsystemMarshallingContext context) throws XMLStreamException { context.startSubsystemElement(Namespace.CURRENT.getUriString(), false); ModelNode node = context.getModelNode(); writeAttribute(writer, Attribute.NATIVE.getLocalName(), node); writeAttribute(writer, Attribute.DEFAULT_VIRTUAL_SERVER.getLocalName(), node); if(node.hasDefined(CONTAINER_CONFIG)) { writeContainerConfig(writer, node.get(CONTAINER_CONFIG)); } if(node.hasDefined(CONNECTOR)) { for(final Property connector : node.get(CONNECTOR).asPropertyList()) { final ModelNode config = connector.getValue(); writer.writeStartElement(Element.CONNECTOR.getLocalName()); writer.writeAttribute(NAME, connector.getName()); writeAttribute(writer, Attribute.PROTOCOL.getLocalName(), config); writeAttribute(writer, Attribute.SOCKET_BINDING.getLocalName(), config); writeAttribute(writer, Attribute.SCHEME.getLocalName(), config); writeAttribute(writer, Attribute.ENABLED.getLocalName(), config); writeAttribute(writer, Attribute.ENABLE_LOOKUPS.getLocalName(), config); writeAttribute(writer, Attribute.PROXY_NAME.getLocalName(), config); writeAttribute(writer, Attribute.PROXY_PORT.getLocalName(), config); writeAttribute(writer, Attribute.SECURE.getLocalName(), config); writeAttribute(writer, Attribute.EXECUTOR.getLocalName(), config); writeAttribute(writer, Attribute.MAX_POST_SIZE.getLocalName(), config); writeAttribute(writer, Attribute.MAX_SAVE_POST_SIZE.getLocalName(), config); writeAttribute(writer, Attribute.MAX_CONNECTIONS.getLocalName(), config); writeAttribute(writer, Attribute.REDIRECT_PORT.getLocalName(), config); if (config.hasDefined(SSL)) { writer.writeStartElement(Element.SSL.getLocalName()); final ModelNode sslConfig = config.get(SSL); writeAttribute(writer, Attribute.NAME.getLocalName(), sslConfig); writeAttribute(writer, Attribute.KEY_ALIAS.getLocalName(), sslConfig); writeAttribute(writer, Attribute.PASSWORD.getLocalName(), sslConfig); writeAttribute(writer, Attribute.CERTIFICATE_KEY_FILE.getLocalName(), sslConfig); writeAttribute(writer, Attribute.CIPHER_SUITE.getLocalName(), sslConfig); writeAttribute(writer, Attribute.PROTOCOL.getLocalName(), sslConfig); writeAttribute(writer, Attribute.VERIFY_CLIENT.getLocalName(), sslConfig); writeAttribute(writer, Attribute.VERIFY_DEPTH.getLocalName(), sslConfig); writeAttribute(writer, Attribute.CERTIFICATE_FILE.getLocalName(), sslConfig); writeAttribute(writer, Attribute.CA_CERTIFICATE_FILE.getLocalName(), sslConfig); writeAttribute(writer, Attribute.CA_REVOCATION_URL.getLocalName(), sslConfig); writeAttribute(writer, Attribute.SESSION_CACHE_SIZE.getLocalName(), sslConfig); writeAttribute(writer, Attribute.SESSION_TIMEOUT.getLocalName(), sslConfig); writer.writeEndElement(); } if (config.hasDefined(VIRTUAL_SERVER)) { for(final ModelNode virtualServer : config.get(VIRTUAL_SERVER).asList()) { writer.writeEmptyElement(VIRTUAL_SERVER); writer.writeAttribute(NAME, virtualServer.asString()); } } writer.writeEndElement(); } } if(node.hasDefined(VIRTUAL_SERVER)) { for(final Property host : node.get(VIRTUAL_SERVER).asPropertyList()) { final ModelNode config = host.getValue(); writer.writeStartElement(Element.VIRTUAL_SERVER.getLocalName()); writer.writeAttribute(NAME, host.getName()); writeAttribute(writer, Attribute.DEFAULT_WEB_MODULE.getLocalName(), config); if (config.hasDefined(ENABLE_WELCOME_ROOT) && config.get(ENABLE_WELCOME_ROOT).asBoolean()) writer.writeAttribute(ENABLE_WELCOME_ROOT, "true"); if(config.hasDefined(ALIAS)) { for(final ModelNode alias : config.get(ALIAS).asList()) { writer.writeEmptyElement(ALIAS); writer.writeAttribute(NAME, alias.asString()); } } if(config.hasDefined(ACCESS_LOG)) { writer.writeStartElement(Element.ACCESS_LOG.getLocalName()); final ModelNode accessLog = config.get(ACCESS_LOG); writeAttribute(writer, Attribute.PATTERN.getLocalName(), accessLog); writeAttribute(writer, Attribute.RESOLVE_HOSTS.getLocalName(), accessLog); writeAttribute(writer, Attribute.EXTENDED.getLocalName(), accessLog); writeAttribute(writer, Attribute.PREFIX.getLocalName(), accessLog); writeAttribute(writer, Attribute.ROTATE.getLocalName(), accessLog); if(accessLog.has(DIRECTORY)) { final ModelNode directory = accessLog.get(DIRECTORY); writer.writeEmptyElement(DIRECTORY); writeAttribute(writer, Attribute.PATH.getLocalName(), directory); writeAttribute(writer, Attribute.RELATIVE_TO.getLocalName(), directory); } writer.writeEndElement(); } if (config.hasDefined(REWRITE)) { for (final ModelNode rewrite : config.get(REWRITE).asList()) { writer.writeStartElement(REWRITE); writeAttribute(writer, Attribute.PATTERN.getLocalName(), rewrite); writeAttribute(writer, Attribute.SUBSTITUTION.getLocalName(), rewrite); writeAttribute(writer, Attribute.FLAGS.getLocalName(), rewrite); if (rewrite.hasDefined(CONDITION)) { for (final ModelNode condition : rewrite.get(CONDITION).asList()) { writer.writeEmptyElement(CONDITION); writeAttribute(writer, Attribute.TEST.getLocalName(), condition); writeAttribute(writer, Attribute.PATTERN.getLocalName(), condition); writeAttribute(writer, Attribute.FLAGS.getLocalName(), condition); } } writer.writeEndElement(); } } if(config.hasDefined(SSO)) { writer.writeEmptyElement(SSO); final ModelNode sso = config.get(SSO); writeAttribute(writer, Attribute.CACHE_CONTAINER.getLocalName(), sso); writeAttribute(writer, Attribute.DOMAIN.getLocalName(), sso); writeAttribute(writer, Attribute.REAUTHENTICATE.getLocalName(), sso); } writer.writeEndElement(); } } writer.writeEndElement(); } private void writeContainerConfig(XMLExtendedStreamWriter writer, ModelNode config) throws XMLStreamException { boolean containerConfigStartWritten = false; if(config.hasDefined(STATIC_RESOURCES)) { containerConfigStartWritten = writeStaticResources(writer, config.get(STATIC_RESOURCES)); } if(config.hasDefined(JSP_CONFIGURATION)) { containerConfigStartWritten = writeJSPConfiguration(writer, config.get(JSP_CONFIGURATION), containerConfigStartWritten) || containerConfigStartWritten ; } if(config.hasDefined(MIME_MAPPING)) { if (!containerConfigStartWritten) { writer.writeStartElement(Element.CONTAINER_CONFIG.getLocalName()); containerConfigStartWritten = true; } for(final Property entry : config.get(MIME_MAPPING).asPropertyList()) { writer.writeEmptyElement(Element.MIME_MAPPING.getLocalName()); writer.writeAttribute(Attribute.NAME.getLocalName(), entry.getName()); writer.writeAttribute(Attribute.VALUE.getLocalName(), entry.getValue().asString()); } } if(config.hasDefined(WELCOME_FILE)) { if (!containerConfigStartWritten) { writer.writeStartElement(Element.CONTAINER_CONFIG.getLocalName()); containerConfigStartWritten = true; } for(final ModelNode file : config.get(WELCOME_FILE).asList()) { writer.writeStartElement(Element.WELCOME_FILE.getLocalName()); writer.writeCharacters(file.asString()); writer.writeEndElement(); } } if (containerConfigStartWritten) { writer.writeEndElement(); } } private boolean writeStaticResources(XMLExtendedStreamWriter writer, ModelNode config) throws XMLStreamException { boolean startWritten = writeStaticResourceAttribute(writer, Attribute.LISTINGS.getLocalName(), config, false); startWritten = writeStaticResourceAttribute(writer, Attribute.SENDFILE.getLocalName(), config, startWritten) || startWritten; startWritten = writeStaticResourceAttribute(writer, Attribute.FILE_ENCONDING.getLocalName(), config, startWritten) || startWritten; startWritten = writeStaticResourceAttribute(writer, Attribute.READ_ONLY.getLocalName(), config, startWritten) || startWritten; startWritten = writeStaticResourceAttribute(writer, Attribute.WEBDAV.getLocalName(), config, startWritten) || startWritten; startWritten = writeStaticResourceAttribute(writer, Attribute.SECRET.getLocalName(), config, startWritten) || startWritten; startWritten = writeStaticResourceAttribute(writer, Attribute.MAX_DEPTH.getLocalName(), config, startWritten) || startWritten; startWritten = writeStaticResourceAttribute(writer, Attribute.DISABLED.getLocalName(), config, startWritten) || startWritten; if (startWritten) { writer.writeEndElement(); } return startWritten; } private boolean writeStaticResourceAttribute(XMLExtendedStreamWriter writer, String attribute, ModelNode config, boolean startWritten) throws XMLStreamException { if (DefaultStaticResources.hasNotDefault(config, attribute)) { if (!startWritten) { writer.writeStartElement(Element.CONTAINER_CONFIG.getLocalName()); writer.writeStartElement(Element.STATIC_RESOURCES.getLocalName()); } writer.writeAttribute(attribute, config.get(attribute).asString()); return true; } return false; } private boolean writeJSPConfiguration(XMLExtendedStreamWriter writer, ModelNode jsp, boolean containerConfigStartWritten) throws XMLStreamException { boolean startWritten = writeJspConfigAttribute(writer, Attribute.DEVELOPMENT.getLocalName(), jsp, false, containerConfigStartWritten); startWritten = writeJspConfigAttribute(writer, Attribute.KEEP_GENERATED.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.TRIM_SPACES.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.TAG_POOLING.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.MAPPED_FILE.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.CHECK_INTERVAL.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.MODIFIFICATION_TEST_INTERVAL.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.RECOMPILE_ON_FAIL.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.SMAP.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.DUMP_SMAP.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.GENERATE_STRINGS_AS_CHAR_ARRAYS.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.ERROR_ON_USE_BEAN_INVALID_CLASS_ATTRIBUTE.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.SCRATCH_DIR.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.SOURCE_VM.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.TARGET_VM.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.JAVA_ENCODING.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.X_POWERED_BY.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.DISPLAY_SOURCE_FRAGMENT.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; startWritten = writeJspConfigAttribute(writer, Attribute.DISABLED.getLocalName(), jsp, startWritten, containerConfigStartWritten) || startWritten; if (startWritten) { writer.writeEndElement(); } return startWritten; } private boolean writeJspConfigAttribute(XMLExtendedStreamWriter writer, String attribute, ModelNode config, boolean startWritten, boolean containerConfigStartWritten) throws XMLStreamException { if (DefaultJspConfig.hasNotDefault(config, attribute)) { if (!startWritten) { if (!containerConfigStartWritten) { writer.writeStartElement(Element.CONTAINER_CONFIG.getLocalName()); } writer.writeStartElement(Element.JSP_CONFIGURATION.getLocalName()); } writer.writeAttribute(attribute, config.get(attribute).asString()); return true; } return false; } /** {@inheritDoc} */ @Override public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException { final ModelNode address = new ModelNode(); address.add(SUBSYSTEM, WebExtension.SUBSYSTEM_NAME); address.protect(); final ModelNode subsystem = new ModelNode(); subsystem.get(OP).set(ADD); subsystem.get(OP_ADDR).set(address); final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NATIVE: case DEFAULT_VIRTUAL_SERVER: subsystem.get(attribute.getLocalName()).set(value); break; default: throw unexpectedAttribute(reader, i); } } list.add(subsystem); // elements while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { switch (Namespace.forUri(reader.getNamespaceURI())) { case WEB_1_0: { final Element element = Element.forName(reader.getLocalName()); switch (element) { case CONTAINER_CONFIG: { final ModelNode config = parseContainerConfig(reader); subsystem.get(CONTAINER_CONFIG).set(config); break; } case CONNECTOR: { parseConnector(reader,address, list); break; } case VIRTUAL_SERVER: { parseHost(reader, address, list); break; } default: { throw unexpectedElement(reader); } } break; } default: { throw unexpectedElement(reader); } } } } static ModelNode parseContainerConfig(XMLExtendedStreamReader reader) throws XMLStreamException { final ModelNode config = new ModelNode(); // no attributes if (reader.getAttributeCount() > 0) { throw unexpectedAttribute(reader, 0); } // elements while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { final Element element = Element.forName(reader.getLocalName()); switch (element) { case STATIC_RESOURCES: { final ModelNode resourceServing = parseStaticResources(reader); config.get(STATIC_RESOURCES).set(resourceServing); break; } case JSP_CONFIGURATION: { final ModelNode jspConfiguration = parseJSPConfiguration(reader); config.get(JSP_CONFIGURATION).set(jspConfiguration); break; } case MIME_MAPPING: { final String[] array = requireAttributes(reader, Attribute.NAME.getLocalName(), Attribute.VALUE.getLocalName()); config.get(MIME_MAPPING).get(array[0]).set(array[1]); break; } case WELCOME_FILE: { final String welcomeFile = reader.getElementText().trim(); config.get(WELCOME_FILE).add(welcomeFile); break; } default: throw unexpectedElement(reader); } } return config; } static ModelNode parseJSPConfiguration(XMLExtendedStreamReader reader) throws XMLStreamException { final ModelNode jsp = new ModelNode(); final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case DEVELOPMENT: case DISABLED: case KEEP_GENERATED: case TRIM_SPACES: case TAG_POOLING: case MAPPED_FILE: case CHECK_INTERVAL: case MODIFIFICATION_TEST_INTERVAL: case RECOMPILE_ON_FAIL: case SMAP: case DUMP_SMAP: case GENERATE_STRINGS_AS_CHAR_ARRAYS: case ERROR_ON_USE_BEAN_INVALID_CLASS_ATTRIBUTE: case SCRATCH_DIR: case SOURCE_VM: case TARGET_VM: case JAVA_ENCODING: case X_POWERED_BY: case DISPLAY_SOURCE_FRAGMENT: jsp.get(attribute.getLocalName()).set(value); break; default: throw unexpectedAttribute(reader, i); } } requireNoContent(reader); return jsp; } static ModelNode parseStaticResources(XMLExtendedStreamReader reader) throws XMLStreamException { final ModelNode resources = new ModelNode(); final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case LISTINGS: resources.get(LISTINGS).set(value); break; case SENDFILE: resources.get(SENDFILE).set(value); break; case FILE_ENCONDING: resources.get(FILE_ENCONDING).set(value); break; case READ_ONLY: resources.get(READ_ONLY).set(value); break; case WEBDAV: resources.get(WEBDAV).set(value); break; case SECRET: resources.get(SECRET).set(value); break; case MAX_DEPTH: resources.get(MAX_DEPTH).set(value); break; case DISABLED: resources.get(DISABLED).set(value); break; default: throw unexpectedAttribute(reader, i); } } requireNoContent(reader); return resources; } static void parseHost(XMLExtendedStreamReader reader, final ModelNode address, List<ModelNode> list) throws XMLStreamException { String name = null; String defaultWebModule = null; boolean welcome = false; final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NAME: name = value; break; case DEFAULT_WEB_MODULE: if (welcome) throw new XMLStreamException("A default web module can not be specified when the welcome root has been enabled", reader.getLocation()); defaultWebModule = value; break; case ENABLE_WELCOME_ROOT: welcome = Boolean.parseBoolean(value); if (welcome && defaultWebModule != null) throw new XMLStreamException("The welcome root can not be enabled on a host that has a default web module", reader.getLocation()); break; default: throw unexpectedAttribute(reader, i); } } if(name == null) { throw missingRequired(reader, Collections.singleton(Attribute.NAME)); } final ModelNode host = new ModelNode(); host.get(OP).set(ADD); host.get(OP_ADDR).set(address).add(VIRTUAL_SERVER, name); if (defaultWebModule != null) { host.get(DEFAULT_WEB_MODULE).set(defaultWebModule); } host.get(ENABLE_WELCOME_ROOT).set(welcome); list.add(host); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { switch (Namespace.forUri(reader.getNamespaceURI())) { case WEB_1_0: { final Element element = Element.forName(reader.getLocalName()); switch (element) { case ALIAS: host.get(ALIAS).add(readStringAttributeElement(reader, Attribute.NAME.getLocalName())); break; case ACCESS_LOG: final ModelNode log = parseHostAccessLog(reader); host.get(ACCESS_LOG).set(log); break; case REWRITE: final ModelNode rewrite = parseHostRewrite(reader); host.get(REWRITE).add(rewrite); break; case SSO: final ModelNode sso = parseSso(reader); host.get(SSO).add(sso); break; default: throw unexpectedElement(reader); } break; } default: throw unexpectedElement(reader); } } } static ModelNode parseSso(XMLExtendedStreamReader reader) throws XMLStreamException { final ModelNode sso = new ModelNode(); final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case CACHE_CONTAINER: case DOMAIN: case REAUTHENTICATE: sso.get(attribute.getLocalName()).set(value); break; default: throw unexpectedAttribute(reader, i); } } requireNoContent(reader); return sso; } static ModelNode parseHostRewrite(XMLExtendedStreamReader reader) throws XMLStreamException { final ModelNode rewrite = new ModelNode(); rewrite.setEmptyObject(); final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case PATTERN: rewrite.get(PATTERN).set(value); break; case SUBSTITUTION: rewrite.get(SUBSTITUTION).set(value); break; case FLAGS: rewrite.get(REWRITE).set(value); break; default: throw unexpectedAttribute(reader, i); } } while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { switch (Namespace.forUri(reader.getNamespaceURI())) { case WEB_1_0: { final Element element = Element.forName(reader.getLocalName()); switch (element) { case CONDITION: final ModelNode condition = new ModelNode(); condition.setEmptyObject(); final int count2 = reader.getAttributeCount(); for (int i = 0; i < count2; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case TEST: condition.get(TEST).set(value); break; case PATTERN: condition.get(PATTERN).set(value); break; case FLAGS: condition.get(FLAGS).set(value); break; default: throw unexpectedAttribute(reader, i); } } requireNoContent(reader); rewrite.get(CONDITION).add(condition); break; default: throw unexpectedElement(reader); } break; } default: throw unexpectedElement(reader); } } return rewrite; } static ModelNode parseHostAccessLog(XMLExtendedStreamReader reader) throws XMLStreamException { final ModelNode log = new ModelNode(); log.setEmptyObject(); final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case PATTERN: log.get(PATTERN).set(value); break; case RESOLVE_HOSTS: log.get(RESOLVE_HOSTS).set(value); break; case EXTENDED: log.get(EXTENDED).set(value); break; case PREFIX: log.get(PREFIX).set(value); break; case ROTATE: log.get(ROTATE).set(value); break; default: throw unexpectedAttribute(reader, i); } } while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { switch (Namespace.forUri(reader.getNamespaceURI())) { case WEB_1_0: { final Element element = Element.forName(reader.getLocalName()); switch (element) { case DIRECTORY: final ModelNode directory = new ModelNode(); final int count2 = reader.getAttributeCount(); for (int i = 0; i < count2; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case PATH: directory.get(PATH).set(value); break; case RELATIVE_TO: directory.get(RELATIVE_TO).set(value); break; default: throw unexpectedAttribute(reader, i); } } requireNoContent(reader); log.get(DIRECTORY).set(directory); break; default: throw unexpectedElement(reader); } break; } default: throw unexpectedElement(reader); } } return log; } static void parseConnector(XMLExtendedStreamReader reader, ModelNode address, List<ModelNode> list) throws XMLStreamException { String name = null; String protocol = null; String bindingRef = null; String scheme = null; String executorRef = null; String enabled = null; String enableLookups = null; String proxyName = null; String proxyPort = null; String maxPostSize = null; String maxSavePostSize = null; String secure = null; String redirectPort = null; String maxConnections = null; final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NAME: name = value; break; case SOCKET_BINDING: bindingRef = value; break; case SCHEME: scheme = value; break; case PROTOCOL: protocol = value; break; case EXECUTOR: executorRef = value; break; case ENABLED: enabled = value; break; case ENABLE_LOOKUPS: enableLookups = value; break; case PROXY_NAME: proxyName = value; break; case PROXY_PORT: proxyPort = value; break; case MAX_POST_SIZE: maxPostSize = value; break; case MAX_SAVE_POST_SIZE: maxSavePostSize = value; break; case SECURE: secure = value; break; case REDIRECT_PORT: redirectPort = value; break; case MAX_CONNECTIONS: maxConnections = value; break; default: throw unexpectedAttribute(reader, i); } } if (name == null) { throw missingRequired(reader, Collections.singleton(Attribute.NAME)); } if (bindingRef == null) { throw missingRequired(reader, Collections.singleton(Attribute.SOCKET_BINDING)); } final ModelNode connector = new ModelNode(); connector.get(OP).set(ADD); connector.get(OP_ADDR).set(address).add(CONNECTOR, name); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { switch (Namespace.forUri(reader.getNamespaceURI())) { case WEB_1_0: { final Element element = Element.forName(reader.getLocalName()); switch (element) { case SSL: final ModelNode ssl = parseSsl(reader); connector.get(SSL).set(ssl); break; case VIRTUAL_SERVER: connector.get(VIRTUAL_SERVER).add(readStringAttributeElement(reader, Attribute.NAME.getLocalName())); break; default: throw unexpectedElement(reader); } break; } default: throw unexpectedElement(reader); } } if(protocol != null) connector.get(PROTOCOL).set(protocol); connector.get(SOCKET_BINDING).set(bindingRef); if(scheme != null) connector.get(SCHEME).set(scheme); if(executorRef != null) connector.get(EXECUTOR).set(executorRef); if(enabled != null) connector.get(ENABLED).set(enabled); if(enableLookups != null) connector.get(ENABLE_LOOKUPS).set(enableLookups); if(proxyName != null) connector.get(PROXY_NAME).set(proxyName); if(proxyPort != null) connector.get(PROXY_PORT).set(proxyPort); if(maxPostSize != null) connector.get(MAX_POST_SIZE).set(maxPostSize); if(maxSavePostSize != null) connector.get(MAX_SAVE_POST_SIZE).set(maxSavePostSize); if(secure != null) connector.get(SECURE).set(secure); if(redirectPort != null) connector.get(REDIRECT_PORT).set(redirectPort); if(maxConnections != null) connector.get(MAX_CONNECTIONS).set(maxConnections); list.add(connector); } static ModelNode parseSsl(XMLExtendedStreamReader reader) throws XMLStreamException { final ModelNode ssl = new ModelNode(); ssl.setEmptyObject(); final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NAME: ssl.get(NAME).set(value); break; case KEY_ALIAS: ssl.get(KEY_ALIAS).set(value); break; case PASSWORD: ssl.get(PASSWORD).set(value); break; case CERTIFICATE_KEY_FILE: ssl.get(CERTIFICATE_KEY_FILE).set(value); break; case CIPHER_SUITE: ssl.get(CIPHER_SUITE).set(value); break; case PROTOCOL: ssl.get(PROTOCOL).set(value); break; case VERIFY_CLIENT: ssl.get(VERIFY_CLIENT).set(value); break; case VERIFY_DEPTH: ssl.get(VERIFY_DEPTH).set(Integer.valueOf(value)); break; case CERTIFICATE_FILE: ssl.get(CERTIFICATE_FILE).set(value); break; case CA_CERTIFICATE_FILE: ssl.get(CA_CERTIFICATE_FILE).set(value); break; case CA_REVOCATION_URL: ssl.get(CA_REVOCATION_URL).set(value); break; case SESSION_CACHE_SIZE: ssl.get(SESSION_CACHE_SIZE).set(value); break; case SESSION_TIMEOUT: ssl.get(SESSION_TIMEOUT).set(value); break; default: throw unexpectedAttribute(reader, i); } } requireNoContent(reader); return ssl; } static void writeAttribute(final XMLExtendedStreamWriter writer, final String name, ModelNode node) throws XMLStreamException { if(node.hasDefined(name)) { writer.writeAttribute(name, node.get(name).asString()); } } }
package org.noear.weed.utils; import java.io.Serializable; import java.lang.invoke.SerializedLambda; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class PropertyWrap implements Serializable { private static Map<String, Class<?>> _clzCache = new ConcurrentHashMap<>(); private static Class<?> getClz(String implClz) { Class<?> clz = _clzCache.get(implClz); if (clz == null) { try { clz = Class.forName(implClz.replace("/", ".")); _clzCache.putIfAbsent(implClz, clz); } catch (Exception ex) { throw new RuntimeException(ex); } } return clz; } public final Property property; /** Class wrap */ public final ClassWrap clzWrap; public final String name; private String _alias; public PropertyWrap alias(String alias){ _alias = alias; return this; } public PropertyWrap(PropertyWrap pw){ property = pw.property; clzWrap = pw.clzWrap; name = pw.name; } public PropertyWrap(Property p, String implClz, String name) { this.property = p; this.clzWrap = ClassWrap.get(getClz(implClz)); this.name = name; } public String getColumnName(List<ClassWrap> cl) { if (cl == null) { return name; } else { int idx = cl.indexOf(clzWrap); if (idx < 0) { return name; } else { return "t" + idx + "." + name; } } } public String getSelectName(List<ClassWrap> cl) { if (_alias == null) { return getColumnName(cl); } else { return getColumnName(cl) + " " + _alias; } } private static Map<Property, PropertyWrap> _popCache = new ConcurrentHashMap<>(); public static <C> PropertyWrap get(Property<C, ?> p) { PropertyWrap tmp = _popCache.get(p); if (tmp == null) { tmp = wrap(p); _popCache.putIfAbsent(p, tmp); } return tmp; } /** Property PropertyWrap */ private static <C> PropertyWrap wrap(Property<C, ?> p) { try { Method fun = p.getClass().getDeclaredMethod("writeReplace"); fun.setAccessible(Boolean.TRUE); SerializedLambda slambda = (SerializedLambda) fun.invoke(p); String method = slambda.getImplMethodName(); String attr = null; if (method.startsWith("get")) { attr = method.substring(3); } else { attr = method.substring(2); } return new PropertyWrap(p, slambda.getImplClass(), attr); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } public static <C> PropertyWrap $(Property<C, ?> p) { return new PropertyWrap(get(p)); } }
package org.openspaces.grid.esm; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import org.openspaces.admin.Admin; import org.openspaces.admin.AdminFactory; import org.openspaces.admin.esm.deployment.DeploymentContext; import org.openspaces.admin.esm.deployment.ElasticDataGridDeployment; import org.openspaces.admin.esm.deployment.MemorySla; import org.openspaces.admin.gsa.GridServiceAgent; import org.openspaces.admin.gsa.GridServiceContainerOptions; import org.openspaces.admin.gsc.GridServiceContainer; import org.openspaces.admin.machine.Machine; import org.openspaces.admin.pu.DeploymentStatus; import org.openspaces.admin.pu.ProcessingUnit; import org.openspaces.admin.pu.ProcessingUnitInstance; import org.openspaces.admin.pu.ProcessingUnits; import org.openspaces.admin.pu.events.BackupGridServiceManagerChangedEvent; import org.openspaces.admin.pu.events.ManagingGridServiceManagerChangedEvent; import org.openspaces.admin.pu.events.ProcessingUnitLifecycleEventListener; import org.openspaces.admin.pu.events.ProcessingUnitStatusChangedEvent; import org.openspaces.admin.space.SpaceDeployment; import org.openspaces.admin.space.SpaceInstance; import org.openspaces.admin.zone.Zone; import com.gigaspaces.cluster.activeelection.SpaceMode; import com.j_spaces.core.IJSpace; import com.j_spaces.core.admin.IRemoteJSpaceAdmin; import com.j_spaces.core.admin.SpaceRuntimeInfo; import com.j_spaces.kernel.ClassLoaderHelper; import com.j_spaces.kernel.TimeUnitProperty; public class EsmExecutor { public static void main(String[] args) { new EsmExecutor(); } private final static Logger logger = Logger.getLogger("org.openspaces.grid.esm"); private final static long initialDelay = TimeUnitProperty.getProperty("org.openspaces.grid.esm.initialDelay", "5s"); private final static long fixedDelay = TimeUnitProperty.getProperty("org.openspaces.grid.esm.fixedDelay", "5s"); private final static int memorySafetyBufferInMB = MemorySettings.valueOf(System.getProperty("org.openspaces.grid.esm.memorySafetyBuffer", "100m")).toMB(); private final static NumberFormat NUMBER_FORMAT = NumberFormat.getInstance(); //maps pu-name to elastic-scale impl private final Map<String, OnDemandElasticScale> elasticScaleMap = new HashMap<String, OnDemandElasticScale>(); private final Admin admin = new AdminFactory().createAdmin(); private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { final ThreadFactory factory = Executors.defaultThreadFactory(); public Thread newThread(Runnable r) { Thread newThread = factory.newThread(r); newThread.setName("ESM-ScheduledTask"); return newThread; } }); public EsmExecutor() { NUMBER_FORMAT.setMinimumFractionDigits(1); NUMBER_FORMAT.setMaximumFractionDigits(2); String loggerProp = System.getProperty("logger.level"); if (loggerProp != null) logger.setLevel(Level.parse(loggerProp)); logger.config("Initial Delay: " + initialDelay + " ms"); logger.config("Fixed Delay: " + fixedDelay + " ms"); if (Boolean.valueOf(System.getProperty("esm.enabled", "true"))) { executorService.scheduleWithFixedDelay(new ScheduledTask(), initialDelay, fixedDelay, TimeUnit.MILLISECONDS); admin.getProcessingUnits().addLifecycleListener(new UndeployedProcessingUnitLifecycleEventListener()); } } public void deploy(ElasticDataGridDeployment deployment) { DeploymentContext context = deployment.getContext(); final String zoneName = deployment.getDataGridName(); SpaceDeployment spaceDeployment = new SpaceDeployment(deployment.getDataGridName()); spaceDeployment.addZone(zoneName); int numberOfParitions = calculateNumberOfPartitions(context); if (context.isHighlyAvailable()) { spaceDeployment.maxInstancesPerMachine(1); spaceDeployment.partitioned(numberOfParitions, 1); } else { spaceDeployment.partitioned(numberOfParitions, 0); } spaceDeployment.setContextProperty("elastic", "true"); spaceDeployment.setContextProperty("minMemory", context.getMinMemory()); spaceDeployment.setContextProperty("maxMemory", context.getMaxMemory()); spaceDeployment.setContextProperty("initialJavaHeapSize", context.getInitialJavaHeapSize()); spaceDeployment.setContextProperty("maximumJavaHeapSize", context.getMaximumJavaHeapSize()); spaceDeployment.setContextProperty("isolationLevel", context.getIsolationLevel().name()); spaceDeployment.setContextProperty("sla", context.getSlaDescriptors()); if (deployment.getElasticScaleConfig() != null) { spaceDeployment.setContextProperty("elasticScaleConfig", ElasticScaleConfigSerializer.toString(deployment.getElasticScaleConfig())); } if (!deployment.getContextProperties().isEmpty()) { Set<Entry<Object,Object>> entrySet = deployment.getContextProperties().entrySet(); for (Entry<Object,Object> entry : entrySet) { spaceDeployment.setContextProperty((String)entry.getKey(), (String)entry.getValue()); } } if (deployment.getContext().getVmInputArguments()!= null) { spaceDeployment.setContextProperty("vmArguments", deployment.getContext().getVmInputArguments()); } logger.finest("Deploying " + deployment.getDataGridName() + "\n\t Zone: " + zoneName + "\n\t Min Memory: " + context.getMinMemory() + "\n\t Max Memory: " + context.getMaxMemory() + "\n\t Initial Java Heap Size: " + context.getInitialJavaHeapSize() + "\n\t Maximum Java Heap Size: " + context.getMaximumJavaHeapSize() + "\n\t Isolation Level: " + context.getIsolationLevel().name() + "\n\t Highly Available? " + context.isHighlyAvailable() + "\n\t Partitions: " + numberOfParitions + "\n\t SLA: " + context.getSlaDescriptors()); admin.getGridServiceManagers().waitForAtLeastOne().deploy(spaceDeployment); } private int calculateNumberOfPartitions(DeploymentContext context) { int numberOfPartitions = MemorySettings.valueOf(context.getMaxMemory()).floorDividedBy(context.getMaximumJavaHeapSize()); if (context.isHighlyAvailable()) { numberOfPartitions /= 2; } return numberOfPartitions; } /** * Life cycle listener of processing units which are un-deployed, and their resources should be scaled down. */ private final class UndeployedProcessingUnitLifecycleEventListener implements ProcessingUnitLifecycleEventListener { public void processingUnitAdded(ProcessingUnit processingUnit) { } public void processingUnitRemoved(ProcessingUnit processingUnit) { if (!PuCapacityPlanner.isElastic(processingUnit)) return; try { executorService.schedule(new UndeployHandler(new PuCapacityPlanner(processingUnit, getOnDemandElasticScale(processingUnit))), fixedDelay, TimeUnit.MILLISECONDS); } catch (Exception e) { logger.log(Level.SEVERE, "Failed to invoke undeploy handler for " +processingUnit.getName(), e); } } public void processingUnitStatusChanged(ProcessingUnitStatusChangedEvent event) { } public void processingUnitManagingGridServiceManagerChanged(ManagingGridServiceManagerChangedEvent event) { } public void processingUnitBackupGridServiceManagerChanged(BackupGridServiceManagerChangedEvent event) { } } private final class ScheduledTask implements Runnable { public ScheduledTask() { } public void run() { try { if (Level.OFF.equals(logger.getLevel())) { return; //turn off cruise control } logger.finest("ScheduledTask is running..."); ProcessingUnits processingUnits = admin.getProcessingUnits(); for (ProcessingUnit pu : processingUnits) { logger.finest(ToStringHelper.puToString(pu)); if (!PuCapacityPlanner.isElastic(pu)) continue; PuCapacityPlanner puCapacityPlanner = new PuCapacityPlanner(pu, getOnDemandElasticScale(pu)); logger.finest(ToStringHelper.puCapacityPlannerToString(puCapacityPlanner)); Workflow workflow = new Workflow(puCapacityPlanner); while (workflow.hasNext()) { Runnable nextInWorkflow = workflow.removeFirst(); nextInWorkflow.run(); } } } catch (Throwable t) { logger.log(Level.WARNING, "Caught exception: " + t, t); } } } private OnDemandElasticScale getOnDemandElasticScale(ProcessingUnit pu) throws Exception { OnDemandElasticScale onDemandElasticScale = elasticScaleMap.get(pu.getName()); if (onDemandElasticScale != null) { return onDemandElasticScale; } String elasticScaleConfigStr = pu.getBeanLevelProperties().getContextProperties().getProperty("elasticScaleConfig"); if (elasticScaleConfigStr == null) { return new NullOnDemandElasticScale(); } ElasticScaleConfig elasticScaleConfig = ElasticScaleConfigSerializer.fromString(elasticScaleConfigStr); Class<? extends OnDemandElasticScale> clazz = ClassLoaderHelper.loadClass(elasticScaleConfig.getClassName()).asSubclass(OnDemandElasticScale.class); OnDemandElasticScale newInstance = clazz.newInstance(); newInstance.init(elasticScaleConfig); elasticScaleMap.put(pu.getName(), newInstance); return newInstance; } private class Workflow { private boolean isBroken = false; final List<Runnable> runnables = new ArrayList<Runnable>(); /** constructs an empty workflow */ public Workflow() { } public Workflow(PuCapacityPlanner puCapacityPlanner) { runnables.add(new UnderCapacityHandler(puCapacityPlanner, this)); runnables.add(new MemorySlaHandler(puCapacityPlanner, this)); runnables.add(new RebalancerHandler(puCapacityPlanner, this)); runnables.add(new GscCollectorHandler(puCapacityPlanner, this)); runnables.add(new CompromisedDeploymentHandler(puCapacityPlanner, this)); } public void add(Runnable runner) { runnables.add(runner); } public boolean hasNext() { return !runnables.isEmpty(); } public Runnable removeFirst() { return runnables.remove(0); } public void breakWorkflow() { isBroken = true; runnables.clear(); } public boolean isBroken() { return isBroken; } } private class UnderCapacityHandler implements Runnable { private final PuCapacityPlanner puCapacityPlanner; private final Workflow workflow; public UnderCapacityHandler(PuCapacityPlanner puCapacityPlanner, Workflow workflow) { this.puCapacityPlanner = puCapacityPlanner; this.workflow = workflow; } public void run() { logger.finest(UnderCapacityHandler.class.getSimpleName() + " invoked"); if (underMinCapcity()) { workflow.breakWorkflow(); workflow.add(new StartGscHandler(puCapacityPlanner, workflow)); } } private boolean underMinCapcity() { return puCapacityPlanner.getNumberOfGSCsInZone() < puCapacityPlanner.getMinNumberOfGSCs(); } } public class StartGscHandler implements Runnable { private final PuCapacityPlanner puCapacityPlanner; private final Workflow workflow; public StartGscHandler(PuCapacityPlanner puCapacityPlanner, Workflow workflow) { this.puCapacityPlanner = puCapacityPlanner; this.workflow = workflow; } public void run() { if (reachedMaxCapacity()) { logger.warning("Reached Capacity Limit"); return; } final ZoneCorrelator zoneCorrelator = new ZoneCorrelator(admin, puCapacityPlanner.getZoneName()); List<Machine> machines = zoneCorrelator.getMachines(); //sort by least number of GSCs in zone //TODO when not dedicated, we might need to take other GSCs into account Collections.sort(machines, new Comparator<Machine>() { public int compare(Machine m1, Machine m2) { List<GridServiceContainer> gscsM1 = zoneCorrelator.getGridServiceContainersByMachine(m1); List<GridServiceContainer> gscsM2 = zoneCorrelator.getGridServiceContainersByMachine(m2); return gscsM1.size() - gscsM2.size(); } }); boolean needsNewMachine = true; for (Machine machine : machines) { if (!puCapacityPlanner.getElasticScale().accept(machine)) { logger.finest("Machine ["+ToStringHelper.machineToString(machine)+"] was filtered out by [" + puCapacityPlanner.getElasticScale().getClass().getName()+"]"); continue; } if (!machineHasAnAgent(machine)) { logger.finest("Can't start a GSC on machine ["+ToStringHelper.machineToString(machine)+"] - doesn't have an agent."); continue; } if (!meetsDedicatedIsolationConstaint(machine, puCapacityPlanner.getZoneName())) { logger.finest("Can't start GSC on machine ["+ToStringHelper.machineToString(machine)+"] - doesn't meet dedicated isolation constraint."); continue; } if (aboveMinCapcity() && machineHasAnEmptyGSC(zoneCorrelator, machine)) { logger.finest("Won't start a GSC on machine ["+ToStringHelper.machineToString(machine)+"] - already has an empty GSC."); // needsNewMachine = false; continue; } if (!hasEnoughMemoryForNewGSC(machine)) { logger.finest("Can't start a GSC on machine ["+ToStringHelper.machineToString(machine)+"] - doesn't have enough memory to start a new GSC"); continue; // can't start GSC here } startGscOnMachine(machine); needsNewMachine = false; break; } if (needsNewMachine) { logger.finest("Can't start a GSC on the available machines - needs a new machine."); ElasticScaleCommand elasticScaleCommand = new ElasticScaleCommand(); elasticScaleCommand.setMachines(machines); puCapacityPlanner.getElasticScale().scaleOut(elasticScaleCommand); } } // requires this machine to contain only GSCs matching the zone name provided private boolean meetsDedicatedIsolationConstaint(Machine machine, String zoneName) { for (GridServiceContainer gsc : machine.getGridServiceContainers()) { Map<String, Zone> gscZones = gsc.getZones(); if (gscZones.isEmpty() || !gscZones.containsKey(zoneName)) { return false; // GSC either has no zone or is of another zone } } return true; } private boolean reachedMaxCapacity() { return puCapacityPlanner.getNumberOfGSCsInZone() >= puCapacityPlanner.getMaxNumberOfGSCs(); } private boolean aboveMinCapcity() { return puCapacityPlanner.getNumberOfGSCsInZone() >= puCapacityPlanner.getMinNumberOfGSCs(); } // due to timing delays, a machine might have an empty GSC - don't start a GSC on it private boolean machineHasAnEmptyGSC(ZoneCorrelator zoneCorrelator, Machine machine) { List<GridServiceContainer> list = zoneCorrelator.getGridServiceContainersByMachine(machine); for (GridServiceContainer gscOnMachine : list) { if (gscOnMachine.getProcessingUnitInstances().length == 0) { return true; } } return false; } //if machine does not have an agent, it can't be used to start a new GSC private boolean machineHasAnAgent(Machine machine) { GridServiceAgent agent = machine.getGridServiceAgent(); return (agent != null); } // machine has enough memory to start a new GSC private boolean hasEnoughMemoryForNewGSC(Machine machine) { double totalPhysicalMemorySizeInMB = machine.getOperatingSystem() .getDetails() .getTotalPhysicalMemorySizeInMB(); int jvmSizeInMB = MemorySettings.valueOf(puCapacityPlanner.getMaxJavaHeapSize()).toMB(); int numberOfGSCsScaleLimit = (int) Math.floor(totalPhysicalMemorySizeInMB / jvmSizeInMB); int freePhysicalMemorySizeInMB = (int) Math.floor(machine.getOperatingSystem() .getStatistics() .getFreePhysicalMemorySizeInMB()); // Check according to the calculated limit, but also check that the physical memory is // enough return (machine.getGridServiceContainers().getSize() < numberOfGSCsScaleLimit && jvmSizeInMB < (freePhysicalMemorySizeInMB - memorySafetyBufferInMB)); } private void startGscOnMachine(Machine machine) { logger.info("Scaling up - Starting GSC on machine ["+ToStringHelper.machineToString(machine)+"]"); GridServiceContainerOptions vmInputArgument = new GridServiceContainerOptions() .vmInputArgument("-Xms" + puCapacityPlanner.getInitJavaHeapSize()) .vmInputArgument("-Xmx" + puCapacityPlanner.getMaxJavaHeapSize()) .vmInputArgument("-Dcom.gs.zones=" + puCapacityPlanner.getZoneName()) .vmInputArgument("-Dcom.gigaspaces.grid.gsc.serviceLimit=" + puCapacityPlanner.getScalingFactor()); if (puCapacityPlanner.getVmArguments() != null) { String[] vmArguments = puCapacityPlanner.getVmArguments().split(","); for (String vmArgument : vmArguments) { vmInputArgument.vmInputArgument(vmArgument); } } GridServiceContainer newGSC = machine.getGridServiceAgent().startGridServiceAndWait( vmInputArgument , 60, TimeUnit.SECONDS); if (newGSC == null) { logger.warning("Failed Scaling up - Failed to start GSC on machine ["+ToStringHelper.machineToString(machine)+"]"); } else { workflow.breakWorkflow(); logger.info("Successfully started GSC ["+ToStringHelper.gscToString(newGSC)+"] on machine ["+ToStringHelper.machineToString(newGSC.getMachine())+"]"); } } } private class MemorySlaHandler implements Runnable { private final PuCapacityPlanner puCapacityPlanner; private final Workflow workflow; private final MemorySla memorySla; public MemorySlaHandler(PuCapacityPlanner puCapacityPlanner, Workflow workflow) { this.puCapacityPlanner = puCapacityPlanner; this.workflow = workflow; SlaExtractor slaExtractor = new SlaExtractor(puCapacityPlanner.getProcessingUnit()); memorySla = slaExtractor.getMemorySla(); } public boolean hasMemorySla() { return memorySla != null; } public void run() { if (!hasMemorySla()) return; logger.finest(MemorySlaHandler.class.getSimpleName() + " invoked"); handleBreachAboveThreshold(); if (!workflow.isBroken()) handleBreachBelowThreshold(); } public void handleBreachAboveThreshold() { /* * Go over GSCs, and gather GSCs above threshold */ List<GridServiceContainer> gscs = new ArrayList<GridServiceContainer>(); for (ProcessingUnitInstance puInstance : puCapacityPlanner.getProcessingUnit()) { GridServiceContainer gsc = puInstance.getGridServiceContainer(); if (!gscs.contains(gsc)) { gscs.add(gsc); } } List<GridServiceContainer> gscsWithBreach = new ArrayList<GridServiceContainer>(); for (GridServiceContainer gsc : gscs) { double memoryHeapUsedPerc = gsc.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); if (memoryHeapUsedPerc > memorySla.getThreshold()) { if (gsc.getProcessingUnitInstances().length == 1) { logger.warning("Can't amend GSC [" + ToStringHelper.gscToString(gsc) + "] - Memory [" + NUMBER_FORMAT.format(memoryHeapUsedPerc) + "%] breached threshold of [" + NUMBER_FORMAT.format(memorySla.getThreshold()) + "%]"); } else { logger.warning("GSC [" + ToStringHelper.gscToString(gsc) + "] - Memory [" + NUMBER_FORMAT.format(memoryHeapUsedPerc) + "%] breached threshold of [" + NUMBER_FORMAT.format(memorySla.getThreshold()) + "%]"); gscsWithBreach.add(gsc); } } } //nothing to do if (gscsWithBreach.isEmpty()) { return; } //sort from high to low Collections.sort(gscsWithBreach, new Comparator<GridServiceContainer>() { public int compare(GridServiceContainer gsc1, GridServiceContainer gsc2) { double memoryHeapUsedPerc1 = gsc1.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); double memoryHeapUsedPerc2 = gsc2.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); return (int)(memoryHeapUsedPerc2 - memoryHeapUsedPerc1); } }); ProcessingUnit pu = puCapacityPlanner.getProcessingUnit(); ZoneCorrelator zoneCorrelator = new ZoneCorrelator(admin, puCapacityPlanner.getZoneName()); for (GridServiceContainer gsc : gscsWithBreach) { logger.finer("GSC ["+ToStringHelper.gscToString(gsc)+"] has ["+gsc.getProcessingUnitInstances().length+"] processing unit instances"); for (ProcessingUnitInstance puInstanceToMaybeRelocate : gsc.getProcessingUnitInstances()) { int estimatedMemoryHeapUsedPercPerInstance = getEstimatedMemoryHeapUsedPercPerInstance(gsc, puInstanceToMaybeRelocate); logger.finer("Finding GSC that can hold [" + ToStringHelper.puInstanceToString(puInstanceToMaybeRelocate) + "] with an estimate of [" + NUMBER_FORMAT.format(estimatedMemoryHeapUsedPercPerInstance) + "%]"); List<GridServiceContainer> gscsInZone = zoneCorrelator.getGridServiceContainers(); //sort from low to high Collections.sort(gscsInZone, new Comparator<GridServiceContainer>() { public int compare(GridServiceContainer gsc1, GridServiceContainer gsc2) { double memoryHeapUsedPerc1 = gsc1.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); double memoryHeapUsedPerc2 = gsc2.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); return (int)(memoryHeapUsedPerc1 - memoryHeapUsedPerc2); } }); for (GridServiceContainer gscToRelocateTo : gscsInZone) { //if gsc is the same gsc as the pu instance we are handling - skip it if (gscToRelocateTo.equals(puInstanceToMaybeRelocate.getGridServiceContainer())) { continue; } //if gsc reached its scale limit (of processing units) then skip it if (!(gscToRelocateTo.getProcessingUnitInstances().length < puCapacityPlanner.getScalingFactor())) { logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - reached the scale limit"); continue; //can't use this GSC to scale } int memoryHeapUsedByThisGsc = (int)Math.ceil(gscToRelocateTo.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc()); if (memoryHeapUsedByThisGsc + estimatedMemoryHeapUsedPercPerInstance > memorySla.getThreshold()) { logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - memory used ["+NUMBER_FORMAT.format(memoryHeapUsedByThisGsc)+"%]"); continue; } // if GSC on same machine, no need to check for co-location constraints // since these were already checked when instance was instantiated if (!gscToRelocateTo.getMachine().equals(puInstanceToMaybeRelocate.getMachine())) { //TODO add max-instances-per-vm and max-instances-per-zone if necessary //verify max instances per machine if (pu.getMaxInstancesPerMachine() > 0) { int instancesOnMachine = 0; for (ProcessingUnitInstance instance : puInstanceToMaybeRelocate.getPartition().getInstances()) { if (instance.getMachine().equals(gscToRelocateTo.getMachine())) { ++instancesOnMachine; } } if (instancesOnMachine >= pu.getMaxInstancesPerMachine()) { logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - reached max-instances-per-machine limit"); continue; //reached limit } } } //precaution - if we are about to relocate make sure there is a backup in a partition-sync2backup topology. if (puInstanceToMaybeRelocate.getProcessingUnit().getNumberOfBackups() > 0) { ProcessingUnitInstance backup = puInstanceToMaybeRelocate.getPartition().getBackup(); if (backup == null) { logger.finest("No backup found for instance : " +ToStringHelper.puInstanceToString(puInstanceToMaybeRelocate)); return; } } logger.finer("Found GSC [" + ToStringHelper.gscToString(gscToRelocateTo) + "] which has only ["+NUMBER_FORMAT.format(memoryHeapUsedByThisGsc)+"%] used."); logger.finer("Relocating ["+ToStringHelper.puInstanceToString(puInstanceToMaybeRelocate)+"] to GSC [" + ToStringHelper.gscToString(gscToRelocateTo) + "]"); puInstanceToMaybeRelocate.relocateAndWait(gscToRelocateTo, 60, TimeUnit.SECONDS); workflow.breakWorkflow(); return; //found a gsc } } } logger.finest("Needs to scale up/out to obey memory SLA"); workflow.breakWorkflow(); workflow.add(new StartGscHandler(puCapacityPlanner, workflow)); } public void handleBreachBelowThreshold() { //handle only if deployment is intact if (!puCapacityPlanner.getProcessingUnit().getStatus().equals(DeploymentStatus.INTACT)) { return; } /* * Go over GSCs, and gather GSCs below threshold */ List<GridServiceContainer> gscs = new ArrayList<GridServiceContainer>(); for (ProcessingUnitInstance puInstance : puCapacityPlanner.getProcessingUnit()) { GridServiceContainer gsc = puInstance.getGridServiceContainer(); if (!gscs.contains(gsc)) { gscs.add(gsc); } } List<GridServiceContainer> gscsWithoutBreach = new ArrayList<GridServiceContainer>(); for (GridServiceContainer gsc : gscs) { double memoryHeapUsedPerc = gsc.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); if (memoryHeapUsedPerc < memorySla.getThreshold() && gsc.getProcessingUnitInstances().length == 1) { logger.finest("GSC [" + ToStringHelper.gscToString(gsc) + "] - Memory [" + NUMBER_FORMAT.format(memoryHeapUsedPerc) + "%] is below threshold of [" + NUMBER_FORMAT.format(memorySla.getThreshold()) + "%]"); gscsWithoutBreach.add(gsc); } } //nothing to do if (gscsWithoutBreach.isEmpty()) { return; } //sort from low to high Collections.sort(gscsWithoutBreach, new Comparator<GridServiceContainer>() { public int compare(GridServiceContainer gsc1, GridServiceContainer gsc2) { double memoryHeapUsedPerc1 = gsc1.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); double memoryHeapUsedPerc2 = gsc2.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); return (int)(memoryHeapUsedPerc1 - memoryHeapUsedPerc2); } }); ProcessingUnit pu = puCapacityPlanner.getProcessingUnit(); ZoneCorrelator zoneCorrelator = new ZoneCorrelator(admin, puCapacityPlanner.getZoneName()); for (GridServiceContainer gsc : gscsWithoutBreach) { if (gsc.getProcessingUnitInstances().length > 1) { continue; } for (ProcessingUnitInstance puInstanceToMaybeRelocate : gsc.getProcessingUnitInstances()) { int estimatedMemoryHeapUsedInMB = (int)Math.ceil(gsc.getVirtualMachine().getStatistics().getMemoryHeapUsedInMB()); int estimatedMemoryHeapUsedPerc = (int)Math.ceil(gsc.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc()); //getEstimatedMemoryHeapUsedPercPerInstance(gsc, puInstanceToMaybeRelocate); logger.finer("Finding GSC that can hold [" + ToStringHelper.puInstanceToString(puInstanceToMaybeRelocate) + "] with [" + NUMBER_FORMAT.format(estimatedMemoryHeapUsedPerc) + "%]"); List<GridServiceContainer> gscsInZone = zoneCorrelator.getGridServiceContainers(); //sort from low to high Collections.sort(gscsInZone, new Comparator<GridServiceContainer>() { public int compare(GridServiceContainer gsc1, GridServiceContainer gsc2) { double memoryHeapUsedPerc1 = gsc1.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); double memoryHeapUsedPerc2 = gsc2.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); return (int)(memoryHeapUsedPerc1 - memoryHeapUsedPerc2); } }); for (GridServiceContainer gscToRelocateTo : gscsInZone) { //if gsc is the same gsc as the pu instance we are handling - skip it if (gscToRelocateTo.equals(puInstanceToMaybeRelocate.getGridServiceContainer())) { //logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - same GSC as this instance"); continue; } //if gsc reached its scale limit (of processing units) then skip it if (!(gscToRelocateTo.getProcessingUnitInstances().length < puCapacityPlanner.getScalingFactor())) { logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - reached the scale limit"); continue; //can't use this GSC to scale } int memoryHeapUsedPercByThisGsc = (int)Math.ceil(gscToRelocateTo.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc()); int memoryRequiredInPerc = memoryHeapUsedPercByThisGsc + estimatedMemoryHeapUsedPerc; if (memoryRequiredInPerc > memorySla.getThreshold()) { logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - memory used ["+NUMBER_FORMAT.format(memoryHeapUsedPercByThisGsc)+"%]" + " - required ["+ memoryRequiredInPerc+"%] exceeds threshold of ["+memorySla.getThreshold()+"%]"); continue; } int memoryHeapUsedInMB = (int)Math.ceil(gscToRelocateTo.getVirtualMachine().getStatistics().getMemoryHeapUsedInMB()); int memoryRequiredInMB = memoryHeapUsedInMB+estimatedMemoryHeapUsedInMB+memorySafetyBufferInMB; int memorySlaThresholdInMB = (int)Math.ceil((100.0-memorySla.getThreshold())*gscToRelocateTo.getVirtualMachine().getDetails().getMemoryHeapMaxInMB()/100); if (memoryRequiredInMB > memorySlaThresholdInMB) { logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - required ["+NUMBER_FORMAT.format(memoryRequiredInMB)+" MB] exceeds threshold of ["+memorySlaThresholdInMB+" MB]"); continue; } // if GSC on same machine, no need to check for co-location constraints // since these were already checked when instance was instantiated if (!gscToRelocateTo.getMachine().equals(puInstanceToMaybeRelocate.getMachine())) { //TODO add max-instances-per-vm and max-instances-per-zone if necessary //verify max instances per machine if (pu.getMaxInstancesPerMachine() > 0) { int instancesOnMachine = 0; for (ProcessingUnitInstance instance : puInstanceToMaybeRelocate.getPartition().getInstances()) { if (instance.getMachine().equals(gscToRelocateTo.getMachine())) { ++instancesOnMachine; } } if (instancesOnMachine >= pu.getMaxInstancesPerMachine()) { logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - reached max-instances-per-machine limit"); continue; //reached limit } } } logger.finer("Found GSC [" + ToStringHelper.gscToString(gscToRelocateTo) + "] which has only ["+NUMBER_FORMAT.format(memoryHeapUsedPercByThisGsc)+"%] used."); logger.finer("Relocating ["+ToStringHelper.puInstanceToString(puInstanceToMaybeRelocate)+"] to GSC [" + ToStringHelper.gscToString(gscToRelocateTo) + "]"); puInstanceToMaybeRelocate.relocateAndWait(gscToRelocateTo, 60, TimeUnit.SECONDS); workflow.breakWorkflow(); return; } } } return; } private int getEstimatedMemoryHeapUsedPercPerInstance(GridServiceContainer gsc, ProcessingUnitInstance puInstance) { int totalPuNumOfObjects = 0; int thisPuNumOfObjects = 0; for (ProcessingUnitInstance aPuInstance : gsc.getProcessingUnitInstances()) { try { IJSpace space = aPuInstance.getSpaceInstance().getGigaSpace().getSpace(); SpaceRuntimeInfo runtimeInfo = ((IRemoteJSpaceAdmin)space.getAdmin()).getRuntimeInfo(); Integer numOfEntries = runtimeInfo.m_NumOFEntries.isEmpty() ? 0 : runtimeInfo.m_NumOFEntries.get(0); Integer numOfTemplates = runtimeInfo.m_NumOFTemplates.isEmpty() ? 0 : runtimeInfo.m_NumOFTemplates.get(0); int nObjects = numOfEntries + numOfTemplates; totalPuNumOfObjects += nObjects; if (aPuInstance.equals(puInstance)) { thisPuNumOfObjects = nObjects; } }catch(Exception e) { e.printStackTrace(); } } double memoryHeapUsed = gsc.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); int estimatedMemoryHeapUsedPerc = 0; if (thisPuNumOfObjects == 0) { if (totalPuNumOfObjects == 0) { estimatedMemoryHeapUsedPerc = (int)Math.ceil(memoryHeapUsed/gsc.getProcessingUnitInstances().length); } else { estimatedMemoryHeapUsedPerc = (int)Math.ceil(memoryHeapUsed/totalPuNumOfObjects); } } else { estimatedMemoryHeapUsedPerc = (int)Math.ceil((thisPuNumOfObjects * memoryHeapUsed)/totalPuNumOfObjects); } return estimatedMemoryHeapUsedPerc; } } private class RebalancerHandler implements Runnable { private final PuCapacityPlanner puCapacityPlanner; private final Workflow workflow; public RebalancerHandler(PuCapacityPlanner puCapacityPlanner, Workflow workflow) { this.puCapacityPlanner = puCapacityPlanner; this.workflow = workflow; } public void run() { if (!puCapacityPlanner.getProcessingUnit().getStatus().equals(DeploymentStatus.INTACT)) { return; } logger.finest(RebalancerHandler.class.getSimpleName() + " invoked"); List<Machine> machinesSortedByNumOfPrimaries = getMachinesSortedByNumPrimaries(puCapacityPlanner); Machine firstMachine = machinesSortedByNumOfPrimaries.get(0); int optimalNumberOfPrimariesPerMachine = (int)Math.ceil(1.0*puCapacityPlanner.getProcessingUnit().getNumberOfInstances() / puCapacityPlanner.getNumberOfMachinesInZone()); int numPrimariesOnMachine = getNumPrimariesOnMachine(puCapacityPlanner, firstMachine); logger.finest("Rebalancer - Expects " + optimalNumberOfPrimariesPerMachine + " primaries per machine"); if (numPrimariesOnMachine > optimalNumberOfPrimariesPerMachine) { logger.finest("Rebalancer - Machine [" + ToStringHelper.machineToString(firstMachine) + " has: " + numPrimariesOnMachine + " - rebalancing..."); findPrimaryProcessingUnitToRestart(puCapacityPlanner, machinesSortedByNumOfPrimaries); } else { logger.finest("Rebalancer - Machines are balanced"); } } private List<Machine> getMachinesSortedByNumPrimaries(final PuCapacityPlanner puCapacityPlanner) { String zoneName = puCapacityPlanner.getZoneName(); Zone zone = admin.getZones().getByName(zoneName); List<GridServiceContainer> gscList = Arrays.asList(zone.getGridServiceContainers().getContainers()); List<Machine> machinesInZone = new ArrayList<Machine>(); for (GridServiceContainer gsc : gscList) { if (!machinesInZone.contains(gsc.getMachine())) machinesInZone.add(gsc.getMachine()); } Collections.sort(machinesInZone, new Comparator<Machine>() { public int compare(Machine m1, Machine m2) { return getNumPrimariesOnMachine(puCapacityPlanner, m2) - getNumPrimariesOnMachine(puCapacityPlanner, m1); } }); return machinesInZone; } private int getNumPrimariesOnMachine(PuCapacityPlanner puCapacityPlanner, Machine machine) { String zoneName = puCapacityPlanner.getZoneName(); Zone zone = admin.getZones().getByName(zoneName); int numPrimaries = 0; ProcessingUnitInstance[] instances = zone.getProcessingUnitInstances(); for (ProcessingUnitInstance instance : instances) { if (!instance.getMachine().equals(machine)) { continue; } if (isPrimary(instance)) { numPrimaries++; } } return numPrimaries; } private boolean isPrimary(ProcessingUnitInstance instance) { SpaceInstance spaceInstance = instance.getSpaceInstance(); return (spaceInstance != null && spaceInstance.getMode().equals(SpaceMode.PRIMARY)); } //find primary processing unit that it's backup is on a machine with the least number of primaries and restart it private void findPrimaryProcessingUnitToRestart(PuCapacityPlanner puCapacityPlanner, List<Machine> machinesSortedByNumOfPrimaries) { Machine lastMachine = machinesSortedByNumOfPrimaries.get(machinesSortedByNumOfPrimaries.size() -1); for (Machine machine : machinesSortedByNumOfPrimaries) { List<GridServiceContainer> gscsSortedByNumPrimaries = getGscsSortedByNumPrimaries(puCapacityPlanner, machine); for (GridServiceContainer gsc : gscsSortedByNumPrimaries) { for (ProcessingUnitInstance puInstance : gsc.getProcessingUnitInstances()) { if (isPrimary(puInstance)) { ProcessingUnitInstance backup = puInstance.getPartition().getBackup(); if (backup == null) { logger.finest("---> no backup found for instance : " +ToStringHelper.puInstanceToString(puInstance)); return; //something is wrong, wait for next reschedule } GridServiceContainer backupGsc = backup.getGridServiceContainer(); if (backupGsc.getMachine().equals(lastMachine)) { restartPrimaryInstance(puInstance); return; } } } } } } private List<GridServiceContainer> getGscsSortedByNumPrimaries(PuCapacityPlanner puCapacityPlanner, Machine machine) { String zoneName = puCapacityPlanner.getZoneName(); Zone zone = admin.getZones().getByName(zoneName); //extract only gscs within this machine which belong to this zone List<GridServiceContainer> gscList = new ArrayList<GridServiceContainer>(); for (GridServiceContainer gsc : zone.getGridServiceContainers().getContainers()) { if (gsc.getMachine().equals(machine)) { gscList.add(gsc); } } Collections.sort(gscList, new Comparator<GridServiceContainer>() { public int compare(GridServiceContainer gsc1, GridServiceContainer gsc2) { int puDiff = getNumPrimaries(gsc2) - getNumPrimaries(gsc1); return puDiff; } }); return gscList; } private int getNumPrimaries(GridServiceContainer gsc) { int numPrimaries = 0; ProcessingUnitInstance[] instances = gsc.getProcessingUnitInstances(); for (ProcessingUnitInstance instance : instances) { if (isPrimary(instance)) { numPrimaries++; } } return numPrimaries; } private void restartPrimaryInstance(ProcessingUnitInstance instance) { //Perquisite precaution - can happen if state changed if (!instance.getProcessingUnit().getStatus().equals(DeploymentStatus.INTACT)) { return; } logger.finest("Restarting instance " + ToStringHelper.puInstanceToString(instance) + " at GSC " + ToStringHelper.gscToString(instance.getGridServiceContainer())); ProcessingUnitInstance restartedInstance = instance.restartAndWait(); workflow.breakWorkflow(); boolean isBackup = restartedInstance.waitForSpaceInstance().waitForMode(SpaceMode.BACKUP, 10, TimeUnit.SECONDS); if (!isBackup) { logger.finest("Waited 10 seconds, instance " + ToStringHelper.puInstanceToString(instance) + " still not registered as backup"); return; } logger.finest("Done restarting instance " + ToStringHelper.puInstanceToString(instance)); } } private class GscCollectorHandler implements Runnable { private final PuCapacityPlanner puCapacityPlanner; private final Workflow workflow; public GscCollectorHandler(PuCapacityPlanner puCapacityPlanner, Workflow workflow) { this.puCapacityPlanner = puCapacityPlanner; this.workflow = workflow; } public void run() { //Perquisite precaution if (!puCapacityPlanner.getProcessingUnit().getStatus().equals(DeploymentStatus.INTACT)) { return; } logger.finest(GscCollectorHandler.class.getSimpleName() + " invoked"); String zoneName = puCapacityPlanner.getZoneName(); Zone zone = admin.getZones().getByName(zoneName); if (zone == null) return; for (GridServiceContainer gsc : zone.getGridServiceContainers()) { if (gsc.getProcessingUnitInstances().length == 0) { logger.info("Scaling down - Terminate empty GSC ["+ToStringHelper.gscToString(gsc)+"]"); gsc.kill(); workflow.breakWorkflow(); } if (gsc.getMachine().getGridServiceContainers().getSize() == 0) { logger.info("Scaling in - No need for machine ["+ToStringHelper.machineToString(gsc.getMachine())+"]"); puCapacityPlanner.getElasticScale().scaleIn(gsc.getMachine()); } } } } private class UndeployHandler implements Runnable { private final PuCapacityPlanner puCapacityPlanner; public UndeployHandler(PuCapacityPlanner puCapacityPlanner) { this.puCapacityPlanner = puCapacityPlanner; } public void run() { //Perquisite precaution //TODO due to bug in status, postpone this check // if (!puCapacityPlanner.getProcessingUnit().getStatus().equals(DeploymentStatus.UNDEPLOYED)) { // return; logger.finest(UndeployHandler.class.getSimpleName() + " invoked"); elasticScaleMap.remove(puCapacityPlanner.getProcessingUnit().getName()); String zoneName = puCapacityPlanner.getZoneName(); Zone zone = admin.getZones().getByName(zoneName); if (zone == null) return; for (GridServiceContainer gsc : zone.getGridServiceContainers()) { int gscsOnMachine = gsc.getMachine().getGridServiceContainers().getSize(); if (gsc.getProcessingUnitInstances().length == 0) { logger.info("Scaling down - Terminate empty GSC ["+ToStringHelper.gscToString(gsc)+"]"); gsc.kill(); gscsOnMachine } if (gscsOnMachine == 0) { logger.info("Scaling in - No need for machine ["+ToStringHelper.machineToString(gsc.getMachine())+"]"); puCapacityPlanner.getElasticScale().scaleIn(gsc.getMachine()); } } } } private final class CompromisedDeploymentHandler implements Runnable { private final PuCapacityPlanner puCapacityPlanner; private final Workflow workflow; public CompromisedDeploymentHandler(PuCapacityPlanner puCapacityPlanner, Workflow workflow) { this.puCapacityPlanner = puCapacityPlanner; this.workflow = workflow; } public void run() { if (deploymentStatusCompromised()) { logger.finest(CompromisedDeploymentHandler.class.getSimpleName() + " invoked"); workflow.breakWorkflow(); workflow.add(new StartGscHandler(puCapacityPlanner, workflow)); } } private boolean deploymentStatusCompromised() { DeploymentStatus status = puCapacityPlanner.getProcessingUnit().getStatus(); return DeploymentStatus.BROKEN.equals(status) || DeploymentStatus.COMPROMISED.equals(status); } } }
package net.tomp2p.rpc; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.SortedMap; import java.util.concurrent.atomic.AtomicInteger; import net.tomp2p.Utils2; import net.tomp2p.connection.ChannelCreator; import net.tomp2p.connection.ChannelServerConficuration; import net.tomp2p.connection.Ports; import net.tomp2p.futures.FutureChannelCreator; import net.tomp2p.futures.FutureResponse; import net.tomp2p.message.DataMap; import net.tomp2p.message.KeyMapByte; import net.tomp2p.message.Message; import net.tomp2p.p2p.Peer; import net.tomp2p.p2p.PeerMaker; import net.tomp2p.p2p.Replication; import net.tomp2p.p2p.ResponsibilityListener; import net.tomp2p.p2p.builder.AddBuilder; import net.tomp2p.p2p.builder.DigestBuilder; import net.tomp2p.p2p.builder.GetBuilder; import net.tomp2p.p2p.builder.PutBuilder; import net.tomp2p.p2p.builder.RemoveBuilder; import net.tomp2p.peers.Number160; import net.tomp2p.peers.Number320; import net.tomp2p.peers.Number640; import net.tomp2p.peers.PeerAddress; import net.tomp2p.peers.PeerStatusListener.FailReason; import net.tomp2p.storage.Data; //import net.tomp2p.storage.StorageDisk; import net.tomp2p.storage.StorageLayer; import net.tomp2p.storage.StorageMemory; import net.tomp2p.storage.StorageMemoryReplication; import net.tomp2p.storage.StorageMemoryReplicationNRoot; import net.tomp2p.utils.Timings; import net.tomp2p.utils.Utils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; public class TestStorage { final private static Number160 domainKey = new Number160(20); private static String DIR1; private static String DIR2; @Before public void before() throws IOException { DIR1 = Utils2.createTempDirectory().getCanonicalPath(); DIR2 = Utils2.createTempDirectory().getCanonicalPath(); } @After public void after() { cleanUp(DIR1); cleanUp(DIR2); } private void cleanUp(String dir) { File f = new File(dir); f.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.isFile()) pathname.delete(); return false; } }); f.delete(); } @Test public void testAdd() throws Exception { StorageMemory storeSender = new StorageMemory(); StorageMemory storeRecv = new StorageMemory(); Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { sender = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424).makeAndListen(); recv1 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088).makeAndListen(); sender.getPeerBean().storage(new StorageLayer(storeSender)); StorageRPC smmSender = new StorageRPC(sender.getPeerBean(), sender.getConnectionBean()); recv1.getPeerBean().storage(new StorageLayer(storeRecv)); new StorageRPC(recv1.getPeerBean(), recv1.getConnectionBean()); FutureChannelCreator fcc = recv1.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); Collection<Data> dataSet = new HashSet<Data>(); dataSet.add(new Data(1)); AddBuilder addBuilder = new AddBuilder(recv1, new Number160(33)); addBuilder.setDomainKey(Number160.createHash("test")); addBuilder.setDataSet(dataSet); addBuilder.setVersionKey(Number160.ZERO); // addBuilder.setList(); // addBuilder.random(new Random(42)); FutureResponse fr = smmSender.add(recv1.getPeerAddress(), addBuilder, cc); fr.awaitUninterruptibly(); System.err.println(fr.getFailedReason()); Assert.assertEquals(true, fr.isSuccess()); // add a the same data twice fr = smmSender.add(recv1.getPeerAddress(), addBuilder, cc); fr.awaitUninterruptibly(); System.err.println(fr.getFailedReason()); Assert.assertEquals(true, fr.isSuccess()); Number320 key = new Number320(new Number160(33), Number160.createHash("test")); // Set<Number480> tofetch = new HashSet<Number480>(); Number640 from = new Number640(key, Number160.ZERO, Number160.ZERO); Number640 to = new Number640(key, Number160.MAX_VALUE, Number160.MAX_VALUE); SortedMap<Number640, Data> c = storeRecv.subMap(from, to, -1, true); Assert.assertEquals(1, c.size()); for (Data data : c.values()) { Assert.assertEquals((Integer) 1, (Integer) data.object()); } // now add again, but as a list addBuilder.setList(); addBuilder.random(new Random(42)); fr = smmSender.add(recv1.getPeerAddress(), addBuilder, cc); fr.awaitUninterruptibly(); System.err.println(fr.getFailedReason()); Assert.assertEquals(true, fr.isSuccess()); key = new Number320(new Number160(33), Number160.createHash("test")); // Set<Number480> tofetch = new HashSet<Number480>(); from = new Number640(key, Number160.ZERO, Number160.ZERO); to = new Number640(key, Number160.MAX_VALUE, Number160.MAX_VALUE); c = storeRecv.subMap(from, to, -1, true); Assert.assertEquals(2, c.size()); for (Data data : c.values()) { Assert.assertEquals((Integer) 1, (Integer) data.object()); } } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test public void testStorePut() throws Exception { StorageMemory storeSender = new StorageMemory(); StorageMemory storeRecv = new StorageMemory(); Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { sender = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424).makeAndListen(); recv1 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088).makeAndListen(); sender.getPeerBean().storage(new StorageLayer(storeSender)); StorageRPC smmSender = new StorageRPC(sender.getPeerBean(), sender.getConnectionBean()); recv1.getPeerBean().storage(new StorageLayer(storeRecv)); new StorageRPC(recv1.getPeerBean(), recv1.getConnectionBean()); Map<Number160, Data> tmp = new HashMap<Number160, Data>(); byte[] me1 = new byte[] { 1, 2, 3 }; byte[] me2 = new byte[] { 2, 3, 4 }; Data test = new Data(me1); Data test2 = new Data(me2); tmp.put(new Number160(77), test); tmp.put(new Number160(88), test2); System.err.println(recv1.getPeerAddress()); FutureChannelCreator fcc = recv1.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); PutBuilder putBuilder = new PutBuilder(recv1, new Number160(33)); putBuilder.setDomainKey(Number160.createHash("test")); putBuilder.setVersionKey(Number160.ZERO); putBuilder.setDataMapContent(tmp); putBuilder.setVersionKey(Number160.ZERO); FutureResponse fr = smmSender.put(recv1.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); System.err.println(fr.getFailedReason()); Assert.assertEquals(true, fr.isSuccess()); Number640 key1 = new Number640(new Number160(33), Number160.createHash("test"), new Number160(77), Number160.ZERO); Data c = storeRecv.get(key1); Assert.assertEquals(test, c); //Thread.sleep(10000000); tmp.clear(); me1 = new byte[] { 5, 6, 7 }; me2 = new byte[] { 8, 9, 1, 5 }; test = new Data(me1); test2 = new Data(me2); tmp.put(new Number160(77), test); tmp.put(new Number160(88), test2); putBuilder.setDataMapContent(tmp); fr = smmSender.put(recv1.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); System.err.println(fr.getFailedReason()); Assert.assertEquals(true, fr.isSuccess()); Map<Number640, Data> result2 = storeRecv.subMap(key1.minContentKey(), key1.maxContentKey(), -1, true); Assert.assertEquals(result2.size(), 2); //Number480 search = new Number480(key, new Number160(88)); Number640 key2 = new Number640(new Number160(33), Number160.createHash("test"), new Number160(88), Number160.ZERO); c = result2.get(key2); Assert.assertEquals(c, test2); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test public void testStorePutIfAbsent() throws Exception { StorageMemory storeSender = new StorageMemory(); StorageMemory storeRecv = new StorageMemory(); Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { sender = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424).makeAndListen(); recv1 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088).makeAndListen(); sender.getPeerBean().storage(new StorageLayer(storeSender)); StorageRPC smmSender = new StorageRPC(sender.getPeerBean(), sender.getConnectionBean()); recv1.getPeerBean().storage(new StorageLayer(storeRecv)); new StorageRPC(recv1.getPeerBean(), recv1.getConnectionBean()); Map<Number160, Data> tmp = new HashMap<Number160, Data>(); byte[] me1 = new byte[] { 1, 2, 3 }; byte[] me2 = new byte[] { 2, 3, 4 }; Data test = new Data(me1); Data test2 = new Data(me2); tmp.put(new Number160(77), test); tmp.put(new Number160(88), test2); FutureChannelCreator fcc = recv1.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); PutBuilder putBuilder = new PutBuilder(recv1, new Number160(33)); putBuilder.setDomainKey(Number160.createHash("test")); putBuilder.setDataMapContent(tmp); putBuilder.setVersionKey(Number160.ZERO); //putBuilder.set FutureResponse fr = smmSender.put(recv1.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); Assert.assertEquals(true, fr.isSuccess()); Number640 key = new Number640(new Number160(33), Number160.createHash("test"), new Number160(77), Number160.ZERO); Data c = storeRecv.get(key); Assert.assertEquals(c, test); tmp.clear(); byte[] me3 = new byte[] { 5, 6, 7 }; byte[] me4 = new byte[] { 8, 9, 1, 5 }; tmp.put(new Number160(77), new Data(me3)); tmp.put(new Number160(88), new Data(me4)); putBuilder.setPutIfAbsent(); fr = smmSender.putIfAbsent(recv1.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); // we cannot put anything there, since there already is Assert.assertEquals(true, fr.isSuccess()); Map<Number640, Byte> putKeys = fr.getResponse().getKeyMapByte(0).keysMap(); Assert.assertEquals(2, putKeys.size()); Assert.assertEquals(Byte.valueOf((byte)StorageLayer.PutStatus.FAILED_NOT_ABSENT.ordinal()), putKeys.values().iterator().next()); Number640 key2 = new Number640(new Number160(33), Number160.createHash("test"), new Number160(88), Number160.ZERO); c = storeRecv.get(key2); Assert.assertEquals(c, test2); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test public void testStorePutGetTCP() throws Exception { StorageMemory storeSender = new StorageMemory(); StorageMemory storeRecv = new StorageMemory(); Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { sender = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424).makeAndListen(); recv1 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088).makeAndListen(); sender.getPeerBean().storage(new StorageLayer(storeSender)); StorageRPC smmSender = new StorageRPC(sender.getPeerBean(), sender.getConnectionBean()); recv1.getPeerBean().storage(new StorageLayer(storeRecv)); new StorageRPC(recv1.getPeerBean(), recv1.getConnectionBean()); Map<Number160, Data> tmp = new HashMap<Number160, Data>(); byte[] me1 = new byte[] { 1, 2, 3 }; byte[] me2 = new byte[] { 2, 3, 4 }; tmp.put(new Number160(77), new Data(me1)); tmp.put(new Number160(88), new Data(me2)); FutureChannelCreator fcc = recv1.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); PutBuilder putBuilder = new PutBuilder(recv1, new Number160(33)); putBuilder.setDomainKey(Number160.createHash("test")); DataMap dataMap = new DataMap(new Number160(33), Number160.createHash("test"), Number160.ZERO, tmp); putBuilder.setDataMapContent(tmp); putBuilder.setVersionKey(Number160.ZERO); FutureResponse fr = smmSender.put(recv1.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); // get GetBuilder getBuilder = new GetBuilder(recv1, new Number160(33)); getBuilder.setDomainKey(Number160.createHash("test")); getBuilder.contentKeys(tmp.keySet()); getBuilder.setVersionKey(Number160.ZERO); fr = smmSender.get(recv1.getPeerAddress(), getBuilder, cc); fr.awaitUninterruptibly(); Assert.assertEquals(true, fr.isSuccess()); System.err.println(fr.getFailedReason()); Message m = fr.getResponse(); Map<Number640, Data> stored = m.getDataMap(0).dataMap(); compare(dataMap.convertToMap640(), stored); System.err.println("done!"); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test public void testStorePutGetUDP() throws Exception { StorageMemory storeSender = new StorageMemory(); StorageMemory storeRecv = new StorageMemory(); Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { sender = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424).makeAndListen(); recv1 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088).makeAndListen(); sender.getPeerBean().storage(new StorageLayer(storeSender)); StorageRPC smmSender = new StorageRPC(sender.getPeerBean(), sender.getConnectionBean()); recv1.getPeerBean().storage(new StorageLayer(storeRecv)); new StorageRPC(recv1.getPeerBean(), recv1.getConnectionBean()); Map<Number160, Data> tmp = new HashMap<Number160, Data>(); byte[] me1 = new byte[] { 1, 2, 3 }; byte[] me2 = new byte[] { 2, 3, 4 }; tmp.put(new Number160(77), new Data(me1)); tmp.put(new Number160(88), new Data(me2)); FutureChannelCreator fcc = recv1.getConnectionBean().reservation().create(1, 0); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); PutBuilder putBuilder = new PutBuilder(recv1, new Number160(33)); putBuilder.setDomainKey(Number160.createHash("test")); DataMap dataMap = new DataMap(new Number160(33), Number160.createHash("test"), Number160.ZERO, tmp); putBuilder.setDataMapContent(tmp); putBuilder.setForceUDP(); putBuilder.setVersionKey(Number160.ZERO); FutureResponse fr = smmSender.put(recv1.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); Assert.assertEquals(true, fr.isSuccess()); GetBuilder getBuilder = new GetBuilder(recv1, new Number160(33)); getBuilder.setDomainKey(Number160.createHash("test")); getBuilder.contentKeys(tmp.keySet()); getBuilder.setForceUDP(); getBuilder.setVersionKey(Number160.ZERO); // get fr = smmSender.get(recv1.getPeerAddress(), getBuilder, cc); fr.awaitUninterruptibly(); Assert.assertEquals(true, fr.isSuccess()); Message m = fr.getResponse(); Map<Number640, Data> stored = m.getDataMap(0).dataMap(); compare(dataMap.convertToMap640(), stored); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } private void compare(Map<Number640, Data> tmp, Map<Number640, Data> stored) { Assert.assertEquals(tmp.size(), stored.size()); Iterator<Number640> iterator1 = tmp.keySet().iterator(); while (iterator1.hasNext()) { Number640 key1 = iterator1.next(); Assert.assertEquals(true, stored.containsKey(key1)); Data data1 = tmp.get(key1); Data data2 = stored.get(key1); Assert.assertEquals(data1, data2); } } @Test public void testStorePutRemoveGet() throws Exception { StorageMemory storeSender = new StorageMemory(); StorageMemory storeRecv = new StorageMemory(); Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { sender = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424).makeAndListen(); recv1 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088).makeAndListen(); sender.getPeerBean().storage(new StorageLayer(storeSender)); StorageRPC smmSender = new StorageRPC(sender.getPeerBean(), sender.getConnectionBean()); recv1.getPeerBean().storage(new StorageLayer(storeRecv)); new StorageRPC(recv1.getPeerBean(), recv1.getConnectionBean()); Map<Number160, Data> tmp = new HashMap<Number160, Data>(); byte[] me1 = new byte[] { 1, 2, 3 }; byte[] me2 = new byte[] { 2, 3, 4 }; tmp.put(new Number160(77), new Data(me1)); tmp.put(new Number160(88), new Data(me2)); FutureChannelCreator fcc = recv1.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); PutBuilder putBuilder = new PutBuilder(recv1, new Number160(33)); putBuilder.setDomainKey(Number160.createHash("test")); putBuilder.setDataMapContent(tmp); putBuilder.setVersionKey(Number160.ZERO); FutureResponse fr = smmSender.put(recv1.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); // remove RemoveBuilder removeBuilder = new RemoveBuilder(recv1, new Number160(33)); removeBuilder.setDomainKey(Number160.createHash("test")); removeBuilder.contentKeys(tmp.keySet()); removeBuilder.setReturnResults(); removeBuilder.setVersionKey(Number160.ZERO); fr = smmSender.remove(recv1.getPeerAddress(), removeBuilder, cc); fr.awaitUninterruptibly(); Message m = fr.getResponse(); Assert.assertEquals(true, fr.isSuccess()); // check for returned results Map<Number640, Data> stored = m.getDataMap(0).dataMap(); DataMap dataMap = new DataMap(new Number160(33), Number160.createHash("test"), Number160.ZERO, tmp); compare(dataMap.convertToMap640(), stored); // get GetBuilder getBuilder = new GetBuilder(recv1, new Number160(33)); getBuilder.setDomainKey(Number160.createHash("test")); getBuilder.contentKeys(tmp.keySet()); getBuilder.setVersionKey(Number160.ZERO); fr = smmSender.get(recv1.getPeerAddress(), getBuilder, cc); fr.awaitUninterruptibly(); Assert.assertEquals(true, fr.isSuccess()); m = fr.getResponse(); DataMap stored2 = m.getDataMap(0); Assert.assertEquals(0, stored2.size()); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test public void testBigStorePut() throws Exception { StorageMemory storeSender = new StorageMemory(); StorageMemory storeRecv = new StorageMemory(); Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { sender = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424).makeAndListen(); recv1 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088).makeAndListen(); sender.getPeerBean().storage(new StorageLayer(storeSender)); StorageRPC smmSender = new StorageRPC(sender.getPeerBean(), sender.getConnectionBean()); recv1.getPeerBean().storage(new StorageLayer(storeRecv)); new StorageRPC(recv1.getPeerBean(), recv1.getConnectionBean()); Map<Number160, Data> tmp = new HashMap<Number160, Data>(); byte[] me1 = new byte[100]; byte[] me2 = new byte[10000]; tmp.put(new Number160(77), new Data(me1)); tmp.put(new Number160(88), new Data(me2)); FutureChannelCreator fcc = recv1.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); PutBuilder putBuilder = new PutBuilder(recv1, new Number160(33)); putBuilder.setDomainKey(Number160.createHash("test")); DataMap dataMap = new DataMap(new Number160(33), Number160.createHash("test"), Number160.ZERO, tmp); putBuilder.setDataMapContent(tmp); putBuilder.setVersionKey(Number160.ZERO); FutureResponse fr = smmSender.put(recv1.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); Assert.assertEquals(true, fr.isSuccess()); KeyMapByte keys = fr.getResponse().getKeyMapByte(0); Utils.isSameSets(keys.keysMap().keySet(), dataMap.convertToMap640().keySet()); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test public void testConcurrentStoreAddGet() throws Exception { StorageMemory storeSender = new StorageMemory(); StorageMemory storeRecv = new StorageMemory(); Peer sender = null; Peer recv1 = null; try { sender = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424).makeAndListen(); recv1 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088).makeAndListen(); sender.getPeerBean().storage(new StorageLayer(storeSender)); final StorageRPC smmSender = new StorageRPC(sender.getPeerBean(), sender.getConnectionBean()); recv1.getPeerBean().storage(new StorageLayer(storeRecv)); new StorageRPC(recv1.getPeerBean(), recv1.getConnectionBean()); List<FutureResponse> res = new ArrayList<FutureResponse>(); for (int i = 0; i < 40; i++) { System.err.println("round " + i); FutureChannelCreator fcc = recv1.getConnectionBean().reservation().create(0, 10); fcc.awaitUninterruptibly(); ChannelCreator cc = fcc.getChannelCreator(); // final ChannelCreator // cc1=sender.getConnectionBean().getReservation().reserve(50); for (int j = 0; j < 10; j++) { FutureResponse fr = store(sender, recv1, smmSender, cc); res.add(fr); } // cc1.release(); for (FutureResponse fr : res) { fr.awaitUninterruptibly(); if (!fr.isSuccess()) { System.err.println("failed: " + fr.getFailedReason()); } Assert.assertEquals(true, fr.isSuccess()); } res.clear(); cc.shutdown().awaitListenersUninterruptibly(); } System.err.println("done."); } finally { if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } /** * Test the responsibility and the notifications. * * @throws Exception . */ @Test public void testResponsibility0Root1() throws Exception { // Random rnd=new Random(42L); Peer master = null; Peer slave = null; ChannelCreator cc = null; try { master = new PeerMaker(new Number160("0xee")).makeAndListen(); StorageMemory s1 = new StorageMemory(); master.getPeerBean().storage(new StorageLayer(s1)); final AtomicInteger test1 = new AtomicInteger(0); final AtomicInteger test2 = new AtomicInteger(0); final int replicatioFactor = 5; Replication replication = new Replication(s1, master.getPeerAddress(), master.getPeerBean() .peerMap(), replicatioFactor, false); replication.addResponsibilityListener(new ResponsibilityListener() { @Override public void otherResponsible(final Number160 locationKey, final PeerAddress other, final boolean delayed) { System.err.println("Other peer (" + other + ")is responsible for " + locationKey); test1.incrementAndGet(); } @Override public void meResponsible(final Number160 locationKey) { System.err.println("I'm responsible for " + locationKey + " / "); test2.incrementAndGet(); } @Override public void meResponsible(Number160 locationKey, PeerAddress newPeer) { System.err.println("I sync for " + locationKey + " / "); } }); master.getPeerBean().replicationStorage(replication); Number160 location = new Number160("0xff"); Map<Number160, Data> dataMap = new HashMap<Number160, Data>(); dataMap.put(Number160.ZERO, new Data("string")); FutureChannelCreator fcc = master.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); PutBuilder putBuilder = new PutBuilder(master, location); putBuilder.setDomainKey(location); putBuilder.setDataMapContent(dataMap); putBuilder.setVersionKey(Number160.ZERO); FutureResponse fr = master.getStoreRPC().put(master.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); // s1.put(location, Number160.ZERO, null, dataMap, false, false); final int slavePort = 7701; slave = new PeerMaker(new Number160("0xfe")).ports(slavePort).makeAndListen(); master.getPeerBean().peerMap().peerFound(slave.getPeerAddress(), null); master.getPeerBean().peerMap().peerFailed(slave.getPeerAddress(), FailReason.Shutdown); Assert.assertEquals(1, test1.get()); Assert.assertEquals(2, test2.get()); } catch (Throwable t) { t.printStackTrace(); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (master != null) { master.shutdown().await(); } if (slave != null) { slave.shutdown().await(); } } } /** * Test the responsibility and the notifications. * * @throws Exception . */ @Test public void testResponsibility0Root2() throws Exception { final Random rnd = new Random(42L); final int port = 8000; Peer master = null; Peer slave1 = null; Peer slave2 = null; ChannelCreator cc = null; try { Number160 loc = new Number160(rnd); Map<Number160, Data> contentMap = new HashMap<Number160, Data>(); contentMap.put(Number160.ZERO, new Data("string")); final AtomicInteger test1 = new AtomicInteger(0); final AtomicInteger test2 = new AtomicInteger(0); master = new PeerMaker(new Number160(rnd)).ports(port).makeAndListen(); System.err.println("master is " + master.getPeerAddress()); StorageMemory s1 = new StorageMemory(); master.getPeerBean().storage(new StorageLayer(s1)); final int replicatioFactor = 5; Replication replication = new Replication(s1, master.getPeerAddress(), master.getPeerBean() .peerMap(), replicatioFactor, false); replication.addResponsibilityListener(new ResponsibilityListener() { @Override public void otherResponsible(final Number160 locationKey, final PeerAddress other, final boolean delayed) { System.err.println("Other peer (" + other + ")is responsible for " + locationKey); test1.incrementAndGet(); } @Override public void meResponsible(final Number160 locationKey) { System.err.println("I'm responsible for " + locationKey); test2.incrementAndGet(); } @Override public void meResponsible(Number160 locationKey, PeerAddress newPeer) { System.err.println("I sync for " + locationKey + " / "); } }); master.getPeerBean().replicationStorage(replication); FutureChannelCreator fcc = master.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); PutBuilder putBuilder = new PutBuilder(master, loc); putBuilder.setDomainKey(domainKey); putBuilder.setDataMapContent(contentMap); putBuilder.setVersionKey(Number160.ZERO); master.getStoreRPC().put(master.getPeerAddress(), putBuilder, cc).awaitUninterruptibly(); slave1 = new PeerMaker(new Number160(rnd)).ports(port + 1).makeAndListen(); slave2 = new PeerMaker(new Number160(rnd)).ports(port + 2).makeAndListen(); System.err.println("slave1 is " + slave1.getPeerAddress()); System.err.println("slave2 is " + slave2.getPeerAddress()); // master peer learns about the slave peers master.getPeerBean().peerMap().peerFound(slave1.getPeerAddress(), null); master.getPeerBean().peerMap().peerFound(slave2.getPeerAddress(), null); System.err.println("both peers online"); PeerAddress slaveAddress1 = slave1.getPeerAddress(); slave1.shutdown().await(); master.getPeerBean().peerMap().peerFailed(slaveAddress1, FailReason.Shutdown); Assert.assertEquals(1, test1.get()); Assert.assertEquals(2, test2.get()); PeerAddress slaveAddress2 = slave2.getPeerAddress(); slave2.shutdown().await(); master.getPeerBean().peerMap().peerFailed(slaveAddress2, FailReason.Shutdown); Assert.assertEquals(1, test1.get()); Assert.assertEquals(3, test2.get()); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (master != null) { master.shutdown().await(); } } } /** * Test the responsibility and the notifications for the n-root replication * approach with replication factor 1. * * @throws Exception */ @Test public void testReplicationNRoot1() throws Exception { final int replicationFactor = 1; Number160 keyA = new Number160("0xa"); int[][] joinA = // as first node, node a is always replicating given key {{ 1, 0, 0 }, // node a is closer to key a than node b, node a doesn't have to notify // newly joined node b { 0, 0, 0 }, // node a is closer to key a than node c, node a doesn't have to notify // newly joined node c { 0, 0, 0 }, // node a is closer to key a than node d, node a doesn't have to notify // newly joined node d { 0, 0, 0 }}; int[][] leaveA = // node b leaves, node a has still to replicate key a {{ 0, 0, 0 }, // node c leaves, node a has still to replicate key a { 0, 0, 0 }, // node d leaves, node a has still to replicate key a { 0, 0, 0 }}; testReplication(keyA, replicationFactor, true, joinA, leaveA); Number160 keyB = new Number160("0xb"); int[][] expectedB = // as first node, node a is always replicating given key {{ 1, 0, 0 }, // node b is closer to key b than node a, node a has to notify newly // joined node b { 0, 0, 1 }, // node a has no replication responsibilities to check { 0, 0, 0 }, // node a has no replication responsibilities to check { 0, 0, 0 }}; int[][] leaveB = // node b leaves, node a has no replication responsibilities to check {{ 0, 0, 0 }, // node c leaves, node a has no replication responsibilities to check { 0, 0, 0 }, // node d leaves, node a has no replication responsibilities to check { 0, 0, 0 }}; testReplication(keyB, replicationFactor, true, expectedB, leaveB); Number160 keyC = new Number160("0xc"); int[][] expectedC = // as first node, node a is always replicating given key { { 1, 0, 0 }, // node a is closer to key c than node b, node a doesn't have to // notify newly joined node b { 0, 0, 0 }, // node c is closer to key c than node a, node a doesn't have to // replicate key c anymore, node a has to notify newly joined // node c { 0, 0, 1 }, // node a has no replication responsibilities to check { 0, 0, 0 } }; int[][] leaveC = // node a doesn't know any replication responsibilities for leaving node { { 0, 0, 0 }, // node a doesn't know any replication responsibilities for leaving node { 0, 0, 0 }, // node a doesn't know any replication responsibilities for leaving node { 0, 0, 0 } }; testReplication(keyC, replicationFactor, true, expectedC, leaveC); Number160 keyD = new Number160("0xd"); int[][] expectedD = // as first node, node a is always replicating given key {{ 1, 0, 0 }, // node b is closer to key d than node a, node a has to notify newly // joined node b { 0, 0, 1 }, // node a has no replication responsibilities to check { 0, 0, 0 }, // node a has no replication responsibilities to check { 0, 0, 0 }}; int[][] leaveD = // node a doesn't know any replication responsibilities of // leaving node b { { 0, 0, 0 }, // node a doesn't know any replication responsibilities of // leaving node c { 0, 0, 0 }, // node a doesn't know any replication responsibilities of // leaving node d { 0, 0, 0 }}; testReplication(keyD, replicationFactor, true, expectedD, leaveD); } /** * Test the responsibility and the notifications for the n-root replication * approach with replication factor 2. * * @throws Exception */ @Test public void testReplicationNRoot2() throws Exception { int replicationFactor = 2; Number160 keyA = new Number160("0xa"); int[][] expectedA = // as first node, node a is always replicating given key {{ 1, 0, 0 }, // node a and b have to replicate key a, node a has to notify newly // joined node b { 0, 1, 0 }, // node a and b still have to replicate key a (node a and b are closer // to key a than newly joined node c), node a doesn't has to notify // newly joined node c { 0, 0, 0 }, // node a and b still have to replicate key a (node b is closer to key a // than newly joined node d), node a doesn't has to notify newly joined // node d { 0, 0, 0 }}; int[][] leaveA = // leaving node b was also responsible for key a, node a has to // notify it's replications set (node a and c are closest to key a) { { 1, 0, 0 }, // leaving node c was also responsible for key a, node a has to // notify it's replications set (node a and d are closest to key a) { 1, 0, 0 }, // leaving node d was also responsible for key a, node a has to // notify it's replications set { 1, 0, 0 }}; testReplication(keyA, replicationFactor, true, expectedA, leaveA); Number160 keyB = new Number160("0xb"); int[][] expectedB = // as first node, node a is always replicating given key {{ 1, 0, 0 }, // node a and b have to replicate key b, node a has to notify newly // joined node b { 0, 1, 0 }, // node a and b still have to replicate key b (node a and b are closer // to key b than newly joined c), node a doesn't has to notify newly // joined node c { 0, 0, 0 }, // node a and b still have to replicate key b (node a and b are closer // to key b than newly joined d), node a doesn't has to notify newly // joined node d { 0, 0, 0 }}; int[][] leaveB = // leaving node b was also responsible for key b, node a has to // notify it's replications set (node a and d are closest to key a) { { 1, 0, 0 }, // leaving node c was not responsible for key b, node a has not to // notify someone (node a and d are closest to key a) { 0, 0, 0 }, // leaving node d was also responsible for key a, node a has to // notify it's replications set { 1, 0, 0 }}; testReplication(keyB, replicationFactor, true, expectedB, leaveB); Number160 keyC = new Number160("0xc"); int[][] expectedC = // as first node, node a is always replicating given key {{ 1, 0, 0 }, // node a and b have to replicate key c, node a has to notify newly // joined node b { 0, 1, 0 }, // node a and c have to replicate key c (node a and c are closer to key // c than node b), node a has to notify newly joined node c { 0, 1, 0 }, // node c and d have to replicate key c (node c and d are closer to key // c than node a), node a doesn't has to replicate anymore, node a has // to notify newly joined node d { 0, 0, 1 }}; int[][] leaveC = // node a doesn't know any replication responsibilities of // leaving node b { { 0, 0, 0 }, // node a doesn't know any replication responsibilities of // leaving node c { 0, 0, 0 }, // node a doesn't know any replication responsibilities of // leaving node d { 0, 0, 0 }}; testReplication(keyC, replicationFactor, true, expectedC, leaveC); Number160 keyD = new Number160("0xd"); int[][] expectedD = // as first node, node a is always replicating given key {{ 1, 0, 0 }, // node a and b have to replicate key d, node a has to notify newly // joined node b { 0, 1, 0 }, // node b and c have to replicate key d (node b and c are closer to key // d than node a), node a has to notify newly joined node c { 0, 0, 1 }, // node a has no replication responsibilities to check { 0, 0, 0 }}; int[][] leaveD = // node a has no replication responsibilities to check { { 0, 0, 0 }, // node a has no replication responsibilities to check { 0, 0, 0 }, // node a has no replication responsibilities to check { 0, 0, 0 }}; testReplication(keyD, replicationFactor, true, expectedD, leaveD); } /** * Test the responsibility and the notifications for the n-root replication * approach with replication factor 3. * * @throws Exception */ @Test public void testReplicationNRoot3() throws Exception { int replicationFactor = 3; Number160 key = new Number160("0xa"); int[][] expectedA = // as first node, node a is always replicating given key {{ 1, 0, 0 }, // node a and b have to replicate key a, node a has to notify newly // joined node b { 0, 1, 0 }, // node a, b and c have to replicate key a, node a has to notify newly // joined node c { 0, 1, 0 }, // node c is not closer to key a than node a, b and c, node a doesn't // have to notify newly joined node d { 0, 0, 0 }}; int[][] leaveA = // node b leaves, node b was also responsible for key a, notify replica // set { { 1, 0, 0 }, // node c leaves, node c was also responsible for key a, notify replica // set { 1, 0, 0 }, // node d leaves, node d was also responsible for key a, notify replica // set { 1, 0, 0 }}; testReplication(key, replicationFactor, true, expectedA, leaveA); key = new Number160("0xb"); int[][] expectedB = // as first node, node a is always replicating given key {{ 1, 0, 0 }, // node a and b have to replicate key b, node a has to notify newly // joined node b { 0, 1, 0 }, // node a, b and c have to replicate key b, node a has to notify newly // joined node c { 0, 1, 0 }, // node a, b and d have to replicate key b (node a, b and d are closer // to key b than node c), node a has to notify newly joined node d { 0, 1, 0 }}; int[][] leaveB = // node b leaves, node b was also responsible for key a, notify replica // set {{ 1, 0, 0}, // node c leaves, node c was also responsible for key a, notify replica // set { 1, 0, 0 }, // node d leaves, node d was also responsible for key a, notify replica // set { 1, 0, 0 }}; testReplication(key, replicationFactor, true, expectedB, leaveB); key = new Number160("0xc"); int[][] expectedC = // as first node, node a is always replicating given key {{ 1, 0, 0 }, // node a and b have to replicate key c, node a has to notify newly // joined node b { 0, 1, 0 }, // node a, b and c have to replicate key c, node a has to notify newly // joined node c { 0, 1, 0 }, // node a, c and d have to replicate key c (node a, c and d are closer // to key b than node b), node a has to notify newly joined node d { 0, 1, 0 }}; int[][] leaveC = // node b leaves, node b was not responsible for key a {{ 0, 0, 0}, // node c leaves, node c was also responsible for key a, notify replica // set { 1, 0, 0 }, // node d leaves, node d was also responsible for key a, notify replica // set { 1, 0, 0 }}; testReplication(key, replicationFactor, true, expectedC, leaveC); key = new Number160("0xd"); int[][] expectedD = // as first node, node a is always replicating given key {{ 1, 0, 0 }, // node a and b have to replicate key d, node a has to notify newly // joined node b { 0, 1, 0 }, // node a, b and c have to replicate key d, node a has to notify newly // joined node c { 0, 1, 0 }, // node b, c and d have to replicate key d (node b, c and d are closer // to key d than node a), node a doesn't have to replicate anymore, node // a has to notify newly joined node d { 0, 0, 1 }}; int[][] leaveD = // node a has no replication responsibilities to check {{ 0, 0, 0}, // node a has no replication responsibilities to check { 0, 0, 0 }, // node a has no replication responsibilities to check { 0, 0, 0 }}; testReplication(key, replicationFactor, true, expectedD, leaveD); } /** * Distances between a, b, c and d: * a <-0001-> b <-0111-> c <-0001-> d <-0111-> a, * a <-0110-> c, b <-0110-> d */ private void testReplication(Number160 lKey, int replicationFactor, boolean nRoot, int[][] joins, int[][] leaves) throws IOException, InterruptedException { List<Peer> peers = new ArrayList<Peer>(joins.length); ChannelCreator cc = null; try { char[] letters = { 'a', 'b', 'c', 'd' }; for (int i = 0; i < joins.length; i++) { peers.add(new PeerMaker(new Number160("0x" + letters[i])).ports(Ports.DEFAULT_PORT + i) .makeAndListen()); } StorageMemory storage; if (nRoot) { storage = new StorageMemory(new StorageMemoryReplicationNRoot()); } else { storage = new StorageMemory(new StorageMemoryReplication()); } Peer master = peers.get(0); master.getPeerBean().storage(new StorageLayer(storage)); Replication replication = new Replication(storage, master.getPeerAddress(), master.getPeerBean() .peerMap(), replicationFactor, nRoot); // attach test listener for test verification final AtomicInteger replicateOther = new AtomicInteger(0); final AtomicInteger replicateI = new AtomicInteger(0); final AtomicInteger replicateWe = new AtomicInteger(0); replication.addResponsibilityListener(new ResponsibilityListener() { @Override public void otherResponsible(final Number160 locationKey, final PeerAddress other, final boolean delayed) { replicateOther.incrementAndGet(); } @Override public void meResponsible(final Number160 locationKey) { replicateI.incrementAndGet(); } @Override public void meResponsible(Number160 locationKey, PeerAddress newPeer) { replicateWe.incrementAndGet(); } }); master.getPeerBean().replicationStorage(replication); // create test data with given location key Map<Number160, Data> dataMap = new HashMap<Number160, Data>(); dataMap.put(Number160.ZERO, new Data("string")); PutBuilder putBuilder = new PutBuilder(master, lKey); putBuilder.setDomainKey(Number160.ZERO); putBuilder.setDataMapContent(dataMap); putBuilder.setVersionKey(Number160.ZERO); FutureChannelCreator fcc = master.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); // put test data FutureResponse fr = master.getStoreRPC().put(master.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); Assert.assertEquals(joins[0][0], replicateI.get()); replicateI.set(0); Assert.assertEquals(joins[0][1], replicateWe.get()); replicateWe.set(0); Assert.assertEquals(joins[0][2], replicateOther.get()); replicateOther.set(0); for (int i = 1; i < joins.length; i++) { // insert a peer master.getPeerBean().peerMap().peerFound(peers.get(i).getPeerAddress(), null); // verify replication notifications Assert.assertEquals(joins[i][0], replicateI.get()); replicateI.set(0); Assert.assertEquals(joins[i][1], replicateWe.get()); replicateWe.set(0); Assert.assertEquals(joins[i][2], replicateOther.get()); replicateOther.set(0); } for (int i = 0; i < leaves.length; i++) { // remove a peer master.getPeerBean().peerMap().peerFailed(peers.get(i+1).getPeerAddress(), FailReason.Shutdown); // verify replication notifications Assert.assertEquals(leaves[i][0], replicateI.get()); replicateI.set(0); Assert.assertEquals(leaves[i][1], replicateWe.get()); replicateWe.set(0); Assert.assertEquals(leaves[i][2], replicateOther.get()); replicateOther.set(0); } } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } for (Peer peer: peers) { peer.shutdown().await(); } } } private FutureResponse store(Peer sender, final Peer recv1, StorageRPC smmSender, ChannelCreator cc) throws Exception { Map<Number160, Data> tmp = new HashMap<Number160, Data>(); byte[] me1 = new byte[] { 1, 2, 3 }; byte[] me2 = new byte[] { 2, 3, 4 }; tmp.put(new Number160(77), new Data(me1)); tmp.put(new Number160(88), new Data(me2)); AddBuilder addBuilder = new AddBuilder(recv1, new Number160(33)); addBuilder.setDomainKey(Number160.createHash("test")); addBuilder.setDataSet(tmp.values()); addBuilder.setVersionKey(Number160.ZERO); FutureResponse fr = smmSender.add(recv1.getPeerAddress(), addBuilder, cc); return fr; } @Test public void testBloomFilter() throws Exception { StorageMemory storeSender = new StorageMemory(); StorageMemory storeRecv = new StorageMemory(); Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { sender = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424).makeAndListen(); recv1 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088).makeAndListen(); sender.getPeerBean().storage(new StorageLayer(storeSender)); StorageRPC smmSender = new StorageRPC(sender.getPeerBean(), sender.getConnectionBean()); recv1.getPeerBean().storage(new StorageLayer(storeRecv)); new StorageRPC(recv1.getPeerBean(), recv1.getConnectionBean()); Map<Number160, Data> tmp = new HashMap<Number160, Data>(); byte[] me1 = new byte[] { 1, 2, 3 }; byte[] me2 = new byte[] { 2, 3, 4 }; byte[] me3 = new byte[] { 5, 3, 4 }; tmp.put(new Number160(77), new Data(me1)); tmp.put(new Number160(88), new Data(me2)); tmp.put(new Number160(99), new Data(me3)); FutureChannelCreator fcc = sender.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); PutBuilder putBuilder = new PutBuilder(sender, new Number160(33)); putBuilder.setDomainKey(Number160.createHash("test")); putBuilder.setDataMapContent(tmp); putBuilder.setVersionKey(Number160.ZERO); FutureResponse fr = smmSender.put(recv1.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); SimpleBloomFilter<Number160> sbf = new SimpleBloomFilter<Number160>(100, 1); sbf.add(new Number160(77)); // get GetBuilder getBuilder = new GetBuilder(recv1, new Number160(33)); getBuilder.setDomainKey(Number160.createHash("test")); getBuilder.setKeyBloomFilter(sbf); getBuilder.setVersionKey(Number160.ZERO); fr = smmSender.get(recv1.getPeerAddress(), getBuilder, cc); fr.awaitUninterruptibly(); Assert.assertEquals(true, fr.isSuccess()); Message m = fr.getResponse(); Map<Number640, Data> stored = m.getDataMap(0).dataMap(); Assert.assertEquals(1, stored.size()); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test public void testBloomFilterDigest() throws Exception { StorageMemory storeSender = new StorageMemory(); StorageMemory storeRecv = new StorageMemory(); Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { sender = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424).setEnableMaintenance(false).makeAndListen(); recv1 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088).setEnableMaintenance(false).makeAndListen(); sender.getPeerBean().storage(new StorageLayer(storeSender)); StorageRPC smmSender = new StorageRPC(sender.getPeerBean(), sender.getConnectionBean()); recv1.getPeerBean().storage(new StorageLayer(storeRecv)); new StorageRPC(recv1.getPeerBean(), recv1.getConnectionBean()); Map<Number160, Data> tmp = new HashMap<Number160, Data>(); byte[] me1 = new byte[] { 1, 2, 3 }; byte[] me2 = new byte[] { 2, 3, 4 }; byte[] me3 = new byte[] { 5, 3, 4 }; tmp.put(new Number160(77), new Data(me1)); tmp.put(new Number160(88), new Data(me2)); tmp.put(new Number160(99), new Data(me3)); FutureChannelCreator fcc = sender.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); PutBuilder putBuilder = new PutBuilder(sender, new Number160(33)); putBuilder.setDomainKey(Number160.createHash("test")); putBuilder.setDataMapContent(tmp); putBuilder.setVersionKey(Number160.ZERO); FutureResponse fr = smmSender.put(recv1.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); SimpleBloomFilter<Number160> sbf = new SimpleBloomFilter<Number160>(100, 2); sbf.add(new Number160(77)); sbf.add(new Number160(99)); // digest DigestBuilder getBuilder = new DigestBuilder(recv1, new Number160(33)); getBuilder.setDomainKey(Number160.createHash("test")); getBuilder.setKeyBloomFilter(sbf); getBuilder.setVersionKey(Number160.ZERO); fr = smmSender.digest(recv1.getPeerAddress(), getBuilder, cc); fr.awaitUninterruptibly(); Assert.assertEquals(true, fr.isSuccess()); Message m = fr.getResponse(); Assert.assertEquals(2, m.getKeyMap640Keys(0).size()); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test @Ignore // TODO test is not working public void testBigStore2() throws Exception { StorageMemory storeSender = new StorageMemory(); StorageMemory storeRecv = new StorageMemory(); Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { PeerMaker pm1 = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424); ChannelServerConficuration css = pm1.createDefaultChannelServerConfiguration(); css.idleTCPSeconds(Integer.MAX_VALUE); pm1.channelServerConfiguration(css); sender = pm1.makeAndListen(); PeerMaker pm2 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088); pm2.channelServerConfiguration(css); recv1 = pm2.makeAndListen(); sender.getPeerBean().storage(new StorageLayer(storeSender)); StorageRPC smmSender = new StorageRPC(sender.getPeerBean(), sender.getConnectionBean()); recv1.getPeerBean().storage(new StorageLayer(storeRecv)); new StorageRPC(recv1.getPeerBean(), recv1.getConnectionBean()); Map<Number160, Data> tmp = new HashMap<Number160, Data>(); byte[] me1 = new byte[50 * 1024 * 1024]; tmp.put(new Number160(77), new Data(me1)); FutureChannelCreator fcc = sender.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); PutBuilder putBuilder = new PutBuilder(sender, new Number160(33)); putBuilder.setDomainKey(Number160.createHash("test")); putBuilder.setDataMapContent(tmp); putBuilder.idleTCPSeconds(Integer.MAX_VALUE); putBuilder.setVersionKey(Number160.ZERO); FutureResponse fr = smmSender.put(recv1.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); Assert.assertEquals(true, fr.isSuccess()); Data data = recv1.getPeerBean().storage() .get(new Number640(new Number160(33), Number160.createHash("test"), new Number160(77), Number160.ZERO)); Assert.assertEquals(true, data != null); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test @Ignore // TODO test is not working public void testBigStoreGet() throws Exception { StorageMemory storeSender = new StorageMemory(); StorageMemory storeRecv = new StorageMemory(); Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { PeerMaker pm1 = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424); ChannelServerConficuration css = pm1.createDefaultChannelServerConfiguration(); css.idleTCPSeconds(Integer.MAX_VALUE); pm1.channelServerConfiguration(css); sender = pm1.makeAndListen(); PeerMaker pm2 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088); pm2.channelServerConfiguration(css); recv1 = pm2.makeAndListen(); sender.getPeerBean().storage(new StorageLayer(storeSender)); StorageRPC smmSender = new StorageRPC(sender.getPeerBean(), sender.getConnectionBean()); recv1.getPeerBean().storage(new StorageLayer(storeRecv)); new StorageRPC(recv1.getPeerBean(), recv1.getConnectionBean()); Map<Number160, Data> tmp = new HashMap<Number160, Data>(); byte[] me1 = new byte[50 * 1024 * 1024]; tmp.put(new Number160(77), new Data(me1)); FutureChannelCreator fcc = sender.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); PutBuilder putBuilder = new PutBuilder(sender, new Number160(33)); putBuilder.setDomainKey(Number160.createHash("test")); putBuilder.setDataMapContent(tmp); putBuilder.idleTCPSeconds(Integer.MAX_VALUE); putBuilder.setVersionKey(Number160.ZERO); FutureResponse fr = smmSender.put(recv1.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); Assert.assertEquals(true, fr.isSuccess()); GetBuilder getBuilder = new GetBuilder(recv1, new Number160(33)); getBuilder.setDomainKey(Number160.createHash("test")); getBuilder.idleTCPSeconds(Integer.MAX_VALUE); getBuilder.setVersionKey(Number160.ZERO); fr = smmSender.get(recv1.getPeerAddress(), getBuilder, cc); fr.awaitUninterruptibly(); System.err.println(fr.getFailedReason()); Assert.assertEquals(true, fr.isSuccess()); Number640 key = new Number640(new Number160(33), Number160.createHash("test"), new Number160(77), Number160.ZERO); Assert.assertEquals(50 * 1024 * 1024, fr.getResponse().getDataMap(0).dataMap().get(key) .length()); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test public void testBigStoreCancel() throws Exception { StorageMemory storeSender = new StorageMemory(); StorageMemory storeRecv = new StorageMemory(); Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { sender = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424).makeAndListen(); recv1 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088).makeAndListen(); sender.getPeerBean().storage(new StorageLayer(storeSender)); StorageRPC smmSender = new StorageRPC(sender.getPeerBean(), sender.getConnectionBean()); recv1.getPeerBean().storage(new StorageLayer(storeRecv)); new StorageRPC(recv1.getPeerBean(), recv1.getConnectionBean()); Map<Number160, Data> tmp = new HashMap<Number160, Data>(); byte[] me1 = new byte[50 * 1024 * 1024]; tmp.put(new Number160(77), new Data(me1)); FutureChannelCreator fcc = sender.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); PutBuilder putBuilder = new PutBuilder(sender, new Number160(33)); putBuilder.setDomainKey(Number160.createHash("test")); putBuilder.setDataMapContent(tmp); putBuilder.setVersionKey(Number160.ZERO); FutureResponse fr = smmSender.put(recv1.getPeerAddress(), putBuilder, cc); Timings.sleep(5); fr.cancel(); Assert.assertEquals(false, fr.isSuccess()); System.err.println("good!"); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test public void testBigStoreGetCancel() throws Exception { StorageMemory storeSender = new StorageMemory(); StorageMemory storeRecv = new StorageMemory(); Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { PeerMaker pm1 = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424); ChannelServerConficuration css = pm1.createDefaultChannelServerConfiguration(); css.idleTCPSeconds(Integer.MAX_VALUE); pm1.channelServerConfiguration(css); sender = pm1.makeAndListen(); PeerMaker pm2 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088); pm2.channelServerConfiguration(css); recv1 = pm2.makeAndListen(); sender.getPeerBean().storage(new StorageLayer(storeSender)); StorageRPC smmSender = new StorageRPC(sender.getPeerBean(), sender.getConnectionBean()); recv1.getPeerBean().storage(new StorageLayer(storeRecv)); new StorageRPC(recv1.getPeerBean(), recv1.getConnectionBean()); Map<Number160, Data> tmp = new HashMap<Number160, Data>(); byte[] me1 = new byte[50 * 1024 * 1024]; tmp.put(new Number160(77), new Data(me1)); FutureChannelCreator fcc = sender.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); PutBuilder putBuilder = new PutBuilder(sender, new Number160(33)); putBuilder.setDomainKey(Number160.createHash("test")); putBuilder.setDataMapContent(tmp); putBuilder.idleTCPSeconds(Integer.MAX_VALUE); putBuilder.setVersionKey(Number160.ZERO); FutureResponse fr = smmSender.put(recv1.getPeerAddress(), putBuilder, cc); fr.awaitUninterruptibly(); System.err.println("XX:" + fr.getFailedReason()); Assert.assertEquals(true, fr.isSuccess()); GetBuilder getBuilder = new GetBuilder(recv1, new Number160(33)); getBuilder.setDomainKey(Number160.createHash("test")); fr = smmSender.get(recv1.getPeerAddress(), getBuilder, cc); Timings.sleep(5); fr.cancel(); System.err.println("XX:" + fr.getFailedReason()); Assert.assertEquals(false, fr.isSuccess()); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test public void testData480() throws Exception { final Random rnd = new Random(42L); Peer master = null; Peer slave = null; ChannelCreator cc = null; try { master = new PeerMaker(new Number160(rnd)).ports(4001).makeAndListen(); slave = new PeerMaker(new Number160(rnd)).ports(4002).makeAndListen(); Map<Number640,Data> tmp = new HashMap<>(); for(int i=0;i<5;i++) { byte[] me = new byte[480]; Arrays.fill(me, (byte)(i-6)); Data test = new Data(me); tmp.put(new Number640(rnd), test); } PutBuilder pb = master.put(new Number160("0x51")).setDataMap(tmp); FutureChannelCreator fcc = master.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); FutureResponse fr = master.getStoreRPC().put(slave.getPeerAddress(), pb, cc); fr.awaitUninterruptibly(); Assert.assertEquals(true, fr.isSuccess()); GetBuilder gb = master.get(new Number160("0x51")).setDomainKey(Number160.ZERO); fr = master.getStoreRPC().get(slave.getPeerAddress(), gb, cc); fr.awaitUninterruptibly(); Assert.assertEquals(true, fr.isSuccess()); System.err.println("done"); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (master != null) { master.shutdown().await(); } if (slave != null) { slave.shutdown().await(); } } } }
package xal.tools.apputils; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Frame; import javax.swing.*; import javax.swing.table.*; import java.util.*; import xal.model.probe.Probe; import xal.model.IAlgorithm; import xal.tools.bricks.*; import xal.tools.swing.KeyValueFilteredTableModel; import xal.tools.data.KeyValueAdaptor; import java.beans.*; import java.lang.reflect.*; /** SimpleProbeEditor */ public class SimpleProbeEditor extends JDialog { /** Private serializable version ID */ private static final long serialVersionUID = 1L; /** Table model of ProbeProperty records */ final private KeyValueFilteredTableModel<ProbeProperty> PROPERTY_TABLE_MODEL; /** List of properties that appear in the properties table */ private List<ProbeProperty> propertyList = new ArrayList<ProbeProperty>(); /** Map that contains an object keyed by group name. The Object instance is where the properties and methods. */ private Map<String, Object> propertyClasses = new HashMap<>(); /** Used to look for methods given a method name key */ final private KeyValueAdaptor KEY_VALUE_ADAPTOR; /** Probe that is being edited */ final private Probe PROBE; /* Constructor that takes a window parent * and a probe to fetch properties from */ public SimpleProbeEditor( final Frame owner, final Probe probe ) { super( owner, "Probe Editor", true ); //Set JDialog's owner, title, and modality PROBE = probe; // Set the probe to edit KEY_VALUE_ADAPTOR = new KeyValueAdaptor(); PROPERTY_TABLE_MODEL = new KeyValueFilteredTableModel<ProbeProperty>( new ArrayList<ProbeProperty>(), "group", "property", "value"); final EditablePropertyContainer probeContainer = EditableProperty.getInstanceWithRoot( "Probe", probe ); System.out.println( probeContainer ); setSize( 600, 600 ); // Set the window size initializeComponents(); // Set up each component in the editor pack(); // Fit the components in the window setLocationRelativeTo( owner ); // Center the editor in relation to the frame that constructed the editor setVisible(true); // Make the window visible } /** * Get the probe to edit * @return probe associated with this editor */ public Probe getProbe() { return PROBE; } /* setTableProperties() * * Sets the table data with the properties found through introspection * * Takes each property from the propertyClasses HashMap and adds * them to the list of properties. */ private void setTableProperties() { //Cycle through each element in the HashMap for(String key : propertyClasses.keySet()) { //The instance of the object that will have its properties taken Object instance = propertyClasses.get(key); //Get the BeanInfo from the instance's class final BeanInfo beanInfo = null; //Get each property descriptor from the BeanInfo PropertyDescriptor[] descriptors = getPropertyDescriptors(beanInfo); //Cycle through each property descriptor found in the class for(int propIndex = 0; propIndex < descriptors.length; propIndex++) { //The property's write method for setting data Method write = descriptors[propIndex].getWriteMethod(); //The property's read method for retreiving data Method read = descriptors[propIndex].getReadMethod(); //If there is not a getter AND setter for each property, we can not edit the property if(write != null && read != null) { //Gets the value of the property from the instance's read method Object result = getPropertyValue( read, instance); //Filter out classes we don't want to edit if(isEditableClass(result.getClass())) { //Add the property as a ProbeProperty to the list of editable properties propertyList.add(new ProbeProperty(key, descriptors[propIndex].getName(), result, result.getClass())); }//if(isEditableClass()) }//if(write && read) }//for(descriptors) }//for(HashMap keys) //Update the properties table refreshView(); } /* getPropertyValue(Method, Object) * * Gets the value of a read method by invoking that method on an object instance * */ public Object getPropertyValue(Method method, Object object) { //Result from invoking the read method Object result = null; try { //Try to invoke the read method and get its value result = method.invoke( object ); } catch (IllegalAccessException iae) { System.err.println(iae.getMessage()); } catch (InvocationTargetException ite) { System.err.println(ite.getMessage()); } //TODO: handle null //Return the result return result == null ? "null" : result; } /* getPropertyDescriptor(BeanInfo) * * Gets the PropertyDescriptors from a BeanInfo * */ public PropertyDescriptor[] getPropertyDescriptors( BeanInfo bean ) { //If the bean is not null, return the descriptors return bean != null ? bean.getPropertyDescriptors() : new PropertyDescriptor[0]; } /* initializeComponents() * * Initialize the components of the probe editor * */ public void initializeComponents() { //Panel containing all elements final JPanel mainContainer = new JPanel(); //Set the layout of the panel to a BorderLayout mainContainer.setLayout( new BorderLayout() ); //Panel containing apply and close button with a 1 row, 2 column grid layout final JPanel controlPanel = new JPanel( new GridLayout(1, 2) ); //Apply button final JButton applyButton = new JButton( "Apply" ); applyButton.setEnabled( false ); //Close button final JButton closeButton = new JButton( "Close" ); //Set the close button's action to close the dialog closeButton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); } }); //Add the action listener as the ApplyButtonListener applyButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { //Save the properties saveProbeProperties(); //Mark the properties as unchanged/saved setPropertiesAsUnchanged(); //Re-enable the button applyButton.setEnabled( false ); } }); //Add the close button to the button panel controlPanel.add( closeButton ); //Add the apply button to the button panel controlPanel.add( applyButton ); //Text field that filters the properties final JTextField filterTextField = new JTextField(); //Set the text field properts to search field filterTextField.putClientProperty( "JTextField.variant", "search" ); filterTextField.putClientProperty( "JTextField.Search.Prompt", "Property Filter" ); //Table containing the properties that can be modified final JTable propertyTable = new JTable() { //Serializable version ID private static final long serialVersionUID = 1L; //Get the cell editor for the table @Override public TableCellEditor getCellEditor(int row, int col) { //Value at [row, col] of the table Object value = getValueAt(row, col); //Set the appropriate editor for each value type if( value instanceof Boolean ) return getDefaultEditor( Boolean.class ); else if( value instanceof Double ) return getDefaultEditor( Double.class ); else if( value instanceof Integer ) return getDefaultEditor( Integer.class ); //Default editor (String type) return super.getCellEditor( row, col ); } //Get the cell renderer for the table to change how values are displayed @Override public TableCellRenderer getCellRenderer(int row, int col) { //Value at [row, col] Object value = getValueAt(row, col); //Set the renderer of each type //Boolean = checkbox display //Double/Int = right aligned display if( value instanceof Boolean ) return getDefaultRenderer( Boolean.class ); else if( value instanceof Double ) return getDefaultRenderer( Double.class ); else if( value instanceof Integer ) return getDefaultRenderer( Integer.class ); //Default = left aligned string display return super.getCellRenderer( row, col ); } }; //Set the table to allow one-click edit ((DefaultCellEditor) propertyTable.getDefaultEditor(Object.class)).setClickCountToStart(1); //Resize the last column propertyTable.setAutoResizeMode( JTable.AUTO_RESIZE_LAST_COLUMN); //Allow single selection only propertyTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); //Match the property's keys with their method PROPERTY_TABLE_MODEL.setMatchingKeyPaths( "group", "property", "value"); //Set the table filter component to the text field PROPERTY_TABLE_MODEL.setInputFilterComponent( filterTextField ); //Set the editable column to the "value" column PROPERTY_TABLE_MODEL.setColumnEditable( "value", true ); //Set the model to the table propertyTable.setModel( PROPERTY_TABLE_MODEL ); //Update the table contents refreshView(); //Add the scrollpane to the table with a vertical scrollbar final JScrollPane scrollPane = new JScrollPane( propertyTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ); //Add the text field to the top of the dialog mainContainer.add( filterTextField, BorderLayout.NORTH ); //Add the table to the center of the dialog mainContainer.add( scrollPane, BorderLayout.CENTER ); //Add the buttons to the bottom of the dialog mainContainer.add( controlPanel, BorderLayout.SOUTH ); //Add everything to the dialog add( mainContainer ); } /** Set the values of the table to the property list */ private void refreshView() { //Set the records as the properties from the property list PROPERTY_TABLE_MODEL.setRecords( propertyList ); } /** Set the properties of the probe that have been changed */ private void saveProbeProperties() { //Go through each value in the properties HashMap for(String key : propertyClasses.keySet()) { //The instance of the object from the class Object instance = propertyClasses.get(key); //Get the BeanInfo from the class in the HashMap final BeanInfo beanInfo = null; // BeanInfo beanInfo = getBeanObjectBeanInfo(instance.getClass()); //Get the PropertyDescriptors from the class PropertyDescriptor[] descriptors = getPropertyDescriptors(beanInfo); //Go through each descriptor for(int propIndex = 0; propIndex < descriptors.length; propIndex++) { //Write method of the descriptor Method write = descriptors[propIndex].getWriteMethod(); //Read method of the descriptor Method read = descriptors[propIndex].getReadMethod(); //Do nothing if there is not both a read and write method if(write != null && read != null) { //Find the right property in the list based on name for(ProbeProperty pp : propertyList) { if(pp.hasChanged() && pp.getProperty().equals(descriptors[propIndex].getName())) { //Try to invoke the write method with the changed property try { //Call the invoke method with the instance and value System.out.println("Set property " + pp.getProperty()); write.invoke( instance, pp.getValue()); } catch (Exception e) { //Display an error saying the property could not be set System.out.println("Could not set property '" + pp.getProperty() + "' with value " + pp.getValue() + " of type " + pp.getValueType()); System.err.println(e.getMessage()); }// try/catch }// if(correct property) }// for(each ProbeProperty) }// if(write && read != null) }// for(descriptors) }// for(each HashMap key) //Update the table contents refreshView(); } /** Determine if the property's class is editable or not based on the EDITABLE_CLASSES attribute */ private boolean isEditableClass(Class<?> propertyClass) { // //Look through each class in the EDITABLE_CLASSES array // for(Class<?> c : EDITABLE_CLASSES) { // if(propertyClass == c) // return true; return false; } /* setPropertiesAsUnchanged() * * Sets property to be marked as unchanged after applying the changes * */ private void setPropertiesAsUnchanged() { for(ProbeProperty pp : propertyList) { if(pp.hasChanged()) pp.setHasChanged(false); } } /** ProbeProperty record that gets dislpayed in the property table */ private class ProbeProperty { //Class type of the property private Class<?> _type; //Group name, and property name of the property private String _group, _property; //Actual value of the property private Object _value; //If the property has been changed or not private boolean _hasChanged = false; //ProbeProperty Constructor that takes a group name, property name, value, and class type public ProbeProperty(String group, String property, Object value, Class<?> type) { //Initialize the attributes _type = type; _property = property; _value = value; _group = group; } /* getGroup() * * return the group name formatted with html to be bold * */ public String getGroup() { return "<html><b>" + _group + "</b></html>"; } /* getType() * * return the class type of the property * */ public Class<?> getType() { return _type; } /* getValueType() * * return value type of the class * */ public String getValueType() { return _type.getSimpleName(); } /* getProperty() * * return the property name * */ public String getProperty() { return _property; } /* getValue() * * return the value of the property * */ public Object getValue() { return _value; } /* hasChanged() * * return if the value has changed * */ public boolean hasChanged() { return _hasChanged; } /* setChanged() * * return if the value has changed * */ public void setHasChanged(boolean changed) { _hasChanged = changed; } /* setValue(Boolean) * * Set the value of the value * * If the value is type Boolean, this method will be called and * the value would be set appropriately * */ public void setValue(Boolean value) { // if( !applyButton.isEnabled() ) applyButton.setEnabled(true); _hasChanged = true; _value = value; } /* setValue(String) * * Set the value of the property and parse * the value appropriately * */ public void setValue(String value) { try { if( _type == Double.class ){ _value = Double.parseDouble(value); } else if(_type == Float.class) { _value = Float.parseFloat(value); } else if(_type == Integer.class) { _value = Integer.parseInt(value); } else if(_type == Boolean.class) { _value = Boolean.parseBoolean(value); } else if(_type == Long.class) { _value = Long.parseLong(value); } else if(_type == Short.class) { _value = Short.parseShort(value); } else if(_type == Byte.class) { _value = Byte.parseByte(value); } else { _value = value; } // if(!applyButton.isEnabled()) applyButton.setEnabled(true); _hasChanged = true; } catch (Exception e) { System.err.println("Invalid property value " + value + " for " + getProperty()); } } } } /** base class for a editable property */ abstract class EditableProperty { /** array of classes for which the property can be edited directly */ final static protected Set<Class<?>> EDITABLE_PROPERTY_TYPES = new HashSet<>(); /** property name */ final private String NAME; /** target object which is assigned the property */ final protected Object TARGET; /** property descriptor */ final protected PropertyDescriptor PROPERTY_DESCRIPTOR; // static initializer static { // cache the editable properties in a set for quick comparison later final Class<?>[] editablePropertyTypes = { Double.class, Double.TYPE, Integer.class, Integer.TYPE, Boolean.class, Boolean.TYPE, String.class }; for ( final Class<?> type : editablePropertyTypes ) { EDITABLE_PROPERTY_TYPES.add( type ); } } /** Constructor */ protected EditableProperty( final String name, final Object target, final PropertyDescriptor descriptor ) { NAME = name; TARGET = target; PROPERTY_DESCRIPTOR = descriptor; } /** Constructor */ protected EditableProperty( final Object target, final PropertyDescriptor descriptor ) { this( descriptor.getName(), target, descriptor ); } /** Get an instance starting at the root object */ static public EditablePropertyContainer getInstanceWithRoot( final String name, final Object root ) { return EditablePropertyContainer.getInstanceWithRoot( name, root ); } /** name of the property */ public String getName() { return NAME; } /** Get the property type */ public Class<?> getPropertyType() { return PROPERTY_DESCRIPTOR != null ? PROPERTY_DESCRIPTOR.getPropertyType() : null; } /** Get the value for this property */ public Object getValue() { if ( TARGET != null && PROPERTY_DESCRIPTOR != null ) { final Method getter = PROPERTY_DESCRIPTOR.getReadMethod(); if ( getter.isAccessible() ) { try { return getter.invoke( TARGET ); } catch( Exception exception ) { return null; } } else { return null; } } else { return null; } } /** determine whether the property is a container */ abstract public boolean isContainer(); /** determine whether the property is a primitive */ abstract public boolean isPrimitive(); /* * Get the property descriptors for the given bean info * @param target object for which to get the descriptors * @return the property descriptors for non-null beanInfo otherwise null */ static protected PropertyDescriptor[] getPropertyDescriptors( final Object target ) { if ( target != null ) { final BeanInfo beanInfo = getBeanInfo( target ); return getPropertyDescriptorsForBeanInfo( beanInfo ); } else { return null; } } /* * Get the property descriptors for the given bean info * @param beanInfo bean info * @return the property descriptors for non-null beanInfo otherwise null */ static private PropertyDescriptor[] getPropertyDescriptorsForBeanInfo( final BeanInfo beanInfo ) { return beanInfo != null ? beanInfo.getPropertyDescriptors() : null; } /** Convenience method to get the BeanInfo for an object's class */ static private BeanInfo getBeanInfo( final Object object ) { if ( object != null ) { return getBeanInfoForType( object.getClass() ); } else { return null; } } /** Convenience method to get the BeanInfo for the given type */ static private BeanInfo getBeanInfoForType( final Class<?> propertyType ) { if ( propertyType != null ) { try { return Introspector.getBeanInfo( propertyType ); } catch( IntrospectionException exception ) { return null; } } else { return null; } } /** Get a string represenation of this property */ public String toString() { return getName(); } } /** editable property representing a primitive that is directly editable */ class EditablePrimitiveProperty extends EditableProperty { /** Constructor */ protected EditablePrimitiveProperty( final Object target, final PropertyDescriptor descriptor ) { super( target, descriptor ); } /** determine whether the property is a container */ public boolean isContainer() { return false; } /** determine whether the property is a primitive */ public boolean isPrimitive() { return true; } /** Set the value for this property */ public void setValue( final Object value ) { if ( TARGET != null && PROPERTY_DESCRIPTOR != null ) { final Method setter = PROPERTY_DESCRIPTOR.getWriteMethod(); if ( setter.isAccessible() ) { try { setter.invoke( TARGET, value ); } catch( Exception exception ) { throw new RuntimeException( "Cannot set value " + value + " on target: " + TARGET + " with descriptor: " + PROPERTY_DESCRIPTOR.getName(), exception ); } } else { throw new RuntimeException( "Cannot set value " + value + " on target: " + TARGET + " with descriptor: " + PROPERTY_DESCRIPTOR.getName() + " because the set method is not accessible." ); } } else { if ( TARGET == null && PROPERTY_DESCRIPTOR == null ) { throw new RuntimeException( "Cannot set value " + value + " on target because both the target and descriptor are null." ); } else if ( TARGET == null ) { throw new RuntimeException( "Cannot set value " + value + " on target with descriptor: " + PROPERTY_DESCRIPTOR.getName() + " because the target is null." ); } else if ( PROPERTY_DESCRIPTOR == null ) { throw new RuntimeException( "Cannot set value " + value + " on target: " + TARGET + " because the property descriptor is null." ); } } } } /** base class for a container of editable properties */ class EditablePropertyContainer extends EditableProperty { /** list of child properties */ final List<EditableProperty> CHILD_PROPERTIES; /** target for child properties */ final protected Object CHILD_TARGET; /** Primary Constructor */ protected EditablePropertyContainer( final String name, final Object target, final PropertyDescriptor descriptor, final Object childTarget ) { super( name, target, descriptor ); CHILD_PROPERTIES = new ArrayList<EditableProperty>(); CHILD_TARGET = childTarget; } /** Constructor */ protected EditablePropertyContainer( final Object target, final PropertyDescriptor descriptor, final Object childTarget ) { this( descriptor.getName(), target, descriptor, childTarget ); } /** Constructor */ protected EditablePropertyContainer( final Object target, final PropertyDescriptor descriptor ) { this( target, descriptor, generateChildTarget( target, descriptor ) ); } /** Create an instance witht the specified root Object */ static public EditablePropertyContainer getInstanceWithRoot( final String name, final Object rootObject ) { final EditablePropertyContainer container = new EditablePropertyContainer( name, null, null, rootObject ); container.generateChildPropertiesWithAncestor( rootObject ); return container; } /** Generat the child target from the target and descriptor */ static private Object generateChildTarget( final Object target, final PropertyDescriptor descriptor ) { try { final Method readMethod = descriptor.getReadMethod(); return readMethod.invoke( target ); } catch( Exception exception ) { // System.err.println( "Exception generating child target for target: " + target + " and descriptor: " + descriptor.getName() ); // System.err.println( "Exception: " + exception ); // exception.printStackTrace(); return null; } } /** determine whether this container has any child properties */ public boolean isEmpty() { return CHILD_PROPERTIES.size() == 0; } /** get the number of child properties */ public int getChildCount() { return CHILD_PROPERTIES.size(); } /** determine whether the property is a container */ public boolean isContainer() { return true; } /** determine whether the property is a primitive */ public boolean isPrimitive() { return false; } /** Get the child properties */ public List<EditableProperty> getChildProperties() { return CHILD_PROPERTIES; } /** Generate the child properties this container's child target */ public void generateChildPropertiesWithAncestor( final Object ancestor ) { final Set<Object> rootAncestor = new HashSet<Object>(); generateChildPropertiesWithAncestors( rootAncestor ); } /** Generate the child properties this container's child target */ protected void generateChildPropertiesWithAncestors( final Set<Object> ancestors ) { final PropertyDescriptor[] descriptors = getPropertyDescriptors( CHILD_TARGET ); if ( descriptors != null ) { for ( final PropertyDescriptor descriptor : descriptors ) { if ( descriptor.getPropertyType() != Class.class ) { generateChildPropertyForDescriptorAndAncestors( descriptor, ancestors ); } } } } /** Generate the child properties starting at the specified descriptor for this container's child target */ protected void generateChildPropertyForDescriptorAndAncestors( final PropertyDescriptor descriptor, final Set<Object> ancestorsReference ) { final Set<Object> ancestors = new HashSet<Object>( ancestorsReference ); // make a copy so it is unique for each branch final Class<?> propertyType = descriptor.getPropertyType(); if ( EDITABLE_PROPERTY_TYPES.contains( propertyType ) ) { // if the property is an editable primitive with both a getter and setter then return the primitive property instance otherwise null final Method getter = descriptor.getReadMethod(); final Method setter = descriptor.getWriteMethod(); if ( getter != null && setter != null ) { CHILD_PROPERTIES.add( new EditablePrimitiveProperty( CHILD_TARGET, descriptor ) ); } return; // reached end of branch so we are done } else if ( propertyType == null ) { return; } else if ( propertyType.isArray() ) { // property is an array return; } else { // property is a plain container if ( !ancestors.contains( CHILD_TARGET ) ) { // only propagate down the branch if the targets are unique (avoid cycles) ancestors.add( CHILD_TARGET ); final EditablePropertyContainer container = new EditablePropertyContainer( CHILD_TARGET, descriptor ); container.generateChildPropertiesWithAncestors( ancestors ); if ( container.getChildCount() > 0 ) { // only care about nontrivial containers CHILD_PROPERTIES.add( container ); } } return; } } /** Get the editable properties of the specified target */ static public List<EditableProperty> getChildProperties( final Object target ) { return null; } /** Get the child property for the given descriptor */ protected EditableProperty getChildProperty( final PropertyDescriptor descriptor ) { return null; } /** Get a string represenation of this property */ public String toString() { final StringBuilder buffer = new StringBuilder(); buffer.append( "\n" + getName() + ":\n" ); for ( final EditableProperty property : CHILD_PROPERTIES ) { buffer.append( "\t" + property.toString() + "\n" ); } buffer.append( "\n" ); return buffer.toString(); } } /** container for an editable property that is an array */ class EditableArrayProperty extends EditablePropertyContainer { /** Constructor */ protected EditableArrayProperty( final Object target, final PropertyDescriptor descriptor ) { super( target, descriptor ); } }
package com.dp.examples; import jshellsession.CommandResult; import jshellsession.Config; import jshellsession.JShellSession; import java.io.IOException; import java.util.Arrays; public class CatExample { public static void main(String[] args) throws IOException { final JShellSession shellSession = new JShellSession(Config.defaultConfig()); final CommandResult result = shellSession.run("ls /proc | sort"); System.out.println("ls result: " + Arrays.toString(result.stdOut())); for (String s : result.stdOut()) { if (isInteger(s)) { final CommandResult r = shellSession.run("cat /proc/" + s + "/cmdline"); System.out.println(s + ": " + Arrays.toString(r.stdOut())); } } shellSession.close(); } private static boolean isInteger(String s) { try { Integer.parseInt(s); return true; } catch (NumberFormatException e) { return false; } } }
// 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: // 2008 Jan 21: Use a DataSource instead of a DbConnectionFactory. - dj@opennms.org // 2007 Dec 08: Code formatting. - dj@opennms.org // 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.core.resource; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Enumeration; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import javax.sql.DataSource; public class Vault extends Object { /** * Holds all the application configuration properties. */ protected static Properties properties = new Properties(System.getProperties()); /** * Stores the directory where the OpenNMS configuration files can be found. * The default is <em>/opt/OpenNMS</em>. */ protected static String homeDir = "/opt/opennms/"; private static DataSource s_dataSource; /** * Private, empty constructor so that this class cannot be instantiated. */ private Vault() { } public static void setDataSource(DataSource dataSource) { if (dataSource == null) { throw new IllegalArgumentException("Cannot take null parameters."); } s_dataSource = dataSource; } public static DataSource getDataSource() { if (s_dataSource == null) { throw new IllegalStateException("You must set a DataSource before requesting a data source."); } return s_dataSource; } /** * Retrieve a database connection from the datasource. */ public static Connection getDbConnection() throws SQLException { if (s_dataSource == null) { throw new IllegalStateException("You must set a DataSource before requesting a database connection."); } return s_dataSource.getConnection(); } /** * Release a database connection. * * @param connection * the connection to release * @throws SQLException * If a SQL error occurs while calling connection.close() on the * connection. */ public static void releaseDbConnection(Connection connection) throws SQLException { connection.close(); } /** * Set the application configuration properties. */ public static void setProperties(Properties properties) { if (properties == null) { throw new IllegalArgumentException("Cannot take null parameters."); } Vault.properties = properties; /* * For backwards compatibility; put all these * properties into the system properties. */ Enumeration keys = properties.keys(); Properties sysProps = System.getProperties(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); sysProps.put(key, properties.get(key)); } } /** * Return the entire set of application configuration properties. */ public static Properties getProperties() { return properties; } /** * Return property from the configuration parameter list. */ public static String getProperty(String key) { return properties.getProperty(key); } /** * Set the directory so we will know where we can get the OpenNMS * configuration files. */ public static void setHomeDir(String homeDir) { if (homeDir == null) { throw new IllegalArgumentException("Cannot take null parameters."); } Vault.homeDir = homeDir; Vault.properties.setProperty("opennms.home", homeDir); System.setProperty("opennms.home", homeDir); } /** * Get the directory that holds the OpenNMS configuration files. */ public static String getHomeDir() { return homeDir; } /** * <P> * Adds new keys to the system properties using the passed key name a the * properties location instance. The passed key is used as a key to the * system {@link java.util.Properties#getPropertyget property} to find the * supplementary property information. The returned value should be in the * form of a list of file names, each separated by the system * {@link java.io.File#pathSeparatorCharpath separator} character. * </P> * * <P> * Once the list of files is recovered, each file is visited and loaded into * the system properties. If any file cannot be loaded due to an I/O error * then it is skipped as a whole. No partial key sets are loaded into the * system properties. Also, this method will not overwrite an existing key * in the currently loaded properties. * </P> * * @param key * The key name used to lookup the property path values. * * @return True if all properties loaded correctly, false if any property * file failed to load. */ public static boolean supplementSystemPropertiesFromKey(String key) { boolean loadedOK = true; String path = System.getProperty(key); if (path != null) { StringTokenizer files = new StringTokenizer(path, File.pathSeparator); while (files.hasMoreTokens()) { try { File pfile = new File(files.nextToken()); if (pfile.exists() && pfile.isFile()) { Properties p = new Properties(); InputStream is = new FileInputStream(pfile); try { p.load(is); } catch (IOException ioE) { throw ioE; } finally { try { is.close(); } catch (IOException ioE) { /* do nothing */ } } Iterator i = p.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry) i.next(); if (System.getProperty((String) e.getKey()) == null) System.setProperty((String) e.getKey(), (String) e.getValue()); } } } catch (IOException ioE) { loadedOK = false; } } // end while more files to be processed } // end if property path no null return loadedOK; } }
package falgout.utils.reflection; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import falgout.utils.temp.Predicate; class JLSMethodLocator extends MethodLocator { @Override protected Method findMethod(Collection<? extends Method> methods, Class<?> clazz, String name, Class<?>... args) throws AmbiguousDeclarationException, NoSuchMethodException { return findParameterized(convertMethods(methods), clazz, name, args); } @Override protected Set<Method> findMethods(Collection<? extends Method> methods, Class<?> clazz, String name, Class<?>... args) throws NoSuchMethodException { return findParameterizeds(convertMethods(methods), clazz, name, args); } @Override protected <T> Constructor<T> findConstructor(Collection<? extends Constructor<T>> constructors, Class<T> clazz, Class<?>... args) throws AmbiguousDeclarationException, NoSuchMethodException { return findParameterized(convertConstructors(constructors), clazz, "<init>", args); } @Override protected <T> Set<Constructor<T>> findConstructors(Collection<? extends Constructor<T>> constructors, Class<T> clazz, Class<?>... args) throws NoSuchMethodException { return findParameterizeds(convertConstructors(constructors), clazz, "<init>", args); } private List<Parameterized.Method> convertMethods(Collection<? extends Method> methods) { List<Parameterized.Method> converted = new ArrayList<>(methods.size()); for (Method m : methods) { converted.add(new Parameterized.Method(m)); } return converted; } private <T> List<Parameterized.Constructor<T>> convertConstructors(Collection<? extends Constructor<T>> constructors) { List<Parameterized.Constructor<T>> converted = new ArrayList<>(constructors.size()); for (Constructor<T> c : constructors) { converted.add(new Parameterized.Constructor<>(c)); } return converted; } private <M extends AccessibleObject & GenericDeclaration & Member> M findParameterized( Collection<? extends Parameterized<M>> parameterizeds, Class<?> clazz, String name, Class<?>... args) throws AmbiguousDeclarationException, NoSuchMethodException { Set<M> found = findParameterizeds(parameterizeds, clazz, name, args); if (found.size() > 1) { throw new AmbiguousDeclarationException(found.toString()); } return found.iterator().next(); } private <M extends AccessibleObject & GenericDeclaration & Member> Set<M> findParameterizeds( Collection<? extends Parameterized<M>> parameterizeds, Class<?> clazz, String name, Class<?>... args) throws NoSuchMethodException { Set<Parameterized<M>> potentiallyApplicable = new LinkedHashSet<>(); Predicate<Parameterized<?>> filter = new PotentiallyApplicable(name, args); for (Parameterized<M> p : parameterizeds) { if (filter.test(p)) { potentiallyApplicable.add(p); } } for (Phase phase : Phase.values()) { Set<Parameterized<M>> applicable = new LinkedHashSet<>(); for (Parameterized<M> p : potentiallyApplicable) { if (phase.isApplicable(args, p)) { applicable.add(p); } } if (!applicable.isEmpty()) { return getMostSpecific(applicable); } } throw new NoSuchMethodException(createNoSuchMethodMessage(clazz, name, args)); } private <M extends AccessibleObject & GenericDeclaration & Member> Set<M> getMostSpecific( Collection<? extends Parameterized<M>> applicable) { Parameterized<M> max = Collections.max(applicable, MethodSpecificity.INSTANCE); Set<M> found = new LinkedHashSet<>(); found.add(max.getMember()); for (Parameterized<M> p : applicable) { if (MethodSpecificity.INSTANCE.compare(p, max) == 0) { found.add(p.getMember()); } } return found; } private String createNoSuchMethodMessage(Class<?> clazz, String name, Class<?>... args) { StringBuilder b = new StringBuilder(); b.append(clazz.getName()).append(".").append(name).append("("); for (int x = 0; x < args.length; x++) { if (x != 0) { b.append(", "); } b.append(toHumanReadableName(args[x])); } b.append(")"); return b.toString(); } private String toHumanReadableName(Class<?> clazz) { return clazz.isArray() ? toHumanReadableName(clazz.getComponentType()) + "[]" : clazz.getName(); } }
package com.semmle.jcorn; import static com.semmle.jcorn.Whitespace.isNewLine; import static com.semmle.jcorn.Whitespace.lineBreak; import java.io.File; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.Stack; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.semmle.jcorn.Identifiers.Dialect; import com.semmle.jcorn.Options.AllowReserved; import com.semmle.js.ast.ArrayExpression; import com.semmle.js.ast.ArrayPattern; import com.semmle.js.ast.ArrowFunctionExpression; import com.semmle.js.ast.AssignmentExpression; import com.semmle.js.ast.AssignmentPattern; import com.semmle.js.ast.AwaitExpression; import com.semmle.js.ast.BinaryExpression; import com.semmle.js.ast.BlockStatement; import com.semmle.js.ast.BreakStatement; import com.semmle.js.ast.CallExpression; import com.semmle.js.ast.CatchClause; import com.semmle.js.ast.Chainable; import com.semmle.js.ast.ClassBody; import com.semmle.js.ast.ClassDeclaration; import com.semmle.js.ast.ClassExpression; import com.semmle.js.ast.ConditionalExpression; import com.semmle.js.ast.ContinueStatement; import com.semmle.js.ast.DebuggerStatement; import com.semmle.js.ast.DoWhileStatement; import com.semmle.js.ast.EmptyStatement; import com.semmle.js.ast.EnhancedForStatement; import com.semmle.js.ast.ExportAllDeclaration; import com.semmle.js.ast.ExportDeclaration; import com.semmle.js.ast.ExportDefaultDeclaration; import com.semmle.js.ast.ExportNamedDeclaration; import com.semmle.js.ast.ExportSpecifier; import com.semmle.js.ast.Expression; import com.semmle.js.ast.ExpressionStatement; import com.semmle.js.ast.ForInStatement; import com.semmle.js.ast.ForOfStatement; import com.semmle.js.ast.ForStatement; import com.semmle.js.ast.FunctionDeclaration; import com.semmle.js.ast.FunctionExpression; import com.semmle.js.ast.IFunction; import com.semmle.js.ast.INode; import com.semmle.js.ast.IPattern; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.IfStatement; import com.semmle.js.ast.ImportDeclaration; import com.semmle.js.ast.ImportDefaultSpecifier; import com.semmle.js.ast.ImportNamespaceSpecifier; import com.semmle.js.ast.ImportSpecifier; import com.semmle.js.ast.LabeledStatement; import com.semmle.js.ast.Literal; import com.semmle.js.ast.LogicalExpression; import com.semmle.js.ast.MemberDefinition; import com.semmle.js.ast.MemberExpression; import com.semmle.js.ast.DeclarationFlags; import com.semmle.js.ast.MetaProperty; import com.semmle.js.ast.MethodDefinition; import com.semmle.js.ast.NewExpression; import com.semmle.js.ast.Node; import com.semmle.js.ast.ObjectExpression; import com.semmle.js.ast.ObjectPattern; import com.semmle.js.ast.ParenthesizedExpression; import com.semmle.js.ast.Position; import com.semmle.js.ast.Program; import com.semmle.js.ast.Property; import com.semmle.js.ast.RestElement; import com.semmle.js.ast.ReturnStatement; import com.semmle.js.ast.SequenceExpression; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.SpreadElement; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Super; import com.semmle.js.ast.SwitchCase; import com.semmle.js.ast.SwitchStatement; import com.semmle.js.ast.TaggedTemplateExpression; import com.semmle.js.ast.TemplateElement; import com.semmle.js.ast.TemplateLiteral; import com.semmle.js.ast.ThisExpression; import com.semmle.js.ast.ThrowStatement; import com.semmle.js.ast.Token; import com.semmle.js.ast.TryStatement; import com.semmle.js.ast.UnaryExpression; import com.semmle.js.ast.UpdateExpression; import com.semmle.js.ast.VariableDeclaration; import com.semmle.js.ast.VariableDeclarator; import com.semmle.js.ast.WhileStatement; import com.semmle.js.ast.WithStatement; import com.semmle.js.ast.YieldExpression; import com.semmle.ts.ast.ITypeExpression; import com.semmle.util.collections.CollectionUtil; import com.semmle.util.data.Pair; import com.semmle.util.data.StringUtil; import com.semmle.util.exception.Exceptions; import com.semmle.util.exception.CatastrophicError; import com.semmle.util.io.WholeIO; public class Parser { protected final Options options; protected final Set<String> keywords; private final Set<String> reservedWords, reservedWordsStrict, reservedWordsStrictBind; protected final String input; private boolean containsEsc; protected boolean exprAllowed; protected boolean strict; private boolean inModule; protected boolean inFunction; protected boolean inGenerator; protected boolean inAsync; protected boolean inTemplateElement; protected int pos; protected int lineStart; protected int curLine; protected int start; protected int end; protected TokenType type; protected Object value; protected Position startLoc; protected Position endLoc; protected Position lastTokEndLoc, lastTokStartLoc; protected int lastTokStart, lastTokEnd; protected Stack<TokContext> context; protected int potentialArrowAt; private Stack<LabelInfo> labels; protected int yieldPos, awaitPos; /** * For readability purposes, we pass this instead of false as the argument to * the hasDeclareKeyword parameter (which only exists in TypeScript). */ private static final boolean noDeclareKeyword = false; /** * For readability purposes, we pass this instead of false as the argument to * the isAbstract parameter (which only exists in TypeScript). */ protected static final boolean notAbstract = false; /** * For readability purposes, we pass this instead of null as the argument to the * type annotation parameters (which only exists in TypeScript). */ private static final ITypeExpression noTypeAnnotation = null; protected static class LabelInfo { String name, kind; int statementStart; public LabelInfo(String name, String kind, int statementStart) { this.name = name; this.kind = kind; this.statementStart = statementStart; } } public static void main(String[] args) { new Parser(new Options(), new WholeIO().strictread(new File(args[0])), 0).parse(); } /// begin state.js public Parser(Options options, String input, int startPos) { this.options = options; this.keywords = new LinkedHashSet<String>(Identifiers.keywords.get(options.ecmaVersion() >= 6 ? Identifiers.Dialect.ECMA_6 : Identifiers.Dialect.ECMA_5)); this.reservedWords = new LinkedHashSet<String>(); if (!options.allowReserved().isTrue()) { this.reservedWords.addAll(Identifiers.reservedWords.get(options.getDialect())); if (options.sourceType().equals("module")) this.reservedWords.add("await"); } this.reservedWordsStrict = new LinkedHashSet<String>(this.reservedWords); this.reservedWordsStrict.addAll(Identifiers.reservedWords.get(Dialect.STRICT)); this.reservedWordsStrictBind = new LinkedHashSet<String>(this.reservedWordsStrict); this.reservedWordsStrictBind.addAll(Identifiers.reservedWords.get(Dialect.STRICT_BIND)); this.input = input; // Used to signal to callers of `readWord1` whether the word // contained any escape sequences. This is needed because words with // escape sequences must not be interpreted as keywords. this.containsEsc = false; // Set up token state // The current position of the tokenizer in the input. if (startPos != 0) { this.pos = startPos; this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; this.curLine = inputSubstring(0, this.lineStart).split(Whitespace.lineBreak).length; } else { this.pos = this.lineStart = 0; this.curLine = 1; } // Properties of the current token: // Its type this.type = TokenType.eof; // For tokens that include more information than their type, the value this.value = null; // Its start and end offset this.start = this.end = this.pos; // And, if locations are used, the {line, column} object // corresponding to those offsets this.startLoc = this.endLoc = this.curPosition(); // Position information for the previous token this.lastTokEndLoc = this.lastTokStartLoc = null; this.lastTokStart = this.lastTokEnd = this.pos; // The context stack is used to superficially track syntactic // context to predict whether a regular expression is allowed in a // given position. this.context = this.initialContext(); this.exprAllowed = true; // Figure out if it's a module code. this.strict = this.inModule = options.sourceType().equals("module"); // Used to signify the start of a potential arrow function this.potentialArrowAt = -1; // Flags to track whether we are in a function, a generator, an async function. this.inFunction = this.inGenerator = this.inAsync = false; // Positions to delayed-check that yield/await does not exist in default parameters. this.yieldPos = this.awaitPos = 0; // Labels in scope. this.labels = new Stack<LabelInfo>(); // If enabled, skip leading hashbang line. if (this.pos == 0 && options.allowHashBang() && this.input.startsWith("#!")) this.skipLineComment(2); } public Program parse() { Position startLoc = this.startLoc; this.nextToken(); return this.parseTopLevel(startLoc, this.options.program()); } /// end state.js /// begin location.js protected void raise(int pos, String msg, boolean recoverable) { Position loc = Locutil.getLineInfo(input, pos); raise(loc, msg, recoverable); } protected void raise(int pos, String msg) { raise(pos, msg, false); } protected void raise(Position loc, String msg, boolean recoverable) { msg += " (" + loc.getLine() + ":" + loc.getColumn() + ")"; SyntaxError err = new SyntaxError(msg, loc, this.pos); if (recoverable && options.onRecoverableError() != null) options.onRecoverableError().apply(err); else throw err; } protected void raise(Position loc, String msg) { raise(loc, msg, false); } protected void raise(INode nd, String msg) { raise(nd.getLoc().getStart(), msg, false); } protected void raiseRecoverable(int pos, String msg) { raise(pos, msg, true); } protected void raiseRecoverable(INode nd, String msg) { raise(nd.getLoc().getStart(), msg, true); } protected Position curPosition() { return new Position(curLine, pos - lineStart, pos); } /// end location.js /// begin tokenize.js // Move to the next token protected void next() { if (this.options.onToken() != null) this.options.onToken().apply(mkToken()); this.lastTokEnd = this.end; this.lastTokStart = this.start; this.lastTokEndLoc = this.endLoc; this.lastTokStartLoc = this.startLoc; this.nextToken(); } // Toggle strict mode. Re-reads the next number or string to please // pedantic tests (`"use strict"; 010;` should fail). public void setStrict(boolean strict) { this.strict = strict; if (this.type != TokenType.num && this.type != TokenType.string) return; this.pos = this.start; while (this.pos < this.lineStart) { this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1; --this.curLine; } this.nextToken(); } public TokContext curContext() { return context.peek(); } // Read a single token, updating the parser object's token-related // properties. public Token nextToken() { TokContext curContext = this.curContext(); if (curContext == null || !curContext.preserveSpace) this.skipSpace(); this.start = this.pos; this.startLoc = this.curPosition(); if (this.pos >= this.input.length()) return this.finishToken(TokenType.eof); if (curContext != null && curContext.override != null) return curContext.override.apply(this); else return this.readToken(this.fullCharCodeAtPos()); } protected Token readToken(int code) { // Identifier or keyword. '\\uXXXX' sequences are allowed in // identifiers, so '\' also dispatches to that. if (Identifiers.isIdentifierStart(code, this.options.ecmaVersion() >= 6) || code == 92 ) return this.readWord(); return this.getTokenFromCode(code); } protected int fullCharCodeAtPos() { int code = charAt(this.pos); if (code <= 0xd7ff || code >= 0xe000) return code; int next = charAt(this.pos + 1); return (code << 10) + next - 0x35fdc00; } protected void skipBlockComment() { Position startLoc = this.options.onComment() != null ? this.curPosition() : null; int start = this.pos, end = this.input.indexOf("*/", this.pos += 2); if (end == -1) this.raise(this.pos - 2, "Unterminated comment"); this.pos = end + 2; Matcher m = Whitespace.lineBreakG.matcher(this.input); int next = start; while (m.find(next) && m.start() < this.pos) { ++this.curLine; lineStart = m.end(); next = lineStart; } if (this.options.onComment() != null) this.options.onComment().call(true, this.input, inputSubstring(start + 2, end), start, this.pos, startLoc, this.curPosition()); } protected void skipLineComment(int startSkip) { int start = this.pos; Position startLoc = this.options.onComment() != null ? this.curPosition() : null; this.pos += startSkip; int ch = charAt(this.pos); while (this.pos < this.input.length() && ch != 10 && ch != 13 && ch != 8232 && ch != 8233) { ++this.pos; ch = charAt(this.pos); } if (this.options.onComment() != null) this.options.onComment().call(false, this.input, inputSubstring(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition()); } // Called at the start of the parse and after every token. Skips // whitespace and comments, and. protected void skipSpace() { loop: while (this.pos < this.input.length()) { int ch = this.input.charAt(this.pos); switch (ch) { case 32: case 160: ++this.pos; break; case 13: if (charAt(this.pos + 1) == 10) { ++this.pos; } case 10: case 8232: case 8233: ++this.pos; ++this.curLine; this.lineStart = this.pos; break; case 47: switch (charAt(this.pos + 1)) { case 42: this.skipBlockComment(); break; case 47: this.skipLineComment(2); break; default: break loop; } break; default: if (ch > 8 && ch < 14 || ch >= 5760 && Whitespace.nonASCIIwhitespace.indexOf(ch) > -1) { ++this.pos; } else { break loop; } } } } // Called at the end of every token. Sets `end`, `val`, and // maintains `context` and `exprAllowed`, and skips the space after // the token, so that the next one's `start` will point at the // right position. protected Token finishToken(TokenType type, Object val) { this.end = this.pos; this.endLoc = this.curPosition(); TokenType prevType = this.type; this.type = type; this.value = val; this.updateContext(prevType); return mkToken(); } private Token mkToken() { String src = inputSubstring(start, end); SourceLocation loc = new SourceLocation(src, startLoc, endLoc); String label, keyword; if (isKeyword(src)) { label = keyword = src; } else { label = type.label; keyword = type.keyword; } return new Token(loc, label, keyword); } protected boolean isKeyword(String src) { if (type.keyword != null) return true; if (type == TokenType.name) { if (keywords.contains(src)) return true; if (options.ecmaVersion() >= 6 && ("let".equals(src) || "yield".equals(src))) return true; } return false; } protected Token finishToken(TokenType type) { return finishToken(type, null); } // ### Token reading // This is the function that is called to fetch the next token. It // is somewhat obscure, because it works in character codes rather // than characters, and because operator parsing has been inlined // into it. // All in the name of speed. private Token readToken_dot() { int next = charAt(this.pos + 1); if (next >= 48 && next <= 57) return this.readNumber(true); int next2 = charAt(this.pos + 2); if (this.options.ecmaVersion() >= 6 && next == 46 && next2 == 46) { // 46 = dot '.' this.pos += 3; return this.finishToken(TokenType.ellipsis); } else { ++this.pos; return this.finishToken(TokenType.dot); } } private Token readToken_question() { int next = charAt(this.pos + 1); int next2 = charAt(this.pos + 2); if (this.options.esnext()) { if (next == '.' && !('0' <= next2 && next2 <= '9')) // '?.', but not '?.X' where X is a digit return this.finishOp(TokenType.questiondot, 2); if (next == '?') return this.finishOp(TokenType.questionquestion, 2); } return this.finishOp(TokenType.question, 1); } private Token readToken_slash() { int next = charAt(this.pos + 1); if (this.exprAllowed) { ++this.pos; return this.readRegexp(); } if (next == 61) return this.finishOp(TokenType.assign, 2); return this.finishOp(TokenType.slash, 1); } private Token readToken_mult_modulo_exp(int code) { int next = charAt(this.pos + 1); int size = 1; TokenType tokentype = code == 42 ? TokenType.star : TokenType.modulo; // exponentiation operator ** and **= if (this.options.ecmaVersion() >= 7 && code == 42 && next == 42) { ++size; tokentype = TokenType.starstar; next = charAt(this.pos + 2); } if (next == 61) return this.finishOp(TokenType.assign, size + 1); return this.finishOp(tokentype, size); } private Token readToken_pipe_amp(int code) { int next = charAt(this.pos + 1); if (next == code) return this.finishOp(code == 124 ? TokenType.logicalOR : TokenType.logicalAND, 2); if (next == 61) return this.finishOp(TokenType.assign, 2); return this.finishOp(code == 124 ? TokenType.bitwiseOR : TokenType.bitwiseAND, 1); } private Token readToken_caret() { int next = charAt(this.pos + 1); if (next == 61) return this.finishOp(TokenType.assign, 2); return this.finishOp(TokenType.bitwiseXOR, 1); } private Token readToken_plus_min(int code) { int next = charAt(this.pos + 1); if (next == code) { if (next == 45 && charAt(this.pos + 2) == 62 && inputSubstring(this.lastTokEnd, this.pos).matches("(?s).*(?:" + lineBreak + ").*")) { // A `-->` line comment this.skipLineComment(3); this.skipSpace(); return this.nextToken(); } return this.finishOp(TokenType.incDec, 2); } if (next == 61) return this.finishOp(TokenType.assign, 2); return this.finishOp(TokenType.plusMin, 1); } private Token readToken_lt_gt(int code) { int next = charAt(this.pos + 1); int size = 1; if (next == code) { size = code == 62 && charAt(this.pos + 2) == 62 ? 3 : 2; if (charAt(this.pos + size) == 61) return this.finishOp(TokenType.assign, size + 1); return this.finishOp(TokenType.bitShift, size); } if (next == 33 && code == 60 && charAt(this.pos + 2) == 45 && charAt(this.pos + 3) == 45) { if (this.inModule) this.unexpected(); // `<!--`, an XML-style comment that should be interpreted as a line comment this.skipLineComment(4); this.skipSpace(); return this.nextToken(); } if (next == 61) size = 2; return this.finishOp(TokenType.relational, size); } private Token readToken_eq_excl(int code) { int next = charAt(this.pos + 1); if (next == 61) return this.finishOp(TokenType.equality, charAt(this.pos + 2) == 61 ? 3 : 2); if (code == 61 && next == 62 && this.options.ecmaVersion() >= 6) { this.pos += 2; return this.finishToken(TokenType.arrow); } return this.finishOp(code == 61 ? TokenType.eq : TokenType.prefix, 1); } protected Token getTokenFromCode(int code) { switch (code) { // The interpretation of a dot depends on whether it is followed // by a digit or another two dots. case 46: return this.readToken_dot(); // Punctuation tokens. case 40: ++this.pos; return this.finishToken(TokenType.parenL); case 41: ++this.pos; return this.finishToken(TokenType.parenR); case 59: ++this.pos; return this.finishToken(TokenType.semi); case 44: ++this.pos; return this.finishToken(TokenType.comma); case 91: ++this.pos; return this.finishToken(TokenType.bracketL); case 93: ++this.pos; return this.finishToken(TokenType.bracketR); case 123: ++this.pos; return this.finishToken(TokenType.braceL); case 125: ++this.pos; return this.finishToken(TokenType.braceR); case 58: ++this.pos; return this.finishToken(TokenType.colon); case 63: return this.readToken_question(); case 96: if (this.options.ecmaVersion() < 6) break; ++this.pos; return this.finishToken(TokenType.backQuote); case 48: int next = charAt(this.pos + 1); if (next == 120 || next == 88) return this.readRadixNumber(16); // '0x', '0X' - hex number if (this.options.ecmaVersion() >= 6) { if (next == 111 || next == 79) return this.readRadixNumber(8); // '0o', '0O' - octal number if (next == 98 || next == 66) return this.readRadixNumber(2); // '0b', '0B' - binary number } // Anything else beginning with a digit is an integer, octal // number, or float. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return this.readNumber(false); // Quotes produce strings. case 34: case 39: return this.readString((char)code); // Operators are parsed inline in tiny state machines. '=' (61) is // often referred to. `finishOp` simply skips the amount of // characters it is given as second argument, and returns a token // of the type given by its first argument. case 47: return this.readToken_slash(); case 37: case 42: return this.readToken_mult_modulo_exp(code); case 124: case 38: return this.readToken_pipe_amp(code); case 94: return this.readToken_caret(); case 43: case 45: return this.readToken_plus_min(code); case 60: case 62: return this.readToken_lt_gt(code); case 61: case 33: return this.readToken_eq_excl(code); case 126: return this.finishOp(TokenType.prefix, 1); } this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); return null; } protected Token finishOp(TokenType type, int size) { String str = inputSubstring(this.pos, this.pos + size); this.pos += size; return this.finishToken(type, str); } private Token readRegexp() { boolean escaped = false, inClass = false; int start = this.pos; for (;;) { if (this.pos >= this.input.length()) this.raise(start, "Unterminated regular expression"); int ch = this.input.charAt(this.pos); if (isNewLine(ch)) this.raise(start, "Unterminated regular expression"); if (!escaped) { if (ch == '[') inClass = true; else if (ch == ']' && inClass) inClass = false; else if (ch == '/' && !inClass) break; escaped = ch == '\\'; } else { escaped = false; } ++this.pos; } String content = inputSubstring(start, this.pos); ++this.pos; // Need to use `readWord1` because '\\uXXXX' sequences are allowed // here (don't ask). String mods = this.readWord1(); if (mods != null) { String validFlags = "gim"; if (this.options.ecmaVersion() >= 6) validFlags = "gimuy"; if (this.options.ecmaVersion() >= 9) validFlags = "gimsuy"; if (!mods.matches("^[" + validFlags + "]*$")) this.raise(start, "Invalid regular expression flag"); if (mods.indexOf('u') >= 0) { Matcher m = Pattern.compile("\\\\u\\{([0-9a-fA-F]+)\\}").matcher(content); while (m.find()) { try { int code = Integer.parseInt(m.group(1), 16); if (code > 0x10FFFF) this.raiseRecoverable(start + m.start() + 3, "Code point out of bounds"); } catch (NumberFormatException nfe) { Exceptions.ignore(nfe, "Don't complain about code points we don't understand."); } } } } return this.finishToken(TokenType.regexp, content); } // Read an integer in the given radix. Return null if zero digits // were read, the integer value otherwise. When `len` is given, this // will return `null` unless the integer has exactly `len` digits. protected Number readInt(int radix, Integer len) { int start = this.pos; double total = 0; for (int i = 0, e = len == null ? Integer.MAX_VALUE : len; i < e; ++i) { if (this.pos >= this.input.length()) break; int code = this.input.charAt(this.pos), val; if (code >= 97) val = code - 97 + 10; else if (code >= 65) val = code - 65 + 10; else if (code >= 48 && code <= 57) val = code - 48; else val = Integer.MAX_VALUE; if (val >= radix) break; ++this.pos; total = total * radix + val; } if (this.pos == start || len != null && this.pos - start != len) return null; return total; } protected Token readRadixNumber(int radix) { this.pos += 2; Number val = this.readInt(radix, null); if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix); // check for bigint literal if (options.esnext() && this.fullCharCodeAtPos() == 'n') { ++this.pos; return this.finishToken(TokenType.bigint, val); } if (Identifiers.isIdentifierStart(this.fullCharCodeAtPos(), false)) this.raise(this.pos, "Identifier directly after number"); return this.finishToken(TokenType.num, val); } // Read an integer, octal integer, or floating-point number. protected Token readNumber(boolean startsWithDot) { int start = this.pos; boolean isFloat = false, octal = charAt(this.pos) == 48, isBigInt = false; if (!startsWithDot && this.readInt(10, null) == null) this.raise(start, "Invalid number"); if (octal && this.pos == start + 1) octal = false; if (this.pos < this.input.length()) { int next = this.input.charAt(this.pos); if (next == 46 && !octal) { ++this.pos; this.readInt(10, null); isFloat = true; next = charAt(this.pos); } if ((next == 69 || next == 101) && !octal) { next = charAt(++this.pos); if (next == 43 || next == 45) ++this.pos; if (this.readInt(10, null) == null) this.raise(start, "Invalid number"); isFloat = true; } if (!isFloat && options.esnext() && this.fullCharCodeAtPos() == 'n') isBigInt = true; else if (Identifiers.isIdentifierStart(this.fullCharCodeAtPos(), false)) this.raise(this.pos, "Identifier directly after number"); } String str = inputSubstring(start, this.pos); Number val = null; if (isFloat) val = parseFloat(str); else if (!octal || str.length() == 1) val = parseInt(str, 10); else if (str.matches(".*[89].*") || this.strict) this.raise(start, "Invalid number"); else val = parseInt(str, 8); // handle bigints if (isBigInt) { ++this.pos; return this.finishToken(TokenType.bigint, val); } return this.finishToken(TokenType.num, val); } // Read a string value, interpreting backslash-escapes. protected int readCodePoint() { int ch = charAt(this.pos), code; if (ch == 123) { if (this.options.ecmaVersion() < 6) this.unexpected(); int codePos = ++this.pos; code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos); ++this.pos; if (code > 0x10FFFF) this.invalidStringToken(codePos, "Code point out of bounds"); } else { code = this.readHexChar(4); } return code; } protected String codePointToString(int code) { // UTF-16 Decoding if (code <= 0xFFFF) return String.valueOf((char)code); code -= 0x10000; return new String(new char[] { (char)((code >> 10) + 0xD800), (char)((code & 1023) + 0xDC00) }); } protected Token readString(char quote) { StringBuilder out = new StringBuilder(); int chunkStart = ++this.pos; for (;;) { if (this.pos >= this.input.length()) this.raise(this.start, "Unterminated string constant"); int ch = this.input.charAt(this.pos); if (ch == quote) break; if (ch == 92) { out.append(inputSubstring(chunkStart, this.pos)); out.append(this.readEscapedChar(false)); chunkStart = this.pos; } else { if (Whitespace.isNewLine(ch)) this.raise(this.start, "Unterminated string constant"); ++this.pos; } } out.append(inputSubstring(chunkStart, this.pos++)); return this.finishToken(TokenType.string, out.toString()); } // Reads template string tokens. private static final RuntimeException INVALID_TEMPLATE_ESCAPE_ERROR = new RuntimeException(); private Token tryReadTemplateToken() { this.inTemplateElement = true; try { return this.readTmplToken(); } catch (RuntimeException err) { if (err == INVALID_TEMPLATE_ESCAPE_ERROR) { return this.readInvalidTemplateToken(); } else { throw err; } } finally { this.inTemplateElement = false; } } private void invalidStringToken(int position, String message) { if (this.inTemplateElement && this.options.ecmaVersion() >= 9) { throw INVALID_TEMPLATE_ESCAPE_ERROR; } else { this.raise(position, message); } } protected Token readTmplToken() { StringBuilder out = new StringBuilder(); int chunkStart = this.pos; for (;;) { if (this.pos >= this.input.length()) this.raise(this.start, "Unterminated template"); int ch = this.input.charAt(this.pos); if (ch == 96 || ch == 36 && charAt(this.pos + 1) == 123) { if (this.pos == this.start && (this.type == TokenType.template || this.type == TokenType.invalidTemplate)) { if (ch == 36) { this.pos += 2; return this.finishToken(TokenType.dollarBraceL); } else { ++this.pos; return this.finishToken(TokenType.backQuote); } } out.append(inputSubstring(chunkStart, this.pos)); return this.finishToken(TokenType.template, out.toString()); } if (ch == 92) { out.append(inputSubstring(chunkStart, this.pos)); out.append(this.readEscapedChar(true)); chunkStart = this.pos; } else if (Whitespace.isNewLine(ch)) { out.append(inputSubstring(chunkStart, this.pos)); ++this.pos; switch (ch) { case 13: if (charAt(this.pos) == 10) ++this.pos; case 10: out.append('\n'); break; default: out.append((char)ch); break; } ++this.curLine; this.lineStart = this.pos; chunkStart = this.pos; } else { ++this.pos; } } } // Reads a template token to search for the end, without validating any escape sequences private Token readInvalidTemplateToken() { for (; this.pos < this.input.length(); this.pos++) { switch (this.input.charAt(this.pos)) { case '\\': ++this.pos; break; case '$': if (this.charAt(this.pos + 1) != '{') { break; } // falls through case '`': return this.finishToken(TokenType.invalidTemplate, this.inputSubstring(this.start, this.pos)); // no default } } this.raise(this.start, "Unterminated template"); return null; } // Used to read escaped characters protected String readEscapedChar(boolean inTemplate) { int ch = charAt(++this.pos); ++this.pos; switch (ch) { case 110: return "\n"; // 'n' -> '\n' case 114: return "\r"; // 'r' -> '\r' case 120: return String.valueOf((char)this.readHexChar(2)); case 117: return codePointToString(this.readCodePoint()); case 116: return "\t"; // 't' -> '\t' case 98: return "\b"; // 'b' -> '\b' case 118: return "\u000b"; // 'v' -> '\u000b' case 102: return "\f"; // 'f' -> '\f' case 13: if (charAt(this.pos) == 10) ++this.pos; case 10: this.lineStart = this.pos; ++this.curLine; return ""; default: if (ch >= 48 && ch <= 55) { String octalStr = inputSubstring(this.pos - 1, this.pos + 2); Matcher m = Pattern.compile("^[0-7]+").matcher(octalStr); m.find(); octalStr = m.group(); int octal = parseInt(octalStr, 8).intValue(); if (octal > 255) { octalStr = octalStr.substring(0, octalStr.length()-1); octal = parseInt(octalStr, 8).intValue(); } if (!octalStr.equals("0") && (this.strict || inTemplate)) { this.invalidStringToken(this.pos - 2, "Octal literal in strict mode"); } this.pos += octalStr.length() - 1; return String.valueOf((char)octal); } return String.valueOf((char)ch); } } // Used to read character escape sequences ('\x', '\\u', '\U'). protected int readHexChar(int len) { int codePos = this.pos; Number n = this.readInt(16, len); if (n == null) this.invalidStringToken(codePos, "Bad character escape sequence"); return n.intValue(); } // Read an identifier, and return it as a string. Sets `this.containsEsc` // to whether the word contained a '\\u' escape. // Incrementally adds only escaped chars, adding other chunks as-is // as a micro-optimization. protected String readWord1() { this.containsEsc = false; String word = ""; boolean first = true; int chunkStart = this.pos; boolean astral = this.options.ecmaVersion() >= 6; while (this.pos < this.input.length()) { int ch = this.fullCharCodeAtPos(); if (Identifiers.isIdentifierChar(ch, astral)) { this.pos += ch <= 0xffff ? 1 : 2; } else if (ch == 92) { this.containsEsc = true; word += inputSubstring(chunkStart, this.pos); int escStart = this.pos; if (charAt(++this.pos) != 117) this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); ++this.pos; int esc = this.readCodePoint(); if (!(first ? Identifiers.isIdentifierStart(esc, astral) : Identifiers.isIdentifierChar(esc, astral))) this.invalidStringToken(escStart, "Invalid Unicode escape"); word += codePointToString(esc); chunkStart = this.pos; } else { break; } first = false; } return word + inputSubstring(chunkStart, this.pos); } // Read an identifier or keyword token. Will check for reserved // words when necessary. protected Token readWord() { String word = this.readWord1(); TokenType type = TokenType.name; if ((this.options.ecmaVersion() >= 6 || !this.containsEsc) && this.keywords.contains(word)) type = TokenType.keywords.get(word); return this.finishToken(type, word); } /// end tokenize.js /// begin parseutil.js // ## Parser utilities // Test whether a statement node is the string literal `"use strict"`. protected boolean isUseStrict(Statement stmt) { if (!(this.options.ecmaVersion() >= 5 && stmt instanceof ExpressionStatement)) return false; Expression e = ((ExpressionStatement) stmt).getExpression(); if (!(e instanceof Literal)) return false; String raw = ((Literal) e).getRaw(); return raw.length() >= 2 && raw.substring(1, raw.length()-1).equals("use strict"); } // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. protected boolean eat(TokenType type) { if (this.type == type) { this.next(); return true; } else { return false; } } // Tests whether parsed token is a contextual keyword. protected boolean isContextual(String name) { return this.type == TokenType.name && Objects.equals(this.value, name); } // Consumes contextual keyword if possible. protected boolean eatContextual(String name) { return Objects.equals(this.value, name) && this.eat(TokenType.name); } // Asserts that following token is given contextual keyword. protected void expectContextual(String name) { if (!this.eatContextual(name)) this.unexpected(); } private static final Pattern CONTAINS_LINEBREAK = Pattern.compile("(?s).*(?:" + lineBreak + ").*"); // Test whether a semicolon can be inserted at the current position. protected boolean canInsertSemicolon() { return this.type == TokenType.eof || this.type == TokenType.braceR || CONTAINS_LINEBREAK.matcher(inputSubstring(this.lastTokEnd, this.start)).matches(); } protected boolean insertSemicolon() { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon() != null) this.options.onInsertedSemicolon().apply(this.lastTokEnd, this.lastTokEndLoc); return true; } return false; } // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. protected void semicolon() { if (!this.eat(TokenType.semi) && !this.insertSemicolon()) this.unexpected(); } protected boolean afterTrailingComma(TokenType tokType, boolean notNext) { if (this.type == tokType) { if (this.options.onTrailingComma() != null) this.options.onTrailingComma().apply(this.lastTokStart, this.lastTokStartLoc); if (!notNext) this.next(); return true; } return false; } // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. protected void expect(TokenType type) { if (!this.eat(type)) this.unexpected(); } // Raise an unexpected token error. protected void unexpected(Integer pos) { this.raise(pos != null ? pos : this.start, "Unexpected token"); } protected void unexpected(Position pos) { this.raise(pos, "Unexpected token"); } protected void unexpected() { unexpected((Integer)null); } public static class DestructuringErrors { private int shorthandAssign, trailingComma; public void reset() { this.shorthandAssign = 0; this.trailingComma = 0; } } protected boolean checkPatternErrors(DestructuringErrors refDestructuringErrors, boolean andThrow) { int trailing = refDestructuringErrors != null ? refDestructuringErrors.trailingComma : 0; if (!andThrow) return trailing != 0; if (trailing != 0) this.raise(trailing, "Comma is not permitted after the rest element"); return false; } protected boolean checkExpressionErrors(DestructuringErrors refDestructuringErrors, boolean andThrow) { int pos = refDestructuringErrors != null ? refDestructuringErrors.shorthandAssign : 0; if (!andThrow) return pos != 0; if (pos != 0) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns"); return false; } private void checkYieldAwaitInDefaultParams() { if (this.yieldPos > 0 && (this.awaitPos == 0 || this.yieldPos < this.awaitPos)) this.raise(this.yieldPos, "Yield expression cannot be a default value"); if (this.awaitPos > 0) this.raise(this.awaitPos, "Await expression cannot be a default value"); } /// end parseutil.js /// begin node.js protected <T extends INode> T finishNode(T node) { return finishNodeAt(node, this.lastTokEndLoc); } protected <T extends INode> T finishNodeAt(T node, Position pos) { SourceLocation loc = node.getLoc(); loc.setSource(inputSubstring(loc.getStart().getOffset(), pos.getOffset())); loc.setEnd(pos); return node; } /// begin expression.js protected static class PropInfo { boolean init, get, set; boolean is(Property.Kind kind) { switch (kind) { case INIT: return init; case GET: return get; case SET: return set; default: throw new CatastrophicError("Unexpected kind " + kind + "."); } } void set(Property.Kind kind) { switch (kind) { case INIT: init = true; break; case GET: get = true; break; case SET: set = true; break; default: throw new CatastrophicError("Unexpected kind " + kind + "."); } } } // Check if property name clashes with already added. // strict mode, init properties are also not allowed to be repeated. private void checkPropClash(Property prop, Map<String, PropInfo> propHash) { if (this.options.ecmaVersion() >= 6 && (prop.isComputed() || prop.isMethod() || prop.isShorthand())) return; Expression key = prop.getKey(); String name; if (key instanceof Identifier) name = ((Identifier) key).getName(); else if (key instanceof Literal) name = ((Literal) key).getStringValue(); else return; Property.Kind kind = prop.getKind(); if (this.options.ecmaVersion() >= 6) { if ("__proto__".equals(name) && kind == Property.Kind.INIT) { if (propHash.containsKey(name)) this.raiseRecoverable(key, "Redefinition of __proto__ property"); PropInfo pi = new PropInfo(); pi.set(Property.Kind.INIT); propHash.put(name, pi); } return; } PropInfo other = propHash.get(name); if (other != null) { boolean isGetSet = kind.isAccessor; if ((this.strict || isGetSet) && other.is(kind) || !(isGetSet ^ other.init)) this.raiseRecoverable(key, "Redefinition of property"); } else { propHash.put(name, other = new PropInfo()); } other.set(kind); } // ### Expression parsing // These nest, from the most general expression type at the top to // 'atomic', nondivisible expression types at the bottom. Most of // the functions will simply let the function(s) below them parse, // and, *if* the syntactic construct they handle is present, wrap // the AST node that the inner parser gave them in another node. // Parse a full expression. The optional arguments are used to // forbid the `in` operator (in for loops initalization expressions) // and provide reference for storing '=' operator inside shorthand // property assignment in contexts where both object expression // and object pattern might appear (so it's possible to raise // delayed syntax error at correct position). protected Expression parseExpression(boolean noIn, DestructuringErrors refDestructuringErrors) { Position startLoc = this.startLoc; Expression expr = this.parseMaybeAssign(noIn, refDestructuringErrors, null); if (this.type == TokenType.comma) { List<Expression> expressions = CollectionUtil.makeList(expr); SequenceExpression node = new SequenceExpression(new SourceLocation(startLoc), expressions); while (this.eat(TokenType.comma)) expressions.add(this.parseMaybeAssign(noIn, refDestructuringErrors, null)); return this.finishNode(node); } return expr; } public interface AfterLeftParse { Expression call(Expression left, int startPos, Position startLoc); } // Parse an assignment expression. This includes applications of // operators like `+=`. protected Expression parseMaybeAssign(boolean noIn, DestructuringErrors refDestructuringErrors, AfterLeftParse afterLeftParse) { if (this.inGenerator && this.isContextual("yield")) return this.parseYield(); boolean ownDestructuringErrors = false; if (refDestructuringErrors == null) { refDestructuringErrors = new DestructuringErrors(); ownDestructuringErrors = true; } int startPos = this.start; Position startLoc = this.startLoc; if (this.type == TokenType.parenL || this.type == TokenType.name) this.potentialArrowAt = this.start; Expression left = this.parseMaybeConditional(noIn, refDestructuringErrors); if (afterLeftParse != null) left = afterLeftParse.call(left, startPos, startLoc); if (this.type.isAssign) { this.checkPatternErrors(refDestructuringErrors, true); if (!ownDestructuringErrors) refDestructuringErrors.reset(); Expression l = this.type == TokenType.eq ? (Expression) this.toAssignable(left, false) : left; refDestructuringErrors.shorthandAssign = 0; // reset because shorthand default was used correctly String operator = String.valueOf(this.value); this.checkLVal(l, false, null); this.next(); Expression r = this.parseMaybeAssign(noIn, null, null); AssignmentExpression node = new AssignmentExpression(new SourceLocation(startLoc), operator, l, r); return this.finishNode(node); } else { if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true); } return left; } // Parse a ternary conditional (`?:`) operator. protected Expression parseMaybeConditional(boolean noIn, DestructuringErrors refDestructuringErrors) { Position startLoc = this.startLoc; Expression expr = this.parseExprOps(noIn, refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors, false)) return expr; if (this.eat(TokenType.question)) { return parseConditionalRest(noIn, startLoc, expr); } return expr; } protected Expression parseConditionalRest(boolean noIn, Position start, Expression test) { Expression consequent = this.parseMaybeAssign(false, null, null); this.expect(TokenType.colon); Expression alternate = this.parseMaybeAssign(noIn, null, null); ConditionalExpression node = new ConditionalExpression(new SourceLocation(start), test, consequent, alternate); return this.finishNode(node); } // Start the precedence parser. protected Expression parseExprOps(boolean noIn, DestructuringErrors refDestructuringErrors) { int startPos = this.start; Position startLoc = this.startLoc; Expression expr = this.parseMaybeUnary(refDestructuringErrors, false); if (this.checkExpressionErrors(refDestructuringErrors, false)) return expr; return this.parseExprOp(expr, startPos, startLoc, -1, noIn); } // Parse binary operators with the operator precedence parsing // algorithm. `left` is the left-hand side of the operator. // `minPrec` provides context that allows the function to stop and // defer further parser to one of its callers when it encounters an // operator that has a lower precedence than the set it is parsing. protected Expression parseExprOp(Expression left, int leftStartPos, Position leftStartLoc, int minPrec, boolean noIn) { int prec = this.type.binop; if (prec != 0 && (!noIn || this.type != TokenType._in)) { if (prec > minPrec) { boolean logical = this.type == TokenType.logicalOR || this.type == TokenType.logicalAND; String op = String.valueOf(this.value); this.next(); int startPos = this.start; Position startLoc = this.startLoc; Expression right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn); Expression node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical); return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn); } } return left; } private Expression buildBinary(int startPos, Position startLoc, Expression left, Expression right, String op, boolean logical) { SourceLocation loc = new SourceLocation(startLoc); Expression node = logical ? new LogicalExpression(loc, op, left, right) : new BinaryExpression(loc, op, left, right); return this.finishNode(node); } // Parse unary operators, both prefix and postfix. protected Expression parseMaybeUnary(DestructuringErrors refDestructuringErrors, boolean sawUnary) { int startPos = this.start; Position startLoc = this.startLoc; Expression expr; if (this.inAsync && this.isContextual("await")) { expr = this.parseAwait(); sawUnary = true; } else if (this.type.isPrefix) { String operator = String.valueOf(this.value); boolean update = this.type == TokenType.incDec; this.next(); Expression argument = this.parseMaybeUnary(null, true); SourceLocation loc = new SourceLocation(startLoc); Expression node = update ? new UpdateExpression(loc, operator, argument, true) : new UnaryExpression(loc, operator, argument, true); this.checkExpressionErrors(refDestructuringErrors, true); if (update) this.checkLVal(argument, false, null); else if (this.strict && operator.equals("delete") && argument instanceof Identifier) this.raiseRecoverable(node, "Deleting local variable in strict mode"); else sawUnary = true; expr = this.finishNode(node); } else { expr = this.parseExprSubscripts(refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors, false)) return expr; while (this.type.isPostfix && !this.canInsertSemicolon()) { UpdateExpression node = new UpdateExpression(new SourceLocation(startLoc), String.valueOf(this.value), expr, false); this.checkLVal(expr, false, null); this.next(); expr = this.finishNode(node); } } if (!sawUnary && this.eat(TokenType.starstar)) return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false); else return expr; } // Parse call, dot, and `[]`-subscript expressions. protected Expression parseExprSubscripts(DestructuringErrors refDestructuringErrors) { int startPos = this.start; Position startLoc = this.startLoc; Expression expr = this.parseExprAtom(refDestructuringErrors); boolean skipArrowSubscripts = expr instanceof ArrowFunctionExpression && !inputSubstring(this.lastTokStart, this.lastTokEnd).equals(")"); if (this.checkExpressionErrors(refDestructuringErrors, false) || skipArrowSubscripts) return expr; return this.parseSubscripts(expr, startPos, startLoc, false); } protected Expression parseSubscripts(Expression base, int startPos, Position startLoc, boolean noCalls) { for (;;) { Pair<Expression, Boolean> p = parseSubscript(base, startLoc, noCalls); if (p.snd()) base = p.fst(); else return p.fst(); } } protected boolean isOnOptionalChain(boolean optional, Expression base) { return optional || base instanceof Chainable && ((Chainable)base).isOnOptionalChain(); } /** * Parse a single subscript {@code s}; if more subscripts could follow, return {@code Pair.make(s, true}, * otherwise return {@code Pair.make(s, false)}. */ protected Pair<Expression, Boolean> parseSubscript(final Expression base, Position startLoc, boolean noCalls) { boolean maybeAsyncArrow = this.options.ecmaVersion() >= 8 && base instanceof Identifier && "async".equals(((Identifier) base).getName()) && !this.canInsertSemicolon(); boolean optional = this.eat(TokenType.questiondot); if (this.eat(TokenType.bracketL)) { MemberExpression node = new MemberExpression(new SourceLocation(startLoc), base, this.parseExpression(false, null), true, optional, isOnOptionalChain(optional, base)); this.expect(TokenType.bracketR); return Pair.make(this.finishNode(node), true); } else if (!noCalls && this.eat(TokenType.parenL)) { DestructuringErrors refDestructuringErrors = new DestructuringErrors(); int oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos; this.yieldPos = 0; this.awaitPos = 0; List<Expression> exprList = this.parseExprList(TokenType.parenR, this.options.ecmaVersion() >= 8, false, refDestructuringErrors); if (maybeAsyncArrow && shouldParseAsyncArrow()) { this.checkPatternErrors(refDestructuringErrors, true); this.checkYieldAwaitInDefaultParams(); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; return Pair.make(this.parseArrowExpression(startLoc, exprList, true), false); } this.checkExpressionErrors(refDestructuringErrors, true); if (oldYieldPos > 0) this.yieldPos = oldYieldPos; if (oldAwaitPos > 0) this.awaitPos = oldAwaitPos; CallExpression node = new CallExpression(new SourceLocation(startLoc), base, new ArrayList<>(), exprList, optional, isOnOptionalChain(optional, base)); return Pair.make(this.finishNode(node), true); } else if (this.type == TokenType.backQuote) { if (isOnOptionalChain(optional, base)) { this.raise(base, "An optional chain may not be used in a tagged template expression."); } TaggedTemplateExpression node = new TaggedTemplateExpression(new SourceLocation(startLoc), base, this.parseTemplate(true)); return Pair.make(this.finishNode(node), true); } else if (optional || this.eat(TokenType.dot)) { MemberExpression node = new MemberExpression(new SourceLocation(startLoc), base, this.parseIdent(true), false, optional, isOnOptionalChain(optional, base)); return Pair.make(this.finishNode(node), true); } else { return Pair.make(base, false); } } protected boolean shouldParseAsyncArrow() { return !this.canInsertSemicolon() && this.eat(TokenType.arrow); } // expression, an expression started by a keyword like `function` or // `new`, or an expression wrapped in punctuation like `()`, `[]`, protected Expression parseExprAtom(DestructuringErrors refDestructuringErrors) { Expression node; boolean canBeArrow = this.potentialArrowAt == this.start; if (this.type == TokenType._super) { if (!this.inFunction) this.raise(this.start, "'super' outside of function or class"); node = new Super(new SourceLocation(this.startLoc)); this.next(); return this.finishNode(node); } else if (this.type == TokenType._this) { node = new ThisExpression(new SourceLocation(this.startLoc)); this.next(); return this.finishNode(node); } else if (this.type == TokenType.name) { Position startLoc = this.startLoc; Identifier id = this.parseIdent(this.type != TokenType.name); if (this.options.ecmaVersion() >= 8 && "async".equals(id.getName()) && !this.canInsertSemicolon() && this.eat(TokenType._function)) return (Expression) this.parseFunction(startLoc, false, false, true); if (canBeArrow && !this.canInsertSemicolon()) { if (this.eat(TokenType.arrow)) return this.parseArrowExpression(startLoc, CollectionUtil.makeList(id), false); if (this.options.ecmaVersion() >= 8 && id.getName().equals("async") && this.type == TokenType.name) { id = this.parseIdent(false); if (this.canInsertSemicolon() || !this.eat(TokenType.arrow)) this.unexpected(); return this.parseArrowExpression(startLoc, CollectionUtil.makeList(id), true); } } return id; } else if (this.type == TokenType.regexp || this.type == TokenType.num || this.type == TokenType.string || this.type == TokenType.bigint) { return this.parseLiteral(this.type, this.value); } else if (this.type == TokenType._null || this.type == TokenType._true || this.type == TokenType._false) { Object val = this.type == TokenType._null ? null : this.type == TokenType._true; node = new Literal(new SourceLocation(this.type.keyword, startLoc), this.type, val); this.next(); return this.finishNode(node); } else if (this.type == TokenType.parenL) { return this.parseParenAndDistinguishExpression(canBeArrow); } else if (this.type == TokenType.bracketL) { Position startLoc = this.startLoc; this.next(); List<Expression> elements = this.parseExprList(TokenType.bracketR, true, true, refDestructuringErrors); node = new ArrayExpression(new SourceLocation(startLoc), elements); return this.finishNode(node); } else if (this.type == TokenType.braceL) { return this.parseObj(false, refDestructuringErrors); } else if (this.type == TokenType._function) { Position startLoc = this.startLoc; this.next(); return (Expression) this.parseFunction(startLoc, false, false, false); } else if (this.type == TokenType._class) { return (Expression) this.parseClass(this.startLoc, false); } else if (this.type == TokenType._new) { return this.parseNew(); } else if (this.type == TokenType.backQuote) { return this.parseTemplate(false); } else { this.unexpected(); return null; } } protected Literal parseLiteral(TokenType tokenType, Object value) { SourceLocation loc = new SourceLocation(inputSubstring(this.start, this.end), this.startLoc); Literal node = new Literal(loc, tokenType, value); this.next(); return this.finishNode(node); } protected Expression parseParenExpression() { this.expect(TokenType.parenL); Expression val = this.parseExpression(false, null); this.expect(TokenType.parenR); return val; } protected Expression parseParenAndDistinguishExpression(boolean canBeArrow) { Position startLoc = this.startLoc; Expression val; if (this.options.ecmaVersion() >= 6) { this.next(); DestructuringErrors refDestructuringErrors = new DestructuringErrors(); int oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos; ParenthesisedExpressions parenExprs = parseParenthesisedExpressions(refDestructuringErrors); if (canBeArrow && !this.canInsertSemicolon() && this.eat(TokenType.arrow)) { this.checkPatternErrors(refDestructuringErrors, true); this.checkYieldAwaitInDefaultParams(); if (parenExprs.innerParenStart != 0) this.unexpected(parenExprs.innerParenStart); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; return this.parseParenArrowList(startLoc, parenExprs.exprList); } if (parenExprs.exprList.isEmpty() || parenExprs.lastIsComma) this.unexpected(this.lastTokStart); if (parenExprs.spreadStart != 0) this.unexpected(parenExprs.spreadStart); this.checkExpressionErrors(refDestructuringErrors, true); if (oldYieldPos > 0) this.yieldPos = oldYieldPos; if (oldAwaitPos > 0) this.awaitPos = oldAwaitPos; if (parenExprs.exprList.size() > 1) { val = new SequenceExpression(new SourceLocation(parenExprs.startLoc), parenExprs.exprList); this.finishNodeAt(val, parenExprs.endLoc); } else { val = parenExprs.exprList.get(0); } } else { val = this.parseParenExpression(); } if (this.options.preserveParens()) { ParenthesizedExpression par = new ParenthesizedExpression(new SourceLocation(startLoc), val); return this.finishNode(par); } else { return val; } } /** * Information about a list of expressions between parentheses. */ static protected class ParenthesisedExpressions { /** If non-zero, indicates the location of a spread expression in the list. */ int spreadStart = 0; /** If non-zero, indicates the location of a parenthesised expression in the list. */ int innerParenStart = 0; /** * The start position (i.e., right after the opening parenthesis) and * end location (i.e., before the closing parenthesis) of the list. */ Position startLoc, endLoc; /** * The list itself. */ List<Expression> exprList = new ArrayList<Expression>(); boolean lastIsComma; } protected ParenthesisedExpressions parseParenthesisedExpressions(DestructuringErrors refDestructuringErrors) { boolean allowTrailingComma = this.options.ecmaVersion() >= 8; ParenthesisedExpressions parenExprs = new ParenthesisedExpressions(); parenExprs.startLoc = this.startLoc; boolean first = true; this.yieldPos = 0; this.awaitPos = 0; while (this.type != TokenType.parenR) { if (first) first = false; else this.expect(TokenType.comma); if (!parseParenthesisedExpression(refDestructuringErrors, allowTrailingComma, parenExprs, first)) break; } parenExprs.endLoc = this.startLoc; this.expect(TokenType.parenR); return parenExprs; } protected boolean parseParenthesisedExpression(DestructuringErrors refDestructuringErrors, boolean allowTrailingComma, ParenthesisedExpressions parenExprs, boolean first) { if (allowTrailingComma && this.afterTrailingComma(TokenType.parenR, true)) { parenExprs.lastIsComma = true; return false; } else if (this.type == TokenType.ellipsis) { parenExprs.spreadStart = this.start; parenExprs.exprList.add(this.parseParenItem(this.parseRest(false), -1, null)); if (this.type == TokenType.comma) this.raise(this.startLoc, "Comma is not permitted after the rest element"); return false; } else { if (this.type == TokenType.parenL && parenExprs.innerParenStart == 0) { parenExprs.innerParenStart = this.start; } parenExprs.exprList.add(this.parseMaybeAssign(false, refDestructuringErrors, this::parseParenItem)); } return true; } protected Expression parseParenItem(Expression left, int startPos, Position startLoc) { return left; } protected Expression parseParenArrowList(Position startLoc, List<Expression> exprList) { return this.parseArrowExpression(startLoc, exprList, false); } // New's precedence is slightly tricky. It must allow its argument to // not without wrapping it in parentheses. Thus, it uses the noCalls // argument to parseSubscripts to prevent it from consuming the // argument list. protected Expression parseNew() { Position startLoc = this.startLoc; Identifier meta = this.parseIdent(true); if (this.options.ecmaVersion() >= 6 && this.eat(TokenType.dot)) { Identifier property = this.parseIdent(true); if (!property.getName().equals("target")) this.raiseRecoverable(property, "The only valid meta property for new is new.target"); if (!this.inFunction) this.raiseRecoverable(meta, "new.target can only be used in functions"); MetaProperty node = new MetaProperty(new SourceLocation(startLoc), meta, property); return this.finishNode(node); } int innerStartPos = this.start; Position innerStartLoc = this.startLoc; Expression callee = this.parseSubscripts(this.parseExprAtom(null), innerStartPos, innerStartLoc, true); if (isOnOptionalChain(false, callee)) this.raise(callee, "An optional chain may not be used in a `new` expression."); return parseNewArguments(startLoc, callee); } protected Expression parseNewArguments(Position startLoc, Expression callee) { List<Expression> arguments; if (this.eat(TokenType.parenL)) arguments = this.parseExprList(TokenType.parenR, this.options.ecmaVersion() >= 8, false, null); else arguments = new ArrayList<Expression>(); NewExpression node = new NewExpression(new SourceLocation(startLoc), callee, new ArrayList<>(), arguments); return this.finishNode(node); } // Parse template expression. protected TemplateElement parseTemplateElement(boolean isTagged) { Position startLoc = this.startLoc; String raw, cooked; if (this.type == TokenType.invalidTemplate) { if (!isTagged) { this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); } raw = String.valueOf(this.value); cooked = null; } else { raw = inputSubstring(this.start, this.end).replaceAll("\r\n?", "\n"); cooked = String.valueOf(this.value); } this.next(); boolean tail = this.type == TokenType.backQuote; TemplateElement elem = new TemplateElement(new SourceLocation(startLoc), cooked, raw, tail); return this.finishNode(elem); } protected TemplateLiteral parseTemplate(boolean isTagged) { Position startLoc = this.startLoc; this.next(); List<Expression> expressions = new ArrayList<Expression>(); TemplateElement curElt = this.parseTemplateElement(isTagged); List<TemplateElement> quasis = CollectionUtil.makeList(curElt); while (!curElt.isTail()) { this.expect(TokenType.dollarBraceL); expressions.add(this.parseExpression(false, null)); this.expect(TokenType.braceR); quasis.add(curElt = this.parseTemplateElement(isTagged)); } this.next(); TemplateLiteral node = new TemplateLiteral(new SourceLocation(startLoc), expressions, quasis); return this.finishNode(node); } /* * Auxiliary class used to collect information about properties during parsing. * * This is needed because parsing properties and methods requires a fair bit of lookahead. */ protected static class PropertyInfo { Expression key, value; String kind = "init"; boolean computed = false, method = false, isPattern, isGenerator, isAsync; Position startLoc; public PropertyInfo(boolean isPattern, boolean isGenerator, Position startLoc) { this.isPattern = isPattern; this.isGenerator = isGenerator; this.startLoc = startLoc; } MethodDefinition.Kind getMethodKind() { return MethodDefinition.Kind.valueOf(StringUtil.uc(kind)); } } // Parse an object literal or binding pattern. protected Expression parseObj(boolean isPattern, DestructuringErrors refDestructuringErrors) { Position startLoc = this.startLoc; boolean first = true; Map<String, PropInfo> propHash = new LinkedHashMap<>(); List<Property> properties = new ArrayList<Property>(); this.next(); while (!this.eat(TokenType.braceR)) { if (!first) { this.expect(TokenType.comma); if (this.afterTrailingComma(TokenType.braceR, false)) break; } else { first = false; } properties.add(this.finishNode(parseProperty(isPattern, refDestructuringErrors, propHash))); } SourceLocation loc = new SourceLocation(startLoc); Expression node = isPattern ? new ObjectPattern(loc, properties) : new ObjectExpression(loc, properties); return this.finishNode(node); } protected Property parseProperty(boolean isPattern, DestructuringErrors refDestructuringErrors, Map<String, PropInfo> propHash) { Position propStartLoc = this.startLoc; boolean isGenerator = false; if (this.options.ecmaVersion() >= 6) { if (!isPattern) isGenerator = this.eat(TokenType.star); } PropertyInfo pi = new PropertyInfo(isPattern, isGenerator, propStartLoc); this.parsePropertyName(pi); if (!isPattern && this.options.ecmaVersion() >= 8 && !isGenerator && this.isAsyncProp(pi)) { pi.isAsync = true; this.parsePropertyName(pi); } else { pi.isAsync = false; } this.parsePropertyValue(pi, refDestructuringErrors); Property prop = new Property(new SourceLocation(pi.startLoc), pi.key, pi.value, pi.kind, pi.computed, pi.method); this.checkPropClash(prop, propHash); return prop; } private boolean isAsyncProp(PropertyInfo pi) { return !pi.computed && pi.key instanceof Identifier && ((Identifier) pi.key).getName().equals("async") && (this.type == TokenType.name || this.type == TokenType.num || this.type == TokenType.string || this.type == TokenType.bracketL || this.type.keyword != null) && !this.canInsertSemicolon(); } protected void parsePropertyValue(PropertyInfo pi, DestructuringErrors refDestructuringErrors) { if ((pi.isGenerator || pi.isAsync) && this.type == TokenType.colon) this.unexpected(); if (this.eat(TokenType.colon)) { pi.value = pi.isPattern ? this.parseMaybeDefault(this.startLoc, null) : this.parseMaybeAssign(false, refDestructuringErrors, null); pi.kind = "init"; } else if (this.options.ecmaVersion() >= 6 && this.type == TokenType.parenL) { if (pi.isPattern) this.unexpected(); pi.kind = "init"; pi.method = true; pi.value = this.parseMethod(pi.isGenerator, pi.isAsync); } else if (this.options.ecmaVersion() >= 5 && !pi.computed && pi.key instanceof Identifier && (((Identifier)pi.key).getName().equals("get") || ((Identifier)pi.key).getName().equals("set")) && (this.type != TokenType.comma && this.type != TokenType.braceR)) { if (pi.isGenerator || pi.isAsync || pi.isPattern) this.unexpected(); pi.kind = ((Identifier) pi.key).getName(); PropertyInfo pi2 = new PropertyInfo(false, false, this.startLoc); this.parsePropertyName(pi2); pi.key = pi2.key; pi.computed = pi2.computed; pi.value = this.parseMethod(false, false); int paramCount = pi.kind.equals("get") ? 0 : 1; FunctionExpression fn = (FunctionExpression) pi.value; List<Expression> params = fn.getRawParameters(); if (params.size() != paramCount) { if (pi.kind.equals("get")) this.raiseRecoverable(pi.value, "getter should have no params"); else this.raiseRecoverable(pi.value, "setter should have exactly one param"); } if (pi.kind.equals("set") && fn.hasRest()) this.raiseRecoverable(params.get(params.size()-1), "Setter cannot use rest params"); } else if (this.options.ecmaVersion() >= 6 && !pi.computed && pi.key instanceof Identifier) { String name = ((Identifier) pi.key).getName(); if (this.keywords.contains(name) || (this.strict ? this.reservedWordsStrict : this.reservedWords).contains(name) || (this.inGenerator && name.equals("yield")) || (this.inAsync && name.equals("await"))) this.raiseRecoverable(pi.key, "'" + name + "' can not be used as shorthand property"); pi.kind = "init"; if (pi.isPattern) { pi.value = this.parseMaybeDefault(pi.startLoc, pi.key); } else if (this.type == TokenType.eq && refDestructuringErrors != null) { if (refDestructuringErrors.shorthandAssign == 0) refDestructuringErrors.shorthandAssign = this.start; pi.value = this.parseMaybeDefault(pi.startLoc, pi.key); } else { pi.value = pi.key; } } else { this.unexpected(); } } protected void parsePropertyName(PropertyInfo result) { if (this.options.ecmaVersion() >= 6) { if (this.eat(TokenType.bracketL)) { result.key = this.parseMaybeAssign(false, null, null); result.computed = true; this.expect(TokenType.bracketR); return; } } if (this.type == TokenType.num || this.type == TokenType.string) result.key = this.parseExprAtom(null); else result.key = this.parseIdent(true); } // Parse object or class method. protected FunctionExpression parseMethod(boolean isGenerator, boolean isAsync) { Position startLoc = this.startLoc; boolean oldInGen = this.inGenerator, oldInAsync = this.inAsync; int oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos; this.inGenerator = isGenerator; this.inAsync = isAsync; this.yieldPos = 0; this.awaitPos = 0; this.expect(TokenType.parenL); List<Expression> params = this.parseBindingList(TokenType.parenR, false, this.options.ecmaVersion() >= 8, false); this.checkYieldAwaitInDefaultParams(); boolean generator = this.options.ecmaVersion() >= 6 && isGenerator; Node body = this.parseFunctionBody(null, params, false); this.inGenerator = oldInGen; this.inAsync = oldInAsync; this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; Identifier id = null; FunctionExpression node = new FunctionExpression(new SourceLocation(startLoc), id, params, body, generator, isAsync); return this.finishNode(node); } // Parse arrow function expression with given parameters. protected ArrowFunctionExpression parseArrowExpression(Position startLoc, List<Expression> rawParams, boolean isAsync) { boolean oldInGen = this.inGenerator, oldInAsync = this.inAsync; int oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos; this.inGenerator = false; this.inAsync = isAsync; this.yieldPos = 0; this.awaitPos = 0; List<Expression> params = this.toAssignableList(rawParams, true); Node body = this.parseFunctionBody(null, params, true); this.inGenerator = oldInGen; this.inAsync = oldInAsync; this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; ArrowFunctionExpression node = new ArrowFunctionExpression(new SourceLocation(startLoc), params, body, false, isAsync); return this.finishNode(node); } // Parse function body and check parameters. protected Node parseFunctionBody(Identifier id, List<Expression> params, boolean isArrowFunction) { boolean isExpression = isArrowFunction && this.type != TokenType.braceL; Node body; if (isExpression) { body = this.parseMaybeAssign(false, null, null); } else { // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). boolean oldInFunc = this.inFunction; Stack<LabelInfo> oldLabels = this.labels; this.inFunction = true; this.labels = new Stack<LabelInfo>(); body = this.parseBlock(true); this.inFunction = oldInFunc; this.labels = oldLabels; } // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. Statement useStrict = null; if (!isExpression && body instanceof BlockStatement) { List<Statement> bodyStmts = ((BlockStatement) body).getBody(); if (!bodyStmts.isEmpty() && isUseStrict(bodyStmts.get(0))) useStrict = bodyStmts.get(0); } if (useStrict != null && options.ecmaVersion() >= 7 && !isSimpleParamList(params)) raiseRecoverable(useStrict, "Illegal 'use strict' directive in function with non-simple parameter list"); if (this.strict || useStrict != null) { boolean oldStrict = this.strict; this.strict = true; if (id != null) this.checkLVal(id, true, null); this.checkParams(params); this.strict = oldStrict; } else if (isArrowFunction || !isSimpleParamList(params)) { this.checkParams(params); } return body; } private boolean isSimpleParamList(List<Expression> params) { for (Expression param : params) if (!(param instanceof Identifier)) return false; return true; } // Checks function params for various disallowed patterns such as using "eval" // or "arguments" and duplicate parameters. protected void checkParams(List<? extends INode> params) { Set<String> nameHash = new LinkedHashSet<>(); for (INode param : params) this.checkLVal(param, true, nameHash); } // Parses a comma-separated list of expressions, and returns them as // an array. `close` is the token type that ends the list, and // `allowEmpty` can be turned on to allow subsequent commas with // nothing in between them to be parsed as `null` (which is needed // for array literals). protected List<Expression> parseExprList(TokenType close, boolean allowTrailingComma, boolean allowEmpty, DestructuringErrors refDestructuringErrors) { List<Expression> elts = new ArrayList<Expression>(); boolean first = true; while (!this.eat(close)) { if (!first) { this.expect(TokenType.comma); if (allowTrailingComma && this.afterTrailingComma(close, false)) break; } else { first = false; } Expression elt; if (allowEmpty && this.type == TokenType.comma) { elt = null; } else if (this.type == TokenType.ellipsis) { elt = this.processExprListItem(this.parseSpread(refDestructuringErrors)); if (this.type == TokenType.comma && refDestructuringErrors != null && refDestructuringErrors.trailingComma == 0) { refDestructuringErrors.trailingComma = this.start; } } else elt = this.processExprListItem(this.parseMaybeAssign(false, refDestructuringErrors, null)); elts.add(elt); } return elts; } protected Expression processExprListItem(Expression e) { return e; } // Parse the next token as an identifier. If `liberal` is true (used // when parsing properties), it will also convert keywords into // identifiers. protected Identifier parseIdent(boolean liberal) { Position startLoc = this.startLoc; if (liberal && this.options.allowReserved() == AllowReserved.NEVER) liberal = false; String name = null; if (this.type == TokenType.name) { if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).contains(this.value) && (this.options.ecmaVersion() >= 6 || inputSubstring(this.start, this.end).indexOf("\\") == -1)) this.raiseRecoverable(this.start, "The keyword '" + this.value + "' is reserved"); if (this.inGenerator && this.value.equals("yield")) this.raiseRecoverable(this.start, "Can not use 'yield' as identifier inside a generator"); if (this.inAsync && this.value.equals("await")) this.raiseRecoverable(this.start, "Can not use 'await' as identifier inside an async function"); name = String.valueOf(this.value); } else if (liberal && this.type.keyword != null) { name = this.type.keyword; } else { this.unexpected(); } this.next(); Identifier node = new Identifier(new SourceLocation(startLoc), name); return this.finishNode(node); } // Parses yield expression inside generator. protected YieldExpression parseYield() { if (this.awaitPos == 0) this.awaitPos = this.start; Position startLoc = this.startLoc; this.next(); boolean delegate; Expression argument; if (this.type == TokenType.semi || this.canInsertSemicolon() || (this.type != TokenType.star && !this.type.startsExpr)) { delegate = false; argument = null; } else { delegate = this.eat(TokenType.star); argument = this.parseMaybeAssign(false, null, null); } YieldExpression node = new YieldExpression(new SourceLocation(startLoc), argument, delegate); return this.finishNode(node); } protected AwaitExpression parseAwait() { Position startLoc = this.startLoc; this.next(); Expression argument = this.parseMaybeUnary(null, true); AwaitExpression node = new AwaitExpression(new SourceLocation(startLoc), argument); return this.finishNode(node); } /// end expression.js /// begin lval.js // Convert existing expression atom to assignable pattern // if possible. protected INode toAssignable(INode node, boolean isBinding) { if (this.options.ecmaVersion() >= 6 && node != null) { if (node instanceof Identifier) { if (this.inAsync && ((Identifier) node).getName().equals("await")) this.raise(node, "Can not use 'await' as identifier inside an async function"); return node; } if (node instanceof ObjectPattern || node instanceof ArrayPattern) { return node; } if (node instanceof ObjectExpression) { List<Property> properties = new ArrayList<Property>(); for (Property prop : ((ObjectExpression) node).getProperties()) { if (prop.getKind().isAccessor) this.raise(prop.getKey(), "Object pattern can't contain getter or setter"); Expression val = (Expression) this.toAssignable(prop.getRawValue(), isBinding); properties.add(new Property(prop.getLoc(), prop.getKey(), val, prop.getKind().name(), prop.isComputed(), prop.isMethod())); } return new ObjectPattern(node.getLoc(), properties); } if (node instanceof ArrayExpression) return new ArrayPattern(node.getLoc(), this.toAssignableList(((ArrayExpression) node).getElements(), isBinding)); if (node instanceof AssignmentExpression) { AssignmentExpression assgn = (AssignmentExpression) node; if (assgn.getOperator().equals("=")) { this.toAssignable(assgn.getLeft(), isBinding); return new AssignmentPattern(node.getLoc(), "=", assgn.getLeft(), assgn.getRight()); } else { this.raise(assgn.getLeft().getLoc().getEnd(), "Only '=' operator can be used for specifying default value."); } } if (node instanceof AssignmentPattern) { return node; } if (node instanceof ParenthesizedExpression) { Expression expr = ((ParenthesizedExpression) node).getExpression(); return new ParenthesizedExpression(node.getLoc(), (Expression) this.toAssignable(expr, isBinding)); } if (node instanceof MemberExpression) { if (isOnOptionalChain(false, (MemberExpression)node)) this.raise(node, "Invalid left-hand side in assignment"); if (!isBinding) return node; } this.raise(node, "Assigning to rvalue"); } return node; } // Convert list of expression atoms to binding list. protected List<Expression> toAssignableList(List<Expression> exprList, boolean isBinding) { int end = exprList.size(); if (end > 0) { Expression last = exprList.get(end-1); if (last != null && last instanceof RestElement) { --end; } else if (last != null && last instanceof SpreadElement) { Expression arg = ((SpreadElement) last).getArgument(); arg = (Expression) this.toAssignable(arg, isBinding); if (!(arg instanceof Identifier || arg instanceof MemberExpression || arg instanceof ArrayPattern)) this.unexpected(arg.getLoc().getStart()); exprList.set(end-1, last = new RestElement(last.getLoc(), arg)); --end; } if (isBinding && last instanceof RestElement && !(((RestElement) last).getArgument() instanceof Identifier)) this.unexpected(((RestElement) last).getArgument().getLoc().getStart()); } for (int i=0; i<end; ++i) exprList.set(i, (Expression) this.toAssignable(exprList.get(i), isBinding)); return exprList; } // Parses spread element. protected SpreadElement parseSpread(DestructuringErrors refDestructuringErrors) { Position start = this.startLoc; this.next(); SpreadElement node = new SpreadElement(new SourceLocation(start), this.parseMaybeAssign(false, refDestructuringErrors, null)); return this.finishNode(node); } protected RestElement parseRest(boolean allowNonIdent) { Position start = this.startLoc; this.next(); // RestElement inside of a function parameter must be an identifier Expression argument = null; if (allowNonIdent) if (this.type == TokenType.name) argument = this.parseIdent(false); else this.unexpected(); else if (this.type == TokenType.name || this.type == TokenType.bracketL) argument = this.parseBindingAtom(); else this.unexpected(); RestElement node = new RestElement(new SourceLocation(start), argument); return this.finishNode(node); } // Parses lvalue (assignable) atom. protected Expression parseBindingAtom() { if (this.options.ecmaVersion() < 6) return this.parseIdent(false); if (this.type == TokenType.name) return this.parseIdent(false); if (this.type == TokenType.bracketL) { Position start = this.startLoc; this.next(); List<Expression> elements = this.parseBindingList(TokenType.bracketR, true, true, false); ArrayPattern node = new ArrayPattern(new SourceLocation(start), elements); return this.finishNode(node); } if (this.type == TokenType.braceL) return this.parseObj(true, null); this.unexpected(); return null; } protected List<Expression> parseBindingList(TokenType close, boolean allowEmpty, boolean allowTrailingComma, boolean allowNonIdent) { List<Expression> result = new ArrayList<Expression>(); boolean first = true; while (!this.eat(close)) { if (first) first = false; else this.expect(TokenType.comma); if (allowEmpty && this.type == TokenType.comma) { result.add(null); } else if (allowTrailingComma && this.afterTrailingComma(close, false)) { break; } else if (this.type == TokenType.ellipsis) { result.add(this.processBindingListItem(this.parseRest(allowNonIdent))); if (this.type == TokenType.comma) this.raise(this.start, "Comma is not permitted after the rest element"); this.expect(close); break; } else { result.add(this.processBindingListItem(this.parseMaybeDefault(this.startLoc, null))); } } return result; } protected Expression processBindingListItem(Expression e) { return e; } // Parses assignment pattern around given atom if possible. protected Expression parseMaybeDefault(Position startLoc, Expression left) { if (left == null) left = this.parseBindingAtom(); if (this.options.ecmaVersion() < 6 || !this.eat(TokenType.eq)) return left; AssignmentPattern node = new AssignmentPattern(new SourceLocation(startLoc), "=", left, this.parseMaybeAssign(false, null, null)); return this.finishNode(node); } protected void checkLVal(INode expr, boolean isBinding, Set<String> checkClashes) { if (expr instanceof Identifier) { String name = ((Identifier) expr).getName(); if (this.strict && this.reservedWordsStrictBind.contains(name)) this.raiseRecoverable(expr, (isBinding ? "Binding " : "Assigning to ") + name + " in strict mode"); if (checkClashes != null) { if (!checkClashes.add(name)) this.raiseRecoverable(expr, "Argument name clash"); } } else if (expr instanceof MemberExpression) { if (isBinding) this.raiseRecoverable(expr, (isBinding ? "Binding" : "Assigning to") + " member expression"); } else if (expr instanceof ObjectPattern) { for (Property prop : ((ObjectPattern) expr).getProperties()) this.checkLVal(prop.getRawValue(), isBinding, checkClashes); } else if (expr instanceof ArrayPattern) { for (Expression elem : ((ArrayPattern) expr).getRawElements()) if (elem != null) this.checkLVal(elem, isBinding, checkClashes); } else if (expr instanceof AssignmentPattern) { this.checkLVal(((AssignmentPattern) expr).getLeft(), isBinding, checkClashes); } else if (expr instanceof RestElement) { this.checkLVal(((RestElement) expr).getArgument(), isBinding, checkClashes); } else if (expr instanceof ParenthesizedExpression) { this.checkLVal(((ParenthesizedExpression) expr).getExpression(), isBinding, checkClashes); } else { this.raise(expr.getLoc().getStart(), (isBinding ? "Binding" : "Assigning to") + " rvalue"); } } /// end lval.js /// begin tokencontext.js public static class TokContext { public static final TokContext b_stat = new TokContext("{", false), b_expr = new TokContext("{", true), b_tmpl = new TokContext("${", true), p_stat = new TokContext("(", false), p_expr = new TokContext("(", true), q_tmpl = new TokContext("`", true, true, p -> p.tryReadTemplateToken()), f_expr = new TokContext("function", true); public final String token; public final boolean isExpr, preserveSpace; public final Function<Parser, Token> override; public TokContext(String token, boolean isExpr, boolean preserveSpace, Function<Parser, Token> override) { this.token = token; this.isExpr = isExpr; this.preserveSpace = preserveSpace; this.override = override; } public TokContext(String token, boolean isExpr) { this(token, isExpr, false, null); } } private Stack<TokContext> initialContext() { Stack<TokContext> s = new Stack<TokContext>(); s.push(TokContext.b_stat); return s; } protected boolean braceIsBlock(TokenType prevType) { if (prevType == TokenType.colon) { TokContext parent = this.curContext(); if (parent == TokContext.b_stat || parent == TokContext.b_expr) return !parent.isExpr; } if (prevType == TokenType._return) return inputSubstring(this.lastTokEnd, this.start).matches("(?s).*(?:" + lineBreak + ").*"); if (prevType == TokenType._else || prevType == TokenType.semi || prevType == TokenType.eof || prevType == TokenType.parenR) return true; if (prevType == TokenType.braceL) return this.curContext() == TokContext.b_stat; return !this.exprAllowed; } protected void updateContext(TokenType prevType) { TokenType type = this.type; if (type.keyword != null && prevType == TokenType.dot) this.exprAllowed = false; else type.updateContext(this, prevType); } /// end tokencontext.js /// begin statement.js // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. protected Program parseTopLevel(Position startLoc, Program node) { boolean first = true; Set<String> exports = new LinkedHashSet<String>(); List<Statement> body = new ArrayList<Statement>(); while (this.type != TokenType.eof) { Statement stmt = this.parseStatement(true, true, exports); if (stmt != null) body.add(stmt); if (first) { if (this.isUseStrict(stmt)) this.setStrict(true); first = false; } } this.next(); if (node == null) { String sourceType = this.options.ecmaVersion() >= 6 ? this.options.sourceType() : null; node = new Program(new SourceLocation(startLoc), body, sourceType); } else { node.getBody().addAll(body); } return this.finishNode(node); } private final LabelInfo loopLabel = new LabelInfo(null, "loop", -1); private final LabelInfo switchLabel = new LabelInfo(null, "switch", -1); protected boolean isLet() { if (this.type != TokenType.name || this.options.ecmaVersion() < 6 || !this.value.equals("let")) return false; Matcher m = Whitespace.skipWhiteSpace.matcher(this.input); m.find(this.pos); int next = m.end(), nextCh = charAt(next); if (mayFollowLet(nextCh)) return true; // '{' and '[' if (Identifiers.isIdentifierStart(nextCh, true)) { int endPos; for (endPos = next + 1; Identifiers.isIdentifierChar(charAt(endPos), true); ++endPos); String ident = inputSubstring(next, endPos); if (!this.keywords.contains(ident)) return true; } return false; } protected boolean mayFollowLet(int c) { return c == 91 || c == 123; } protected final Statement parseStatement(boolean declaration, boolean topLevel) { return parseStatement(declaration, topLevel, null); } // check 'async [no LineTerminator here] function' // - 'async /*foo*/ function' is OK. // - 'async function' is invalid. boolean isAsyncFunction() { if (this.type != TokenType.name || this.options.ecmaVersion() < 8 || !this.value.equals("async")) return false; Matcher m = Whitespace.skipWhiteSpace.matcher(this.input); m.find(this.pos); int next = m.end(); return !Whitespace.lineBreakG.matcher(inputSubstring(this.pos, next)).matches() && inputSubstring(next, next+8).equals("function") && (next + 8 == this.input.length() || !Identifiers.isIdentifierChar(this.input.codePointAt(next + 8), false)); } /** * Parse a single statement. * * <p> * If expecting a statement and finding a slash operator, parse a * regular expression literal. This is to handle cases like * <code>if (foo) /blah/.exec(foo)</code>, where looking at the previous token * does not help. * * <p> * If {@code declaration} is true, this method may return {@code null}, * indicating the parsed statement was a declaration that has no semantic meaning * (such as a Flow interface declaration). This is never the case in standard * ECMAScript. */ protected Statement parseStatement(boolean declaration, boolean topLevel, Set<String> exports) { TokenType starttype = this.type; String kind = null; Position startLoc = this.startLoc; if (this.isLet()) { starttype = TokenType._var; kind = "let"; } // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. if (starttype == TokenType._break || starttype == TokenType._continue) { return this.parseBreakContinueStatement(startLoc, starttype.keyword); } else if (starttype == TokenType._debugger) { return this.parseDebuggerStatement(startLoc); } else if (starttype == TokenType._do) { return this.parseDoStatement(startLoc); } else if (starttype == TokenType._for) { this.next(); return this.parseForStatement(startLoc); } else if (starttype == TokenType._function) { if (!declaration && this.options.ecmaVersion() >= 6) this.unexpected(); return this.parseFunctionStatement(startLoc, false); } else if (starttype == TokenType._class) { if (!declaration) this.unexpected(); return (Statement) this.parseClass(startLoc, true); } else if (starttype == TokenType._if) { return this.parseIfStatement(startLoc); } else if (starttype == TokenType._return) { return this.parseReturnStatement(startLoc); } else if (starttype == TokenType._switch) { return this.parseSwitchStatement(startLoc); } else if (starttype == TokenType._throw) { return this.parseThrowStatement(startLoc); } else if (starttype == TokenType._try) { return this.parseTryStatement(startLoc); } else if (starttype == TokenType._const || starttype == TokenType._var) { if (kind == null) kind = String.valueOf(this.value); if (!declaration && !kind.equals("var")) this.unexpected(); return this.parseVarStatement(startLoc, kind); } else if (starttype == TokenType._while) { return this.parseWhileStatement(startLoc); } else if (starttype == TokenType._with) { return this.parseWithStatement(startLoc); } else if (starttype == TokenType.braceL) { return this.parseBlock(false); } else if (starttype == TokenType.semi) { return this.parseEmptyStatement(startLoc); } else if (starttype == TokenType._export || starttype == TokenType._import) { if (!this.options.allowImportExportEverywhere()) { if (!topLevel) this.raise(this.start, "'import' and 'export' may only appear at the top level"); if (!this.inModule) this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } return starttype == TokenType._import ? this.parseImport(startLoc) : this.parseExport(startLoc, exports); } else { if (this.isAsyncFunction() && declaration) { this.next(); return this.parseFunctionStatement(startLoc, true); } // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. String maybeName = String.valueOf(this.value); Expression expr = this.parseExpression(false, null); if (starttype == TokenType.name && expr instanceof Identifier && this.eat(TokenType.colon)) return this.parseLabeledStatement(startLoc, maybeName, (Identifier) expr); else return this.parseExpressionStatement(declaration, startLoc, expr); } } protected Statement parseBreakContinueStatement(Position startLoc, String keyword) { SourceLocation loc = new SourceLocation(startLoc); boolean isBreak = keyword.equals("break"); this.next(); Identifier label = null; if (this.eat(TokenType.semi) || this.insertSemicolon()) { label = null; } else if (this.type != TokenType.name) { this.unexpected(); } else { label = this.parseIdent(false); this.semicolon(); } // Verify that there is an actual destination to break or // continue to. int i=0; for (; i<labels.size(); ++i) { LabelInfo lab = labels.get(i); if (label == null || label.getName().equals(lab.name)) { if (lab.kind != null && (isBreak || lab.kind.equals("loop"))) break; if (label != null && isBreak) break; } } if (i == this.labels.size()) this.raise(startLoc, "Unsyntactic " + keyword); Statement node = isBreak ? new BreakStatement(loc, label) : new ContinueStatement(loc, label); return this.finishNode(node); } protected DebuggerStatement parseDebuggerStatement(Position startLoc) { SourceLocation loc = new SourceLocation(startLoc); this.next(); this.semicolon(); return this.finishNode(new DebuggerStatement(loc)); } protected DoWhileStatement parseDoStatement(Position startLoc) { this.next(); this.labels.push(loopLabel); Statement body = this.parseStatement(false, false); this.labels.pop(); this.expect(TokenType._while); Expression test = this.parseParenExpression(); if (this.options.ecmaVersion() >= 6) this.eat(TokenType.semi); else this.semicolon(); return this.finishNode(new DoWhileStatement(new SourceLocation(startLoc), test, body)); } // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. // This method assumes that the initial `for` token has already been consumed. protected Statement parseForStatement(Position startLoc) { this.labels.push(loopLabel); this.expect(TokenType.parenL); if (this.type == TokenType.semi) return this.parseFor(startLoc, null); boolean isLet = this.isLet(); if (this.type == TokenType._var || this.type == TokenType._const || isLet) { Position initStartLoc = this.startLoc; String kind = isLet ? "let" : String.valueOf(this.value); this.next(); VariableDeclaration init = this.finishNode(this.parseVar(initStartLoc, true, kind)); if ((this.type == TokenType._in || (this.options.ecmaVersion() >= 6 && this.isContextual("of"))) && init.getDeclarations().size() == 1 && !(!kind.equals("var") && init.getDeclarations().get(0).hasInit())) return this.parseForIn(startLoc, init); return this.parseFor(startLoc, init); } DestructuringErrors refDestructuringErrors = new DestructuringErrors(); Expression init = this.parseExpression(true, refDestructuringErrors); if (this.type == TokenType._in || (this.options.ecmaVersion() >= 6 && this.isContextual("of"))) { this.checkPatternErrors(refDestructuringErrors, true); init = (Expression) this.toAssignable(init, false); this.checkLVal(init, false, null); return this.parseForIn(startLoc, init); } else { this.checkExpressionErrors(refDestructuringErrors, true); } return this.parseFor(startLoc, init); } protected Statement parseFunctionStatement(Position startLoc, boolean isAsync) { this.next(); INode fn = this.parseFunction(startLoc, true, false, isAsync); // if we encountered an anonymous function, wrap it in an expression // statement (we will have logged a syntax error already) if (fn instanceof Expression) return this.finishNode(new ExpressionStatement(new SourceLocation(startLoc), (Expression) fn)); return (Statement) fn; } private boolean isFunction() { return this.type == TokenType._function || this.isAsyncFunction(); } protected Statement parseIfStatement(Position startLoc) { this.next(); Expression test = this.parseParenExpression(); // allow function declarations in branches, but only in non-strict mode Statement consequent = this.parseStatement(!this.strict && this.isFunction(), false); Statement alternate = this.eat(TokenType._else) ? this.parseStatement(!this.strict && this.isFunction(), false) : null; return this.finishNode(new IfStatement(new SourceLocation(startLoc), test, consequent, alternate)); } protected ReturnStatement parseReturnStatement(Position startLoc) { if (!this.inFunction && !this.options.allowReturnOutsideFunction()) this.raise(this.start, "'return' outside of function"); this.next(); // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. Expression argument; if (this.eat(TokenType.semi) || this.insertSemicolon()) { argument = null; } else { argument = this.parseExpression(false, null); this.semicolon(); } return this.finishNode(new ReturnStatement(new SourceLocation(startLoc), argument)); } protected SwitchStatement parseSwitchStatement(Position startLoc) { this.next(); Expression discriminant = this.parseParenExpression(); List<SwitchCase> cases = new ArrayList<SwitchCase>(); this.expect(TokenType.braceL); this.labels.push(switchLabel); // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. boolean sawDefault = false; Position curCaseStart = null; Expression curTest = null; List<Statement> curConsequent = null; while (this.type != TokenType.braceR) { if (this.type == TokenType._case || this.type == TokenType._default) { boolean isCase = this.type == TokenType._case; if (curConsequent != null) cases.add(this.finishNode(new SwitchCase(new SourceLocation(curCaseStart), curTest, curConsequent))); curCaseStart = this.startLoc; curTest = null; curConsequent = new ArrayList<Statement>(); this.next(); if (isCase) { curTest = this.parseExpression(false, null); } else { if (sawDefault) this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); sawDefault = true; curTest = null; } this.expect(TokenType.colon); } else { if (curConsequent == null) this.unexpected(); Statement stmt = this.parseStatement(true, false); if (stmt != null) curConsequent.add(stmt); } } if (curConsequent != null) cases.add(this.finishNode(new SwitchCase(new SourceLocation(curCaseStart), curTest, curConsequent))); this.next(); // Closing brace this.labels.pop(); return this.finishNode(new SwitchStatement(new SourceLocation(startLoc), discriminant, cases)); } protected ThrowStatement parseThrowStatement(Position startLoc) { this.next(); if (inputSubstring(this.lastTokEnd, this.start).matches("(?s).*(?:" + lineBreak + ").*")) this.raise(this.lastTokEnd, "Illegal newline after throw"); Expression argument = this.parseExpression(false, null); this.semicolon(); return this.finishNode(new ThrowStatement(new SourceLocation(startLoc), argument)); } protected TryStatement parseTryStatement(Position startLoc) { this.next(); BlockStatement block = this.parseBlock(false); CatchClause handler = this.type == TokenType._catch ? this.parseCatchClause(this.startLoc) : null; BlockStatement finalizer = this.eat(TokenType._finally) ? this.parseBlock(false) : null; if (handler == null && finalizer == null) this.raise(startLoc, "Missing catch or finally clause"); return this.finishNode(new TryStatement(new SourceLocation(startLoc), block, handler, null, finalizer)); } protected CatchClause parseCatchClause(Position startLoc) { this.next(); this.expect(TokenType.parenL); Expression param = this.parseBindingAtom(); this.checkLVal(param, true, null); this.expect(TokenType.parenR); BlockStatement catchBody = this.parseBlock(false); return this.finishNode(new CatchClause(new SourceLocation(startLoc), (IPattern)param, null, catchBody)); } protected Statement parseVarStatement(Position startLoc, String kind) { this.next(); VariableDeclaration node = this.parseVar(startLoc, false, kind); this.semicolon(); return this.finishNode(node); } protected WhileStatement parseWhileStatement(Position startLoc) { this.next(); Expression test = this.parseParenExpression(); this.labels.push(loopLabel); Statement body = this.parseStatement(false, false); this.labels.pop(); return this.finishNode(new WhileStatement(new SourceLocation(startLoc), test, body)); } protected WithStatement parseWithStatement(Position startLoc) { if (this.strict) this.raise(startLoc, "'with' in strict mode"); this.next(); Expression object = this.parseParenExpression(); Statement body = this.parseStatement(false, false); return this.finishNode(new WithStatement(new SourceLocation(startLoc), object, body)); } protected EmptyStatement parseEmptyStatement(Position startLoc) { this.next(); return this.finishNode(new EmptyStatement(new SourceLocation(startLoc))); } protected LabeledStatement parseLabeledStatement(Position startLoc, String maybeName, Identifier expr) { for (int i = 0; i < this.labels.size(); ++i) if (maybeName.equals(this.labels.get(i).name)) this.raise(expr, "Label '" + maybeName + "' is already declared"); String kind = this.type.isLoop ? "loop" : this.type == TokenType._switch ? "switch" : null; for (int i = this.labels.size() - 1; i >= 0; i LabelInfo label = this.labels.get(i); if (label.statementStart == startLoc.getOffset()) { label.statementStart = this.start; label.kind = kind; } else { break; } } this.labels.push(new LabelInfo(maybeName, kind, this.start)); Statement body = this.parseStatement(true, false); this.labels.pop(); if (body == null) return null; Identifier label = expr; return this.finishNode(new LabeledStatement(new SourceLocation(startLoc), label, body)); } protected ExpressionStatement parseExpressionStatement(boolean declaration, Position startLoc, Expression expr) { this.semicolon(); return this.finishNode(new ExpressionStatement(new SourceLocation(startLoc), expr)); } // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). protected BlockStatement parseBlock(boolean allowStrict) { Position startLoc = this.startLoc; boolean first = true; Boolean oldStrict = null; List<Statement> body = new ArrayList<Statement>(); this.expect(TokenType.braceL); while (!this.eat(TokenType.braceR)) { Statement stmt = this.parseStatement(true, false); if (stmt != null) body.add(stmt); if (first && allowStrict && this.isUseStrict(stmt)) { oldStrict = this.strict; this.setStrict(this.strict = true); } first = false; } if (oldStrict == Boolean.FALSE) this.setStrict(false); return this.finishNode(new BlockStatement(new SourceLocation(startLoc), body)); } // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. protected ForStatement parseFor(Position startLoc, Node init) { this.expect(TokenType.semi); Expression test = this.type == TokenType.semi ? null : this.parseExpression(false, null); this.expect(TokenType.semi); Expression update = this.type == TokenType.parenR ? null : this.parseExpression(false, null); this.expect(TokenType.parenR); Statement body = this.parseStatement(false, false); this.labels.pop(); return this.finishNode(new ForStatement(new SourceLocation(startLoc), init, test, update, body)); } // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. protected Statement parseForIn(Position startLoc, Node left) { SourceLocation loc = new SourceLocation(startLoc); boolean isForIn = this.type == TokenType._in; this.next(); Expression right = this.parseExpression(false, null); this.expect(TokenType.parenR); Statement body = this.parseStatement(false, false); this.labels.pop(); EnhancedForStatement node; if (isForIn) node = new ForInStatement(loc, left, right, body, false); else node = new ForOfStatement(loc, left, right, body); return this.finishNode(node); } // Parse a list of variable declarations. protected VariableDeclaration parseVar(Position startLoc, boolean isFor, String kind) { List<VariableDeclarator> declarations = new ArrayList<VariableDeclarator>(); for (;;) { Position varDeclStart = this.startLoc; Expression id = this.parseVarId(); Expression init = null; if (this.eat(TokenType.eq)) { init = this.parseMaybeAssign(isFor, null, null); } else if (kind.equals("const") && !(this.type == TokenType._in || (this.options.ecmaVersion() >= 6 && this.isContextual("of")))) { this.raiseRecoverable(this.lastTokEnd, "Constant declarations require an initialization value"); } else if (!(id instanceof Identifier) && !(isFor && (this.type == TokenType._in || this.isContextual("of")))) { this.raiseRecoverable(this.lastTokEnd, "Complex binding patterns require an initialization value"); } declarations.add(this.finishNode( new VariableDeclarator(new SourceLocation(varDeclStart), (IPattern) id, init, noTypeAnnotation, DeclarationFlags.none))); if (!this.eat(TokenType.comma)) break; } return new VariableDeclaration(new SourceLocation(startLoc), kind, declarations, noDeclareKeyword); } protected Expression parseVarId() { Expression res = this.parseBindingAtom(); this.checkLVal(res, true, null); return res; } /** * If {@code isStatement} is true and the function has a name, the result is a * {@linkplain FunctionDeclaration}, otherwise it is a {@linkplain FunctionExpression}. */ protected INode parseFunction(Position startLoc, boolean isStatement, boolean allowExpressionBody, boolean isAsync) { boolean oldInGen = this.inGenerator, oldInAsync = this.inAsync; int oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos; Pair<Boolean, Identifier> p = parseFunctionName(isStatement, isAsync); return parseFunctionRest(startLoc, isStatement, allowExpressionBody, oldInGen, oldInAsync, oldYieldPos, oldAwaitPos, p.fst(), p.snd()); } protected Pair<Boolean, Identifier> parseFunctionName(boolean isStatement, boolean isAsync) { boolean generator = parseGeneratorMarker(isAsync); Identifier id = null; if (isStatement) if (this.type == TokenType.name) id = this.parseIdent(false); else this.raise(this.start, "Missing function name", true); this.inGenerator = generator; this.inAsync = isAsync; this.yieldPos = 0; this.awaitPos = 0; if (!isStatement && this.type == TokenType.name) id = this.parseIdent(false); return Pair.make(generator, id); } protected boolean parseGeneratorMarker(boolean isAsync) { boolean generator = false; if (this.options.ecmaVersion() >= 6 && !isAsync) generator = this.eat(TokenType.star); return generator; } protected IFunction parseFunctionRest(Position startLoc, boolean isStatement, boolean allowExpressionBody, boolean oldInGen, boolean oldInAsync, int oldYieldPos, int oldAwaitPos, boolean generator, Identifier id) { boolean async = this.inAsync; List<Expression> params = this.parseFunctionParams(); Node body = this.parseFunctionBody(id, params, allowExpressionBody); this.inGenerator = oldInGen; this.inAsync = oldInAsync; this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; IFunction node; SourceLocation loc = new SourceLocation(startLoc); if (isStatement && id != null) node = new FunctionDeclaration(loc, id, params, body, generator, async); else node = new FunctionExpression(loc, id, params, body, generator, async); return this.finishNode(node); } protected List<Expression> parseFunctionParams() { this.expect(TokenType.parenL); List<Expression> params = this.parseBindingList(TokenType.parenR, false, this.options.ecmaVersion() >= 8, true); this.checkYieldAwaitInDefaultParams(); return params; } // Parse a class declaration or literal (depending on the // `isStatement` parameter). protected Node parseClass(Position startLoc, boolean isStatement) { SourceLocation loc = new SourceLocation(startLoc); this.next(); Identifier id = this.parseClassId(isStatement); Expression superClass = this.parseClassSuper(); Position bodyStartLoc = this.startLoc; boolean hadConstructor = false; List<MemberDefinition<?>> body = new ArrayList<MemberDefinition<?>>(); this.expect(TokenType.braceL); while (!this.eat(TokenType.braceR)) { if (this.eat(TokenType.semi)) continue; MemberDefinition<?> member = parseClassMember(hadConstructor); body.add(member); hadConstructor = hadConstructor || member.isConstructor(); } ClassBody classBody = this.finishNode(new ClassBody(new SourceLocation(bodyStartLoc), body)); Node node; if (isStatement) node = new ClassDeclaration(loc, id, superClass, classBody); else node = new ClassExpression(loc, id, superClass, classBody); return this.finishNode(node); } /** * Parse a member declaration in a class. */ protected MemberDefinition<?> parseClassMember(boolean hadConstructor) { Position methodStartLoc = this.startLoc; boolean isGenerator = this.eat(TokenType.star); boolean isMaybeStatic = this.type == TokenType.name && this.value.equals("static"); PropertyInfo pi = new PropertyInfo(false, isGenerator, methodStartLoc); this.parsePropertyName(pi); boolean isStatic = isMaybeStatic && this.type != TokenType.parenL; if (isStatic) { if (isGenerator) this.unexpected(); isGenerator = this.eat(TokenType.star); pi = new PropertyInfo(false, isGenerator, methodStartLoc); this.parsePropertyName(pi); } if (this.options.ecmaVersion() >= 8 && !isGenerator && this.isAsyncProp(pi)) { pi.isAsync = true; this.parsePropertyName(pi); } return parseClassPropertyBody(pi, hadConstructor, isStatic); } protected boolean atGetterSetterName(PropertyInfo pi) { return !pi.isGenerator && !pi.isAsync && pi.key instanceof Identifier && this.type != TokenType.parenL && (((Identifier) pi.key).getName().equals("get") || ((Identifier) pi.key).getName().equals("set")); } /** * Parse a method declaration in a class, assuming that its name has already been consumed. */ protected MemberDefinition<?> parseClassPropertyBody(PropertyInfo pi, boolean hadConstructor, boolean isStatic) { pi.kind = "method"; boolean isGetSet = false; if (!pi.computed) { if (atGetterSetterName(pi)) { isGetSet = true; pi.kind = ((Identifier) pi.key).getName(); this.parsePropertyName(pi); } if (!isStatic && (pi.key instanceof Identifier && ((Identifier) pi.key).getName().equals("constructor") || pi.key instanceof Literal && ((Literal) pi.key).getStringValue().equals("constructor"))) { if (hadConstructor) this.raise(pi.key, "Duplicate constructor in the same class"); if (isGetSet) this.raise(pi.key, "Constructor can't have get/set modifier"); if (pi.isGenerator) this.raise(pi.key, "Constructor can't be a generator"); if (pi.isAsync) this.raise(pi.key, "Constructor can't be an async method"); pi.kind = "constructor"; } } MethodDefinition node = this.parseClassMethod(pi.startLoc, pi.isGenerator, pi.isAsync, isStatic, pi.computed, pi.getMethodKind(), pi.key); if (isGetSet) { int paramCount = pi.kind.equals("get") ? 0 : 1; List<Expression> params = node.getValue().getRawParameters(); if (params.size() != paramCount) { if (pi.kind.equals("get")) this.raiseRecoverable(node.getValue(), "getter should have no params"); else this.raiseRecoverable(node.getValue(), "setter should have exactly one param"); } if (pi.kind.equals("set") && node.getValue().hasRest()) this.raiseRecoverable(params.get(params.size()-1), "Setter cannot use rest params"); } return node; } protected MethodDefinition parseClassMethod(Position startLoc, boolean isGenerator, boolean isAsync, boolean isStatic, boolean isComputed, MethodDefinition.Kind kind, Expression key) { SourceLocation loc = new SourceLocation(startLoc); FunctionExpression body = this.parseMethod(isGenerator, isAsync); int flags = DeclarationFlags.getStatic(isStatic) | DeclarationFlags.getComputed(isComputed); MethodDefinition m = new MethodDefinition(loc, flags, kind, key, body); return this.finishNode(m); } protected Identifier parseClassId(boolean isStatement) { if (this.type == TokenType.name) return this.parseIdent(false); if (isStatement) this.unexpected(); return null; } protected Expression parseClassSuper() { return this.eat(TokenType._extends) ? this.parseExprSubscripts(null) : null; } // Parses module export declaration. protected ExportDeclaration parseExport(Position startLoc, Set<String> exports) { SourceLocation loc = new SourceLocation(startLoc); this.next(); return parseExportRest(loc, exports); } /** * Parse the body of an {@code export} declaration, assuming that the {@code export} * keyword itself has already been consumed. */ protected ExportDeclaration parseExportRest(SourceLocation loc, Set<String> exports) { Position exportRestLoc = startLoc; // export * from '...' if (this.eat(TokenType.star)) { return parseExportAll(loc, exportRestLoc, exports); } if (this.eat(TokenType._default)) { // export default ... this.checkExport(exports, "default", this.lastTokStartLoc); boolean isAsync = false; Node declaration; if (this.type == TokenType._function || (isAsync = this.isAsyncFunction())) { Position startLoc = this.startLoc; this.next(); if (isAsync) this.next(); FunctionExpression fe = (FunctionExpression) this.parseFunction(startLoc, false, false, isAsync); if (fe.hasId()) declaration = new FunctionDeclaration(fe.getLoc(), fe.getId(), fe.getRawParameters(), (BlockStatement) fe.getBody(), fe.isGenerator(), fe.isAsync()); else declaration = fe; } else if (this.type == TokenType._class) { ClassExpression ce = (ClassExpression) parseClass(this.startLoc, false); if (ce.getClassDef().hasId()) declaration = new ClassDeclaration(ce.getLoc(), ce.getClassDef(), noDeclareKeyword, notAbstract); else declaration = ce; } else { declaration = this.parseMaybeAssign(false, null, null); this.semicolon(); } return this.finishNode(new ExportDefaultDeclaration(loc, declaration)); } // export var|const|let|function|class ... Statement declaration; List<ExportSpecifier> specifiers; Expression source = null; if (this.shouldParseExportStatement()) { declaration = this.parseStatement(true, false); if (declaration == null) return null; if (declaration instanceof VariableDeclaration) { checkVariableExport(exports, ((VariableDeclaration)declaration).getDeclarations()); } else { Identifier id = getId(declaration); if (id != null) checkExport(exports, id.getName(), id.getLoc().getStart()); } specifiers = new ArrayList<ExportSpecifier>(); source = null; } else { // export { x, y as z } [from '...'] declaration = null; specifiers = this.parseExportSpecifiers(exports); source = parseExportFrom(specifiers, source, false); } return this.finishNode(new ExportNamedDeclaration(loc, declaration, specifiers, (Literal) source)); } protected Expression parseExportFrom(List<ExportSpecifier> specifiers, Expression source, boolean expectFrom) { if (this.eatContextual("from")) { if (this.type == TokenType.string) source = this.parseExprAtom(null); else this.unexpected(); } else { if (expectFrom) this.unexpected(); // check for keywords used as local names for (ExportSpecifier specifier : specifiers) { String localName = specifier.getLocal().getName(); if (this.keywords.contains(localName) || this.reservedWords.contains(localName)) { this.unexpected(specifier.getLoc().getStart()); } } source = null; } this.semicolon(); return source; } protected ExportDeclaration parseExportAll(SourceLocation loc, Position starLoc, Set<String> exports) { Expression source = parseExportFrom(null, null, true); return this.finishNode(new ExportAllDeclaration(loc, (Literal)source)); } private void checkExport(Set<String> exports, String name, Position pos) { if (exports == null) return; if (exports.contains(name)) raiseRecoverable(pos.getOffset(), "Duplicate export '" + name + "'"); exports.add(name); } private void checkPatternExport(Set<String> exports, Expression pat) { if (pat instanceof Identifier) { checkExport(exports, ((Identifier) pat).getName(), pat.getLoc().getStart()); } else if (pat instanceof ObjectPattern) { for (Property prop : ((ObjectPattern) pat).getProperties()) checkPatternExport(exports, prop.getValue()); } else if (pat instanceof ArrayPattern) { for (Expression elt : ((ArrayPattern) pat).getElements()) if (elt != null) checkPatternExport(exports, elt); } else if (pat instanceof AssignmentPattern) { checkPatternExport(exports, ((AssignmentPattern) pat).getLeft()); } else if (pat instanceof ParenthesizedExpression) { checkPatternExport(exports, ((ParenthesizedExpression) pat).getExpression()); } } private void checkVariableExport(Set<String> exports, List<VariableDeclarator> decls) { if (exports == null) return; for (VariableDeclarator decl : decls) checkPatternExport(exports, (Expression) decl.getId()); } protected boolean shouldParseExportStatement() { return this.type.keyword != null || this.isLet() || this.isAsyncFunction(); } // Parses a comma-separated list of module exports. protected List<ExportSpecifier> parseExportSpecifiers(Set<String> exports) { List<ExportSpecifier> nodes = new ArrayList<ExportSpecifier>(); boolean first = true; // export { x, y as z } [from '...'] this.expect(TokenType.braceL); while (!this.eat(TokenType.braceR)) { if (!first) { this.expect(TokenType.comma); if (this.afterTrailingComma(TokenType.braceR, false)) break; } else { first = false; } SourceLocation loc = new SourceLocation(this.startLoc); Identifier local = this.parseIdent(this.type == TokenType._default); Identifier exported = this.eatContextual("as") ? this.parseIdent(true) : local; checkExport(exports, exported.getName(), exported.getLoc().getStart()); nodes.add(this.finishNode(new ExportSpecifier(loc, local, exported))); } return nodes; } // Parses import declaration. protected Statement parseImport(Position startLoc) { SourceLocation loc = new SourceLocation(startLoc); this.next(); return parseImportRest(loc); } protected ImportDeclaration parseImportRest(SourceLocation loc) { List<ImportSpecifier> specifiers; Literal source; // import '...' if (this.type == TokenType.string) { specifiers = new ArrayList<ImportSpecifier>(); source = (Literal) this.parseExprAtom(null); } else { specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); if (this.type != TokenType.string) this.unexpected(); source = (Literal) this.parseExprAtom(null); } this.semicolon(); if (specifiers == null) return null; return this.finishNode(new ImportDeclaration(loc, specifiers, source)); } // Parses a comma-separated list of module imports. protected List<ImportSpecifier> parseImportSpecifiers() { List<ImportSpecifier> nodes = new ArrayList<ImportSpecifier>(); boolean first = true; if (this.type == TokenType.name) { // import defaultObj, { x, y as z } from '...' SourceLocation loc = new SourceLocation(this.startLoc); Identifier local = this.parseIdent(false); this.checkLVal(local, true, null); nodes.add(this.finishNode(new ImportDefaultSpecifier(loc, local))); if (!this.eat(TokenType.comma)) return nodes; } if (this.type == TokenType.star) { SourceLocation loc = new SourceLocation(this.startLoc); this.next(); this.expectContextual("as"); Identifier local = this.parseIdent(false); this.checkLVal(local, true, null); nodes.add(this.finishNode(new ImportNamespaceSpecifier(loc, local))); return nodes; } this.expect(TokenType.braceL); while (!this.eat(TokenType.braceR)) { if (!first) { this.expect(TokenType.comma); if (this.afterTrailingComma(TokenType.braceR, false)) break; } else { first = false; } ImportSpecifier importSpecifier = parseImportSpecifier(); if (importSpecifier != null) nodes.add(importSpecifier); } return nodes; } protected ImportSpecifier parseImportSpecifier() { SourceLocation loc = new SourceLocation(this.startLoc); Identifier imported = this.parseIdent(true), local; if (this.eatContextual("as")) { local = this.parseIdent(false); } else { local = imported; if (this.keywords.contains(local.getName())) this.unexpected(local.getLoc().getStart()); if (this.reservedWordsStrict.contains(local.getName())) this.raiseRecoverable(local, "The keyword '" + local.getName() + "' is reserved"); } this.checkLVal(local, true, null); return this.finishNode(new ImportSpecifier(loc, imported, local)); } /// end statement.js /// helpers protected Number parseInt(String s, int radix) { return stringToNumber(s, 0, radix); } protected Number parseFloat(String s) { try { return Double.valueOf(s); } catch (NumberFormatException nfe) { this.raise(this.start, "Invalid number"); return null; } } protected int charAt(int i) { if (i < input.length()) return input.charAt(i); else return -1; } protected String inputSubstring(int start, int end) { if (start >= input.length()) return ""; if (end > input.length()) end = input.length(); return input.substring(start, end); } protected Identifier getId(Statement s) { if (s instanceof ClassDeclaration) return ((ClassDeclaration) s).getClassDef().getId(); if (s instanceof FunctionDeclaration) return ((FunctionDeclaration) s).getId(); return null; } /* * Helper function for toNumber, parseInt, and TokenStream.getToken. * * Copied from Rhino. */ private static double stringToNumber(String s, int start, int radix) { char digitMax = '9'; char lowerCaseBound = 'a'; char upperCaseBound = 'A'; int len = s.length(); if (radix < 10) { digitMax = (char) ('0' + radix - 1); } if (radix > 10) { lowerCaseBound = (char) ('a' + radix - 10); upperCaseBound = (char) ('A' + radix - 10); } int end; double sum = 0.0; for (end=start; end < len; end++) { char c = s.charAt(end); int newDigit; if ('0' <= c && c <= digitMax) newDigit = c - '0'; else if ('a' <= c && c < lowerCaseBound) newDigit = c - 'a' + 10; else if ('A' <= c && c < upperCaseBound) newDigit = c - 'A' + 10; else break; sum = sum*radix + newDigit; } if (start == end) { return Double.NaN; } if (sum >= 9007199254740992.0) { if (radix == 10) { /* If we're accumulating a decimal number and the number * is >= 2^53, then the result from the repeated multiply-add * above may be inaccurate. Call Java to get the correct * answer. */ try { return Double.parseDouble(s.substring(start, end)); } catch (NumberFormatException nfe) { return Double.NaN; } } else if (radix == 2 || radix == 4 || radix == 8 || radix == 16 || radix == 32) { /* The number may also be inaccurate for one of these bases. * This happens if the addition in value*radix + digit causes * a round-down to an even least significant mantissa bit * when the first dropped bit is a one. If any of the * following digits in the number (which haven't been added * in yet) are nonzero then the correct action would have * been to round up instead of down. An example of this * occurs when reading the number 0x1000000000000081, which * rounds to 0x1000000000000000 instead of 0x1000000000000100. */ int bitShiftInChar = 1; int digit = 0; final int SKIP_LEADING_ZEROS = 0; final int FIRST_EXACT_53_BITS = 1; final int AFTER_BIT_53 = 2; final int ZEROS_AFTER_54 = 3; final int MIXED_AFTER_54 = 4; int state = SKIP_LEADING_ZEROS; int exactBitsLimit = 53; double factor = 0.0; boolean bit53 = false; // bit54 is the 54th bit (the first dropped from the mantissa) boolean bit54 = false; for (;;) { if (bitShiftInChar == 1) { if (start == end) break; digit = s.charAt(start++); if ('0' <= digit && digit <= '9') digit -= '0'; else if ('a' <= digit && digit <= 'z') digit -= 'a' - 10; else digit -= 'A' - 10; bitShiftInChar = radix; } bitShiftInChar >>= 1; boolean bit = (digit & bitShiftInChar) != 0; switch (state) { case SKIP_LEADING_ZEROS: if (bit) { --exactBitsLimit; sum = 1.0; state = FIRST_EXACT_53_BITS; } break; case FIRST_EXACT_53_BITS: sum *= 2.0; if (bit) sum += 1.0; --exactBitsLimit; if (exactBitsLimit == 0) { bit53 = bit; state = AFTER_BIT_53; } break; case AFTER_BIT_53: bit54 = bit; factor = 2.0; state = ZEROS_AFTER_54; break; case ZEROS_AFTER_54: if (bit) { state = MIXED_AFTER_54; } // fallthrough case MIXED_AFTER_54: factor *= 2; break; } } switch (state) { case SKIP_LEADING_ZEROS: sum = 0.0; break; case FIRST_EXACT_53_BITS: case AFTER_BIT_53: // do nothing break; case ZEROS_AFTER_54: // x1.1 -> x1 + 1 (round up) // x0.1 -> x0 (round down) if (bit54 & bit53) sum += 1.0; sum *= factor; break; case MIXED_AFTER_54: // x.100...1.. -> x + 1 (round up) // x.0anything -> x (round down) if (bit54) sum += 1.0; sum *= factor; break; } } /* We don't worry about inaccurate numbers for any other base. */ } return sum; } /** * Return the next {@code n} characters of lookahead (or as many as are * available), after skipping over whitespace and comments. */ protected String lookahead(int n, boolean allowNewline) { Matcher m = (allowNewline ? Whitespace.skipWhiteSpace : Whitespace.skipWhiteSpaceNoNewline).matcher(this.input); m.find(this.pos); return this.inputSubstring(m.end(), m.end()+n); } /** * Is the next input token (after skipping over whitespace and comments) * the identifier {@code name}? */ protected boolean lookaheadIsIdent(String name, boolean allowNewline) { int n = name.length(); String lh = lookahead(n+1, allowNewline); return lh.startsWith(name) && (lh.length() == n || !Identifiers.isIdentifierChar(lh.codePointAt(n), true)); } // getters and setters public void pushTokenContext(TokContext ctxt) { this.context.push(ctxt); } public TokContext popTokenContext() { return this.context.pop(); } public void exprAllowed(boolean exprAllowed) { this.exprAllowed = exprAllowed; } }
package analogclocksvg; import javafx.application.Application; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.input.MouseButton; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.stage.StageStyle; /** * * @author TAKAHASHI,Toru */ public class AnalogClockSvg extends Application { private double dragStartX; private double dragStartY; private ContextMenu popup = new ContextMenu(); @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("AnalogClock.fxml")); Scene scene = new Scene(root, 200, 200, Color.TRANSPARENT); scene.setOnMousePressed(e -> { dragStartX = e.getSceneX(); dragStartY = e.getSceneY(); }); scene.setOnMouseDragged(e -> { stage.setX(e.getScreenX() - dragStartX); stage.setY(e.getScreenY() - dragStartY); }); MenuItem exitItem = new MenuItem("exit"); exitItem.setOnAction(e -> Platform.exit()); popup.getItems().add(exitItem); scene.setOnMouseClicked(e -> { if (e.getButton() == MouseButton.SECONDARY) { popup.show(stage, e.getScreenX(), e.getScreenY()); } }); stage.initStyle(StageStyle.TRANSPARENT); stage.setScene(scene); stage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
package com.jme3.gde.core.assets; import com.jme3.asset.AssetKey; import java.io.BufferedOutputStream; import java.io.BufferedInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.openide.cookies.SaveCookie; import org.openide.filesystems.FileAlreadyLockedException; import org.openide.filesystems.FileLock; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.Exceptions; import org.openide.util.Mutex; import org.openide.util.Mutex.Action; /** * Global object to access actual jME3 data within an AssetDataObject, available * through the Lookup of any AssetDataObject. AssetDataObjects that wish to use * * @author normenhansen */ @SuppressWarnings("unchecked") public class AssetData { private static final Logger logger = Logger.getLogger(AssetData.class.getName()); private final Mutex propsMutex = new Mutex(); private final Properties props = new Properties(); private AssetDataObject file; private String extension = "jmpdata"; private Date lastLoaded; public AssetData(AssetDataObject file) { this.file = file; FileObject primaryFile = file.getPrimaryFile(); if (primaryFile != null) { extension = primaryFile.getExt() + "data"; } } public AssetData(AssetDataObject file, String extension) { this.file = file; this.extension = extension; } public void setExtension(String extension) { this.extension = extension; } public AssetKey<?> getAssetKey() { return file.getAssetKey(); } public void setAssetKey(AssetKey key) { file.setAssetKeyData(key); } public void setModified(boolean modified) { file.setModified(modified); } public void setSaveCookie(SaveCookie cookie) { file.setSaveCookie(cookie); } public Object loadAsset() { return file.loadAsset(); } public void saveAsset() throws IOException { file.saveAsset(); } public void closeAsset() { file.closeAsset(); } public List<FileObject> getAssetList() { return file.getAssetList(); } public List<AssetKey> getAssetKeyList() { return file.getAssetKeyList(); } public List<AssetKey> getFailedList() { return file.getFailedList(); } public synchronized String getProperty(final String key) { return propsMutex.readAccess(new Action<String>() { public String run() { readProperties(); return props.getProperty(key); } }); } public synchronized String getProperty(final String key, final String defaultValue) { return propsMutex.readAccess(new Action<String>() { public String run() { readProperties(); return props.getProperty(key, defaultValue); } }); } public synchronized String setProperty(final String key, final String value) { return propsMutex.writeAccess(new Action<String>() { public String run() { String ret = (String) props.setProperty(key, value); readProperties(); writeProperties(); return ret; } }); } @Deprecated public void loadProperties() { } @Deprecated public void saveProperties() throws FileAlreadyLockedException, IOException { } private void readProperties() { propsMutex.readAccess(new Runnable() { public void run() { final FileObject myFile = FileUtil.findBrother(file.getPrimaryFile(), extension); if (myFile == null) { return; } final Date lastMod = myFile.lastModified(); if (!lastMod.equals(lastLoaded)) { propsMutex.writeAccess(new Runnable() { public void run() { props.clear(); lastLoaded = lastMod; InputStream in = null; try { in = new BufferedInputStream(myFile.getInputStream()); try { props.load(in); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } catch (FileNotFoundException ex) { Exceptions.printStackTrace(ex); } finally { try { in.close(); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } logger.log(Level.INFO, "Read AssetData properties for {0}", file); } }); } } }); } private void writeProperties() { //writeAccess because we write lastMod date, not because we write to the file //the mutex protects the properties object, not the file propsMutex.writeAccess(new Runnable() { public void run() { OutputStream out = null; FileLock lock = null; try { FileObject pFile = file.getPrimaryFile(); FileObject myFile = FileUtil.findBrother(pFile, extension); if (myFile == null) { myFile = FileUtil.createData(pFile.getParent(), pFile.getName() + "." + extension); } lock = myFile.lock(); out = new BufferedOutputStream(myFile.getOutputStream(lock)); props.store(out, ""); out.flush(); lastLoaded = myFile.lastModified(); logger.log(Level.INFO, "Written AssetData properties for {0}", file); } catch (IOException e) { Exceptions.printStackTrace(e); } finally { if (out != null) { try { out.close(); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } if (lock != null) { lock.releaseLock(); } } } }); } }
package com.jme3.gde.core.util; import com.jme3.animation.AnimControl; import com.jme3.gde.core.scene.ApplicationLogHandler.LogLevel; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.SceneGraphVisitor; import com.jme3.scene.SceneGraphVisitorAdapter; import com.jme3.scene.Spatial; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * Various utilities, mostly for operating on Spatials recursively. * * @author normenhansen */ public class SpatialUtil { private static final Logger logger = Logger.getLogger(SpatialUtil.class.getName()); //TODO: use these variables public static final String ORIGINAL_NAME = "ORIGINAL_NAME"; public static final String ORIGINAL_PATH = "ORIGINAL_PATH"; /** * Gets a "pathname" for the given Spatial, combines the Spatials and * parents names to make a long name. This "path" is stored in geometry * after the first import for example. * * @param spat * @return */ public static String getSpatialPath(Spatial spat) { StringBuilder geometryIdentifier = new StringBuilder(); while (spat != null) { String name = spat.getName(); if (name == null) { logger.log(Level.WARNING, "Null spatial name!"); name = "null"; } geometryIdentifier.insert(0, name); geometryIdentifier.insert(0, '/'); spat = spat.getParent(); } String id = geometryIdentifier.toString(); return id; } /** * Stores ORIGINAL_NAME and ORIGINAL_PATH UserData to all Geometry in loaded * spatial * * @param spat */ public static void storeOriginalPathUserData(Spatial spat) { //TODO: only stores for geometry atm final ArrayList<String> geomMap = new ArrayList<String>(); if (spat != null) { spat.depthFirstTraversal(new SceneGraphVisitorAdapter() { @Override public void visit(Geometry geom) { Spatial curSpat = geom; String geomName = curSpat.getName(); if (geomName == null) { logger.log(Level.WARNING, "Null Geometry name!"); geomName = "null"; } geom.setUserData("ORIGINAL_NAME", geomName); logger.log(Level.FINE, "Set ORIGINAL_NAME for {0}", geomName); String id = SpatialUtil.getSpatialPath(curSpat); if (geomMap.contains(id)) { logger.log(Level.WARNING, "Cannot create unique name for Geometry {0}: {1}", new Object[]{geom, id}); } geomMap.add(id); geom.setUserData("ORIGINAL_PATH", id); logger.log(Level.FINE, "Set ORIGINAL_PATH for {0}", id); super.visit(geom); } }); } else { logger.log(Level.SEVERE, "No geometry available when trying to scan initial Geometry configuration"); } } /** * Finds a previously marked spatial in the supplied root Spatial, creates * the name and path to be looked for from the given needle Spatial. * * @param root * @param needle * @return */ public static Spatial findTaggedSpatial(final Spatial root, final Spatial needle) { if (needle == null) { logger.log(Level.WARNING, "Trying to find null needle for {0}", root); return null; } final String name = needle.getName(); final String path = getSpatialPath(needle); if (name == null || path == null) { logger.log(Level.INFO, "Trying to find tagged Spatial with null name spatial for {0}.", root); } final Class clazz = needle.getClass(); String rootName = root.getUserData("ORIGINAL_NAME"); String rootPath = root.getUserData("ORIGINAL_PATH"); if (name.equals(rootName) && path.equals(rootPath)) { return root; } final SpatialHolder holder = new SpatialHolder(); root.depthFirstTraversal(new SceneGraphVisitor() { public void visit(Spatial spatial) { String spName = spatial.getUserData("ORIGINAL_NAME"); String spPath = spatial.getUserData("ORIGINAL_PATH"); if (name.equals(spName) && path.equals(spPath) && clazz.isInstance(spatial)) { if (holder.spatial == null) { holder.spatial = spatial; } else { logger.log(Level.WARNING, "Found Spatial {0} twice in {1}", new Object[]{path, root}); } } } }); return holder.spatial; } /** * Finds a spatial in the given Spatial tree with the specified name and * path, the path and name are constructed from the given (sub-)spatial(s) * and is not read from the UserData of the objects. This is mainly used to * check if the original spatial still exists in the original file. * * @param root * @param name * @param path */ public static Spatial findSpatial(final Spatial root, final String name, final String path) { if (name == null || path == null) { logger.log(Level.INFO, "Trying to find Spatial with null name spatial for {0}.", root); } if (name.equals(root.getName()) && path.equals(getSpatialPath(root))) { return root; } final SpatialHolder holder = new SpatialHolder(); root.depthFirstTraversal(new SceneGraphVisitor() { public void visit(Spatial spatial) { if (name.equals(spatial.getName()) && path.equals(getSpatialPath(spatial))) { if (holder.spatial == null) { holder.spatial = spatial; } else { logger.log(Level.WARNING, "Found Spatial {0} twice in {1}", new Object[]{path, root}); } } } }); return holder.spatial; } /** * Updates the mesh data of existing objects from an original file, adds new * nonexisting geometry objects to the root, including their parents if they * don't exist. * * @param root * @param original */ public static void updateMeshDataFromOriginal(final Spatial root, final Spatial original) { //loop through original to also find new geometry original.depthFirstTraversal(new SceneGraphVisitorAdapter() { @Override public void visit(Geometry geom) { //will always return same class type as 2nd param, so casting is safe Geometry spat = (Geometry) findTaggedSpatial(root, geom); if (spat != null) { spat.setMesh(geom.getMesh()); logger.log(LogLevel.USERINFO, "Updated mesh for Geometry {0}", geom.getName()); } else { addLeafWithNonExistingParents(root, geom); } } }); } /** * Adds a leaf to a spatial, including all nonexisting parents. * * @param root * @param original */ private static void addLeafWithNonExistingParents(Spatial root, Spatial leaf) { if (!(root instanceof Node)) { logger.log(Level.WARNING, "Cannot add new Leaf {0} to {1}, is not a Node!", new Object[]{leaf.getName(), root.getName()}); return; } for (Spatial s = leaf; s.getParent() != null; s = s.getParent()) { Spatial parent = s.getParent(); Spatial other = findSpatial(root, parent.getName(), getSpatialPath(parent)); if (other == null) { continue; } if (other instanceof Node) { logger.log(Level.INFO, "Attaching {0} to {1} in root {2} to add leaf {3}", new Object[]{s, other, root, leaf}); Node otherNode = (Node) other; otherNode.attachChild(s); //set original path data to leaf leaf.setUserData(ORIGINAL_NAME, leaf.getName()); leaf.setUserData(ORIGINAL_PATH, getSpatialPath(leaf)); logger.log(LogLevel.USERINFO, "Attached Node {0} with leaf {0}", new Object[]{other, leaf}); return; } else { logger.log(Level.WARNING, "Cannot attach leaf {0} to found spatial {1} in root {2}, not a node.", new Object[]{leaf, other, root}); } } } public static void clearRemovedOriginals(final Spatial root, final Spatial original) { //TODO: Clear old stuff at all? return; } private static class SpatialHolder { Spatial spatial; } }
package com.jme3.scene; import com.jme3.export.*; import com.jme3.material.Material; import com.jme3.math.Matrix4f; import com.jme3.math.Vector3f; import com.jme3.scene.mesh.IndexBuffer; import com.jme3.util.SafeArrayList; import com.jme3.util.TempVars; import java.io.IOException; import java.nio.Buffer; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * BatchNode holds geometries that are a batched version of all the geometries that are in its sub scenegraph. * There is one geometry per different material in the sub tree. * The geometries are directly attached to the node in the scene graph. * Usage is like any other node except you have to call the {@link #batch()} method once all the geometries have been attached to the sub scene graph and their material set * (see todo more automagic for further enhancements) * All the geometries that have been batched are set to {@link CullHint#Always} to not render them. * The sub geometries can be transformed as usual, their transforms are used to update the mesh of the geometryBatch. * Sub geoms can be removed but it may be slower than the normal spatial removing * Sub geoms can be added after the batch() method has been called but won't be batched and will just be rendered as normal geometries. * To integrate them in the batch you have to call the batch() method again on the batchNode. * * TODO normal or tangents or both looks a bit weird * TODO more automagic (batch when needed in the updateLogicalState) * @author Nehon */ public class BatchNode extends GeometryGroupNode implements Savable { private static final Logger logger = Logger.getLogger(BatchNode.class.getName()); /** * the list of geometry holding the batched meshes */ protected SafeArrayList<Batch> batches = new SafeArrayList<Batch>(Batch.class); /** * a map storing he batches by geometry to quickly acces the batch when updating */ protected Map<Geometry, Batch> batchesByGeom = new HashMap<Geometry, Batch>(); /** * used to store transformed vectors before proceeding to a bulk put into the FloatBuffer */ private float[] tmpFloat; private float[] tmpFloatN; private float[] tmpFloatT; int maxVertCount = 0; boolean useTangents = false; boolean needsFullRebatch = true; /** * Construct a batchNode */ public BatchNode() { super(); } public BatchNode(String name) { super(name); } @Override public void onTransformChange(Geometry geom) { updateSubBatch(geom); } @Override public void onMaterialChange(Geometry geom) { throw new UnsupportedOperationException( "Cannot set the material of a batched geometry, " + "change the material of the parent BatchNode."); } @Override public void onMeshChange(Geometry geom) { throw new UnsupportedOperationException( "Cannot set the mesh of a batched geometry"); } @Override public void onGeoemtryUnassociated(Geometry geom) { setNeedsFullRebatch(true); } @Override public void updateGeometricState() { if (!children.isEmpty()) { for (Batch batch : batches.getArray()) { if (batch.needMeshUpdate) { batch.geometry.updateModelBound(); batch.geometry.updateWorldBound(); batch.needMeshUpdate = false; } } } super.updateGeometricState(); } protected Matrix4f getTransformMatrix(Geometry g){ return g.cachedWorldMat; } protected void updateSubBatch(Geometry bg) { Batch batch = batchesByGeom.get(bg); if (batch != null) { Mesh mesh = batch.geometry.getMesh(); Mesh origMesh = bg.getMesh(); VertexBuffer pvb = mesh.getBuffer(VertexBuffer.Type.Position); FloatBuffer posBuf = (FloatBuffer) pvb.getData(); VertexBuffer nvb = mesh.getBuffer(VertexBuffer.Type.Normal); FloatBuffer normBuf = (FloatBuffer) nvb.getData(); VertexBuffer opvb = origMesh.getBuffer(VertexBuffer.Type.Position); FloatBuffer oposBuf = (FloatBuffer) opvb.getData(); VertexBuffer onvb = origMesh.getBuffer(VertexBuffer.Type.Normal); FloatBuffer onormBuf = (FloatBuffer) onvb.getData(); Matrix4f transformMat = getTransformMatrix(bg); if (mesh.getBuffer(VertexBuffer.Type.Tangent) != null) { VertexBuffer tvb = mesh.getBuffer(VertexBuffer.Type.Tangent); FloatBuffer tanBuf = (FloatBuffer) tvb.getData(); VertexBuffer otvb = origMesh.getBuffer(VertexBuffer.Type.Tangent); FloatBuffer otanBuf = (FloatBuffer) otvb.getData(); doTransformsTangents(oposBuf, onormBuf, otanBuf, posBuf, normBuf, tanBuf, bg.startIndex, bg.startIndex + bg.getVertexCount(), transformMat); tvb.updateData(tanBuf); } else { doTransforms(oposBuf, onormBuf, posBuf, normBuf, bg.startIndex, bg.startIndex + bg.getVertexCount(), transformMat); } pvb.updateData(posBuf); nvb.updateData(normBuf); batch.needMeshUpdate = true; } } /** * Batch this batchNode * every geometry of the sub scene graph of this node will be batched into a single mesh that will be rendered in one call */ public void batch() { doBatch(); //we set the batch geometries to ignore transforms to avoid transforms of parent nodes to be applied twice for (Batch batch : batches.getArray()) { batch.geometry.setIgnoreTransform(true); batch.geometry.setUserData(UserData.JME_PHYSICSIGNORE, true); } } protected void doBatch() { Map<Material, List<Geometry>> matMap = new HashMap<Material, List<Geometry>>(); int nbGeoms = 0; gatherGeomerties(matMap, this, needsFullRebatch); if (needsFullRebatch) { for (Batch batch : batches.getArray()) { batch.geometry.removeFromParent(); } batches.clear(); batchesByGeom.clear(); } //only reset maxVertCount if there is something new to batch if (matMap.size() > 0) { maxVertCount = 0; } for (Map.Entry<Material, List<Geometry>> entry : matMap.entrySet()) { Mesh m = new Mesh(); Material material = entry.getKey(); List<Geometry> list = entry.getValue(); nbGeoms += list.size(); String batchName = name + "-batch" + batches.size(); Batch batch; if (!needsFullRebatch) { batch = findBatchByMaterial(material); if (batch != null) { list.add(0, batch.geometry); batchName = batch.geometry.getName(); batch.geometry.removeFromParent(); } else { batch = new Batch(); } } else { batch = new Batch(); } mergeGeometries(m, list); m.setDynamic(); batch.updateGeomList(list); batch.geometry = new Geometry(batchName); batch.geometry.setMaterial(material); this.attachChild(batch.geometry); batch.geometry.setMesh(m); batch.geometry.getMesh().updateCounts(); batch.geometry.getMesh().updateBound(); batches.add(batch); } if (batches.size() > 0) { needsFullRebatch = false; } logger.log(Level.FINE, "Batched {0} geometries in {1} batches.", new Object[]{nbGeoms, batches.size()}); //init the temp arrays if something has been batched only. if(matMap.size()>0){ //TODO these arrays should be allocated by chunk instead to avoid recreating them each time the batch is changed. //init temp float arrays tmpFloat = new float[maxVertCount * 3]; tmpFloatN = new float[maxVertCount * 3]; if (useTangents) { tmpFloatT = new float[maxVertCount * 4]; } } } //in case the detached spatial is a node, we unbatch all geometries in its subegraph @Override public Spatial detachChildAt(int index) { Spatial s = super.detachChildAt(index); if (s instanceof Node) { unbatchSubGraph(s); } return s; } /** * recursively visit the subgraph and unbatch geometries * @param s */ private void unbatchSubGraph(Spatial s) { if (s instanceof Node) { for (Spatial sp : ((Node) s).getChildren()) { unbatchSubGraph(sp); } } else if (s instanceof Geometry) { Geometry g = (Geometry) s; if (g.isGrouped()) { g.unassociateFromGroupNode(); } } } private void gatherGeomerties(Map<Material, List<Geometry>> map, Spatial n, boolean rebatch) { if (n instanceof Geometry) { if (!isBatch(n) && n.getBatchHint() != BatchHint.Never) { Geometry g = (Geometry) n; if (!g.isGrouped() || rebatch) { if (g.getMaterial() == null) { throw new IllegalStateException("No material is set for Geometry: " + g.getName() + " please set a material before batching"); } List<Geometry> list = map.get(g.getMaterial()); if (list == null) { //trying to compare materials with the isEqual method for (Map.Entry<Material, List<Geometry>> mat : map.entrySet()) { if (g.getMaterial().contentEquals(mat.getKey())) { list = mat.getValue(); } } } if (list == null) { list = new ArrayList<Geometry>(); map.put(g.getMaterial(), list); } g.setTransformRefresh(); list.add(g); } } } else if (n instanceof Node) { for (Spatial child : ((Node) n).getChildren()) { if (child instanceof BatchNode) { continue; } gatherGeomerties(map, child, rebatch); } } } private Batch findBatchByMaterial(Material m) { for (Batch batch : batches.getArray()) { if (batch.geometry.getMaterial().contentEquals(m)) { return batch; } } return null; } private boolean isBatch(Spatial s) { for (Batch batch : batches.getArray()) { if (batch.geometry == s) { return true; } } return false; } /** * Sets the material to the all the batches of this BatchNode * use setMaterial(Material material,int batchIndex) to set a material to a specific batch * * @param material the material to use for this geometry */ @Override public void setMaterial(Material material) { // for (Batch batch : batches.values()) { // batch.geometry.setMaterial(material); throw new UnsupportedOperationException("Unsupported for now, please set the material on the geoms before batching"); } /** * Returns the material that is used for the first batch of this BatchNode * * use getMaterial(Material material,int batchIndex) to get a material from a specific batch * * @return the material that is used for the first batch of this BatchNode * * @see #setMaterial(com.jme3.material.Material) */ public Material getMaterial() { if (!batches.isEmpty()) { Batch b = batches.iterator().next(); return b.geometry.getMaterial(); } return null;//material; } // /** // * Sets the material to the a specific batch of this BatchNode // * // * // * @param material the material to use for this geometry // */ // public void setMaterial(Material material,int batchIndex) { // if (!batches.isEmpty()) { // /** // * Returns the material that is used for the first batch of this BatchNode // * // * use getMaterial(Material material,int batchIndex) to get a material from a specific batch // * // * @return the material that is used for the first batch of this BatchNode // * // * @see #setMaterial(com.jme3.material.Material) // */ // public Material getMaterial(int batchIndex) { // if (!batches.isEmpty()) { // Batch b = batches.get(batches.keySet().iterator().next()); // return b.geometry.getMaterial(); // return null;//material; @Override public void write(JmeExporter ex) throws IOException { super.write(ex); OutputCapsule oc = ex.getCapsule(this); // if (material != null) { // oc.write(material.getAssetName(), "materialName", null); // oc.write(material, "material", null); } @Override public void read(JmeImporter im) throws IOException { super.read(im); InputCapsule ic = im.getCapsule(this); // material = null; // String matName = ic.readString("materialName", null); // if (matName != null) { // // Material name is set, // // Attempt to load material via J3M // try { // material = im.getAssetManager().loadMaterial(matName); // } catch (AssetNotFoundException ex) { // // Cannot find J3M file. // logger.log(Level.FINE, "Could not load J3M file {0} for Geometry.", // matName); // // If material is NULL, try to load it from the geometry // if (material == null) { // material = (Material) ic.readSavable("material", null); } /** * Merges all geometries in the collection into * the output mesh. Does not take into account materials. * * @param geometries * @param outMesh */ private void mergeGeometries(Mesh outMesh, List<Geometry> geometries) { int[] compsForBuf = new int[VertexBuffer.Type.values().length]; VertexBuffer.Format[] formatForBuf = new VertexBuffer.Format[compsForBuf.length]; boolean[] normForBuf = new boolean[VertexBuffer.Type.values().length]; int totalVerts = 0; int totalTris = 0; int totalLodLevels = 0; int maxWeights = -1; Mesh.Mode mode = null; for (Geometry geom : geometries) { totalVerts += geom.getVertexCount(); totalTris += geom.getTriangleCount(); totalLodLevels = Math.min(totalLodLevels, geom.getMesh().getNumLodLevels()); if (maxVertCount < geom.getVertexCount()) { maxVertCount = geom.getVertexCount(); } Mesh.Mode listMode; int components; switch (geom.getMesh().getMode()) { case Points: listMode = Mesh.Mode.Points; components = 1; break; case LineLoop: case LineStrip: case Lines: listMode = Mesh.Mode.Lines; components = 2; break; case TriangleFan: case TriangleStrip: case Triangles: listMode = Mesh.Mode.Triangles; components = 3; break; default: throw new UnsupportedOperationException(); } for (VertexBuffer vb : geom.getMesh().getBufferList().getArray()) { int currentCompsForBuf = compsForBuf[vb.getBufferType().ordinal()]; if (vb.getBufferType() != VertexBuffer.Type.Index && currentCompsForBuf != 0 && currentCompsForBuf != vb.getNumComponents()) { throw new UnsupportedOperationException("The geometry " + geom + " buffer " + vb.getBufferType() + " has different number of components than the rest of the meshes " + "(this: " + vb.getNumComponents() + ", expected: " + currentCompsForBuf + ")"); } compsForBuf[vb.getBufferType().ordinal()] = vb.getNumComponents(); formatForBuf[vb.getBufferType().ordinal()] = vb.getFormat(); normForBuf[vb.getBufferType().ordinal()] = vb.isNormalized(); } maxWeights = Math.max(maxWeights, geom.getMesh().getMaxNumWeights()); if (mode != null && mode != listMode) { throw new UnsupportedOperationException("Cannot combine different" + " primitive types: " + mode + " != " + listMode); } mode = listMode; compsForBuf[VertexBuffer.Type.Index.ordinal()] = components; } outMesh.setMaxNumWeights(maxWeights); outMesh.setMode(mode); if (totalVerts >= 65536) { // make sure we create an UnsignedInt buffer so // we can fit all of the meshes formatForBuf[VertexBuffer.Type.Index.ordinal()] = VertexBuffer.Format.UnsignedInt; } else { formatForBuf[VertexBuffer.Type.Index.ordinal()] = VertexBuffer.Format.UnsignedShort; } // generate output buffers based on retrieved info for (int i = 0; i < compsForBuf.length; i++) { if (compsForBuf[i] == 0) { continue; } Buffer data; if (i == VertexBuffer.Type.Index.ordinal()) { data = VertexBuffer.createBuffer(formatForBuf[i], compsForBuf[i], totalTris); } else { data = VertexBuffer.createBuffer(formatForBuf[i], compsForBuf[i], totalVerts); } VertexBuffer vb = new VertexBuffer(VertexBuffer.Type.values()[i]); vb.setupData(VertexBuffer.Usage.Dynamic, compsForBuf[i], formatForBuf[i], data); vb.setNormalized(normForBuf[i]); outMesh.setBuffer(vb); } int globalVertIndex = 0; int globalTriIndex = 0; for (Geometry geom : geometries) { Mesh inMesh = geom.getMesh(); if (!isBatch(geom)) { geom.associateWithGroupNode(this, globalVertIndex); } int geomVertCount = inMesh.getVertexCount(); int geomTriCount = inMesh.getTriangleCount(); for (int bufType = 0; bufType < compsForBuf.length; bufType++) { VertexBuffer inBuf = inMesh.getBuffer(VertexBuffer.Type.values()[bufType]); VertexBuffer outBuf = outMesh.getBuffer(VertexBuffer.Type.values()[bufType]); if (outBuf == null) { continue; } if (VertexBuffer.Type.Index.ordinal() == bufType) { int components = compsForBuf[bufType]; IndexBuffer inIdx = inMesh.getIndicesAsList(); IndexBuffer outIdx = outMesh.getIndexBuffer(); for (int tri = 0; tri < geomTriCount; tri++) { for (int comp = 0; comp < components; comp++) { int idx = inIdx.get(tri * components + comp) + globalVertIndex; outIdx.put((globalTriIndex + tri) * components + comp, idx); } } } else if (VertexBuffer.Type.Position.ordinal() == bufType) { FloatBuffer inPos = (FloatBuffer) inBuf.getData(); FloatBuffer outPos = (FloatBuffer) outBuf.getData(); doCopyBuffer(inPos, globalVertIndex, outPos, 3); } else if (VertexBuffer.Type.Normal.ordinal() == bufType || VertexBuffer.Type.Tangent.ordinal() == bufType) { FloatBuffer inPos = (FloatBuffer) inBuf.getData(); FloatBuffer outPos = (FloatBuffer) outBuf.getData(); doCopyBuffer(inPos, globalVertIndex, outPos, compsForBuf[bufType]); if (VertexBuffer.Type.Tangent.ordinal() == bufType) { useTangents = true; } } else { inBuf.copyElements(0, outBuf, globalVertIndex, geomVertCount); // for (int vert = 0; vert < geomVertCount; vert++) { // int curGlobalVertIndex = globalVertIndex + vert; // inBuf.copyElement(vert, outBuf, curGlobalVertIndex); } } globalVertIndex += geomVertCount; globalTriIndex += geomTriCount; } } private void doTransforms(FloatBuffer bindBufPos, FloatBuffer bindBufNorm, FloatBuffer bufPos, FloatBuffer bufNorm, int start, int end, Matrix4f transform) { TempVars vars = TempVars.get(); Vector3f pos = vars.vect1; Vector3f norm = vars.vect2; int length = (end - start) * 3; // offset is given in element units // convert to be in component units int offset = start * 3; bindBufPos.rewind(); bindBufNorm.rewind(); //bufPos.position(offset); //bufNorm.position(offset); bindBufPos.get(tmpFloat, 0, length); bindBufNorm.get(tmpFloatN, 0, length); int index = 0; while (index < length) { pos.x = tmpFloat[index]; norm.x = tmpFloatN[index++]; pos.y = tmpFloat[index]; norm.y = tmpFloatN[index++]; pos.z = tmpFloat[index]; norm.z = tmpFloatN[index]; transform.mult(pos, pos); transform.multNormal(norm, norm); index -= 2; tmpFloat[index] = pos.x; tmpFloatN[index++] = norm.x; tmpFloat[index] = pos.y; tmpFloatN[index++] = norm.y; tmpFloat[index] = pos.z; tmpFloatN[index++] = norm.z; } vars.release(); bufPos.position(offset); //using bulk put as it's faster bufPos.put(tmpFloat, 0, length); bufNorm.position(offset); //using bulk put as it's faster bufNorm.put(tmpFloatN, 0, length); } private void doTransformsTangents(FloatBuffer bindBufPos, FloatBuffer bindBufNorm, FloatBuffer bindBufTangents,FloatBuffer bufPos, FloatBuffer bufNorm, FloatBuffer bufTangents, int start, int end, Matrix4f transform) { TempVars vars = TempVars.get(); Vector3f pos = vars.vect1; Vector3f norm = vars.vect2; Vector3f tan = vars.vect3; int length = (end - start) * 3; int tanLength = (end - start) * 4; // offset is given in element units // convert to be in component units int offset = start * 3; int tanOffset = start * 4; bindBufPos.rewind(); bindBufNorm.rewind(); bindBufTangents.rewind(); bindBufPos.get(tmpFloat, 0, length); bindBufNorm.get(tmpFloatN, 0, length); bindBufTangents.get(tmpFloatT, 0, tanLength); int index = 0; int tanIndex = 0; while (index < length) { pos.x = tmpFloat[index]; norm.x = tmpFloatN[index++]; pos.y = tmpFloat[index]; norm.y = tmpFloatN[index++]; pos.z = tmpFloat[index]; norm.z = tmpFloatN[index]; tan.x = tmpFloatT[tanIndex++]; tan.y = tmpFloatT[tanIndex++]; tan.z = tmpFloatT[tanIndex++]; transform.mult(pos, pos); transform.multNormal(norm, norm); transform.multNormal(tan, tan); index -= 2; tanIndex -= 3; tmpFloat[index] = pos.x; tmpFloatN[index++] = norm.x; tmpFloat[index] = pos.y; tmpFloatN[index++] = norm.y; tmpFloat[index] = pos.z; tmpFloatN[index++] = norm.z; tmpFloatT[tanIndex++] = tan.x; tmpFloatT[tanIndex++] = tan.y; tmpFloatT[tanIndex++] = tan.z; //Skipping 4th element of tangent buffer (handedness) tanIndex++; } vars.release(); bufPos.position(offset); //using bulk put as it's faster bufPos.put(tmpFloat, 0, length); bufNorm.position(offset); //using bulk put as it's faster bufNorm.put(tmpFloatN, 0, length); bufTangents.position(tanOffset); //using bulk put as it's faster bufTangents.put(tmpFloatT, 0, tanLength); } private void doCopyBuffer(FloatBuffer inBuf, int offset, FloatBuffer outBuf, int componentSize) { TempVars vars = TempVars.get(); Vector3f pos = vars.vect1; // offset is given in element units // convert to be in component units offset *= componentSize; for (int i = 0; i < inBuf.limit() / componentSize; i++) { pos.x = inBuf.get(i * componentSize + 0); pos.y = inBuf.get(i * componentSize + 1); pos.z = inBuf.get(i * componentSize + 2); outBuf.put(offset + i * componentSize + 0, pos.x); outBuf.put(offset + i * componentSize + 1, pos.y); outBuf.put(offset + i * componentSize + 2, pos.z); } vars.release(); } protected class Batch { /** * update the batchesByGeom map for this batch with the given List of geometries * @param list */ void updateGeomList(List<Geometry> list) { for (Geometry geom : list) { if (!isBatch(geom)) { batchesByGeom.put(geom, this); } } } Geometry geometry; boolean needMeshUpdate = false; } protected void setNeedsFullRebatch(boolean needsFullRebatch) { this.needsFullRebatch = needsFullRebatch; } @Override public Node clone(boolean cloneMaterials) { BatchNode clone = (BatchNode)super.clone(cloneMaterials); if ( batches.size() > 0) { for ( Batch b : batches ) { for ( int i =0; i < clone.children.size(); i++ ) { if ( clone.children.get(i).getName().equals(b.geometry.getName())) { clone.children.remove(i); break; } } } clone.needsFullRebatch = true; clone.batches = new SafeArrayList<Batch>(Batch.class); clone.batchesByGeom = new HashMap<Geometry, Batch>(); clone.batch(); } return clone; } }
package jodd.lagarto.dom; import jodd.lagarto.LagartoLexer; import jodd.util.StringPool; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * DOM node. */ @SuppressWarnings({"ForLoopReplaceableByForEach", "ClassReferencesSubclass"}) public abstract class Node implements Cloneable { /** * Node types. */ public enum NodeType { DOCUMENT, ELEMENT, TEXT, COMMENT, CDATA, DOCUMENT_TYPE, XML_DECLARATION } // node values protected final String nodeName; protected final String nodeRawName; protected final NodeType nodeType; protected Document ownerDocument; // root document node protected String nodeValue; // attributes protected List<Attribute> attributes; // parent protected Node parentNode; // children protected List<Node> childNodes; protected int childElementNodesCount; protected Element[] childElementNodes; // siblings protected int siblingIndex; protected int siblingElementIndex = -1; protected int siblingNameIndex = -1; // position information protected int deepLevel; protected LagartoLexer.Position position; /** * Creates new node. */ protected Node(Document document, NodeType nodeType, String nodeName) { this.ownerDocument = document; this.nodeRawName = nodeName; if (nodeName != null) { this.nodeName = document.isLowercase() ? nodeName.toLowerCase() : nodeName; } else { this.nodeName = null; } this.nodeType = nodeType; } /** * Copies all non-final values to the empty cloned object. * Cache-related values are not copied. */ protected <T extends Node> T cloneTo(T dest) { // dest.nodeValue = nodeValue; // already in clone implementations! dest.parentNode = parentNode; dest.deepLevel = deepLevel; if (attributes != null) { dest.attributes = new ArrayList<Attribute>(attributes.size()); for (int i = 0, attributesSize = attributes.size(); i < attributesSize; i++) { Attribute attr = attributes.get(i); dest.attributes.add(attr.clone()); } } if (childNodes != null) { dest.childNodes = new ArrayList<Node>(childNodes.size()); for (int i = 0, childNodesSize = childNodes.size(); i < childNodesSize; i++) { Node child = childNodes.get(i); Node childClone = child.clone(); childClone.parentNode = dest; // fix parent! dest.childNodes.add(childClone); } } return dest; } @Override public abstract Node clone(); /** * Returns {@link NodeType node type}. */ public NodeType getNodeType() { return nodeType; } /** * Returns nodes name or <code>null</code> if name is not available. */ public String getNodeName() { return nodeName; } /** * Returns nodes raw name - exactly as it was given in the input. */ public String getNodeRawName() { return nodeRawName; } /** * Returns node value or <code>null</code> if value is not available. */ public String getNodeValue() { return nodeValue; } /** * Sets node value. */ public void setNodeValue(String value) { this.nodeValue = value; } /** * Returns owner document, root node for this DOM tree. */ public Document getOwnerDocument() { return ownerDocument; } /** * Removes this node from DOM tree. */ public void detachFromParent() { if (parentNode == null) { return; } if (parentNode.childNodes != null) { parentNode.childNodes.remove(siblingIndex); parentNode.reindexChildren(); } parentNode = null; deepLevel = 0; } /** * Appends child node. Don't use this node in the loop, * since it might be slow due to {@link #reindexChildren()}. */ public void addChild(Node node) { node.detachFromParent(); node.parentNode = this; node.deepLevel = deepLevel + 1; initChildNodes(node); childNodes.add(node); reindexChildrenOnAdd(1); } /** * Appends several child nodes at once. * Reindex is done after all children are added. */ public void addChild(Node... nodes) { for (Node node : nodes) { node.detachFromParent(); node.parentNode = this; node.deepLevel = deepLevel + 1; initChildNodes(node); childNodes.add(node); } reindexChildrenOnAdd(nodes.length); } /** * Inserts node at given index. */ public void insertChild(Node node, int index) { node.detachFromParent(); node.parentNode = this; node.deepLevel = deepLevel + 1; try { initChildNodes(node); childNodes.add(index, node); } catch (IndexOutOfBoundsException ignore) { throw new LagartoDOMException("Invalid node index: " + index); } reindexChildren(); } /** * Inserts node before provided node. */ public void insertBefore(Node newChild, Node refChild) { int siblingIndex = refChild.getSiblingIndex(); refChild.parentNode.insertChild(newChild, siblingIndex); } /** * Inserts node after provided node. */ public void insertAfter(Node newChild, Node refChild) { int siblingIndex = refChild.getSiblingIndex() + 1; if (siblingIndex == refChild.parentNode.getChildNodesCount()) { refChild.parentNode.addChild(newChild); } else { refChild.parentNode.insertChild(newChild, siblingIndex); } } /** * Removes child node at given index. * Returns removed node or <code>null</code> if index is invalid. */ public Node removeChild(int index) { if (childNodes == null) { return null; } Node node; try { node = childNodes.get(index); } catch (IndexOutOfBoundsException ignore) { return null; } node.detachFromParent(); return node; } /** * Removes child node. It works only with direct children, i.e. * if provided child node is not a child nothing happens. */ public void removeChild(Node childNode) { if (childNode.getParentNode() != this) { return; } childNode.detachFromParent(); } /** * Removes all child nodes. Each child node will be detached from this parent. */ public void removeAllChilds() { List<Node> removedNodes = childNodes; childNodes = null; childElementNodes = null; childElementNodesCount = 0; if (removedNodes != null) { for (int i = 0, removedNodesSize = removedNodes.size(); i < removedNodesSize; i++) { Node removedNode = removedNodes.get(i); removedNode.detachFromParent(); } } } /** * Returns parent node or <code>null</code> if no parent exist. */ public Node getParentNode() { return parentNode; } /** * Returns <code>true</code> if node has attributes. */ public boolean hasAttributes() { if (attributes == null) { return false; } return !attributes.isEmpty(); } /** * Returns total number of attributes. */ public int getAttributesCount() { if (attributes == null) { return 0; } return attributes.size(); } /** * Returns attribute at given index or <code>null</code> if index not found. */ public Attribute getAttribute(int index) { if (attributes == null) { return null; } if ((index < 0) || (index >= attributes.size())) { return null; } return attributes.get(index); } /** * Returns <code>true</code> if node contains an attribute. */ public boolean hasAttribute(String name) { if (attributes == null) { return false; } for (int i = 0, attributesSize = attributes.size(); i < attributesSize; i++) { Attribute attr = attributes.get(i); if (attr.getName().equals(name)) { return true; } } return false; } /** * Returns attribute value. Returns <code>null</code> when * attribute doesn't exist or when attribute exist but doesn't * specify a value. */ public String getAttribute(String name) { Attribute attribute = getAttributeInstance(name); if (attribute == null) { return null; } return attribute.getValue(); } protected Attribute getAttributeInstance(String name) { if (attributes == null) { return null; } if (ownerDocument.isLowercase()) { name = name.toLowerCase(); } for (int i = 0, attributesSize = attributes.size(); i < attributesSize; i++) { Attribute attr = attributes.get(i); if (attr.getName().equals(name)) { return attr; } } return null; } protected int indexOfAttributeInstance(String name) { if (attributes == null) { return -1; } if (ownerDocument.isLowercase()) { name = name.toLowerCase(); } for (int i = 0, attributesSize = attributes.size(); i < attributesSize; i++) { Attribute attr = attributes.get(i); if (attr.getName().equals(name)) { return i; } } return -1; } public boolean removeAttribute(String name) { int index = indexOfAttributeInstance(name); if (index == -1) { return false; } attributes.remove(index); return true; } /** * Sets attribute value. Value may be <code>null</code>. */ public void setAttribute(String name, String value) { initAttributes(); String rawAttributeName = name; if (ownerDocument.isLowercase()) { name = name.toLowerCase(); } // search if attribute with the same name exist for (int i = 0, attributesSize = attributes.size(); i < attributesSize; i++) { Attribute attr = attributes.get(i); if (attr.getName().equals(name)) { attr.setValue(value); return; } } attributes.add(new Attribute(rawAttributeName, name, value, true)); } /** * Sets attribute that doesn't need a value. */ public void setAttribute(String name) { setAttribute(name, null); } /** * Returns <code>true</code> if attribute includes some word. */ public boolean isAttributeIncluding(String name, String word) { Attribute attr = getAttributeInstance(name); if (attr == null) { return false; } return attr.isIncluding(word); } /** * Returns <code>true</code> if node has child nodes. */ public boolean hasChildNodes() { if (childNodes == null) { return false; } return !childNodes.isEmpty(); } /** * Returns number of all child nodes. */ public int getChildNodesCount() { if (childNodes == null) { return 0; } return childNodes.size(); } /** * Returns number of child <b>elements</b>. */ public int getChildElementsCount() { return childElementNodesCount; } /** * Returns number of child <b>elements</b> with given name. */ public int getChildElementsCount(String elementName) { Node lastChild = getLastChildElement(elementName); return lastChild.siblingNameIndex + 1; } /** * Returns an array of all children nodes. Returns an empty array * if there are no children. */ public Node[] getChildNodes() { if (childNodes == null) { return new Node[0]; } return childNodes.toArray(new Node[childNodes.size()]); } /** * Returns an array of all children elements. */ public Element[] getChildElements() { initChildElementNodes(); return childElementNodes.clone(); } /** * Returns a child node at given index or <code>null</code> * if child doesn't exist for that index. */ public Node getChild(int index) { if (childNodes == null) { return null; } if ((index < 0) || (index >= childNodes.size())) { return null; } return childNodes.get(index); } /** * Returns a child element node at given index. */ public Element getChildElement(int index) { initChildElementNodes(); if ((index < 0) || (index >= childElementNodes.length)) { return null; } return childElementNodes[index]; } /** * Returns first child or <code>null</code> if no children exist. */ public Node getFirstChild() { if (childNodes == null) { return null; } if (childNodes.isEmpty()) { return null; } return childNodes.get(0); } /** * Returns first child <b>element</b> node or * <code>null</code> if no element children exist. */ public Element getFirstChildElement() { initChildElementNodes(); if (childElementNodes.length == 0) { return null; } return childElementNodes[0]; } /** * Returns first child <b>element</b> with given name or * <code>null</code> if no such children exist. */ public Element getFirstChildElement(String elementName) { if (childNodes == null) { return null; } for (int i = 0, childNodesSize = childNodes.size(); i < childNodesSize; i++) { Node child = childNodes.get(i); if (child.getNodeType() == NodeType.ELEMENT && elementName.equals(child.getNodeName())) { child.initSiblingNames(); return (Element) child; } } return null; } /** * Returns last child or <code>null</code> if no children exist. */ public Node getLastChild() { if (childNodes == null) { return null; } if (childNodes.isEmpty()) { return null; } return childNodes.get(getChildNodesCount() - 1); } /** * Returns last child <b>element</b> node or * <code>null</code> if no such child node exist. */ public Element getLastChildElement() { initChildElementNodes(); if (childElementNodes.length == 0) { return null; } return childElementNodes[childElementNodes.length - 1]; } /** * Returns last child <b>element</b> with given name or * <code>null</code> if no such child node exist. */ public Element getLastChildElement(String elementName) { if (childNodes == null) { return null; } int from = childNodes.size() - 1; for (int i = from; i >= 0; i Node child = childNodes.get(i); if (child.getNodeType() == NodeType.ELEMENT && elementName.equals(child.getNodeName())) { child.initSiblingNames(); return (Element) child; } } return null; } /** * Checks the health of child nodes. Useful during complex tree manipulation, * to check if everything is OK. Not optimized for speed, should be used just * for testing purposes. */ public boolean check() { if (childNodes == null) { return true; } // children int siblingElementIndex = 0; for (int i = 0, childNodesSize = childNodes.size(); i < childNodesSize; i++) { Node childNode = childNodes.get(i); if (childNode.siblingIndex != i) { return false; } if (childNode.getNodeType() == NodeType.ELEMENT) { if (childNode.siblingElementIndex != siblingElementIndex) { return false; } siblingElementIndex++; } } if (childElementNodesCount != siblingElementIndex) { return false; } // child element nodes if (childElementNodes != null) { if (childElementNodes.length != childElementNodesCount) { return false; } int childCount = getChildNodesCount(); for (int i = 0; i < childCount; i++) { Node child = getChild(i); if (child.siblingElementIndex >= 0) { if (childElementNodes[child.siblingElementIndex] != child) { return false; } } } } // sibling names if (siblingNameIndex != -1) { List<Node> siblings = parentNode.childNodes; int index = 0; for (int i = 0, siblingsSize = siblings.size(); i < siblingsSize; i++) { Node sibling = siblings.get(i); if (sibling.siblingNameIndex == -1 && nodeType == NodeType.ELEMENT && nodeName.equals(sibling.getNodeName())) { if (sibling.siblingNameIndex != index++) { return false; } } } } // process children for (Node childNode : childNodes) { if (!childNode.check()) { return false; } } return true; } /** * Reindex children nodes. Must be called on every children addition/removal. * Iterates {@link #childNodes} list and: * <ul> * <li>calculates three different sibling indexes,</li> * <li>calculates total child element node count,</li> * <li>resets child element nodes array (will be init lazy later by @{#initChildElementNodes}.</li> * </ul> */ protected void reindexChildren() { int siblingElementIndex = 0; for (int i = 0, childNodesSize = childNodes.size(); i < childNodesSize; i++) { Node childNode = childNodes.get(i); childNode.siblingIndex = i; childNode.siblingNameIndex = -1; // reset sibling name info if (childNode.getNodeType() == NodeType.ELEMENT) { childNode.siblingElementIndex = siblingElementIndex; siblingElementIndex++; } } childElementNodesCount = siblingElementIndex; childElementNodes = null; // reset child element nodes } /** * Optimized variant of {@link #reindexChildren()} for addition. * Only added children are optimized. */ protected void reindexChildrenOnAdd(int addedCount) { int childNodesSize = childNodes.size(); int previousSize = childNodes.size() - addedCount; int siblingElementIndex = childElementNodesCount; for (int i = previousSize; i < childNodesSize; i++) { Node childNode = childNodes.get(i); childNode.siblingIndex = i; childNode.siblingNameIndex = -1; // reset sibling name info if (childNode.getNodeType() == NodeType.ELEMENT) { childNode.siblingElementIndex = siblingElementIndex; siblingElementIndex++; } } childElementNodesCount = siblingElementIndex; childElementNodes = null; // reset child element nodes } /** * Initializes list of child elements. */ protected void initChildElementNodes() { if (childElementNodes == null) { childElementNodes = new Element[childElementNodesCount]; int childCount = getChildNodesCount(); for (int i = 0; i < childCount; i++) { Node child = getChild(i); if (child.siblingElementIndex >= 0) { childElementNodes[child.siblingElementIndex] = (Element) child; } } } } /** * Initializes siblings elements of the same name. */ protected void initSiblingNames() { if (siblingNameIndex == -1) { List<Node> siblings = parentNode.childNodes; int index = 0; for (int i = 0, siblingsSize = siblings.size(); i < siblingsSize; i++) { Node sibling = siblings.get(i); if (sibling.siblingNameIndex == -1 && nodeType == NodeType.ELEMENT && nodeName.equals(sibling.getNodeName())) { sibling.siblingNameIndex = index++; } } } } /** * Initializes attributes when needed. */ protected void initAttributes() { if (attributes == null) { attributes = new ArrayList<Attribute>(5); } } /** * Initializes child nodes list when needed. * Also fix owner document for new node, if needed. */ protected void initChildNodes(Node newNode) { if (childNodes == null) { childNodes = new ArrayList<Node>(); } if (ownerDocument != null) { if (newNode.ownerDocument != ownerDocument) { changeOwnerDocument(newNode, ownerDocument); } } } /** * Changes owner document for given node and all its children. */ protected void changeOwnerDocument(Node node, Document ownerDocument) { node.ownerDocument = ownerDocument; int childCount = node.getChildNodesCount(); for (int i = 0; i < childCount; i++) { Node child = node.getChild(i); changeOwnerDocument(child, ownerDocument); } } /** * Get the list index of this node in its node sibling list. * For example, if this is the first node sibling, returns 0. * Index address all nodes, i.e. of all node types. */ public int getSiblingIndex() { return siblingIndex; } public int getSiblingElementIndex() { return siblingElementIndex; } public int getSiblingNameIndex() { initSiblingNames(); return siblingNameIndex; } /** * Returns this node's next sibling of <b>any</b> type or * <code>null</code> if this is the last sibling. */ public Node getNextSibling() { List<Node> siblings = parentNode.childNodes; int index = siblingIndex + 1; if (index >= siblings.size()) { return null; } return siblings.get(index); } /** * Returns this node's next <b>element</b>. */ public Node getNextSiblingElement() { parentNode.initChildElementNodes(); if (siblingElementIndex == -1) { int max = parentNode.getChildNodesCount(); for (int i = siblingIndex; i < max; i++) { Node sibling = parentNode.childNodes.get(i); if (sibling.getNodeType() == NodeType.ELEMENT) { return sibling; } } return null; } int index = siblingElementIndex + 1; if (index >= parentNode.childElementNodesCount) { return null; } return parentNode.childElementNodes[index]; } /** * Returns this node's next <b>element</b> with the same name. */ public Node getNextSiblingName() { if (nodeName == null) { return null; } initSiblingNames(); int index = siblingNameIndex + 1; int max = parentNode.getChildNodesCount(); for (int i = siblingIndex + 1; i < max; i++) { Node sibling = parentNode.childNodes.get(i); if ((index == sibling.siblingNameIndex) && nodeName.equals(sibling.getNodeName())) { return sibling; } } return null; } /** * Returns this node's previous sibling of <b>any</b> type * or <code>null</code> if this is the first sibling. */ public Node getPreviousSibling() { List<Node> siblings = parentNode.childNodes; int index = siblingIndex - 1; if (index < 0) { return null; } return siblings.get(index); } /** * Returns this node's previous sibling of <b>element</b> type * or <code>null</code> if this is the first sibling. */ public Node getPreviousSiblingElement() { parentNode.initChildElementNodes(); if (siblingElementIndex == -1) { for (int i = siblingIndex - 1; i >= 0; i Node sibling = parentNode.childNodes.get(i); if (sibling.getNodeType() == NodeType.ELEMENT) { return sibling; } } return null; } int index = siblingElementIndex - 1; if (index < 0) { return null; } return parentNode.childElementNodes[index]; } /** * Returns this node's previous sibling element with the same name. */ public Node getPreviousSiblingName() { if (nodeName == null) { return null; } initSiblingNames(); int index = siblingNameIndex -1; for (int i = siblingIndex; i >= 0; i Node sibling = parentNode.childNodes.get(i); if ((index == sibling.siblingNameIndex) && nodeName.equals(sibling.getNodeName())) { return sibling; } } return null; } /** * Returns the text content of this node and its descendants. * @see #appendTextContent(Appendable) */ public String getTextContent() { StringBuilder sb = new StringBuilder(getChildNodesCount() + 1); appendTextContent(sb); return sb.toString(); } /** * Appends the text content to an <code>Appendable</code> * (<code>StringBuilder</code>, <code>CharBuffer</code>...). * This way we can reuse the <code>Appendable</code> instance * during the creation of text content and have better performances. */ public void appendTextContent(Appendable appendable) { if (nodeValue != null) { if ((nodeType == NodeType.TEXT) || (nodeType == NodeType.CDATA)) { try { appendable.append(nodeValue); } catch (IOException ioex) { throw new LagartoDOMException(ioex); } } } if (childNodes != null) { for (int i = 0, childNodesSize = childNodes.size(); i < childNodesSize; i++) { Node childNode = childNodes.get(i); childNode.appendTextContent(appendable); } } } /** * Generates HTML. */ public String getHtml() { StringBuilder sb = new StringBuilder(); try { toHtml(sb); } catch (IOException ioex) { throw new LagartoDOMException(ioex); } return sb.toString(); } /** * Generates inner HTML. */ public String getInnerHtml() { StringBuilder sb = new StringBuilder(); try { toInnerHtml(sb); } catch (IOException ioex) { throw new LagartoDOMException(ioex); } return sb.toString(); } /** * Generates HTML by appending it to the provided <code>Appendable</code>. */ public void toHtml(Appendable appendable) throws IOException { ownerDocument.getRenderer().renderNodeValue(this, appendable); toInnerHtml(appendable); } protected void toInnerHtml(Appendable appendable) throws IOException { if (childNodes != null) { for (int i = 0, childNodesSize = childNodes.size(); i < childNodesSize; i++) { Node childNode = childNodes.get(i); childNode.toHtml(appendable); } } } /** * Returns deep level. */ public int getDeepLevel() { return deepLevel; } /** * Returns node position, if position is calculated, otherwise <code>null</code>. */ public LagartoLexer.Position getPosition() { return position; } /** * Returns {@link #getPosition() node position} as a string, * ready to be appended to a message. If position is not * calculated, returns an empty string. */ public String getPositionString() { if (parentNode.position != null) { return parentNode.position.toString(); } return StringPool.EMPTY; } /** * Returns CSS path to this node from document root. */ public String getCssPath() { StringBuilder path = new StringBuilder(); Node node = this; while (node != null) { String nodeName = node.getNodeName(); if (nodeName != null) { StringBuilder sb = new StringBuilder(); sb.append(' '); sb.append(nodeName); String id = node.getAttribute("id"); if (id != null) { sb.append('#').append(id); } path.insert(0, sb); } node = node.getParentNode(); } if (path.charAt(0) == ' ') { return path.substring(1); } return path.toString(); } }
package fr.utc.assos.uvweb.adapters; import android.content.Context; import android.text.Html; import android.view.View; import android.view.ViewGroup; import android.widget.SectionIndexer; import android.widget.TextView; import com.emilsjolander.components.stickylistheaders.StickyListHeadersAdapter; import fr.utc.assos.uvweb.R; import fr.utc.assos.uvweb.ThreadPreconditions; import fr.utc.assos.uvweb.data.UVwebContent; import fr.utc.assos.uvweb.holders.UVwebHolder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; /** * An adapter used all together with the {@link fr.utc.assos.uvweb.UVListFragment}'s ListView. * It relies on a standard ViewHolder pattern implemented in the {@link fr.utc.assos.uvweb.holders.UVwebHolder} class and thus allows UVs recycling. * It implements both SectionIndexer and StickyListHeadersAdapter interfaces */ public class UVListAdapter extends UVAdapter implements SectionIndexer, StickyListHeadersAdapter { private static final String TAG = "UVListAdapter"; private List<UVwebContent.UV> mUVs = Collections.emptyList(); private HashMap<String, Integer> mSectionToPosition = new HashMap<String, Integer>(); private HashMap<Integer, String> mSectionHeaderPosition = new HashMap<Integer, String>(); // TODO: int[] ? private String[] mSections; public UVListAdapter(Context context) { super(context); } @Override public int getCount() { return mUVs.size(); } @Override public UVwebContent.UV getItem(int position) { return mUVs.get(position); } public void updateUVs(List<UVwebContent.UV> UVs) { ThreadPreconditions.checkOnMainThread(); int i = 0; for (UVwebContent.UV UV : UVs) { final String s = UV.getLetterCode().substring(0, 1).toUpperCase(); if (!mSectionToPosition.containsKey(s)) { mSectionToPosition.put(s, i); } mSectionHeaderPosition.put(i, s); i++; } // create a list from the set to sort ArrayList<String> sectionList = new ArrayList<String>(mSectionToPosition.keySet()); Collections.sort(sectionList); mSections = new String[sectionList.size()]; sectionList.toArray(mSections); mUVs = UVs; notifyDataSetChanged(); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.uv, null); } TextView codeView = UVwebHolder.get(convertView, R.id.uvcode); TextView rateView = UVwebHolder.get(convertView, R.id.rate); TextView descView = UVwebHolder.get(convertView, R.id.desc); final UVwebContent.UV UV = getItem(position); codeView.setText(Html.fromHtml(String.format(UVwebContent.UV_TITLE_FORMAT, UV.getLetterCode(), UV.getNumberCode()))); descView.setText(UV.getDescription()); rateView.setText(UV.getFormattedRate()); return convertView; } /** * SectionIndexer interface's methods */ @Override public int getSectionForPosition(int position) { return 1; } @Override public int getPositionForSection(int section) { return mSectionToPosition.get(mSections[Math.min(section, mSections.length - 1)]); } @Override public Object[] getSections() { return mSections; } /** * StickyListHeadersAdapter interface's methods */ @Override public View getHeaderView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.header_uv_list, null); } // Set header text as first char in name TextView headerView = UVwebHolder.get(convertView, R.id.header_text); headerView.setText((String.valueOf(getSectionName(position)))); return convertView; } @Override public long getHeaderId(int position) { return getSectionName(position); } /** * @param position the position of a given item in the ListView * @return the name of the corresponding section */ private char getSectionName(int position) { return mSectionHeaderPosition.get(position).charAt(0); } }
package net.localizethat.tasks; import java.util.concurrent.ExecutionException; import javax.swing.SwingWorker; import net.localizethat.Main; import net.localizethat.system.AppSettings; import net.localizethat.util.gui.JStatusBar; /** * Task that saves the preferences in the background (created as task more as an exercise * than for real necessity) * @author rpalomares */ public class SavePreferencesWorker extends SwingWorker<Boolean, Void> { private final JStatusBar statusBar; public SavePreferencesWorker() { statusBar = Main.mainWindow.getStatusBar(); } @Override protected Boolean doInBackground() { AppSettings settings = Main.appSettings; boolean result = settings.save(); return result; } @Override protected void done() { try { boolean result = get(); statusBar.setInfoText("Preferences saved"); } catch (InterruptedException | ExecutionException ex) { statusBar.logMessage(JStatusBar.LogMsgType.ERROR, "Error saving preferences", "Something has prevented from successfully saving preferences", ex); } } }
package com.rnfs; import java.util.Map; import java.util.HashMap; import android.os.Environment; import android.os.StatFs; import android.util.Base64; import android.support.annotation.Nullable; import android.util.SparseArray; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.net.URL; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.WritableArray; import com.facebook.react.modules.core.DeviceEventManagerModule; public class RNFSManager extends ReactContextBaseJavaModule { private static final String NSDocumentDirectoryPath = "NSDocumentDirectoryPath"; private static final String NSExternalDirectoryPath = "NSExternalDirectoryPath"; private static final String NSPicturesDirectoryPath = "NSPicturesDirectoryPath"; private static final String NSCachesDirectoryPath = "NSCachesDirectoryPath"; private static final String NSDocumentDirectory = "NSDocumentDirectory"; private static final String NSFileTypeRegular = "NSFileTypeRegular"; private static final String NSFileTypeDirectory = "NSFileTypeDirectory"; private SparseArray<Downloader> downloaders = new SparseArray<Downloader>(); public RNFSManager(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "RNFSManager"; } @ReactMethod public void writeFile(String filepath, String base64Content, ReadableMap options, Promise promise) { try { byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT); FileOutputStream outputStream = new FileOutputStream(filepath); outputStream.write(bytes); outputStream.close(); promise.resolve(filepath); } catch (Exception ex) { ex.printStackTrace(); reject(promise, ex); } } @ReactMethod public void exists(String filepath, Promise promise) { try { File file = new File(filepath); promise.resolve(file.exists()); } catch (Exception ex) { ex.printStackTrace(); reject(promise, ex); } } @ReactMethod public void readFile(String filepath, Promise promise) { try { File file = new File(filepath); if (!file.exists()) throw new Exception("File does not exist"); FileInputStream inputStream = new FileInputStream(filepath); byte[] buffer = new byte[(int)file.length()]; inputStream.read(buffer); String base64Content = Base64.encodeToString(buffer, Base64.NO_WRAP); promise.resolve(base64Content); } catch (Exception ex) { ex.printStackTrace(); reject(promise, ex); } } @ReactMethod public void moveFile(String filepath, String destPath, Promise promise) { try { File from = new File(filepath); File to = new File(destPath); from.renameTo(to); promise.resolve(true); } catch (Exception ex) { ex.printStackTrace(); reject(promise, ex); } } @ReactMethod public void readDir(String directory, Promise promise) { try { File file = new File(directory); if (!file.exists()) throw new Exception("Folder does not exist"); File[] files = file.listFiles(); WritableArray fileMaps = Arguments.createArray(); for (File childFile : files) { WritableMap fileMap = Arguments.createMap(); fileMap.putString("name", childFile.getName()); fileMap.putString("path", childFile.getAbsolutePath()); fileMap.putInt("size", (int)childFile.length()); fileMap.putInt("type", childFile.isDirectory() ? 1 : 0); fileMaps.pushMap(fileMap); } promise.resolve(fileMaps); } catch (Exception ex) { ex.printStackTrace(); reject(promise, ex); } } @ReactMethod public void stat(String filepath, Promise promise) { try { File file = new File(filepath); if (!file.exists()) throw new Exception("File does not exist"); WritableMap statMap = Arguments.createMap(); statMap.putInt("ctime", (int)(file.lastModified() / 1000)); statMap.putInt("mtime", (int)(file.lastModified() / 1000)); statMap.putInt("size", (int)file.length()); statMap.putInt("type", file.isDirectory() ? 1 : 0); promise.resolve(statMap); } catch (Exception ex) { ex.printStackTrace(); reject(promise, ex); } } @ReactMethod public void unlink(String filepath, Promise promise) { try { File file = new File(filepath); if (!file.exists()) throw new Exception("File does not exist"); boolean success = DeleteRecursive(file); promise.resolve(success); } catch (Exception ex) { ex.printStackTrace(); reject(promise, ex); } } private boolean DeleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) { for (File child : fileOrDirectory.listFiles()) { DeleteRecursive(child); } } return fileOrDirectory.delete(); } @ReactMethod public void mkdir(String filepath, Boolean excludeFromBackup, Promise promise) { try { File file = new File(filepath); file.mkdirs(); boolean success = file.exists(); promise.resolve(success); } catch (Exception ex) { ex.printStackTrace(); reject(promise, ex); } } private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) { reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); } @ReactMethod public void downloadFile(String urlStr, final String filepath, final int jobId, final Promise promise) { try { File file = new File(filepath); URL url = new URL(urlStr); DownloadParams params = new DownloadParams(); params.src = url; params.dest = file; params.onTaskCompleted = new DownloadParams.OnTaskCompleted() { public void onTaskCompleted(DownloadResult res) { if (res.exception == null) { WritableMap infoMap = Arguments.createMap(); infoMap.putInt("jobId", jobId); infoMap.putInt("statusCode", res.statusCode); infoMap.putInt("bytesWritten", res.bytesWritten); promise.resolve(infoMap); } else { reject(promise, ex); } } }; params.onDownloadBegin = new DownloadParams.OnDownloadBegin() { public void onDownloadBegin(int statusCode, int contentLength, Map<String, String> headers) { WritableMap headersMap = Arguments.createMap(); for (Map.Entry<String, String> entry : headers.entrySet()) { headersMap.putString(entry.getKey(), entry.getValue()); } WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); data.putInt("statusCode", statusCode); data.putInt("contentLength", contentLength); data.putMap("headers", headersMap); sendEvent(getReactApplicationContext(), "DownloadBegin-" + jobId, data); } }; params.onDownloadProgress = new DownloadParams.OnDownloadProgress() { public void onDownloadProgress(int contentLength, int bytesWritten) { WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); data.putInt("contentLength", contentLength); data.putInt("bytesWritten", bytesWritten); sendEvent(getReactApplicationContext(), "DownloadProgress-" + jobId, data); } }; Downloader downloader = new Downloader(); downloader.execute(params); this.downloaders.put(jobId, downloader); } catch (Exception ex) { ex.printStackTrace(); reject(promise, ex); } } @ReactMethod public void stopDownload(int jobId) { Downloader downloader = this.downloaders.get(jobId); if (downloader != null) { downloader.stop(); } } @ReactMethod public void pathForBundle(String bundleNamed, Promise promise) { // TODO: Not sure what equilivent would be? } @ReactMethod public void getFSInfo(Promise promise) { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long totalSpace; long freeSpace; if (android.os.Build.VERSION.SDK_INT >= 18) { totalSpace = stat.getTotalBytes(); freeSpace = stat.getFreeBytes(); } else { long blockSize = stat.getBlockSize(); totalSpace = blockSize * stat.getBlockCount(); freeSpace = blockSize * stat.getAvailableBlocks(); } WritableMap info = Arguments.createMap(); info.putDouble("totalSpace", (double)totalSpace); // Int32 too small, must use Double info.putDouble("freeSpace", (double)freeSpace); promise.resolve(info); } private void reject(Promise promise, Exception ex) { promise.reject(ex.getClass().getSimpleName(), ex.getMessage()); } @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put(NSDocumentDirectory, 0); constants.put(NSDocumentDirectoryPath, this.getReactApplicationContext().getFilesDir().getAbsolutePath()); File externalDirectory = this.getReactApplicationContext().getExternalFilesDir(null); if (externalDirectory != null) { constants.put(NSExternalDirectoryPath, externalDirectory.getAbsolutePath()); } else { constants.put(NSExternalDirectoryPath, null); } constants.put(NSPicturesDirectoryPath, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()); constants.put(NSCachesDirectoryPath, this.getReactApplicationContext().getCacheDir().getAbsolutePath()); constants.put(NSFileTypeRegular, 0); constants.put(NSFileTypeDirectory, 1); return constants; } }
package org.voltdb.planner; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.json_voltpatches.JSONException; import org.voltdb.VoltType; import org.voltdb.catalog.CatalogMap; import org.voltdb.catalog.Cluster; import org.voltdb.catalog.Column; import org.voltdb.catalog.ColumnRef; import org.voltdb.catalog.Connector; import org.voltdb.catalog.ConnectorTableInfo; import org.voltdb.catalog.Database; import org.voltdb.catalog.Index; import org.voltdb.catalog.Table; import org.voltdb.expressions.AbstractExpression; import org.voltdb.expressions.AggregateExpression; import org.voltdb.expressions.ConstantValueExpression; import org.voltdb.expressions.ExpressionUtil; import org.voltdb.expressions.OperatorExpression; import org.voltdb.expressions.TupleAddressExpression; import org.voltdb.expressions.TupleValueExpression; import org.voltdb.planner.ParsedSelectStmt.ParsedColInfo; import org.voltdb.plannodes.AbstractPlanNode; import org.voltdb.plannodes.AbstractScanPlanNode; import org.voltdb.plannodes.AggregatePlanNode; import org.voltdb.plannodes.DeletePlanNode; import org.voltdb.plannodes.DistinctPlanNode; import org.voltdb.plannodes.HashAggregatePlanNode; import org.voltdb.plannodes.IndexScanPlanNode; import org.voltdb.plannodes.InsertPlanNode; import org.voltdb.plannodes.LimitPlanNode; import org.voltdb.plannodes.MaterializePlanNode; import org.voltdb.plannodes.NodeSchema; import org.voltdb.plannodes.OrderByPlanNode; import org.voltdb.plannodes.ProjectionPlanNode; import org.voltdb.plannodes.ReceivePlanNode; import org.voltdb.plannodes.SchemaColumn; import org.voltdb.plannodes.SendPlanNode; import org.voltdb.plannodes.SeqScanPlanNode; import org.voltdb.plannodes.UpdatePlanNode; import org.voltdb.types.ExpressionType; import org.voltdb.types.PlanNodeType; import org.voltdb.types.SortDirectionType; import org.voltdb.utils.CatalogUtil; /** * The query planner accepts catalog data, SQL statements from the catalog, then * outputs a set of complete and correct query plans. It will output MANY plans * and some of them will be stupid. The best plan will be selected by computing * resource usage statistics for the plans, then using those statistics to * compute the cost of a specific plan. The plan with the lowest cost wins. * */ public class PlanAssembler { /** convenience pointer to the cluster object in the catalog */ final Cluster m_catalogCluster; /** convenience pointer to the database object in the catalog */ final Database m_catalogDb; /** parsed statement for an insert */ ParsedInsertStmt m_parsedInsert = null; /** parsed statement for an update */ ParsedUpdateStmt m_parsedUpdate = null; /** parsed statement for an delete */ ParsedDeleteStmt m_parsedDelete = null; /** parsed statement for an select */ ParsedSelectStmt m_parsedSelect = null; /** parsed statement for an union */ ParsedUnionStmt m_parsedUnion = null; /** plan selector */ PlanSelector m_planSelector; /** Describes the specified and inferred partition context. */ private final PartitioningForStatement m_partitioning; /** Error message */ String m_recentErrorMsg; /** * Used to generate the table-touching parts of a plan. All join-order and * access path selection stuff is done by the SelectSubPlanAssember. */ SubPlanAssembler subAssembler = null; /** * Counter for the number of plans generated to date for a single statement. */ boolean m_insertPlanWasGenerated = false; /** * Whenever a parameter has its type changed during compilation, the new type is stored * here, indexed by parameter index. */ Map<Integer, VoltType> m_paramTypeOverrideMap = new HashMap<Integer, VoltType>(); /** * * @param catalogCluster * Catalog info about the physical layout of the cluster. * @param catalogDb * Catalog info about schema, metadata and procedures. * @param partitioning * Describes the specified and inferred partition context. */ PlanAssembler(Cluster catalogCluster, Database catalogDb, PartitioningForStatement partitioning, PlanSelector planSelector) { m_catalogCluster = catalogCluster; m_catalogDb = catalogDb; m_partitioning = partitioning; m_planSelector = planSelector; } String getSQLText() { if (m_parsedDelete != null) { return m_parsedDelete.sql; } else if (m_parsedInsert != null) { return m_parsedInsert.sql; } else if (m_parsedUpdate != null) { return m_parsedUpdate.sql; } else if (m_parsedSelect != null) { return m_parsedSelect.sql; } assert(false); return null; } /** * Return true if tableList includes at least one matview. */ private boolean tableListIncludesView(List<Table> tableList) { for (Table table : tableList) { if (table.getMaterializer() != null) { return true; } } return false; } /** * Return true if tableList includes at least one export table. */ private boolean tableListIncludesExportOnly(List<Table> tableList) { // the single well-known connector Connector connector = m_catalogDb.getConnectors().get("0"); // no export tables with out a connector if (connector == null) { return false; } CatalogMap<ConnectorTableInfo> tableinfo = connector.getTableinfo(); // this loop is O(number-of-joins * number-of-export-tables) // which seems acceptable if not great. Probably faster than // re-hashing the export only tables for faster lookup. for (Table table : tableList) { for (ConnectorTableInfo ti : tableinfo) { if (ti.getAppendonly() && ti.getTable().getTypeName().equalsIgnoreCase(table.getTypeName())) { return true; } } } return false; } /** * Clear any old state and get ready to plan a new plan. The next call to * getNextPlan() will return the first candidate plan for these parameters. * */ void setupForNewPlans(AbstractParsedStmt parsedStmt) { m_insertPlanWasGenerated = false; int countOfPartitionedTables = 0; Map<String, String> partitionColumnByTable = new HashMap<String, String>(); // Do we have a need for a distributed scan at all? // Iterate over the tables to collect partition columns. for (Table table : parsedStmt.tableList) { if (table.getIsreplicated()) { continue; } ++countOfPartitionedTables; String colName = null; Column partitionCol = table.getPartitioncolumn(); // "(partitionCol != null)" tests around an obscure edge case. // The table is declared non-replicated yet specifies no partitioning column. // This can occur legitimately when views based on partitioned tables neglect to group by the partition column. // The interpretation of this edge case is that the table has "randomly distributed data". // In such a case, the table is valid for use by MP queries only and can only be joined with replicated tables // because it has no recognized partitioning join key. if (partitionCol != null) { colName = partitionCol.getTypeName(); // Note getTypeName gets the column name -- go figure. } //TODO: This map really wants to be indexed by table "alias" (the in-query table scan identifier) // so self-joins can be supported without ambiguity. String partitionedTable = table.getTypeName(); partitionColumnByTable.put(partitionedTable, colName); } m_partitioning.setPartitionedTables(partitionColumnByTable, countOfPartitionedTables); if ((m_partitioning.wasSpecifiedAsSingle() == false) && m_partitioning.getCountOfPartitionedTables() > 0) { m_partitioning.analyzeForMultiPartitionAccess(parsedStmt.tableList, parsedStmt.valueEquivalence); int multiPartitionScanCount = m_partitioning.getCountOfIndependentlyPartitionedTables(); if (multiPartitionScanCount > 1) { String msg = "Join or union of multiple partitioned tables has insufficient join criteria."; throw new PlanningErrorException(msg); } } if (parsedStmt instanceof ParsedUnionStmt) { m_parsedUnion = (ParsedUnionStmt) parsedStmt; subAssembler = new UnionSubPlanAssembler(m_catalogDb, parsedStmt, m_partitioning); } else if (parsedStmt instanceof ParsedSelectStmt) { if (tableListIncludesExportOnly(parsedStmt.tableList)) { throw new RuntimeException( "Illegal to read an export table."); } m_parsedSelect = (ParsedSelectStmt) parsedStmt; subAssembler = new SelectSubPlanAssembler(m_catalogDb, parsedStmt, m_partitioning); } else { // check that no modification happens to views if (tableListIncludesView(parsedStmt.tableList)) { throw new RuntimeException( "Illegal to modify a materialized view."); } // Check that only multi-partition writes are made to replicated tables. // figure out which table we're updating/deleting assert (parsedStmt.tableList.size() == 1); Table targetTable = parsedStmt.tableList.get(0); if (targetTable.getIsreplicated()) { if (m_partitioning.wasSpecifiedAsSingle()) { String msg = "Trying to write to replicated table '" + targetTable.getTypeName() + "' in a single-partition procedure."; throw new PlanningErrorException(msg); } } else if (m_partitioning.wasSpecifiedAsSingle() == false) { m_partitioning.setPartitioningColumn(targetTable.getPartitioncolumn()); } if (parsedStmt instanceof ParsedInsertStmt) { m_parsedInsert = (ParsedInsertStmt) parsedStmt; // The currently handled inserts are too simple to even require a subplan assembler. So, done. return; } if (parsedStmt instanceof ParsedUpdateStmt) { if (tableListIncludesExportOnly(parsedStmt.tableList)) { throw new RuntimeException( "Illegal to update an export table."); } m_parsedUpdate = (ParsedUpdateStmt) parsedStmt; } else if (parsedStmt instanceof ParsedDeleteStmt) { if (tableListIncludesExportOnly(parsedStmt.tableList)) { throw new RuntimeException( "Illegal to delete from an export table."); } m_parsedDelete = (ParsedDeleteStmt) parsedStmt; } else { throw new RuntimeException( "Unknown subclass of AbstractParsedStmt."); } subAssembler = new WriterSubPlanAssembler(m_catalogDb, parsedStmt, m_partitioning); } } /** * Generate the best cost plan for the current SQL statement context. * * @param parsedStmt Current SQL statement to generate plan for * @return The best cost plan or null. */ public CompiledPlan getBestCostPlan(AbstractParsedStmt parsedStmt) { // set up the plan assembler for this statement setupForNewPlans(parsedStmt); // get ready to find the plan with minimal cost CompiledPlan rawplan = null; // loop over all possible plans while (true) { try { rawplan = getNextPlan(); } // on exception, set the error message and bail... catch (PlanningErrorException e) { m_recentErrorMsg = e.getMessage(); return null; } // stop this while loop when no more plans are generated if (rawplan == null) break; // Update the best cost plan so far m_planSelector.considerCandidatePlan(rawplan); } return m_planSelector.m_bestPlan; } /** * Output the best cost plan. * */ public void finalizeBestCostPlan() { m_planSelector.finalizeOutput(); } /** * Generate a unique and correct plan for the current SQL statement context. * This method gets called repeatedly until it returns null, meaning there * are no more plans. * * @return A not-previously returned query plan or null if no more * computable plans. */ CompiledPlan getNextPlan() { // reset the plan column guids and pool //PlanColumn.resetAll(); CompiledPlan retval = new CompiledPlan(); AbstractParsedStmt nextStmt = null; if (m_parsedUnion != null) { nextStmt = m_parsedUnion; retval = getNextUnionPlan(); if (retval != null) { retval.readOnly = true; } } else if (m_parsedSelect != null) { nextStmt = m_parsedSelect; retval.rootPlanGraph = getNextSelectPlan(); retval.readOnly = true; if (retval.rootPlanGraph != null) { // only add the output columns if we actually have a plan // avoid PlanColumn resource leakage addColumns(retval, m_parsedSelect); boolean orderIsDeterministic = m_parsedSelect.isOrderDeterministic(); boolean contentIsDeterministic = (m_parsedSelect.hasLimitOrOffset() == false) || orderIsDeterministic; retval.statementGuaranteesDeterminism(contentIsDeterministic, orderIsDeterministic); } } else { retval.readOnly = false; if (m_parsedInsert != null) { nextStmt = m_parsedInsert; retval.rootPlanGraph = getNextInsertPlan(); } else if (m_parsedUpdate != null) { nextStmt = m_parsedUpdate; retval.rootPlanGraph = getNextUpdatePlan(); // note that for replicated tables, multi-fragment plans // need to divide the result by the number of partitions } else if (m_parsedDelete != null) { nextStmt = m_parsedDelete; retval.rootPlanGraph = getNextDeletePlan(); // note that for replicated tables, multi-fragment plans // need to divide the result by the number of partitions } else { throw new RuntimeException( "setupForNewPlans not called or not successfull."); } assert (nextStmt.tableList.size() == 1); if (nextStmt.tableList.get(0).getIsreplicated()) retval.replicatedTableDML = true; retval.statementGuaranteesDeterminism(true, true); // Until we support DML w/ subqueries/limits } if (retval == null || retval.rootPlanGraph == null) { return null; } assert (nextStmt != null); addParameters(retval, nextStmt); retval.fullWhereClause = nextStmt.where; retval.fullWinnerPlan = retval.rootPlanGraph; // Do a final generateOutputSchema pass. retval.rootPlanGraph.generateOutputSchema(m_catalogDb); retval.setPartitioningKey(m_partitioning.effectivePartitioningValue()); return retval; } /** * This is a UNION specific method. Generate a unique and correct plan * for the current SQL UNION statement by building the best plans for each individual statements * within the UNION. * * @return A union plan or null. */ private CompiledPlan getNextUnionPlan() { AbstractPlanNode subUnionRoot = subAssembler.nextPlan(); if (subUnionRoot == null) { return null; } m_recentErrorMsg = null; ArrayList<CompiledPlan> childrenPlans = new ArrayList<CompiledPlan>(); boolean orderIsDeterministic = true; boolean contentIsDeterministic = true; // The children plans are never final - don't need send/receive pair on top ArrayList<PartitioningForStatement> partitioningList = new ArrayList<PartitioningForStatement>(); // Build best plans for the children first int planId = 0; for (AbstractParsedStmt parsedChildStmt : m_parsedUnion.m_children) { PartitioningForStatement partitioning = (PartitioningForStatement)m_partitioning.clone(); PlanSelector processor = (PlanSelector) m_planSelector.clone(); processor.m_planId = planId; PlanAssembler assembler = new PlanAssembler( m_catalogCluster, m_catalogDb, partitioning, processor); CompiledPlan bestChildPlan = assembler.getBestCostPlan(parsedChildStmt); // make sure we got a winner if (bestChildPlan == null) { if (m_recentErrorMsg == null) { m_recentErrorMsg = "Unable to plan for statement. Error unknown."; } return null; } childrenPlans.add(bestChildPlan); orderIsDeterministic = orderIsDeterministic && bestChildPlan.isOrderDeterministic(); contentIsDeterministic = contentIsDeterministic && bestChildPlan.isContentDeterministic(); partitioningList.add(partitioning); // Make sure that next child's plans won't override current ones. planId = processor.m_planId; } // need to reset plan id for the entire UNION m_planSelector.m_planId = planId; // Add and link children plans for (CompiledPlan selectPlan : childrenPlans) { subUnionRoot.addAndLinkChild(selectPlan.rootPlanGraph); } CompiledPlan retval = new CompiledPlan(); retval.rootPlanGraph = subUnionRoot; retval.readOnly = true; retval.sql = m_planSelector.m_sql; retval.statementGuaranteesDeterminism(contentIsDeterministic, orderIsDeterministic); // compute the cost - total of all children retval.cost = 0.0; for (CompiledPlan bestChildPlan : childrenPlans) { retval.cost += bestChildPlan.cost; } return retval; } private void addColumns(CompiledPlan plan, ParsedSelectStmt stmt) { NodeSchema output_schema = plan.rootPlanGraph.getOutputSchema(); // Sanity-check the output NodeSchema columns against the display columns if (stmt.displayColumns.size() != output_schema.size()) { throw new PlanningErrorException("Mismatched plan output cols " + "to parsed display columns"); } for (ParsedColInfo display_col : stmt.displayColumns) { SchemaColumn col = output_schema.find(display_col.tableName, display_col.columnName, display_col.alias); if (col == null) { throw new PlanningErrorException("Mismatched plan output cols " + "to parsed display columns"); } } plan.columns = output_schema; } private void addParameters(CompiledPlan plan, AbstractParsedStmt stmt) { plan.parameters = new VoltType[stmt.paramList.length]; for (int i = 0; i < stmt.paramList.length; ++i) { VoltType override = m_paramTypeOverrideMap.get(i); if (override != null) { plan.parameters[i] = override; } else { plan.parameters[i] = stmt.paramList[i]; } } } private AbstractPlanNode getNextSelectPlan() { assert (subAssembler != null); AbstractPlanNode subSelectRoot = subAssembler.nextPlan(); if (subSelectRoot == null) return null; AbstractPlanNode root = subSelectRoot; /* * Establish the output columns for the sub select plan. */ root.generateOutputSchema(m_catalogDb); root = handleAggregationOperators(root); root = handleOrderBy(root); if ((root.getPlanNodeType() != PlanNodeType.AGGREGATE) && (root.getPlanNodeType() != PlanNodeType.HASHAGGREGATE) && (root.getPlanNodeType() != PlanNodeType.DISTINCT) && (root.getPlanNodeType() != PlanNodeType.PROJECTION)) { root = addProjection(root); } if (m_parsedSelect.hasLimitOrOffset()) { root = handleLimitOperator(root); } root.generateOutputSchema(m_catalogDb); return root; } private AbstractPlanNode getNextDeletePlan() { assert (subAssembler != null); // figure out which table we're deleting from assert (m_parsedDelete.tableList.size() == 1); Table targetTable = m_parsedDelete.tableList.get(0); AbstractPlanNode subSelectRoot = subAssembler.nextPlan(); if (subSelectRoot == null) return null; // generate the delete node with the right target table DeletePlanNode deleteNode = new DeletePlanNode(); deleteNode.setTargetTableName(targetTable.getTypeName()); ProjectionPlanNode projectionNode = new ProjectionPlanNode(); AbstractExpression addressExpr = new TupleAddressExpression(); NodeSchema proj_schema = new NodeSchema(); // This planner-created column is magic. proj_schema.addColumn(new SchemaColumn("VOLT_TEMP_TABLE", "tuple_address", "tuple_address", addressExpr)); projectionNode.setOutputSchema(proj_schema); assert(subSelectRoot instanceof AbstractScanPlanNode); // If the scan matches all rows, we can throw away the scan // nodes and use a truncate delete node. // Assume all index scans have filters in this context, so only consider seq scans. if (m_partitioning.wasSpecifiedAsSingle() && (subSelectRoot instanceof SeqScanPlanNode) && (((SeqScanPlanNode) subSelectRoot).getPredicate() == null)) { deleteNode.setTruncate(true); return deleteNode; } // OPTIMIZATION: Projection Inline // If the root node we got back from createSelectTree() is an // AbstractScanNode, then // we put the Projection node we just created inside of it // When we inline this projection into the scan, we're going // to overwrite any original projection that we might have inlined // in order to simply cull the columns from the persistent table. // The call here to generateOutputSchema() will recurse down to // the scan node and cause it to update appropriately. subSelectRoot.addInlinePlanNode(projectionNode); // connect the nodes to build the graph deleteNode.addAndLinkChild(subSelectRoot); if (m_partitioning.wasSpecifiedAsSingle() || m_partitioning.hasPartitioningConstantLockedIn()) { deleteNode.generateOutputSchema(m_catalogDb); return deleteNode; } // Send the local result counts to the coordinator. AbstractPlanNode recvNode = subAssembler.addSendReceivePair(deleteNode); // add a sum and send on top of the union return addSumAndSendToDMLNode(recvNode); } private AbstractPlanNode getNextUpdatePlan() { assert (subAssembler != null); AbstractPlanNode subSelectRoot = subAssembler.nextPlan(); if (subSelectRoot == null) return null; UpdatePlanNode updateNode = new UpdatePlanNode(); Table targetTable = m_parsedUpdate.tableList.get(0); updateNode.setTargetTableName(targetTable.getTypeName()); // set this to false until proven otherwise updateNode.setUpdateIndexes(false); ProjectionPlanNode projectionNode = new ProjectionPlanNode(); TupleAddressExpression tae = new TupleAddressExpression(); NodeSchema proj_schema = new NodeSchema(); // This planner-generated column is magic. proj_schema.addColumn(new SchemaColumn("VOLT_TEMP_TABLE", "tuple_address", "tuple_address", tae)); // get the set of columns affected by indexes Set<String> affectedColumns = getIndexedColumnSetForTable(targetTable); // add the output columns we need to the projection // Right now, the EE is going to use the original column names // and compare these to the persistent table column names in the // update executor in order to figure out which table columns get // updated. We'll associate the actual values with VOLT_TEMP_TABLE // to avoid any false schema/column matches with the actual table. for (Entry<Column, AbstractExpression> col : m_parsedUpdate.columns.entrySet()) { // make the literal type we're going to insert match the column type AbstractExpression castedExpr = null; try { castedExpr = (AbstractExpression) col.getValue().clone(); ExpressionUtil.setOutputTypeForInsertExpression( castedExpr, VoltType.get((byte) col.getKey().getType()), col.getKey().getSize(), m_paramTypeOverrideMap); } catch (Exception e) { throw new PlanningErrorException(e.getMessage()); } proj_schema.addColumn(new SchemaColumn("VOLT_TEMP_TABLE", col.getKey().getTypeName(), col.getKey().getTypeName(), castedExpr)); // check if this column is an indexed column if (affectedColumns.contains(col.getKey().getTypeName())) { updateNode.setUpdateIndexes(true); } } projectionNode.setOutputSchema(proj_schema); // add the projection inline (TODO: this will break if more than one // layer is below this) // When we inline this projection into the scan, we're going // to overwrite any original projection that we might have inlined // in order to simply cull the columns from the persistent table. // The call here to generateOutputSchema() will recurse down to // the scan node and cause it to update appropriately. assert(subSelectRoot instanceof AbstractScanPlanNode); subSelectRoot.addInlinePlanNode(projectionNode); // connect the nodes to build the graph updateNode.addAndLinkChild(subSelectRoot); if (m_partitioning.wasSpecifiedAsSingle() || m_partitioning.hasPartitioningConstantLockedIn()) { updateNode.generateOutputSchema(m_catalogDb); return updateNode; } // Send the local result counts to the coordinator. AbstractPlanNode recvNode = subAssembler.addSendReceivePair(updateNode); // add a sum and send on top of the union return addSumAndSendToDMLNode(recvNode); } /** * Get the next (only) plan for a SQL insertion. Inserts are pretty simple * and this will only generate a single plan. * * @return The next plan for a given insert statement. */ private AbstractPlanNode getNextInsertPlan() { // there's really only one way to do an insert, so just // do it the right way once, then return null after that if (m_insertPlanWasGenerated) return null; m_insertPlanWasGenerated = true; // figure out which table we're inserting into assert (m_parsedInsert.tableList.size() == 1); Table targetTable = m_parsedInsert.tableList.get(0); // the root of the insert plan is always an InsertPlanNode InsertPlanNode insertNode = new InsertPlanNode(); insertNode.setTargetTableName(targetTable.getTypeName()); insertNode.setMultiPartition(m_partitioning.wasSpecifiedAsSingle() == false); // the materialize node creates a tuple to insert (which is frankly not // always optimal) MaterializePlanNode materializeNode = new MaterializePlanNode(); NodeSchema mat_schema = new NodeSchema(); // get the ordered list of columns for the targettable using a helper // function they're not guaranteed to be in order in the catalog List<Column> columns = CatalogUtil.getSortedCatalogItems(targetTable.getColumns(), "index"); // for each column in the table in order... for (Column column : columns) { // get the expression for the column AbstractExpression expr = m_parsedInsert.columns.get(column); // if there's no expression, make sure the column has // some supported default value if (expr == null) { // if it's not nullable or defaulted we have a problem if (column.getNullable() == false && column.getDefaulttype() == 0) { throw new PlanningErrorException("Column " + column.getName() + " has no default and is not nullable."); } ConstantValueExpression const_expr = new ConstantValueExpression(); expr = const_expr; if (column.getDefaulttype() != 0) { const_expr.setValue(column.getDefaultvalue()); const_expr.setValueType(VoltType.get((byte) column.getDefaulttype())); } else { const_expr.setValue(null); } } if (expr.getValueType() == VoltType.NULL) { ConstantValueExpression const_expr = new ConstantValueExpression(); const_expr.setValue("NULL"); } // set the expression type to match the corresponding Column. try { ExpressionUtil.setOutputTypeForInsertExpression(expr, VoltType.get((byte)column.getType()), column.getSize(), m_paramTypeOverrideMap); } catch (Exception e) { throw new PlanningErrorException(e.getMessage()); } // Hint that this statement can be executed SP. if (column.equals(m_partitioning.getColumn())) { String fullColumnName = targetTable.getTypeName() + "." + column.getTypeName(); m_partitioning.addPartitioningExpression(fullColumnName, expr); m_partitioning.setInferredValue(ConstantValueExpression.extractPartitioningValue(expr.getValueType(), expr)); } // add column to the materialize node. // This table name is magic. mat_schema.addColumn(new SchemaColumn("VOLT_TEMP_TABLE", column.getTypeName(), column.getTypeName(), expr)); } materializeNode.setOutputSchema(mat_schema); // connect the insert and the materialize nodes together insertNode.addAndLinkChild(materializeNode); insertNode.generateOutputSchema(m_catalogDb); if (m_partitioning.wasSpecifiedAsSingle() || m_partitioning.hasPartitioningConstantLockedIn()) { return insertNode; } SendPlanNode sendNode = new SendPlanNode(); // this will make the child plan fragment be sent to all partitions sendNode.isMultiPartition = true; sendNode.addAndLinkChild(insertNode); // sendNode.generateOutputSchema(m_catalogDb); AbstractPlanNode recvNode = new ReceivePlanNode(); recvNode.addAndLinkChild(sendNode); recvNode.generateOutputSchema(m_catalogDb); // add a count and send on top of the union return addSumAndSendToDMLNode(recvNode); } AbstractPlanNode addSumAndSendToDMLNode(AbstractPlanNode dmlRoot) { // create the nodes being pushed on top of dmlRoot. AggregatePlanNode countNode = new AggregatePlanNode(); SendPlanNode sendNode = new SendPlanNode(); // configure the count aggregate (sum) node to produce a single // output column containing the result of the sum. // Create a TVE that should match the tuple count input column // This TVE is magic. // really really need to make this less hard-wired TupleValueExpression count_tve = new TupleValueExpression(); count_tve.setValueType(VoltType.BIGINT); count_tve.setValueSize(VoltType.BIGINT.getLengthInBytesForFixedTypes()); count_tve.setColumnIndex(0); count_tve.setColumnName("modified_tuples"); count_tve.setColumnAlias("modified_tuples"); count_tve.setTableName("VOLT_TEMP_TABLE"); countNode.addAggregate(ExpressionType.AGGREGATE_SUM, false, 0, count_tve); // The output column. Not really based on a TVE (it is really the // count expression represented by the count configured above). But // this is sufficient for now. This looks identical to the above // TVE but it's logically different so we'll create a fresh one. // And yes, oh, oh, it's magic</elo> TupleValueExpression tve = new TupleValueExpression(); tve.setValueType(VoltType.BIGINT); tve.setValueSize(VoltType.BIGINT.getLengthInBytesForFixedTypes()); tve.setColumnIndex(0); tve.setColumnName("modified_tuples"); tve.setColumnAlias("modified_tuples"); tve.setTableName("VOLT_TEMP_TABLE"); NodeSchema count_schema = new NodeSchema(); SchemaColumn col = new SchemaColumn("VOLT_TEMP_TABLE", "modified_tuples", "modified_tuples", tve); count_schema.addColumn(col); countNode.setOutputSchema(count_schema); // connect the nodes to build the graph countNode.addAndLinkChild(dmlRoot); countNode.generateOutputSchema(m_catalogDb); sendNode.addAndLinkChild(countNode); sendNode.generateOutputSchema(m_catalogDb); return sendNode; } /** * Given a relatively complete plan-sub-graph, apply a trivial projection * (filter) to it. If the root node can embed the projection do so. If not, * add a new projection node. * * @param rootNode * The root of the plan-sub-graph to add the projection to. * @return The new root of the plan-sub-graph (might be the same as the * input). */ AbstractPlanNode addProjection(AbstractPlanNode rootNode) { assert (m_parsedSelect != null); assert (m_parsedSelect.displayColumns != null); ProjectionPlanNode projectionNode = new ProjectionPlanNode(); NodeSchema proj_schema = new NodeSchema(); // Build the output schema for the projection based on the display columns for (ParsedSelectStmt.ParsedColInfo outputCol : m_parsedSelect.displayColumns) { assert(outputCol.expression != null); SchemaColumn col = new SchemaColumn(outputCol.tableName, outputCol.columnName, outputCol.alias, outputCol.expression); proj_schema.addColumn(col); } projectionNode.setOutputSchema(proj_schema); // if the projection can be done inline... if (rootNode instanceof AbstractScanPlanNode) { rootNode.addInlinePlanNode(projectionNode); return rootNode; } else { projectionNode.addAndLinkChild(rootNode); projectionNode.generateOutputSchema(m_catalogDb); return projectionNode; } } /** * Create an order by node as required by the statement and make it a parent of root. * @param root * @return new orderByNode (the new root) or the original root if no orderByNode was required. */ AbstractPlanNode handleOrderBy(AbstractPlanNode root) { assert (m_parsedSelect != null); // Only sort when the statement has an ORDER BY. if ( ! m_parsedSelect.hasOrderByColumns()) { return root; } // Ignore ORDER BY in cases where there can be at most one row. if (m_parsedSelect.guaranteesUniqueRow()) { return root; } // Skip the explicit ORDER BY plan step if an IndexScan is already providing the equivalent ordering. // Note that even tree index scans that produce values in their own "key order" only report // their sort direction != SortDirectionType.INVALID // when they enforce an ordering equivalent to the one requested in the ORDER BY clause. if (root.getPlanNodeType() == PlanNodeType.INDEXSCAN) { if (((IndexScanPlanNode) root).getSortDirection() != SortDirectionType.INVALID) { return root; } } OrderByPlanNode orderByNode = new OrderByPlanNode(); for (ParsedSelectStmt.ParsedColInfo col : m_parsedSelect.orderColumns) { orderByNode.addSort(col.expression, col.ascending ? SortDirectionType.ASC : SortDirectionType.DESC); } orderByNode.addAndLinkChild(root); orderByNode.generateOutputSchema(m_catalogDb); // In theory, for a single-table query, there just needs to exist a uniqueness constraint (primary key or other unique index) // on some of the ORDER BY values regardless of whether the associated index is used in the selected plan. // Strictly speaking, if it was used at the top of the plan, this function would have already returned without adding an orderByNode. // The interesting case here, addressing issue ENG-3335, is when the index scan is in the distributed part of the plan. // Then, the orderByNode is required to re-order the results at the coordinator. // Start by eliminating joins since, in general, a join (one-to-many) may produce multiple joined rows for each unique input row. // TODO: In theory, it is possible to analyze the join criteria and/or projected columns // to determine whether the particular join preserves the uniqueness of its index-scanned input. if (m_parsedSelect.tableList.size() == 1) { Table table = m_parsedSelect.tableList.get(0); // get all of the columns in the sort List<AbstractExpression> orderExpressions = orderByNode.getSortExpressions(); // search indexes for one that makes the order by deterministic for (Index index : table.getIndexes()) { // skip non-unique indexes if (!index.getUnique()) { continue; } // get the list of expressions for the index List<AbstractExpression> indexExpressions = new ArrayList<AbstractExpression>(); String jsonExpr = index.getExpressionsjson(); // if this is a pure-column index... if (jsonExpr.isEmpty()) { for (ColumnRef cref : index.getColumns()) { Column col = cref.getColumn(); TupleValueExpression tve = new TupleValueExpression(); tve.setColumnIndex(col.getIndex()); tve.setColumnName(col.getName()); tve.setExpressionType(ExpressionType.VALUE_TUPLE); tve.setHasAggregate(false); tve.setTableName(table.getTypeName()); tve.setValueSize(col.getSize()); tve.setValueType(VoltType.get((byte) col.getType())); indexExpressions.add(tve); } } // if this is a fancy expression-based index... else { try { indexExpressions = AbstractExpression.fromJSONArrayString(jsonExpr, null); } catch (JSONException e) { e.printStackTrace(); // danger will robinson assert(false); return null; } } // if the sort covers the index, then it's a unique sort if (orderExpressions.containsAll(indexExpressions)) { orderByNode.setOrderingByUniqueColumns(); } } } return orderByNode; } /** * Add a limit, pushed-down if possible, and return the new root. * @param root top of the original plan * @return new plan's root node */ AbstractPlanNode handleLimitOperator(AbstractPlanNode root) { int limitParamIndex = m_parsedSelect.getLimitParameterIndex(); int offsetParamIndex = m_parsedSelect.getOffsetParameterIndex(); // The coordinator's top limit graph fragment for a MP plan. // If planning "order by ... limit", getNextSelectPlan() // will have already added an order by to the coordinator frag. // This is the only limit node in a SP plan LimitPlanNode topLimit = new LimitPlanNode(); topLimit.setLimit((int)m_parsedSelect.limit); topLimit.setOffset((int) m_parsedSelect.offset); topLimit.setLimitParameterIndex(limitParamIndex); topLimit.setOffsetParameterIndex(offsetParamIndex); /* * TODO: allow push down limit with distinct (select distinct C from T limit 5) * or distinct in aggregates. */ AbstractPlanNode sendNode = null; // Whether or not we can push the limit node down boolean canPushDown = ! m_parsedSelect.distinct; if (canPushDown) { sendNode = checkPushDownViability(root); if (sendNode == null) { canPushDown = false; } else { for (ParsedSelectStmt.ParsedColInfo col : m_parsedSelect.displayColumns) { AbstractExpression rootExpr = col.expression; if (rootExpr instanceof AggregateExpression) { if (((AggregateExpression)rootExpr).m_distinct) { canPushDown = false; break; } } } } } /* * Push down the limit plan node when possible even if offset is set. If * the plan is for a partitioned table, do the push down. Otherwise, * there is no need to do the push down work, the limit plan node will * be run in the partition. */ if (canPushDown) { /* * For partitioned table, the pushed-down limit plan node has a limit based * on the combined limit and offset, which may require an expression if either of these was not a hard-coded constant. * The top level limit plan node remains the same, with the original limit and offset values. */ LimitPlanNode distLimit = new LimitPlanNode(); // Offset on a pushed-down limit node makes no sense, just defaults to 0 // -- the original offset must be factored into the pushed-down limit as a pad on the limit. if (m_parsedSelect.limit != -1) { distLimit.setLimit((int) (m_parsedSelect.limit + m_parsedSelect.offset)); } if (m_parsedSelect.hasLimitOrOffsetParameters()) { AbstractExpression left = m_parsedSelect.getOffsetExpression(); assert (left != null); AbstractExpression right = m_parsedSelect.getLimitExpression(); assert (right != null); OperatorExpression expr = new OperatorExpression(ExpressionType.OPERATOR_PLUS, left, right); expr.setValueType(VoltType.INTEGER); expr.setValueSize(VoltType.INTEGER.getLengthInBytesForFixedTypes()); distLimit.setLimitExpression(expr); } // else let the parameterized forms of offset/limit default to unused/invalid. // Disconnect the distributed parts of the plan below the SEND node AbstractPlanNode distributedPlan = sendNode.getChild(0); distributedPlan.clearParents(); sendNode.clearChildren(); // If the distributed limit must be performed on ordered input, // ensure the order of the data on each partition. distributedPlan = handleOrderBy(distributedPlan); // Apply the distributed limit. distLimit.addAndLinkChild(distributedPlan); // Add the distributed work back to the plan sendNode.addAndLinkChild(distLimit); } topLimit.addAndLinkChild(root); topLimit.generateOutputSchema(m_catalogDb); return topLimit; } AbstractPlanNode handleAggregationOperators(AbstractPlanNode root) { boolean containsAggregateExpression = false; AggregatePlanNode aggNode = null; /* Check if any aggregate expressions are present */ for (ParsedSelectStmt.ParsedColInfo col : m_parsedSelect.displayColumns) { if (col.expression.hasAnySubexpressionOfClass(AggregateExpression.class)) { containsAggregateExpression = true; break; } } /* * "Select A from T group by A" is grouped but has no aggregate operator * expressions. Catch that case by checking the grouped flag */ if (containsAggregateExpression || m_parsedSelect.grouped) { AggregatePlanNode topAggNode; //TODO: add "m_parsedSelect.grouped &&" to the preconditions for HashAggregate. // Otherwise, a runtime hash is built for nothing -- just to hold a single entry. if (root.getPlanNodeType() != PlanNodeType.INDEXSCAN || ((IndexScanPlanNode) root).getSortDirection() == SortDirectionType.INVALID) { aggNode = new HashAggregatePlanNode(); topAggNode = new HashAggregatePlanNode(); } else { aggNode = new AggregatePlanNode(); topAggNode = new AggregatePlanNode(); } int outputColumnIndex = 0; int topOutputColumnIndex = 0; NodeSchema agg_schema = new NodeSchema(); NodeSchema topAggSchema = new NodeSchema(); boolean hasAggregates = false; boolean isPushDownAgg = true; // TODO: Aggregates could theoretically ONLY appear in the ORDER BY clause but not the display columns, but we don't support that yet. for (ParsedSelectStmt.ParsedColInfo col : m_parsedSelect.displayColumns) { AbstractExpression rootExpr = col.expression; AbstractExpression agg_input_expr = null; SchemaColumn schema_col = null; SchemaColumn topSchemaCol = null; ExpressionType agg_expression_type = rootExpr.getExpressionType(); if (rootExpr.hasAnySubexpressionOfClass(AggregateExpression.class)) { // If the rootExpr is not itself an AggregateExpression but simply contains one (or more) // like "MAX(counter)+1" or "MAX(col)/MIN(col)", // it gets classified as a non-push-down-able aggregate. // That beats getting it confused with a pass-through column. // TODO: support expressions of aggregates by greater differentiation of display columns between the top-level // aggregate (potentially containing aggregate functions and expressions of aggregate functions) and the pushed-down // aggregate (potentially containing aggregate functions and aggregate functions of expressions). agg_input_expr = rootExpr.getLeft(); hasAggregates = true; // count(*) hack. we're not getting AGGREGATE_COUNT_STAR // expression types from the parsing, so we have // to detect the null inner expression case and do the // switcharoo ourselves. if (rootExpr.getExpressionType() == ExpressionType.AGGREGATE_COUNT && rootExpr.getLeft() == null) { agg_expression_type = ExpressionType.AGGREGATE_COUNT_STAR; // Just need a random input column for now. // The EE won't actually evaluate this, so we // just pick something innocuous // At some point we should special-case count-star so // we don't go digging for TVEs // XXX: Danger: according to standard SQL, if first_col has nulls, COUNT(first_col) < COUNT(*) // -- consider using something non-nullable like TupleAddressExpression? SchemaColumn first_col = root.getOutputSchema().getColumns().get(0); TupleValueExpression tve = new TupleValueExpression(); tve.setValueType(first_col.getType()); tve.setValueSize(first_col.getSize()); tve.setColumnIndex(0); tve.setColumnName(first_col.getColumnName()); tve.setColumnAlias(first_col.getColumnName()); tve.setTableName(first_col.getTableName()); agg_input_expr = tve; } // A bit of a hack: ProjectionNodes after the // aggregate node need the output columns here to // contain TupleValueExpressions (effectively on a temp table). // So we construct one based on the output of the // aggregate expression, the column alias provided by HSQL, // and the offset into the output table schema for the // aggregate node that we're computing. // Oh, oh, it's magic, you know.. TupleValueExpression tve = new TupleValueExpression(); tve.setValueType(rootExpr.getValueType()); tve.setValueSize(rootExpr.getValueSize()); tve.setColumnIndex(outputColumnIndex); tve.setColumnName(""); tve.setColumnAlias(col.alias); tve.setTableName("VOLT_TEMP_TABLE"); boolean is_distinct = ((AggregateExpression)rootExpr).m_distinct; aggNode.addAggregate(agg_expression_type, is_distinct, outputColumnIndex, agg_input_expr); schema_col = new SchemaColumn("VOLT_TEMP_TABLE", "", col.alias, tve); /* * Special case count(*), count(), sum(), min() and max() to * push them down to each partition. It will do the * push-down if the select columns only contains the listed * aggregate operators and other group-by columns. If the * select columns includes any other aggregates, it will not * do the push-down. - nshi */ if (!is_distinct && (agg_expression_type == ExpressionType.AGGREGATE_COUNT_STAR || agg_expression_type == ExpressionType.AGGREGATE_COUNT || agg_expression_type == ExpressionType.AGGREGATE_SUM)) { /* * For count(*), count() and sum(), the pushed-down * aggregate node doesn't change. An extra sum() * aggregate node is added to the coordinator to sum up * the numbers from all the partitions. The input schema * and the output schema of the sum() aggregate node is * the same as the output schema of the push-down * aggregate node. * * If DISTINCT is specified, don't do push-down for * count() and sum() */ // Output column for the sum() aggregate node TupleValueExpression topOutputExpr = new TupleValueExpression(); topOutputExpr.setValueType(rootExpr.getValueType()); topOutputExpr.setValueSize(rootExpr.getValueSize()); topOutputExpr.setColumnIndex(topOutputColumnIndex); topOutputExpr.setColumnName(""); topOutputExpr.setColumnAlias(col.alias); topOutputExpr.setTableName("VOLT_TEMP_TABLE"); /* * Input column of the sum() aggregate node is the * output column of the push-down aggregate node */ topAggNode.addAggregate(ExpressionType.AGGREGATE_SUM, false, outputColumnIndex, tve); topSchemaCol = new SchemaColumn("VOLT_TEMP_TABLE", "", col.alias, topOutputExpr); } else if (agg_expression_type == ExpressionType.AGGREGATE_MIN || agg_expression_type == ExpressionType.AGGREGATE_MAX) { /* * For min() and max(), the pushed-down aggregate node * doesn't change. An extra aggregate node of the same * type is added to the coordinator. The input schema * and the output schema of the top aggregate node is * the same as the output schema of the pushed-down * aggregate node. */ topAggNode.addAggregate(agg_expression_type, is_distinct, outputColumnIndex, tve); topSchemaCol = schema_col; } else { /* * Unsupported aggregate (AVG for example) * or some expression of aggregates. */ isPushDownAgg = false; } } else { /* * These columns are the pass through columns that are not being * aggregated on. These are the ones from the SELECT list. They * MUST already exist in the child node's output. Find them and * add them to the aggregate's output. */ schema_col = new SchemaColumn(col.tableName, col.columnName, col.alias, col.expression); } if (topSchemaCol == null) { /* * If we didn't set the column schema for the top node, it * means either it's not a count(*) aggregate or it's a * pass-through column. So just copy it. */ topSchemaCol = new SchemaColumn(schema_col.getTableName(), schema_col.getColumnName(), schema_col.getColumnAlias(), schema_col.getExpression()); } agg_schema.addColumn(schema_col); topAggSchema.addColumn(topSchemaCol); outputColumnIndex++; topOutputColumnIndex++; } for (ParsedSelectStmt.ParsedColInfo col : m_parsedSelect.groupByColumns) { if (agg_schema.find(col.tableName, col.columnName, col.alias) == null) { throw new PlanningErrorException("GROUP BY column " + col.alias + " is not in the display columns." + " Please specify " + col.alias + " as a display column."); } aggNode.addGroupByExpression(col.expression); topAggNode.addGroupByExpression(col.expression); } aggNode.setOutputSchema(agg_schema); topAggNode.setOutputSchema(agg_schema); /* * Is there a necessary coordinator-aggregate node... */ if (!hasAggregates || !isPushDownAgg) { topAggNode = null; } root = pushDownAggregate(root, aggNode, topAggNode); } else { /* * Handle DISTINCT only when there is no aggregate operator * expression */ root = handleDistinct(root); } return root; } /** * Push the given aggregate if the plan is distributed, then add the * coordinator node on top of the send/receive pair. If the plan * is not distributed, or coordNode is not provided, the distNode * is added at the top of the plan. * * Note: this works in part because the push-down node is also an acceptable * top level node if the plan is not distributed. This wouldn't be true * if we started pushing down something like (sum, count) to calculate * a distributed average. * * @param root * The root node * @param distNode * The node to push down * @param coordNode * The top node to put on top of the send/receive pair after * push-down. If this is null, no push-down will be performed. * @return The new root node. */ AbstractPlanNode pushDownAggregate(AbstractPlanNode root, AggregatePlanNode distNode, AggregatePlanNode coordNode) { // remember that coordinating aggregation has a pushed-down // counterpart deeper in the plan. this allows other operators // to be pushed down past the receive as well. if (coordNode != null) { coordNode.m_isCoordinatingAggregator = true; } /* * Push this node down to partition if it's distributed. First remove * the send/receive pair, add the node, then put the send/receive pair * back on top of the node, followed by another top node at the * coordinator. */ AbstractPlanNode accessPlanTemp = root; if (coordNode != null && root instanceof ReceivePlanNode) { root = root.getChild(0).getChild(0); root.clearParents(); } else { accessPlanTemp = null; } distNode.addAndLinkChild(root); distNode.generateOutputSchema(m_catalogDb); root = distNode; // Put the send/receive pair back into place if (accessPlanTemp != null) { accessPlanTemp.getChild(0).clearChildren(); accessPlanTemp.getChild(0).addAndLinkChild(root); root = accessPlanTemp; // Add the top node coordNode.addAndLinkChild(root); coordNode.generateOutputSchema(m_catalogDb); root = coordNode; } return root; } /** * Check if we can push the limit node down. * * @param root * @return If we can push it down, the receive node is returned. Otherwise, * it returns null. */ protected AbstractPlanNode checkPushDownViability(AbstractPlanNode root) { AbstractPlanNode receiveNode = root; // Return a mid-plan send node, if one exists and can host a distributed limit node. // There is guaranteed to be at most a single receive/send pair. // Abort the search if a node that a "limit" can't be pushed past is found before its receive node. // Can only push past: // * coordinatingAggregator: a distributed aggregator a copy of which has already been pushed down. // Distributing a LIMIT to just above that aggregator is correct. (I've got some doubts that this is correct??? --paul) // * order by: if the plan requires a sort, getNextSelectPlan() will have already added an ORDER BY. // A distributed LIMIT will be added above a copy of that ORDER BY node. // * projection: these have no effect on the application of limits. // Return null if the plan is single-partition or if its "coordinator" part contains a push-blocking node type. while (!(receiveNode instanceof ReceivePlanNode)) { // Limitation: can only push past some nodes (see above comment) if (!(receiveNode instanceof AggregatePlanNode) && !(receiveNode instanceof OrderByPlanNode) && !(receiveNode instanceof ProjectionPlanNode)) { return null; } // Limitation: can only push past coordinating aggregation nodes if (receiveNode instanceof AggregatePlanNode && !((AggregatePlanNode)receiveNode).m_isCoordinatingAggregator) { return null; } if (receiveNode instanceof OrderByPlanNode) { for (ParsedSelectStmt.ParsedColInfo col : m_parsedSelect.orderByColumns()) { AbstractExpression rootExpr = col.expression; // Fix ENG-3487: can't push down limits when results are ordered by aggregate values. if (rootExpr instanceof TupleValueExpression) { if (((TupleValueExpression) rootExpr).hasAggregate()) { return null; } } } } // Traverse... if (receiveNode.getChildCount() == 0) { return null; } // nothing that allows pushing past has multiple inputs assert(receiveNode.getChildCount() == 1); receiveNode = receiveNode.getChild(0); } return receiveNode.getChild(0); } /** * Handle select distinct a from t * * @param root * @return */ AbstractPlanNode handleDistinct(AbstractPlanNode root) { if (m_parsedSelect.distinct) { // We currently can't handle DISTINCT of multiple columns. // Throw a planner error if this is attempted. //if (m_parsedSelect.displayColumns.size() > 1) // throw new PlanningErrorException("Multiple DISTINCT columns currently unsupported"); AbstractExpression distinctExpr = null; AbstractExpression nextExpr = null; for (ParsedSelectStmt.ParsedColInfo col : m_parsedSelect.displayColumns) { // Distinct can in theory handle any expression now, but it's // untested so we'll balk on anything other than a TVE here // --izzy if (col.expression instanceof TupleValueExpression) { // Add distinct node(s) to the plan if (distinctExpr == null) { distinctExpr = col.expression; nextExpr = distinctExpr; } else { nextExpr.setRight(col.expression); nextExpr = nextExpr.getRight(); } } else { throw new PlanningErrorException("DISTINCT of an expression currently unsupported"); } } // Add distinct node(s) to the plan root = addDistinctNodes(root, distinctExpr); // aggregate handlers are expected to produce the required projection. // the other aggregates do this inherently but distinct may need a // projection node. root = addProjection(root); } return root; } /** * If plan is distributed than add distinct nodes to each partition and the coordinator. * Otherwise simply add the distinct node on top of the current root * * @param root The root node * @param expr The distinct expression * @return The new root node. */ AbstractPlanNode addDistinctNodes(AbstractPlanNode root, AbstractExpression expr) { assert(root != null); AbstractPlanNode accessPlanTemp = root; if (root instanceof ReceivePlanNode) { // Temporarily strip send/receive pair accessPlanTemp = root.getChild(0).getChild(0); accessPlanTemp.clearParents(); root.getChild(0).unlinkChild(accessPlanTemp); // Add new distinct node to each partition AbstractPlanNode distinctNode = addDistinctNode(accessPlanTemp, expr); // Add send/receive pair back root.getChild(0).addAndLinkChild(distinctNode); } // Add new distinct node to the coordinator root = addDistinctNode(root, expr); return root; } /** * Build new distinct node and put it on top of the current root * * @param root The root node * @param expr The distinct expression * @return The new root node. */ AbstractPlanNode addDistinctNode(AbstractPlanNode root, AbstractExpression expr) { DistinctPlanNode distinctNode = new DistinctPlanNode(); distinctNode.setDistinctExpression(expr); distinctNode.addAndLinkChild(root); distinctNode.generateOutputSchema(m_catalogDb); return distinctNode; } /** * Get the unique set of names of all columns that are part of an index on * the given table. * * @param table * The table to build the list of index-affected columns with. * @return The set of column names affected by indexes with duplicates * removed. */ public Set<String> getIndexedColumnSetForTable(Table table) { HashSet<String> columns = new HashSet<String>(); for (Index index : table.getIndexes()) { for (ColumnRef colRef : index.getColumns()) { columns.add(colRef.getColumn().getTypeName()); } } return columns; } public String getErrorMessage() { return m_recentErrorMsg; } }
package nl.sense_os.commonsense.client.main; import nl.sense_os.commonsense.client.CommonSense; import nl.sense_os.commonsense.client.login.LoginEvents; import nl.sense_os.commonsense.client.main.components.HelpScreen; import nl.sense_os.commonsense.client.main.components.HomeScreen; import nl.sense_os.commonsense.client.main.components.NavPanel; import nl.sense_os.commonsense.client.utility.Log; import nl.sense_os.commonsense.client.visualization.VizEvents; import nl.sense_os.commonsense.shared.UserModel; import com.extjs.gxt.ui.client.Style.LayoutRegion; import com.extjs.gxt.ui.client.event.EventType; import com.extjs.gxt.ui.client.mvc.AppEvent; import com.extjs.gxt.ui.client.mvc.Controller; import com.extjs.gxt.ui.client.mvc.Dispatcher; import com.extjs.gxt.ui.client.mvc.View; import com.extjs.gxt.ui.client.util.Margins; import com.extjs.gxt.ui.client.widget.Component; import com.extjs.gxt.ui.client.widget.LayoutContainer; import com.extjs.gxt.ui.client.widget.Text; import com.extjs.gxt.ui.client.widget.Viewport; import com.extjs.gxt.ui.client.widget.layout.BorderLayout; import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData; import com.extjs.gxt.ui.client.widget.layout.CenterLayout; import com.extjs.gxt.ui.client.widget.layout.FitLayout; import com.google.gwt.user.client.ui.RootPanel; public class MainView extends View { private static final String TAG = "MainView"; private Viewport viewport; private LayoutContainer center; private NavPanel navPanel; private Component homeComponent; private Component helpComponent; public MainView(Controller controller) { super(controller); } private void createCenter() { this.center = new LayoutContainer(new FitLayout()); BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER); this.viewport.add(this.center, centerData); } private void createFooter() { LayoutContainer footer = new LayoutContainer(new CenterLayout()); Text footerText = new Text("& + CommonSense.LAST_DEPLOYED); footerText.setStyleAttribute("font-size", "9pt"); footer.add(footerText); footer.setId("footer-bar"); BorderLayoutData southData = new BorderLayoutData(LayoutRegion.SOUTH, 30); southData.setMargins(new Margins(0)); southData.setSplit(false); this.viewport.add(footer, southData); } private void createNavigation() { this.navPanel = new NavPanel(); this.navPanel.setId("navigation-bar"); BorderLayoutData northData = new BorderLayoutData(LayoutRegion.NORTH, 23); northData.setMargins(new Margins(0)); northData.setSplit(false); this.viewport.add(this.navPanel, northData); } @Override protected void handleEvent(AppEvent event) { EventType type = event.getType(); if (type.equals(MainEvents.Error)) { Log.e(TAG, "Error"); onError(event); } else if (type.equals(MainEvents.Init)) { Log.d(TAG, "Init"); // do nothing: actual initialization is done in initialize() } else if (type.equals(MainEvents.UiReady)) { Log.d(TAG, "UiReady"); onUiReady(event); } else if (type.equals(MainEvents.Navigate)) { // Log.d(TAG, "Navigate: \'" + event.<String> getData() + "\'"); onNavigate(event); } else if (type.equals(LoginEvents.LoggedIn)) { // Log.d(TAG, "LoggedIn"); onLoggedIn(event); } else if (type.equals(LoginEvents.LoggedOut)) { // Log.d(TAG, "LoggedOut"); onLoggedOut(event); } else { Log.e(TAG, "Unexpected event type: " + type); } } @Override protected void initialize() { super.initialize(); // ViewPort fills browser screen and automatically resizes content this.viewport = new Viewport(); this.viewport.setId("viewport"); this.viewport.setLayout(new BorderLayout()); this.viewport.setStyleAttribute("background", "url('img/bg/right_top_pre-light.png') no-repeat top right;"); createNavigation(); createCenter(); createFooter(); } private void onError(AppEvent event) { Log.e(TAG, "Error: " + event.<String> getData()); } private void onLoggedIn(AppEvent event) { final UserModel user = event.<UserModel> getData(); this.navPanel.setUser(user); this.navPanel.setLoggedIn(true); } private void onLoggedOut(AppEvent event) { this.navPanel.setLoggedIn(false); } private void onNavigate(AppEvent event) { String location = event.<String> getData("new"); // select the new center content Component newContent = null; if (null != location) { if (location.equals(NavPanel.SIGN_IN)) { newContent = new LayoutContainer(); Dispatcher.forwardEvent(LoginEvents.Show); } else if (location.equals(NavPanel.SIGN_OUT)) { newContent = new LayoutContainer(); Dispatcher.forwardEvent(LoginEvents.RequestLogout); } else if (location.equals(NavPanel.HOME)) { if (null == this.homeComponent) { this.homeComponent = new HomeScreen(); } newContent = this.homeComponent; } else if (location.equals(NavPanel.HELP)) { if (null == this.helpComponent) { this.helpComponent = new HelpScreen(); } newContent = this.helpComponent; } else if (location.equals(NavPanel.VISUALIZATION)) { Dispatcher.forwardEvent(VizEvents.Show, this.center); } else { LayoutContainer lc = new LayoutContainer(new CenterLayout()); lc.add(new Text("Under construction...")); newContent = lc; } } // remove old center content if (null != newContent) { newContent.setId("center-content"); this.center.removeAll(); this.center.add(newContent); this.center.layout(); } // hide login window String oldLocation = event.<String> getData("old"); if (NavPanel.SIGN_IN.equalsIgnoreCase(oldLocation) && !NavPanel.SIGN_IN.equalsIgnoreCase(location)) { Dispatcher.forwardEvent(LoginEvents.Hide); } // update navigation panel this.navPanel.setHighlight(location); } private void onUiReady(AppEvent event) { RootPanel.get().add(this.viewport); } }
package org.adligo.xml_io.generator; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.adligo.models.params.client.I_TemplateParams; import org.adligo.xml.parsers.template.Template; import org.adligo.xml.parsers.template.TemplateParserEngine; public class SourceFileWriter { private Template template; private String dir; public void writeSourceFile(String clazzName, I_TemplateParams params) throws IOException { try { String filePath = dir + File.separator + clazzName + ".java"; File file = new File(filePath); file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); String result = TemplateParserEngine.parse(template, params); fos.write(result.getBytes("ASCII")); fos.close(); } catch (UnsupportedEncodingException x) { throw new IllegalStateException("the encoding ASCII is required by the java specification"); } catch (FileNotFoundException p) { throw new IOException(p); } } public Template getTemplate() { return template; } public void setTemplate(Template template) { this.template = template; } public String getDir() { return dir; } public void setDir(String dir) { this.dir = dir; } }
package org.apache.xerces.impl.xs; import org.apache.xerces.impl.RevalidationHandler; import org.apache.xerces.impl.dv.XSSimpleType; import org.apache.xerces.impl.dv.ValidatedInfo; import org.apache.xerces.impl.dv.DatatypeException; import org.apache.xerces.impl.dv.InvalidDatatypeValueException; import org.apache.xerces.impl.xs.identity.*; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.validation.ValidationManager; import org.apache.xerces.util.XMLGrammarPoolImpl; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.xs.traversers.XSAttributeChecker; import org.apache.xerces.impl.xs.models.CMBuilder; import org.apache.xerces.impl.xs.models.XSCMValidator; import org.apache.xerces.impl.xs.psvi.XSConstants; import org.apache.xerces.impl.xs.psvi.XSObjectList; import org.apache.xerces.impl.msg.XMLMessageFormatter; import org.apache.xerces.impl.validation.ValidationState; import org.apache.xerces.impl.XMLEntityManager; import org.apache.xerces.util.AugmentationsImpl; import org.apache.xerces.util.NamespaceSupport; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLSymbols; import org.apache.xerces.util.XMLChar; import org.apache.xerces.util.IntStack; import org.apache.xerces.util.XMLResourceIdentifierImpl; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLString; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.XMLDocumentHandler; import org.apache.xerces.xni.parser.XMLDocumentFilter; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XMLResourceIdentifier; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.parser.XMLComponent; import org.apache.xerces.xni.parser.XMLComponentManager; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLDocumentSource; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.apache.xerces.xni.grammars.Grammar; import org.apache.xerces.xni.grammars.XMLGrammarDescription; import org.apache.xerces.xni.psvi.ElementPSVI; import org.apache.xerces.xni.psvi.AttributePSVI; import org.xml.sax.InputSource ; import java.util.Enumeration; import java.util.Hashtable; import java.util.Stack; import java.util.Vector; import java.io.IOException; public class XMLSchemaValidator implements XMLComponent, XMLDocumentFilter, FieldActivator, RevalidationHandler { // Constants private static final boolean DEBUG = false; // feature identifiers /** Feature identifier: validation. */ protected static final String VALIDATION = Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE; /** Feature identifier: validation. */ protected static final String SCHEMA_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE; /** Feature identifier: schema full checking*/ protected static final String SCHEMA_FULL_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING; /** Feature identifier: dynamic validation. */ protected static final String DYNAMIC_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.DYNAMIC_VALIDATION_FEATURE; /** Feature identifier: expose schema normalized value */ protected static final String NORMALIZE_DATA = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_NORMALIZED_VALUE; /** Feature identifier: send element default value via characters() */ protected static final String SCHEMA_ELEMENT_DEFAULT = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_ELEMENT_DEFAULT; /** Feature identifier: whether to recognize java encoding names */ protected static final String ALLOW_JAVA_ENCODING = Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE; // property identifiers /** Property identifier: symbol table. */ public static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; /** Property identifier: error reporter. */ public static final String ERROR_REPORTER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; /** Property identifier: entity resolver. */ public static final String ENTITY_RESOLVER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; /** Property identifier: grammar pool. */ public static final String XMLGRAMMAR_POOL = Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY; protected static final String VALIDATION_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY; protected static final String ENTITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY; /** Property identifier: schema location. */ protected static final String SCHEMA_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_LOCATION; /** Property identifier: no namespace schema location. */ protected static final String SCHEMA_NONS_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_NONS_LOCATION; /** Property identifier: JAXP schema source. */ protected static final String JAXP_SCHEMA_SOURCE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE; // recognized features and properties /** Recognized features. */ private static final String[] RECOGNIZED_FEATURES = { VALIDATION, SCHEMA_VALIDATION, DYNAMIC_VALIDATION, SCHEMA_FULL_CHECKING, }; /** Recognized properties. */ private static final String[] RECOGNIZED_PROPERTIES = { SYMBOL_TABLE, ERROR_REPORTER, ENTITY_RESOLVER, VALIDATION_MANAGER, SCHEMA_LOCATION, SCHEMA_NONS_LOCATION, JAXP_SCHEMA_SOURCE }; // this is the number of valuestores of each kind // we expect an element to have. It's almost // never > 1; so leave it at that. protected static final int ID_CONSTRAINT_NUM = 1; // Data /** PSV infoset information for element */ protected final ElementPSVImpl fElemPSVI = new ElementPSVImpl(); /** current PSVI element info */ protected ElementPSVImpl fCurrentPSVI = null; // since it is the responsibility of each component to an // Augmentations parameter if one is null, to save ourselves from // having to create this object continually, it is created here. // If it is not present in calls that we're passing on, we *must* // clear this before we introduce it into the pipeline. protected final AugmentationsImpl fAugmentations = new AugmentationsImpl(); // this is included for the convenience of handleEndElement protected XMLString fDefaultValue; /** Validation. */ protected boolean fValidation = false; protected boolean fDynamicValidation = false; protected boolean fDoValidation = false; protected boolean fFullChecking = false; protected boolean fNormalizeData = true; protected boolean fSchemaElementDefault = true; protected boolean fEntityRef = false; protected boolean fInCDATA = false; // properties /** Symbol table. */ protected SymbolTable fSymbolTable; /** * A wrapper of the standard error reporter. We'll store all schema errors * in this wrapper object, so that we can get all errors (error codes) of * a specific element. This is useful for PSVI. */ class XSIErrorReporter { // the error reporter property XMLErrorReporter fErrorReporter; // store error codes; starting position of the errors for each element; // number of element (depth); and whether to record error Vector fErrors = new Vector(INITIAL_STACK_SIZE, INC_STACK_SIZE); int[] fContext = new int[INITIAL_STACK_SIZE]; int fContextCount; // set the external error reporter, clear errors public void reset(XMLErrorReporter errorReporter) { fErrorReporter = errorReporter; fErrors.removeAllElements(); fContextCount = 0; } // should be called on startElement: store the starting position // for the current element public void pushContext() { // resize array if necessary if (fContextCount == fContext.length) { int newSize = fContextCount + INC_STACK_SIZE; int[] newArray = new int[newSize]; System.arraycopy(fContext, 0, newArray, 0, fContextCount); fContext = newArray; } fContext[fContextCount++] = fErrors.size(); } // should be called on endElement: get all errors of the current element public String[] popContext() { // get starting position of the current element int contextPos = fContext[--fContextCount]; // number of errors of the current element int size = fErrors.size() - contextPos; // if no errors, return null if (size == 0) return null; // copy errors from the list to an string array String[] errors = new String[size]; for (int i = 0; i < size; i++) { errors[i] = (String)fErrors.elementAt(contextPos + i); } // remove errors of the current element fErrors.setSize(contextPos); return errors; } public void reportError(String domain, String key, Object[] arguments, short severity) throws XNIException { fErrorReporter.reportError(domain, key, arguments, severity); fErrors.addElement(key); } // reportError(String,String,Object[],short) public void reportError(XMLLocator location, String domain, String key, Object[] arguments, short severity) throws XNIException { fErrorReporter.reportError(location, domain, key, arguments, severity); fErrors.addElement(key); } // reportError(XMLLocator,String,String,Object[],short) } /** Error reporter. */ protected final XSIErrorReporter fXSIErrorReporter = new XSIErrorReporter(); /** Entity resolver */ protected XMLEntityResolver fEntityResolver; // updated during reset protected ValidationManager fValidationManager = null; protected ValidationState fValidationState = new ValidationState(); protected XMLGrammarPool fGrammarPool; // schema location property values protected String fExternalSchemas = null; protected String fExternalNoNamespaceSchema = null; //JAXP Schema Source property protected Object fJaxpSchemaSource = null ; //ResourceIdentifier for use in calling EntityResolver final XMLResourceIdentifierImpl fResourceIdentifier = new XMLResourceIdentifierImpl(); /** Schema Grammar Description passed, to give a chance to application to supply the Grammar */ protected final XSDDescription fXSDDescription = new XSDDescription() ; protected final Hashtable fLocationPairs = new Hashtable() ; protected final XMLSchemaLoader.LocationArray fNoNamespaceLocationArray = new XMLSchemaLoader.LocationArray(); /** Base URI for the DOM revalidation*/ protected String fBaseURI = null; // handlers /** Document handler. */ protected XMLDocumentHandler fDocumentHandler; protected XMLDocumentSource fDocumentSource; // XMLComponent methods /** * Returns a list of feature identifiers that are recognized by * this component. This method may return null if no features * are recognized by this component. */ public String[] getRecognizedFeatures() { return (String[])(RECOGNIZED_FEATURES.clone()); } // getRecognizedFeatures():String[] /** * Sets the state of a feature. This method is called by the component * manager any time after reset when a feature changes state. * <p> * <strong>Note:</strong> Components should silently ignore features * that do not affect the operation of the component. * * @param featureId The feature identifier. * @param state The state of the feature. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setFeature(String featureId, boolean state) throws XMLConfigurationException { } // setFeature(String,boolean) /** * Returns a list of property identifiers that are recognized by * this component. This method may return null if no properties * are recognized by this component. */ public String[] getRecognizedProperties() { return (String[])(RECOGNIZED_PROPERTIES.clone()); } // getRecognizedProperties():String[] /** * Sets the value of a property. This method is called by the component * manager any time after reset when a property changes value. * <p> * <strong>Note:</strong> Components should silently ignore properties * that do not affect the operation of the component. * * @param propertyId The property identifier. * @param value The value of the property. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setProperty(String propertyId, Object value) throws XMLConfigurationException { } // setProperty(String,Object) // XMLDocumentSource methods /** Sets the document handler to receive information about the document. */ public void setDocumentHandler(XMLDocumentHandler documentHandler) { fDocumentHandler = documentHandler; } // setDocumentHandler(XMLDocumentHandler) /** Returns the document handler */ public XMLDocumentHandler getDocumentHandler() { return fDocumentHandler; } // setDocumentHandler(XMLDocumentHandler) // XMLDocumentHandler methods /** Sets the document source */ public void setDocumentSource(XMLDocumentSource source){ fDocumentSource = source; } // setDocumentSource /** Returns the document source */ public XMLDocumentSource getDocumentSource (){ return fDocumentSource; } // getDocumentSource /** * The start of the document. * * @param locator The system identifier of the entity if the entity * is external, null otherwise. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startDocument(XMLLocator locator, String encoding, Augmentations augs) throws XNIException { handleStartDocument(locator, encoding); // call handlers if (fDocumentHandler != null) { fDocumentHandler.startDocument(locator, encoding, augs); } } // startDocument(XMLLocator,String) /** * Notifies of the presence of an XMLDecl line in the document. If * present, this method will be called immediately following the * startDocument call. * * @param version The XML version. * @param encoding The IANA encoding name of the document, or null if * not specified. * @param standalone The standalone value, or null if not specified. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void xmlDecl(String version, String encoding, String standalone, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.xmlDecl(version, encoding, standalone, augs); } } // xmlDecl(String,String,String) /** * Notifies of the presence of the DOCTYPE line in the document. * * @param rootElement The name of the root element. * @param publicId The public identifier if an external DTD or null * if the external DTD is specified using SYSTEM. * @param systemId The system identifier if an external DTD, null * otherwise. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void doctypeDecl(String rootElement, String publicId, String systemId, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.doctypeDecl(rootElement, publicId, systemId, augs); } } // doctypeDecl(String,String,String) /** * The start of a namespace prefix mapping. This method will only be * called when namespace processing is enabled. * * @param prefix The namespace prefix. * @param uri The URI bound to the prefix. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startPrefixMapping(String prefix, String uri, Augmentations augs) throws XNIException { if (DEBUG) { System.out.println("startPrefixMapping("+prefix+","+uri+")"); } handleStartPrefix(prefix, uri); // call handlers if (fDocumentHandler != null) { fDocumentHandler.startPrefixMapping(prefix, uri, augs); } } // startPrefixMapping(String,String) /** * The start of an element. * * @param element The name of the element. * @param attributes The element attributes. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { Augmentations modifiedAugs = handleStartElement(element, attributes, augs); // call handlers if (fDocumentHandler != null) { fDocumentHandler.startElement(element, attributes, modifiedAugs ); } } // startElement(QName,XMLAttributes, Augmentations) /** * An empty element. * * @param element The name of the element. * @param attributes The element attributes. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { Augmentations modifiedAugs = handleStartElement(element, attributes, augs); // in the case where there is a {value constraint}, and the element // doesn't have any text content, change emptyElement call to // start + characters + end modifiedAugs = handleEndElement(element, modifiedAugs); // call handlers if (fDocumentHandler != null) { if (!fSchemaElementDefault || fDefaultValue == null) { fDocumentHandler.emptyElement(element, attributes, modifiedAugs); } else { fDocumentHandler.startElement(element, attributes, modifiedAugs); fDocumentHandler.characters(fDefaultValue, modifiedAugs); fDocumentHandler.endElement(element, modifiedAugs); } } } // emptyElement(QName,XMLAttributes, Augmentations) /** * Character content. * * @param text The content. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void characters(XMLString text, Augmentations augs) throws XNIException { boolean emptyAug = false; if (fNormalizeData) { if (augs == null) { emptyAug = true; augs = fAugmentations; augs.clear(); } // get PSVI object fCurrentPSVI = (ElementPSVImpl)augs.getItem(Constants.ELEMENT_PSVI); if (fCurrentPSVI == null) { fCurrentPSVI = fElemPSVI; augs.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); } else { fCurrentPSVI.reset(); } } else { fCurrentPSVI = fElemPSVI; } handleCharacters(text); // call handlers if (fDocumentHandler != null) { if (fNormalizeData && fUnionType) { // for union types we can't normalize data // thus we only need to send augs information if any; // the normalized data for union will be send // after normalization is performed (at the endElement()) if (!emptyAug) { fDocumentHandler.characters(fEmptyXMLStr, augs); } } else { fDocumentHandler.characters(text, augs); } } } // characters(XMLString) /** * Ignorable whitespace. For this method to be called, the document * source must have some way of determining that the text containing * only whitespace characters should be considered ignorable. For * example, the validator can determine if a length of whitespace * characters in the document are ignorable based on the element * content model. * * @param text The ignorable whitespace. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException { handleIgnorableWhitespace(text); // call handlers if (fDocumentHandler != null) { fDocumentHandler.ignorableWhitespace(text, augs); } } // ignorableWhitespace(XMLString) /** * The end of an element. * * @param element The name of the element. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endElement(QName element, Augmentations augs) throws XNIException { // in the case where there is a {value constraint}, and the element // doesn't have any text content, add a characters call. Augmentations modifiedAugs = handleEndElement(element, augs); // call handlers if (fDocumentHandler != null) { if (fSchemaElementDefault || fDefaultValue == null) { fDocumentHandler.endElement(element, modifiedAugs); } else { fDocumentHandler.characters(fDefaultValue, modifiedAugs); fDocumentHandler.endElement(element, modifiedAugs); } } } // endElement(QName, Augmentations) /** * The end of a namespace prefix mapping. This method will only be * called when namespace processing is enabled. * * @param prefix The namespace prefix. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endPrefixMapping(String prefix, Augmentations augs) throws XNIException { if (DEBUG) { System.out.println("endPrefixMapping("+prefix+")"); } // call handlers if (fDocumentHandler != null) { fDocumentHandler.endPrefixMapping(prefix, augs); } } // endPrefixMapping(String) /** * The start of a CDATA section. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startCDATA(Augmentations augs) throws XNIException { // REVISIT: what should we do here if schema normalization is on?? fInCDATA = true; // call handlers if (fDocumentHandler != null) { fDocumentHandler.startCDATA(augs); } } // startCDATA() /** * The end of a CDATA section. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endCDATA(Augmentations augs) throws XNIException { // call handlers fInCDATA = false; if (fDocumentHandler != null) { fDocumentHandler.endCDATA(augs); } } // endCDATA() /** * The end of the document. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endDocument(Augmentations augs) throws XNIException { handleEndDocument(); // call handlers if (fDocumentHandler != null) { fDocumentHandler.endDocument(augs); } } // endDocument(Augmentations) // DOMRevalidationHandler methods public void setBaseURI (String base){ fBaseURI = base; } public boolean characterData(String data, Augmentations augs){ // REVISIT: this methods basically duplicates implementation of // handleCharacters(). We should be able to reuse some code boolean allWhiteSpace = true; String normalizedStr = null; if (augs == null) { augs = fAugmentations; augs.clear(); } // get PSVI object fCurrentPSVI = (ElementPSVImpl)augs.getItem(Constants.ELEMENT_PSVI); if (fCurrentPSVI == null) { fCurrentPSVI = fElemPSVI; augs.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); } else { fCurrentPSVI.reset(); } if (fNormalizeData) { // if whitespace == -1 skip normalization, because it is a complexType if (fWhiteSpace != -1 && fWhiteSpace != XSSimpleType.WS_PRESERVE) { // normalize data int spaces = normalizeWhitespace(data, fWhiteSpace == XSSimpleType.WS_COLLAPSE); normalizedStr = fNormalizedStr.toString(); fCurrentPSVI.fNormalizedValue = normalizedStr; } } boolean mixed = false; if (fCurrentType != null && fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { mixed = true; } } if (DEBUG) { System.out.println("==>characters("+data+")," +fCurrentType.getName()+","+mixed); } if (mixed || fWhiteSpace !=-1 || fUnionType) { // don't check characters: since it is either // a) mixed content model - we don't care if there were some characters // b) simpleType/simpleContent - in which case it is data in ELEMENT content } else { // data outside of element content for (int i=0; i< data.length(); i++) { if (!XMLChar.isSpace(data.charAt(i))) { allWhiteSpace = false; break; } } } // we saw first chunk of characters fFirstChunk = false; // save normalized value for validation purposes if (fNil) { // if element was nil and there is some character data // we should expose it to the user // otherwise error does not make much sense fCurrentPSVI.fNormalizedValue = null; fBuffer.append(data); } if (normalizedStr != null) { fBuffer.append(normalizedStr); } else { fBuffer.append(data); } if (!allWhiteSpace) { fSawCharacters = true; } return allWhiteSpace; } public void elementDefault(String data){ // no-op } // XMLDocumentHandler and XMLDTDHandler methods /** * This method notifies the start of a general entity. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the general entity. * @param identifier The resource identifier. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * @param augs Additional information that may include infoset augmentations * * @exception XNIException Thrown by handler to signal an error. */ public void startGeneralEntity(String name, XMLResourceIdentifier identifier, String encoding, Augmentations augs) throws XNIException { // REVISIT: what should happen if normalize_data_ is on?? fEntityRef = true; // call handlers if (fDocumentHandler != null) { fDocumentHandler.startGeneralEntity(name, identifier, encoding, augs); } } // startEntity(String,String,String,String,String) /** * Notifies of the presence of a TextDecl line in an entity. If present, * this method will be called immediately following the startEntity call. * <p> * <strong>Note:</strong> This method will never be called for the * document entity; it is only called for external general entities * referenced in document content. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param version The XML version, or null if not specified. * @param encoding The IANA encoding name of the entity. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void textDecl(String version, String encoding, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.textDecl(version, encoding, augs); } } // textDecl(String,String) /** * A comment. * * @param text The text in the comment. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by application to signal an error. */ public void comment(XMLString text, Augmentations augs) throws XNIException { // record the fact that there is a comment child. fSawChildren = true; // call handlers if (fDocumentHandler != null) { fDocumentHandler.comment(text, augs); } } // comment(XMLString) /** * A processing instruction. Processing instructions consist of a * target name and, optionally, text data. The data is only meaningful * to the application. * <p> * Typically, a processing instruction's data will contain a series * of pseudo-attributes. These pseudo-attributes follow the form of * element attributes but are <strong>not</strong> parsed or presented * to the application as anything other than text. The application is * responsible for parsing the data. * * @param target The target. * @param data The data or null if none specified. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void processingInstruction(String target, XMLString data, Augmentations augs) throws XNIException { // record the fact that there is a PI child. fSawChildren = true; // call handlers if (fDocumentHandler != null) { fDocumentHandler.processingInstruction(target, data, augs); } } // processingInstruction(String,XMLString) /** * This method notifies the end of a general entity. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the entity. * @param augs Additional information that may include infoset augmentations * * @exception XNIException * Thrown by handler to signal an error. */ public void endGeneralEntity(String name, Augmentations augs) throws XNIException { // call handlers fEntityRef = false; if (fDocumentHandler != null) { fDocumentHandler.endGeneralEntity(name, augs); } } // endEntity(String) // constants static final int INITIAL_STACK_SIZE = 8; static final int INC_STACK_SIZE = 8; // Data // Schema Normalization private static final boolean DEBUG_NORMALIZATION = false; // temporary empty string buffer. private final XMLString fEmptyXMLStr = new XMLString(null, 0, -1); // temporary character buffer, and empty string buffer. private static final int BUFFER_SIZE = 20; private char[] fCharBuffer = new char[BUFFER_SIZE]; private final StringBuffer fNormalizedStr = new StringBuffer(); private final XMLString fXMLString = new XMLString(fCharBuffer, 0, -1); private boolean fFirstChunk = true; // got first chunk in characters() (SAX) private boolean fTrailing = false; // Previous chunk had a trailing space private short fWhiteSpace = -1; //whiteSpace: preserve/replace/collapse private boolean fUnionType = false; /** Schema grammar resolver. */ final XSGrammarBucket fGrammarBucket; final SubstitutionGroupHandler fSubGroupHandler; // Schema grammar loader final XMLSchemaLoader fSchemaLoader; /** Namespace support. */ final NamespaceSupport fNamespaceSupport = new NamespaceSupport(); /** this flag is used to indicate whether the next prefix binding * should start a new context (.pushContext) */ boolean fPushForNextBinding; /** the DV usd to convert xsi:type to a QName */ // REVISIT: in new simple type design, make things in DVs static, // so that we can QNameDV.getCompiledForm() final XSSimpleType fQNameDV = (XSSimpleType)SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_QNAME); /** used to build content models */ // REVISIT: create decl pool, and pass it to each traversers final CMBuilder fCMBuilder = new CMBuilder(); // state /** String representation of the validation root. */ // REVISIT: what do we store here? QName, XPATH, some ID? use rawname now. String fValidationRoot; /** Skip validation. */ int fSkipValidationDepth; /** Partial validation depth */ int fPartialValidationDepth; /** Element depth. */ int fElementDepth; /** Child count. */ int fChildCount; /** Element decl stack. */ int[] fChildCountStack = new int[INITIAL_STACK_SIZE]; /** Current element declaration. */ XSElementDecl fCurrentElemDecl; /** Element decl stack. */ XSElementDecl[] fElemDeclStack = new XSElementDecl[INITIAL_STACK_SIZE]; /** nil value of the current element */ boolean fNil; /** nil value stack */ boolean[] fNilStack = new boolean[INITIAL_STACK_SIZE]; /** notation value of the current element */ XSNotationDecl fNotation; /** notation stack */ XSNotationDecl[] fNotationStack = new XSNotationDecl[INITIAL_STACK_SIZE]; /** Current type. */ XSTypeDecl fCurrentType; /** type stack. */ XSTypeDecl[] fTypeStack = new XSTypeDecl[INITIAL_STACK_SIZE]; /** Current content model. */ XSCMValidator fCurrentCM; /** Content model stack. */ XSCMValidator[] fCMStack = new XSCMValidator[INITIAL_STACK_SIZE]; /** the current state of the current content model */ int[] fCurrCMState; /** stack to hold content model states */ int[][] fCMStateStack = new int[INITIAL_STACK_SIZE][]; /** Temporary string buffers. */ final StringBuffer fBuffer = new StringBuffer(); /** Did we see non-whitespace character data? */ boolean fSawCharacters = false; /** Stack to record if we saw character data outside of element content*/ boolean[] fStringContent = new boolean[INITIAL_STACK_SIZE]; /** Did we see children that are neither characters nor elements? */ boolean fSawChildren = false; /** Stack to record if we other children that character or elements */ boolean[] fSawChildrenStack = new boolean[INITIAL_STACK_SIZE]; /** temprory qname */ final QName fTempQName = new QName(); /** temprory validated info */ ValidatedInfo fValidatedInfo = new ValidatedInfo(); // used to validate default/fixed values against xsi:type // only need to check facets, so we set extraChecking to false (in reset) private ValidationState fState4XsiType = new ValidationState(); // used to apply default/fixed values // only need to check id/idref/entity, so we set checkFacets to false private ValidationState fState4ApplyDefault = new ValidationState(); // identity constraint information /** * Stack of active XPath matchers for identity constraints. All * active XPath matchers are notified of startElement * and endElement callbacks in order to perform their matches. * <p> * For each element with identity constraints, the selector of * each identity constraint is activated. When the selector matches * its XPath, then all the fields of the identity constraint are * activated. * <p> * <strong>Note:</strong> Once the activation scope is left, the * XPath matchers are automatically removed from the stack of * active matchers and no longer receive callbacks. */ protected XPathMatcherStack fMatcherStack = new XPathMatcherStack(); /** Cache of value stores for identity constraint fields. */ protected ValueStoreCache fValueStoreCache = new ValueStoreCache(); // Constructors /** Default constructor. */ public XMLSchemaValidator() { fGrammarBucket = new XSGrammarBucket(); fSubGroupHandler = new SubstitutionGroupHandler(fGrammarBucket); // initialize the schema loader fSchemaLoader = new XMLSchemaLoader(fXSIErrorReporter.fErrorReporter, fGrammarBucket, fSubGroupHandler, fCMBuilder); fValidationState.setNamespaceSupport(fNamespaceSupport); fState4XsiType.setExtraChecking(false); fState4XsiType.setNamespaceSupport(fNamespaceSupport); fState4ApplyDefault.setFacetChecking(false); fState4ApplyDefault.setNamespaceSupport(fNamespaceSupport); } // <init>() /* * Resets the component. The component can query the component manager * about any features and properties that affect the operation of the * component. * * @param componentManager The component manager. * * @throws SAXException Thrown by component on finitialization error. * For example, if a feature or property is * required for the operation of the component, the * component manager may throw a * SAXNotRecognizedException or a * SAXNotSupportedException. */ public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { // get error reporter fXSIErrorReporter.reset((XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER)); fSchemaLoader.setProperty(ERROR_REPORTER, fXSIErrorReporter.fErrorReporter); // get symbol table. if it's a new one, add symbols to it. SymbolTable symbolTable = (SymbolTable)componentManager.getProperty(SYMBOL_TABLE); if (symbolTable != fSymbolTable) { fSchemaLoader.setProperty(SYMBOL_TABLE, symbolTable); fSymbolTable = symbolTable; } try { fValidation = componentManager.getFeature(VALIDATION); } catch (XMLConfigurationException e) { fValidation = false; } // Xerces features try { fValidation = fValidation && componentManager.getFeature(SCHEMA_VALIDATION); } catch (XMLConfigurationException e) { fValidation = false; } try { fFullChecking = componentManager.getFeature(SCHEMA_FULL_CHECKING); } catch (XMLConfigurationException e) { fFullChecking = false; } // the validator will do full checking anyway; the loader should // not (and in fact cannot) concern itself with this. fSchemaLoader.setFeature(SCHEMA_FULL_CHECKING, false); try { fDynamicValidation = componentManager.getFeature(DYNAMIC_VALIDATION); } catch (XMLConfigurationException e) { fDynamicValidation = false; } try { fNormalizeData = componentManager.getFeature(NORMALIZE_DATA); } catch (XMLConfigurationException e) { fNormalizeData = false; } try { fSchemaElementDefault = componentManager.getFeature(SCHEMA_ELEMENT_DEFAULT); } catch (XMLConfigurationException e) { fSchemaElementDefault = false; } fEntityResolver = (XMLEntityResolver)componentManager.getProperty(ENTITY_MANAGER); fSchemaLoader.setEntityResolver(fEntityResolver); // initialize namespace support fNamespaceSupport.reset(); fPushForNextBinding = true; fValidationManager = (ValidationManager)componentManager.getProperty(VALIDATION_MANAGER); fValidationManager.addValidationState(fValidationState); fValidationState.setSymbolTable(fSymbolTable); // get schema location properties try { fExternalSchemas = (String)componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNamespaceSchema = (String)componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNamespaceSchema = null; } fSchemaLoader.setProperty(SCHEMA_LOCATION, fExternalSchemas); fSchemaLoader.setProperty(SCHEMA_NONS_LOCATION, fExternalNoNamespaceSchema); try { fJaxpSchemaSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE); } catch (XMLConfigurationException e){ fJaxpSchemaSource = null; } fSchemaLoader.setProperty(JAXP_SCHEMA_SOURCE, fJaxpSchemaSource); fResourceIdentifier.clear(); // clear grammars, and put the one for schema namespace there try { fGrammarPool = (XMLGrammarPool)componentManager.getProperty(XMLGRAMMAR_POOL); } catch (XMLConfigurationException e){ fGrammarPool = null; } fSchemaLoader.setProperty(XMLGRAMMAR_POOL, fGrammarPool); // Copy the allow-java-encoding feature to the grammar loader. // REVISIT: what other fetures/properties do we want to copy? try { boolean jencoding = componentManager.getFeature(ALLOW_JAVA_ENCODING); fSchemaLoader.setFeature(ALLOW_JAVA_ENCODING, jencoding); } catch (XMLConfigurationException e){ } // clear grammars, and put the one for schema namespace there // logic for resetting grammar-related components moved // to schema loader fSchemaLoader.reset(); //reset XSDDescription fXSDDescription.reset() ; fLocationPairs.clear(); fNoNamespaceLocationArray.resize(0 , 2) ; // initialize state fCurrentElemDecl = null; fNil = false; fNotation = null; fCurrentPSVI = null; fCurrentType = null; fCurrentCM = null; fCurrCMState = null; fBuffer.setLength(0); fSawCharacters=false; fSawChildren=false; fValidationRoot = null; fSkipValidationDepth = -1; fPartialValidationDepth = -1; fElementDepth = -1; fChildCount = 0; // datatype normalization fFirstChunk = true; fTrailing = false; fNormalizedStr.setLength(0); fWhiteSpace = -1; fUnionType = false; fWhiteSpace = -1; fAugmentations.clear(); fEntityRef = false; fInCDATA = false; fMatcherStack.clear(); fBaseURI = null; fState4XsiType.setSymbolTable(symbolTable); fState4ApplyDefault.setSymbolTable(symbolTable); } // reset(XMLComponentManager) // FieldActivator methods /** * Start the value scope for the specified identity constraint. This * method is called when the selector matches in order to initialize * the value store. * * @param identityConstraint The identity constraint. */ public void startValueScopeFor(IdentityConstraint identityConstraint, int initialDepth) throws XNIException { ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint, initialDepth); valueStore.startValueScope(); } // startValueScopeFor(IdentityConstraint identityConstraint) /** * Request to activate the specified field. This method returns the * matcher for the field. * * @param field The field to activate. */ public XPathMatcher activateField(Field field, int initialDepth) { ValueStore valueStore = fValueStoreCache.getValueStoreFor(field.getIdentityConstraint(), initialDepth); field.setMayMatch(true); XPathMatcher matcher = field.createMatcher(valueStore); fMatcherStack.addMatcher(matcher); matcher.startDocumentFragment(fSymbolTable); return matcher; } // activateField(Field):XPathMatcher /** * Ends the value scope for the specified identity constraint. * * @param identityConstraint The identity constraint. */ public void endValueScopeFor(IdentityConstraint identityConstraint, int initialDepth) throws XNIException { ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint, initialDepth); valueStore.endValueScope(); } // endValueScopeFor(IdentityConstraint) // a utility method for Idnetity constraints private void activateSelectorFor(IdentityConstraint ic) throws XNIException { Selector selector = ic.getSelector(); FieldActivator activator = this; if (selector == null) return; XPathMatcher matcher = selector.createMatcher(activator, fElementDepth); fMatcherStack.addMatcher(matcher); matcher.startDocumentFragment(fSymbolTable); } // Protected methods /** ensure element stack capacity */ void ensureStackCapacity() { if (fElementDepth == fElemDeclStack.length) { int newSize = fElementDepth + INC_STACK_SIZE; int[] newArrayI = new int[newSize]; System.arraycopy(fChildCountStack, 0, newArrayI, 0, fElementDepth); fChildCountStack = newArrayI; XSElementDecl[] newArrayE = new XSElementDecl[newSize]; System.arraycopy(fElemDeclStack, 0, newArrayE, 0, fElementDepth); fElemDeclStack = newArrayE; boolean[] newArrayB = new boolean[newSize]; System.arraycopy(fNilStack, 0, newArrayB, 0, fElementDepth); fNilStack = newArrayB; XSNotationDecl[] newArrayN = new XSNotationDecl[newSize]; System.arraycopy(fNotationStack, 0, newArrayN, 0, fElementDepth); fNotationStack = newArrayN; XSTypeDecl[] newArrayT = new XSTypeDecl[newSize]; System.arraycopy(fTypeStack, 0, newArrayT, 0, fElementDepth); fTypeStack = newArrayT; XSCMValidator[] newArrayC = new XSCMValidator[newSize]; System.arraycopy(fCMStack, 0, newArrayC, 0, fElementDepth); fCMStack = newArrayC; boolean[] newArrayD = new boolean[newSize]; System.arraycopy(fStringContent, 0, newArrayD, 0, fElementDepth); fStringContent = newArrayD; newArrayD = new boolean[newSize]; System.arraycopy(fSawChildrenStack, 0, newArrayD, 0, fElementDepth); fSawChildrenStack = newArrayD; int[][] newArrayIA = new int[newSize][]; System.arraycopy(fCMStateStack, 0, newArrayIA, 0, fElementDepth); fCMStateStack = newArrayIA; } } // ensureStackCapacity // handle start document void handleStartDocument(XMLLocator locator, String encoding) { if (fValidation) fValueStoreCache.startDocument(); } // handleStartDocument(XMLLocator,String) void handleEndDocument() { if (fValidation) fValueStoreCache.endDocument(); } // handleEndDocument() // handle character contents void handleCharacters(XMLString text) { fCurrentPSVI.fNormalizedValue = null; if (fSkipValidationDepth >= 0) return; String normalizedStr = null; boolean allWhiteSpace = true; // find out if type is union, what is whitespace, // determine if there is a need to do normalization // Note: data in EntityRef and CDATA is normalized as well if (fNormalizeData) { // if whitespace == -1 skip normalization, because it is a complexType if (fWhiteSpace != -1 && !fUnionType && fWhiteSpace != XSSimpleType.WS_PRESERVE) { // normalize data int spaces = normalizeWhitespace(text, fWhiteSpace == XSSimpleType.WS_COLLAPSE); int length = fNormalizedStr.length(); if (length > 0) { if (!fFirstChunk && (fWhiteSpace==XSSimpleType.WS_COLLAPSE) ) { if (fTrailing) { // previous chunk ended on whitespace // insert whitespace fNormalizedStr.insert(0, ' '); } else if (spaces == 1 || spaces == 3) { // previous chunk ended on character, // this chunk starts with whitespace fNormalizedStr.insert(0, ' '); } } } normalizedStr = fNormalizedStr.toString(); fCurrentPSVI.fNormalizedValue = normalizedStr; fTrailing = (spaces > 1)?true:false; } } boolean mixed = false; if (fCurrentType != null && fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { mixed = true; } } if (DEBUG) { System.out.println("==>characters("+text.toString()+")," +fCurrentType.getName()+","+mixed); } if (mixed || fWhiteSpace !=-1 || fUnionType) { // don't check characters: since it is either // a) mixed content model - we don't care if there were some characters // b) simpleType/simpleContent - in which case it is data in ELEMENT content } else { // data outside of element content for (int i=text.offset; i< text.offset+text.length; i++) { if (!XMLChar.isSpace(text.ch[i])) { allWhiteSpace = false; break; } } } // we saw first chunk of characters fFirstChunk = false; // save normalized value for validation purposes if (fNil) { // if element was nil and there is some character data // we should expose it to the user // otherwise error does not make much sense fCurrentPSVI.fNormalizedValue = null; fBuffer.append(text.ch, text.offset, text.length); } if (normalizedStr != null) { fBuffer.append(normalizedStr); } else { fBuffer.append(text.ch, text.offset, text.length); } if (!allWhiteSpace) { fSawCharacters = true; } } // handleCharacters(XMLString) /** * Normalize whitespace in an XMLString according to the rules defined * in XML Schema specifications. * @param value The string to normalize. * @param collapse replace or collapse * @returns 0 if no triming is done or if there is neither leading nor * trailing whitespace, * 1 if there is only leading whitespace, * 2 if there is only trailing whitespace, * 3 if there is both leading and trailing whitespace. */ private int normalizeWhitespace( XMLString value, boolean collapse) { boolean skipSpace = collapse; boolean sawNonWS = false; int leading = 0; int trailing = 0; int c; int size = value.offset+value.length; fNormalizedStr.setLength(0); for (int i = value.offset; i < size; i++) { c = value.ch[i]; if (c == 0x20 || c == 0x0D || c == 0x0A || c == 0x09) { if (!skipSpace) { // take the first whitespace as a space and skip the others fNormalizedStr.append(' '); skipSpace = collapse; } if (!sawNonWS) { // this is a leading whitespace, record it leading = 1; } } else { fNormalizedStr.append((char)c); skipSpace = false; sawNonWS = true; } } if (skipSpace) { c = fNormalizedStr.length(); if ( c != 0) { // if we finished on a space trim it but also record it fNormalizedStr.setLength (--c); trailing = 2; } else if (leading != 0 && !sawNonWS) { // if all we had was whitespace we skipped record it as // trailing whitespace as well trailing = 2; } } return collapse ? leading + trailing : 0; } private int normalizeWhitespace( String value, boolean collapse) { boolean skipSpace = collapse; boolean sawNonWS = false; int leading = 0; int trailing = 0; int c; int size = value.length(); fNormalizedStr.setLength(0); for (int i = 0; i < size; i++) { c = value.charAt(i); if (c == 0x20 || c == 0x0D || c == 0x0A || c == 0x09) { if (!skipSpace) { // take the first whitespace as a space and skip the others fNormalizedStr.append(' '); skipSpace = collapse; } if (!sawNonWS) { // this is a leading whitespace, record it leading = 1; } } else { fNormalizedStr.append((char)c); skipSpace = false; sawNonWS = true; } } if (skipSpace) { c = fNormalizedStr.length(); if ( c != 0) { // if we finished on a space trim it but also record it fNormalizedStr.setLength (--c); trailing = 2; } else if (leading != 0 && !sawNonWS) { // if all we had was whitespace we skipped record it as // trailing whitespace as well trailing = 2; } } return collapse ? leading + trailing : 0; } // handle ignorable whitespace void handleIgnorableWhitespace(XMLString text) { if (fSkipValidationDepth >= 0) return; // REVISIT: the same process needs to be performed as handleCharacters. // only it's simpler here: we know all characters are whitespaces. } // handleIgnorableWhitespace(XMLString) /** Handle element. */ Augmentations handleStartElement(QName element, XMLAttributes attributes, Augmentations augs) { if (DEBUG) { System.out.println("==>handleStartElement: " +element); } if(augs == null) { augs = fAugmentations; augs.clear(); } fCurrentPSVI = (ElementPSVImpl)augs.getItem(Constants.ELEMENT_PSVI); if (fCurrentPSVI == null) { fCurrentPSVI = fElemPSVI; augs.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); } fCurrentPSVI.reset(); // we receive prefix binding events before this one, // so at this point, the prefix bindings for this element is done, // and we need to push context when we receive another prefix binding. // but if fPushForNextBinding is still true, that means there has // been no prefix binding for this element. we still need to push // context, because the context is always popped in end element. if (fPushForNextBinding) fNamespaceSupport.pushContext(); else fPushForNextBinding = true; // root element if (fElementDepth == -1) { // at this point we assume that no XML schemas found in the instance document // thus we will not validate in the case dynamic feature is on or we found dtd grammar fDoValidation = fValidation && !(fValidationManager.isGrammarFound() || fDynamicValidation); //store the external schema locations, these locations will be set at root element, so any other // schemaLocation declaration for the same namespace will be effectively ignored.. becuase we // choose to take first location hint available for a particular namespace. storeLocations(fExternalSchemas, fExternalNoNamespaceSchema) ; } // get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes, // parse them to get the grammars String sLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION); String nsLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); //store the location hints.. we need to do it so that we can defer the loading of grammar until //there is a reference to a component from that namespace. To provide location hints to the //application for a namespace storeLocations(sLocation, nsLocation) ; //REVISIT: We should do the same in XSDHandler also... we should not //load the actual grammar (eg. import) unless there is reference to it. // REVISIT: we should not rely on presence of // schemaLocation or noNamespaceSchemaLocation // attributes if (sLocation !=null || nsLocation !=null) { // if we found grammar we should attempt to validate // based on values of validation & schema features // only fDoValidation = fValidation; } // update normalization flags if (fNormalizeData) { // reset values fFirstChunk = true; fUnionType = false; fWhiteSpace = -1; } // if we are in the content of "skip", then just skip this element // REVISIT: is this the correct behaviour for ID constraints? -NG if (fSkipValidationDepth >= 0) { fElementDepth++; return augs; } //try to find schema grammar by different means.. SchemaGrammar sGrammar = findSchemaGrammar(XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, attributes); // if we are not skipping this element, and there is a content model, // we try to find the corresponding decl object for this element. // the reason we move this part of code here is to make sure the // error reported here (if any) is stored within the parent element's // context, instead of that of the current element. Object decl = null; if (fCurrentCM != null) { decl = fCurrentCM.oneTransition(element, fCurrCMState, fSubGroupHandler); // it could be an element decl or a wildcard decl if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR && fDoValidation) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; //REVISIT: is it the only case we will have particle = null? if (ctype.fParticle != null) { reportSchemaError("cvc-complex-type.2.4.a", new Object[]{element.rawname, ctype.fParticle.toString()}); } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[]{element.rawname, "mixed with no element content"}); } } } // push error reporter context: record the current position fXSIErrorReporter.pushContext(); // if it's not the root element, we push the current states in the stacks if (fElementDepth != -1) { ensureStackCapacity(); fChildCountStack[fElementDepth] = fChildCount+1; fChildCount = 0; fElemDeclStack[fElementDepth] = fCurrentElemDecl; fNilStack[fElementDepth] = fNil; fNotationStack[fElementDepth] = fNotation; fTypeStack[fElementDepth] = fCurrentType; fCMStack[fElementDepth] = fCurrentCM; fCMStateStack[fElementDepth] = fCurrCMState; fStringContent[fElementDepth] = fSawCharacters; fSawChildrenStack[fElementDepth] = fSawChildren; } // increase the element depth after we've saved // all states for the parent element fElementDepth++; fCurrentElemDecl = null; XSWildcardDecl wildcard = null; fCurrentType = null; fNil = false; fNotation = null; // and the buffer to hold the value of the element fBuffer.setLength(0); fSawCharacters = false; fSawChildren = false; // check what kind of declaration the "decl" from // oneTransition() maps to if (decl != null) { if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl)decl; } else { wildcard = (XSWildcardDecl)decl; } } // if the wildcard is skip, then return if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_SKIP) { fSkipValidationDepth = fElementDepth; return augs; } // try again to get the element decl: // case 1: find declaration for root element // case 2: find declaration for element from another namespace if (fCurrentElemDecl == null) { if (sGrammar != null){ fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart); } } // Element Locally Valid (Element) // 2 Its {abstract} must be false. if (fCurrentElemDecl != null && fCurrentElemDecl.getIsAbstract()) reportSchemaError("cvc-elt.2", new Object[]{element.rawname}); if (fCurrentElemDecl != null) { // then get the type fCurrentType = fCurrentElemDecl.fType; } // get type from xsi:type String xsiType = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_TYPE); if (xsiType != null) fCurrentType = getAndCheckXsiType(element, xsiType, attributes); // if the element decl is not found if (fCurrentType == null) { if (fDoValidation) { // if this is the validation root, report an error, because // we can't find eith decl or type for this element // REVISIT: should we report error, or warning? if (fElementDepth == 0) { // report error, because it's root element reportSchemaError("cvc-elt.1", new Object[]{element.rawname}); } // if wildcard = strict, report error else if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { // report error, because wilcard = strict reportSchemaError("cvc-complex-type.2.4.c", new Object[]{element.rawname}); } } // no element decl or type found for this element. // Allowed by the spec, we can choose to either laxly assess this // element, or to skip it. Now we choose lax assessment. // REVISIT: IMO, we should perform lax assessment when validation // feature is on, and skip when dynamic validation feature is on. fCurrentType = SchemaGrammar.fAnyType; } // make the current element validation root if (fElementDepth == 0) { fValidationRoot = element.rawname; } // PSVI: add validation context fCurrentPSVI.fValidationContext = fValidationRoot; // PSVI: add element declaration fCurrentPSVI.fDeclaration = fCurrentElemDecl; // PSVI: add element type fCurrentPSVI.fTypeDecl = fCurrentType; // Element Locally Valid (Type) // 2 Its {abstract} must be false. if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; if (ctype.getIsAbstract()) { reportSchemaError("cvc-type.2", new Object[]{"Element " + element.rawname + " is declared with a type that is abstract. Use xsi:type to specify a non-abstract type"}); } if (fNormalizeData) { // find out if the content type is simple and if variety is union // to be able to do character normalization if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (ctype.fXSSimpleType.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = ctype.fXSSimpleType.getWhitespace(); } catch (DatatypeException e){ // do nothing } } } } } // normalization if (fNormalizeData && fCurrentType.getTypeCategory() == XSTypeDecl.SIMPLE_TYPE ) { // if !union type XSSimpleType dv = (XSSimpleType)fCurrentType; if (dv.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = dv.getWhitespace(); } catch (DatatypeException e){ // do nothing } } } // then try to get the content model fCurrentCM = null; if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) { fCurrentCM = ((XSComplexTypeDecl)fCurrentType).getContentModel(fCMBuilder); } // and get the initial content model state fCurrCMState = null; if (fCurrentCM != null) fCurrCMState = fCurrentCM.startContentModel(); // get information about xsi:nil String xsiNil = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NIL); // only deal with xsi:nil when there is an element declaration if (xsiNil != null && fCurrentElemDecl != null) fNil = getXsiNil(element, xsiNil); // now validate everything related with the attributes // first, get the attribute group XSAttributeGroupDecl attrGrp = null; if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; attrGrp = ctype.getAttrGrp(); } processAttributes(element, attributes, attrGrp); // add default attributes if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } // activate identity constraints if (fDoValidation) { fValueStoreCache.startElement(); fMatcherStack.pushContext(); if (fCurrentElemDecl != null) { fValueStoreCache.initValueStoresFor(fCurrentElemDecl); int icCount = fCurrentElemDecl.fIDCPos; int uniqueOrKey = 0; for (;uniqueOrKey < icCount; uniqueOrKey++) { if (fCurrentElemDecl.fIDConstraints[uniqueOrKey].getCategory() != IdentityConstraint.IC_KEYREF) { activateSelectorFor(fCurrentElemDecl.fIDConstraints[uniqueOrKey]); } else break; } for (int keyref = uniqueOrKey; keyref < icCount; keyref++) { activateSelectorFor((IdentityConstraint)fCurrentElemDecl.fIDConstraints[keyref]); } } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.startElement(element, attributes, fCurrentElemDecl); } } return augs; } // handleStartElement(QName,XMLAttributes,boolean) /** * Handle end element. If there is not text content, and there is a * {value constraint} on the corresponding element decl, then * set the fDefaultValue XMLString representing the default value. */ Augmentations handleEndElement(QName element, Augmentations augs) { if (DEBUG) { System.out.println("==>handleEndElement:" +element); } if(augs == null) { // again, always assume adding augmentations... augs = fAugmentations; augs.clear(); } fCurrentPSVI = (ElementPSVImpl)augs.getItem(Constants.ELEMENT_PSVI); if (fCurrentPSVI == null) { fCurrentPSVI = fElemPSVI; augs.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); } fCurrentPSVI.reset(); // if we are skipping, return if (fSkipValidationDepth >= 0) { // but if this is the top element that we are skipping, // restore the states. if (fSkipValidationDepth == fElementDepth && fSkipValidationDepth > 0) { // set the partial validation depth to the depth of parent fPartialValidationDepth = fSkipValidationDepth-1; fSkipValidationDepth = -1; fElementDepth fChildCount = fChildCountStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fNotation = fNotationStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; fSawChildren = fSawChildrenStack[fElementDepth]; } else { fElementDepth } // need to pop context so that the bindings for this element is // discarded. fNamespaceSupport.popContext(); // pop error reporter context: get all errors for the current // element, and remove them from the error list // String[] errors = fXSIErrorReporter.popContext(); // PSVI: validation attempted: // use default values in psvi item for // validation attempted, validity, and error codes // check extra schema constraints on root element if (fElementDepth == -1 && fDoValidation && fFullChecking) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter); } fDefaultValue = null; return augs; } // now validate the content of the element XMLString defaultValue = processElementContent(element); // Element Locally Valid (Element) // 6 The element information item must be valid with respect to each of the {identity-constraint definitions} as per Identity-constraint Satisfied (3.11.4). // call matchers and de-activate context int oldCount = fMatcherStack.getMatcherCount(); for (int i = oldCount - 1; i >= 0; i XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.endElement(element, fCurrentElemDecl, fCurrentPSVI); } if (fMatcherStack.size() > 0) { fMatcherStack.popContext(); } int newCount = fMatcherStack.getMatcherCount(); // handle everything *but* keyref's. for (int i = oldCount - 1; i >= newCount; i XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if(matcher instanceof Selector.Matcher) { Selector.Matcher selMatcher = (Selector.Matcher)matcher; IdentityConstraint id; if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() != IdentityConstraint.IC_KEYREF) { fValueStoreCache.transplant(id, selMatcher.getInitialDepth()); } } } // now handle keyref's/... for (int i = oldCount - 1; i >= newCount; i XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if(matcher instanceof Selector.Matcher) { Selector.Matcher selMatcher = (Selector.Matcher)matcher; IdentityConstraint id; if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() == IdentityConstraint.IC_KEYREF) { ValueStoreBase values = fValueStoreCache.getValueStoreFor(id, selMatcher.getInitialDepth()); if (values != null) // nothing to do if nothing matched! values.endDocumentFragment(); } } } fValueStoreCache.endElement(); // decrease element depth and restore states fElementDepth // have we reached the end tag of the validation root? if (fElementDepth == -1) { if (fDoValidation) { // 7 If the element information item is the validation root, it must be valid per Validation Root Valid (ID/IDREF) (3.3.4). String invIdRef = fValidationState.checkIDRefID(); if (invIdRef != null) { reportSchemaError("cvc-id.1", new Object[]{invIdRef}); } // check extra schema constraints if (fFullChecking) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter); } } fValidationState.resetIDTables(); SchemaGrammar[] grammars = fGrammarBucket.getGrammars(); // return the final set of grammars validator ended up with if (fGrammarPool != null) { fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA, grammars); } // store [schema information] in the PSVI fCurrentPSVI.fSchemaInformation = new XSModelImpl(grammars); } else { // get the states for the parent element. fChildCount = fChildCountStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fNotation = fNotationStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; fSawChildren = fSawChildrenStack[fElementDepth]; } // need to pop context so that the bindings for this element is // discarded. fNamespaceSupport.popContext(); fCurrentPSVI.fDeclaration = this.fCurrentElemDecl; fCurrentPSVI.fTypeDecl = this.fCurrentType; fCurrentPSVI.fNotation = this.fNotation; fCurrentPSVI.fValidationContext = this.fValidationRoot; // PSVI: validation attempted if (fElementDepth <= fPartialValidationDepth) { // the element had child with a content skip. fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_PARTIAL; if (fElementDepth == fPartialValidationDepth) { // set depth to the depth of the parent fPartialValidationDepth } } else { fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_FULL; } // pop error reporter context: get all errors for the current // element, and remove them from the error list String[] errors = fXSIErrorReporter.popContext(); // PSVI: error codes fCurrentPSVI.fErrorCodes = errors; // PSVI: validity fCurrentPSVI.fValidity = (errors == null) ? ElementPSVI.VALIDITY_VALID : ElementPSVI.VALIDITY_INVALID; fDefaultValue = defaultValue; // reset normalization values if (fNormalizeData) { fTrailing = false; fUnionType = false; fWhiteSpace = -1; } return augs; } // handleEndElement(QName,boolean)*/ void handleStartPrefix(String prefix, String uri) { // push namespace context if necessary if (fPushForNextBinding) { fNamespaceSupport.pushContext(); fPushForNextBinding = false; } // add prefix declaration to the namespace support fNamespaceSupport.declarePrefix(prefix, uri.length() != 0 ? uri : null); } void storeLocations(String sLocation, String nsLocation){ if (sLocation != null) { if(!XMLSchemaLoader.tokenizeSchemaLocationStr(sLocation, fLocationPairs)) { // error! fXSIErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, "SchemaLocation", new Object[]{sLocation}, XMLErrorReporter.SEVERITY_WARNING); } } if (nsLocation != null) { fNoNamespaceLocationArray.addLocation(nsLocation); fLocationPairs.put(XMLSymbols.EMPTY_STRING, fNoNamespaceLocationArray); } }//storeLocations //this is the function where logic of retrieving grammar is written , parser first tries to get the grammar from //the local pool, if not in local pool, it gives chance to application to be able to retrieve the grammar, then it //tries to parse the grammar using location hints from the give namespace. SchemaGrammar findSchemaGrammar(short contextType , String namespace , QName enclosingElement, QName triggeringComponet, XMLAttributes attributes ){ SchemaGrammar grammar = null ; //get the grammar from local pool... grammar = fGrammarBucket.getGrammar(namespace); if (grammar == null){ fXSDDescription.reset(); fXSDDescription.fContextType = contextType ; fXSDDescription.fTargetNamespace = namespace ; fXSDDescription.fEnclosedElementName = enclosingElement ; fXSDDescription.fTriggeringComponent = triggeringComponet ; fXSDDescription.fAttributes = attributes ; if (fBaseURI != null) { fXSDDescription.setBaseSystemId(fBaseURI); } String[] temp = null ; if( namespace != null){ Object locationArray = fLocationPairs.get(namespace) ; if(locationArray != null) temp = ((XMLSchemaLoader.LocationArray)locationArray).getLocationArray() ; }else{ temp = fNoNamespaceLocationArray.getLocationArray() ; } if (temp != null && temp.length != 0) { fXSDDescription.fLocationHints = new String [temp.length] ; System.arraycopy(temp, 0 , fXSDDescription.fLocationHints, 0, temp.length ); } // give a chance to application to be able to retreive the grammar. if (fGrammarPool != null){ grammar = (SchemaGrammar)fGrammarPool.retrieveGrammar(fXSDDescription); if (grammar != null) { // put this grammar into the bucket, along with grammars // imported by it (directly or indirectly) if (!fGrammarBucket.putGrammar(grammar, true)) { // REVISIT: a conflict between new grammar(s) and grammars // in the bucket. What to do? A warning? An exception? fXSIErrorReporter.fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, "GrammarConflict", null, XMLErrorReporter.SEVERITY_WARNING); grammar = null; } } } if (grammar == null) { // try to parse the grammar using location hints from that namespace.. try { XMLInputSource xis = XMLSchemaLoader.resolveDocument(fXSDDescription, fLocationPairs, fEntityResolver); grammar = fSchemaLoader.loadSchema(fXSDDescription, xis, fLocationPairs); } catch (IOException ex) { fXSIErrorReporter.fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, "schema_reference.4", new Object[]{fXSDDescription.getLocationHints()[0]}, XMLErrorReporter.SEVERITY_WARNING); } } } return grammar ; }//findSchemaGrammar XSTypeDecl getAndCheckXsiType(QName element, String xsiType, XMLAttributes attributes) { // This method also deals with clause 1.2.1.2 of the constraint // Validation Rule: Schema-Validity Assessment (Element) // Element Locally Valid (Element) // 4.1 The normalized value of that attribute information item must be valid with respect to the built-in QName simple type, as defined by String Valid (3.14.4); QName typeName = null; try { typeName = (QName)fQNameDV.validate(xsiType, fValidationState, null); } catch (InvalidDatatypeValueException e) { reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError("cvc-elt.4.1", new Object[]{element.rawname, SchemaSymbols.URI_XSI+","+SchemaSymbols.XSI_TYPE, xsiType}); return null; } // 4.2 The local name and namespace name (as defined in QName Interpretation (3.15.3)), of the actual value of that attribute information item must resolve to a type definition, as defined in QName resolution (Instance) (3.15.4) XSTypeDecl type = null; // if the namespace is schema namespace, first try built-in types if (typeName.uri == SchemaSymbols.URI_SCHEMAFORSCHEMA) { type = SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(typeName.localpart); } // if it's not schema built-in types, then try to get a grammar if (type == null) { //try to find schema grammar by different means.... SchemaGrammar grammar = findSchemaGrammar( XSDDescription.CONTEXT_XSITYPE , typeName.uri , element , typeName , attributes); if (grammar != null) type = grammar.getGlobalTypeDecl(typeName.localpart); } // still couldn't find the type, report an error if (type == null) { reportSchemaError("cvc-elt.4.2", new Object[]{element.rawname, xsiType}); return null; } // if there is no current type, set this one as current. // and we don't need to do extra checking if (fCurrentType != null) { // 4.3 The local type definition must be validly derived from the {type definition} given the union of the {disallowed substitutions} and the {type definition}'s {prohibited substitutions}, as defined in Type Derivation OK (Complex) (3.4.6) (if it is a complex type definition), or given {disallowed substitutions} as defined in Type Derivation OK (Simple) (3.14.6) (if it is a simple type definition). short block = fCurrentElemDecl.fBlock; if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) block |= ((XSComplexTypeDecl)fCurrentType).fBlock; if (!XSConstraints.checkTypeDerivationOk(type, fCurrentType, block)) reportSchemaError("cvc-elt.4.3", new Object[]{element.rawname, xsiType}); } return type; }//getAndCheckXsiType boolean getXsiNil(QName element, String xsiNil) { // Element Locally Valid (Element) // 3 The appropriate case among the following must be true: if (fCurrentElemDecl != null && !fCurrentElemDecl.getIsNillable()) { reportSchemaError("cvc-elt.3.1", new Object[]{element.rawname, SchemaSymbols.URI_XSI+","+SchemaSymbols.XSI_NIL}); } // 3.2 If {nillable} is true and there is such an attribute information item and its actual value is true , then all of the following must be true: // 3.2.2 There must be no fixed {value constraint}. else { String value = xsiNil.trim(); if (value.equals(SchemaSymbols.ATTVAL_TRUE) || value.equals(SchemaSymbols.ATTVAL_TRUE_1)) { if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { reportSchemaError("cvc-elt.3.2.2", new Object[]{element.rawname, SchemaSymbols.URI_XSI+","+SchemaSymbols.XSI_NIL}); } return true; } } return false; } void processAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) { if (DEBUG) { System.out.println("==>processAttributes: " +attributes.getLength()); } // REVISIT: should we assume that XMLAttributeImpl removes // all augmentations from Augmentations? if yes.. we loose objects // if no - we always produce attribute psvi objects which may not be filled in // in this case we need to create/reset here all objects Augmentations augs = null; AttributePSVImpl attrPSVI = null; for (int k=0;k<attributes.getLength();k++) { augs = attributes.getAugmentations(k); attrPSVI = (AttributePSVImpl) augs.getItem(Constants.ATTRIBUTE_PSVI); if (attrPSVI != null) { attrPSVI.reset(); } else { attrPSVI= new AttributePSVImpl(); augs.putItem(Constants.ATTRIBUTE_PSVI, attrPSVI); } // PSVI attribute: validation context attrPSVI.fValidationContext = fValidationRoot; } // if we don't do validation, we don't need to validate the attributes if (!fDoValidation || attributes.getLength() == 0){ // PSVI: validity is unknown, and validation attempted is none // this is a default value thus we should not set anything else here. return; } // Element Locally Valid (Type) // 3.1.1 The element information item's [attributes] must be empty, excepting those // whose [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation. if (fCurrentType == null || fCurrentType.getTypeCategory() == XSTypeDecl.SIMPLE_TYPE) { int attCount = attributes.getLength(); for (int index = 0; index < attCount; index++) { if (DEBUG) { System.out.println("==>process attribute: "+fTempQName); } attributes.getName(index, fTempQName); // get attribute PSVI attrPSVI = (AttributePSVImpl)attributes.getAugmentations(index).getItem(Constants.ATTRIBUTE_PSVI); // for the 4 xsi attributes, get appropriate decl, and validate if (fTempQName.uri == SchemaSymbols.URI_XSI) { XSAttributeDecl attrDecl = null; if (fTempQName.localpart == SchemaSymbols.XSI_SCHEMALOCATION) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION); else if (fTempQName.localpart == SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); else if (fTempQName.localpart == SchemaSymbols.XSI_NIL) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL); else if (fTempQName.localpart == SchemaSymbols.XSI_TYPE) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE); if (attrDecl != null) { processOneAttribute(element, attributes.getValue(index), attrDecl, null, attrPSVI); continue; } } // for all other attributes, no_validation/unknow_validity if (fTempQName.rawname != XMLSymbols.PREFIX_XMLNS && !fTempQName.rawname.startsWith("xmlns:")) { reportSchemaError("cvc-type.3.1.1", new Object[]{element.rawname}); } } return; } XSObjectList attrUses = attrGrp.getAttributeUses(); int useCount = attrUses.getLength(); XSWildcardDecl attrWildcard = attrGrp.fAttributeWC; // whether we have seen a Wildcard ID. String wildcardIDName = null; // for each present attribute int attCount = attributes.getLength(); // Element Locally Valid (Complex Type) // get the corresponding attribute decl for (int index = 0; index < attCount; index++) { attributes.getName(index, fTempQName); if (DEBUG) { System.out.println("==>process attribute: "+fTempQName); } // get attribute PSVI attrPSVI = (AttributePSVImpl)attributes.getAugmentations(index).getItem(Constants.ATTRIBUTE_PSVI); // for the 4 xsi attributes, get appropriate decl, and validate if (fTempQName.uri == SchemaSymbols.URI_XSI) { XSAttributeDecl attrDecl = null; if (fTempQName.localpart == SchemaSymbols.XSI_SCHEMALOCATION) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION); else if (fTempQName.localpart == SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); else if (fTempQName.localpart == SchemaSymbols.XSI_NIL) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL); else if (fTempQName.localpart == SchemaSymbols.XSI_TYPE) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE); if (attrDecl != null) { processOneAttribute(element, attributes.getValue(index), attrDecl, null, attrPSVI); continue; } } // for namespace attributes, no_validation/unknow_validity if (fTempQName.rawname == XMLSymbols.PREFIX_XMLNS || fTempQName.rawname.startsWith("xmlns:")) { continue; } // it's not xmlns, and not xsi, then we need to find a decl for it XSAttributeUseImpl currUse = null, oneUse; for (int i = 0; i < useCount; i++) { oneUse = (XSAttributeUseImpl)attrUses.getItem(i); if (oneUse.fAttrDecl.fName == fTempQName.localpart && oneUse.fAttrDecl.fTargetNamespace == fTempQName.uri) { currUse = oneUse; break; } } // 3.2 otherwise all of the following must be true: // 3.2.1 There must be an {attribute wildcard}. // 3.2.2 The attribute information item must be valid with respect to it as defined in Item Valid (Wildcard) (3.10.4). // if failed, get it from wildcard if (currUse == null) { //if (attrWildcard == null) // reportSchemaError("cvc-complex-type.3.2.1", new Object[]{element.rawname, fTempQName.rawname}); if (attrWildcard == null || !attrWildcard.allowNamespace(fTempQName.uri)) { // so this attribute is not allowed reportSchemaError("cvc-complex-type.3.2.2", new Object[]{element.rawname, fTempQName.rawname}); continue; } } XSAttributeDecl currDecl = null; if (currUse != null) { currDecl = currUse.fAttrDecl; } else { // which means it matches a wildcard // skip it if processContents is skip if (attrWildcard.fProcessContents == XSWildcardDecl.PC_SKIP) continue; //try to find grammar by different means... SchemaGrammar grammar = findSchemaGrammar( XSDDescription.CONTEXT_ATTRIBUTE , fTempQName.uri , element , fTempQName , attributes); if (grammar != null){ currDecl = grammar.getGlobalAttributeDecl(fTempQName.localpart); } // if can't find if (currDecl == null) { // if strict, report error if (attrWildcard.fProcessContents == XSWildcardDecl.PC_STRICT){ reportSchemaError("cvc-complex-type.3.2.2", new Object[]{element.rawname, fTempQName.rawname}); } // then continue to the next attribute continue; } else { // 5 Let [Definition:] the wild IDs be the set of all attribute information item to which clause 3.2 applied and whose validation resulted in a context-determined declaration of mustFind or no context-determined declaration at all, and whose [local name] and [namespace name] resolve (as defined by QName resolution (Instance) (3.15.4)) to an attribute declaration whose {type definition} is or is derived from ID. Then all of the following must be true: // 5.1 There must be no more than one item in wild IDs. if (currDecl.fType.getTypeCategory() == XSTypeDecl.SIMPLE_TYPE && ((XSSimpleType)currDecl.fType).isIDType()) { if (wildcardIDName != null){ reportSchemaError("cvc-complex-type.5.1", new Object[]{element.rawname, currDecl.fName, wildcardIDName}); // PSVI: attribute is invalid, record errors attrPSVI.fValidity = AttributePSVI.VALIDITY_INVALID; attrPSVI.addErrorCode("cvc-complex-type.5.1"); } else wildcardIDName = currDecl.fName; } } } processOneAttribute(element, attributes.getValue(index), currDecl, currUse, attrPSVI); } // end of for (all attributes) // 5.2 If wild IDs is non-empty, there must not be any attribute uses among the {attribute uses} whose {attribute declaration}'s {type definition} is or is derived from ID. if (attrGrp.fIDAttrName != null && wildcardIDName != null){ // PSVI: attribute is invalid, record errors reportSchemaError("cvc-complex-type.5.2", new Object[]{element.rawname, wildcardIDName, attrGrp.fIDAttrName}); } } //processAttributes void processOneAttribute(QName element, String attrValue, XSAttributeDecl currDecl, XSAttributeUseImpl currUse, AttributePSVImpl attrPSVI) { // Attribute Locally Valid // For an attribute information item to be locally valid with respect to an attribute declaration all of the following must be true: // 1 The declaration must not be absent (see Missing Sub-components (5.3) for how this can fail to be the case). // 2 Its {type definition} must not be absent. // 3 The item's normalized value must be locally valid with respect to that {type definition} as per String Valid (3.14.4). // get simple type XSSimpleType attDV = currDecl.fType; // PSVI: attribute declaration attrPSVI.fDeclaration = currDecl; // PSVI: attribute type attrPSVI.fTypeDecl = attDV; // PSVI: validation attempted: attrPSVI.fValidationAttempted = AttributePSVI.VALIDATION_FULL; attrPSVI.fValidity = AttributePSVI.VALIDITY_VALID; Object actualValue = null; try { actualValue = attDV.validate(attrValue, fValidationState, fValidatedInfo); // PSVI: attribute memberType attrPSVI.fMemberType = fValidatedInfo.memberType; // PSVI: element notation if (attDV.getVariety() == XSSimpleType.VARIETY_ATOMIC && attDV.getPrimitiveKind() == XSSimpleType.PRIMITIVE_NOTATION){ QName qName = (QName)actualValue; SchemaGrammar grammar = fGrammarBucket.getGrammar(qName.uri); //REVISIT: is it possible for the notation to be in different namespace than the attribute //with which it is associated, CHECK !! <fof n1:att1 = "n2:notation1" ..> // should we give chance to the application to be able to retrieve a grammar - nb //REVISIT: what would be the triggering component here.. if it is attribute value that // triggered the loading of grammar ?? -nb if (grammar != null) { fNotation = grammar.getGlobalNotationDecl(qName.localpart); fCurrentPSVI.fNotation = fNotation; } } } catch (InvalidDatatypeValueException idve) { // PSVI: attribute is invalid, record errors attrPSVI.fValidity = AttributePSVI.VALIDITY_INVALID; attrPSVI.addErrorCode("cvc-attribute.3"); reportSchemaError(idve.getKey(), idve.getArgs()); reportSchemaError("cvc-attribute.3", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } // PSVI: attribute normalized value // NOTE: we always store the normalized value, even if it's invlid, // because it might still be useful to the user. But when the it's // not valid, the normalized value is not trustable. attrPSVI.fNormalizedValue = fValidatedInfo.normalizedValue; // get the value constraint from use or decl // 4 The item's actual value must match the value of the {value constraint}, if it is present and fixed. // now check the value against the simpleType if (actualValue != null && currDecl.getConstraintType() == XSConstants.VC_FIXED) { if (!attDV.isEqual(actualValue, currDecl.fDefault.actualValue)){ // PSVI: attribute is invalid, record errors attrPSVI.fValidity = AttributePSVI.VALIDITY_INVALID; attrPSVI.addErrorCode("cvc-attribute.4"); reportSchemaError("cvc-attribute.4", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } } // 3.1 If there is among the {attribute uses} an attribute use with an {attribute declaration} whose {name} matches the attribute information item's [local name] and whose {target namespace} is identical to the attribute information item's [namespace name] (where an absent {target namespace} is taken to be identical to a [namespace name] with no value), then the attribute information must be valid with respect to that attribute use as per Attribute Locally Valid (Use) (3.5.4). In this case the {attribute declaration} of that attribute use is the context-determined declaration for the attribute information item with respect to Schema-Validity Assessment (Attribute) (3.2.4) and Assessment Outcome (Attribute) (3.2.5). if (actualValue != null && currUse != null && currUse.fConstraintType == XSConstants.VC_FIXED) { if (!attDV.isEqual(actualValue, currUse.fDefault.actualValue)){ // PSVI: attribute is invalid, record errors attrPSVI.fValidity = AttributePSVI.VALIDITY_INVALID; attrPSVI.addErrorCode("cvc-complex-type.3.1"); reportSchemaError("cvc-complex-type.3.1", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } } } void addDefaultAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) { // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // REVISIT: should we check prohibited attributes? // (2) report error for PROHIBITED attrs that are present (V_TAGc) // (3) add default attrs (FIXED and NOT_FIXED) if (DEBUG) { System.out.println("==>addDefaultAttributes: " + element); } XSObjectList attrUses = attrGrp.getAttributeUses(); int useCount = attrUses.getLength(); XSAttributeUseImpl currUse; XSAttributeDecl currDecl; short constType; ValidatedInfo defaultValue; boolean isSpecified; QName attName; // for each attribute use for (int i = 0; i < useCount; i++) { currUse = (XSAttributeUseImpl)attrUses.getItem(i); currDecl = currUse.fAttrDecl; // get value constraint constType = currUse.fConstraintType; defaultValue = currUse.fDefault; if (constType == XSConstants.VC_NONE) { constType = currDecl.getConstraintType(); defaultValue = currDecl.fDefault; } // whether this attribute is specified isSpecified = attributes.getValue(currDecl.fTargetNamespace, currDecl.fName) != null; // Element Locally Valid (Complex Type) // 4 The {attribute declaration} of each attribute use in the {attribute uses} whose // {required} is true matches one of the attribute information items in the element // information item's [attributes] as per clause 3.1 above. if (currUse.fUse == SchemaSymbols.USE_REQUIRED) { if (!isSpecified) reportSchemaError("cvc-complex-type.4", new Object[]{element.rawname, currDecl.fName}); } // if the attribute is not specified, then apply the value constraint if (!isSpecified && constType != XSConstants.VC_NONE) { attName = new QName(null, currDecl.fName, currDecl.fName, currDecl.fTargetNamespace); int attrIndex = attributes.addAttribute(attName, "CDATA", (defaultValue!=null)?defaultValue.normalizedValue:""); // PSVI: attribute is "schema" specified Augmentations augs = attributes.getAugmentations(attrIndex); AttributePSVImpl attrPSVI = (AttributePSVImpl)augs.getItem(Constants.ATTRIBUTE_PSVI); // check if PSVIAttribute was added to Augmentations. // it is possible that we just created new chunck of attributes // in this case PSVI attribute are not there. if (attrPSVI != null) { attrPSVI.reset(); } else { attrPSVI = new AttributePSVImpl(); augs.putItem(Constants.ATTRIBUTE_PSVI, attrPSVI); } attrPSVI.fSpecified = false; // PSVI attribute: validation context attrPSVI.fValidationContext = fValidationRoot; } } // for } // addDefaultAttributes /** * If there is not text content, and there is a * {value constraint} on the corresponding element decl, then return * an XMLString representing the default value. */ XMLString processElementContent(QName element) { // fCurrentElemDecl: default value; ... XMLString defaultValue = null; // 1 If the item is ?valid? with respect to an element declaration as per Element Locally Valid (Element) (?3.3.4) and the {value constraint} is present, but clause 3.2 of Element Locally Valid (Element) (?3.3.4) above is not satisfied and the item has no element or character information item [children], then schema. Furthermore, the post-schema-validation infoset has the canonical lexical representation of the {value constraint} value as the item's [schema normalized value] property. if (fCurrentElemDecl != null && fCurrentElemDecl.fDefault != null && fBuffer.toString().length() == 0 && fChildCount == 0 && !fNil) { // PSVI: specified fCurrentPSVI.fSpecified = false; int bufLen = fCurrentElemDecl.fDefault.normalizedValue.length(); char [] chars = new char[bufLen]; fCurrentElemDecl.fDefault.normalizedValue.getChars(0, bufLen, chars, 0); defaultValue = new XMLString(chars, 0, bufLen); } // fixed values are handled later, after xsi:type determined. if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_DEFAULT) { } if (fDoValidation) { String content = fBuffer.toString(); // Element Locally Valid (Element) // 3.2.1 The element information item must have no character or element information item [children]. if (fNil) { if (fChildCount != 0 || content.length() != 0){ reportSchemaError("cvc-elt.3.2.1", new Object[]{element.rawname, SchemaSymbols.URI_XSI+","+SchemaSymbols.XSI_NIL}); // PSVI: nil fCurrentPSVI.fNil = false; } else { fCurrentPSVI.fNil = true; } } // 5 The appropriate case among the following must be true: // 5.1 If the declaration has a {value constraint}, the item has neither element nor character [children] and clause 3.2 has not applied, then all of the following must be true: if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() != XSConstants.VC_NONE && fChildCount == 0 && content.length() == 0 && !fNil) { // 5.1.1 If the actual type definition is a local type definition then the canonical lexical representation of the {value constraint} value must be a valid default for the actual type definition as defined in Element Default Valid (Immediate) (3.3.6). if (fCurrentType != fCurrentElemDecl.fType) { //REVISIT:we should pass ValidatedInfo here. if (XSConstraints.ElementDefaultValidImmediate(fCurrentType, fCurrentElemDecl.fDefault.normalizedValue, fState4XsiType, null) == null) reportSchemaError("cvc-elt.5.1.1", new Object[]{element.rawname, fCurrentType.getName(), fCurrentElemDecl.fDefault.normalizedValue}); } // 5.1.2 The element information item with the canonical lexical representation of the {value constraint} value used as its normalized value must be valid with respect to the actual type definition as defined by Element Locally Valid (Type) (3.3.4). // REVISIT: don't use toString, but validateActualValue instead // use the fState4ApplyDefault elementLocallyValidType(element, fCurrentElemDecl.fDefault.normalizedValue); } else { // The following method call also deal with clause 1.2.2 of the constraint // Validation Rule: Schema-Validity Assessment (Element) // 5.2 If the declaration has no {value constraint} or the item has either element or character [children] or clause 3.2 has applied, then all of the following must be true: // 5.2.1 The element information item must be valid with respect to the actual type definition as defined by Element Locally Valid (Type) (3.3.4). Object actualValue = elementLocallyValidType(element, content); // 5.2.2 If there is a fixed {value constraint} and clause 3.2 has not applied, all of the following must be true: if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED && !fNil) { // 5.2.2.1 The element information item must have no element information item [children]. if (fChildCount != 0) reportSchemaError("cvc-elt.5.2.2.1", new Object[]{element.rawname}); // 5.2.2.2 The appropriate case among the following must be true: if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; // 5.2.2.2.1 If the {content type} of the actual type definition is mixed, then the initial value of the item must match the canonical lexical representation of the {value constraint} value. if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { // REVISIT: how to get the initial value, does whiteSpace count? if (!fCurrentElemDecl.fDefault.normalizedValue.equals(content)) reportSchemaError("cvc-elt.5.2.2.2.1", new Object[]{element.rawname, content, fCurrentElemDecl.fDefault.normalizedValue}); } // 5.2.2.2.2 If the {content type} of the actual type definition is a simple type definition, then the actual value of the item must match the canonical lexical representation of the {value constraint} value. else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (actualValue != null && !ctype.fXSSimpleType.isEqual(actualValue, fCurrentElemDecl.fDefault.actualValue)) reportSchemaError("cvc-elt.5.2.2.2.2", new Object[]{element.rawname, content, fCurrentElemDecl.fDefault.normalizedValue}); } } else if (fCurrentType.getTypeCategory() == XSTypeDecl.SIMPLE_TYPE) { XSSimpleType sType = (XSSimpleType)fCurrentType; if (actualValue != null && !sType.isEqual(actualValue, fCurrentElemDecl.fDefault.actualValue)) // REVISIT: the spec didn't mention this case: fixed // value with simple type reportSchemaError("cvc-elt.5.2.2.2.2", new Object[]{element.rawname, content, fCurrentElemDecl.fDefault.normalizedValue}); } } } } // if fDoValidation return defaultValue; } // processElementContent Object elementLocallyValidType(QName element, String textContent) { if (fCurrentType == null) return null; if (fUnionType) { // for union types we need to send data because we delayed sending this data // when we received it in the characters() call. // XMLString will inlude non-normalized value, PSVIElement will include // normalized value int bufLen = textContent.length(); if (bufLen >= BUFFER_SIZE) { fCharBuffer = new char[bufLen*2]; } textContent.getChars(0, bufLen, fCharBuffer, 0); fXMLString.setValues(fCharBuffer, 0, bufLen); } Object retValue = null; // Element Locally Valid (Type) // 3 The appropriate case among the following must be true: // 3.1 If the type definition is a simple type definition, then all of the following must be true: if (fCurrentType.getTypeCategory() == XSTypeDecl.SIMPLE_TYPE) { // 3.1.2 The element information item must have no element information item [children]. if (fChildCount != 0) reportSchemaError("cvc-type.3.1.2", new Object[]{element.rawname}); // 3.1.3 If clause 3.2 of Element Locally Valid (Element) (3.3.4) did not apply, then the normalized value must be valid with respect to the type definition as defined by String Valid (3.14.4). if (!fNil) { XSSimpleType dv = (XSSimpleType)fCurrentType; try { if (!fNormalizeData || fUnionType) { fValidationState.setNormalizationRequired(true); } retValue = dv.validate(textContent, fValidationState, fValidatedInfo); // PSVI: schema normalized value fCurrentPSVI.fNormalizedValue = fValidatedInfo.normalizedValue; // PSVI: memberType fCurrentPSVI.fMemberType = fValidatedInfo.memberType; if (fDocumentHandler != null && fUnionType) { // send normalized values // at this point we should only rely on normalized value // available via PSVI fAugmentations.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); fDocumentHandler.characters(fXMLString, fAugmentations); } } catch (InvalidDatatypeValueException e) { if (fDocumentHandler != null && fUnionType) { fCurrentPSVI.fNormalizedValue = null; fAugmentations.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); fDocumentHandler.characters(fXMLString, fAugmentations); } reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError("cvc-type.3.1.3", new Object[]{element.rawname, textContent}); } } } else { // 3.2 If the type definition is a complex type definition, then the element information item must be valid with respect to the type definition as per Element Locally Valid (Complex Type) (3.4.4); retValue = elementLocallyValidComplexType(element, textContent); } return retValue; } // elementLocallyValidType Object elementLocallyValidComplexType(QName element, String textContent) { Object actualValue = null; XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; // Element Locally Valid (Complex Type) // For an element information item to be locally valid with respect to a complex type definition all of the following must be true: // 1 {abstract} is false. // 2 If clause 3.2 of Element Locally Valid (Element) (3.3.4) did not apply, then the appropriate case among the following must be true: if (!fNil) { // 2.1 If the {content type} is empty, then the element information item has no character or element information item [children]. if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_EMPTY && (fChildCount != 0 || textContent.length() != 0 || fSawChildren)) { reportSchemaError("cvc-complex-type.2.1", new Object[]{element.rawname}); } // 2.2 If the {content type} is a simple type definition, then the element information item has no element information item [children], and the normalized value of the element information item is valid with respect to that simple type definition as defined by String Valid (3.14.4). else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (fChildCount != 0) reportSchemaError("cvc-complex-type.2.2", new Object[]{element.rawname}); XSSimpleType dv = ctype.fXSSimpleType; try { if (!fNormalizeData || fUnionType) { fValidationState.setNormalizationRequired(true); } actualValue = dv.validate(textContent, fValidationState, fValidatedInfo); // PSVI: memberType fCurrentPSVI.fMemberType = fValidatedInfo.memberType; if (fDocumentHandler != null && fUnionType) { fDocumentHandler.characters(fXMLString, fAugmentations); } } catch (InvalidDatatypeValueException e) { if (fDocumentHandler != null && fUnionType) { fCurrentPSVI.fNormalizedValue = null; fDocumentHandler.characters(fXMLString, fAugmentations); } reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError("cvc-complex-type.2.2", new Object[]{element.rawname}); } // REVISIT: eventually, this method should return the same actualValue as elementLocallyValidType... // obviously it'll return null when the content is complex. // PSVI: schema normalized value fCurrentPSVI.fNormalizedValue = fValidatedInfo.normalizedValue; } // 2.3 If the {content type} is element-only, then the element information item has no character information item [children] other than those whose [character code] is defined as a white space in [XML 1.0 (Second Edition)]. else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) { if (fSawCharacters) { reportSchemaError("cvc-complex-type.2.3", new Object[]{element.rawname}); } } // 2.4 If the {content type} is element-only or mixed, then the sequence of the element information item's element information item [children], if any, taken in order, is valid with respect to the {content type}'s particle, as defined in Element Sequence Locally Valid (Particle) (3.9.4). if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT || ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { // if the current state is a valid state, check whether // it's one of the final states. if (DEBUG) { System.out.println(fCurrCMState); } if (fCurrCMState[0] >= 0 && !fCurrentCM.endContentModel(fCurrCMState)) { reportSchemaError("cvc-complex-type.2.4.b", new Object[]{element.rawname, ((XSParticleDecl)ctype.getParticle()).toString()}); } } } return actualValue; } // elementLocallyValidComplexType void reportSchemaError(String key, Object[] arguments) { if (fDoValidation) fXSIErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, key, arguments, XMLErrorReporter.SEVERITY_ERROR); } // xpath matcher information /** * Stack of XPath matchers for identity constraints. * * @author Andy Clark, IBM */ protected static class XPathMatcherStack { // Data /** Active matchers. */ protected XPathMatcher[] fMatchers = new XPathMatcher[4]; /** Count of active matchers. */ protected int fMatchersCount; /** Offset stack for contexts. */ protected IntStack fContextStack = new IntStack(); // Constructors public XPathMatcherStack() { } // <init>() // Public methods /** Resets the XPath matcher stack. */ public void clear() { for (int i = 0; i < fMatchersCount; i++) { fMatchers[i] = null; } fMatchersCount = 0; fContextStack.clear(); } // clear() /** Returns the size of the stack. */ public int size() { return fContextStack.size(); } // size():int /** Returns the count of XPath matchers. */ public int getMatcherCount() { return fMatchersCount; } // getMatcherCount():int /** Adds a matcher. */ public void addMatcher(XPathMatcher matcher) { ensureMatcherCapacity(); fMatchers[fMatchersCount++] = matcher; } // addMatcher(XPathMatcher) /** Returns the XPath matcher at the specified index. */ public XPathMatcher getMatcherAt(int index) { return fMatchers[index]; } // getMatcherAt(index):XPathMatcher /** Pushes a new context onto the stack. */ public void pushContext() { fContextStack.push(fMatchersCount); } // pushContext() /** Pops a context off of the stack. */ public void popContext() { fMatchersCount = fContextStack.pop(); } // popContext() // Private methods /** Ensures the size of the matchers array. */ private void ensureMatcherCapacity() { if (fMatchersCount == fMatchers.length) { XPathMatcher[] array = new XPathMatcher[fMatchers.length * 2]; System.arraycopy(fMatchers, 0, array, 0, fMatchers.length); fMatchers = array; } } // ensureMatcherCapacity() } // class XPathMatcherStack // value store implementations /** * Value store implementation base class. There are specific subclasses * for handling unique, key, and keyref. * * @author Andy Clark, IBM */ protected abstract class ValueStoreBase implements ValueStore { // Constants /** Not a value (Unicode: #FFFF). */ protected IDValue NOT_AN_IDVALUE = new IDValue("\uFFFF", null); // Data /** Identity constraint. */ protected IdentityConstraint fIdentityConstraint; /** Current data values. */ protected final OrderedHashtable fValues = new OrderedHashtable(); /** Current data value count. */ protected int fValuesCount; /** Data value tuples. */ protected final Vector fValueTuples = new Vector(); // Constructors /** Constructs a value store for the specified identity constraint. */ protected ValueStoreBase(IdentityConstraint identityConstraint) { fIdentityConstraint = identityConstraint; } // <init>(IdentityConstraint) // Public methods // destroys this ValueStore; useful when, for instance, a // locally-scoped ID constraint is involved. public void clear() { fValuesCount = 0; fValues.clear(); fValueTuples.removeAllElements(); } // end clear():void // appends the contents of one ValueStore to those of us. public void append(ValueStoreBase newVal) { for (int i = 0; i < newVal.fValueTuples.size(); i++) { OrderedHashtable o = (OrderedHashtable)newVal.fValueTuples.elementAt(i); if (!contains(o)) fValueTuples.addElement(o); } } // append(ValueStoreBase) /** Start scope for value store. */ public void startValueScope() throws XNIException { fValuesCount = 0; int count = fIdentityConstraint.getFieldCount(); for (int i = 0; i < count; i++) { fValues.put(fIdentityConstraint.getFieldAt(i), NOT_AN_IDVALUE); } } // startValueScope() /** Ends scope for value store. */ public void endValueScope() throws XNIException { // is there anything to do? // REVISIT: This check solves the problem with field matchers // that get activated because they are at the same // level as the declaring element (e.g. selector xpath // is ".") but never match. // However, this doesn't help us catch the problem // when we expect a field value but never see it. A // better solution has to be found. -Ac // REVISIT: Is this a problem? -Ac // Yes - NG if (fValuesCount == 0) { if (fIdentityConstraint.getCategory() == IdentityConstraint.IC_KEY) { String code = "AbsentKeyValue"; String eName = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{eName}); } return; } // do we have enough values? if (fValuesCount != fIdentityConstraint.getFieldCount()) { switch (fIdentityConstraint.getCategory()) { case IdentityConstraint.IC_UNIQUE: { String code = "UniqueNotEnoughValues"; String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{ename}); break; } case IdentityConstraint.IC_KEY: { String code = "KeyNotEnoughValues"; UniqueOrKey key = (UniqueOrKey)fIdentityConstraint; String ename = fIdentityConstraint.getElementName(); String kname = key.getIdentityConstraintName(); reportSchemaError(code, new Object[]{ename,kname}); break; } case IdentityConstraint.IC_KEYREF: { String code = "KeyRefNotEnoughValues"; KeyRef keyref = (KeyRef)fIdentityConstraint; String ename = fIdentityConstraint.getElementName(); String kname = (keyref.getKey()).getIdentityConstraintName(); reportSchemaError(code, new Object[]{ename,kname}); break; } } return; } } // endValueScope() // This is needed to allow keyref's to look for matched keys // in the correct scope. Unique and Key may also need to // override this method for purposes of their own. // This method is called whenever the DocumentFragment // of an ID Constraint goes out of scope. public void endDocumentFragment() throws XNIException { } // endDocumentFragment():void /** * Signals the end of the document. This is where the specific * instances of value stores can verify the integrity of the * identity constraints. */ public void endDocument() throws XNIException { } // endDocument() // ValueStore methods /* reports an error if an element is matched * has nillable true and is matched by a key. */ public void reportError(String key, Object[] args) { reportSchemaError(key, args); } // reportError(String,Object[]) /** * Adds the specified value to the value store. * * @param value The value to add. * @param field The field associated to the value. This reference * is used to ensure that each field only adds a value * once within a selection scope. */ public void addValue(Field field, IDValue value) { if (!field.mayMatch()) { String code = "FieldMultipleMatch"; reportSchemaError(code, new Object[]{field.toString()}); } // do we even know this field? int index = fValues.indexOf(field); if (index == -1) { String code = "UnknownField"; reportSchemaError(code, new Object[]{field.toString()}); return; } // store value IDValue storedValue = fValues.valueAt(index); if (storedValue.isDuplicateOf(NOT_AN_IDVALUE)) { fValuesCount++; } fValues.put(field, value); if (fValuesCount == fValues.size()) { // is this value as a group duplicated? if (contains(fValues)) { duplicateValue(fValues); } // store values OrderedHashtable values = (OrderedHashtable)fValues.clone(); fValueTuples.addElement(values); } } // addValue(String,Field) /** * Returns true if this value store contains the specified * values tuple. */ public boolean contains(OrderedHashtable tuple) { // do sizes match? int tcount = tuple.size(); // iterate over tuples to find it int count = fValueTuples.size(); LOOP: for (int i = 0; i < count; i++) { OrderedHashtable vtuple = (OrderedHashtable)fValueTuples.elementAt(i); // compare values for (int j = 0; j < tcount; j++) { IDValue value1 = vtuple.valueAt(j); IDValue value2 = tuple.valueAt(j); if (!(value1.isDuplicateOf(value2))) { continue LOOP; } } // found it return true; } // didn't find it return false; } // contains(Hashtable):boolean // Protected methods /** * Called when a duplicate value is added. Subclasses should override * this method to perform error checking. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws XNIException { // no-op } // duplicateValue(Hashtable) /** Returns a string of the specified values. */ protected String toString(OrderedHashtable tuple) { // no values int size = tuple.size(); if (size == 0) { return ""; } // construct value string StringBuffer str = new StringBuffer(); for (int i = 0; i < size; i++) { if (i > 0) { str.append(','); } str.append(tuple.valueAt(i)); } return str.toString(); } // toString(OrderedHashtable):String // Object methods /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { s = s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { s = s.substring(index2 + 1); } return s + '[' + fIdentityConstraint + ']'; } // toString():String } // class ValueStoreBase /** * Unique value store. * * @author Andy Clark, IBM */ protected class UniqueValueStore extends ValueStoreBase { // Constructors /** Constructs a unique value store. */ public UniqueValueStore(UniqueOrKey unique) { super(unique); } // <init>(Unique) // ValueStoreBase protected methods /** * Called when a duplicate value is added. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws XNIException { String code = "DuplicateUnique"; String value = toString(tuple); String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{value,ename}); } // duplicateValue(Hashtable) } // class UniqueValueStore /** * Key value store. * * @author Andy Clark, IBM */ protected class KeyValueStore extends ValueStoreBase { // REVISIT: Implement a more efficient storage mechanism. -Ac // Constructors /** Constructs a key value store. */ public KeyValueStore(UniqueOrKey key) { super(key); } // <init>(Key) // ValueStoreBase protected methods /** * Called when a duplicate value is added. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws XNIException { String code = "DuplicateKey"; String value = toString(tuple); String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{value,ename}); } // duplicateValue(Hashtable) } // class KeyValueStore /** * Key reference value store. * * @author Andy Clark, IBM */ protected class KeyRefValueStore extends ValueStoreBase { // Data /** Key value store. */ protected ValueStoreBase fKeyValueStore; // Constructors /** Constructs a key value store. */ public KeyRefValueStore(KeyRef keyRef, KeyValueStore keyValueStore) { super(keyRef); fKeyValueStore = keyValueStore; } // <init>(KeyRef) // ValueStoreBase methods // end the value Scope; here's where we have to tie // up keyRef loose ends. public void endDocumentFragment () throws XNIException { // do all the necessary management... super.endDocumentFragment (); // verify references // get the key store corresponding (if it exists): fKeyValueStore = (ValueStoreBase)fValueStoreCache.fGlobalIDConstraintMap.get(((KeyRef)fIdentityConstraint).getKey()); if (fKeyValueStore == null) { // report error String code = "KeyRefOutOfScope"; String value = fIdentityConstraint.toString(); reportSchemaError(code, new Object[]{value}); return; } int count = fValueTuples.size(); for (int i = 0; i < count; i++) { OrderedHashtable values = (OrderedHashtable)fValueTuples.elementAt(i); if (!fKeyValueStore.contains(values)) { String code = "KeyNotFound"; String value = toString(values); String element = fIdentityConstraint.getElementName(); String name = fIdentityConstraint.getName(); reportSchemaError(code, new Object[]{name, value,element}); } } } // endDocumentFragment() /** End document. */ public void endDocument() throws XNIException { super.endDocument(); } // endDocument() } // class KeyRefValueStore // value store management /** * Value store cache. This class is used to store the values for * identity constraints. * * @author Andy Clark, IBM */ protected class ValueStoreCache { // Data // values stores /** stores all global Values stores. */ protected final Vector fValueStores = new Vector(); /** * Values stores associated to specific identity constraints. * This hashtable maps IdentityConstraints and * the 0-based element on which their selectors first matched to * a corresponding ValueStore. This should take care * of all cases, including where ID constraints with * descendant-or-self axes occur on recursively-defined * elements. */ protected final Hashtable fIdentityConstraint2ValueStoreMap = new Hashtable(); // sketch of algorithm: // - when a constraint is first encountered, its // values are stored in the (local) fIdentityConstraint2ValueStoreMap; // - Once it is validated (i.e., wen it goes out of scope), // its values are merged into the fGlobalIDConstraintMap; // - as we encounter keyref's, we look at the global table to // validate them. // the fGlobalIDMapStack has the following structure: // - validation always occurs against the fGlobalIDConstraintMap // (which comprises all the "eligible" id constraints); // When an endelement is found, this Hashtable is merged with the one // below in the stack. // When a start tag is encountered, we create a new // fGlobalIDConstraintMap. // i.e., the top of the fGlobalIDMapStack always contains // the preceding siblings' eligible id constraints; // the fGlobalIDConstraintMap contains descendants+self. // keyrefs can only match descendants+self. protected final Stack fGlobalMapStack = new Stack(); protected final Hashtable fGlobalIDConstraintMap = new Hashtable(); // Constructors /** Default constructor. */ public ValueStoreCache() { } // <init>() // Public methods /** Resets the identity constraint cache. */ public void startDocument() throws XNIException { fValueStores.removeAllElements(); fIdentityConstraint2ValueStoreMap.clear(); fGlobalIDConstraintMap.clear(); fGlobalMapStack.removeAllElements(); } // startDocument() // startElement: pushes the current fGlobalIDConstraintMap // onto fGlobalMapStack and clears fGlobalIDConstraint map. public void startElement() { // only clone the hashtable when there are elements if (fGlobalIDConstraintMap.size() > 0) fGlobalMapStack.push(fGlobalIDConstraintMap.clone()); else fGlobalMapStack.push(null); fGlobalIDConstraintMap.clear(); } // startElement(void) // endElement(): merges contents of fGlobalIDConstraintMap with the // top of fGlobalMapStack into fGlobalIDConstraintMap. public void endElement() { if (fGlobalMapStack.isEmpty()) return; // must be an invalid doc! Hashtable oldMap = (Hashtable)fGlobalMapStack.pop(); // return if there is no element if (oldMap == null) return; Enumeration keys = oldMap.keys(); while (keys.hasMoreElements()) { IdentityConstraint id = (IdentityConstraint)keys.nextElement(); ValueStoreBase oldVal = (ValueStoreBase)oldMap.get(id); if (oldVal != null) { ValueStoreBase currVal = (ValueStoreBase)fGlobalIDConstraintMap.get(id); if (currVal == null) fGlobalIDConstraintMap.put(id, oldVal); else { currVal.append(oldVal); } } } } // endElement() /** * Initializes the value stores for the specified element * declaration. */ public void initValueStoresFor(XSElementDecl eDecl) { // initialize value stores for unique fields IdentityConstraint [] icArray = eDecl.fIDConstraints; int icCount = eDecl.fIDCPos; for (int i = 0; i < icCount; i++) { switch (icArray[i].getCategory()) { case (IdentityConstraint.IC_UNIQUE): // initialize value stores for unique fields UniqueOrKey unique = (UniqueOrKey)icArray[i]; LocalIDKey toHash = new LocalIDKey (unique, fElementDepth); UniqueValueStore uniqueValueStore = (UniqueValueStore)fIdentityConstraint2ValueStoreMap.get(toHash); if (uniqueValueStore == null) { uniqueValueStore = new UniqueValueStore(unique); fIdentityConstraint2ValueStoreMap.put(toHash, uniqueValueStore); } else { uniqueValueStore.clear(); } fValueStores.addElement(uniqueValueStore); break; case (IdentityConstraint.IC_KEY): // initialize value stores for key fields UniqueOrKey key = (UniqueOrKey)icArray[i]; toHash = new LocalIDKey(key, fElementDepth); KeyValueStore keyValueStore = (KeyValueStore)fIdentityConstraint2ValueStoreMap.get(toHash); if (keyValueStore == null) { keyValueStore = new KeyValueStore(key); fIdentityConstraint2ValueStoreMap.put(toHash, keyValueStore); } else { keyValueStore.clear(); } fValueStores.addElement(keyValueStore); break; case (IdentityConstraint.IC_KEYREF): // initialize value stores for keyRef fields KeyRef keyRef = (KeyRef)icArray[i]; toHash = new LocalIDKey(keyRef, fElementDepth); KeyRefValueStore keyRefValueStore = (KeyRefValueStore)fIdentityConstraint2ValueStoreMap.get(toHash); if (keyRefValueStore == null) { keyRefValueStore = new KeyRefValueStore(keyRef, null); fIdentityConstraint2ValueStoreMap.put(toHash, keyRefValueStore); } else { keyRefValueStore.clear(); } fValueStores.addElement(keyRefValueStore); break; } } } // initValueStoresFor(XSElementDecl) /** Returns the value store associated to the specified IdentityConstraint. */ public ValueStoreBase getValueStoreFor(IdentityConstraint id, int initialDepth) { ValueStoreBase vb = (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(new LocalIDKey(id, initialDepth)); // vb should *never* be null! return vb; } // getValueStoreFor(IdentityConstraint, int):ValueStoreBase /** Returns the global value store associated to the specified IdentityConstraint. */ public ValueStoreBase getGlobalValueStoreFor(IdentityConstraint id) { return(ValueStoreBase)fGlobalIDConstraintMap.get(id); } // getValueStoreFor(IdentityConstraint):ValueStoreBase // This method takes the contents of the (local) ValueStore // associated with id and moves them into the global // hashtable, if id is a <unique> or a <key>. // If it's a <keyRef>, then we leave it for later. public void transplant(IdentityConstraint id, int initialDepth) { ValueStoreBase newVals = (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(new LocalIDKey(id, initialDepth)); if (id.getCategory() == IdentityConstraint.IC_KEYREF) return; ValueStoreBase currVals = (ValueStoreBase)fGlobalIDConstraintMap.get(id); if (currVals != null) { currVals.append(newVals); fGlobalIDConstraintMap.put(id, currVals); } else fGlobalIDConstraintMap.put(id, newVals); } // transplant(id) /** Check identity constraints. */ public void endDocument() { int count = fValueStores.size(); for (int i = 0; i < count; i++) { ValueStoreBase valueStore = (ValueStoreBase)fValueStores.elementAt(i); valueStore.endDocument(); } } // endDocument() // Object methods /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { return s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { return s.substring(index2 + 1); } return s; } // toString():String } // class ValueStoreCache // utility classes /** * Ordered hashtable. This class acts as a hashtable with * <code>put()</code> and <code>get()</code> operations but also * allows values to be queried via the order that they were * added to the hashtable. * <p> * <strong>Note:</strong> This class does not perform any error * checking. * <p> * <strong>Note:</strong> This class is <em>not</em> efficient but * is assumed to be used for a very small set of values. * * @author Andy Clark, IBM */ static final class OrderedHashtable implements Cloneable { // Data /** Size. */ private int fSize; /** Hashtable entries. */ private Entry[] fEntries = null; // Public methods /** Returns the number of entries in the hashtable. */ public int size() { return fSize; } // size():int /** Puts an entry into the hashtable. */ public void put(Field key, IDValue value) { int index = indexOf(key); if (index == -1) { ensureCapacity(fSize); index = fSize++; fEntries[index].key = key; } fEntries[index].value = value; } // put(Field,String) /** Returns the value associated to the specified key. */ public IDValue get(Field key) { return fEntries[indexOf(key)].value; } // get(Field):String /** Returns the index of the entry with the specified key. */ public int indexOf(Field key) { for (int i = 0; i < fSize; i++) { // NOTE: Only way to be sure that the keys are the // same is by using a reference comparison. In // order to rely on the equals method, each // field would have to take into account its // position in the identity constraint, the // identity constraint, the declaring element, // and the grammar that it is defined in. // Otherwise, you have the possibility that // the equals method would return true for two // fields that look *very* similar. // The reference compare isn't bad, actually, // because the field objects are cacheable. -Ac if (fEntries[i].key == key) { return i; } } return -1; } // indexOf(Field):int /** Returns the key at the specified index. */ public Field keyAt(int index) { return fEntries[index].key; } // keyAt(int):Field /** Returns the value at the specified index. */ public IDValue valueAt(int index) { return fEntries[index].value; } // valueAt(int):String /** Removes all of the entries from the hashtable. */ public void clear() { fSize = 0; } // clear() // Private methods /** Ensures the capacity of the entries array. */ private void ensureCapacity(int size) { // sizes int osize = -1; int nsize = -1; // create array if (fEntries == null) { osize = 0; nsize = 2; fEntries = new Entry[nsize]; } // resize array else if (fEntries.length <= size) { osize = fEntries.length; nsize = 2 * osize; Entry[] array = new Entry[nsize]; System.arraycopy(fEntries, 0, array, 0, osize); fEntries = array; } // create new entries for (int i = osize; i < nsize; i++) { fEntries[i] = new Entry(); } } // ensureCapacity(int) // Cloneable methods /** Clones this object. */ public Object clone() { OrderedHashtable hashtable = new OrderedHashtable(); for (int i = 0; i < fSize; i++) { hashtable.put(fEntries[i].key, fEntries[i].value); } return hashtable; } // clone():Object // Object methods /** Returns a string representation of this object. */ public String toString() { if (fSize == 0) { return "[]"; } StringBuffer str = new StringBuffer(); str.append('['); for (int i = 0; i < fSize; i++) { if (i > 0) { str.append(','); } str.append('{'); str.append(fEntries[i].key); str.append(','); str.append(fEntries[i].value); str.append('}'); } str.append(']'); return str.toString(); } // toString():String // Classes /** * Hashtable entry. */ public static final class Entry { // Data /** Key. */ public Field key; /** Value. */ public IDValue value; } // class Entry } // class OrderedHashtable // the purpose of this class is to enable IdentityConstraint,int // pairs to be used easily as keys in Hashtables. protected class LocalIDKey { private IdentityConstraint fId; private int fDepth; public LocalIDKey (IdentityConstraint id, int depth) { fId = id; fDepth = depth; } // init(IdentityConstraint, int) // object method public int hashCode() { return fId.hashCode()+fDepth; } public boolean equals(Object localIDKey) { if(localIDKey instanceof LocalIDKey) { LocalIDKey lIDKey = (LocalIDKey)localIDKey; return (lIDKey.fId == fId && lIDKey.fDepth == fDepth); } return false; } } // class LocalIDKey } // class SchemaValidator
package org.yamcs.tctm; import java.io.IOException; import java.net.ConnectException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.yamcs.ConfigurationException; import org.yamcs.YConfiguration; import org.yamcs.YamcsServer; import org.yamcs.cmdhistory.CommandHistoryPublisher; import org.yamcs.commanding.PreparedCommand; import org.yamcs.parameter.ParameterValue; import org.yamcs.parameter.SystemParametersCollector; import org.yamcs.parameter.SystemParametersProducer; import org.yamcs.time.TimeService; import org.yamcs.utils.LoggingUtils; import org.yamcs.utils.TimeEncoding; import org.yamcs.utils.YObjectLoader; import com.google.common.util.concurrent.AbstractService; import com.google.common.util.concurrent.RateLimiter; /** * Sends raw packets on Tcp socket. * * @author nm * */ public class TcpTcDataLink extends AbstractService implements Runnable, TcDataLink, SystemParametersProducer { protected SocketChannel socketChannel = null; protected String host = "whirl"; protected int port = 10003; protected CommandHistoryPublisher commandHistoryListener; protected Selector selector; SelectionKey selectionKey; protected ScheduledThreadPoolExecutor timer; protected volatile boolean disabled = false; protected BlockingQueue<PreparedCommand> commandQueue; RateLimiter rateLimiter; protected volatile long tcCount; private String sv_linkStatus_id, sp_dataCount_id; private SystemParametersCollector sysParamCollector; protected final Logger log; private final String yamcsInstance; private final String name; TimeService timeService; static final PreparedCommand SIGNAL_QUIT = new PreparedCommand(new byte[0]); TcDequeueAndSend tcSender; CommandPostprocessor cmdPostProcessor; public TcpTcDataLink(String yamcsInstance, String name, Map<String, Object> config) throws ConfigurationException { log = LoggingUtils.getLogger(this.getClass(), yamcsInstance); this.yamcsInstance = yamcsInstance; this.name = name; configure(yamcsInstance, config); timeService = YamcsServer.getTimeService(yamcsInstance); } public TcpTcDataLink(String yamcsInstance, String name, String spec) throws ConfigurationException { this(yamcsInstance, name, YConfiguration.getConfiguration("tcp").getMap(spec)); } private void configure(String yamcsInstance, Map<String, Object> config) { if(config.containsKey("tcHost")) {//this is when the config is specified in tcp.yaml host = YConfiguration.getString(config, "tcHost"); port = YConfiguration.getInt(config, "tcPort"); } else { host = YConfiguration.getString(config, "host"); port = YConfiguration.getInt(config, "port"); } initPostprocessor(yamcsInstance, config); if (config.containsKey("tcQueueSize")) { commandQueue = new LinkedBlockingQueue<>(YConfiguration.getInt(config, "tcQueueSize")); } else { commandQueue = new LinkedBlockingQueue<>(); } if (config.containsKey("tcMaxRate")) { rateLimiter = RateLimiter.create( YConfiguration.getInt(config, "tcMaxRate")); } } protected long getCurrentTime() { if (timeService != null) { return timeService.getMissionTime(); } else { return TimeEncoding.getWallclockTime(); } } @Override protected void doStart() { setupSysVariables(); this.timer = new ScheduledThreadPoolExecutor(2); openSocket(); tcSender = new TcDequeueAndSend(); timer.execute(tcSender); timer.scheduleAtFixedRate(this, 10L, 10L, TimeUnit.SECONDS); notifyStarted(); } protected void initPostprocessor(String instance, Map<String, Object> args) { String commandPostprocessorClassName = IssCommandPostprocessor.class.getName(); Object commandPostprocessorArgs = null; if(args!=null) { commandPostprocessorClassName = YConfiguration.getString(args, "commandPostprocessorClassName", IssCommandPostprocessor.class.getName()); commandPostprocessorArgs = args.get("commandPostprocessorArgs"); } try { if (commandPostprocessorArgs != null) { cmdPostProcessor = YObjectLoader.loadObject(commandPostprocessorClassName, instance, commandPostprocessorArgs); } else { cmdPostProcessor = YObjectLoader.loadObject(commandPostprocessorClassName, instance); } } catch (ConfigurationException e) { log.error("Cannot instantiate the command postprocessor", e); throw e; } catch (IOException e) { log.error("Cannot instantiate the command postprocessor", e); throw new ConfigurationException(e); } } /** * attempts to open the socket if not already open and returns true if its open at the end of the call * @return */ protected synchronized boolean openSocket() { if(isSocketOpen()) { return true; } try { InetAddress address = InetAddress.getByName(host); selector = Selector.open(); socketChannel = SocketChannel.open(new InetSocketAddress(address, port)); socketChannel.configureBlocking(false); socketChannel.socket().setKeepAlive(true); selectionKey = socketChannel.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ); log.info("TC connection established to {}:{}", host, port); return true; } catch (IOException e) { String exc = (e instanceof ConnectException) ? ((ConnectException) e).getMessage() : e.toString(); log.info("Cannot open TC connection to {}:{} '{}'. Retrying in 10s", host, port, exc.toString()); try { socketChannel.close(); } catch (Exception e1) { } try { selector.close(); } catch (Exception e1) { } socketChannel = null; } return false; } protected void disconnect() { if (socketChannel == null) { return; } try { socketChannel.close(); selector.close(); socketChannel = null; } catch (IOException e) { log.warn("Exception caught when checking if the socket to {}:{} is open", host, port, e); } } /** * we check if the socket is open by trying a select on the read part of it * * @return */ private boolean isSocketOpen() { if (socketChannel == null) { return false; } final ByteBuffer bb = ByteBuffer.allocate(16); boolean connected = false; try { selector.select(); if (selectionKey.isReadable()) { int read = socketChannel.read(bb); if (read > 0) { log.info("Data read on the TC socket to {}:{}!! : {}", host, port, bb); connected = true; } else if (read < 0) { log.warn("TC socket to {}:{} has been closed", host, port); socketChannel.close(); selector.close(); socketChannel = null; connected = false; } } else if (selectionKey.isWritable()) { connected = true; } else { log.warn("The TC socket to {}:{} is neither writable nor readable", host, port); connected = false; } } catch (IOException e) { log.warn("Exception caught when checking if the socket to {}:{} is open:", host, port, e); connected = false; } return connected; } /** * Sends */ @Override public void sendTc(PreparedCommand pc) { if (disabled) { log.warn("TC disabled, ignoring command {}", pc.getCommandId()); return; } if (!commandQueue.offer(pc)) { log.warn("Cannot put command {} in the queue, because it's full; sending NACK", pc); commandHistoryListener.publishWithTime(pc.getCommandId(), "Acknowledge_Sent", getCurrentTime(), "NOK"); } } @Override public void setCommandHistoryPublisher(CommandHistoryPublisher commandHistoryListener) { this.commandHistoryListener = commandHistoryListener; cmdPostProcessor.setCommandHistoryPublisher(commandHistoryListener); } @Override public Status getLinkStatus() { if (disabled) { return Status.DISABLED; } if (isSocketOpen()) { return Status.OK; } else { return Status.UNAVAIL; } } @Override public String getDetailedStatus() { if (disabled) return String.format("DISABLED (should connect to %s:%d)", host, port); if (isSocketOpen()) { return String.format("OK, connected to %s:%d", host, port); } else { return String.format("Not connected to %s:%d", host, port); } } @Override public void disable() { disabled = true; if (isRunning()) { disconnect(); } } @Override public void enable() { disabled = false; } @Override public boolean isDisabled() { return disabled; } @Override public void run() { if (!isRunning() || disabled) { return; } openSocket(); } @Override public void doStop() { disconnect(); commandQueue.clear(); commandQueue.offer(SIGNAL_QUIT); timer.shutdownNow(); notifyStopped(); } private class TcDequeueAndSend implements Runnable { PreparedCommand pc; @Override public void run() { while (true) { try { pc = commandQueue.take(); if(pc==SIGNAL_QUIT) { break; } if(rateLimiter!=null) { rateLimiter.acquire(); } send(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Send command interrupted while waiting for the queue.", e); return; } catch (Exception e) { log.error("Error when sending command: ", e); throw e; } } } public void send() { byte[] binary = cmdPostProcessor.process(pc); int retries = 5; boolean sent = false; ByteBuffer bb = ByteBuffer.wrap(binary); bb.rewind(); while (!sent && (retries > 0)) { if (openSocket()) { try { socketChannel.write(bb); tcCount++; sent = true; } catch (IOException e) { log.warn("Error writing to TC socket to {}:{} : {}", host, port, e.getMessage()); try { if (socketChannel.isOpen()) { socketChannel.close(); } selector.close(); socketChannel = null; } catch (IOException e1) { e1.printStackTrace(); } } } retries if (!sent && (retries > 0)) { try { log.warn("Command not sent, retrying in 2 seconds"); Thread.sleep(2000); } catch (InterruptedException e) { log.warn("exception {} thrown when sleeping 2 sec", e.toString()); Thread.currentThread().interrupt(); } } } if (sent) { commandHistoryListener.publishWithTime(pc.getCommandId(), "Acknowledge_Sent", getCurrentTime(), "OK"); } else { commandHistoryListener.publishWithTime(pc.getCommandId(), "Acknowledge_Sent", getCurrentTime(), "NOK"); } } } @Override public long getDataCount() { return tcCount; } protected void setupSysVariables() { this.sysParamCollector = SystemParametersCollector.getInstance(yamcsInstance); if (sysParamCollector != null) { sysParamCollector.registerProducer(this); sv_linkStatus_id = sysParamCollector.getNamespace() + "/" + name + "/linkStatus"; sp_dataCount_id = sysParamCollector.getNamespace() + "/" + name + "/dataCount"; } else { log.info("System variables collector not defined for instance {} ", yamcsInstance); } } @Override public Collection<ParameterValue> getSystemParameters() { long time = getCurrentTime(); ParameterValue linkStatus = SystemParametersCollector.getPV(sv_linkStatus_id, time, getLinkStatus().name()); ParameterValue dataCount = SystemParametersCollector.getPV(sp_dataCount_id, time, getDataCount()); return Arrays.asList(linkStatus, dataCount); } }
package org.apache.xml.security.transforms; import java.util.Iterator; import java.util.HashMap; import java.io.InputStream; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.*; import org.xml.sax.SAXException; import org.apache.xml.security.c14n.*; import org.apache.xml.security.signature.XMLSignatureInput; import org.apache.xml.security.signature.XMLSignatureException; import org.apache.xml.security.exceptions.*; import org.apache.xml.security.utils.*; public class Transform extends SignatureElementProxy { /** {@link org.apache.log4j} logging facility */ static org.apache.log4j.Category cat = org.apache.log4j.Category.getInstance(Transform.class.getName()); /** Field _alreadyInitialized */ static boolean _alreadyInitialized = false; /** All available Transform classes are registered here */ static HashMap _transformHash = null; /** Field transformSpi */ protected TransformSpi transformSpi = null; /** * Constructs {@link Transform} * * @param doc the {@link Document} in which <code>Transform</code> will be placed * @param algorithmURI URI representation of <code>transfrom algorithm</code> will be specified as parameter of {@link #getInstance}, when generate. </br> * @param contextNodes the child node list of <code>Transform</code> element * @throws InvalidTransformException */ public Transform(Document doc, String algorithmURI, NodeList contextNodes) throws InvalidTransformException { super(doc, Constants._TAG_TRANSFORM); try { this._constructionElement.setAttribute(Constants._ATT_ALGORITHM, algorithmURI); String implementingClass = Transform.getImplementingClass(algorithmURI); cat.debug("Create URI \"" + algorithmURI + "\" class \"" + implementingClass + "\""); cat.debug("The NodeList is " + contextNodes); // create the custom Transform object this.transformSpi = (TransformSpi) Class.forName(implementingClass).newInstance(); this.transformSpi.setTransform(this); // give it to the current document if ((contextNodes != null) && (contextNodes.getLength() > 0)) { for (int i = 0; i < contextNodes.getLength(); i++) { this._constructionElement.appendChild(contextNodes.item(i)); } } } catch (ClassNotFoundException ex) { Object exArgs[] = { algorithmURI }; throw new InvalidTransformException( "signature.Transform.UnknownTransform", exArgs, ex); } catch (IllegalAccessException ex) { Object exArgs[] = { algorithmURI }; throw new InvalidTransformException( "signature.Transform.UnknownTransform", exArgs, ex); } catch (InstantiationException ex) { Object exArgs[] = { algorithmURI }; throw new InvalidTransformException( "signature.Transform.UnknownTransform", exArgs, ex); } } /** * * This constructor can only be called from the {@link Transforms} object, so * it's protected. * * @param element <code>ds:Transform</code> element * @param BaseURI the URI of the resource where the XML instance was stored * @throws InvalidTransformException * @throws TransformationException * @throws XMLSecurityException */ public Transform(Element element, String BaseURI) throws InvalidTransformException, TransformationException, XMLSecurityException { super(element, BaseURI, Constants._TAG_TRANSFORM); // retrieve Algorithm Attribute from ds:Transform String AlgorithmURI = element.getAttribute(Constants._ATT_ALGORITHM); if ((AlgorithmURI == null) || (AlgorithmURI.length() == 0)) { Object exArgs[] = { Constants._ATT_ALGORITHM, Constants._TAG_TRANSFORM }; throw new TransformationException("xml.WrongContent", exArgs); } try { String implementingClass = (String) _transformHash.get(AlgorithmURI); this.transformSpi = (TransformSpi) Class.forName(implementingClass).newInstance(); this.transformSpi.setTransform(this); } catch (ClassNotFoundException e) { Object exArgs[] = { AlgorithmURI }; throw new InvalidTransformException( "signature.Transform.UnknownTransform", exArgs); } catch (IllegalAccessException e) { Object exArgs[] = { AlgorithmURI }; throw new InvalidTransformException( "signature.Transform.UnknownTransform", exArgs); } catch (InstantiationException e) { Object exArgs[] = { AlgorithmURI }; throw new InvalidTransformException( "signature.Transform.UnknownTransform", exArgs); } } public static final Transform getInstance( Document doc, String algorithmURI) throws InvalidTransformException { return Transform.getInstance(doc, algorithmURI, (NodeList) null); } public static final Transform getInstance( Document doc, String algorithmURI, Element contextChild) throws InvalidTransformException { HelperNodeList contextNodes = new HelperNodeList(); contextNodes.appendChild(contextChild); return Transform.getInstance(doc, algorithmURI, contextNodes); } public static final Transform getInstance( Document doc, String algorithmURI, NodeList contextNodes) throws InvalidTransformException { return new Transform(doc, algorithmURI, contextNodes); } /** * Initalizes for this {@link Transform} * */ public static void init() { if (!_alreadyInitialized) { _transformHash = new HashMap(10); _alreadyInitialized = true; } } /** * Registers implementing class of the transfrom algorithm with algorithmURI * * @param algorithmURI algorithmURI URI representation of <code>transfrom algorithm</code> will be specified as parameter of {@link #getInstance}, when generate. </br> * @param implementingClass <code>implementingClass</code> the implementing class of {@link TransformSpi} * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered */ public static void register(String algorithmURI, String implementingClass) throws AlgorithmAlreadyRegisteredException { { // are we already registered? String registeredClass = Transform.getImplementingClass(algorithmURI); if ((registeredClass != null) && (registeredClass.length() != 0)) { Object exArgs[] = { algorithmURI, registeredClass }; throw new AlgorithmAlreadyRegisteredException( "algorithm.alreadyRegistered", exArgs); } Transform._transformHash.put(algorithmURI, implementingClass); } } /** * Returns the URI representation of Transformation algorithm * * @return the URI representation of Transformation algorithm */ public final String getURI() { return this._constructionElement.getAttribute(Constants._ATT_ALGORITHM); } /** * Transforms the input, and generats {@link XMLSignatureInput} as output. * * @param input input {@link XMLSignatureInput} which can supplied Octect Stream and NodeSet as Input of Transformation * @return the {@link XMLSignatureInput} class as the result of transformation * @throws CanonicalizationException * @throws IOException * @throws InvalidCanonicalizerException * @throws TransformationException */ public XMLSignatureInput performTransform(XMLSignatureInput input) throws IOException, CanonicalizationException, InvalidCanonicalizerException, TransformationException { XMLSignatureInput result = null; try { result = transformSpi.enginePerformTransform(input); } catch (ParserConfigurationException ex) { Object exArgs[] = { this.getURI(), "ParserConfigurationException" }; throw new CanonicalizationException( "signature.Transform.ErrorDuringTransform", exArgs, ex); } catch (SAXException ex) { Object exArgs[] = { this.getURI(), "SAXException" }; throw new CanonicalizationException( "signature.Transform.ErrorDuringTransform", exArgs, ex); } return result; } /** * Method getImplementingClass * * @param URI * @return */ private static String getImplementingClass(String URI) { try { Iterator i = Transform._transformHash.keySet().iterator(); while (i.hasNext()) { String key = (String) i.next(); if (key.equals(URI)) { return (String) Transform._transformHash.get(key); } } } catch (NullPointerException ex) {} return null; } static { org.apache.xml.security.Init.init(); } }
package org.biojava.bio.structure.io; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.biojava.bio.structure.Structure; import org.biojava.bio.structure.io.StructureIOFile; import org.biojava.bio.structure.io.mmcif.MMcifParser; import org.biojava.bio.structure.io.mmcif.SimpleMMcifConsumer; import org.biojava.bio.structure.io.mmcif.SimpleMMcifParser; import org.biojava.utils.io.InputStreamProvider; /** How to parse an mmCif file: * <pre> public static void main(String[] args){ String filename = "/path/to/something.cif.gz" ; StructureIOFile reader = new MMCIFFileReader(); try{ Structure struc = reader.getStructure(filename); System.out.println(struc); } catch (Exception e) { e.printStackTrace(); } } </pre> * * @author Andreas Prlic * @since 1.7 * */ public class MMCIFFileReader implements StructureIOFile { String path; List<String> extensions; boolean autoFetch; public static void main(String[] args){ String filename = "/Users/andreas/WORK/PDB/mmcif_files/a9/2a9w.cif.gz" ; StructureIOFile reader = new MMCIFFileReader(); reader.setAutoFetch(true); try{ Structure struc = reader.getStructure(filename); System.out.println(struc); } catch (Exception e) { e.printStackTrace(); } } public MMCIFFileReader(){ extensions = new ArrayList<String>(); path = "" ; extensions.add(".cif"); extensions.add(".mmcif"); extensions.add(".cif.gz"); extensions.add(".mmcif.gz"); autoFetch = false; } public void addExtension(String ext) { extensions.add(ext); } public void clearExtensions(){ extensions.clear(); } /** Opens filename, parses it and returns * a Structure object . * @param filename a String * @return the Structure object * @throws IOException ... */ public Structure getStructure(String filename) throws IOException { File f = new File(filename); return getStructure(f); } /** Opens filename, parses it and returns a Structure object. * * @param filename a File object * @return the Structure object * @throws IOException ... */ public Structure getStructure(File filename) throws IOException { InputStreamProvider isp = new InputStreamProvider(); InputStream inStream = isp.getInputStream(filename); return parseFromInputStream(inStream); } private Structure parseFromInputStream(InputStream inStream) throws IOException{ MMcifParser parser = new SimpleMMcifParser(); SimpleMMcifConsumer consumer = new SimpleMMcifConsumer(); // The Consumer builds up the BioJava - structure object. // you could also hook in your own and build up you own data model. parser.addMMcifConsumer(consumer); parser.parse(new BufferedReader(new InputStreamReader(inStream))); // now get the protein structure. Structure cifStructure = consumer.getStructure(); return cifStructure; } public void setPath(String path) { this.path = path; } public String getPath() { return path; } /** Get a structure by PDB code. This works if a PATH has been set via setPath, or if setAutoFetch has been set to true. * * @param pdbId a 4 letter PDB code. */ public Structure getStructureById(String pdbId) throws IOException { InputStream inStream = getInputStream(pdbId); return parseFromInputStream(inStream); } private InputStream getInputStream(String pdbId) throws IOException{ InputStream inputStream =null; String pdbFile = null ; File f = null ; // this are the possible PDB file names... String fpath = path+"/"+pdbId; //String ppath = path +"/pdb"+pdbId; String[] paths = new String[]{fpath,}; for ( int p=0;p<paths.length;p++ ){ String testpath = paths[p]; //System.out.println(testpath); for (int i=0 ; i<extensions.size();i++){ String ex = (String)extensions.get(i) ; //System.out.println("PDBFileReader testing: "+testpath+ex); f = new File(testpath+ex) ; if ( f.exists()) { //System.out.println("found!"); pdbFile = testpath+ex ; InputStreamProvider isp = new InputStreamProvider(); inputStream = isp.getInputStream(pdbFile); break; } if ( pdbFile != null) break; } } if ( pdbFile == null ) { if ( autoFetch) return downloadAndGetInputStream(pdbId); String message = "no structure with PDB code " + pdbId + " found!" ; throw new IOException (message); } return inputStream ; } private InputStream downloadAndGetInputStream(String pdbId) throws IOException{ //PDBURLReader reader = new PDBURLReader(); //Structure s = reader.getStructureById(pdbId); File tmp = downloadPDB(pdbId); if ( tmp != null ) { InputStreamProvider prov = new InputStreamProvider(); return prov.getInputStream(tmp); } else { throw new IOException("could not find PDB " + pdbId + " in file system and also could not download"); } } private File downloadPDB(String pdbId){ File tempFile = new File(path+"/"+pdbId+".cif.gz"); File pdbHome = new File(path); if ( ! pdbHome.canWrite() ){ System.err.println("can not write to " + pdbHome); return null; } String ftp = String.format("ftp://ftp.wwpdb.org/pub/pdb/data/structures/all/mmCIF/%s.cif.gz", pdbId.toLowerCase()); System.out.println("Fetching " + ftp); try { URL url = new URL(ftp); InputStream conn = url.openStream(); // prepare destination System.out.println("writing to " + tempFile); FileOutputStream outPut = new FileOutputStream(tempFile); GZIPOutputStream gzOutPut = new GZIPOutputStream(outPut); PrintWriter pw = new PrintWriter(gzOutPut); BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(new GZIPInputStream(conn))); String line; while ((line = fileBuffer.readLine()) != null) { pw.println(line); } pw.flush(); pw.close(); outPut.close(); conn.close(); } catch (Exception e){ e.printStackTrace(); return null; } return tempFile; } public boolean isAutoFetch() { return autoFetch; } public void setAutoFetch(boolean autoFetch) { this.autoFetch = autoFetch; } }
package org.helioviewer.jhv.database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import javax.annotation.Nonnull; import org.helioviewer.jhv.base.Pair; import org.helioviewer.jhv.log.Log; import org.helioviewer.jhv.threads.JHVThread; public class SourcesDatabase extends Thread { private static class NamedDbThreadFactory extends JHVThread.NamedThreadFactory { NamedDbThreadFactory(String _name) { super(_name); } @Override public SourcesDatabase newThread(@Nonnull Runnable r) { SourcesDatabase thread = new SourcesDatabase(r, name); thread.setDaemon(true); return thread; } } private static final ExecutorService executor = Executors.newSingleThreadExecutor(new NamedDbThreadFactory("SourcesDatabase")); private static Connection connection; private static PreparedStatement insert; private static PreparedStatement select; private SourcesDatabase(Runnable r, String name) { super(r, name); try { connection = DriverManager.getConnection("jdbc:sqlite::memory:"); try (Statement create = connection.createStatement()) { create.setQueryTimeout(30); create.executeUpdate("drop table if exists Sources"); // debug create.executeUpdate("CREATE TABLE Sources(sourceId INTEGER, server STRING, observatory STRING, dataset STRING, start INTEGER, end INTEGER, UNIQUE(sourceId, server) ON CONFLICT REPLACE)"); } insert = connection.prepareStatement("INSERT INTO Sources(sourceId, server, observatory, dataset, start, end) VALUES(?,?,?,?,?,?)"); insert.setQueryTimeout(30); select = connection.prepareStatement("SELECT sourceId,server FROM Sources WHERE server=? AND observatory LIKE ? AND dataset LIKE ?"); select.setQueryTimeout(30); } catch (SQLException e) { Log.error("Could not create database connection", e); try { connection.close(); } catch (Exception ignore) { } connection = null; } } public static void insert(int sourceId, @Nonnull String server, @Nonnull String observatory, @Nonnull String dataset, long start, long end) { FutureTask<Void> ft = new FutureTask<>(new Insert(sourceId, server, observatory, dataset, start, end)); executor.execute(ft); /* try { ft.get(); } catch (InterruptedException | ExecutionException e) { e.getCause().printStackTrace(); } */ } private static class Insert implements Callable<Void> { private final int sourceId; private final String server; private final String observatory; private final String dataset; private final long start; private final long end; Insert(int _sourceId, @Nonnull String _server, @Nonnull String _observatory, @Nonnull String _dataset, long _start, long _end) { sourceId = _sourceId; server = _server; observatory = _observatory; dataset = _dataset; start = _start; end = _end; } @Override public Void call() { if (connection == null) return null; try { insert.setInt(1, sourceId); insert.setString(2, server); insert.setString(3, observatory); insert.setString(4, dataset); insert.setLong(5, start); insert.setLong(6, end); insert.executeUpdate(); } catch (SQLException e) { Log.error("Failed to insert", e); } return null; } } public static ArrayList<Pair<Integer, String>> select(@Nonnull String server, @Nonnull String observatory, @Nonnull String dataset) { FutureTask<ArrayList<Pair<Integer, String>>> ft = new FutureTask<>(new Select(server, observatory, dataset)); executor.execute(ft); try { return ft.get(); } catch (InterruptedException | ExecutionException e) { e.getCause().printStackTrace(); } return new ArrayList<>(); } private static class Select implements Callable<ArrayList<Pair<Integer, String>>> { private final String server; private final String observatory; private final String dataset; Select(@Nonnull String _server, @Nonnull String _observatory, @Nonnull String _dataset) { server = _server; observatory = _observatory; dataset = _dataset; } @Override public ArrayList<Pair<Integer, String>> call() { ArrayList<Pair<Integer, String>> res = new ArrayList<>(); if (connection == null) return res; try { select.setString(1, server); select.setString(2, '%' + observatory + '%'); select.setString(3, '%' + dataset + '%'); try (ResultSet rs = select.executeQuery()) { while (rs.next()) res.add(new Pair<>(rs.getInt(1), rs.getString(2))); } } catch (SQLException e) { Log.error("Failed to select", e); } return res; } } private SourcesDatabase() { } }
package org.jitsi.impl.neomedia; import java.awt.*; import java.net.*; import java.util.*; import javax.media.format.*; import javax.media.control.*; import javax.media.protocol.*; import javax.media.rtp.*; import net.sf.fmj.media.rtp.*; import org.jitsi.impl.neomedia.device.*; import org.jitsi.service.neomedia.*; import org.jitsi.service.neomedia.control.*; import org.jitsi.service.neomedia.format.*; import org.jitsi.util.*; /** * Class used to compute stats concerning a MediaStream. * * @author Vincent Lucas * @author Boris Grozev */ public class MediaStreamStatsImpl implements MediaStreamStats { /** * The <tt>Logger</tt> used by the <tt>MediaStreamImpl</tt> class and its * instances for logging output. */ private static final Logger logger = Logger.getLogger(MediaStreamStatsImpl.class); /** * Enumeration of the direction (DOWNLOAD or UPLOAD) used for the stats. */ private enum StreamDirection { DOWNLOAD, UPLOAD } /** * The source data stream to analyze in order to compute the stats. */ private final MediaStreamImpl mediaStreamImpl; /** * The last time these stats have been updated. */ private long updateTimeMs; /** * The last number of received/sent packets. */ private long[] nbPackets = {0, 0}; /** * The last number of sent packets when the last feedback has been received. * This counter is used to compute the upload loss rate. */ private long uploadFeedbackNbPackets = 0; /** * The last number of download/upload lost packets. */ private long[] nbLost = {0, 0}; /** * The total number of discarded packets */ private long nbDiscarded = 0; /** * The number of packets for which FEC data was decoded. This is only */ private long nbFec = 0; /** * The last number of received/sent Bytes. */ private long[] nbByte = {0, 0}; /** * The last download/upload loss rate computed (in %). */ private double[] percentLoss = {0, 0}; /** * The last percent of discarded packets */ private double percentDiscarded = 0; /** * The last used bandwidth computed in download/upload (in Kbit/s). */ private double[] rateKiloBitPerSec = {0, 0}; /** * The last jitter received/sent in a RTCP feedback (in RTP timestamp * units). */ private double[] jitterRTPTimestampUnits = {0, 0}; /** * The RTT computed with the RTCP feedback (cf. RFC3550, section 6.4.1, * subsection "delay since last SR (DLSR): 32 bits"). * -1 if the RTT has not been computed yet. Otherwise the RTT in ms. */ private long rttMs = -1; /** * Creates a new instance of stats concerning a MediaStream. * * @param mediaStreamImpl The MediaStreamImpl used to compute the stats. */ public MediaStreamStatsImpl(MediaStreamImpl mediaStreamImpl) { this.updateTimeMs = System.currentTimeMillis(); this.mediaStreamImpl = mediaStreamImpl; } /** * Computes and updates information for a specific stream. */ public void updateStats() { // Gets the current time. long currentTimeMs = System.currentTimeMillis(); // UPdates stats for the download stream. this.updateStreamDirectionStats( StreamDirection.DOWNLOAD, currentTimeMs); // UPdates stats for the upload stream. this.updateStreamDirectionStats( StreamDirection.UPLOAD, currentTimeMs); // Saves the last update values. this.updateTimeMs = currentTimeMs; } /** * Computes and updates information for a specific stream. * * @param streamDirection The stream direction (DOWNLOAD or UPLOAD) of the * stream from which this function updates the stats. * @param currentTimeMs The current time in ms. */ private void updateStreamDirectionStats( StreamDirection streamDirection, long currentTimeMs) { int streamDirectionIndex = streamDirection.ordinal(); // Gets the current number of packets correctly received since the // beginning of this stream. long newNbRecv = this.getNbPDU(streamDirection); // Gets the number of byte received/sent since the beginning of this // stream. long newNbByte = this.getNbBytes(streamDirection); // Computes the number of update steps which has not been done since // last update. long nbSteps = newNbRecv - this.nbPackets[streamDirectionIndex]; // Even if the remote peer does not send any packets (i.e. is // microphone is muted), Jitsi must updates it stats. Thus, Jitsi // computes a number of steps equivalent as if Jitsi receives a packet // each 20ms (default value). if(nbSteps == 0) { nbSteps = (currentTimeMs - this.updateTimeMs) / 20; } // The upload percentLoss is only computed when a new RTCP feedback is // received. This is not the case for the download percentLoss which is // updated for each new RTP packet received. // Computes the loss rate for this stream. if(streamDirection == StreamDirection.DOWNLOAD) { // Gets the current number of losses in download since the beginning // of this stream. long newNbLost = this.getDownloadNbPDULost() - this.nbLost[streamDirectionIndex]; updateNbLoss(streamDirection, newNbLost, nbSteps + newNbLost); long newNbDiscarded = this.getNbDiscarded() - this.nbDiscarded; updateNbDiscarded(newNbDiscarded, nbSteps + newNbDiscarded); } // Computes the bandwidth used by this stream. double newRateKiloBitPerSec = MediaStreamStatsImpl.computeRateKiloBitPerSec( newNbByte - this.nbByte[streamDirectionIndex], currentTimeMs - this.updateTimeMs); this.rateKiloBitPerSec[streamDirectionIndex] = MediaStreamStatsImpl.computeEWMA( nbSteps, this.rateKiloBitPerSec[streamDirectionIndex], newRateKiloBitPerSec); // Saves the last update values. this.nbPackets[streamDirectionIndex] = newNbRecv; this.nbByte[streamDirectionIndex] = newNbByte; updateNbFec(); } /** * Returns the local IP address of the MediaStream. * * @return the local IP address of the stream. */ public String getLocalIPAddress() { InetSocketAddress mediaStreamLocalDataAddress = mediaStreamImpl.getLocalDataAddress(); return (mediaStreamLocalDataAddress == null) ? null : mediaStreamLocalDataAddress.getAddress().getHostAddress(); } /** * Returns the local port of the MediaStream. * * @return the local port of the stream. */ public int getLocalPort() { InetSocketAddress mediaStreamLocalDataAddress = mediaStreamImpl.getLocalDataAddress(); return (mediaStreamLocalDataAddress == null) ? -1 : mediaStreamLocalDataAddress.getPort(); } /** * Returns the remote IP address of the MediaStream. * * @return the remote IP address of the stream. */ public String getRemoteIPAddress() { MediaStreamTarget mediaStreamTarget = mediaStreamImpl.getTarget(); // Gets this stream IP address endpoint. Stops if the endpoint is // disconnected. return (mediaStreamTarget == null) ? null : mediaStreamTarget.getDataAddress().getAddress() .getHostAddress(); } /** * Returns the remote port of the MediaStream. * * @return the remote port of the stream. */ public int getRemotePort() { MediaStreamTarget mediaStreamTarget = mediaStreamImpl.getTarget(); // Gets this stream port endpoint. Stops if the endpoint is // disconnected. return (mediaStreamTarget == null) ? -1 : mediaStreamTarget.getDataAddress().getPort(); } /** * Returns the MediaStream enconding. * * @return the encoding used by the stream. */ public String getEncoding() { MediaFormat format = mediaStreamImpl.getFormat(); return (format == null) ? null : format.getEncoding(); } /** * Returns the MediaStream enconding rate (in Hz).. * * @return the encoding rate used by the stream. */ public String getEncodingClockRate() { MediaFormat format = mediaStreamImpl.getFormat(); return (format == null) ? null : format.getRealUsedClockRateString(); } /** * Returns the upload video format if this stream uploads a video, or null * if not. * * @return the upload video format if this stream uploads a video, or null * if not. */ private VideoFormat getUploadVideoFormat() { MediaDeviceSession deviceSession = mediaStreamImpl.getDeviceSession(); return (deviceSession instanceof VideoMediaDeviceSession) ? ((VideoMediaDeviceSession) deviceSession) .getSentVideoFormat() : null; } /** * Returns the download video format if this stream downloads a video, or * null if not. * * @return the download video format if this stream downloads a video, or * null if not. */ private VideoFormat getDownloadVideoFormat() { MediaDeviceSession deviceSession = mediaStreamImpl.getDeviceSession(); return (deviceSession instanceof VideoMediaDeviceSession) ? ((VideoMediaDeviceSession) deviceSession) .getReceivedVideoFormat() : null; } /** * Returns the upload video size if this stream uploads a video, or null if * not. * * @return the upload video size if this stream uploads a video, or null if * not. */ public Dimension getUploadVideoSize() { VideoFormat format = getUploadVideoFormat(); return (format == null) ? null : format.getSize(); } /** * Returns the download video size if this stream downloads a video, or * null if not. * * @return the download video size if this stream downloads a video, or null * if not. */ public Dimension getDownloadVideoSize() { VideoFormat format = getDownloadVideoFormat(); return (format == null) ? null : format.getSize(); } /** * Returns the percent loss of the download stream. * * @return the last loss rate computed (in %). */ public double getDownloadPercentLoss() { return this.percentLoss[StreamDirection.DOWNLOAD.ordinal()]; } /** * Returns the percent of discarded packets * * @return the percent of discarded packets */ public double getPercentDiscarded() { return percentDiscarded; } /** * Returns the percent loss of the upload stream. * * @return the last loss rate computed (in %). */ public double getUploadPercentLoss() { return this.percentLoss[StreamDirection.UPLOAD.ordinal()]; } /** * Returns the bandwidth used by this download stream. * * @return the last used download bandwidth computed (in Kbit/s). */ public double getDownloadRateKiloBitPerSec() { return this.rateKiloBitPerSec[StreamDirection.DOWNLOAD.ordinal()]; } /** * Returns the bandwidth used by this download stream. * * @return the last used upload bandwidth computed (in Kbit/s). */ public double getUploadRateKiloBitPerSec() { return this.rateKiloBitPerSec[StreamDirection.UPLOAD.ordinal()]; } /** * Returns the jitter average of this download stream. * * @return the last jitter average computed (in ms). */ public double getDownloadJitterMs() { return this.getJitterMs(StreamDirection.DOWNLOAD); } /** * Returns the jitter average of this upload stream. * * @return the last jitter average computed (in ms). */ public double getUploadJitterMs() { return this.getJitterMs(StreamDirection.UPLOAD); } /** * Returns the jitter average of this upload/download stream. * * @param streamDirection The stream direction (DOWNLOAD or UPLOAD) of the * stream from which this function retrieve the jitter. * * @return the last jitter average computed (in ms). */ private double getJitterMs(StreamDirection streamDirection) { MediaFormat format = mediaStreamImpl.getFormat(); double clockRate; if (format == null) { MediaType mediaType = mediaStreamImpl.getMediaType(); clockRate = MediaType.VIDEO.equals(mediaType) ? 90000 : -1; } else clockRate = format.getClockRate(); if (clockRate <= 0) return -1; // RFC3550 says that concerning the RTP timestamp unit (cf. section 5.1 // RTP Fixed Header Fields, subsection timestamp: 32 bits): // As an example, for fixed-rate audio the timestamp clock would likely // increment by one for each sampling period. // Thus we take the jitter in RTP timestamp units, convert it to seconds // (/ clockRate) and finally converts it to milliseconds (* 1000). return (jitterRTPTimestampUnits[streamDirection.ordinal()] / clockRate) * 1000.0; } /** * Updates the jitter stream stats with the new feedback sent. * * @param feedback The last RTCP feedback sent by the MediaStream. * @param streamDirection The stream direction (DOWNLOAD or UPLOAD) of the * stream from which this function retrieve the jitter. */ private void updateJitterRTPTimestampUnits( RTCPFeedback feedback, StreamDirection streamDirection) { // Updates the download jitter in RTP timestamp units. // There is no need to compute a jitter average, since (cf. RFC3550, // section 6.4.1 SR: Sender Report RTCP Packet, subsection interarrival // jitter: 32 bits) the value contained in the RTCP sender report packet // contains a mean deviation of the jitter. this.jitterRTPTimestampUnits[streamDirection.ordinal()] = feedback.getJitter(); } /** * Updates this stream stats with the new feedback sent. * * @param feedback The last RTCP feedback sent by the MediaStream. */ public void updateNewSentFeedback(RTCPFeedback feedback) { updateJitterRTPTimestampUnits(feedback, StreamDirection.DOWNLOAD); // No need to update the download loss as we have a more accurate value // in the global reception stats, which are updated for each new packet // received. } /** * Updates this stream stats with the new feedback received. * * @param feedback The last RTCP feedback received by the MediaStream. */ public void updateNewReceivedFeedback(RTCPFeedback feedback) { StreamDirection streamDirection = StreamDirection.UPLOAD; updateJitterRTPTimestampUnits(feedback, streamDirection); // Updates the loss rate with the RTCP sender report feedback, since // this is the only information source available for the upload stream. long uploadNewNbRecv = feedback.getXtndSeqNum(); long newNbLost = feedback.getNumLost() - this.nbLost[streamDirection.ordinal()]; long nbSteps = uploadNewNbRecv - this.uploadFeedbackNbPackets; updateNbLoss(streamDirection, newNbLost, nbSteps); // Updates the upload loss counters. this.uploadFeedbackNbPackets = uploadNewNbRecv; // Computes RTT. this.rttMs = computeRTTInMs(feedback); } /** * Updates the number of loss for a given stream. * * @param streamDirection The stream direction (DOWNLOAD or UPLOAD) of the * stream from which this function updates the stats. * @param newNbLost The last update of the number of lost. * @param nbSteps The number of elapsed steps since the last number of loss * update. */ private void updateNbLoss( StreamDirection streamDirection, long newNbLost, long nbSteps) { int streamDirectionIndex = streamDirection.ordinal(); double newPercentLoss = MediaStreamStatsImpl.computePercentLoss( nbSteps, newNbLost); this.percentLoss[streamDirectionIndex] = MediaStreamStatsImpl.computeEWMA( nbSteps, this.percentLoss[streamDirectionIndex], newPercentLoss); // Saves the last update number download lost value. this.nbLost[streamDirectionIndex] += newNbLost; } /** * Computes the loss rate. * * @param nbLostAndRecv The number of lost and received packets. * @param nbLost The number of lost packets. * * @return The loss rate in percent. */ private static double computePercentLoss(long nbLostAndRecv, long nbLost) { if(nbLostAndRecv == 0) { return 0; } return ((double) 100 * nbLost) / ((nbLostAndRecv)); } /** * Computes the bandwidth usage in Kilo bits per seconds. * * @param nbByteRecv The number of Byte received. * @param callNbTimeMsSpent The time spent since the mediaStreamImpl is * connected to the endpoint. * * @return the bandwidth rate computed in Kilo bits per seconds. */ private static double computeRateKiloBitPerSec( long nbByteRecv, long callNbTimeMsSpent) { if(nbByteRecv == 0) { return 0; } return (nbByteRecv * 8.0 / 1000.0) / (callNbTimeMsSpent / 1000.0); } /** * Computes an Exponentially Weighted Moving Average (EWMA). Thus, the most * recent history has a more preponderant importance in the average * computed. * * @param nbStepSinceLastUpdate The number of step which has not been * computed since last update. In our case the number of packets received * since the last computation. * @param lastValue The value computed during the last update. * @param newValue The value newly computed. * * @return The EWMA average computed. */ private static double computeEWMA( long nbStepSinceLastUpdate, double lastValue, double newValue) { // For each new packet received the EWMA moves by a 0.1 coefficient. double EWMACoeff = 0.01 * nbStepSinceLastUpdate; // EWMA must be <= 1. if(EWMACoeff > 1) { EWMACoeff = 1.0; } return lastValue * (1.0 - EWMACoeff) + newValue * EWMACoeff; } /** * Returns the number of Protocol Data Units (PDU) sent/received since the * beginning of the session. * * @param streamDirection The stream direction (DOWNLOAD or UPLOAD) of the * stream from which this function retrieve the number of sent/received * packets. * * @return the number of packets sent/received for this stream. */ private long getNbPDU(StreamDirection streamDirection) { StreamRTPManager rtpManager = mediaStreamImpl.queryRTPManager(); long nbPDU = 0; if(rtpManager != null) { switch(streamDirection) { case UPLOAD: nbPDU = rtpManager.getGlobalTransmissionStats().getRTPSent(); break; case DOWNLOAD: GlobalReceptionStats globalReceptionStats = rtpManager.getGlobalReceptionStats(); nbPDU = globalReceptionStats.getPacketsRecd() - globalReceptionStats.getRTCPRecd(); break; } } return nbPDU; } /** * Returns the number of Protocol Data Units (PDU) lost in download since * the beginning of the session. * * @return the number of packets lost for this stream. */ private long getDownloadNbPDULost() { MediaDeviceSession devSession = mediaStreamImpl.getDeviceSession(); int nbLost = 0; if (devSession != null) { for(ReceiveStream receiveStream : devSession.getReceiveStreams()) nbLost += receiveStream.getSourceReceptionStats().getPDUlost(); } return nbLost; } /** * Returns the total number of Protocol Data Units (PDU) discarded by the * FMJ packet queue since the beginning of the session. It's the sum over * all <tt>ReceiveStream</tt>s of the <tt>MediaStream</tt> * * @return the number of discarded packets. */ public long getNbDiscarded() { int nbDiscarded = 0; for(PacketQueueControl pqc : getPacketQueueControls()) nbDiscarded =+ pqc.getDiscarded(); return nbDiscarded; } /** * Returns the number of Protocol Data Units (PDU) discarded by the * FMJ packet queue since the beginning of the session due to shrinking. * It's the sum over all <tt>ReceiveStream</tt>s of the <tt>MediaStream</tt> * * @return the number of discarded packets due to shrinking. */ public int getNbDiscardedShrink() { int nbDiscardedShrink = 0; for(PacketQueueControl pqc : getPacketQueueControls()) nbDiscardedShrink =+ pqc.getDiscardedShrink(); return nbDiscardedShrink; } /** * Returns the number of Protocol Data Units (PDU) discarded by the * FMJ packet queue since the beginning of the session because it was full. * It's the sum over all <tt>ReceiveStream</tt>s of the <tt>MediaStream</tt> * * @return the number of discarded packets because it was full. */ public int getNbDiscardedFull() { int nbDiscardedFull = 0; for(PacketQueueControl pqc : getPacketQueueControls()) nbDiscardedFull =+ pqc.getDiscardedFull(); return nbDiscardedFull; } /** * Returns the number of Protocol Data Units (PDU) discarded by the * FMJ packet queue since the beginning of the session because they were late. * It's the sum over all <tt>ReceiveStream</tt>s of the <tt>MediaStream</tt> * * @return the number of discarded packets because they were late. */ public int getNbDiscardedLate() { int nbDiscardedLate = 0; for(PacketQueueControl pqc : getPacketQueueControls()) nbDiscardedLate =+ pqc.getDiscardedLate(); return nbDiscardedLate; } /** * Returns the number of Protocol Data Units (PDU) discarded by the * FMJ packet queue since the beginning of the session during resets. * It's the sum over all <tt>ReceiveStream</tt>s of the <tt>MediaStream</tt> * * @return the number of discarded packets during resets. */ public int getNbDiscardedReset() { int nbDiscardedReset = 0; for(PacketQueueControl pqc : getPacketQueueControls()) nbDiscardedReset =+ pqc.getDiscardedReset(); return nbDiscardedReset; } /** * Returns the number of sent/received bytes since the beginning of the * session. * * @param streamDirection The stream direction (DOWNLOAD or UPLOAD) of the * stream from which this function retrieve the number of sent/received * bytes. * * @return the number of sent/received bytes for this stream. */ private long getNbBytes(StreamDirection streamDirection) { StreamRTPManager rtpManager = mediaStreamImpl.queryRTPManager(); long nbBytes = 0; if(rtpManager != null) { switch(streamDirection) { case DOWNLOAD: nbBytes = rtpManager.getGlobalReceptionStats().getBytesRecd(); break; case UPLOAD: nbBytes = rtpManager.getGlobalTransmissionStats().getBytesSent(); break; } } return nbBytes; } /** * Computes the RTT with the data (LSR and DLSR) contained in the last * RTCP Sender Report (RTCP feedback). This RTT computation is based on * RFC3550, section 6.4.1, subsection "delay since last SR (DLSR): 32 * bits". * * @param feedback The last RTCP feedback received by the MediaStream. * * @return The RTT in milliseconds, or -1 if the RTT is not computable. */ private long computeRTTInMs(RTCPFeedback feedback) { // Computes RTT. long currentTime = System.currentTimeMillis(); long DLSR = feedback.getDLSR(); long LSR = feedback.getLSR(); // If the peer sending us the sender report has at least received on // sender report from our side, then computes the RTT. if(DLSR != 0 && LSR != 0) { long LSRs = LSR >> 16; long LSRms = ((LSR & 0xffff) * 1000) / 0xffff; long DLSRs = DLSR / 0xffff; long DLSRms = ((DLSR & 0xffff) *1000) / 0xffff; long currentTimeS = (currentTime / 1000) & 0x0000ffff; long currentTimeMs = (currentTime % 1000); long rttS = currentTimeS - DLSRs - LSRs; long rttMs = currentTimeMs - DLSRms - LSRms; long computedRTTms = (rttS * 1000) + rttMs; // If the RTT is greater than a minute there might be a bug. Thus we // log the info to see the source of this error. if(computedRTTms > 60000 && logger.isInfoEnabled()) { logger.info("Stream: " + mediaStreamImpl.getName() + ", RTT computation seems to be wrong (" + computedRTTms + "> 60 seconds):" + "\n\tcurrentTime: " + currentTime + " (" + Long.toHexString(currentTime) + ")" + "\n\tDLSR: " + DLSR + " (" + Long.toHexString(DLSR) + ")" + "\n\tLSR: " + LSR + " (" + Long.toHexString(LSR) + ")" + "\n\n\tcurrentTimeS: " + currentTimeS + " (" + Long.toHexString(currentTimeS) + ")" + "\n\tDLSRs: " + DLSRs + " (" + Long.toHexString(DLSRs) + ")" + "\n\tLSRs: " + LSRs + " (" + Long.toHexString(LSRs) + ")" + "\n\trttS: " + rttS + " (" + Long.toHexString(rttS) + ")" + "\n\n\tcurrentTimeMs: " + currentTimeMs + " (" + Long.toHexString(currentTimeMs) + ")" + "\n\tDLSRms: " + DLSRms + " (" + Long.toHexString(DLSRms) + ")" + "\n\tLSRms: " + LSRms + " (" + Long.toHexString(LSRms) + ")" + "\n\trttMs: " + rttMs + " (" + Long.toHexString(rttMs) + ")" ); } return computedRTTms; } // Else the RTT can not be computed yet. return -1; } /** * Returns the RTT computed with the RTCP feedback (cf. RFC3550, section * 6.4.1, subsection "delay since last SR (DLSR): 32 bits"). * * @return The RTT computed with the RTCP feedback. Returns -1 if the RTT * has not been computed yet. Otherwise the RTT in ms. */ public long getRttMs() { return this.rttMs; } /** * Returns the number of packets for which FEC data was decoded. Currently * this is cumulative over all <tt>ReceiveStream</tt>s. * * @return the number of packets for which FEC data was decoded. Currently * this is cumulative over all <tt>ReceiveStream</tt>s. * * @see org.jitsi.impl.neomedia.MediaStreamStatsImpl#updateNbFec() */ public long getNbFec() { return nbFec; } /** * Updates the <tt>nbFec</tt> field with the sum of FEC-decoded packets * over the different <tt>ReceiveStream</tt>s */ private void updateNbFec() { MediaDeviceSession devSession = mediaStreamImpl.getDeviceSession(); int nbFec = 0; if(devSession != null) { for(ReceiveStream receiveStream : devSession.getReceiveStreams()) { for(FECDecoderControl fecDecoderControl : devSession.getDecoderControls( receiveStream, FECDecoderControl.class)) { nbFec += fecDecoderControl.fecPacketsDecoded(); } } } this.nbFec = nbFec; } /** * Updates the number of discarded packets. * * @param newNbDiscarded The last update of the number of lost. * @param nbSteps The number of elapsed steps since the last number of loss * update. */ private void updateNbDiscarded( long newNbDiscarded, long nbSteps) { double newPercentDiscarded = MediaStreamStatsImpl.computePercentLoss( nbSteps, newNbDiscarded); this.percentDiscarded = MediaStreamStatsImpl.computeEWMA( nbSteps, this.percentDiscarded, newPercentDiscarded); // Saves the last update number download lost value. this.nbDiscarded += newNbDiscarded; } public boolean isAdaptiveBufferEnabled() { for(PacketQueueControl pcq : getPacketQueueControls()) if(pcq.isAdaptiveBufferEnabled()) return true; return false; } /** * Returns the delay in number of packets introduced by the jitter buffer. * Since there might be multiple <tt>ReceiveStreams</tt>, returns the * biggest delay found in any of them. * * @return the delay in number of packets introduced by the jitter buffer */ public int getJitterBufferDelayPackets() { int delay = 0; for(PacketQueueControl pqc : getPacketQueueControls()) if(pqc.getCurrentDelayPackets() > delay) delay = pqc.getCurrentDelayPackets(); return delay; } /** * Returns the delay in milliseconds introduced by the jitter buffer. * Since there might be multiple <tt>ReceiveStreams</tt>, returns the * biggest delay found in any of them. * * @return the delay in milliseconds introduces by the jitter buffer */ public int getJitterBufferDelayMs() { int delay = 0; for(PacketQueueControl pqc : getPacketQueueControls()) if(pqc.getCurrentDelayMs() > delay) delay = pqc.getCurrentDelayMs(); return delay; } /** * Returns the size of the first <tt>PacketQueueControl</tt> found via * <tt>getPacketQueueControls</tt>. * * @return the size of the first <tt>PacketQueueControl</tt> found via * <tt>getPacketQueueControls</tt>. */ public int getPacketQueueSize() { for(PacketQueueControl pqc : getPacketQueueControls()) return pqc.getCurrentSizePackets(); return 0; } /** * Returns the number of packets in the first <tt>PacketQueueControl</tt> * found via <tt>getPacketQueueControls</tt>. * * @return the number of packets in the first <tt>PacketQueueControl</tt> * found via <tt>getPacketQueueControls</tt>. */ public int getPacketQueueCountPackets() { for(PacketQueueControl pqc : getPacketQueueControls()) return pqc.getCurrentPacketCount(); return 0; } /** * Returns the set of <tt>PacketQueueControls</tt> found for all the * <tt>DataSource</tt>s of all the <tt>ReceiveStream</tt>s. The set contains * only non-null elements. * * @return the set of <tt>PacketQueueControls</tt> found for all the * <tt>DataSource</tt>s of all the <tt>ReceiveStream</tt>s. The set contains * only non-null elements. */ private Set<PacketQueueControl> getPacketQueueControls() { Set<PacketQueueControl> set = new HashSet<PacketQueueControl>(); if (mediaStreamImpl.isStarted()) { MediaDeviceSession devSession = mediaStreamImpl.getDeviceSession(); if (devSession != null) { for(ReceiveStream receiveStream : devSession.getReceiveStreams()) { DataSource ds = receiveStream.getDataSource(); if(ds instanceof net.sf.fmj.media.protocol.rtp.DataSource) { for (PushBufferStream pbs : ((net.sf.fmj.media.protocol.rtp.DataSource)ds) .getStreams()) { PacketQueueControl pqc = (PacketQueueControl) pbs.getControl( PacketQueueControl.class.getName()); if(pqc != null) set.add(pqc); } } } } } return set; } }
/* * $Id: XmlDomMetadataExtractor.java,v 1.3 2012-03-12 04:23:18 pgust Exp $ */ package org.lockss.extractor; import java.io.*; import java.text.NumberFormat; import java.text.ParseException; import java.util.*; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.lockss.plugin.CachedUrl; import org.lockss.util.Logger; import org.lockss.util.StringUtil; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class XmlDomMetadataExtractor extends SimpleFileMetadataExtractor { static Logger log = Logger.getLogger("XmlMetadataExtractor"); /** The xpath map to use for extracting */ final protected XPathExpression[] xpathExprs; final protected String[] xpathKeys; final protected XPathValue[] nodeValues; /** * This class defines a function to extract text from an XPath value * according to the specified type: as a nodeset if type is * XPathConstants.NODESET, as a String if type is XPathConstants.STRING, * as a Boolean if type is XPathConstants.BOOLEAN, or as a Number * if type is XPathConstants.NUMBER. * * @author Philip Gust */ static abstract public class XPathValue { /** Override this method to specify a different type */ public abstract QName getType(); /** * Override this method to handle a node-valued * property or attribute. The default implementation * returns the text content of the node. * @param node the node value * @return the text value of the node */ public String getValue(Node node) { return (node == null) ? null : node.getTextContent(); } /** * Override this method to handle a text-valued * property or attribute. The default implementation * returns the input string. * @param s the text value * @return the text value */ public String getValue(String s) { return s; } /** * Override this method to handle a boolean-valued * property or attribute. The default implementation * returns the string value of the input boolean. * @param b the boolean value * @return the string value of the boolean */ public String getValue(Boolean b) { return (b == null) ? null : b.toString(); } /** * Override this method to handle a number-valued * property or attribute. The default implementation * returns the string value of the input number. * @param n the number value * @return the string value of the number */ public String getValue(Number n) { return (n == null) ? null : n.toString(); } } /** XPathValue for a nodeset */ static public class NodeValue extends XPathValue { @Override public QName getType() { return XPathConstants.NODE; } } static final public XPathValue NODE_VALUE = new NodeValue(); /** XPathValue value for a single text value */ static public class TextValue extends XPathValue { @Override public QName getType() { return XPathConstants.STRING; } } static final public XPathValue TEXT_VALUE = new TextValue(); /** XPathValue for a single number value */ static public class NumberValue extends XPathValue { @Override public QName getType() { return XPathConstants.NUMBER; } } static final public XPathValue NUMBER_VALUE = new NumberValue(); /** XPathValue for a boolean value */ static public class BooleanValue extends XPathValue { @Override public QName getType() { return XPathConstants.BOOLEAN; } } static final public XPathValue BOOLEAN_VALUE = new BooleanValue(); /** * Create an extractor based on the required size. * * @param size the required size. */ protected XmlDomMetadataExtractor(int size) { xpathExprs = new XPathExpression[size]; xpathKeys = new String[size]; nodeValues = new XPathValue[size]; } /** * Create an extractor that will extract the textContent of the * nodes specified by the XPath expressions. * * @param xpaths the collection of XPath expressions whose * text content to extract. */ public XmlDomMetadataExtractor(Collection<String> xpaths) throws XPathExpressionException { this(xpaths.size()); int i = 0; XPath xpath = XPathFactory.newInstance().newXPath(); for (String xp : xpaths) { xpathKeys[i] = xp; xpathExprs[i] = xpath.compile(xp); nodeValues[i] = TEXT_VALUE; i++; } } /** * Create an extractor that will extract the textContent of the * nodes specified by the XPath expressions by applying the * corresponding NodeValues. * * @param xpathMap the map of XPath expressions whose value to extract * by applying the corresponding NodeValues. */ public XmlDomMetadataExtractor(Map<String, XPathValue> xpathMap) throws XPathExpressionException { this(xpathMap.size()); int i = 0; XPath xpath = XPathFactory.newInstance().newXPath(); for (Map.Entry<String,XPathValue> entry : xpathMap.entrySet()) { xpathKeys[i] = entry.getKey(); xpathExprs[i] = xpath.compile(entry.getKey()); nodeValues[i] = entry.getValue(); i++; } } /** * Extract metadata from source specified by the input stream. * * @param target the MetadataTarget * @param in the input stream to use as the source */ public ArticleMetadata extract(MetadataTarget target, CachedUrl cu) throws IOException { if (cu == null) { throw new IllegalArgumentException("null CachedUrl"); } ArticleMetadata am = new ArticleMetadata(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { dbf.setValidating(false); dbf.setFeature("http://xml.org/sax/features/namespaces", false); dbf.setFeature("http://xml.org/sax/features/validation", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException ex) { log.warning(ex.getMessage()); return am; } Document doc; InputSource bReader = new InputSource(cu.openForReading()); try { doc = builder.parse(bReader); } catch (SAXException ex) { log.warning(ex.getMessage()); return am; } // search for values using specified XPath expressions and // set raw value using string based on type of node value for (int i = 0; i < xpathKeys.length; i++) { try { QName type = nodeValues[i].getType(); Object result = xpathExprs[i].evaluate(doc, XPathConstants.NODESET); NodeList nodeList = (NodeList)result; for (int j = 0; j < nodeList.getLength(); j++) { Node node = nodeList.item(j); if (node == null) { continue; } String value = null; if (type == XPathConstants.NODE) { // filter node value = nodeValues[i].getValue(node); } else if (type == XPathConstants.STRING) { // filter node text content String text = node.getTextContent(); value = nodeValues[i].getValue(text); } else if (type == XPathConstants.BOOLEAN) { // filter boolean value of node text content String text = node.getTextContent(); value = nodeValues[i].getValue(Boolean.parseBoolean(text)); } else if (type == XPathConstants.NUMBER) { // filter number value of node text content try { NumberFormat format = NumberFormat.getInstance(); String text = node.getTextContent(); value = nodeValues[i].getValue(format.parse(text)); } catch (ParseException ex) { // ignore invalid number log.debug3(ex.getMessage()); continue; } } else { log.debug("Unknown nodeValue type: " + type.toString()); continue; } if (!StringUtil.isNullString(value)) { am.putRaw(xpathKeys[i], value); } } } catch (XPathExpressionException ex) { // ignore evaluation errors log.warning("ignorning xpath error", ex); } } return am; } }
package net.example.iot.client; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import net.example.iot.R; import net.example.iot.client.util.SystemUiHider; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import android.view.View; /** * An example full-screen activity that shows and hides the * system UI (i.e. status bar and navigation/system bar) * with user interaction. * * @see SystemUiHider */ public class FullscreenActivity extends Activity implements SensorEventListener { private static final String TAG = FullscreenActivity.class.getSimpleName(); private static final boolean AUTO_HIDE = true; private static final int AUTO_HIDE_DELAY_MILLIS = 3000; private static final boolean TOGGLE_ON_CLICK = true; private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION; private static final String WS_URL = "ws://192.168.1.6:8080"; private SystemUiHider mSystemUiHider; private SensorManager manager; private WebSocketClient mClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fullscreen); final View controlsView = findViewById(R.id.fullscreen_content_controls); final View contentView = findViewById(R.id.fullscreen_content); // Set up an instance of SystemUiHider to control the system UI for // this activity. mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS); mSystemUiHider.setup(); mSystemUiHider.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() { // Cached values. int mControlsHeight; int mShortAnimTime; @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void onVisibilityChange(boolean visible) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { // If the ViewPropertyAnimator API is available // (Honeycomb MR2 and later), use it to animate the // in-layout UI controls at the bottom of the // screen. if (mControlsHeight == 0) { mControlsHeight = controlsView.getHeight(); } if (mShortAnimTime == 0) { mShortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); } controlsView.animate().translationY(visible ? 0 : mControlsHeight).setDuration(mShortAnimTime); } else { // If the ViewPropertyAnimator APIs aren't // available, simply show or hide the in-layout UI // controls. controlsView.setVisibility(visible ? View.VISIBLE : View.GONE); } if (visible && AUTO_HIDE) { // Schedule a hide(). delayedHide(AUTO_HIDE_DELAY_MILLIS); } } }); // Set up the user interaction to manually show or hide the system UI. contentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (TOGGLE_ON_CLICK) { mSystemUiHider.toggle(); } else { mSystemUiHider.show(); } } }); // Upon interacting with UI controls, delay any scheduled hide() // operations to prevent the jarring behavior of controls going away // while interacting with the UI. findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener); manager = (SensorManager) getSystemService(SENSOR_SERVICE); try { Log.d(TAG, "ws"); URI uri = new URI(WS_URL); mClient = new WebSocketClient(uri) { @Override public void onOpen(ServerHandshake handshake) { Log.d(TAG, "onOpen()"); } @Override public void onMessage(final String message) { // Log.d(TAG, "onMessage(" + message + ")"); } @Override public void onError(Exception e) { Log.d(TAG, "onError(" + e + ")"); Log.d(TAG, e.getMessage(), e); } @Override public void onClose(int code, String reason, boolean remote) { Log.d(TAG, "onClose(" + reason + "," + remote + ")"); } }; try { Log.d(TAG, "connecting"); mClient.connect(); Log.d(TAG, "connected"); } catch (Exception e) { Log.d(TAG, e.getMessage(), e); } } catch (URISyntaxException e) { Log.d(TAG, e.getMessage(), e); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); delayedHide(100); } View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() { @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (AUTO_HIDE) delayedHide(AUTO_HIDE_DELAY_MILLIS); return false; } }; Handler mHideHandler = new Handler(); Runnable mHideRunnable = new Runnable() { @Override public void run() { mSystemUiHider.hide(); } }; private void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); } @Override protected void onStop() { super.onStop(); manager.unregisterListener(this); } @Override protected void onResume() { super.onResume(); List<Sensor> sensors = manager.getSensorList(Sensor.TYPE_ACCELEROMETER); if (sensors.size() > 0) { Sensor s = sensors.get(0); manager.registerListener(this, s, SensorManager.SENSOR_DELAY_UI); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { Log.d(TAG, "onAccuracyChanged(" + sensor + "," + Integer.valueOf(accuracy) + ")"); } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) return; try { JSONObject json = new JSONObject(); json.put("accuracy", event.accuracy); json.put("timestamp", event.timestamp); json.put("values", new JSONArray(event.values)); json.put("sensor", SensorUtils.toJSON(event.sensor)); Log.v(TAG, "json(" + json + ")"); try { mClient.send(json.toString()); } catch (Exception e) { Log.v(TAG, e.getMessage(), e); } } catch (JSONException e) { Log.e(TAG, e.getMessage(), e); } } }
package kernitus.plugin.OldCombatMechanics; import org.bukkit.Bukkit; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Team; import java.io.IOException; import java.util.logging.Logger; public class OCMMain extends JavaPlugin { protected OCMUpdateChecker updateChecker = new OCMUpdateChecker(this); private OCMConfigHandler CH = new OCMConfigHandler(this); private OCMTask task = new OCMTask(this); Logger logger = getLogger(); @Override public void onEnable() { //Checking for updates updateChecker.sendUpdateMessages(logger); PluginDescriptionFile pdfFile = this.getDescription(); // Listeners and stuff getServer().getPluginManager().registerEvents((new OCMListener(this)), this);// Firing event listener getCommand("OldCombatMechanics").setExecutor(new OCMCommandHandler(this));// Firing commands listener // Setting up config.yml CH.setupConfigyml(); // Initialize Config utility Config.Initialize(this); // Initialize the team if it doesn't already exist createTeam(); // Disabling player collisions if(Config.moduleEnabled("disable-player-collisions")){ // Even though it says "restart", it works for just starting it too restartTask(); } // Metrics try { MetricsLite metrics = new MetricsLite(this); metrics.start(); } catch (IOException e) { // Failed to submit the stats } // Logging to console the correct enabling of OCM logger.info(pdfFile.getName() + " v" + pdfFile.getVersion() + " has been enabled correctly"); } @Override public void onDisable() { PluginDescriptionFile pdfFile = this.getDescription(); task.cancel(); // Logging to console the disabling of OCM logger.info(pdfFile.getName() + " v" + pdfFile.getVersion() + " has been disabled"); } private void createTeam() { String name = "ocmInternal"; Scoreboard scoreboard = Bukkit.getScoreboardManager().getMainScoreboard(); Team team = null; for (Team t : scoreboard.getTeams()) { if (t.getName().equals(name)) { team = t; break; } } if (team == null) { team = scoreboard.registerNewTeam(name); } team.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER); team.setAllowFriendlyFire(true); } public void upgradeConfig(){ CH.upgradeConfig(); } public boolean doesConfigymlExist(){ return CH.doesConfigymlExist(); } public void restartTask() { if (Bukkit.getScheduler().isCurrentlyRunning(task.getTaskId())) task.cancel(); double minutes = getConfig().getDouble("disable-player-collisions.collision-check-frequency"); if(minutes>0) task.runTaskTimerAsynchronously(this, 0, (long) minutes*60*20); else task.runTaskTimerAsynchronously(this, 0, 60*20); } }
package org.junit.gen5.api; import static org.junit.gen5.commons.meta.API.Usage.Stable; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.gen5.commons.meta.API; /** * {@code @Test} is used to signal that the annotated method is a * <em>test</em> method. * * <p>{@code @Test} may also be used as a meta-annotation in order to * create a custom <em>composed annotation</em> that inherits the semantics * of {@code @Test}. * * <p>{@code @Test} methods must not be {@code private} or {@code static}. * * <p>{@code @Test} methods may optionally declare parameters to be * resolved by {@link org.junit.gen5.api.extension.MethodParameterResolver * MethodParameterResolvers}. * * @since 5.0 * @see TestInfo * @see DisplayName * @see BeforeEach * @see AfterEach * @see BeforeAll * @see AfterAll */ @Target({ ElementType.ANNOTATION_TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @API(Stable) public @interface Test { }
package net.sf.farrago.syslib; import java.io.*; import java.sql.*; import java.util.*; import net.sf.farrago.db.*; import net.sf.farrago.namespace.FarragoMedDataWrapper; import net.sf.farrago.namespace.util.FarragoDataWrapperCache; import net.sf.farrago.runtime.FarragoUdrRuntime; import net.sf.farrago.util.FarragoObjectCache; /** A class to get certain Farrago Med property values. The UDX functions * in initsql cause these functions to be invoked. */ public class FarragoMedInfo { public static final int NAME = 1; public static final int AVALUE = 2; public static final int DESCRIPTION = 3; public static final int CHOICES = 4; public static final int REQUIRED = 5; public static final int ISFOREIGN = 1; protected static FarragoDataWrapperCache dataWrapperCache = null; /** * Get the plugin property info for the mofId, library combo passed in. * @param mofId The mofId to get property info for. * @param libraryName The library to get property info for. * @param optionsArg The options to pass to the data wrapper. * @param wrapperPropertiesString The wrapper props to request. * @param localeArg What locale to get properties for. * @param resultInserter Where the result rows are placed. * @throws SQLException Thrown on repo access failure. */ public static void getPluginPropertyInfo( String mofId, String libraryName, String optionsArg, String wrapperPropertiesString, String localeArg, PreparedStatement resultInserter) throws SQLException { Properties options = new Properties( getPropertiesFromString(optionsArg)); Locale locale = toLocale(localeArg); Properties wrapperProperties = getPropertiesFromString( wrapperPropertiesString); FarragoMedDataWrapper dataWrapper = getWrapper( mofId, libraryName, options); DriverPropertyInfo[] driverPropertyInfo; try { driverPropertyInfo = dataWrapper.getPluginPropertyInfo( locale, wrapperProperties); } finally { closeWrapperCache(); } moveDriverPropertyInfoToResult(driverPropertyInfo, resultInserter); } /** * Get the server property info for the mofId, library combo passed in. * @param mofId The mofId to get property info for. * @param libraryName The library to get property info for. * @param optionsArg The options to pass to the data wrapper. * @param wrapperPropertiesString The wrapper props to request. * @param serverPropertiesString The server props to request. * @param localeArg What locale to get properties for. * @param resultInserter Where the result rows are placed. * @throws SQLException Thrown on repo access failure. */ public static void getServerPropertyInfo( String mofId, String libraryName, String optionsArg, String wrapperPropertiesString, String serverPropertiesString, String localeArg, PreparedStatement resultInserter) throws SQLException { Properties options = new Properties( getPropertiesFromString(optionsArg)); Locale locale = toLocale(localeArg); Properties wrapperProperties = getPropertiesFromString( wrapperPropertiesString); FarragoMedDataWrapper dataWrapper = getWrapper( mofId, libraryName, options); Properties serverProperties = getPropertiesFromString( serverPropertiesString); DriverPropertyInfo[] driverPropertyInfo; try { driverPropertyInfo = dataWrapper.getServerPropertyInfo( locale, wrapperProperties, serverProperties); } finally { closeWrapperCache(); } moveDriverPropertyInfoToResult(driverPropertyInfo, resultInserter); } /** * Get the column set property info for the mofId, library combo passed in. * @param mofId The mofId to get property info for. * @param libraryName The library to get property info for. * @param optionsString The options to pass to the data wrapper. * @param wrapperPropertiesString The wrapper props to request. * @param serverPropertiesString The table props to request. * @param tablePropertiesString The table props to request. * @param localeArg What locale to get properties for. * @param resultInserter Where the result rows are placed. * @throws SQLException Thrown on repo access failure. */ public static void getColumnSetPropertyInfo( String mofId, String libraryName, String optionsString, String wrapperPropertiesString, String serverPropertiesString, String tablePropertiesString, String localeArg, PreparedStatement resultInserter) throws SQLException { Properties options = new Properties( getPropertiesFromString(optionsString)); Locale locale = toLocale(localeArg); Properties wrapperProperties = getPropertiesFromString( wrapperPropertiesString); FarragoMedDataWrapper dataWrapper = getWrapper( mofId, libraryName, options); Properties serverProperties = getPropertiesFromString( serverPropertiesString); Properties tableProperties = getPropertiesFromString( tablePropertiesString); DriverPropertyInfo[] driverPropertyInfo; try { driverPropertyInfo = dataWrapper.getColumnSetPropertyInfo( locale, wrapperProperties, serverProperties, tableProperties); } finally { closeWrapperCache(); } moveDriverPropertyInfoToResult(driverPropertyInfo, resultInserter); } /** * Get the column property info for the mofId, library combo passed in. * @param mofId The mofId to get property info for. * @param libraryName The library to get property info for. * @param optionsString The options to pass to the data wrapper. * @param wrapperPropertiesString The wrapper props to request. * @param serverPropertiesString The table props to request. * @param tablePropertiesString The table props to request. * @param columnPropertiesString The column props to request. * @param localeArg What locale to get properties for. * @param resultInserter Where the result rows are placed. * @throws SQLException Thrown on repo access failure. */ public static void getColumnPropertyInfo( String mofId, String libraryName, String optionsString, String wrapperPropertiesString, String serverPropertiesString, String tablePropertiesString, String columnPropertiesString, String localeArg, PreparedStatement resultInserter) throws SQLException { Properties options = new Properties( getPropertiesFromString(optionsString)); Locale locale = toLocale(localeArg); Properties wrapperProperties = getPropertiesFromString( wrapperPropertiesString); FarragoMedDataWrapper dataWrapper = getWrapper( mofId, libraryName, options); Properties serverProperties = getPropertiesFromString( serverPropertiesString); Properties tableProperties = getPropertiesFromString( tablePropertiesString); Properties columnProperties = getPropertiesFromString( columnPropertiesString); DriverPropertyInfo[] driverPropertyInfo; try { driverPropertyInfo = dataWrapper.getColumnPropertyInfo( locale, wrapperProperties, serverProperties, tableProperties, columnProperties); } finally { closeWrapperCache(); } moveDriverPropertyInfoToResult(driverPropertyInfo, resultInserter); } /** * Is the library object foreign? * @param mofId The id to check. * @param libraryName The library to check. * @param optionsString The options to pass to the data wrapper. * @param localeString What locale to check for. * @param resultInserter Where the result rows are placed. * @throws SQLException Thrown on repo access failure. */ public static void isForeign( String mofId, String libraryName, String optionsString, String localeString, // TODO Should this be removed? PreparedStatement resultInserter) throws SQLException { Properties options = new Properties( getPropertiesFromString(optionsString)); FarragoMedDataWrapper dataWrapper = getWrapper( mofId, libraryName, options); try { boolean isForeign = dataWrapper.isForeign(); resultInserter.setBoolean(ISFOREIGN, isForeign); resultInserter.executeUpdate(); // TODO Can we skip the result update when there is an exception? } finally { closeWrapperCache(); } } /** Get an exception's stack trace as a String. * @param exception The exception to get the stack trace for. * @return A String version of the stack trace of the exception * parameter. */ public static String getExceptionStackTraceAsString(Throwable exception) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); exception.printStackTrace(printWriter); return stringWriter.toString(); } /** Get a FarragoMedDataWrapper based on the data passed in. * @param mofId The Meta object ID of the wrapper to get. * @param libraryName The library name of the wrapper to get. * @param options The options to pass to the wrapper. * @return The FarragoMedDataWrapper that matches the args passed in. */ public static FarragoMedDataWrapper getWrapper( String mofId, String libraryName, Properties options) { closeWrapperCache(); FarragoDbSession session = (FarragoDbSession) FarragoUdrRuntime.getSession(); FarragoDatabase db = session.getDatabase(); FarragoObjectCache sharedCache = db.getDataWrapperCache(); dataWrapperCache = session.newFarragoDataWrapperCache( session, sharedCache, session.getRepos(), db.getFennelDbHandle(), null); return dataWrapperCache.loadWrapper( mofId, libraryName, options); } /** Close the wrapper cache. */ public static void closeWrapperCache() { if (dataWrapperCache != null) { dataWrapperCache.closeAllocation(); dataWrapperCache = null; } } /** Parse a String formatted as putPropertiesToString generates to create a Properties table. It is assumed that the input String is well-formed. @param propertiesString Properties in a tab and CR delimited String. @return Properties as an object. */ public static Properties getPropertiesFromString( String propertiesString) { Properties result = new Properties(); String[] propertyList = propertiesString.split("\n"); for (String property : propertyList) { String keyAndValue[] = property.split("\t"); // An empty String can get into loop and must be skipped if (keyAndValue.length > 1) { result.put(keyAndValue[0], keyAndValue[1]); } } return result; } /** Produces output that looks like this (where a single space is a tab): "key1 value1 key2 value2 " @param properties A standard Java Property set that will be converted to a String (formatted as described above). @return A String containing the contents of the passed Property set. */ public static String putPropertiesToString( Properties properties) { String result = new String(); for (Object key : Collections.list(properties.keys())) { result += key + "\t" + properties.get(key) + "\n"; } return result; } /** Convert a String version of a Locale to an SQL Locale. * @param localeString The locale String to convert. * @return The Locale based on the String passed in. */ public static Locale toLocale(String localeString) { return new Locale(localeString); } /** Move the driver property info array to an SQL result. * @param driverPropertyInfo The array to convert. * @param resultInserter Where to put the result. * @throws SQLException If there's a problem writing the result. */ public static void moveDriverPropertyInfoToResult( DriverPropertyInfo[] driverPropertyInfo, PreparedStatement resultInserter) throws SQLException { for (DriverPropertyInfo oneProperty : driverPropertyInfo) { resultInserter.setString(NAME, oneProperty.name); resultInserter.setString(AVALUE, oneProperty.value); resultInserter.setString(DESCRIPTION, oneProperty.description); // Just treat choices like properties for simplicity Properties choices = new Properties(); if (oneProperty.choices != null) { for (String oneChoice : oneProperty.choices) { choices.put(oneChoice, oneChoice); } } resultInserter.setString(CHOICES, putPropertiesToString(choices)); resultInserter.setBoolean(REQUIRED, oneProperty.required); resultInserter.executeUpdate(); } } } // End FarragoMedInfo.java
package it.cnr.isti.vir.util.bytes; import it.cnr.isti.vir.features.ILongBinaryValues; import it.cnr.isti.vir.util.RandomOperations; import java.util.Collection; public class LongBinaryUtil { public static long[] getMean(Collection coll) { long[][] temp = new long[coll.size()][]; int i=0; for ( Object curr : coll ) { temp[i++] = ((ILongBinaryValues) curr).getElements(); } return getMean( temp ); } public static long[] getMeanFromLongs(Collection<long[]> coll) { long[][] temp = new long[coll.size()][]; coll.toArray(temp); return getMean( temp ); } public static long[] getMean(long[][] coll) { if ( coll.length == 0 ) return null; int nlongs = coll[0].length; int[] bitsSum = new int[nlongs*Long.SIZE]; for ( long[] currVec : coll ) { //long[] currVec = it.next(); int iBitSum = 0; for ( int iLong=0; iLong<currVec.length; iLong++ ) { // for each bit long mask = 1; for ( int i=0; i<Long.SIZE; i++) { if ( (currVec[iLong] & mask) != 0 ) bitsSum[iBitSum]++; iBitSum++; mask = mask << 1; } } } long[] newValues = new long[nlongs]; int threshold = coll.length / 2; long oneLong = 1; for ( int i=0; i<bitsSum.length; i++ ) { if ( bitsSum[i] > threshold // ( bitsSum[i] == threshold // && RandomOperations.getBoolean() ) { newValues[i/Long.SIZE] ^= (oneLong << i%Long.SIZE ); } } return newValues; } }
package org.royaldev.royalcommands.rcommands; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.royaldev.royalcommands.RUtils; import org.royaldev.royalcommands.RoyalCommands; public class CmdMotd implements CommandExecutor { static RoyalCommands plugin; public CmdMotd(RoyalCommands instance) { plugin = instance; } public static void showMotd(CommandSender cs) { String ps = (plugin.simpleList) ? CmdList.getSimpleList(cs) : RUtils.join(CmdList.getGroupList(cs), "\n"); Integer onnum = plugin.getServer().getOnlinePlayers().length; int hid = plugin.getNumberVanished(); String onlinenum; try { onlinenum = Integer.toString(onnum - hid); } catch (Exception e) { onlinenum = null; } Integer maxon = plugin.getServer().getMaxPlayers(); String maxonl; try { maxonl = Integer.toString(maxon); } catch (Exception e) { maxonl = null; } for (String s : plugin.motd) { if (s == null) continue; s = RUtils.colorize(s); s = s.replace("{name}", cs.getName()); s = (cs instanceof Player) ? s.replace("{dispname}", ((Player) cs).getDisplayName()) : s.replace("{dispname}", cs.getName()); if (onlinenum != null) s = s.replace("{players}", onlinenum); s = s.replace("{playerlist}", ps); s = (cs instanceof Player) ? s.replace("{world}", RUtils.getMVWorldName(((Player) cs).getWorld())) : s.replace("{world}", "No World"); if (maxonl != null) s = s.replace("{maxplayers}", maxonl); s = (plugin.getServer().getServerName() != null || !plugin.getServer().getServerName().equals("")) ? s.replace("{servername}", plugin.getServer().getServerName()) : s.replace("{servername}", "this server"); cs.sendMessage(s); } } @Override public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("motd")) { if (!plugin.isAuthorized(cs, "rcmds.motd")) { RUtils.dispNoPerms(cs); return true; } showMotd(cs); return true; } return false; } }
package net.maizegenetics.pipeline; import java.awt.Frame; import java.io.BufferedReader; import java.io.File; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import net.maizegenetics.baseplugins.AbstractDisplayPlugin; import net.maizegenetics.baseplugins.CombineDataSetsPlugin; import net.maizegenetics.baseplugins.ConvertAlignmentCoordinatesPlugin; import net.maizegenetics.baseplugins.ExportMultiplePlugin; import net.maizegenetics.baseplugins.FileLoadPlugin; import net.maizegenetics.baseplugins.FilterAlignmentPlugin; import net.maizegenetics.baseplugins.FilterSiteNamePlugin; import net.maizegenetics.baseplugins.FilterTaxaAlignmentPlugin; import net.maizegenetics.baseplugins.FilterTraitsPlugin; import net.maizegenetics.baseplugins.FixedEffectLMPlugin; import net.maizegenetics.baseplugins.FlapjackLoadPlugin; import net.maizegenetics.baseplugins.GenotypeImputationPlugin; import net.maizegenetics.baseplugins.GenotypeSummaryPlugin; import net.maizegenetics.baseplugins.IntersectionAlignmentPlugin; import net.maizegenetics.baseplugins.KinshipPlugin; import net.maizegenetics.baseplugins.LinkageDiseqDisplayPlugin; import net.maizegenetics.baseplugins.LinkageDisequilibriumPlugin; import net.maizegenetics.baseplugins.MLMPlugin; import net.maizegenetics.baseplugins.MergeAlignmentsPlugin; import net.maizegenetics.baseplugins.MergeAlignmentsSameSitesPlugin; import net.maizegenetics.baseplugins.NumericalGenotypePlugin; import net.maizegenetics.baseplugins.PlinkLoadPlugin; import net.maizegenetics.baseplugins.SeparatePlugin; import net.maizegenetics.baseplugins.TableDisplayPlugin; import net.maizegenetics.baseplugins.UnionAlignmentPlugin; import net.maizegenetics.baseplugins.genomicselection.RidgeRegressionEmmaPlugin; import net.maizegenetics.pal.gui.LinkageDisequilibriumComponent; import net.maizegenetics.pal.popgen.LinkageDisequilibrium.testDesign; import net.maizegenetics.pal.ids.Identifier; import net.maizegenetics.pal.ids.SimpleIdGroup; import net.maizegenetics.plugindef.AbstractPlugin; import net.maizegenetics.plugindef.DataSet; import net.maizegenetics.plugindef.Datum; import net.maizegenetics.plugindef.Plugin; import net.maizegenetics.plugindef.PluginEvent; import net.maizegenetics.plugindef.PluginListener; import net.maizegenetics.plugindef.ThreadedPluginListener; import net.maizegenetics.prefs.TasselPrefs; import net.maizegenetics.progress.ProgressPanel; import net.maizegenetics.tassel.DataTreePanel; import net.maizegenetics.tassel.TASSELMainFrame; import net.maizegenetics.util.ExceptionUtils; import net.maizegenetics.util.Utils; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; /** * * @author terryc */ public class TasselPipeline implements PluginListener { private static final Logger myLogger = Logger.getLogger(TasselPipeline.class); private final TASSELMainFrame myMainFrame; private final Map<String, List> myForks = new LinkedHashMap<String, List>(); private String myCurrentFork = null; private List<Plugin> myCurrentPipe = null; private Plugin myFirstPlugin = null; private final List<ThreadedPluginListener> myThreads = new ArrayList(); private final Map<Plugin, Integer> myProgressValues = new HashMap<Plugin, Integer>(); /** Creates a new instance of TasselPipeline */ public TasselPipeline(String args[], TASSELMainFrame frame) { myMainFrame = frame; java.util.Properties props = new java.util.Properties(); props.setProperty("log4j.logger.net.maizegenetics", "INFO, stdout"); props.setProperty("log4j.appender.stdout", "org.apache.log4j.ConsoleAppender"); props.setProperty("log4j.appender.stdout.layout", "org.apache.log4j.TTCCLayout"); PropertyConfigurator.configure(props); try { myLogger.info("Tassel Version: " + myMainFrame.version + " Date: " + myMainFrame.versionDate); parseArgs(args); if (myMainFrame != null) { ProgressPanel progressPanel = myMainFrame.getProgressPanel(); if (progressPanel != null) { Iterator itr = myForks.keySet().iterator(); while (itr.hasNext()) { String key = (String) itr.next(); List<Plugin> current = myForks.get(key); progressPanel.addPipelineSegment(current); } } } for (int i = 0; i < myThreads.size(); i++) { ThreadedPluginListener current = (ThreadedPluginListener) myThreads.get(i); current.start(); } } catch (Exception e) { System.exit(1); } } public static void main(String args[]) { if ((args.length >= 2) && (args[0].equalsIgnoreCase("-createXML"))) { String xmlFilename = args[1].trim(); String[] temp = new String[args.length - 2]; System.arraycopy(args, 2, temp, 0, temp.length); TasselPipelineXMLUtil.writeArgsAsXML(xmlFilename, temp); } else if ((args.length >= 2) && (args[0].equalsIgnoreCase("-translateXML"))) { String xmlFilename = args[1].trim(); String[] result = TasselPipelineXMLUtil.readXMLAsArgs(xmlFilename); for (int i = 0; i < result.length; i++) { System.out.print(result[i]); System.out.print(" "); } System.out.println(""); } else { new TasselPipeline(args, null); } } public void parseArgs(String[] args) { if ((args.length >= 2) && (args[0].equalsIgnoreCase("-configFile"))) { String xmlFilename = args[1].trim(); args = TasselPipelineXMLUtil.readXMLAsArgs(xmlFilename); } int index = 0; while (index < args.length) { try { String current = args[index++]; if (!current.startsWith("-")) { throw new IllegalArgumentException("TasselPipeline: parseArgs: expecting argument beginning with dash: " + current); } if (current.startsWith("-runfork")) { String key = current.replaceFirst("-runfork", "-fork"); List specifiedPipe = (List) myForks.get(key); if (specifiedPipe == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: unknown fork: " + current); } else if (specifiedPipe.size() == 0) { throw new IllegalArgumentException("TasselPipeline: parseArgs: empty fork: " + current); } else { PluginEvent event = new PluginEvent(new DataSet((Datum) null, null)); ThreadedPluginListener thread = new ThreadedPluginListener((Plugin) specifiedPipe.get(0), event); myThreads.add(thread); } } else if (current.startsWith("-fork")) { if ((myCurrentPipe != null) && (myCurrentPipe.size() != 0)) { myCurrentPipe.get(myCurrentPipe.size() - 1).setThreaded(true); } myCurrentFork = current; myCurrentPipe = new ArrayList<Plugin>(); myForks.put(myCurrentFork, myCurrentPipe); } else if (current.startsWith("-input")) { String key = current.replaceFirst("-input", "-fork"); List specifiedPipe = (List) myForks.get(key); if (specifiedPipe == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: unknown input: " + current); } else { Plugin lastCurrentPipe = null; try { lastCurrentPipe = (Plugin) myCurrentPipe.get(myCurrentPipe.size() - 1); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: -input must come after plugin in current fork."); } Plugin endSpecifiedPipe = (Plugin) specifiedPipe.get(specifiedPipe.size() - 1); lastCurrentPipe.receiveInput(endSpecifiedPipe); } } else if (current.startsWith("-inputOnce")) { String key = current.replaceFirst("-input", "-fork"); List specifiedPipe = (List) myForks.get(key); if (specifiedPipe == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: unknown input: " + current); } else { CombineDataSetsPlugin combinePlugin = null; try { combinePlugin = (CombineDataSetsPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: -inputOnce must follow -combine flag."); } Plugin endSpecifiedPipe = (Plugin) specifiedPipe.get(specifiedPipe.size() - 1); combinePlugin.receiveDataSetOnceFrom(endSpecifiedPipe); } } else if (current.startsWith("-combine")) { current = current.replaceFirst("-combine", "-fork"); if ((myCurrentPipe != null) && (myCurrentPipe.size() != 0)) { myCurrentPipe.get(myCurrentPipe.size() - 1).setThreaded(true); } myCurrentFork = current; myCurrentPipe = new ArrayList<Plugin>(); myForks.put(myCurrentFork, myCurrentPipe); integratePlugin(new CombineDataSetsPlugin(), false); } else if (current.equalsIgnoreCase("-t")) { String traitFile = args[index++].trim(); loadFile(traitFile, FileLoadPlugin.TasselFileType.Numerical); } else if (current.equalsIgnoreCase("-s")) { String inputFile = args[index++].trim(); loadFile(inputFile, FileLoadPlugin.TasselFileType.Sequence); } else if (current.equalsIgnoreCase("-p")) { String inputFile = args[index++].trim(); loadFile(inputFile, FileLoadPlugin.TasselFileType.Polymorphism); } else if (current.equalsIgnoreCase("-a")) { String inputFile = args[index++].trim(); loadFile(inputFile, FileLoadPlugin.TasselFileType.Annotated); } else if (current.equalsIgnoreCase("-k")) { String kinshipFile = args[index++].trim(); loadFile(kinshipFile, FileLoadPlugin.TasselFileType.SqrMatrix); } else if (current.equalsIgnoreCase("-q")) { String populationFile = args[index++].trim(); loadFile(populationFile, FileLoadPlugin.TasselFileType.Phenotype); } else if (current.equalsIgnoreCase("-h")) { String hapFile = args[index++].trim(); loadFile(hapFile, FileLoadPlugin.TasselFileType.Hapmap); } else if (current.equalsIgnoreCase("-r")) { String phenotypeFile = args[index++].trim(); loadFile(phenotypeFile, FileLoadPlugin.TasselFileType.Phenotype); } else if (current.equalsIgnoreCase("-plink")) { String pedFile = null; String mapFile = null; for (int i = 0; i < 2; i++) { String fileType = args[index++].trim(); String filename = args[index++].trim(); if (fileType.equalsIgnoreCase("-ped")) { pedFile = filename; } else if (fileType.equalsIgnoreCase("-map")) { mapFile = filename; } else { throw new IllegalArgumentException("TasselPipeline: parseArgs: -plink: unknown file type: " + fileType); } } if ((pedFile == null) || (mapFile == null)) { throw new IllegalArgumentException("TasselPipeline: parseArgs: -plink must specify both ped and map files."); } PlinkLoadPlugin plugin = new PlinkLoadPlugin(myMainFrame, false); plugin.setPedFile(pedFile); plugin.setMapFile(mapFile); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-flapjack")) { String genoFile = null; String mapFile = null; for (int i = 0; i < 2; i++) { String fileType = args[index++].trim(); String filename = args[index++].trim(); if (fileType.equalsIgnoreCase("-geno")) { genoFile = filename; } else if (fileType.equalsIgnoreCase("-map")) { mapFile = filename; } else { throw new IllegalArgumentException("TasselPipeline: parseArgs: -flapjack: unknown file type: " + fileType); } } if ((genoFile == null) || (mapFile == null)) { throw new IllegalArgumentException("TasselPipeline: parseArgs: -flapjack must specify both ped and map files."); } FlapjackLoadPlugin plugin = new FlapjackLoadPlugin(myMainFrame, false); plugin.setGenoFile(genoFile); plugin.setMapFile(mapFile); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-fasta")) { String fastaFile = args[index++].trim(); loadFile(fastaFile, FileLoadPlugin.TasselFileType.Fasta); } else if (current.equalsIgnoreCase("-geneticMap")) { String geneticMapFile = args[index++].trim(); loadFile(geneticMapFile, FileLoadPlugin.TasselFileType.GeneticMap); } else if (current.equalsIgnoreCase("-readSerialAlignment")) { String file = args[index++].trim(); loadFile(file, FileLoadPlugin.TasselFileType.Serial); } else if (current.equalsIgnoreCase("-taxaJoinStrict")) { String temp = args[index++].trim(); boolean strict = true; if (temp.equalsIgnoreCase("false")) { strict = false; } else if (temp.equalsIgnoreCase("true")) { strict = true; } else { throw new IllegalArgumentException("TasselPipeline: parseArgs: -taxaJoinStrict parameter must be true or false."); } TasselPrefs.putIDJoinStrict(strict); } else if (current.equalsIgnoreCase("-retainRareAlleles")) { String temp = args[index++].trim(); boolean retain = true; if (temp.equalsIgnoreCase("false")) { retain = false; } else if (temp.equalsIgnoreCase("true")) { retain = true; } else { throw new IllegalArgumentException("TasselPipeline: parseArgs: -retainRareAlleles parameter must be true or false."); } TasselPrefs.putAlignmentRetainRareAlleles(retain); } else if (current.equalsIgnoreCase("-maxAllelesToRetain")) { String temp = args[index++].trim(); int maxAlleles = 0; try { maxAlleles = Integer.parseInt(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing max alleles to retain: " + temp); } TasselPrefs.putAlignmentMaxAllelesToRetain(maxAlleles); } else if (current.equalsIgnoreCase("-union")) { UnionAlignmentPlugin plugin = new UnionAlignmentPlugin(myMainFrame, false); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-intersect")) { IntersectionAlignmentPlugin plugin = new IntersectionAlignmentPlugin(myMainFrame, false); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-separate")) { SeparatePlugin plugin = new SeparatePlugin(myMainFrame, false); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-mergeAlignments")) { MergeAlignmentsPlugin plugin = new MergeAlignmentsPlugin(myMainFrame, false); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-mergeAlignmentsSameSites")) { MergeAlignmentsSameSitesPlugin plugin = new MergeAlignmentsSameSitesPlugin(myMainFrame); try { for (int i = 0; i < 2; i++) { String paraType = args[index++].trim(); String value = args[index++].trim(); if (paraType.equalsIgnoreCase("-input")) { String[] files = value.split(","); List<String> filenames = new ArrayList<String>(); for (int j = 0; j < files.length; j++) { filenames.add(files[j]); } plugin.setInputFiles(filenames); } else if (paraType.equalsIgnoreCase("-output")) { plugin.setOutputFile(value); } else { throw new IllegalArgumentException("TasselPipeline: parseArgs: -mergeAlignmentsSameSites: unknown descriptor: " + paraType); } } } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: -mergeAlignmentsSameSites: not specified correctly."); } integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-excludeLastTrait")) { FilterTraitsPlugin plugin = new FilterTraitsPlugin(myMainFrame, false); ArrayList input = new ArrayList(); int[] excludeLast = new int[]{-1}; input.add(excludeLast); plugin.setIncludeList(input); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-mlm")) { MLMPlugin plugin = new MLMPlugin(myMainFrame, false); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-mlmVarCompEst")) { MLMPlugin plugin = (MLMPlugin) findLastPluginFromCurrentPipe(new Class[]{MLMPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No MLM step defined: " + current); } String method = args[index++].trim(); plugin.setVarCompEst(method); } else if (current.equalsIgnoreCase("-mlmCompressionLevel")) { MLMPlugin plugin = (MLMPlugin) findLastPluginFromCurrentPipe(new Class[]{MLMPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No MLM step defined: " + current); } String type = args[index++].trim(); if (type.equalsIgnoreCase("Optimum")) { plugin.setCompressionType(MLMPlugin.CompressionType.Optimum); } else if (type.equalsIgnoreCase("Custom")) { plugin.setCompressionType(MLMPlugin.CompressionType.Custom); } else if (type.equalsIgnoreCase("None")) { plugin.setCompressionType(MLMPlugin.CompressionType.None); } else { throw new IllegalArgumentException("TasselPipeline: parseArgs: Unknown compression type: " + type); } } else if (current.equalsIgnoreCase("-mlmCustomCompression")) { MLMPlugin plugin = (MLMPlugin) findLastPluginFromCurrentPipe(new Class[]{MLMPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No MLM step defined: " + current); } String temp = args[index++].trim(); double value = 0; try { value = Double.parseDouble(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing custom compression: " + temp); } plugin.setCustomCompression(value); } else if (current.equalsIgnoreCase("-mlmOutputFile")) { MLMPlugin plugin = (MLMPlugin) findLastPluginFromCurrentPipe(new Class[]{MLMPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No MLM step defined: " + current); } String filename = args[index++].trim(); plugin.setOutputName(filename); } else if (current.equalsIgnoreCase("-mlmMaxP")) { MLMPlugin plugin = (MLMPlugin) findLastPluginFromCurrentPipe(new Class[]{MLMPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No MLM step defined: " + current); } String temp = args[index++].trim(); double maxP = 0; try { maxP = Double.parseDouble(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing max P: " + temp); } plugin.setMaxp(maxP); } else if (current.equalsIgnoreCase("-glm")) { FixedEffectLMPlugin plugin = new FixedEffectLMPlugin(myMainFrame, false); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-glmOutputFile")) { FixedEffectLMPlugin plugin = (FixedEffectLMPlugin) findLastPluginFromCurrentPipe(new Class[]{FixedEffectLMPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No GLM step defined: " + current); } String filename = args[index++].trim(); plugin.setOutputFile(filename); } else if (current.equalsIgnoreCase("-glmMaxP")) { FixedEffectLMPlugin plugin = (FixedEffectLMPlugin) findLastPluginFromCurrentPipe(new Class[]{FixedEffectLMPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No GLM step defined: " + current); } String temp = args[index++].trim(); double maxP = 0; try { maxP = Double.parseDouble(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing max P: " + temp); } plugin.setMaxP(maxP); } else if (current.equalsIgnoreCase("-glmPermutations")) { FixedEffectLMPlugin plugin = (FixedEffectLMPlugin) findLastPluginFromCurrentPipe(new Class[]{FixedEffectLMPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No GLM step defined: " + current); } String temp = args[index++].trim(); int permutations = 0; try { permutations = Integer.parseInt(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing number of permutations: " + temp); } plugin.setPermute(true); plugin.setNumberOfPermutations(permutations); } else if (current.equalsIgnoreCase("-td_csv")) { String csvFile = args[index++].trim(); getTableDisplayPlugin(csvFile, current); } else if (current.equalsIgnoreCase("-td_tab")) { String tabFile = args[index++].trim(); getTableDisplayPlugin(tabFile, current); } else if (current.equalsIgnoreCase("-td_gui")) { getTableDisplayPlugin(null, current); } else if (current.equalsIgnoreCase("-ld")) { getLinkageDisequilibriumPlugin(); } else if (current.equalsIgnoreCase("-ldPermNum")) { LinkageDisequilibriumPlugin plugin = null; try { plugin = (LinkageDisequilibriumPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDisequilibriumPlugin step defined: " + current); } String str = args[index++].trim(); int permNum = -1; try { permNum = Integer.parseInt(str); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem with LD Permutation number: " + str); } if (permNum < 1) { throw new IllegalArgumentException("TasselPipeline: parseArgs: LD Permutation size can't be less than 1."); } plugin.setPermutationNumber(permNum); } else if (current.equalsIgnoreCase("-ldTestSite")) { LinkageDisequilibriumPlugin plugin = null; try { plugin = (LinkageDisequilibriumPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDisequilibriumPlugin step defined: " + current); } String str = args[index++].trim(); int testSite = -1; try { testSite = Integer.parseInt(str); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem with LD Test Site number: " + str); } if (testSite < 1) { throw new IllegalArgumentException("TasselPipeline: parseArgs: LD Test Site can't be less than 1."); } plugin.setTestSite(testSite); } else if (current.equalsIgnoreCase("-ldWinSize")) { LinkageDisequilibriumPlugin plugin = null; try { plugin = (LinkageDisequilibriumPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDisequilibriumPlugin step defined: " + current); } String str = args[index++].trim(); int winSize = -1; try { winSize = Integer.parseInt(str); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem with LD Window Size: " + str); } if (winSize < 1) { throw new IllegalArgumentException("TasselPipeline: parseArgs: LD Window Size can't be less than 1."); } plugin.setWinSize(winSize); } else if (current.equalsIgnoreCase("-ldRapidAnalysis")) { LinkageDisequilibriumPlugin plugin = null; try { plugin = (LinkageDisequilibriumPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDisequilibriumPlugin step defined: " + current); } String temp = args[index++].trim(); boolean rapid = true; if (temp.equalsIgnoreCase("false")) { rapid = false; } else if (temp.equalsIgnoreCase("true")) { rapid = true; } else { throw new IllegalArgumentException("TasselPipeline: parseArgs: LD Rapid Analysis parameter must be true or false."); } plugin.setRapidAnalysis(rapid); } else if (current.equalsIgnoreCase("-ldType")) { LinkageDisequilibriumPlugin plugin = null; try { plugin = (LinkageDisequilibriumPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDisequilibriumPlugin step defined: " + current); } String temp = args[index++].trim(); if (temp.equalsIgnoreCase("All")) { plugin.setLDType(testDesign.All); } else if (temp.equalsIgnoreCase("SlidingWindow")) { plugin.setLDType(testDesign.SlidingWindow); } else if (temp.equalsIgnoreCase("SiteByAll")) { plugin.setLDType(testDesign.SiteByAll); } else { throw new IllegalArgumentException("TasselPipeline: parseArgs: LD Type parameter must be All, SlidingWindow, or SiteByAll."); } } else if (current.equalsIgnoreCase("-ldd")) { String outputType = args[index++].trim(); getLinkageDiseqDisplayPlugin(outputType); } else if (current.equalsIgnoreCase("-ldplotsize")) { LinkageDiseqDisplayPlugin plugin = null; try { plugin = (LinkageDiseqDisplayPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDiseqDisplay step defined: " + current); } String str = args[index++].trim(); int plotSize = -1; try { plotSize = Integer.parseInt(str); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem with LD Plot size number: " + str); } if (plotSize < 1) { throw new IllegalArgumentException("TasselPipeline: parseArgs: LD Plot size can't be less than 1."); } plugin.setImageSize(plotSize, plotSize); } else if (current.equalsIgnoreCase("-ldplotlabels")) { LinkageDiseqDisplayPlugin plugin = null; try { plugin = (LinkageDiseqDisplayPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDiseqDisplay step defined: " + current); } String temp = args[index++].trim(); boolean ldPlotLabels = true; if (temp.equalsIgnoreCase("false")) { ldPlotLabels = false; } else if (temp.equalsIgnoreCase("true")) { ldPlotLabels = true; } else { throw new IllegalArgumentException("TasselPipeline: parseArgs: LD Plot labels parameter must be true or false."); } plugin.setShowLabels(ldPlotLabels); } else if (current.equalsIgnoreCase("-o")) { Plugin plugin = findLastPluginFromCurrentPipe(new Class[]{LinkageDiseqDisplayPlugin.class}); String temp = args[index++].trim(); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDiseqDisplay step defined: " + current + " " + temp); } else if (plugin instanceof LinkageDiseqDisplayPlugin) { ((LinkageDiseqDisplayPlugin) plugin).setSaveFile(new File(temp)); } } else if (current.equalsIgnoreCase("-ck")) { KinshipPlugin plugin = new KinshipPlugin(myMainFrame, false); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-ckModelHets")) { throw new IllegalArgumentException("TasselPipeline: parseArgs: -ckModelHets not needed in Tassel 4.0. It is designed to handle heterzygotes."); } else if (current.equalsIgnoreCase("-ckRescale")) { throw new IllegalArgumentException("TasselPipeline: parseArgs: -ckRescale not needed in Tassel 4.0. It is designed to handle heterzygotes."); } else if (current.equalsIgnoreCase("-gs")) { RidgeRegressionEmmaPlugin plugin = new RidgeRegressionEmmaPlugin(myMainFrame, false); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-genotypeSummary")) { GenotypeSummaryPlugin plugin = new GenotypeSummaryPlugin(myMainFrame, false); String temp = args[index++].trim(); String[] types = temp.split(","); plugin.setCaculateOverview(false); plugin.setCalculateSiteSummary(false); plugin.setCalculateTaxaSummary(false); for (int i = 0; i < types.length; i++) { if (types[i].equalsIgnoreCase("overall")) { plugin.setCaculateOverview(true); } else if (types[i].equalsIgnoreCase("site")) { plugin.setCalculateSiteSummary(true); } else if (types[i].equalsIgnoreCase("taxa")) { plugin.setCalculateTaxaSummary(true); } else if (types[i].equalsIgnoreCase("all")) { plugin.setCaculateOverview(true); plugin.setCalculateSiteSummary(true); plugin.setCalculateTaxaSummary(true); } else { throw new IllegalArgumentException("TasselPipeline: parseArgs: -genotypeSummary illegal types: " + temp); } } integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-export")) { String[] filenames = args[index++].trim().split(","); ExportMultiplePlugin plugin = new ExportMultiplePlugin(myMainFrame); plugin.setSaveFiles(filenames); integratePlugin(plugin, false); } else if (current.equalsIgnoreCase("-exportType")) { ExportMultiplePlugin plugin = (ExportMultiplePlugin) findLastPluginFromCurrentPipe(new Class[]{ExportMultiplePlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Export step defined: " + current); } String type = args[index++].trim(); if (type.equalsIgnoreCase(FileLoadPlugin.TasselFileType.Flapjack.toString())) { plugin.setAlignmentFileType(FileLoadPlugin.TasselFileType.Flapjack); } else if (type.equalsIgnoreCase(FileLoadPlugin.TasselFileType.Hapmap.toString())) { plugin.setAlignmentFileType(FileLoadPlugin.TasselFileType.Hapmap); } else if (type.equalsIgnoreCase(FileLoadPlugin.TasselFileType.HapmapDiploid.toString())) { plugin.setAlignmentFileType(FileLoadPlugin.TasselFileType.HapmapDiploid); } else if (type.equalsIgnoreCase(FileLoadPlugin.TasselFileType.Phylip_Inter.toString())) { plugin.setAlignmentFileType(FileLoadPlugin.TasselFileType.Phylip_Inter); } else if (type.equalsIgnoreCase(FileLoadPlugin.TasselFileType.Phylip_Seq.toString())) { plugin.setAlignmentFileType(FileLoadPlugin.TasselFileType.Phylip_Seq); } else if (type.equalsIgnoreCase(FileLoadPlugin.TasselFileType.Plink.toString())) { plugin.setAlignmentFileType(FileLoadPlugin.TasselFileType.Plink); } else if (type.equalsIgnoreCase(FileLoadPlugin.TasselFileType.Serial.toString())) { plugin.setAlignmentFileType(FileLoadPlugin.TasselFileType.Serial); } } else if (current.equalsIgnoreCase("-impute")) { GenotypeImputationPlugin plugin = new GenotypeImputationPlugin(myMainFrame, false); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-imputeMethod")) { GenotypeImputationPlugin plugin = (GenotypeImputationPlugin) findLastPluginFromCurrentPipe(new Class[]{GenotypeImputationPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Impute step defined: " + current); } String temp = args[index++].trim(); if (temp.equalsIgnoreCase(GenotypeImputationPlugin.ImpMethod.Length.toString())) { plugin.setMethod(GenotypeImputationPlugin.ImpMethod.Length); } else if (temp.equalsIgnoreCase(GenotypeImputationPlugin.ImpMethod.MajorAllele.toString())) { plugin.setMethod(GenotypeImputationPlugin.ImpMethod.MajorAllele); } else if (temp.equalsIgnoreCase(GenotypeImputationPlugin.ImpMethod.IBDProb.toString())) { plugin.setMethod(GenotypeImputationPlugin.ImpMethod.IBDProb); } else if (temp.equalsIgnoreCase(GenotypeImputationPlugin.ImpMethod.SimilarWindow.toString())) { plugin.setMethod(GenotypeImputationPlugin.ImpMethod.SimilarWindow); } else { throw new IllegalArgumentException("TasselPipeline: parseArgs: Not defined impute method: " + temp); } } else if (current.equalsIgnoreCase("-imputeMinLength")) { GenotypeImputationPlugin plugin = (GenotypeImputationPlugin) findLastPluginFromCurrentPipe(new Class[]{GenotypeImputationPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Impute step defined: " + current); } String temp = args[index++].trim(); int minLength = 0; try { minLength = Integer.parseInt(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing impute min length: " + temp); } plugin.setMinLength(minLength); } else if (current.equalsIgnoreCase("-imputeMaxMismatch")) { GenotypeImputationPlugin plugin = (GenotypeImputationPlugin) findLastPluginFromCurrentPipe(new Class[]{GenotypeImputationPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Impute step defined: " + current); } String temp = args[index++].trim(); int maxMismatch = 0; try { maxMismatch = Integer.parseInt(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing impute max mismatch: " + temp); } plugin.setMaxMisMatch(maxMismatch); } else if (current.equalsIgnoreCase("-imputeMinProb")) { GenotypeImputationPlugin plugin = (GenotypeImputationPlugin) findLastPluginFromCurrentPipe(new Class[]{GenotypeImputationPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Impute step defined: " + current); } String temp = args[index++].trim(); double minProb = 0; try { minProb = Double.parseDouble(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing impute min probability: " + temp); } plugin.setMinProb(minProb); } else if (current.equalsIgnoreCase("-filterAlign")) { FilterAlignmentPlugin plugin = new FilterAlignmentPlugin(myMainFrame, false); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-filterAlignMinCount")) { FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current); } String temp = args[index++].trim(); int minCount = 0; try { minCount = Integer.parseInt(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing filter alignment min count: " + temp); } plugin.setMinCount(minCount); } else if (current.equalsIgnoreCase("-filterAlignMinFreq")) { FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current); } String temp = args[index++].trim(); double minFreq = 0; try { minFreq = Double.parseDouble(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing filter alignment min frequency: " + temp); } plugin.setMinFreq(minFreq); } else if (current.equalsIgnoreCase("-filterAlignMaxFreq")) { FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current); } String temp = args[index++].trim(); double maxFreq = 0; try { maxFreq = Double.parseDouble(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing filter alignment max frequency: " + temp); } plugin.setMaxFreq(maxFreq); } else if (current.equalsIgnoreCase("-filterAlignStart")) { FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current); } String temp = args[index++].trim(); int start = 0; try { start = Integer.parseInt(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing filter alignment start: " + temp); } plugin.setStart(start); } else if (current.equalsIgnoreCase("-filterAlignEnd")) { FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current); } String temp = args[index++].trim(); int end = 0; try { end = Integer.parseInt(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing filter alignment end: " + temp); } plugin.setEnd(end); } else if (current.equalsIgnoreCase("-filterAlignExtInd")) { FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current); } plugin.setExtractIndels(true); } else if (current.equalsIgnoreCase("-filterAlignRemMinor")) { FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current); } plugin.setFilterMinorSNPs(true); } else if (current.equalsIgnoreCase("-filterAlignSliding")) { FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current); } plugin.setDoSlidingHaps(true); } else if (current.equalsIgnoreCase("-filterAlignHapLen")) { FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current); } String temp = args[index++].trim(); int hapLen = 0; try { hapLen = Integer.parseInt(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing filter alignment haplotype length: " + temp); } plugin.setWinSize(hapLen); } else if (current.equalsIgnoreCase("-filterAlignStepLen")) { FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class}); if (plugin == null) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current); } String temp = args[index++].trim(); int stepLen = 0; try { stepLen = Integer.parseInt(temp); } catch (Exception e) { throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing filter alignment step length: " + temp); } plugin.setStepSize(stepLen); } else if (current.equalsIgnoreCase("-numericalGenoTransform")) { NumericalGenotypePlugin plugin = new NumericalGenotypePlugin(); String temp = args[index++].trim(); if (temp.equalsIgnoreCase(NumericalGenotypePlugin.TRANSFORM_TYPE.colapse.toString())) { plugin.setTransformType(NumericalGenotypePlugin.TRANSFORM_TYPE.colapse); } else if (temp.equalsIgnoreCase(NumericalGenotypePlugin.TRANSFORM_TYPE.separated.toString())) { plugin.setTransformType(NumericalGenotypePlugin.TRANSFORM_TYPE.separated); } else { throw new IllegalArgumentException("TasselPipeline: parseArgs: Not defined genotype transform type: " + temp); } integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-includeTaxa")) { FilterTaxaAlignmentPlugin plugin = new FilterTaxaAlignmentPlugin(myMainFrame, false); String[] taxa = args[index++].trim().split(","); Identifier[] ids = new Identifier[taxa.length]; for (int i = 0; i < taxa.length; i++) { ids[i] = new Identifier(taxa[i]); } plugin.setIdsToKeep(new SimpleIdGroup(ids)); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-includeTaxaInFile")) { FilterTaxaAlignmentPlugin plugin = new FilterTaxaAlignmentPlugin(myMainFrame, false); String taxaListFile = args[index++].trim(); List taxa = new ArrayList(); BufferedReader br = null; try { br = Utils.getBufferedReader(taxaListFile); String inputline = br.readLine(); Pattern sep = Pattern.compile("\\s+"); while (inputline != null) { inputline = inputline.trim(); String[] parsedline = sep.split(inputline); for (int i = 0; i < parsedline.length; i++) { if ((parsedline[i] != null) || (parsedline[i].length() != 0)) { taxa.add(parsedline[i]); } } inputline = br.readLine(); } } finally { br.close(); } Identifier[] ids = new Identifier[taxa.size()]; for (int i = 0; i < taxa.size(); i++) { ids[i] = new Identifier((String) taxa.get(i)); } plugin.setIdsToKeep(new SimpleIdGroup(ids)); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-excludeTaxa")) { FilterTaxaAlignmentPlugin plugin = new FilterTaxaAlignmentPlugin(myMainFrame, false); String[] taxa = args[index++].trim().split(","); Identifier[] ids = new Identifier[taxa.length]; for (int i = 0; i < taxa.length; i++) { ids[i] = new Identifier(taxa[i]); } plugin.setIdsToRemove(new SimpleIdGroup(ids)); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-excludeTaxaInFile")) { FilterTaxaAlignmentPlugin plugin = new FilterTaxaAlignmentPlugin(myMainFrame, false); String taxaListFile = args[index++].trim(); List taxa = new ArrayList(); BufferedReader br = null; try { br = Utils.getBufferedReader(taxaListFile); String inputline = br.readLine(); Pattern sep = Pattern.compile("\\s+"); while (inputline != null) { inputline = inputline.trim(); String[] parsedline = sep.split(inputline); for (int i = 0; i < parsedline.length; i++) { if ((parsedline[i] != null) || (parsedline[i].length() != 0)) { taxa.add(parsedline[i]); } } inputline = br.readLine(); } } finally { br.close(); } Identifier[] ids = new Identifier[taxa.size()]; for (int i = 0; i < taxa.size(); i++) { ids[i] = new Identifier((String) taxa.get(i)); } plugin.setIdsToRemove(new SimpleIdGroup(ids)); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-includeSiteNames")) { FilterSiteNamePlugin plugin = new FilterSiteNamePlugin(myMainFrame, false); String[] names = args[index++].trim().split(","); plugin.setSiteNamesToKeep(names); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-includeSiteNamesInFile")) { FilterSiteNamePlugin plugin = new FilterSiteNamePlugin(myMainFrame, false); String siteNameListFile = args[index++].trim(); List siteNames = new ArrayList(); BufferedReader br = null; try { br = Utils.getBufferedReader(siteNameListFile); String inputline = br.readLine(); Pattern sep = Pattern.compile("\\s+"); while (inputline != null) { inputline = inputline.trim(); String[] parsedline = sep.split(inputline); for (int i = 0; i < parsedline.length; i++) { if ((parsedline[i] != null) || (parsedline[i].length() != 0)) { siteNames.add(parsedline[i]); } } inputline = br.readLine(); } } finally { br.close(); } String[] siteNameArray = new String[siteNames.size()]; siteNameArray = (String[]) siteNames.toArray(siteNameArray); plugin.setSiteNamesToKeep(siteNameArray); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-excludeSiteNames")) { FilterSiteNamePlugin plugin = new FilterSiteNamePlugin(myMainFrame, false); String[] sites = args[index++].trim().split(","); plugin.setSiteNamesToRemove(sites); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-excludeSiteNamesInFile")) { FilterSiteNamePlugin plugin = new FilterSiteNamePlugin(myMainFrame, false); String siteNameListFile = args[index++].trim(); List siteNames = new ArrayList(); BufferedReader br = null; try { br = Utils.getBufferedReader(siteNameListFile); String inputline = br.readLine(); Pattern sep = Pattern.compile("\\s+"); while (inputline != null) { inputline = inputline.trim(); String[] parsedline = sep.split(inputline); for (int i = 0; i < parsedline.length; i++) { if ((parsedline[i] != null) || (parsedline[i].length() != 0)) { siteNames.add(parsedline[i]); } } inputline = br.readLine(); } } finally { br.close(); } String[] names = new String[siteNames.size()]; for (int i = 0; i < siteNames.size(); i++) { names[i] = (String) siteNames.get(i); } plugin.setSiteNamesToRemove(names); integratePlugin(plugin, true); } else if (current.equalsIgnoreCase("-newCoordinates")) { ConvertAlignmentCoordinatesPlugin plugin = new ConvertAlignmentCoordinatesPlugin(myMainFrame); String mapFile = args[index++].trim(); plugin.setMapFilename(mapFile); integratePlugin(plugin, true); } else { try { Plugin plugin = null; String possibleClassName = current.substring(1); List<String> matches = Utils.getFullyQualifiedClassNames(possibleClassName); for (String match : matches) { try { Class currentMatch = Class.forName(match); Constructor constructor = currentMatch.getConstructor(Frame.class); plugin = (Plugin) constructor.newInstance(myMainFrame); break; } catch (NoSuchMethodException nsme) { myLogger.warn("Self-describing Plugins should implement this constructor: " + current); myLogger.warn("public Plugin(Frame parentFrame) {"); myLogger.warn(" super(parentFrame, false);"); myLogger.warn("}"); } catch (Exception e) { // do nothing } } if (plugin == null) { try { Class possibleClass = Class.forName(possibleClassName); Constructor constructor = possibleClass.getConstructor(Frame.class); plugin = (Plugin) constructor.newInstance(myMainFrame); } catch (NoSuchMethodException nsme) { myLogger.warn("Self-describing Plugins should implement this constructor: " + current); myLogger.warn("public Plugin(Frame parentFrame) {"); myLogger.warn(" super(parentFrame, false);"); myLogger.warn("}"); } catch (Exception e) { // do nothing } } if (plugin != null) { List pluginArgs = new ArrayList(); if (index == args.length) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No -endPlugin flag specified."); } String temp = args[index++].trim(); while (!temp.equalsIgnoreCase("-endPlugin")) { pluginArgs.add(temp); if (index == args.length) { throw new IllegalArgumentException("TasselPipeline: parseArgs: No -endPlugin flag specified."); } temp = args[index++].trim(); } String[] result = new String[pluginArgs.size()]; result = (String[]) pluginArgs.toArray(result); plugin.setParameters(result); integratePlugin(plugin, true); } else { throw new IllegalArgumentException("TasselPipeline: parseArgs: Unknown parameter: " + current); } } catch (UnsupportedOperationException usoe) { throw new IllegalArgumentException("TasselPipeline: parseArgs: this plugin is not self-described: " + current); } catch (Exception e) { ExceptionUtils.logExceptionCauses(e, myLogger, Level.ERROR); throw new IllegalArgumentException("TasselPipeline: parseArgs: Unknown parameter: " + current); } } } catch (Exception e) { e.printStackTrace(); System.exit(1); } } if (myFirstPlugin != null) { //((AbstractPlugin) myFirstPlugin).trace(0); tracePipeline(); } else { myLogger.warn("parseArgs: no arguments specified."); } } private void tracePipeline() { for (int i = 0; i < myThreads.size(); i++) { Plugin current = (Plugin) ((ThreadedPluginListener) myThreads.get(i)).getPluginListener(); ((AbstractPlugin) current).trace(0); } } public FileLoadPlugin loadFile(String filename, FileLoadPlugin.TasselFileType fileType) { myLogger.info("loadFile: " + filename); FileLoadPlugin plugin = new FileLoadPlugin(myMainFrame, false); if (fileType == null) { plugin.setTheFileType(FileLoadPlugin.TasselFileType.Unknown); } else { plugin.setTheFileType(fileType); } plugin.setOpenFiles(new String[]{filename}); integratePlugin(plugin, true); return plugin; } public TableDisplayPlugin getTableDisplayPlugin(String filename, String flag) { TableDisplayPlugin plugin = null; if (flag.equalsIgnoreCase("-td_gui")) { plugin = new TableDisplayPlugin(myMainFrame, true); integratePlugin(plugin, false); } else if (flag.equalsIgnoreCase("-td_tab")) { myLogger.info("getTableDisplayPlugin: " + filename); plugin = new TableDisplayPlugin(myMainFrame, false); plugin.setDelimiter("\t"); plugin.setSaveFile(new File(filename)); integratePlugin(plugin, false); } else if (flag.equalsIgnoreCase("-td_csv")) { myLogger.info("getTableDisplayPlugin: " + filename); plugin = new TableDisplayPlugin(myMainFrame, false); plugin.setDelimiter(","); plugin.setSaveFile(new File(filename)); integratePlugin(plugin, false); } return plugin; } public LinkageDisequilibriumPlugin getLinkageDisequilibriumPlugin() { LinkageDisequilibriumPlugin plugin = new LinkageDisequilibriumPlugin(myMainFrame, false); integratePlugin(plugin, true); return plugin; } public LinkageDiseqDisplayPlugin getLinkageDiseqDisplayPlugin(String type) { LinkageDiseqDisplayPlugin plugin = new LinkageDiseqDisplayPlugin(myMainFrame, true); if (type.equalsIgnoreCase("gui")) { plugin = new LinkageDiseqDisplayPlugin(null, true); plugin.setBlockSchematic(false); plugin.setLowerCorner(LinkageDisequilibriumComponent.P_VALUE); plugin.setUpperCorner(LinkageDisequilibriumComponent.RSQUARE); } else { plugin = new LinkageDiseqDisplayPlugin(null, false); plugin.setBlockSchematic(false); plugin.setLowerCorner(LinkageDisequilibriumComponent.P_VALUE); plugin.setUpperCorner(LinkageDisequilibriumComponent.RSQUARE); if (type.equalsIgnoreCase("png")) { plugin.setOutformat(AbstractDisplayPlugin.Outformat.png); } else if (type.equalsIgnoreCase("gif")) { plugin.setOutformat(AbstractDisplayPlugin.Outformat.gif); } else if (type.equalsIgnoreCase("bmp")) { plugin.setOutformat(AbstractDisplayPlugin.Outformat.bmp); } else if (type.equalsIgnoreCase("jpg")) { plugin.setOutformat(AbstractDisplayPlugin.Outformat.jpg); } else if (type.equalsIgnoreCase("svg")) { plugin.setOutformat(AbstractDisplayPlugin.Outformat.svg); } else { throw new IllegalArgumentException("TasselPipeline: getLinkageDiseqDisplayPlugin: unknown output type: " + type); } } integratePlugin(plugin, false); return plugin; } private void integratePlugin(Plugin plugin, boolean displayDataTree) { if (myFirstPlugin == null) { myFirstPlugin = plugin; } if (displayDataTree) { plugin.addListener(this); } if (myCurrentPipe == null) { myCurrentPipe = new ArrayList(); } if (myCurrentPipe.size() == 0) { myCurrentPipe.add(plugin); } else { plugin.receiveInput(((Plugin) myCurrentPipe.get(myCurrentPipe.size() - 1))); myCurrentPipe.add(plugin); } } private Plugin findLastPluginFromAll(Class[] types) { if ((myCurrentPipe != null) && (myCurrentPipe.size() != 0)) { for (int i = myCurrentPipe.size() - 1; i >= 0; i Plugin current = (Plugin) myCurrentPipe.get(i); if (matchType(types, current)) { return current; } } } List keys = new ArrayList(myForks.keySet()); for (int i = keys.size() - 1; i >= 0; i List currentPipe = (List) myForks.get(keys.get(i)); for (int j = currentPipe.size() - 1; j >= 0; j Plugin current = (Plugin) currentPipe.get(j); if (matchType(types, current)) { return current; } } } return null; } private Plugin findLastPluginFromCurrentPipe(Class[] types) { if ((myCurrentPipe != null) && (myCurrentPipe.size() != 0)) { for (int i = myCurrentPipe.size() - 1; i >= 0; i Plugin current = (Plugin) myCurrentPipe.get(i); if (matchType(types, current)) { return current; } } } return null; } private boolean matchType(Class[] types, Object test) { for (int i = 0; i < types.length; i++) { if (types[i].isInstance(test)) { return true; } } return false; } /** * Returns Tassel data set after complete. * * @param event event */ public void dataSetReturned(PluginEvent event) { DataSet tds = (DataSet) event.getSource(); if ((tds != null) && (tds.getSize() != 0) && (myMainFrame != null)) { myMainFrame.getDataTreePanel().addDataSet(tds, DataTreePanel.NODE_TYPE_DEFAULT); } } /** * Returns progress of execution. * * @param event event */ public void progress(PluginEvent event) { if (myMainFrame == null) { DataSet ds = (DataSet) event.getSource(); if (ds != null) { List percentage = ds.getDataOfType(Integer.class); Plugin plugin = ds.getCreator(); Integer lastValue = (Integer) myProgressValues.get(plugin); if (lastValue == null) { lastValue = new Integer(0); } if (percentage.size() > 0) { Datum datum = (Datum) percentage.get(0); Integer percent = (Integer) datum.getData(); if (percent >= lastValue) { myLogger.info(ds.getCreator().getClass().getName() + ": progress: " + percent.intValue() + "%"); lastValue = lastValue + 10; myProgressValues.put(plugin, lastValue); } } } } } }
package org.xins.server; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.znerd.xmlenc.XMLOutputter; /** * Base class for API implementation classes. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ public abstract class API extends Object implements DefaultReturnCodes { // Class fields /** * Checks if the specified value is <code>null</code> or an empty string. * Only if it is then <code>true</code> is returned. * * @param value * the value to check. * * @return * <code>true</code> if and only if <code>value != null &amp;&amp; * value.length() != 0</code>. */ protected final static boolean isMissing(String value) { return value == null || value.length() == 0; } // Class functions // Constructors /** * Constructs a new <code>API</code> object. */ protected API() { _functionsByName = new HashMap(); _functionList = new ArrayList(); } // Fields /** * Map that maps function names to <code>Function</code> instances. * Contains all functions associated with this API. * * <p />This field is initialised to a non-<code>null</code> value by the * constructor. */ private final Map _functionsByName; /** * List of all functions. This field cannot be <code>null</code>. */ private final List _functionList; // Methods /** * Initialises this API. * * <p />The implementation of this method in class {@link API} is empty. * * @param properties * the properties, can be <code>null</code>. * * @throws Throwable * if the initialisation fails. */ public void init(Properties properties) throws Throwable { // empty } /** * Callback method invoked when a function is constructed. * * @param function * the function that is added, not <code>null</code>. * * @throws NullPointerException * if <code>function == null</code>. */ final void functionAdded(Function function) { _functionsByName.put(function.getName(), function); _functionList.add(function); } /** * Returns the function with the specified name. * * @param name * the name of the function, will not be checked if it is * <code>null</code>. * * @return * the function with the specified name, or <code>null</code> if there * is no match. */ final Function getFunction(String name) { return (Function) _functionsByName.get(name); } /** * Forwards a call to the <code>handleCall(CallContext)</code> method. * * @param out * the output stream to write to, not <code>null</code>. * * @param map * the parameters, not <code>null</code>. * * @throws IOException * if an I/O error occurs. */ final void handleCall(PrintWriter out, Map map) throws IOException { // Reset the XMLOutputter StringWriter stringWriter = new StringWriter(); XMLOutputter xmlOutputter = new XMLOutputter(stringWriter, "UTF-8"); // Create a new call context CallContext context = new CallContext(xmlOutputter, map); // Determine the function name String functionName = context.getFunction(); if ("_GetFunctionList".equals(functionName)) { doGetFunctionList(context); return; } // Forward the call boolean exceptionThrown = true; boolean success; String code; try { handleCall(context); success = context.getSuccess(); code = context.getCode(); exceptionThrown = false; } catch (Throwable exception) { success = false; code = INTERNAL_ERROR; xmlOutputter.reset(out, "UTF-8"); xmlOutputter.startTag("result"); xmlOutputter.attribute("success", "false"); xmlOutputter.attribute("code", code); xmlOutputter.startTag("param"); xmlOutputter.attribute("name", "_exception.class"); xmlOutputter.pcdata(exception.getClass().getName()); String message = exception.getMessage(); if (message != null && message.length() > 0) { xmlOutputter.endTag(); xmlOutputter.startTag("param"); xmlOutputter.attribute("name", "_exception.message"); xmlOutputter.pcdata(message); } StringWriter stWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stWriter); exception.printStackTrace(printWriter); String stackTrace = stWriter.toString(); if (stackTrace != null && stackTrace.length() > 0) { xmlOutputter.endTag(); xmlOutputter.startTag("param"); xmlOutputter.attribute("name", "_exception.stacktrace"); xmlOutputter.pcdata(stackTrace); } xmlOutputter.close(); } if (!exceptionThrown) { out.print(stringWriter.toString()); } Function f = getFunction(functionName); long start = context.getStart(); long duration = System.currentTimeMillis() - start; f.performedCall(start, duration, success, code); out.flush(); } /** * Handles a call to this API. * * @param context * the context for this call, never <code>null</code>. * * @throws Throwable * if anything goes wrong. */ protected abstract void handleCall(CallContext context) throws Throwable; /** * Returns a list of all functions in this API. Per function the name and * the version are returned. * * @param context * the context, guaranteed to be not <code>null</code>. * * @throws IOException * if an I/O error occurs. */ private final void doGetFunctionList(CallContext context) throws IOException { int count = _functionList.size(); for (int i = 0; i < count; i++) { Function function = (Function) _functionList.get(i); context.startTag("function"); context.attribute("name", function.getName()); context.attribute("version", function.getVersion()); context.endTag(); } } }
package org.subethamail.smtp.io; import java.io.ByteArrayInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import org.subethamail.smtp.util.TextUtils; /** * Prepends a Received: header at the beginning of the input stream. */ public class ReceivedHeaderStream extends FilterInputStream { ByteArrayInputStream header; public ReceivedHeaderStream(InputStream in, String heloHost, InetAddress host, String whoami) { super(in); /* Looks like: Received: from iamhelo (wasabi.infohazard.org [209.237.247.14]) by mx.google.com with SMTP id 32si2669129wfa.13.2009.05.27.18.27.31; Wed, 27 May 2009 18:27:48 -0700 (PDT) */ DateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z (z)", Locale.US); String timestamp = fmt.format(new Date()); String header = "Received: from " + heloHost + " (" + host.getCanonicalHostName() + " [" + host + "])\r\n" + " by " + whoami + " with SMTP;\r\n" + " " + timestamp + "\r\n"; this.header = new ByteArrayInputStream(TextUtils.getAsciiBytes(header)); } @Override public int available() throws IOException { return this.header.available() + super.available(); } @Override public void close() throws IOException { super.close(); } @Override public synchronized void mark(int readlimit) { throw new UnsupportedOperationException(); } @Override public boolean markSupported() { return false; } @Override public int read() throws IOException { if (this.header.available() > 0) return this.header.read(); else return super.read(); } @Override public int read(byte[] b, int off, int len) throws IOException { if (this.header.available() > 0) { int countRead = this.header.read(b, off, len); if (countRead < len) { // We need to add a little extra from the normal stream int remainder = len - countRead; int additionalRead = super.read(b, countRead, remainder); return countRead + additionalRead; } else return countRead; } else return super.read(b, off, len); } @Override public int read(byte[] b) throws IOException { return this.read(b, 0, b.length); } @Override public synchronized void reset() throws IOException { throw new UnsupportedOperationException(); } @Override public long skip(long n) throws IOException { throw new UnsupportedOperationException(); } }
package net.tootallnate.websocket; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.NotYetConnectedException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.nio.channels.UnresolvedAddressException; import java.nio.charset.CharacterCodingException; import java.util.Iterator; import java.util.Set; import net.tootallnate.websocket.drafts.Draft_10; import net.tootallnate.websocket.exeptions.InvalidHandshakeException; /** * The <tt>WebSocketClient</tt> is an abstract class that expects a valid * "ws://" URI to connect to. When connected, an instance recieves important * events related to the life of the connection. A subclass must implement * <var>onOpen</var>, <var>onClose</var>, and <var>onMessage</var> to be * useful. An instance can send messages to it's connected server via the * <var>send</var> method. * * @author Nathan Rajlich */ public abstract class WebSocketClient extends WebSocketAdapter implements Runnable { // INSTANCE PROPERTIES ///////////////////////////////////////////////////// /** * The URI this client is supposed to connect to. */ private URI uri = null; /** * The WebSocket instance this client object wraps. */ private WebSocket conn = null; /** * The SocketChannel instance this client uses. */ private SocketChannel client = null; /** * The 'Selector' used to get event keys from the underlying socket. */ private Selector selector = null; private Thread thread; private Draft draft; // CONSTRUCTORS //////////////////////////////////////////////////////////// public WebSocketClient( URI serverURI ) { this( serverURI, new Draft_10() ); } /** * Constructs a WebSocketClient instance and sets it to the connect to the * specified URI. The client does not attampt to connect automatically. You * must call <var>connect</var> first to initiate the socket connection. */ public WebSocketClient( URI serverUri , Draft draft ) { if( serverUri == null ) { throw new IllegalArgumentException(); } if( draft == null ) { throw new IllegalArgumentException( "null as draft is permitted for `WebSocketServer` only!" ); } this.uri = serverUri; this.draft = draft; } // PUBLIC INSTANCE METHODS ///////////////////////////////////////////////// /** * Gets the URI that this WebSocketClient is connected to. * * @return The <tt>URI</tt> for this WebSocketClient. */ public URI getURI() { return uri; } public Draft getDraft() { return draft; } /** * Starts a background thread that attempts and maintains a WebSocket * connection to the URI specified in the constructor or via <var>setURI</var>. * <var>setURI</var>. */ public void connect() { if( thread != null ) throw new IllegalStateException( "already/still connected" ); thread = new Thread( this ); thread.start(); } public void close() { if( thread != null ) { thread.interrupt(); } } /** * Sends <var>text</var> to the connected WebSocket server. * * @param text * The String to send to the WebSocket server. */ public void send( String text ) throws NotYetConnectedException , InterruptedException { if( conn != null ) { conn.send( text ); } } private void tryToConnect( InetSocketAddress remote ) throws IOException { client = SocketChannel.open(); client.configureBlocking( false ); client.connect( remote ); selector = Selector.open(); client.register( selector, SelectionKey.OP_CONNECT ); } // Runnable IMPLEMENTATION ///////////////////////////////////////////////// public void run() { if( thread == null ) thread = Thread.currentThread(); interruptableRun(); thread = null; } protected void interruptableRun() { try { tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) ); } catch ( ClosedByInterruptException e ) { onError( null, e ); return; } catch ( IOException e ) { onError( conn, e ); return; } catch ( SecurityException e ) { onError( conn, e ); return; } catch ( UnresolvedAddressException e ) { onError( conn, e ); return; } conn = new WebSocket( this, draft, client ); try{ while ( !Thread.interrupted() && !conn.isClosed() ) { SelectionKey key = null; conn.flush(); selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { try { key = i.next(); i.remove(); if( key.isReadable() ) { conn.handleRead(); } if( !key.isValid() ) { continue; } if( key.isWritable() ) { conn.flush(); } if( key.isConnectable() ) { try { finishConnect(); } catch ( InterruptedException e ) { conn.close( CloseFrame.NEVERCONNECTED );// report error to only break; } catch ( InvalidHandshakeException e ) { conn.close( e ); // http error conn.flush(); } } } catch ( CharacterCodingException e ) { conn.close( CloseFrame.NO_UTF8 ); } } } } catch ( IOException e ) { onError( e ); conn.close( CloseFrame.ABNROMAL_CLOSE ); return; } catch ( RuntimeException e ) { // this catch case covers internal errors only and indicates a bug in this websocket implementation onError( e ); conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false ); return; } conn.close( CloseFrame.NORMAL ); // close() is synchronously calling onClose(conn) so we don't have to try { selector.close(); } catch ( IOException e ) { onError( e ); } selector = null; try { client.close(); } catch ( IOException e ) { onError( e ); } client = null; } private int getPort() { int port = uri.getPort(); return port == -1 ? WebSocket.DEFAULT_PORT : port; } private void finishConnect() throws IOException , InvalidHandshakeException , InterruptedException { if( client.isConnectionPending() ) { client.finishConnect(); } // Now that we're connected, re-register for only 'READ' keys. client.register( selector, SelectionKey.OP_READ ); sendHandshake(); } private void sendHandshake() throws IOException , InvalidHandshakeException , InterruptedException { String path; String part1 = uri.getPath(); String part2 = uri.getQuery(); if( part1 == null || part1.length() == 0 ) path = "/"; else path = part1; if( part2 != null ) path += "?" + part2; int port = getPort(); String host = uri.getHost() + ( port != WebSocket.DEFAULT_PORT ? ":" + port : "" ); HandshakedataImpl1 handshake = new HandshakedataImpl1(); handshake.setResourceDescriptor( path ); handshake.put( "Host", host ); conn.startHandshake( handshake ); } /** * Calls subclass' implementation of <var>onMessage</var>. * * @param conn * @param message */ @Override public void onMessage( WebSocket conn, String message ) { onMessage( message ); } /** * Calls subclass' implementation of <var>onOpen</var>. * * @param conn */ @Override public void onOpen( WebSocket conn ) { onOpen(); } /** * Calls subclass' implementation of <var>onClose</var>. * * @param conn */ @Override public void onClose( WebSocket conn, int code, String reason ) { thread.interrupt(); onClose( code, reason ); } /** * Calls subclass' implementation of <var>onIOError</var>. * * @param conn */ @Override public void onError( WebSocket conn, Exception ex ) { onError( ex ); } @Override public void onWriteDemand( WebSocket conn ) { selector.wakeup(); } // ABTRACT METHODS ///////////////////////////////////////////////////////// public abstract void onMessage( String message ); public abstract void onOpen(); public abstract void onClose( int code, String reason ); public abstract void onError( Exception ex ); }
package com.plausiblelabs.mdb; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import java.util.Map; import java.util.Set; import com.healthmarketscience.jackcess.Column; import com.healthmarketscience.jackcess.Database; import com.healthmarketscience.jackcess.Table; /** * Handles export of an MS Access database to an SQLite file. */ public class AccessExporter { /** * Create a new exporter with the provided MS Access * database * * @param db A reference to an Access database. */ public AccessExporter (Database db) { this.db = db; } /* XXX: Manual escaping of identifiers. */ private String escapeIdentifier (final String identifier) { return "'" + identifier.replace("'", "''") + "'"; } /** * Create an SQLite table for the corresponding MS Access table. * * @param table MS Access table * @param jdbc The SQLite database JDBC connection * @throws SQLException */ private void createTable (final Table table, final Connection jdbc) throws SQLException { final List<Column> columns = table.getColumns(); final StringBuilder stmtBuilder = new StringBuilder(); /* Create the statement */ stmtBuilder.append("CREATE TABLE " + escapeIdentifier(table.getName()) + " ("); final int columnCount = columns.size(); for (int i = 0; i < columnCount; i++) { final Column column = columns.get(i); stmtBuilder.append(escapeIdentifier(column.getName())); stmtBuilder.append(" "); switch (column.getType()) { /* Blob */ case BINARY: case OLE: stmtBuilder.append("BLOB"); break; /* Integers */ case BOOLEAN: case BYTE: case INT: case LONG: stmtBuilder.append("INTEGER"); break; /* Timestamp */ case SHORT_DATE_TIME: stmtBuilder.append("DATETIME"); break; /* Floating point */ case DOUBLE: case FLOAT: case NUMERIC: stmtBuilder.append("DOUBLE"); break; /* Strings */ case TEXT: case GUID: case MEMO: stmtBuilder.append("TEXT"); break; /* Money -- This can't be floating point, so let's be safe with strings */ case MONEY: stmtBuilder.append("TEXT"); break; default: throw new SQLException("Unhandled MS Acess datatype: " + column.getType()); } if (i + 1 < columnCount) stmtBuilder.append(", "); } stmtBuilder.append(")"); /* Execute it */ final Statement stmt = jdbc.createStatement(); stmt.execute(stmtBuilder.toString()); } /** * Iterate over and create SQLite tables for every table defined * in the MS Access database. * * @param jdbc The SQLite database JDBC connection */ private void createTables (final Connection jdbc) throws IOException, SQLException { final Set<String> tableNames = db.getTableNames(); for (String tableName : tableNames) { Table table = db.getTable(tableName); createTable(table, jdbc); } } private void populateTable (Table table, Connection jdbc) throws SQLException { final List<Column> columns = table.getColumns(); final StringBuilder stmtBuilder = new StringBuilder(); final StringBuilder valueStmtBuilder = new StringBuilder(); /* Record the column count */ final int columnCount = columns.size(); /* Build the INSERT statement (in two pieces simultaneously) */ stmtBuilder.append("INSERT INTO " + escapeIdentifier(table.getName()) + " ("); valueStmtBuilder.append("("); for (int i = 0; i < columnCount; i++) { final Column column = columns.get(i); /* The column name and the VALUE binding */ stmtBuilder.append(escapeIdentifier(column.getName())); valueStmtBuilder.append("?"); if (i + 1 < columnCount) { stmtBuilder.append(", "); valueStmtBuilder.append(", "); } } /* Now append the VALUES piece */ stmtBuilder.append(") VALUES "); stmtBuilder.append(valueStmtBuilder); stmtBuilder.append(")"); /* Create the prepared statement */ final PreparedStatement prep = jdbc.prepareStatement(stmtBuilder.toString()); /* Kick off the insert spree */ for (Map<String, Object> row : table) { /* Bind all the column values. We let JDBC do type conversion -- is this correct?. */ for (int i = 0; i < columnCount; i++) { final Column column = columns.get(i); final Object value = row.get(column.getName()); /* If null, just bail out early and avoid a lot of NULL checking */ if (value == null) { prep.setObject(i + 1, value); continue; } /* Perform any conversions */ switch (column.getType()) { case MONEY: /* Store money as a string. Is there any other valid representation in SQLite? */ prep.setString(i + 1, row.get(column.getName()).toString()); break; case BOOLEAN: /* The SQLite JDBC driver does not handle boolean values */ final boolean bool; final int intVal; /* Determine the value (1/0) */ bool = (Boolean) row.get(column.getName()); if (bool) intVal = 1; else intVal = 0; /* Store it */ prep.setInt(i + 1, intVal); break; default: prep.setObject(i + 1, row.get(column.getName())); break; } } /* Execute the insert */ prep.executeUpdate(); } } /** * Iterate over all data and populate the SQLite tables * @param jdbc The SQLite database JDBC connection * @throws IOException * @throws SQLException */ private void populateTables (final Connection jdbc) throws IOException, SQLException { final Set<String> tableNames = db.getTableNames(); for (String tableName : tableNames) { Table table = db.getTable(tableName); populateTable(table, jdbc); } } /** * Export the Access database to the given SQLite JDBC connection. * The referenced SQLite database should be empty. * * @param jdbc A JDBC connection to a SQLite database. * @throws SQLException */ public void export (final Connection jdbc) throws IOException, SQLException { /* Start a transaction */ jdbc.setAutoCommit(false); /* Create the tables */ createTables(jdbc); /* Populate the tables */ populateTables(jdbc); jdbc.commit(); jdbc.setAutoCommit(true); } /** MS Access database */ private final Database db; }
package org.terifan.util.bundle; import java.io.IOException; public interface BundleExternalizable { default void readExternal(Bundle aBundle) throws IOException {}; default void writeExternal(Bundle aBundle) throws IOException {}; }
package org.jcoderz.phoenix.report; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.jcoderz.commons.util.ArraysUtil; import org.jcoderz.commons.util.Assert; import org.jcoderz.commons.util.Constants; import org.jcoderz.commons.util.EmptyIterator; import org.jcoderz.commons.util.FileUtils; import org.jcoderz.commons.util.IoUtil; import org.jcoderz.commons.util.LoggingUtils; import org.jcoderz.commons.util.StringUtil; import org.jcoderz.commons.util.XmlUtil; import org.jcoderz.phoenix.report.jaxb.Item; import org.jcoderz.phoenix.report.jaxb.Report; /** * TODO: Link to current build * TODO: Link to CC home * TODO: Add @media printer??? * * @author Andreas Mandel */ public final class Java2Html { /** property name for the wiki url prefix. */ public static final String WIKI_BASE_PROPERTY = "report.wiki-prefix"; /** Pattern helper to generate css style names of the listings. */ private static final String[] PATTERN = {"odd", "even"}; /** Size of the pattern. */ private static final int PATTERN_SIZE = PATTERN.length; /** Name of this class. */ private static final String CLASSNAME = Java2Html.class.getName(); /** The logger used for technical logging inside this class. */ private static final Logger logger = Logger.getLogger(CLASSNAME); /** String used as line separator in the output html. */ private static final String NEWLINE = "\n"; /** Name of the index page with content sorted by package name. */ private static final String SORT_BY_PACKAGE_INDEX = "index.html"; /** Name of the index page with content sorted by quality. */ private static final String SORT_BY_QUALITY_INDEX = "index_q.html"; /** Name of the index page with content sorted by coverage. */ private static final String SORT_BY_COVERAGE_INDEX = "index_c.html"; /** Marker for ccs styles used as the last row in a table. */ private static final String LAST_MARKER = "_last"; private static final String DEFAULT_STYLESHEET = "reportstyle.css"; /** * Only findings that span at maximum this number of lines are * highlighted in the code. */ private static final int MAX_LINES_WITH_INLINE_MARK = 3; /** Collects a List of all <code>FileSummary</code>s of the report. */ private final List<FileSummary> mAllFiles = new ArrayList<FileSummary>(); private static final int ABSOLUTE_END_OF_LINE = 9999; /** Default tab with to use. */ private static final int DEFAULT_TAB_WIDTH = 8; /** Map of package name + FileSummary for this package. */ private final Map<String, FileSummary> mPackageSummary = new HashMap<String, FileSummary>(); private final Map<String, List<FileSummary>> mAllPackages = new HashMap<String, List<FileSummary>>(); /** * Collects findings in the current file. * Maps from the line number (Integer) to a List of Item objects. */ private final Map<Integer, List<Item>> mFindingsInFile = new HashMap<Integer, List<Item>>(); private final Set<Item> mFindingsInCurrentLine = new HashSet<Item>(); private final List<Item> mCurrentFindings = new ArrayList<Item>(); private final List<Item> mHandledFindings = new ArrayList<Item>(); /** List of findings with no (available) file assignment */ private final List<org.jcoderz.phoenix.report.jaxb.File> mGlobalFindings = new ArrayList<org.jcoderz.phoenix.report.jaxb.File>(); /** file summary for all files */ private FileSummary mGlobalSummary; private String mProjectName = ""; private String mWebVcBase = null; private String mWebVcSuffix = ""; private String mProjectHome; private String mTimestamp = null; private String mStyle = DEFAULT_STYLESHEET; // the CSS stuff to use private String mClassname; private String mPackage; private String mPackageBase; private final StringBuilder mStringBuilder = new StringBuilder(); /** String buffer to be used by the getIcons method. */ private final StringBuilder mGetIconsStringBuffer = new StringBuilder(); private java.io.File mInputData; private java.io.File mOutDir; private boolean mCoverageData = true; private Level mLogLevel = Level.INFO; /** * Holds a list of items that are currently active for the * current file and line. */ private final List<Item> mActiveItems = new LinkedList<Item>(); private Charset mCharSet = Charset.defaultCharset(); private int mTabWidth = DEFAULT_TAB_WIDTH; /** * Constructor. * * @throws IOException In case the current working directory cannot be * determined. */ public Java2Html () throws IOException { mProjectHome = new java.io.File(".").getCanonicalPath(); } /** * Main entry point. * * @param args The command line arguments. * @throws IOException an io exception occurs. * @throws JAXBException if the xml can not be parsed. */ public static void main (String[] args) throws IOException, JAXBException { final Java2Html engine = new Java2Html(); engine.parseArguments(args); // Turn on logging Logger.getLogger("org.jcoderz.phoenix.report").setLevel(Level.FINEST); engine.process(); } /** * Returns the string "odd" or "even", depending on the number given. * @param number the number to check if it'S odd or even. * @return the string "odd" if the given number is odd, "even" * otherwise. */ public static String toOddEvenString (int number) { return PATTERN[number % PATTERN_SIZE]; } /** * Set the name of the package that should be treated as project "root" * package. * @param packageBase the project base package name. */ public void setPackageBase (String packageBase) { mPackageBase = packageBase; logger.config("Package base set to '" + mPackageBase + "'."); } /** * Set the timestamp when the report has been initiated. * * @param timestamp the report creation timestamp. */ public void setTimestamp (String timestamp) { mTimestamp = timestamp; logger.config("Timestamp set to '" + mTimestamp + "'."); } /** * Sets the flag if coverage data is available and should be taken * into account. * @param coverageDataAvailable true, if coverage data is available and * should be taken into account. */ public void setCoverageData (boolean coverageDataAvailable) { mCoverageData = coverageDataAvailable; logger.config("Coverage data set to '" + mCoverageData + "'."); } /** * Sets the css file to be used can be relative to report path or * absolute. * @param style the css file to be used can be relative to report path or * absolute. */ public void setStyle (String style) { mStyle = style; logger.config("Style set to '" + mStyle + "'."); } /** * Base url to the wiki to use. * Finding pages link to a wiki page combined of this url and the * finding type. * @param wikiBase url to the wiki to use. */ public void setWikiBase (String wikiBase) { logger.config("Wiki base set to '" + wikiBase + "'."); System.getProperties().setProperty(WIKI_BASE_PROPERTY, wikiBase); } /** * Base path (url) to the cvs repository used to create links to * the cvs. * @param cvsBase url that points to a web cvs of the project. */ public void setCvsBase (String cvsBase) { mWebVcBase = cvsBase; logger.config("CVS base set to '" + mWebVcBase + "'."); } /** * Suffix to be added at the end of web vc links. * @param suffix String, to be added at the end of web vc links. */ public void setCvsSuffix (String suffix) { mWebVcSuffix = suffix; logger.config("CVS suffix set to '" + suffix + "'."); } /** * Returns the name of the project. * @return the name of the project. */ public String getProjectName () { return mProjectName; } /** * Sets the name of the project used as readable string at several * places in the report. * @param name the name of the project used as readable string at several * places in the report. */ public void setProjectName (String name) { Assert.notNull(name, "name"); mProjectName = name; logger.config("Project name set to '" + getProjectName() + "'."); } /** * Sets the tab with to be used when calculating the position in the current line. * @param tabWidth the tab width to assume in input files. */ public void setTabwidth (String tabWidth) { Assert.notNull(tabWidth, "width"); mTabWidth = Integer.parseInt(tabWidth); logger.config("Source tab width set to '" + mTabWidth + "'."); } /** * The log level to be used when processing the input. * Level must be parseable by {@link Level#parse(String)}. * @param loglevel the log level to set. */ public void setLoglevel (String loglevel) { mLogLevel = Level.parse(loglevel); LoggingUtils.setGlobalHandlerLogLevel(Level.ALL); logger.fine("Setting log level: " + mLogLevel); logger.setLevel(mLogLevel); } /** * Sets the char-set used for the source files. * @param charset The char-set in which the source files are expected. */ public void setSourceCharset (Charset charset) { Assert.notNull(charset, "charset"); mCharSet = charset; logger.config("Source charset set to '" + charset + "'."); } /** * The base path where the source files can be found. * @param file base path where the source files can be found. * @throws IOException if access to the path fails. */ public void setProjectHome (java.io.File file) throws IOException { final java.io.File projectHomeFile = file.getCanonicalFile(); mProjectHome = projectHomeFile.getCanonicalPath(); if (!projectHomeFile.isDirectory()) { throw new RuntimeException("'projectHome' must be a directory '" + projectHomeFile + "'."); } logger.config("Using project home " + mProjectHome + "."); } /** * The input file containing the jcoderz report. * @param file input file containing the jcoderz report. * @throws IOException if access to the file fails. */ public void setInputFile (java.io.File file) throws IOException { mInputData = file.getCanonicalFile(); if (!mInputData.canRead()) { throw new RuntimeException("Can not read report file '" + mInputData + "'."); } logger.config("Using report file " + mInputData + "."); } /** * The output directory where the report should be written to. * If the directory does not exist it is created. * @param dir the output directory where the report should be written to. * @throws IOException if access or creation of the directory fails. */ public void setOutDir (java.io.File dir) throws IOException { mOutDir = dir.getCanonicalFile(); if (!mOutDir.exists()) { if (!mOutDir.mkdir()) { throw new RuntimeException("Could not create 'outDir' '" + mOutDir + "'."); } } if (!mOutDir.isDirectory()) { throw new RuntimeException("'outDir' must be a directory '" + mOutDir + "'."); } logger.config("Using out dir " + mOutDir + "."); } /** * Starts the actual generation process. * @throws JAXBException if the xmp parsing fails. * @throws IOException if a IO problem occurs. */ public void process () throws JAXBException, IOException { final JAXBContext jaxbContext = JAXBContext.newInstance("org.jcoderz.phoenix.report.jaxb", this.getClass().getClassLoader()); final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setValidating(true); final Report report = (Report) unmarshaller.unmarshal(mInputData); mGlobalSummary = new FileSummary(); for (final org.jcoderz.phoenix.report.jaxb.File file : (List<org.jcoderz.phoenix.report.jaxb.File>) report.getFile()) { try { java2html(new java.io.File(file.getName()), file); } catch (Exception ex) { logger.log(Level.SEVERE, "Failed to generate report for '" + file.getName() + "'.", ex); mGlobalFindings.add(file); } } // create package summary for (final List<FileSummary> pkg : mAllPackages.values()) { createPackageSummary(pkg); } createFullSummary(); createFindingsSummary(); createPerFindingSummary(); logger.fine("Charts."); final StatisticCollector sc; if (mPackageBase == null) { sc = new StatisticCollector(report, mOutDir, mTimestamp); } else { sc = new StatisticCollector(report, mPackageBase, mOutDir, mTimestamp); } sc.createCharts(); copyStylesheet(); copyIcons(); logger.fine("Done."); } private void copyIcons () throws IOException { // create images sub-folder final File outDir = new File(mOutDir, "images"); FileUtils.mkdirs(outDir); for (int i = 0; i < Severity.VALUES.size(); i++) { final Severity s = Severity.fromInt(i); if (s.equals(Severity.OK) || s.equals(Severity.COVERAGE)) { continue; } copyImage(outDir, "icon_" + s.toString() + ".gif"); copyImage(outDir, "bg-" + s.toString() + ".gif"); } } private void copyImage (final File outDir, final String name) { final InputStream in = this.getClass().getResourceAsStream(name); if (in != null) { copyResource(in, name, outDir); } else { logger.warning("Could not find resource '" + name + "'!"); } } private void copyResource (InputStream in, String resource, File outDir) { // Copy it to the output folder OutputStream out = null; try { out = new FileOutputStream(new File(outDir, resource)); FileUtils.copy(in, out); } catch (FileNotFoundException ex) { throw new RuntimeException("Can not find output folder '" + mOutDir + "'.", ex); } catch (IOException ex) { throw new RuntimeException("Could not copy resource '" + resource + "'.", ex); } finally { IoUtil.close(in); IoUtil.close(out); } } private void copyStylesheet () { // 1. Try to read the stylesheet from the jar (default stylesheet) // 2. Try to open it from a user-defined location // 3. Use the default one if the user-defined is not found InputStream in = this.getClass().getResourceAsStream(mStyle); if (in == null) { try { final File style = new File(mStyle); in = new FileInputStream(style); } catch (FileNotFoundException ex) { IoUtil.close(in); in = this.getClass().getResourceAsStream(DEFAULT_STYLESHEET); if (in == null) { throw new RuntimeException("Can not find stylesheet file '" + mStyle + "'.", ex); } } } copyResource(in, DEFAULT_STYLESHEET, mOutDir); } private void parseArguments (String[] args) { try { for (int i = 0; i < args.length; ) { if ("-outDir".equals(args[i])) { setOutDir(new java.io.File(args[i + 1])); } else if ("-report".equals(args[i])) { setInputFile(new java.io.File(args[i + 1])); } else if ("-projectHome".equals(args[i])) { setProjectHome(new java.io.File(args[i + 1])); } else if ("-projectName".equals(args[i])) { setProjectName(args[i + 1]); } else if ("-cvsBase".equals(args[i])) { setCvsBase(args[i + 1]); } else if ("-cvsSuffix".equals(args[i])) { setCvsSuffix(args[i + 1]); } else if ("-timestamp".equals(args[i])) { setTimestamp(args[i + 1]); } else if ("-wikiBase".equals(args[i])) { setWikiBase(args[i + 1]); } else if ("-reportStyle".equals(args[i])) { setStyle(args[i + 1]); } else if ("-noCoverage".equals(args[i])) { setCoverageData(false); i -= 1; } else if ("-sourceEncoding".equals(args[i])) { setSourceCharset(Charset.forName(args[i + 1])); } else if ("-packageBase".equals(args[i])) { setPackageBase(args[i + 1]); } else if ("-loglevel".equals(args[i])) { setLoglevel(args[i + 1]); } else if ("-tabwidth".equals(args[i])) { setTabwidth(args[i + 1]); } else { throw new IllegalArgumentException( "Invalid argument '" + args[i] + "'"); } i += 1 /* command */ + 1 /* argument */; } } catch (IndexOutOfBoundsException e) { final IllegalArgumentException ex = new IllegalArgumentException("Missing value for " + args[args.length - 1]); ex.initCause(e); throw ex; } catch (Exception e) { final IllegalArgumentException ex = new IllegalArgumentException( "Problem with arument value for " + args[args.length - 1] + "Argument line was " + ArraysUtil.toString(args)); ex.initCause(e); throw ex; } } private void createPerFindingSummary () throws IOException { for (final FindingsSummary.FindingSummary summary : FindingsSummary.getFindingsSummary().getFindings().values()) { final String filename = summary.createFindingDetailFilename(); final BufferedWriter out = openWriter(filename); try { htmlHeader(out, "Finding-" + summary.getFindingType().getSymbol() + "-report " + mProjectName, ""); summary.createFindingTypeContent(out); out.write("</body></html>"); } finally { IoUtil.close(out); } } } private void createFindingsSummary () throws IOException { final BufferedWriter out = openWriter("findings.html"); try { htmlHeader(out, "Finding report " + mProjectName, ""); FindingsSummary.createOverallContent(out); out.write("</body></html>"); } finally { IoUtil.close(out); } } /** * converts a java source to HTML * with syntax highlighting for the * comments, keywords, strings and chars */ private void java2html (java.io.File inFile, org.jcoderz.phoenix.report.jaxb.File data) { mCurrentFindings.clear(); mHandledFindings.clear(); mFindingsInFile.clear(); mFindingsInCurrentLine.clear(); mActiveItems.clear(); mCurrentFindings.addAll(data.getItem()); fillFindingsInFile(data); logger.finest("Processing file " + inFile); BufferedWriter bw = null; String file = null; try { mPackage = data.getPackage(); mClassname = data.getClassname(); // If no class name is reported take the filename. if (StringUtil.isEmptyOrNull(mClassname)) { mClassname = inFile.getName(); } final String subdir = mPackage.replaceAll("\\.", "/"); final java.io.File dir = new java.io.File(mOutDir, subdir); FileUtils.mkdirs(dir); bw = openWriter(dir, mClassname + ".html"); final Syntax src = new Syntax(inFile, mCharSet, mTabWidth); final FileSummary summary = createFileSummary(src.getNumberOfLines(), subdir); addSummary(summary); file = mPackage + "." + mClassname; htmlHeader(bw, mClassname, mPackage); bw.write("<h1><a href='"); bw.write(relativeRoot(mPackage)); bw.write("'>Project Report: "); bw.write(mProjectName); bw.write("</a></h1>" + NEWLINE); bw.write("<h2><a href ='index.html'>Packagesummary "); bw.write(mPackage); bw.write("</a></h2>" + NEWLINE); final String cvsLink = getCvsLink(inFile.getAbsolutePath()); if (cvsLink != null) { bw.write("<h3><a href='" + cvsLink + "' class='cvs' title='cvs version'>" + file + "</a></h3>" + NEWLINE); } else { bw.write("<h3>" + file + "</h3>" + NEWLINE); } // create header!!!! bw.write("<table border='0' cellpadding='2' cellspacing='0' " + "width='95%'>"); bw.write("<thead><tr><th>Line</th><th>Hits</th><th>Note</th>" + "<th class='remainder'>Source</th></tr></thead>"); bw.write("<tbody>"); // PASS 2 final int lastLine = src.getNumberOfLines(); for (int currentLine = 1; currentLine <= lastLine; currentLine++) { bw.write("<tr class='" + errorLevel(currentLine) + Java2Html.toOddEvenString(currentLine) + "'>"); bw.write("<td align='right' class='lineno"); final boolean isLast = currentLine == lastLine; appendIf(bw, isLast, LAST_MARKER); bw.write("'><a name='LINE" + currentLine + "' />"); bw.write(String.valueOf(currentLine)); bw.write("</td>"); hitsCell(bw, String.valueOf(getHits(currentLine)), isLast); bw.write("<td class='note"); appendIf(bw, isLast, LAST_MARKER); bw.write("'>"); bw.write(getIcons(currentLine)); bw.write("</td><td class='code-"); bw.write(Java2Html.toOddEvenString(currentLine)); appendIf(bw, isLast, LAST_MARKER); bw.write("'>"); createCodeLine(bw, src); bw.write("</td></tr>\n"); } bw.write("</tbody>"); bw.write("</table>\n"); // findings table bw.write("<h2 class='findings-header'>Findings in this File</h2>"); bw.write("<table width='95%' cellpadding='0' cellspacing='0' " + "border='0'>\n"); int rowCounter = 0; final String relativeRoot = relativeRoot(mPackage, ""); int pos = mHandledFindings.size(); // findings with no line number or uncovered jet for (final List<Item> lineFindings : mFindingsInFile.values()) { for (final Item item : lineFindings) { if (!item.getOrigin().equals(Origin.COVERAGE)) { pos++; rowCounter++; bw.write("<tr class='findings-"); bw.write(Java2Html.toOddEvenString(rowCounter)); bw.write("row'>\n"); bw.write(" <td class='findings-image'>\n"); appendSeverityImage(bw, item, relativeRoot); bw.write(" </td>\n"); bw.write(" <td class='findings-id'>\n"); bw.write(" <a name='FINDING" + pos + "' />\n"); bw.write(" (" + pos + ")\n"); bw.write(" </td>\n"); bw.write(" <td></td><td></td><td></td>\n"); // line number bw.write(" <td width='100%' class='findings-data'>\n"); bw.write(XmlUtil.escape(item.getMessage())); if (item.getSeverityReason() != null) { bw.write(XmlUtil.escape(item.getSeverityReason())); } bw.write(" </td>\n"); bw.write("</tr>\n"); } } } // Findings as marked in the code. pos = 0; for (final Item item : mHandledFindings) { pos++; rowCounter++; final String link = "#LINE" + item.getLine(); bw.write("<tr class='findings-"); bw.write(Java2Html.toOddEvenString(rowCounter)); bw.write("row'>\n"); bw.write(" <td class='findings-image'>\n"); appendSeverityImage(bw, item, relativeRoot); bw.write(" </td>\n"); bw.write(" <td class='findings-id'>\n"); bw.write(" <a name='FINDING" + pos + "' />\n"); bw.write(" <a href='" + link + "' title='" + item.getOrigin() + "' >\n"); bw.write(" (" + pos + ")\n"); bw.write(" </a>\n"); bw.write(" </td>\n"); bw.write(" <td class='findings-line-number' align='right'>\n"); bw.write(" <a href='" + link + "' >\n"); bw.write(String.valueOf(item.getLine())); bw.write(" </a>\n"); bw.write(" </td>\n"); bw.write(" <td class='findings-line-number' align='center'>\n"); bw.write(" <a href='" + link + "' >:</a>\n"); bw.write(" </td>\n"); bw.write(" <td class='findings-line-number' align='left'>\n"); bw.write(" <a href='" + link + "' >\n"); bw.write(String.valueOf(item.getColumn())); bw.write(" </a>\n"); bw.write(" </td>\n"); bw.write(" <td width='100%' class='findings-data'>\n"); bw.write(" <a href='" + link + "' >\n"); bw.write(XmlUtil.escape(item.getMessage())); bw.write("\n"); bw.write(" </a>\n"); bw.write(" </td>\n"); bw.write("</tr>\n"); } bw.write("</table>\n"); bw.write("\n</body>\n</html>"); } catch (FileNotFoundException fnfe) { logger.log(Level.WARNING, "Source file '" + file + "' not found.", fnfe); } catch (IOException ioe) { logger.log(Level.WARNING, "Problem with '" + file + "'.", ioe); } finally { IoUtil.close(bw); } } /** * Generates a image related to the severity of the given Item. * The image links back to the general finding page of the item. * @param w the writer where to write the output to. * @param item the item to be documented. * @param root the relative path from the page generated to the root dir. * @throws IOException if the datas could not be written to the given * writer. */ private void appendSeverityImage (Writer w, Item item, String root) throws IOException { w.write("<a href='"); w.write(root); w.write(FindingsSummary.getFindingsSummary() .getFindingSummary(item).createFindingDetailFilename()); w.write("'><img border='0' title='"); w.write(String.valueOf(item.getSeverity())); w.write(" ["); w.write(String.valueOf(item.getOrigin())); w.write("]' alt='"); w.write(item.getSeverity().toString().substring(0, 1)); w.write("' src='"); w.write(root); w.write(getImage(item.getSeverity())); w.write("' /></a>\n"); } private String getImage (Severity severity) { return "images/icon_" + severity.toString() + ".gif"; } private FileSummary createFileSummary (final int linesCount, final String subdir) { // Create file summary info final FileSummary summary = new FileSummary(mClassname, mPackage, subdir + "/" + mClassname + ".html", linesCount, mCoverageData); for (final Item item : mCurrentFindings) { FindingsSummary.addFinding(item, summary); if (item.getOrigin().equals(Origin.COVERAGE)) { if (item.getCounter() != 0) { summary.addCoveredLine(); } else { summary.addViolation(Severity.COVERAGE); } } else { summary.addViolation(item.getSeverity()); } } return summary; } private void fillFindingsInFile ( org.jcoderz.phoenix.report.jaxb.File data) { for (final Item item : (List<Item>) data.getItem()) { final int lineNumber = item.getLine(); List<Item> itemsInLine = mFindingsInFile.get(lineNumber); if (itemsInLine == null) { itemsInLine = new ArrayList<Item>(); mFindingsInFile.put(lineNumber, itemsInLine); } itemsInLine.add(item); } } /** * Generates the stylesheet link for html output. * @param packageName the package of the current generated file. Used * to generate a relative link. * @param style the style to use (relative to report path or absolute) * @return the style link as to be placed in the head of the generated * html file. */ private static String createStyle (String packageName, String style) { // TODO: use the default stylesheet if not explicitly specified String result = ""; if (style != null) { final String styleLink; if (style.indexOf(" { // absolute style styleLink = style; } else { styleLink = relativeRoot(packageName, style); } result = "<link rel='stylesheet' type='text/css' href='" + styleLink + "' />"; } return result; } private Severity errorLevel (int line) { Severity severity = Severity.OK; final Iterator<Item> active = mActiveItems.iterator(); while (active.hasNext()) { final Item item = active.next(); if (item.getEndLine() < line) { active.remove(); } else { severity = severity.max(item.getSeverity()); } } final Iterator<Item> items = findingsInLine(line); while (items.hasNext()) { final Item item = items.next(); if (item.getOrigin() == Origin.COVERAGE) { if (item.getCounter() == 0) { severity = severity.max(Severity.COVERAGE); } } else { severity = severity.max(item.getSeverity()); if (item.getEndLine() > line) { mActiveItems.add(item); } } } return severity; } private Iterator<Item> findingsInLine (int line) { final List<Item> findingsInLine = mFindingsInFile.get(line); final Iterator<Item> result; if (findingsInLine == null) { result = EmptyIterator.EMPTY_ITERATOR; } else { result = findingsInLine.iterator(); } return result; } private String getHits (int line) { String hits = "&nbsp;"; final Iterator<Item> items = findingsInLine(line); while (items.hasNext()) { final Item item = items.next(); if (item.getOrigin() == Origin.COVERAGE) { hits = String.valueOf(item.getCounter()); break; } } return hits; } /** * Fills the 'Note' column for the given line. * @param line the line under inspection. * @return the content to be put in the notes column for the given line. */ private String getIcons (int line) { final StringBuilder icons = new StringBuilder(); // collect relevant findings final Iterator<Item> items = findingsInLine(line); while (items.hasNext()) { final Item item = items.next(); if (item.getOrigin() == Origin.COVERAGE) { if (item.getCounter() == 0) { items.remove(); // will never see this again! } } else if (item.getSeverity() == Severity.FILTERED) { // not listen with the code but in the global section below the // code. } else { mHandledFindings.add(item); // create the magic icon string with a hyperlink mGetIconsStringBuffer.setLength(0); mGetIconsStringBuffer.append("<a href='#FINDING"); mGetIconsStringBuffer.append(mHandledFindings.size()); mGetIconsStringBuffer.append("' title='"); mGetIconsStringBuffer.append( XmlUtil.attributeEscape(item.getMessage())); mGetIconsStringBuffer.append("'><span class='"); mGetIconsStringBuffer.append(item.getOrigin()); mGetIconsStringBuffer.append("note'>("); mGetIconsStringBuffer.append(mHandledFindings.size()); mGetIconsStringBuffer.append(")</span></a>"); icons.append(mGetIconsStringBuffer); if (item.isSetColumn() && (!item.isSetEndLine() || item.getEndLine() - line <= MAX_LINES_WITH_INLINE_MARK)) { mFindingsInCurrentLine.add(item); } items.remove(); // item was handled fully } } if (icons.length() == 0) { icons.append("&nbsp;"); } return icons.toString(); } /** * Replaces leading whitespace by a none breakable html string * (entity). * Uses <code>mStringBuffer</code> as temporary string buffer. * @param in The string to modify. * @return The string with leading white spaces replaced. */ private String replaceLeadingSpaces (String in) { final String result; if (in == null || in.length() == 0) { result = "&nbsp;"; } else if (in.charAt(0) == ' ') { mStringBuilder.setLength(0); int i; for (i = 0; i < in.length() && in.charAt(i) == ' '; i++) { mStringBuilder.append("&nbsp;"); } mStringBuilder.append(in.substring(i)); result = mStringBuilder.toString(); } else { result = in; } return result; } /** * Adds the file summary to all summary lists. */ private void addSummary (FileSummary summary) { mAllFiles.add(summary); List<FileSummary> packageList = mAllPackages.get(summary.getPackage()); if (packageList == null) { packageList = new ArrayList<FileSummary>(); mAllPackages.put(summary.getPackage(), packageList); } packageList.add(summary); FileSummary packageSummary = mPackageSummary.get(summary.getPackage()); if (packageSummary == null) { packageSummary = new FileSummary(mPackage); mPackageSummary.put(summary.getPackage(), packageSummary); } packageSummary.add(summary); mGlobalSummary.add(summary); } private void createPackageSummary (List<FileSummary> pkg) throws IOException { createPackageSummary(new FileSummary.SortByPackage(), pkg); createPackageSummary(new FileSummary.SortByQuality(), pkg); createPackageSummary(new FileSummary.SortByCoverage(), pkg); } private void createPackageSummary (Comparator<FileSummary> order, List<FileSummary> pkg) throws IOException { final String filename = fileNameForOrder(order); final String packageName = pkg.get(0).getPackage(); final String subdir = packageName.replaceAll("\\.", "/"); final java.io.File dir = new java.io.File(mOutDir, subdir); FileUtils.mkdirs(dir); final BufferedWriter bw = openWriter(dir, filename); try { htmlHeader(bw, packageName, packageName); bw.write("<h1><a href='" + relativeRoot(packageName, filename) + "'>Project-Report " + mProjectName + "</a></h1>"); bw.write("<h2>Packagesummary " + packageName + "</h2>"); createClassListTable(bw, pkg, false, order); bw.write("</body></html>"); } finally { IoUtil.close(bw); } } private void createFullSummary () throws IOException { createFullSummary(new FileSummary.SortByPackage()); createFullSummary(new FileSummary.SortByQuality()); createFullSummary(new FileSummary.SortByCoverage()); } private void createFullSummary (Comparator<FileSummary> order) throws IOException { final String filename = fileNameForOrder(order); final BufferedWriter bw = openWriter(filename); try { htmlHeader(bw, "Project Report " + mProjectName, ""); bw.write("<h1>Project Report " + mProjectName + "</h1>"); bw.write("<table border='0' cellpadding='2' cellspacing='0' " + "width='95%'>"); bw.write("<thead><tr><th>"); if (filename != SORT_BY_PACKAGE_INDEX) { bw.write("<a href='" + SORT_BY_PACKAGE_INDEX + "' title='Sort by name'>"); } bw.write("Package"); if (filename != SORT_BY_PACKAGE_INDEX) { bw.write("</a>"); } bw.write("</th><th>findings</th>"); bw.write("<th>files</th><th>lines</th>"); if (mCoverageData) { bw.write("<th>%</th><th>"); if (filename != SORT_BY_COVERAGE_INDEX) { bw.write("<a href='" + SORT_BY_COVERAGE_INDEX + "' title='Sort by coverage'>"); } bw.write("Coverage"); if (filename != SORT_BY_COVERAGE_INDEX) { bw.write("</a>"); } bw.write("</th>"); } bw.write("<th>%</th><th class='remainder'>"); if (filename != SORT_BY_QUALITY_INDEX) { bw.write("<a href='" + SORT_BY_QUALITY_INDEX + "' title='Sort by quality'>"); } bw.write("Quality"); if (filename != SORT_BY_QUALITY_INDEX) { bw.write("</a>"); } bw.write("</th></tr></thead>"); bw.write("<tbody>"); bw.write(NEWLINE); bw.write("<tr class='odd'><td class='classname" + LAST_MARKER + "'>"); bw.write("Overall summary"); bw.write("</td>"); hitsCell(bw, String.valueOf(mGlobalSummary.getNumberOfFindings()), true); hitsCell(bw, String.valueOf(mGlobalSummary.getNumberOfFiles()), true); hitsCell(bw, String.valueOf(mGlobalSummary.getLinesOfCode()), true); if (mCoverageData) { hitsCell(bw, String.valueOf(mGlobalSummary.getCoverageAsString()), true); bw.write("<td valign='middle' class='hits" + LAST_MARKER + "' width='100'>"); bw.write(mGlobalSummary.getCoverageBar()); bw.write("</td>"); } hitsCell(bw, String.valueOf(mGlobalSummary.getQuality()) + "%", true); bw.write("<td valign='middle' class='code" + LAST_MARKER + "' width='100'>"); bw.write(mGlobalSummary.getPercentBar()); bw.write("</td></tr>"); bw.write(NEWLINE); bw.write("</tbody>"); bw.write("</table>"); bw.write("<h1><a href='findings.html'>View by Finding</a></h1>"); bw.write("<h1>Packages</h1>"); bw.write("<table border='0' cellpadding='2' cellspacing='0' " + "width='95%'>"); bw.write("<thead><tr><th>Package</th>" + "<th>findings</th><th>files</th><th>lines</th>"); if (mCoverageData) { bw.write("<th>%</th><th>Coverage</th>"); } bw.write("<th>%</th><th class='remainder'>Quality</th></tr></thead>"); bw.write("<tbody>"); bw.write(NEWLINE); final Set<FileSummary> packages = new TreeSet<FileSummary>(order); packages.addAll(mPackageSummary.values()); int pos = 0; final Iterator<FileSummary> i = packages.iterator(); while (i.hasNext()) { pos++; final FileSummary pkg = i.next(); final boolean isLast = !i.hasNext(); appendPackageLink(bw, pkg, filename, pos, isLast); } bw.write("</tbody></table>\n"); // findings with no line number... createUnassignedFindingsTable(bw); bw.write("<h1>Java Files</h1>"); createClassListTable(bw, mAllFiles, true, order); bw.write("</body></html>"); } finally { IoUtil.close(bw); } } private void createUnassignedFindingsTable (final BufferedWriter bw) throws IOException { boolean tableOpened = false; int row = 0; for (final org.jcoderz.phoenix.report.jaxb.File file : mGlobalFindings) { for (final Item item : (List<Item>) file.getItem()) { row++; if (!tableOpened) { bw.write("<h1>Unassigned findings</h1>"); bw.write("<table border='0' cellpadding='0' " + "cellspacing='0' width='95%'>"); tableOpened = true; } bw.write("<tr class='"); bw.write(item.getSeverity().toString()); bw.write(Java2Html.toOddEvenString(row)); bw.write("'><td class='unassigned-filename'>"); bw.write(cutPath(file.getName())); bw.write("</td><td class='unassigned-data' width='100%'>"); bw.write(item.getMessage()); bw.write("</td></tr>"); FindingsSummary.addFinding(item, mGlobalSummary); } } if (tableOpened) { bw.write("</table>"); } } private void appendPackageLink (final BufferedWriter bw, final FileSummary pkg, final String filename, final int pos, final boolean isLast) throws IOException { final String name = pkg.getPackage(); final String subdir = name.replaceAll("\\.", "/"); bw.write("<tr class='" + Java2Html.toOddEvenString(pos) + "'><td class='classname"); appendIf(bw, isLast, LAST_MARKER); bw.write("'><a href='" + subdir + "/" + filename + "'>"); bw.write(pkg.getPackage()); bw.write("</a></td>"); hitsCell(bw, String.valueOf(pkg.getNumberOfFindings()), isLast); hitsCell(bw, String.valueOf(pkg.getNumberOfFiles()), isLast); hitsCell(bw, String.valueOf(pkg.getLinesOfCode()), isLast); if (mCoverageData) { hitsCell(bw, String.valueOf(pkg.getCoverageAsString()), isLast); bw.write("<td valign='middle' class='hits"); appendIf(bw, isLast, LAST_MARKER); bw.write("' width='100'>"); bw.write(pkg.getCoverageBar()); bw.write("</td>"); } hitsCell(bw, String.valueOf(pkg.getQuality()) + "%", isLast); bw.write("<td valign='middle' class='code"); appendIf(bw, isLast, LAST_MARKER); bw.write("' width='100'>"); bw.write(pkg.getPercentBar()); bw.write("</td></tr>" + NEWLINE); } /** * Writes a html header to the given output stream. * @param bw the stream to use for output * @param title the title of the page. Should be the package name for * sub packages. */ private void htmlHeader (BufferedWriter bw, String title, String packageName) throws IOException { bw.write("<?xml version='1.0' encoding='UTF-8'?>" + NEWLINE + "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" " + NEWLINE + "\"http: + NEWLINE + "<html xmlns='http: + " lang='en'>" + NEWLINE + "<head>" + NEWLINE + "\t<title>"); bw.write(title); bw.write("</title>" + NEWLINE + "\t<meta name='author' content='jCoderZ java2html' />" + NEWLINE); bw.write(createStyle(packageName, mStyle)); bw.write(NEWLINE + "</head>" + NEWLINE + "<body>" + NEWLINE); } private static String relativeRoot (String currentPackage) { return relativeRoot(currentPackage, "index.html"); } private static String relativeRoot (String currentPackage, String page) { final StringBuilder rootDir = new StringBuilder(); if (currentPackage.length() != 0) { rootDir.append("../"); } for (int i = 0; i < currentPackage.length(); i++) { if (currentPackage.charAt(i) == '.') { rootDir.append("../"); } } rootDir.append(page); return rootDir.toString().replaceAll(" } private String cutPath (String fileName) { String result = fileName; if (fileName.toLowerCase(Constants.SYSTEM_LOCALE) .startsWith(mProjectHome.toLowerCase(Constants.SYSTEM_LOCALE))) { result = fileName.substring(mProjectHome.length()); } return result; } private String getCvsLink (String absFile) { String result; if (mWebVcBase == null || mProjectHome == null) { result = null; } else if (absFile.toLowerCase(Constants.SYSTEM_LOCALE) .startsWith(mProjectHome.toLowerCase(Constants.SYSTEM_LOCALE))) { result = absFile.substring(mProjectHome.length()); } else { absFile = (new java.io.File(absFile)).getAbsolutePath(); if (absFile.toLowerCase(Constants.SYSTEM_LOCALE) .startsWith(mProjectHome.toLowerCase(Constants.SYSTEM_LOCALE))) { result = absFile.substring(mProjectHome.length()); } else { result = null; } } if (result != null) { result = mWebVcBase + result + mWebVcSuffix; result = result.replaceAll("\\\\", "/"); } return result; } /** * Create the marked html output for the current line. * @param out the writer to generate the output to. * @param src the source to read the line data from. * @throws IOException if IO operations fail writing to the * given writer. */ private void createCodeLine (Writer out, Syntax src) throws IOException { String text = src.nextToken(); String lastTokenType = null; Item lastFinding = null; boolean isFirst = true; while (null != src.getCurrentTokenType()) { final Item currentFinding = getCurrentFinding(text, src.getCurrentLineNumber(), src.getCurrentLinePos(), src.getCurrentTokenLength()); if (currentFinding != lastFinding) { if (lastTokenType != null) { out.write("</span>"); // close token type lastTokenType = null; } if (lastFinding != null) { out.write("</span>"); // close last finding } if (currentFinding != null) { out.write("<span class='finding-"); out.write(currentFinding.getSeverity().toString()); out.write("' title='"); out.write( XmlUtil.attributeEscape(currentFinding.getMessage())); out.write("'>"); } lastFinding = currentFinding; } final String tokenType = src.getCurrentTokenType(); if (!tokenType.equals(lastTokenType)) { if (lastTokenType != null) { out.write("</span>"); isFirst = false; } out.write("<span class='code-"); out.write(tokenType); out.write("'>"); } String xml = XmlUtil.escape(text); if (isFirst) { xml = replaceLeadingSpaces(xml); } out.write(xml); lastTokenType = tokenType; text = src.nextToken(); } if (lastTokenType != null) { out.write("</span>"); } if (lastFinding != null) { out.write("</span>"); } } private Item getCurrentFinding ( String text, int currentLineNumber, int currentLinePos, int tokenLen) { Item theFinding = null; final Iterator<Item> i = mFindingsInCurrentLine.iterator(); while (i.hasNext()) { final Item finding = i.next(); if (finding.getEndLine() < currentLineNumber && finding.getLine() < currentLineNumber) { i.remove(); continue; } final int start = finding.getLine() == currentLineNumber ? finding.getColumn() : 0; int end = finding.getEndLine() == currentLineNumber ? finding.getEndColumn() : ABSOLUTE_END_OF_LINE; if (finding.getEndLine() == 0) { end = finding.getEndColumn(); } // TODO Add code to find pos by symbol! // finding at current pos if ((start == currentLinePos && end == 0) // or in range that contains the current pos || (start <= currentLinePos && end >= currentLinePos) // or inside the token || (start >= currentLinePos && start < currentLinePos + tokenLen)) { if (theFinding == null || finding.getSeverity().compareTo( theFinding.getSeverity()) > 0) { theFinding = finding; } } } return theFinding; } /** * Creates a list of all classes as html table and appends it to the * given bw. */ private void createClassListTable (BufferedWriter bw, Collection<FileSummary> files, boolean fullPackageNames, Comparator<FileSummary> order) throws IOException { // Do not create a table if no classes are here. if (!files.isEmpty()) { final String filename = fileNameForOrder(order); final FileSummary[] summaries = files.toArray(new FileSummary[files.size()]); Arrays.sort(summaries, order); bw.write("<table border='0' cellpadding='2' cellspacing='0' " + "width='95%'>"); bw.write("<thead><tr><th>"); if (filename != SORT_BY_PACKAGE_INDEX) { bw.write("<a href='"); bw.write(SORT_BY_PACKAGE_INDEX); bw.write("' title='Sort by name'>"); } bw.write("Classfile"); if (filename != SORT_BY_PACKAGE_INDEX) { bw.write("</a>"); } bw.write("</th><th>findings</th><th>lines</th>"); if (mCoverageData) { bw.write("<th>%</th><th>"); if (filename != SORT_BY_COVERAGE_INDEX) { bw.write("<a href='"); bw.write(SORT_BY_COVERAGE_INDEX); bw.write("' title='Sort by coverage'>"); } bw.write("Coverage"); if (filename != SORT_BY_COVERAGE_INDEX) { bw.write("</a>"); } bw.write("</th>"); } bw.write("<th>%</th><th class='remainder'>"); if (filename != SORT_BY_QUALITY_INDEX) { bw.write("<a href='"); bw.write(SORT_BY_QUALITY_INDEX); bw.write("' title='Sort by quality'>"); } bw.write("Quality"); if (filename != SORT_BY_QUALITY_INDEX) { bw.write("</a>"); } bw.write("</th></tr></thead>"); bw.write("<tbody>"); bw.write(NEWLINE); int pos = 0; final Iterator<FileSummary> i = Arrays.asList(summaries).iterator(); while (i.hasNext()) { pos++; final FileSummary file = i.next(); final boolean isLast = !i.hasNext(); appendClassLink(bw, file, fullPackageNames, pos, isLast); } bw.write("</tbody>"); bw.write("</table>"); } else { bw.write("EMPTY!?"); } } private void appendClassLink (BufferedWriter bw, final FileSummary file, boolean fullPackageNames, int pos, final boolean isLast) throws IOException { final String name; final String link; if (fullPackageNames) { name = file.getPackage() + '.' + file.getClassName(); link = file.getPackage().replaceAll("\\.", "/") + "/" + file.getClassName() + ".html"; } else { name = file.getClassName(); link = file.getClassName() + ".html"; } bw.write("<tr class='"); bw.write(Java2Html.toOddEvenString(pos)); bw.write("'><td class='classname"); appendIf(bw, isLast, LAST_MARKER); bw.write("'><a href='"); bw.write(link); bw.write("'>"); bw.write(name); bw.write("</a></td>"); hitsCell(bw, String.valueOf(file.getNumberOfFindings()), isLast); hitsCell(bw, String.valueOf(file.getLinesOfCode()), isLast); if (mCoverageData) { hitsCell(bw, file.getCoverageAsString(), isLast); bw.write("<td valign='middle' class='hits"); appendIf(bw, isLast, LAST_MARKER); bw.write("' width='100'>"); bw.write(file.getCoverageBar()); bw.write("</td>"); } hitsCell(bw, String.valueOf(file.getQuality()) + "%", isLast); bw.write("<td valign='middle' class='code"); appendIf(bw, isLast, LAST_MARKER); bw.write("' width='100'>"); bw.write(file.getPercentBar()); bw.write("</td></tr>"); bw.write(NEWLINE); } private static String fileNameForOrder (Comparator<FileSummary> order) { String filename; if (order instanceof FileSummary.SortByPackage) { filename = SORT_BY_PACKAGE_INDEX; } else if (order instanceof FileSummary.SortByQuality) { filename = SORT_BY_QUALITY_INDEX; } else if (order instanceof FileSummary.SortByCoverage) { filename = SORT_BY_COVERAGE_INDEX; } else { throw new RuntimeException("Order not expected " + order); } return filename; } /** * Generates the content (including surounding elements) of a cell * of hits type. * @param bw the writer to write to. * @param content the cell contend * @param isLast true if this sell is in the last row. * @throws IOException if the write fails. */ private static void hitsCell (BufferedWriter bw, String content, boolean isLast) throws IOException { bw.write("<td valign='middle' class='hits"); appendIf(bw, isLast, LAST_MARKER); bw.write("'>"); bw.write(content); bw.write("</td>"); } private static void appendIf (BufferedWriter bw, boolean condition, String str) throws IOException { if (condition) { bw.write(str); } } private BufferedWriter openWriter (String filename) throws IOException { return openWriter(mOutDir, filename); } private BufferedWriter openWriter (File dir, String filename) throws IOException { FileOutputStream fos = null; OutputStreamWriter osw = null; BufferedWriter result = null; try { fos = new FileOutputStream(new java.io.File(dir, filename)); osw = new OutputStreamWriter(fos, Constants.ENCODING_UTF8); result = new BufferedWriter(osw); } catch (RuntimeException ex) { IoUtil.close(result); IoUtil.close(osw); IoUtil.close(fos); throw ex; } catch (IOException ex) { IoUtil.close(result); IoUtil.close(osw); IoUtil.close(fos); throw ex; } return result; } }
package org.jcoderz.phoenix.report; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Serializable; import java.io.Writer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.jcoderz.commons.types.Date; import org.jcoderz.commons.util.ArraysUtil; import org.jcoderz.commons.util.Assert; import org.jcoderz.commons.util.Constants; import org.jcoderz.commons.util.EmptyIterator; import org.jcoderz.commons.util.FileUtils; import org.jcoderz.commons.util.IoUtil; import org.jcoderz.commons.util.LoggingUtils; import org.jcoderz.commons.util.ObjectUtil; import org.jcoderz.commons.util.StringUtil; import org.jcoderz.commons.util.XmlUtil; import org.jcoderz.phoenix.report.jaxb.Item; import org.jcoderz.phoenix.report.jaxb.Report; /** * TODO: Link to current build * TODO: Link to CC home * TODO: Add @media printer??? * TODO: Refactor, split class. * * @author Andreas Mandel */ public final class Java2Html { /** property name for the wiki url prefix. */ public static final String WIKI_BASE_PROPERTY = "report.wiki-prefix"; /** Pattern helper to generate css style names of the listings. */ private static final String[] PATTERN = {"odd", "even"}; /** Size of the pattern. */ private static final int PATTERN_SIZE = PATTERN.length; /** Name of this class. */ private static final String CLASSNAME = Java2Html.class.getName(); /** The logger used for technical logging inside this class. */ private static final Logger logger = Logger.getLogger(CLASSNAME); /** String used as line separator in the output html. */ private static final String NEWLINE = "\n"; /** Name of the index page with content sorted by package name. */ private static final String SORT_BY_PACKAGE_INDEX = "index.html"; /** Name of the index page with content sorted by quality. */ private static final String SORT_BY_QUALITY_INDEX = "index_q.html"; /** Name of the index page with content sorted by coverage. */ private static final String SORT_BY_COVERAGE_INDEX = "index_c.html"; /** Marker for ccs styles used as the last row in a table. */ private static final String LAST_MARKER = "_last"; private static final String DEFAULT_STYLESHEET = "reportstyle.css"; private static final int NUMBER_OF_AGE_SEGMENTS = 5; /** * Only findings that span at maximum this number of lines are * highlighted in the code. */ private static final int MAX_LINES_WITH_INLINE_MARK = 3; private static final int ABSOLUTE_END_OF_LINE = 9999; /** Default tab with to use. */ private static final int DEFAULT_TAB_WIDTH = 8; /** Collects a List of all <code>FileSummary</code>s of the report. */ private final List<FileSummary> mAllFiles = new ArrayList<FileSummary>(); /** Map of package name + FileSummary for this package. */ private final Map<String, FileSummary> mPackageSummary = new HashMap<String, FileSummary>(); private final Map<String, List<FileSummary>> mAllPackages = new HashMap<String, List<FileSummary>>(); /** * Collects findings in the current file. * Maps from the line number (Integer) to a List of Item objects. */ private final Map<Integer, List<Item>> mFindingsInFile = new HashMap<Integer, List<Item>>(); private final Set<Item> mFindingsInCurrentLine = new HashSet<Item>(); private final List<Item> mCurrentFindings = new ArrayList<Item>(); private final List<Item> mHandledFindings = new ArrayList<Item>(); /** List of findings with no (available) file assignment */ private final List<org.jcoderz.phoenix.report.jaxb.File> mGlobalFindings = new ArrayList<org.jcoderz.phoenix.report.jaxb.File>(); /** file summary for all files */ private FileSummary mGlobalSummary; private String mProjectName = ""; private String mWebVcBase = null; private String mWebVcSuffix = ""; private String mProjectHome; private String mTimestamp = null; private String mStyle = DEFAULT_STYLESHEET; // the CSS stuff to use private String mClassname; private String mPackage; private String mPackageBase; private final StringBuilder mStringBuilder = new StringBuilder(); /** String buffer to be used by the getIcons method. */ private final StringBuilder mGetIconsStringBuffer = new StringBuilder(); private java.io.File mInputData; private java.io.File mOutDir; private boolean mCoverageData = true; private Level mLogLevel = Level.INFO; /** * Holds a list of items that are currently active for the * current file and line. */ private final List<Item> mActiveItems = new LinkedList<Item>(); private Charset mCharSet = Charset.defaultCharset(); private int mTabWidth = DEFAULT_TAB_WIDTH; /** The full Report. */ private Report mReport; private final Map<Item, org.jcoderz.phoenix.report.jaxb.File> mItemToFileMap = new HashMap<Item, org.jcoderz.phoenix.report.jaxb.File>(); /** * Constructor. * * @throws IOException In case the current working directory cannot be * determined. */ public Java2Html () throws IOException { mProjectHome = new java.io.File(".").getCanonicalPath(); } /** * Main entry point. * * @param args The command line arguments. * @throws IOException an io exception occurs. * @throws JAXBException if the xml can not be parsed. */ public static void main (String[] args) throws IOException, JAXBException { final Java2Html engine = new Java2Html(); engine.parseArguments(args); // Turn on logging Logger.getLogger("org.jcoderz.phoenix.report").setLevel(Level.FINEST); engine.process(); } /** * Returns the string "odd" or "even", depending on the number given. * @param number the number to check if it'S odd or even. * @return the string "odd" if the given number is odd, "even" * otherwise. */ public static String toOddEvenString (int number) { return PATTERN[number % PATTERN_SIZE]; } /** * Set the name of the package that should be treated as project "root" * package. * @param packageBase the project base package name. */ public void setPackageBase (String packageBase) { mPackageBase = packageBase; logger.config("Package base set to '" + mPackageBase + "'."); } /** * Set the timestamp when the report has been initiated. * * @param timestamp the report creation timestamp. */ public void setTimestamp (String timestamp) { mTimestamp = timestamp; logger.config("Timestamp set to '" + mTimestamp + "'."); } /** * Sets the flag if coverage data is available and should be taken * into account. * @param coverageDataAvailable true, if coverage data is available and * should be taken into account. */ public void setCoverageData (boolean coverageDataAvailable) { mCoverageData = coverageDataAvailable; logger.config("Coverage data set to '" + mCoverageData + "'."); } /** * Sets the css file to be used can be relative to report path or * absolute. * @param style the css file to be used can be relative to report path or * absolute. */ public void setStyle (String style) { mStyle = style; logger.config("Style set to '" + mStyle + "'."); } /** * Base url to the wiki to use. * Finding pages link to a wiki page combined of this url and the * finding type. * @param wikiBase url to the wiki to use. */ public void setWikiBase (String wikiBase) { logger.config("Wiki base set to '" + wikiBase + "'."); System.getProperties().setProperty(WIKI_BASE_PROPERTY, wikiBase); } /** * Base path (url) to the cvs repository used to create links to * the cvs. * @param cvsBase url that points to a web cvs of the project. */ public void setCvsBase (String cvsBase) { mWebVcBase = cvsBase; logger.config("CVS base set to '" + mWebVcBase + "'."); } /** * Suffix to be added at the end of web vc links. * @param suffix String, to be added at the end of web vc links. */ public void setCvsSuffix (String suffix) { mWebVcSuffix = suffix; logger.config("CVS suffix set to '" + suffix + "'."); } /** * Returns the name of the project. * @return the name of the project. */ public String getProjectName () { return mProjectName; } /** * Sets the name of the project used as readable string at several * places in the report. * @param name the name of the project used as readable string at several * places in the report. */ public void setProjectName (String name) { Assert.notNull(name, "name"); mProjectName = name; logger.config("Project name set to '" + getProjectName() + "'."); } /** * Sets the tab with to be used when calculating the position in the * current line. * @param tabWidth the tab width to assume in input files. */ public void setTabwidth (String tabWidth) { Assert.notNull(tabWidth, "width"); mTabWidth = Integer.parseInt(tabWidth); logger.config("Source tab width set to '" + mTabWidth + "'."); } /** * The log level to be used when processing the input. * Level must be parseable by {@link Level#parse(String)}. * @param loglevel the log level to set. */ public void setLoglevel (String loglevel) { mLogLevel = Level.parse(loglevel); LoggingUtils.setGlobalHandlerLogLevel(Level.ALL); logger.fine("Setting log level: " + mLogLevel); logger.setLevel(mLogLevel); } /** * Sets the char-set used for the source files. * @param charset The char-set in which the source files are expected. */ public void setSourceCharset (Charset charset) { Assert.notNull(charset, "charset"); mCharSet = charset; logger.config("Source charset set to '" + charset + "'."); } /** * The base path where the source files can be found. * @param file base path where the source files can be found. * @throws IOException if access to the path fails. */ public void setProjectHome (java.io.File file) throws IOException { final java.io.File projectHomeFile = file.getCanonicalFile(); mProjectHome = projectHomeFile.getCanonicalPath(); if (!projectHomeFile.isDirectory()) { throw new RuntimeException("'projectHome' must be a directory '" + projectHomeFile + "'."); } logger.config("Using project home " + mProjectHome + "."); } /** * The input file containing the jcoderz report. * @param file input file containing the jcoderz report. * @throws IOException if access to the file fails. */ public void setInputFile (java.io.File file) throws IOException { mInputData = file.getCanonicalFile(); if (!mInputData.canRead()) { throw new RuntimeException("Can not read report file '" + mInputData + "'."); } logger.config("Using report file " + mInputData + "."); } /** * The output directory where the report should be written to. * If the directory does not exist it is created. * @param dir the output directory where the report should be written to. * @throws IOException if access or creation of the directory fails. */ public void setOutDir (java.io.File dir) throws IOException { mOutDir = dir.getCanonicalFile(); if (!mOutDir.exists()) { if (!mOutDir.mkdir()) { throw new RuntimeException("Could not create 'outDir' '" + mOutDir + "'."); } } if (!mOutDir.isDirectory()) { throw new RuntimeException("'outDir' must be a directory '" + mOutDir + "'."); } logger.config("Using out dir " + mOutDir + "."); } /** * Starts the actual generation process. * @throws JAXBException if the xmp parsing fails. * @throws IOException if a IO problem occurs. */ public void process () throws JAXBException, IOException { final JAXBContext jaxbContext = JAXBContext.newInstance("org.jcoderz.phoenix.report.jaxb", this.getClass().getClassLoader()); final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setValidating(true); mReport = (Report) unmarshaller.unmarshal(mInputData); mGlobalSummary = new FileSummary(); initialiteFindingTypes(); for (final org.jcoderz.phoenix.report.jaxb.File file : (List<org.jcoderz.phoenix.report.jaxb.File>) mReport.getFile()) { try { if (file.getName() != null) { java2html(new java.io.File(file.getName()), file); } else { mGlobalFindings.add(file); } } catch (Exception ex) { if (file.getItem().isEmpty()) { logger.log(Level.FINE, "No report for file without items '" + file.getName() + "'.", ex); } else { logger.log(Level.SEVERE, "Failed to generate report for '" + file.getName() + "'.", ex); mGlobalFindings.add(file); } } } // create package summary for (final List<FileSummary> pkg : mAllPackages.values()) { createPackageSummary(pkg); } createFullSummary(); createFindingsSummary(); createPerFindingSummary(); createAgeSummary(); logger.fine("Charts."); final StatisticCollector sc; if (mPackageBase == null) { sc = new StatisticCollector(mReport, mOutDir, mTimestamp); } else { sc = new StatisticCollector(mReport, mPackageBase, mOutDir, mTimestamp); } sc.createCharts(); copyStylesheet(); copyIcons(); logger.fine("Done."); } private void initialiteFindingTypes () { for (final org.jcoderz.phoenix.report.jaxb.File file : (List<org.jcoderz.phoenix.report.jaxb.File>) mReport.getFile()) { for (Item i : (List<Item>) file.getItem()) { try { FindingType.initialize(i.getOrigin()); } catch (Exception ex) { logger.log(Level.WARNING, "Could not initialize finding type " + i.getFindingType()); } } } } private void createAgeSummary () throws IOException { final List<Item> items = new ArrayList<Item>(); for (final org.jcoderz.phoenix.report.jaxb.File file : (List<org.jcoderz.phoenix.report.jaxb.File>) mReport.getFile()) { for (Item i : (List<Item>) file.getItem()) { if (i.isSetSince()) { items.add(i); mItemToFileMap.put(i, file); } } } Collections.sort(items, Collections.reverseOrder(new ItemAgeComperator())); renderAgePage(items, Date.FUTURE_DATE, ReportInterval.BUILD); renderAgePage(items, Date.FUTURE_DATE, ReportInterval.DAY); renderAgePage(items, Date.FUTURE_DATE, ReportInterval.WEEK); final Date oldest = renderAgePage(items, Date.FUTURE_DATE, ReportInterval.MONTH); renderAgePage(items, oldest, ReportInterval.OLD); } private void copyIcons () throws IOException { // create images sub-folder final File outDir = new File(mOutDir, "images"); FileUtils.mkdirs(outDir); for (int i = 0; i < Severity.VALUES.size(); i++) { final Severity s = Severity.fromInt(i); if (s.equals(Severity.OK) || s.equals(Severity.COVERAGE)) { continue; } copyImage(outDir, "icon_" + s.toString() + ".gif"); copyImage(outDir, "bg-" + s.toString() + ".gif"); } } private void copyImage (final File outDir, final String name) { final InputStream in = this.getClass().getResourceAsStream(name); if (in != null) { copyResource(in, name, outDir); } else { logger.warning("Could not find resource '" + name + "'!"); } } private void copyResource (InputStream in, String resource, File outDir) { // Copy it to the output folder OutputStream out = null; try { out = new FileOutputStream(new File(outDir, resource)); FileUtils.copy(in, out); } catch (FileNotFoundException ex) { throw new RuntimeException("Can not find output folder '" + mOutDir + "'.", ex); } catch (IOException ex) { throw new RuntimeException("Could not copy resource '" + resource + "'.", ex); } finally { IoUtil.close(in); IoUtil.close(out); } } private void copyStylesheet () { // 1. Try to read the stylesheet from the jar (default stylesheet) // 2. Try to open it from a user-defined location // 3. Use the default one if the user-defined is not found InputStream in = this.getClass().getResourceAsStream(mStyle); if (in == null) { try { final File style = new File(mStyle); in = new FileInputStream(style); } catch (FileNotFoundException ex) { IoUtil.close(in); in = this.getClass().getResourceAsStream(DEFAULT_STYLESHEET); if (in == null) { throw new RuntimeException("Can not find stylesheet file '" + mStyle + "'.", ex); } } } copyResource(in, DEFAULT_STYLESHEET, mOutDir); } private void parseArguments (String[] args) { try { for (int i = 0; i < args.length; ) { if ("-outDir".equals(args[i])) { setOutDir(new java.io.File(args[i + 1])); } else if ("-report".equals(args[i])) { setInputFile(new java.io.File(args[i + 1])); } else if ("-projectHome".equals(args[i])) { setProjectHome(new java.io.File(args[i + 1])); } else if ("-projectName".equals(args[i])) { setProjectName(args[i + 1]); } else if ("-cvsBase".equals(args[i])) { setCvsBase(args[i + 1]); } else if ("-cvsSuffix".equals(args[i])) { setCvsSuffix(args[i + 1]); } else if ("-timestamp".equals(args[i])) { setTimestamp(args[i + 1]); } else if ("-wikiBase".equals(args[i])) { setWikiBase(args[i + 1]); } else if ("-reportStyle".equals(args[i])) { setStyle(args[i + 1]); } else if ("-noCoverage".equals(args[i])) { setCoverageData(false); i -= 1; } else if ("-sourceEncoding".equals(args[i])) { setSourceCharset(Charset.forName(args[i + 1])); } else if ("-packageBase".equals(args[i])) { setPackageBase(args[i + 1]); } else if ("-loglevel".equals(args[i])) { setLoglevel(args[i + 1]); } else if ("-tabwidth".equals(args[i])) { setTabwidth(args[i + 1]); } else { throw new IllegalArgumentException( "Invalid argument '" + args[i] + "'"); } i += 1 /* command */ + 1 /* argument */; } } catch (IndexOutOfBoundsException e) { final IllegalArgumentException ex = new IllegalArgumentException("Missing value for " + args[args.length - 1]); ex.initCause(e); throw ex; } catch (Exception e) { final IllegalArgumentException ex = new IllegalArgumentException( "Problem with arument value for " + args[args.length - 1] + "Argument line was " + ArraysUtil.toString(args)); ex.initCause(e); throw ex; } } private void createPerFindingSummary () throws IOException { for (final FindingsSummary.FindingSummary summary : FindingsSummary.getFindingsSummary().getFindings().values()) { final String filename = summary.createFindingDetailFilename(); final BufferedWriter out = openWriter(filename); try { htmlHeader(out, "Finding-" + summary.getFindingType().getSymbol() + "-report " + mProjectName, ""); summary.createFindingTypeContent(out); out.write("</body></html>"); } finally { IoUtil.close(out); } } } private void createFindingsSummary () throws IOException { final BufferedWriter out = openWriter("findings.html"); try { htmlHeader(out, "Finding report " + mProjectName, ""); out.write("<h1><a href='index.html'>View by Classes</a></h1>"); out.write("<h1><a href='age-Build.html'>View by Age per Build</a> " + "<a href='age-Day.html'> Day</a> " + "<a href='age-Week.html'> Week</a> " + "<a href='age-Month.html'> Month</a> " + "<a href='age-Old.html'> Old</a></h1>"); out.write("<h1>Findings - Overview</h1>"); createNewFindingsList(out); createOldFindingsList(out); FindingsSummary.createOverallContent(out); out.write("</body></html>"); } finally { IoUtil.close(out); } } private void createNewFindingsList (BufferedWriter out) throws IOException { int row = 0; for (org.jcoderz.phoenix.report.jaxb.File file : (List<org.jcoderz.phoenix.report.jaxb.File>) mReport.getFile()) { for (Item item : (List<Item>) file.getItem()) { if (item.isNew()) { if (row == 0) { openTable(out, "New"); } createRow(out, file, item, row); row++; } } } if (row > 0) { closeTable(out); } } private void createOldFindingsList (BufferedWriter out) throws IOException { int row = 0; for (org.jcoderz.phoenix.report.jaxb.File file : (List<org.jcoderz.phoenix.report.jaxb.File>) mReport.getFile()) { for (Item item : (List<Item>) file.getItem()) { if (item.isOld()) { if (row == 0) { openTable(out, "Fixed"); } createRow(out, file, item, row); row++; } } } if (row > 0) { closeTable(out); } } private void createRow (Writer bw, org.jcoderz.phoenix.report.jaxb.File file, Item item, int rowCounter) throws IOException { // Don't be to colorful, use the OK coloring // for all entries. bw.write("<tr class='findings-"); bw.write(Java2Html.toOddEvenString(rowCounter)); bw.write("row'><td class='findings-image'>"); appendSeverityImage(bw, item, ""); bw.write("</td><td width='100%' class='findings-data'>"); bw.write("<a href='"); bw.write(createReportLink(file)); bw.write("#LINE"); bw.write(String.valueOf(item.getLine())); bw.write("'>"); bw.write(XmlUtil.escape(file.getClassname())); bw.write(": "); appendItemMessage(bw, item); bw.write("</a></td><td>"); if (item.isSetSince()) { bw.write(item.getSince().toDateString()); } bw.write("</td></tr>\n"); } private void openTable (Writer writer, String string) throws IOException { writer.write("<h2 class='severity-header'>"); writer.write(string); writer.write(" Findings</h2>"); writer.write("<table width='95%' cellpadding='2' cellspacing='0' " + "border='0'>"); } private void closeTable (Writer bw) throws IOException { bw.append("</table>"); } /** * converts a java source to HTML * with syntax highlighting for the * comments, keywords, strings and chars */ private void java2html (java.io.File inFile, org.jcoderz.phoenix.report.jaxb.File data) { mCurrentFindings.clear(); mHandledFindings.clear(); mFindingsInFile.clear(); mFindingsInCurrentLine.clear(); mActiveItems.clear(); mCurrentFindings.addAll(data.getItem()); fillFindingsInFile(data); logger.finest("Processing file " + inFile); BufferedWriter bw = null; String file = null; try { mPackage = data.getPackage(); mClassname = data.getClassname(); // If no class name is reported take the filename. if (StringUtil.isEmptyOrNull(mClassname)) { mClassname = inFile.getName(); } final String subdir = mPackage.replaceAll("\\.", "/"); final java.io.File dir = new java.io.File(mOutDir, subdir); FileUtils.mkdirs(dir); bw = openWriter(dir, mClassname + ".html"); final Syntax src = new Syntax(inFile, mCharSet, mTabWidth); final FileSummary summary = createFileSummary(src.getNumberOfLines(), subdir); addSummary(summary); file = mPackage + "." + mClassname; htmlHeader(bw, mClassname, mPackage); bw.write("<h1><a href='"); bw.write(relativeRoot(mPackage)); bw.write("'>Project Report: "); bw.write(mProjectName); bw.write("</a></h1>" + NEWLINE); bw.write("<h2><a href ='index.html'>Packagesummary "); bw.write(mPackage); bw.write("</a></h2>" + NEWLINE); final String cvsLink = getCvsLink(inFile.getAbsolutePath()); if (cvsLink != null) { bw.write("<h3><a href='" + cvsLink + "' class='cvs' title='cvs version'>" + file + "</a></h3>" + NEWLINE); } else { bw.write("<h3>" + file + "</h3>" + NEWLINE); } // create header!!!! bw.write("<table border='0' cellpadding='2' cellspacing='0' " + "width='95%'>"); bw.write("<thead><tr><th>Line</th><th>Hits</th><th>Note</th>" + "<th class='remainder'>Source</th></tr></thead>"); bw.write("<tbody>"); // PASS 2 final int lastLine = src.getNumberOfLines(); for (int currentLine = 1; currentLine <= lastLine; currentLine++) { bw.write("<tr class='" + errorLevel(currentLine) + Java2Html.toOddEvenString(currentLine) + "'>"); bw.write("<td align='right' class='lineno"); final boolean isLast = currentLine == lastLine; appendIf(bw, isLast, LAST_MARKER); bw.write("'><a name='LINE" + currentLine + "' />"); bw.write(String.valueOf(currentLine)); bw.write("</td>"); hitsCell(bw, String.valueOf(getHits(currentLine)), isLast); bw.write("<td class='note"); appendIf(bw, isLast, LAST_MARKER); bw.write("'>"); bw.write(getIcons(currentLine)); bw.write("</td><td class='code-"); bw.write(Java2Html.toOddEvenString(currentLine)); appendIf(bw, isLast, LAST_MARKER); bw.write("'>"); createCodeLine(bw, src); bw.write("</td></tr>\n"); } bw.write("</tbody>"); bw.write("</table>\n"); // findings table bw.write("<h2 class='findings-header'>Findings in this File</h2>"); bw.write("<table width='95%' cellpadding='0' cellspacing='0' " + "border='0'>\n"); int rowCounter = 0; final String relativeRoot = relativeRoot(mPackage, ""); int pos = mHandledFindings.size(); // findings with no line number or uncovered jet for (final List<Item> lineFindings : mFindingsInFile.values()) { for (final Item item : lineFindings) { if (!Origin.COVERAGE.equals(item.getOrigin())) { pos++; rowCounter++; bw.write("<tr class='findings-"); bw.write(Java2Html.toOddEvenString(rowCounter)); bw.write("row'>\n"); bw.write(" <td class='findings-image'>\n"); appendSeverityImage(bw, item, relativeRoot); bw.write(" </td>\n"); bw.write(" <td class='findings-id'>\n"); bw.write(" <a name='FINDING" + pos + "' />\n"); bw.write(" (" + pos + ")\n"); bw.write(" </td>\n"); bw.write(" <td></td><td></td><td></td>\n"); // line number bw.write(" <td width='100%' class='findings-data'>\n"); appendItemMessage(bw, item); bw.write(" </td>\n"); bw.write("</tr>\n"); } } } // Findings as marked in the code. pos = 0; for (final Item item : mHandledFindings) { pos++; rowCounter++; final String link = "#LINE" + item.getLine(); bw.write("<tr class='findings-"); bw.write(Java2Html.toOddEvenString(rowCounter)); bw.write("row'>\n"); bw.write(" <td class='findings-image'>\n"); appendSeverityImage(bw, item, relativeRoot); bw.write(" </td>\n"); bw.write(" <td class='findings-id'>\n"); bw.write(" <a name='FINDING" + pos + "' />\n"); bw.write(" <a href='" + link + "' title='" + item.getOrigin() + "' >\n"); bw.write(" (" + pos + ")\n"); bw.write(" </a>\n"); bw.write(" </td>\n"); bw.write(" <td class='findings-line-number' align='right'>\n"); bw.write(" <a href='" + link + "' >\n"); bw.write(String.valueOf(item.getLine())); bw.write(" </a>\n"); bw.write(" </td>\n"); bw.write(" <td class='findings-line-number' align='center'>\n"); bw.write(" <a href='" + link + "' >:</a>\n"); bw.write(" </td>\n"); bw.write(" <td class='findings-line-number' align='left'>\n"); bw.write(" <a href='" + link + "' >\n"); bw.write(String.valueOf(item.getColumn())); bw.write(" </a>\n"); bw.write(" </td>\n"); bw.write(" <td width='100%' class='findings-data'>\n"); bw.write(" <a href='" + link + "' >\n"); appendItemMessage(bw, item); bw.write("\n"); bw.write(" </a>\n"); bw.write(" </td>\n"); bw.write("</tr>\n"); } bw.write("</table>\n"); bw.write("\n</body>\n</html>"); } catch (FileNotFoundException fnfe) { logger.log(Level.WARNING, "Source file '" + file + "' not found.", fnfe); } catch (IOException ioe) { logger.log(Level.WARNING, "Problem with '" + file + "'.", ioe); } finally { IoUtil.close(bw); } } private void appendItemMessage (Writer bw, final Item item) throws IOException { if (item.isOld()) { bw.write("Fixed: "); } if (item.isNew()) { bw.write("New: "); } bw.write(XmlUtil.escape(item.getMessage())); if (item.getSeverityReason() != null) { bw.write(' '); bw.write(XmlUtil.escape(item.getSeverityReason())); } } /** * Generates a image related to the severity of the given Item. * The image links back to the general finding page of the item. * @param w the writer where to write the output to. * @param item the item to be documented. * @param root the relative path from the page generated to the root dir. * @throws IOException if the datas could not be written to the given * writer. */ private void appendSeverityImage (Writer w, Item item, String root) throws IOException { w.write("<a href='"); w.write(root); w.write(FindingsSummary.getFindingsSummary() .getFindingSummary(item).createFindingDetailFilename()); w.write("'><img border='0' title='"); w.write(String.valueOf(item.getSeverity())); w.write(" ["); w.write(String.valueOf(item.getOrigin())); w.write("]' alt='"); w.write(item.getSeverity().toString().substring(0, 1)); w.write("' src='"); w.write(root); w.write(getImage(item.getSeverity())); w.write("' /></a>\n"); } private String getImage (Severity severity) { return "images/icon_" + severity.toString() + ".gif"; } private FileSummary createFileSummary (final int linesCount, final String subdir) { // Create file summary info final FileSummary summary = new FileSummary(mClassname, mPackage, subdir + "/" + mClassname + ".html", linesCount, mCoverageData); for (final Item item : mCurrentFindings) { FindingsSummary.addFinding(item, summary); if (Origin.COVERAGE.equals(item.getOrigin())) { if (item.getCounter() != 0) { summary.addCoveredLine(); } else { summary.addViolation(Severity.COVERAGE); } } else { summary.addViolation(item.getSeverity()); } } return summary; } private void fillFindingsInFile ( org.jcoderz.phoenix.report.jaxb.File data) { for (final Item item : (List<Item>) data.getItem()) { final int lineNumber = item.getLine(); List<Item> itemsInLine = mFindingsInFile.get(lineNumber); if (itemsInLine == null) { itemsInLine = new ArrayList<Item>(); mFindingsInFile.put(lineNumber, itemsInLine); } itemsInLine.add(item); } } /** * Generates the stylesheet link for html output. * @param packageName the package of the current generated file. Used * to generate a relative link. * @param style the style to use (relative to report path or absolute) * @return the style link as to be placed in the head of the generated * html file. */ private static String createStyle (String packageName, String style) { // TODO: use the default stylesheet if not explicitly specified String result = ""; if (style != null) { final String styleLink; if (style.indexOf(" { // absolute style styleLink = style; } else { styleLink = relativeRoot(packageName, style); } result = "<link rel='stylesheet' type='text/css' href='" + styleLink + "' />"; } return result; } private Severity errorLevel (int line) { Severity severity = Severity.OK; final Iterator<Item> active = mActiveItems.iterator(); while (active.hasNext()) { final Item item = active.next(); if (item.getEndLine() < line) { active.remove(); } else { severity = severity.max(item.getSeverity()); } } final Iterator<Item> items = findingsInLine(line); while (items.hasNext()) { final Item item = items.next(); if (item.getOrigin().equals(Origin.COVERAGE)) { if (item.getCounter() == 0) { severity = severity.max(Severity.COVERAGE); } } else { severity = severity.max(item.getSeverity()); if (item.getEndLine() > line) { mActiveItems.add(item); } } } return severity; } private Iterator<Item> findingsInLine (int line) { final List<Item> findingsInLine = mFindingsInFile.get(line); final Iterator<Item> result; if (findingsInLine == null) { result = EmptyIterator.EMPTY_ITERATOR; } else { result = findingsInLine.iterator(); } return result; } private String getHits (int line) { String hits = "&nbsp;"; final Iterator<Item> items = findingsInLine(line); while (items.hasNext()) { final Item item = items.next(); if (Origin.COVERAGE.equals(item.getOrigin())) { hits = String.valueOf(item.getCounter()); break; } } return hits; } /** * Fills the 'Note' column for the given line. * @param line the line under inspection. * @return the content to be put in the notes column for the given line. */ private String getIcons (int line) { final StringBuilder icons = new StringBuilder(); // collect relevant findings final Iterator<Item> items = findingsInLine(line); while (items.hasNext()) { final Item item = items.next(); if (Origin.COVERAGE.equals(item.getOrigin())) { if (item.getCounter() == 0) { items.remove(); // will never see this again! } } else if (item.getSeverity() == Severity.FILTERED || item.isOld()) { // not listen with the code but in the global section below the // code. } else { mHandledFindings.add(item); // create the magic icon string with a hyperlink mGetIconsStringBuffer.setLength(0); mGetIconsStringBuffer.append("<a href='#FINDING"); mGetIconsStringBuffer.append(mHandledFindings.size()); mGetIconsStringBuffer.append("' title='"); mGetIconsStringBuffer.append( XmlUtil.attributeEscape(item.getMessage())); mGetIconsStringBuffer.append("'><span class='"); mGetIconsStringBuffer.append(item.getOrigin()); mGetIconsStringBuffer.append("note'>("); mGetIconsStringBuffer.append(mHandledFindings.size()); mGetIconsStringBuffer.append(")</span></a>"); icons.append(mGetIconsStringBuffer); if (item.isSetColumn() && (!item.isSetEndLine() || item.getEndLine() - line <= MAX_LINES_WITH_INLINE_MARK)) { mFindingsInCurrentLine.add(item); } items.remove(); // item was handled fully } } if (icons.length() == 0) { icons.append("&nbsp;"); } return icons.toString(); } /** * Replaces leading whitespace by a none breakable html string * (entity). * Uses <code>mStringBuffer</code> as temporary string buffer. * @param in The string to modify. * @return The string with leading white spaces replaced. */ private String replaceLeadingSpaces (String in) { final String result; if (in == null || in.length() == 0) { result = "&nbsp;"; } else if (in.charAt(0) == ' ' || in.charAt(0) == '\t') { mStringBuilder.setLength(0); int i; int pos = 0; for (i = 0; i < in.length() && (in.charAt(i) == ' ' || in.charAt(i) == '\t'); i++) { if (in.charAt(i) == ' ') { mStringBuilder.append("&nbsp;"); pos++; } else if (in.charAt(i) == '\t') { mStringBuilder.append("&nbsp;"); pos++; while (pos % mTabWidth != 0) { mStringBuilder.append("&nbsp;"); pos++; } } } mStringBuilder.append(in.substring(i)); result = mStringBuilder.toString(); } else { result = in; } return result; } /** * Adds the file summary to all summary lists. */ private void addSummary (FileSummary summary) { mAllFiles.add(summary); List<FileSummary> packageList = mAllPackages.get(summary.getPackage()); if (packageList == null) { packageList = new ArrayList<FileSummary>(); mAllPackages.put(summary.getPackage(), packageList); } packageList.add(summary); FileSummary packageSummary = mPackageSummary.get(summary.getPackage()); if (packageSummary == null) { packageSummary = new FileSummary(mPackage); mPackageSummary.put(summary.getPackage(), packageSummary); } packageSummary.add(summary); mGlobalSummary.add(summary); } private void createPackageSummary (List<FileSummary> pkg) throws IOException { createPackageSummary(new FileSummary.SortByPackage(), pkg); createPackageSummary(new FileSummary.SortByQuality(), pkg); createPackageSummary(new FileSummary.SortByCoverage(), pkg); } private void createPackageSummary (Comparator<FileSummary> order, List<FileSummary> pkg) throws IOException { final String filename = fileNameForOrder(order); final String packageName = pkg.get(0).getPackage(); final String subdir = packageName.replaceAll("\\.", "/"); final java.io.File dir = new java.io.File(mOutDir, subdir); FileUtils.mkdirs(dir); final BufferedWriter bw = openWriter(dir, filename); try { htmlHeader(bw, packageName, packageName); bw.write("<h1><a href='" + relativeRoot(packageName, filename) + "'>Project-Report " + mProjectName + "</a></h1>"); bw.write("<h2>Packagesummary " + packageName + "</h2>"); createClassListTable(bw, pkg, false, order); bw.write("</body></html>"); } finally { IoUtil.close(bw); } } private void createFullSummary () throws IOException { createFullSummary(new FileSummary.SortByPackage()); createFullSummary(new FileSummary.SortByQuality()); createFullSummary(new FileSummary.SortByCoverage()); } private void createFullSummary (Comparator<FileSummary> order) throws IOException { final String filename = fileNameForOrder(order); final BufferedWriter bw = openWriter(filename); try { htmlHeader(bw, "Project Report " + mProjectName, ""); bw.write("<h1>Project Report " + mProjectName + "</h1>"); bw.write("<table border='0' cellpadding='2' cellspacing='0' " + "width='95%'>"); bw.write("<thead><tr><th>"); if (filename != SORT_BY_PACKAGE_INDEX) { bw.write("<a href='" + SORT_BY_PACKAGE_INDEX + "' title='Sort by name'>"); } bw.write("Package"); if (filename != SORT_BY_PACKAGE_INDEX) { bw.write("</a>"); } bw.write("</th><th>findings</th>"); bw.write("<th>files</th><th>lines</th>"); if (mCoverageData) { bw.write("<th>%</th><th>"); if (filename != SORT_BY_COVERAGE_INDEX) { bw.write("<a href='" + SORT_BY_COVERAGE_INDEX + "' title='Sort by coverage'>"); } bw.write("Coverage"); if (filename != SORT_BY_COVERAGE_INDEX) { bw.write("</a>"); } bw.write("</th>"); } bw.write("<th>%</th><th class='remainder'>"); if (filename != SORT_BY_QUALITY_INDEX) { bw.write("<a href='" + SORT_BY_QUALITY_INDEX + "' title='Sort by quality'>"); } bw.write("Quality"); if (filename != SORT_BY_QUALITY_INDEX) { bw.write("</a>"); } bw.write("</th></tr></thead>"); bw.write("<tbody>"); bw.write(NEWLINE); bw.write("<tr class='odd'><td class='classname" + LAST_MARKER + "'>"); bw.write("Overall summary"); bw.write("</td>"); hitsCell(bw, String.valueOf(mGlobalSummary.getNumberOfFindings()), true); hitsCell(bw, String.valueOf(mGlobalSummary.getNumberOfFiles()), true); hitsCell(bw, String.valueOf(mGlobalSummary.getLinesOfCode()), true); if (mCoverageData) { hitsCell(bw, String.valueOf(mGlobalSummary.getCoverageAsString()), true); bw.write("<td valign='middle' class='hits" + LAST_MARKER + "' width='100'>"); bw.write(mGlobalSummary.getCoverageBar()); bw.write("</td>"); } hitsCell(bw, String.valueOf(mGlobalSummary.getQuality()) + "%", true); bw.write("<td valign='middle' class='code" + LAST_MARKER + "' width='100'>"); bw.write(mGlobalSummary.getPercentBar()); bw.write("</td></tr>"); bw.write(NEWLINE); bw.write("</tbody>"); bw.write("</table>"); bw.write("<h1><a href='findings.html'>View by Finding</a></h1>"); bw.write("<h1><a href='age-Build.html'>View by Age per Build</a> " + "<a href='age-Day.html'> Day</a> " + "<a href='age-Week.html'> Week</a> " + "<a href='age-Month.html'> Month</a> " + "<a href='age-Old.html'> Old</a></h1>"); bw.write("<h1>Packages</h1>"); bw.write("<table border='0' cellpadding='2' cellspacing='0' " + "width='95%'>"); bw.write("<thead><tr><th>Package</th>" + "<th>findings</th><th>files</th><th>lines</th>"); if (mCoverageData) { bw.write("<th>%</th><th>Coverage</th>"); } bw.write("<th>%</th><th class='remainder'>Quality</th></tr></thead>"); bw.write("<tbody>"); bw.write(NEWLINE); final Set<FileSummary> packages = new TreeSet<FileSummary>(order); packages.addAll(mPackageSummary.values()); int pos = 0; final Iterator<FileSummary> i = packages.iterator(); while (i.hasNext()) { pos++; final FileSummary pkg = i.next(); final boolean isLast = !i.hasNext(); appendPackageLink(bw, pkg, filename, pos, isLast); } bw.write("</tbody></table>\n"); // findings with no line number... createUnassignedFindingsTable(bw); bw.write("<h1>Java Files</h1>"); createClassListTable(bw, mAllFiles, true, order); bw.write("</body></html>"); } finally { IoUtil.close(bw); } } private void createUnassignedFindingsTable (final BufferedWriter bw) throws IOException { boolean tableOpened = false; int row = 0; for (final org.jcoderz.phoenix.report.jaxb.File file : mGlobalFindings) { for (final Item item : (List<Item>) file.getItem()) { row++; if (!tableOpened) { bw.write("<h1>Unassigned findings</h1>"); bw.write("<table border='0' cellpadding='0' " + "cellspacing='0' width='95%'>"); tableOpened = true; } bw.write("<tr class='"); bw.write(item.getSeverity().toString()); bw.write(Java2Html.toOddEvenString(row)); bw.write("'><td class='unassigned-origin'>"); bw.write(ObjectUtil.toStringOrEmpty(item.getOrigin())); bw.write("</td><td class='unassigned-filename'>"); bw.write(cutPath(file.getName())); bw.write("</td><td class='unassigned-data' width='100%'>"); bw.write(item.getMessage()); bw.write("</td></tr>"); FindingsSummary.addFinding(item, mGlobalSummary); } } if (tableOpened) { bw.write("</table>"); } } private void appendPackageLink (final BufferedWriter bw, final FileSummary pkg, final String filename, final int pos, final boolean isLast) throws IOException { final String name = pkg.getPackage(); final String subdir = name.replaceAll("\\.", "/"); bw.write("<tr class='" + Java2Html.toOddEvenString(pos) + "'><td class='classname"); appendIf(bw, isLast, LAST_MARKER); bw.write("'><a href='" + subdir + "/" + filename + "'>"); bw.write(pkg.getPackage()); bw.write("</a></td>"); hitsCell(bw, String.valueOf(pkg.getNumberOfFindings()), isLast); hitsCell(bw, String.valueOf(pkg.getNumberOfFiles()), isLast); hitsCell(bw, String.valueOf(pkg.getLinesOfCode()), isLast); if (mCoverageData) { hitsCell(bw, String.valueOf(pkg.getCoverageAsString()), isLast); bw.write("<td valign='middle' class='hits"); appendIf(bw, isLast, LAST_MARKER); bw.write("' width='100'>"); bw.write(pkg.getCoverageBar()); bw.write("</td>"); } hitsCell(bw, String.valueOf(pkg.getQuality()) + "%", isLast); bw.write("<td valign='middle' class='code"); appendIf(bw, isLast, LAST_MARKER); bw.write("' width='100'>"); bw.write(pkg.getPercentBar()); bw.write("</td></tr>" + NEWLINE); } /** * Writes a html header to the given output stream. * @param bw the stream to use for output * @param title the title of the page. Should be the package name for * sub packages. */ private void htmlHeader (Writer bw, String title, String packageName) throws IOException { bw.write("<?xml version='1.0' encoding='UTF-8'?>" + NEWLINE + "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" " + NEWLINE + "\"http: + NEWLINE + "<html xmlns='http: + " lang='en'>" + NEWLINE + "<head>" + NEWLINE + "\t<title>"); bw.write(title); bw.write("</title>" + NEWLINE + "\t<meta name='author' content='jCoderZ java2html' />" + NEWLINE); bw.write(createStyle(packageName, mStyle)); bw.write(NEWLINE + "</head>" + NEWLINE + "<body>" + NEWLINE); } private Date renderAgePage ( List<Item> findings, Date startDate, ReportInterval periode) throws IOException { final Writer bw = openWriter(mOutDir, "age-" + periode.toString() + ".html"); htmlHeader(bw, "Finding in " + periode.toString(), ""); bw.write("<h1><a href='index.html'>View by Classes</a></h1>"); bw.write("<h1><a href='findings.html'>View by Finding</a></h1>"); bw.write("<h1><a href='age-Build.html'>View by Age per Build</a> " + "<a href='age-Day.html'> Day</a> " + "<a href='age-Week.html'> Week</a> " + "<a href='age-Month.html'> Month</a> " + "<a href='age-Old.html'> Old</a></h1>"); if (ReportInterval.OLD != periode) { bw.write("<h1>Current Findings by " + periode.toString() + "</h1>"); } else { bw.write("<h1>Old findings since " + startDate + "</h1>"); } int numberOfSegments = 0; Date iStart = null; try { Date iEnd = null; final List<Item> interval = new ArrayList<Item>(); for (Item i : findings) { if (iEnd == null) { if (i.getSince().before(startDate)) { iStart = getPeriodStart(periode, i.getSince()); iEnd = getPeriodEnd(periode, i.getSince()); } else { continue; } } if (i.getSince().before(iStart)) { Collections.sort(interval, new ItemSeverityComperator()); createSegment(bw, interval, iStart, iEnd); interval.clear(); numberOfSegments++; if (numberOfSegments > NUMBER_OF_AGE_SEGMENTS) { break; } iStart = getPeriodStart(periode, i.getSince()); iEnd = getPeriodEnd(periode, i.getSince()); } interval.add(i); } if (!interval.isEmpty()) { Collections.sort(interval, new ItemSeverityComperator()); createSegment(bw, interval, iStart, iEnd); interval.clear(); } } finally { IoUtil.close(bw); } return iStart == null ? startDate : iStart; } private void createSegment ( Writer bw, List<Item> items, Date start, Date end) throws IOException { if (!items.isEmpty()) { openTable(bw, "Findings " + start + (start.equals(end) ? "" : (" - " + end)) + " " + items.size()); } int pos = 0; for (final Item item : items) { createRow(bw, getFile(item), item, pos); pos++; } if (!items.isEmpty()) { closeTable(bw); } } private org.jcoderz.phoenix.report.jaxb.File getFile (Item item) { return mItemToFileMap.get(item); } private Date getPeriodEnd (ReportInterval periode, Date actualStart) { final Date result; if (ReportInterval.BUILD == periode) { result = actualStart.plus(1); } else if (ReportInterval.DAY == periode) { final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.setTimeInMillis(actualStart.getTime()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.add(Calendar.DAY_OF_MONTH, 1); result = new Date(cal.getTimeInMillis()); } else if (ReportInterval.WEEK == periode) { final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.setFirstDayOfWeek(Calendar.MONDAY); cal.setTimeInMillis(actualStart.getTime()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.add(Calendar.WEEK_OF_YEAR, 1); result = new Date(cal.getTimeInMillis()); } else if (ReportInterval.MONTH == periode) { final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.setFirstDayOfWeek(Calendar.MONDAY); cal.setTimeInMillis(actualStart.getTime()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.DAY_OF_MONTH, 1); cal.add(Calendar.MONTH, 1); result = new Date(cal.getTimeInMillis()); } else if (ReportInterval.OLD == periode) { result = actualStart; } else { Assert.fail("Unsupported value for ReportInterval " + periode); result = null; // never reached } return result; } private Date getPeriodStart (ReportInterval periode, Date pos) { final Date result; if (ReportInterval.BUILD == periode) { result = pos; } else if (ReportInterval.DAY == periode) { final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.setTimeInMillis(pos.getTime()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); result = new Date(cal.getTimeInMillis()); } else if (ReportInterval.WEEK == periode) { final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.setFirstDayOfWeek(Calendar.MONDAY); cal.setTimeInMillis(pos.getTime()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.add(Calendar.DAY_OF_MONTH, 1 - cal.get(Calendar.DAY_OF_WEEK)); result = new Date(cal.getTimeInMillis()); } else if (ReportInterval.MONTH == periode) { final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.setFirstDayOfWeek(Calendar.MONDAY); cal.setTimeInMillis(pos.getTime()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.DAY_OF_MONTH, 1); result = new Date(cal.getTimeInMillis()); } else if (ReportInterval.OLD == periode) { result = Date.OLD_DATE; } else { Assert.fail("Unsupported value for ReportInterval " + periode); result = null; // never reached } return result; } private static String relativeRoot (String currentPackage) { return relativeRoot(currentPackage, "index.html"); } private static String relativeRoot (String currentPackage, String page) { final StringBuilder rootDir = new StringBuilder(); if (currentPackage.length() != 0) { rootDir.append("../"); } for (int i = 0; i < currentPackage.length(); i++) { if (currentPackage.charAt(i) == '.') { rootDir.append("../"); } } rootDir.append(page); return rootDir.toString().replaceAll(" } private String cutPath (String fileName) { String result = ObjectUtil.toStringOrEmpty(fileName); if (fileName != null && fileName.toLowerCase(Constants.SYSTEM_LOCALE) .startsWith(mProjectHome.toLowerCase(Constants.SYSTEM_LOCALE))) { result = fileName.substring(mProjectHome.length()); } return result; } private String getCvsLink (String absFile) { String result; if (mWebVcBase == null || mProjectHome == null) { result = null; } else if (absFile.toLowerCase(Constants.SYSTEM_LOCALE) .startsWith(mProjectHome.toLowerCase(Constants.SYSTEM_LOCALE))) { result = absFile.substring(mProjectHome.length()); } else { absFile = (new java.io.File(absFile)).getAbsolutePath(); if (absFile.toLowerCase(Constants.SYSTEM_LOCALE) .startsWith(mProjectHome.toLowerCase(Constants.SYSTEM_LOCALE))) { result = absFile.substring(mProjectHome.length()); } else { result = null; } } if (result != null) { result = mWebVcBase + result + mWebVcSuffix; result = result.replaceAll("\\\\", "/"); } return result; } /** * Create the marked html output for the current line. * @param out the writer to generate the output to. * @param src the source to read the line data from. * @throws IOException if IO operations fail writing to the * given writer. */ private void createCodeLine (Writer out, Syntax src) throws IOException { String text = src.nextToken(); String lastTokenType = null; Item lastFinding = null; boolean isFirst = true; while (null != src.getCurrentTokenType()) { final Item currentFinding = getCurrentFinding(text, src.getCurrentLineNumber(), src.getCurrentLinePos(), src.getCurrentTokenLength()); if (currentFinding != lastFinding) { if (lastTokenType != null) { out.write("</span>"); // close token type lastTokenType = null; } if (lastFinding != null) { out.write("</span>"); // close last finding } if (currentFinding != null) { out.write("<span class='finding-"); out.write(currentFinding.getSeverity().toString()); out.write("' title='"); out.write( XmlUtil.attributeEscape(currentFinding.getMessage())); out.write("'>"); } lastFinding = currentFinding; } final String tokenType = src.getCurrentTokenType(); if (!tokenType.equals(lastTokenType)) { if (lastTokenType != null) { out.write("</span>"); isFirst = false; } out.write("<span class='code-"); out.write(tokenType); out.write("'>"); } String xml = XmlUtil.escape(text); if (isFirst) { xml = replaceLeadingSpaces(xml); } out.write(xml); lastTokenType = tokenType; text = src.nextToken(); } if (lastTokenType != null) { out.write("</span>"); } if (lastFinding != null) { out.write("</span>"); } } private Item getCurrentFinding ( String text, int currentLineNumber, int currentLinePos, int tokenLen) { Item theFinding = null; final Iterator<Item> i = mFindingsInCurrentLine.iterator(); while (i.hasNext()) { final Item finding = i.next(); if (finding.getEndLine() < currentLineNumber && finding.getLine() < currentLineNumber) { i.remove(); continue; } final int start = finding.getLine() == currentLineNumber ? finding.getColumn() : 0; int end = finding.getEndLine() == currentLineNumber ? finding.getEndColumn() : ABSOLUTE_END_OF_LINE; if (finding.getEndLine() == 0) { end = finding.getEndColumn(); } // TODO Add code to find pos by symbol! // finding at current pos if ((start == currentLinePos && end == 0) // or in range that contains the current pos || (start <= currentLinePos && end >= currentLinePos) // or inside the token || (start >= currentLinePos && start < currentLinePos + tokenLen)) { if (theFinding == null || finding.getSeverity().compareTo( theFinding.getSeverity()) > 0) { theFinding = finding; } } } return theFinding; } /** * Creates a list of all classes as html table and appends it to the * given bw. */ private void createClassListTable (BufferedWriter bw, Collection<FileSummary> files, boolean fullPackageNames, Comparator<FileSummary> order) throws IOException { // Do not create a table if no classes are here. if (!files.isEmpty()) { final String filename = fileNameForOrder(order); final FileSummary[] summaries = files.toArray(new FileSummary[files.size()]); Arrays.sort(summaries, order); bw.write("<table border='0' cellpadding='2' cellspacing='0' " + "width='95%'>"); bw.write("<thead><tr><th>"); if (filename != SORT_BY_PACKAGE_INDEX) { bw.write("<a href='"); bw.write(SORT_BY_PACKAGE_INDEX); bw.write("' title='Sort by name'>"); } bw.write("Classfile"); if (filename != SORT_BY_PACKAGE_INDEX) { bw.write("</a>"); } bw.write("</th><th>findings</th><th>lines</th>"); if (mCoverageData) { bw.write("<th>%</th><th>"); if (filename != SORT_BY_COVERAGE_INDEX) { bw.write("<a href='"); bw.write(SORT_BY_COVERAGE_INDEX); bw.write("' title='Sort by coverage'>"); } bw.write("Coverage"); if (filename != SORT_BY_COVERAGE_INDEX) { bw.write("</a>"); } bw.write("</th>"); } bw.write("<th>%</th><th class='remainder'>"); if (filename != SORT_BY_QUALITY_INDEX) { bw.write("<a href='"); bw.write(SORT_BY_QUALITY_INDEX); bw.write("' title='Sort by quality'>"); } bw.write("Quality"); if (filename != SORT_BY_QUALITY_INDEX) { bw.write("</a>"); } bw.write("</th></tr></thead>"); bw.write("<tbody>"); bw.write(NEWLINE); int pos = 0; final Iterator<FileSummary> i = Arrays.asList(summaries).iterator(); while (i.hasNext()) { pos++; final FileSummary file = i.next(); final boolean isLast = !i.hasNext(); appendClassLink(bw, file, fullPackageNames, pos, isLast); } bw.write("</tbody>"); bw.write("</table>"); } else { bw.write("EMPTY!?"); } } private void appendClassLink (BufferedWriter bw, final FileSummary file, boolean fullPackageNames, int pos, final boolean isLast) throws IOException { final String name; final String link; if (fullPackageNames) { name = file.getPackage() + '.' + file.getClassName(); link = file.getPackage().replaceAll("\\.", "/") + "/" + file.getClassName() + ".html"; } else { name = file.getClassName(); link = file.getClassName() + ".html"; } bw.write("<tr class='"); bw.write(Java2Html.toOddEvenString(pos)); bw.write("'><td class='classname"); appendIf(bw, isLast, LAST_MARKER); bw.write("'><a href='"); bw.write(link); bw.write("'>"); bw.write(name); bw.write("</a></td>"); hitsCell(bw, String.valueOf(file.getNumberOfFindings()), isLast); hitsCell(bw, String.valueOf(file.getLinesOfCode()), isLast); if (mCoverageData) { hitsCell(bw, file.getCoverageAsString(), isLast); bw.write("<td valign='middle' class='hits"); appendIf(bw, isLast, LAST_MARKER); bw.write("' width='100'>"); bw.write(file.getCoverageBar()); bw.write("</td>"); } hitsCell(bw, String.valueOf(file.getQuality()) + "%", isLast); bw.write("<td valign='middle' class='code"); appendIf(bw, isLast, LAST_MARKER); bw.write("' width='100'>"); bw.write(file.getPercentBar()); bw.write("</td></tr>"); bw.write(NEWLINE); } private static String fileNameForOrder (Comparator<FileSummary> order) { String filename; if (order instanceof FileSummary.SortByPackage) { filename = SORT_BY_PACKAGE_INDEX; } else if (order instanceof FileSummary.SortByQuality) { filename = SORT_BY_QUALITY_INDEX; } else if (order instanceof FileSummary.SortByCoverage) { filename = SORT_BY_COVERAGE_INDEX; } else { throw new RuntimeException("Order not expected " + order); } return filename; } /** * Generates the content (including surounding elements) of a cell * of hits type. * @param bw the writer to write to. * @param content the cell contend * @param isLast true if this sell is in the last row. * @throws IOException if the write fails. */ private static void hitsCell (BufferedWriter bw, String content, boolean isLast) throws IOException { bw.write("<td valign='middle' class='hits"); appendIf(bw, isLast, LAST_MARKER); bw.write("'>"); bw.write(content); bw.write("</td>"); } private static void appendIf (BufferedWriter bw, boolean condition, String str) throws IOException { if (condition) { bw.write(str); } } private BufferedWriter openWriter (String filename) throws IOException { return openWriter(mOutDir, filename); } private BufferedWriter openWriter (File dir, String filename) throws IOException { FileOutputStream fos = null; OutputStreamWriter osw = null; BufferedWriter result = null; try { fos = new FileOutputStream(new java.io.File(dir, filename)); osw = new OutputStreamWriter(fos, Constants.ENCODING_UTF8); result = new BufferedWriter(osw); } catch (RuntimeException ex) { IoUtil.close(result); IoUtil.close(osw); IoUtil.close(fos); throw ex; } catch (IOException ex) { IoUtil.close(result); IoUtil.close(osw); IoUtil.close(fos); throw ex; } return result; } private static String createReportLink ( org.jcoderz.phoenix.report.jaxb.File file) { final String pkg = ObjectUtil.toStringOrEmpty(file.getPackage()); String clazzName = ObjectUtil.toStringOrEmpty(file.getClassname()); // If no class name is reported take the filename. if (StringUtil.isEmptyOrNull(clazzName)) { if (!StringUtil.isEmptyOrNull(file.getName())) { clazzName = new File(file.getName()).getName(); } else { clazzName = ""; } } final String subdir = pkg.replaceAll("\\.", "/"); return subdir + "/" + clazzName + ".html"; } private static class ItemSeverityComperator implements Comparator<Item>, Serializable { private static final long serialVersionUID = 1L; public int compare (Item o1, Item o2) { int result = 0; result = -(o1.getSeverity().compareTo(o2.getSeverity())); if (result == 0) { result = o1.getSince().compareTo(o2.getSince()); } if (result == 0) { if (o1.getLine() > o2.getLine()) { result = 1; } else if (o1.getLine() < o2.getLine()) { result = -1; } else { result = 0; } } if (result == 0) { result = o1.getFindingType().compareTo(o2.getFindingType()); } return result; } } private static class ItemAgeComperator implements Comparator<Item>, Serializable { private static final long serialVersionUID = 1L; public int compare (Item o1, Item o2) { final Date since1 = o1.isSetSince() ? o1.getSince() : Date.OLD_DATE; final Date since2 = o2.isSetSince() ? o2.getSince() : Date.OLD_DATE; return since1.compareTo(since2); } } }
package tests.net.sf.jabref; import java.io.File; import java.io.IOException; import java.io.StringReader; import junit.framework.TestCase; import net.sf.jabref.BibtexDatabase; import net.sf.jabref.BibtexEntry; import net.sf.jabref.Globals; import net.sf.jabref.JabRefPreferences; import net.sf.jabref.Util; import net.sf.jabref.imports.BibtexParser; import net.sf.jabref.imports.ParserResult; /** * Testing Util.findFile for finding files based on regular expressions. * * @author Christopher Oezbek <oezi@oezi.de> */ public class UtilFindFileTest extends FileBasedTestCase { String findFile(String dir, String file) { return Util.findFile(entry, database, dir, file, true); } /** * Test that more than one slash is taken to mean that a relative path is to * be returned. * * @throws IOException */ public void testFindFileRelative() throws IOException { // Most basic case assertEqualPaths("HipKro03.pdf", findFile(root.getAbsolutePath() + "/test/", "[bibtexkey].pdf")); // Including directory assertEqualPaths("test/HipKro03.pdf", findFile(root.getAbsolutePath(), "test/[bibtexkey].pdf")); // No relative paths assertEqualPaths(new File(root, "test/HipKro03.pdf").getCanonicalPath(), findFile(null, root.getAbsolutePath() + "/test/" + "[bibtexkey].pdf")); // No relative paths assertEqualPaths(new File(root, "test/HipKro03.pdf").getCanonicalPath(), Util.findFile( entry, database, root.getAbsolutePath() + "/test/" + "[bibtexkey].pdf")); } public void testFindPdf() throws IOException { { String pdf = Util.findPdf(entry, "pdf", root.getAbsolutePath()); assertEqualPaths("HipKro03 - Hello.pdf", pdf); File fullPath = Util.expandFilename(pdf, root.getAbsolutePath()); assertTrue(fullPath.exists()); } { String pdf = Util.findPdf(entry, "pdf", root.getAbsolutePath() + "/pdfs/"); assertEqualPaths("sub/HipKro03-sub.pdf", pdf); File fullPath = Util.expandFilename(pdf, root.getAbsolutePath() + "/pdfs/"); assertTrue(fullPath.exists()); } } public void testFindPdfInMultiple() throws IOException { { String[] dirsToSearch = new String[] { root.getAbsolutePath(), root.getAbsolutePath() + "/pdfs/" }; String pdf = Util.findPdf(entry, "pdf", dirsToSearch); assertEqualPaths("HipKro03 - Hello.pdf", pdf); File fullPath = Util.expandFilename(pdf, dirsToSearch); assertTrue(fullPath.exists()); assertEqualPaths(root.getAbsolutePath() + "/HipKro03 - Hello.pdf", fullPath .getAbsolutePath()); String tmp = dirsToSearch[1]; dirsToSearch[1] = dirsToSearch[0]; dirsToSearch[0] = tmp; fullPath = Util.expandFilename(pdf, dirsToSearch); assertTrue(fullPath.exists()); assertEqualPaths(root.getAbsolutePath() + "/HipKro03 - Hello.pdf", fullPath .getAbsolutePath()); fullPath = Util.expandFilename(pdf, new String[] { dirsToSearch[0] }); assertEquals(null, fullPath); fullPath = Util.expandFilename(pdf, new String[] { dirsToSearch[1] }); assertTrue(fullPath.exists()); assertEqualPaths(root.getAbsolutePath() + "/HipKro03 - Hello.pdf", fullPath .getAbsolutePath()); } { String[] dirsToSearch = new String[] { root.getAbsolutePath() + "/pdfs/", root.getAbsolutePath() }; String pdf = Util.findPdf(entry, "pdf", dirsToSearch); assertEqualPaths("sub/HipKro03-sub.pdf", pdf); File fullPath = Util.expandFilename(pdf, dirsToSearch); assertTrue(fullPath.exists()); assertEqualPaths(root.getAbsolutePath() + "/pdfs/sub/HipKro03-sub.pdf", fullPath .getAbsolutePath()); String tmp = dirsToSearch[1]; dirsToSearch[1] = dirsToSearch[0]; dirsToSearch[0] = tmp; fullPath = Util.expandFilename(pdf, dirsToSearch); assertTrue(fullPath.exists()); assertEqualPaths(root.getAbsolutePath() + "/pdfs/sub/HipKro03-sub.pdf", fullPath .getAbsolutePath()); fullPath = Util.expandFilename(pdf, new String[] { dirsToSearch[0] }); assertEquals(null, fullPath); fullPath = Util.expandFilename(pdf, new String[] { dirsToSearch[1] }); assertTrue(fullPath.exists()); assertEqualPaths(root.getAbsolutePath() + "/pdfs/sub/HipKro03-sub.pdf", fullPath .getAbsolutePath()); } } public void testFindFile() throws IOException { // Simple case assertEqualPaths("HipKro03.pdf", Util.findFile(entry, database, root.getAbsolutePath() + "/test/", "[bibtexkey].pdf", true)); // Not found assertEqualPaths(null, Util.findFile(entry, database, root.getAbsolutePath() + "/test/", "Not there [bibtexkey].pdf", true)); // Test current dir assertEqualPaths(new File(new File("."), "build.xml").getCanonicalPath(), Util.findFile( entry, database, "./build.xml")); assertEqualPaths("build.xml", Util.findFile(entry, database, ".", "build.xml", true)); // Test keys in path and regular expression in file assertEqualPaths(new File(root, "/2003/Paper by HipKro03.pdf").getCanonicalPath(), Util .findFile(entry, database, root.getAbsolutePath() + "/[year]/.*[bibtexkey].pdf")); // Test . and .. assertEqualPaths(new File(root, "/Organization Science/HipKro03 - Hello.pdf") .getCanonicalPath(), Util.findFile(entry, database, root.getAbsolutePath() + "/[year]/../2003/.././././[journal]\\" + ".*[bibtexkey].*.pdf")); // Test Escape assertEqualPaths(new File(root, "/Organization Science/HipKro03 - Hello.pdf") .getCanonicalPath(), Util.findFile(entry, database, root.getAbsolutePath() + "/*/" + "[bibtexkey] - Hello\\\\.pdf")); assertEqualPaths("TE.ST", Util.findFile(entry, database, root.getAbsolutePath() + "/test/", "TE\\\\.ST", true)); assertEqualPaths(".TEST", Util.findFile(entry, database, root.getAbsolutePath() + "/test/", "\\\\.TEST", true)); assertEqualPaths("TEST[", Util.findFile(entry, database, root.getAbsolutePath() + "/test/", "TEST\\\\[", true)); // Test * assertEqualPaths(new File(root, "/Organization Science/HipKro03 - Hello.pdf") .getCanonicalPath(), Util.findFile(entry, database, root.getAbsolutePath() + "/*/" + "[bibtexkey].+?.pdf")); // Test ** assertEqualPaths(new File(root, "/pdfs/sub/HipKro03-sub.pdf").getCanonicalPath(), Util .findFile(entry, database, root.getAbsolutePath() + "" + "[bibtexkey]-sub.pdf")); // Test ** - Find in level itself too assertEqualPaths(new File(root, "/pdfs/sub/HipKro03-sub.pdf").getCanonicalPath(), Util .findFile(entry, database, root.getAbsolutePath() + "/pdfs/sub" + "[bibtexkey]-sub.pdf")); // Test ** - Find lowest level first (Rest is Depth first) assertEqualPaths(new File(root, "/HipKro03 - Hello.pdf").getCanonicalPath(), Util.findFile( entry, database, root.getAbsolutePath() + "" + "[bibtexkey].*Hello.pdf")); } }
package jswingshell.action; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.Icon; import javax.swing.JComboBox; import javax.swing.JRadioButton; import javax.swing.JRadioButtonMenuItem; import javax.swing.event.ListDataListener; import jswingshell.IJssController; /** * A {@code AbstractJssComboAction} is a multiple choice operation that can be * called through an id and a parameter. * * <p> * This action is used to define a status or mode among multiple choice. It is * higly appropriate for {@code JComboBox} GUI components.</p> * * <p> * Note: this class has a natural ordering that is inconsistent with equals.</p> * * @author Mathieu Brunot * * @param <T> Data type of the values associated to this action. * * @since 1.2 */ public abstract class AbstractJssComboAction<T> extends AbstractJssAction implements ComboBoxModel { protected Map<T, Collection<String>> switchArgumentsByValue; protected Map<String, T> switchValuesByArgument; /** * This protected field is implementation specific. Do not access directly * or override. Use the accessor methods instead. * * @see #getModel * @see #setModel */ protected ComboBoxModel<T> dataModel; /** * The inner action group that the internal {@link ComboElementAction} * belongs to. * * @since 1.3 */ private ActionGroup innerGroup = null; /** * The internal {@link ComboElementAction} referencing combo items. * * @since 1.3 */ private Collection<ComboElementAction<T>> innerElementActions; // public AbstractJssComboAction() { this(new DefaultComboBoxModel<T>()); } public AbstractJssComboAction(T[] items) { this(new DefaultComboBoxModel<>(items)); } public AbstractJssComboAction(ComboBoxModel<T> aModel) { super(); this.setModel(aModel); } public AbstractJssComboAction(IJssController shellController) { this(new DefaultComboBoxModel<T>(), shellController); } public AbstractJssComboAction(T[] items, IJssController shellController) { this(new DefaultComboBoxModel<>(items), shellController); } public AbstractJssComboAction(ComboBoxModel<T> aModel, IJssController shellController) { super(shellController); this.setModel(aModel); } public AbstractJssComboAction(IJssController shellController, String[] args) { this(new DefaultComboBoxModel<T>(), shellController, args); } public AbstractJssComboAction(T[] items, IJssController shellController, String[] args) { this(new DefaultComboBoxModel<>(items), shellController, args); } public AbstractJssComboAction(ComboBoxModel<T> aModel, IJssController shellController, String[] args) { super(shellController, args); this.setModel(aModel); } public AbstractJssComboAction(String name, IJssController shellController, String[] args) { this(new DefaultComboBoxModel<T>(), name, shellController, args); } public AbstractJssComboAction(T[] items, String name, IJssController shellController, String[] args) { this(new DefaultComboBoxModel<>(items), name, shellController, args); } public AbstractJssComboAction(ComboBoxModel<T> aModel, String name, IJssController shellController, String[] args) { super(name, shellController, args); this.setModel(aModel); } public AbstractJssComboAction(String name, Icon icon, IJssController shellController, String[] args) { this(new DefaultComboBoxModel<T>(), name, icon, shellController, args); } public AbstractJssComboAction(T[] items, String name, Icon icon, IJssController shellController, String[] args) { this(new DefaultComboBoxModel<>(items), name, icon, shellController, args); } public AbstractJssComboAction(ComboBoxModel<T> aModel, String name, Icon icon, IJssController shellController, String[] args) { super(name, icon, shellController, args); this.setModel(aModel); } // /** * Sets the data model that a {@code JComboBox} uses to obtain the list of * items. * * @param aModel the {@code ComboBoxModel} that provides the list of items * * @beaninfo bound: true description: Model that the combo box uses to get * data to display. */ public final void setModel(ComboBoxModel<T> aModel) { this.dataModel = aModel; } /** * Returns the data model currently used by the * {@code AbstractJssComboAction}. * * @return the {@code ComboBoxModel} that provides the displayed list of * items */ public final ComboBoxModel<T> getModel() { return dataModel; } /** * Set the selected item. The implementation of this method should notify * all registered {@code ListDataListener}s that the contents * have changed. * * @param anItem the list object to select or {@code null} * to clear the selection */ @Override public void setSelectedItem(Object anItem) { dataModel.setSelectedItem(anItem); // If this is action has a default argument that corresponds to a value if (getDefaultArguments() != null && getDefaultArguments().length > 1) { String name = getDefaultArguments()[1]; if (name instanceof String) { super.putValue(SELECTED_KEY, getSwitchValuesByArgument().containsKey(name)); } } // If this action has a inner group and element actions if (innerGroup != null) { for (ComboElementAction<T> elementAction : innerElementActions) { if ((anItem == null && anItem == elementAction.dataItem) || (anItem != null && anItem.equals(elementAction.dataItem))) { innerGroup.setSelected(elementAction, true); } } } } /** * {@inheritDoc } */ @Override public Object getSelectedItem() { return dataModel.getSelectedItem(); } /** * {@inheritDoc } */ @Override public int getSize() { return dataModel.getSize(); } /** * {@inheritDoc } */ @Override public T getElementAt(int index) { return dataModel.getElementAt(index); } /** * {@inheritDoc } */ @Override public void addListDataListener(ListDataListener l) { dataModel.addListDataListener(l); } /** * {@inheritDoc } */ @Override public void removeListDataListener(ListDataListener l) { dataModel.removeListDataListener(l); } // @Override public void putValue(String key, Object newValue) { Object oldValue = getValue(key); if (oldValue == null || !oldValue.equals(newValue)) { super.putValue(key, newValue); // If this action has a default argument that corresponds to a value if (SELECTED_KEY.equals(key) && getDefaultArguments() != null && getDefaultArguments().length > 1) { String name = getDefaultArguments()[1]; Map<String, T> argumentsByValue = getSwitchValuesByArgument(); if (argumentsByValue != null && argumentsByValue.containsKey(name)) { T item = argumentsByValue.get(name); dataModel.setSelectedItem(item); // If this action has a inner group and element actions if (innerGroup != null) { for (ComboElementAction<T> elementAction : innerElementActions) { if ((item == null && item == elementAction.dataItem) || (item != null && item.equals(elementAction.dataItem))) { innerGroup.setSelected(elementAction, true); } } } } } } } // /** * Get an extensive text describing the use of this shell command in regards * to a given shell. * * @param shellController The shell controller for which we should retrieve * the action's help. This is useful for * * @return a string describing the use of this shell command. */ @Override public String getHelp(IJssController shellController) { StringBuilder stringBuilder = new StringBuilder(); String commandIdsAsString = this.getCommandIdentifiersAsString(); stringBuilder.append(this.getBriefHelp()); stringBuilder.append("\n\t").append(commandIdsAsString); stringBuilder.append("\n"); stringBuilder.append("\n").append("You can set the value as follow:"); Map<T, Collection<String>> argumentsByValue = getSwitchArgumentsByValue(); if (argumentsByValue != null) { for (Map.Entry<T, Collection<String>> entry : argumentsByValue.entrySet()) { stringBuilder.append("\n\t").append(commandIdsAsString).append(" ").append(getArgumentsAsString(entry.getValue())); } } return stringBuilder.toString(); } @Override protected String[] extractArgumentsFromEvent(ActionEvent e) { String[] eventArgs = null; if (e != null) { if (e.getSource() instanceof JComboBox) { JComboBox sourceCombo = (JComboBox) e.getSource(); String commandIdentifier = getDefaultCommandIdentifier(); Object selectedItem = sourceCombo.getSelectedItem(); eventArgs = new String[]{commandIdentifier, selectedItem != null ? selectedItem.toString() : null}; } else if (e.getSource() instanceof JRadioButton) { JRadioButton sourceRadio = (JRadioButton) e.getSource(); String commandIdentifier = getDefaultCommandIdentifier(); Object selectedItem; if (sourceRadio.getActionCommand() != null) { selectedItem = sourceRadio.getActionCommand(); } else { selectedItem = sourceRadio.getText(); } eventArgs = new String[]{commandIdentifier, selectedItem != null ? selectedItem.toString() : null}; } else if (e.getSource() instanceof JRadioButtonMenuItem) { JRadioButtonMenuItem sourceRadio = (JRadioButtonMenuItem) e.getSource(); String commandIdentifier = getDefaultCommandIdentifier(); Object selectedItem; if (sourceRadio.getActionCommand() != null) { selectedItem = sourceRadio.getActionCommand(); } else { selectedItem = sourceRadio.getText(); } eventArgs = new String[]{commandIdentifier, selectedItem != null ? selectedItem.toString() : null}; } } return eventArgs; } @Override public int run(IJssController shellController, String[] args ) { int commandReturnStatus = AbstractJssAction.SUCCESS; T switchValue = null; if (args != null && args.length > 1) { Map<String, T> argumentsByValue = getSwitchValuesByArgument(); if (args.length == 2 && args[1] != null && argumentsByValue != null) { String switchArgument = args[1].trim().toUpperCase(); switchValue = argumentsByValue.get(switchArgument); if (switchValue == null && !argumentsByValue.containsKey(switchArgument)) { shellController.publish(IJssController.PublicationLevel.WARNING, "\"" + switchArgument + "\" is not a valid value."); } } else if (shellController != null) { switchValue = null; shellController.publish(IJssController.PublicationLevel.WARNING, getHelp(shellController)); } } // Do switch if (!doSwitch(shellController, switchValue)) { commandReturnStatus = AbstractJssAction.ERROR; } else { this.setSelectedItem(switchValue); } return commandReturnStatus; } public Map<String, T> getSwitchValuesByArgument() { if (switchValuesByArgument == null) { switchValuesByArgument = constructValuesByArgument(getSwitchArgumentsByValue()); } return switchValuesByArgument; } private Map<String, T> constructValuesByArgument(Map<T, Collection<String>> argumentsByValue) { Map<String, T> valuesByArgument = new HashMap<>(); if (argumentsByValue != null) { for (Map.Entry<T, Collection<String>> entry : argumentsByValue.entrySet()) { for (String arg : entry.getValue()) { valuesByArgument.put(arg.trim().toUpperCase(), entry.getKey()); } } } return valuesByArgument; } protected Map<T, Collection<String>> getSwitchArgumentsByValue() { if (switchArgumentsByValue == null) { switchArgumentsByValue = constructArgumentsByValue(); } return switchArgumentsByValue; } /** * The actual switch operation for this action. * * @param switchValue the value for the switch. * * @return {@code true} if the switch was done. */ protected boolean doSwitch(T switchValue) { return doSwitch(getDefaultShellController(), switchValue); } /** * The actual switch operation for this action. * * @param shellController the shell controller for which to execute the * action * * @param switchValue the value for the switch. * * @return {@code true} if the switch was done. */ protected abstract boolean doSwitch(IJssController shellController, T switchValue); protected Map<T, Collection<String>> constructArgumentsByValue() { Map<T, Collection<String>> argumentsByValue = new HashMap<>(this.getSize()); for (int i = 0, n = this.getSize(); i < n; i++) { T data = this.getElementAt(i); if (data != null) { argumentsByValue.put(data, Collections.singleton(data.toString())); } else { argumentsByValue.put(data, Collections.singleton("")); } } return argumentsByValue; } // /** * The inner action group that the internal {@link ComboElementAction} * belongs to. * * @return inner action group that the internal {@link ComboElementAction} * belongs to. * * @see #getInnerElementActions() * @since 1.3 */ protected final ActionGroup getInnerGroup() { return innerGroup; } /** * The internal {@link ComboElementAction}s referencing combo items. * * <p> * Each {@code ComboElementAction} is a switch action which shall trigger * one of this combo action value. The consistency between the switch * actions and the combo selected item is managed through the an * {@link ActionGroup}.</p> * * <p> * If you need to update the model for this combo action, make sure to * reset the inner elements actions.</p> * * @return internal collection of {@link ComboElementAction}s referencing * combo items. * * @see ComboElementAction * @see #resetInnerElementActions() * @since 1.3 */ public final Collection<ComboElementAction<T>> getInnerElementActions() { if (innerElementActions == null) { innerGroup = new ActionGroup(); innerElementActions = new ArrayList<>(dataModel.getSize()); for (int i = 0, n = dataModel.getSize(); i < n; i++) { ComboElementAction<T> elementAction = this.new ComboElementAction<>(this, dataModel.getElementAt(i)); innerElementActions.add(elementAction); innerGroup.add(elementAction); } } return innerElementActions; } /** * Reset the combo elements switch action and group. * * @since 1.3 */ public final void resetInnerElementActions() { if (innerElementActions != null) { for (ComboElementAction<T> elementAction : innerElementActions) { elementAction.setSelected(false); if (elementAction.getGroup() != null && elementAction.getGroup() == innerGroup) { elementAction.getGroup().remove(elementAction); elementAction.setGroup(null); } } innerElementActions.clear(); innerElementActions = null; } if (innerGroup != null) { innerGroup.clearSelection(); innerGroup = null; } } // /** * A {@code ComboElementAction} is a switch operation (<em>on/off</em>) that * can be called through an id and a parameter, that refers to a * {@link AbstractJssComboAction} item. * * <p> * This action is used to toggle a {@link AbstractJssComboAction} item from * {@code TRUE} to {@code FALSE}. It is higly appropriate for * {@code JCheckBox} and {@code JCheckBoxMenuItem} GUI components.</p> * * <p> * Note: this class has a natural ordering that is inconsistent with * equals.</p> * * @param <T> Data type of the values associated to this action. * * @since 1.3 */ public class ComboElementAction<T> extends AbstractJssSwitchAction { private final String[] identifiers; private final String commandBriefHelp; private final AbstractJssComboAction<T> parentAction; private final T dataItem; private ComboElementAction(AbstractJssComboAction<T> parentAction, T dataItem) { super(parentAction.getSelectedItem() == dataItem, dataItem.toString(), parentAction.getDefaultShellController(), new String[]{parentAction.getDefaultCommandIdentifier(), dataItem.toString()}); this.parentAction = parentAction; this.dataItem = dataItem; // Initialize the element identifiers from the parent action and item String[] parentIdentifiers = parentAction.getCommandIdentifiers(); String[] elementIdentifiers = new String[parentIdentifiers.length]; for (int i = 0, n = parentIdentifiers.length; i < n; i++) { String parentIdentifier = parentIdentifiers[i]; elementIdentifiers[i] = parentIdentifier + "_" + dataItem.toString(); } this.identifiers = elementIdentifiers; // Initialize the element brief help from the parent action and item this.commandBriefHelp = "Set " + parentAction.getDefaultCommandIdentifier() + " to " + dataItem.toString(); this.setGroup(this.parentAction.getInnerGroup()); } @Override protected boolean doSwitch(IJssController shellController, Boolean switchValue) { boolean switchDone = false; if (switchValue) { switchDone = parentAction.doSwitch(dataItem); if (switchDone) { parentAction.setSelectedItem(dataItem); } } return switchDone; } @Override public String[] getCommandIdentifiers() { return identifiers; } @Override public String getBriefHelp() { return commandBriefHelp; } } }
package lama.tablegen.sqlite3; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import lama.Expression; import lama.Expression.Constant; import lama.Main.StateToReproduce; import lama.Randomly; import lama.schema.Schema.Column; import lama.schema.Schema.Table; import lama.sqlite3.SQLite3Visitor; public class SQLite3RowGenerator { public static void insertRow(Table table, Connection con, StateToReproduce state) throws SQLException { SQLite3RowGenerator generator = new SQLite3RowGenerator(); String query = generator.insertRow(table); try (Statement s = con.createStatement()) { state.statements.add(query); s.execute(query); } catch (SQLException e) { if (generator.mightFail && e.getMessage().startsWith("[SQLITE_CONSTRAINT]")) { return; } else if (e.getMessage().startsWith("[SQLITE_FULL]")) { return; } else if (e.getMessage().startsWith("[SQLITE_ERROR] SQL error or missing database (integer overflow)")) { return; } else if (e.getMessage().startsWith("[SQLITE_ERROR] SQL error or missing database (foreign key mismatch")) { return; } else if (e.getMessage().startsWith("[SQLITE_CONSTRAINT] Abort due to constraint violation (FOREIGN KEY constraint failed)")) { return; } else { throw new AssertionError(e); } } } private boolean mightFail; private String insertRow(Table table) { StringBuilder sb = new StringBuilder(); // TODO: see sb.append("INSERT "); if (Randomly.getBoolean()) { sb.append("OR IGNORE "); // TODO: try to generate REPLACE } else { mightFail = true; sb.append(Randomly.fromOptions("OR REPLACE ", "OR ROLLBACK ", "OR ABORT ", "OR FAIL ")); } sb.append("INTO " + table.getName()); if (Randomly.getBooleanWithSmallProbability()) { sb.append(" DEFAULT VALUES"); } else { sb.append("("); List<Column> columns = appendColumnNames(table, sb); sb.append(")"); sb.append(" VALUES "); int nrValues = 1 + Randomly.smallNumber(); appendNrValues(sb, columns, nrValues); } sb.append(";"); return sb.toString(); } private static void appendNrValues(StringBuilder sb, List<Column> columns, int nrValues) { for (int i = 0; i < nrValues; i++) { if (i != 0) { sb.append(", "); } sb.append("("); appendValue(sb, columns); sb.append(")"); } } private static void appendValue(StringBuilder sb, List<Column> columns) { for (int i = 0; i < columns.size(); i++) { if (i != 0) { sb.append(", "); } Expression literal; if (columns.get(i).isIntegerPrimaryKey()) { literal = Constant.createIntConstant(Randomly.getInteger()); } else { literal = SQLite3ExpressionGenerator.getRandomLiteralValue(false); } SQLite3Visitor visitor = new SQLite3Visitor(); visitor.visit(literal); sb.append(visitor.get()); } } private static List<Column> appendColumnNames(Table table, StringBuilder sb) { List<Column> columns = table.getColumns(); for (int i = 0; i < columns.size(); i++) { if (i != 0) { sb.append(", "); } sb.append(columns.get(i).getName()); } return columns; } }
package lbms.plugins.mldht.kad.utils; import static the8472.utils.Functional.unchecked; import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.ProtocolFamily; import java.net.SocketException; import java.net.StandardProtocolFamily; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.util.Collections; import java.util.LinkedList; import java.util.List; import lbms.plugins.mldht.kad.PeerAddressDBItem; import the8472.utils.Arrays; public class AddressUtils { public static boolean isBogon(PeerAddressDBItem item) { return isBogon(item.getInetAddress(), item.getPort()); } public static boolean isBogon(InetSocketAddress addr) { return isBogon(addr.getAddress(),addr.getPort()); } public static boolean isBogon(InetAddress addr, int port) { return !(port > 0 && port <= 0xFFFF && isGlobalUnicast(addr)); } public static boolean isGlobalUnicast(InetAddress addr) { if(addr instanceof Inet4Address && addr.getAddress()[0] == 0) return false; return !(addr.isAnyLocalAddress() || addr.isLinkLocalAddress() || addr.isLoopbackAddress() || addr.isMulticastAddress() || addr.isSiteLocalAddress()); } public static byte[] packAddress(InetSocketAddress addr) { byte[] result = null; int port = addr.getPort(); if(addr.getAddress() instanceof Inet4Address) { result = new byte[6]; } if(addr.getAddress() instanceof Inet6Address) { result = new byte[18]; } ByteBuffer buf = ByteBuffer.wrap(result); buf.put(addr.getAddress().getAddress()); buf.putChar((char)(addr.getPort() & 0xffff)); return result; } public static List<InetSocketAddress> unpackCompact(byte[] raw, Class<? extends InetAddress> type) { if(raw == null || raw.length == 0) return Collections.emptyList(); int addressSize = 0; if(type == Inet4Address.class) addressSize = 6; if(type == Inet6Address.class) addressSize = 18; if((raw.length % addressSize) != 0) throw new IllegalArgumentException("ipv4 / ipv6 compact format length must be multiple of 6 / 18 bytes"); InetSocketAddress[] addrs = new InetSocketAddress[raw.length / addressSize]; ByteBuffer buf = ByteBuffer.wrap(raw); byte[] ip = new byte[addressSize - 2]; int i = 0; while(buf.hasRemaining()) { buf.get(ip); addrs[i] = new InetSocketAddress(unchecked(() -> InetAddress.getByAddress(ip)), Short.toUnsignedInt(buf.getShort())); i++; } return java.util.Arrays.asList(addrs); } public static InetSocketAddress unpackAddress(byte[] raw) { if(raw.length != 6 && raw.length != 18) return null; ByteBuffer buf = ByteBuffer.wrap(raw); byte[] rawIP = new byte[raw.length - 2]; buf.get(rawIP); int port = buf.getChar(); InetAddress ip; try { ip = InetAddress.getByAddress(rawIP); } catch (UnknownHostException e) { return null; } return new InetSocketAddress(ip, port); } public static List<InetAddress> getAvailableGloballyRoutableAddrs(Class<? extends InetAddress> type) { LinkedList<InetAddress> addrs = new LinkedList<InetAddress>(); try { for (NetworkInterface iface : Collections.list(NetworkInterface.getNetworkInterfaces())) { if(!iface.isUp() || iface.isLoopback()) continue; for (InterfaceAddress ifaceAddr : iface.getInterfaceAddresses()) { if (type == Inet6Address.class && ifaceAddr.getAddress() instanceof Inet6Address) { Inet6Address addr = (Inet6Address) ifaceAddr.getAddress(); // only accept globally reachable IPv6 unicast addresses if (addr.isIPv4CompatibleAddress() || !isGlobalUnicast(addr)) continue; byte[] raw = addr.getAddress(); // prefer other addresses over teredo if (raw[0] == 0x20 && raw[1] == 0x01 && raw[2] == 0x00 && raw[3] == 0x00) addrs.addLast(addr); else addrs.addFirst(addr); } if(type == Inet4Address.class && ifaceAddr.getAddress() instanceof Inet4Address) { Inet4Address addr = (Inet4Address) ifaceAddr.getAddress(); if(!isGlobalUnicast(addr)) continue; addrs.add(addr); } } } } catch (Exception e) { e.printStackTrace(); } Collections.sort(addrs, (a, b) -> Arrays.compareUnsigned(a.getAddress(), b.getAddress())); return addrs; } public static boolean isValidBindAddress(InetAddress addr) { // we don't like them them but have to allow them if(addr.isAnyLocalAddress()) return true; try { NetworkInterface iface = NetworkInterface.getByInetAddress(addr); if(iface == null) return false; return iface.isUp() && !iface.isLoopback(); } catch (SocketException e) { return false; } } public static InetAddress getAnyLocalAddress(Class<? extends InetAddress> type) { try { if(type == Inet6Address.class) return InetAddress.getByAddress(new byte[16]); if(type == Inet4Address.class) return InetAddress.getByAddress(new byte[4]); } catch (UnknownHostException e) { e.printStackTrace(); } throw new RuntimeException("this shouldn't happen"); } public static InetAddress getDefaultRoute(Class<? extends InetAddress> type) { InetAddress target = null; ProtocolFamily family = type == Inet6Address.class ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET; try(DatagramChannel chan=DatagramChannel.open(family)) { if(type == Inet4Address.class) target = InetAddress.getByAddress(new byte[] {8,8,8,8}); if(type == Inet6Address.class) target = InetAddress.getByName("2001:4860:4860::8888"); chan.connect(new InetSocketAddress(target,63)); InetSocketAddress soa = (InetSocketAddress) chan.getLocalAddress(); InetAddress local = soa.getAddress(); if(type.isInstance(local) && !local.isAnyLocalAddress()) return local; return null; } catch (IOException e) { e.printStackTrace(); return null; } } }
package example.ftl; import freemarker.cache.TemplateLoader; import freemarker.log.Logger; import freemarker.template.Configuration; import freemarker.template.TemplateException; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import java.io.IOException; import java.util.List; public class HtmlFreeMarkerConfigurer extends FreeMarkerConfigurer { @Override protected TemplateLoader getAggregateTemplateLoader(List<TemplateLoader> templateLoaders) { logger.info("Using HtmlTemplateLoader to enforce HTML-safe content"); return new HtmlTemplateLoader(super.getAggregateTemplateLoader(templateLoaders)); } @Override protected void postProcessTemplateLoaders(List<TemplateLoader> templateLoaders) { // spring.ftl from classpath will not work with the HtmlTemplateLoader // use /WEB-INF/templates/spring.ftl instead } @Override protected void postProcessConfiguration(Configuration config) throws IOException, TemplateException { config.setTemplateExceptionHandler(new HtmlExceptionHandler()); } @Override public void afterPropertiesSet() throws IOException, TemplateException { configureFreemarkerLogger(); super.afterPropertiesSet(); } private void configureFreemarkerLogger() { try { Logger.selectLoggerLibrary(Logger.LIBRARY_SLF4J); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } }
package br.eb.ime.jwar.webapi; import br.eb.ime.jwar.Jogo; import br.eb.ime.jwar.models.Cor; import br.eb.ime.jwar.models.templates.RiskSecretMission; import com.corundumstudio.socketio.*; import com.corundumstudio.socketio.listener.ConnectListener; import com.corundumstudio.socketio.listener.DataListener; import com.corundumstudio.socketio.listener.DisconnectListener; import java.util.Arrays; public class ApiServer extends SocketIOServer { Jogo jogo; public ApiServer(Configuration config) { super(config); // Criar um jogo, por enquanto igual ao em Application jogo = new Jogo(Arrays.asList(Cor.AZUL, Cor.VERMELHO, Cor.AMARELO, Cor.PRETO, Cor.VERDE, Cor.BRANCO), new RiskSecretMission()); final SocketIONamespace chatServer = this.addNamespace("/chat"); chatServer.addJsonObjectListener(ChatObject.class, new DataListener<ChatObject>() { @Override public void onData(SocketIOClient client, ChatObject msg, AckRequest ackRequest) { // broadcast messages to all clients msg.type = "message"; chatServer.getBroadcastOperations().sendJsonObject(msg); } }); chatServer.addConnectListener(new ConnectListener() { @Override public void onConnect(SocketIOClient socketIOClient) { ChatObject msg = new ChatObject(); msg.message = "Alguém se conectou."; msg.type = "connect"; chatServer.getBroadcastOperations().sendJsonObject(msg); } }); chatServer.addDisconnectListener(new DisconnectListener() { @Override public void onDisconnect(SocketIOClient socketIOClient) { ChatObject msg = new ChatObject(); msg.message = "Alguém se desconectou."; msg.type = "disconnect"; chatServer.getBroadcastOperations().sendJsonObject(msg); } }); // Servidor da api em si final SocketIONamespace apiServer = this.addNamespace("/api"); apiServer.addConnectListener(new ConnectListener() { @Override public void onConnect(SocketIOClient client) { client.sendJsonObject(new StateObject(jogo, true)); } }); apiServer.addJsonObjectListener(CommandObject.class, new CommandListener(jogo, apiServer)); } public static ApiServer newConfiguredApiServer() { Configuration config = new Configuration(); //config.setHostname("localhost"); config.setPort(9092); return new ApiServer(config); } }
package com.bio4j.angulillos; import java.util.Set; /* ## Typed graphs A `TypedGraph` is, unsurprisingly, the typed version of [UntypedGraph](UntypedGraph.java.md). */ interface AnyTypedGraph { Set<AnyVertexType> vertexTypes(); Set<AnyEdgeType> edgeTypes(); } public abstract class TypedGraph< G extends TypedGraph<G,RV,RE>, RV,RE > implements AnyTypedGraph { public abstract G self(); private final UntypedGraph<RV,RE> raw; public final UntypedGraph<RV,RE> raw() { return this.raw; } protected TypedGraph(UntypedGraph<RV,RE> raw) { this.raw = raw; } /* This set will store all vertex types defined for this graph */ private final Set<AnyVertexType> vertexTypes = new java.util.HashSet<>(); public final Set<AnyVertexType> vertexTypes() { return this.vertexTypes; } /* This set will store all edge types defined for this graph */ private final Set<AnyEdgeType> edgeTypes = new java.util.HashSet<>(); public final Set<AnyEdgeType> edgeTypes() { return this.edgeTypes; } private final Set<TypedVertexIndex.Unique<?,?,?,?>> uniqueVertexIndexes = new java.util.HashSet<>(); private abstract class Element< F extends Element<F,FT, RF>, FT extends ElementType<F,FT, RF>, RF > implements TypedElement<F,FT, G,RF> { private final RF raw; private final FT type; @Override public final RF raw() { return this.raw; } @Override public final FT type() { return this.type; } // NOTE: we cannot do the same to `self`, because `super()` constructor cannot refer to `this` protected Element(RF raw, FT type) { this.raw = raw; this.type = type; } } public abstract class ElementType< F extends Element<F,FT, RF>, FT extends ElementType<F,FT, RF>, RF > implements TypedElement.Type<F,FT, G,RF> { @Override public final G graph() { return TypedGraph.this.self(); } public abstract F fromRaw(RF raw); protected abstract FT self(); /* This set stores all properties that are defined on this element type */ private final Set<AnyProperty> properties = new java.util.HashSet<>(); public final Set<AnyProperty> properties() { return this.properties; } public abstract class Property<X> implements com.bio4j.angulillos.Property<FT,X> { // NOTE: this initializer block will be inherited and will add each vertex type to the set { if ( ElementType.this.properties.removeIf( (AnyProperty p) -> p._label().equals( this._label() ) ) ) { throw new IllegalArgumentException( "Element type [" + ElementType.this._label() + "] contains duplicate property: " + this._label() ); } ElementType.this.properties.add(this); } private final Class<X> valueClass; @Override public final FT elementType() { return self(); } @Override public final Class<X> valueClass() { return this.valueClass; } protected Property(Class<X> valueClass) { this.valueClass = valueClass; } } } public abstract class Vertex< V extends Vertex<V> > extends Element<V, VertexType<V>, RV> implements TypedVertex<V, VertexType<V>, G,RV,RE> { protected Vertex(RV raw, VertexType<V> type) { super(raw, type); } } public abstract class VertexType< V extends Vertex<V> > extends ElementType<V, VertexType<V>, RV> implements TypedVertex.Type<V, VertexType<V>, G,RV,RE> { protected VertexType<V> self() { return this; } private final Set<AnyEdgeType> inEdges = new java.util.HashSet<>(); public final Set<AnyEdgeType> inEdges() { return this.inEdges; } private final Set<AnyEdgeType> outEdges = new java.util.HashSet<>(); public final Set<AnyEdgeType> outEdges() { return this.outEdges; } // NOTE: this initializer block will be inherited and will add each vertex type to the set { if ( TypedGraph.this.vertexTypes.removeIf( (AnyVertexType vt) -> vt._label().equals( self()._label() ) ) ) { throw new IllegalArgumentException("The graph contains duplicate vertex type: " + self()._label()); } TypedGraph.this.vertexTypes.add( self() ); } public abstract class UniqueIndex< P extends Property<X> & Arity.FromAtMostOne, X > implements TypedVertexIndex.Unique<V,VertexType<V>,P,X> { { if( TypedGraph.this.uniqueVertexIndexes.removeIf( vt -> vt._label().equals( _label() ) ) ) { throw new IllegalArgumentException("The graph contains a duplicate index type: " + _label()); } else { TypedGraph.this.uniqueVertexIndexes.add( this ); } } } } public abstract class Edge< S extends Vertex<S>, E extends Edge<S,E,T>, T extends Vertex<T> > extends Element<E, EdgeType<S,E,T>, RE> implements TypedEdge< S, VertexType<S>, E, EdgeType<S,E,T>, T, VertexType<T>, G,RV,RE > { protected Edge(RE raw, EdgeType<S,E,T> type) { super(raw, type); } } public abstract class EdgeType< S extends Vertex<S>, E extends Edge<S,E,T>, T extends Vertex<T> > extends ElementType<E, EdgeType<S,E,T>, RE> implements TypedEdge.Type< S, VertexType<S>, E, EdgeType<S,E,T>, T, VertexType<T>, G,RV,RE > { protected EdgeType<S,E,T> self() { return this; } private final VertexType<S> sourceType; private final VertexType<T> targetType; @Override public final VertexType<S> sourceType() { return this.sourceType; } @Override public final VertexType<T> targetType() { return this.targetType; } // NOTE: this initializer block will be inherited and will add each edge type to the set { if ( TypedGraph.this.edgeTypes.removeIf( (AnyEdgeType et) -> et._label().equals( self()._label() ) ) ) { throw new IllegalArgumentException("The graph contains duplicate edge type: " + self()._label()); } TypedGraph.this.edgeTypes.add(self()); } protected EdgeType(VertexType<S> sourceType, VertexType<T> targetType) { this.sourceType = sourceType; this.targetType = targetType; sourceType.outEdges.add( self() ); targetType.inEdges.add( self() ); } } }
package com.box.sdk; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public class BoxMultipartRequest extends BoxAPIRequest { private static final Logger LOGGER = Logger.getLogger(BoxMultipartRequest.class.getName()); private static final String BOUNDARY = "da39a3ee5e6b4b0d3255bfef95601890afd80709"; private static final int BUFFER_SIZE = 8192; private final StringBuilder loggedRequest = new StringBuilder(); private OutputStream outputStream; private InputStream inputStream; private String filename; private long fileSize; private Map<String, String> fields; private boolean firstBoundary; /** * Constructs an authenticated BoxMultipartRequest using a provided BoxAPIConnection. * @param api an API connection for authenticating the request. * @param url the URL of the request. */ public BoxMultipartRequest(BoxAPIConnection api, URL url) { super(api, url, "POST"); this.fields = new HashMap<String, String>(); this.firstBoundary = true; this.addHeader("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); } /** * Adds or updates a multipart field in this request. * @param key the field's key. * @param value the field's value. */ public void putField(String key, String value) { this.fields.put(key, value); } /** * Adds or updates a multipart field in this request. * @param key the field's key. * @param value the field's value. */ public void putField(String key, Date value) { this.fields.put(key, BoxDateFormat.format(value)); } /** * Sets the file contents of this request. * @param inputStream a stream containing the file contents. * @param filename the name of the file. */ public void setFile(InputStream inputStream, String filename) { this.inputStream = inputStream; this.filename = filename; } /** * Sets the file contents of this request. * @param inputStream a stream containing the file contents. * @param filename the name of the file. * @param fileSize the size of the file. */ public void setFile(InputStream inputStream, String filename, long fileSize) { this.setFile(inputStream, filename); this.fileSize = fileSize; } /** * Sets the SHA1 hash of the file contents of this request. * If set, it will ensure that the file is not corrupted in transit. * @param sha1 a string containing the SHA1 hash of the file contents. */ public void setContentSHA1(String sha1) { this.addHeader("Content-MD5", sha1); } /** * This method is unsupported in BoxMultipartRequest. Instead, the body should be modified via the {@code putField} * and {@code setFile} methods. * @param stream N/A * @throws UnsupportedOperationException this method is unsupported. */ @Override public void setBody(InputStream stream) { throw new UnsupportedOperationException(); } /** * This method is unsupported in BoxMultipartRequest. Instead, the body should be modified via the {@code putField} * and {@code setFile} methods. * @param body N/A * @throws UnsupportedOperationException this method is unsupported. */ @Override public void setBody(String body) { throw new UnsupportedOperationException(); } @Override protected void writeBody(HttpURLConnection connection, ProgressListener listener) { try { connection.setChunkedStreamingMode(0); connection.setDoOutput(true); this.outputStream = connection.getOutputStream(); for (Map.Entry<String, String> entry : this.fields.entrySet()) { this.writePartHeader(new String[][] {{"name", entry.getKey()}}); this.writeOutput(entry.getValue()); } this.writePartHeader(new String[][] {{"name", "file"}, {"filename", this.filename}}, "application/octet-stream"); OutputStream fileContentsOutputStream = this.outputStream; if (listener != null) { fileContentsOutputStream = new ProgressOutputStream(this.outputStream, listener, this.fileSize); } byte[] buffer = new byte[BUFFER_SIZE]; int n = this.inputStream.read(buffer); while (n != -1) { fileContentsOutputStream.write(buffer, 0, n); n = this.inputStream.read(buffer); } if (LOGGER.isLoggable(Level.FINE)) { this.loggedRequest.append("<File Contents Omitted>"); } this.writeBoundary(); } catch (IOException e) { throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); } } @Override protected void resetBody() throws IOException { this.firstBoundary = true; this.inputStream.reset(); this.loggedRequest.setLength(0); } @Override protected String bodyToString() { return this.loggedRequest.toString(); } private void writeBoundary() throws IOException { if (!this.firstBoundary) { this.writeOutput("\r\n"); } this.firstBoundary = false; this.writeOutput(" this.writeOutput(BOUNDARY); } private void writePartHeader(String[][] formData) throws IOException { this.writePartHeader(formData, null); } private void writePartHeader(String[][] formData, String contentType) throws IOException { this.writeBoundary(); this.writeOutput("\r\n"); this.writeOutput("Content-Disposition: form-data"); for (int i = 0; i < formData.length; i++) { this.writeOutput("; "); this.writeOutput(formData[i][0]); this.writeOutput("=\""); this.writeOutput(URLEncoder.encode(formData[i][1], "UTF-8")); this.writeOutput("\""); } if (contentType != null) { this.writeOutput("\r\nContent-Type: "); this.writeOutput(contentType); } this.writeOutput("\r\n\r\n"); } private void writeOutput(String s) throws IOException { this.outputStream.write(s.getBytes(StandardCharsets.UTF_8)); if (LOGGER.isLoggable(Level.FINE)) { this.loggedRequest.append(s); } } private void writeOutput(int b) throws IOException { this.outputStream.write(b); } }
package com.epictodo.model; import static org.junit.Assert.*; import java.util.*; import java.text.ParseException; public class DeadlineTask extends Task { private long endDateTime; public DeadlineTask(String taskName, String taskDescription, int priority, String ddmmyy, String time) throws Exception { super(taskName, taskDescription, priority); // This checks whether date and time entered are of correct length assert ddmmyy.length() == 6; assert time.length() == 5; setDateTime(ddmmyy, time); } public DeadlineTask(Task t, long endDateTime) throws Exception { super(t.getTaskName(), t.getTaskDescription(), t.getPriority()); this.endDateTime = endDateTime; } public long getEndDateTime() { return this.endDateTime; } // This method converts the unixTimeStamp to readable date time format public String getEndDateTimeAsString() { String dateTime = new java.text.SimpleDateFormat("ddMMyy HH:mm") .format(new java.util.Date(endDateTime * 1000)); return dateTime; } public String getDate() { String dateTime = new java.text.SimpleDateFormat("ddMMyy HH:mm") .format(new java.util.Date(endDateTime * 1000)); String date = dateTime.substring(0, 6); return date; } public String getTime() { String dateTime = new java.text.SimpleDateFormat("ddMMyy HH:mm") .format(new java.util.Date(endDateTime * 1000)); // Index 9 is the colon String timeHour = dateTime.substring(7, 9); String timeMinute = dateTime.substring(10); return timeHour + timeMinute; } public void setDateTime(String date, String time) throws Exception { // This checks whether date and time entered are of correct length assert date.length() == 6; assert time.length() == 5; if (checkTimeIsValid(time) && checkDateIsValid(date)) { String dateTimeTemp = date + " " + time; // long epoch = new // java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() // / 1000; long epoch = new java.text.SimpleDateFormat("ddMMyy HH:mm").parse( dateTimeTemp).getTime() / 1000; assert epoch != 0; endDateTime = epoch; } else { throw new Exception(); } } public String toString() { return super.toString() + " by " + this.getEndDateTimeAsString(); } public DeadlineTask copy() { Task t = super.copy(); DeadlineTask cloned = null; try { cloned = new DeadlineTask(t, getEndDateTime()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } cloned.setUid(t.getUid()); return cloned; } private boolean checkTimeIsValid(String time) { try { String regex = "[0-9]+"; String hour = time.substring(0, 2); assertTrue(hour.matches(regex)); int hourInt = Integer.parseInt(hour); assert (hourInt < 24) && (hourInt >= 00); String minute = time.substring(3, 5); assertTrue(minute.matches(regex)); int minuteInt = Integer.parseInt(minute); assert (minuteInt <= 59) && (minuteInt > 00); String colon = time.substring(2, 3); assertEquals(colon, ":"); String newTime = hour + minute; assert newTime.length() == 4; assertTrue(newTime.matches(regex)); return true; } catch (Error r) { return false; } } private boolean checkDateIsValid(String date) throws ParseException { try { assert date.length() == 6; String regex = "[0-9]+"; // Step 1: Check if date entered consists of digits assertTrue(date.matches(regex)); String month = date.substring(2, 4); int monthInt = Integer.parseInt(month); // Step 2: Check if month entered is between Jan to Dec assert (monthInt < 13) && (monthInt > 00); String day = date.substring(0, 2); int dayInt = Integer.parseInt(day); String year = date.substring(4, 6); int yearInt = Integer.parseInt(year); // We accept years from 2014 up to 2038 since unixtimestamp max is // year 2038 assert (yearInt > 13) && (yearInt < 39); String yyyy = "20" + year; int yyyyInt = Integer.parseInt(yyyy); if (isLeapYear(yyyyInt) && monthInt == 02) { // Step 3: Check if year entered is leap year and month is Feb assert (dayInt > 00) && (dayInt < 30); } else if (!isLeapYear(yyyyInt) && monthInt == 02) { // Step 4: If not leap year, check is Feb has 28 days assert (dayInt > 00) && (dayInt < 29); } else if (month.equals("01") || month.equals("03") || month.equals("05") || month.equals("07") || month.equals("08") || month.equals("10") || month.equals("12")) { // Step 5: Check months with max 31 days assert (dayInt > 00) && (dayInt < 32); } else { // Step 6: The rest of the months should have max 30 days assert (dayInt > 00) && (dayInt < 31); } // Step 7: Check whether date entered is in the future Date currDate = new Date(); Date enteredDate = new Date(yyyyInt - 1900, monthInt - 1, dayInt); assert (enteredDate.after(currDate)); return true; } catch (Error e) { return false; } } private boolean isLeapYear(int year) { return ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)); } }
package com.es.lib.common.file; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; import java.nio.file.Path; @Getter @ToString @RequiredArgsConstructor public class FileInfo { private final Path path; private final FileName fileName; private final long size; private final long crc32; private final String mime; public FileInfo(FileName fileName, long size, long crc32, String mime) { this(null, fileName, size, crc32, mime); } public FileInfo(String name, String ext, long size, long crc32, String mime) { this(null, FileName.create(name, ext), size, crc32, mime); } }
package com.fishercoder.solutions; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class _1228 { public static class Solution1 { /** * A super verbose and inefficient but working way... */ public int missingNumber(int[] arr) { Arrays.sort(arr); Map<Integer, List<Integer>> map = new HashMap<>(); for (int i = 0; i < arr.length - 1; i++) { int diff = arr[i + 1] - arr[i]; List<Integer> list = map.getOrDefault(diff, new ArrayList<>()); list.add(i); map.put(diff, list); } int smallDiff = arr[arr.length - 1]; int bigDiff = 0; for (int key : map.keySet()) { smallDiff = Math.min(smallDiff, key); bigDiff = Math.max(bigDiff, key); } return arr[map.get(bigDiff).get(0)] + smallDiff; } } public static class Solution2 { public int missingNumber(int[] arr) { int min = arr[0]; int max = arr[0]; int sum = 0; for (int num : arr) { max = Math.max(max, num); min = Math.min(min, num); sum += num; } return (max + min) * (arr.length + 1) / 2 - sum; } } }
package com.gamingmesh.jobs.dao; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.entity.Player; import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.container.ArchivedJobs; import com.gamingmesh.jobs.container.BlockProtection; import com.gamingmesh.jobs.container.Convert; import com.gamingmesh.jobs.container.CurrencyType; import com.gamingmesh.jobs.container.DBAction; import com.gamingmesh.jobs.container.ExploreChunk; import com.gamingmesh.jobs.container.ExploreRegion; import com.gamingmesh.jobs.container.Job; import com.gamingmesh.jobs.container.JobProgression; import com.gamingmesh.jobs.container.JobsPlayer; import com.gamingmesh.jobs.container.Log; import com.gamingmesh.jobs.container.LogAmounts; import com.gamingmesh.jobs.container.PlayerInfo; import com.gamingmesh.jobs.container.PlayerPoints; import com.gamingmesh.jobs.container.TopList; import com.gamingmesh.jobs.dao.JobsManager.DataBaseType; import com.gamingmesh.jobs.economy.PaymentData; import com.gamingmesh.jobs.stuff.TimeManage; public abstract class JobsDAO { private JobsConnectionPool pool; private static String prefix; private Jobs plugin; private static DataBaseType dbType = DataBaseType.SqLite; // Not in use currently public enum TablesFieldsType { decimal, number, text, varchar, stringList, stringLongMap, stringIntMap, locationMap, state, location, longNumber; } public enum UserTableFields implements JobsTableInterface { player_uuid("varchar(36)", TablesFieldsType.varchar), username("text", TablesFieldsType.text), seen("bigint", TablesFieldsType.longNumber), donequests("int", TablesFieldsType.number), quests("text", TablesFieldsType.text); private String type; private TablesFieldsType fieldType; UserTableFields(String type, TablesFieldsType fieldType) { this.type = type; this.fieldType = fieldType; } @Override public String getCollumn() { return this.name(); } @Override public String getType() { return type; } @Override public TablesFieldsType getFieldType() { return fieldType; } } public enum JobsTableFields implements JobsTableInterface { userid("int", TablesFieldsType.number), job("text", TablesFieldsType.text), experience("int", TablesFieldsType.number), level("int", TablesFieldsType.number); private String type; private TablesFieldsType fieldType; JobsTableFields(String type, TablesFieldsType fieldType) { this.type = type; this.fieldType = fieldType; } @Override public String getCollumn() { return this.name(); } @Override public String getType() { return type; } @Override public TablesFieldsType getFieldType() { return fieldType; } } public enum ArchiveTableFields implements JobsTableInterface { userid("int", TablesFieldsType.number), job("text", TablesFieldsType.text), experience("int", TablesFieldsType.number), level("int", TablesFieldsType.number), left("bigint", TablesFieldsType.longNumber); private String type; private TablesFieldsType fieldType; ArchiveTableFields(String type, TablesFieldsType fieldType) { this.type = type; this.fieldType = fieldType; } @Override public String getCollumn() { return this.name(); } @Override public String getType() { return type; } @Override public TablesFieldsType getFieldType() { return fieldType; } } public enum BlockTableFields implements JobsTableInterface { world("varchar(36)", TablesFieldsType.varchar), x("int", TablesFieldsType.number), y("int", TablesFieldsType.number), z("int", TablesFieldsType.number), recorded("bigint", TablesFieldsType.longNumber), resets("bigint", TablesFieldsType.longNumber); private String type; private TablesFieldsType fieldType; BlockTableFields(String type, TablesFieldsType fieldType) { this.type = type; this.fieldType = fieldType; } @Override public String getCollumn() { return this.name(); } @Override public String getType() { return type; } @Override public TablesFieldsType getFieldType() { return fieldType; } } public enum LimitTableFields implements JobsTableInterface { userid("int", TablesFieldsType.number), type("varchar(36)", TablesFieldsType.number), collected("double", TablesFieldsType.decimal), started("bigint", TablesFieldsType.longNumber); private String ttype; private TablesFieldsType fieldType; LimitTableFields(String type, TablesFieldsType fieldType) { this.ttype = type; this.fieldType = fieldType; } @Override public String getCollumn() { return this.name(); } @Override public String getType() { return ttype; } @Override public TablesFieldsType getFieldType() { return fieldType; } } public enum LogTableFields implements JobsTableInterface { userid("int", TablesFieldsType.number), time("bigint", TablesFieldsType.longNumber), action("varchar(20)", TablesFieldsType.varchar), itemname("text", TablesFieldsType.text), count("int", TablesFieldsType.number), money("double", TablesFieldsType.decimal), exp("double", TablesFieldsType.decimal), points("double", TablesFieldsType.decimal); private String type; private TablesFieldsType fieldType; LogTableFields(String type, TablesFieldsType fieldType) { this.type = type; this.fieldType = fieldType; } @Override public String getCollumn() { return this.name(); } @Override public String getType() { return type; } @Override public TablesFieldsType getFieldType() { return fieldType; } } public enum PointsTableFields implements JobsTableInterface { userid("int", TablesFieldsType.number), totalpoints("double", TablesFieldsType.decimal), currentpoints("double", TablesFieldsType.decimal); private String type; private TablesFieldsType fieldType; PointsTableFields(String type, TablesFieldsType fieldType) { this.type = type; this.fieldType = fieldType; } @Override public String getCollumn() { return this.name(); } @Override public String getType() { return type; } @Override public TablesFieldsType getFieldType() { return fieldType; } } public enum ExploreDataTableFields implements JobsTableInterface { worldname("varchar(64)", TablesFieldsType.varchar), chunkX("int", TablesFieldsType.number), chunkZ("int", TablesFieldsType.number), playerNames("text", TablesFieldsType.text); private String type; private TablesFieldsType fieldType; ExploreDataTableFields(String type, TablesFieldsType fieldType) { this.type = type; this.fieldType = fieldType; } @Override public String getCollumn() { return this.name(); } @Override public String getType() { return type; } @Override public TablesFieldsType getFieldType() { return fieldType; } } public enum DBTables { UsersTable("users", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", UserTableFields.class), JobsTable("jobs", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", JobsTableFields.class), ArchiveTable("archive", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", ArchiveTableFields.class), BlocksTable("blocks", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", BlockTableFields.class), LimitsTable("limits", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", LimitTableFields.class), LogTable("log", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", LogTableFields.class), ExploreDataTable("exploreData", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", ExploreDataTableFields.class), PointsTable("points", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", PointsTableFields.class); private String mySQL; private String sQlite; private String tableName; private JobsTableInterface[] c; DBTables(String tableName, String MySQL, String SQlite, Class<?> cc) { this.tableName = tableName; this.mySQL = MySQL; this.sQlite = SQlite; this.c = (JobsTableInterface[]) cc.getEnumConstants(); } private String getQR() { switch (dbType) { case MySQL: return this.mySQL.replace("[tableName]", prefix + this.tableName); case SqLite: return this.sQlite.replace("[tableName]", this.tableName); } return ""; } public String getQuery() { String rp = ""; for (JobsTableInterface one : this.getInterface()) { rp += ", " + "`" + one.getCollumn() + "` " + one.getType(); } return getQR().replace("[fields]", rp); } public JobsTableInterface[] getInterface() { return this.c; } public String getTableName() { return prefix + tableName; } } protected JobsDAO(Jobs plugin, String driverName, String url, String username, String password, String pr) { this.plugin = plugin; prefix = pr; try { pool = new JobsConnectionPool(driverName, url, username, password); } catch (Exception e) { e.printStackTrace(); } } public final synchronized void setUp() throws SQLException { setupConfig(); if (getConnection() == null) return; try { for (DBTables one : DBTables.values()) { createDefaultTable(one); } checkDefaultCollumns(); } finally { } } protected abstract void setupConfig() throws SQLException; protected abstract void checkUpdate() throws SQLException; public abstract Statement prepareStatement(String query) throws SQLException; public abstract boolean createTable(String query) throws SQLException; public abstract boolean isTable(String table); public abstract boolean isCollumn(String table, String collumn); public abstract boolean truncate(String table); public abstract boolean addCollumn(String table, String collumn, String type); public abstract boolean drop(String table); public boolean isConnected() { try { return pool != null && pool.getConnection() != null && !pool.getConnection().isClosed(); } catch (SQLException e) { return false; } } public void setAutoCommit(boolean state) { JobsConnection conn = getConnection(); if (conn == null) return; try { conn.setAutoCommit(state); } catch (SQLException e) { e.printStackTrace(); } } public void commit() { JobsConnection conn = getConnection(); if (conn == null) return; try { conn.commit(); } catch (SQLException e) { e.printStackTrace(); } } private boolean createDefaultTable(DBTables table) { if (this.isTable(table.getTableName())) return true; try { this.createTable(table.getQuery()); return true; } catch (SQLException e) { e.printStackTrace(); } return false; } private boolean checkDefaultCollumns() { for (DBTables one : DBTables.values()) { for (JobsTableInterface oneT : one.getInterface()) { if (this.isCollumn(one.getTableName(), oneT.getCollumn())) continue; this.addCollumn(one.getTableName(), oneT.getCollumn(), oneT.getType()); } } return true; } public void truncateAllTables() { for (DBTables one : DBTables.values()) { this.truncate(one.getTableName()); } } public DataBaseType getDbType() { return dbType; } public void setDbType(DataBaseType dabType) { dbType = dabType; } /** * Gets the database prefix * @return the prefix */ protected String getPrefix() { return prefix; } public List<JobsDAOData> getAllJobs(OfflinePlayer player) { return getAllJobs(player.getName(), player.getUniqueId()); } /** * Get all jobs the player is part of. * @param playerUUID - the player being searched for * @return list of all of the names of the jobs the players are part of. */ public List<JobsDAOData> getAllJobs(String playerName, UUID uuid) { int id = -1; PlayerInfo userData = null; if (Jobs.getGCManager().MultiServerCompatability()) userData = loadPlayerData(uuid); else userData = Jobs.getPlayerManager().getPlayerInfo(uuid); ArrayList<JobsDAOData> jobs = new ArrayList<>(); if (userData == null) { recordNewPlayer(playerName, uuid); return jobs; } id = userData.getID(); JobsConnection conn = getConnection(); if (conn == null) return jobs; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT `job`, `level`, `experience` FROM `" + prefix + "jobs` WHERE `userid` = ?;"); prest.setInt(1, id); res = prest.executeQuery(); while (res.next()) { jobs.add(new JobsDAOData(res.getString("job"), res.getInt("level"), res.getInt("experience"))); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return jobs; } public HashMap<Integer, List<JobsDAOData>> getAllJobs() { HashMap<Integer, List<JobsDAOData>> map = new HashMap<>(); JobsConnection conn = getConnection(); if (conn == null) return map; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + prefix + "jobs`;"); res = prest.executeQuery(); while (res.next()) { int id = res.getInt("userid"); List<JobsDAOData> ls = map.get(id); if (ls == null) ls = new ArrayList<>(); ls.add(new JobsDAOData(res.getString("job"), res.getInt("level"), res.getInt("experience"))); map.put(id, ls); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return map; } public HashMap<Integer, PlayerPoints> getAllPoints() { HashMap<Integer, PlayerPoints> map = new HashMap<>(); JobsConnection conn = getConnection(); if (conn == null) return map; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + prefix + "points`;"); res = prest.executeQuery(); while (res.next()) { map.put(res.getInt(PointsTableFields.userid.getCollumn()), new PlayerPoints(res.getDouble("currentpoints"), res.getDouble("totalpoints"))); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return map; } public HashMap<Integer, ArchivedJobs> getAllArchivedJobs() { HashMap<Integer, ArchivedJobs> map = new HashMap<>(); JobsConnection conn = getConnection(); if (conn == null) return map; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + prefix + "archive`;"); res = prest.executeQuery(); while (res.next()) { int id = res.getInt("userid"); String jobName = res.getString("job"); Double exp = res.getDouble("experience"); int lvl = res.getInt("level"); Long left = res.getLong("left"); Job job = Jobs.getJob(jobName); if (job == null) continue; ArchivedJobs m = map.get(id); if (m == null) m = new ArchivedJobs(); JobProgression jp = new JobProgression(job, null, lvl, exp); if (left != 0L) jp.setLeftOn(left); m.addArchivedJob(jp); map.put(id, m); } } catch (Exception e) { close(res); close(prest); } finally { close(res); close(prest); } return map; } public HashMap<Integer, HashMap<String, Log>> getAllLogs() { HashMap<Integer, HashMap<String, Log>> map = new HashMap<>(); JobsConnection conn = getConnection(); if (conn == null) return map; PreparedStatement prest = null; ResultSet res = null; try { int time = TimeManage.timeInInt(); prest = conn.prepareStatement("SELECT * FROM `" + prefix + "log` WHERE `time` = ? ;"); prest.setInt(1, time); res = prest.executeQuery(); while (res.next()) { int id = res.getInt("userid"); HashMap<String, Log> m = map.get(id); if (m == null) m = new HashMap<>(); String action = res.getString("action"); Log log = m.get(action); if (log == null) log = new Log(action); HashMap<CurrencyType, Double> amounts = new HashMap<>(); amounts.put(CurrencyType.MONEY, res.getDouble("money")); amounts.put(CurrencyType.EXP, res.getDouble("exp")); amounts.put(CurrencyType.POINTS, res.getDouble("points")); log.add(res.getString("itemname"), res.getInt("count"), amounts); m.put(action, log); map.put(id, m); // Jobs.getLoging().loadToLog(player, res.getString("action"), res.getString("itemname"), res.getInt("count"), res.getDouble("money"), res.getDouble("exp")); } } catch (Exception e) { close(res); close(prest); } finally { close(res); close(prest); } return map; } private HashMap<Integer, ArrayList<JobsDAOData>> map = new HashMap<>(); public List<JobsDAOData> getAllJobs(PlayerInfo pInfo) { List<JobsDAOData> list = map.get(pInfo.getID()); if (list != null) return list; return new ArrayList<JobsDAOData>(); } public void cleanUsers() { if (!Jobs.getGCManager().DBCleaningUsersUse) return; JobsConnection conn = getConnection(); if (conn == null) return; long mark = System.currentTimeMillis() - (Jobs.getGCManager().DBCleaningUsersDays * 24 * 60 * 60 * 1000); PreparedStatement prest = null; try { prest = conn.prepareStatement("DELETE FROM `" + prefix + "users` WHERE `seen` < ?;"); prest.setLong(1, mark); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } public void cleanJobs() { if (!Jobs.getGCManager().DBCleaningJobsUse) return; JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { prest = conn.prepareStatement("DELETE FROM `" + prefix + "jobs` WHERE `level` <= ?;"); prest.setInt(1, Jobs.getGCManager().DBCleaningJobsLvl); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } public void recordNewPlayer(Player player) { recordNewPlayer((OfflinePlayer) player); } public void recordNewPlayer(OfflinePlayer player) { recordNewPlayer(player.getName(), player.getUniqueId()); } public void recordNewPlayer(String playerName, UUID uuid) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prestt = null; ResultSet res2 = null; try { prestt = conn.prepareStatement("INSERT INTO `" + prefix + "users` (`player_uuid`, `username`, `seen`, `donequests`) VALUES (?, ?, ?, ?);", Statement.RETURN_GENERATED_KEYS); prestt.setString(1, uuid.toString()); prestt.setString(2, playerName); prestt.setLong(3, System.currentTimeMillis()); prestt.setInt(4, 0); prestt.executeUpdate(); res2 = prestt.getGeneratedKeys(); int id = 0; if (res2.next()) id = res2.getInt(1); Jobs.getPlayerManager().addPlayerToMap(new PlayerInfo(playerName, id, uuid, System.currentTimeMillis(), 0)); } catch (SQLException e) { e.printStackTrace(); } finally { close(prestt); close(res2); } } /** * Get player count for a job. * @param JobName - the job name * @return amount of player currently working. */ public synchronized int getTotalPlayerAmountByJobName(String JobName) { JobsConnection conn = getConnection(); if (conn == null) return 0; int count = 0; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT COUNT(*) FROM `" + prefix + "jobs` WHERE `job` = ?;"); prest.setString(1, JobName); res = prest.executeQuery(); while (res.next()) { count = res.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return count; } /** * Get player count for a job. * @return total amount of player currently working. */ public synchronized int getTotalPlayers() { int total = 0; for (Job one : Jobs.getJobs()) { total += one.getTotalPlayers(); } return total; } /** * Get all jobs the player is part of. * @param userName - the player being searched for * @return list of all of the names of the jobs the players are part of. */ public synchronized List<JobsDAOData> getAllJobsOffline(String userName) { ArrayList<JobsDAOData> jobs = new ArrayList<>(); PlayerInfo info = Jobs.getPlayerManager().getPlayerInfo(userName); if (info == null) return jobs; JobsConnection conn = getConnection(); if (conn == null) return jobs; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT `job`, `level`, `experience` FROM `" + prefix + "jobs` WHERE `userid` = ?;"); prest.setInt(1, info.getID()); res = prest.executeQuery(); while (res.next()) { jobs.add(new JobsDAOData(res.getString(2), res.getInt(3), res.getInt(4))); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return jobs; } public synchronized void recordPlayersLimits(JobsPlayer jPlayer) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest2 = null; try { prest2 = conn.prepareStatement("DELETE FROM `" + prefix + "limits` WHERE `userid` = ?;"); prest2.setInt(1, jPlayer.getUserId()); prest2.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest2); } PreparedStatement prest = null; try { PaymentData limit = jPlayer.getPaymentLimit(); prest = conn.prepareStatement("INSERT INTO `" + prefix + "limits` (`userid`, `type`, `collected`, `started`) VALUES (?, ?, ?, ?);"); conn.setAutoCommit(false); for (CurrencyType type : CurrencyType.values()) { if (limit == null) continue; if (limit.GetAmount(type) == 0D) continue; if (limit.GetLeftTime(type) < 0) continue; prest.setInt(1, jPlayer.getUserId()); prest.setString(2, type.getName()); prest.setDouble(3, limit.GetAmount(type)); prest.setLong(4, limit.GetTime(type)); prest.addBatch(); } prest.executeBatch(); conn.commit(); } catch (Exception e) { e.printStackTrace(); } finally { close(prest); try { conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } } public synchronized PaymentData getPlayersLimits(JobsPlayer jPlayer) { PaymentData data = new PaymentData(); JobsConnection conn = getConnection(); if (conn == null) return data; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT `type`, `collected`, `started` FROM `" + prefix + "limits` WHERE `userid` = ?;"); prest.setInt(1, jPlayer.getUserId()); res = prest.executeQuery(); while (res.next()) { CurrencyType type = CurrencyType.getByName(res.getString("type")); if (type == null) continue; data.AddNewAmount(type, res.getDouble("collected"), res.getLong("started")); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return data; } public synchronized HashMap<Integer, PaymentData> loadPlayerLimits() { HashMap<Integer, PaymentData> map = new HashMap<>(); JobsConnection conn = getConnection(); if (conn == null) return map; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + prefix + "limits`;"); res = prest.executeQuery(); while (res.next()) { int id = res.getInt(LimitTableFields.userid.getCollumn()); PaymentData data = map.get(id); if (data == null) data = new PaymentData(); CurrencyType type = CurrencyType.getByName(res.getString("type")); if (type == null) continue; data.AddNewAmount(type, res.getDouble("collected"), res.getLong("started")); map.put(id, data); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return map; } /** * Join a job (create player-job entry from storage) * @param player - player that wishes to join the job * @param job - job that the player wishes to join */ public synchronized void joinJob(JobsPlayer jPlayer, JobProgression job) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { int level = job.getLevel(); Double exp = job.getExperience(); prest = conn.prepareStatement("INSERT INTO `" + prefix + "jobs` (`userid`, `job`, `level`, `experience`) VALUES (?, ?, ?, ?);"); prest.setInt(1, jPlayer.getUserId()); prest.setString(2, job.getJob().getName()); prest.setInt(3, level); prest.setInt(4, exp.intValue()); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } /** * Join a job (create player-job entry from storage) * @param player - player that wishes to join the job * @param job - job that the player wishes to join */ public synchronized void insertJob(JobsPlayer jPlayer, JobProgression prog) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { int exp = (int) prog.getExperience(); if (exp < 0) exp = 0; prest = conn.prepareStatement("INSERT INTO `" + prefix + "jobs` (`userid`, `job`, `level`, `experience`) VALUES (?, ?, ?, ?);"); prest.setInt(1, jPlayer.getUserId()); prest.setString(2, prog.getJob().getName()); prest.setInt(3, prog.getLevel()); prest.setInt(4, exp); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } /** * Join a job (create player-job entry from storage) * @param player - player that wishes to join the job * @param job - job that the player wishes to join * @throws SQLException */ public List<Convert> convertDatabase(String table) throws SQLException { JobsConnection conn = getConnection(); if (conn == null) return null; List<Convert> list = new ArrayList<>(); PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + prefix + table + "`"); res = prest.executeQuery(); while (res.next()) { int id = res.getInt("userid"); PlayerInfo pi = Jobs.getPlayerManager().getPlayerInfo(id); if (pi == null) continue; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(pi.getUuid()); if (jPlayer == null) continue; list.add(new Convert(res.getInt("id"), jPlayer.getPlayerUUID(), res.getString("job"), res.getInt("level"), res.getInt("experience"))); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } try { conn.closeConnection(); } catch (SQLException e) { e.printStackTrace(); } return list; } public void continueConvertions(List<Convert> list, String table) throws SQLException { JobsConnection conns = this.getConnection(); if (conns == null) return; PreparedStatement insert = null; Statement statement = null; int i = list.size(); try { statement = conns.createStatement(); if (Jobs.getDBManager().getDbType().toString().equalsIgnoreCase("mysql")) { statement.executeUpdate("TRUNCATE TABLE `" + getPrefix() + table + "`"); } else { statement.executeUpdate("DELETE from `" + getPrefix() + table + "`"); } insert = conns.prepareStatement("INSERT INTO `" + getPrefix() + table + "` (`userid`, `job`, `level`, `experience`) VALUES (?, ?, ?, ?);"); conns.setAutoCommit(false); while (i > 0) { i Convert convertData = list.get(i); JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(convertData.GetUserUUID()); if (jPlayer == null) continue; insert.setInt(1, jPlayer.getUserId()); insert.setString(2, convertData.GetJobName()); insert.setInt(3, convertData.GetLevel()); insert.setInt(4, convertData.GetExp()); insert.addBatch(); } insert.executeBatch(); conns.commit(); conns.setAutoCommit(true); } finally { close(statement); close(insert); try { conns.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } } /** * Quit a job (delete player-job entry from storage) * @param player - player that wishes to quit the job * @param job - job that the player wishes to quit */ public synchronized boolean quitJob(JobsPlayer jPlayer, Job job) { JobsConnection conn = getConnection(); if (conn == null) return false; PreparedStatement prest = null; boolean ok = true; try { prest = conn.prepareStatement("DELETE FROM `" + prefix + "jobs` WHERE `userid` = ? AND `job` = ?;"); prest.setInt(1, jPlayer.getUserId()); prest.setString(2, job.getName()); prest.execute(); } catch (SQLException e) { e.printStackTrace(); ok = false; } finally { close(prest); } return ok; } /** * Record job to archive * @param player - player that wishes to quit the job * @param job - job that the player wishes to quit */ public void recordToArchive(JobsPlayer jPlayer, Job job) { JobProgression jp = jPlayer.getJobProgression(job); if (jp == null) return; jp.setLeftOn(System.currentTimeMillis()); jPlayer.getArchivedJobs().addArchivedJob(jp); JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { int level = jp.getLevel(); Double exp = jp.getExperience(); prest = conn.prepareStatement("INSERT INTO `" + prefix + "archive` (`userid`, `job`, `level`, `experience`, `left`) VALUES (?, ?, ?, ?, ?);"); prest.setInt(1, jPlayer.getUserId()); prest.setString(2, job.getName()); prest.setInt(3, level); prest.setInt(4, exp.intValue()); prest.setLong(5, System.currentTimeMillis()); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } public List<TopList> getGlobalTopList() { return getGlobalTopList(0); } /** * Get all jobs from archive by player * @param player - targeted player * @return info - information about jobs */ public List<TopList> getGlobalTopList(int start) { JobsConnection conn = getConnection(); List<TopList> names = new ArrayList<>(); if (conn == null) return names; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT userid, COUNT(*) AS amount, sum(level) AS totallvl FROM `" + prefix + "jobs` GROUP BY userid ORDER BY totallvl DESC LIMIT " + start + ",100;"); res = prest.executeQuery(); while (res.next()) { PlayerInfo info = Jobs.getPlayerManager().getPlayerInfo(res.getInt("userid")); if (info == null) continue; if (info.getName() == null) continue; TopList top = new TopList(info, res.getInt("totallvl"), 0); names.add(top); if (names.size() >= Jobs.getGCManager().JobsTopAmount) break; } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return names; } public PlayerInfo loadPlayerData(UUID uuid) { PlayerInfo pInfo = null; JobsConnection conn = getConnection(); if (conn == null) return pInfo; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + prefix + "users` WHERE `player_uuid` = ?;"); prest.setString(1, uuid.toString()); res = prest.executeQuery(); while (res.next()) { pInfo = new PlayerInfo( res.getString("username"), res.getInt("id"), uuid, res.getLong("seen"), res.getInt("donequests"), res.getString("quests")); Jobs.getPlayerManager().addPlayerToMap(pInfo); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return pInfo; } public void loadPlayerData() { Jobs.getPlayerManager().clearMaps(); JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + prefix + "users`;"); res = prest.executeQuery(); while (res.next()) { long seen = System.currentTimeMillis(); try { seen = res.getLong("seen"); Jobs.getPlayerManager().addPlayerToMap(new PlayerInfo( res.getString("username"), res.getInt("id"), UUID.fromString(res.getString("player_uuid")), seen, res.getInt("donequests"), res.getString("quests"))); } catch (Exception e) { } } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return; } public JobsPlayer loadFromDao(OfflinePlayer player) { JobsPlayer jPlayer = new JobsPlayer(player.getName()); jPlayer.setPlayerUUID(player.getUniqueId()); List<JobsDAOData> list = getAllJobs(player); // synchronized (jPlayer.saveLock) { jPlayer.progression.clear(); for (JobsDAOData jobdata : list) { if (!plugin.isEnabled()) return null; // add the job Job job = Jobs.getJob(jobdata.getJobName()); if (job == null) continue; // create the progression object JobProgression jobProgression = new JobProgression(job, jPlayer, jobdata.getLevel(), jobdata.getExperience()); // calculate the max level // add the progression level. jPlayer.progression.add(jobProgression); } jPlayer.reloadMaxExperience(); jPlayer.reloadLimits(); jPlayer.setUserId(Jobs.getPlayerManager().getPlayerId(player.getUniqueId())); loadPoints(jPlayer); return jPlayer; } // public void loadAllData() { // Jobs.getPlayerManager().clearMaps(); // JobsConnection conn = getConnection(); // if (conn == null) // return; // PreparedStatement prest = null; // ResultSet res = null; // try { // prest = conn.prepareStatement("SELECT * FROM `" + prefix + "users`;"); // res = prest.executeQuery(); // while (res.next()) { // try { // Jobs.getPlayerManager().addPlayerToMap(new PlayerInfo( // res.getString("username"), // res.getInt("id"), // UUID.fromString(res.getString("player_uuid")), // res.getLong("seen"), // res.getInt("donequests"), // res.getString("quests"))); // } catch (Exception e) { // } catch (SQLException e) { // e.printStackTrace(); // } finally { // close(res); // close(prest); // return; /** * Delete job from archive * @param player - player that wishes to quit the job * @param job - job that the player wishes to quit */ public synchronized void deleteArchive(JobsPlayer jPlayer, Job job) { jPlayer.getArchivedJobs().removeArchivedJob(job); JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { prest = conn.prepareStatement("DELETE FROM `" + prefix + "archive` WHERE `userid` = ? AND `job` = ?;"); prest.setInt(1, jPlayer.getUserId()); prest.setString(2, job.getName()); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } /** * Save player-job information * @param jobInfo - the information getting saved */ public void save(JobsPlayer player) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { prest = conn.prepareStatement("UPDATE `" + prefix + "jobs` SET `level` = ?, `experience` = ? WHERE `userid` = ? AND `job` = ?;"); for (JobProgression progression : player.getJobProgression()) { prest.setInt(1, progression.getLevel()); prest.setInt(2, (int) progression.getExperience()); prest.setInt(3, player.getUserId()); prest.setString(4, progression.getJob().getName()); prest.execute(); } } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } public void updateSeen(JobsPlayer player) { if (player.getUserId() == -1) { insertPlayer(player); return; } JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { prest = conn.prepareStatement("UPDATE `" + prefix + "users` SET `seen` = ?, `username` = ?, `donequests` = ?, `quests` = ? WHERE `id` = ?;"); prest.setLong(1, System.currentTimeMillis()); prest.setString(2, player.getUserName()); prest.setInt(3, player.getDoneQuests()); prest.setString(4, player.getQuestProgressionString()); prest.setInt(5, player.getUserId()); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } private void insertPlayer(JobsPlayer player) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prestt = null; try { prestt = conn.prepareStatement("INSERT INTO `" + prefix + "users` (`player_uuid`, `username`, `seen`, `donequests`) VALUES (?, ?, ?, ?);"); prestt.setString(1, player.getPlayerUUID().toString()); prestt.setString(2, player.getUserName()); prestt.setLong(3, player.getSeen()); prestt.setInt(4, 0); prestt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prestt); } PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT `id`,`donequests` FROM `" + prefix + "users` WHERE `player_uuid` = ?;"); prest.setString(1, player.getPlayerUUID().toString()); res = prest.executeQuery(); res.next(); int id = res.getInt("id"); player.setUserId(id); Jobs.getPlayerManager().addPlayerToMap(new PlayerInfo( player.getUserName(), id, player.getPlayerUUID(), player.getSeen(), res.getInt("donequests"))); } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } } public void savePoints(JobsPlayer jPlayer) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest2 = null; try { prest2 = conn.prepareStatement("DELETE FROM `" + prefix + "points` WHERE `userid` = ?;"); prest2.setInt(1, jPlayer.getUserId()); prest2.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest2); } PreparedStatement prest = null; try { PlayerPoints pointInfo = Jobs.getPointsData().getPlayerPointsInfo(jPlayer.getPlayerUUID()); prest = conn.prepareStatement("INSERT INTO `" + prefix + "points` (`totalpoints`, `currentpoints`, `userid`) VALUES (?, ?, ?);"); prest.setDouble(1, pointInfo.getTotalPoints()); prest.setDouble(2, pointInfo.getCurrentPoints()); prest.setInt(3, jPlayer.getUserId()); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } public void loadPoints(JobsPlayer player) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT `totalpoints`, `currentpoints` FROM `" + prefix + "points` WHERE `userid` = ?;"); prest.setInt(1, player.getUserId()); res = prest.executeQuery(); if (res.next()) { Jobs.getPointsData().addPlayer(player.getPlayerUUID(), res.getDouble("currentpoints"), res.getDouble("totalpoints")); } else { Jobs.getPointsData().addPlayer(player.getPlayerUUID()); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } } /** * Save player-job information * @param jobInfo - the information getting saved */ public void saveLog(JobsPlayer player) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest1 = null; PreparedStatement prest2 = null; try { conn.setAutoCommit(false); prest1 = conn.prepareStatement("UPDATE `" + prefix + "log` SET `count` = ?, `money` = ?, `exp` = ?, `points` = ? WHERE `userid` = ? AND `time` = ? AND `action` = ? AND `itemname` = ?;"); boolean added = false; for (Entry<String, Log> l : player.getLog().entrySet()) { Log log = l.getValue(); for (Entry<String, LogAmounts> one : log.getAmountList().entrySet()) { if (one.getValue().isNewEntry()) continue; prest1.setInt(1, one.getValue().getCount()); prest1.setDouble(2, one.getValue().get(CurrencyType.MONEY)); prest1.setDouble(3, one.getValue().get(CurrencyType.EXP)); prest1.setDouble(4, one.getValue().get(CurrencyType.POINTS)); prest1.setInt(5, player.getUserId()); prest1.setInt(6, log.getDate()); prest1.setString(7, log.getActionType()); prest1.setString(8, one.getKey()); // prest1.addBatch(); added = true; } } if (added) { prest1.execute(); conn.commit(); } added = false; prest2 = conn.prepareStatement("INSERT INTO `" + prefix + "log` (`userid`, `time`, `action`, `itemname`, `count`, `money`, `exp`, `points`) VALUES (?, ?, ?, ?, ?, ?, ?, ?);"); for (Entry<String, Log> l : player.getLog().entrySet()) { Log log = l.getValue(); for (Entry<String, LogAmounts> one : log.getAmountList().entrySet()) { if (!one.getValue().isNewEntry()) continue; one.getValue().setNewEntry(false); prest2.setInt(1, player.getUserId()); prest2.setInt(2, log.getDate()); prest2.setString(3, log.getActionType()); prest2.setString(4, one.getKey()); prest2.setInt(5, one.getValue().getCount()); prest2.setDouble(6, one.getValue().get(CurrencyType.MONEY)); prest2.setDouble(7, one.getValue().get(CurrencyType.EXP)); prest2.setDouble(8, one.getValue().get(CurrencyType.POINTS)); // prest2.addBatch(); added = true; } } if (added) { prest2.execute(); conn.commit(); } conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); close(prest1); close(prest2); } finally { close(prest1); close(prest2); try { conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } } /** * Save player-job information * @param jobInfo - the information getting saved */ public void loadLog(JobsPlayer player) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; ResultSet res = null; try { int time = TimeManage.timeInInt(); prest = conn.prepareStatement("SELECT * FROM `" + prefix + "log` WHERE `userid` = ? AND `time` = ? ;"); prest.setInt(1, player.getUserId()); prest.setInt(2, time); res = prest.executeQuery(); while (res.next()) { HashMap<CurrencyType, Double> amounts = new HashMap<>(); amounts.put(CurrencyType.MONEY, res.getDouble("money")); amounts.put(CurrencyType.EXP, res.getDouble("exp")); amounts.put(CurrencyType.POINTS, res.getDouble("points")); Jobs.getLoging().loadToLog(player, res.getString("action"), res.getString("itemname"), res.getInt("count"), amounts); } } catch (Exception e) { close(res); close(prest); drop(DBTables.LogTable.getTableName()); createDefaultTable(DBTables.LogTable); } finally { close(res); close(prest); } } /** * Save block protection information * @param jobBlockProtection - the information getting saved */ public void saveBlockProtection() { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement insert = null; PreparedStatement update = null; PreparedStatement delete = null; try { insert = conn.prepareStatement("INSERT INTO `" + prefix + "blocks` (`world`, `x`, `y`, `z`, `recorded`, `resets`) VALUES (?, ?, ?, ?, ?, ?);"); update = conn.prepareStatement("UPDATE `" + prefix + "blocks` SET `recorded` = ?, `resets` = ? WHERE `id` = ?;"); delete = conn.prepareStatement("DELETE from `" + getPrefix() + "blocks` WHERE `id` = ?;"); Jobs.getPluginLogger().info("Saving blocks"); conn.setAutoCommit(false); int inserted = 0; int updated = 0; int deleted = 0; Long current = System.currentTimeMillis(); Long mark = System.currentTimeMillis() - (Jobs.getGCManager().BlockProtectionDays * 24L * 60L * 60L * 1000L); for (Entry<World, HashMap<String, HashMap<String, HashMap<String, BlockProtection>>>> worlds : Jobs.getBpManager().getMap().entrySet()) { for (Entry<String, HashMap<String, HashMap<String, BlockProtection>>> regions : worlds.getValue().entrySet()) { for (Entry<String, HashMap<String, BlockProtection>> chunks : regions.getValue().entrySet()) { for (Entry<String, BlockProtection> block : chunks.getValue().entrySet()) { if (block.getValue() == null) continue; switch (block.getValue().getAction()) { case DELETE: delete.setInt(1, block.getValue().getId()); delete.addBatch(); deleted++; if (deleted % 10000 == 0) { delete.executeBatch(); Jobs.consoleMsg("&6[Jobs] Removed " + deleted + " old block protection entries."); } break; case INSERT: if (block.getValue().getTime() < current && block.getValue().getTime() != -1) continue; insert.setString(1, worlds.getKey().getName()); insert.setInt(2, block.getValue().getPos().getBlockX()); insert.setInt(3, block.getValue().getPos().getBlockY()); insert.setInt(4, block.getValue().getPos().getBlockZ()); insert.setLong(5, block.getValue().getRecorded()); insert.setLong(6, block.getValue().getTime()); insert.addBatch(); inserted++; if (inserted % 10000 == 0) { insert.executeBatch(); Jobs.consoleMsg("&6[Jobs] Added " + inserted + " new block protection entries."); } break; case UPDATE: if (block.getValue().getTime() < current && block.getValue().getTime() != -1) continue; update.setLong(1, block.getValue().getRecorded()); update.setLong(2, block.getValue().getTime()); update.setInt(3, block.getValue().getId()); update.addBatch(); updated++; if (updated % 10000 == 0) { update.executeBatch(); Jobs.consoleMsg("&6[Jobs] Upadated " + updated + " old block protection entries."); } break; case NONE: if (block.getValue().getTime() < current && block.getValue().getTime() != -1) continue; if (block.getValue().getTime() == -1 && block.getValue().getRecorded() > mark) continue; delete.setInt(1, block.getValue().getId()); delete.addBatch(); deleted++; if (deleted % 10000 == 0) { delete.executeBatch(); Jobs.getPluginLogger().info("[Jobs] Removed " + deleted + " old block protection entries."); } break; default: continue; } } } } } insert.executeBatch(); update.executeBatch(); delete.executeBatch(); conn.commit(); conn.setAutoCommit(true); if (inserted > 0) { Jobs.consoleMsg("&6[Jobs] Added " + inserted + " new block protection entries."); } if (updated > 0) { Jobs.consoleMsg("&6[Jobs] Updated " + updated + " with new block protection entries."); } if (deleted > 0) { Jobs.consoleMsg("&6[Jobs] Deleted " + deleted + " old block protection entries."); } } catch (SQLException e) { e.printStackTrace(); } finally { close(insert); close(update); close(delete); try { conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } } /** * Save block protection information * @param jobBlockProtection - the information getting saved */ public void loadBlockProtection() { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; ResultSet res = null; Jobs.getBpManager().timer = 0L; try { prest = conn.prepareStatement("SELECT * FROM `" + prefix + "blocks`;"); res = prest.executeQuery(); int i = 0; int ii = 0; while (res.next()) { World world = Bukkit.getWorld(res.getString("world")); if (world == null) continue; int id = res.getInt("id"); int x = res.getInt("x"); int y = res.getInt("y"); int z = res.getInt("z"); long resets = res.getLong("resets"); Location loc = new Location(world, x, y, z); BlockProtection bp = Jobs.getBpManager().addP(loc, resets, true); bp.setId(id); long t = System.currentTimeMillis(); bp.setRecorded(res.getLong("recorded")); bp.setAction(DBAction.NONE); i++; ii++; if (ii >= 100000) { Jobs.consoleMsg("&6[Jobs] Loading (" + i + ") BP"); ii = 0; } Jobs.getBpManager().timer += System.currentTimeMillis() - t; } if (i > 0) { Jobs.consoleMsg("&e[Jobs] Loaded " + i + " block protection entries. " + Jobs.getBpManager().timer); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } } /** * Save player-explore information */ public void saveExplore() { insertExplore(); updateExplore(); } public void insertExplore() { if (!Jobs.getExplore().isExploreEnabled()) return; JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest2 = null; try { prest2 = conn.prepareStatement("INSERT INTO `" + prefix + "exploreData` (`worldname`, `chunkX`, `chunkZ`, `playerNames`) VALUES (?, ?, ?, ?);"); conn.setAutoCommit(false); int i = 0; HashMap<String, ExploreRegion> temp = new HashMap<>(Jobs.getExplore().getWorlds()); for (Entry<String, ExploreRegion> worlds : temp.entrySet()) { for (Entry<String, ExploreChunk> oneChunk : worlds.getValue().getChunks().entrySet()) { if (oneChunk.getValue().getDbId() != null) continue; prest2.setString(1, worlds.getKey()); prest2.setInt(2, oneChunk.getValue().getX()); prest2.setInt(3, oneChunk.getValue().getZ()); prest2.setString(4, oneChunk.getValue().serializeNames()); prest2.addBatch(); i++; } } prest2.executeBatch(); conn.commit(); conn.setAutoCommit(true); if (i > 0) Jobs.consoleMsg("&e[Jobs] Saved " + i + " new explorer entries."); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest2); try { conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } } public void updateExplore() { if (!Jobs.getExplore().isExploreEnabled()) return; JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { conn.setAutoCommit(false); prest = conn.prepareStatement("UPDATE `" + prefix + "exploreData` SET `playerNames` = ? WHERE `id` = ?;"); int i = 0; HashMap<String, ExploreRegion> temp = new HashMap<>(Jobs.getExplore().getWorlds()); for (Entry<String, ExploreRegion> worlds : temp.entrySet()) { for (Entry<String, ExploreChunk> oneChunk : worlds.getValue().getChunks().entrySet()) { if (oneChunk.getValue().getDbId() == null) continue; if (!oneChunk.getValue().isUpdated()) continue; prest.setString(1, oneChunk.getValue().serializeNames()); prest.setInt(2, oneChunk.getValue().getDbId()); prest.addBatch(); i++; } } prest.executeBatch(); conn.commit(); conn.setAutoCommit(true); if (i > 0) Jobs.consoleMsg("&e[Jobs] Updated " + i + " explorer entries."); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); try { conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } } /** * Save player-explore information * @param jobexplore - the information getting saved */ public void loadExplore() { if (!Jobs.getExplore().isExploreEnabled()) return; JobsConnection conn = getConnection(); if (conn == null) return; if (this.isTable(prefix + "explore")) { PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + prefix + "explore`;"); res = prest.executeQuery(); while (res.next()) { Jobs.getExplore().ChunkRespond(res.getString("playerName"), res.getString("worldname"), res.getInt("chunkX"), res.getInt("chunkZ")); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } Statement stmt = null; try { stmt = conn.createStatement(); stmt.executeUpdate("DROP TABLE `" + prefix + "explore`;"); } catch (SQLException e) { e.printStackTrace(); } finally { close(stmt); } } PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + prefix + "exploreData`;"); res = prest.executeQuery(); while (res.next()) { Jobs.getExplore().load(res); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } } /** * Save player-job information * @param jobInfo - the information getting saved * @return */ public List<Integer> getLognameList(int fromtime, int untiltime) { JobsConnection conn = getConnection(); List<Integer> nameList = new ArrayList<>(); if (conn == null) return nameList; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT `userid` FROM `" + prefix + "log` WHERE `time` >= ? AND `time` <= ? ;"); prest.setInt(1, fromtime); prest.setInt(2, untiltime); res = prest.executeQuery(); while (res.next()) { if (!nameList.contains(res.getInt("userid"))) nameList.add(res.getInt("userid")); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return nameList; } /** * Show top list * @param toplist - toplist by jobs name * @return */ public ArrayList<TopList> toplist(String jobsname) { return toplist(jobsname, 0); } /** * Show top list * @param toplist - toplist by jobs name * @return */ public ArrayList<TopList> toplist(String jobsname, int limit) { ArrayList<TopList> jobs = new ArrayList<>(); JobsConnection conn = getConnection(); if (conn == null) return jobs; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT `userid`, `level`, `experience` FROM `" + prefix + "jobs` WHERE `job` LIKE ? ORDER BY `level` DESC, LOWER(experience) DESC LIMIT " + limit + ", 50;"); prest.setString(1, jobsname); res = prest.executeQuery(); while (res.next()) { PlayerInfo info = Jobs.getPlayerManager().getPlayerInfo(res.getInt("userid")); if (info == null) continue; if (info.getName() == null) continue; jobs.add(new TopList(info, res.getInt("level"), res.getInt("experience"))); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return jobs; } /** * Get the number of players that have a particular job * @param job - the job * @return the number of players that have a particular job */ public synchronized int getSlotsTaken(Job job) { int slot = 0; JobsConnection conn = getConnection(); if (conn == null) return slot; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT COUNT(*) FROM `" + prefix + "jobs` WHERE `job` = ?;"); prest.setString(1, job.getName()); res = prest.executeQuery(); if (res.next()) { slot = res.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return slot; } /** * Executes an SQL query * @param sql - The SQL * @throws SQLException */ public void executeSQL(String sql) throws SQLException { JobsConnection conn = getConnection(); Statement stmt = null; try { stmt = conn.createStatement(); stmt.execute(sql); } finally { close(stmt); } } /** * Get a database connection * @return DBConnection object * @throws SQLException */ protected JobsConnection getConnection() { try { return isConnected() ? pool.getConnection() : null; } catch (SQLException e) { Jobs.getPluginLogger().severe("Unable to connect to the database: " + e.getMessage()); return null; } } /** * Close all active database handles */ public synchronized void closeConnections() { pool.closeConnection(); } protected static void close(ResultSet res) { if (res != null) try { res.close(); } catch (SQLException e) { e.printStackTrace(); } } protected static void close(Statement stmt) { if (stmt != null) try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } public HashMap<Integer, ArrayList<JobsDAOData>> getMap() { return map; } }
package org.bdgp.OpenHiCAMM.Modules; import java.awt.Component; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.swing.JPanel; import org.bdgp.OpenHiCAMM.Dao; import org.bdgp.OpenHiCAMM.Logger; import org.bdgp.OpenHiCAMM.Util; import org.bdgp.OpenHiCAMM.ValidationError; import org.bdgp.OpenHiCAMM.WorkflowRunner; import org.bdgp.OpenHiCAMM.DB.Acquisition; import org.bdgp.OpenHiCAMM.DB.Config; import org.bdgp.OpenHiCAMM.DB.Image; import org.bdgp.OpenHiCAMM.DB.Task; import org.bdgp.OpenHiCAMM.DB.Task.Status; import org.bdgp.OpenHiCAMM.DB.TaskConfig; import org.bdgp.OpenHiCAMM.DB.TaskDispatch; import org.bdgp.OpenHiCAMM.Modules.Interfaces.Configuration; import org.bdgp.OpenHiCAMM.Modules.Interfaces.Module; import org.json.JSONArray; import org.json.JSONException; import org.micromanager.acquisition.MMAcquisition; import org.micromanager.api.ImageCache; import org.micromanager.utils.ImageUtils; import ij.IJ; import ij.ImagePlus; import ij.WindowManager; import ij.gui.ImageWindow; import ij.io.FileSaver; import ij.process.ImageProcessor; import mmcorej.TaggedImage; import static org.bdgp.OpenHiCAMM.Util.where; public class ImageStitcher implements Module { private static final String FUSION_METHOD = "Linear Blending"; private static final int CHECK_PEAKS = 5; private static final boolean COMPUTE_OVERLAP = true; private static final String REGISTRATION_CHANNEL_IMAGE_1 = "Average all channels"; private static final String REGISTRATION_CHANNEL_IMAGE_2 = "Average all channels"; private static final double OVERLAP_WIDTH = 0.25; private static final double OVERLAP_HEIGHT = 0.25; private static final String STITCHED_IMAGE_DIRECTORY_PREFIX = "stitched"; WorkflowRunner workflowRunner; String moduleId; @Override public void initialize(WorkflowRunner workflowRunner, String moduleId) { this.workflowRunner = workflowRunner; this.moduleId = moduleId; } public static class TaskTile { public Task task; public Map<String,TaskConfig> taskConfig; public int tileX; public int tileY; public ImagePlus image; public TaskTile(Task task, Map<String,TaskConfig> taskConfig, int tileX, int tileY, ImagePlus image) { this.task = task; this.taskConfig = taskConfig; this.tileX = tileX; this.tileY = tileY; this.image = image; } } @Override public Status run(Task task, Map<String,Config> config, Logger logger) { Dao<TaskConfig> taskConfigDao = this.workflowRunner.getTaskConfig(); logger.fine(String.format("Running task %s: %s", task.getName(), task)); // get the stitch group name Config stitchGroupConf = config.get("stitchGroup"); if (stitchGroupConf == null) throw new RuntimeException(String.format( "%s: stitchGroup config not found!", task.getName())); String stitchGroup = stitchGroupConf.getValue(); logger.fine(String.format("Stitching group: %s", stitchGroup)); // get the stitched folder Config stitchedFolderConf = config.get("stitchedFolder"); if (stitchedFolderConf == null) throw new RuntimeException(String.format( "%s: stitchedFolder config not found!", task.getName())); String stitchedFolder = stitchedFolderConf.getValue(); logger.fine(String.format("Stitched folder: %s", stitchedFolder)); // get the list of stitch task IDs Config stitchTaskIdsConf = config.get("stitchTaskIds"); if (stitchTaskIdsConf == null) throw new RuntimeException(String.format( "%s: stitchTaskIds config not found!", task.getName())); // get the list of stitch task IDs from the JSON array List<Integer> stitchTaskIds = new ArrayList<Integer>(); try { JSONArray stitchTaskJson = new JSONArray(stitchTaskIdsConf.getValue()); for (int i=0; i<stitchTaskJson.length(); ++i) { Integer stitchTaskId = stitchTaskJson.getInt(i); stitchTaskIds.add(stitchTaskId); } } catch (JSONException e) {throw new RuntimeException(e);} Dao<Image> imageDao = this.workflowRunner.getInstanceDb().table(Image.class); Dao<Acquisition> acqDao = workflowRunner.getInstanceDb().table(Acquisition.class); // Organize the tasks into a grid of TaskTiles Integer gridWidth = null; Integer gridHeight = null; List<TaskTile> taskTiles = new ArrayList<TaskTile>(); Integer frame = null; Integer channel = null; Integer slice = null; for (Integer stitchTaskId : stitchTaskIds) { Task stitchTask = this.workflowRunner.getTaskStatus().selectOne(where("id", stitchTaskId)); if (stitchTask == null) throw new RuntimeException(String.format( "%s: Stitch task with ID %d not found in database!", task.getName(), stitchTaskId)); // get the task config for each stitch task List<TaskConfig> taskConfigs = this.workflowRunner.getTaskConfig().select(where("id", stitchTask.getId())); Map<String,TaskConfig> taskConfig = new HashMap<String,TaskConfig>(); for (TaskConfig tc : taskConfigs) { taskConfig.put(tc.getKey(), tc); } // get the tileX and tileY, figure out gridWidth and gridHeight TaskConfig tileXConf = taskConfig.get("tileX"); if (tileXConf == null) throw new RuntimeException(String.format("Task %s: tileX is null!", stitchTask)); Integer tileX = new Integer(tileXConf.getValue()); TaskConfig tileYConf = taskConfig.get("tileY"); if (tileYConf == null) throw new RuntimeException(String.format("Task %s: tileY is null!", stitchTask)); Integer tileY = new Integer(tileYConf.getValue()); if (gridWidth == null || gridWidth < tileX+1) gridWidth = tileX+1; if (gridHeight == null || gridHeight < tileY+1) gridHeight = tileY+1; // get the image ID TaskConfig imageId = taskConfig.get("imageId"); if (imageId == null) throw new RuntimeException(String.format("Task %s: imageId is null!", stitchTask)); // get the Image record Image image = imageDao.selectOneOrDie(where("id", new Integer(imageId.getValue()))); if (frame == null) frame = image.getFrame(); if (channel == null) channel = image.getChannel(); if (slice == null) slice = image.getSlice(); // Initialize the acquisition Acquisition acquisition = acqDao.selectOneOrDie(where("id",image.getAcquisitionId())); MMAcquisition mmacquisition = acquisition.getAcquisition(acqDao); // Get the image cache object ImageCache imageCache = mmacquisition.getImageCache(); if (imageCache == null) throw new RuntimeException("Acquisition was not initialized; imageCache is null!"); // Get the tagged image from the image cache TaggedImage taggedImage = image.getImage(imageCache); if (taggedImage == null) throw new RuntimeException(String.format("Acqusition %s, Image %s is not in the image cache!", acquisition, image)); // convert the tagged image into an ImagePlus object ImageProcessor processor = ImageUtils.makeProcessor(taggedImage); ImagePlus imp = new ImagePlus(image.getName(), processor); // create the TaskTile object TaskTile taskTile = new TaskTile(task, taskConfig, tileX, tileY, imp); taskTiles.add(taskTile); } TaskTile[][] taskGrid = new TaskTile[gridHeight][gridWidth]; for (TaskTile taskTile : taskTiles) { taskGrid[taskTile.tileY][taskTile.tileX] = taskTile; } // Create a fake acquisition directory to store the stitched images List<File> tempImages = new ArrayList<File>(); try { // stitch the images into a single tagged image ImagePlus stitchedImage = stitchGrid(taskGrid, stitchedFolder, tempImages); // save the stitched image to the stitched folder using the stitch group as the // file name. FileSaver fileSaver = new FileSaver(stitchedImage); String imageFile = new File(stitchedFolder, String.format("%s.tif", stitchGroup)).getPath(); fileSaver.saveAsTiff(imageFile); // close the stitched image stitchedImage.changes = false; ImageWindow stitchedImageWindow = stitchedImage.getWindow(); if (stitchedImageWindow != null) stitchedImageWindow.close(); stitchedImage.close(); // write a task configuration for the stitched image location TaskConfig imageFileConf = new TaskConfig(new Integer(task.getId()).toString(), "stitchedImageFile", imageFile); taskConfigDao.insertOrUpdate(imageFileConf, "id", "key"); } finally { // delete the intermediate temporary image files for (File tempImage : tempImages) { tempImage.delete(); } } return Status.SUCCESS; } public ImagePlus stitchGrid(TaskTile[][] taskGrid, String stitchedImageDirectory, List<File> tempImages) { ImagePlus image1; ImagePlus image2; if (taskGrid.length > 1 || (taskGrid.length > 0 && taskGrid[0].length > 1)) { TaskTile[][] grid1; TaskTile[][] grid2; // vertical split if (taskGrid.length < taskGrid[0].length) { int splitPoint = taskGrid[0].length / 2; grid1 = new TaskTile[taskGrid.length][splitPoint]; for (int r=0; r<taskGrid.length; ++r) { for (int c=0; c<splitPoint; ++c) { grid1[r][c] = taskGrid[r][c]; } } grid2 = new TaskTile[taskGrid.length][taskGrid[0].length-splitPoint]; for (int r=0; r<taskGrid.length; ++r) { for (int c=splitPoint; c<taskGrid[0].length; ++c) { grid2[r][c-splitPoint] = taskGrid[r][c]; } } image1 = stitchGrid(grid1, stitchedImageDirectory, tempImages); image2 = stitchGrid(grid2, stitchedImageDirectory, tempImages); return stitchImages(image1, image2, false); } // horizontal split else { int splitPoint = taskGrid.length / 2; grid1 = new TaskTile[splitPoint][taskGrid[0].length]; for (int r=0; r<splitPoint; ++r) { for (int c=0; c<taskGrid[0].length; ++c) { grid1[r][c] = taskGrid[r][c]; } } grid2 = new TaskTile[taskGrid.length-splitPoint][taskGrid[0].length]; for (int r=splitPoint; r<taskGrid.length; ++r) { for (int c=0; c<taskGrid[0].length; ++c) { grid2[r-splitPoint][c] = taskGrid[r][c]; } } image1 = stitchGrid(grid1, stitchedImageDirectory, tempImages); image2 = stitchGrid(grid2, stitchedImageDirectory, tempImages); return stitchImages(image1, image2, true); } } else if (taskGrid.length > 1) { image1 = taskGrid[0][0].image; image2 = taskGrid[1][0].image; return stitchImages(image1, image2, true); } else if (taskGrid.length > 0 && taskGrid[0].length > 1) { image1 = taskGrid[0][0].image; image2 = taskGrid[0][1].image; return stitchImages(image1, image2, false); } else if (taskGrid.length == 1 && taskGrid[0].length == 1) { return taskGrid[0][0].image; } else { throw new RuntimeException("Empty TaskTile array passed to stitchGrid!"); } } public ImagePlus stitchImages( ImagePlus image1, ImagePlus image2, boolean isVerticallyAligned) { String fusion_method = FUSION_METHOD; int check_peaks = CHECK_PEAKS; boolean compute_overlap = COMPUTE_OVERLAP; double overlapWidth = OVERLAP_WIDTH; double overlapHeight = OVERLAP_HEIGHT; double x = isVerticallyAligned? 0.0 : image1.getWidth() * (1.0 - overlapWidth); double y = isVerticallyAligned? image1.getHeight() * (1.0 - overlapHeight) : 0.0; String registration_channel_image_1 = REGISTRATION_CHANNEL_IMAGE_1; String registration_channel_image_2 = REGISTRATION_CHANNEL_IMAGE_2; // open the input images image1.show(); image2.show(); // run the pairwise stitching plugin String fusedImageTitle = String.format("%s<->%s", image1.getTitle(), image2.getTitle()); String params = Util.join(" ", String.format("first_image=%s", Util.macroEscape(image1.getTitle())), String.format("second_image=%s", Util.macroEscape(image2.getTitle())), String.format("fusion_method=%s", Util.macroEscape(fusion_method)), String.format("fused_image=%s", Util.macroEscape(fusedImageTitle)), String.format("check_peaks=%d", check_peaks), compute_overlap? "compute_overlap" : null, String.format("x=%.4f", x), String.format("y=%.4f", y), String.format("registration_channel_image_1=%s", Util.macroEscape(registration_channel_image_1)), String.format("registration_channel_image_2=%s", Util.macroEscape(registration_channel_image_2))); IJ.run(image1, "Pairwise stitching", params); // close the input images image1.changes = false; ImageWindow image1Window = image1.getWindow(); if (image1Window != null) image1Window.close(); image1.close(); image2.changes = false; ImageWindow image2Window = image2.getWindow(); if (image2Window != null) image2Window.close(); image2.close(); // get the fused image ImagePlus fusedImage = WindowManager.getImage(fusedImageTitle); if (fusedImage == null) throw new RuntimeException(String.format( "Pairwise Stitching: could not find fused image with title: %s", fusedImageTitle)); // convert stack to RGB if (fusedImage.getNChannels() == 3) { IJ.run(fusedImage, "Stack to RGB", ""); String rgbImageTitle = String.format("%s (RGB)", fusedImage.getTitle()); ImagePlus rgbImage = WindowManager.getImage(rgbImageTitle); if (rgbImage == null) throw new RuntimeException(String.format( "Pairwise Stitching: could not find RGB image with title: %s", rgbImageTitle)); // close the separate-channel fused image fusedImage.changes = false; ImageWindow fusedImageWindow = fusedImage.getWindow(); if (fusedImageWindow != null) fusedImageWindow.close(); fusedImage.close(); // return the RGB image return rgbImage; } return fusedImage; } @Override public String getTitle() { return this.getClass().getName(); } @Override public String getDescription() { return this.getClass().getName(); } @Override public Configuration configure() { return new Configuration() { @Override public Config[] retrieve() { return new Config[0]; } @Override public Component display(Config[] configs) { return new JPanel(); } @Override public ValidationError[] validate() { return null; } }; } @Override public List<Task> createTaskRecords(List<Task> parentTasks) { Dao<Task> taskDao = this.workflowRunner.getTaskStatus(); Dao<TaskConfig> taskConfigDao = this.workflowRunner.getTaskConfig(); Dao<TaskDispatch> taskDispatchDao = this.workflowRunner.getTaskDispatch(); // Group the parent tasks by stitchGroup name Map<String,List<Task>> stitchGroups = new LinkedHashMap<String,List<Task>>(); for (Task parentTask : parentTasks) { TaskConfig stitchGroup = taskConfigDao.selectOne(where("id", parentTask.getId()).and("key", "stitchGroup")); if (stitchGroup != null) { // make sure tileX and tileY are set TaskConfig tileX = taskConfigDao.selectOne(where("id", parentTask.getId()).and("key", "tileX")); TaskConfig tileY = taskConfigDao.selectOne(where("id", parentTask.getId()).and("key", "tileY")); if (tileX == null || tileY == null) { throw new RuntimeException(String.format("tileX and tileY not defined for task: %s", parentTask)); } // add the task to the stitch group if (!stitchGroups.containsKey(stitchGroup.getValue())) { stitchGroups.put(stitchGroup.getValue(), new ArrayList<Task>()); } stitchGroups.get(stitchGroup.getValue()).add(parentTask); } } // create a folder to store the stitched images File stitchedFolder = createStitchedImageFolder(); List<Task> tasks = new ArrayList<Task>(); for (Map.Entry<String, List<Task>> entry : stitchGroups.entrySet()) { String stitchGroup = entry.getKey(); List<Task> stitchTasks = entry.getValue(); // insert the task record Task task = new Task(this.moduleId, Status.NEW); taskDao.insert(task); tasks.add(task); // add the stitchedFolder task config TaskConfig stitchedFolderConf = new TaskConfig( new Integer(task.getId()).toString(), "stitchedFolder", stitchedFolder.toString()); taskConfigDao.insert(stitchedFolderConf); // add the stitchGroup task config TaskConfig stitchGroupConf = new TaskConfig( new Integer(task.getId()).toString(), "stitchGroup", stitchGroup); taskConfigDao.insert(stitchGroupConf); // add the stitchTaskIds task config, a JSONArray of stitch task IDs. JSONArray stitchTaskIds = new JSONArray(); for (Task stitchTask : stitchTasks) { stitchTaskIds.put(stitchTask.getId()); } TaskConfig stitchTaskIdsConf = new TaskConfig( new Integer(task.getId()).toString(), "stitchTaskIds", stitchTaskIds.toString()); taskConfigDao.insert(stitchTaskIdsConf); // add the task dispatch records for (Task stitchTask : stitchTasks) { TaskDispatch td = new TaskDispatch(task.getId(), stitchTask.getId()); taskDispatchDao.insert(td); } } return tasks; } private File createStitchedImageFolder() { String rootDir = new File( this.workflowRunner.getWorkflowDir(), this.workflowRunner.getInstance().getStorageLocation()).getPath(); int count = 1; File stitchedFolder = new File(rootDir, String.format("%s_%d", STITCHED_IMAGE_DIRECTORY_PREFIX, count)); while (!stitchedFolder.mkdirs()) { ++count; stitchedFolder = new File(rootDir, String.format("%s_%d", STITCHED_IMAGE_DIRECTORY_PREFIX, count)); } return stitchedFolder; } @Override public TaskType getTaskType() { return Module.TaskType.PARALLEL; } @Override public void cleanup(Task task) { } @Override public void runIntialize() { } }
package com.gamingmesh.jobs.dao; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.entity.Player; import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.container.ArchivedJobs; import com.gamingmesh.jobs.container.BlockProtection; import com.gamingmesh.jobs.container.Convert; import com.gamingmesh.jobs.container.CurrencyType; import com.gamingmesh.jobs.container.DBAction; import com.gamingmesh.jobs.container.ExploreChunk; import com.gamingmesh.jobs.container.ExploreRegion; import com.gamingmesh.jobs.container.Job; import com.gamingmesh.jobs.container.JobProgression; import com.gamingmesh.jobs.container.JobsPlayer; import com.gamingmesh.jobs.container.JobsWorld; import com.gamingmesh.jobs.container.Log; import com.gamingmesh.jobs.container.LogAmounts; import com.gamingmesh.jobs.container.PlayerInfo; import com.gamingmesh.jobs.container.PlayerPoints; import com.gamingmesh.jobs.container.TopList; import com.gamingmesh.jobs.dao.JobsManager.DataBaseType; import com.gamingmesh.jobs.economy.PaymentData; import com.gamingmesh.jobs.stuff.TimeManage; import com.gamingmesh.jobs.stuff.Util; import net.Zrips.CMILib.Logs.CMIDebug; import net.Zrips.CMILib.Messages.CMIMessages; public abstract class JobsDAO { private JobsConnectionPool pool; private static String prefix; private Jobs plugin; private static DataBaseType dbType = DataBaseType.SqLite; // Not in use currently public enum TablesFieldsType { decimal, number, text, varchar, stringList, stringLongMap, stringIntMap, locationMap, state, location, longNumber; } public enum worldsTableFields implements JobsTableInterface { name("varchar(36)", true); private String type; private boolean unique = false; worldsTableFields(String type) { this(type, false); } worldsTableFields(String type, boolean unique) { this.type = type; this.unique = unique; } @Override public String getCollumn() { return name(); } @Override public String getType() { return type; } @Override public boolean isUnique() { return unique; } } public enum jobsNameTableFields implements JobsTableInterface { name("varchar(36)", true); private String type; private boolean unique = false; jobsNameTableFields(String type) { this(type, false); } jobsNameTableFields(String type, boolean unique) { this.type = type; this.unique = unique; } @Override public String getCollumn() { return name(); } @Override public String getType() { return type; } @Override public boolean isUnique() { return unique; } } public enum UserTableFields implements JobsTableInterface { player_uuid("varchar(36)"), username("text"), seen("bigint"), donequests("int"), quests("text"); private String type; UserTableFields(String type) { this.type = type; } @Override public String getCollumn() { return name(); } @Override public String getType() { return type; } @Override public boolean isUnique() { return false; } } public enum JobsTableFields implements JobsTableInterface { userid("int"), job("text"), experience("double"), level("int"), jobid("int"); private String type; JobsTableFields(String type) { this.type = type; } @Override public String getCollumn() { return name(); } @Override public String getType() { return type; } @Override public boolean isUnique() { return false; } } public enum ArchiveTableFields implements JobsTableInterface { userid("int"), job("text"), experience("int"), level("int"), left("bigint"), jobid("int"); private String type; ArchiveTableFields(String type) { this.type = type; } @Override public String getCollumn() { return name(); } @Override public String getType() { return type; } @Override public boolean isUnique() { return false; } } public enum BlockTableFields implements JobsTableInterface { world("varchar(36)"), x("int"), y("int"), z("int"), recorded("bigint"), resets("bigint"), worldid("int"); private String type; BlockTableFields(String type) { this.type = type; } @Override public String getCollumn() { return name(); } @Override public String getType() { return type; } @Override public boolean isUnique() { return false; } } public enum LimitTableFields implements JobsTableInterface { userid("int"), type("varchar(36)"), collected("double"), started("bigint"), typeid("int"); private String ttype; LimitTableFields(String type) { this.ttype = type; } @Override public String getCollumn() { return name(); } @Override public String getType() { return ttype; } @Override public boolean isUnique() { return false; } } public enum LogTableFields implements JobsTableInterface { userid("int"), time("bigint"), action("varchar(20)"), itemname("text"), count("int"), money("double"), exp("double"), points("double"); private String type; LogTableFields(String type) { this.type = type; } @Override public String getCollumn() { return name(); } @Override public String getType() { return type; } @Override public boolean isUnique() { return false; } } public enum PointsTableFields implements JobsTableInterface { userid("int"), totalpoints("double"), currentpoints("double"); private String type; PointsTableFields(String type) { this.type = type; } @Override public String getCollumn() { return name(); } @Override public String getType() { return type; } @Override public boolean isUnique() { return false; } } public enum ExploreDataTableFields implements JobsTableInterface { worldname("varchar(64)"), chunkX("int"), chunkZ("int"), playerNames("text"), worldid("int"); private String type; ExploreDataTableFields(String type) { this.type = type; } @Override public String getCollumn() { return name(); } @Override public String getType() { return type; } @Override public boolean isUnique() { return false; } } public enum DBTables { JobNameTable("jobNames", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", jobsNameTableFields.class), WorldTable("worlds", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", worldsTableFields.class), UsersTable("users", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", UserTableFields.class), JobsTable("jobs", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", JobsTableFields.class), ArchiveTable("archive", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", ArchiveTableFields.class), BlocksTable("blocks", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", BlockTableFields.class), LimitsTable("limits", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", LimitTableFields.class), LogTable("log", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", LogTableFields.class), ExploreDataTable("exploreData", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", ExploreDataTableFields.class), PointsTable("points", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", "CREATE TABLE IF NOT EXISTS `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", PointsTableFields.class); private String mySQL; private String sQlite; private String tableName; private JobsTableInterface[] c; DBTables(String tableName, String MySQL, String SQlite, Class<?> cc) { this.tableName = tableName; this.mySQL = MySQL; this.sQlite = SQlite; this.c = (JobsTableInterface[]) cc.getEnumConstants(); } private String getQR() { switch (dbType) { case MySQL: return mySQL.replace("[tableName]", prefix + tableName); case SqLite: return sQlite.replace("[tableName]", tableName); default: break; } return ""; } public String getQuery() { String rp = ""; List<JobsTableInterface> uniques = new ArrayList<>(); for (JobsTableInterface one : c) { if (one.isUnique()) { uniques.add(one); } rp += " , `" + one.getCollumn() + "` " + one.getType(); } String unique = ""; for (JobsTableInterface one : uniques) { if (!unique.isEmpty()) { unique += " ,"; } unique += "`" + one.getCollumn() + "`"; } if (!unique.isEmpty()) { switch (dbType) { case MySQL: unique = " , UNIQUE KEY template_" + tableName + " (" + unique + ")"; break; case SqLite: unique = " , UNIQUE (" + unique + ")"; break; default: break; } } return getQR().replace("[fields]", rp + unique); } public JobsTableInterface[] getInterface() { return c; } public String getTableName() { return prefix + tableName; } } protected JobsDAO(Jobs plugin, String driverName, String url, String username, String password, String pr) { this.plugin = plugin; prefix = pr; try { Class.forName(driverName); } catch (ClassNotFoundException c) { c.printStackTrace(); return; } try { pool = new JobsConnectionPool(driverName, url, username, password); } catch (Exception e) { e.printStackTrace(); } } public final synchronized boolean setUp() { if (getConnection() == null) { CMIMessages.consoleMessage("&cFAILED to connect to database"); return false; } CMIMessages.consoleMessage("&eConnected to database (&6" + dbType + "&e)"); vacuum(); try { for (DBTables one : DBTables.values()) { createDefaultTable(one); } checkDefaultCollumns(); } finally { } return true; } protected abstract void checkUpdate() throws SQLException; public abstract Statement prepareStatement(String query) throws SQLException; public abstract boolean createTable(String query) throws SQLException; public abstract boolean isTable(String table); public abstract boolean isCollumn(String table, String collumn); public abstract boolean truncate(String table); public abstract boolean addCollumn(String table, String collumn, String type); public abstract boolean drop(String table); public boolean isConnected() { if (pool == null) { return false; } try { JobsConnection conn = pool.getConnection(); return conn != null && !conn.isClosed(); } catch (SQLException e) { return false; } } private boolean createDefaultTable(DBTables table) { if (isTable(table.getTableName())) return true; try { createTable(table.getQuery()); return true; } catch (SQLException e) { e.printStackTrace(); } return false; } private boolean checkDefaultCollumns() { for (DBTables one : DBTables.values()) { String tableName = one.getTableName(); for (JobsTableInterface oneT : one.getInterface()) { if (!isCollumn(tableName, oneT.getCollumn())) addCollumn(tableName, oneT.getCollumn(), oneT.getType()); } } return true; } public void truncateAllTables() { for (DBTables one : DBTables.values()) { truncate(one.getTableName()); } } public DataBaseType getDbType() { return dbType; } public void setDbType(DataBaseType dabType) { dbType = dabType; } /** * Gets the database prefix * @return the prefix */ protected String getPrefix() { return prefix; } public List<JobsDAOData> getAllJobs(OfflinePlayer player) { return getAllJobs(player.getName(), player.getUniqueId()); } /** * Get all jobs the player is part of. * @param playerUUID - the player being searched for * @return list of all of the names of the jobs the players are part of. */ public List<JobsDAOData> getAllJobs(String playerName, UUID uuid) { PlayerInfo userData = null; if (Jobs.getGCManager().MultiServerCompatability()) userData = loadPlayerData(uuid); else userData = Jobs.getPlayerManager().getPlayerInfo(uuid); List<JobsDAOData> jobs = new ArrayList<>(); if (userData == null) { recordNewPlayer(playerName, uuid); return jobs; } JobsConnection conn = getConnection(); if (conn == null) return jobs; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + getJobsTableName() + "` WHERE `" + JobsTableFields.userid.getCollumn() + "` = ?;"); prest.setInt(1, userData.getID()); res = prest.executeQuery(); while (res.next()) { int jobId = res.getInt(JobsTableFields.jobid.getCollumn()); if (jobId == 0) { jobs.add(new JobsDAOData(res.getString(JobsTableFields.job.getCollumn()), res.getInt(JobsTableFields.level.getCollumn()), res.getDouble(JobsTableFields.experience.getCollumn()))); } else { Job job = Jobs.getJob(jobId); if (job != null) jobs.add(new JobsDAOData(job.getName(), res.getInt(JobsTableFields.level.getCollumn()), res.getDouble(JobsTableFields.experience.getCollumn()))); } } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return jobs; } public Map<Integer, List<JobsDAOData>> getAllJobs() { Map<Integer, List<JobsDAOData>> map = new HashMap<>(); JobsConnection conn = getConnection(); if (conn == null) return map; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + getJobsTableName() + "`;"); res = prest.executeQuery(); while (res.next()) { int id = res.getInt(JobsTableFields.userid.getCollumn()); List<JobsDAOData> ls = map.get(id); if (ls == null) ls = new ArrayList<>(); int jobId = res.getInt(JobsTableFields.jobid.getCollumn()); if (jobId == 0) { ls.add(new JobsDAOData(res.getString(JobsTableFields.job.getCollumn()), res.getInt(JobsTableFields.level.getCollumn()), res.getDouble(JobsTableFields.experience.getCollumn()))); converted = false; } else { // This should be removed when we switch over to id only method if (converted && res.getString(JobsTableFields.job.getCollumn()) == null || res.getString(JobsTableFields.job.getCollumn()).isEmpty()) converted = false; Job job = Jobs.getJob(jobId); if (job != null) { ls.add(new JobsDAOData(job.getName(), res.getInt(JobsTableFields.level.getCollumn()), res.getDouble(JobsTableFields.experience.getCollumn()))); } } map.put(id, ls); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return map; } public Map<Integer, PlayerPoints> getAllPoints() { Map<Integer, PlayerPoints> map = new HashMap<>(); JobsConnection conn = getConnection(); if (conn == null) return map; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + DBTables.PointsTable.getTableName() + "`;"); res = prest.executeQuery(); while (res.next()) { map.put(res.getInt(PointsTableFields.userid.getCollumn()), new PlayerPoints(res.getDouble(PointsTableFields.currentpoints.getCollumn()), res.getDouble(PointsTableFields.totalpoints .getCollumn()))); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return map; } public PlayerPoints getPlayerPoints(JobsPlayer player) { PlayerPoints points = new PlayerPoints(); JobsConnection conn = getConnection(); if (conn == null) return points; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + DBTables.PointsTable.getTableName() + "` WHERE `" + PointsTableFields.userid.getCollumn() + "` = ?;"); prest.setInt(1, player.getUserId()); res = prest.executeQuery(); while (res.next()) { points = new PlayerPoints(res.getDouble(PointsTableFields.currentpoints.getCollumn()), res.getDouble(PointsTableFields.totalpoints.getCollumn())); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return points; } public Map<Integer, ArchivedJobs> getAllArchivedJobs() { Map<Integer, ArchivedJobs> map = new HashMap<>(); JobsConnection conn = getConnection(); if (conn == null) return map; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + DBTables.ArchiveTable.getTableName() + "`;"); res = prest.executeQuery(); while (res.next()) { int id = res.getInt(ArchiveTableFields.userid.getCollumn()); String jobName = res.getString(ArchiveTableFields.job.getCollumn()); Double exp = res.getDouble(ArchiveTableFields.experience.getCollumn()); int lvl = res.getInt(ArchiveTableFields.level.getCollumn()); Long left = res.getLong(ArchiveTableFields.left.getCollumn()); int jobid = res.getInt(ArchiveTableFields.jobid.getCollumn()); Job job = null; if (jobid != 0) { job = Jobs.getJob(jobid); } else { job = Jobs.getJob(jobName); converted = false; } if (job == null) continue; ArchivedJobs m = map.get(id); if (m == null) m = new ArchivedJobs(); JobProgression jp = new JobProgression(job, null, lvl, exp); if (left != 0L) jp.setLeftOn(left); m.addArchivedJob(jp); map.put(id, m); } } catch (Exception e) { close(res); close(prest); } finally { close(res); close(prest); } return map; } public ArchivedJobs getArchivedJobs(JobsPlayer player) { ArchivedJobs jobs = new ArchivedJobs(); JobsConnection conn = getConnection(); if (conn == null || player == null) return jobs; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + DBTables.ArchiveTable.getTableName() + "` WHERE `" + ArchiveTableFields.userid.getCollumn() + "` = ?;"); prest.setInt(1, player.getUserId()); res = prest.executeQuery(); while (res.next()) { String jobName = res.getString(ArchiveTableFields.job.getCollumn()); double exp = res.getDouble(ArchiveTableFields.experience.getCollumn()); int lvl = res.getInt(ArchiveTableFields.level.getCollumn()); Long left = res.getLong(ArchiveTableFields.left.getCollumn()); int jobid = res.getInt(ArchiveTableFields.jobid.getCollumn()); Job job = null; if (jobid != 0) { job = Jobs.getJob(jobid); } else { job = Jobs.getJob(jobName); } if (job == null) continue; JobProgression jp = new JobProgression(job, player, lvl, exp); if (left != 0L) jp.setLeftOn(left); jobs.addArchivedJob(jp); } } catch (Exception e) { close(res); close(prest); } finally { close(res); close(prest); } return jobs; } public Map<Integer, Map<String, Log>> getAllLogs() { Map<Integer, Map<String, Log>> map = new HashMap<>(); JobsConnection conn = getConnection(); if (conn == null) return map; PreparedStatement prest = null; ResultSet res = null; try { int time = TimeManage.timeInInt(); prest = conn.prepareStatement("SELECT * FROM `" + DBTables.LogTable.getTableName() + "` WHERE `" + LogTableFields.time.getCollumn() + "` = ? ;"); prest.setInt(1, time); res = prest.executeQuery(); while (res.next()) { int id = res.getInt(LogTableFields.userid.getCollumn()); String action = res.getString(LogTableFields.action.getCollumn()); Map<String, Log> m = map.getOrDefault(id, new HashMap<>()); Log log = m.getOrDefault(action, new Log(action)); Map<CurrencyType, Double> amounts = new HashMap<>(); amounts.put(CurrencyType.MONEY, res.getDouble(LogTableFields.money.getCollumn())); amounts.put(CurrencyType.EXP, res.getDouble(LogTableFields.exp.getCollumn())); amounts.put(CurrencyType.POINTS, res.getDouble(LogTableFields.points.getCollumn())); log.add(res.getString(LogTableFields.itemname.getCollumn()), res.getInt(LogTableFields.count.getCollumn()), amounts); m.put(action, log); map.put(id, m); // Jobs.getLoging().loadToLog(player, res.getString("action"), res.getString("itemname"), res.getInt("count"), res.getDouble("money"), res.getDouble("exp")); } } catch (Exception e) { close(res); close(prest); } finally { close(res); close(prest); } return map; } public void cleanUsers() { if (!Jobs.getGCManager().DBCleaningUsersUse) return; JobsConnection conn = getConnection(); if (conn == null) return; Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -Jobs.getGCManager().DBCleaningUsersDays); long mark = cal.getTimeInMillis(); PreparedStatement prest = null; try { prest = conn.prepareStatement("DELETE FROM `" + DBTables.UsersTable.getTableName() + "` WHERE `" + UserTableFields.seen.getCollumn() + "` < ?;"); prest.setLong(1, mark); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } public void cleanJobs() { if (!Jobs.getGCManager().DBCleaningJobsUse) return; JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { prest = conn.prepareStatement("DELETE FROM `" + getJobsTableName() + "` WHERE `" + JobsTableFields.level.getCollumn() + "` <= ?;"); prest.setInt(1, Jobs.getGCManager().DBCleaningJobsLvl); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } public void recordNewPlayer(Player player) { recordNewPlayer(player.getName(), player.getUniqueId()); } public void recordNewPlayer(String playerName, UUID uuid) { JobsConnection conn = getConnection(); if (conn == null) return; // Checking possible record in database to avoid duplicates PlayerInfo info = loadPlayerData(uuid); if (info != null) { Jobs.getPlayerManager().addPlayerToMap(info); return; } PreparedStatement prestt = null; ResultSet res2 = null; try { prestt = conn.prepareStatement("INSERT INTO `" + DBTables.UsersTable.getTableName() + "` (`" + UserTableFields.player_uuid.getCollumn() + "`, `" + UserTableFields.username.getCollumn() + "`, `" + UserTableFields.seen.getCollumn() + "`, `" + UserTableFields.donequests.getCollumn() + "`) VALUES (?, ?, ?, ?);", Statement.RETURN_GENERATED_KEYS); prestt.setString(1, uuid.toString()); prestt.setString(2, playerName); prestt.setLong(3, System.currentTimeMillis()); prestt.setInt(4, 0); prestt.execute(); res2 = prestt.getGeneratedKeys(); Jobs.getPlayerManager().addPlayerToMap(new PlayerInfo(playerName, res2.next() ? res2.getInt(1) : 0, uuid, System.currentTimeMillis(), 0)); } catch (SQLException e) { e.printStackTrace(); } finally { close(prestt); close(res2); } } public void recordNewWorld(String worldName) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prestt = null; ResultSet res2 = null; try { prestt = conn.prepareStatement("INSERT INTO `" + DBTables.WorldTable.getTableName() + "` (`" + worldsTableFields.name.getCollumn() + "`) VALUES (?);", Statement.RETURN_GENERATED_KEYS); prestt.setString(1, worldName); prestt.executeUpdate(); res2 = prestt.getGeneratedKeys(); Util.addJobsWorld(new JobsWorld(worldName, res2.next() ? res2.getInt(1) : 0)); } catch (SQLException e) { e.printStackTrace(); } finally { close(prestt); close(res2); } } public void recordNewWorld(String worldName, int id) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prestt = null; ResultSet res2 = null; try { prestt = conn.prepareStatement("INSERT INTO `" + DBTables.WorldTable.getTableName() + "` (`id`,`" + worldsTableFields.name.getCollumn() + "`) VALUES (?,?);", Statement.RETURN_GENERATED_KEYS); prestt.setInt(1, id); prestt.setString(2, worldName); prestt.executeUpdate(); res2 = prestt.getGeneratedKeys(); Util.addJobsWorld(new JobsWorld(worldName, res2.next() ? res2.getInt(1) : 0)); } catch (SQLException e) { e.printStackTrace(); } finally { close(prestt); close(res2); } } public synchronized void loadAllJobsWorlds() { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + DBTables.WorldTable.getTableName() + "`;"); res = prest.executeQuery(); while (res.next()) { int id = res.getInt("id"); String name = res.getString(worldsTableFields.name.getCollumn()); Util.addJobsWorld(new JobsWorld(name, id)); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } for (World one : Bukkit.getWorlds()) { if (Util.getJobsWorld(one.getName()) == null) recordNewWorld(one.getName()); } } private boolean converted = true; public void triggerTableIdUpdate() { // Lets convert old fields if (!converted) { Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> { Jobs.consoleMsg("&6[Jobs] Converting to new database format"); convertID(); Jobs.consoleMsg("&6[Jobs] Converted to new database format"); converted = true; }, 60L); } } private void convertID() { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement exploreStatement = null; try { exploreStatement = conn.prepareStatement("UPDATE `" + DBTables.ExploreDataTable.getTableName() + "` SET `" + ExploreDataTableFields.worldid.getCollumn() + "` = ? WHERE `" + ExploreDataTableFields.worldname.getCollumn() + "` = ?;"); for (JobsWorld jobsWorld : Util.getJobsWorlds().values()) { exploreStatement.setInt(1, jobsWorld.getId()); exploreStatement.setString(2, jobsWorld.getName()); exploreStatement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { close(exploreStatement); } PreparedStatement exploreStatementBack = null; try { exploreStatementBack = conn.prepareStatement("UPDATE `" + DBTables.ExploreDataTable.getTableName() + "` SET `" + ExploreDataTableFields.worldname.getCollumn() + "` = ? WHERE `" + ExploreDataTableFields.worldid.getCollumn() + "` = ?;"); for (JobsWorld jobsWorld : Util.getJobsWorlds().values()) { exploreStatementBack.setString(1, jobsWorld.getName()); exploreStatementBack.setInt(2, jobsWorld.getId()); exploreStatementBack.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { close(exploreStatementBack); } PreparedStatement bpStatement = null; try { bpStatement = conn.prepareStatement("UPDATE `" + DBTables.BlocksTable.getTableName() + "` SET `" + BlockTableFields.worldid.getCollumn() + "` = ? WHERE `" + BlockTableFields.world .getCollumn() + "` = ?;"); for (JobsWorld jobsWorld : Util.getJobsWorlds().values()) { bpStatement.setInt(1, jobsWorld.getId()); bpStatement.setString(2, jobsWorld.getName()); bpStatement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { close(bpStatement); } PreparedStatement bpStatementback = null; try { bpStatementback = conn.prepareStatement("UPDATE `" + DBTables.BlocksTable.getTableName() + "` SET `" + BlockTableFields.world.getCollumn() + "` = ? WHERE `" + BlockTableFields.worldid .getCollumn() + "` = ?;"); for (JobsWorld jobsWorld : Util.getJobsWorlds().values()) { bpStatementback.setString(1, jobsWorld.getName()); bpStatementback.setInt(2, jobsWorld.getId()); bpStatementback.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { close(bpStatementback); } PreparedStatement archiveStatement = null; try { archiveStatement = conn.prepareStatement("UPDATE `" + DBTables.ArchiveTable.getTableName() + "` SET `" + ArchiveTableFields.jobid.getCollumn() + "` = ? WHERE `" + ArchiveTableFields.job .getCollumn() + "` = ?;"); for (Job job : Jobs.getJobs()) { archiveStatement.setInt(1, job.getId()); archiveStatement.setString(2, job.getName()); archiveStatement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { close(archiveStatement); } PreparedStatement archiveStatementBack = null; try { archiveStatementBack = conn.prepareStatement("UPDATE `" + DBTables.ArchiveTable.getTableName() + "` SET `" + ArchiveTableFields.job.getCollumn() + "` = ? WHERE `" + ArchiveTableFields.jobid .getCollumn() + "` = ?;"); for (Job job : Jobs.getJobs()) { archiveStatementBack.setString(1, job.getName()); archiveStatementBack.setInt(2, job.getId()); archiveStatementBack.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { close(archiveStatementBack); } PreparedStatement usersStatement = null; try { usersStatement = conn.prepareStatement("UPDATE `" + getJobsTableName() + "` SET `" + JobsTableFields.jobid.getCollumn() + "` = ? WHERE `" + JobsTableFields.job.getCollumn() + "` = ?;"); for (Job job : Jobs.getJobs()) { usersStatement.setInt(1, job.getId()); usersStatement.setString(2, job.getName()); usersStatement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { close(usersStatement); } PreparedStatement usersStatementBack = null; try { usersStatementBack = conn.prepareStatement("UPDATE `" + getJobsTableName() + "` SET `" + JobsTableFields.job.getCollumn() + "` = ? WHERE `" + JobsTableFields.jobid.getCollumn() + "` = ?;"); for (Job job : Jobs.getJobs()) { usersStatementBack.setString(1, job.getName()); usersStatementBack.setInt(2, job.getId()); usersStatementBack.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { close(usersStatementBack); } PreparedStatement limitsStatement = null; try { limitsStatement = conn.prepareStatement("UPDATE `" + DBTables.LimitsTable.getTableName() + "` SET `" + LimitTableFields.typeid.getCollumn() + "` = ? WHERE `" + LimitTableFields.type .getCollumn() + "` = ?;"); for (CurrencyType type : CurrencyType.values()) { limitsStatement.setInt(1, type.getId()); limitsStatement.setString(2, type.getName()); limitsStatement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { close(limitsStatement); } PreparedStatement limitsStatementBack = null; try { limitsStatementBack = conn.prepareStatement("UPDATE `" + DBTables.LimitsTable.getTableName() + "` SET `" + LimitTableFields.type.getCollumn() + "` = ? WHERE `" + LimitTableFields.typeid .getCollumn() + "` = ?;"); for (CurrencyType type : CurrencyType.values()) { limitsStatementBack.setString(1, type.getName()); limitsStatementBack.setInt(2, type.getId()); limitsStatementBack.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { close(limitsStatementBack); } } public void recordNewJobName(Job job) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prestt = null; ResultSet res2 = null; try { conn.setAutoCommit(false); prestt = conn.prepareStatement("INSERT INTO `" + DBTables.JobNameTable.getTableName() + "` (`" + jobsNameTableFields.name.getCollumn() + "`) VALUES (?);", Statement.RETURN_GENERATED_KEYS); prestt.setString(1, job.getName()); int rowAffected = prestt.executeUpdate(); res2 = prestt.getGeneratedKeys(); job.setId(res2.next() ? res2.getInt(1) : 0); if (rowAffected != 1) { conn.getConnection().rollback(); } conn.commit(); } catch (SQLException e) { } finally { close(prestt); close(res2); } } public void recordNewJobName(Job job, int id) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prestt = null; ResultSet res2 = null; try { conn.setAutoCommit(false); prestt = conn.prepareStatement("INSERT INTO `" + DBTables.JobNameTable.getTableName() + "` (`id`,`" + jobsNameTableFields.name.getCollumn() + "`) VALUES (?,?);", Statement.RETURN_GENERATED_KEYS); prestt.setInt(1, id); prestt.setString(2, job.getName()); int rowAffected = prestt.executeUpdate(); res2 = prestt.getGeneratedKeys(); job.setId(res2.next() ? res2.getInt(1) : 0); if (rowAffected != 1) { conn.getConnection().rollback(); } conn.commit(); } catch (SQLException e) { } finally { close(prestt); close(res2); } } public synchronized void loadAllJobsNames() { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + DBTables.JobNameTable.getTableName() + "`;"); res = prest.executeQuery(); while (res.next()) { int id = res.getInt("id"); String name = res.getString(worldsTableFields.name.getCollumn()); Job job = Jobs.getJob(name); if (job != null) { if (job.getId() == 0) job.setId(id); else { // Prioritizing id which matches actual job name and not full name which can be different if (job.getName().equals(name)) { job.setLegacyId(job.getId()); job.setId(id); } else job.setLegacyId(id); } } } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } for (Job one : Jobs.getJobs()) { if (one.getId() == 0) recordNewJobName(one); } } /** * Get player count for a job. * @param JobName - the job name * @return amount of player currently working. */ public synchronized int getTotalPlayerAmountByJobName(String JobName) { JobsConnection conn = getConnection(); if (conn == null) return 0; int count = 0; PreparedStatement prest = null; ResultSet res = null; try { Job job = Jobs.getJob(JobName); if (job != null && job.getId() != 0) { prest = conn.prepareStatement("SELECT COUNT(*) FROM `" + getJobsTableName() + "` WHERE `" + JobsTableFields.jobid + "` = ?;"); prest.setInt(1, job.getId()); res = prest.executeQuery(); if (res.next()) { count += res.getInt(1); } } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return count; } /** * Get player count for a job. * @return total amount of player currently working. */ public synchronized int getTotalPlayers() { int total = 0; for (Job one : Jobs.getJobs()) { total += one.getTotalPlayers(); } return total; } /** * Get all jobs the player is part of. * @param userName - the player being searched for * @return list of all of the names of the jobs the players are part of. */ public synchronized List<JobsDAOData> getAllJobsOffline2(String userName) { List<JobsDAOData> jobs = new ArrayList<>(); PlayerInfo info = Jobs.getPlayerManager().getPlayerInfo(userName); if (info == null) return jobs; JobsConnection conn = getConnection(); if (conn == null) return jobs; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + getJobsTableName() + "` WHERE `" + JobsTableFields.userid.getCollumn() + "` = ?;"); prest.setInt(1, info.getID()); res = prest.executeQuery(); while (res.next()) { int jobId = res.getInt(JobsTableFields.jobid.getCollumn()); if (jobId == 0) { jobs.add(new JobsDAOData(res.getString(JobsTableFields.job.getCollumn()), res.getInt(JobsTableFields.level.getCollumn()), res.getDouble(JobsTableFields.experience.getCollumn()))); } else { Job job = Jobs.getJob(jobId); jobs.add(new JobsDAOData(job.getName(), res.getInt(JobsTableFields.level.getCollumn()), res.getDouble(JobsTableFields.experience.getCollumn()))); } } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return jobs; } public synchronized void recordPlayersLimits(JobsPlayer jPlayer) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest2 = null; try { prest2 = conn.prepareStatement("DELETE FROM `" + DBTables.LimitsTable.getTableName() + "` WHERE `" + LimitTableFields.userid.getCollumn() + "` = ?;"); prest2.setInt(1, jPlayer.getUserId()); prest2.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest2); } PaymentData limit = jPlayer.getPaymentLimit(); if (limit == null) return; PreparedStatement prest = null; try { prest = conn.prepareStatement("INSERT INTO `" + DBTables.LimitsTable.getTableName() + "` (`" + LimitTableFields.userid.getCollumn() + "`, `" + LimitTableFields.typeid.getCollumn() + "`, `" + LimitTableFields.collected.getCollumn() + "`, `" + LimitTableFields.started.getCollumn() + "`, `" + LimitTableFields.type.getCollumn() + "`) VALUES (?, ?, ?, ?, ?);"); conn.setAutoCommit(false); for (CurrencyType type : CurrencyType.values()) { if (limit.getAmount(type) == 0D || limit.getLeftTime(type) < 0) continue; prest.setInt(1, jPlayer.getUserId()); prest.setInt(2, type.getId()); prest.setDouble(3, limit.getAmount(type)); prest.setLong(4, limit.getTime(type)); prest.setString(5, type.toString()); prest.addBatch(); } prest.executeBatch(); conn.commit(); } catch (Exception e) { e.printStackTrace(); } finally { close(prest); try { conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } } public synchronized PaymentData getPlayersLimits(JobsPlayer jPlayer) { PaymentData data = new PaymentData(); JobsConnection conn = getConnection(); if (conn == null) return data; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + DBTables.LimitsTable.getTableName() + "` WHERE `" + LimitTableFields.userid.getCollumn() + "` = ?;"); prest.setInt(1, jPlayer.getUserId()); res = prest.executeQuery(); while (res.next()) { String typeName = res.getString(LimitTableFields.type.getCollumn()); int typeId = res.getInt(LimitTableFields.typeid.getCollumn()); CurrencyType type = typeId != 0 ? CurrencyType.get(typeId) : CurrencyType.getByName(typeName); if (type != null) data.addNewAmount(type, res.getDouble(LimitTableFields.collected.getCollumn()), res.getLong(LimitTableFields.started.getCollumn())); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return data; } public synchronized Map<Integer, PaymentData> loadPlayerLimits() { Map<Integer, PaymentData> map = new HashMap<>(); JobsConnection conn = getConnection(); if (conn == null) return map; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + DBTables.LimitsTable.getTableName() + "`;"); res = prest.executeQuery(); while (res.next()) { int id = res.getInt(LimitTableFields.userid.getCollumn()); PaymentData data = map.getOrDefault(id, new PaymentData()); String typeName = res.getString(LimitTableFields.type.getCollumn()); int typeId = res.getInt(LimitTableFields.typeid.getCollumn()); CurrencyType type = null; if (typeId != 0) type = CurrencyType.get(typeId); else type = CurrencyType.getByName(typeName); if (type == null) continue; data.addNewAmount(type, res.getDouble(LimitTableFields.collected.getCollumn()), res.getLong(LimitTableFields.started.getCollumn())); map.put(id, data); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return map; } /** * Join a job (create player-job entry from storage) * @param player - player that wishes to join the job * @param job - job that the player wishes to join */ public synchronized void joinJob(JobsPlayer jPlayer, JobProgression job) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { prest = conn.prepareStatement("INSERT INTO `" + getJobsTableName() + "` (`" + JobsTableFields.userid.getCollumn() + "`, `" + JobsTableFields.jobid.getCollumn() + "`, `" + JobsTableFields.level.getCollumn() + "`, `" + JobsTableFields.experience.getCollumn() + "`, `" + JobsTableFields.job.getCollumn() + "`) VALUES (?, ?, ?, ?, ?);"); prest.setInt(1, jPlayer.getUserId()); prest.setInt(2, job.getJob().getId()); prest.setInt(3, job.getLevel()); prest.setDouble(4, job.getExperience()); prest.setString(5, job.getJob().getName()); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } /** * Join a job (create player-job entry from storage) * @param player - player that wishes to join the job * @param job - job that the player wishes to join */ public synchronized void insertJob(JobsPlayer jPlayer, JobProgression prog) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { double exp = prog.getExperience(); if (exp < 0) exp = 0; prest = conn.prepareStatement("INSERT INTO `" + getJobsTableName() + "` (`" + JobsTableFields.userid.getCollumn() + "`, `" + JobsTableFields.jobid.getCollumn() + "`, `" + JobsTableFields.level.getCollumn() + "`, `" + JobsTableFields.experience.getCollumn() + "`, `" + JobsTableFields.job.getCollumn() + "`) VALUES (?, ?, ?, ?, ?);"); prest.setInt(1, jPlayer.getUserId()); prest.setInt(2, prog.getJob().getId()); prest.setInt(3, prog.getLevel()); prest.setDouble(4, exp); prest.setString(5, prog.getJob().getName()); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } /** * Join a job (create player-job entry from storage) * @param player - player that wishes to join the job * @param job - job that the player wishes to join * @throws SQLException */ public List<Convert> convertDatabase() throws SQLException { List<Convert> list = new ArrayList<>(); JobsConnection conn = getConnection(); if (conn == null) return list; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + DBTables.ArchiveTable.getTableName() + "`"); res = prest.executeQuery(); while (res.next()) { int id = res.getInt(ArchiveTableFields.userid.getCollumn()); PlayerInfo pi = Jobs.getPlayerManager().getPlayerInfo(id); if (pi == null) continue; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(pi.getUuid()); if (jPlayer == null) continue; String jobName = res.getString(ArchiveTableFields.job.getCollumn()); int jobid = res.getInt(ArchiveTableFields.jobid.getCollumn()); Job job = jobid != 0 ? Jobs.getJob(jobid) : Jobs.getJob(jobName); if (job == null) continue; list.add(new Convert(res.getInt("id"), jPlayer.getUniqueId(), job.getId(), res.getInt(ArchiveTableFields.level.getCollumn()), res.getInt(ArchiveTableFields.experience.getCollumn()))); } } finally { close(res); close(prest); } conn.closeConnection(); return list; } public void continueConvertions(List<Convert> list) throws SQLException { JobsConnection conns = getConnection(); if (conns == null) return; PreparedStatement insert = null; Statement statement = null; int i = list.size(); try { statement = conns.createStatement(); if (Jobs.getDBManager().getDbType() == DataBaseType.MySQL) { statement.executeUpdate("TRUNCATE TABLE `" + DBTables.ArchiveTable.getTableName() + "`"); } else { statement.executeUpdate("DELETE from `" + DBTables.ArchiveTable.getTableName() + "`"); } insert = conns.prepareStatement("INSERT INTO `" + DBTables.ArchiveTable.getTableName() + "` (`" + ArchiveTableFields.userid.getCollumn() + "`, `" + ArchiveTableFields.jobid.getCollumn() + "`, `" + ArchiveTableFields.level.getCollumn() + "`, `" + ArchiveTableFields.experience.getCollumn() + "`, `" + ArchiveTableFields.job.getCollumn() + "`) VALUES (?, ?, ?, ?, ?);"); conns.setAutoCommit(false); while (i > 0) { i Convert convertData = list.get(i); JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(convertData.getUserUUID()); Job job = Jobs.getJob(convertData.getJobId()); insert.setInt(1, jPlayer != null ? jPlayer.getUserId() : -1); insert.setInt(2, convertData.getJobId()); insert.setInt(3, convertData.getLevel()); insert.setInt(4, convertData.getExp()); insert.setString(5, job != null ? job.getName() : ""); insert.addBatch(); } insert.executeBatch(); conns.commit(); conns.setAutoCommit(true); } finally { close(statement); close(insert); try { conns.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } } /** * Quit a job (delete player-job entry from storage) * @param player - player that wishes to quit the job * @param job - job that the player wishes to quit */ public synchronized boolean quitJob(JobsPlayer jPlayer, Job job) { JobsConnection conn = getConnection(); if (conn == null) return false; PreparedStatement prest = null; boolean done = true; try { prest = conn.prepareStatement("DELETE FROM `" + getJobsTableName() + "` WHERE `" + JobsTableFields.userid.getCollumn() + "` = ? AND `" + JobsTableFields.jobid.getCollumn() + "` = ?;"); prest.setInt(1, jPlayer.getUserId()); prest.setInt(2, job.getId()); prest.execute(); } catch (SQLException e) { e.printStackTrace(); done = false; } finally { close(prest); } return done; } /** * Remove duplicated job by specific criteria */ public synchronized boolean removeSpecificJob(int userId, String jobName, String legacyName, int level, double exp) { JobsConnection conn = getConnection(); if (conn == null) return false; PreparedStatement prest = null; boolean done = true; try { prest = conn.prepareStatement("DELETE FROM `" + getJobsTableName() + "` WHERE `" + JobsTableFields.userid.getCollumn() + "` = ? AND (`" + JobsTableFields.job.getCollumn() + "` = ? OR `" + JobsTableFields.job.getCollumn() + "` = ?) AND `" + JobsTableFields.level.getCollumn() + "` = ? AND `" + JobsTableFields.experience.getCollumn() + "` = ?;"); prest.setInt(1, userId); prest.setString(2, jobName); prest.setString(3, legacyName); prest.setInt(4, level); prest.setDouble(5, exp); prest.execute(); } catch (SQLException e) { e.printStackTrace(); done = false; } finally { close(prest); } return done; } /** * Record job to archive * @param player - player that wishes to quit the job * @param job - job that the player wishes to quit */ public void recordToArchive(JobsPlayer jPlayer, Job job) { JobProgression jp = jPlayer.getJobProgression(job); if (jp == null) return; jp.setLeftOn(System.currentTimeMillis()); jPlayer.getArchivedJobs().addArchivedJob(jp); JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { Double exp = jp.getExperience(); prest = conn.prepareStatement("INSERT INTO `" + DBTables.ArchiveTable.getTableName() + "` (`" + ArchiveTableFields.userid.getCollumn() + "`, `" + ArchiveTableFields.jobid.getCollumn() + "`, `" + ArchiveTableFields.level.getCollumn() + "`, `" + ArchiveTableFields.experience.getCollumn() + "`, `" + ArchiveTableFields.left.getCollumn() + "`, `" + ArchiveTableFields.job.getCollumn() + "`) VALUES (?, ?, ?, ?, ?, ?);"); prest.setInt(1, jPlayer.getUserId()); prest.setInt(2, job.getId()); prest.setInt(3, jp.getLevel()); prest.setInt(4, exp.intValue()); prest.setLong(5, System.currentTimeMillis()); prest.setString(6, job.getName()); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } public List<TopList> getGlobalTopList() { return getGlobalTopList(0); } /** * Get player list by total job level * @param start - starting entry * @return info - information about jobs */ public List<TopList> getGlobalTopList(int start) { JobsConnection conn = getConnection(); List<TopList> names = new ArrayList<>(); if (conn == null) return names; if (start < 0) { start = 0; } int jobsTopAmount = Jobs.getGCManager().JobsTopAmount * 2; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT " + JobsTableFields.userid.getCollumn() + ", COUNT(*) AS amount, sum(" + JobsTableFields.level.getCollumn() + ") AS totallvl, sum(" + JobsTableFields.experience.getCollumn() + ") AS totalexp FROM `" + getJobsTableName() + "` GROUP BY userid ORDER BY totallvl DESC, totalexp DESC LIMIT " + start + "," + jobsTopAmount + ";"); res = prest.executeQuery(); while (res.next()) { PlayerInfo info = Jobs.getPlayerManager().getPlayerInfo(res.getInt(JobsTableFields.userid.getCollumn())); if (info == null) continue; names.add(new TopList(info, res.getInt("totallvl"), res.getInt("totalexp"))); if (names.size() >= jobsTopAmount) break; } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return names; } /** * Get players by quests done * @param start - starting entry * @param size - max count of entries * @return info - information about jobs */ public List<TopList> getQuestTopList(int start) { JobsConnection conn = getConnection(); List<TopList> names = new ArrayList<>(); if (conn == null) return names; if (start < 0) { start = 0; } PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT `id`, `" + UserTableFields.player_uuid.getCollumn() + "`, `" + UserTableFields.donequests.getCollumn() + "` FROM `" + DBTables.UsersTable.getTableName() + "` ORDER BY `" + UserTableFields.donequests.getCollumn() + "` DESC, LOWER(" + UserTableFields.seen.getCollumn() + ") DESC LIMIT " + start + ", 30;"); res = prest.executeQuery(); while (res.next()) { PlayerInfo info = Jobs.getPlayerManager().getPlayerInfo(res.getInt("id")); if (info == null) continue; names.add(new TopList(info, res.getInt(UserTableFields.donequests.getCollumn()), 0)); if (names.size() >= Jobs.getGCManager().JobsTopAmount) break; } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return names; } public PlayerInfo loadPlayerData(UUID uuid) { JobsConnection conn = getConnection(); if (conn == null) return null; PlayerInfo pInfo = null; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + DBTables.UsersTable.getTableName() + "` WHERE `" + UserTableFields.player_uuid.getCollumn() + "` = ?;"); prest.setString(1, uuid.toString()); res = prest.executeQuery(); while (res.next()) { pInfo = new PlayerInfo( res.getString(UserTableFields.username.getCollumn()), res.getInt("id"), uuid, res.getLong(UserTableFields.seen.getCollumn()), res.getInt(UserTableFields.donequests.getCollumn()), res.getString(UserTableFields.quests.getCollumn())); Jobs.getPlayerManager().addPlayerToMap(pInfo); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return pInfo; } public void loadPlayerData() { Jobs.getPlayerManager().clearMaps(); JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + DBTables.UsersTable.getTableName() + "`;"); res = prest.executeQuery(); List<String> uuids = new ArrayList<>(); while (res.next()) { String uuid = res.getString(UserTableFields.player_uuid.getCollumn()); if (uuid == null || uuid.isEmpty()) { uuids.add(uuid); continue; } long seen = res.getLong(UserTableFields.seen.getCollumn()); try { Jobs.getPlayerManager().addPlayerToMap(new PlayerInfo( res.getString(UserTableFields.username.getCollumn()), res.getInt("id"), UUID.fromString(uuid), seen, res.getInt(UserTableFields.donequests.getCollumn()), res.getString(UserTableFields.quests.getCollumn()))); } catch (IllegalArgumentException e) { } } for (String u : uuids) { PreparedStatement ps = conn.prepareStatement("DELETE FROM `" + DBTables.UsersTable.getTableName() + "` WHERE `" + UserTableFields.player_uuid.getCollumn() + "` = ?;"); ps.setString(1, u); ps.execute(); close(ps); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } } public JobsPlayer loadFromDao(JobsPlayer jPlayer) { List<JobsDAOData> list = getAllJobs(jPlayer.getName(), jPlayer.getUniqueId()); jPlayer.progression.clear(); for (JobsDAOData jobdata : list) { if (!plugin.isEnabled()) return null; // add the job Job job = Jobs.getJob(jobdata.getJobName()); if (job != null) jPlayer.progression.add(new JobProgression(job, jPlayer, jobdata.getLevel(), jobdata.getExperience())); } jPlayer.reloadMaxExperience(); jPlayer.reloadLimits(); jPlayer.setUserId(Jobs.getPlayerManager().getPlayerId(jPlayer.getUniqueId())); return jPlayer; } public JobsPlayer loadFromDao(OfflinePlayer player) { JobsPlayer jPlayer = new JobsPlayer(player); return loadFromDao(jPlayer); } /** * Delete job from archive * @param player - player that wishes to quit the job * @param job - job that the player wishes to quit */ public synchronized void deleteArchive(JobsPlayer jPlayer, Job job) { jPlayer.getArchivedJobs().removeArchivedJob(job); JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { prest = conn.prepareStatement("DELETE FROM `" + DBTables.ArchiveTable.getTableName() + "` WHERE `" + ArchiveTableFields.userid.getCollumn() + "` = ? AND `" + ArchiveTableFields.jobid .getCollumn() + "` = ?;"); prest.setInt(1, jPlayer.getUserId()); prest.setInt(2, job.getId()); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } /** * Save player-job information * @param jobInfo - the information getting saved */ public void save(JobsPlayer player) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { prest = conn.prepareStatement("UPDATE `" + getJobsTableName() + "` SET `" + JobsTableFields.level.getCollumn() + "` = ?, `" + JobsTableFields.experience.getCollumn() + "` = ? WHERE `" + JobsTableFields.userid.getCollumn() + "` = ? AND `" + JobsTableFields.jobid.getCollumn() + "` = ? " + "OR `" + JobsTableFields.userid.getCollumn() + "` = ? AND `" + JobsTableFields.jobid.getCollumn() + "` = ?;"); for (JobProgression progression : player.getJobProgression()) { prest.setInt(1, progression.getLevel()); prest.setDouble(2, progression.getExperience()); prest.setInt(3, player.getUserId()); prest.setInt(4, progression.getJob().getId()); prest.setInt(5, player.getUserId()); prest.setInt(6, progression.getJob().getLegacyId()); prest.execute(); } } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } public void updateSeen(JobsPlayer player) { if (player.getUserId() == -1) { insertPlayer(player); return; } JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { prest = conn.prepareStatement("UPDATE `" + DBTables.UsersTable.getTableName() + "` SET `" + UserTableFields.seen.getCollumn() + "` = ?, `" + UserTableFields.username.getCollumn() + "` = ?, `" + UserTableFields.donequests.getCollumn() + "` = ?, `" + UserTableFields.quests.getCollumn() + "` = ? WHERE `id` = ?;"); prest.setLong(1, System.currentTimeMillis()); prest.setString(2, player.getName()); prest.setInt(3, player.getDoneQuests()); prest.setString(4, player.getQuestProgressionString()); prest.setInt(5, player.getUserId()); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } public void resetDoneQuests() { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { prest = conn.prepareStatement("UPDATE `" + DBTables.UsersTable.getTableName() + "` SET `" + UserTableFields.donequests.getCollumn() + "` = ?;"); prest.setInt(1, 0); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } private void insertPlayer(JobsPlayer player) { JobsConnection conn = getConnection(); if (conn == null) return; String uuid = player.getUniqueId().toString(); String name = player.getName(); PreparedStatement prestt = null; try { prestt = conn.prepareStatement("INSERT INTO `" + DBTables.UsersTable.getTableName() + "` (`" + UserTableFields.player_uuid.getCollumn() + "`, `" + UserTableFields.username.getCollumn() + "`, `" + UserTableFields.seen.getCollumn() + "`, `" + UserTableFields.donequests.getCollumn() + "`) VALUES (?, ?, ?, ?);"); prestt.setString(1, uuid); prestt.setString(2, name); prestt.setLong(3, player.getSeen()); prestt.setInt(4, 0); prestt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prestt); } PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT `id`, `" + UserTableFields.donequests.getCollumn() + "` FROM `" + DBTables.UsersTable.getTableName() + "` WHERE `" + UserTableFields.player_uuid.getCollumn() + "` = ?;"); prest.setString(1, uuid); res = prest.executeQuery(); if (res.next()) { int id = res.getInt("id"); player.setUserId(id); Jobs.getPlayerManager().addPlayerToMap(new PlayerInfo( name, id, player.getUniqueId(), player.getSeen(), res.getInt(UserTableFields.donequests.getCollumn()))); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } } public void savePoints(JobsPlayer jPlayer) { JobsConnection conn = getConnection(); if (conn == null) return; PlayerPoints pointInfo = jPlayer.getPointsData(); if (pointInfo.getDbId() == 0) { // This needs to exist, removing existing entry by user id unless we have actual line id PreparedStatement prest2 = null; try { prest2 = conn.prepareStatement("DELETE FROM `" + DBTables.PointsTable.getTableName() + "` WHERE `" + PointsTableFields.userid.getCollumn() + "` = ?;"); prest2.setInt(1, jPlayer.getUserId()); prest2.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest2); } PreparedStatement prest = null; try { prest = conn.prepareStatement("INSERT INTO `" + DBTables.PointsTable.getTableName() + "` (`" + PointsTableFields.totalpoints.getCollumn() + "`, `" + PointsTableFields.currentpoints .getCollumn() + "`, `" + PointsTableFields.userid.getCollumn() + "`) VALUES (?, ?, ?);"); prest.setDouble(1, pointInfo.getTotalPoints()); prest.setDouble(2, pointInfo.getCurrentPoints()); prest.setInt(3, jPlayer.getUserId()); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } else { PreparedStatement prest = null; try { prest = conn.prepareStatement("UPDATE `" + DBTables.PointsTable.getTableName() + "` SET `" + PointsTableFields.totalpoints.getCollumn() + "` = ?, `" + PointsTableFields.currentpoints.getCollumn() + "` = ? WHERE `id` = ?;"); prest.setDouble(1, pointInfo.getTotalPoints()); prest.setDouble(2, pointInfo.getCurrentPoints()); prest.setInt(3, pointInfo.getDbId()); prest.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); } } } public void loadPoints(JobsPlayer player) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT `" + PointsTableFields.totalpoints.getCollumn() + "`, `" + PointsTableFields.currentpoints.getCollumn() + "` FROM `" + DBTables.PointsTable.getTableName() + "` WHERE `" + PointsTableFields.userid.getCollumn() + "` = ?;"); prest.setInt(1, player.getUserId()); res = prest.executeQuery(); if (res.next()) { player.getPointsData().setDbId(res.getInt("id")); player.getPointsData().setPoints(res.getDouble(PointsTableFields.currentpoints.getCollumn())); player.getPointsData().setTotalPoints(res.getDouble(PointsTableFields.totalpoints.getCollumn())); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } } /** * Save player-job information * @param jobInfo - the information getting saved */ public void saveLog(JobsPlayer player) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest1 = null; PreparedStatement prest2 = null; try { conn.setAutoCommit(false); prest1 = conn.prepareStatement("UPDATE `" + DBTables.LogTable.getTableName() + "` SET `" + LogTableFields.count.getCollumn() + "` = ?, `" + LogTableFields.money.getCollumn() + "` = ?, `" + LogTableFields.exp.getCollumn() + "` = ?, `" + LogTableFields.points.getCollumn() + "` = ? WHERE `" + LogTableFields.userid.getCollumn() + "` = ? AND `" + LogTableFields.time.getCollumn() + "` = ? AND `" + LogTableFields.action.getCollumn() + "` = ? AND `" + LogTableFields.itemname.getCollumn() + "` = ?;"); boolean added = false; for (Log log : player.getLog().values()) { for (Entry<String, LogAmounts> one : log.getAmountList().entrySet()) { if (one.getValue().isNewEntry()) continue; prest1.setInt(1, one.getValue().getCount()); prest1.setDouble(2, one.getValue().get(CurrencyType.MONEY)); prest1.setDouble(3, one.getValue().get(CurrencyType.EXP)); prest1.setDouble(4, one.getValue().get(CurrencyType.POINTS)); prest1.setInt(5, player.getUserId()); prest1.setInt(6, log.getDate()); prest1.setString(7, log.getActionType()); prest1.setString(8, one.getKey()); // prest1.addBatch(); added = true; } } if (added) { prest1.execute(); conn.commit(); } added = false; prest2 = conn.prepareStatement("INSERT INTO `" + DBTables.LogTable.getTableName() + "` (`" + LogTableFields.userid.getCollumn() + "`, `" + LogTableFields.time.getCollumn() + "`, `" + LogTableFields.action.getCollumn() + "`, `" + LogTableFields.itemname.getCollumn() + "`, `" + LogTableFields.count.getCollumn() + "`, `" + LogTableFields.money.getCollumn() + "`, `" + LogTableFields.exp.getCollumn() + "`, `" + LogTableFields.points.getCollumn() + "`) VALUES (?, ?, ?, ?, ?, ?, ?, ?);"); for (Log log : player.getLog().values()) { for (Entry<String, LogAmounts> one : log.getAmountList().entrySet()) { if (!one.getValue().isNewEntry()) continue; one.getValue().setNewEntry(false); prest2.setInt(1, player.getUserId()); prest2.setInt(2, log.getDate()); prest2.setString(3, log.getActionType()); prest2.setString(4, one.getKey()); prest2.setInt(5, one.getValue().getCount()); prest2.setDouble(6, one.getValue().get(CurrencyType.MONEY)); prest2.setDouble(7, one.getValue().get(CurrencyType.EXP)); prest2.setDouble(8, one.getValue().get(CurrencyType.POINTS)); // prest2.addBatch(); added = true; } } if (added) { prest2.execute(); conn.commit(); } } catch (SQLException e) { e.printStackTrace(); close(prest1); close(prest2); } finally { close(prest1); close(prest2); try { conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } } /** * Save player-job information * @param jobInfo - the information getting saved */ public void loadLog(JobsPlayer player) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; ResultSet res = null; try { int time = TimeManage.timeInInt(); prest = conn.prepareStatement("SELECT * FROM `" + DBTables.LogTable.getTableName() + "` WHERE `" + LogTableFields.userid.getCollumn() + "` = ? AND `" + LogTableFields.time.getCollumn() + "` = ? ;"); prest.setInt(1, player.getUserId()); prest.setInt(2, time); res = prest.executeQuery(); while (res.next()) { Map<CurrencyType, Double> amounts = new HashMap<>(); amounts.put(CurrencyType.MONEY, res.getDouble(LogTableFields.money.getCollumn())); amounts.put(CurrencyType.EXP, res.getDouble(LogTableFields.exp.getCollumn())); amounts.put(CurrencyType.POINTS, res.getDouble(LogTableFields.points.getCollumn())); Jobs.getLoging().loadToLog(player, res.getString(LogTableFields.action.getCollumn()), res.getString(LogTableFields.itemname.getCollumn()), res.getInt(LogTableFields.count.getCollumn()), amounts); } } catch (Exception e) { close(res); close(prest); drop(DBTables.LogTable.getTableName()); createDefaultTable(DBTables.LogTable); } finally { close(res); close(prest); } } /** * Save block protection information * @param jobBlockProtection - the information getting saved */ public void saveBlockProtection(String world, java.util.concurrent.ConcurrentMap<String, BlockProtection> concurrentHashMap) { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement insert = null; PreparedStatement update = null; PreparedStatement delete = null; try { conn.setAutoCommit(false); JobsWorld jobsWorld = Util.getJobsWorld(world); if (jobsWorld == null) return; int worldId = jobsWorld.getId(); if (worldId == 0) return; insert = conn.prepareStatement("INSERT INTO `" + DBTables.BlocksTable.getTableName() + "` (`" + BlockTableFields.worldid.getCollumn() + "`, `" + BlockTableFields.x.getCollumn() + "`, `" + BlockTableFields.y.getCollumn() + "`, `" + BlockTableFields.z.getCollumn() + "`, `" + BlockTableFields.recorded.getCollumn() + "`, `" + BlockTableFields.resets.getCollumn() + "`, `" + BlockTableFields.world.getCollumn() + "`) VALUES (?, ?, ?, ?, ?, ?, ?);"); update = conn.prepareStatement("UPDATE `" + DBTables.BlocksTable.getTableName() + "` SET `" + BlockTableFields.recorded.getCollumn() + "` = ?, `" + BlockTableFields.resets.getCollumn() + "` = ? WHERE `id` = ?;"); delete = conn.prepareStatement("DELETE from `" + DBTables.BlocksTable.getTableName() + "` WHERE `id` = ?;"); Long current = System.currentTimeMillis(); Long mark = System.currentTimeMillis() - (Jobs.getGCManager().BlockProtectionDays * 24L * 60L * 60L * 1000L); for (Entry<String, BlockProtection> block : concurrentHashMap.entrySet()) { if (block.getValue() == null) continue; switch (block.getValue().getAction()) { case DELETE: delete.setInt(1, block.getValue().getId()); delete.addBatch(); break; case INSERT: if (block.getValue().getTime() < current && block.getValue().getTime() != -1) continue; insert.setInt(1, worldId); insert.setInt(2, block.getValue().getX()); insert.setInt(3, block.getValue().getY()); insert.setInt(4, block.getValue().getZ()); insert.setLong(5, block.getValue().getRecorded()); insert.setLong(6, block.getValue().getTime()); insert.setString(7, world); insert.addBatch(); block.getValue().setAction(DBAction.NONE); break; case UPDATE: if (block.getValue().getTime() < current && block.getValue().getTime() != -1) continue; update.setLong(1, block.getValue().getRecorded()); update.setLong(2, block.getValue().getTime()); update.setInt(3, block.getValue().getId()); update.addBatch(); block.getValue().setAction(DBAction.NONE); break; case NONE: if (block.getValue().getTime() < current && block.getValue().getTime() != -1) continue; if (block.getValue().getTime() == -1 && block.getValue().getRecorded() > mark) continue; delete.setInt(1, block.getValue().getId()); delete.addBatch(); break; default: continue; } } insert.executeBatch(); update.executeBatch(); delete.executeBatch(); conn.commit(); } catch (SQLException e) { e.printStackTrace(); } finally { close(insert); close(update); close(delete); try { conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } } /** * Save block protection information * @param jobBlockProtection - the information getting saved */ public void loadBlockProtection() { JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; PreparedStatement prestDel = null; ResultSet res = null; long timer = System.currentTimeMillis(); try { long mark = System.currentTimeMillis() - (Jobs.getGCManager().BlockProtectionDays * 24L * 60L * 60L * 1000L); prestDel = conn.prepareStatement("DELETE FROM `" + DBTables.BlocksTable.getTableName() + "` WHERE `" + BlockTableFields.recorded.getCollumn() + "` < ? OR `" + BlockTableFields.resets.getCollumn() + "` < ? AND `" + BlockTableFields.resets.getCollumn() + "` > 0;"); prestDel.setLong(1, mark); prestDel.setLong(2, System.currentTimeMillis()); prestDel.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { close(prestDel); } try { prest = conn.prepareStatement("SELECT * FROM `" + DBTables.BlocksTable.getTableName() + "`;"); res = prest.executeQuery(); int i = 0; int ii = 0; while (res.next()) { String name = res.getString(BlockTableFields.world.getCollumn()); int worldId = res.getInt(BlockTableFields.worldid.getCollumn()); World world = null; if (worldId != 0) { JobsWorld jobsWorld = Util.getJobsWorld(worldId); if (jobsWorld != null) world = jobsWorld.getWorld(); } else { world = Bukkit.getWorld(name); } if (world == null) continue; int id = res.getInt("id"); int x = res.getInt(BlockTableFields.x.getCollumn()); int y = res.getInt(BlockTableFields.y.getCollumn()); int z = res.getInt(BlockTableFields.z.getCollumn()); long resets = res.getLong(BlockTableFields.resets.getCollumn()); Location loc = new Location(world, x, y, z); BlockProtection bp = Jobs.getBpManager().addP(loc, resets, true, false); bp.setId(id); bp.setRecorded(res.getLong(BlockTableFields.recorded.getCollumn())); bp.setAction(DBAction.NONE); i++; if (ii++ >= 100000) { Jobs.consoleMsg("&6[Jobs] Loading (" + i + ") BP"); ii = 0; } } if (i > 0) { Jobs.consoleMsg("&e[Jobs] Loaded " + i + " block protection entries. " + (System.currentTimeMillis() - timer) + "ms"); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } } /** * Save player-explore information */ public void saveExplore() { insertExplore(); updateExplore(); } public void insertExplore() { if (!Jobs.getExploreManager().isExploreEnabled()) return; JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest2 = null; try { prest2 = conn.prepareStatement("INSERT INTO `" + DBTables.ExploreDataTable.getTableName() + "` (`" + ExploreDataTableFields.worldid.getCollumn() + "`, `" + ExploreDataTableFields.chunkX.getCollumn() + "`, `" + ExploreDataTableFields.chunkZ.getCollumn() + "`, `" + ExploreDataTableFields.playerNames.getCollumn() + "`, `" + ExploreDataTableFields.worldname.getCollumn() + "`) VALUES (?, ?, ?, ?, ?);"); conn.setAutoCommit(false); int i = 0; Map<String, Map<String, ExploreRegion>> temp = new HashMap<>(Jobs.getExploreManager().getWorlds()); for (Entry<String, Map<String, ExploreRegion>> worlds : temp.entrySet()) { for (Entry<String, ExploreRegion> region : worlds.getValue().entrySet()) { JobsWorld jobsWorld = Util.getJobsWorld(worlds.getKey()); int id = jobsWorld == null ? 0 : jobsWorld.getId(); if (id != 0) for (Entry<Long, ExploreChunk> oneChunk : region.getValue().getChunks().entrySet()) { ExploreChunk chunk = oneChunk.getValue(); if (chunk.getDbId() != -1) continue; prest2.setInt(1, id); prest2.setInt(2, region.getValue().getChunkX(oneChunk.getKey())); prest2.setInt(3, region.getValue().getChunkZ(oneChunk.getKey())); prest2.setString(4, chunk.serializeNames()); prest2.setString(5, jobsWorld != null ? jobsWorld.getName() : ""); prest2.addBatch(); i++; } } } prest2.executeBatch(); conn.commit(); conn.setAutoCommit(true); if (i > 0) Jobs.consoleMsg("&e[Jobs] Saved " + i + " new explorer entries."); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest2); try { conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } } public void updateExplore() { if (!Jobs.getExploreManager().isExploreEnabled()) return; JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { conn.setAutoCommit(false); prest = conn.prepareStatement("UPDATE `" + DBTables.ExploreDataTable.getTableName() + "` SET `" + ExploreDataTableFields.playerNames.getCollumn() + "` = ? WHERE `id` = ?;"); int i = 0; Map<String, Map<String, ExploreRegion>> temp = new HashMap<>(Jobs.getExploreManager().getWorlds()); for (Entry<String, Map<String, ExploreRegion>> worlds : temp.entrySet()) { for (Entry<String, ExploreRegion> region : worlds.getValue().entrySet()) { for (ExploreChunk oneChunk : region.getValue().getChunks().values()) { if (oneChunk.getDbId() == -1 || !oneChunk.isUpdated()) continue; prest.setString(1, oneChunk.serializeNames()); prest.setInt(2, oneChunk.getDbId()); prest.addBatch(); i++; } } } prest.executeBatch(); conn.commit(); conn.setAutoCommit(true); if (i > 0) Jobs.consoleMsg("&e[Jobs] Updated " + i + " explorer entries."); } catch (SQLException e) { e.printStackTrace(); } finally { close(prest); try { conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } } /** * Save player-explore information * @param jobexplore - the information getting saved */ public void loadExplore() { if (!Jobs.getExploreManager().isExploreEnabled()) return; JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT * FROM `" + DBTables.ExploreDataTable.getTableName() + "`;"); res = prest.executeQuery(); Set<Integer> missingWorlds = new HashSet<>(); while (res.next()) { int worldId = res.getInt(ExploreDataTableFields.worldid.getCollumn()); JobsWorld jworld = Util.getJobsWorld(worldId); if (jworld == null || jworld.getWorld() == null) { missingWorlds.add(worldId); } else { Jobs.getExploreManager().load(res); } } for (Integer one : missingWorlds) { PreparedStatement prest2 = null; try { prest2 = conn.prepareStatement("DELETE FROM `" + DBTables.ExploreDataTable.getTableName() + "` WHERE `" + ExploreDataTableFields.worldid.getCollumn() + "` = ?;"); prest2.setInt(1, one); prest2.execute(); } catch (Throwable e) { e.printStackTrace(); } finally { close(prest2); } } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } } /** * Delete player-explore information * @param worldName - the world getting removed */ public boolean deleteExploredWorld(String worldName) { if (!Jobs.getExploreManager().isExploreEnabled()) return false; JobsConnection conn = getConnection(); if (conn == null) return false; JobsWorld target = Util.getJobsWorld(worldName); if (null == target) { return false; } boolean res = true; PreparedStatement prest = null; try { prest = conn.prepareStatement("DELETE FROM `" + DBTables.ExploreDataTable.getTableName() + "` WHERE `" + ExploreDataTableFields.worldid.getCollumn() + "` = ?;"); prest.setInt(1, target.getId()); prest.execute(); } catch (Throwable e) { e.printStackTrace(); res = false; } finally { close(prest); } return res; } /** * Save player-job information * @param jobInfo - the information getting saved * @return */ public List<Integer> getLognameList(int fromtime, int untiltime) { JobsConnection conn = getConnection(); List<Integer> nameList = new ArrayList<>(); if (conn == null) return nameList; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT `" + LogTableFields.userid.getCollumn() + "` FROM `" + DBTables.LogTable.getTableName() + "` WHERE `" + LogTableFields.time.getCollumn() + "` >= ? AND `" + LogTableFields.time.getCollumn() + "` <= ? ;"); prest.setInt(1, fromtime); prest.setInt(2, untiltime); res = prest.executeQuery(); while (res.next()) { int id = res.getInt(LogTableFields.userid.getCollumn()); if (!nameList.contains(id)) nameList.add(id); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return nameList; } /** * Show top list * @param toplist - toplist by jobs name * @return */ public List<TopList> toplist(String jobsname) { return toplist(jobsname, 0); } /** * Show top list * @param toplist - toplist by jobs name * @return */ public List<TopList> toplist(String jobsname, int limit) { List<TopList> jobs = new ArrayList<>(); JobsConnection conn = getConnection(); if (conn == null) return jobs; Job job = Jobs.getJob(jobsname); if (job == null) return jobs; PreparedStatement prest = null; ResultSet res = null; if (limit < 0) limit = 0; try { prest = conn.prepareStatement("SELECT `" + JobsTableFields.userid.getCollumn() + "`, `" + JobsTableFields.level.getCollumn() + "`, `" + JobsTableFields.experience.getCollumn() + "` FROM `" + getJobsTableName() + "` WHERE `" + JobsTableFields.jobid.getCollumn() + "` LIKE ? OR `" + JobsTableFields.jobid.getCollumn() + "` LIKE ? ORDER BY `" + JobsTableFields.level.getCollumn() + "` DESC, LOWER(" + JobsTableFields.experience.getCollumn() + ") DESC LIMIT " + limit + ", 50;"); prest.setInt(1, job.getId()); prest.setInt(2, job.getLegacyId()); res = prest.executeQuery(); while (res.next()) { PlayerInfo info = Jobs.getPlayerManager().getPlayerInfo(res.getInt(JobsTableFields.userid.getCollumn())); if (info != null) jobs.add(new TopList(info, res.getInt(JobsTableFields.level.getCollumn()), res.getInt(JobsTableFields.experience.getCollumn()))); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return jobs; } /** * Get the number of players that have a particular job * @param job - the job * @return the number of players that have a particular job */ public synchronized int getSlotsTaken(Job job) { int slot = 0; JobsConnection conn = getConnection(); if (conn == null) return slot; PreparedStatement prest = null; ResultSet res = null; try { prest = conn.prepareStatement("SELECT COUNT(*) FROM `" + getJobsTableName() + "` WHERE `" + JobsTableFields.jobid.getCollumn() + "` = ? OR `" + JobsTableFields.jobid.getCollumn() + "` = ?;"); prest.setInt(1, job.getId()); prest.setInt(2, job.getLegacyId()); res = prest.executeQuery(); if (res.next()) { slot = res.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } finally { close(res); close(prest); } return slot; } /** * Executes an SQL query * @param sql - The SQL * @throws SQLException */ public void executeSQL(String sql) throws SQLException { JobsConnection conn = getConnection(); if (conn == null) { return; } try (Statement stmt = conn.createStatement()) { stmt.execute(sql); } } protected JobsConnection getConnection() { try { return isConnected() ? pool.getConnection() : null; } catch (SQLException e) { Jobs.getPluginLogger().severe("Unable to connect to the database: " + e.getMessage()); return null; } } public synchronized void vacuum() { if (dbType != DataBaseType.SqLite) return; JobsConnection conn = getConnection(); if (conn == null) return; PreparedStatement prest = null; try { prest = conn.prepareStatement("VACUUM;"); prest.execute(); } catch (Throwable e) { } finally { close(prest); } } /** * Close all active database handles */ public void closeConnections() { pool.closeConnection(); } protected static void close(ResultSet res) { if (res != null) try { res.close(); } catch (SQLException e) { e.printStackTrace(); } } protected static void close(Statement stmt) { if (stmt != null) try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } protected static void close(PreparedStatement stmt) { if (stmt != null) try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } public String getJobsTableName() { return DBTables.JobsTable.getTableName(); } }
package org.bouncycastle.math.ec; import java.math.BigInteger; /** * Class representing a simple version of a big decimal. A * <code>SimpleBigDecimal</code> is basically a * {@link java.math.BigInteger BigInteger} with a few digits on the right of * the decimal point. The number of (binary) digits on the right of the decimal * point is called the <code>scale</code> of the <code>SimpleBigDecimal</code>. * Unlike in {@link java.math.BigDecimal BigDecimal}, the scale is not adjusted * automatically, but must be set manually. All <code>SimpleBigDecimal</code>s * taking part in the same arithmetic operation must have equal scale. The * result of a multiplication of two <code>SimpleBigDecimal</code>s returns a * <code>SimpleBigDecimal</code> with double scale. */ class SimpleBigDecimal //extends Number // not in J2ME - add compatibility class? { private static final long serialVersionUID = 1L; private final BigInteger bigInt; private final int scale; /** * Returns a <code>SimpleBigDecimal</code> representing the same numerical * value as <code>value</code>. * @param value The value of the <code>SimpleBigDecimal</code> to be * created. * @param scale The scale of the <code>SimpleBigDecimal</code> to be * created. * @return The such created <code>SimpleBigDecimal</code>. */ public static SimpleBigDecimal getInstance(BigInteger value, int scale) { return new SimpleBigDecimal(value.shiftLeft(scale), scale); } /** * Constructor for <code>SimpleBigDecimal</code>. The value of the * constructed <code>SimpleBigDecimal</code> equals <code>bigInt / * 2<sup>scale</sup></code>. * @param bigInt The <code>bigInt</code> value parameter. * @param scale The scale of the constructed <code>SimpleBigDecimal</code>. */ public SimpleBigDecimal(BigInteger bigInt, int scale) { if (scale < 0) { throw new IllegalArgumentException("scale may not be negative"); } this.bigInt = bigInt; this.scale = scale; } private SimpleBigDecimal(SimpleBigDecimal limBigDec) { bigInt = limBigDec.bigInt; scale = limBigDec.scale; } private void checkScale(SimpleBigDecimal b) { if (scale != b.scale) { throw new IllegalArgumentException("Only SimpleBigDecimal of " + "same scale allowed in arithmetic operations"); } } public SimpleBigDecimal adjustScale(int newScale) { if (newScale < 0) { throw new IllegalArgumentException("scale may not be negative"); } if (newScale == scale) { return new SimpleBigDecimal(this); } return new SimpleBigDecimal(bigInt.shiftLeft(newScale - scale), newScale); } public SimpleBigDecimal add(SimpleBigDecimal b) { checkScale(b); return new SimpleBigDecimal(bigInt.add(b.bigInt), scale); } public SimpleBigDecimal add(BigInteger b) { return new SimpleBigDecimal(bigInt.add(b.shiftLeft(scale)), scale); } public SimpleBigDecimal negate() { return new SimpleBigDecimal(bigInt.negate(), scale); } public SimpleBigDecimal subtract(SimpleBigDecimal b) { return add(b.negate()); } public SimpleBigDecimal subtract(BigInteger b) { return new SimpleBigDecimal(bigInt.subtract(b.shiftLeft(scale)), scale); } public SimpleBigDecimal multiply(SimpleBigDecimal b) { checkScale(b); return new SimpleBigDecimal(bigInt.multiply(b.bigInt), scale + scale); } public SimpleBigDecimal multiply(BigInteger b) { return new SimpleBigDecimal(bigInt.multiply(b), scale); } public SimpleBigDecimal divide(SimpleBigDecimal b) { checkScale(b); BigInteger dividend = bigInt.shiftLeft(scale); return new SimpleBigDecimal(dividend.divide(b.bigInt), scale); } public SimpleBigDecimal divide(BigInteger b) { return new SimpleBigDecimal(bigInt.divide(b), scale); } public SimpleBigDecimal shiftLeft(int n) { return new SimpleBigDecimal(bigInt.shiftLeft(n), scale); } public int compareTo(SimpleBigDecimal val) { checkScale(val); return bigInt.compareTo(val.bigInt); } public int compareTo(BigInteger val) { return bigInt.compareTo(val.shiftLeft(scale)); } public BigInteger floor() { return bigInt.shiftRight(scale); } public BigInteger round() { SimpleBigDecimal oneHalf = new SimpleBigDecimal(ECConstants.ONE, 1); return add(oneHalf.adjustScale(scale)).floor(); } public int intValue() { return floor().intValue(); } public long longValue() { return floor().longValue(); } /* NON-J2ME compliant. public double doubleValue() { return Double.valueOf(toString()).doubleValue(); } public float floatValue() { return Float.valueOf(toString()).floatValue(); } */ public int getScale() { return scale; } public String toString() { if (scale == 0) { return bigInt.toString(); } BigInteger floorBigInt = floor(); BigInteger fract = bigInt.subtract(floorBigInt.shiftLeft(scale)); if (bigInt.signum() == -1) { fract = ECConstants.ONE.shiftLeft(scale).subtract(fract); } if ((floorBigInt.signum() == -1) && (!(fract.equals(ECConstants.ZERO)))) { floorBigInt = floorBigInt.add(ECConstants.ONE); } String leftOfPoint = floorBigInt.toString(); char[] fractCharArr = new char[scale]; String fractStr = fract.toString(2); int fractLen = fractStr.length(); int zeroes = scale - fractLen; for (int i = 0; i < zeroes; i++) { fractCharArr[i] = '0'; } for (int j = 0; j < fractLen; j++) { fractCharArr[zeroes + j] = fractStr.charAt(j); } String rightOfPoint = new String(fractCharArr); StringBuffer sb = new StringBuffer(leftOfPoint); sb.append("."); sb.append(rightOfPoint); return sb.toString(); } public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof SimpleBigDecimal)) { return false; } SimpleBigDecimal other = (SimpleBigDecimal)o; return ((bigInt.equals(other.bigInt)) && (scale == other.scale)); } public int hashCode() { return bigInt.hashCode() ^ scale; } }
package org.broad.igv.util; import org.apache.log4j.Logger; import org.broad.igv.PreferenceManager; import org.broad.igv.gs.GSUtils; import org.broad.igv.ui.IGV; import org.broad.igv.util.ftp.FTPClient; import org.broad.igv.util.ftp.FTPStream; import org.broad.igv.util.ftp.FTPUtils; import sun.misc.BASE64Encoder; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.awt.*; import java.io.*; import java.net.*; import java.util.HashMap; import java.util.Map; /** * Notes -- 401 => client authentication, 407 => proxy authentication, 403 => forbidden * * @author Jim Robinson * @date 9/22/11 */ public class HttpURLConnectionUtils extends HttpUtils { private static Logger log = Logger.getLogger(HttpURLConnectionUtils.class); private static ProxySettings proxySettings = null; private static HttpURLConnectionUtils instance; public static final int MAX_REDIRECTS = 5; private String genomeSpaceUser; private String genomeSpaceIdentityServer; static { synchronized (HttpURLConnectionUtils.class) { instance = new HttpURLConnectionUtils(); } } public static HttpURLConnectionUtils getInstance() { return instance; } private HttpURLConnectionUtils() { Authenticator.setDefault(new IGVAuthenticator()); String gsURL = PreferenceManager.getInstance().get(PreferenceManager.GENOME_SPACE_ID_SERVER); try { genomeSpaceIdentityServer = (new URL(gsURL)).getHost(); } catch (Exception e) { log.error("Error parsing Genome Space ID url ", e); } } /** * Code for disabling SSL certification */ private void disableCertificateValidation() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { } } public void shutdown() { //To change body of implemented methods use File | Settings | File Templates. } /** * Return the contents of the url as a String. This method should only be used for queries expected to return * a small amount of data. * * @param url * @return */ public String getContentsAsString(URL url) throws IOException { InputStream is = null; HttpURLConnection conn = openConnection(url, null); try { is = conn.getInputStream(); return readContents(is); } finally { if (is != null) is.close(); } } private String readContents(InputStream is) throws IOException { BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int b; while ((b = bis.read()) >= 0) { bos.write(b); } return new String(bos.toByteArray()); } public InputStream openConnectionStream(URL url) throws IOException { if (url.getProtocol().toUpperCase().equals("FTP")) { String userInfo = url.getUserInfo(); String host = url.getHost(); String file = url.getPath(); FTPClient ftp = FTPUtils.connect(host, userInfo); ftp.pasv(); ftp.retr(file); return new FTPStream(ftp); } else { return openConnectionStream(url, null); } } public InputStream openConnectionStream(URL url, boolean abortOnClose) throws IOException { return openConnection(url, null).getInputStream(); } public InputStream openConnectionStream(URL url, Map<String, String> requestProperties) throws IOException { HttpURLConnection conn = openConnection(url, requestProperties); return conn.getInputStream(); } public InputStream openConnectionStream(URL url, boolean abortOnClose, Map<String, String> requestProperties) throws IOException { HttpURLConnection conn = openConnection(url, requestProperties); return conn.getInputStream(); } public boolean resourceAvailable(URL url) { try { HttpURLConnection conn = openConnection(url, null, "HEAD"); int code = conn.getResponseCode(); return code == 200; } catch (IOException e) { return false; } } public String getHeaderField(URL url, String key) throws IOException { HttpURLConnection conn = openConnection(url, null, "HEAD"); int code = conn.getResponseCode(); // TODO -- check code return conn.getHeaderField(key); } public long getContentLength(URL url) throws IOException { String contentLengthString = ""; contentLengthString = getHeaderField(url, "Content-Length"); if (contentLengthString == null) { return -1; } else { return Long.parseLong(contentLengthString); } } public void updateProxySettings() { boolean useProxy; String proxyHost; int proxyPort = -1; boolean auth = false; String user = null; String pw = null; PreferenceManager prefMgr = PreferenceManager.getInstance(); useProxy = prefMgr.getAsBoolean(PreferenceManager.USE_PROXY); proxyHost = prefMgr.get(PreferenceManager.PROXY_HOST, null); try { proxyPort = Integer.parseInt(prefMgr.get(PreferenceManager.PROXY_PORT, "-1")); } catch (NumberFormatException e) { proxyPort = -1; } auth = prefMgr.getAsBoolean(PreferenceManager.PROXY_AUTHENTICATE); user = prefMgr.get(PreferenceManager.PROXY_USER, null); String pwString = prefMgr.get(PreferenceManager.PROXY_PW, null); if (pwString != null) { pw = Utilities.base64Decode(pwString); } proxySettings = new ProxySettings(useProxy, user, pw, auth, proxyHost, proxyPort); } public boolean downloadFile(String url, File outputFile) throws IOException { log.info("Downloading " + url + " to " + outputFile.getAbsolutePath()); HttpURLConnection conn = openConnection(new URL(url), null); int code = conn.getResponseCode(); // TODO -- check code long contentLength = -1; String contentLengthString = conn.getHeaderField("Content-Length"); if (contentLengthString != null) { contentLength = Long.parseLong(contentLengthString); } log.info("Content length = " + contentLength); InputStream is = null; OutputStream out = null; try { is = conn.getInputStream(); out = new FileOutputStream(outputFile); byte[] buf = new byte[64 * 1024]; int downloaded = 0; int bytesRead = 0; while ((bytesRead = is.read(buf)) != -1) { out.write(buf, 0, bytesRead); downloaded += bytesRead; } log.info("Download complete. Total bytes downloaded = " + downloaded); } finally { if (is != null) is.close(); if (out != null) { out.flush(); out.close(); } } long fileLength = outputFile.length(); return contentLength <= 0 || contentLength == fileLength; } @Override public void uploadGenomeSpaceFile(String uri, File file, Map<String, String> headers) throws IOException { HttpURLConnection urlconnection = null; OutputStream bos = null; URL url = new URL(uri); urlconnection = openConnection(url, headers, "PUT"); urlconnection.setDoOutput(true); urlconnection.setDoInput(true); bos = new BufferedOutputStream(urlconnection.getOutputStream()); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); int i; // read byte by byte until end of stream while ((i = bis.read()) > 0) { bos.write(i); } bos.close(); int responseCode = urlconnection.getResponseCode(); // Error messages below. if (responseCode >= 400) { String message = readErrorStream(urlconnection); throw new IOException("Error uploading " + file.getName() + " : " + message); } } private String readErrorStream(HttpURLConnection connection) throws IOException { InputStream inputStream = null; try { inputStream = connection.getErrorStream(); return readContents(inputStream); } finally { if (inputStream != null) inputStream.close(); } } @Override public String createGenomeSpaceDirectory(URL url, String body) throws IOException { HttpURLConnection urlconnection = null; OutputStream bos = null; Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); headers.put("Content-Length", String.valueOf(body.getBytes().length)); urlconnection = openConnection(url, headers, "PUT"); urlconnection.setDoOutput(true); urlconnection.setDoInput(true); bos = new BufferedOutputStream(urlconnection.getOutputStream()); bos.write(body.getBytes()); bos.close(); int responseCode = urlconnection.getResponseCode(); // Error messages below. StringBuffer buf = new StringBuffer(); InputStream inputStream = null; if (responseCode >= 200 && responseCode < 300) { inputStream = urlconnection.getInputStream(); } else { inputStream = urlconnection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String nextLine; while ((nextLine = br.readLine()) != null) { buf.append(nextLine); buf.append('\n'); } inputStream.close(); if (responseCode >= 200 && responseCode < 300) { return buf.toString(); } else { throw new IOException("Error creating GS directory: " + buf.toString()); } } // HttpPut put = new HttpPut(url.toExternalForm()); // put.setHeader("Content-Type", "application/json"); // StringEntity se = new StringEntity(body); // put.setEntity(se); // HttpResponse response = execute(put, url); // String responseString = EntityUtils.toString(response.getEntity()); // int code = response.getStatusLine().getStatusCode(); // if (code != 200) { // throw new IOException("Error creating directory: " + code); // return responseString; private HttpURLConnection openConnection(URL url, Map<String, String> requestProperties) throws IOException { return openConnection(url, requestProperties, "GET"); } private HttpURLConnection openConnection(URL url, Map<String, String> requestProperties, String method) throws IOException { return openConnection(url, requestProperties, method, 0); } /** * The "real" connection method * * @param url * @param requestProperties * @param method * @return * @throws IOException */ private HttpURLConnection openConnection( URL url, Map<String, String> requestProperties, String method, int redirectCount) throws IOException { boolean useProxy = proxySettings != null && proxySettings.useProxy && proxySettings.proxyHost != null && proxySettings.proxyPort > 0; HttpURLConnection conn = null; if (useProxy) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxySettings.proxyHost, proxySettings.proxyPort)); conn = (HttpURLConnection) url.openConnection(proxy); if (proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) { byte[] bytes = (proxySettings.user + ":" + proxySettings.pw).getBytes(); String encodedUserPwd = (new BASE64Encoder()).encode(bytes); conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); } } else { conn = (HttpURLConnection) url.openConnection(); } if (GSUtils.isGenomeSpace(url)) { // Manually follow GS redicts so we can grab the identity token conn.setInstanceFollowRedirects(false); if (!url.toString().contains(PreferenceManager.getInstance().get(PreferenceManager.GENOME_SPACE_ID_SERVER))) { checkGenomeSpaceCookie(conn); } if (!url.toString().contains("datamanager/uploadurls")) { conn.setRequestProperty("Accept", "application/json,application/text"); } } conn.setConnectTimeout(10000); conn.setReadTimeout(60000); conn.setRequestMethod(method); conn.setRequestProperty("Connection", "close"); if (requestProperties != null) { for (Map.Entry<String, String> prop : requestProperties.entrySet()) { conn.setRequestProperty(prop.getKey(), prop.getValue()); } } if (method.equals("PUT")) { return conn; } else { int code = conn.getResponseCode(); // Redirects. These can occur even if followRedirects == true if there is a change in protocol, // for example http -> https. if (code > 300 && code < 400) { if (redirectCount > MAX_REDIRECTS) { throw new IOException("Too many redirects"); } String newLocation = conn.getHeaderField("Location"); if (newLocation != null) { log.debug("Redirecting to " + newLocation); URL redirectURL = new URL(newLocation); if (genomeSpaceIdentityServer != null && genomeSpaceIdentityServer.equals(url.getHost())) { URL identityURL = new URL(PreferenceManager.getInstance().get(PreferenceManager.GENOME_SPACE_ID_SERVER)); String token = getContentsAsString(identityURL); if (token != null && token.length() > 0) { setGenomeSpaceCookie(conn, token); } } return openConnection(new URL(newLocation), requestProperties, method, redirectCount++); } else { throw new IOException("Server indicated redirect but Location header is missing"); } } // TODO -- handle other response codes. if (code > 400) { String message = conn.getResponseMessage(); String details = readErrorStream(conn); throw new IOException("Server returned error code " + details); } return conn; } } public void checkGenomeSpaceCookie(URLConnection conn) throws IOException { File file = GSUtils.getTokenFile(); if (file.exists()) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(file)); String token = br.readLine(); if (token != null) { String cookie = GSUtils.AUTH_TOKEN_COOKIE_NAME + "=" + token; conn.setRequestProperty("Cookie", cookie); } } catch (IOException e) { log.error("Error reading GS cookie", e); throw e; } finally { if (br != null) try { br.close(); } catch (IOException e) { // Ignore } } } else { URL identityURL = new URL(PreferenceManager.getInstance().get(PreferenceManager.GENOME_SPACE_ID_SERVER)); String responseBody = getContentsAsString(identityURL); if (responseBody != null && responseBody.length() > 0) { setGenomeSpaceCookie(conn, responseBody); } } } private void setGenomeSpaceCookie(URLConnection conn, String responseBody) { String cookie = GSUtils.AUTH_TOKEN_COOKIE_NAME + "=" + responseBody; conn.setRequestProperty("Cookie", cookie); GSUtils.saveGSLogin(responseBody, genomeSpaceUser); } public static class ProxySettings { boolean auth = false; String user; String pw; boolean useProxy; String proxyHost; int proxyPort = -1; public ProxySettings(boolean useProxy, String user, String pw, boolean auth, String proxyHost, int proxyPort) { this.auth = auth; this.proxyHost = proxyHost; this.proxyPort = proxyPort; this.pw = pw; this.useProxy = useProxy; this.user = user; } } /** * The default authenticator */ public class IGVAuthenticator extends Authenticator { /** * Called when password authentcation is needed. * * @return */ @Override protected PasswordAuthentication getPasswordAuthentication() { Authenticator.RequestorType type = getRequestorType(); URL url = this.getRequestingURL(); boolean isProxyChallenge = type == RequestorType.PROXY; if (isProxyChallenge) { if (proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) { return new PasswordAuthentication(proxySettings.user, proxySettings.pw.toCharArray()); } } Frame owner = IGV.hasInstance() ? IGV.getMainFrame() : null; boolean isGenomeSpace = GSUtils.isGenomeSpace(url); LoginDialog dlg = new LoginDialog(owner, isGenomeSpace, url.toString(), isProxyChallenge); dlg.setVisible(true); if (dlg.isCanceled()) { return null; } else { final String userString = dlg.getUsername(); final char[] userPass = dlg.getPassword(); if (isGenomeSpace) { genomeSpaceUser = userString; } if (isProxyChallenge) { proxySettings.user = userString; proxySettings.pw = new String(userPass); } return new PasswordAuthentication(userString, userPass); } } } }
package org.clapper.util.io; public enum CombinationFilterMode { /** * Mode setting that instructs the filter to <tt>AND</tt> all the * contained filters. */ AND_FILTERS, /** * Mode setting that instructs the filter to <tt>OR</tt> all the * contained filters. */ OR_FILTERS };
package com.landian.sql.jpa.order; import com.landian.sql.jpa.annotation.OrderPolicy; import java.io.Serializable; public class Order implements Serializable { public static String ASC = "ASC"; public static String DESC = "DESC"; public static Order asc(String property){ Order proxyOrder = new Order(property, OrderPolicy.ASC); return proxyOrder; } public static Order[] asArray(OrderVo... orderVos){ if(null == orderVos){ return new Order[]{}; } Order[] array = new Order[orderVos.length]; for (int i=0; i<orderVos.length; i++) { array[i] = newInstance(orderVos[i]); } return array; } public static Order newInstance(OrderVo orderVo){ if(orderVo.getOrder().equalsIgnoreCase(ASC)){ return Order.asc(orderVo.getSort()); } return Order.desc(orderVo.getSort()); } public static Order desc(String property){ Order proxyOrder = new Order(property, OrderPolicy.DESC); return proxyOrder; } private String property; private OrderPolicy orderExpr; private Order(){} private Order(String property, OrderPolicy orderExpr) { this.property = property; this.orderExpr = orderExpr; } public String getProperty() { return property; } public OrderPolicy getOrderExpr() { return orderExpr; } public String getSortKey(){ if(OrderPolicy.ASC == orderExpr){ return ASC; } return DESC; } /** * SQL */ public String nativeSQL(){ return getProperty() + " " + getSortKey(); } }
package com.maxmind.geoip; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; /** * Provides a lookup service for information based on an IP address. The * location of a database file is supplied when creating a lookup service * instance. The edition of the database determines what information is * available about an IP address. See the DatabaseInfo class for further * details. * <p> * * The following code snippet demonstrates looking up the country that an IP * address is from: * * <pre> * // First, create a LookupService instance with the location of the database. * LookupService lookupService = new LookupService(&quot;c:\\geoip.dat&quot;); * // Assume we have a String ipAddress (in dot-decimal form). * Country country = lookupService.getCountry(ipAddress); * System.out.println(&quot;The country is: &quot; + country.getName()); * System.out.println(&quot;The country code is: &quot; + country.getCode()); * </pre> * * In general, a single LookupService instance should be created and then reused * repeatedly. * <p> * * <i>Tip:</i> Those deploying the GeoIP API as part of a web application may * find it difficult to pass in a File to create the lookup service, as the * location of the database may vary per deployment or may even be part of the * web-application. In this case, the database should be added to the classpath * of the web-app. For example, by putting it into the WEB-INF/classes directory * of the web application. The following code snippet demonstrates how to create * a LookupService using a database that can be found on the classpath: * * <pre> * String fileName = getClass().getResource(&quot;/GeoIP.dat&quot;).toExternalForm() * .substring(6); * LookupService lookupService = new LookupService(fileName); * </pre> * * @author Matt Tucker (matt@jivesoftware.com) */ public class LookupService { /** * Database file. */ private RandomAccessFile file; private final File databaseFile; /** * Information about the database. */ private DatabaseInfo databaseInfo; private static final Charset charset = Charset.forName("ISO-8859-1"); private final CharsetDecoder charsetDecoder = charset.newDecoder(); /** * The database type. Default is the country edition. */ private byte databaseType = DatabaseInfo.COUNTRY_EDITION; private int[] databaseSegments; private int recordLength; private int dboptions; private byte[] dbbuffer; private byte[] index_cache; private long mtime; private int last_netmask; private static final int US_OFFSET = 1; private static final int CANADA_OFFSET = 677; private static final int WORLD_OFFSET = 1353; private static final int FIPS_RANGE = 360; private static final int COUNTRY_BEGIN = 16776960; private static final int STATE_BEGIN_REV0 = 16700000; private static final int STATE_BEGIN_REV1 = 16000000; private static final int STRUCTURE_INFO_MAX_SIZE = 20; private static final int DATABASE_INFO_MAX_SIZE = 100; public static final int GEOIP_STANDARD = 0; public static final int GEOIP_MEMORY_CACHE = 1; public static final int GEOIP_CHECK_CACHE = 2; public static final int GEOIP_INDEX_CACHE = 4; public static final int GEOIP_UNKNOWN_SPEED = 0; public static final int GEOIP_DIALUP_SPEED = 1; public static final int GEOIP_CABLEDSL_SPEED = 2; public static final int GEOIP_CORPORATE_SPEED = 3; private static final int SEGMENT_RECORD_LENGTH = 3; private static final int STANDARD_RECORD_LENGTH = 3; private static final int ORG_RECORD_LENGTH = 4; private static final int MAX_RECORD_LENGTH = 4; private static final int MAX_ORG_RECORD_LENGTH = 300; private static final int FULL_RECORD_LENGTH = 60; private final Country UNKNOWN_COUNTRY = new Country(" private static final String[] countryCode = { "--", "AP", "EU", "AD", "AE", "AF", "AG", "AI", "AL", "AM", "CW", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BM", "BN", "BO", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CU", "CV", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "SX", "GA", "GB", "GD", "GE", "GF", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IN", "IO", "IQ", "IR", "IS", "IT", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "ST", "SV", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TM", "TN", "TO", "TL", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "RS", "ZA", "ZM", "ME", "ZW", "A1", "A2", "O1", "AX", "GG", "IM", "JE", "BL", "MF", "BQ", "SS", "O1" }; private static final String[] countryName = { "N/A", "Asia/Pacific Region", "Europe", "Andorra", "United Arab Emirates", "Afghanistan", "Antigua and Barbuda", "Anguilla", "Albania", "Armenia", "Curacao", "Angola", "Antarctica", "Argentina", "American Samoa", "Austria", "Australia", "Aruba", "Azerbaijan", "Bosnia and Herzegovina", "Barbados", "Bangladesh", "Belgium", "Burkina Faso", "Bulgaria", "Bahrain", "Burundi", "Benin", "Bermuda", "Brunei Darussalam", "Bolivia", "Brazil", "Bahamas", "Bhutan", "Bouvet Island", "Botswana", "Belarus", "Belize", "Canada", "Cocos (Keeling) Islands", "Congo, The Democratic Republic of the", "Central African Republic", "Congo", "Switzerland", "Cote D'Ivoire", "Cook Islands", "Chile", "Cameroon", "China", "Colombia", "Costa Rica", "Cuba", "Cape Verde", "Christmas Island", "Cyprus", "Czech Republic", "Germany", "Djibouti", "Denmark", "Dominica", "Dominican Republic", "Algeria", "Ecuador", "Estonia", "Egypt", "Western Sahara", "Eritrea", "Spain", "Ethiopia", "Finland", "Fiji", "Falkland Islands (Malvinas)", "Micronesia, Federated States of", "Faroe Islands", "France", "Sint Maarten (Dutch part)", "Gabon", "United Kingdom", "Grenada", "Georgia", "French Guiana", "Ghana", "Gibraltar", "Greenland", "Gambia", "Guinea", "Guadeloupe", "Equatorial Guinea", "Greece", "South Georgia and the South Sandwich Islands", "Guatemala", "Guam", "Guinea-Bissau", "Guyana", "Hong Kong", "Heard Island and McDonald Islands", "Honduras", "Croatia", "Haiti", "Hungary", "Indonesia", "Ireland", "Israel", "India", "British Indian Ocean Territory", "Iraq", "Iran, Islamic Republic of", "Iceland", "Italy", "Jamaica", "Jordan", "Japan", "Kenya", "Kyrgyzstan", "Cambodia", "Kiribati", "Comoros", "Saint Kitts and Nevis", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Cayman Islands", "Kazakhstan", "Lao People's Democratic Republic", "Lebanon", "Saint Lucia", "Liechtenstein", "Sri Lanka", "Liberia", "Lesotho", "Lithuania", "Luxembourg", "Latvia", "Libya", "Morocco", "Monaco", "Moldova, Republic of", "Madagascar", "Marshall Islands", "Macedonia", "Mali", "Myanmar", "Mongolia", "Macau", "Northern Mariana Islands", "Martinique", "Mauritania", "Montserrat", "Malta", "Mauritius", "Maldives", "Malawi", "Mexico", "Malaysia", "Mozambique", "Namibia", "New Caledonia", "Niger", "Norfolk Island", "Nigeria", "Nicaragua", "Netherlands", "Norway", "Nepal", "Nauru", "Niue", "New Zealand", "Oman", "Panama", "Peru", "French Polynesia", "Papua New Guinea", "Philippines", "Pakistan", "Poland", "Saint Pierre and Miquelon", "Pitcairn Islands", "Puerto Rico", "Palestinian Territory", "Portugal", "Palau", "Paraguay", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saudi Arabia", "Solomon Islands", "Seychelles", "Sudan", "Sweden", "Singapore", "Saint Helena", "Slovenia", "Svalbard and Jan Mayen", "Slovakia", "Sierra Leone", "San Marino", "Senegal", "Somalia", "Suriname", "Sao Tome and Principe", "El Salvador", "Syrian Arab Republic", "Swaziland", "Turks and Caicos Islands", "Chad", "French Southern Territories", "Togo", "Thailand", "Tajikistan", "Tokelau", "Turkmenistan", "Tunisia", "Tonga", "Timor-Leste", "Turkey", "Trinidad and Tobago", "Tuvalu", "Taiwan", "Tanzania, United Republic of", "Ukraine", "Uganda", "United States Minor Outlying Islands", "United States", "Uruguay", "Uzbekistan", "Holy See (Vatican City State)", "Saint Vincent and the Grenadines", "Venezuela", "Virgin Islands, British", "Virgin Islands, U.S.", "Vietnam", "Vanuatu", "Wallis and Futuna", "Samoa", "Yemen", "Mayotte", "Serbia", "South Africa", "Zambia", "Montenegro", "Zimbabwe", "Anonymous Proxy", "Satellite Provider", "Other", "Aland Islands", "Guernsey", "Isle of Man", "Jersey", "Saint Barthelemy", "Saint Martin", "Bonaire, Saint Eustatius and Saba", "South Sudan", "Other" }; /* init the hashmap once at startup time */ static { if (countryCode.length != countryName.length) { throw new AssertionError("countryCode.length!=countryName.length"); } } /** * Create a new lookup service using the specified database file. * * @param databaseFile * String representation of the database file. * @throws IOException * if an error occured creating the lookup service from the * database file. */ public LookupService(String databaseFile) throws IOException { this(new File(databaseFile)); } /** * Create a new lookup service using the specified database file. * * @param databaseFile * the database file. * @throws IOException * if an error occured creating the lookup service from the * database file. */ public LookupService(File databaseFile) throws IOException { this.databaseFile = databaseFile; file = new RandomAccessFile(databaseFile, "r"); init(); } /** * Create a new lookup service using the specified database file. * * @param databaseFile * String representation of the database file. * @param options * database flags to use when opening the database GEOIP_STANDARD * read database from disk GEOIP_MEMORY_CACHE cache the database * in RAM and read it from RAM * @throws IOException * if an error occured creating the lookup service from the * database file. */ public LookupService(String databaseFile, int options) throws IOException { this(new File(databaseFile), options); } /** * Create a new lookup service using the specified database file. * * @param databaseFile * the database file. * @param options * database flags to use when opening the database GEOIP_STANDARD * read database from disk GEOIP_MEMORY_CACHE cache the database * in RAM and read it from RAM * @throws IOException * if an error occured creating the lookup service from the * database file. */ public LookupService(File databaseFile, int options) throws IOException { this.databaseFile = databaseFile; file = new RandomAccessFile(databaseFile, "r"); dboptions = options; init(); } /** * Reads meta-data from the database file. * * @throws IOException * if an error occurs reading from the database file. */ private synchronized void init() throws IOException { byte[] delim = new byte[3]; byte[] buf = new byte[SEGMENT_RECORD_LENGTH]; if (file == null) { return; } if ((dboptions & GEOIP_CHECK_CACHE) != 0) { mtime = databaseFile.lastModified(); } file.seek(file.length() - 3); for (int i = 0; i < STRUCTURE_INFO_MAX_SIZE; i++) { file.readFully(delim); if (delim[0] == -1 && delim[1] == -1 && delim[2] == -1) { databaseType = file.readByte(); if (databaseType >= 106) { // Backward compatibility with databases from April 2003 and // earlier databaseType -= 105; } // Determine the database type. if (databaseType == DatabaseInfo.REGION_EDITION_REV0) { databaseSegments = new int[1]; databaseSegments[0] = STATE_BEGIN_REV0; recordLength = STANDARD_RECORD_LENGTH; } else if (databaseType == DatabaseInfo.REGION_EDITION_REV1) { databaseSegments = new int[1]; databaseSegments[0] = STATE_BEGIN_REV1; recordLength = STANDARD_RECORD_LENGTH; } else if (databaseType == DatabaseInfo.CITY_EDITION_REV0 || databaseType == DatabaseInfo.CITY_EDITION_REV1 || databaseType == DatabaseInfo.ORG_EDITION || databaseType == DatabaseInfo.ORG_EDITION_V6 || databaseType == DatabaseInfo.ISP_EDITION || databaseType == DatabaseInfo.ISP_EDITION_V6 || databaseType == DatabaseInfo.DOMAIN_EDITION || databaseType == DatabaseInfo.DOMAIN_EDITION_V6 || databaseType == DatabaseInfo.ASNUM_EDITION || databaseType == DatabaseInfo.ASNUM_EDITION_V6 || databaseType == DatabaseInfo.NETSPEED_EDITION_REV1 || databaseType == DatabaseInfo.NETSPEED_EDITION_REV1_V6 || databaseType == DatabaseInfo.CITY_EDITION_REV0_V6 || databaseType == DatabaseInfo.CITY_EDITION_REV1_V6) { databaseSegments = new int[1]; databaseSegments[0] = 0; if (databaseType == DatabaseInfo.CITY_EDITION_REV0 || databaseType == DatabaseInfo.CITY_EDITION_REV1 || databaseType == DatabaseInfo.ASNUM_EDITION_V6 || databaseType == DatabaseInfo.NETSPEED_EDITION_REV1 || databaseType == DatabaseInfo.NETSPEED_EDITION_REV1_V6 || databaseType == DatabaseInfo.CITY_EDITION_REV0_V6 || databaseType == DatabaseInfo.CITY_EDITION_REV1_V6 || databaseType == DatabaseInfo.ASNUM_EDITION) { recordLength = STANDARD_RECORD_LENGTH; } else { recordLength = ORG_RECORD_LENGTH; } file.readFully(buf); for (int j = 0; j < SEGMENT_RECORD_LENGTH; j++) { databaseSegments[0] += (unsignedByteToInt(buf[j]) << (j * 8)); } } break; } else { file.seek(file.getFilePointer() - 4); } } if ((databaseType == DatabaseInfo.COUNTRY_EDITION) || (databaseType == DatabaseInfo.COUNTRY_EDITION_V6) || (databaseType == DatabaseInfo.PROXY_EDITION) || (databaseType == DatabaseInfo.NETSPEED_EDITION)) { databaseSegments = new int[1]; databaseSegments[0] = COUNTRY_BEGIN; recordLength = STANDARD_RECORD_LENGTH; } if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { int l = (int) file.length(); dbbuffer = new byte[l]; file.seek(0); file.readFully(dbbuffer, 0, l); databaseInfo = getDatabaseInfo(); file.close(); } if ((dboptions & GEOIP_INDEX_CACHE) != 0) { int l = databaseSegments[0] * recordLength * 2; index_cache = new byte[l]; file.seek(0); file.readFully(index_cache, 0, l); } else { index_cache = null; } } /** * Closes the lookup service. */ public synchronized void close() { try { if (file != null) { file.close(); } file = null; } catch (IOException e) { // Here for backward compatibility. } } /** * @return The list of all known country names */ public String[] getAllCountryNames() { return countryName; } /** * @return The list of all known country codes */ public String[] getAllCountryCodes() { return countryCode; } /** * Returns the country the IP address is in. * * @param ipAddress * String version of an IPv6 address, i.e. "::127.0.0.1" * @return the country the IP address is from. */ public Country getCountryV6(String ipAddress) { InetAddress addr; try { addr = InetAddress.getByName(ipAddress); } catch (UnknownHostException e) { return UNKNOWN_COUNTRY; } return getCountryV6(addr); } /** * Returns the country the IP address is in. * * @param ipAddress * String version of an IP address, i.e. "127.0.0.1" * @return the country the IP address is from. */ public Country getCountry(String ipAddress) { InetAddress addr; try { addr = InetAddress.getByName(ipAddress); } catch (UnknownHostException e) { return UNKNOWN_COUNTRY; } return getCountry(addr); } /** * Returns the country the IP address is in. * * @param ipAddress * the IP address. * @return the country the IP address is from. */ public synchronized Country getCountry(InetAddress ipAddress) { return getCountry(bytesToLong(ipAddress.getAddress())); } /** * Returns the country the IP address is in. * * @param addr * the IP address as Inet6Address. * @return the country the IP address is from. */ public synchronized Country getCountryV6(InetAddress addr) { if (file == null && (dboptions & GEOIP_MEMORY_CACHE) == 0) { throw new IllegalStateException("Database has been closed."); } int ret = seekCountryV6(addr) - COUNTRY_BEGIN; if (ret == 0) { return UNKNOWN_COUNTRY; } else { return new Country(countryCode[ret], countryName[ret]); } } /** * Returns the country the IP address is in. * * @param ipAddress * the IP address in long format. * @return the country the IP address is from. */ public synchronized Country getCountry(long ipAddress) { if (file == null && (dboptions & GEOIP_MEMORY_CACHE) == 0) { throw new IllegalStateException("Database has been closed."); } int ret = seekCountry(ipAddress) - COUNTRY_BEGIN; if (ret == 0) { return UNKNOWN_COUNTRY; } else { return new Country(countryCode[ret], countryName[ret]); } } public int getID(String ipAddress) { InetAddress addr; try { addr = InetAddress.getByName(ipAddress); } catch (UnknownHostException e) { return 0; } return getID(bytesToLong(addr.getAddress())); } public int getID(InetAddress ipAddress) { return getID(bytesToLong(ipAddress.getAddress())); } public synchronized int getID(long ipAddress) { if (file == null && (dboptions & GEOIP_MEMORY_CACHE) == 0) { throw new IllegalStateException("Database has been closed."); } return seekCountry(ipAddress) - databaseSegments[0]; } public int last_netmask() { return last_netmask; } public void netmask(int nm) { last_netmask = nm; } /** * Returns information about the database. * * @return database info. */ public synchronized DatabaseInfo getDatabaseInfo() { if (databaseInfo != null) { return databaseInfo; } try { _check_mtime(); boolean hasStructureInfo = false; byte[] delim = new byte[3]; // Advance to part of file where database info is stored. file.seek(file.length() - 3); for (int i = 0; i < STRUCTURE_INFO_MAX_SIZE; i++) { int read = file.read(delim); if (read == 3 && (delim[0] & 0xFF) == 255 && (delim[1] & 0xFF) == 255 && (delim[2] & 0xFF) == 255) { hasStructureInfo = true; break; } file.seek(file.getFilePointer() - 4); } if (hasStructureInfo) { file.seek(file.getFilePointer() - 6); } else { // No structure info, must be pre Sep 2002 database, go back to // end. file.seek(file.length() - 3); } // Find the database info string. for (int i = 0; i < DATABASE_INFO_MAX_SIZE; i++) { file.readFully(delim); if (delim[0] == 0 && delim[1] == 0 && delim[2] == 0) { byte[] dbInfo = new byte[i]; file.readFully(dbInfo); // Create the database info object using the string. databaseInfo = new DatabaseInfo(new String(dbInfo, charset)); return databaseInfo; } file.seek(file.getFilePointer() - 4); } } catch (IOException e) { throw new InvalidDatabaseException("Error reading database info", e); } return new DatabaseInfo(""); } synchronized void _check_mtime() { try { if ((dboptions & GEOIP_CHECK_CACHE) != 0) { long t = databaseFile.lastModified(); if (t != mtime) { /* GeoIP Database file updated */ /* refresh filehandle */ close(); file = new RandomAccessFile(databaseFile, "r"); databaseInfo = null; init(); } } } catch (IOException e) { throw new InvalidDatabaseException("Database not found", e); } } // for GeoIP City only public Location getLocationV6(String str) { InetAddress addr; try { addr = InetAddress.getByName(str); } catch (UnknownHostException e) { return null; } return getLocationV6(addr); } // for GeoIP City only public Location getLocation(InetAddress addr) { return getLocation(bytesToLong(addr.getAddress())); } // for GeoIP City only public Location getLocation(String str) { InetAddress addr; try { addr = InetAddress.getByName(str); } catch (UnknownHostException e) { return null; } return getLocation(addr); } public synchronized Region getRegion(String str) { InetAddress addr; try { addr = InetAddress.getByName(str); } catch (UnknownHostException e) { return null; } return getRegion(bytesToLong(addr.getAddress())); } public synchronized Region getRegion(InetAddress addr) { return getRegion(bytesToLong(addr.getAddress())); } public synchronized Region getRegion(long ipnum) { Region record = new Region(); int seek_region; if (databaseType == DatabaseInfo.REGION_EDITION_REV0) { seek_region = seekCountry(ipnum) - STATE_BEGIN_REV0; char[] ch = new char[2]; if (seek_region >= 1000) { record.countryCode = "US"; record.countryName = "United States"; ch[0] = (char) (((seek_region - 1000) / 26) + 65); ch[1] = (char) (((seek_region - 1000) % 26) + 65); record.region = new String(ch); } else { record.countryCode = countryCode[seek_region]; record.countryName = countryName[seek_region]; record.region = ""; } } else if (databaseType == DatabaseInfo.REGION_EDITION_REV1) { seek_region = seekCountry(ipnum) - STATE_BEGIN_REV1; char[] ch = new char[2]; if (seek_region < US_OFFSET) { record.countryCode = ""; record.countryName = ""; record.region = ""; } else if (seek_region < CANADA_OFFSET) { record.countryCode = "US"; record.countryName = "United States"; ch[0] = (char) (((seek_region - US_OFFSET) / 26) + 65); ch[1] = (char) (((seek_region - US_OFFSET) % 26) + 65); record.region = new String(ch); } else if (seek_region < WORLD_OFFSET) { record.countryCode = "CA"; record.countryName = "Canada"; ch[0] = (char) (((seek_region - CANADA_OFFSET) / 26) + 65); ch[1] = (char) (((seek_region - CANADA_OFFSET) % 26) + 65); record.region = new String(ch); } else { record.countryCode = countryCode[(seek_region - WORLD_OFFSET) / FIPS_RANGE]; record.countryName = countryName[(seek_region - WORLD_OFFSET) / FIPS_RANGE]; record.region = ""; } } return record; } public synchronized Location getLocationV6(InetAddress addr) { int seek_country; try { seek_country = seekCountryV6(addr); return readCityRecord(seek_country); } catch (IOException e) { throw new InvalidDatabaseException("Error while seting up segments", e); } } public synchronized Location getLocation(long ipnum) { int seek_country; try { seek_country = seekCountry(ipnum); return readCityRecord(seek_country); } catch (IOException e) { throw new InvalidDatabaseException("Error while seting up segments", e); } } private Location readCityRecord(int seekCountry) throws IOException { if (seekCountry == databaseSegments[0]) { return null; } ByteBuffer buffer = readRecordBuf(seekCountry, FULL_RECORD_LENGTH); Location record = new Location(); int country = unsignedByteToInt(buffer.get()); // get country record.countryCode = countryCode[country]; record.countryName = countryName[country]; record.region = readString(buffer); record.city = readString(buffer); record.postalCode = readString(buffer); record.latitude = readAngle(buffer); record.longitude = readAngle(buffer); if (databaseType == DatabaseInfo.CITY_EDITION_REV1) { // get DMA code if ("US".equals(record.countryCode)) { int metroarea_combo = readMetroAreaCombo(buffer); record.metro_code = record.dma_code = metroarea_combo / 1000; record.area_code = metroarea_combo % 1000; } } return record; } private ByteBuffer readRecordBuf(int seek, int maxLength) throws IOException { int recordPointer = seek + (2 * recordLength - 1) * databaseSegments[0]; ByteBuffer buffer; if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { buffer = ByteBuffer.wrap(dbbuffer, recordPointer, Math .min(dbbuffer.length - recordPointer, maxLength)); } else { byte[] recordBuf = new byte[maxLength]; // read from disk file.seek(recordPointer); file.read(recordBuf); buffer = ByteBuffer.wrap(recordBuf); } return buffer; } private String readString(ByteBuffer buffer) throws CharacterCodingException { int start = buffer.position(); int oldLimit = buffer.limit(); while (buffer.hasRemaining() && buffer.get() != 0) {} int end = buffer.position() - 1; String str = null; if (end > start) { buffer.position(start); buffer.limit(end); str = charsetDecoder.decode(buffer).toString(); buffer.limit(oldLimit); } buffer.position(end + 1); return str; } private static float readAngle(ByteBuffer buffer) { if (buffer.remaining() < 3) { throw new InvalidDatabaseException("Unexpected end of data record when reading angle"); } double num = 0; for (int j = 0; j < 3; j++) { num += unsignedByteToInt(buffer.get()) << (j * 8); } return (float) num / 10000 - 180; } private static int readMetroAreaCombo(ByteBuffer buffer) { if (buffer.remaining() < 3) { throw new InvalidDatabaseException("Unexpected end of data record when reading metro area"); } int metroareaCombo = 0; for (int j = 0; j < 3; j++) { metroareaCombo += unsignedByteToInt(buffer.get()) << (j * 8); } return metroareaCombo; } public String getOrg(InetAddress addr) { return getOrg(bytesToLong(addr.getAddress())); } public String getOrg(String str) { InetAddress addr; try { addr = InetAddress.getByName(str); } catch (UnknownHostException e) { return null; } return getOrg(addr); } // GeoIP Organization and ISP Edition methods public synchronized String getOrg(long ipnum) { try { int seekOrg = seekCountry(ipnum); return readOrgRecord(seekOrg); } catch (IOException e) { throw new InvalidDatabaseException("Error while reading org", e); } } public String getOrgV6(String str) { InetAddress addr; try { addr = InetAddress.getByName(str); } catch (UnknownHostException e) { return null; } return getOrgV6(addr); } // GeoIP Organization and ISP Edition methods public synchronized String getOrgV6(InetAddress addr) { try { int seekOrg = seekCountryV6(addr); return readOrgRecord(seekOrg); } catch (IOException e) { throw new InvalidDatabaseException("Error while reading org", e); } } private String readOrgRecord(int seekOrg) throws IOException { if (seekOrg == databaseSegments[0]) { return null; } ByteBuffer buf = readRecordBuf(seekOrg, MAX_ORG_RECORD_LENGTH); return readString(buf); } /** * Finds the country index value given an IPv6 address. * * @param addr * the ip address to find in long format. * @return the country index. */ private synchronized int seekCountryV6(InetAddress addr) { byte[] v6vec = addr.getAddress(); if (v6vec.length == 4) { // sometimes java returns an ipv4 address for IPv6 input // we have to work around that feature // It happens for ::ffff:24.24.24.24 byte[] t = new byte[16]; System.arraycopy(v6vec, 0, t, 12, 4); v6vec = t; } byte[] buf = new byte[2 * MAX_RECORD_LENGTH]; int[] x = new int[2]; int offset = 0; _check_mtime(); for (int depth = 127; depth >= 0; depth readNode(buf, x, offset); int bnum = 127 - depth; int idx = bnum >> 3; int b_mask = 1 << (bnum & 7 ^ 7); if ((v6vec[idx] & b_mask) > 0) { if (x[1] >= databaseSegments[0]) { last_netmask = 128 - depth; return x[1]; } offset = x[1]; } else { if (x[0] >= databaseSegments[0]) { last_netmask = 128 - depth; return x[0]; } offset = x[0]; } } throw new InvalidDatabaseException("Error seeking country while searching for " + addr.getHostAddress()); } /** * Finds the country index value given an IP address. * * @param ipAddress * the ip address to find in long format. * @return the country index. */ private synchronized int seekCountry(long ipAddress) { byte[] buf = new byte[2 * MAX_RECORD_LENGTH]; int[] x = new int[2]; int offset = 0; _check_mtime(); for (int depth = 31; depth >= 0; depth readNode(buf, x, offset); if ((ipAddress & (1 << depth)) > 0) { if (x[1] >= databaseSegments[0]) { last_netmask = 32 - depth; return x[1]; } offset = x[1]; } else { if (x[0] >= databaseSegments[0]) { last_netmask = 32 - depth; return x[0]; } offset = x[0]; } } throw new InvalidDatabaseException("Error seeking country while searching for " + ipAddress); } private void readNode(byte[] buf, int[] x, int offset) { if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { // read from memory System.arraycopy(dbbuffer, (2 * recordLength * offset), buf, 0, 2 * recordLength); } else if ((dboptions & GEOIP_INDEX_CACHE) != 0) { // read from index cache System.arraycopy(index_cache, (2 * recordLength * offset), buf, 0, 2 * recordLength); } else { // read from disk try { file.seek(2 * recordLength * offset); file.read(buf); } catch (IOException e) { throw new InvalidDatabaseException("Error seeking in database", e); } } for (int i = 0; i < 2; i++) { x[i] = 0; for (int j = 0; j < recordLength; j++) { int y = buf[i * recordLength + j]; if (y < 0) { y += 256; } x[i] += (y << (j * 8)); } } } /** * Returns the long version of an IP address given an InetAddress object. * * @param address * the InetAddress. * @return the long form of the IP address. */ private static long bytesToLong(byte[] address) { long ipnum = 0; for (int i = 0; i < 4; ++i) { long y = address[i]; if (y < 0) { y += 256; } ipnum += y << ((3 - i) * 8); } return ipnum; } private static int unsignedByteToInt(byte b) { return (int) b & 0xFF; } }
package org.exist.memtree; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.exist.dom.NodeProxy; import org.exist.dom.QName; import org.exist.dom.StoredNode; import org.exist.util.serializer.AttrList; import org.exist.util.serializer.Receiver; import org.exist.xquery.XQueryContext; import java.util.HashMap; import java.util.Map; /** * Builds an in-memory DOM tree from SAX {@link org.exist.util.serializer.Receiver} events. * * @author Wolfgang <wolfgang@exist-db.org> */ public class DocumentBuilderReceiver implements ContentHandler, LexicalHandler, Receiver { private MemTreeBuilder builder = null; private Map<String, String> namespaces = null; private boolean explicitNSDecl = false; public boolean checkNS = false; public DocumentBuilderReceiver() { super(); } public DocumentBuilderReceiver(MemTreeBuilder builder) { this(builder, false); } public DocumentBuilderReceiver(MemTreeBuilder builder, boolean declareNamespaces) { super(); this.builder = builder; this.explicitNSDecl = declareNamespaces; } @Override public Document getDocument() { return builder.getDocument(); } public XQueryContext getContext() { return builder.getContext(); } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator) */ @Override public void setDocumentLocator(Locator locator) { } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#startDocument() */ @Override public void startDocument() throws SAXException { if(builder == null) { builder = new MemTreeBuilder(); builder.startDocument(); } } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#endDocument() */ @Override public void endDocument() throws SAXException { builder.endDocument(); } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String) */ @Override public void startPrefixMapping(String prefix, String namespace) throws SAXException { if(!explicitNSDecl) { return; } if(namespaces == null) { namespaces = new HashMap<String, String>(); } namespaces.put(prefix, namespace); } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) */ @Override public void endPrefixMapping(String prefix) throws SAXException { } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException { builder.startElement(namespaceURI, localName, qName, attrs); declareNamespaces(); } private void declareNamespaces() { if(explicitNSDecl && namespaces != null) { for(Map.Entry<String, String> entry : namespaces.entrySet()) { builder.namespaceNode(entry.getKey(), entry.getValue()); } namespaces.clear(); } } @Override public void startElement(QName qname, AttrList attribs) { qname = checkNS(qname); builder.startElement(qname, null); declareNamespaces(); if(attribs != null) { for(int i = 0; i < attribs.getLength(); i++) { builder.addAttribute( attribs.getQName(i), attribs.getValue(i)); } } } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { builder.endElement(); } @Override public void endElement(QName qname) throws SAXException { builder.endElement(); } public void addReferenceNode(NodeProxy proxy) throws SAXException { builder.addReferenceNode(proxy); } public void addNamespaceNode(QName qname) throws SAXException { builder.namespaceNode(qname); } @Override public void characters(CharSequence seq) throws SAXException { builder.characters(seq); } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#characters(char[], int, int) */ @Override public void characters(char[] ch, int start, int len) throws SAXException { builder.characters( ch, start, len ); } @Override public void attribute(QName qname, String value) throws SAXException { try { qname = checkNS(qname); builder.addAttribute(qname, value); } catch(DOMException e) { throw new SAXException(e.getMessage()); } } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) */ @Override public void ignorableWhitespace(char[] ch, int start, int len) throws SAXException { } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String) */ @Override public void processingInstruction(String target, String data) throws SAXException { builder.processingInstruction(target, data); } /* (non-Javadoc) * @see org.exist.util.serializer.Receiver#cdataSection(char[], int, int) */ @Override public void cdataSection(char[] ch, int start, int len) throws SAXException { builder.cdataSection(new String(ch, start, len)); } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) */ @Override public void skippedEntity(String arg0) throws SAXException { } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#endCDATA() */ @Override public void endCDATA() throws SAXException { // TODO ignored } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#endDTD() */ @Override public void endDTD() throws SAXException { } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#startCDATA() */ @Override public void startCDATA() throws SAXException { // TODO Ignored } @Override public void documentType(String name, String publicId, String systemId) throws SAXException { builder.documentType(name, publicId, systemId); } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#comment(char[], int, int) */ @Override public void comment(char[] ch, int start, int length) throws SAXException { builder.comment(ch, start, length); } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#endEntity(java.lang.String) */ @Override public void endEntity(String name) throws SAXException{ } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#startEntity(java.lang.String) */ @Override public void startEntity(String name) throws SAXException { } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#startDTD(java.lang.String, java.lang.String, java.lang.String) */ @Override public void startDTD(String name, String publicId, String systemId) throws SAXException { } @Override public void highlightText(CharSequence seq) { // not supported with this receiver } @Override public void setCurrentNode(StoredNode node) { // ignored } public QName checkNS(QName qname) { if(checkNS) { if(qname.getPrefix() == null || qname.getPrefix().equals("") || qname.getNamespaceURI() == null) { return qname; } XQueryContext context = builder.getContext(); String inScopeNamespace = context.getInScopeNamespace(qname.getPrefix()); if(inScopeNamespace == null) { context.declareInScopeNamespace(qname.getPrefix(), qname.getNamespaceURI()); } else if(!inScopeNamespace.equals(qname.getNamespaceURI())) { String prefix = context.getInScopePrefix(qname.getNamespaceURI()); int i = 0; while(prefix == null) { prefix = "XXX"; if(i > 0) { prefix += String.valueOf(i); } if(context.getInScopeNamespace(prefix) != null) { prefix = null; i++; } } context.declareInScopeNamespace(prefix, qname.getNamespaceURI()); qname.setPrefix(prefix); } } return qname; } }
package com.ociweb.iot.maker; import java.util.ArrayList; import com.ociweb.gl.api.TelemetryConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ociweb.gl.api.Behavior; import com.ociweb.gl.api.MsgCommandChannel; import com.ociweb.gl.api.MsgRuntime; import com.ociweb.gl.impl.ChildClassScanner; import com.ociweb.gl.impl.schema.MessagePubSub; import com.ociweb.gl.impl.schema.MessageSubscription; import com.ociweb.gl.impl.schema.TrafficOrderSchema; import com.ociweb.gl.impl.stage.ReactiveManagerPipeConsumer; import com.ociweb.iot.hardware.HardwareImpl; import com.ociweb.iot.hardware.impl.SerialInputSchema; import com.ociweb.iot.hardware.impl.edison.GroveV3EdisonImpl; import com.ociweb.iot.hardware.impl.grovepi.BeagleBoneModel; import com.ociweb.iot.hardware.impl.grovepi.GrovePiHardwareImpl; import com.ociweb.iot.hardware.impl.grovepi.LinuxDesktopModel; import com.ociweb.iot.hardware.impl.grovepi.MacModel; import com.ociweb.iot.hardware.impl.grovepi.PiModel; import com.ociweb.iot.hardware.impl.grovepi.WindowsDesktopModel; import com.ociweb.iot.hardware.impl.test.TestHardware; import com.ociweb.pronghorn.iot.ReactiveIoTListenerStage; import com.ociweb.pronghorn.iot.i2c.I2CBacking; import com.ociweb.pronghorn.iot.schema.GroveRequestSchema; import com.ociweb.pronghorn.iot.schema.GroveResponseSchema; import com.ociweb.pronghorn.iot.schema.I2CCommandSchema; import com.ociweb.pronghorn.iot.schema.I2CResponseSchema; import com.ociweb.pronghorn.iot.schema.ImageSchema; import com.ociweb.pronghorn.pipe.DataInputBlobReader; import com.ociweb.pronghorn.pipe.Pipe; import com.ociweb.pronghorn.pipe.PipeConfig; import com.ociweb.pronghorn.pipe.PipeConfigManager; import com.ociweb.pronghorn.stage.scheduling.GraphManager; import com.ociweb.pronghorn.stage.scheduling.ScriptedNonThreadScheduler; public class FogRuntime extends MsgRuntime<HardwareImpl, ListenerFilterIoT> { private static boolean isRunning = false; public static final int I2C_WRITER = FogCommandChannel.I2C_WRITER; public static final int PIN_WRITER = FogCommandChannel.PIN_WRITER; public static final int SERIAL_WRITER = FogCommandChannel.SERIAL_WRITER; public static final int BT_WRITER = FogCommandChannel.BT_WRITER; private static final Logger logger = LoggerFactory.getLogger(FogRuntime.class); private static final int i2cDefaultLength = 300; private static final int i2cDefaultMaxPayload = 16; private static final byte edI2C = 6; static final String PROVIDED_HARDWARE_IMPL_NAME = "com.ociweb.iot.hardware.impl.ProvidedHardwareImpl"; private boolean disableHardwareDetection; public FogRuntime() { this(new String[0]); } public FogRuntime(String[] args) { super(args); disableHardwareDetection = this.hasArgument("disableHardwareDetection", "--dhd"); } public Hardware getHardware(){ if(this.builder==null){ if (!disableHardwareDetection) { //setup system for binary binding in case Zulu is found on Arm //must populate os.arch as "arm" instead of "aarch32" or "aarch64" in that case, JIFFI is dependent on this value. if (System.getProperty("os.arch", "unknown").contains("aarch")) { System.setProperty("os.arch", "arm"); //TODO: investigate if this a bug against jiffi or zulu and inform them } long startTime = System.currentTimeMillis(); // Detect provided hardware implementation. // TODO: Should this ONLY occur on Android devices? try { Class.forName("android.app.Activity"); logger.trace("Detected Android environment. Searching for {}.", PROVIDED_HARDWARE_IMPL_NAME); try { Class<?> clazz = Class.forName(PROVIDED_HARDWARE_IMPL_NAME); logger.trace("Detected {}.", PROVIDED_HARDWARE_IMPL_NAME); try { this.builder = (HardwareImpl) clazz.getConstructor(GraphManager.class).newInstance(gm); return this.builder; } catch (NoSuchMethodException e) { logger.warn( "{} does not provide a single argument constructor that accepts a GraphManager. Continuing native hardware detection.", PROVIDED_HARDWARE_IMPL_NAME); } catch (Throwable e) { logger.warn( "Unable to instantiate {}. Continuing native hardware detection.", PROVIDED_HARDWARE_IMPL_NAME, e); } } catch (ClassNotFoundException e) { logger.trace("No {} is present.", PROVIDED_HARDWARE_IMPL_NAME); } } catch (ClassNotFoundException ignored) { } logger.info("android duration {} ",System.currentTimeMillis()-startTime); //The best way to detect the pi or edison is to first check for the expected matching i2c implmentation PiModel pm = null; BeagleBoneModel bm = null; I2CBacking i2cBacking = null; // else if((bm = BeagleBoneModel.detect()) != BeagleBoneModel.Unknown) { //NOTE: this requres Super user to run // this.builder = new TestHardware(gm, args); // logger.info("Detected running on " + bm); if ((pm = PiModel.detect()) != PiModel.Unknown){ logger.info("Detected running on " + pm); this.builder = new GrovePiHardwareImpl(gm, args, pm.i2cBus()); } else if(WindowsDesktopModel.detect() != WindowsDesktopModel.Unknown) { this.builder = new TestHardware(gm, args); logger.info("Detected running on Windows, test mock hardware will be used"); } else if(LinuxDesktopModel.detect() != LinuxDesktopModel.Unknown) { this.builder = new TestHardware(gm, args); logger.info("Detected Running on Linux, test mock hardware will be used"); } else if(MacModel.detect() != MacModel.Unknown) { this.builder = new TestHardware(gm, args); logger.info("Detected running on Mac, test mock hardware will be used"); } else if (null != (this.builder = new GroveV3EdisonImpl(gm, args, edI2C)).getI2CBacking() ) { logger.info("Detected running on Edison"); System.out.println("You are running on the Edison hardware."); } else { this.builder = new TestHardware(gm, args); logger.info("Unrecognized hardware, test mock hardware will be used"); } } else { this.builder = new TestHardware(gm, args); logger.info("Hardware detection disabled on the command line, now using mock hardware."); } } return this.builder; } public FogCommandChannel newCommandChannel() { int instance = -1; PipeConfigManager pcm = buildPipeManager(); return this.builder.newCommandChannel(instance, pcm); } public FogCommandChannel newCommandChannel(int features) { int instance = -1; PipeConfigManager pcm = buildPipeManager(); return this.builder.newCommandChannel(features, instance, pcm); } protected PipeConfigManager buildPipeManager() { PipeConfigManager pcm = super.buildPipeManager(); pcm.addConfig(new PipeConfig<GroveRequestSchema>(GroveRequestSchema.instance, defaultCommandChannelLength)); pcm.addConfig(new PipeConfig<I2CCommandSchema>(I2CCommandSchema.instance, i2cDefaultLength,i2cDefaultMaxPayload)); pcm.addConfig(defaultCommandChannelLength,0,TrafficOrderSchema.class ); return pcm; } public FogCommandChannel newCommandChannel(int features, int customChannelLength) { int instance = -1; PipeConfigManager pcm = new PipeConfigManager(); pcm.addConfig(customChannelLength,0,GroveRequestSchema.class); pcm.addConfig(customChannelLength, defaultCommandChannelMaxPayload, I2CCommandSchema.class); pcm.addConfig(customChannelLength, defaultCommandChannelMaxPayload, MessagePubSub.class ); pcm.addConfig(customChannelLength,0,TrafficOrderSchema.class); return this.builder.newCommandChannel(features, instance, pcm); } public ListenerFilterIoT addRotaryListener(RotaryListener listener) { return registerListener(listener); } public ListenerFilterIoT addAnalogListener(AnalogListener listener) { return registerListener(listener); } public ListenerFilterIoT addDigitalListener(DigitalListener listener) { return registerListener(listener); } public ListenerFilterIoT addSerialListener(SerialListener listener) { return registerListener(listener); } public ListenerFilterIoT registerListener(Behavior listener) { return registerListenerImpl(listener); } public ListenerFilterIoT addImageListener(ImageListener listener) { switch (builder.getPlatformType()) { case GROVE_PI: return registerListener(listener); default: throw new UnsupportedOperationException("Image listeners are not supported for [" + builder.getPlatformType() + "] hardware"); } } public ListenerFilterIoT addI2CListener(I2CListener listener) { return registerListenerImpl(listener); } private ListenerFilterIoT registerListenerImpl(Behavior listener) { outputPipes = new Pipe<?>[0]; ChildClassScanner.visitUsedByClass(listener, gatherPipesVisitor, MsgCommandChannel.class);//populates OutputPipes //pre-count how many pipes will be needed so the array can be built to the right size int pipesCount = 0; if (this.builder.isListeningToI2C(listener) && this.builder.hasI2CInputs()) { pipesCount++; } if (this.builder.isListeningToPins(listener) && this.builder.hasDigitalOrAnalogInputs()) { pipesCount++; } if (this.builder.isListeningToSerial(listener)) { pipesCount++; } if (this.builder.isListeningToCamera(listener)) { pipesCount++; } pipesCount = addGreenPipesCount(listener, pipesCount); Pipe<?>[] inputPipes = new Pipe<?>[pipesCount]; if (this.builder.isListeningToI2C(listener) && this.builder.hasI2CInputs()) { inputPipes[--pipesCount] = new Pipe<I2CResponseSchema>(new PipeConfig<I2CResponseSchema>(I2CResponseSchema.instance, defaultCommandChannelLength, defaultCommandChannelMaxPayload).grow2x()); } if (this.builder.isListeningToPins(listener) && this.builder.hasDigitalOrAnalogInputs()) { inputPipes[--pipesCount] = new Pipe<GroveResponseSchema>(new PipeConfig<GroveResponseSchema>(GroveResponseSchema.instance, defaultCommandChannelLength).grow2x()); } if (this.builder.isListeningToSerial(listener) ) { inputPipes[--pipesCount] = newSerialInputPipe(new PipeConfig<SerialInputSchema>(SerialInputSchema.instance, defaultCommandChannelLength, defaultCommandChannelMaxPayload).grow2x()); } if (this.builder.isListeningToCamera(listener)) { inputPipes[--pipesCount] = new Pipe<ImageSchema>(new PipeConfig<ImageSchema>(ImageSchema.instance, defaultCommandChannelLength, defaultCommandChannelMaxPayload).grow2x()); } final int httpClientPipeId = netResponsePipeIdx; //must be grabbed before populateGreenPipes populateGreenPipes(listener, pipesCount, inputPipes); //StartupListener is not driven by any response data and is called when the stage is started up. no pipe needed. //TimeListener, time rate signals are sent from the stages its self and therefore does not need a pipe to consume. //this is empty when transducerAutowiring is off final ArrayList<ReactiveManagerPipeConsumer> consumers = new ArrayList<ReactiveManagerPipeConsumer>(); //extract this into common method to be called in GL and FL if (transducerAutowiring) { inputPipes = autoWireTransducers(listener, inputPipes, consumers); } ReactiveIoTListenerStage reactiveListener = builder.createReactiveListener( gm, listener, inputPipes, outputPipes, consumers, parallelInstanceUnderActiveConstruction); configureStageRate(listener, reactiveListener); if (httpClientPipeId != netResponsePipeIdx) { reactiveListener.configureHTTPClientResponseSupport(httpClientPipeId); } assert(checkPipeOrders(inputPipes)); return reactiveListener; } private boolean checkPipeOrders(Pipe<?>[] inputPipes) { ///only for assert int testId = -1; int i = inputPipes.length; while (--i>=0) { if (inputPipes[i]!=null && Pipe.isForSchema((Pipe<MessageSubscription>)inputPipes[i], MessageSubscription.class)) { testId = inputPipes[i].id; } } assert(-1==testId || GraphManager.allPipesOfType(gm, MessageSubscription.instance)[subscriptionPipeIdx-1].id==testId) : "GraphManager has returned the pipes out of the expected order"; return true; } private static Pipe<SerialInputSchema> newSerialInputPipe(PipeConfig<SerialInputSchema> config) { return new Pipe<SerialInputSchema>(config) { @SuppressWarnings("unchecked") @Override protected DataInputBlobReader<SerialInputSchema> createNewBlobReader() { return new SerialReader(this); } }; } @Deprecated public static FogRuntime test(FogApp app) { FogRuntime runtime = new FogRuntime(); test(app, runtime); return runtime; } public static boolean testUntilShutdownRequested(FogApp app, long timeoutMS) { FogRuntime runtime = new FogRuntime(); ScriptedNonThreadScheduler s = test(app, runtime); long limit = System.nanoTime() + (timeoutMS*1_000_000L); boolean result = true; s.startup(); while (!ScriptedNonThreadScheduler.isShutdownRequested(s)) { s.run(); if (System.nanoTime() > limit) { result = false; break; } } s.shutdown(); return result; } public static ScriptedNonThreadScheduler test(FogApp app, FogRuntime runtime) { //force hardware to TestHardware regardless of where or what platform its run on. //this is done because this is the test() method and must behave the same everywhere. runtime.builder = new TestHardware(runtime.gm, runtime.args); TestHardware hardware = (TestHardware)runtime.getHardware(); hardware.isInUnitTest = true; app.declareConfiguration(runtime.builder); GraphManager.addDefaultNota(runtime.gm, GraphManager.SCHEDULE_RATE, runtime.builder.getDefaultSleepRateNS()); runtime.declareBehavior(app); runtime.builder.coldSetup(); //TODO: should we add LCD init in the PI hardware code? How do we know when its used? runtime.builder.buildStages(runtime); runtime.logStageScheduleRates(); TelemetryConfig telemetryConfig = runtime.builder.getTelemetryConfig(); if ( telemetryConfig != null) { runtime.gm.enableTelemetry(telemetryConfig.getHost(),telemetryConfig.getPort()); } //exportGraphDotFile(); runtime.scheduler = new ScriptedNonThreadScheduler(runtime.gm, false); //= runtime.builder.createScheduler(runtime); //for test we do not call startup and wait instead for this to be done by test. return (ScriptedNonThreadScheduler)runtime.scheduler; } public static FogRuntime run(FogApp app) { return run(app,new String[0]); } public static FogRuntime run(FogApp app, String[] args) throws UnsupportedOperationException { if (FogRuntime.isRunning){ throw new UnsupportedOperationException("An FogApp is already running!"); } long lastTime; long nowTime; FogRuntime.isRunning = true; FogRuntime runtime = new FogRuntime(args); logger.info("{} ms startup", lastTime = System.currentTimeMillis()); Hardware hardware = runtime.getHardware(); //this default for Fog is slower due to the expected minimum hardware of iot devices hardware.setDefaultRate(4_000_000); // 4 ms app.declareConfiguration(hardware); GraphManager.addDefaultNota(runtime.gm, GraphManager.SCHEDULE_RATE, runtime.builder.getDefaultSleepRateNS()); logger.info("{} ms duration {} ms finished declare configuration", nowTime = System.currentTimeMillis(), nowTime-lastTime); lastTime = nowTime; runtime.declareBehavior(app); logger.info("{} ms duration {} ms finished declare behavior", nowTime = System.currentTimeMillis(), nowTime-lastTime); lastTime = nowTime; //TODO: at this point realize the stages in declare behavior // all updates are done so create the reactors with the right pipes and names // this change will let us move routes to part of the fluent API plus other benifits.. // move all reactor fields into object created early, shell is created here. // register must hold list of all temp objects (linked list to preserve order?) System.out.println("To exit app press Ctrl-C"); runtime.builder.coldSetup(); //TODO: should we add LCD init in the PI hardware code? How do we know when its used? runtime.builder.buildStages(runtime); runtime.logStageScheduleRates(); logger.info("{} ms duration {} ms finished building internal graph", nowTime = System.currentTimeMillis(), nowTime-lastTime); lastTime = nowTime; TelemetryConfig telemetryConfig = runtime.builder.getTelemetryConfig(); if ( telemetryConfig != null) { runtime.gm.enableTelemetry(telemetryConfig.getHost(),telemetryConfig.getPort()); logger.info("{} ms duration {} ms finished building telemetry", lastTime = nowTime = System.currentTimeMillis(), nowTime-lastTime); } //exportGraphDotFile(); runtime.scheduler = runtime.builder.createScheduler(runtime); runtime.scheduler.startup(); logger.info("{} ms duration {} ms finished graph startup", nowTime = System.currentTimeMillis(), nowTime-lastTime); lastTime = nowTime; return runtime; } }
package org.griphyn.vdl.karajan.lib; import org.apache.log4j.Logger; import org.griphyn.vdl.karajan.Pair; import org.griphyn.vdl.karajan.FuturePairIterator; import org.griphyn.vdl.karajan.PairIterator; import org.griphyn.vdl.karajan.VDL2FutureException; import org.globus.cog.karajan.arguments.Arg; import org.globus.cog.karajan.stack.VariableStack; import org.globus.cog.karajan.workflow.ExecutionException; import org.globus.cog.karajan.workflow.futures.FutureNotYetAvailable; import org.griphyn.vdl.mapping.DSHandle; import org.griphyn.vdl.mapping.InvalidPathException; import org.griphyn.vdl.mapping.Path; public class SetFieldValue extends VDLFunction { public static final Logger logger = Logger.getLogger(SetFieldValue.class); public static final Arg PA_VALUE = new Arg.Positional("value"); static { setArguments(SetFieldValue.class, new Arg[] { OA_PATH, PA_VAR, PA_VALUE }); } public Object function(VariableStack stack) throws ExecutionException { DSHandle var = (DSHandle) PA_VAR.getValue(stack); try { Path path = parsePath(OA_PATH.getValue(stack), stack); DSHandle leaf = var.getField(path); DSHandle value = (DSHandle)PA_VALUE.getValue(stack); if (logger.isInfoEnabled()) { logger.info("Setting " + leaf + " to " + value); } synchronized (var.getRoot()) { // TODO want to do a type check here, for runtime type checking // and pull out the appropriate internal value from value if it // is a DSHandle. There is no need (I think? maybe numerical casting?) // for type conversion here; but would be useful to have // type checking. synchronized(value.getRoot()) { if(!value.isClosed()) { throw new FutureNotYetAvailable(addFutureListener(stack, value)); } deepCopy(leaf,value,stack); } } return null; } catch (FutureNotYetAvailable fnya) { throw fnya; } catch (Exception e) { // TODO tighten this throw new ExecutionException(e); } } /** make dest look like source - if its a simple value, copy that and if its an array then recursively copy */ void deepCopy(DSHandle dest, DSHandle source, VariableStack stack) throws ExecutionException { if(source.getType().isPrimitive()) { dest.setValue(source.getValue()); } else if(source.getType().isArray()) { PairIterator it = new PairIterator(source.getArrayValue()); while(it.hasNext()) { Pair pair = (Pair) it.next(); Object lhs = pair.get(0); DSHandle rhs = (DSHandle) pair.get(1); Path memberPath = Path.EMPTY_PATH.addLast(String.valueOf(lhs),true); DSHandle field; try { field = dest.getField(memberPath); } catch(InvalidPathException ipe) { throw new ExecutionException("Could not get destination field",ipe); } deepCopy(field,rhs,stack); } closeShallow(stack, dest); } else { // TODO implement this throw new RuntimeException("Deep non-array structure copying not implemented, when trying to copy "+source); } } }
package com.qiniu.storage; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.qiniu.common.Constants; import com.qiniu.common.QiniuException; import com.qiniu.http.Client; import com.qiniu.http.Response; import com.qiniu.storage.model.*; import com.qiniu.util.*; import java.util.*; public final class BucketManager { /** * Auth * QBoxAuth */ private final Auth auth; /** * Configuration * HTTP */ private Configuration configuration; /** * HTTP Client * HTTP */ private final Client client; /** * BucketManager * * @param auth Auth * @param cfg Configuration */ public BucketManager(Auth auth, Configuration cfg) { this.auth = auth; this.configuration = cfg.clone(); client = new Client(this.configuration); } public BucketManager(Auth auth, Client client) { this.auth = auth; this.client = client; } public static String encodedEntry(String bucket, String key) { String encodedEntry; if (key != null) { encodedEntry = UrlSafeBase64.encodeToString(bucket + ":" + key); } else { encodedEntry = UrlSafeBase64.encodeToString(bucket); } return encodedEntry; } public static String encodedEntry(String bucket) { return encodedEntry(bucket, null); } /** * * * @return */ public String[] buckets() throws QiniuException { String url = String.format("%s/buckets", configuration.rsHost()); Response res = get(url); if (!res.isOK()) { throw new QiniuException(res); } String[] buckets = res.jsonToObject(String[].class); res.close(); return buckets; } public void createBucket(String bucketName, String region) throws QiniuException { String url = String.format("%s/mkbucketv2/%s/region/%s", configuration.rsHost(), UrlSafeBase64.encodeToString(bucketName), region); Response res = post(url, null); if (!res.isOK()) { throw new QiniuException(res); } res.close(); } /** * domain * * @param bucket * @return domain * @throws QiniuException */ public String[] domainList(String bucket) throws QiniuException { String url = String.format("%s/v6/domain/list?tbl=%s", configuration.apiHost(), bucket); Response res = get(url); if (!res.isOK()) { throw new QiniuException(res); } String[] domains = res.jsonToObject(String[].class); res.close(); return domains; } /** * * * @param bucket * @param prefix * @return FileInfo */ public FileListIterator createFileListIterator(String bucket, String prefix) { return new FileListIterator(bucket, prefix, 1000, null); } /** * * * @param bucket * @param prefix * @param limit 1000 100 * @param delimiter * @return FileInfo */ public FileListIterator createFileListIterator(String bucket, String prefix, int limit, String delimiter) { return new FileListIterator(bucket, prefix, limit, delimiter); } private String listQuery(String bucket, String prefix, String marker, int limit, String delimiter) { StringMap map = new StringMap().put("bucket", bucket).putNotEmpty("marker", marker) .putNotEmpty("prefix", prefix).putNotEmpty("delimiter", delimiter).putWhen("limit", limit, limit > 0); return map.formString(); } /** * v1 response * * @param bucket * @param prefix * @param marker marker * @param limit 1000 100 * @param delimiter * @return * @throws QiniuException */ public Response listV1(String bucket, String prefix, String marker, int limit, String delimiter) throws QiniuException { String url = String.format("%s/list?%s", configuration.rsfHost(auth.accessKey, bucket), listQuery(bucket, prefix, marker, limit, delimiter)); return get(url); } public FileListing listFiles(String bucket, String prefix, String marker, int limit, String delimiter) throws QiniuException { Response response = listV1(bucket, prefix, marker, limit, delimiter); if (!response.isOK()) { throw new QiniuException(response); } FileListing fileListing = response.jsonToObject(FileListing.class); response.close(); return fileListing; } /** * v2 response v2 response body * string stream * * @param bucket * @param prefix * @param marker marker * @param limit 10000 * @param delimiter * @return Response okhttp response * @throws QiniuException */ public Response listV2(String bucket, String prefix, String marker, int limit, String delimiter) throws QiniuException { String url = String.format("%s/v2/list?%s", configuration.rsfHost(auth.accessKey, bucket), listQuery(bucket, prefix, marker, limit, delimiter)); return get(url); } public FileListing listFilesV2(String bucket, String prefix, String marker, int limit, String delimiter) throws QiniuException { Response response = listV2(bucket, prefix, marker, limit, delimiter); final String result = response.bodyString(); response.close(); List<String> lineList = Arrays.asList(result.split("\n")); FileListing fileListing = new FileListing(); List<FileInfo> fileInfoList = new ArrayList<>(); Set<String> commonPrefixSet = new HashSet<>(); for (int i = 0; i < lineList.size(); i++) { String line = lineList.get(i); JsonObject jsonObject = Json.decode(line, JsonObject.class); if (!(jsonObject.get("item") instanceof JsonNull)) fileInfoList.add(Json.decode(jsonObject.get("item"), FileInfo.class)); String dir = jsonObject.get("dir").getAsString(); if (!"".equals(dir)) commonPrefixSet.add(dir); if (i == lineList.size() - 1) fileListing.marker = jsonObject.get("marker").getAsString(); } fileListing.items = fileInfoList.toArray(new FileInfo[]{}); fileListing.commonPrefixes = commonPrefixSet.toArray(new String[]{}); return fileListing; } public FileInfo stat(String bucket, String fileKey) throws QiniuException { Response res = rsGet(bucket, String.format("/stat/%s", encodedEntry(bucket, fileKey))); if (!res.isOK()) { throw new QiniuException(res); } FileInfo fileInfo = res.jsonToObject(FileInfo.class); res.close(); return fileInfo; } public Response delete(String bucket, String key) throws QiniuException { return rsPost(bucket, String.format("/delete/%s", encodedEntry(bucket, key)), null); } public Response changeMime(String bucket, String key, String mime) throws QiniuException { String resource = encodedEntry(bucket, key); String encodedMime = UrlSafeBase64.encodeToString(mime); String path = String.format("/chgm/%s/mime/%s", resource, encodedMime); return rsPost(bucket, path, null); } public Response changeHeaders(String bucket, String key, Map<String, String> headers) throws QiniuException { String resource = encodedEntry(bucket, key); String path = String.format("/chgm/%s", resource); for (String k : headers.keySet()) { String encodedMetaValue = UrlSafeBase64.encodeToString(headers.get(k)); path = String.format("%s/x-qn-meta-!%s/%s", path, k, encodedMetaValue); } return rsPost(bucket, path, null); } /** * * * @param bucket * @param key * @param type type=0 type=1 * @throws QiniuException */ public Response changeType(String bucket, String key, StorageType type) throws QiniuException { String resource = encodedEntry(bucket, key); String path = String.format("/chtype/%s/type/%d", resource, type.ordinal()); return rsPost(bucket, path, null); } /** * * * @param bucket * @param key * @param status 01 * @throws QiniuException */ public Response changeStatus(String bucket, String key, int status) throws QiniuException { String resource = encodedEntry(bucket, key); String path = String.format("/chstatus/%s/status/%d", resource, status); return rsPost(bucket, path, null); } /** * forcetrue * * @param bucket * @param oldFileKey * @param newFileKey * @param force newFileKey * @throws QiniuException */ public Response rename(String bucket, String oldFileKey, String newFileKey, boolean force) throws QiniuException { return move(bucket, oldFileKey, bucket, newFileKey, force); } public Response rename(String bucket, String oldFileKey, String newFileKey) throws QiniuException { return move(bucket, oldFileKey, bucket, newFileKey); } /** * forcetrue * * @param fromBucket * @param fromFileKey * @param toBucket * @param toFileKey * @param force toFileKey * @throws QiniuException */ public Response copy(String fromBucket, String fromFileKey, String toBucket, String toFileKey, boolean force) throws QiniuException { String from = encodedEntry(fromBucket, fromFileKey); String to = encodedEntry(toBucket, toFileKey); String path = String.format("/copy/%s/%s/force/%s", from, to, force); return rsPost(fromBucket, path, null); } /** * * * @param fromBucket * @param fromFileKey * @param toBucket * @param toFileKey * @throws QiniuException */ public void copy(String fromBucket, String fromFileKey, String toBucket, String toFileKey) throws QiniuException { Response res = copy(fromBucket, fromFileKey, toBucket, toFileKey, false); if (!res.isOK()) { throw new QiniuException(res); } res.close(); } /** * * * @param fromBucket * @param fromFileKey * @param toBucket * @param toFileKey * @param force toFileKey * @throws QiniuException */ public Response move(String fromBucket, String fromFileKey, String toBucket, String toFileKey, boolean force) throws QiniuException { String from = encodedEntry(fromBucket, fromFileKey); String to = encodedEntry(toBucket, toFileKey); String path = String.format("/move/%s/%s/force/%s", from, to, force); return rsPost(fromBucket, path, null); } /** * , forcetrue * * @param fromBucket * @param fromFileKey * @param toBucket * @param toFileKey * @throws QiniuException */ public Response move(String fromBucket, String fromFileKey, String toBucket, String toFileKey) throws QiniuException { return move(fromBucket, fromFileKey, toBucket, toFileKey, false); } /** * * url * etag * * @param url * @param bucket * @throws QiniuException */ public FetchRet fetch(String url, String bucket) throws QiniuException { return fetch(url, bucket, null); } /** * * url * * @param url * @param bucket * @param key * @throws QiniuException */ public FetchRet fetch(String url, String bucket, String key) throws QiniuException { String resource = UrlSafeBase64.encodeToString(url); String to = encodedEntry(bucket, key); String path = String.format("/fetch/%s/to/%s", resource, to); Response res = ioPost(bucket, path); if (!res.isOK()) { throw new QiniuException(res); } FetchRet fetchRet = res.jsonToObject(FetchRet.class); res.close(); return fetchRet; } public Response asynFetch(String url, String bucket, String key) throws QiniuException { String requesturl = configuration.apiHost(auth.accessKey, bucket) + "/sisyphus/fetch"; StringMap stringMap = new StringMap().put("url", url).put("bucket", bucket).putNotNull("key", key); byte[] bodyByte = Json.encode(stringMap).getBytes(Constants.UTF_8); return client.post(requesturl, bodyByte, auth.authorizationV2(requesturl, "POST", bodyByte, "application/json"), Client.JsonMime); } public Response asynFetch(String url, String bucket, String key, String md5, String etag, String callbackurl, String callbackbody, String callbackbodytype, String callbackhost, String fileType) throws QiniuException { String requesturl = configuration.apiHost(auth.accessKey, bucket) + "/sisyphus/fetch"; StringMap stringMap = new StringMap().put("url", url).put("bucket", bucket). putNotNull("key", key).putNotNull("md5", md5).putNotNull("etag", etag). putNotNull("callbackurl", callbackurl).putNotNull("callbackbody", callbackbody). putNotNull("callbackbodytype", callbackbodytype). putNotNull("callbackhost", callbackhost).putNotNull("file_type", fileType); byte[] bodyByte = Json.encode(stringMap).getBytes(Constants.UTF_8); return client.post(requesturl, bodyByte, auth.authorizationV2(requesturl, "POST", bodyByte, "application/json"), Client.JsonMime); } /** * * * @param region bucket z0 z1 z2 na0 as0 * @param fetchWorkId id * @return Response * @throws QiniuException */ public Response checkAsynFetchid(String region, String fetchWorkId) throws QiniuException { String path = String.format("http://api-%s.qiniu.com/sisyphus/fetch?id=%s", region, fetchWorkId); return client.get(path, auth.authorization(path)); } /** * * * * @param bucket * @param key * @throws QiniuException */ public void prefetch(String bucket, String key) throws QiniuException { String resource = encodedEntry(bucket, key); String path = String.format("/prefetch/%s", resource); Response res = ioPost(bucket, path); if (!res.isOK()) { throw new QiniuException(res); } res.close(); } /** * * * @param bucket * @param srcSiteUrl */ public Response setImage(String bucket, String srcSiteUrl) throws QiniuException { return setImage(bucket, srcSiteUrl, null); } /** * * * @param bucket * @param srcSiteUrl * @param host Host */ public Response setImage(String bucket, String srcSiteUrl, String host) throws QiniuException { String encodedSiteUrl = UrlSafeBase64.encodeToString(srcSiteUrl); String encodedHost = null; if (host != null && host.length() > 0) { encodedHost = UrlSafeBase64.encodeToString(host); } String path = String.format("/image/%s/from/%s", bucket, encodedSiteUrl); if (encodedHost != null) { path += String.format("/host/%s", encodedHost); } return pubPost(path); } /** * * * @param bucket */ public Response unsetImage(String bucket) throws QiniuException { String path = String.format("/unimage/%s", bucket); return pubPost(path); } /** * * * @param bucket * @param key * @param days */ public Response deleteAfterDays(String bucket, String key, int days) throws QiniuException { return rsPost(bucket, String.format("/deleteAfterDays/%s/%d", encodedEntry(bucket, key), days), null); } public void setBucketAcl(String bucket, AclType acl) throws QiniuException { String url = String.format("%s/private?bucket=%s&private=%s", configuration.ucHost(), bucket, acl.getType()); Response res = post(url, null); if (!res.isOK()) { throw new QiniuException(res); } res.close(); } public BucketInfo getBucketInfo(String bucket) throws QiniuException { String url = String.format("%s/v2/bucketInfo?bucket=%s", configuration.ucHost(), bucket); Response res = post(url, null); if (!res.isOK()) { throw new QiniuException(res); } BucketInfo info = res.jsonToObject(BucketInfo.class); res.close(); return info; } public void setIndexPage(String bucket, IndexPageType type) throws QiniuException { String url = String.format("%s/noIndexPage?bucket=%s&noIndexPage=%s", configuration.ucHost(), bucket, type.getType()); Response res = post(url, null); if (!res.isOK()) { throw new QiniuException(res); } res.close(); } private Response rsPost(String bucket, String path, byte[] body) throws QiniuException { check(bucket); String url = configuration.rsHost(auth.accessKey, bucket) + path; return post(url, body); } private Response rsGet(String bucket, String path) throws QiniuException { check(bucket); String url = configuration.rsHost(auth.accessKey, bucket) + path; return get(url); } private Response ioPost(String bucket, String path) throws QiniuException { check(bucket); String url = configuration.ioHost(auth.accessKey, bucket) + path; return post(url, null); } private Response pubPost(String path) throws QiniuException { String url = "http://pu.qbox.me:10200" + path; return post(url, null); } private Response get(String url) throws QiniuException { StringMap headers = auth.authorization(url); return client.get(url, headers); } private Response post(String url, byte[] body) throws QiniuException { StringMap headers = auth.authorization(url, body, Client.FormMime); return client.post(url, body, headers, Client.FormMime); } private void check(String bucket) throws QiniuException { if (StringUtils.isNullOrEmpty(bucket)) { throw new QiniuException(Response.createError(null, null, 0, "")); } } public Response batch(BatchOperations operations) throws QiniuException { return rsPost(operations.execBucket(), "/batch", operations.toBody()); } public static class BatchOperations { private ArrayList<String> ops; private String execBucket = null; public BatchOperations() { this.ops = new ArrayList<String>(); } /** * chgm */ public BatchOperations addChgmOp(String bucket, String key, String newMimeType) { String resource = encodedEntry(bucket, key); String encodedMime = UrlSafeBase64.encodeToString(newMimeType); ops.add(String.format("/chgm/%s/mime/%s", resource, encodedMime)); setExecBucket(bucket); return this; } /** * copy */ public BatchOperations addCopyOp(String fromBucket, String fromFileKey, String toBucket, String toFileKey) { String from = encodedEntry(fromBucket, fromFileKey); String to = encodedEntry(toBucket, toFileKey); ops.add(String.format("copy/%s/%s", from, to)); setExecBucket(fromBucket); return this; } public BatchOperations addRenameOp(String fromBucket, String fromFileKey, String toFileKey) { return addMoveOp(fromBucket, fromFileKey, fromBucket, toFileKey); } /** * move */ public BatchOperations addMoveOp(String fromBucket, String fromKey, String toBucket, String toKey) { String from = encodedEntry(fromBucket, fromKey); String to = encodedEntry(toBucket, toKey); ops.add(String.format("move/%s/%s", from, to)); setExecBucket(fromBucket); return this; } /** * delete */ public BatchOperations addDeleteOp(String bucket, String... keys) { for (String key : keys) { ops.add(String.format("delete/%s", encodedEntry(bucket, key))); } setExecBucket(bucket); return this; } /** * stat */ public BatchOperations addStatOps(String bucket, String... keys) { for (String key : keys) { ops.add(String.format("stat/%s", encodedEntry(bucket, key))); } setExecBucket(bucket); return this; } /** * changeType */ public BatchOperations addChangeTypeOps(String bucket, StorageType type, String... keys) { for (String key : keys) { ops.add(String.format("chtype/%s/type/%d", encodedEntry(bucket, key), type.ordinal())); } setExecBucket(bucket); return this; } /** * changeStatus */ public BatchOperations addChangeStatusOps(String bucket, int status, String... keys) { for (String key : keys) { ops.add(String.format("chstatus/%s/status/%d", encodedEntry(bucket, key), status)); } setExecBucket(bucket); return this; } /** * deleteAfterDays */ public BatchOperations addDeleteAfterDaysOps(String bucket, int days, String... keys) { for (String key : keys) { ops.add(String.format("deleteAfterDays/%s/%d", encodedEntry(bucket, key), days)); } setExecBucket(bucket); return this; } public byte[] toBody() { String body = StringUtils.join(ops, "&op=", "op="); return StringUtils.utf8Bytes(body); } public BatchOperations merge(BatchOperations batch) { this.ops.addAll(batch.ops); setExecBucket(batch.execBucket()); return this; } public BatchOperations clearOps() { this.ops.clear(); return this; } private void setExecBucket(String bucket) { if (execBucket == null) { execBucket = bucket; } } public String execBucket() { return execBucket; } } public class FileListIterator implements Iterator<FileInfo[]> { private String marker = null; private String bucket; private String delimiter; private int limit; private String prefix; private QiniuException exception = null; public FileListIterator(String bucket, String prefix, int limit, String delimiter) { if (limit <= 0) { throw new IllegalArgumentException("limit must greater than 0"); } if (limit > 1000) { throw new IllegalArgumentException("limit must not greater than 1000"); } this.bucket = bucket; this.prefix = prefix; this.limit = limit; this.delimiter = delimiter; } public QiniuException error() { return exception; } @Override public boolean hasNext() { return exception == null && !"".equals(marker); } @Override public FileInfo[] next() { try { FileListing f = listFiles(bucket, prefix, marker, limit, delimiter); this.marker = f.marker == null ? "" : f.marker; return f.items; } catch (QiniuException e) { this.exception = e; return null; } } @Override public void remove() { throw new UnsupportedOperationException("remove"); } } }
package org.helioviewer.jhv.imagedata; import java.nio.ByteBuffer; import java.nio.ShortBuffer; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveTask; import java.util.ArrayList; import org.helioviewer.jhv.math.MathUtils; public class ImageFilter { private static final int SII_MIN_K = 3; private static final int SII_MAX_K = 5; private static final double sigma0 = 100.0 / Math.PI; private static final short[][] radii0 = { {76, 46, 23, 0, 0}, {82, 56, 37, 19, 0}, {85, 61, 44, 30, 16}}; private static final float[][] weights0 = { {0.1618f, 0.5502f, 0.9495f, 0, 0}, {0.0976f, 0.3376f, 0.6700f, 0.9649f, 0}, {0.0739f, 0.2534f, 0.5031f, 0.7596f, 0.9738f}}; // Box weights private final float[] weights = new float[SII_MAX_K]; // Box radii private final int[] radii = new int[SII_MAX_K]; // Number of boxes private final int K; private final float[] buffer; public ImageFilter(double sigma, int _K, int N) { K = _K; int i = K - SII_MIN_K; double sum = 0; for (int k = 0; k < K; ++k) { radii[k] = (int) (radii0[i][k] * (sigma / sigma0) + 0.5); sum += weights0[i][k] * (2 * radii[k] + 1); } for (int k = 0; k < K; ++k) weights[k] = (float) (weights0[i][k] / sum); int pad = radii[0] + 1; buffer = new float[N + 2 * pad]; } private static int extension(int N, int n) { while (true) { if (n < 0) n = -1 - n; // Reflect over n = -1/2 else if (n >= N) n = 2 * N - 1 - n; // Reflect over n = N - 1/2 else break; } return n; } private void gaussianConv(float[] dst, float[] src, int N, int stride, int offset) { int pad = radii[0] + 1; float accum = 0; // Compute cumulative sum of src over n = -pad,..., N + pad - 1 for (int n = -pad; n < 0; ++n) { accum += src[offset + stride * extension(N, n)]; buffer[pad + n] = accum; } for (int n = 0; n < N; ++n) { accum += src[offset + stride * n]; buffer[pad + n] = accum; } for (int n = N; n < N + pad; ++n) { accum += src[offset + stride * extension(N, n)]; buffer[pad + n] = accum; } // Compute stacked box filters for (int n = 0; n < N; ++n) { accum = weights[0] * (buffer[pad + n + radii[0]] - buffer[pad + n - radii[0] - 1]); for (int k = 1; k < K; ++k) accum += weights[k] * (buffer[pad + n + radii[k]] - buffer[pad + n - radii[k] - 1]); dst[offset + stride * n] = accum; } } private void gaussianConvImage(float[] dst, float[] src, int width, int height) { // Filter each row for (int y = 0; y < height; ++y) gaussianConv(dst, src, width, 1, width * y); // Filter each column for (int x = 0; x < width; ++x) gaussianConv(dst, dst, height, width, x); } private static final int _K = 3; private static final float H = 0.7f; private static final double[] sigmas = {1, 4, 16, 64}; @SuppressWarnings("serial") private static class ScaleTask extends RecursiveTask<float[]> { private final float[] data; private final int width; private final int height; private final double sigma; ScaleTask(float[] _data, int _width, int _height, double _sigma) { data = _data; width = _width; height = _height; sigma = _sigma; } @Override protected float[] compute() { ImageFilter filter = new ImageFilter(sigma, _K, Math.max(width, height)); int size = width * height; float[] conv = new float[size]; float[] conv2 = new float[size]; filter.gaussianConvImage(conv, data, width, height); for (int i = 0; i < size; ++i) { float v = data[i] - conv[i]; conv[i] = v; conv2[i] = v * v; } filter.gaussianConvImage(conv2, conv2, width, height); for (int i = 0; i < size; ++i) conv[i] = (float) MathUtils.clip(conv[i] / Math.sqrt(conv2[i]), -1, 1); return conv; } } private static float[] multiScale(float[] data, int width, int height) { ArrayList<ForkJoinTask<float[]>> tasks = new ArrayList<>(sigmas.length); for (double sigma : sigmas) tasks.add(new ScaleTask(data, width, height, sigma).fork()); int size = width * height; float[] image = new float[size]; for (ForkJoinTask<float[]> task : tasks) { float[] res = task.join(); for (int i = 0; i < size; ++i) image[i] += res[i]; } float min = 1e6f, max = -1e6f; for (int i = 0; i < size; ++i) { float v = image[i] / sigmas.length; if (v > max) max = v; if (v < min) min = v; image[i] = v; } if (max == min) return data; float k = (1 - H) / (max - min); for (int i = 0; i < size; ++i) { image[i] = k * (image[i] - min) + H * data[i]; } return image; } public static ByteBuffer mgn(ByteBuffer buf, int width, int height) { int size = width * height; float[] data = new float[size]; byte[] array = buf.array(); // always backed by array for (int i = 0; i < size; ++i) data[i] = ((array[i] + 256) & 0xFF) / 255f; float[] image = multiScale(data, width, height); byte[] out = new byte[size]; for (int i = 0; i < size; ++i) out[i] = (byte) MathUtils.clip(image[i] * 255 + .5f, 0, 255); return ByteBuffer.wrap(out); } public static ShortBuffer mgn(ShortBuffer buf, int width, int height) { int size = width * height; float[] data = new float[size]; short[] array = buf.array(); // always backed by array for (int i = 0; i < size; ++i) data[i] = ((array[i] + 65536) & 0xFFFF) / 65535f; float[] image = multiScale(data, width, height); short[] out = new short[size]; for (int i = 0; i < size; ++i) out[i] = (short) MathUtils.clip(image[i] * 65535 + .5f, 0, 65535); return ShortBuffer.wrap(out); } }
package com.rarchives.ripme.utils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Constructor; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.Line; import javax.sound.sampled.LineEvent; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import com.rarchives.ripme.ripper.AbstractRipper; /** * Common utility functions used in various places throughout the project. */ public class Utils { private static final String RIP_DIRECTORY = "rips"; private static final String configFile = "rip.properties"; private static final String OS = System.getProperty("os.name").toLowerCase(); private static final Logger logger = Logger.getLogger(Utils.class); private static PropertiesConfiguration config; static { try { String configPath = getConfigFilePath(); File f = new File(configPath); if (!f.exists()) { // Use default bundled with .jar configPath = configFile; } config = new PropertiesConfiguration(configPath); logger.info("Loaded " + config.getPath()); if (f.exists()) { // Config was loaded from file if ( !config.containsKey("twitter.auth") || !config.containsKey("twitter.max_requests") || !config.containsKey("tumblr.auth") || !config.containsKey("error.skip404") || !config.containsKey("gw.api") || !config.containsKey("page.timeout") || !config.containsKey("download.max_size") ) { // Config is missing key fields // Need to reload the default config logger.warn("Config does not contain key fields, deleting old config"); f.delete(); config = new PropertiesConfiguration(configFile); logger.info("Loaded " + config.getPath()); } } } catch (Exception e) { logger.error("[!] Failed to load properties file from " + configFile, e); } } /** * Get the root rips directory. * @return * Root directory to save rips to. * @throws IOException */ public static File getWorkingDirectory() { String currentDir = "."; try { currentDir = new File(".").getCanonicalPath() + File.separator + RIP_DIRECTORY + File.separator; } catch (IOException e) { logger.error("Error while finding working dir: ", e); } if (config != null) { currentDir = getConfigString("rips.directory", currentDir); } File workingDir = new File(currentDir); if (!workingDir.exists()) { workingDir.mkdirs(); } return workingDir; } public static String getConfigString(String key, String defaultValue) { return config.getString(key, defaultValue); } public static int getConfigInteger(String key, int defaultValue) { return config.getInt(key, defaultValue); } public static boolean getConfigBoolean(String key, boolean defaultValue) { return config.getBoolean(key, defaultValue); } public static List<String> getConfigList(String key) { List<String> result = new ArrayList<>(); for (Object obj : config.getList(key, new ArrayList<String>())) { if (obj instanceof String) { result.add( (String) obj); } } return result; } public static void setConfigBoolean(String key, boolean value) { config.setProperty(key, value); } public static void setConfigString(String key, String value) { config.setProperty(key, value); } public static void setConfigInteger(String key, int value) { config.setProperty(key, value); } public static void setConfigList(String key, List<Object> list) { config.clearProperty(key); config.addProperty(key, list); } public static void setConfigList(String key, Enumeration<Object> enumeration) { config.clearProperty(key); List<Object> list = new ArrayList<>(); while (enumeration.hasMoreElements()) { list.add(enumeration.nextElement()); } config.addProperty(key, list); } public static void saveConfig() { try { config.save(getConfigFilePath()); logger.info("Saved configuration to " + getConfigFilePath()); } catch (ConfigurationException e) { logger.error("Error while saving configuration: ", e); } } private static boolean isWindows() { return OS.contains("win"); } private static boolean isMacOS() { return OS.contains("mac"); } private static boolean isUnix() { return OS.contains("nix") || OS.contains("nux") || OS.contains("bsd"); } private static String getWindowsConfigDir() { return System.getenv("LOCALAPPDATA") + File.separator + "ripme"; } private static String getUnixConfigDir() { return System.getProperty("user.home") + File.separator + ".config" + File.separator + "ripme"; } private static String getMacOSConfigDir() { return System.getProperty("user.home") + File.separator + "Library" + File.separator + "Application Support" + File.separator + "ripme"; } private static boolean portableMode() { try { File f = new File(new File(".").getCanonicalPath() + File.separator + configFile); if(f.exists() && !f.isDirectory()) { return true; } } catch (IOException e) { return false; } return false; } public static String getConfigDir() { if (portableMode()) { try { return new File(".").getCanonicalPath(); } catch (Exception e) { return "."; } } if (isWindows()) return getWindowsConfigDir(); if (isMacOS()) return getMacOSConfigDir(); if (isUnix()) return getUnixConfigDir(); try { return new File(".").getCanonicalPath(); } catch (Exception e) { return "."; } } // Delete the url history file public static void clearURLHistory() { File file = new File(getURLHistoryFile()); file.delete(); } // Return the path of the url history file public static String getURLHistoryFile() { return getConfigDir() + File.separator + "url_history.txt"; } private static String getConfigFilePath() { return getConfigDir() + File.separator + configFile; } /** * Removes the current working directory (CWD) from a File. * @param saveAs * The File path * @return * saveAs in relation to the CWD */ public static String removeCWD(File saveAs) { String prettySaveAs = saveAs.toString(); try { prettySaveAs = saveAs.getCanonicalPath(); String cwd = new File(".").getCanonicalPath() + File.separator; prettySaveAs = prettySaveAs.replace( cwd, "." + File.separator); } catch (Exception e) { logger.error("Exception: ", e); } return prettySaveAs; } public static String stripURLParameter(String url, String parameter) { int paramIndex = url.indexOf("?" + parameter); boolean wasFirstParam = true; if (paramIndex < 0) { wasFirstParam = false; paramIndex = url.indexOf("&" + parameter); } if (paramIndex > 0) { int nextParam = url.indexOf("&", paramIndex+1); if (nextParam != -1) { String c = "&"; if (wasFirstParam) { c = "?"; } url = url.substring(0, paramIndex) + c + url.substring(nextParam+1, url.length()); } else { url = url.substring(0, paramIndex); } } return url; } /** * Removes the current working directory from a given filename * @param file * @return * 'file' without the leading current working directory */ public static String removeCWD(String file) { return removeCWD(new File(file)); } /** * Get a list of all Classes within a package. * Works with file system projects and jar files! * Borrowed from StackOverflow, but I don't have a link :[ * @param pkgname * The name of the package * @return * List of classes within the package */ public static ArrayList<Class<?>> getClassesForPackage(String pkgname) { ArrayList<Class<?>> classes = new ArrayList<>(); String relPath = pkgname.replace('.', '/'); URL resource = ClassLoader.getSystemClassLoader().getResource(relPath); if (resource == null) { throw new RuntimeException("No resource for " + relPath); } String fullPath = resource.getFile(); File directory = null; try { directory = new File(resource.toURI()); } catch (URISyntaxException e) { throw new RuntimeException(pkgname + " (" + resource + ") does not appear to be a valid URL / URI. Strange, since we got it from the system...", e); } catch (IllegalArgumentException e) { directory = null; } if (directory != null && directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (String file : files) { if (file.endsWith(".class") && !file.contains("$")) { String className = pkgname + '.' + file.substring(0, file.length() - 6); try { classes.add(Class.forName(className)); } catch (ClassNotFoundException e) { throw new RuntimeException("ClassNotFoundException loading " + className); } } } } else { // Load from JAR try { String jarPath = fullPath .replaceFirst("[.]jar[!].*", ".jar") .replaceFirst("file:", ""); jarPath = URLDecoder.decode(jarPath, "UTF-8"); JarFile jarFile = new JarFile(jarPath); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry nextElement = entries.nextElement(); String entryName = nextElement.getName(); if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length()) && !nextElement.isDirectory()) { String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", ""); try { classes.add(Class.forName(className)); } catch (ClassNotFoundException e) { logger.error("ClassNotFoundException loading " + className); jarFile.close(); // Resource leak fix? throw new RuntimeException("ClassNotFoundException loading " + className); } } } jarFile.close(); // Eclipse said not closing it would have a resource leak } catch (IOException e) { logger.error("Error while loading jar file:", e); throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e); } } return classes; } private static final int SHORTENED_PATH_LENGTH = 12; public static String shortenPath(String path) { return shortenPath(new File(path)); } public static String shortenPath(File file) { String path = removeCWD(file); if (path.length() < SHORTENED_PATH_LENGTH * 2) { return path; } return path.substring(0, SHORTENED_PATH_LENGTH) + "..." + path.substring(path.length() - SHORTENED_PATH_LENGTH); } public static String filesystemSanitized(String text) { text = text.replaceAll("[^a-zA-Z0-9.-]", "_"); return text; } public static String filesystemSafe(String text) { text = text.replaceAll("[^a-zA-Z0-9.-]", "_") .replaceAll("__", "_") .replaceAll("_+$", ""); if (text.length() > 100) { text = text.substring(0, 99); } return text; } /** * Checks if given path already exists as lowercase * * @param path - original path entered to be ripped * @return path of existing folder or the original path if not present */ public static String getOriginalDirectory(String path) { int index; if(isUnix() || isMacOS()) { index = path.lastIndexOf('/'); } else { // current OS is windows - nothing to do here return path; } String original = path; // needs to be checked if lowercase exists String lastPart = original.substring(index+1).toLowerCase(); // setting lowercase to check if it exists // Get a List of all Directories and check its lowercase // if file exists return it File f = new File(path.substring(0, index)); ArrayList<String> names = new ArrayList<String>(Arrays.asList(f.list())); for (String s : names) { if(s.toLowerCase().equals(lastPart)) { // Building Path of existing file return path.substring(0, index) + File.separator + s; } } return original; } public static String bytesToHumanReadable(int bytes) { float fbytes = (float) bytes; String[] mags = new String[] {"", "K", "M", "G", "T"}; int magIndex = 0; while (fbytes >= 1024) { fbytes /= 1024; magIndex++; } return String.format("%.2f%siB", fbytes, mags[magIndex]); } public static List<String> getListOfAlbumRippers() throws Exception { List<String> list = new ArrayList<>(); for (Constructor<?> ripper : AbstractRipper.getRipperConstructors("com.rarchives.ripme.ripper.rippers")) { list.add(ripper.getName()); } return list; } public static List<String> getListOfVideoRippers() throws Exception { List<String> list = new ArrayList<>(); for (Constructor<?> ripper : AbstractRipper.getRipperConstructors("com.rarchives.ripme.ripper.rippers.video")) { list.add(ripper.getName()); } return list; } public static void playSound(String filename) { URL resource = ClassLoader.getSystemClassLoader().getResource(filename); try { final Clip clip = (Clip) AudioSystem.getLine(new Line.Info(Clip.class)); clip.addLineListener(event -> { if (event.getType() == LineEvent.Type.STOP) { clip.close(); } }); clip.open(AudioSystem.getAudioInputStream(resource)); clip.start(); } catch (Exception e) { logger.error("Failed to play sound " + filename, e); } } /** * Configures root logger, either for FILE output or just console. */ public static void configureLogger() { LogManager.shutdown(); String logFile; if (getConfigBoolean("log.save", false)) { logFile = "log4j.file.properties"; } else { logFile = "log4j.properties"; } InputStream stream = Utils.class.getClassLoader().getResourceAsStream(logFile); if (stream == null) { PropertyConfigurator.configure("src/main/resources/" + logFile); } else { PropertyConfigurator.configure(stream); } logger.info("Loaded " + logFile); try { stream.close(); } catch (IOException e) { } } /** * Gets list of strings between two strings. * @param fullText Text to retrieve from. * @param start String that precedes the desired text * @param finish String that follows the desired text * @return List of all strings that are between 'start' and 'finish' */ public static List<String> between(String fullText, String start, String finish) { List<String> result = new ArrayList<>(); int i, j; i = fullText.indexOf(start); while (i >= 0) { i += start.length(); j = fullText.indexOf(finish, i); if (j < 0) { break; } result.add(fullText.substring(i, j)); i = fullText.indexOf(start, j + finish.length()); } return result; } /** * Parses an URL query * * @param query * The query part of an URL * @return The map of all query parameters */ public static Map<String,String> parseUrlQuery(String query) { Map<String,String> res = new HashMap<>(); if (query.equals("")) { return res; } String[] parts = query.split("&"); int pos; try { for (String part : parts) { if ((pos = part.indexOf('=')) >= 0) { res.put(URLDecoder.decode(part.substring(0, pos), "UTF-8"), URLDecoder.decode(part.substring(pos + 1), "UTF-8")); } else { res.put(URLDecoder.decode(part, "UTF-8"), ""); } } } catch (UnsupportedEncodingException e) { // Shouldn't happen since UTF-8 is required to be supported throw new RuntimeException(e); } return res; } /** * Parses an URL query and returns the requested parameter's value * * @param query * The query part of an URL * @param key * The key whose value is requested * @return The associated value or null if key wasn't found */ public static String parseUrlQuery(String query, String key) { if (query.equals("")) { return null; } String[] parts = query.split("&"); int pos; try { for (String part : parts) { if ((pos = part.indexOf('=')) >= 0) { if (URLDecoder.decode(part.substring(0, pos), "UTF-8").equals(key)) { return URLDecoder.decode(part.substring(pos + 1), "UTF-8"); } } else if (URLDecoder.decode(part, "UTF-8").equals(key)) { return ""; } } } catch (UnsupportedEncodingException e) { // Shouldn't happen since UTF-8 is required to be supported throw new RuntimeException(e); } return null; } private static HashMap<String, HashMap<String, String>> cookieCache; static { cookieCache = new HashMap<String, HashMap<String, String>>(); } public static Map<String, String> getCookies(String host) { HashMap<String, String> domainCookies = cookieCache.get(host); if (domainCookies == null) { domainCookies = new HashMap<String, String>(); String cookiesConfig = getConfigString("cookies." + host, ""); for (String pair : cookiesConfig.split(" ")) { pair = pair.trim(); if (pair.contains("=")) { String[] pieces = pair.split("=", 2); domainCookies.put(pieces[0], pieces[1]); } } cookieCache.put(host, domainCookies); } return domainCookies; } }
package pt.up.fe.aiad.gui.controllers; import jade.wrapper.AgentContainer; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TextField; import javafx.stage.Stage; import pt.up.fe.aiad.scheduler.SchedulerAgent; import pt.up.fe.aiad.utils.FXUtils; import pt.up.fe.aiad.utils.IPAddressValidator; import pt.up.fe.aiad.utils.StringUtils; import java.util.Random; public class MainController { private static Random r = new Random(); public static AgentContainer container = null; @FXML private TextField _addressTextField; @FXML private TextField _nicknameTextField; @FXML private CheckBox _showGUICheckBox; @FXML private Button _startClientButton; @FXML private Button _startServerButton; @FXML private ChoiceBox<SchedulerAgent.Type> _algorithmChoiceBox; private static String _exampleNicknames[] = new String[] { "Luis", "Duarte", "Miguel", "Ruben", "Adolf", "Anne", "Frank", "Katie", "Natalie", "Benji", "Makoto Yooko", "Dovahkiin", "Judith", "Zelda", "Link", "Red", "Ash", "Mario", "Luigi", "Wario", "Lucina", "Kirby", "Pikachu", "Diglet", "Misty", "Brock", "Ezio", "Captain Falcon", "Captain Shepard", "Master Chief", "Spyro", "Ryu", "Megaman", "Lara Croft", "Gordon Freeman", "Solid Snake", "Samus", "Sonic", "Tails", "Kratos", "Donkey Kong", "Dante", "Obi Wan Kenobi", "Anakin Skywalker", "Luke Skywalker", "Bomberman" }; @FXML void initialize() { _nicknameTextField.textProperty().addListener((observable, oldValue, newValue) -> validateClientInput()); _addressTextField.textProperty().addListener((observable, oldValue, newValue) -> validateClientInput()); _addressTextField.setText("127.0.0.1:1099"); _nicknameTextField.setText(getNewNickname()); _algorithmChoiceBox.getItems().addAll(SchedulerAgent.Type.values()); _algorithmChoiceBox.setValue(SchedulerAgent.Type.values()[0]); } private static String getNewNickname() { return _exampleNicknames[r.nextInt(_exampleNicknames.length)]; } @FXML void startClientButtonOnAction(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(getClass().getResource("../views/client.fxml")); Stage stage = new Stage(); stage.setTitle(_nicknameTextField.getText() + " | " + _algorithmChoiceBox.getValue() + " | iScheduler"); Scene scene = new Scene(loader.load()); scene.getStylesheets().add(getClass().getResource("../views/main.css").toExternalForm()); stage.setScene(scene); String addressSplit[] = _addressTextField.getText().split(":"); ClientController controller = loader.<ClientController>getController(); controller.initData(addressSplit[0], Integer.parseInt(addressSplit[1]), _nicknameTextField.getText(), _algorithmChoiceBox.getValue(), stage); controller.start(); stage.show(); stage.setOnHiding(eventHiding -> controller.stop()); _nicknameTextField.setText(getNewNickname()); } catch (Exception e) { FXUtils.showExceptionDialog(e); } } @FXML void startServerButtonOnAction(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(getClass().getResource("../views/server.fxml")); Stage stage = new Stage(); stage.setTitle("Server | iScheduler"); Scene scene = new Scene(loader.load()); scene.getStylesheets().add(getClass().getResource("../views/main.css").toExternalForm()); stage.setScene(scene); ServerController controller = loader.<ServerController>getController(); controller.initData(stage, _showGUICheckBox.isSelected()); controller.start(); stage.show(); _startServerButton.setDisable(true); _addressTextField.setDisable(true); stage.setOnHiding(eventHiding -> { _startServerButton.setDisable(false); _addressTextField.setDisable(false); }); } catch (Exception e) { FXUtils.showExceptionDialog(e); } } private void validateClientInput() { _startClientButton.setDisable(true); if (StringUtils.isNullOrEmpty(_addressTextField.getText())) return; if (StringUtils.isNullOrEmpty(_nicknameTextField.getText())) return; if (!IPAddressValidator.validate(_addressTextField.getText(), true)) return; _startClientButton.setDisable(false); } }
package org.mtransit.android.data; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.WeakHashMap; import org.mtransit.android.R; import org.mtransit.android.commons.CollectionUtils; import org.mtransit.android.commons.ColorUtils; import org.mtransit.android.commons.Constants; import org.mtransit.android.commons.LocationUtils; import org.mtransit.android.commons.MTLog; import org.mtransit.android.commons.SensorUtils; import org.mtransit.android.commons.TimeUtils; import org.mtransit.android.commons.data.AvailabilityPercent; import org.mtransit.android.commons.data.POI; import org.mtransit.android.commons.data.POIStatus; import org.mtransit.android.commons.data.RouteTripStop; import org.mtransit.android.commons.data.Schedule; import org.mtransit.android.commons.task.MTAsyncTask; import org.mtransit.android.commons.ui.widget.MTArrayAdapter; import org.mtransit.android.provider.FavoriteManager; import org.mtransit.android.provider.FavoriteManager.FavoriteUpdateListener; import org.mtransit.android.task.StatusLoader; import org.mtransit.android.ui.view.MTCompassView; import org.mtransit.android.ui.view.MTPieChartPercentView; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.location.Location; import android.os.Handler; import android.text.TextUtils; import android.util.Pair; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; public class POIArrayAdapter extends MTArrayAdapter<POIManager> implements SensorUtils.CompassListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, SensorEventListener, AbsListView.OnScrollListener, StatusLoader.StatusLoaderListener, MTLog.Loggable, FavoriteUpdateListener, SensorUtils.SensorTaskCompleted { private static final String TAG = POIArrayAdapter.class.getSimpleName(); private String tag = TAG; @Override public String getLogTag() { return tag; } public void setTag(String tag) { this.tag = tag; } private static IntentFilter s_intentFilter; static { s_intentFilter = new IntentFilter(); s_intentFilter.addAction(Intent.ACTION_TIME_TICK); s_intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED); s_intentFilter.addAction(Intent.ACTION_TIME_CHANGED); } private LayoutInflater layoutInflater; private List<POIManager> pois; private Set<String> favUUIDs; private Activity activity; private Location location; private int lastCompassInDegree = -1; private float locationDeclination; @Deprecated private Pair<Integer, String> closestPOI; private int lastSuccessfulRefresh = -1; private float[] accelerometerValues = new float[3]; private float[] magneticFieldValues = new float[3]; private boolean showStatus = true; // show times / availability private ViewGroup manualLayout; private ScrollView manualScrollView; private long lastNotifyDataSetChanged = -1; private int scrollState = AbsListView.OnScrollListener.SCROLL_STATE_IDLE; private long nowToTheMinute = -1; private boolean timeChangedReceiverEnabled = false; private boolean compassUpdatesEnabled = false; private long lastCompassChanged = -1; public POIArrayAdapter(Activity activity) { super(activity, R.layout.layout_loading_small); this.activity = activity; this.layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void setManualLayout(ViewGroup manualLayout) { this.manualLayout = manualLayout; } public void setShowStatus(boolean showData) { this.showStatus = showData; } private static final int VIEW_TYPE_COUNT = 4; @Override public int getViewTypeCount() { // RETURN MUST MATCH getItemViewType(position) ! return VIEW_TYPE_COUNT; // see getItemViewType() } @Override public int getItemViewType(int position) { // RETURN MUST MATCH getViewTypeCount() ! POIManager poim = getItem(position); if (poim == null) { MTLog.d(this, "Cannot find type for object null!"); return Adapter.IGNORE_ITEM_VIEW_TYPE; } int type = poim.poi.getType(); int statusType = poim.getStatusType(); switch (type) { case POI.ITEM_VIEW_TYPE_ROUTE_TRIP_STOP: switch (statusType) { case POI.ITEM_STATUS_TYPE_SCHEDULE: return 3; // RTS & SCHEDULE default: return 4; // RTS } case POI.ITEM_VIEW_TYPE_BASIC_POI: default: switch (statusType) { case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT: return 0; // DEFAULT & AVAILABILITY % default: return 1; // DEFAULT } } } @Override public int getCount() { final int count = pois == null ? 0 : pois.size(); return count; } @Override public int getPosition(POIManager item) { final int position = pois == null ? 0 : pois.indexOf(item); return position; } @Override public POIManager getItem(int position) { final POIManager item = this.pois == null ? null : this.pois.get(position); return item; } @Override public View getView(int position, View convertView, ViewGroup parent) { POIManager poim = getItem(position); if (poim == null) { MTLog.w(this, "getView() > Cannot create view for null poi at position '%s'!", position); return null; // CRASH!!! } switch (poim.poi.getType()) { case POI.ITEM_VIEW_TYPE_ROUTE_TRIP_STOP: return getRouteTripStopView(poim, convertView, parent); case POI.ITEM_VIEW_TYPE_BASIC_POI: return getBasicPOIView(poim, convertView, parent); default: MTLog.w(this, "getView() > Unknow view type at position %s!", position); return null; // CRASH!!! } } private void updateCommonViewManual(int position, View convertView) { if (convertView == null || convertView.getTag() == null || !(convertView.getTag() instanceof CommonViewHolder)) { return; } CommonViewHolder holder = (CommonViewHolder) convertView.getTag(); POIManager poim = getItem(position); updateCommonView(holder, poim); return; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { showPoiViewerActivity(position); } @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { return showPoiMenu(position); } public boolean showClosestPOI() { if (!hasClosestPOI()) { return false; } return false; } public boolean showPoiViewerActivity(int position) { if (this.pois != null && position < this.pois.size() && this.pois.get(position) != null) { return showPoiViewerActivity(this.pois.get(position)); } return false; } public boolean showPoiMenu(int position) { if (this.pois != null && position < this.pois.size() && this.pois.get(position) != null) { return showPoiMenu(this.pois.get(position)); } return false; } public boolean showPoiViewerActivity(final POIManager poim) { if (poim == null) { return false; } if (poim.onActionItemClick(this.activity)) { return true; } MTLog.w(this, "Unknow view type for poi %s!", poim); return false; } public boolean showPoiMenu(final POIManager poim) { if (poim == null) { return false; } switch (poim.poi.getType()) { case POI.ITEM_VIEW_TYPE_ROUTE_TRIP_STOP: case POI.ITEM_VIEW_TYPE_BASIC_POI: StringBuilder title = new StringBuilder(poim.poi.getName()); final Favorite findFavorite = FavoriteManager.findFavorite(getContext(), poim.poi.getUUID()); final boolean isFavorite = findFavorite != null; new AlertDialog.Builder(getContext()).setTitle(title) .setItems(poim.getActionsItems(getContext(), getContext().getString(R.string.view_details), isFavorite), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { MTLog.v(POIArrayAdapter.this, "onClick(%s)", item); if (poim.onActionsItemClick(POIArrayAdapter.this.activity, item, isFavorite, POIArrayAdapter.this)) { return; } switch (item) { case 0: showPoiViewerActivity(poim); break; default: break; } } }).create().show(); return true; default: MTLog.w(this, "Unknow view type for poi %s!", poim); return false; } } @Override public void onFavoriteUpdated() { refreshFavorites(); } public void setPois(List<POIManager> pois) { this.pois = pois; } public List<POIManager> getPois() { return pois; } public int getPoisCount() { if (pois == null) { return 0; } return pois.size(); } public boolean hasPois() { return getPoisCount() > 0; } @Deprecated private void updateClosestPoi() { } @Deprecated public boolean hasClosestPOI() { return false; } @Deprecated public boolean isClosestPOI(int position) { return false; } public POI findPoi(String uuid) { if (this.pois != null) { for (final POIManager poim : this.pois) { if (poim.poi.getUUID().equals(uuid)) { return poim.poi; } } } return null; } public int indexOfPoi(String uuid) { if (this.pois != null) { for (int i = 0; i < pois.size(); i++) { if (pois.get(i).poi.getUUID().equals(uuid)) { return i; } } } return -1; } @Deprecated public void prefetchClosests() { } @Deprecated public void prefetchFavorites() { } private MTAsyncTask<Location, Void, Void> updateDistanceWithStringTask; private void updateDistances(Location currentLocation) { if (this.updateDistanceWithStringTask != null) { this.updateDistanceWithStringTask.cancel(true); } if (this.pois != null && currentLocation != null) { this.updateDistanceWithStringTask = new MTAsyncTask<Location, Void, Void>() { @Override public String getLogTag() { return POIArrayAdapter.this.getLogTag(); } @Override protected Void doInBackgroundMT(Location... params) { android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); LocationUtils.updateDistanceWithString(POIArrayAdapter.this.getContext(), POIArrayAdapter.this.pois, params[0], this); return null; } @Override protected void onPostExecute(Void result) { if (isCancelled()) { return; } final Pair<Integer, String> previousClosest = POIArrayAdapter.this.closestPOI; updateClosestPoi(); boolean newClosest = POIArrayAdapter.this.closestPOI == null ? false : POIArrayAdapter.this.closestPOI.equals(previousClosest); notifyDataSetChanged(newClosest); prefetchClosests(); } }; this.updateDistanceWithStringTask.execute(currentLocation); } } public void updateDistancesNowSync(Location currentLocation) { if (this.pois != null && currentLocation != null) { LocationUtils.updateDistanceWithString(getContext(), this.pois, currentLocation, null); updateClosestPoi(); } setLocation(currentLocation); } public void updateDistanceNowAsync(Location currentLocation) { this.location = null; // clear current location to force refresh setLocation(currentLocation); } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { setScrollState(scrollState); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } public void setScrollState(int scrollState) { this.scrollState = scrollState; } @Override public void onStatusLoaded(POIStatus status) { if (this.showStatus) { // needs to force data set changed or schedule might never be shown if (this.poiStatusViewHoldersWR != null && this.poiStatusViewHoldersWR.containsKey(status.getTargetUUID())) { updatePOIStatus(this.poiStatusViewHoldersWR.get(status.getTargetUUID()), status); } } } public void notifyDataSetChanged(boolean force) { notifyDataSetChanged(force, Constants.ADAPTER_NOTIFY_THRESOLD_IN_MS); } private Handler handler = new Handler(); private Runnable notifyDataSetChangedLater = new Runnable() { @Override public void run() { notifyDataSetChanged(true); // still really need to show new data } }; public void notifyDataSetChanged(boolean force, int minAdapterThresoldInMs) { long now = System.currentTimeMillis(); final long adapterThreasold = Math.max(minAdapterThresoldInMs, Constants.ADAPTER_NOTIFY_THRESOLD_IN_MS); if (this.scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && (force || (now - this.lastNotifyDataSetChanged) > adapterThreasold)) { notifyDataSetChanged(); notifyDataSetChangedManual(); this.lastNotifyDataSetChanged = now; this.handler.removeCallbacks(this.notifyDataSetChangedLater); tryLoadingScheduleIfNotBusy(); } else { // IF we really needed to show new data AND list wasn't not idle DO try again later if (force && this.scrollState != AbsListView.OnScrollListener.SCROLL_STATE_IDLE) { this.handler.postDelayed(this.notifyDataSetChangedLater, adapterThreasold); } } } private void notifyDataSetChangedManual() { if (this.manualLayout != null && hasPois()) { int position = 0; for (int i = 0; i < this.manualLayout.getChildCount(); i++) { View view = this.manualLayout.getChildAt(i); Object tag = view.getTag(); if (tag != null && tag instanceof CommonViewHolder) { updateCommonViewManual(position, view); position++; } } } } public void setListView(AbsListView listView) { listView.setOnItemClickListener(this); listView.setOnItemLongClickListener(this); listView.setOnScrollListener(this); listView.setAdapter(this); } public void initManual() { if (this.manualLayout != null && hasPois()) { this.manualLayout.removeAllViews(); for (int i = 0; i < getPoisCount(); i++) { if (this.manualLayout.getChildCount() > 0) { this.manualLayout.addView(this.layoutInflater.inflate(R.layout.list_view_divider, this.manualLayout, false)); } View view = getView(i, null, this.manualLayout); final int position = i; view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPoiViewerActivity(position); } }); view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { return showPoiMenu(position); } }); this.manualLayout.addView(view); } } } public void scrollManualScrollViewTo(int x, int y) { if (this.manualScrollView != null) { this.manualScrollView.scrollTo(x, y); } } public void setManualScrollView(ScrollView scrollView) { this.manualScrollView = scrollView; if (scrollView == null) { return; } scrollView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_SCROLL: case MotionEvent.ACTION_MOVE: setScrollState(AbsListView.OnScrollListener.SCROLL_STATE_FLING); break; case MotionEvent.ACTION_DOWN: setScrollState(AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: // scroll view can still by flying setScrollState(AbsListView.OnScrollListener.SCROLL_STATE_IDLE); break; default: MTLog.v(POIArrayAdapter.this, "Unexpected event %s", event); } return false; } }); } public void setLocation(Location newLocation) { if (newLocation != null) { if (this.location == null || LocationUtils.isMoreRelevant(getLogTag(), this.location, newLocation)) { this.location = newLocation; this.locationDeclination = SensorUtils.getLocationDeclination(this.location); if (!this.compassUpdatesEnabled) { SensorUtils.registerCompassListener(getContext(), this); this.compassUpdatesEnabled = true; } updateDistances(this.location); } } } public void onPause() { if (this.compassUpdatesEnabled) { SensorUtils.unregisterSensorListener(getContext(), this); this.compassUpdatesEnabled = false; } this.handler.removeCallbacks(this.notifyDataSetChangedLater); if (this.refreshFavoritesTask != null) { this.refreshFavoritesTask.cancel(true); this.refreshFavoritesTask = null; } disableTimeChangeddReceiver(); } @Override public String toString() { return new StringBuilder().append(POIArrayAdapter.class.getSimpleName()) .append(getLogTag()) .toString(); } public void onResume() { if (!this.compassUpdatesEnabled) { SensorUtils.registerCompassListener(getContext(), this); this.compassUpdatesEnabled = true; } } public void onDestroy() { disableTimeChangeddReceiver(); } @Override public void updateCompass(final float orientation, boolean force) { if (this.pois == null) { return; } long now = System.currentTimeMillis(); int roundedOrientation = SensorUtils.convertToPosivite360Degree((int) orientation); SensorUtils.updateCompass(force, this.location, roundedOrientation, now, this.scrollState, this.lastCompassChanged, this.lastCompassInDegree, Constants.ADAPTER_NOTIFY_THRESOLD_IN_MS, this); } @Override public void onSensorTaskCompleted(boolean result, int roundedOrientation, long now) { if (result) { this.lastCompassInDegree = roundedOrientation; this.lastCompassChanged = now; if (this.compassUpdatesEnabled && this.location != null && this.lastCompassInDegree >= 0) { if (this.compassImgsWR != null) { for (MTCompassView compassView : this.compassImgsWR.keySet()) { if (compassView != null && compassView.getVisibility() == View.VISIBLE) { compassView.generateAndSetHeading(this.location, this.lastCompassInDegree, this.locationDeclination); } } } } } } @Override public void onSensorChanged(SensorEvent se) { SensorUtils.checkForCompass(getContext(), se, this.accelerometerValues, this.magneticFieldValues, this); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } private WeakHashMap<String, CommonStatusViewHolder> poiStatusViewHoldersWR = new WeakHashMap<String, CommonStatusViewHolder>(); private View getBasicPOIView(POIManager poim, View convertView, ViewGroup parent) { if (convertView == null) { convertView = this.layoutInflater.inflate(getBasicPOILayout(poim.getStatusType()), parent, false); BasicPOIViewHolder holder = new BasicPOIViewHolder(); initCommonViewHolder(holder, convertView, poim.poi.getUUID()); holder.statusViewHolder = getPOIStatusViewHolder(poim.getStatusType(), convertView); this.poiStatusViewHoldersWR.put(holder.uuid, holder.statusViewHolder); convertView.setTag(holder); } updateBasicPOIView(poim, convertView); return convertView; } private CommonStatusViewHolder getPOIStatusViewHolder(int status, View convertView) { switch (status) { case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT: AvailabilityPercentStatusViewHolder availabilityPercentStatusViewHolder = new AvailabilityPercentStatusViewHolder(); initCommonStatusViewHolderHolder(availabilityPercentStatusViewHolder, convertView); availabilityPercentStatusViewHolder.textTv = (TextView) convertView.findViewById(R.id.textTv); availabilityPercentStatusViewHolder.piePercentV = (MTPieChartPercentView) convertView.findViewById(R.id.pie); return availabilityPercentStatusViewHolder; case POI.ITEM_STATUS_TYPE_SCHEDULE: ScheduleStatusViewHolder scheduleStatusViewHolder = new ScheduleStatusViewHolder(); initCommonStatusViewHolderHolder(scheduleStatusViewHolder, convertView); scheduleStatusViewHolder.dataNextLine1Tv = (TextView) convertView.findViewById(R.id.data_next_line_1); scheduleStatusViewHolder.dataNextLine2Tv = (TextView) convertView.findViewById(R.id.data_next_line_2); return scheduleStatusViewHolder; default: MTLog.w(this, "Unexpected status '%s' (no view holder)!", status); return null; } } private int getBasicPOILayout(int status) { int layoutRes = R.layout.layout_poi_basic; switch (status) { case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT: layoutRes = R.layout.layout_poi_basic_availability_percent; break; default: MTLog.w(this, "Unexpected status '%s' (basic view w/o status)!", status); break; } return layoutRes; } private WeakHashMap<MTCompassView, Object> compassImgsWR = new WeakHashMap<MTCompassView, Object>(); private void initCommonViewHolder(CommonViewHolder holder, View convertView, String poiUUID) { holder.uuid = poiUUID; holder.view = convertView; holder.nameTv = (TextView) convertView.findViewById(R.id.name); holder.favImg = (ImageView) convertView.findViewById(R.id.fav); holder.distanceTv = (TextView) convertView.findViewById(R.id.distance); holder.compassV = (MTCompassView) convertView.findViewById(R.id.compass); this.compassImgsWR.put(holder.compassV, null); } private static void initCommonStatusViewHolderHolder(CommonStatusViewHolder holder, View convertView) { holder.statusV = convertView.findViewById(R.id.status); } private View updateBasicPOIView(POIManager poim, View convertView) { if (convertView == null || poim == null) { return convertView; } BasicPOIViewHolder holder = (BasicPOIViewHolder) convertView.getTag(); updateCommonView(holder, poim); updatePOIStatus(holder.statusViewHolder, poim); return convertView; } private void updateAvailabilityPercent(CommonStatusViewHolder statusViewHolder, POIManager poim) { if (this.showStatus && poim != null && statusViewHolder instanceof AvailabilityPercentStatusViewHolder) { poim.setStatusLoaderListener(this); updateAvailabilityPercent(statusViewHolder, poim.getStatus(getContext())); } else { statusViewHolder.statusV.setVisibility(View.GONE); } } private void updateAvailabilityPercent(CommonStatusViewHolder statusViewHolder, POIStatus status) { AvailabilityPercentStatusViewHolder availabilityPercentStatusViewHolder = (AvailabilityPercentStatusViewHolder) statusViewHolder; if (status != null && status instanceof AvailabilityPercent) { AvailabilityPercent availabilityPercent = (AvailabilityPercent) status; if (!availabilityPercent.isStatusOK()) { availabilityPercentStatusViewHolder.textTv.setText(availabilityPercent.getStatusMsg(getContext())); availabilityPercentStatusViewHolder.textTv.setVisibility(View.VISIBLE); availabilityPercentStatusViewHolder.piePercentV.setVisibility(View.GONE); } else if (availabilityPercent.isShowingLowerValue()) { availabilityPercentStatusViewHolder.textTv.setText(availabilityPercent.getLowerValueText(getContext())); availabilityPercentStatusViewHolder.textTv.setVisibility(View.VISIBLE); availabilityPercentStatusViewHolder.piePercentV.setVisibility(View.GONE); } else { availabilityPercentStatusViewHolder.piePercentV.setValueColors( availabilityPercent.getValue1Color(), availabilityPercent.getValue1ColorBg(), availabilityPercent.getValue2Color(), availabilityPercent.getValue2ColorBg() ); availabilityPercentStatusViewHolder.piePercentV.setValues(availabilityPercent.getValue1(), availabilityPercent.getValue2()); availabilityPercentStatusViewHolder.piePercentV.setVisibility(View.VISIBLE); availabilityPercentStatusViewHolder.textTv.setVisibility(View.GONE); } statusViewHolder.statusV.setVisibility(View.VISIBLE); } else { statusViewHolder.statusV.setVisibility(View.GONE); } } public void setLastSuccessfulRefresh(int lastSuccessfulRefresh) { this.lastSuccessfulRefresh = lastSuccessfulRefresh; } public int getLastSuccessfulRefresh() { return lastSuccessfulRefresh; } private int getRTSLayout(int status) { int layoutRes = R.layout.layout_poi_rts; switch (status) { case POI.ITEM_STATUS_TYPE_SCHEDULE: layoutRes = R.layout.layout_poi_rts_schedule; break; default: MTLog.w(this, "Unexpected status '%s' (rts view w/o status)!", status); break; } return layoutRes; } private View getRouteTripStopView(POIManager poim, View convertView, ViewGroup parent) { if (convertView == null) { convertView = this.layoutInflater.inflate(getRTSLayout(poim.getStatusType()), parent, false); RouteTripStopViewHolder holder = new RouteTripStopViewHolder(); initCommonViewHolder(holder, convertView, poim.poi.getUUID()); initRTSExtra(convertView, holder); // schedule status holder.statusViewHolder = getPOIStatusViewHolder(poim.getStatusType(), convertView); this.poiStatusViewHoldersWR.put(holder.uuid, holder.statusViewHolder); convertView.setTag(holder); } updateRouteTripStopView(poim, convertView); return convertView; } private void initRTSExtra(View convertView, RouteTripStopViewHolder holder) { holder.rtsExtraV = convertView.findViewById(R.id.rts_extra); holder.routeFL = convertView.findViewById(R.id.route); holder.routeShortNameTv = (TextView) convertView.findViewById(R.id.route_short_name); holder.tripHeadingTv = (TextView) convertView.findViewById(R.id.trip_heading); } private View updateRouteTripStopView(POIManager poim, View convertView) { if (convertView == null || poim == null) { return convertView; } RouteTripStopViewHolder holder = (RouteTripStopViewHolder) convertView.getTag(); updateCommonView(holder, poim); updateRTSExtra(poim, holder); updatePOIStatus(holder.statusViewHolder, poim); return convertView; } private void updateRTSExtra(POIManager poim, RouteTripStopViewHolder holder) { if (poim.poi instanceof RouteTripStop) { final RouteTripStop rts = (RouteTripStop) poim.poi; if (rts.route == null) { holder.rtsExtraV.setVisibility(View.GONE); holder.routeFL.setVisibility(View.GONE); holder.tripHeadingTv.setVisibility(View.GONE); } else { int routeTextColor = ColorUtils.parseColor(rts.route.textColor); int routeColor = ColorUtils.parseColor(rts.route.color); if (TextUtils.isEmpty(rts.route.shortName)) { holder.routeShortNameTv.setVisibility(View.INVISIBLE); } else { holder.routeShortNameTv.setText(rts.route.shortName); holder.routeShortNameTv.setTextColor(routeTextColor); holder.routeShortNameTv.setVisibility(View.VISIBLE); } holder.routeFL.setBackgroundColor(routeColor); holder.routeFL.setVisibility(View.VISIBLE); holder.rtsExtraV.setVisibility(View.VISIBLE); if (rts.trip == null) { holder.tripHeadingTv.setVisibility(View.GONE); } else { holder.tripHeadingTv.setText(rts.trip.getHeading(getContext()).toUpperCase(Locale.getDefault())); holder.tripHeadingTv.setVisibility(View.VISIBLE); } } } } private void updatePOIStatus(CommonStatusViewHolder statusViewHolder, POIStatus status) { if (!this.showStatus || status == null || statusViewHolder == null) { if (statusViewHolder != null) { statusViewHolder.statusV.setVisibility(View.GONE); } return; } switch (status.getType()) { case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT: updateAvailabilityPercent(statusViewHolder, status); break; case POI.ITEM_STATUS_TYPE_SCHEDULE: updateRTSSchedule(statusViewHolder, status); break; default: MTLog.w(this, "Unexpected status type '%s'!", status.getType()); statusViewHolder.statusV.setVisibility(View.GONE); return; } } private void updatePOIStatus(CommonStatusViewHolder statusViewHolder, POIManager poim) { if (!this.showStatus || poim == null || statusViewHolder == null) { if (statusViewHolder != null) { statusViewHolder.statusV.setVisibility(View.GONE); } return; } switch (poim.getStatusType()) { case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT: updateAvailabilityPercent(statusViewHolder, poim); break; case POI.ITEM_STATUS_TYPE_SCHEDULE: updateRTSSchedule(statusViewHolder, poim); break; default: MTLog.w(this, "Unexpected status type '%s'!", poim.getStatusType()); statusViewHolder.statusV.setVisibility(View.GONE); } } private void updateRTSSchedule(CommonStatusViewHolder statusViewHolder, POIManager poim) { if (this.showStatus && poim != null && statusViewHolder instanceof ScheduleStatusViewHolder) { poim.setStatusLoaderListener(this); updateRTSSchedule(statusViewHolder, poim.getStatus(getContext())); } else { statusViewHolder.statusV.setVisibility(View.GONE); } } private void updateRTSSchedule(CommonStatusViewHolder statusViewHolder, POIStatus status) { CharSequence line1CS = null; CharSequence line2CS = null; if (status != null && status instanceof Schedule) { Schedule schedule = (Schedule) status; final int count = 20; // needs enough to check if service is frequent (every 5 minutes or less for at least 30 minutes) List<Pair<CharSequence, CharSequence>> lines = schedule.getNextTimesStrings(getContext(), getNowToTheMinute(), count); // , schedule.decentOnly); if (lines != null && lines.size() >= 1) { line1CS = lines.get(0).first; line2CS = lines.get(0).second; } } ScheduleStatusViewHolder scheduleStatusViewHolder = (ScheduleStatusViewHolder) statusViewHolder; scheduleStatusViewHolder.dataNextLine1Tv.setText(line1CS); scheduleStatusViewHolder.dataNextLine2Tv.setText(line2CS); scheduleStatusViewHolder.dataNextLine2Tv.setVisibility(line2CS != null && line2CS.length() > 0 ? View.VISIBLE : View.GONE); statusViewHolder.statusV.setVisibility(line1CS != null && line1CS.length() > 0 ? View.VISIBLE : View.GONE); } private long getNowToTheMinute() { if (this.nowToTheMinute < 0) { resetNowToTheMinute(); enableTimeChangedReceiver(); } return this.nowToTheMinute; } private void resetNowToTheMinute() { this.nowToTheMinute = TimeUtils.currentTimeToTheMinuteMillis(); notifyDataSetChanged(false); // TODO true? } private final BroadcastReceiver timeChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (Intent.ACTION_TIME_TICK.equals(action) || Intent.ACTION_TIME_CHANGED.equals(action) || Intent.ACTION_TIMEZONE_CHANGED.equals(action)) { resetNowToTheMinute(); tryLoadingScheduleIfNotBusy(); } } }; private void tryLoadingScheduleIfNotBusy() { } private void enableTimeChangedReceiver() { if (!this.timeChangedReceiverEnabled) { getContext().registerReceiver(timeChangedReceiver, s_intentFilter); this.timeChangedReceiverEnabled = true; } } private void disableTimeChangeddReceiver() { if (this.timeChangedReceiverEnabled) { getContext().unregisterReceiver(this.timeChangedReceiver); this.timeChangedReceiverEnabled = false; this.nowToTheMinute = -1; } } private void updateCommonView(CommonViewHolder holder, POIManager poim) { if (poim == null || holder == null) { return; } if (holder.uuid != null) { this.poiStatusViewHoldersWR.remove(holder.uuid); } holder.uuid = poim.poi.getUUID(); if (holder.uuid != null) { this.poiStatusViewHoldersWR.put(holder.uuid, holder.statusViewHolder); } holder.compassV.setLatLng(poim.getLat(), poim.getLng()); // name holder.nameTv.setText(poim.poi.getName()); // distance if (!TextUtils.isEmpty(poim.getDistanceString())) { if (!poim.getDistanceString().equals(holder.distanceTv.getText())) { holder.distanceTv.setText(poim.getDistanceString()); } holder.distanceTv.setVisibility(View.VISIBLE); } else { holder.distanceTv.setVisibility(View.GONE); holder.distanceTv.setText(null); } // compass (if distance available) if (holder.distanceTv.getVisibility() == View.VISIBLE && this.location != null && this.lastCompassInDegree >= 0 && this.location.getAccuracy() <= poim.getDistance()) { float compassRotation = SensorUtils.getCompassRotationInDegree(this.location.getLatitude(), this.location.getLongitude(), poim.getLat(), poim.getLng(), this.lastCompassInDegree, this.locationDeclination); holder.compassV.setHeadingInDegree((int) compassRotation); holder.compassV.setVisibility(View.VISIBLE); } else { holder.compassV.setVisibility(View.GONE); } // favorite if (this.favUUIDs != null && this.favUUIDs.contains(poim.poi.getUUID())) { holder.favImg.setVisibility(View.VISIBLE); } else { holder.favImg.setVisibility(View.GONE); } } private MTAsyncTask<Integer, Void, List<Favorite>> refreshFavoritesTask; public void refreshFavorites(Integer... typesFilter) { if (this.refreshFavoritesTask != null && this.refreshFavoritesTask.getStatus() == MTAsyncTask.Status.RUNNING) { return; // skipped, last refresh still in progress so probably good enough } this.refreshFavoritesTask = new MTAsyncTask<Integer, Void, List<Favorite>>() { @Override public String getLogTag() { return POIArrayAdapter.this.getLogTag(); } @Override protected List<Favorite> doInBackgroundMT(Integer... params) { return FavoriteManager.findFavorites(POIArrayAdapter.this.getContext(), params); } @Override protected void onPostExecute(List<Favorite> result) { setFavorites(result); }; }; this.refreshFavoritesTask.execute(typesFilter); } public void setFavorites(List<Favorite> favorites) { boolean newFav = false; // don't trigger update if favorites are the same if (CollectionUtils.getSize(favorites) != CollectionUtils.getSize(this.favUUIDs)) { newFav = true; // different size => different favorites } Set<String> newFavUUIDs = new HashSet<String>(); if (favorites != null) { for (Favorite favorite : favorites) { final String uid = favorite.getFkId(); if (!newFav && this.favUUIDs != null && !this.favUUIDs.contains(uid)) { newFav = true; } newFavUUIDs.add(uid); break; } } this.favUUIDs = newFavUUIDs; if (newFav) { notifyDataSetChanged(true); prefetchFavorites(); } } public static class RouteTripStopViewHolder extends CommonViewHolder { TextView routeShortNameTv; View routeFL; View rtsExtraV; TextView tripHeadingTv; } public static class BasicPOIViewHolder extends CommonViewHolder { } public static class CommonViewHolder { String uuid; View view; TextView nameTv; TextView distanceTv; ImageView favImg; MTCompassView compassV; CommonStatusViewHolder statusViewHolder; } public static class ScheduleStatusViewHolder extends CommonStatusViewHolder { TextView dataNextLine1Tv; TextView dataNextLine2Tv; } public static class AvailabilityPercentStatusViewHolder extends CommonStatusViewHolder { TextView textTv; MTPieChartPercentView piePercentV; } public static class CommonStatusViewHolder { View statusV; } }
package com.venky.cache; import com.esotericsoftware.kryo.KryoException; import com.venky.core.util.MultiException; import com.venky.core.util.ObjectUtil; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.util.AbstractSet; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public abstract class PersistentCache<K,V> extends Cache<K, V>{ private static final long serialVersionUID = -1707252397643517532L; public PersistentCache() { this(Cache.MAX_ENTRIES_DEFAULT,Cache.PRUNE_FACTOR_DEFAULT); } public PersistentCache(int maxEntries,double pruneFactor) { super(maxEntries,pruneFactor); } public int size() { ensureOpen(); return indexMap.size(); } public boolean containsKey(Object key) { ensureOpen(); return indexMap.containsKey(key); } @Override public boolean containsValue(Object value) { ensureOpen(); for (K k : keySet()) { if (get(k).equals(value)) { return true; } } return false; } @Override public Set<K> keySet(){ ensureOpen(); return new AbstractSet<K>() { @Override public Iterator<K> iterator() { Iterator<K> ki = new Iterator<K>() { Iterator<K> keys = indexMap.keySet().iterator(); @Override public boolean hasNext() { return keys.hasNext(); } @Override public K next() { return keys.next(); } }; return ki; } @Override public int size() { return indexMap.size(); } }; } @Override public Set<V> values(){ ensureOpen(); Set<V> set = new AbstractSet<V>() { @Override public Iterator<V> iterator() { return new Iterator<V>() { Iterator<K> keys = indexMap.keySet().iterator(); @Override public boolean hasNext() { return keys.hasNext(); } @Override public V next() { return get(keys.next()); } }; } @Override public int size() { return indexMap.size(); } }; return set; } @SuppressWarnings("unchecked") @Override public V get(Object key){ ensureOpen(); V v = null; if (super.containsKey(key)) { v = super.get(key); }else { synchronized (this) { if (super.containsKey(key)) { v = super.get(key); }else { v = getPersistedValue((K)key); put((K)key, v, true); } } } return v; } public V put(K key,V value){ return put(key,value,false); } private V put(K key,V value,boolean alreadyPersisted){ ensureOpen(); V ret = super.put(key,value); if (!alreadyPersisted){ indexMap.remove(key); } if (!indexMap.containsKey(key)){ if (isAutoPersist()) { persist(key,value); }else { indexMap.put(key, -1L); } } return ret; } @Override protected void evictKeys(List<K> keys){ super.evictKeys(keys); flush(); } @Override protected V evictKey(K key){ V value = super.evictKey(key); if (!indexMap.containsKey(key) || indexMap.get(key) < 0) { persist(key, value, false); } return value; } public V remove(Object key){ ensureOpen(); super.remove(key); Long position = indexMap.get(key); V v = null; if (position != null){ if (position > 0) { synchronized (this) { KryoStore cacheStore = getCacheStore(); cacheStore.position(position); K k = cacheStore.read(); V pv = cacheStore.read(); if (k.equals(key)) { indexMap.remove(key);//Will need to repersist. v = pv; compactIndex(); } } }else { indexMap.remove(key); } } return v; } private KryoStore indexStore = null ; private KryoStore cacheStore = null ; private KryoStore getIndexStore() { synchronized (this){ if (indexStore == null ) { indexStore = new KryoStore(getIndexDB()); } } return indexStore; } private KryoStore getCacheStore() { synchronized (this){ if (cacheStore == null) { cacheStore = new KryoStore(getCacheDB()); } } return cacheStore; } private Map<K,Long> indexMap = null; public void persist(K k, V v) { persist(k,v,true); } private void persist(K k, V v,boolean flush) { ensureOpen(); synchronized (this){ KryoStore indexStore = getIndexStore(); KryoStore cacheStore = getCacheStore(); if (cacheStore.getWriterPosition() < cacheStore.size()){ cacheStore.position(cacheStore.size()); } if (indexStore.getWriterPosition() < indexStore.size()) { indexStore.position(getIndexStore().size()); } long iPos = indexStore.getWriterPosition(); long cPos = cacheStore.getWriterPosition(); MultiException mex = new MultiException("Cache could not be persisted!"); try { if (indexMap.containsKey(k) && indexMap.get(k) > 0) { return; } indexStore.write(k); indexStore.write(new Long(cPos)); if (flush) { indexStore.flush(); } cacheStore.write(k); cacheStore.write(v); if (flush) { cacheStore.flush(); } indexMap.put(k, cPos); } catch (KryoException e) { mex.add(e); try { indexStore.position(iPos); cacheStore.position(cPos); indexStore.truncate(iPos); cacheStore.truncate(cPos); }catch(KryoException ke) { mex.add(ke); //Cache is corrupt. indexStore.delete(); cacheStore.delete(); this.indexStore = null; this.cacheStore = null; } throw mex; } } } @Override public Set<java.util.Map.Entry<K, V>> entrySet() { ensureOpen(); return new AbstractSet<Map.Entry<K,V>>() { @Override public Iterator<Entry<K, V>> iterator() { return new Iterator<Entry<K,V>>(){ Iterator<K> keys = keySet().iterator(); @Override public boolean hasNext() { return keys.hasNext(); } @Override public Entry<K, V> next() { final K key = keys.next(); final V v = get(key); return new Entry<K, V>() { @Override public K getKey() { return key; } @Override public V getValue() { return v; } @Override public V setValue(V value) { if (!ObjectUtil.equals(v, value)) { indexMap.remove(key); put(key,value); } return v; } }; } }; } @Override public int size() { return indexMap.size(); } }; } protected V getPersistedValue(K key) { Long position = indexMap.get(key); V v = null; if (position == null) { v = getValue(key); }else { synchronized (this) { KryoStore cacheStore = getCacheStore(); cacheStore.position(position); K k = cacheStore.read(); V pv = cacheStore.read(); if (k.equals(key)) { v = pv; } } if (v == null){ indexMap.remove(key);//Will need to repersist. v = getValue(key); } } return v; } private void ensureOpen(){ if (indexMap != null){ return; } synchronized (this){ if (indexMap != null){ return; } Map<K,Long> tmp = new HashMap<>(); KryoStore indexStore = getIndexStore(); while (! indexStore.eof() ) { K k = indexStore.read(); Long v = indexStore.read(); tmp.put(k,v); } indexMap = tmp; } } public void close() { clear(); indexMap.clear(); getIndexStore().close(); getCacheStore().close(); this.cacheStore = null ; this.indexStore = null ; } protected File getTempCacheDB() { return new File(getCacheDirectory(),"data.work.db"); } protected File getTempIndexDB() { return new File(getCacheDirectory(),"index.work.db"); } protected File getCacheDB() { return new File(getCacheDirectory(),"data.db"); } protected File getIndexDB() { return new File(getCacheDirectory(),"index.db"); } protected File getCacheDirectory(){ String cacheDir = getCacheDirectoryName(); if (cacheDir == null) { throw new NullPointerException("Cache Directory not passed"); }else { File cd = new File(cacheDir); cd.mkdirs(); if (!cd.isDirectory()) { throw new RuntimeException(cacheDir + " is not a directory!"); }else if (!cd.exists()) { throw new RuntimeException("Unable to create directory " + cacheDir ); } return cd; } } protected abstract String getCacheDirectoryName(); @Override protected abstract V getValue(K key) ; private boolean autoPersist = true; public boolean isAutoPersist() { return autoPersist; } public void setAutoPersist(boolean autoPersist){ this.autoPersist = autoPersist; } public void persist() { List<K> keys = new ArrayList<>(keySet()); for (K k : keys) { //Avoid concurrent modification exception. persist(k,get(k),false); } flush(); } private void flush(){ getIndexStore().flush(); getCacheStore().flush(); } public void persist(K k) { persist(k,get(k)); } public synchronized void compact() { KryoStore oldStore = getCacheStore(); KryoStore oldIndexStore = getIndexStore(); KryoStore newStore = new KryoStore(getTempCacheDB()); KryoStore newIndexStore = new KryoStore(getTempIndexDB()); for (Map.Entry<K,Long> entry : indexMap.entrySet() ){ K k= entry.getKey(); Long p= entry.getValue(); oldStore.position(p); K pk = oldStore.read(); V v = oldStore.read(); if (k.equals(pk)) { newStore.write(k); newStore.write(v); newIndexStore.write(k); newIndexStore.write(new Long(newStore.getWriterPosition())); } }; oldStore.close(); oldIndexStore.close(); newStore.close(); newIndexStore.close(); move(getTempCacheDB(),getCacheDB()); move(getTempIndexDB(),getIndexDB()); this.cacheStore = null; this.indexStore = null; } protected synchronized void compactIndex() { KryoStore indexStore = new KryoStore(getTempIndexDB()); for( Map.Entry<K,Long> entry : indexMap.entrySet() ) { K k = entry.getKey(); Long p = entry.getValue(); indexStore.write(k); indexStore.write(p); }; indexStore.close(); move(getTempIndexDB(),getIndexDB()); this.indexStore = null; } protected void move (File source , File target) { if (!target.equals(source)){ try { target.delete(); FileUtils.moveFile(source, target); } catch (IOException e) { throw new RuntimeException(e); } } } }
package org.myrobotlab.service; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.genetic.GeneticAlgorithm; import org.myrobotlab.genetic.Chromosome; import org.myrobotlab.genetic.Genetic; import org.myrobotlab.kinematics.CollisionDectection; import org.myrobotlab.kinematics.CollisionItem; import org.myrobotlab.kinematics.DHLink; import org.myrobotlab.kinematics.DHRobotArm; import org.myrobotlab.kinematics.Map3D; import org.myrobotlab.kinematics.Map3DPoint; import org.myrobotlab.kinematics.Matrix; import org.myrobotlab.kinematics.Point; import org.myrobotlab.kinematics.TestJmeIntegratedMovement; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.math.Mapper; import org.myrobotlab.math.MathUtils; import org.myrobotlab.openni.OpenNiData; import org.myrobotlab.service.Servo.IKData; import org.myrobotlab.service.interfaces.IKJointAnglePublisher; import org.myrobotlab.service.interfaces.PointsListener; import org.slf4j.Logger; /** * * IntegratedMovement - This class provides a 3D based inverse kinematics * implementation that allows you to specify the robot arm geometry based on DH * Parameters. The work is based on InversedKinematics3D by kwatters with different computation and goal, * including collision detection and moveToObject * * Rotation and Orientation information is not currently supported. (but should * be easy to add) * * @author Christian/Calamity * */ public class IntegratedMovement extends Service implements IKJointAnglePublisher, PointsListener, Genetic { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(InverseKinematics3D.class.getCanonicalName()); private DHRobotArm currentArm = null; private HashMap<String, DHRobotArm> arms = new HashMap<String, DHRobotArm>(); private Matrix inputMatrix = null; Point goTo; private CollisionDectection collisionItems = new CollisionDectection(); public static final int IK_COMPUTE_METHOD_PI_JACOBIAN = 1; public static final int IK_COMPUTE_METHOD_GENETIC_ALGORYTHM = 2; private int computeMethod = IK_COMPUTE_METHOD_PI_JACOBIAN; private int geneticPoolSize = 200; private double geneticMutationRate = 0.01; private double geneticRecombinationRate = 0.7; private int geneticGeneration = 300; private boolean geneticComputeSimulation = false; private HashMap<String, Servo> currentServos = new HashMap<String, Servo>(); //private HashMap<String, HashMap<String, Servo>> servos = new HashMap<String, HashMap<String, Servo>>(); private double time; private boolean stopMoving = false; public enum ObjectPointLocation { ORIGIN_CENTER (0x01,"Center Origin"), ORIGIN_SIDE (0x02, "Side Origin"), END_SIDE(0x04, "Side End"), END_CENTER(0x05, "Center End"), CLOSEST_POINT(0x06, "Closest Point"), CENTER(0x07, "Center"), CENTER_SIDE(0x08, "Side Center"); public int value; public String location; private ObjectPointLocation(int value, String location) { this.value = value; this.location = location; } } private class MoveInfo { Point offset = null; CollisionItem targetItem = null; ObjectPointLocation objectLocation = null; DHLink lastLink = null; } private MoveInfo moveInfo = null; private OpenNi openni = null; public Map3D map3d = new Map3D(); private String kinectName = "kinect"; private boolean ProcessKinectData = false; TestJmeIntegratedMovement jmeApp = null; public IntegratedMovement(String n) { super(n); } public void changeArm(String arm) { if (arms.containsKey(arm)) { currentArm = arms.get(arm); //currentServos = servos.get(arm); } else { log.info("IK service have no data for {}", arm); } } public Point currentPosition() { return currentArm.getPalmPosition(); } public Point currentPosition(String arm) { if (arms.containsKey(arm)) { return arms.get(arm).getPalmPosition(); } log.info("IK service have no data for {}", arm); return new Point(0, 0, 0, 0, 0, 0); } public void moveTo(double x, double y, double z) { // TODO: allow passing roll pitch and yaw moveTo(new Point(x, y, z, 0, 0, 0)); } public void moveTo(String arm, double x, double y, double z) { moveTo(arm, new Point(x, y, z, 0, 0, 0)); } /** * This create a rotation and translation matrix that will be applied on the * "moveTo" call. * * @param dx * - x axis translation * @param dy * - y axis translation * @param dz * - z axis translation * @param roll * - rotation about z (in degrees) * @param pitch * - rotation about x (in degrees) * @param yaw * - rotation about y (in degrees) * @return */ public Matrix createInputMatrix(double dx, double dy, double dz, double roll, double pitch, double yaw) { roll = MathUtils.degToRad(roll); pitch = MathUtils.degToRad(pitch); yaw = MathUtils.degToRad(yaw); Matrix trMatrix = Matrix.translation(dx, dy, dz); Matrix rotMatrix = Matrix.zRotation(roll).multiply(Matrix.yRotation(yaw).multiply(Matrix.xRotation(pitch))); inputMatrix = trMatrix.multiply(rotMatrix); return inputMatrix; } public Point rotateAndTranslate(Point pIn) { Matrix m = new Matrix(4, 1); m.elements[0][0] = pIn.getX(); m.elements[1][0] = pIn.getY(); m.elements[2][0] = pIn.getZ(); m.elements[3][0] = 1; Matrix pOM = inputMatrix.multiply(m); // TODO: compute the roll pitch yaw double roll = 0; double pitch = 0; double yaw = 0; Point pOut = new Point(pOM.elements[0][0], pOM.elements[1][0], pOM.elements[2][0], roll, pitch, yaw); return pOut; } public void moveTo(Point p) { // log.info("Move TO {}", p ); if (inputMatrix != null) { p = rotateAndTranslate(p); } boolean success = false; if(computeMethod == IK_COMPUTE_METHOD_PI_JACOBIAN) { success = currentArm.moveToGoal(p); } else if (computeMethod == IK_COMPUTE_METHOD_GENETIC_ALGORYTHM) { goTo = p; GeneticAlgorithm GA = new GeneticAlgorithm(this, geneticPoolSize, currentArm.getNumLinks(), 11, geneticRecombinationRate, geneticMutationRate); //HashMap<Integer,Integer> lastIteration = new HashMap<Integer,Integer>(); int retry = 0; //stopMoving = false; while (retry++ < 100) { if (stopMoving) { //stopMoving = false; break; } Chromosome bestFit = GA.doGeneration(geneticGeneration); // this is the number of time the chromosome pool will be recombined and mutate //DHRobotArm checkedArm = simulateMove(bestFit.getDecodedGenome()); currentArm = simulateMove(bestFit.getDecodedGenome()); for (int i = 0; i < currentArm.getNumLinks(); i++){ Servo servo = currentServos.get(currentArm.getLink(i).getName()); while (servo.isMoving()){ sleep(10); } } for (int i = 0; i < currentArm.getNumLinks(); i++){ Servo servo = currentServos.get(currentArm.getLink(i).getName()); servo.moveTo(currentArm.getLink(i).getPositionValueDeg()); } this. log.info("moving to {}", currentPosition()); if (collisionItems.haveCollision()) { //collision avoiding need to be improved CollisionItem ci = null; int itemIndex = 0; for (DHLink l : currentArm.getLinks()) { boolean foundIt = false; for (itemIndex = 0; itemIndex < 2; itemIndex++) { if (l.getName().equals(collisionItems.getCollisionItem()[itemIndex].getName())) { ci = collisionItems.getCollisionItem()[itemIndex]; foundIt = true; break; } } if (foundIt) break; //we have the item to watch } if (ci == null) { log.info("Collision between static item {} and {} detected", collisionItems.getCollisionItem()[0].getName(), collisionItems.getCollisionItem()[1].getName()); break; //collision is between items that we can't control } //current implementation of the collision avoidance is not very good //need to calculate a vector away from the object and a vector to avoid the object and move that way //current implementation add a bias toward outside position Point newPos = currentPosition(); newPos.setX(newPos.getX()+collisionItems.getCollisionPoint()[itemIndex].getX()-collisionItems.getCollisionPoint()[1-itemIndex].getX()); newPos.setY(newPos.getY()+collisionItems.getCollisionPoint()[itemIndex].getY()-collisionItems.getCollisionPoint()[1-itemIndex].getY()); newPos.setZ(newPos.getZ()+collisionItems.getCollisionPoint()[itemIndex].getZ()-collisionItems.getCollisionPoint()[1-itemIndex].getZ()); Point ori=collisionItems.getCollisionItem()[1-itemIndex].getOrigin(); Point end=collisionItems.getCollisionItem()[1-itemIndex].getEnd(); Point colPoint = collisionItems.getCollisionPoint()[1-itemIndex]; if (collisionItems.getCollisionLocation()[1-itemIndex] > 0.0 || collisionItems.getCollisionLocation()[1-itemIndex] < 1.0) { // collision on the side of item if (collisionItems.getCollisionLocation()[1-itemIndex] < 0.5) { //collision near the origin newPos.setX(newPos.getX()+ori.getX()-colPoint.getX()); newPos.setY(newPos.getY()+ori.getY()-colPoint.getY()); newPos.setZ(newPos.getZ()+ori.getZ()-colPoint.getZ()); } else { //collision near the end newPos.setX(newPos.getX()+end.getX()-colPoint.getX()); newPos.setY(newPos.getY()+end.getY()-colPoint.getY()); newPos.setZ(newPos.getZ()+end.getZ()-colPoint.getZ()); } } //move away by the radius of the part double length = collisionItems.getCollisionItem()[1-itemIndex].getLength(); double ratio = collisionItems.getCollisionItem()[itemIndex].getRadius() / length; double[] vector = collisionItems.getCollisionItem()[1-itemIndex].getVector(); for (int i=0; i<3; i++){ vector[i] *= ratio; } if (collisionItems.getCollisionLocation()[1-itemIndex] < 0.5) { //collision near the origin newPos.setX(newPos.getX() - vector[0]); newPos.setY(newPos.getY() - vector[1]); newPos.setZ(newPos.getZ() - vector[2]); } else { newPos.setX(newPos.getX() + vector[0]); newPos.setY(newPos.getY() + vector[1]); newPos.setZ(newPos.getZ() + vector[2]); } this.outbox.notify(); Point oldGoTo = goTo; if(!stopMoving) moveTo(newPos); goTo = oldGoTo; if (moveInfo != null) { goTo = moveToObject(); } } else break; } } if (success) { publishTelemetry(); } } public void moveTo(String arm, Point p) { changeArm(arm); moveTo(p); } public void publishTelemetry() { Map<String, Double> angleMap = new HashMap<String, Double>(); for (DHLink l : currentArm.getLinks()) { String jointName = l.getName(); double theta = l.getTheta(); // angles between 0 - 360 degrees.. not sure what people will really want? // - 180 to + 180 ? angleMap.put(jointName, (double) MathUtils.radToDeg(theta) % 360.0F); } invoke("publishJointAngles", angleMap); // we want to publish the joint positions // this way we can render on the web gui.. double[][] jointPositionMap = createJointPositionMap(); // TODO: pass a better datastructure? invoke("publishJointPositions", (Object) jointPositionMap); } public double[][] createJointPositionMap() { return createJointPositionMap(currentArm); } public double[][] createJointPositionMap(String arm) { changeArm(arm); return createJointPositionMap(currentArm); } public double[][] createJointPositionMap(DHRobotArm arm) { double[][] jointPositionMap = new double[arm.getNumLinks() + 1][3]; // first position is the origin... second is the end of the first link jointPositionMap[0][0] = 0; jointPositionMap[0][1] = 0; jointPositionMap[0][2] = 0; for (int i = 1; i <= arm.getNumLinks(); i++) { Point jp = arm.getJointPosition(i - 1); jointPositionMap[i][0] = jp.getX(); jointPositionMap[i][1] = jp.getY(); jointPositionMap[i][2] = jp.getZ(); } return jointPositionMap; } public DHRobotArm getCurrentArm() { return currentArm; } public DHRobotArm getArm(String arm) { if (arms.containsKey(arm)) { return arms.get(arm); } else return currentArm; } public void setCurrentArm(DHRobotArm currentArm) { this.currentArm = currentArm; } public void setCurrentArm(String name) { if (arms.get(name) != null) { this.currentArm = arms.get(name); } else { log.info("Arm do not exist"); } } public void addArm(String name, DHRobotArm currentArm) { arms.put(name, currentArm); this.currentArm = currentArm; } public static void main(String[] args) throws Exception { LoggingFactory.init(Level.INFO); Runtime.createAndStart("python", "Python"); Runtime.createAndStart("gui", "GUIService"); IntegratedMovement ik = (IntegratedMovement) Runtime.start("ik", "IntegratedMovement"); Arduino arduino = (Arduino) Runtime.start("arduino", "Arduino"); arduino.connect("COM22"); arduino.enableBoardInfo(false); //define and attach servo //map is set so servo accept angle as input, output where //they need to go so that their part they where attach to //move by the input degree Servo mtorso = (Servo)Runtime.start("mtorso","Servo"); mtorso.attach(arduino,26,90); mtorso.map(15,165,148,38); //#mtorso.setMinMax(35,150); mtorso.setVelocity(13); mtorso.moveTo(90); Servo ttorso = (Servo) Runtime.start("ttorso","Servo"); ttorso.attach(arduino,7,90); ttorso.map(80,100,92,118); //ttorso.setInverted(False) //#ttorso.setMinMax(85,125) ttorso.setVelocity(13); ttorso.moveTo(90); Servo omoplate = (Servo) Runtime.start("omoplate","Servo"); omoplate.attach(arduino,11,10); omoplate.map(10,70,10,70); omoplate.setVelocity(15); //#omoplate.setMinMax(10,70) omoplate.moveTo(10); Servo shoulder = (Servo) Runtime.start("shoulder","Servo"); shoulder.attach(arduino,6,30); shoulder.map(0,180,0,180); //#shoulder.setMinMax(0,180) shoulder.setVelocity(14); shoulder.moveTo(20); Servo rotate = (Servo) Runtime.start("rotate","Servo"); rotate.attach(arduino,9,90); rotate.map(46,160,46,160); //#rotate.setMinMax(46,180) rotate.setVelocity(18); rotate.moveTo(90); Servo bicep = (Servo) Runtime.start("bicep","Servo"); bicep.attach(arduino,8,10); bicep.map(5,60,5,80); bicep.setVelocity(26); //#bicep.setMinMax(5,90) bicep.moveTo(10); Servo wrist = (Servo) Runtime.start("wrist","Servo"); wrist.attach(arduino,7,10); //#wrist.map(45,135,45,135) wrist.map(90,90,90,90); wrist.setVelocity(26); //#bicep.setMinMax(5,90) wrist.moveTo(90); Servo finger = (Servo) Runtime.start("finger","Servo"); finger.attach(arduino,8,90); finger.map(90,90,90,90); finger.setVelocity(26); //#bicep.setMinMax(5,90) finger.moveTo(90); //#define the DH parameters for the ik service ik.setNewDHRobotArm("leftArm"); ik.setDHLink(mtorso,113,90,0,-90); ik.setDHLink(ttorso,0,90+65.6,346,0); ik.setDHLink(omoplate,0,-5.6+24.4+180,55,-90); ik.setDHLink(shoulder,77,-20+90,0,90); ik.setDHLink(rotate,284,90,40,90); ik.setDHLink(bicep,0,-7+24.4+90,300,90); //#ik.setDHLink(wrist,00,-90,200,0) ik.setDHLink(wrist,00,-90,100,-90); //print ik.currentPosition(); ik.setDHLink(finger,00,00,300,0); ik.setNewDHRobotArm("kinect"); ik.setDHLink(mtorso,113,90,0,-90); ik.setDHLink(ttorso,0,90+90,110,-90); ik.setDHLink("camera",0,90,10,90); //#define object, each dh link are set as an object, but the //#start point and end point will be update by the ik service, but still need //#a name and a radius //#static object need a start point, an end point, a name and a radius ik.clearObject(); ik.addObject(0.0, 0.0, 0.0, 0.0, 0.0, -150.0, "base", 150.0); ik.addObject("mtorso", 150.0); ik.addObject("ttorso", 10.0); ik.addObject("omoplate", 10.0); ik.addObject("shoulder", 50.0); ik.addObject("rotate", 50.0); ik.addObject("bicep", 60.0); ik.addObject("wrist", 70.0); ik.addObject("finger",10.0); //#ik.addObject(-1000.0, 300, 0, 1000, 300, 00, "obstacle",40) //#ik.addObject(360,540,117,360, 550,107,"cymbal",200) //#ik.addObject(90,530,-180,300,545,-181,"bell", 25) //#ik.addObject(-170,640,-70,-170,720,-250,"tom",150) //print ik.currentPosition(); //#setting ik parameters for the computing ik.setComputeMethodGeneticAlgorythm(); ik.setGeneticComputeSimulation(false); //#move to a position ik.moveTo("leftArm",260,410,-120); //ik.moveTo(280,190,-345); //#ik.moveTo("cymbal",ik.ObjectPointLocation.ORIGIN_SIDE, 0,0,5) //#mtorso.moveTo(45) //print ik.currentPosition("leftArm") //print "kinect Position" + str(ik.currentPosition("kinect")); ik.startOpenNI(); ik.processKinectData(); } @Override public Map<String, Double> publishJointAngles(HashMap<String, Double> angleMap) { return angleMap; } public double[][] publishJointPositions(double[][] jointPositionMap) { return jointPositionMap; } public Point publishTracking(Point tracking) { return tracking; } @Override public void onPoints(List<Point> points) { // TODO : move input matrix translation to here? or somewhere? // TODO: also don't like that i'm going to just say take the first point // now. // TODO: points should probably be a map, each point should have a name ? moveTo(points.get(0)); } /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(InverseKinematics3D.class.getCanonicalName()); meta.addDescription("a 3D kinematics service supporting D-H parameters"); meta.addCategory("robot", "control"); meta.addPeer("openni", "OpenNi", "Kinect service"); return meta; } public void setDHLink (String name, double d, double theta, double r, double alpha) { DHLink dhLink = new DHLink(name, d, r, MathUtils.degToRad(theta), MathUtils.degToRad(alpha)); currentArm.addLink(dhLink); arms.put(currentArm.name, currentArm); } public void setDHLink (Servo servo, double d, double theta, double r, double alpha) { DHLink dhLink = new DHLink(servo.getName(), d, r, MathUtils.degToRad(theta), MathUtils.degToRad(alpha)); servo.addIKServoEventListener(this); currentServos.put(servo.getName(), servo); dhLink.addPositionValue(servo.getPos()); dhLink.setMin(MathUtils.degToRad(theta + Math.min(servo.getMin(), servo.getMax()))); dhLink.setMax(MathUtils.degToRad(theta + Math.max(servo.getMax(), servo.getMin()))); currentArm.addLink(dhLink); arms.put(currentArm.name, currentArm); } public void setDHLink (String armName, String name, double d, double theta, double r, double alpha) { changeArm(armName); setDHLink(name, d, theta, r, alpha); } public void setDHLink (String armName, Servo servo, double d, double theta, double r, double alpha) { changeArm(armName); setDHLink(servo, d, theta, r, alpha); arms.put(currentArm.name, currentArm); } public void setNewDHRobotArm(String name) { currentArm = new DHRobotArm(); currentArm.name = name; arms.put(name, currentArm); } public void moveTo(int x , int y, int z, int roll, int pitch, int yaw) { moveTo(new Point(x, y, z, roll, pitch, yaw)); } public void moveTo(int x, int y, int z) { Point goTo = new Point((double)x,(double)y,(double)z,0.0,0.0,0.0); moveTo(goTo); } public void moveTo(String arm, int x, int y, int z) { changeArm(arm); moveTo(x, y, z); } @Override public void calcFitness(ArrayList<Chromosome> pool) { for (Chromosome chromosome : pool) { DHRobotArm arm = new DHRobotArm(); double fitnessMult = 1; double fitnessTime = 0; for (int i = 0; i < currentArm.getNumLinks(); i++){ //copy the value of the currentArm DHLink newLink = new DHLink(currentArm.getLink(i)); if (chromosome.getDecodedGenome() != null) { newLink.addPositionValue((double)chromosome.getDecodedGenome().get(i)); Double delta = currentArm.getLink(i).getPositionValueDeg() - (Double)chromosome.getDecodedGenome().get(i); double timeOfMove = Math.abs(delta / currentServos.get(currentArm.getLink(i).getName()).getVelocity()); if (timeOfMove > fitnessTime) { fitnessTime = timeOfMove; } } arm.addLink(newLink); } if (geneticComputeSimulation) { //work well but long computing time arm = simulateMove(chromosome.getDecodedGenome()); } Point potLocation = arm.getPalmPosition(); Double distance = potLocation.distanceTo(goTo); //not sure about weight for roll/pitch/yaw. adding a wrist will probably help // double dRoll = (potLocation.getRoll() - goTo.getRoll())/360; // fitnessMult*=(1-dRoll)*10000; // double dPitch = (potLocation.getPitch() - goTo.getPitch())/360; // fitnessMult*=(1-dPitch)*10000; // double dYaw = (potLocation.getYaw() - goTo.getYaw())/360; // fitnessMult*=(1-dYaw)*10000; if (fitnessTime < 0.1) { fitnessTime = 0.1; } //fitness is the score showing how close the results is to the target position Double fitness = (fitnessMult/distance*1000);// + (1/fitnessTime*.01); if (fitness < 0) fitness *=-1; chromosome.setFitness(fitness); } return; } // convert the genetic algorythm to the data we want to use @Override public void decode(ArrayList<Chromosome> chromosomes) { for (Chromosome chromosome : chromosomes ){ int pos=0; ArrayList<Object>decodedGenome = new ArrayList<Object>(); for (DHLink link: currentArm.getLinks()){ Servo servo = currentServos.get(link.getName()); if (servo == null) { decodedGenome.add(null); continue; } Mapper map = null; if(servo.getMin() == servo.getMax()) { decodedGenome.add(servo.getMin()); continue; } else { map = new Mapper(0,2047,servo.getMin(),servo.getMax()); } Double value=0.0; for (int i= pos; i< chromosome.getGenome().length() && i < pos+11; i++){ if(chromosome.getGenome().charAt(i) == '1') value += 1 << i-pos; } pos += 11; value = map.calcOutput(value); if (value.isNaN()) { value = link.getPositionValueDeg(); } //if (value < MathUtils.radToDeg(link.getMin()-link.getInitialTheta())) value = link.getPositionValueDeg(); //if (value > MathUtils.radToDeg(link.getMax()-link.getInitialTheta())) value = link.getPositionValueDeg(); decodedGenome.add(value); } chromosome.setDecodedGenome(decodedGenome); } } private DHRobotArm simulateMove(ArrayList<Object> decodedGenome) { // simulate movement of the servos in time to get an approximation of their position time = 0.1; boolean isMoving = true; DHRobotArm oldArm = currentArm; // stop simulating when all servo reach position while (isMoving) { isMoving = false; DHRobotArm newArm = new DHRobotArm(); newArm.name = currentArm.name; for (int i = 0; i < currentArm.getNumLinks(); i++) { DHLink newLink = new DHLink(currentArm.getLink(i)); double degrees = currentArm.getLink(i).getPositionValueDeg(); double deltaDegree = java.lang.Math.abs(degrees - (Double)decodedGenome.get(i)); double deltaDegree2 = time * currentServos.get(currentArm.getLink(i).getName()).getVelocity(); if (deltaDegree >= deltaDegree2) { deltaDegree = deltaDegree2; isMoving = true; } if (degrees > ((Double)decodedGenome.get(i)).intValue()) { degrees -= deltaDegree; } else if (degrees < ((Double)decodedGenome.get(i)).intValue()) { degrees += deltaDegree; } newLink.addPositionValue( degrees); newArm.addLink(newLink); } double[][] jp = createJointPositionMap(newArm); //send data to the collision detector class for (int i = 0; i < currentArm.getNumLinks(); i++) { CollisionItem ci = new CollisionItem(new Point(jp[i][0], jp[i][1], jp[i][2], 0 , 0, 0), new Point(jp[i+1][0], jp[i+1][1], jp[i+1][2], 0, 0, 0), currentArm.getLink(i).getName()); if (i != currentArm.getNumLinks()-1) { ci.addIgnore(currentArm.getLink(i+1).getName()); } collisionItems.addItem(ci); } collisionItems.runTest(); if (collisionItems.haveCollision() ){ //log.info("Collision at {} - {}", collisionItems.getCollisionPoint()[0], collisionItems.getCollisionPoint()[1]); return oldArm; } oldArm = newArm; //log.info("time: {} Position:{}", ((Double)time).floatValue(), newArm.getPalmPosition().toString()); //log.info("collision: {}", collisionItems.haveCollision()); for (int i = 1; i < jp.length; i++){ //log.info("jp:{} {} - {} - {}", newArm.getLink(i-1).getName(), ((Double)jp[i][0]).intValue(), ((Double)jp[i][1]).intValue(), ((Double)jp[i][2]).intValue()); } time += 0.1; } return oldArm; } public String addObject(double oX, double oY, double oZ, double eX, double eY, double eZ, String name, double radius) { return addObject(new Point(oX, oY, oZ, 0, 0, 0), new Point(eX, eY, eZ, 0, 0, 0), name, radius); } public String addObject(Point origin, Point end, String name, double radius) { CollisionItem item = new CollisionItem(origin, end, name, radius); collisionItems.addItem(item); return item.getName(); } public String addObject(String name, double radius) { return addObject(new Point(0, 0, 0, 0, 0, 0), new Point(0, 0, 0, 0, 0, 0), name, radius); } public String addObject(HashMap<Integer[],Map3DPoint> cloudMap) { CollisionItem item = new CollisionItem(cloudMap); collisionItems.addItem(item); return item.getName(); } public void clearObject(){ collisionItems.clearItem(); } public void setComputeMethodPSIJacobian() { computeMethod = IK_COMPUTE_METHOD_PI_JACOBIAN; } public void setComputeMethodGeneticAlgorythm() { computeMethod = IK_COMPUTE_METHOD_GENETIC_ALGORYTHM; } public void setGeneticPoolSize(int size) { geneticPoolSize = size; } public void setGeneticMutationRate(double rate) { geneticMutationRate = rate; } public void setGeneticRecombinationRate(double rate) { geneticRecombinationRate = rate; } public void setGeneticGeneration(int generation) { geneticGeneration = generation; } public void setGeneticComputeSimulation(boolean compute) { geneticComputeSimulation = compute; } public void objectAddIgnore(String object1, String object2) { collisionItems.addIgnore(object1, object2); } public void onIKServoEvent(IKData data) { for (DHRobotArm a : arms.values()) { for (DHLink l: a.getLinks()) { if (l.getName().equals(data.name)){ l.addPositionValue(data.pos.doubleValue()); } } } if (openni != null) { map3d.updateKinectPosition(currentPosition(kinectName)); } if (jmeApp != null) { jmeApp.updateObjects(collisionItems.getItems()); } } public void moveTo(String name, ObjectPointLocation location, int xoffset, int yoffset, int zoffset) { stopMoving = false; moveInfo = new MoveInfo(); moveInfo.offset = new Point(xoffset, yoffset, zoffset, 0, 0, 0); moveInfo.targetItem = collisionItems.getItem(name); moveInfo.objectLocation = location; if (moveInfo.targetItem == null){ log.info("no items named {} found",name); moveInfo = null; return; } moveTo(moveToObject()); } private Point moveToObject() { Point[] point = new Point[2]; moveInfo.lastLink = currentArm.getLink(currentArm.getNumLinks()-1); CollisionItem lastLinkItem = collisionItems.getItem(moveInfo.lastLink.getName()); Double[] vector = new Double[3]; boolean addRadius=false; switch (moveInfo.objectLocation) { case ORIGIN_CENTER: { point[0] = moveInfo.targetItem.getOrigin(); break; } case END_CENTER: { point[0] = moveInfo.targetItem.getEnd(); break; } case CLOSEST_POINT: { point = collisionItems.getClosestPoint(moveInfo.targetItem, lastLinkItem, new Double[2], vector); addRadius = true; break; } case ORIGIN_SIDE: { point[0] = moveInfo.targetItem.getOrigin(); addRadius = true; break; } case END_SIDE: { point[0] = moveInfo.targetItem.getEnd(); addRadius = true; break; } case CENTER_SIDE: { point = collisionItems.getClosestPoint(moveInfo.targetItem, lastLinkItem, new Double[]{0.5, 0.5}, vector); addRadius = true; } case CENTER: { point = collisionItems.getClosestPoint(moveInfo.targetItem, lastLinkItem, new Double[]{0.5, 0.5}, vector); } } if(addRadius) { double[] vectori = moveInfo.targetItem.getVector(); double[] vectorT = moveInfo.targetItem.getVectorT(); Point side0 = new Point(point[0].getX()+vectorT[0], point[0].getY()+vectorT[1], point[0].getZ()+vectorT[2], 0, 0, 0); Point pointF = side0; Point curPos = currentPosition(); double d = Math.pow((side0.getX() - curPos.getX()),2) + Math.pow((side0.getY() - curPos.getY()),2) + Math.pow((side0.getZ() - curPos.getZ()),2); for (int i = 0; i < 360; i+=10) { double L = vectori[0]*vectori[0] + vectori[1]*vectori[1] + vectori[2]*vectori[2]; double x = ((moveInfo.targetItem.getOrigin().getX()*(Math.pow(vectori[1],2)+Math.pow(vectori[2], 2)) - vectori[0] * (moveInfo.targetItem.getOrigin().getY()*vectori[1] + moveInfo.targetItem.getOrigin().getZ()*vectori[2] - vectori[0]*side0.getX() - vectori[1]*side0.getY() - vectori[2]*side0.getZ())) * (1 - Math.cos(MathUtils.degToRad(i))) + L * side0.getX() * Math.cos(MathUtils.degToRad(i)) + Math.sqrt(L) * (-moveInfo.targetItem.getOrigin().getZ()*vectori[1] + moveInfo.targetItem.getOrigin().getY()*vectori[2] - vectori[2]*side0.getY() + vectori[1]*side0.getZ()) * Math.sin(MathUtils.degToRad(i))) / L; double y = ((moveInfo.targetItem.getOrigin().getY()*(Math.pow(vectori[0],2)+Math.pow(vectori[2], 2)) - vectori[1] * (moveInfo.targetItem.getOrigin().getX()*vectori[0] + moveInfo.targetItem.getOrigin().getZ()*vectori[2] - vectori[0]*side0.getX() - vectori[1]*side0.getY() - vectori[2]*side0.getZ())) * (1 - Math.cos(MathUtils.degToRad(i))) + L * side0.getY() * Math.cos(MathUtils.degToRad(i)) + Math.sqrt(L) * ( moveInfo.targetItem.getOrigin().getZ()*vectori[0] - moveInfo.targetItem.getOrigin().getX()*vectori[2] + vectori[2]*side0.getX() - vectori[0]*side0.getZ()) * Math.sin(MathUtils.degToRad(i))) / L; double z = ((moveInfo.targetItem.getOrigin().getZ()*(Math.pow(vectori[0],2)+Math.pow(vectori[1], 2)) - vectori[2] * (moveInfo.targetItem.getOrigin().getX()*vectori[0] + moveInfo.targetItem.getOrigin().getY()*vectori[1] - vectori[0]*side0.getX() - vectori[1]*side0.getY() - vectori[2]*side0.getZ())) * (1 - Math.cos(MathUtils.degToRad(i))) + L * side0.getZ() * Math.cos(MathUtils.degToRad(i)) + Math.sqrt(L) * (-moveInfo.targetItem.getOrigin().getY()*vectori[0] + moveInfo.targetItem.getOrigin().getX()*vectori[1] - vectori[1]*side0.getX() + vectori[0]*side0.getY()) * Math.sin(MathUtils.degToRad(i))) / L; Point check = new Point(x,y,z,0,0,0); double dt = Math.pow((check.getX() - curPos.getX()),2) + Math.pow((check.getY() - curPos.getY()),2) + Math.pow((check.getZ() - curPos.getZ()),2); if (dt < d) { pointF = check; d = dt; } } point[0] = pointF; } Point moveToPoint = point[0].add(moveInfo.offset); log.info("Moving to point {}", moveToPoint); return moveToPoint; } public void stopMoving() { stopMoving = true; } public OpenNi startOpenNI() throws Exception { if (openni == null) { openni = (OpenNi) startPeer("openni"); openni.start3DData(); map3d.updateKinectPosition(currentPosition(kinectName)); //this.subscribe(openni.getName(), "publishOpenNIData", this.getName(), "onOpenNiData"); } return openni; } public void onOpenNiData(OpenNiData data){ if (ProcessKinectData) { ProcessKinectData = false; long a = System.currentTimeMillis(); log.info("start {}",a); map3d.processDepthMap(data); removeKinectObject(); ArrayList<HashMap<Integer[],Map3DPoint>> object = map3d.getObject(); for (int i = 0; i < object.size(); i++) { addObject(object.get(i)); } long b = System.currentTimeMillis(); log.info("end {} - {} - {}",b, b-a, this.inbox.size()); broadcastState(); } } private void removeKinectObject() { collisionItems.removeKinectObject(); } public void processKinectData(){ ProcessKinectData = true; onOpenNiData(openni.get3DData()); } public void setKinectName(String kinectName) { this.kinectName = kinectName; } public HashMap<String, CollisionItem> getCollisionObject() { return collisionItems.getItems(); } public ObjectPointLocation[] getEnumLocationValue() { return ObjectPointLocation.values(); } public Collection<DHRobotArm> getArms() { return this.arms.values(); } public void visualize() { jmeApp = new TestJmeIntegratedMovement(); jmeApp.setObjects(getCollisionObject()); jmeApp.start(); } }
package org.nschmidt.ldparteditor.project; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashSet; import org.nschmidt.ldparteditor.data.DatFile; import org.nschmidt.ldparteditor.helpers.Version; import org.nschmidt.ldparteditor.logger.NLogger; import org.nschmidt.ldparteditor.shells.editor3d.Editor3DWindow; import org.nschmidt.ldparteditor.shells.editortext.EditorTextWindow; /** * The static project class * * @author nils * */ public enum Project { INSTANCE; private static String projectName = "default"; //$NON-NLS-1$ private static String projectPath = new File("project").getAbsolutePath(); //$NON-NLS-1$ private static String tempProjectName = "default"; //$NON-NLS-1$ private static String tempProjectPath = new File("project").getAbsolutePath(); //$NON-NLS-1$ private static boolean defaultProject = true; /** A set of all open EditorTextWindow instances */ private static HashSet<EditorTextWindow> openTextWindows = new HashSet<EditorTextWindow>(); /** A set of all absolute filenames, which are not saved */ private static final HashSet<DatFile> unsavedFiles = new HashSet<DatFile>(); /** A set of all absolute filenames, which were parsed */ private static final HashSet<DatFile> parsedFiles = new HashSet<DatFile>(); /** The file which is currently displayed in the 3D editor */ private static DatFile fileToEdit = new DatFile(getProjectPath() + File.separator + "PARTS" + File.separator + "new.dat"); //$NON-NLS-1$ //$NON-NLS-2$ /** * Creates the new project file structure */ public static void create(boolean withFolders) { if (withFolders) resetEditor(); setDefaultProject(false); createFileStructure(withFolders); updateEditor(); Editor3DWindow.getWindow().getProjectParts().getItems().clear(); Editor3DWindow.getWindow().getProjectParts().setData(new ArrayList<DatFile>()); Editor3DWindow.getWindow().getProjectSubparts().getItems().clear(); Editor3DWindow.getWindow().getProjectSubparts().setData(new ArrayList<DatFile>()); Editor3DWindow.getWindow().getProjectPrimitives().getItems().clear(); Editor3DWindow.getWindow().getProjectPrimitives().setData(new ArrayList<DatFile>()); Editor3DWindow.getWindow().getProjectPrimitives48().getItems().clear(); Editor3DWindow.getWindow().getProjectPrimitives48().setData(new ArrayList<DatFile>()); Editor3DWindow.getWindow().getProjectPrimitives8().getItems().clear(); Editor3DWindow.getWindow().getProjectPrimitives8().setData(new ArrayList<DatFile>()); Editor3DWindow.getWindow().getShell().update(); Editor3DWindow.getWindow().getProjectParts().getParent().build(); Editor3DWindow.getWindow().getProjectParts().getParent().redraw(); Editor3DWindow.getWindow().getProjectParts().getParent().update(); // TODO Needs implementation! } /** * Saves the whole project */ @SuppressWarnings("unchecked") public static boolean save() { HashSet<DatFile> projectFiles = new HashSet<DatFile>(); if (isDefaultProject()) { // Linked project parts need a new path, because they were copied to a new directory String defaultPrefix = new File("project").getAbsolutePath() + File.separator; //$NON-NLS-1$ String projectPrefix = new File(projectPath).getAbsolutePath() + File.separator; Editor3DWindow.getWindow().getProjectParts().getParentItem().setData(projectPath); projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectParts().getData()); projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectSubparts().getData()); projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectPrimitives().getData()); projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectPrimitives48().getData()); projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectPrimitives8().getData()); for (DatFile df : projectFiles) { boolean isUnsaved = Project.getUnsavedFiles().contains(df); boolean isParsed = Project.getParsedFiles().contains(df); Project.getParsedFiles().remove(df); Project.getUnsavedFiles().remove(df); String newName = df.getNewName(); String oldName = df.getOldName(); if (!newName.startsWith(projectPrefix) && newName.startsWith(defaultPrefix)) { df.setNewName(projectPrefix + newName.substring(defaultPrefix.length())); } if (!oldName.startsWith(projectPrefix) && oldName.startsWith(defaultPrefix)) { df.setOldName(projectPrefix + oldName.substring(defaultPrefix.length())); } if (isUnsaved) Project.addUnsavedFile(df); if (isParsed) Project.getParsedFiles().add(df); } } try { if (isDefaultProject()) { copyFolder(new File("project"), new File(projectPath)); //$NON-NLS-1$ for (DatFile df : projectFiles) { df.updateLastModified(); } } setDefaultProject(false); return true; } catch (Exception ex) { return false; } } public static void copyFolder(File src, File dest) throws IOException{ if(src.isDirectory()){ //if directory not exists, create it if(!dest.exists()){ dest.mkdir(); NLogger.debug(Project.class, "Directory copied from " //$NON-NLS-1$ + src + " to " + dest); //$NON-NLS-1$ } //list all the directory contents String files[] = src.list(); for (String file : files) { //construct the src and dest file structure File srcFile = new File(src, file); File destFile = new File(dest, file); //recursive copy copyFolder(srcFile,destFile); } }else{ //if file, then copy it //Use bytes stream to support all file types InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; //copy the file content in bytes while ((length = in.read(buffer)) > 0){ out.write(buffer, 0, length); } in.close(); out.close(); NLogger.debug(Project.class, "File copied from " + src + " to " + dest); //$NON-NLS-1$ //$NON-NLS-2$ } } public static void deleteFolder(File src) throws IOException{ if(src.isDirectory()){ File files[] = src.listFiles(); for (File file : files) { deleteFolder(file); } src.delete(); NLogger.debug(Project.class, "Directory deleted " + src); //$NON-NLS-1$ }else{ NLogger.debug(Project.class, "File deleted " + src); //$NON-NLS-1$ src.delete(); } } /** * Creates the default project datastructure */ public static void createDefault() { resetEditor(); setDefaultProject(true); setProjectPath(new File("project").getAbsolutePath()); //$NON-NLS-1$ createFileStructure(false); Editor3DWindow.getWindow().getShell().setText(Version.getApplicationName()); Editor3DWindow.getWindow().getShell().update(); } private static void createFileStructure(boolean makeProjectRoot) { try { if (makeProjectRoot) { File projectFolder = new File(getProjectPath()); projectFolder.mkdir(); } File partsFolder = new File(getProjectPath() + File.separator + "PARTS"); //$NON-NLS-1$ partsFolder.mkdir(); File subpartsFolder = new File(getProjectPath() + File.separator + "PARTS" + File.separator + "S"); //$NON-NLS-1$ //$NON-NLS-2$ subpartsFolder.mkdir(); File primitivesFolder = new File(getProjectPath() + File.separator + "P"); //$NON-NLS-1$ primitivesFolder.mkdir(); File primitives48Folder = new File(getProjectPath() + File.separator + "P" + File.separator + "48"); //$NON-NLS-1$ //$NON-NLS-2$ primitives48Folder.mkdir(); File primitives8Folder = new File(getProjectPath() + File.separator + "P" + File.separator + "8"); //$NON-NLS-1$ //$NON-NLS-2$ primitives8Folder.mkdir(); File texturesFolder = new File(getProjectPath() + File.separator + "TEXTURES"); //$NON-NLS-1$ texturesFolder.mkdir(); } catch (SecurityException consumed) { } } private static void resetEditor() { HashSet<EditorTextWindow> openWindows = new HashSet<EditorTextWindow>(); openWindows.addAll(openTextWindows); for (EditorTextWindow txtwin : openWindows) { txtwin.getShell().close(); } } public static void updateEditor() { // Update the window text of the 3D editor Editor3DWindow.getWindow().getProjectParts().getParentItem().setText(getProjectName()); Editor3DWindow.getWindow().getShell().setText(getProjectName() + " - " + Version.getApplicationName()); //$NON-NLS-1$ } /** * @return {@code true} if the project is the default project */ public static boolean isDefaultProject() { return defaultProject; } /** * @param defaultProject * {@code true} if the project is the default project */ private static void setDefaultProject(boolean defaultProject) { Project.defaultProject = defaultProject; } /** * @return the path of the project */ public static String getProjectPath() { return projectPath; } /** * @param projectPath * the new project path */ public static void setProjectPath(String projectPath) { Project.projectPath = projectPath; } /** * @return the name of the project */ public static String getProjectName() { return projectName; } /** * @param projectName * the new project name */ public static void setProjectName(String projectName) { Project.projectName = projectName; } /** * @return the open text editor windows from the current project */ public static HashSet<EditorTextWindow> getOpenTextWindows() { return openTextWindows; } /** * @return all absolut filenames, which are not saved */ public static HashSet<DatFile> getUnsavedFiles() { return unsavedFiles; } public static void addUnsavedFile(DatFile file) { unsavedFiles.add(file); } public static void removeUnsavedFile(DatFile file) { unsavedFiles.remove(file); } /** * @return all absolut filenames, which were parsed */ public static HashSet<DatFile> getParsedFiles() { return parsedFiles; } /** * @return the fileToEdit */ public static DatFile getFileToEdit() { return fileToEdit; } /** * @param fileToEdit * the fileToEdit to set */ public static void setFileToEdit(DatFile fileToEdit) { Project.fileToEdit = fileToEdit; } public static String getTempProjectName() { return tempProjectName; } public static void setTempProjectName(String tempProjectName) { Project.tempProjectName = tempProjectName; } public static String getTempProjectPath() { return tempProjectPath; } public static void setTempProjectPath(String tempProjectPath) { Project.tempProjectPath = tempProjectPath; } }
package org.pentaho.ui.xul.swing.tags; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.BevelBorder; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.components.XulButton; import org.pentaho.ui.xul.components.XulDialogheader; import org.pentaho.ui.xul.containers.XulDialog; import org.pentaho.ui.xul.containers.XulWindow; import org.pentaho.ui.xul.dom.Document; import org.pentaho.ui.xul.dom.Element; import org.pentaho.ui.xul.swing.SwingElement; import org.pentaho.ui.xul.util.Orient; public class SwingDialog extends SwingElement implements XulDialog{ private JDialog dialog; private String buttonlabelaccept; private String buttonlabelcancel; private TreeMap<SwingDialog.BUTTONS, XulButton> buttons = new TreeMap<SwingDialog.BUTTONS, XulButton>(); private String ondialogaccept; private String ondialogcancel; private String title = "Dialog"; private String onload; private XulDialogheader header; private int height = 300; private int width = 450; private BUTTON_ALIGN buttonAlignment; private enum BUTTONS{ ACCEPT, CANCEL, HELP }; private enum BUTTON_ALIGN{ START, CENTER, END, LEFT, RIGHT, MIDDLE }; public SwingDialog(XulComponent parent, XulDomContainer domContainer, String tagName) { super("dialog"); this.orientation = Orient.VERTICAL; container = new JPanel(new GridBagLayout()); managedObject = "empty"; // enclosing containers should not try to attach this as a child resetContainer(); } public void resetContainer(){ container.removeAll(); gc = new GridBagConstraints(); gc.gridy = GridBagConstraints.RELATIVE; gc.gridx = 0; gc.gridheight = 1; gc.gridwidth = GridBagConstraints.REMAINDER; gc.insets = new Insets(2,2,2,2); gc.fill = GridBagConstraints.HORIZONTAL; gc.anchor = GridBagConstraints.NORTHWEST; gc.weightx = 1; } public String getButtonlabelaccept() { return buttonlabelaccept; } public String getButtonlabelcancel() { return buttonlabelcancel; } public String getButtons() { return null; //new ArrayList<XulButton>(this.buttons.values()); } public String getOndialogaccept() { return ondialogaccept; } public String getOndialogcancel() { return ondialogcancel; } public String getTitle() { return title; } public void setButtonlabelaccept(String label) { this.buttonlabelaccept = label; } public void setButtonlabelcancel(String label) { this.buttonlabelcancel = label; } public void setButtons(String buttons) { String[] tempButtons = buttons.split(","); for(int i=0; i< tempButtons.length; i++){ this.buttons.put( SwingDialog.BUTTONS.valueOf(tempButtons[i].trim().toUpperCase()), new SwingButton() ); } } public void setOndialogaccept(String command) { this.ondialogaccept = command; } public void setOndialogcancel(String command) { this.ondialogcancel = command; } public void setTitle(String title) { this.title = title; } public void show(){ Document doc = getDocument(); Element rootElement = doc.getRootElement(); XulWindow window = (XulWindow) rootElement; dialog = new JDialog((JFrame)window.getManagedObject()); dialog.setLayout(new BorderLayout()); JPanel mainPanel = new JPanel(new BorderLayout()); mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); dialog.setTitle(title); dialog.setModal(true); dialog.add(mainPanel, BorderLayout.CENTER); mainPanel.add(container, BorderLayout.CENTER); if(this.header != null){ JPanel headerPanel = new JPanel(new BorderLayout()); headerPanel.setBackground(Color.decode("#888888")); JPanel headerPanelInner = new JPanel(new BorderLayout()); headerPanelInner.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); headerPanelInner.setOpaque(false); headerPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.decode("#AAAAAA"), Color.decode("#666666"))); JLabel title = new JLabel(this.header.getTitle()); title.setForeground(Color.white); headerPanelInner.add(title, BorderLayout.WEST); JLabel desc = new JLabel(this.header.getDescription()); desc.setForeground(Color.white); headerPanelInner.add(desc, BorderLayout.EAST); headerPanel.add(headerPanelInner, BorderLayout.CENTER); mainPanel.add(headerPanel, BorderLayout.NORTH); } Box buttonPanel = Box.createHorizontalBox(); if( this.buttonAlignment == BUTTON_ALIGN.RIGHT || this.buttonAlignment == BUTTON_ALIGN.END || this.buttonAlignment == BUTTON_ALIGN.MIDDLE || this.buttonAlignment == BUTTON_ALIGN.CENTER) { buttonPanel.add(Box.createHorizontalGlue()); } for(int i=this.buttons.size(); i>=0; i buttonPanel.add(Box.createHorizontalStrut(5)); buttonPanel.add((JButton) this.buttons.get(i).getManagedObject()); } buttonPanel.add(Box.createHorizontalStrut(5)); if( this.buttonAlignment == BUTTON_ALIGN.START || this.buttonAlignment == BUTTON_ALIGN.LEFT || this.buttonAlignment == BUTTON_ALIGN.MIDDLE || this.buttonAlignment == BUTTON_ALIGN.CENTER) { buttonPanel.add(Box.createHorizontalGlue()); } mainPanel.add(buttonPanel, BorderLayout.SOUTH); dialog.setSize(new Dimension(getWidth(), getHeight())); dialog.setPreferredSize(new Dimension(getWidth(), getHeight())); dialog.setMinimumSize(new Dimension(getWidth(), getHeight())); if(buttons.containsKey(SwingDialog.BUTTONS.ACCEPT)){ this.buttons.get(SwingDialog.BUTTONS.ACCEPT).setLabel(this.getButtonlabelaccept()); this.buttons.get(SwingDialog.BUTTONS.ACCEPT).setOnclick(this.getOndialogaccept()); } if(buttons.containsKey(SwingDialog.BUTTONS.CANCEL)){ this.buttons.get(SwingDialog.BUTTONS.CANCEL).setLabel(this.getButtonlabelcancel()); this.buttons.get(SwingDialog.BUTTONS.CANCEL).setOnclick(this.getOndialogcancel()); } dialog.setVisible(true); } public void hide(){ dialog.setVisible(false); } public void setVisible(boolean visible){ if(visible){ show(); } else { hide(); } } @Override public void layout() { super.layout(); for(XulComponent comp : this.children){ if(comp instanceof XulDialogheader){ header = (XulDialogheader) comp; } } } public int getHeight() { return this.height; } public int getWidth() { return this.width; } public void setHeight(int height) { this.height = height; } public void setWidth(int width) { this.width = width; } public String getButtonalign() { return this.buttonAlignment.toString().toLowerCase(); } public void setButtonalign(String align) { this.buttonAlignment = SwingDialog.BUTTON_ALIGN.valueOf(align.toUpperCase()); } public String getOnload() { return onload; } public void setOnload(String onload) { this.onload = onload; } }
package de.dhbw.humbuch.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import au.com.bytecode.opencsv.CSVReader; import de.dhbw.humbuch.model.SubjectHandler; import de.dhbw.humbuch.model.entity.Grade; import de.dhbw.humbuch.model.entity.Parent; import de.dhbw.humbuch.model.entity.Student; import de.dhbw.humbuch.model.entity.Subject; public final class CSVHandler { /** * Reads a csv file and creates student objects of it's records. * * @param path * a path to the csv which contains information about students * @return an ArrayList that contains student objects * @exception throws an UnsupportedOperationException if an error occurred * @see ArrayList */ public static ArrayList<Student> createStudentObjectsFromCSV(CSVReader csvReaderParam) throws UnsupportedOperationException { ArrayList<Student> studentArrayList = new ArrayList<Student>(); try { //csvReader - separator is ';'; CSVReader csvReader = csvReaderParam; Properties csvHeaderProperties = readCSVConfigurationFile(); Map<String, String> csvHeaderPropertyStrings = new LinkedHashMap<>(); for(Object property : csvHeaderProperties.keySet()){ csvHeaderPropertyStrings.put(((String) property).replaceAll("\\p{C}", ""), csvHeaderProperties.getProperty((String) property)); } List<String[]> allRecords = csvReader.readAll(); Iterator<String[]> allRecordsIterator = allRecords.iterator(); HashMap<String, Integer> headerIndexMap = new HashMap<String, Integer>(); if (allRecordsIterator.hasNext()) { String[] headerRecord = allRecordsIterator.next(); for (int i = 0; i < headerRecord.length; i++) { // removes all non-printable characters headerIndexMap.put(headerRecord[i].replaceAll("\\p{C}", ""), i); } } while (allRecordsIterator.hasNext()) { String[] record = allRecordsIterator.next(); Student student = createStudentObject(record, csvHeaderPropertyStrings, headerIndexMap); if (student != null) { studentArrayList.add(student); } else { throw new UnsupportedOperationException("Mindestens ein Studenten-Datensatz war korrumpiert"); } } csvReader.close(); } catch (IOException e) { throw new UnsupportedOperationException("Die Studentendaten konnten nicht eingelesen werden"); } return studentArrayList; } private static Properties readCSVConfigurationFile() { Properties csvHeaderProperties = new Properties(); try { csvHeaderProperties.load(new InputStreamReader(new FileInputStream("src/main/resources/csvConfiguration.properties"), "UTF-8")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return csvHeaderProperties; } /** * Creates a student object with the information in the record. * * @param record * is one line of the loaded csv-file * @return Student */ private static Student createStudentObject(String[] record, Map<String, String> properties, HashMap<String, Integer> index) throws UnsupportedOperationException { String foreignLanguage1, foreignLanguage2, foreignLanguage3, gradeString, firstName, lastName, gender, birthDay, religion; int id; try { foreignLanguage1 = record[getAttributeNameToHeaderIndex(properties, index, "foreignLanguage1")]; foreignLanguage2 = record[getAttributeNameToHeaderIndex(properties, index, "foreignLanguage2")]; foreignLanguage3 = record[getAttributeNameToHeaderIndex(properties, index, "foreignLanguage3")]; gradeString = record[getAttributeNameToHeaderIndex(properties, index, "grade")]; firstName = record[getAttributeNameToHeaderIndex(properties, index, "firstName")]; lastName = record[getAttributeNameToHeaderIndex(properties, index, "lastName")]; gender = record[getAttributeNameToHeaderIndex(properties, index, "gender")]; birthDay = record[getAttributeNameToHeaderIndex(properties, index, "birthDay")]; id = Integer.parseInt(record[getAttributeNameToHeaderIndex(properties, index, "id")]); religion = record[getAttributeNameToHeaderIndex(properties, index, "religion")]; } catch (ArrayIndexOutOfBoundsException a) { throw new UnsupportedOperationException("Ein Wert im Studentendatensatz konnte nicht gelesen werden."); } catch(NumberFormatException e){ throw new UnsupportedOperationException("Mindestens eine Postleitzahl ist keine gültige Nummer."); } Parent parent = null; try { String parentTitle = record[getAttributeNameToHeaderIndex(properties, index, "parentTitle")]; String parentLastName = record[getAttributeNameToHeaderIndex(properties, index, "parentLastName")]; String parentFirstName = record[getAttributeNameToHeaderIndex(properties, index, "parentFirstName")]; String parentStreet = record[getAttributeNameToHeaderIndex(properties, index, "parentStreet")]; int parentPostalcode = Integer.parseInt(record[getAttributeNameToHeaderIndex(properties, index, "parentPostalcode")]); String parentPlace = record[getAttributeNameToHeaderIndex(properties, index, "parentPlace")]; parent = new Parent.Builder(parentFirstName, parentLastName).title(parentTitle) .street(parentStreet).postcode(parentPostalcode).city(parentPlace).build(); } catch (NullPointerException e) { System.err.println("Could not create parent object to student"); throw new UnsupportedOperationException("Die Elterndaten enthalten an mindestens einer Stelle einen Fehler"); } catch(ArrayIndexOutOfBoundsException e){ throw new UnsupportedOperationException("Mindestens ein Datensatz enthält keine Eltern-Informationen"); } catch(NumberFormatException e){ throw new UnsupportedOperationException("Mindestens eine Postleitzahl ist keine gültige Nummer."); } Map<String, Boolean> checkValidityMap = new LinkedHashMap<>(); checkValidityMap.put(foreignLanguage1, true); checkValidityMap.put(foreignLanguage2, true); checkValidityMap.put(foreignLanguage3, true); checkValidityMap.put(gradeString, false); checkValidityMap.put(firstName, false); checkValidityMap.put(lastName, false); checkValidityMap.put(gender, false); checkValidityMap.put(birthDay, false); checkValidityMap.put("" + id, false); checkValidityMap.put(religion, false); if (!checkForValidityOfAttributes(checkValidityMap)) { return null; } Date date = null; try { date = new SimpleDateFormat("dd.mm.yyyy", Locale.GERMAN).parse(birthDay); } catch (ParseException e) { System.err.println("Could not format date " + e.getStackTrace()); return null; } Grade grade = new Grade.Builder(gradeString).build(); String[] foreignLanguage = new String[3]; foreignLanguage[0] = foreignLanguage1; foreignLanguage[1] = foreignLanguage2; foreignLanguage[2] = foreignLanguage3; Set<Subject> subjectSet = SubjectHandler.createProfile(foreignLanguage, religion); return new Student.Builder(id, firstName, lastName, date, grade).profile(subjectSet).gender(gender).parent(parent).leavingSchool(false).build(); } private static int getAttributeNameToHeaderIndex(Map<String, String> properties, HashMap<String, Integer> indexMap, String attributeName) throws UnsupportedOperationException { String headerValue = (String) properties.get(attributeName); if (headerValue != null) { int indexHeader = -1; if (indexMap.get(headerValue) != null) { indexHeader = indexMap.get(headerValue); } else { throw new UnsupportedOperationException("Ein CSV-Spaltenname konnte nicht zugeordnet werden. " + "Bitte die Einstellungsdatei mit der CSV-Datei abgleichen. Spaltenname: " + headerValue); } return indexHeader; } return -1; } private static boolean checkForValidityOfAttributes(Map<String, Boolean> attributes) { for (String str : attributes.keySet()) { if (str.equals("-1")) { return false; } if(!attributes.get(str)){ if(str.equals("")){ return false; } } } return true; } }
package de.iani.cubequest; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteStreams; import de.iani.cubequest.events.QuestDeleteEvent; import de.iani.cubequest.events.QuestFailEvent; import de.iani.cubequest.events.QuestFreezeEvent; import de.iani.cubequest.events.QuestRenameEvent; import de.iani.cubequest.events.QuestSetReadyEvent; import de.iani.cubequest.events.QuestSuccessEvent; import de.iani.cubequest.events.QuestWouldBeDeletedEvent; import de.iani.cubequest.generation.DeliveryQuestSpecification; import de.iani.cubequest.generation.DeliveryQuestSpecification.DeliveryReceiverSpecification; import de.iani.cubequest.generation.QuestGenerator; import de.iani.cubequest.generation.QuestSpecification; import de.iani.cubequest.interaction.BlockInteractor; import de.iani.cubequest.interaction.BlockInteractorDamagedEvent; import de.iani.cubequest.interaction.EntityInteractor; import de.iani.cubequest.interaction.EntityInteractorDamagedEvent; import de.iani.cubequest.interaction.InteractorDamagedEvent; import de.iani.cubequest.interaction.InteractorProtecting; import de.iani.cubequest.interaction.PlayerInteractBlockInteractorEvent; import de.iani.cubequest.interaction.PlayerInteractEntityInteractorEvent; import de.iani.cubequest.interaction.PlayerInteractInteractorEvent; import de.iani.cubequest.questStates.QuestState; import de.iani.cubequest.questStates.QuestState.Status; import de.iani.cubequest.quests.ComplexQuest; import de.iani.cubequest.quests.InteractorQuest; import de.iani.cubequest.quests.Quest; import de.iani.cubequest.util.ChatAndTextUtil; import de.iani.cubequest.util.ParameterizedConsumer; import de.iani.cubequest.wrapper.NPCEventListener; import de.speedy64.globalchat.api.GlobalChatDataEvent; import java.io.DataInputStream; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.logging.Level; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.HoverEvent; import org.bukkit.Bukkit; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBurnEvent; import org.bukkit.event.block.BlockExplodeEvent; import org.bukkit.event.block.BlockFadeEvent; import org.bukkit.event.block.BlockFromToEvent; import org.bukkit.event.block.BlockGrowEvent; import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPistonRetractEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.LeavesDecayEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityCreatePortalEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityTameEvent; import org.bukkit.event.entity.ExplosionPrimeEvent; import org.bukkit.event.hanging.HangingBreakEvent; import org.bukkit.event.player.PlayerArmorStandManipulateEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerFishEvent; import org.bukkit.event.player.PlayerInteractAtEntityEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.messaging.PluginMessageListener; public class EventListener implements Listener, PluginMessageListener { private static class QuestConsumerForInteractorEvent implements Consumer<QuestState> { private PlayerInteractInteractorEvent<?> param; private boolean aggregated; public QuestConsumerForInteractorEvent() { this.param = null; this.aggregated = false; } @Override public void accept(QuestState state) { Quest quest = state.getQuest(); if (quest.onPlayerInteractInteractorEvent(this.param, state)) { this.aggregated = true; if (this.param.getInteractor() instanceof EntityInteractor) { this.param.setCancelled(true); } if (quest instanceof InteractorQuest) { if (((InteractorQuest) quest).isRequireConfirmation()) { CubeQuest.getInstance().getInteractionConfirmationHandler() .addQuestToNextBook((InteractorQuest) quest); } else { ((InteractorQuest) quest).playerConfirmedInteraction(this.param.getPlayer(), state); } } } } public PlayerInteractInteractorEvent<?> getParam() { return this.param; } public void setParam(PlayerInteractInteractorEvent<?> event) { this.param = event; } public boolean popAggregated() { boolean res = this.aggregated; this.aggregated = false; return res; } } private CubeQuest plugin; private NPCEventListener npcListener; private Map<PlayerInteractInteractorEvent<?>, PlayerInteractInteractorEvent<?>> interactsThisTick; private List<Consumer<Player>> onPlayerJoin; private List<Consumer<Player>> onPlayerQuit; private Consumer<QuestState> forEachActiveQuestAfterPlayerJoinEvent = (state -> state.getQuest().afterPlayerJoinEvent(state)); private ParameterizedConsumer<PlayerQuitEvent, QuestState> forEachActiveQuestOnPlayerQuitEvent = new ParameterizedConsumer<>( (event, state) -> state.getQuest().onPlayerQuitEvent(event, state)); private ParameterizedConsumer<BlockBreakEvent, QuestState> forEachActiveQuestOnBlockBreakEvent = new ParameterizedConsumer<>( (event, state) -> state.getQuest().onBlockBreakEvent(event, state)); private ParameterizedConsumer<BlockPlaceEvent, QuestState> forEachActiveQuestOnBlockPlaceEvent = new ParameterizedConsumer<>( (event, state) -> state.getQuest().onBlockPlaceEvent(event, state)); private ParameterizedConsumer<EntityDeathEvent, QuestState> forEachActiveQuestOnEntityKilledByPlayerEvent = new ParameterizedConsumer<>( (event, state) -> state.getQuest().onEntityKilledByPlayerEvent(event, state)); private ParameterizedConsumer<EntityTameEvent, QuestState> forEachActiveQuestOnEntityTamedByPlayerEvent = new ParameterizedConsumer<>( (event, state) -> state.getQuest().onEntityTamedByPlayerEvent(event, state)); private ParameterizedConsumer<PlayerMoveEvent, QuestState> forEachActiveQuestOnPlayerMoveEvent = new ParameterizedConsumer<>( (event, state) -> state.getQuest().onPlayerMoveEvent(event, state)); private ParameterizedConsumer<PlayerFishEvent, QuestState> forEachActiveQuestOnPlayerFishEvent = new ParameterizedConsumer<>( (event, state) -> state.getQuest().onPlayerFishEvent(event, state)); private ParameterizedConsumer<PlayerCommandPreprocessEvent, QuestState> forEachActiveQuestOnPlayerCommandPreprocessEvent = new ParameterizedConsumer<>((event, state) -> state.getQuest() .onPlayerCommandPreprocessEvent(event, state)); private QuestConsumerForInteractorEvent forEachActiveQuestOnPlayerInteractInteractorEvent = new QuestConsumerForInteractorEvent(); private ParameterizedConsumer<QuestSuccessEvent, QuestState> forEachActiveQuestOnQuestSuccessEvent = new ParameterizedConsumer<>( (event, state) -> state.getQuest().onQuestSuccessEvent(event, state)); private ParameterizedConsumer<QuestFailEvent, QuestState> forEachActiveQuestOnQuestFailEvent = new ParameterizedConsumer<>( (event, state) -> state.getQuest().onQuestFailEvent(event, state)); private ParameterizedConsumer<QuestFreezeEvent, QuestState> forEachActiveQuestOnQuestFreezeEvent = new ParameterizedConsumer<>( (event, state) -> state.getQuest().onQuestFreezeEvent(event, state)); public enum GlobalChatMsgType { QUEST_UPDATED, QUEST_DELETED, NPC_QUEST_SETREADY, GENERATE_DAILY_QUEST, DAILY_QUEST_GENERATED, DAILY_QUEST_FINISHED, DAILY_QUESTS_REMOVED; private static GlobalChatMsgType[] values = values(); public static GlobalChatMsgType fromOrdinal(int ordinal) { return values[ordinal]; } } public EventListener(CubeQuest plugin) { this.plugin = plugin; Bukkit.getPluginManager().registerEvents(this, plugin); Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(plugin, "BungeeCord"); Bukkit.getServer().getMessenger().registerIncomingPluginChannel(plugin, "BungeeCord", this); if (CubeQuest.getInstance().hasCitizensPlugin()) { this.npcListener = new NPCEventListener(); } this.interactsThisTick = new HashMap<>(); this.onPlayerJoin = new ArrayList<>(); this.onPlayerQuit = new ArrayList<>(); } public void tick() { if (!this.interactsThisTick.isEmpty()) { this.interactsThisTick.clear(); } } public void addOnPlayerJoin(Consumer<Player> action) { this.onPlayerJoin.add(action); } public void addOnPlayerQuit(Consumer<Player> action) { this.onPlayerQuit.add(action); } public void callEventIfDistinct(PlayerInteractInteractorEvent<?> event) { PlayerInteractInteractorEvent<?> oldEvent = this.interactsThisTick.put(event, event); if (oldEvent == null) { Bukkit.getPluginManager().callEvent(event); } else if (oldEvent.isCancelled()) { event.setCancelled(true); } } @Override public void onPluginMessageReceived(String channel, Player player, byte[] message) { if (!channel.equals("BungeeCord")) { return; } ByteArrayDataInput in = ByteStreams.newDataInput(message); String subchannel = in.readUTF(); if (subchannel.equals("GetServer")) { String servername = in.readUTF(); this.plugin.setBungeeServerName(servername); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onGlobalChatDataEvent(GlobalChatDataEvent event) { if (!event.getChannel().equals("CubeQuest")) { return; } try { DataInputStream msgin = event.getData(); GlobalChatMsgType type = GlobalChatMsgType.fromOrdinal(msgin.readInt()); switch (type) { case QUEST_UPDATED: int questId = msgin.readInt(); Quest quest = QuestManager.getInstance().getQuest(questId); if (quest == null) { this.plugin.getQuestCreator().loadQuest(questId); } else { this.plugin.getQuestCreator().refreshQuest(questId); } break; case QUEST_DELETED: questId = msgin.readInt(); quest = QuestManager.getInstance().getQuest(questId); if (quest != null) { QuestManager.getInstance().questDeleted(quest); } else { CubeQuest.getInstance().getLogger().log(Level.WARNING, "Quest deleted on other server not found on this server."); } break; case NPC_QUEST_SETREADY: questId = msgin.readInt(); InteractorQuest npcQuest = (InteractorQuest) QuestManager.getInstance().getQuest(questId); npcQuest.hasBeenSetReady(msgin.readBoolean()); break; case GENERATE_DAILY_QUEST: if (!msgin.readUTF().equals(this.plugin.getBungeeServerName())) { return; } if (!this.plugin.getQuestGenerator().checkForDelegatedGeneration()) { this.plugin.getLogger().log(Level.SEVERE, "No delegated generation found despite global chat message received."); } break; case DAILY_QUEST_GENERATED: int ordinal = msgin.readInt(); questId = msgin.readInt(); quest = QuestManager.getInstance().getQuest(questId); if (quest == null) { this.plugin.getQuestCreator().loadQuest(questId); quest = QuestManager.getInstance().getQuest(questId); } else { this.plugin.getQuestCreator().refreshQuest(quest); } this.plugin.getQuestGenerator().dailyQuestGenerated(ordinal, quest); break; case DAILY_QUEST_FINISHED: case DAILY_QUESTS_REMOVED: if (this.plugin.getQuestGenerator() != null) { // possible with to bad timing (event arrives before QuestGenerator is // loaded. this.plugin.getQuestGenerator().refreshDailyQuests(); } break; default: this.plugin.getLogger().log(Level.WARNING, "Unknown GlobalChatMsgType " + type + "."); } } catch (IOException e) { this.plugin.getLogger().log(Level.SEVERE, "Exception reading incoming GlobalChatMessage!", e); return; } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerJoinEvent(PlayerJoinEvent event) { final Player player = event.getPlayer(); this.plugin.unloadPlayerData(player.getUniqueId()); this.plugin.playerArrived(); if (this.plugin.hasTreasureChest()) { try { for (Reward r : this.plugin.getDatabaseFassade() .getAndDeleteRewardsToDeliver(player.getUniqueId())) { this.plugin.addToTreasureChest(player.getUniqueId(), r); } } catch (SQLException | InvalidConfigurationException e) { this.plugin.getLogger().log(Level.SEVERE, "Could not load rewards to deliver for player " + event.getPlayer().getName() + ":", e); } } PlayerData data = this.plugin.getPlayerData(player); Bukkit.getScheduler().scheduleSyncDelayedTask(this.plugin, () -> { data.getActiveQuests().forEach(this.forEachActiveQuestAfterPlayerJoinEvent); if (player.hasPermission(CubeQuest.ACCEPT_QUESTS_PERMISSION)) { for (Quest quest : CubeQuest.getInstance().getAutoGivenQuests()) { if (data.getPlayerStatus(quest.getId()) == Status.NOTGIVENTO && quest.fulfillsGivingConditions(player, data)) { // fullfillsgivingconditions impliziert ready quest.giveToPlayer(player); } } } for (Consumer<Player> c : this.onPlayerJoin) { c.accept(event.getPlayer()); } }, 1L); } @EventHandler(priority = EventPriority.MONITOR) public void onPlayerQuitEvent(PlayerQuitEvent event) { for (Consumer<Player> c : this.onPlayerQuit) { c.accept(event.getPlayer()); } this.plugin.getQuestGivers().forEach(qg -> qg.removeMightGetFromHere(event.getPlayer())); PlayerQuitEvent oldEvent = this.forEachActiveQuestOnPlayerQuitEvent.getParam(); this.forEachActiveQuestOnPlayerQuitEvent.setParam(event); this.plugin.getPlayerData(event.getPlayer()).getActiveQuests() .forEach(this.forEachActiveQuestOnPlayerQuitEvent); this.forEachActiveQuestOnPlayerQuitEvent.setParam(oldEvent); this.plugin.unloadPlayerData(event.getPlayer().getUniqueId()); } // BlockEvents for security and quests @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnBlockBurnEvent(BlockBurnEvent event) { BlockInteractor interactor = new BlockInteractor(event.getBlock()); BlockInteractorDamagedEvent<BlockBurnEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnBlockExplodeEvent(BlockExplodeEvent event) { BlockInteractor interactor = new BlockInteractor(event.getBlock()); BlockInteractorDamagedEvent<BlockExplodeEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); for (Block b : event.blockList()) { System.out.println(b); if (event.isCancelled()) { System.out.println(event.isCancelled()); return; } BlockInteractor otherInteractor = new BlockInteractor(b); BlockInteractorDamagedEvent<BlockExplodeEvent> otherNewEvent = new BlockInteractorDamagedEvent<>(event, otherInteractor); Bukkit.getPluginManager().callEvent(otherNewEvent); } System.out.println(event.isCancelled()); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnBlockFadeEvent(BlockFadeEvent event) { BlockInteractor interactor = new BlockInteractor(event.getBlock()); BlockInteractorDamagedEvent<BlockFadeEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnBlockFromToEvent(BlockFromToEvent event) { BlockInteractor interactor = new BlockInteractor(event.getBlock()); BlockInteractorDamagedEvent<BlockFromToEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); if (event.isCancelled()) { return; } BlockInteractor secondInteractor = new BlockInteractor(event.getToBlock()); BlockInteractorDamagedEvent<BlockFromToEvent> secondNewEvent = new BlockInteractorDamagedEvent<>(event, secondInteractor); Bukkit.getPluginManager().callEvent(secondNewEvent); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnBlockGrowEvent(BlockGrowEvent event) { BlockInteractor interactor = new BlockInteractor(event.getBlock()); BlockInteractorDamagedEvent<BlockGrowEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onBlockIgniteEvent(BlockIgniteEvent event) { BlockInteractor interactor = new BlockInteractor(event.getBlock()); BlockInteractorDamagedEvent<BlockIgniteEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnBlockPhysicsEvent(BlockPhysicsEvent event) { BlockInteractor interactor = new BlockInteractor(event.getBlock()); BlockInteractorDamagedEvent<BlockPhysicsEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnBlockPistonExtendEvent(BlockPistonExtendEvent event) { for (Block b : event.getBlocks()) { BlockInteractor interactor = new BlockInteractor(b); BlockInteractorDamagedEvent<BlockPistonExtendEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); if (event.isCancelled()) { return; } } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnBlockPistonRetractEvent(BlockPistonRetractEvent event) { for (Block b : event.getBlocks()) { BlockInteractor interactor = new BlockInteractor(b); BlockInteractorDamagedEvent<BlockPistonRetractEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); if (event.isCancelled()) { return; } } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnLeavesDecayEvent(LeavesDecayEvent event) { BlockInteractor interactor = new BlockInteractor(event.getBlock()); BlockInteractorDamagedEvent<LeavesDecayEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnBlockBreakEvent(BlockBreakEvent event) { BlockInteractor interactor = new BlockInteractor(event.getBlock()); BlockInteractorDamagedEvent<BlockBreakEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockBreakEvent(BlockBreakEvent event) { BlockBreakEvent oldEvent = this.forEachActiveQuestOnBlockBreakEvent.getParam(); this.forEachActiveQuestOnBlockBreakEvent.setParam(event); this.plugin.getPlayerData(event.getPlayer()).getActiveQuests() .forEach(this.forEachActiveQuestOnBlockBreakEvent); this.forEachActiveQuestOnBlockBreakEvent.setParam(oldEvent); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnBlockPlaceEvent(BlockPlaceEvent event) { BlockInteractor interactor = new BlockInteractor(event.getBlock()); BlockInteractorDamagedEvent<BlockPlaceEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPlaceEvent(BlockPlaceEvent event) { BlockPlaceEvent oldEvent = this.forEachActiveQuestOnBlockPlaceEvent.getParam(); this.forEachActiveQuestOnBlockPlaceEvent.setParam(event); this.plugin.getPlayerData(event.getPlayer()).getActiveQuests() .forEach(this.forEachActiveQuestOnBlockPlaceEvent); this.forEachActiveQuestOnBlockPlaceEvent.setParam(oldEvent); } // EntityEvents for security and quests @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnHangingBreakEvent(HangingBreakEvent event) { EntityInteractor interactor = new EntityInteractor(event.getEntity()); EntityInteractorDamagedEvent<HangingBreakEvent> newEvent = new EntityInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnEntityChangeBlockEvent(EntityChangeBlockEvent event) { BlockInteractor interactor = new BlockInteractor(event.getBlock()); BlockInteractorDamagedEvent<EntityChangeBlockEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnEntityCreatePortalEvent(EntityCreatePortalEvent event) { for (BlockState state : event.getBlocks()) { BlockInteractor interactor = new BlockInteractor(state.getBlock()); BlockInteractorDamagedEvent<EntityCreatePortalEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); if (event.isCancelled()) { return; } } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnEntityDamageEvent(EntityDamageEvent event) { EntityInteractor interactor = new EntityInteractor(event.getEntity()); EntityInteractorDamagedEvent<EntityDamageEvent> newEvent = new EntityInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityDeathEvent(EntityDeathEvent event) { Player player = event.getEntity().getKiller(); if (player == null) { return; } EntityDeathEvent oldEvent = this.forEachActiveQuestOnEntityKilledByPlayerEvent.getParam(); this.forEachActiveQuestOnEntityKilledByPlayerEvent.setParam(event); this.plugin.getPlayerData(player).getActiveQuests() .forEach(this.forEachActiveQuestOnEntityKilledByPlayerEvent); this.forEachActiveQuestOnEntityKilledByPlayerEvent.setParam(oldEvent); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnEntityExplodeEvent(EntityExplodeEvent event) { for (Block b : event.blockList()) { BlockInteractor interactor = new BlockInteractor(b); BlockInteractorDamagedEvent<EntityExplodeEvent> newEvent = new BlockInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); if (event.isCancelled()) { return; } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityTameEvent(EntityTameEvent event) { if (!(event.getOwner() instanceof Player)) { return; } EntityTameEvent oldEvent = this.forEachActiveQuestOnEntityTamedByPlayerEvent.getParam(); this.forEachActiveQuestOnEntityTamedByPlayerEvent.setParam(event); this.plugin.getPlayerData((Player) event.getOwner()).getActiveQuests() .forEach(this.forEachActiveQuestOnEntityTamedByPlayerEvent); this.forEachActiveQuestOnEntityTamedByPlayerEvent.setParam(oldEvent); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void earlierOnExplosionPrimeEvent(ExplosionPrimeEvent event) { EntityInteractor interactor = new EntityInteractor(event.getEntity()); EntityInteractorDamagedEvent<ExplosionPrimeEvent> newEvent = new EntityInteractorDamagedEvent<>(event, interactor); Bukkit.getPluginManager().callEvent(newEvent); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerMoveEvent(PlayerMoveEvent event) { PlayerMoveEvent oldEvent = this.forEachActiveQuestOnPlayerMoveEvent.getParam(); this.forEachActiveQuestOnPlayerMoveEvent.setParam(event); this.plugin.getPlayerData(event.getPlayer()).getActiveQuests() .forEach(this.forEachActiveQuestOnPlayerMoveEvent); this.forEachActiveQuestOnPlayerMoveEvent.setParam(oldEvent); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerFishEvent(PlayerFishEvent event) { PlayerFishEvent oldEvent = this.forEachActiveQuestOnPlayerFishEvent.getParam(); this.forEachActiveQuestOnPlayerFishEvent.setParam(event); this.plugin.getPlayerData(event.getPlayer()).getActiveQuests() .forEach(this.forEachActiveQuestOnPlayerFishEvent); this.forEachActiveQuestOnPlayerFishEvent.setParam(oldEvent); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerCommandPreprocessEvent(PlayerCommandPreprocessEvent event) { PlayerCommandPreprocessEvent oldEvent = this.forEachActiveQuestOnPlayerCommandPreprocessEvent.getParam(); this.forEachActiveQuestOnPlayerCommandPreprocessEvent.setParam(event); this.plugin.getPlayerData(event.getPlayer()).getActiveQuests() .forEach(this.forEachActiveQuestOnPlayerCommandPreprocessEvent); this.forEachActiveQuestOnPlayerCommandPreprocessEvent.setParam(oldEvent); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) public void onPlayerInteractEntityEvent(PlayerInteractEntityEvent event) { if (this.npcListener != null && this.npcListener.onPlayerInteractEntityEvent(event)) { return; } if (event.getPlayer().isSneaking()) { return; } PlayerInteractInteractorEvent<?> newEvent = new PlayerInteractEntityInteractorEvent(event, new EntityInteractor(event.getRightClicked())); callEventIfDistinct(newEvent); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) public void onPlayerInteractAtEntityEvent(PlayerInteractAtEntityEvent event) { onPlayerInteractEntityEvent(event); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) public void onPlayerArmorStandManipulateEvent(PlayerArmorStandManipulateEvent event) { onPlayerInteractEntityEvent(event); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) public void onPlayerInteractEvent(PlayerInteractEvent event) { if (event.getClickedBlock() == null) { return; } if (event.getPlayer().isSneaking()) { return; } PlayerInteractInteractorEvent<?> newEvent = new PlayerInteractBlockInteractorEvent(event, new BlockInteractor(event.getClickedBlock())); callEventIfDistinct(newEvent); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerInteractInteractorEvent(PlayerInteractInteractorEvent<?> event) { PlayerInteractInteractorEvent<?> oldEvent = this.forEachActiveQuestOnPlayerInteractInteractorEvent.getParam(); this.forEachActiveQuestOnPlayerInteractInteractorEvent.setParam(event); this.plugin.getPlayerData(event.getPlayer()).getActiveQuests() .forEach(this.forEachActiveQuestOnPlayerInteractInteractorEvent); boolean ignoreGiver = this.forEachActiveQuestOnPlayerInteractInteractorEvent.popAggregated(); this.forEachActiveQuestOnPlayerInteractInteractorEvent.setParam(oldEvent); if (CubeQuest.getInstance().getInteractionConfirmationHandler() .showBook(event.getPlayer())) { event.setCancelled(true); ignoreGiver = true; } if (ignoreGiver) { return; } QuestGiver giver = this.plugin.getQuestGiver(event.getInteractor()); if (giver != null) { event.setCancelled(true); // range check also updates location cache if (event.getPlayer().getLocation() .distance(giver.getInteractor().getLocation()) <= 7) { giver.showQuestsToPlayer(event.getPlayer()); } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onQuestSuccessEvent(QuestSuccessEvent event) { QuestSuccessEvent oldEvent = this.forEachActiveQuestOnQuestSuccessEvent.getParam(); this.forEachActiveQuestOnQuestSuccessEvent.setParam(event); this.plugin.getPlayerData(event.getPlayer()).getActiveQuests() .forEach(this.forEachActiveQuestOnQuestSuccessEvent); this.forEachActiveQuestOnQuestSuccessEvent.setParam(oldEvent); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onQuestFailEvent(QuestFailEvent event) { QuestFailEvent oldEvent = this.forEachActiveQuestOnQuestFailEvent.getParam(); this.forEachActiveQuestOnQuestFailEvent.setParam(event); this.plugin.getPlayerData(event.getPlayer()).getActiveQuests() .forEach(this.forEachActiveQuestOnQuestFailEvent); this.forEachActiveQuestOnQuestFailEvent.setParam(oldEvent); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onQuestFreezeEvent(QuestFreezeEvent event) { QuestFreezeEvent oldEvent = this.forEachActiveQuestOnQuestFreezeEvent.getParam(); this.forEachActiveQuestOnQuestFreezeEvent.setParam(event); this.plugin.getPlayerData(event.getPlayer()).getActiveQuests() .forEach(this.forEachActiveQuestOnQuestFreezeEvent); this.forEachActiveQuestOnQuestFreezeEvent.setParam(oldEvent); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onQuestRenameEvent(QuestRenameEvent event) { QuestManager.getInstance().onQuestRenameEvent(event); } @EventHandler public void onQuestSetReadyEvent(QuestSetReadyEvent event) { for (ComplexQuest q : QuestManager.getInstance().getQuests(ComplexQuest.class)) { q.onQuestSetReadyEvent(event); } if (event.isCancelled()) { return; } if (event.getSetReady()) { return; } for (PlayerData data : CubeQuest.getInstance().getLoadedPlayerData()) { if (data.isGivenTo(event.getQuest().getId())) { event.getQuest().removeFromPlayer(data.getId()); } } } @EventHandler public void onQuestDeleteEvent(QuestDeleteEvent event) { for (ComplexQuest q : QuestManager.getInstance().getQuests(ComplexQuest.class)) { q.onQuestDeleteEvent(event); } } @EventHandler public void onQuestWouldBeDeletedEvent(QuestWouldBeDeletedEvent event) { for (ComplexQuest q : QuestManager.getInstance().getQuests(ComplexQuest.class)) { q.onQuestWouldBeDeletedEvent(event); } } @EventHandler public void onInteractorDamagedEvent(InteractorDamagedEvent<?> event) { if (event.getInteractor() instanceof EntityInteractor) { if (((EntityInteractor) event.getInteractor()).getEntity() instanceof Player) { return; } } Set<InteractorProtecting> protecting = CubeQuest.getInstance().getProtectedBy(event.getInteractor()); for (InteractorProtecting prot : protecting) { if (prot.onInteractorDamagedEvent(event)) { interactorDamagingCancelled(prot, event); return; } } } @SuppressWarnings({"null", "unlikely-arg-type"}) private void interactorDamagingCancelled(InteractorProtecting cancelledBy, InteractorDamagedEvent<?> event) { Player player = event.getPlayer(); if (player == null) { return; } boolean isQuest = cancelledBy instanceof Quest; Quest q = isQuest ? (Quest) cancelledBy : null; boolean isReceiver = !isQuest && (cancelledBy instanceof DeliveryReceiverSpecification); DeliveryReceiverSpecification r = isReceiver ? (DeliveryReceiverSpecification) cancelledBy : null; boolean isGiver = !isQuest && !isReceiver && (cancelledBy instanceof QuestGiver); QuestGiver g = isGiver ? (QuestGiver) cancelledBy : null; if ((isGiver && !player.hasPermission(CubeQuest.EDIT_QUEST_GIVERS_PERMISSION)) || (isQuest && !player.hasPermission(CubeQuest.EDIT_QUESTS_PERMISSION)) || ((isReceiver || !isGiver && !isQuest) && !player.hasPermission(CubeQuest.EDIT_QUEST_SPECIFICATIONS_PERMISSION))) { ChatAndTextUtil.sendErrorMessage(player, event.getNoPermissionMessage()); return; } String prefix; int index; boolean warning; if (isQuest) { prefix = "Dieser Interactor ist Teil von Quest "; index = -1; warning = false; } else if (isReceiver) { prefix = "Dieser Interactor ist Teil folgender DeliveryReceiverSpecification "; index = (new ArrayList<>( DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification.getInstance() .getTargets())).indexOf(r); warning = false; } else if (isGiver) { prefix = "Dieser Interactor ist QuestGiver "; index = -1; warning = false; } else if (cancelledBy instanceof QuestSpecification) { prefix = "Dieser Interactor ist Teil von QuestSpecification "; index = QuestGenerator.getInstance().getPossibleQuestsIncludingNulls() .indexOf(cancelledBy); warning = false; } else { prefix = "Dieser Interactor ist Teil des Quest-Systems."; index = -1; warning = true; } HoverEvent he = isGiver ? null : new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(isQuest ? "Info zu " + q.toString() + " anzeigen" : ("QuestSpecifications auflisten")).create()); ClickEvent ce = isGiver ? null : new ClickEvent(ClickEvent.Action.RUN_COMMAND, isQuest ? "/quest info " + q.getId() : isReceiver ? ("/quest listDeliveryQuestReceiverSpecifications " + Math.max(0, ((index / ChatAndTextUtil.PAGE_LENGTH) + 1))) : ("/quest listQuestSpecifications " + Math.max(0, ((index / ChatAndTextUtil.PAGE_LENGTH) + 1)))); ComponentBuilder builder = new ComponentBuilder(prefix).color(ChatColor.GOLD); if (warning) { CubeQuest.getInstance().getLogger().log(Level.WARNING, "Unknown InteractorProtector: " + cancelledBy.getClass().getName()); } else { builder.append((isQuest ? q.getId() + " " : isReceiver ? "" : isGiver ? g.getName() + " " : (index + 1 + " "))); if (!isGiver) { builder.event(he).event(ce); } builder.append("und kann nicht zerstört werden" + (isReceiver ? ": " : ".")).reset() .color(ChatColor.GOLD); if (isReceiver) { builder.append(r.getSpecificationInfo()); } } ChatAndTextUtil.sendBaseComponent(player, builder.create()); } }
package org.subethamail.core.util; import java.util.logging.Level; import javax.annotation.PostConstruct; import javax.ejb.Startup; import lombok.extern.java.Log; import org.apache.velocity.app.Velocity; /** * This Bean just initializes the static use of Velocity. * * @author Jon Stevens * @author Scott Hernandez */ @Startup @Log public class VelocityService { /** * Simply initialize the Velocity engine */ @PostConstruct public void start() throws Exception { try { Velocity.setProperty(Velocity.RESOURCE_LOADER, "cp"); Velocity.setProperty("cp.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocity.setProperty("cp.resource.loader.cache", "true"); Velocity.setProperty("cp.resource.loader.modificationCheckInterval ", "0"); Velocity.setProperty("input.encoding", "UTF-8"); Velocity.setProperty("output.encoding", "UTF-8"); // Very busy servers should increase this value. Default: 20 // Velocity.setProperty("velocity.pool.size", "20"); Velocity.init(); log.log(Level.FINE,"Velocity initialized!"); } catch (Exception ex) { log.log(Level.SEVERE,"Unable to initialize Velocity", ex); throw new RuntimeException(ex); } } }
package de.prob2.ui.beditor; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.Objects; import java.util.ResourceBundle; import java.util.stream.Collectors; import java.util.stream.Stream; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import de.prob.animator.command.GetAllUsedFilenamesCommand; import de.prob.animator.command.GetInternalRepresentationPrettyPrintCommand; import de.prob.animator.domainobjects.MachineFileInformation; import de.prob.model.eventb.EventBModel; import de.prob2.ui.helpsystem.HelpButton; import de.prob2.ui.internal.StageManager; import de.prob2.ui.internal.StopActions; import de.prob2.ui.menu.ExternalEditor; import de.prob2.ui.prob2fx.CurrentProject; import de.prob2.ui.prob2fx.CurrentTrace; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class BEditorView extends BorderPane { private static final Logger LOGGER = LoggerFactory.getLogger(BEditorView.class); private static final Charset EDITOR_CHARSET = Charset.forName("UTF-8"); @FXML private Button saveButton; @FXML private Button openExternalButton; @FXML private Label warningLabel; @FXML private BEditor beditor; @FXML private HelpButton helpButton; @FXML private ChoiceBox<MachineFileInformation> machineChoice; private final StageManager stageManager; private final ResourceBundle bundle; private final CurrentProject currentProject; private final CurrentTrace currentTrace; private final StopActions stopActions; private final Injector injector; private final ObjectProperty<Path> path; private final StringProperty lastSavedText; private final BooleanProperty saved; private final BooleanProperty reloaded; private Thread watchThread; private WatchKey key; @Inject private BEditorView(final StageManager stageManager, final ResourceBundle bundle, final CurrentProject currentProject, final CurrentTrace currentTrace, final StopActions stopActions, final Injector injector) { this.stageManager = stageManager; this.bundle = bundle; this.currentProject = currentProject; this.currentTrace = currentTrace; this.stopActions = stopActions; this.injector = injector; this.path = new SimpleObjectProperty<>(this, "path", null); this.lastSavedText = new SimpleStringProperty(this, "lastSavedText", null); this.saved = new SimpleBooleanProperty(this, "saved", true); this.reloaded = new SimpleBooleanProperty(this, "reloaded", true); this.watchThread = null; this.key = null; stageManager.loadFXML(this, "beditorView.fxml"); } @FXML private void initialize() { // We can't use Bindings.equal here, because beditor.textProperty() is not an ObservableObjectValue. saved.bind(Bindings.createBooleanBinding( () -> Objects.equals(lastSavedText.get(), beditor.getText()), lastSavedText, beditor.textProperty() ).or(machineChoice.getSelectionModel().selectedItemProperty().isNull())); currentTrace.stateSpaceProperty().addListener((o, from, to) -> { if(to == null) { return; } updateIncludedMachines(); reloaded.set(true); }); saveButton.disableProperty().bind(saved); openExternalButton.disableProperty().bind(this.pathProperty().isNull()); warningLabel.textProperty().bind(Bindings.when(saved) .then(Bindings.when(reloaded) .then("") .otherwise(bundle.getString("beditor.reloadWarning")) ) .otherwise(bundle.getString("beditor.unsavedWarning")) ); setHint(); currentProject.currentMachineProperty().addListener((observable, from, to) -> { machineChoice.getItems().clear(); if (to == null) { this.setHint(); } else { final Path machinePath = currentProject.getLocation().resolve(to.getPath()); if(currentProject.getCurrentMachine().getName().equals(machineChoice.getSelectionModel().getSelectedItem())) { registerFile(machinePath); setText(machinePath); } } }); machineChoice.getSelectionModel().selectedItemProperty().addListener((observable, from, to) -> { if(to == null) { return; } switchMachine(to.getPath()); }); this.stopActions.add(beditor::stopHighlighting); helpButton.setHelpContent(this.getClass()); } private void switchMachine(String path) { final Path machinePath = currentProject.getLocation().resolve(path); resetWatching(); registerFile(machinePath); if(currentTrace.getModel() instanceof EventBModel) { GetInternalRepresentationPrettyPrintCommand cmd = new GetInternalRepresentationPrettyPrintCommand(); currentTrace.getStateSpace().execute(cmd); this.setEditorText(cmd.getPrettyPrint(), machinePath); beditor.setEditable(false); } else { String extension = path.split("\\.")[1]; setText(machinePath); if("def".equals(extension)) { beditor.setEditable(false); } } } private void updateIncludedMachines() { GetAllUsedFilenamesCommand cmd = new GetAllUsedFilenamesCommand(); currentTrace.getStateSpace().execute(cmd); if(cmd.getFiles().isEmpty()) { String machinePath = currentProject.getCurrentMachine().getPath().toString(); String[] machinePathSeparated = machinePath.split(File.separator); String[] fileSeparated = machinePathSeparated[machinePathSeparated.length - 1].split("\\."); String file = fileSeparated[0]; String extension = machinePathSeparated[1]; machineChoice.getItems().add(new MachineFileInformation(file, extension, machinePath)); } else { machineChoice.getItems().setAll(cmd.getFiles()); } machineChoice.getSelectionModel().selectFirst(); } private void registerFile(Path path) { Path directory = path.getParent(); WatchService watcher; try { watcher = directory.getFileSystem().newWatchService(); directory.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); } catch (IOException e) { LOGGER.error(String.format("Could not register file: %s", path), e); return; } watchThread = new Thread(() -> { while (true) { try { key = watcher.take(); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { setText(path); } } key.reset(); } }, "BEditor File Change Watcher"); injector.getInstance(StopActions.class).add(watchThread::interrupt); watchThread.start(); } public ObjectProperty<Path> pathProperty() { return this.path; } public Path getPath() { return this.pathProperty().get(); } public void setPath(final Path path) { this.pathProperty().set(path); } public ReadOnlyBooleanProperty savedProperty() { return saved; } private void setHint() { this.setEditorText(bundle.getString("beditor.hint"), null); beditor.setEditable(false); } private void setEditorText(String text, Path path) { this.setPath(path); this.lastSavedText.set(text); beditor.clear(); beditor.appendText(text); beditor.getStyleClass().add("editor"); beditor.startHighlighting(); beditor.setEditable(true); } private void setText(Path path) { String text; try (final Stream<String> lines = Files.lines(path)) { text = lines.collect(Collectors.joining(System.lineSeparator())); } catch (IOException | UncheckedIOException e) { stageManager.makeExceptionAlert(e, "common.alerts.couldNotReadFile.content", path).showAndWait(); LOGGER.error(String.format("Could not read file: %s", path), e); return; } this.setEditorText(text, path); } @FXML public void handleSave() { resetWatching(); lastSavedText.set(beditor.getText()); reloaded.set(false); assert this.getPath() != null; // Maybe add something for the user, that reloads the machine automatically? try { Files.write(this.getPath(), beditor.getText().getBytes(EDITOR_CHARSET), StandardOpenOption.TRUNCATE_EXISTING); registerFile(this.getPath()); } catch (IOException e) { stageManager.makeExceptionAlert(e, "common.alerts.couldNotSaveFile.content", path).showAndWait(); LOGGER.error(String.format("Could not save file: %s", path), e); } } private void resetWatching() { if(watchThread != null) { watchThread.interrupt(); } if(key != null) { key.reset(); } } @FXML private void handleOpenExternal() { injector.getInstance(ExternalEditor.class).open(this.getPath()); } }
package de.prob2.ui.menu; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.prefs.Preferences; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import de.be4.classicalb.core.parser.exceptions.BException; import de.codecentric.centerdevice.MenuToolkit; import de.prob.scripting.Api; import de.prob.statespace.AnimationSelector; import de.prob2.ui.animations.AnimationsView; import de.prob2.ui.consoles.b.BConsoleStage; import de.prob2.ui.consoles.groovy.GroovyConsoleStage; import de.prob2.ui.formula.FormulaInputStage; import de.prob2.ui.history.HistoryView; import de.prob2.ui.internal.UIState; import de.prob2.ui.modelchecking.ModelcheckingController; import de.prob2.ui.operations.OperationsView; import de.prob2.ui.preferences.PreferencesStage; import de.prob2.ui.prob2fx.CurrentProject; import de.prob2.ui.prob2fx.CurrentStage; import de.prob2.ui.prob2fx.CurrentTrace; import de.prob2.ui.project.NewProjectStage; import de.prob2.ui.project.Project; import de.prob2.ui.stats.StatsView; import javafx.application.Platform; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Accordion; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.SplitPane; import javafx.scene.control.TitledPane; import javafx.scene.image.Image; import javafx.scene.input.KeyCombination; import javafx.stage.FileChooser; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.stage.Window; @Singleton public final class MenuController extends MenuBar { private enum ApplyDetachedEnum { JSON, USER } private final class DetachViewStageController { @FXML private Stage detached; @FXML private Button apply; @FXML private CheckBox detachOperations; @FXML private CheckBox detachHistory; @FXML private CheckBox detachModelcheck; @FXML private CheckBox detachStats; @FXML private CheckBox detachAnimations; private final Preferences windowPrefs; private final Set<Stage> wrapperStages; private DetachViewStageController() { windowPrefs = Preferences.userNodeForPackage(MenuController.DetachViewStageController.class); wrapperStages = new HashSet<>(); } @FXML public void initialize() { detached.getIcons().add(new Image("prob_128.gif")); currentStage.register(detached); } @FXML private void apply() { apply(ApplyDetachedEnum.USER); } private void apply(ApplyDetachedEnum detachedBy) { Parent root = loadPreset("main.fxml"); assert root != null; SplitPane pane = (SplitPane) root.getChildrenUnmodifiable().get(0); Accordion accordion = (Accordion) pane.getItems().get(0); removeTP(accordion, pane, detachedBy); uiState.setGuiState("detached"); this.detached.close(); } private void removeTP(Accordion accordion, SplitPane pane, ApplyDetachedEnum detachedBy) { final HashSet<Stage> wrapperStagesCopy = new HashSet<>(wrapperStages); wrapperStages.clear(); for (final Stage stage : wrapperStagesCopy) { stage.setScene(null); stage.hide(); uiState.getStages().remove(stage.getTitle()); } for (final Iterator<TitledPane> it = accordion.getPanes().iterator(); it.hasNext();) { final TitledPane tp = it.next(); if (removable(tp, detachedBy)) { it.remove(); transferToNewWindow((Parent) tp.getContent(), tp.getText()); } } if (accordion.getPanes().isEmpty()) { pane.getItems().remove(accordion); pane.setDividerPositions(0); pane.lookupAll(".split-pane-divider").forEach(div -> div.setMouseTransparent(true)); } } private boolean removable(TitledPane tp, ApplyDetachedEnum detachedBy) { return removableOperations(tp, detachedBy) || removableHistory(tp, detachedBy) || removableModelcheck(tp, detachedBy) || removableStats(tp, detachedBy) || removableAnimations(tp, detachedBy); } private boolean removableOperations(TitledPane tp, ApplyDetachedEnum detachedBy) { boolean condition = detachOperations.isSelected(); if (detachedBy == ApplyDetachedEnum.JSON) { condition = uiState.getStages().contains(tp.getText()); if (condition) { detachOperations.setSelected(true); } } return tp.getContent() instanceof OperationsView && condition; } private boolean removableHistory(TitledPane tp, ApplyDetachedEnum detachedBy) { boolean condition = detachHistory.isSelected(); if (detachedBy == ApplyDetachedEnum.JSON) { condition = uiState.getStages().contains(tp.getText()); if (condition) { detachHistory.setSelected(true); } } return tp.getContent() instanceof HistoryView && condition; } private boolean removableModelcheck(TitledPane tp, ApplyDetachedEnum detachedBy) { boolean condition = detachModelcheck.isSelected(); if (detachedBy == ApplyDetachedEnum.JSON) { condition = uiState.getStages().contains(tp.getText()); if (condition) { detachModelcheck.setSelected(true); } } return tp.getContent() instanceof ModelcheckingController && condition; } private boolean removableStats(TitledPane tp, ApplyDetachedEnum detachedBy) { boolean condition = detachStats.isSelected(); if (detachedBy == ApplyDetachedEnum.JSON) { condition = uiState.getStages().contains(tp.getText()); if (condition) { detachStats.setSelected(true); } } return tp.getContent() instanceof StatsView && condition; } private boolean removableAnimations(TitledPane tp, ApplyDetachedEnum detachedBy) { boolean condition = detachAnimations.isSelected(); if (detachedBy == ApplyDetachedEnum.JSON) { condition = uiState.getStages().contains(tp.getText()); if (condition) { detachAnimations.setSelected(true); } } return tp.getContent() instanceof AnimationsView && condition; } private void transferToNewWindow(Parent node, String title) { Stage stage = new Stage(); wrapperStages.add(stage); stage.setTitle(title); currentStage.register(stage); stage.getIcons().add(new Image("prob_128.gif")); stage.showingProperty().addListener((observable, from, to) -> { if (!to) { windowPrefs.putDouble(node.getClass() + "X", stage.getX()); windowPrefs.putDouble(node.getClass() + "Y", stage.getY()); windowPrefs.putDouble(node.getClass() + "Width", stage.getWidth()); windowPrefs.putDouble(node.getClass() + "Height", stage.getHeight()); if (node instanceof OperationsView) { detachOperations.setSelected(false); } else if (node instanceof HistoryView) { detachHistory.setSelected(false); } else if (node instanceof ModelcheckingController) { detachModelcheck.setSelected(false); } else if (node instanceof StatsView) { detachStats.setSelected(false); } else if (node instanceof AnimationsView) { detachAnimations.setSelected(false); } uiState.getStages().remove(stage.getTitle()); dvController.apply(); } }); stage.setWidth(windowPrefs.getDouble(node.getClass() + "Width", 200)); stage.setHeight(windowPrefs.getDouble(node.getClass() + "Height", 100)); stage.setX(windowPrefs.getDouble(node.getClass() + "X", Screen.getPrimary().getVisualBounds().getWidth() - stage.getWidth() / 2)); stage.setY(windowPrefs.getDouble(node.getClass() + "Y", Screen.getPrimary().getVisualBounds().getHeight() - stage.getHeight() / 2)); Scene scene = new Scene(node); scene.getStylesheets().add("prob.css"); stage.setScene(scene); stage.show(); } } private static final URL FXML_ROOT; static { try { FXML_ROOT = new URL(MenuController.class.getResource("menu.fxml"), ".."); } catch (MalformedURLException e) { throw new IllegalStateException(e); } } private static final Logger logger = LoggerFactory.getLogger(MenuController.class); private final Injector injector; private final Api api; private final CurrentStage currentStage; private final CurrentTrace currentTrace; private final RecentFiles recentFiles; private final UIState uiState; private final DetachViewStageController dvController; private final Object openLock; private Window window; @FXML private Menu recentFilesMenu; @FXML private MenuItem recentFilesPlaceholder; @FXML private MenuItem clearRecentFiles; @FXML private Menu windowMenu; @FXML private MenuItem preferencesItem; @FXML private MenuItem enterFormulaForVisualization; @FXML private MenuItem aboutItem; @FXML private MenuItem saveProjectItem; private CurrentProject currentProject; @Inject private MenuController(final FXMLLoader loader, final Injector injector, final Api api, final AnimationSelector animationSelector, final CurrentStage currentStage, final CurrentProject currentProject, final CurrentTrace currentTrace, final RecentFiles recentFiles, final UIState uiState) { this.injector = injector; this.api = api; this.currentStage = currentStage; this.currentTrace = currentTrace; this.currentProject = currentProject; this.recentFiles = recentFiles; this.uiState = uiState; this.openLock = new Object(); loader.setLocation(getClass().getResource("menu.fxml")); loader.setRoot(this); loader.setController(this); try { loader.load(); } catch (IOException e) { logger.error("loading fxml failed", e); } if (System.getProperty("os.name", "").toLowerCase().contains("mac")) { // Mac-specific menu stuff this.setUseSystemMenuBar(true); final MenuToolkit tk = MenuToolkit.toolkit(); // Remove About menu item from Help aboutItem.getParentMenu().getItems().remove(aboutItem); aboutItem.setText("About ProB 2"); // Remove Preferences menu item from Edit preferencesItem.getParentMenu().getItems().remove(preferencesItem); preferencesItem.setAccelerator(KeyCombination.valueOf("Shortcut+,")); // Create Mac-style application menu final Menu applicationMenu = tk.createDefaultApplicationMenu("ProB 2"); this.getMenus().add(0, applicationMenu); tk.setApplicationMenu(applicationMenu); applicationMenu.getItems().setAll(aboutItem, new SeparatorMenuItem(), preferencesItem, new SeparatorMenuItem(), tk.createHideMenuItem("ProB 2"), tk.createHideOthersMenuItem(), tk.createUnhideAllMenuItem(), new SeparatorMenuItem(), tk.createQuitMenuItem("ProB 2")); // Add Mac-style items to Window menu windowMenu.getItems().addAll(tk.createMinimizeMenuItem(), tk.createZoomMenuItem(), tk.createCycleWindowsItem(), new SeparatorMenuItem(), tk.createBringAllToFrontItem(), new SeparatorMenuItem()); tk.autoAddWindowMenuItems(windowMenu); // Make this the global menu bar tk.setGlobalMenuBar(this); } final FXMLLoader stageLoader = injector.getInstance(FXMLLoader.class); stageLoader.setLocation(getClass().getResource("detachedPerspectivesChoice.fxml")); this.dvController = new DetachViewStageController(); stageLoader.setController(this.dvController); try { stageLoader.load(); } catch (IOException e) { logger.error("loading fxml failed", e); } } @FXML public void initialize() { this.sceneProperty().addListener((observable, from, to) -> { if (to != null) { to.windowProperty().addListener((observable1, from1, to1) -> this.window = to1); } }); final ListChangeListener<String> recentFilesListener = change -> { final ObservableList<MenuItem> recentItems = this.recentFilesMenu.getItems(); final List<MenuItem> newItems = getRecentFileItems(); // If there are no recent files, show a placeholder and disable // clearing this.clearRecentFiles.setDisable(newItems.isEmpty()); if (newItems.isEmpty()) { newItems.add(this.recentFilesPlaceholder); } // Add a shortcut for reopening the most recent file newItems.get(0).setAccelerator(KeyCombination.valueOf("Shift+Shortcut+'O'")); // Keep the last two items (the separator and the "clear recent // files" item) newItems.addAll(recentItems.subList(recentItems.size() - 2, recentItems.size())); // Replace the old recents with the new ones this.recentFilesMenu.getItems().setAll(newItems); }; this.recentFiles.addListener(recentFilesListener); // Fire the listener once to populate the recent files menu recentFilesListener.onChanged(null); this.enterFormulaForVisualization.disableProperty() .bind(currentTrace.currentStateProperty().initializedProperty().not()); this.saveProjectItem.disableProperty() .bind(currentProject.existsProperty().not().or(currentProject.isSingleFileProperty())); } @FXML private void handleClearRecentFiles() { this.recentFiles.clear(); } @FXML private void handleLoadDefault() { loadPreset("main.fxml"); uiState.getStages().clear(); } @FXML private void handleLoadSeparated() { loadPreset("separatedHistory.fxml"); uiState.getStages().clear(); } @FXML private void handleLoadSeparated2() { loadPreset("separatedHistoryAndStatistics.fxml"); uiState.getStages().clear(); } @FXML private void handleLoadStacked() { loadPreset("stackedLists.fxml"); uiState.getStages().clear(); } @FXML public void handleLoadDetached() { this.dvController.detached.show(); } public void applyDetached() { this.dvController.apply(ApplyDetachedEnum.JSON); } @FXML private void handleLoadPerspective() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open File"); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("FXML Files", "*.fxml")); File selectedFile = fileChooser.showOpenDialog(window); if (selectedFile != null) { try { FXMLLoader loader = injector.getInstance(FXMLLoader.class); loader.setLocation(selectedFile.toURI().toURL()); uiState.setGuiState(selectedFile.toString()); Parent root = loader.load(); window.getScene().setRoot(root); } catch (IOException e) { logger.error("loading fxml failed", e); Alert alert = new Alert(Alert.AlertType.ERROR, "Could not open file:\n" + e); alert.getDialogPane().getStylesheets().add("prob.css"); alert.showAndWait(); } } } private void open(String path) { if (currentProject.exists()) { Alert alert = new Alert(AlertType.CONFIRMATION); alert.getDialogPane().getStylesheets().add("prob.css"); ButtonType buttonTypeAdd = new ButtonType("Add"); ButtonType buttonTypeClose = new ButtonType("Close"); ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE); if (currentProject.isSingleFile()) { alert.setHeaderText("You've already opened a file."); alert.setContentText("Do you want to close the current file?"); alert.getButtonTypes().setAll(buttonTypeClose, buttonTypeCancel); } else { alert.setHeaderText("You've already opened a project."); alert.setContentText("Do you want to close the current project or add the selected file?"); alert.getButtonTypes().setAll(buttonTypeAdd, buttonTypeClose, buttonTypeCancel); } Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeAdd) { currentProject.addMachine(new File(path)); } else if (result.get() == buttonTypeClose) { openAsync(path); } } else { openAsync(path); } } private void openAsync(String path) { new Thread(() -> this.openPath(path), "File Opener Thread").start(); } private void openPath(String path) { // NOTE: This method may be called from outside the JavaFX main thread, // for example from openAsync. // This means that all JavaFX calls must be wrapped in // Platform.runLater. // Prevent multiple threads from loading a file at the same time synchronized (this.openLock) { try { this.api.b_load(path); } catch (IOException | BException e) { logger.error("loading file failed", e); Platform.runLater(() -> { Alert alert = new Alert(Alert.AlertType.ERROR, "Could not open file:\n" + e); alert.getDialogPane().getStylesheets().add("prob.css"); alert.show(); }); return; } Platform.runLater(() -> { this.currentProject.changeCurrentProject(new Project(new File(path))); injector.getInstance(ModelcheckingController.class).resetView(); // Remove the path first to avoid listing the same file twice. this.recentFiles.remove(path); this.recentFiles.add(0, path); }); } } @FXML private void handleOpen(ActionEvent event) { final FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open File"); fileChooser.getExtensionFilters() .add(new FileChooser.ExtensionFilter("Classical B Files", "*.mch", "*.ref", "*.imp")); final File selectedFile = fileChooser.showOpenDialog(this.window); if (selectedFile == null) { return; } this.open(selectedFile.getAbsolutePath()); } @FXML private void handleClose(final ActionEvent event) { final Stage stage = this.currentStage.get(); if (stage != null) { stage.close(); } } @FXML public void handlePreferences() { final Stage preferencesStage = injector.getInstance(PreferencesStage.class); preferencesStage.show(); preferencesStage.toFront(); } @FXML private void handleFormulaInput() { final Stage formulaInputStage = injector.getInstance(FormulaInputStage.class); formulaInputStage.show(); formulaInputStage.toFront(); } @FXML public void handleGroovyConsole() { final Stage groovyConsoleStage = injector.getInstance(GroovyConsoleStage.class); groovyConsoleStage.show(); groovyConsoleStage.toFront(); } @FXML public void handleBConsole() { final Stage bConsoleStage = injector.getInstance(BConsoleStage.class); bConsoleStage.show(); bConsoleStage.toFront(); } public Parent loadPreset(String location) { FXMLLoader loader = injector.getInstance(FXMLLoader.class); this.uiState.setGuiState(location); try { loader.setLocation(new URL(FXML_ROOT, location)); } catch (MalformedURLException e) { logger.error("Malformed location", e); Alert alert = new Alert(Alert.AlertType.ERROR, "Malformed location:\n" + e); alert.getDialogPane().getStylesheets().add("prob.css"); alert.showAndWait(); return null; } Parent root; try { root = loader.load(); } catch (IOException e) { logger.error("loading fxml failed", e); Alert alert = new Alert(Alert.AlertType.ERROR, "Could not open file:\n" + e); alert.getDialogPane().getStylesheets().add("prob.css"); alert.showAndWait(); return null; } window.getScene().setRoot(root); if (System.getProperty("os.name", "").toLowerCase().contains("mac")) { final MenuToolkit tk = MenuToolkit.toolkit(); tk.setGlobalMenuBar(this); tk.setApplicationMenu(this.getMenus().get(0)); } return root; } @FXML public void handleReportBug() { final Stage reportBugStage = injector.getInstance(ReportBugStage.class); reportBugStage.show(); reportBugStage.toFront(); } @FXML private void createNewProject(ActionEvent event) { if (currentProject.exists()) { Alert alert = new Alert(AlertType.CONFIRMATION); alert.getDialogPane().getStylesheets().add("prob.css"); if (currentProject.isSingleFile()) { alert.setHeaderText("You've already opened a file."); alert.setContentText("Do you want to close the current file?"); } else { alert.setHeaderText("You've already opened a project."); alert.setContentText("Do you want to close the current project?"); } Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { final Stage newProjectStage = injector.getInstance(NewProjectStage.class); newProjectStage.showAndWait(); newProjectStage.toFront(); } } else { final Stage newProjectStage = injector.getInstance(NewProjectStage.class); newProjectStage.showAndWait(); newProjectStage.toFront(); } } @FXML private void saveProject(ActionEvent event) { currentProject.save(); } @FXML private void openProject(ActionEvent event) { final FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open Project"); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("ProB2 Projects", "*.json")); final File selectedProject = fileChooser.showOpenDialog(this.window); if (selectedProject == null) { return; } if (currentProject.exists()) { Alert alert = new Alert(AlertType.CONFIRMATION); alert.getDialogPane().getStylesheets().add("prob.css"); if (currentProject.isSingleFile()) { alert.setHeaderText("You've already opened a file."); alert.setContentText("Do you want to close the current file?"); } else { alert.setHeaderText("You've already opened a project."); alert.setContentText("Do you want to close the current project?"); } Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { currentProject.open(selectedProject); } } else { currentProject.open(selectedProject); } } private List<MenuItem> getRecentFileItems() { final List<MenuItem> newItems = new ArrayList<>(); for (String s : this.recentFiles) { final MenuItem item = new MenuItem(new File(s).getName()); item.setOnAction(event -> this.open(s)); newItems.add(item); } return newItems; } }
package org.treetank.sessionlayer; import org.treetank.api.IConstants; import org.treetank.api.IReadTransaction; import org.treetank.nodelayer.AbstractNode; /** * <h1>ReadTransaction</h1> * * <p> * Read-only transaction wiht single-threaded cursor semantics. Each * read-only transaction works on a given revision key. * </p> */ public class ReadTransaction implements IReadTransaction { /** Session state this write transaction is bound to. */ private SessionState mSessionState; /** State of transaction including all cached stuff. */ private ReadTransactionState mTransactionState; /** Strong reference to currently selected node. */ private AbstractNode mCurrentNode; /** Tracks whether the transaction is closed. */ private boolean mClosed; /** * Constructor. * * @param sessionState Session state to work with. * @param transactionState Transaction state to work with. */ protected ReadTransaction( final SessionState sessionState, final ReadTransactionState transactionState) { mSessionState = sessionState; mTransactionState = transactionState; mCurrentNode = null; mClosed = false; moveToDocumentRoot(); } /** * {@inheritDoc} */ public final long getRevisionNumber() { assertNotClosed(); return mTransactionState.getRevisionRootPage().getRevisionNumber(); } /** * {@inheritDoc} */ public final long getRevisionSize() { assertNotClosed(); return mTransactionState.getRevisionRootPage().getRevisionSize(); } /** * {@inheritDoc} */ public final long getRevisionTimestamp() { assertNotClosed(); return mTransactionState.getRevisionRootPage().getRevisionTimestamp(); } /** * {@inheritDoc} */ public final boolean isSelected() { assertNotClosed(); return (mCurrentNode != null); } /** * {@inheritDoc} */ public final long moveTo(final long nodeKey) { assertNotClosed(); // Do nothing if this node is already selected. if (mCurrentNode != null && mCurrentNode.getNodeKey() == nodeKey) { return nodeKey; } // Find node by its key. if (nodeKey != IConstants.NULL_KEY) { mCurrentNode = mTransactionState.getNode(nodeKey); if (mCurrentNode != null) { return nodeKey; } else { return IConstants.NULL_KEY; } } else { mCurrentNode = null; return IConstants.NULL_KEY; } } /** * {@inheritDoc} */ public final long moveToToken(final String token) { assertNotClosed(); moveToFullTextRoot(); boolean contained = true; for (final char character : token.toCharArray()) { if (hasFirstChild()) { moveToFirstChild(); while (isFullText() && (getLocalPartKey() != character) && hasRightSibling()) { moveToRightSibling(); } contained = contained && (getLocalPartKey() == character); } else { contained = false; } } if (contained) { return mCurrentNode.getNodeKey(); } else { return moveToFullTextRoot(); } } /** * {@inheritDoc} */ public final long moveToDocumentRoot() { assertNotClosed(); return moveTo(IConstants.DOCUMENT_ROOT_KEY); } /** * {@inheritDoc} */ public final long moveToFullTextRoot() { assertNotClosed(); return moveTo(IConstants.FULLTEXT_ROOT_KEY); } /** * {@inheritDoc} */ public final long moveToParent() { assertNotClosedAndSelected(); return moveTo(mCurrentNode.getParentKey()); } /** * {@inheritDoc} */ public final long moveToFirstChild() { assertNotClosedAndSelected(); return moveTo(mCurrentNode.getFirstChildKey()); } /** * {@inheritDoc} */ public final long moveToLeftSibling() { assertNotClosedAndSelected(); return moveTo(mCurrentNode.getLeftSiblingKey()); } /** * {@inheritDoc} */ public final long moveToRightSibling() { assertNotClosedAndSelected(); return moveTo(mCurrentNode.getRightSiblingKey()); } /** * {@inheritDoc} */ public final long moveToAttribute(final int index) { assertNotClosedAndSelected(); mCurrentNode = mCurrentNode.getAttribute(index); return mCurrentNode.getNodeKey(); } /** * {@inheritDoc} */ public final long getNodeKey() { assertNotClosedAndSelected(); return mCurrentNode.getNodeKey(); } /** * {@inheritDoc} */ public final boolean hasParent() { assertNotClosedAndSelected(); return mCurrentNode.hasParent(); } /** * {@inheritDoc} */ public final long getParentKey() { assertNotClosedAndSelected(); return mCurrentNode.getParentKey(); } /** * {@inheritDoc} */ public final boolean hasFirstChild() { assertNotClosedAndSelected(); return mCurrentNode.hasFirstChild(); } /** * {@inheritDoc} */ public final long getFirstChildKey() { assertNotClosedAndSelected(); return mCurrentNode.getFirstChildKey(); } /** * {@inheritDoc} */ public final boolean hasLeftSibling() { assertNotClosedAndSelected(); return mCurrentNode.hasLeftSibling(); } /** * {@inheritDoc} */ public final long getLeftSiblingKey() { assertNotClosedAndSelected(); return mCurrentNode.getLeftSiblingKey(); } /** * {@inheritDoc} */ public final boolean hasRightSibling() { assertNotClosedAndSelected(); return mCurrentNode.hasRightSibling(); } /** * {@inheritDoc} */ public final long getRightSiblingKey() { assertNotClosedAndSelected(); return mCurrentNode.getRightSiblingKey(); } /** * {@inheritDoc} */ public final long getChildCount() { assertNotClosedAndSelected(); return mCurrentNode.getChildCount(); } /** * {@inheritDoc} */ public final int getAttributeCount() { assertNotClosedAndSelected(); return mCurrentNode.getAttributeCount(); } /** * {@inheritDoc} */ public final int getAttributeLocalPartKey(final int index) { assertNotClosedAndSelected(); return mCurrentNode.getAttribute(index).getLocalPartKey(); } /** * {@inheritDoc} */ public final String getAttributeLocalPart(final int index) { assertNotClosedAndSelected(); return nameForKey(mCurrentNode.getAttribute(index).getLocalPartKey()); } /** * {@inheritDoc} */ public final int getAttributePrefixKey(final int index) { assertNotClosedAndSelected(); return mCurrentNode.getAttribute(index).getPrefixKey(); } /** * {@inheritDoc} */ public final String getAttributePrefix(final int index) { assertNotClosedAndSelected(); return nameForKey(mCurrentNode.getAttribute(index).getPrefixKey()); } /** * {@inheritDoc} */ public final int getAttributeURIKey(final int index) { assertNotClosedAndSelected(); return mCurrentNode.getAttribute(index).getURIKey(); } /** * {@inheritDoc} */ public final String getAttributeURI(final int index) { assertNotClosedAndSelected(); return nameForKey(mCurrentNode.getAttribute(index).getURIKey()); } /** * {@inheritDoc} */ public final byte[] getAttributeValue(final int index) { assertNotClosedAndSelected(); return mCurrentNode.getAttribute(index).getValue(); } /** * {@inheritDoc} */ public final int getNamespaceCount() { assertNotClosedAndSelected(); return mCurrentNode.getNamespaceCount(); } /** * {@inheritDoc} */ public final int getNamespacePrefixKey(final int index) { assertNotClosedAndSelected(); return mCurrentNode.getNamespace(index).getPrefixKey(); } /** * {@inheritDoc} */ public final String getNamespacePrefix(final int index) { assertNotClosedAndSelected(); return nameForKey(mCurrentNode.getNamespace(index).getPrefixKey()); } /** * {@inheritDoc} */ public final int getNamespaceURIKey(final int index) { assertNotClosedAndSelected(); return mCurrentNode.getNamespace(index).getURIKey(); } /** * {@inheritDoc} */ public final String getNamespaceURI(final int index) { assertNotClosedAndSelected(); return nameForKey(mCurrentNode.getNamespace(index).getURIKey()); } /** * {@inheritDoc} */ public final int getKind() { assertNotClosedAndSelected(); return mCurrentNode.getKind(); } /** * {@inheritDoc} */ public final boolean isDocumentRoot() { assertNotClosedAndSelected(); return mCurrentNode.isDocumentRoot(); } /** * {@inheritDoc} */ public final boolean isElement() { assertNotClosedAndSelected(); return mCurrentNode.isElement(); } /** * {@inheritDoc} */ public final boolean isAttribute() { assertNotClosedAndSelected(); return mCurrentNode.isAttribute(); } /** * {@inheritDoc} */ public final boolean isText() { assertNotClosedAndSelected(); return mCurrentNode.isText(); } /** * {@inheritDoc} */ public final boolean isFullText() { assertNotClosedAndSelected(); return mCurrentNode.isFullText(); } /** * {@inheritDoc} */ public final boolean isFullTextLeaf() { assertNotClosedAndSelected(); return mCurrentNode.isFullTextLeaf(); } /** * {@inheritDoc} */ public final boolean isFullTextRoot() { assertNotClosedAndSelected(); return mCurrentNode.isFullTextRoot(); } /** * {@inheritDoc} */ public final int getLocalPartKey() { assertNotClosedAndSelected(); return mCurrentNode.getLocalPartKey(); } /** * {@inheritDoc} */ public final String getLocalPart() { assertNotClosedAndSelected(); return mTransactionState.getName(mCurrentNode.getLocalPartKey()); } /** * {@inheritDoc} */ public final int getURIKey() { assertNotClosedAndSelected(); return mCurrentNode.getURIKey(); } /** * {@inheritDoc} */ public final String getURI() { assertNotClosedAndSelected(); return mTransactionState.getName(mCurrentNode.getURIKey()); } /** * {@inheritDoc} */ public final int getPrefixKey() { assertNotClosedAndSelected(); return mCurrentNode.getPrefixKey(); } /** * {@inheritDoc} */ public final String getPrefix() { assertNotClosedAndSelected(); return mTransactionState.getName(mCurrentNode.getPrefixKey()); } /** * {@inheritDoc} */ public final byte[] getValue() { assertNotClosedAndSelected(); return mCurrentNode.getValue(); } /** * {@inheritDoc} */ public final int keyForName(final String name) { assertNotClosed(); return name.hashCode(); } /** * {@inheritDoc} */ public final String nameForKey(final int key) { assertNotClosed(); return mTransactionState.getName(key); } /** * {@inheritDoc} */ public void close() { if (!mClosed) { // Close own state. mTransactionState.close(); // Callback on session to make sure everything is cleaned up. mSessionState.closeReadTransaction(); // Immediately release all references. mSessionState = null; mTransactionState = null; mCurrentNode = null; mClosed = true; } } /** * {@inheritDoc} */ @Override public String toString() { assertNotClosed(); String localPart = ""; try { localPart = getLocalPart(); } catch (Exception e) { throw new IllegalStateException(e); } return "Node " + this.getNodeKey() + "\nwith name: " + localPart + "\nand value:" + getValue(); } /** * Test both whether transaction is closed and a node is selected. */ protected final void assertNotClosedAndSelected() { if (mClosed) { throw new IllegalStateException("Transaction is already closed."); } if (mCurrentNode == null) { throw new IllegalStateException("No node selected."); } } /** * Assert that a node is selected. */ protected final void assertIsSelected() { if (mCurrentNode == null) { throw new IllegalStateException("No node selected."); } } /** * Set state to closed. */ protected final void setClosed() { mClosed = true; } /** * Is the transaction closed? * * @return True if the transaction was closed. */ protected final boolean isClosed() { return mClosed; } /** * Make sure that the session is not yet closed when calling this method. */ protected final void assertNotClosed() { if (mClosed) { throw new IllegalStateException("Transaction is already closed."); } } /** * Getter for superclasses. * * @return The state of this transaction. */ protected final ReadTransactionState getTransactionState() { return mTransactionState; } /** * Replace the state of the transaction. * * @param transactionState State of transaction. */ protected final void setTransactionState( final ReadTransactionState transactionState) { mTransactionState = transactionState; } /** * Getter for superclasses. * * @return The session state. */ protected final SessionState getSessionState() { return mSessionState; } /** * Set session state. * * @param sessionState Session state to set. */ protected final void setSessionState(final SessionState sessionState) { mSessionState = sessionState; } /** * Getter for superclasses. * * @return The current node. */ protected final AbstractNode getCurrentNode() { return mCurrentNode; } /** * Setter for superclasses. * * @param currentNode The current node to set. */ protected final void setCurrentNode(final AbstractNode currentNode) { mCurrentNode = currentNode; } }
// FILE NAME: Hardware.java (Team 339 - Kilroy) // ABSTRACT: // This file contains all of the global definitions for the // hardware objects in the system // Team 339. package org.usfirst.frc.team339.Hardware; import com.ctre.CANTalon; import org.usfirst.frc.team339.HardwareInterfaces.KilroyCamera; import org.usfirst.frc.team339.HardwareInterfaces.MomentarySwitch; import org.usfirst.frc.team339.HardwareInterfaces.Potentiometer; import org.usfirst.frc.team339.HardwareInterfaces.SingleThrowSwitch; import org.usfirst.frc.team339.HardwareInterfaces.UltraSonic; import org.usfirst.frc.team339.HardwareInterfaces.transmission.TransmissionFourWheel; import org.usfirst.frc.team339.HardwareInterfaces.transmission.TransmissionMecanum; import org.usfirst.frc.team339.Utils.Drive; import org.usfirst.frc.team339.Vision.ImageProcessor; import org.usfirst.frc.team339.Vision.VisionScript; import org.usfirst.frc.team339.Vision.operators.ConvexHullOperator; import org.usfirst.frc.team339.Vision.operators.HSLColorThresholdOperator; import org.usfirst.frc.team339.Vision.operators.RemoveSmallObjectsOperator; import edu.wpi.cscore.UsbCamera; import edu.wpi.first.wpilibj.ADXRS450_Gyro; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.MotorSafetyHelper; import edu.wpi.first.wpilibj.PowerDistributionPanel; import edu.wpi.first.wpilibj.Relay; import edu.wpi.first.wpilibj.TalonSRX; import edu.wpi.first.wpilibj.Timer; public class Hardware { // Public Constants /** * denote whether we are running in the lab or not. This will allow us to test * in the lab once the robot is bagged */ public static boolean runningInLab = false; // Private Constants // Hardware Tunables // DIGITAL I/O CLASSES // PWM classes // Jaguar classes // Talon classes /** * Default motor controller. */ public static TalonSRX rightRearMotor = new TalonSRX(4); public static TalonSRX rightFrontMotor = new TalonSRX(2); /** * Default motor controller. */ public static TalonSRX leftRearMotor = new TalonSRX(3); public static TalonSRX leftFrontMotor = new TalonSRX(1); public static CANTalon shooterMotor = new CANTalon(1); // Victor classes // CAN classes public static PowerDistributionPanel pdp = new PowerDistributionPanel( 0); // Relay classes public static Relay ringlightRelay = new Relay(0); // Digital Inputs // Single and double throw switches public static SingleThrowSwitch gearLimitSwitch = new SingleThrowSwitch( 5); // Gear Tooth Sensors // Encoders /** * Default motor encoder */ public static Encoder leftRearEncoder = new Encoder(10, 11); /** * Default motor encoder */ public static Encoder rightRearEncoder = new Encoder(12, 13); // Wiring diagram // Orange - Red PWM 1 // Yellow - White PWM 1 Signal // Brown - Black PWM 1 (or PWM 2) // Blue - White PWM 2 Signal // For the AMT103 Encoders UNVERIFIED // B - White PWM 2 // 5V - Red PWM 1 or 2 // A - White PWM 1 // X - index channel, unused // G - Black PWM 1 or 2 // (DIP Switch) Settings (currently all are off) // Red Light/IR Sensor class // I2C Classes // SOLENOID I/O CLASSES // Compressor class - runs the compressor // public static Compressor compressor = new Compressor(); // Pneumatic Control Module // Solenoids // Double Solenoids // Single Solenoids // ANALOG I/O CLASSES // Analog classes // Gyro class public static ADXRS450_Gyro driveGyro = new ADXRS450_Gyro(); // Potentiometers public static Potentiometer delayPot = new Potentiometer(0, 270);// TODO max // degree value // Sonar/Ultrasonic public static UltraSonic leftUS = new UltraSonic(1); public static UltraSonic rightUS = new UltraSonic(2); // roboRIO CONNECTIONS CLASSES // Axis/USB Camera class // If you are not getting the camera dropdowns on the driver station, make this // ture, send, then make // make it false and send again. // Note: If causing problems, replace "USB_Camera_0" w/ "cam0", and // "USB_Camera_1" w/ "cam1" public static UsbCamera cam0 = new UsbCamera("USB_Camera_0", 0); public static UsbCamera cam1 = new UsbCamera("USB_Camera_1", 1); // Used by the USB Cameras in robot init to set their FPS's public final static int USB_FPS = 15; public static KilroyCamera axisCamera = new KilroyCamera(true); // Used by the Axis Camera in robot init to limit its FPS public final static int AXIS_FPS = 15; public static VisionScript visionScript = new VisionScript( new HSLColorThresholdOperator(55, 147, 14, 255, 78, 255), new RemoveSmallObjectsOperator(3, true), new ConvexHullOperator(false)); public static ImageProcessor imageProcessor = new ImageProcessor( axisCamera, visionScript); // declare the USB camera server and the // USB camera it serves // DRIVER STATION CLASSES // DriverStations class /** * The software object representing the driver station. */ public static final DriverStation driverStation = DriverStation .getInstance(); // Joystick classes /** * The left joystick controlling the drive train. */ public static Joystick leftDriver = new Joystick(0); /** * The right joystick controlling the drive train. */ public static Joystick rightDriver = new Joystick(1); /** * The left joystick controlling misc operations on the robot. */ public static Joystick leftOperator = new Joystick(2); public static MomentarySwitch ringlightSwitch = new MomentarySwitch( leftOperator, 2, false); /** * The right joystick controlling misc operations on the robot. */ public static Joystick rightOperator = new Joystick(3); // Kilroy's Ancillary classes // PID tuneables // PID classes // Transmission class // public static Transmission_old transmission = new Transmission_old( // rightRearMotor, leftRearMotor, rightRearEncoder, // leftRearEncoder); // Drive system public static TransmissionMecanum mecanumDrive = new TransmissionMecanum( rightFrontMotor, rightRearMotor, leftFrontMotor, leftRearMotor); public static TransmissionFourWheel tankDrive = new TransmissionFourWheel( rightFrontMotor, rightRearMotor, leftFrontMotor, leftRearMotor); // Change when we get the robot for mecanum and two ultrasonic. public static Drive autoDrive = new Drive(tankDrive, axisCamera, imageProcessor, leftRearEncoder, rightRearEncoder, leftRearEncoder, rightRearEncoder, rightUS, rightUS); /** * are we using mecanum? set false for tank drive */ public static boolean isUsingMecanum = false; /** * are we using 2 joysticks? */ public static boolean twoJoystickControl = false; // Assembly classes (e.g. forklift) // Utility classes /** * Default timer. */ public static final Timer kilroyTimer = new Timer(); public static final Timer autoStateTimer = new Timer(); /** * Default motor safety */ public static final MotorSafetyHelper leftRearMotorSafety = new MotorSafetyHelper( leftRearMotor); /** * Default motor safety */ public static final MotorSafetyHelper rightRearMotorSafety = new MotorSafetyHelper( rightRearMotor); public static final MotorSafetyHelper rightFrontMotorSafety = new MotorSafetyHelper( rightFrontMotor); public static final MotorSafetyHelper leftFrontMotorSafety = new MotorSafetyHelper( leftFrontMotor); public static final int MINIMUM_AXIS_CAMERA_BRIGHTNESS = 6; } // end class
package exh3y.telebot.data; import java.io.IOException; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.json.JSONObject; import exh3y.telebot.data.enums.ETelegramChatType; public class TelegramChat { private int id; private ETelegramChatType type; private String title = ""; private String username = ""; private String first_name = ""; private String last_name = ""; private Boolean all_members_are_administrators = false; public static TelegramChat create(JSONObject json) throws JsonParseException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(json.toString(), TelegramChat.class); } @Override public boolean equals(Object obj) { if (super.equals(obj)) { return true; } if (obj instanceof TelegramChat) { return ((TelegramChat) obj).getId() == this.getId(); } return false; } /** * Returns the chat's type * * @return The chat's type * @since 0.0.6 */ public ETelegramChatType getType() { return type; } /** * Returns the chat's id * * @return The chat's id * @since 0.0.6 */ public int getId() { return this.id; } /** * @param id * the id to set */ public void setId(int id) { this.id = id; } /** * @param type * the type to set */ public void setType(String type) { this.type = ETelegramChatType.getEnumByName(type); } /** * @return the title */ public String getTitle() { return title; } /** * @param title * the title to set */ public void setTitle(String title) { this.title = title; } /** * @return the username */ public String getUsername() { return username; } /** * @param username * the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the first_name */ public String getFirst_name() { return first_name; } /** * @param first_name * the first_name to set */ public void setFirst_name(String first_name) { this.first_name = first_name; } /** * @return the last_name */ public String getLast_name() { return last_name; } /** * @param last_name * the last_name to set */ public void setLast_name(String last_name) { this.last_name = last_name; } /** * @return the all_members_are_administrators */ public Boolean getAll_members_are_administrators() { return all_members_are_administrators; } /** * @param all_members_are_administrators * the all_members_are_administrators to set */ public void setAll_members_are_administrators(Boolean all_members_are_administrators) { this.all_members_are_administrators = all_members_are_administrators; } /** * @param type * the type to set */ @JsonIgnore public void setType(ETelegramChatType type) { this.type = type; } }
// 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.frc319.subsystems; import java.util.Comparator; import java.util.Vector; import org.usfirst.frc319.RobotMap; import org.usfirst.frc319.commands.*; import com.ni.vision.NIVision; import com.ni.vision.NIVision.Image; import com.ni.vision.NIVision.ImageType; import edu.wpi.first.wpilibj.CameraServer; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class TowerCamera extends Subsystem { private boolean running = false; //Images int session; Image frame; Image binaryFrame; int imaqError; //Final Constants private static double VIEW_ANGLE = 49.4; //View angle fo camera, set to Axis m1011 by default, 64 for m1013, 51.7 for 206, 52 for HD3000 square, 60 for HD3000 640x480 //Flexible Constants private NIVision.Range RED_TARGET_R_RANGE = new NIVision.Range(100, 255); //Default red range for the red target private NIVision.Range RED_TARGET_G_RANGE = new NIVision.Range(0, 255); //Default green range for the red target private NIVision.Range RED_TARGET_B_RANGE = new NIVision.Range(0, 155); //Default blue range for the red target private NIVision.Range BLU_TARGET_R_RANGE = new NIVision.Range(0, 155); //Default red range for the blue target private NIVision.Range BLU_TARGET_G_RANGE = new NIVision.Range(0, 255); //Default green range for the blue target private NIVision.Range BLU_TARGET_B_RANGE = new NIVision.Range(100, 255); //Default blue range for the blue target private boolean RED_TEAM = false; private boolean BLU_TEAM = false; int MAX_PARTICLES = 5; //The maximum number of particles to iterate over double AREA_MINIMUM = 0.5; //Default Area minimum for particle as a percentage of total image area double SCORE_MIN = 75.0; //Minimum score to be considered a target NIVision.ParticleFilterCriteria2 criteria[] = new NIVision.ParticleFilterCriteria2[1]; NIVision.ParticleFilterOptions2 filterOptions = new NIVision.ParticleFilterOptions2(0,0,1,1); Scores scores = new Scores(); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS // Put methods for controlling this subsystem // here. Call these from Commands. public void initDefaultCommand() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND setDefaultCommand(new PauseTowerCamera()); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // Set the default command for a subsystem here. // setDefaultCommand(new MySpecialCommand()); } public void initialize(){ // create images frame = NIVision.imaqCreateImage(ImageType.IMAGE_RGB, 0); binaryFrame = NIVision.imaqCreateImage(ImageType.IMAGE_U8, 0); criteria[0] = new NIVision.ParticleFilterCriteria2(NIVision.MeasurementType.MT_AREA_BY_IMAGE_AREA, AREA_MINIMUM, 100.0, 0, 0); // the camera name (ex "cam0") can be found through the roborio web interface session = NIVision.IMAQdxOpenCamera("cam0", NIVision.IMAQdxCameraControlMode.CameraControlModeController); this.initializeDashboard(); } public void run(){ if(!running){ //if we are not currently running, start the camera NIVision.IMAQdxStartAcquisition(session); } //grab the latest image NIVision.IMAQdxGrab(session, frame, 1); this.readDashboard(); if(BLU_TEAM == RED_TEAM){ //THIS IS AN INCOMPATIBLE STATE, SOME ACTION SHOULD BE TAKEN }else if(BLU_TEAM){ //Threshold the image looking for blue target NIVision.imaqColorThreshold(binaryFrame, frame, 255, NIVision.ColorMode.RGB, BLU_TARGET_R_RANGE, BLU_TARGET_G_RANGE, BLU_TARGET_B_RANGE); }else if(RED_TEAM){ //Threshold the image looking for red target NIVision.imaqColorThreshold(binaryFrame, frame, 255, NIVision.ColorMode.RGB, RED_TARGET_R_RANGE, RED_TARGET_G_RANGE, RED_TARGET_B_RANGE); }else{ //THIS IS AN INCOMPATIBLE STATE, SOME ACTION SHOULD BE TAKEN } //Send particle count to dashboard int numParticles = NIVision.imaqCountParticles(binaryFrame, 1); SmartDashboard.putNumber("Masked particles", numParticles); //Send masked image to dashboard to assist in tweaking mask. CameraServer.getInstance().setImage(binaryFrame); //filter out small particles //MWT: IN 2014 WE USED A WIDTH FILTER INSTEAD OF AREA float areaMin = (float)SmartDashboard.getNumber("Area min %", AREA_MINIMUM); criteria[0].lower = areaMin; imaqError = NIVision.imaqParticleFilter4(binaryFrame, binaryFrame, criteria, filterOptions, null); //Send particle count after filtering to dashboard numParticles = NIVision.imaqCountParticles(binaryFrame, 1); SmartDashboard.putNumber("Filtered particles", numParticles); boolean foundTarget = false; double distance = 0d; if(numParticles > 0){ //Measure particles and sort by particle size Vector<ParticleReport> particles = new Vector<ParticleReport>(); //MWT: IN 2014 WE USED A MAX PARTICLE COUNT TO AVOID BOGGING DOWN THE CPU for(int particleIndex = 0; particleIndex < MAX_PARTICLES && particleIndex < numParticles; particleIndex++){ //MWT: IN 2014 WE USED AN ASPECT RATIO FILTER HERE ParticleReport par = new ParticleReport(); par.PercentAreaToImageArea = NIVision.imaqMeasureParticle(binaryFrame, particleIndex, 0, NIVision.MeasurementType.MT_AREA_BY_IMAGE_AREA); par.Area = NIVision.imaqMeasureParticle(binaryFrame, particleIndex, 0, NIVision.MeasurementType.MT_AREA); par.BoundingRectTop = NIVision.imaqMeasureParticle(binaryFrame, particleIndex, 0, NIVision.MeasurementType.MT_BOUNDING_RECT_TOP); par.BoundingRectLeft = NIVision.imaqMeasureParticle(binaryFrame, particleIndex, 0, NIVision.MeasurementType.MT_BOUNDING_RECT_LEFT); par.BoundingRectBottom = NIVision.imaqMeasureParticle(binaryFrame, particleIndex, 0, NIVision.MeasurementType.MT_BOUNDING_RECT_BOTTOM); par.BoundingRectRight = NIVision.imaqMeasureParticle(binaryFrame, particleIndex, 0, NIVision.MeasurementType.MT_BOUNDING_RECT_RIGHT); particles.add(par); } particles.sort(null); //MWT: IN 2014 WE EXPLICITLY DIDN'T USE THE SCORES MECHANISM //This example only scores the largest particle. Extending to score all particles and choosing the desired one is left as an exercise //for the reader. Note that this scores and reports information about a single particle (single U shaped target). To get accurate information //you will need to evaluate the target against 1 or 2 other targets. scores.Aspect = getApspectScore(particles.elementAt(0)); SmartDashboard.putNumber("Aspect", scores.Aspect); scores.Area = getAreaScore(particles.elementAt(0)); SmartDashboard.putNumber("Area", scores.Area); foundTarget= scores.Aspect > SCORE_MIN && scores.Area > SCORE_MIN; distance = computeDistance(binaryFrame, particles.elementAt(0)); } //MWT: IDEALLY WE WOULD PUT A GREEN AROUND THE IMAGE WHEN THE TARGET IS FOUND AND RED WHEN IT IS NOT //Send distance and target status to dashboard. The bounding rect, particularly the horizontal center (left - right) may be useful for rotating/driving towards a target SmartDashboard.putBoolean("Found Target", foundTarget); SmartDashboard.putNumber("Distance", distance); } //MWT: THIS IS NEVER REFERENCED //Comparator function for sorting particles. Returns true if particle 1 is larger static boolean compareParticleSizes(ParticleReport particle1, ParticleReport particle2) { //we want descending sort order return particle1.PercentAreaToImageArea > particle2.PercentAreaToImageArea; } /** * Converts a ratio with ideal value of 1 to a score. The resulting function is piecewise * linear going from (0,0) to (1,100) to (2,0) and is 0 for all inputs outside the range 0-2 */ double ratioToScore(double ratio) { return (Math.max(0, Math.min(100*(1-Math.abs(1-ratio)), 100))); } double getAreaScore(ParticleReport report) { double boundingArea = (report.BoundingRectBottom - report.BoundingRectTop) * (report.BoundingRectRight - report.BoundingRectLeft); //Tape is 7" edge so 49" bounding rect. With 2" wide tape it covers 24" of the rect. return ratioToScore((49/24)*report.Area/boundingArea); } /** * Method to score if the aspect ratio of the particle appears to match the retro-reflective target. Target is 7"x7" so aspect should be 1 */ double getApspectScore(ParticleReport report) { return ratioToScore(((report.BoundingRectRight-report.BoundingRectLeft)/(report.BoundingRectBottom-report.BoundingRectTop))); } /** * Computes the estimated distance to a target using the width of the particle in the image. For more information and graphics * showing the math behind this approach see the Vision Processing section of the ScreenStepsLive documentation. * * @param image The image to use for measuring the particle estimated rectangle * @param report The Particle Analysis Report for the particle * @return The estimated distance to the target in feet. */ double computeDistance (Image image, ParticleReport report) { double normalizedWidth, targetWidth; NIVision.GetImageSizeResult size; size = NIVision.imaqGetImageSize(image); normalizedWidth = 2*(report.BoundingRectRight - report.BoundingRectLeft)/size.width; targetWidth = 7; return targetWidth/(normalizedWidth*12*Math.tan(VIEW_ANGLE*Math.PI/(180*2))); } private void initializeDashboard(){ //Put default values to SmartDashboard so fields will appear SmartDashboard.putNumber("RED TARGET (R min)", RED_TARGET_R_RANGE.minValue); SmartDashboard.putNumber("RED TARGET (R max)", RED_TARGET_R_RANGE.maxValue); SmartDashboard.putNumber("RED TARGET (G min)", RED_TARGET_G_RANGE.minValue); SmartDashboard.putNumber("RED TARGET (G max)", RED_TARGET_G_RANGE.maxValue); SmartDashboard.putNumber("RED TARGET (B min)", RED_TARGET_B_RANGE.minValue); SmartDashboard.putNumber("RED TARGET (B max)", RED_TARGET_B_RANGE.maxValue); SmartDashboard.putNumber("BLUE TARGET (R min)", BLU_TARGET_R_RANGE.minValue); SmartDashboard.putNumber("BLUE TARGET (R max)", BLU_TARGET_R_RANGE.maxValue); SmartDashboard.putNumber("BLUE TARGET (G min)", BLU_TARGET_G_RANGE.minValue); SmartDashboard.putNumber("BLUE TARGET (G max)", BLU_TARGET_G_RANGE.maxValue); SmartDashboard.putNumber("BLUE TARGET (B min)", BLU_TARGET_B_RANGE.minValue); SmartDashboard.putNumber("BLUE TARGET (B max)", BLU_TARGET_B_RANGE.maxValue); SmartDashboard.putBoolean("RED TEAM", RED_TEAM); SmartDashboard.putBoolean("BLUE TEAM", BLU_TEAM); SmartDashboard.putNumber("AREA MIN %", AREA_MINIMUM); } private void readDashboard(){ //Update threshold values from SmartDashboard. For performance reasons it is recommended to remove this after calibration is finished. RED_TARGET_R_RANGE.minValue = (int)SmartDashboard.getNumber("RED TARGET (R min)", RED_TARGET_R_RANGE.minValue); RED_TARGET_R_RANGE.maxValue = (int)SmartDashboard.getNumber("RED TARGET (R max)", RED_TARGET_R_RANGE.maxValue); RED_TARGET_G_RANGE.minValue = (int)SmartDashboard.getNumber("RED TARGET (G min)", RED_TARGET_G_RANGE.minValue); RED_TARGET_G_RANGE.maxValue = (int)SmartDashboard.getNumber("RED TARGET (G max)", RED_TARGET_G_RANGE.maxValue); RED_TARGET_B_RANGE.minValue = (int)SmartDashboard.getNumber("RED TARGET (B min)", RED_TARGET_B_RANGE.minValue); RED_TARGET_B_RANGE.maxValue = (int)SmartDashboard.getNumber("RED TARGET (B max)", RED_TARGET_B_RANGE.maxValue); BLU_TARGET_R_RANGE.minValue = (int)SmartDashboard.getNumber("BLUE TARGET (R min)", BLU_TARGET_R_RANGE.minValue); BLU_TARGET_R_RANGE.maxValue = (int)SmartDashboard.getNumber("BLUE TARGET (R max)", BLU_TARGET_R_RANGE.maxValue); BLU_TARGET_G_RANGE.minValue = (int)SmartDashboard.getNumber("BLUE TARGET (G min)", BLU_TARGET_G_RANGE.minValue); BLU_TARGET_G_RANGE.maxValue = (int)SmartDashboard.getNumber("BLUE TARGET (G max)", BLU_TARGET_G_RANGE.maxValue); BLU_TARGET_B_RANGE.minValue = (int)SmartDashboard.getNumber("BLUE TARGET (B min)", BLU_TARGET_B_RANGE.minValue); BLU_TARGET_B_RANGE.maxValue = (int)SmartDashboard.getNumber("BLUE TARGET (B max)", BLU_TARGET_B_RANGE.maxValue); RED_TEAM = SmartDashboard.getBoolean("RED TEAM", RED_TEAM); BLU_TEAM = SmartDashboard.getBoolean("BLUE TEAM", BLU_TEAM); AREA_MINIMUM = SmartDashboard.getNumber("AREA MIN %", AREA_MINIMUM); } //A structure to hold measurements of a particle public class ParticleReport implements Comparator<ParticleReport>, Comparable<ParticleReport>{ double PercentAreaToImageArea; double Area; double BoundingRectLeft; double BoundingRectTop; double BoundingRectRight; double BoundingRectBottom; public int compareTo(ParticleReport r) { return (int)(r.Area - this.Area); } public int compare(ParticleReport r1, ParticleReport r2) { return (int)(r1.Area - r2.Area); } }; //Structure to represent the scores for the various tests used for target identification public class Scores { double Area; double Aspect; }; }
package istc.bigdawg.monitoring; import istc.bigdawg.BDConstants; import istc.bigdawg.exceptions.NotSupportIslandException; import istc.bigdawg.postgresql.PostgreSQLHandler; import istc.bigdawg.query.ASTNode; import istc.bigdawg.query.parser.Parser; import istc.bigdawg.query.parser.simpleParser; import istc.bigdawg.catalog.CatalogInstance; import istc.bigdawg.catalog.CatalogViewer; import istc.bigdawg.executor.Executor; import istc.bigdawg.executor.plan.ExecutionNodeFactory; import istc.bigdawg.executor.plan.QueryExecutionPlan; import istc.bigdawg.packages.QueriesAndPerformanceInformation; import istc.bigdawg.plan.SQLQueryPlan; import istc.bigdawg.plan.extract.SQLPlanParser; import istc.bigdawg.plan.operators.Operator; import istc.bigdawg.signature.Signature; import javax.ws.rs.core.Response; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; public class Monitor { private static final String INSERT = "INSERT INTO monitoring(island, query, lastRan, duration) VALUES ('%s', '%s', -1, -1)"; private static final String DELETE = "DELETE FROM monitoring WHERE island='%s' AND query='%s'"; private static final String UPDATE = "UPDATE monitoring SET lastRan=%d, duration=%d WHERE island='%s' AND query='%s'"; private static final String RETRIEVE = "SELECT * FROM monitoring WHERE island='%s' AND query='%s'"; public static boolean addBenchmarks(List<QueryExecutionPlan> qeps, boolean lean) { BDConstants.Shim[] shims = BDConstants.Shim.values(); return addBenchmarks(qeps, lean, shims); } public static boolean addBenchmarks(List<QueryExecutionPlan> qeps, boolean lean, BDConstants.Shim[] shims) { for (QueryExecutionPlan qep: qeps) { try { if (!insert(QueryExecutionPlan.qepToString(qep), qep.getIsland())) { return false; } } catch (NotSupportIslandException e) { e.printStackTrace(); } } if (!lean) { try { runBenchmarks(qeps); } catch (Exception e) { e.printStackTrace(); } } return true; } public static boolean removeBenchmarks(List<QueryExecutionPlan> qeps) { return removeBenchmarks(qeps, false); } public static boolean removeBenchmarks(List<QueryExecutionPlan> qeps, boolean removeAll) { for (QueryExecutionPlan qep: qeps) { try { if (!delete(QueryExecutionPlan.qepToString(qep), qep.getIsland())) { return false; } } catch (NotSupportIslandException e) { e.printStackTrace(); } } return true; } public static QueriesAndPerformanceInformation getBenchmarkPerformance(List<QueryExecutionPlan> qeps) throws NotSupportIslandException { List<String> queries = new ArrayList<>(); List<Object> perfInfo = new ArrayList<>(); for (QueryExecutionPlan qep: qeps) { String qepString = QueryExecutionPlan.qepToString(qep); queries.add(qepString); PostgreSQLHandler handler = new PostgreSQLHandler(); perfInfo.add(handler.executeQuery(String.format(RETRIEVE, qep.getIsland(), qepString))); } List<List<String>> queryList = new ArrayList(); queryList.add(queries); System.out.printf("[BigDAWG] MONITOR: Performance information generated.\n"); return new QueriesAndPerformanceInformation(queryList, perfInfo); } private static boolean insert(String query, String island) throws NotSupportIslandException { PostgreSQLHandler handler = new PostgreSQLHandler(); Response response = handler.executeQuery(String.format(INSERT, island, query)); return response.getStatus() == 200; } private static boolean delete(String query, String island) throws NotSupportIslandException { PostgreSQLHandler handler = new PostgreSQLHandler(); Response response = handler.executeQuery(String.format(DELETE, island, query)); return response.getStatus() == 200; } public static void runBenchmarks(List<QueryExecutionPlan> qeps) throws Exception { for (QueryExecutionPlan qep: qeps) { Executor.executePlan(qep); } } public void finishedBenchmark(QueryExecutionPlan qep, long startTime, long endTime) throws SQLException { PostgreSQLHandler handler = new PostgreSQLHandler(); handler.executeNotQueryPostgreSQL(String.format(UPDATE, endTime, endTime-startTime, qep.getIsland(), QueryExecutionPlan.qepToString(qep))); } }
package me.jjm_223.pt; import me.jjm_223.pt.listeners.EggClick; import me.jjm_223.pt.listeners.EggHit; import me.jjm_223.pt.listeners.ItemDespawn; import me.jjm_223.pt.utils.DataStorage; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.IOException; /** * Main class for PetTransportation. */ public class PetTransportation extends JavaPlugin { private DataStorage storage; @Override public void onEnable() { storage = new DataStorage(this); PluginManager pm = getServer().getPluginManager(); pm.registerEvents(new EggHit(this), this); pm.registerEvents(new EggClick(this), this); pm.registerEvents(new ItemDespawn(this), this); } @Override public void onDisable() { try { storage.save(); } catch (IOException e) { e.printStackTrace(); } } public DataStorage getStorage() { return this.storage; } }
package mho.qbar.objects; import mho.wheels.misc.Readers; import mho.wheels.ordering.Ordering; import mho.wheels.ordering.comparators.ShortlexComparator; import mho.wheels.structures.Pair; import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import static mho.wheels.iterables.IterableUtils.*; /** * <p>A vector with {@link Rational} coordinates. May be zero-dimensional. * * <p>There is only one instance of {@code ZERO_DIMENSIONAL}, so it may be compared with other {@code RationalVector}s * using {@code ==}. * * <p>This class is immutable. */ @SuppressWarnings("ConstantConditions") public class RationalVector implements Comparable<RationalVector>, Iterable<Rational> { public static final RationalVector ZERO_DIMENSIONAL = new RationalVector(new ArrayList<>()); /** * Used by {@link mho.qbar.objects.RationalVector#compareTo} */ private static Comparator<Iterable<Rational>> RATIONAL_ITERABLE_COMPARATOR = new ShortlexComparator<>(); /** * The vector's coordinates */ private @NotNull List<Rational> coordinates; /** * Private constructor for {@code RationalVector}; assumes arguments are valid * * <ul> * <li>{@code coordinates} cannot have any null elements.</li> * <li>Any {@code RationalVector} may be constructed with this constructor.</li> * </ul> * * @param coordinates the vector's coordinates */ private RationalVector(@NotNull List<Rational> coordinates) { this.coordinates = coordinates; } /** * Returns an {@code Iterator} over this {@code RationalVector}'s coordinates. Does not support removal. * * <ul> * <li>The result is finite and contains no nulls.</li> * </ul> * * Length is |{@code coordinates}| * * @return an {@code Iterator} over this {@code RationalVector}'s coordinates */ @Override public @NotNull Iterator<Rational> iterator() { return new Iterator<Rational>() { private int i = 0; @Override public boolean hasNext() { return i < coordinates.size(); } @Override public Rational next() { return coordinates.get(i++); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * Returns {@code this}'s x-coordinate. * * <ul> * <li>{@code this} must be non-empty.</li> * <li>The result is non-null.</li> * </ul> * * @return the x-coordinate of {@code this} */ public @NotNull Rational x() { return coordinates.get(0); } /** * Returns {@code this}'s y-coordinate. * * <ul> * <li>{@code this} must have dimension at least 2.</li> * <li>The result is non-null.</li> * </ul> * * @return the y-coordinate of {@code this} */ public @NotNull Rational y() { return coordinates.get(1); } /** * Returns {@code this}'s z-coordinate. * * <ul> * <li>{@code this} must have dimension at least 3.</li> * <li>The result is non-null.</li> * </ul> * * @return the z-coordinate of {@code this} */ public @NotNull Rational z() { return coordinates.get(2); } /** * Returns {@code this}'s w-coordinate (the coordinate of the 4th dimension). * * <ul> * <li>{@code this} must have dimension at least 4.</li> * <li>The result is non-null.</li> * </ul> * * @return the w-coordinate of {@code this} */ public @NotNull Rational w() { return coordinates.get(3); } /** * Returns one of {@code this}'s coordinates. 0-indexed. * * <ul> * <li>{@code this} must be non-empty.</li> * <li>{@code i} must be non-negative.</li> * <li>{@code i} must be less than the dimension of {@code this}.</li> * <li>The result is non-null.</li> * </ul> * * @param i the 0-based coordinate index * @return the {@code i}th coordinate of {@code this} */ public @NotNull Rational x(int i) { return coordinates.get(i); } /** * Creates a {@code RationalVector} from a list of {@code Rational}s. Throws an exception if any element is null. * Makes a defensive copy of {@code coordinates}. * * <ul> * <li>{@code coordinates} cannot have any null elements.</li> * <li>The result is not null.</li> * </ul> * * Length is |{@code coordinates}| * * @param coordinates the vector's coordinates * @return the {@code RationalVector} with the specified coordinates */ public static @NotNull RationalVector of(@NotNull List<Rational> coordinates) { if (coordinates.isEmpty()) return ZERO_DIMENSIONAL; if (any(a -> a == null, coordinates)) throw new NullPointerException(); return new RationalVector(toList(coordinates)); } /** * Creates a one-dimensional {@code RationalVector} from a single {@code Rational} coordinate. * * <ul> * <li>{@code a} must be non-null.</li> * <li>The result is a one-dimensional vector.</li> * </ul> * * Length is 1 * * @param a the vector's coordinate * @return [a] */ public static @NotNull RationalVector of(@NotNull Rational a) { return new RationalVector(Arrays.asList(a)); } /** * Returns this {@code RationalVector}'s dimension * * <ul> * <li>{@code this} may be any {@code RationalVector}.</li> * <li>The result is non-negative.</li> * </ul> * * @return this {@code RationalVector}'s dimension */ public int dimension() { return coordinates.size(); } /** * Creates the zero vector with a given dimension. * * <ul> * <li>{@code dimension} must be non-negative.</li> * <li>The result is a {@code RationalVector} all of whose coordinates are 0.</li> * </ul> * * Length is {@code dimension} * * @param dimension the zero vector's dimension * @return 0 */ public static @NotNull RationalVector zero(int dimension) { if (dimension == 0) return ZERO_DIMENSIONAL; if (dimension < 0) throw new IllegalArgumentException("dimension must be non-negative"); return new RationalVector(toList(replicate(dimension, Rational.ZERO))); } /** * Creates an identity vector; that is, a vector with a given dimension, all of whose coordinates are 0, except for * a single coordinate which is 1. Identity matrices are made up of identity vectors. There is no identity vector * of dimension 0. * * <ul> * <li>{@code dimension} must be positive.</li> * <li>{@code i} must be non-negative.</li> * <li>{@code i} must be less than {@code dimension}.</li> * <li>The result is a {@code RationalVector} with one coordinate equal to 1 and the others equal to 0.</li> * </ul> * * Length is {@code dimension} * * @param dimension the vector's dimension * @param i the index of the vector coordinate which is 1 * @return an identity vector */ public static @NotNull RationalVector identity(int dimension, int i) { if (dimension < 1) throw new IllegalArgumentException("dimension must be positive"); if (i < 0) throw new IllegalArgumentException("i must be non-negative"); if (i >= dimension) throw new IllegalArgumentException("i must be less than dimension"); return new RationalVector(toList(insert(replicate(dimension - 1, Rational.ZERO), i, Rational.ONE))); } /** * Determines whether {@code this} is a zero vector * * <ul> * <li>{@code this} may be any {@code RationalVector}.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @return whether {@code this}=0 */ public boolean isZero() { return all(r -> r == Rational.ZERO, coordinates); } public @NotNull RationalVector negate() { if (this == ZERO_DIMENSIONAL) return ZERO_DIMENSIONAL; return new RationalVector(toList(map(Rational::negate, coordinates))); } /** * Returns the sum of {@code this} and {@code that}. * * <ul> * <li>{@code this} may be any {@code RationalVector}.</li> * <li>{@code that} cannot be null.</li> * <li>{@code this} and {@code that} must have the same dimension.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code RationalVector} added to {@code this} * @return {@code this}+{@code that} */ public @NotNull RationalVector add(@NotNull RationalVector that) { if (coordinates.size() != that.coordinates.size()) throw new ArithmeticException("vectors must have same dimension"); if (this == ZERO_DIMENSIONAL) return ZERO_DIMENSIONAL; return new RationalVector(toList(zipWith(p -> p.a.add(p.b), coordinates, that.coordinates))); } public @NotNull RationalVector subtract(@NotNull RationalVector that) { return add(that.negate()); } public @NotNull RationalVector multiply(@NotNull Rational that) { if (this == ZERO_DIMENSIONAL) return ZERO_DIMENSIONAL; return new RationalVector(toList(map(r -> r.multiply(that), coordinates))); } public @NotNull RationalVector multiply(@NotNull BigInteger that) { if (this == ZERO_DIMENSIONAL) return ZERO_DIMENSIONAL; return new RationalVector(toList(map(r -> r.multiply(that), coordinates))); } public @NotNull RationalVector multiply(int that) { if (this == ZERO_DIMENSIONAL) return ZERO_DIMENSIONAL; return new RationalVector(toList(map(r -> r.multiply(that), coordinates))); } /** * Returns the scalar product of {@code this} and the inverse of {@code that}. * * <ul> * <li>{@code this} can be any {@code RationalVector}.</li> * <li>{@code that} cannot be zero.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code RationalVector} {@code this} is multiplied by * @return {@code this}/{@code that} */ public @NotNull RationalVector divide(@NotNull Rational that) { return multiply(that.invert()); } /** * Returns the scalar product of {@code this} and the inverse of {@code that}. * * <ul> * <li>{@code this} can be any {@code RationalVector}.</li> * <li>{@code that} cannot be zero.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code RationalVector} {@code this} is multiplied by * @return {@code this}/{@code that} */ public @NotNull RationalVector divide(@NotNull BigInteger that) { return multiply(Rational.of(BigInteger.ONE, that)); } /** * Returns the scalar product of {@code this} and the inverse of {@code that}. * * <ul> * <li>{@code this} can be any {@code RationalVector}.</li> * <li>{@code that} cannot be zero.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code RationalVector} {@code this} is multiplied by * @return {@code this}/{@code that} */ public @NotNull RationalVector divide(int that) { return multiply(Rational.of(1, that)); } public @NotNull RationalVector shiftLeft(int bits) { if (this == ZERO_DIMENSIONAL) return ZERO_DIMENSIONAL; if (bits == 0) return this; return new RationalVector(toList(map(r -> r.shiftLeft(bits), coordinates))); } public @NotNull RationalVector shiftRight(int bits) { if (this == ZERO_DIMENSIONAL) return ZERO_DIMENSIONAL; if (bits == 0) return this; return new RationalVector(toList(map(r -> r.shiftRight(bits), coordinates))); } public static RationalVector sum(@NotNull Iterable<RationalVector> xs) { if (isEmpty(xs)) throw new IllegalArgumentException("cannot take sum of empty RationalVector list"); if (!same(map(RationalVector::dimension, xs))) throw new ArithmeticException("all elements must have the same dimension"); List<Rational> coordinates = toList(map(Rational::sum, transpose(map(v -> (Iterable<Rational>) v, xs)))); return coordinates.isEmpty() ? ZERO_DIMENSIONAL : new RationalVector(coordinates); } public static @NotNull Iterable<RationalVector> delta(@NotNull Iterable<RationalVector> xs) { if (isEmpty(xs)) throw new IllegalArgumentException("cannot get delta of empty Iterable"); if (head(xs) == null) throw new NullPointerException(); return adjacentPairsWith(p -> p.b.subtract(p.a), xs); } public @NotNull Rational dot(@NotNull RationalVector that) { if (coordinates.size() != that.coordinates.size()) throw new ArithmeticException("vectors must have same dimension"); return Rational.sum(zipWith(p -> p.a.multiply(p.b), coordinates, that.coordinates)); } /** * Determines whether the angle between {@code this} and {@code that} is less than, equal to, or greater than a * right angle. For the purposes of this method, zero vectors are considered to be at a right angle to any other * vector. * * <ul> * <li>{@code this} may be any {@code RationalVector}.</li> * <li>{@code that} cannot be null.</li> * <li>{@code this} and {@code that} must have the same dimension.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code RationalVector} which, along with {@code this}, creates the angle under consideration * @return whether the angle between {@code this} and {@code that} is acute ({@code LT}), right ({@code EQ}), or * obtuse ({@code GT}). */ public @NotNull Ordering rightAngleCompare(@NotNull RationalVector that) { return Ordering.compare(dot(that), Rational.ZERO).invert(); } /** * Determines whether {@code this} is equal to {@code that}. * * <ul> * <li>{@code this} may be any {@code RationalVector}.</li> * <li>{@code that} may be any {@code Object}.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param that The {@code RationalVector} to be compared with {@code this} * @return {@code this}={@code that} */ @Override public boolean equals(Object that) { return this == that || that != null && getClass() == that.getClass() && coordinates.equals(((RationalVector) that).coordinates); } /** * Calculates the hash code of {@code this}. * * <ul> * <li>{@code this} may be any {@code RationalVector}.</li> * <li>(conjecture) The result may be any {@code int}.</li> * </ul> * * @return {@code this}'s hash code. */ @Override public int hashCode() { return coordinates.hashCode(); } @Override public int compareTo(@NotNull RationalVector that) { return RATIONAL_ITERABLE_COMPARATOR.compare(coordinates, that.coordinates); } /** * Creates a {@code RationalVector} from a {@code String}. A valid {@code String} begins with '[' and ends with * ']', and the rest is a possibly-empty list of comma-separated {@code String}s, each of which validly represents * a {@code Rational} (see {@link Rational#toString}). * * <ul> * <li>{@code s} must be non-null.</li> * <li>The result may contain any {@code RationalVector}, or be empty.</li> * </ul> * * @param s a string representation of a {@code RationalVector} * @return the {@code RationalVector} represented by {@code s}, or an empty {@code Optional} if {@code s} is * invalid */ public static @NotNull Optional<RationalVector> read(@NotNull String s) { Optional<List<Rational>> ors = Readers.readList(Rational::findIn, s); if (!ors.isPresent()) return Optional.empty(); if (ors.get().isEmpty()) return Optional.of(ZERO_DIMENSIONAL); return Optional.of(new RationalVector(ors.get())); } /** * Finds the first occurrence of a {@code RationalVector} in a {@code String}. Returns the {@code RationalVector} * and the index at which it was found. Returns an empty {@code Optional} if no {@code RationalVector} is found. * Only {@code String}s which could have been emitted by {@link RationalVector#toString} are recognized. The * longest possible {@code RationalVector} is parsed. * * <ul> * <li>{@code s} must be non-null.</li> * <li>The result is non-null. If it is non-empty, then neither of the {@code Pair}'s components is null, and the * second component is non-negative.</li> * </ul> * * @param s the input {@code String} * @return the first {@code RationalVector} found in {@code s}, and the index at which it was found */ public static @NotNull Optional<Pair<RationalVector, Integer>> findIn(@NotNull String s) { Optional<Pair<List<Rational>, Integer>> op = Readers.findListIn(Rational::findIn, s); if (!op.isPresent()) return Optional.empty(); Pair<List<Rational>, Integer> p = op.get(); if (p.a.isEmpty()) return Optional.of(new Pair<>(ZERO_DIMENSIONAL, p.b)); return Optional.of(new Pair<>(new RationalVector(p.a), p.b)); } /** * Creates a {@code String} representation of {@code this}. * * <ul> * <li>{@code this} may be any {@code RationalVector}.</li> * <li>The result is a {@code String} which begins with '[' and ends with ']', and the rest is a possibly-empty * list of comma-separated {@code String}s, each of which validly represents a {@code Rational} (see * {@link Rational#toString}).</li> * </ul> * * @return a {@code String} representation of {@code this} */ public @NotNull String toString() { return coordinates.toString(); } }
package mil.nga.geopackage.user; import java.util.Date; import mil.nga.geopackage.GeoPackageException; import mil.nga.geopackage.db.DateConverter; /** * User Row containing the values from a single Result Set row * * @param <TColumn> * column type * @param <TTable> * table type * * @author osbornb */ public abstract class UserRow<TColumn extends UserColumn, TTable extends UserTable<TColumn>> extends UserCoreRow<TColumn, TTable> { /** * Constructor * * @param table * table * @param columns * columns * @param columnTypes * column types * @param values * values * @since 3.5.0 */ protected UserRow(TTable table, UserColumns<TColumn> columns, int[] columnTypes, Object[] values) { super(table, columns, columnTypes, values); } /** * Constructor to create an empty row * * @param table * table */ protected UserRow(TTable table) { super(table); } /** * Copy Constructor * * @param userRow * user row to copy */ protected UserRow(UserRow<TColumn, TTable> userRow) { super(userRow); } /** * Convert the row to content values * * @return content values */ public ContentValues toContentValues() { return toContentValues(true); } /** * Convert the row to content values * * @param includeNulls * include null values * * @return content values */ public ContentValues toContentValues(boolean includeNulls) { ContentValues contentValues = new ContentValues(); for (TColumn column : columns.getColumns()) { Object value = values[column.getIndex()]; if (!column.isPrimaryKey() || (value != null && columns.isPkModifiable())) { String columnName = column.getName(); if (value != null) { columnToContentValue(contentValues, column, value); } else if (includeNulls) { contentValues.putNull(columnName); } } } if (contentValues.size() == 0) { for (TColumn column : columns.getColumns()) { if (!column.isPrimaryKey()) { contentValues.putNull(column.getName()); } } } return contentValues; } /** * Map the column to the content values * * @param contentValues * content values * @param column * column * @param value * value */ protected void columnToContentValue(ContentValues contentValues, TColumn column, Object value) { String columnName = column.getName(); if (value instanceof Number) { if (value instanceof Byte) { validateValue(column, value, Byte.class, Short.class, Integer.class, Long.class); contentValues.put(columnName, (Byte) value); } else if (value instanceof Short) { validateValue(column, value, Short.class, Integer.class, Long.class); contentValues.put(columnName, (Short) value); } else if (value instanceof Integer) { validateValue(column, value, Integer.class, Long.class, Byte.class, Short.class); contentValues.put(columnName, (Integer) value); } else if (value instanceof Long) { validateValue(column, value, Long.class, Double.class); contentValues.put(columnName, (Long) value); } else if (value instanceof Float) { validateValue(column, value, Float.class); contentValues.put(columnName, (Float) value); } else if (value instanceof Double) { validateValue(column, value, Double.class); contentValues.put(columnName, (Double) value); } else { throw new GeoPackageException("Unsupported Number type: " + value.getClass().getSimpleName()); } } else if (value instanceof String) { validateValue(column, value, String.class); String stringValue = (String) value; if (column.getMax() != null && stringValue.length() > column.getMax()) { throw new GeoPackageException( "String is larger than the column max. Size: " + stringValue.length() + ", Max: " + column.getMax() + ", Column: " + columnName); } contentValues.put(columnName, stringValue); } else if (value instanceof byte[]) { validateValue(column, value, byte[].class); byte[] byteValue = (byte[]) value; if (column.getMax() != null && byteValue.length > column.getMax()) { throw new GeoPackageException( "Byte array is larger than the column max. Size: " + byteValue.length + ", Max: " + column.getMax() + ", Column: " + columnName); } contentValues.put(columnName, byteValue); } else if (value instanceof Boolean) { validateValue(column, value, Boolean.class); Boolean booleanValue = (Boolean) value; short shortBoolean = booleanValue ? (short) 1 : (short) 0; contentValues.put(columnName, shortBoolean); } else if (value instanceof Date) { validateValue(column, value, Date.class, String.class); Date dateValue = (Date) value; DateConverter converter = DateConverter .converter(column.getDataType()); String dateString = converter.stringValue(dateValue); contentValues.put(columnName, dateString); } else { throw new GeoPackageException( "Unsupported update column value. column: " + columnName + ", value: " + value); } } }
package net.darkhax.bookshelf; import net.darkhax.bookshelf.handler.BookshelfEventHandler; import net.darkhax.bookshelf.lib.Constants; import net.darkhax.bookshelf.util.AnnotationUtils; import net.darkhax.bookshelf.util.OreDictUtils; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.event.FMLConstructionEvent; import net.minecraftforge.fml.common.event.FMLInitializationEvent; @Mod(modid = Constants.MOD_ID, name = Constants.MOD_NAME, version = Constants.VERSION_NUMBER, acceptedMinecraftVersions = "[1.12,1.12.2)") public class Bookshelf { @Instance(Constants.MOD_ID) public static Bookshelf instance; @EventHandler public void onConstruction (FMLConstructionEvent event) { AnnotationUtils.asmData = event.getASMHarvestedData(); MinecraftForge.EVENT_BUS.register(new BookshelfEventHandler()); } @EventHandler public void Init (FMLInitializationEvent event) { OreDictUtils.initAdditionalVanillaEntries(); } }
/* * Note: this class contains code adapted from wicket-contrib-database. */ package net.databinder; import java.util.HashMap; import java.util.Map; import javax.servlet.http.Cookie; import org.hibernate.HibernateException; import org.hibernate.Session; import wicket.Page; import wicket.RequestCycle; import wicket.Response; import wicket.WicketRuntimeException; import wicket.protocol.http.WebRequest; import wicket.protocol.http.WebRequestCycle; import wicket.protocol.http.WebResponse; import wicket.protocol.http.WebSession; /** * <p>Opens Hibernate sessions as required and closes (but does not flush) them at a request's * end. Creates a Hibernate session factory in a static initialization block, configuring it with * annotatied classes in a DataApplication subclass.</p> * <p>If you want to use a custom session factory, you will need to override initHibernate() * and openSession(). Both of these refer to this class's private static session factory, which * would remain null in such a configuration. </p> * @see DataApplication.initDataRequestCycle() * @author Nathan Hamblen */ public class DataRequestCycle extends WebRequestCycle { private Session hibernateSession; /** cache of cookies from request */ private Map<String, Cookie> cookies; public DataRequestCycle(final WebSession session, final WebRequest request, final Response response) { super(session, request, response); } /** * Will open a session if one is not already open for this request. * @return the open Hibernate session for the current request cycle. */ public static Session getHibernateSession() { RequestCycle cycle = get(); if (!(cycle instanceof DataRequestCycle)) throw new WicketRuntimeException("Current request cycle not managed by Databinder. " + "Your application session factory must return a DataSession or some other session " + "that produces DataRequestCycle."); return ((DataRequestCycle)cycle).getCycleHibernateSession(); } /** * Opens a session and a transaction if a session is not already associated with * this request cycle. * @return the open Hibernate session for this request cycle. */ protected Session getCycleHibernateSession() { if(hibernateSession == null) { hibernateSession = openSession(); hibernateSession.beginTransaction(); } return hibernateSession; } /** * @return a newly opened session */ protected Session openSession() throws HibernateException { return DataStaticService.getHibernateSessionFactory().openSession(); } /** Roll back active transactions and close session. */ protected void closeSession() { if (hibernateSession != null) { try { if (hibernateSession.getTransaction().isActive()) hibernateSession.getTransaction().rollback(); } finally { try { hibernateSession.close(); } finally { hibernateSession = null; } } } } /** * Closes the Hibernate session, if one was open for this request. If a transaction has * not been committed, it will be rolled back before cloing the session. * @see net.databinder.components.DataForm#onSubmit() */ @Override protected void onEndRequest() { closeSession(); } /** Roll back active transactions and close session. */ @Override public Page onRuntimeException(Page page, RuntimeException e) { closeSession(); // close session; another one will open if models load themselves return null; } /** * Return or build cache of cookies cookies from request. */ protected Map<String, Cookie> getCookies() { if (cookies == null) { Cookie ary[] = ((WebRequest)getRequest()).getCookies(); cookies = new HashMap<String, Cookie>(ary == null ? 0 : ary.length); if (ary != null) for (Cookie c : ary) cookies.put(c.getName(), c); } return cookies; } /** * Retrieve cookie from request, so long as it hasn't been cleared. Cookies cleared by * clearCookie() are still contained in the current request's cookie array, but this method * will not return them. * @param name cookie name * @return cookie requested, or null if unavailable */ public Cookie getCookie(String name) { return getCookies().get(name); } /** * Sets a new a cookie with an expiration time of zero to an clear an old one from the * browser, and removes any copy from this request's cookie cache. Subsequent calls to * <tt>getCookie(String name)</tt> during this request will not return a cookie of that name. * @param name cookie name */ public void clearCookie(String name) { getCookies().remove(name); ((WebResponse)getResponse()).clearCookie(new Cookie(name, "")); } }
package net.sf.jabref; import java.awt.Color; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.util.*; import java.util.prefs.BackingStoreException; import java.util.prefs.InvalidPreferencesFormatException; import java.util.prefs.Preferences; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import javax.swing.*; import net.sf.jabref.gui.*; import net.sf.jabref.gui.actions.CleanUpAction; import net.sf.jabref.gui.entryeditor.EntryEditorTabList; import net.sf.jabref.gui.maintable.PersistenceTableColumnListener; import net.sf.jabref.gui.preftabs.ImportSettingsTab; import net.sf.jabref.importer.fileformat.ImportFormat; import net.sf.jabref.logic.autocompleter.AutoCompletePreferences; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.logic.labelPattern.GlobalLabelPattern; import net.sf.jabref.logic.util.OS; import net.sf.jabref.model.entry.EntryUtil; import net.sf.jabref.model.entry.CustomEntryType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import net.sf.jabref.exporter.CustomExportList; import net.sf.jabref.exporter.ExportComparator; import net.sf.jabref.external.DroppedFileHandler; import net.sf.jabref.importer.CustomImportList; import net.sf.jabref.logic.remote.RemotePreferences; import net.sf.jabref.specialfields.SpecialFieldsUtils; public final class JabRefPreferences { private static final Log LOGGER = LogFactory.getLog(JabRefPreferences.class); public static final String EXTERNAL_FILE_TYPES = "externalFileTypes"; /** * HashMap that contains all preferences which are set by default */ public final Map<String, Object> defaults = new HashMap<>(); /* contents of the defaults HashMap that are defined in this class. * There are more default parameters in this map which belong to separate preference classes. */ public static final String EMACS_PATH = "emacsPath"; public static final String EMACS_ADDITIONAL_PARAMETERS = "emacsParameters"; public static final String EMACS_23 = "emacsUseV23InsertString"; public static final String FONT_FAMILY = "fontFamily"; public static final String WIN_LOOK_AND_FEEL = "lookAndFeel"; public static final String LATEX_EDITOR_PATH = "latexEditorPath"; public static final String TEXSTUDIO_PATH = "TeXstudioPath"; public static final String WIN_EDT_PATH = "winEdtPath"; public static final String TEXMAKER_PATH = "texmakerPath"; public static final String LANGUAGE = "language"; public static final String NAMES_LAST_ONLY = "namesLastOnly"; public static final String ABBR_AUTHOR_NAMES = "abbrAuthorNames"; public static final String NAMES_NATBIB = "namesNatbib"; public static final String NAMES_FIRST_LAST = "namesFf"; public static final String NAMES_AS_IS = "namesAsIs"; public static final String TABLE_COLOR_CODES_ON = "tableColorCodesOn"; public static final String ENTRY_EDITOR_HEIGHT = "entryEditorHeight"; public static final String PREVIEW_PANEL_HEIGHT = "previewPanelHeight"; public static final String AUTO_RESIZE_MODE = "autoResizeMode"; public static final String WINDOW_MAXIMISED = "windowMaximised"; public static final String SIZE_Y = "mainWindowSizeY"; public static final String SIZE_X = "mainWindowSizeX"; public static final String POS_Y = "mainWindowPosY"; public static final String POS_X = "mainWindowPosX"; public static final String VIM_SERVER = "vimServer"; public static final String VIM = "vim"; public static final String LYXPIPE = "lyxpipe"; public static final String USE_DEFAULT_LOOK_AND_FEEL = "useDefaultLookAndFeel"; public static final String PROXY_PORT = "proxyPort"; public static final String PROXY_HOSTNAME = "proxyHostname"; public static final String USE_PROXY = "useProxy"; public static final String PROXY_USERNAME = "proxyUsername"; public static final String PROXY_PASSWORD = "proxyPassword"; public static final String USE_PROXY_AUTHENTICATION = "useProxyAuthentication"; public static final String TABLE_PRIMARY_SORT_FIELD = "priSort"; public static final String TABLE_PRIMARY_SORT_DESCENDING = "priDescending"; public static final String TABLE_SECONDARY_SORT_FIELD = "secSort"; public static final String TABLE_SECONDARY_SORT_DESCENDING = "secDescending"; public static final String TABLE_TERTIARY_SORT_FIELD = "terSort"; public static final String TABLE_TERTIARY_SORT_DESCENDING = "terDescending"; public static final String SAVE_IN_ORIGINAL_ORDER = "saveInOriginalOrder"; public static final String SAVE_IN_SPECIFIED_ORDER = "saveInSpecifiedOrder"; public static final String SAVE_PRIMARY_SORT_FIELD = "savePriSort"; public static final String SAVE_PRIMARY_SORT_DESCENDING = "savePriDescending"; public static final String SAVE_SECONDARY_SORT_FIELD = "saveSecSort"; public static final String SAVE_SECONDARY_SORT_DESCENDING = "saveSecDescending"; public static final String SAVE_TERTIARY_SORT_FIELD = "saveTerSort"; public static final String SAVE_TERTIARY_SORT_DESCENDING = "saveTerDescending"; public static final String EXPORT_IN_ORIGINAL_ORDER = "exportInOriginalOrder"; public static final String EXPORT_IN_SPECIFIED_ORDER = "exportInSpecifiedOrder"; public static final String EXPORT_PRIMARY_SORT_FIELD = "exportPriSort"; public static final String EXPORT_PRIMARY_SORT_DESCENDING = "exportPriDescending"; public static final String EXPORT_SECONDARY_SORT_FIELD = "exportSecSort"; public static final String EXPORT_SECONDARY_SORT_DESCENDING = "exportSecDescending"; public static final String EXPORT_TERTIARY_SORT_FIELD = "exportTerSort"; public static final String EXPORT_TERTIARY_SORT_DESCENDING = "exportTerDescending"; public static final String NEWLINE = "newline"; public static final String COLUMN_WIDTHS = "columnWidths"; public static final String COLUMN_NAMES = "columnNames"; public static final String SIDE_PANE_COMPONENT_PREFERRED_POSITIONS = "sidePaneComponentPreferredPositions"; public static final String SIDE_PANE_COMPONENT_NAMES = "sidePaneComponentNames"; public static final String XMP_PRIVACY_FILTERS = "xmpPrivacyFilters"; public static final String USE_XMP_PRIVACY_FILTER = "useXmpPrivacyFilter"; public static final String SEARCH_MODE_FILTER = "searchModeFilter"; public static final String SEARCH_CASE_SENSITIVE = "caseSensitiveSearch"; public static final String DEFAULT_AUTO_SORT = "defaultAutoSort"; public static final String DEFAULT_SHOW_SOURCE = "defaultShowSource"; public static final String STRINGS_SIZE_Y = "stringsSizeY"; public static final String STRINGS_SIZE_X = "stringsSizeX"; public static final String STRINGS_POS_Y = "stringsPosY"; public static final String STRINGS_POS_X = "stringsPosX"; public static final String DUPLICATES_SIZE_Y = "duplicatesSizeY"; public static final String DUPLICATES_SIZE_X = "duplicatesSizeX"; public static final String DUPLICATES_POS_Y = "duplicatesPosY"; public static final String DUPLICATES_POS_X = "duplicatesPosX"; public static final String MERGEENTRIES_SIZE_Y = "mergeEntriesSizeY"; public static final String MERGEENTRIES_SIZE_X = "mergeEntriesSizeX"; public static final String MERGEENTRIES_POS_Y = "mergeEntriesPosY"; public static final String MERGEENTRIES_POS_X = "mergeEntriesPosX"; public static final String LAST_EDITED = "lastEdited"; public static final String OPEN_LAST_EDITED = "openLastEdited"; public static final String LAST_FOCUSED = "lastFocused"; public static final String BACKUP = "backup"; public static final String ENTRY_TYPE_FORM_WIDTH = "entryTypeFormWidth"; public static final String ENTRY_TYPE_FORM_HEIGHT_FACTOR = "entryTypeFormHeightFactor"; public static final String AUTO_OPEN_FORM = "autoOpenForm"; public static final String FILE_WORKING_DIRECTORY = "fileWorkingDirectory"; public static final String IMPORT_WORKING_DIRECTORY = "importWorkingDirectory"; public static final String EXPORT_WORKING_DIRECTORY = "exportWorkingDirectory"; public static final String WORKING_DIRECTORY = "workingDirectory"; public static final String NUMBER_COL_WIDTH = "numberColWidth"; public static final String AUTO_COMPLETE = "autoComplete"; public static final String SEARCH_PANE_POS_Y = "searchPanePosY"; public static final String SEARCH_PANE_POS_X = "searchPanePosX"; public static final String SEARCH_REG_EXP = "regExpSearch"; public static final String EDITOR_EMACS_KEYBINDINGS = "editorEMACSkeyBindings"; public static final String EDITOR_EMACS_KEYBINDINGS_REBIND_CA = "editorEMACSkeyBindingsRebindCA"; public static final String EDITOR_EMACS_KEYBINDINGS_REBIND_CF = "editorEMACSkeyBindingsRebindCF"; public static final String GROUP_SHOW_NUMBER_OF_ELEMENTS = "groupShowNumberOfElements"; public static final String GROUP_AUTO_HIDE = "groupAutoHide"; public static final String GROUP_AUTO_SHOW = "groupAutoShow"; public static final String GROUP_EXPAND_TREE = "groupExpandTree"; public static final String GROUP_SHOW_DYNAMIC = "groupShowDynamic"; public static final String GROUP_SHOW_ICONS = "groupShowIcons"; public static final String GROUPS_DEFAULT_FIELD = "groupsDefaultField"; public static final String GROUP_SELECT_MATCHES = "groupSelectMatches"; public static final String GROUP_SHOW_OVERLAPPING = "groupShowOverlapping"; public static final String GROUP_INVERT_SELECTIONS = "groupInvertSelections"; public static final String GROUP_INTERSECT_SELECTIONS = "groupIntersectSelections"; public static final String GROUP_FLOAT_SELECTIONS = "groupFloatSelections"; public static final String EDIT_GROUP_MEMBERSHIP_MODE = "groupEditGroupMembershipMode"; public static final String GROUP_KEYWORD_SEPARATOR = "groupKeywordSeparator"; public static final String AUTO_ASSIGN_GROUP = "autoAssignGroup"; public static final String LIST_OF_FILE_COLUMNS = "listOfFileColumns"; public static final String EXTRA_FILE_COLUMNS = "extraFileColumns"; public static final String ARXIV_COLUMN = "arxivColumn"; public static final String FILE_COLUMN = "fileColumn"; public static final String PREFER_URL_DOI = "preferUrlDoi"; public static final String URL_COLUMN = "urlColumn"; public static final String DISABLE_ON_MULTIPLE_SELECTION = "disableOnMultipleSelection"; public static final String CTRL_CLICK = "ctrlClick"; public static final String INCOMPLETE_ENTRY_BACKGROUND = "incompleteEntryBackground"; public static final String FIELD_EDITOR_TEXT_COLOR = "fieldEditorTextColor"; public static final String ACTIVE_FIELD_EDITOR_BACKGROUND_COLOR = "activeFieldEditorBackgroundColor"; public static final String INVALID_FIELD_BACKGROUND_COLOR = "invalidFieldBackgroundColor"; public static final String VALID_FIELD_BACKGROUND_COLOR = "validFieldBackgroundColor"; public static final String MARKED_ENTRY_BACKGROUND5 = "markedEntryBackground5"; public static final String MARKED_ENTRY_BACKGROUND4 = "markedEntryBackground4"; public static final String MARKED_ENTRY_BACKGROUND3 = "markedEntryBackground3"; public static final String MARKED_ENTRY_BACKGROUND2 = "markedEntryBackground2"; public static final String MARKED_ENTRY_BACKGROUND1 = "markedEntryBackground1"; public static final String MARKED_ENTRY_BACKGROUND0 = "markedEntryBackground0"; public static final String VERY_GRAYED_OUT_TEXT = "veryGrayedOutText"; public static final String VERY_GRAYED_OUT_BACKGROUND = "veryGrayedOutBackground"; public static final String GRAYED_OUT_TEXT = "grayedOutText"; public static final String GRAYED_OUT_BACKGROUND = "grayedOutBackground"; public static final String GRID_COLOR = "gridColor"; public static final String TABLE_TEXT = "tableText"; public static final String TABLE_OPT_FIELD_BACKGROUND = "tableOptFieldBackground"; public static final String TABLE_REQ_FIELD_BACKGROUND = "tableReqFieldBackground"; public static final String TABLE_BACKGROUND = "tableBackground"; public static final String TABLE_SHOW_GRID = "tableShowGrid"; public static final String TABLE_ROW_PADDING = "tableRowPadding"; public static final String MENU_FONT_SIZE = "menuFontSize"; public static final String OVERRIDE_DEFAULT_FONTS = "overrideDefaultFonts"; public static final String FONT_SIZE = "fontSize"; public static final String FONT_STYLE = "fontStyle"; public static final String RECENT_FILES = "recentFiles"; public static final String GENERAL_FIELDS = "generalFields"; public static final String RENAME_ON_MOVE_FILE_TO_FILE_DIR = "renameOnMoveFileToFileDir"; public static final String MEMORY_STICK_MODE = "memoryStickMode"; public static final String DEFAULT_OWNER = "defaultOwner"; public static final String GROUPS_VISIBLE_ROWS = "groupsVisibleRows"; public static final String DEFAULT_ENCODING = "defaultEncoding"; public static final String TOOLBAR_VISIBLE = "toolbarVisible"; public static final String HIGHLIGHT_GROUPS_MATCHING_ALL = "highlightGroupsMatchingAll"; public static final String HIGHLIGHT_GROUPS_MATCHING_ANY = "highlightGroupsMatchingAny"; public static final String UPDATE_TIMESTAMP = "updateTimestamp"; public static final String TIME_STAMP_FIELD = "timeStampField"; public static final String TIME_STAMP_FORMAT = "timeStampFormat"; public static final String OVERWRITE_TIME_STAMP = "overwriteTimeStamp"; public static final String USE_TIME_STAMP = "useTimeStamp"; public static final String WARN_ABOUT_DUPLICATES_IN_INSPECTION = "warnAboutDuplicatesInInspection"; public static final String UNMARK_ALL_ENTRIES_BEFORE_IMPORTING = "unmarkAllEntriesBeforeImporting"; public static final String MARK_IMPORTED_ENTRIES = "markImportedEntries"; public static final String GENERATE_KEYS_AFTER_INSPECTION = "generateKeysAfterInspection"; public static final String NON_WRAPPABLE_FIELDS = "nonWrappableFields"; public static final String PUT_BRACES_AROUND_CAPITALS = "putBracesAroundCapitals"; public static final String RESOLVE_STRINGS_ALL_FIELDS = "resolveStringsAllFields"; public static final String DO_NOT_RESOLVE_STRINGS_FOR = "doNotResolveStringsFor"; public static final String AUTO_DOUBLE_BRACES = "autoDoubleBraces"; public static final String PREVIEW_PRINT_BUTTON = "previewPrintButton"; public static final String PREVIEW_1 = "preview1"; public static final String PREVIEW_0 = "preview0"; public static final String ACTIVE_PREVIEW = "activePreview"; public static final String PREVIEW_ENABLED = "previewEnabled"; public static final String CUSTOM_EXPORT_FORMAT = "customExportFormat"; public static final String CUSTOM_IMPORT_FORMAT = "customImportFormat"; public static final String PSVIEWER = "psviewer"; public static final String PDFVIEWER = "pdfviewer"; public static final String BINDINGS = "bindings"; public static final String BIND_NAMES = "bindNames"; public static final String MARKED_ENTRY_BACKGROUND = "markedEntryBackground"; public static final String KEY_PATTERN_REGEX = "KeyPatternRegex"; public static final String KEY_PATTERN_REPLACEMENT = "KeyPatternReplacement"; // Currently, it is not possible to specify defaults for specific entry types // When this should be made possible, the code to inspect is net.sf.jabref.gui.preftabs.LabelPatternPrefTab.storeSettings() -> LabelPattern keypatterns = getLabelPattern(); etc public static final String DEFAULT_LABEL_PATTERN = "defaultLabelPattern"; public static final String SEARCH_MODE_FLOAT = "floatSearch"; public static final String GRAY_OUT_NON_HITS = "grayOutNonHits"; public static final String CONFIRM_DELETE = "confirmDelete"; public static final String WARN_BEFORE_OVERWRITING_KEY = "warnBeforeOverwritingKey"; public static final String AVOID_OVERWRITING_KEY = "avoidOverwritingKey"; public static final String DISPLAY_KEY_WARNING_DIALOG_AT_STARTUP = "displayKeyWarningDialogAtStartup"; public static final String DIALOG_WARNING_FOR_EMPTY_KEY = "dialogWarningForEmptyKey"; public static final String DIALOG_WARNING_FOR_DUPLICATE_KEY = "dialogWarningForDuplicateKey"; public static final String ALLOW_TABLE_EDITING = "allowTableEditing"; public static final String OVERWRITE_OWNER = "overwriteOwner"; public static final String USE_OWNER = "useOwner"; public static final String AUTOLINK_EXACT_KEY_ONLY = "autolinkExactKeyOnly"; public static final String SHOW_FILE_LINKS_UPGRADE_WARNING = "showFileLinksUpgradeWarning"; public static final String SEARCH_DIALOG_HEIGHT = "searchDialogHeight"; public static final String SEARCH_DIALOG_WIDTH = "searchDialogWidth"; public static final String IMPORT_INSPECTION_DIALOG_HEIGHT = "importInspectionDialogHeight"; public static final String IMPORT_INSPECTION_DIALOG_WIDTH = "importInspectionDialogWidth"; public static final String SIDE_PANE_WIDTH = "sidePaneWidth"; public static final String LAST_USED_EXPORT = "lastUsedExport"; public static final String LAST_USED_IMPORT = "lastUsedImport"; public static final String FLOAT_MARKED_ENTRIES = "floatMarkedEntries"; public static final String CITE_COMMAND = "citeCommand"; public static final String EXTERNAL_JOURNAL_LISTS = "externalJournalLists"; public static final String PERSONAL_JOURNAL_LIST = "personalJournalList"; public static final String GENERATE_KEYS_BEFORE_SAVING = "generateKeysBeforeSaving"; public static final String EMAIL_SUBJECT = "emailSubject"; public static final String OPEN_FOLDERS_OF_ATTACHED_FILES = "openFoldersOfAttachedFiles"; public static final String KEY_GEN_ALWAYS_ADD_LETTER = "keyGenAlwaysAddLetter"; public static final String KEY_GEN_FIRST_LETTER_A = "keyGenFirstLetterA"; public static final String VALUE_DELIMITERS2 = "valueDelimiters"; public static final String BIBLATEX_MODE = "biblatexMode"; public static final String ENFORCE_LEGAL_BIBTEX_KEY = "enforceLegalBibtexKey"; public static final String PROMPT_BEFORE_USING_AUTOSAVE = "promptBeforeUsingAutosave"; public static final String AUTO_SAVE_INTERVAL = "autoSaveInterval"; public static final String AUTO_SAVE = "autoSave"; public static final String USE_LOCK_FILES = "useLockFiles"; public static final String RUN_AUTOMATIC_FILE_SEARCH = "runAutomaticFileSearch"; public static final String NUMERIC_FIELDS = "numericFields"; public static final String DEFAULT_REG_EXP_SEARCH_EXPRESSION_KEY = "defaultRegExpSearchExpression"; public static final String REG_EXP_SEARCH_EXPRESSION_KEY = "regExpSearchExpression"; public static final String AUTOLINK_USE_REG_EXP_SEARCH_KEY = "useRegExpSearch"; public static final String DB_CONNECT_USERNAME = "dbConnectUsername"; public static final String DB_CONNECT_DATABASE = "dbConnectDatabase"; public static final String DB_CONNECT_HOSTNAME = "dbConnectHostname"; public static final String DB_CONNECT_SERVER_TYPE = "dbConnectServerType"; public static final String BIB_LOC_AS_PRIMARY_DIR = "bibLocAsPrimaryDir"; public static final String SELECTED_FETCHER_INDEX = "selectedFetcherIndex"; public static final String WEB_SEARCH_VISIBLE = "webSearchVisible"; public static final String ALLOW_FILE_AUTO_OPEN_BROWSE = "allowFileAutoOpenBrowse"; public static final String CUSTOM_TAB_NAME = "customTabName_"; public static final String CUSTOM_TAB_FIELDS = "customTabFields_"; public static final String USER_FILE_DIR_INDIVIDUAL = "userFileDirIndividual"; public static final String USER_FILE_DIR_IND_LEGACY = "userFileDirInd_Legacy"; public static final String USER_FILE_DIR = "userFileDir"; public static final String USE_UNIT_FORMATTER_ON_SEARCH = "useUnitFormatterOnSearch"; public static final String USE_CASE_KEEPER_ON_SEARCH = "useCaseKeeperOnSearch"; public static final String USE_CONVERT_TO_EQUATION = "useConvertToEquation"; public static final String USE_IEEE_ABRV = "useIEEEAbrv"; public static final String PUSH_TO_APPLICATION = "pushToApplication"; // OpenOffice/LibreOffice preferences public static final String OO_EXECUTABLE_PATH = "ooExecutablePath"; public static final String OO_PATH = "ooPath"; public static final String OO_JARS_PATH = "ooJarsPath"; public static final String SHOW_OO_PANEL = "showOOPanel"; public static final String SYNC_OO_WHEN_CITING = "syncOOWhenCiting"; public static final String USE_ALL_OPEN_BASES = "useAllOpenBases"; public static final String OO_BIBLIOGRAPHY_STYLE_FILE = "ooBibliographyStyleFile"; public static final String OO_USE_DEFAULT_AUTHORYEAR_STYLE = "ooUseDefaultAuthoryearStyle"; public static final String OO_USE_DEFAULT_NUMERICAL_STYLE = "ooUseDefaultNumericalStyle"; public static final String OO_CHOOSE_STYLE_DIRECTLY = "ooChooseStyleDirectly"; public static final String OO_DIRECT_FILE = "ooDirectFile"; public static final String OO_STYLE_DIRECTORY = "ooStyleDirectory"; //non-default preferences private static final String CUSTOM_TYPE_NAME = "customTypeName_"; private static final String CUSTOM_TYPE_REQ = "customTypeReq_"; private static final String CUSTOM_TYPE_OPT = "customTypeOpt_"; private static final String CUSTOM_TYPE_PRIOPT = "customTypePriOpt_"; public static final String PDF_PREVIEW = "pdfPreview"; private static final char[][] VALUE_DELIMITERS = new char[][] { {'"', '"'}, {'{', '}'}}; public String WRAPPED_USERNAME; public final String MARKING_WITH_NUMBER_PATTERN; private final Preferences prefs; private final Set<String> putBracesAroundCapitalsFields = new HashSet<>(4); private final Set<String> nonWrappableFields = new HashSet<>(5); private GlobalLabelPattern keyPattern; // Object containing custom export formats: public final CustomExportList customExports; // Helper string private static final String USER_HOME = System.getProperty("user.home"); /** * Set with all custom {@link ImportFormat}s */ public final CustomImportList customImports; // Object containing info about customized entry editor tabs. private EntryEditorTabList tabList; // The following field is used as a global variable during the export of a database. // By setting this field to the path of the database's default file directory, formatters // that should resolve external file paths can access this field. This is an ugly hack // to solve the problem of formatters not having access to any context except for the // string to be formatted and possible formatter arguments. public String[] fileDirForDatabase; // Similarly to the previous variable, this is a global that can be used during // the export of a database if the database filename should be output. If a database // is tied to a file on disk, this variable is set to that file before export starts: public File databaseFile; // The following field is used as a global variable during the export of a database. // It is used to hold custom name formatters defined by a custom export filter. // It is set before the export starts: public Map<String, String> customExportNameFormatters; // The only instance of this class: private static JabRefPreferences singleton; public static JabRefPreferences getInstance() { if (JabRefPreferences.singleton == null) { JabRefPreferences.singleton = new JabRefPreferences(); } return JabRefPreferences.singleton; } // The constructor is made private to enforce this as a singleton class: private JabRefPreferences() { try { if (new File("jabref.xml").exists()) { importPreferences("jabref.xml"); } } catch (JabRefException e) { LOGGER.warn("Could not import preferences from jabref.xml: " + e.getMessage(), e); } // load user preferences prefs = Preferences.userNodeForPackage(JabRef.class); defaults.put(TEXMAKER_PATH, OS.guessProgramPath("texmaker", "Texmaker")); defaults.put(WIN_EDT_PATH, OS.guessProgramPath("WinEdt", "WinEdt Team\\WinEdt")); defaults.put(LATEX_EDITOR_PATH, OS.guessProgramPath("LEd", "LEd")); defaults.put(TEXSTUDIO_PATH, OS.guessProgramPath("texstudio", "TeXstudio")); if (OS.OS_X) { //defaults.put(JabRefPreferences.PDFVIEWER, "/Applications/Preview.app"); //defaults.put(JabRefPreferences.PSVIEWER, "/Applications/Preview.app"); //defaults.put("htmlviewer", "/Applications/Safari.app"); defaults.put(EMACS_PATH, "emacsclient"); defaults.put(EMACS_23, true); defaults.put(EMACS_ADDITIONAL_PARAMETERS, "-n -e"); defaults.put(FONT_FAMILY, "SansSerif"); defaults.put(WIN_LOOK_AND_FEEL, UIManager.getSystemLookAndFeelClassName()); } else if (OS.WINDOWS) { //defaults.put(JabRefPreferences.PDFVIEWER, "cmd.exe /c start /b"); //defaults.put(JabRefPreferences.PSVIEWER, "cmd.exe /c start /b"); //defaults.put("htmlviewer", "cmd.exe /c start /b"); defaults.put(WIN_LOOK_AND_FEEL, "com.jgoodies.looks.windows.WindowsLookAndFeel"); defaults.put(EMACS_PATH, "emacsclient.exe"); defaults.put(EMACS_23, true); defaults.put(EMACS_ADDITIONAL_PARAMETERS, "-n -e"); defaults.put(FONT_FAMILY, "Arial"); } else { //defaults.put(JabRefPreferences.PDFVIEWER, "evince"); //defaults.put(JabRefPreferences.PSVIEWER, "gv"); //defaults.put("htmlviewer", "firefox"); defaults.put(WIN_LOOK_AND_FEEL, "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel"); defaults.put(FONT_FAMILY, "SansSerif"); // linux defaults.put(EMACS_PATH, "gnuclient"); defaults.put(EMACS_23, false); defaults.put(EMACS_ADDITIONAL_PARAMETERS, "-batch -eval"); } defaults.put(PUSH_TO_APPLICATION, "TeXstudio"); defaults.put(USE_PROXY, Boolean.FALSE); defaults.put(PROXY_HOSTNAME, ""); defaults.put(PROXY_PORT, "80"); defaults.put(USE_PROXY_AUTHENTICATION, Boolean.FALSE); defaults.put(PROXY_USERNAME, ""); defaults.put(PROXY_PASSWORD, ""); defaults.put(PDF_PREVIEW, Boolean.FALSE); defaults.put(USE_DEFAULT_LOOK_AND_FEEL, Boolean.TRUE); defaults.put(LYXPIPE, USER_HOME + File.separator + ".lyx/lyxpipe"); defaults.put(VIM, "vim"); defaults.put(VIM_SERVER, "vim"); defaults.put(POS_X, 0); defaults.put(POS_Y, 0); defaults.put(SIZE_X, 840); defaults.put(SIZE_Y, 680); defaults.put(WINDOW_MAXIMISED, Boolean.FALSE); defaults.put(AUTO_RESIZE_MODE, JTable.AUTO_RESIZE_ALL_COLUMNS); defaults.put(PREVIEW_PANEL_HEIGHT, 200); defaults.put(ENTRY_EDITOR_HEIGHT, 400); defaults.put(TABLE_COLOR_CODES_ON, Boolean.FALSE); defaults.put(NAMES_AS_IS, Boolean.FALSE); // "Show names unchanged" defaults.put(NAMES_FIRST_LAST, Boolean.FALSE); // "Show 'Firstname Lastname'" defaults.put(NAMES_NATBIB, Boolean.TRUE); // "Natbib style" defaults.put(ABBR_AUTHOR_NAMES, Boolean.TRUE); // "Abbreviate names" defaults.put(NAMES_LAST_ONLY, Boolean.TRUE); // "Show last names only" // system locale as default defaults.put(LANGUAGE, Locale.getDefault().getLanguage()); // Sorting preferences defaults.put(TABLE_PRIMARY_SORT_FIELD, "author"); defaults.put(TABLE_PRIMARY_SORT_DESCENDING, Boolean.FALSE); defaults.put(TABLE_SECONDARY_SORT_FIELD, "year"); defaults.put(TABLE_SECONDARY_SORT_DESCENDING, Boolean.TRUE); defaults.put(TABLE_TERTIARY_SORT_FIELD, "title"); defaults.put(TABLE_TERTIARY_SORT_DESCENDING, Boolean.FALSE); // if both are false, then the entries are saved in table order defaults.put(SAVE_IN_ORIGINAL_ORDER, Boolean.FALSE); defaults.put(SAVE_IN_SPECIFIED_ORDER, Boolean.TRUE); // save order: if SAVE_IN_SPECIFIED_ORDER, then use following criteria defaults.put(SAVE_PRIMARY_SORT_FIELD, "bibtexkey"); defaults.put(SAVE_PRIMARY_SORT_DESCENDING, Boolean.FALSE); defaults.put(SAVE_SECONDARY_SORT_FIELD, "author"); defaults.put(SAVE_SECONDARY_SORT_DESCENDING, Boolean.FALSE); defaults.put(SAVE_TERTIARY_SORT_FIELD, "title"); defaults.put(SAVE_TERTIARY_SORT_DESCENDING, Boolean.FALSE); // export order defaults.put(EXPORT_IN_ORIGINAL_ORDER, Boolean.FALSE); defaults.put(EXPORT_IN_SPECIFIED_ORDER, Boolean.FALSE); // export order: if EXPORT_IN_SPECIFIED_ORDER, then use following criteria defaults.put(EXPORT_PRIMARY_SORT_FIELD, "bibtexkey"); defaults.put(EXPORT_PRIMARY_SORT_DESCENDING, Boolean.FALSE); defaults.put(EXPORT_SECONDARY_SORT_FIELD, "author"); defaults.put(EXPORT_SECONDARY_SORT_DESCENDING, Boolean.FALSE); defaults.put(EXPORT_TERTIARY_SORT_FIELD, "title"); defaults.put(EXPORT_TERTIARY_SORT_DESCENDING, Boolean.TRUE); defaults.put(NEWLINE, System.lineSeparator()); defaults.put(SIDE_PANE_COMPONENT_NAMES, ""); defaults.put(SIDE_PANE_COMPONENT_PREFERRED_POSITIONS, ""); defaults.put(COLUMN_NAMES, "entrytype;author/editor;title;year;journal/booktitle;bibtexkey"); defaults.put(COLUMN_WIDTHS, "75;300;470;60;130;100"); defaults.put(PersistenceTableColumnListener.ACTIVATE_PREF_KEY, PersistenceTableColumnListener.DEFAULT_ENABLED); defaults.put(XMP_PRIVACY_FILTERS, "pdf;timestamp;keywords;owner;note;review"); defaults.put(USE_XMP_PRIVACY_FILTER, Boolean.FALSE); defaults.put(NUMBER_COL_WIDTH, GUIGlobals.NUMBER_COL_LENGTH); defaults.put(WORKING_DIRECTORY, USER_HOME); defaults.put(EXPORT_WORKING_DIRECTORY, USER_HOME); // Remembers working directory of last import defaults.put(IMPORT_WORKING_DIRECTORY, USER_HOME); defaults.put(FILE_WORKING_DIRECTORY, USER_HOME); defaults.put(AUTO_OPEN_FORM, Boolean.TRUE); defaults.put(ENTRY_TYPE_FORM_HEIGHT_FACTOR, 1); defaults.put(ENTRY_TYPE_FORM_WIDTH, 1); defaults.put(BACKUP, Boolean.TRUE); defaults.put(OPEN_LAST_EDITED, Boolean.TRUE); defaults.put(LAST_EDITED, null); defaults.put(LAST_FOCUSED, null); defaults.put(STRINGS_POS_X, 0); defaults.put(STRINGS_POS_Y, 0); defaults.put(STRINGS_SIZE_X, 600); defaults.put(STRINGS_SIZE_Y, 400); defaults.put(DUPLICATES_POS_X, 0); defaults.put(DUPLICATES_POS_Y, 0); defaults.put(DUPLICATES_SIZE_X, 800); defaults.put(DUPLICATES_SIZE_Y, 600); defaults.put(MERGEENTRIES_POS_X, 0); defaults.put(MERGEENTRIES_POS_Y, 0); defaults.put(MERGEENTRIES_SIZE_X, 800); defaults.put(MERGEENTRIES_SIZE_Y, 600); defaults.put(DEFAULT_SHOW_SOURCE, Boolean.FALSE); defaults.put(DEFAULT_AUTO_SORT, Boolean.FALSE); defaults.put(SEARCH_CASE_SENSITIVE, Boolean.FALSE); defaults.put(SEARCH_MODE_FILTER, Boolean.TRUE); defaults.put(SEARCH_REG_EXP, Boolean.FALSE); defaults.put(SEARCH_PANE_POS_X, 0); defaults.put(SEARCH_PANE_POS_Y, 0); defaults.put(EDITOR_EMACS_KEYBINDINGS, Boolean.FALSE); defaults.put(EDITOR_EMACS_KEYBINDINGS_REBIND_CA, Boolean.TRUE); defaults.put(EDITOR_EMACS_KEYBINDINGS_REBIND_CF, Boolean.TRUE); defaults.put(AUTO_COMPLETE, Boolean.TRUE); AutoCompletePreferences.putDefaults(defaults); defaults.put(GROUP_FLOAT_SELECTIONS, Boolean.TRUE); defaults.put(GROUP_INTERSECT_SELECTIONS, Boolean.TRUE); defaults.put(GROUP_INVERT_SELECTIONS, Boolean.FALSE); defaults.put(GROUP_SHOW_OVERLAPPING, Boolean.FALSE); defaults.put(GROUP_SELECT_MATCHES, Boolean.FALSE); defaults.put(GROUPS_DEFAULT_FIELD, "keywords"); defaults.put(GROUP_SHOW_ICONS, Boolean.TRUE); defaults.put(GROUP_SHOW_DYNAMIC, Boolean.TRUE); defaults.put(GROUP_EXPAND_TREE, Boolean.TRUE); defaults.put(GROUP_AUTO_SHOW, Boolean.TRUE); defaults.put(GROUP_AUTO_HIDE, Boolean.TRUE); defaults.put(GROUP_SHOW_NUMBER_OF_ELEMENTS, Boolean.FALSE); defaults.put(AUTO_ASSIGN_GROUP, Boolean.TRUE); defaults.put(GROUP_KEYWORD_SEPARATOR, ", "); defaults.put(EDIT_GROUP_MEMBERSHIP_MODE, Boolean.FALSE); defaults.put(HIGHLIGHT_GROUPS_MATCHING_ANY, Boolean.FALSE); defaults.put(HIGHLIGHT_GROUPS_MATCHING_ALL, Boolean.FALSE); defaults.put(TOOLBAR_VISIBLE, Boolean.TRUE); defaults.put(DEFAULT_ENCODING, StandardCharsets.UTF_8.name()); defaults.put(GROUPS_VISIBLE_ROWS, 8); defaults.put(DEFAULT_OWNER, System.getProperty("user.name")); defaults.put(MEMORY_STICK_MODE, Boolean.FALSE); defaults.put(RENAME_ON_MOVE_FILE_TO_FILE_DIR, Boolean.TRUE); // The general fields stuff is made obsolete by the CUSTOM_TAB_... entries. defaults.put(GENERAL_FIELDS, "crossref;keywords;file;doi;url;urldate;" + "pdf;comment;owner"); defaults.put(FONT_STYLE, java.awt.Font.PLAIN); defaults.put(FONT_SIZE, 12); defaults.put(OVERRIDE_DEFAULT_FONTS, Boolean.FALSE); defaults.put(MENU_FONT_SIZE, 11); defaults.put(TABLE_ROW_PADDING, GUIGlobals.TABLE_ROW_PADDING); defaults.put(TABLE_SHOW_GRID, Boolean.FALSE); // Main table color settings: defaults.put(TABLE_BACKGROUND, "255:255:255"); defaults.put(TABLE_REQ_FIELD_BACKGROUND, "230:235:255"); defaults.put(TABLE_OPT_FIELD_BACKGROUND, "230:255:230"); defaults.put(TABLE_TEXT, "0:0:0"); defaults.put(GRID_COLOR, "210:210:210"); defaults.put(GRAYED_OUT_BACKGROUND, "210:210:210"); defaults.put(GRAYED_OUT_TEXT, "40:40:40"); defaults.put(VERY_GRAYED_OUT_BACKGROUND, "180:180:180"); defaults.put(VERY_GRAYED_OUT_TEXT, "40:40:40"); defaults.put(MARKED_ENTRY_BACKGROUND0, "255:255:180"); defaults.put(MARKED_ENTRY_BACKGROUND1, "255:220:180"); defaults.put(MARKED_ENTRY_BACKGROUND2, "255:180:160"); defaults.put(MARKED_ENTRY_BACKGROUND3, "255:120:120"); defaults.put(MARKED_ENTRY_BACKGROUND4, "255:75:75"); defaults.put(MARKED_ENTRY_BACKGROUND5, "220:255:220"); defaults.put(VALID_FIELD_BACKGROUND_COLOR, "255:255:255"); defaults.put(INVALID_FIELD_BACKGROUND_COLOR, "255:0:0"); defaults.put(ACTIVE_FIELD_EDITOR_BACKGROUND_COLOR, "220:220:255"); defaults.put(FIELD_EDITOR_TEXT_COLOR, "0:0:0"); defaults.put(INCOMPLETE_ENTRY_BACKGROUND, "250:175:175"); defaults.put(CTRL_CLICK, Boolean.FALSE); defaults.put(DISABLE_ON_MULTIPLE_SELECTION, Boolean.FALSE); defaults.put(URL_COLUMN, Boolean.TRUE); defaults.put(PREFER_URL_DOI, Boolean.FALSE); defaults.put(FILE_COLUMN, Boolean.TRUE); defaults.put(ARXIV_COLUMN, Boolean.FALSE); defaults.put(EXTRA_FILE_COLUMNS, Boolean.FALSE); defaults.put(LIST_OF_FILE_COLUMNS, ""); defaults.put(SpecialFieldsUtils.PREF_SPECIALFIELDSENABLED, SpecialFieldsUtils.PREF_SPECIALFIELDSENABLED_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRIORITY, SpecialFieldsUtils.PREF_SHOWCOLUMN_PRIORITY_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_QUALITY, SpecialFieldsUtils.PREF_SHOWCOLUMN_QUALITY_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_RANKING, SpecialFieldsUtils.PREF_SHOWCOLUMN_RANKING_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_RELEVANCE, SpecialFieldsUtils.PREF_SHOWCOLUMN_RELEVANCE_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRINTED, SpecialFieldsUtils.PREF_SHOWCOLUMN_PRINTED_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_READ, SpecialFieldsUtils.PREF_SHOWCOLUMN_READ_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_AUTOSYNCSPECIALFIELDSTOKEYWORDS, SpecialFieldsUtils.PREF_AUTOSYNCSPECIALFIELDSTOKEYWORDS_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_SERIALIZESPECIALFIELDS, SpecialFieldsUtils.PREF_SERIALIZESPECIALFIELDS_DEFAULT); defaults.put(USE_OWNER, Boolean.FALSE); defaults.put(OVERWRITE_OWNER, Boolean.FALSE); defaults.put(ALLOW_TABLE_EDITING, Boolean.FALSE); defaults.put(DIALOG_WARNING_FOR_DUPLICATE_KEY, Boolean.TRUE); defaults.put(DIALOG_WARNING_FOR_EMPTY_KEY, Boolean.TRUE); defaults.put(DISPLAY_KEY_WARNING_DIALOG_AT_STARTUP, Boolean.TRUE); defaults.put(AVOID_OVERWRITING_KEY, Boolean.FALSE); defaults.put(WARN_BEFORE_OVERWRITING_KEY, Boolean.TRUE); defaults.put(CONFIRM_DELETE, Boolean.TRUE); defaults.put(GRAY_OUT_NON_HITS, Boolean.TRUE); defaults.put(SEARCH_MODE_FLOAT, Boolean.FALSE); defaults.put(DEFAULT_LABEL_PATTERN, "[authors3][year]"); defaults.put(PREVIEW_ENABLED, Boolean.TRUE); defaults.put(ACTIVE_PREVIEW, 0); defaults.put(PREVIEW_0, "<font face=\"arial\">" + "<b><i>\\bibtextype</i><a name=\"\\bibtexkey\">\\begin{bibtexkey} (\\bibtexkey)</a>" + "\\end{bibtexkey}</b><br>__NEWLINE__" + "\\begin{author} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\author}<BR>\\end{author}__NEWLINE__" + "\\begin{editor} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\editor} " + "<i>(\\format[IfPlural(Eds.,Ed.)]{\\editor})</i><BR>\\end{editor}__NEWLINE__" + "\\begin{title} \\format[HTMLChars]{\\title} \\end{title}<BR>__NEWLINE__" + "\\begin{chapter} \\format[HTMLChars]{\\chapter}<BR>\\end{chapter}__NEWLINE__" + "\\begin{journal} <em>\\format[HTMLChars]{\\journal}, </em>\\end{journal}__NEWLINE__" // Include the booktitle field for @inproceedings, @proceedings, etc. + "\\begin{booktitle} <em>\\format[HTMLChars]{\\booktitle}, </em>\\end{booktitle}__NEWLINE__" + "\\begin{school} <em>\\format[HTMLChars]{\\school}, </em>\\end{school}__NEWLINE__" + "\\begin{institution} <em>\\format[HTMLChars]{\\institution}, </em>\\end{institution}__NEWLINE__" + "\\begin{publisher} <em>\\format[HTMLChars]{\\publisher}, </em>\\end{publisher}__NEWLINE__" + "\\begin{year}<b>\\year</b>\\end{year}\\begin{volume}<i>, \\volume</i>\\end{volume}" + "\\begin{pages}, \\format[FormatPagesForHTML]{\\pages} \\end{pages}__NEWLINE__" + "\\begin{abstract}<BR><BR><b>Abstract: </b> \\format[HTMLChars]{\\abstract} \\end{abstract}__NEWLINE__" + "\\begin{review}<BR><BR><b>Review: </b> \\format[HTMLChars]{\\review} \\end{review}" + "</dd>__NEWLINE__<p></p></font>"); defaults.put(PREVIEW_1, "<font face=\"arial\">" + "<b><i>\\bibtextype</i><a name=\"\\bibtexkey\">\\begin{bibtexkey} (\\bibtexkey)</a>" + "\\end{bibtexkey}</b><br>__NEWLINE__" + "\\begin{author} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\author}<BR>\\end{author}__NEWLINE__" + "\\begin{editor} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\editor} " + "<i>(\\format[IfPlural(Eds.,Ed.)]{\\editor})</i><BR>\\end{editor}__NEWLINE__" + "\\begin{title} \\format[HTMLChars]{\\title} \\end{title}<BR>__NEWLINE__" + "\\begin{chapter} \\format[HTMLChars]{\\chapter}<BR>\\end{chapter}__NEWLINE__" + "\\begin{journal} <em>\\format[HTMLChars]{\\journal}, </em>\\end{journal}__NEWLINE__" // Include the booktitle field for @inproceedings, @proceedings, etc. + "\\begin{booktitle} <em>\\format[HTMLChars]{\\booktitle}, </em>\\end{booktitle}__NEWLINE__" + "\\begin{school} <em>\\format[HTMLChars]{\\school}, </em>\\end{school}__NEWLINE__" + "\\begin{institution} <em>\\format[HTMLChars]{\\institution}, </em>\\end{institution}__NEWLINE__" + "\\begin{publisher} <em>\\format[HTMLChars]{\\publisher}, </em>\\end{publisher}__NEWLINE__" + "\\begin{year}<b>\\year</b>\\end{year}\\begin{volume}<i>, \\volume</i>\\end{volume}" + "\\begin{pages}, \\format[FormatPagesForHTML]{\\pages} \\end{pages}" + "</dd>__NEWLINE__<p></p></font>"); // TODO: Currently not possible to edit this setting: defaults.put(PREVIEW_PRINT_BUTTON, Boolean.FALSE); defaults.put(AUTO_DOUBLE_BRACES, Boolean.FALSE); defaults.put(DO_NOT_RESOLVE_STRINGS_FOR, "url"); defaults.put(RESOLVE_STRINGS_ALL_FIELDS, Boolean.FALSE); defaults.put(PUT_BRACES_AROUND_CAPITALS, "");//"title;journal;booktitle;review;abstract"); defaults.put(NON_WRAPPABLE_FIELDS, "pdf;ps;url;doi;file"); defaults.put(GENERATE_KEYS_AFTER_INSPECTION, Boolean.TRUE); defaults.put(MARK_IMPORTED_ENTRIES, Boolean.TRUE); defaults.put(UNMARK_ALL_ENTRIES_BEFORE_IMPORTING, Boolean.TRUE); defaults.put(WARN_ABOUT_DUPLICATES_IN_INSPECTION, Boolean.TRUE); defaults.put(USE_TIME_STAMP, Boolean.FALSE); defaults.put(OVERWRITE_TIME_STAMP, Boolean.FALSE); defaults.put(TIME_STAMP_FORMAT, "yyyy-MM-dd"); defaults.put(TIME_STAMP_FIELD, BibtexFields.TIMESTAMP); defaults.put(UPDATE_TIMESTAMP, Boolean.FALSE); defaults.put(GENERATE_KEYS_BEFORE_SAVING, Boolean.FALSE); defaults.put(RemotePreferences.USE_REMOTE_SERVER, Boolean.TRUE); defaults.put(RemotePreferences.REMOTE_SERVER_PORT, 6050); defaults.put(PERSONAL_JOURNAL_LIST, null); defaults.put(EXTERNAL_JOURNAL_LISTS, null); defaults.put(CITE_COMMAND, "\\cite"); // obsoleted by the app-specific ones (not any more?) defaults.put(FLOAT_MARKED_ENTRIES, Boolean.TRUE); defaults.put(LAST_USED_EXPORT, null); defaults.put(SIDE_PANE_WIDTH, -1); defaults.put(IMPORT_INSPECTION_DIALOG_WIDTH, 650); defaults.put(IMPORT_INSPECTION_DIALOG_HEIGHT, 650); defaults.put(SEARCH_DIALOG_WIDTH, 650); defaults.put(SEARCH_DIALOG_HEIGHT, 500); defaults.put(SHOW_FILE_LINKS_UPGRADE_WARNING, Boolean.TRUE); defaults.put(AUTOLINK_EXACT_KEY_ONLY, Boolean.FALSE); defaults.put(NUMERIC_FIELDS, "mittnum;author"); defaults.put(RUN_AUTOMATIC_FILE_SEARCH, Boolean.FALSE); defaults.put(USE_LOCK_FILES, Boolean.TRUE); defaults.put(AUTO_SAVE, Boolean.TRUE); defaults.put(AUTO_SAVE_INTERVAL, 5); defaults.put(PROMPT_BEFORE_USING_AUTOSAVE, Boolean.TRUE); defaults.put(ENFORCE_LEGAL_BIBTEX_KEY, Boolean.TRUE); defaults.put(BIBLATEX_MODE, Boolean.FALSE); // Curly brackets ({}) are the default delimiters, not quotes (") as these cause trouble when they appear within the field value: // Currently, JabRef does not escape them defaults.put(VALUE_DELIMITERS2, 1); defaults.put(KEY_GEN_FIRST_LETTER_A, Boolean.TRUE); defaults.put(KEY_GEN_ALWAYS_ADD_LETTER, Boolean.FALSE); // TODO l10n issue defaults.put(EMAIL_SUBJECT, "References"); defaults.put(OPEN_FOLDERS_OF_ATTACHED_FILES, Boolean.FALSE); defaults.put(ALLOW_FILE_AUTO_OPEN_BROWSE, Boolean.TRUE); defaults.put(WEB_SEARCH_VISIBLE, Boolean.FALSE); defaults.put(SELECTED_FETCHER_INDEX, 0); defaults.put(BIB_LOC_AS_PRIMARY_DIR, Boolean.FALSE); defaults.put(DB_CONNECT_SERVER_TYPE, "MySQL"); defaults.put(DB_CONNECT_HOSTNAME, "localhost"); defaults.put(DB_CONNECT_DATABASE, "jabref"); defaults.put(DB_CONNECT_USERNAME, "root"); CleanUpAction.putDefaults(defaults); // defaults for DroppedFileHandler UI defaults.put(DroppedFileHandler.DFH_LEAVE, Boolean.FALSE); defaults.put(DroppedFileHandler.DFH_COPY, Boolean.TRUE); defaults.put(DroppedFileHandler.DFH_MOVE, Boolean.FALSE); defaults.put(DroppedFileHandler.DFH_RENAME, Boolean.FALSE); //defaults.put("lastAutodetectedImport", ""); //defaults.put("autoRemoveExactDuplicates", Boolean.FALSE); //defaults.put("confirmAutoRemoveExactDuplicates", Boolean.TRUE); //defaults.put("tempDir", System.getProperty("java.io.tmpdir")); LOGGER.debug("Temporary directory: " + System.getProperty("java.io.tempdir")); //defaults.put("keyPattern", new LabelPattern(KEY_PATTERN)); defaults.put(ImportSettingsTab.PREF_IMPORT_ALWAYSUSE, Boolean.FALSE); defaults.put(ImportSettingsTab.PREF_IMPORT_DEFAULT_PDF_IMPORT_STYLE, ImportSettingsTab.DEFAULT_STYLE); // use BibTeX key appended with filename as default pattern defaults.put(ImportSettingsTab.PREF_IMPORT_FILENAMEPATTERN, ImportSettingsTab.DEFAULT_FILENAMEPATTERNS[1]); customExports = new CustomExportList(new ExportComparator()); customImports = new CustomImportList(this); //defaults.put("oooWarning", Boolean.TRUE); updateSpecialFieldHandling(); WRAPPED_USERNAME = '[' + get(DEFAULT_OWNER) + ']'; MARKING_WITH_NUMBER_PATTERN = "\\[" + get(DEFAULT_OWNER).replaceAll("\\\\", "\\\\\\\\") + ":(\\d+)\\]"; String defaultExpression = "**/.*[bibtexkey].*\\\\.[extension]"; defaults.put(DEFAULT_REG_EXP_SEARCH_EXPRESSION_KEY, defaultExpression); defaults.put(REG_EXP_SEARCH_EXPRESSION_KEY, defaultExpression); defaults.put(AUTOLINK_USE_REG_EXP_SEARCH_KEY, Boolean.FALSE); defaults.put(USE_IEEE_ABRV, Boolean.FALSE); defaults.put(USE_CONVERT_TO_EQUATION, Boolean.FALSE); defaults.put(USE_CASE_KEEPER_ON_SEARCH, Boolean.TRUE); defaults.put(USE_UNIT_FORMATTER_ON_SEARCH, Boolean.TRUE); defaults.put(USER_FILE_DIR, Globals.FILE_FIELD + Globals.DIR_SUFFIX); try { defaults.put(USER_FILE_DIR_IND_LEGACY, Globals.FILE_FIELD + Globals.DIR_SUFFIX + '-' + get(DEFAULT_OWNER) + '@' + InetAddress.getLocalHost().getHostName()); // Legacy setting name - was a bug: @ not allowed inside BibTeX comment text. Retained for backward comp. defaults.put(USER_FILE_DIR_INDIVIDUAL, Globals.FILE_FIELD + Globals.DIR_SUFFIX + '-' + get(DEFAULT_OWNER) + '-' + InetAddress.getLocalHost().getHostName()); // Valid setting name } catch (UnknownHostException ex) { LOGGER.info("Hostname not found.", ex); defaults.put(USER_FILE_DIR_IND_LEGACY, Globals.FILE_FIELD + Globals.DIR_SUFFIX + '-' + get(DEFAULT_OWNER)); defaults.put(USER_FILE_DIR_INDIVIDUAL, Globals.FILE_FIELD + Globals.DIR_SUFFIX + '-' + get(DEFAULT_OWNER)); } } public void setLanguageDependentDefaultValues() { // Entry editor tab 0: defaults.put(CUSTOM_TAB_NAME + "_def0", Localization.lang("General")); defaults.put(CUSTOM_TAB_FIELDS + "_def0", "crossref;keywords;file;doi;url;" + "comment;owner;timestamp"); // Entry editor tab 1: defaults.put(CUSTOM_TAB_FIELDS + "_def1", "abstract"); defaults.put(CUSTOM_TAB_NAME + "_def1", Localization.lang("Abstract")); // Entry editor tab 2: Review Field - used for research comments, etc. defaults.put(CUSTOM_TAB_FIELDS + "_def2", "review"); defaults.put(CUSTOM_TAB_NAME + "_def2", Localization.lang("Review")); defaults.put(EMAIL_SUBJECT, Localization.lang("References")); } public boolean putBracesAroundCapitals(String fieldName) { return putBracesAroundCapitalsFields.contains(fieldName); } public void updateSpecialFieldHandling() { putBracesAroundCapitalsFields.clear(); String fieldString = get(PUT_BRACES_AROUND_CAPITALS); if (!fieldString.isEmpty()) { String[] fields = fieldString.split(";"); for (String field : fields) { putBracesAroundCapitalsFields.add(field.trim()); } } nonWrappableFields.clear(); fieldString = get(NON_WRAPPABLE_FIELDS); if (!fieldString.isEmpty()) { String[] fields = fieldString.split(";"); for (String field : fields) { nonWrappableFields.add(field.trim()); } } } public char getValueDelimiters(int index) { return getValueDelimiters()[index]; } private char[] getValueDelimiters() { return JabRefPreferences.VALUE_DELIMITERS[getInt(VALUE_DELIMITERS2)]; } /** * Check whether a key is set (differently from null). * * @param key The key to check. * @return true if the key is set, false otherwise. */ public boolean hasKey(String key) { return prefs.get(key, null) != null; } public String get(String key) { return prefs.get(key, (String) defaults.get(key)); } public String get(String key, String def) { return prefs.get(key, def); } public boolean getBoolean(String key) { return prefs.getBoolean(key, getBooleanDefault(key)); } public boolean getBoolean(String key, boolean def) { return prefs.getBoolean(key, def); } private boolean getBooleanDefault(String key) { return (Boolean) defaults.get(key); } public double getDouble(String key) { return prefs.getDouble(key, getDoubleDefault(key)); } private double getDoubleDefault(String key) { return (Double) defaults.get(key); } public int getInt(String key) { return prefs.getInt(key, getIntDefault(key)); } public int getIntDefault(String key) { return (Integer) defaults.get(key); } public byte[] getByteArray(String key) { return prefs.getByteArray(key, getByteArrayDefault(key)); } private byte[] getByteArrayDefault(String key) { return (byte[]) defaults.get(key); } public void put(String key, String value) { prefs.put(key, value); } public void putBoolean(String key, boolean value) { prefs.putBoolean(key, value); } public void putDouble(String key, double value) { prefs.putDouble(key, value); } public void putInt(String key, int value) { prefs.putInt(key, value); } public void putByteArray(String key, byte[] value) { prefs.putByteArray(key, value); } public void remove(String key) { prefs.remove(key); } /** * Puts a list of strings into the Preferences, by linking its elements with ';' into a single string. Escape * characters make the process transparent even if strings contain ';'. */ public void putStringList(String key, List<String> value) { if ((value == null)) { remove(key); return; } if (value.isEmpty()) { put(key, ""); } else { StringBuilder linked = new StringBuilder(); for (int i = 0; i < (value.size() - 1); i++) { linked.append(makeEscape(value.get(i))); linked.append(';'); } linked.append(makeEscape(value.get(value.size() - 1))); put(key, linked.toString()); } } /** * Returns a List of Strings containing the chosen columns. */ public List<String> getStringList(String key) { String names = get(key); if (names == null) { return new ArrayList<>(); } StringReader rd = new StringReader(names); List<String> res = new ArrayList<>(); String rs; try { while ((rs = getNextUnit(rd)) != null) { res.add(rs); } } catch (IOException ignored) { // Ignored } return res; } /** * Looks up a color definition in preferences, and returns the Color object. * * @param key The key for this setting. * @return The color corresponding to the setting. */ public Color getColor(String key) { String value = get(key); int[] rgb = getRgb(value); return new Color(rgb[0], rgb[1], rgb[2]); } public Color getDefaultColor(String key) { String value = (String) defaults.get(key); int[] rgb = getRgb(value); return new Color(rgb[0], rgb[1], rgb[2]); } /** * Set the default value for a key. This is useful for plugins that need to add default values for the prefs keys * they use. * * @param key The preferences key. * @param value The default value. */ public void putDefaultValue(String key, Object value) { defaults.put(key, value); } /** * Stores a color in preferences. * * @param key The key for this setting. * @param color The Color to store. */ public void putColor(String key, Color color) { String rgb = String.valueOf(color.getRed()) + ':' + color.getGreen() + ':' + color.getBlue(); put(key, rgb); } /** * Looks up a color definition in preferences, and returns an array containing the RGB values. * * @param value The key for this setting. * @return The RGB values corresponding to this color setting. */ private static int[] getRgb(String value) { int[] values = new int[3]; if ((value != null) && !value.isEmpty()) { String[] elements = value.split(":"); values[0] = Integer.parseInt(elements[0]); values[1] = Integer.parseInt(elements[1]); values[2] = Integer.parseInt(elements[2]); } else { values[0] = 0; values[1] = 0; values[2] = 0; } return values; } /** * Clear all preferences. * * @throws BackingStoreException */ public void clear() throws BackingStoreException { prefs.clear(); } public void clear(String key) { prefs.remove(key); } /** * Calling this method will write all preferences into the preference store. */ public void flush() { if (getBoolean(MEMORY_STICK_MODE)) { try { exportPreferences("jabref.xml"); } catch (JabRefException e) { LOGGER.warn("Could not export preferences for memory stick mode: " + e.getMessage(), e); } } try { prefs.flush(); } catch (BackingStoreException ex) { LOGGER.warn("Can not communicate with backing store", ex); } } /** * Fetches key patterns from preferences. * The implementation doesn't cache the results * * @return LabelPattern containing all keys. Returned LabelPattern has no parent */ public GlobalLabelPattern getKeyPattern() { keyPattern = new GlobalLabelPattern(); Preferences pre = Preferences.userNodeForPackage(GlobalLabelPattern.class); try { String[] keys = pre.keys(); if (keys.length > 0) { for (String key : keys) { keyPattern.addLabelPattern(key, pre.get(key, null)); } } } catch (BackingStoreException ex) { LOGGER.info("BackingStoreException in JabRefPreferences.getKeyPattern", ex); } return keyPattern; } /** * Adds the given key pattern to the preferences * * @param pattern the pattern to store */ public void putKeyPattern(GlobalLabelPattern pattern) { keyPattern = pattern; // Store overridden definitions to Preferences. Preferences pre = Preferences.userNodeForPackage(GlobalLabelPattern.class); try { pre.clear(); // We remove all old entries. } catch (BackingStoreException ex) { LOGGER.info("BackingStoreException in JabRefPreferences.putKeyPattern", ex); } Set<String> allKeys = pattern.getAllKeys(); for (String key : allKeys) { if (!pattern.isDefaultValue(key)) { // no default value // the first entry in the array is the full pattern // see net.sf.jabref.logic.labelPattern.LabelPatternUtil.split(String) pre.put(key, pattern.getValue(key).get(0)); } } } private static String getNextUnit(Reader data) throws IOException { // character last read // -1 if end of stream // initialization necessary, because of Java compiler int c = -1; // last character was escape symbol boolean escape = false; // true if a ";" is found boolean done = false; StringBuilder res = new StringBuilder(); while (!done && ((c = data.read()) != -1)) { if (c == '\\') { if (escape) { escape = false; res.append('\\'); } else { escape = true; } } else { if (c == ';') { if (escape) { res.append(';'); } else { done = true; } } else { res.append((char) c); } escape = false; } } if (res.length() > 0) { return res.toString(); } else if (c == -1) { // end of stream return null; } else { return ""; } } private static String makeEscape(String s) { StringBuilder sb = new StringBuilder(); int c; for (int i = 0; i < s.length(); i++) { c = s.charAt(i); if ((c == '\\') || (c == ';')) { sb.append('\\'); } sb.append((char) c); } return sb.toString(); } /** * Stores all information about the entry type in preferences, with the tag given by number. */ public void storeCustomEntryType(CustomEntryType tp, int number) { String nr = String.valueOf(number); put(JabRefPreferences.CUSTOM_TYPE_NAME + nr, tp.getName()); put(JabRefPreferences.CUSTOM_TYPE_REQ + nr, tp.getRequiredFieldsString()); List<String> optionalFields = tp.getOptionalFields(); putStringList(JabRefPreferences.CUSTOM_TYPE_OPT + nr, optionalFields); List<String> primaryOptionalFields = tp.getPrimaryOptionalFields(); putStringList(JabRefPreferences.CUSTOM_TYPE_PRIOPT + nr, primaryOptionalFields); } /** * Retrieves all information about the entry type in preferences, with the tag given by number. */ public CustomEntryType getCustomEntryType(int number) { String nr = String.valueOf(number); String name = get(JabRefPreferences.CUSTOM_TYPE_NAME + nr); if (name == null) { return null; } List<String> req = getStringList(JabRefPreferences.CUSTOM_TYPE_REQ + nr); List<String> opt = getStringList(JabRefPreferences.CUSTOM_TYPE_OPT + nr); List<String> priOpt = getStringList(JabRefPreferences.CUSTOM_TYPE_PRIOPT + nr); if (priOpt.isEmpty()) { return new CustomEntryType(EntryUtil.capitalizeFirst(name), req, opt); } List<String> secondary = EntryUtil.getRemainder(opt, priOpt); return new CustomEntryType(EntryUtil.capitalizeFirst(name), req, priOpt, secondary); } /** * Removes all information about custom entry types with tags of * * @param number or higher. */ public void purgeCustomEntryTypes(int number) { purgeSeries(JabRefPreferences.CUSTOM_TYPE_NAME, number); purgeSeries(JabRefPreferences.CUSTOM_TYPE_REQ, number); purgeSeries(JabRefPreferences.CUSTOM_TYPE_OPT, number); purgeSeries(JabRefPreferences.CUSTOM_TYPE_PRIOPT, number); } /** * Removes all entries keyed by prefix+number, where number is equal to or higher than the given number. * * @param number or higher. */ public void purgeSeries(String prefix, int number) { while (get(prefix + number) != null) { remove(prefix + number); number++; } } public EntryEditorTabList getEntryEditorTabList() { if (tabList == null) { updateEntryEditorTabList(); } return tabList; } public void updateEntryEditorTabList() { tabList = new EntryEditorTabList(); } /** * Exports Preferences to an XML file. * * @param filename String File to export to */ public void exportPreferences(String filename) throws JabRefException { File f = new File(filename); try (OutputStream os = new FileOutputStream(f)) { prefs.exportSubtree(os); } catch (BackingStoreException | IOException ex) { throw new JabRefException("Could not export preferences", Localization.lang("Could not export preferences"), ex); } } /** * Imports Preferences from an XML file. * * @param filename String File to import from * @throws JabRefException thrown if importing the preferences failed due to an InvalidPreferencesFormatException * or an IOException */ public void importPreferences(String filename) throws JabRefException { File f = new File(filename); try (InputStream is = new FileInputStream(f)) { Preferences.importPreferences(is); } catch (InvalidPreferencesFormatException | IOException ex) { throw new JabRefException("Could not import preferences", Localization.lang("Could not import preferences"), ex); } } /** * Determines whether the given field should be written without any sort of wrapping. * * @param fieldName The field name. * @return true if the field should not be wrapped. */ public boolean isNonWrappableField(String fieldName) { return nonWrappableFields.contains(fieldName); } /** * ONLY FOR TESTING! * * Do not use in production code. Otherwise the singleton pattern is broken and preferences might get lost. * * @param owPrefs */ public void overwritePreferences(JabRefPreferences owPrefs) { singleton = owPrefs; } public Charset getDefaultEncoding() { return Charset.forName(get(JabRefPreferences.DEFAULT_ENCODING)); } public void setDefaultEncoding(Charset encoding) { put(JabRefPreferences.DEFAULT_ENCODING, encoding.name()); } }
package org.almibe.codearea; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.ReadOnlyBooleanWrapper; import javafx.beans.property.StringProperty; import javafx.concurrent.Worker; import javafx.scene.Parent; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import netscape.javascript.JSObject; public class AceCodeArea implements CodeArea { private final WebView webView; private final WebEngine webEngine; private final ReadOnlyBooleanWrapper isInitializedProperty = new ReadOnlyBooleanWrapper(false); public AceCodeArea() { webView = new WebView(); webEngine = webView.getEngine(); } @Override public void init() { //final String html = AceCodeArea.class.getResource("html/editor.html").toExternalForm(); //final String html = AceCodeArea.class.getResource("html/codemirror-4.8/mode/groovy/index.html").toExternalForm(); final String html = AceCodeArea.class.getResource("html/codemirror-4.8/demo/vim.html").toExternalForm(); webEngine.load(html); webEngine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> { if(newValue == Worker.State.SUCCEEDED) { isInitializedProperty.setValue(true); } }); } @Override public ReadOnlyBooleanProperty isInitializedProperty() { return isInitializedProperty.getReadOnlyProperty(); } @Override public Parent getWidget() { return this.webView; } public JSObject fetchEditor() { Object editor = webEngine.executeScript("editor;"); if(editor instanceof JSObject) { return (JSObject) editor; } throw new IllegalStateException("CodeArea not loaded."); } public JSObject fetchSession() { Object temp = webEngine.executeScript("editor.session;"); if(temp instanceof JSObject) { return (JSObject) temp; } throw new IllegalStateException("CodeArea not loaded."); } public void setValue(String value) { fetchEditor().call("setValue", value); } public String getValue() { return (String) fetchEditor().call("getValue"); //TODO add check } public void setMode(String mode) { fetchSession().call("setMode", mode); } public String getMode() { return (String) fetchSession().eval("this.getMode().$id;"); } @Override public StringProperty contentProperty() { throw new UnsupportedOperationException("contentProperty is not implemented"); } @Override public BooleanProperty readOnlyProperty() { throw new UnsupportedOperationException("readOnly is not implemented"); } @Override public StringProperty modeProperty() { throw new UnsupportedOperationException("modeProperty is not implemented"); } @Override public StringProperty themeProperty() { throw new UnsupportedOperationException("themeProperty is not implemented"); } }
package org.animotron.manipulator; import org.animotron.exception.AnimoException; import org.animotron.io.PipedOutput; import org.animotron.statement.operator.AN; import org.animotron.statement.operator.Utils; import org.animotron.statement.relation.USE; import org.animotron.utils.MessageDigester; import org.jetlang.channels.Channel; import org.jetlang.channels.MemoryChannel; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.traversal.Evaluation; import org.neo4j.graphdb.traversal.Evaluator; import org.neo4j.graphdb.traversal.TraversalDescription; import org.neo4j.kernel.Traversal; import org.neo4j.kernel.Uniqueness; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.security.MessageDigest; import java.util.Iterator; import java.util.concurrent.CountDownLatch; import static org.animotron.graph.RelationshipTypes.REF; import static org.animotron.graph.RelationshipTypes.RESULT; import static org.neo4j.graphdb.Direction.OUTGOING; import static org.neo4j.graphdb.traversal.Evaluation.*; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public class PFlow { private final Manipulator m; private Channel<QCAVector> aChannel = null; private Channel<PFlow> qChannel = null; private Channel<Throwable> sChannel = null; protected final PFlow parent; private Relationship op = null; private Node opNode = null; //private Vector<QCAVector> path = new Vector<QCAVector>(); private QCAVector path; public PFlow(Manipulator m) { parent = null; this.m = m; } public PFlow(Manipulator m, Relationship op) { parent = null; this.m = m; this.op = op; path = new QCAVector(op); } public PFlow(PFlow parent) { this.parent = parent; this.m = parent.m; //XXX: maybe, clone faster? path = parent.path; } @Deprecated //use one with vector public PFlow(PFlow parent, Relationship op) throws AnimoException { // System.out.print("new PFlow "); // System.out.println("this = "+Utils.shortID(this)+" parent = "+Utils.shortID(parent)); // System.out.print(" "+(new IOException()).getStackTrace()[1]); // System.out.println(" "+op); this.parent = parent; this.m = parent.m; //XXX: maybe, clone faster? path = parent.path; path = path.question(op); cyclingDetection(op); this.op = op; } public PFlow(PFlow parent, Node opNode) { System.out.println("WRONG WRONG WRONG WRONG WRONG WRONG WRONG WRONG WRONG WRONG"); this.parent = parent; this.m = parent.m; //XXX: maybe, clone faster? path = parent.path; this.opNode = opNode; } public PFlow(PFlow parent, QCAVector vector) { this.parent = parent; this.m = parent.m; path = vector; //addContextPoint(vector); this.op = vector.getUnrelaxedClosest(); } public Channel<PFlow> questionChannel() { if (qChannel == null) qChannel = new MemoryChannel<PFlow>(); return qChannel; } public Channel<QCAVector> answerChannel() { if (aChannel == null) aChannel = new MemoryChannel<QCAVector>(); return aChannel; } public Channel<Throwable> stopChannel() { if (sChannel == null) sChannel = new MemoryChannel<Throwable>(); return sChannel; } protected void cyclingDetection() throws AnimoException { cyclingDetection(getOP()); } private void cyclingDetection(Relationship op) throws AnimoException { int deep = 0; int count = 0; //for (QCAVector v : path) { if (deep > 0 && path.haveRelationship(op)) { if (count > 2) throw new AnimoException(op, "cycling detected "+path); else count++; } deep++; } public PFlow getParent() { return parent; } public Relationship getOP() { return op; } //XXX: still required? public Relationship getStartOP() { return path.getQuestion(); } //XXX: still required? public Node getStartNode() { return path.getQuestion().getEndNode(); } public Node getOPNode() { if (opNode != null) return opNode; return op.getEndNode(); } protected void setOPNode(Node opNode) { this.opNode = opNode; this.op = null; } public void sendAnswer(QCAVector r) { if (parent == null) { System.out.println("WORNG - no parent"); throw new IllegalArgumentException("NULL parent @pflow"); } else { parent.answerChannel().publish(r); } } public void sendAnswer(Relationship answer) { sendAnswer(answer, RESULT, getPathHash()); } public void sendAnswer(Relationship answer, RelationshipType rType, byte[] hash) { if (parent == null) { System.out.println("WORNG - no parent"); throw new IllegalArgumentException("NULL parent @pflow"); } else { //System.out.println("send answer to "+parent.answer+" (parent = "+parent+")"); Relationship createdAnswer = Utils.createResult( this, op.getEndNode(), answer, rType, hash ); parent.answerChannel().publish(path.answered(createdAnswer)); } } public void sendAnswer(QCAVector answerVector, RelationshipType rType) { if (parent == null) { System.out.println("WORNG - no parent"); throw new IllegalArgumentException("NULL parent @pflow"); } else { //System.out.println("send answer to "+parent.answer+" (parent = "+parent+")"); Relationship answer = Utils.createResult(this, answerVector.getContext(), op.getEndNode(), answerVector.getAnswer(), rType); parent.answerChannel().publish(new QCAVector(op, answer, answerVector.getContext(), answerVector.getPrecedingSibling())); } } public void sendAnswer(Relationship answer, QCAVector context) { Relationship createdAnswer = Utils.createResult(this, op.getEndNode(), answer, RESULT); sendAnswer(op, context, createdAnswer); } public void sendAnswer(Relationship question, QCAVector context, Relationship answer) { if (parent == null) { System.out.println("WORNG - no parent"); throw new IllegalArgumentException("NULL parent @pflow"); } else { //System.out.println("send answer to "+parent.answer+" (parent = "+parent+")"); parent.answerChannel().publish(new QCAVector(question, context, answer)); } } public void sendException(Throwable t) { t.printStackTrace(); AnimoException ae; if (t instanceof AnimoException) { ae = (AnimoException) t; ae.addToStack(op); } else { ae = new AnimoException(op, t); } parent.stopChannel().publish(ae); done(); } public void done() { if (parent == null) answerChannel().publish(null); else parent.answerChannel().publish(null); } protected CountDownLatch waitBeforeClosePipe = null; public void waitBeforeClosePipe(int count) { //System.out.println("waitBeforeClosePipe "+count+" "+this); waitBeforeClosePipe = new CountDownLatch(count); // if (parent == null) answer.publish(null); // else parent.answer.publish(null); } public void countDown() { if (waitBeforeClosePipe == null) waitBeforeClosePipe(1); waitBeforeClosePipe.countDown(); //System.out.println("countDown "+waitBeforeClosePipe.getCount()+" "+this); } public void countDown(PipedOutput<?> out) { if (waitBeforeClosePipe == null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } return; } waitBeforeClosePipe.countDown(); if (waitBeforeClosePipe.getCount() == 0) try { out.close(); } catch (IOException e) { e.printStackTrace(); } //System.out.println("countDown "+waitBeforeClosePipe.getCount()+" "+this); } public void await() { if (waitBeforeClosePipe == null) return; try { waitBeforeClosePipe.await(); } catch (InterruptedException e) { sendException(e); e.printStackTrace(); } } public Manipulator getManipulator() { return m; } public QCAVector getPFlowPath() { return path; } public Path getFlowPath() { // System.out.println("Path:"); // for (Relationship r : path) { // System.out.println(r); // int i = 0; // for (Path path : td_flow.traverse(getOPNode())) { // System.out.println(" path = "+path); //System.out.println("OPNode = "+getOPNode()); Path first = null; for (Path path : get_td_flow().traverse(getOPNode())) { if (first == null) { first = path; } boolean haveUse = false; for (Relationship r : path.relationships()) { if (r.isType(USE._)) { haveUse = true; break; } } if (!haveUse) return path; } return first; // Iterator<Path> it = td_flow.traverse(getOPNode()).iterator(); // if (it.hasNext()) // return it.next(); // else { // //what looks wrong! // return null; } public Iterable<Relationship> stack() { return new PFlowStack(); } private class PFlowStack implements Iterator<Relationship>, Iterable<Relationship> { private Iterator<Relationship> it = getFlowPath().relationships().iterator(); private Relationship pos = step(); private Relationship step() { while (it.hasNext()) { Relationship r = it.next(); if (r.isType(AN._)){ return r; } } return null; } @Override public boolean hasNext() { return pos != null; } @Override public Relationship next() { Relationship res = pos; pos = step(); return res; } @Override public void remove() { // TODO Auto-generated method stub } @Override public Iterator<Relationship> iterator() { return this; } } public Iterable<Relationship> getStackContext(Relationship r, boolean goDown) { // return td_context.traverse(node).relationships(); Node node = r.getEndNode(); if (goDown && r.isType(AN._)) { node = node.getSingleRelationship(REF, OUTGOING).getEndNode(); } return node.getRelationships(AN._, OUTGOING); } // public QCAVector addContextPoint(QCAVector vector) { // boolean debug = false; // if (debug) System.out.print("adding "+this+" "+vector); //// System.out.println(new IOException().getStackTrace()[1]); // if (path.isEmpty()) { // if (debug) System.out.println(" (added)"); // path.insertElementAt(vector, 0); // return vector; // } else if (!path.isEmpty()) { // QCAVector v = path.get(0); // if (v.merged(vector)) { // //path.set(0, vector); // if (debug) System.out.println(" (merge)"); // return vector; // } else { // path.insertElementAt(vector, 0); // if (debug) System.out.println(" (added)"); // return vector; // if (debug) System.out.println(" (ignored)"); // return null; // public QCAVector addContextPoint(Relationship r) { // return addContextPoint(new QCAVector(r)); // public void popContextPoint(QCAVector vector) { // //System.out.println("pop "+this+" "+path); // if (vector == null) return; // if (path.size() == 0) { // System.out.println("WARNING - path is empty"); // return; //// if (path.get(0) == vector) //// path.remove(0); // path.set(0, vector); public byte[] getPathHash() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); if (path == null) return new byte[0]; try { path.collectHash(dos); } catch (IOException e) { } MessageDigest md = MessageDigester.md(); md.update(bos.toByteArray()); return md.digest(); } public byte[] getOpHash() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); try { dos.writeLong(getOP().getId()); } catch (IOException e) { } MessageDigest md = MessageDigester.md(); md.update(bos.toByteArray()); return md.digest(); } public Relationship getLastContext() { boolean debug = false; if (debug) System.out.print("PFlow get last context "); if (debug) System.out.println(path); return path.getQuestion(); } private TraversalDescription get_td_flow() { return Traversal.description().depthFirst(). uniqueness(Uniqueness.RELATIONSHIP_PATH). evaluator(new Evaluator(){ @Override public Evaluation evaluate(Path path) { //System.out.println(" "+path); if (path.length() > 0) { Relationship r = path.lastRelationship(); if (r.getStartNode().equals(path.endNode())) { if (r.equals(getStartOP())) { return INCLUDE_AND_PRUNE; } return EXCLUDE_AND_CONTINUE; //Allow ...<-IS->... } if (path.length() > 1 && r.isType(AN._)) { return EXCLUDE_AND_CONTINUE; } return EXCLUDE_AND_PRUNE; } return EXCLUDE_AND_CONTINUE; } }); } public boolean isInStack(Relationship r) { boolean debug = false; if (debug) System.out.println("IN STACK CHECK "+r+" in "+path+" "); //for (QCAVector v : path) { if (path.haveRelationship(r)) { if (debug) System.out.println("FOUND!!!"); return true; } if (debug) System.out.println("NOT FOUND"); return false; } public void debug() { StringBuilder sb = new StringBuilder(); sb.append("DEBUG PFlow "); //sb.append(Utils.shortID(this)); sb.append("\nPath = "); sb.append(path); sb.append("\n"); sb.append("OPs "); ops(sb); System.out.println(sb.toString()); } private void ops(StringBuilder sb) { if (op != null) { sb.append(op); sb.append(" ");} if (parent != null) parent.ops(sb); } public QCAVector getVector() { return path; } }
package org.broad.igv.google; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.log4j.Logger; import org.broad.igv.DirectoryManager; import org.broad.igv.prefs.Constants; import org.broad.igv.prefs.PreferencesManager; import org.broad.igv.util.AmazonUtils; import org.broad.igv.util.FileUtils; import org.broad.igv.util.HttpUtils; import org.broad.igv.util.ParsingUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; // XXX: Both Oauth and JWT classes need a serious refactor/audit. Multi-provider support, concurrency, security, etc...: // WARNING: This class requires a thorough security audit of Oauth/JWT implementations. I would recommend going through: // And potentially refactor/substitute this logic with: public class OAuthUtils { private static Logger log = Logger.getLogger(OAuthUtils.class); public static String findString = null; public static String replaceString = null; private static final String PROPERTIES_URL = "https://s3.amazonaws.com/igv.org.app/desktop_google"; private static OAuthUtils theInstance; static Map<String, OAuthProvider> providers; static OAuthProvider defaultProvider; public static synchronized OAuthUtils getInstance() { if (theInstance == null) { theInstance = new OAuthUtils(); } return theInstance; } public OAuthProvider getProvider(String providerName) { if (providerName != null) { if (!providers.containsKey(providerName)) { throw new RuntimeException("Unknwon oAuth provider name: " + providerName); } return providers.get(providerName); } return defaultProvider; } public OAuthProvider getProvider() { return defaultProvider; } private OAuthUtils() { providers = new HashMap<>(); try { fetchOauthProperties(); } catch (IOException e) { log.error(e); } } public void fetchOauthProperties() throws IOException { // Load a provider config specified in preferences String provisioningURL = PreferencesManager.getPreferences().get(Constants.PROVISIONING_URL); if (provisioningURL != null && provisioningURL.length() > 0) { loadProvisioningURL(provisioningURL); } // Local config takes precendence String oauthConfig = DirectoryManager.getIgvDirectory() + "/oauth-config.json"; if ((new File(oauthConfig)).exists()) { try { log.debug("Loading Oauth properties from: " + oauthConfig); String json = FileUtils.getContents(oauthConfig); parseProviderJson(json, oauthConfig); } catch (IOException e) { log.error(e); } } if (defaultProvider == null) { // IGV default log.debug("$HOME/igv/oauth-config.json not found, reading Java .properties instead from: " + PROPERTIES_URL); String propString = HttpUtils.getInstance().getContentsAsGzippedString(HttpUtils.createURL(PROPERTIES_URL)); JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(propString).getAsJsonObject().get("installed").getAsJsonObject(); defaultProvider = new OAuthProvider(obj); } } public void loadProvisioningURL(String provisioningURL) throws IOException { if (provisioningURL != null && provisioningURL.length() > 0) { InputStream is = ParsingUtils.openInputStream(provisioningURL); String json = ParsingUtils.readContentsFromStream(is); parseProviderJson(json, provisioningURL); } } private void parseProviderJson(String json, String path) throws IOException { JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(json).getAsJsonObject(); OAuthProvider p = new OAuthProvider(obj); // Hack - a move towards multiple providers if (obj.has("auth_provider") && obj.get("auth_provider").getAsString().equals("Amazon")) { providers.put("Amazon", p); AmazonUtils.setCognitoConfig(obj); } else { if (defaultProvider != null) { log.info("Overriding default oAuth provider with " + path); } defaultProvider = p; } } // Set the authorization code from the callback (redirect URI). We are sharing a single redirect URI between // all providers. At the moment his is hacked specifically for Google and Amazon, if its not Google we assume // its Amazon. In the future we'll most likely have to use distinct redirect URIs, which means opening more ports. public void setAuthorizationCode(Map<String, String> params) throws IOException { OAuthProvider provider = null; if (params.containsKey("scope") && params.get("scope").contains("googleapis")) { provider = defaultProvider; } else if (providers.containsKey("Amazon")) { provider = providers.get("Amazon"); } if (provider == null) { provider = defaultProvider; } provider.setAuthorizationCode(params.get("code")); } // jtr -- I don't think this is used. If it is I don't know how to distinguish provider. public void setAccessToken(Map<String, String> params) { OAuthProvider provider = defaultProvider; provider.setAccessToken("token"); } }
package org.commcare.suite.model; import org.commcare.cases.entity.Entity; import org.commcare.cases.entity.NodeEntityFactory; import org.commcare.util.DetailFieldPrintInfo; import org.commcare.util.DetailUtil; import org.commcare.util.GridCoordinate; import org.commcare.util.GridStyle; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.util.ArrayUtilities; import org.javarosa.core.util.OrderedHashtable; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.core.util.externalizable.ExtUtil; import org.javarosa.core.util.externalizable.ExtWrapList; import org.javarosa.core.util.externalizable.ExtWrapMap; import org.javarosa.core.util.externalizable.ExtWrapNullable; import org.javarosa.core.util.externalizable.ExtWrapTagged; import org.javarosa.core.util.externalizable.Externalizable; import org.javarosa.core.util.externalizable.PrototypeFactory; import org.javarosa.model.xform.XPathReference; import org.javarosa.xpath.XPathParseTool; import org.javarosa.xpath.expr.FunctionUtils; import org.javarosa.xpath.expr.XPathExpression; import org.javarosa.xpath.parser.XPathSyntaxException; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Vector; /** * A Detail model defines the structure in which * the details about something should be displayed * to users (generally cases or referrals). * * Detail models maintain a set of Text objects * which provide a template for how details about * objects should be displayed, along with a model * which defines the context of what data should be * obtained to fill in those templates. * * @author ctsims */ public class Detail implements Externalizable { public static final String PRINT_TEMPLATE_PROVIDED_VIA_GLOBAL_SETTING = "provided-globally"; private String id; private TreeReference nodeset; private DisplayUnit title; /** * Optional and only relevant if this detail has child details. In that * case, form may be 'image' or omitted. */ private String titleForm; private Detail[] details; private DetailField[] fields; private Callout callout; private OrderedHashtable<String, String> variables; private OrderedHashtable<String, XPathExpression> variablesCompiled; private Vector<Action> actions; // Force the activity that is showing this detail to show itself in landscape view only private boolean forceLandscapeView; private XPathExpression focusFunction; // region -- These fields are only used if this detail is a case tile // Allows for the possibility of case tiles being displayed in a grid private int numEntitiesToDisplayPerRow; // Indicates that the height of a single cell in the tile's grid layout should be treated as // equal to its width, rather than being computed independently private boolean useUniformUnitsInCaseTile; // A button to print this detail should be provided private boolean printEnabled; private String derivedPrintTemplatePath; // endregion /** * Serialization Only */ public Detail() { } public Detail(String id, DisplayUnit title, String nodeset, Vector<Detail> detailsVector, Vector<DetailField> fieldsVector, OrderedHashtable<String, String> variables, Vector<Action> actions, Callout callout, String fitAcross, String uniformUnitsString, String forceLandscape, String focusFunction, String printPathProvided) { if (detailsVector.size() > 0 && fieldsVector.size() > 0) { throw new IllegalArgumentException("A detail may contain either sub-details or fields, but not both."); } this.id = id; this.title = title; if (nodeset != null) { this.nodeset = XPathReference.getPathExpr(nodeset).getReference(); } this.details = ArrayUtilities.copyIntoArray(detailsVector, new Detail[detailsVector.size()]); this.fields = ArrayUtilities.copyIntoArray(fieldsVector, new DetailField[fieldsVector.size()]); this.variables = variables; this.actions = actions; this.callout = callout; this.useUniformUnitsInCaseTile = "true".equals(uniformUnitsString); this.forceLandscapeView = "true".equals(forceLandscape); this.printEnabled = templatePathValid(printPathProvided) && allFieldIdsAvailable(); if (focusFunction != null) { try { this.focusFunction = XPathParseTool.parseXPath(focusFunction); } catch (XPathSyntaxException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } if (fitAcross != null) { try { this.numEntitiesToDisplayPerRow = Integer.parseInt(fitAcross); } catch (NumberFormatException e) { numEntitiesToDisplayPerRow = 1; } } else { numEntitiesToDisplayPerRow = 1; } } /** * @return The id of this detail template */ public String getId() { return id; } /** * @return A title to be displayed to users regarding * the type of content being described. */ public DisplayUnit getTitle() { return title; } /** * @return A reference to a set of sub-elements of this detail. If provided, * the detail will display fields for each element of this nodeset. */ public TreeReference getNodeset() { return nodeset; } /** * @return Any child details of this detail. */ public Detail[] getDetails() { return details; } /** * Given a detail, return an array of details that will contain either * - all child details * - a single-element array containing the given detail, if it has no children */ public Detail[] getFlattenedDetails() { if (this.isCompound()) { return this.getDetails(); } return new Detail[]{this}; } /** * @return Any fields belonging to this detail. */ public DetailField[] getFields() { return fields; } /** * @return True iff this detail has child details. */ public boolean isCompound() { return details.length > 0; } /** * Whether this detail is expected to be so huge in scope that * the platform should limit its strategy for loading it to be asynchronous * and cached on special keys. */ public boolean useAsyncStrategy() { for (DetailField f : getFields()) { if (f.getSortOrder() == DetailField.SORT_ORDER_CACHABLE) { return true; } } return false; } @Override public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { id = (String)ExtUtil.read(in, new ExtWrapNullable(String.class), pf); title = (DisplayUnit)ExtUtil.read(in, DisplayUnit.class, pf); titleForm = (String)ExtUtil.read(in, new ExtWrapNullable(String.class), pf); nodeset = (TreeReference)ExtUtil.read(in, new ExtWrapNullable(TreeReference.class), pf); Vector<Detail> theDetails = (Vector<Detail>)ExtUtil.read(in, new ExtWrapList(Detail.class), pf); details = new Detail[theDetails.size()]; ArrayUtilities.copyIntoArray(theDetails, details); Vector<DetailField> theFields = (Vector<DetailField>)ExtUtil.read(in, new ExtWrapList(DetailField.class), pf); fields = new DetailField[theFields.size()]; ArrayUtilities.copyIntoArray(theFields, fields); variables = (OrderedHashtable<String, String>)ExtUtil.read(in, new ExtWrapMap(String.class, String.class, ExtWrapMap.TYPE_ORDERED), pf); actions = (Vector<Action>)ExtUtil.read(in, new ExtWrapList(Action.class), pf); callout = (Callout)ExtUtil.read(in, new ExtWrapNullable(Callout.class), pf); forceLandscapeView = ExtUtil.readBool(in); focusFunction = (XPathExpression)ExtUtil.read(in, new ExtWrapNullable(new ExtWrapTagged()), pf); numEntitiesToDisplayPerRow = (int)ExtUtil.readNumeric(in); useUniformUnitsInCaseTile = ExtUtil.readBool(in); } @Override public void writeExternal(DataOutputStream out) throws IOException { ExtUtil.write(out, new ExtWrapNullable(id)); ExtUtil.write(out, title); ExtUtil.write(out, new ExtWrapNullable(titleForm)); ExtUtil.write(out, new ExtWrapNullable(nodeset)); ExtUtil.write(out, new ExtWrapList(ArrayUtilities.toVector(details))); ExtUtil.write(out, new ExtWrapList(ArrayUtilities.toVector(fields))); ExtUtil.write(out, new ExtWrapMap(variables)); ExtUtil.write(out, new ExtWrapList(actions)); ExtUtil.write(out, new ExtWrapNullable(callout)); ExtUtil.writeBool(out, forceLandscapeView); ExtUtil.write(out, new ExtWrapNullable(focusFunction == null ? null : new ExtWrapTagged(focusFunction))); ExtUtil.writeNumeric(out, numEntitiesToDisplayPerRow); ExtUtil.writeBool(out, useUniformUnitsInCaseTile); } public OrderedHashtable<String, XPathExpression> getVariableDeclarations() { if (variablesCompiled == null) { variablesCompiled = new OrderedHashtable<>(); for (Enumeration en = variables.keys(); en.hasMoreElements(); ) { String key = (String)en.nextElement(); //TODO: This is stupid, parse this stuff at XML Parse time. try { variablesCompiled.put(key, XPathParseTool.parseXPath(variables.get(key))); } catch (XPathSyntaxException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } } return variablesCompiled; } /** * Retrieve the custom/callback action used in this detail in * the event that there are no matches. * * @return An Action model definition if one is defined for this detail. * Null if there is no associated action. */ public Vector<Action> getCustomActions(EvaluationContext evaluationContext) { Vector<Action> relevantActions = new Vector<>(); for (Action action : actions) { if (action.isRelevant(evaluationContext)) { relevantActions.addElement(action); } } return relevantActions; } /** * @return The indices of which fields should be used for sorting and their order */ public int[] getSortOrder() { Vector<Integer> indices = new Vector<>(); outer: for (int i = 0; i < fields.length; ++i) { int order = fields[i].getSortOrder(); if (order < 1) { continue; } for (int j = 0; j < indices.size(); ++j) { if (order < fields[indices.elementAt(j)].getSortOrder()) { indices.insertElementAt(i, j); continue outer; } } //otherwise it's larger than all of the other fields. indices.addElement(i); continue; } if (indices.size() == 0) { return new int[]{}; } else { int[] ret = new int[indices.size()]; for (int i = 0; i < ret.length; ++i) { ret[i] = indices.elementAt(i); } return ret; } } //These are just helpers around the old structure. Shouldn't really be //used if avoidable /** * Obsoleted - Don't use */ public String[] getTemplateSizeHints() { return new Map<String[]>(new String[fields.length]) { @Override protected void map(DetailField f, String[] a, int i) { a[i] = f.getTemplateWidthHint(); } }.go(); } /** * Obsoleted - Don't use */ public String[] getHeaderForms() { return new Map<String[]>(new String[fields.length]) { @Override protected void map(DetailField f, String[] a, int i) { a[i] = f.getHeaderForm(); } }.go(); } /** * Obsoleted - Don't use */ public String[] getTemplateForms() { return new Map<String[]>(new String[fields.length]) { @Override protected void map(DetailField f, String[] a, int i) { a[i] = f.getTemplateForm(); } }.go(); } public boolean usesEntityTileView() { boolean usingEntityTile = false; for (DetailField currentField : fields) { if (currentField.getGridX() >= 0 && currentField.getGridY() >= 0 && currentField.getGridWidth() >= 0 && currentField.getGridHeight() > 0) { usingEntityTile = true; } } return usingEntityTile; } public boolean shouldBeLaidOutInGrid() { return numEntitiesToDisplayPerRow > 1 && usesEntityTileView(); } public int getNumEntitiesToDisplayPerRow() { return numEntitiesToDisplayPerRow; } public boolean useUniformUnitsInCaseTile() { return useUniformUnitsInCaseTile; } public boolean forcesLandscape() { return forceLandscapeView; } public GridCoordinate[] getGridCoordinates() { GridCoordinate[] mGC = new GridCoordinate[fields.length]; for (int i = 0; i < fields.length; i++) { DetailField currentField = fields[i]; mGC[i] = new GridCoordinate(currentField.getGridX(), currentField.getGridY(), currentField.getGridWidth(), currentField.getGridHeight()); } return mGC; } public GridStyle[] getGridStyles() { GridStyle[] mGC = new GridStyle[fields.length]; for (int i = 0; i < fields.length; i++) { DetailField currentField = fields[i]; mGC[i] = new GridStyle(currentField.getFontSize(), currentField.getHorizontalAlign(), currentField.getVerticalAlign(), currentField.getCssId()); } return mGC; } public Callout getCallout() { return callout; } private abstract class Map<E> { private final E a; private Map(E a) { this.a = a; } protected abstract void map(DetailField f, E a, int i); public E go() { for (int i = 0; i < fields.length; ++i) { map(fields[i], a, i); } return a; } } /** * Given an evaluation context which a qualified nodeset, will populate that EC with the * evaluated variable values associated with this detail. * * @param ec The Evaluation Context to be used to evaluate the variable expressions and which * will be populated by their result. Will be modified in place. */ public void populateEvaluationContextVariables(EvaluationContext ec) { Hashtable<String, XPathExpression> variables = getVariableDeclarations(); //These are actually in an ordered hashtable, so we can't just get the keyset, since it's //in a 1.3 hashtable equivalent for (Enumeration en = variables.keys(); en.hasMoreElements(); ) { String key = (String)en.nextElement(); ec.setVariable(key, FunctionUtils.unpack(variables.get(key).eval(ec))); } } public boolean evaluateFocusFunction(EvaluationContext ec) { if (focusFunction == null) { return false; } Object value = FunctionUtils.unpack(focusFunction.eval(ec)); return FunctionUtils.toBoolean(value); } public XPathExpression getFocusFunction() { return focusFunction; } private boolean templatePathValid(String templatePathProvided) { if (PRINT_TEMPLATE_PROVIDED_VIA_GLOBAL_SETTING.equals(templatePathProvided)) { return true; } else if (templatePathProvided != null) { try { this.derivedPrintTemplatePath = ReferenceManager.instance().DeriveReference(templatePathProvided).getLocalURI(); return true; } catch (InvalidReferenceException e) { System.out.println("Invalid print template path provided for detail with id " + this.id); } } return false; } private boolean allFieldIdsAvailable() { // TODO: implement return true; } public boolean isPrintEnabled() { return this.printEnabled; } public HashMap<String, DetailFieldPrintInfo> getKeyValueMapForPrint(TreeReference selectedEntityRef, EvaluationContext baseContext) { HashMap<String, DetailFieldPrintInfo> mapping = new HashMap<>(); populateMappingWithDetailFields(mapping, selectedEntityRef, baseContext, null); return mapping; } private void populateMappingWithDetailFields(HashMap<String, DetailFieldPrintInfo> mapping, TreeReference selectedEntityRef, EvaluationContext baseContext, Detail parentDetail) { if (isCompound()) { for (Detail childDetail : details) { childDetail.populateMappingWithDetailFields(mapping, selectedEntityRef, baseContext, this); } } else { // this is a normal detail with fields Entity entityForDetail = getCorrespondingEntity(selectedEntityRef, parentDetail, baseContext); for (int i = 0; i < fields.length; i++) { if (entityForDetail.isValidField(i)) { mapping.put( fields[i].getFieldIdentifierRobust(), new DetailFieldPrintInfo(fields[i], entityForDetail, i)); } } } } private Entity getCorrespondingEntity(TreeReference selectedEntityRef, Detail parentDetail, EvaluationContext baseContext) { EvaluationContext entityFactoryContext = DetailUtil.getEntityFactoryContext(selectedEntityRef, parentDetail != null, parentDetail, baseContext); NodeEntityFactory factory = new NodeEntityFactory(this, entityFactoryContext); return factory.getEntity(selectedEntityRef); } public String getDerivedPrintTemplatePath() { return this.derivedPrintTemplatePath; } }
package org.gestern.gringotts; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.command.CommandExecutor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; public class Gringotts extends JavaPlugin { /** The Gringotts plugin instance. */ public static Gringotts gringotts; private PluginManager pluginmanager; private Logger log = Bukkit.getServer().getLogger(); private final Commands gcommand = new Commands(this); public final AccountHolderFactory accountHolderFactory = new AccountHolderFactory(); /** Manages accounts. */ public Accounting accounting; @Override public void onEnable() { gringotts = this; pluginmanager = getServer().getPluginManager(); CommandExecutor playerCommands = gcommand.new Money(); CommandExecutor adminCommands = gcommand.new Moneyadmin(); getCommand("balance").setExecutor(playerCommands); getCommand("money").setExecutor(playerCommands); getCommand("moneyadmin").setExecutor(adminCommands); // load and init configuration FileConfiguration savedConfig = getConfig(); Configuration.config.readConfig(savedConfig); accounting = new Accounting(); registerEvents(); log.info("[Gringotts] enabled"); } @Override public void onDisable() { log.info("[Gringotts] shutting down, saving configuration"); // fill config file Configuration.config.saveConfig(getConfig()); // shut down db connection DAO.getDao().shutdown(); log.info("[Gringotts] disabled"); } private void registerEvents() { pluginmanager.registerEvents(new AccountListener(this), this); } // TODO add optional dependency to factions. how? }
package org.icij.extract.tasks; import org.icij.extract.core.*; import java.nio.file.Path; import java.time.Duration; import java.util.List; import java.util.Optional; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import java.lang.management.ManagementFactory; import com.sun.management.OperatingSystemMXBean; import org.icij.extract.tasks.factories.*; import org.icij.task.DefaultTask; import org.icij.task.annotation.Option; import org.icij.task.annotation.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Spew extracted text from files to an output. * * @author Matthew Caruana Galizia <mcaruana@icij.org> * @since 1.0.0-beta */ @Task("Extract from files.") @Option(name = "queue-type", description = "Set the queue backend type. For now, the only valid value is " + "\"redis\".", parameter = "type", code = "q") @Option(name = "queue-name", description = "The name of the queue, the default of which is type-dependent" + ".", parameter = "name") @Option(name = "queue-buffer", description = "The size of the internal file path buffer used by the queue" + ".", parameter = "size") @Option(name = "queue-poll", description = "Time to wait when polling the queue e.g. \"5s\" or \"1m\". " + "Defaults to 0.", parameter = "duration") @Option(name = "report-type", description = "Set the report backend type. For now, the only valid value is" + " \"redis\".", parameter = "type", code = "r") @Option(name = "report-name", description = "The name of the report, the default of which is " + "type-dependent.", parameter = "name") @Option(name = "redis-address", description = "Set the Redis backend address. Defaults to " + "127.0.0.1:6379.", parameter = "address") @Option(name = "include-pattern", description = "Glob pattern for matching files e.g. \"**/*.{tif,pdf}\". " + "Files not matching the pattern will be ignored.", parameter = "pattern") @Option(name = "exclude-pattern", description = "Glob pattern for excluding files and directories. Files " + "and directories matching the pattern will be ignored.", parameter = "pattern") @Option(name = "follow-symlinks", description = "Follow symbolic links, which are not followed by default" + ".") @Option(name = "include-hidden-files", description = "Don't ignore hidden files. On DOS file systems, this" + " means all files or directories with the \"hidden\" file attribute. On all other file systems, this means " + "all file or directories starting with a dot. Hidden files are ignored by default.") @Option(name = "include-os-files", description = "Include files and directories generated by common " + "operating systems. This includes \"Thumbs.db\" and \".DS_Store\". The list is not determined by the current " + "operating system. OS-generated files are ignored by default.") @Option(name = "path-base", description = "This is useful if your mount path for files varies from system " + "to another, or if you simply want to hide the base of a path. For example, if you're working with a path " + "that looks like \"/home/user/data\", specify \"/home/user/\" as the value for this option so that all queued" + " paths start with \"data/\".") @Option(name = "index-type", description = "Specify the index type. For now, the only valid value is " + "\"solr\" (the default).", parameter = "type") @Option(name = "soft-commit", description = "Performs a soft commit. Makes index changes visible while " + "neither fsync-ing index files nor writing a new index descriptor. This could lead to data loss if Solr is " + "terminated unexpectedly.") @Option(name = "index-address", description = "Index core API endpoint address.", code = "s", parameter = "url") @Option(name = "index-server-certificate", description = "The index server's public certificate, used for" + " certificate pinning. Supported formats are PEM, DER, PKCS #12 and JKS.", parameter = "path") @Option(name = "index-verify-host", description = "Verify the index server's public certificate against " + "the specified host. Use the wildcard \"*\" to disable verification.", parameter = "hostname") @Option(name = "output-format", description = "Set the output format. Either \"text\" or \"HTML\". " + "Defaults to text output.", parameter = "type") @Option(name = "embed-handling", description = "Set the embed handling mode. Either \"ignore\", " + "\"extract\" or \"embed\". When set to extract, embeds are parsed and the output is in-lined into the main " + "output. In embed mode, embeds are not parsed but are in-lined as a data URI representation of the raw embed " + "data. The latter mode only applies when the output format is set to HTML. Defaults to extracting.", parameter = "type") @Option(name = "ocr-language", description = "Set the language used by Tesseract. If none is specified, " + "English is assumed. Multiple languages may be specified, separated by plus characters. Tesseract uses " + "3-character ISO 639-2 language codes.", parameter = "language") @Option(name = "ocr-timeout", description = "Set the timeout for the Tesseract process to finish e.g. \"5s\" or \"1m\". " + "Defaults to 12 hours.", parameter = "duration") @Option(name = "ocr", description = "Enable or disable automatic OCR. On by default.") @Option(name = "working-directory", description = "Set the working directory from which to resolve paths " + "for files passed to the extractor.", parameter = "path") @Option(name = "output-metadata", description = "Output metadata along with extracted text. For the " + "\"file\" output type, a corresponding JSON file is created for every input file. With indexes, metadata " + "fields are set using an optional prefix. On by default.") @Option(name = "tag", description = "Set the given field to a corresponding value on each document output" + ".", parameter = "name-value-pair") @Option(name = "output-encoding", description = "Set the text output encoding. Defaults to UTF-8.", parameter = "character-set") @Option(name = "id-field", description = "Index field for an automatically generated identifier. The ID " + "for the same file is guaranteed not to change if the path doesn't change. Defaults to \"id\".", code = "i", parameter = "name") @Option(name = "text-field", description = "Index field for extracted text. Defaults to \"text\".", code = "t", parameter = "name") @Option(name = "path-field", description = "Index field for the file path. Defaults to \"path\".", parameter = "name", code = "p") @Option(name = "id-algorithm", description = "The hashing algorithm used for generating index document " + "identifiers from paths e.g. \"SHA-224\". Defaults to \"SHA-256\".", parameter = "algorithm") @Option(name = "metadata-prefix", description = "Prefix for metadata fields added to the index. " + "Defaults to \"metadata_\".", parameter = "name") @Option(name = "jobs", description = "The number of documents to process at a time. Defaults to the number" + " of available processors.", parameter = "number") @Option(name = "commit-interval", description = "Commit to the index every time the specified number of " + "documents is added. Disabled by default. Consider using the \"autoCommit\" \"maxDocs\" directive in your " + "Solr update handler configuration instead.", parameter = "number") @Option(name = "commit-within", description = "Instruct Solr to automatically commit a document after the " + "specified amount of time has elapsed since it was added. Disabled by default. Consider using the " + "\"autoCommit\" \"maxTime\" directive in your Solr update handler configuration instead.", parameter = "duration") @Option(name = "atomic-writes", description = "Make atomic updates to the index. If your schema contains " + "fields that are not included in the payload, this prevents their values, if any, from being erased.") @Option(name = "raw-dates", description = "Don't fix invalid dates. Tika's image metadata extractor will " + "generate non-ISO compliant dates if the the timezone is not available in the source metadata. Turning this " + "option on appends \"Z\" to non-compliant dates, making them compatible with the Solr date field type.") @Option(name = "output-directory", description = "Directory to output extracted text. Defaults to the " + "current directory.", parameter = "path") @Option(name = "output-type", description = "Set the output type. Either \"file\", \"stdout\" or \"solr\"" + ".", parameter = "type", code = "o") public class SpewTask extends DefaultTask<Long> { private static final Logger logger = LoggerFactory.getLogger(SpewTask.class); private void checkMemory() { final OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); final long maxMemory = Runtime.getRuntime().maxMemory(); if (maxMemory < (os.getTotalPhysicalMemorySize() / 4)) { logger.warn(String.format("Memory available to JVM (%s) is less than 25%% of available system memory. " + "You should probably increase it.", FileUtils.byteCountToDisplaySize(maxMemory))); } } @Override public Long run(final String[] paths) throws Exception { checkMemory(); try (final Report report = ReportFactory.createReport(options); final Spewer spewer = SpewerFactory.createSpewer(options); final PathQueue queue = PathQueueFactory.createQueue(options)) { return spew(report, spewer, queue, paths); } } @Override public Long run() throws Exception { return run(null); } private Long spew(final Report report, final Spewer spewer, final PathQueue queue, final String[] paths) throws Exception { final int parallelism = options.get("jobs").integer().orElse(ExtractingConsumer.defaultPoolSize()); logger.info(String.format("Processing up to %d file(s) in parallel.", parallelism)); final Extractor extractor = ExtractorFactory.createExtractor(options); final ExtractingConsumer consumer = new ExtractingConsumer(spewer, extractor, parallelism); final PathQueueDrainer drainer = new PathQueueDrainer(queue, consumer); final Optional<Duration> queuePoll = options.get("queue-poll").duration(); if (queuePoll.isPresent()) { drainer.setPollTimeout(queuePoll.get()); } if (null != report) { consumer.setReporter(new Reporter(report)); } final Future<Long> draining; final Long drained; if (null != paths && paths.length > 0) { final Scanner scanner = ScannerFactory.createScanner(options, queue, null); final List<Future<Path>> scanning = scanner.scan(options.get("path-base").value().orElse(null), paths); // Set the latch that will be waited on for polling, then start draining in the background. drainer.setLatch(scanner.getLatch()); draining = drainer.drain(); // Start scanning in a background thread but block until every path has been scanned and queued. for (Future<Path> scan : scanning) scan.get(); // Only a short timeout is needed when awaiting termination, because the call to get the result of each // job is blocking and by the time `awaitTermination` is reached the jobs would have finished. scanner.shutdown(); scanner.awaitTermination(5, TimeUnit.SECONDS); } else { // Start draining in a background thread. draining = drainer.drain(); } // Block until every path in the queue has been consumed. drained = draining.get(); logger.info(String.format("Spewed %d files.", drained)); // Shut down the drainer. Use a short timeout because all jobs should have finished. drainer.shutdown(); drainer.awaitTermination(5, TimeUnit.SECONDS); // Use a long timeout because some files might still be processing. consumer.shutdown(); consumer.awaitTermination(1, TimeUnit.HOURS); return drained; } }
package me.vertretungsplan.parser; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureException; import me.vertretungsplan.exception.CredentialInvalidException; import me.vertretungsplan.objects.*; import me.vertretungsplan.objects.credential.UserPasswordCredential; import org.apache.commons.codec.binary.Base64; import org.apache.http.client.HttpResponseException; import org.apache.http.entity.ContentType; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class IphisParser extends BaseParser { private static final String PARAM_URL = "url"; private static final String PARAM_JWT_KEY = "jwt_key"; private static final String PARAM_KUERZEL = "kuerzel"; /** * URL of given IPHIS instance */ private String api; /** * Shortcode for school */ private String kuerzel; private String jwt_key; private String website; /** * array of grades/classes retrieved from the api */ private JSONArray grades; /** * array of teachers retrieved from the api */ private JSONArray teachers; /** * array of messages retrieved from the api */ private JSONArray messages; /** * hold the Authentication Token (JWT) */ private String authToken; /** * hold the timestamp of the last schedule-update */ private LocalDateTime lastUpdate; public IphisParser(SubstitutionScheduleData scheduleData, CookieProvider cookieProvider) { super(scheduleData, cookieProvider); JSONObject data = scheduleData.getData(); try { api = "https://" + data.getString(PARAM_URL) + "/remote/vertretungsplan/ssp"; kuerzel = data.getString(PARAM_KUERZEL); jwt_key = data.getString(PARAM_JWT_KEY); } catch (JSONException e) { e.printStackTrace(); } } public SubstitutionSchedule getSubstitutionSchedule() throws IOException, JSONException, CredentialInvalidException { final SubstitutionSchedule substitutionSchedule = SubstitutionSchedule.fromData(scheduleData); if (login()) { getGrades(); getTeachers(); getMessages(); final JSONArray changes = getChanges(); substitutionSchedule.setClasses(getAllClasses()); substitutionSchedule.setTeachers(getAllTeachers()); substitutionSchedule.setWebsite(website); parseIphis(substitutionSchedule, changes, grades, teachers, messages); } return substitutionSchedule; } @Override public LocalDateTime getLastChange() throws IOException, JSONException, CredentialInvalidException { if (lastUpdate == null) { login(); } return lastUpdate; } private Boolean login() throws CredentialInvalidException, IOException { final UserPasswordCredential userPasswordCredential = (UserPasswordCredential) credential; final String username = userPasswordCredential.getUsername(); final String password = userPasswordCredential.getPassword(); JSONObject payload = new JSONObject(); try { payload.put("school", kuerzel); payload.put("user", username); payload.put("type", scheduleData.getType()); payload.put("password", password); } catch (JSONException e) { e.printStackTrace(); } httpPost(api + "/login", "UTF-8", payload.toString(), ContentType.APPLICATION_JSON); final String httpResponse = httpPost(api + "/login", "UTF-8", payload.toString(), ContentType.APPLICATION_JSON); final JSONObject token; try { token = new JSONObject(httpResponse); final String key = Base64.encodeBase64String(jwt_key.getBytes()); final Claims jwtToken = Jwts.parser().setSigningKey(key) .parseClaimsJws(token.getString("token")).getBody(); assert jwtToken.getSubject().equals("vertretungsplan.me"); authToken = token.getString("token"); website = jwtToken.getIssuer(); lastUpdate = new LocalDateTime(token.getLong("stand") * 1000); } catch (SignatureException | JSONException e) { throw new CredentialInvalidException(); } return true; } /** * Returns a JSONArray with all changes from now to in one week. */ private JSONArray getChanges() throws IOException, CredentialInvalidException { // Date (or alias of date) when the changes start final String startBy = LocalDate.now().toString(); // Date (or alias of date) when the changes end final String endBy = LocalDate.now().plusWeeks(1).toString(); final String url = api + "/vertretung/von/" + startBy + "/bis/" + endBy; return getJSONArray(url); } /** * Returns a JSONArray with all messages. */ private void getMessages() throws IOException, JSONException, CredentialInvalidException { if (messages == null) { final String url = api + "/nachrichten"; messages = getJSONArray(url); } } /** * Returns a JSONArray with all grades. */ private void getGrades() throws IOException, JSONException, CredentialInvalidException { if (grades == null) { final String url = api + "/klassen"; grades = getJSONArray(url); } } /** * Returns a JSONArray with all teachers. */ private void getTeachers() throws IOException, CredentialInvalidException { if (teachers == null) { final String url = api + "/lehrer"; teachers = getJSONArray(url); } } private JSONArray getJSONArray(String url) throws IOException, CredentialInvalidException { try { Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + authToken); headers.put("Content-Type", "application/json"); headers.put("Accept", "application/json"); final String httpResponse = httpGet(url, "UTF-8", headers); return new JSONArray(httpResponse); } catch (HttpResponseException httpResponseException) { if (httpResponseException.getStatusCode() == 404) { return null; } throw httpResponseException; } catch (JSONException e) { return new JSONArray(); } } void parseIphis(SubstitutionSchedule substitutionSchedule, JSONArray changes, JSONArray grades, JSONArray teachers, JSONArray messages) throws IOException, JSONException { if (changes == null) { return; } // Link course IDs to their names HashMap<String, String> coursesHashMap = null; if (grades != null) { coursesHashMap = new HashMap<>(); for (int i = 0; i < grades.length(); i++) { JSONObject grade = grades.getJSONObject(i); coursesHashMap.put(grade.getString("id"), grade.getString("name")); } } // Link teacher IDs to their names HashMap<String, String> teachersHashMap = null; if (teachers != null) { teachersHashMap = new HashMap<>(); for (int i = 0; i < teachers.length(); i++) { JSONObject teacher = teachers.getJSONObject(i); teachersHashMap.put(teacher.getString("id"), teacher.getString("name")); } } // Add Messages List<AdditionalInfo> infos = new ArrayList<>(messages.length()); for (int i = 0; i < messages.length(); i++) { JSONObject message = messages.getJSONObject(i); AdditionalInfo info = new AdditionalInfo(); info.setHasInformation(message.getBoolean("notification")); info.setTitle(message.getString("titel").trim()); info.setText(message.getString("nachricht").trim()); info.setFromSchedule(true); infos.add(info); } substitutionSchedule.getAdditionalInfos().addAll(infos); substitutionSchedule.setLastChange(lastUpdate); // Add changes to SubstitutionSchedule LocalDate currentDate = LocalDate.now(); SubstitutionScheduleDay substitutionScheduleDay = new SubstitutionScheduleDay(); substitutionScheduleDay.setDate(currentDate); for (int i = 0; i < changes.length(); i++) { final JSONObject change = changes.getJSONObject(i); final LocalDate substitutionDate = new LocalDate(change.getString("datum")); // If starting date of change does not equal date of SubstitutionScheduleDay if (!substitutionDate.isEqual(currentDate)) { if (!substitutionScheduleDay.getSubstitutions().isEmpty()) { substitutionSchedule.addDay(substitutionScheduleDay); } substitutionScheduleDay = new SubstitutionScheduleDay(); substitutionScheduleDay.setDate(substitutionDate); currentDate = substitutionDate; } if (change.getInt("id") > 0) { final Substitution substitution = getSubstitution(change, coursesHashMap, teachersHashMap); substitutionScheduleDay.addSubstitution(substitution); } else if (!change.optString("nachricht").isEmpty()) { substitutionScheduleDay.addMessage(change.optString("nachricht")); } } substitutionSchedule.addDay(substitutionScheduleDay); } private String[] getSQLArray(String data) { String[] retArray = {}; Pattern pattern = Pattern.compile("\\{(.*?)}"); Matcher matcher = pattern.matcher(data); if (matcher.find()) { retArray = matcher.group(1).split(","); } return retArray; } private Substitution getSubstitution(JSONObject change, HashMap<String, String> gradesHashMap, HashMap<String, String> teachersHashMap) throws IOException, JSONException { final Substitution substitution = new Substitution(); // Set class(es) final String[] classIds = getSQLArray(change.getString("id_klasse")); if (classIds.length > 0) { if (gradesHashMap == null) { throw new IOException("Change references a grade but grades are empty."); } final HashSet<String> classes = new HashSet<>(); for (String classId : classIds) { classes.add(gradesHashMap.get(classId)); } substitution.setClasses(classes); } // Set type final String type = change.getString("aenderungsgrund").trim(); if (!type.isEmpty() && !type.toLowerCase().equals("null")) { substitution.setType(type); } else { substitution.setType("Vertretung"); } // Set color substitution.setColor(colorProvider.getColor(type)); // Set covering teacher final String[] coveringTeacherIds = getSQLArray(change.getString("id_person_verantwortlich")); if (coveringTeacherIds.length > 0) { if (teachersHashMap == null) { throw new IOException("Change references a covering teacher but teachers are empty."); } final HashSet<String> teachers = new HashSet<>(); for (String coveringTeacherId : coveringTeacherIds) { if (!coveringTeacherId.toLowerCase().equals("null") && teachersHashMap.get(coveringTeacherId) != null) { teachers.add(teachersHashMap.get(coveringTeacherId)); } } substitution.setTeachers(teachers); } // Set teacher final String[] teacherIds = getSQLArray(change.getString("id_person_verantwortlich_orig")); final HashSet<String> coveringTeachers = new HashSet<>(); if (teacherIds.length > 0) { if (teachersHashMap == null) { throw new IOException("Change references a teacher but teachers are empty."); } for (String coveringTeacherId : coveringTeacherIds) { if (!coveringTeacherId.toLowerCase().equals("null") && teachersHashMap.get(coveringTeacherId) != null) { coveringTeachers.add(teachersHashMap.get(coveringTeacherId)); } } substitution.setPreviousTeachers(coveringTeachers); } //Set room if (!change.optString("raum").isEmpty() && !change.optString("raum").toLowerCase().equals("null")) { substitution.setRoom(change.optString("raum")); } else if (!change.optString("raum_orig").isEmpty() && !change.optString("raum_orig").toLowerCase().equals("null")) { substitution.setRoom(change.optString("raum_orig")); } if (!change.optString("raum_orig").isEmpty() && !change.optString("raum_orig").toLowerCase().equals("null")) { substitution.setPreviousRoom(change.optString("raum_orig")); } else if (!change.optString("raum").isEmpty() && !change.optString("raum").toLowerCase().equals("null")) { substitution.setPreviousRoom(change.optString("raum")); } //Set subject if (!change.optString("fach").isEmpty() && !change.optString("fach").toLowerCase().equals("null")) { substitution.setSubject(change.optString("fach")); } if (!change.optString("fach_orig").isEmpty() && !change.optString("fach_orig").toLowerCase().equals("null")) { substitution.setPreviousSubject(change.optString("fach_orig")); } //Set description if (!change.getString("information").isEmpty() && !change.getString("information").toLowerCase().equals("null")) { substitution.setDesc(change.getString("information").trim()); } final String startingHour = change.getString("zeit_von").replaceFirst("^0+(?!$)", ""); final String endingHour = change.getString("zeit_bis").replaceFirst("^0+(?!$)", ""); if (!startingHour.equals("") || !endingHour.equals("")) { String lesson = ""; if (!startingHour.equals("") && endingHour.equals("")) { lesson = "Ab " + startingHour; } if (startingHour.equals("") && !endingHour.equals("")) { lesson = "Bis " + endingHour; } if (!startingHour.equals("") && !endingHour.equals("")) { lesson = startingHour + " - " + endingHour; } if (startingHour.equals(endingHour)) { lesson = startingHour; } substitution.setLesson(lesson); } return substitution; } @Override public List<String> getAllClasses() throws IOException, JSONException, CredentialInvalidException { final List<String> classesList = new ArrayList<>(); if (grades == null) { return null; } for (int i = 0; i < grades.length(); i++) { final JSONObject grade = grades.getJSONObject(i); classesList.add(grade.getString("name")); } return classesList; } @Override public List<String> getAllTeachers() throws IOException, JSONException, CredentialInvalidException { final List<String> teachersList = new ArrayList<>(); if (teachers == null) { return null; } for (int i = 0; i < teachers.length(); i++) { final JSONObject teacher = teachers.getJSONObject(i); teachersList.add(teacher.getString("name")); } return teachersList; } }