answer
stringlengths 17
10.2M
|
|---|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dae.animation.rig;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.Control;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Koen Samyn
*/
public class AnimationListControl implements Control {
private ArrayList<AnimationController> controllers =
new ArrayList<AnimationController>();
private Rig rig;
public Control cloneForSpatial(Spatial spatial) {
AnimationListControl controller = new AnimationListControl();
for (AnimationController ac : controllers) {
controller.addAnimationController(ac.clone());
}
spatial.addControl(controller);
return controller;
}
public int addAnimationController(AnimationController ac) {
controllers.add(ac);
return controllers.indexOf(ac);
}
public int removeAnimationController(AnimationController ac) {
int index = controllers.indexOf(ac);
controllers.remove(ac);
return index;
}
public List<AnimationController> getAnimationControllers() {
return controllers;
}
public int getNrOfAnimationControllers() {
return controllers.size();
}
public Object getAnimationControllerAt(int index) {
return controllers.get(index);
}
public void setSpatial(Spatial spatial) {
if (spatial instanceof Rig) {
this.rig = (Rig) spatial;
for (AnimationController ac : controllers) {
ac.initialize(rig);
}
}
}
public void update(float tpf) {
for (AnimationController ac : controllers) {
ac.update(tpf);
}
}
public void render(RenderManager rm, ViewPort vp) {
}
public void write(JmeExporter ex) throws IOException {
}
public void read(JmeImporter im) throws IOException {
}
public String generateNewName(String controller) {
int index = 1;
String newName = controller + index;
while (hasName(newName)) {
++index;
newName = controller + index;
}
return newName;
}
private boolean hasName(String name) {
for (AnimationController ac : controllers) {
if (ac.getName().equals(name)) {
return true;
}
}
return false;
}
public void initialize() {
for (AnimationController ac : controllers) {
ac.initialize(rig);
}
}
}
|
package de.espend.idea.php.annotation;
import com.intellij.openapi.components.*;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.Nullable;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
@State(
name = "EspendPhpAnnotationSetting",
storages = {
@Storage(id = "default", file = StoragePathMacros.PROJECT_FILE),
@Storage(id = "dir", file = StoragePathMacros.PROJECT_CONFIG_DIR + "/espend_php_annotation.xml", scheme = StorageScheme.DIRECTORY_BASED)
}
)
public class Settings implements PersistentStateComponent<Settings> {
public static Settings getInstance(Project project) {
return ServiceManager.getService(project, Settings.class);
}
@Nullable
@Override
public Settings getState() {
return this;
}
@Override
public void loadState(Settings settings) {
XmlSerializerUtil.copyBean(settings, this);
}
}
|
package de.lmu.ifi.dbs.wrapper;
import de.lmu.ifi.dbs.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.algorithm.KDDTask;
import de.lmu.ifi.dbs.algorithm.clustering.OPTICS;
import de.lmu.ifi.dbs.database.AbstractDatabase;
import de.lmu.ifi.dbs.database.RTreeDatabase;
import de.lmu.ifi.dbs.database.SpatialIndexDatabase;
import de.lmu.ifi.dbs.database.MTreeDatabase;
import de.lmu.ifi.dbs.database.connection.AbstractDatabaseConnection;
import de.lmu.ifi.dbs.database.connection.MultipleFileBasedDatabaseConnection;
import de.lmu.ifi.dbs.distance.EuklideanDistanceFunction;
import de.lmu.ifi.dbs.distance.LocallyWeightedDistanceFunction;
import de.lmu.ifi.dbs.distance.multirepresented.CombinationTree;
import de.lmu.ifi.dbs.normalization.MultiRepresentedObjectNormalization;
import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler;
import de.lmu.ifi.dbs.utilities.optionhandling.UnusedParameterException;
import java.util.ArrayList;
/**
* Wrapper class for multi represented OPTICS algorithm.
*
* @author Elke Achtert (<a href="mailto:achtert@dbs.ifi.lmu.de">achtert@dbs.ifi.lmu.de</a>)
*/
public class MROPTICSWrapper extends AbstractWrapper {
/**
* Parameter for epsilon.
*/
public static final String EPSILON_P = "epsilon";
/**
* Description for parameter epsilon.
*/
public static final String EPSILON_D = "<epsilon>an epsilon value suitable to the distance function " + LocallyWeightedDistanceFunction.class.getName();
/**
* Parameter minimum points.
*/
public static final String MINPTS_P = "minpts";
/**
* Description for parameter minimum points.
*/
public static final String MINPTS_D = "<int>minpts";
/**
* Epsilon.
*/
protected String epsilon;
/**
* Minimum points.
*/
protected int minpts;
/**
* Sets epsilon and minimum points to the optionhandler additionally to the
* parameters provided by super-classes. Since DBSCANWrapper is a non-abstract class,
* finally optionHandler is initialized.
*/
public MROPTICSWrapper() {
super();
parameterToDescription.put(EPSILON_P + OptionHandler.EXPECTS_VALUE, EPSILON_D);
parameterToDescription.put(MINPTS_P + OptionHandler.EXPECTS_VALUE, MINPTS_D);
optionHandler = new OptionHandler(parameterToDescription, getClass().getName());
}
/**
* Sets the parameters epsilon and minpts additionally to the parameters set
* by the super-class' method. Both epsilon and minpts are required
* parameters.
*
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[])
*/
public String[] setParameters(String[] args) throws IllegalArgumentException {
super.setParameters(args);
try {
epsilon = optionHandler.getOptionValue(EPSILON_P);
minpts = Integer.parseInt(optionHandler.getOptionValue(MINPTS_P));
}
catch (UnusedParameterException e) {
throw new IllegalArgumentException(e);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException(e);
}
return new String[0];
}
/**
* Runs the OPTICS algorithm.
*/
public void runOPTICS() {
String ct = "I(I(I(I(I(I(R:1,R:2),R:3),R:4),R:4),R:5),R:6)";
ArrayList<String> params = getRemainingParameters();
// algorithm OPTICS
params.add(OptionHandler.OPTION_PREFIX + KDDTask.ALGORITHM_P);
params.add(OPTICS.class.getName());
// epsilon
params.add(OptionHandler.OPTION_PREFIX + OPTICS.EPSILON_P);
params.add(epsilon);
// minpts
params.add(OptionHandler.OPTION_PREFIX + OPTICS.MINPTS_P);
params.add(Integer.toString(minpts));
// distance function
params.add(OptionHandler.OPTION_PREFIX + OPTICS.DISTANCE_FUNCTION_P);
params.add(CombinationTree.class.getName());
// combination tree
params.add(OptionHandler.OPTION_PREFIX + CombinationTree.TREE_P);
params.add(ct);
// normalization
params.add(OptionHandler.OPTION_PREFIX + KDDTask.NORMALIZATION_P);
params.add(MultiRepresentedObjectNormalization.class.getName());
params.add(OptionHandler.OPTION_PREFIX + KDDTask.NORMALIZATION_UNDO_F);
// database connection
params.add(OptionHandler.OPTION_PREFIX + KDDTask.DATABASE_CONNECTION_P);
params.add(MultipleFileBasedDatabaseConnection.class.getName());
// database
params.add(OptionHandler.OPTION_PREFIX + AbstractDatabaseConnection.DATABASE_CLASS_P);
params.add(MTreeDatabase.class.getName());
// distance function for db
params.add(OptionHandler.OPTION_PREFIX + MTreeDatabase.DISTANCE_FUNCTION_P);
params.add(CombinationTree.class.getName());
// combination tree
params.add(OptionHandler.OPTION_PREFIX + CombinationTree.TREE_P);
params.add(ct);
// distance cache
params.add(OptionHandler.OPTION_PREFIX + AbstractDatabase.CACHE_F);
// bulk load
params.add(OptionHandler.OPTION_PREFIX + SpatialIndexDatabase.BULK_LOAD_F);
// page size
params.add(OptionHandler.OPTION_PREFIX + SpatialIndexDatabase.PAGE_SIZE_P);
params.add("4000");
// cache size
params.add(OptionHandler.OPTION_PREFIX + SpatialIndexDatabase.CACHE_SIZE_P);
params.add("120000");
// input
params.add(OptionHandler.OPTION_PREFIX + MultipleFileBasedDatabaseConnection.INPUT_P);
params.add(input);
// output
params.add(OptionHandler.OPTION_PREFIX + KDDTask.OUTPUT_P);
params.add(output);
if (time) {
params.add(OptionHandler.OPTION_PREFIX + AbstractAlgorithm.TIME_F);
}
if (verbose) {
params.add(OptionHandler.OPTION_PREFIX + AbstractAlgorithm.VERBOSE_F);
params.add(OptionHandler.OPTION_PREFIX + AbstractAlgorithm.VERBOSE_F);
params.add(OptionHandler.OPTION_PREFIX + AbstractAlgorithm.VERBOSE_F);
}
KDDTask task = new KDDTask();
task.setParameters(params.toArray(new String[params.size()]));
task.run();
}
/**
* Runs the COPAC algorithm accordingly to the specified parameters.
*
* @param args parameter list according to description
*/
public void run(String[] args) {
this.setParameters(args);
this.runOPTICS();
}
public static void main(String[] args) {
MROPTICSWrapper optics = new MROPTICSWrapper();
try {
optics.run(args);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
package dr.app.beauti.options;
import dr.app.beauti.types.PriorScaleType;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.Nucleotides;
import dr.math.MathUtils;
import java.util.List;
/**
* @author Alexei Drummond
* @author Andrew Rambaut
* @author Walter Xie
*/
public abstract class PartitionOptions extends ModelOptions {
protected String partitionName;
protected final BeautiOptions options;
protected double[] avgRootAndRate = new double[]{1.0, 1.0};
public PartitionOptions(BeautiOptions options) {
this.options = options;
}
public PartitionOptions(BeautiOptions options, String name) {
this.options = options;
this.partitionName = name;
initModelParametersAndOpererators();
}
protected abstract void initModelParametersAndOpererators();
protected abstract void selectParameters(List<Parameter> params);
protected abstract void selectOperators(List<Operator> ops);
public abstract String getPrefix();
// protected void createParameterClockRateUndefinedPrior(PartitionOptions options, String name, String description, PriorScaleType scaleType,
// double initial, double truncationLower, double truncationUpper) { // it will change to Uniform
// new Parameter.Builder(name, description).scaleType(scaleType).prior(PriorType.UNDEFINED).initial(initial)
// .isCMTCRate(true).isNonNegative(true)
// .truncationLower(truncationLower).truncationUpper(truncationUpper).partitionOptions(options).build(parameters);
// protected void createParameterClockRateReferencePrior(PartitionOptions options, String name, String description, PriorScaleType scaleType,
// double initial) { // it will change to Uniform
// new Parameter.Builder(name, description).scaleType(scaleType).prior(PriorType.CMTC_RATE_REFERENCE_PRIOR).initial(initial)
// .isCMTCRate(true).isNonNegative(true)
// .truncationLower(truncationLower).truncationUpper(truncationUpper).partitionOptions(options).build(parameters);
// protected void createParameterClockRateUniform(PartitionOptions options, String name, String description, PriorScaleType scaleType,
// double initial, double truncationLower, double truncationUpper) {
// new Parameter.Builder(name, description).scaleType(scaleType).prior(PriorType.UNIFORM_PRIOR).initial(initial)
// .isCMTCRate(true).isNonNegative(true)
// .truncationLower(truncationLower).truncationUpper(truncationUpper).partitionOptions(options).build(parameters);
// protected void createParameterClockRateGamma(PartitionOptions options, String name, String description, PriorScaleType scaleType,
// double initial, double shape, double scale) {
// new Parameter.Builder(name, description).scaleType(scaleType).prior(PriorType.GAMMA_PRIOR).initial(initial)
// .isCMTCRate(true).isNonNegative(true)
// .shape(shape).scale(scale).partitionOptions(options).build(parameters);
// public void createParameterClockRateExponential(PartitionOptions options, String name, String description, PriorScaleType scaleType,
// double initial, double mean, double offset) {
// new Parameter.Builder(name, description).scaleType(scaleType).prior(PriorType.EXPONENTIAL_PRIOR)
// .isCMTCRate(true).isNonNegative(true)
// .initial(initial).mean(mean).offset(offset).partitionOptions(options).build(parameters);
protected void createParameterTree(PartitionOptions options, String name, String description, boolean isNodeHeight, double value) {
new Parameter.Builder(name, description).isNodeHeight(isNodeHeight).scaleType(PriorScaleType.TIME_SCALE)
.isNonNegative(true).initial(value).partitionOptions(options).build(parameters);
}
protected void createAllMusParameter(PartitionOptions options, String name, String description) {
new Parameter.Builder(name, description).partitionOptions(options).build(parameters);
}
public Parameter getParameter(String name) {
Parameter parameter = parameters.get(name);
if (parameter == null) {
throw new IllegalArgumentException("Parameter with name, " + name + ", is unknown");
}
parameter.setPrefix(getPrefix());
autoScale(parameter); // not include clock rate, and treeModel.rootHeight
return parameter;
}
public Operator getOperator(String name) {
Operator operator = operators.get(name);
if (operator == null) throw new IllegalArgumentException("Operator with name, " + name + ", is unknown");
operator.setPrefix(getPrefix());
return operator;
}
public String getName() {
return partitionName;
}
public void setName(String name) {
this.partitionName = name;
}
public String toString() {
return getName();
}
public DataType getDataType() {
if (options.getDataPartitions(this).size() == 0) {
return Nucleotides.INSTANCE;
}
return options.getDataPartitions(this).get(0).getDataType();
}
public double[] getAvgRootAndRate() {
return avgRootAndRate;
}
public void setAvgRootAndRate() {
this.avgRootAndRate = options.clockModelOptions.calculateInitialRootHeightAndRate(options.getDataPartitions(this));
}
protected void autoScale(Parameter param) {
double avgInitialRootHeight = avgRootAndRate[0];
double avgInitialRate = avgRootAndRate[1];
// double growthRateMaximum = 1E6;
double birthRateMaximum = 1E6;
// double substitutionRateMaximum = 100;
// double logStdevMaximum = 10;
// double substitutionParameterMaximum = 100;
// if (options.clockModelOptions.getRateOptionClockModel() == FixRateType.FIX_MEAN
// || options.clockModelOptions.getRateOptionClockModel() == FixRateType.RELATIVE_TO) {
// growthRateMaximum = 1E6 * avgInitialRate;
birthRateMaximum = 1E6 * avgInitialRate;
// if (options.clockModelOptions.getRateOptionClockModel() == FixRateType.FIX_MEAN) {
// double rate = options.clockModelOptions.getMeanRelativeRate();
// growthRateMaximum = 1E6 * rate;
// birthRateMaximum = 1E6 * rate;
// if (options.hasData()) {
// initialRootHeight = meanDistance / rate;
// initialRootHeight = round(initialRootHeight, 2);
// } else {
// if (options.maximumTipHeight > 0) {
// initialRootHeight = options.maximumTipHeight * 10.0;
// initialRate = round((meanDistance * 0.2) / initialRootHeight, 2);
// double timeScaleMaximum = MathUtils.round(avgInitialRootHeight * 1000.0, 2);
// if (!options.hasData()) param.setPriorEdited(false);
if (!param.isPriorEdited()) {
switch (param.scaleType) {
case TIME_SCALE:
// param.lower = Math.max(0.0, param.lower);
// param.upper = Math.min(timeScaleMaximum, param.upper);
// if (param.isNodeHeight) { //TODO only affecting "treeModel.rootHeight", need to review
// param.lower = options.maximumTipHeight;
//// param.upper = timeScaleMaximum;
//// param.initial = avgInitialRootHeight;
// if (param.getOptions() instanceof PartitionTreeModel) { // move to PartitionTreeModel
// param.initial = ((PartitionTreeModel) param.getOptions()).getInitialRootHeight();
// } else {
param.initial = avgInitialRootHeight;
break;
case LOG_TIME_SCALE:
param.initial = Math.log(avgInitialRootHeight);
break;
case T50_SCALE:
// param.lower = Math.max(0.0, param.lower);
//param.upper = Math.min(timeScaleMaximum, param.upper);
param.initial = avgInitialRootHeight / 5.0;
break;
case GROWTH_RATE_SCALE:
param.initial = avgInitialRootHeight / 1000;
// use Laplace
if (param.getBaseName().startsWith("logistic")) {
param.scale = Math.log(1000) / avgInitialRootHeight;
// System.out.println("logistic");
} else {
param.scale = Math.log(10000) / avgInitialRootHeight;
// System.out.println("not logistic");
}
break;
case BIRTH_RATE_SCALE:
// param.uniformLower = Math.max(0.0, param.lower);
// param.uniformUpper = Math.min(birthRateMaximum, param.upper);
param.initial = MathUtils.round(1 / options.treeModelOptions.getExpectedAvgBranchLength(avgInitialRootHeight), 2);
break;
case ORIGIN_SCALE:
param.initial = MathUtils.round(avgInitialRootHeight * 1.1, 2);
break;
case SUBSTITUTION_RATE_SCALE:
// param.lower = Math.max(0.0, param.lower);
//param.upper = Math.min(substitutionRateMaximum, param.upper);
param.initial = avgInitialRate;
break;
case LOG_STDEV_SCALE:
// param.lower = Math.max(0.0, param.lower);
//param.upper = Math.min(logStdevMaximum, param.upper);
break;
case SUBSTITUTION_PARAMETER_SCALE:
// param.lower = Math.max(0.0, param.lower);
//param.upper = Math.min(substitutionParameterMaximum, param.upper);
break;
// Now have a field 'isZeroOne'
// case UNITY_SCALE:
// param.lower = 0.0;
// param.upper = 1.0;
// break;
case ROOT_RATE_SCALE:
param.initial = avgInitialRate;
param.shape = 0.5;
param.scale = param.initial / 0.5;
break;
case LOG_VAR_SCALE:
param.initial = avgInitialRate;
param.shape = 2.0;
param.scale = param.initial / 2.0;
break;
}
}
}
public BeautiOptions getOptions() {
return options;
}
}
|
package ductive.console.shell;
import java.io.IOException;
import java.io.PrintStream;
import javax.inject.Provider;
import org.apache.commons.lang3.StringUtils;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.Ansi.Color;
import ductive.commons.Names;
import ductive.console.commands.parser.CmdParser;
import ductive.console.commands.parser.model.CommandLine;
import ductive.console.commands.register.CommandContext;
import ductive.console.commands.register.CommandInvoker;
import ductive.console.config.StandardPromptProvider;
import ductive.parse.errors.NoMatchException;
import jline.console.UserInterruptException;
public class EmbeddedAppShell implements Shell {
private static final Ansi DEFAULT_STANDARD_PROMPT = new Ansi().reset().bold().fg(Color.MAGENTA).a("app> ").reset();
private static final String HISTORY_KEY = Names.from(EmbeddedAppShell.class,"history");
private CommandInvoker commandInvoker;
private HistoryProvider historyProvider;
private Provider<CmdParser> cmdParserProvider;
private StandardPromptProvider standardPromptProvider = new StandardPromptProvider() {
@Override public Ansi get() {
return DEFAULT_STANDARD_PROMPT;
}
};
@Override
public void execute(InteractiveTerminal terminal, TerminalUser user) throws IOException {
CmdParser cmdParser = cmdParserProvider.get();
try( ShellHistory history = historyProvider.history(HISTORY_KEY) ) {
ShellSettings settings = new StaticShellSettings(standardPromptProvider,cmdParser,history);
terminal.updateSettings(settings);
while (true) {
Integer result = execute(cmdParser,terminal,history,user);
if(result != null)
break;
}
}
}
private Integer execute(CmdParser cmdParser, InteractiveTerminal terminal, ShellHistory history, TerminalUser user) throws IOException {
final CommandLine line;
try {
String command = terminal.readLine();
if (command == null)
return 0;
if (StringUtils.isBlank(command))
return null;
line = cmdParser.parse(command);
} catch(NoMatchException e) {
terminal.errorln(e.getMessage());
return null;
}
try {
commandInvoker.execute(new CommandContext(terminal,user),line);
} catch(UserInterruptException e) {
} catch (Throwable e) {
// Unroll invoker exceptions
if (e.getClass().getCanonicalName().equals("org.codehaus.groovy.runtime.InvokerInvocationException")) {
e = e.getCause();
}
PrintStream ps = new PrintStream(terminal.error());
e.printStackTrace(ps);
ps.flush();
}
return null;
}
public void setCmdParserProvider(Provider<CmdParser> cmdParserProvider) {
this.cmdParserProvider = cmdParserProvider;
}
public void setCommandInvoker(CommandInvoker commandInvoker) {
this.commandInvoker = commandInvoker;
}
public void setHistoryProvider(HistoryProvider historyProvider) {
this.historyProvider = historyProvider;
}
public void setStandardPromptProvider(StandardPromptProvider standardPromptProvider) {
this.standardPromptProvider = standardPromptProvider;
}
}
|
package edu.jhu.hltcoe.parse.cky;
import edu.jhu.hltcoe.parse.cky.chart.Chart;
import edu.jhu.hltcoe.parse.cky.chart.Chart.ChartCellType;
import edu.jhu.hltcoe.parse.cky.chart.ChartCell;
import edu.jhu.hltcoe.parse.cky.chart.ScoresSnapshot;
/**
* CKY Parsing algorithm for a CNF PCFG grammar.
*
* Currently running at 0.075 seconds per sentence for the first 200 sentences of
* WSJ section 24 with LoopOrder.LEFT_CHILD and CellType.FULL. This is about
* twice as fast as the exhaustive bubs-parser "ecpccl", though slightly slower
* than the reported times in (Dunlop et al. 2010).
*
* With chart caching we run slightly faster at: 0.067 seconds per sentence.
*
* @author mgormley
*
*/
public class CkyPcfgParser {
public static class CkyPcfgParserPrm {
// Whether or not to cache the chart cells between calls to the parser.
public boolean cacheChart = true;
public LoopOrder loopOrder = LoopOrder.LEFT_CHILD;
public ChartCellType cellType = ChartCellType.FULL;
}
public enum LoopOrder { LEFT_CHILD, RIGHT_CHILD, CARTESIAN_PRODUCT }
private Chart chart;
// These are private final just to ensure that they are never slow accesses.
private final LoopOrder loopOrder;
private final ChartCellType cellType;
private final boolean cacheChart;
public CkyPcfgParser(CkyPcfgParserPrm prm) {
this.loopOrder = prm.loopOrder;
this.cellType = prm.cellType;
this.cacheChart = prm.cacheChart;
}
// TODO: This would require proper handling of alphabets.
// @Deprecated
// public final Chart parseSentence(final Sentence sentence, final CnfGrammar grammar) {
// // TODO: assert sentence.getAlphabet() == grammar.getLexAlphabet();
// int[] sent = sentence.getLabelIds();
// return parseSentence(sent, grammar);
public final Chart parseSentence(final int[] sent, final CnfGrammar grammar) {
if (!cacheChart || chart == null || chart.getGrammar() != grammar) {
// Construct a new chart.
chart = new Chart(sent, grammar, cellType);
} else {
// If it already exists, just reset it for efficiency.
chart.reset(sent);
}
parseSentence(sent, grammar, loopOrder, chart);
return chart;
}
/**
* Runs CKY and populates the chart.
*
* @param sent The input sentence.
* @param grammar The input grammar.
* @param loopOrder The loop order to use when parsing.
* @param chart The output chart.
*/
public static final void parseSentence(final int[] sent, final CnfGrammar grammar, final LoopOrder loopOrder, final Chart chart) {
// Apply lexical rules to each word.
for (int i = 0; i <= sent.length - 1; i++) {
ChartCell cell = chart.getCell(i, i+1);
for (final Rule r : grammar.getLexicalRulesWithChild(sent[i])) {
double score = r.getScore();
cell.updateCell(i+1, r, score);
}
}
// For each cell in the chart.
for (int width = 1; width <= sent.length; width++) {
for (int start = 0; start <= sent.length - width; start++) {
int end = start + width;
ChartCell cell = chart.getCell(start, end);
// Apply binary rules.
if (loopOrder == LoopOrder.CARTESIAN_PRODUCT) {
processCellCartesianProduct(grammar, chart, start, end, cell);
} else if (loopOrder == LoopOrder.LEFT_CHILD) {
processCellLeftChild(grammar, chart, start, end, cell);
} else if (loopOrder == LoopOrder.RIGHT_CHILD) {
processCellRightChild(grammar, chart, start, end, cell);
} else {
throw new RuntimeException("Not implemented: " + loopOrder);
}
// Apply unary rules.
ScoresSnapshot scoresSnapshot = cell.getScoresSnapshot();
int[] nts = cell.getNts();
for(final int parentNt : nts) {
for (final Rule r : grammar.getUnaryRulesWithChild(parentNt)) {
double score = r.getScore() + scoresSnapshot.getScore(r.getLeftChild());
cell.updateCell(end, r, score);
}
}
cell.close();
}
}
}
/**
* Process a cell (binary rules only) using the Cartesian product of the children's rules.
*
* This follows the description in (Dunlop et al., 2010).
*/
private static final void processCellCartesianProduct(CnfGrammar grammar, Chart chart, int start,
int end, ChartCell cell) {
// Apply binary rules.
for (int mid = start + 1; mid <= end - 1; mid++) {
ChartCell leftCell = chart.getCell(start, mid);
ChartCell rightCell = chart.getCell(mid, end);
// Loop through all possible pairs of left/right non-terminals.
for (final int leftChildNt : leftCell.getNts()) {
double leftScoreForNt = leftCell.getScore(leftChildNt);
for (final int rightChildNt : rightCell.getNts()) {
double rightScoreForNt = rightCell.getScore(rightChildNt);
// Lookup the rules with those left/right children.
for (final Rule r : grammar.getBinaryRulesWithChildren(leftChildNt, rightChildNt)) {
double score = r.getScore()
+ leftScoreForNt
+ rightScoreForNt;
cell.updateCell(mid, r, score);
}
}
}
}
}
/**
* Process a cell (binary rules only) using the left-child to constrain the set of rules we consider.
*
* This follows the description in (Dunlop et al., 2010).
*/
private static final void processCellLeftChild(CnfGrammar grammar, Chart chart, int start,
int end, ChartCell cell) {
// Apply binary rules.
for (int mid = start + 1; mid <= end - 1; mid++) {
ChartCell leftCell = chart.getCell(start, mid);
ChartCell rightCell = chart.getCell(mid, end);
// Loop through each left child non-terminal.
for (final int leftChildNt : leftCell.getNts()) {
double leftScoreForNt = leftCell.getScore(leftChildNt);
// Lookup all rules with that left child.
for (final Rule r : grammar.getBinaryRulesWithLeftChild(leftChildNt)) {
// Check whether the right child of that rule is in the right child cell.
double rightScoreForNt = rightCell.getScore(r.getRightChild());
if (rightScoreForNt > Double.NEGATIVE_INFINITY) {
double score = r.getScore()
+ leftScoreForNt
+ rightScoreForNt;
cell.updateCell(mid, r, score);
}
}
}
}
}
/**
* Process a cell (binary rules only) using the left-child to constrain the set of rules we consider.
*
* This follows the description in (Dunlop et al., 2010).
*/
private static final void processCellRightChild(CnfGrammar grammar, Chart chart, int start,
int end, ChartCell cell) {
// Apply binary rules.
for (int mid = start + 1; mid <= end - 1; mid++) {
ChartCell leftCell = chart.getCell(start, mid);
ChartCell rightCell = chart.getCell(mid, end);
// Loop through each right child non-terminal.
for (final int rightChildNt : rightCell.getNts()) {
double rightScoreForNt = rightCell.getScore(rightChildNt);
// Lookup all rules with that right child.
for (final Rule r : grammar.getBinaryRulesWithRightChild(rightChildNt)) {
// Check whether the left child of that rule is in the left child cell.
double leftScoreForNt = leftCell.getScore(r.getLeftChild());
if (leftScoreForNt > Double.NEGATIVE_INFINITY) {
double score = r.getScore()
+ leftScoreForNt
+ rightScoreForNt;
cell.updateCell(mid, r, score);
}
}
}
}
}
}
|
package eu.visualize.ini.convnet;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.TreeMap;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.awt.GLCanvas;
import com.jogamp.opengl.glu.GLU;
import com.jogamp.opengl.glu.GLUquadric;
import com.jogamp.opengl.util.awt.TextRenderer;
import eu.seebetter.ini.chips.DavisChip;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventio.AEFileInputStream;
import net.sf.jaer.eventio.AEInputStream;
import net.sf.jaer.eventprocessing.EventFilter2DMouseAdaptor;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
/**
* Labels location of target using mouse GUI in recorded data for later
* supervised learning.
*
* @author tobi
*/
@DevelopmentStatus(DevelopmentStatus.Status.Stable)
@Description("Labels location of target using mouse GUI in recorded data for later supervised learning.")
public class TargetLabeler extends EventFilter2DMouseAdaptor implements PropertyChangeListener, KeyListener {
private boolean mousePressed = false;
private boolean shiftPressed = false;
private boolean ctlPressed = false;
private Point mousePoint = null;
final float labelRadius = 5f;
private GLUquadric mouseQuad = null;
private TreeMap<Integer, SimultaneouTargetLocations> targetLocations = new TreeMap();
private TargetLocation targetLocation = null;
private DavisChip apsDvsChip = null;
private int lastFrameNumber = -1;
private int lastTimestamp = Integer.MIN_VALUE;
private int currentFrameNumber = -1;
private final String LAST_FOLDER_KEY = "lastFolder";
TextRenderer textRenderer = null;
private int minTargetPointIntervalUs = getInt("minTargetPointIntervalUs", 2000);
private int targetRadius = getInt("targetRadius", 10);
private int maxTimeLastTargetLocationValidUs = getInt("maxTimeLastTargetLocationValidUs", 50000);
private int minSampleTimestamp = Integer.MAX_VALUE, maxSampleTimestamp = Integer.MIN_VALUE;
private final int N_FRACTIONS = 1000;
private boolean[] labeledFractions = new boolean[N_FRACTIONS]; // to annotate graphically what has been labeled so far in event stream
private boolean[] targetPresentInFractions = new boolean[N_FRACTIONS]; // to annotate graphically what has been labeled so far in event stream
private boolean showLabeledFraction = getBoolean("showLabeledFraction", true);
private boolean showHelpText = getBoolean("showHelpText", true);
// protected int maxTargets = getInt("maxTargets", 8);
protected int currentTargetTypeID = getInt("currentTargetTypeID", 0);
private ArrayList<TargetLocation> currentTargets = new ArrayList(10); // currently valid targets
protected boolean eraseSamplesEnabled = false;
private HashMap<String, String> mapDataFilenameToTargetFilename = new HashMap();
private boolean propertyChangeListenerAdded = false;
private String DEFAULT_FILENAME = "locations.txt";
private String lastFileName = getString("lastFileName", DEFAULT_FILENAME);
protected boolean showStatistics = getBoolean("showStatistics", true);
private String lastDataFilename = null;
private boolean locationsLoadedFromFile = false;
// file statistics
private long firstInputStreamTimestamp = 0, lastInputStreamTimestamp = 0, inputStreamDuration = 0;
private long filePositionEvents = 0, fileLengthEvents = 0;
private int filePositionTimestamp = 0;
private boolean warnSave = true;
public TargetLabeler(AEChip chip) {
super(chip);
if (chip instanceof DavisChip) {
apsDvsChip = ((DavisChip) chip);
}
setPropertyTooltip("minTargetPointIntervalUs", "minimum interval between target positions in the database in us");
setPropertyTooltip("targetRadius", "drawn radius of target in pixels");
setPropertyTooltip("maxTimeLastTargetLocationValidUs", "this time after last sample, the data is shown as not yet been labeled. This time specifies how long a specified target location is valid after its last specified location.");
setPropertyTooltip("saveLocations", "saves target locations");
setPropertyTooltip("saveLocationsAs", "show file dialog to save target locations to a new file");
setPropertyTooltip("loadLocations", "loads locations from a file");
setPropertyTooltip("clearLocations", "clears all existing targets");
setPropertyTooltip("resampleLabeling", "resamples the existing labeling to fill in null locations for unlabeled parts and fills in copies of latest location between samples, to specified minTargetPointIntervalUs");
setPropertyTooltip("showLabeledFraction", "shows labeled part of input by a bar with red=unlabeled, green=labeled, blue=current position");
setPropertyTooltip("showHelpText", "shows help text on screen. Uncheck to hide");
setPropertyTooltip("showStatistics", "shows statistics");
// setPropertyTooltip("maxTargets", "maximum number of simultaneous targets to label");
setPropertyTooltip("currentTargetTypeID", "ID code of current target to be labeled, e.g., 0=dog, 1=cat, etc. User must keep track of the mapping from ID codes to target classes.");
setPropertyTooltip("eraseSamplesEnabled", "Use this mode erase all samples up to minTargetPointIntervalUs before current time.");
Arrays.fill(labeledFractions, false);
Arrays.fill(targetPresentInFractions, false);
try {
byte[] bytes = getPrefs().getByteArray("TargetLabeler.hashmap", null);
if (bytes != null) {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
mapDataFilenameToTargetFilename = (HashMap<String, String>) in.readObject();
in.close();
log.info("loaded mapDataFilenameToTargetFilename: " + mapDataFilenameToTargetFilename.size() + " entries");
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void mouseDragged(MouseEvent e) {
Point p = (getMousePixel(e));
if (p != null) {
if (mousePoint != null) {
mousePoint.setLocation(p);
} else {
mousePoint = new Point(p);
}
} else {
mousePoint = null;
}
}
@Override
public void mouseReleased(MouseEvent e) {
mousePressed = false;
}
@Override
public void mousePressed(MouseEvent e) {
mouseMoved(e);
}
@Override
public void mouseMoved(MouseEvent e) {
Point p = (getMousePixel(e));
if (p != null) {
if (mousePoint != null) {
mousePoint.setLocation(p);
} else {
mousePoint = new Point(p);
}
} else {
mousePoint = null;
}
}
@Override
synchronized public void annotate(GLAutoDrawable drawable) {
if (!isFilterEnabled()) {
return;
}
if (chip.getAeViewer().getPlayMode() != AEViewer.PlayMode.PLAYBACK) {
return;
}
GL2 gl = drawable.getGL().getGL2();
chipCanvas = chip.getCanvas();
if (chipCanvas == null) {
return;
}
glCanvas = (GLCanvas) chipCanvas.getCanvas();
if (glCanvas == null) {
return;
}
glu=GLU.createGLU(gl); // TODO check if this solves problem of bad GL context in file preview
if (isSelected()) {
Point mp = glCanvas.getMousePosition();
Point p = chipCanvas.getPixelFromPoint(mp);
if (p == null) {
return;
}
checkBlend(gl);
float[] compArray = new float[4];
gl.glColor3fv(targetTypeColors[currentTargetTypeID % targetTypeColors.length].getColorComponents(compArray), 0);
gl.glLineWidth(3f);
gl.glPushMatrix();
gl.glTranslatef(p.x, p.y, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glEnd();
gl.glTranslatef(.5f, -.5f, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glEnd();
// if (quad == null) {
// quad = glu.gluNewQuadric();
// glu.gluQuadricDrawStyle(quad, GLU.GLU_FILL);
// glu.gluDisk(quad, 0, 3, 32, 1);
gl.glPopMatrix();
}
if (textRenderer == null) {
textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 36));
textRenderer.setColor(1, 1, 1, 1);
}
MultilineAnnotationTextRenderer.setColor(Color.CYAN);
MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .9f);
MultilineAnnotationTextRenderer.setScale(.3f);
StringBuilder sb = new StringBuilder();
if (showHelpText) {
sb.append("Shift + !Ctrl + mouse position: Specify no target present\n i.e. mark data as looked at\nClt + Shift + mouse position: Specify currentTargetTypeID is present at mouse location\n");
MultilineAnnotationTextRenderer.renderMultilineString(sb.toString());
}
if (showStatistics) {
MultilineAnnotationTextRenderer.renderMultilineString(String.format("%d TargetLocation labels specified\nFirst label time: %.1fs, Last label time: %.1fs\nCurrent frame number: %d\nCurrent # labels within maxTimeLastTargetLocationValidUs: %d",
targetLocations.size(),
minSampleTimestamp * 1e-6f,
maxSampleTimestamp * 1e-6f, getCurrentFrameNumber(),
currentTargets.size()));
if (shiftPressed && !ctlPressed) {
MultilineAnnotationTextRenderer.renderMultilineString("Specifying no target");
} else if (shiftPressed && ctlPressed) {
MultilineAnnotationTextRenderer.renderMultilineString("Specifying target location");
} else {
MultilineAnnotationTextRenderer.renderMultilineString("Playing recorded target locations");
}
}
for (TargetLocation t : currentTargets) {
if (t.location != null) {
t.draw(drawable, gl);
}
}
// show labeled parts
if (showLabeledFraction && (inputStreamDuration > 0)) {
float dx = chip.getSizeX() / (float) N_FRACTIONS;
float y = chip.getSizeY() / 5;
float dy = chip.getSizeY() / 50;
float x = 0;
for (int i = 0; i < N_FRACTIONS; i++) {
boolean b = labeledFractions[i];
if (b) {
gl.glColor3f(0, 1, 0);
} else {
gl.glColor3f(1, 0, 0);
}
gl.glRectf(x - (dx / 2), y, x + (dx / 2), y + (dy * (1 + (targetPresentInFractions[i] ? 1 : 0))));
// gl.glRectf(x-dx/2, y, x + dx/2, y + dy * (1 + (currentTargets.size())));
x += dx;
}
float curPosFrac = ((float) (filePositionTimestamp - firstInputStreamTimestamp) / inputStreamDuration);
x = curPosFrac * chip.getSizeX();
y = y + dy;
gl.glColor3f(1, 1, 1);
gl.glRectf(x - (dx / 2), y - (dy * 2), x + (dx / 2), y + dy);
}
}
synchronized public void doClearLocations() {
targetLocations.clear();
minSampleTimestamp = Integer.MAX_VALUE;
maxSampleTimestamp = Integer.MIN_VALUE;
Arrays.fill(labeledFractions, false);
Arrays.fill(targetPresentInFractions, false);
currentTargets.clear();
locationsLoadedFromFile = false;
}
synchronized public void doSaveLocationsAs() {
String fn = mapDataFilenameToTargetFilename.get(lastDataFilename);
if (fn == null) {
fn = DEFAULT_FILENAME;
}
JFileChooser c = new JFileChooser(fn);
c.setSelectedFile(new File(fn));
int ret = c.showSaveDialog(glCanvas);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
lastFileName = c.getSelectedFile().toString();
// end filename with -targets.txt
File f = c.getSelectedFile();
String s = f.getPath();
if (!s.endsWith("-targets.txt")) {
int idxdot = s.lastIndexOf('.');
if (idxdot > 0) {
s = s.substring(0, idxdot);
}
s = s + "-targets.txt";
f = new File(s);
}
if (f.exists()) {
int r = JOptionPane.showConfirmDialog(glCanvas, "File " + f.toString() + " already exists, overwrite it?");
if (r != JOptionPane.OK_OPTION) {
return;
}
}
lastFileName = f.toString();
putString("lastFileName", lastFileName);
saveLocations(f);
warnSave = false;
}
public void doResampleLabeling() {
if (targetLocations == null) {
log.warning("null targetLocations - nothing to resample");
return;
}
if (chip.getAeViewer().getAePlayer().getAEInputStream() == null) {
log.warning("cannot label unless a file is being played back");
return;
}
if (targetLocations.size() == 0) {
log.warning("no locations labeled - will label entire recording with no visible targets");
}
Map.Entry<Integer, SimultaneouTargetLocations> prevTargets = targetLocations.firstEntry();
TreeMap<Integer, SimultaneouTargetLocations> newTargets = new TreeMap();
if (prevTargets != null) {
for (Map.Entry<Integer, SimultaneouTargetLocations> nextTargets : targetLocations.entrySet()) { // for each existing set of targets by timestamp key list
// if no label at all for minTargetPointIntervalUs, then add copy of last labels up to maxTimeLastTargetLocationValidUs,
// then add null labels after that
if ((nextTargets.getKey() - prevTargets.getKey()) > minTargetPointIntervalUs) {
int n = (nextTargets.getKey() - prevTargets.getKey()) / minTargetPointIntervalUs; // add this many total
int tCopy = prevTargets.getKey() + maxTimeLastTargetLocationValidUs; // add this many total
for (int i = 0; i < n; i++) {
int ts = prevTargets.getKey() + ((i + 1) * minTargetPointIntervalUs);
newTargets.put(ts, copyLocationsToNewTs(prevTargets.getValue(), ts, ts <= tCopy));
}
}
prevTargets = nextTargets;
}
}
// handle time after last label
AEFileInputStream fileInputStream=chip.getAeViewer().getAePlayer().getAEInputStream();
int tFirstLabel = prevTargets != null ? prevTargets.getKey() : fileInputStream.getFirstTimestamp();
int tLastLabel = fileInputStream.getLastTimestamp(); // TODO handle wrapped timestamp during recording
int frameNumber = prevTargets != null ? prevTargets.getValue().get(0).frameNumber : -1;
int n = (tLastLabel-tFirstLabel) / minTargetPointIntervalUs; // add this many total
for (int i = 0; i < n; i++) {
SimultaneouTargetLocations s = new SimultaneouTargetLocations();
int ts = tFirstLabel + ((i + 1) * minTargetPointIntervalUs);
TargetLocation addedNullLabel = new TargetLocation(frameNumber, ts, null, targetRadius, -1, -1);
s.add(addedNullLabel);
newTargets.put(ts, s);
}
targetLocations.putAll(newTargets);
fixLabeledFraction();
}
private SimultaneouTargetLocations copyLocationsToNewTs(SimultaneouTargetLocations src, int ts, boolean useOriginalLocation) {
SimultaneouTargetLocations s = new SimultaneouTargetLocations();
for (TargetLocation t : src) {
TargetLocation tNew = new TargetLocation(t.frameNumber, ts, useOriginalLocation ? t.location : null, targetRadius, t.dimx, t.dimy);
s.add(tNew);
}
return s;
}
synchronized public void doSaveLocations() {
if (warnSave) {
int ret = JOptionPane.showConfirmDialog(chip.getAeViewer().getFilterFrame(), "Really overwrite " + lastFileName + " ?", "Overwrite warning", JOptionPane.WARNING_MESSAGE);
if (ret != JOptionPane.YES_OPTION) {
log.info("save canceled");
return;
}
}
File f = new File(lastFileName);
saveLocations(new File(lastFileName));
}
synchronized public void doLoadLocations() {
if (lastFileName == null) {
lastFileName = mapDataFilenameToTargetFilename.get(lastDataFilename);
}
if (lastFileName == null) {
lastFileName = DEFAULT_FILENAME;
}
if ((lastFileName != null) && lastFileName.equals(DEFAULT_FILENAME)) {
File f = chip.getAeViewer().getRecentFiles().getMostRecentFile();
if (f == null) {
lastFileName = DEFAULT_FILENAME;
} else {
lastFileName = f.getPath();
}
}
JFileChooser c = new JFileChooser(lastFileName);
c.setFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt");
}
@Override
public String getDescription() {
return "Text target label files";
}
});
c.setMultiSelectionEnabled(false);
c.setSelectedFile(new File(lastFileName));
int ret = c.showOpenDialog(glCanvas);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
lastFileName = c.getSelectedFile().toString();
putString("lastFileName", lastFileName);
loadLocations(new File(lastFileName));
}
private TargetLocation lastNewTargetLocation = null;
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
if (chip.getAeViewer().getPlayMode() != AEViewer.PlayMode.PLAYBACK) {
return in;
}
if (!propertyChangeListenerAdded) {
if (chip.getAeViewer() != null) {
chip.getAeViewer().addPropertyChangeListener(this);
propertyChangeListenerAdded = true;
}
}
// currentTargets.clear();
for (BasicEvent e : in) {
if (e.isSpecial()) {
continue;
}
if (apsDvsChip != null) {
// update actual frame number, starting from 0 at start of recording (for playback or after rewind)
// this can be messed up by jumping in the file using slider
int newFrameNumber = apsDvsChip.getFrameCount();
if (newFrameNumber != lastFrameNumber) {
if (newFrameNumber > lastFrameNumber) {
currentFrameNumber++;
} else if (newFrameNumber < lastFrameNumber) {
currentFrameNumber
}
lastFrameNumber = newFrameNumber;
}
if (((long) e.timestamp - (long) lastTimestamp) >= minTargetPointIntervalUs) {
// show the nearest TargetLocation if at least minTargetPointIntervalUs has passed by,
// or "No target" if the location was previously
Map.Entry<Integer, SimultaneouTargetLocations> mostRecentTargetsBeforeThisEvent = targetLocations.lowerEntry(e.timestamp);
if (mostRecentTargetsBeforeThisEvent != null) {
for (TargetLocation t : mostRecentTargetsBeforeThisEvent.getValue()) {
if ((t == null) || ((t != null) && ((e.timestamp - t.timestamp) > maxTimeLastTargetLocationValidUs))) {
targetLocation = null;
} else if (targetLocation != t) {
targetLocation = t;
currentTargets.add(targetLocation);
markDataHasTarget(targetLocation.timestamp, targetLocation.location != null);
}
}
}
lastTimestamp = e.timestamp;
// find next saved target location that is just before this time (lowerEntry)
TargetLocation newTargetLocation = null;
if (shiftPressed && ctlPressed && (mousePoint != null)) { // specify (additional) target present
// add a labeled location sample
maybeEraseSamples(mostRecentTargetsBeforeThisEvent);
newTargetLocation = new TargetLocation(getCurrentFrameNumber(), e.timestamp, mousePoint, currentTargetTypeID, targetRadius, targetRadius);
addSample(e.timestamp, newTargetLocation);
currentTargets.add(newTargetLocation);
} else if (shiftPressed && !ctlPressed) { // specify no target present now but mark recording as reviewed
maybeEraseSamples(mostRecentTargetsBeforeThisEvent);
newTargetLocation = new TargetLocation(getCurrentFrameNumber(), e.timestamp, null, currentTargetTypeID, targetRadius, targetRadius);
addSample(e.timestamp, newTargetLocation);
// markDataReviewedButNoTargetPresent(e.timestamp);
}
if (newTargetLocation != null) {
if (newTargetLocation.timestamp > maxSampleTimestamp) {
maxSampleTimestamp = newTargetLocation.timestamp;
}
if (newTargetLocation.timestamp < minSampleTimestamp) {
minSampleTimestamp = newTargetLocation.timestamp;
}
}
lastNewTargetLocation = newTargetLocation;
}
if (e.timestamp < lastTimestamp) {
lastTimestamp = e.timestamp;
}
}
}
//prune list of current targets to their valid lifetime, and remove leftover targets in the future
ArrayList<TargetLocation> removeList = new ArrayList();
for (TargetLocation t : currentTargets) {
if (((t.timestamp + maxTimeLastTargetLocationValidUs) < in.getLastTimestamp()) || (t.timestamp > in.getLastTimestamp())) {
removeList.add(t);
}
}
currentTargets.removeAll(removeList);
return in;
}
private void maybeEraseSamples(Map.Entry<Integer, SimultaneouTargetLocations> entry) {
if (!isEraseSamplesEnabled() || (entry == null)) {
return;
}
targetLocations.remove(entry.getKey());
fixLabeledFraction();
}
@Override
public void setSelected(boolean yes) {
super.setSelected(yes); // register/deregister mouse listeners
if (yes) {
glCanvas.addKeyListener(this);
} else {
glCanvas.removeKeyListener(this);
}
}
@Override
public void resetFilter() {
}
@Override
public void initFilter() {
}
/**
* @return the minTargetPointIntervalUs
*/
public int getMinTargetPointIntervalUs() {
return minTargetPointIntervalUs;
}
/**
* @param minTargetPointIntervalUs the minTargetPointIntervalUs to set
*/
public void setMinTargetPointIntervalUs(int minTargetPointIntervalUs) {
this.minTargetPointIntervalUs = minTargetPointIntervalUs;
putInt("minTargetPointIntervalUs", minTargetPointIntervalUs);
}
@Override
public void keyTyped(KeyEvent ke) {
// forward space and b (toggle direction of playback) to AEPlayer
int k = ke.getKeyChar();
// log.info("keyChar=" + k + " keyEvent=" + ke.toString());
if (shiftPressed || ctlPressed) { // only forward to AEViewer if we are blocking ordinary input to AEViewer by labeling
switch (k) {
case KeyEvent.VK_SPACE:
chip.getAeViewer().setPaused(!chip.getAeViewer().isPaused());
break;
case KeyEvent.VK_B:
case 2:
chip.getAeViewer().getAePlayer().toggleDirection();
break;
case 'F':
case 6:
chip.getAeViewer().getAePlayer().speedUp();
break;
case 'S':
case 19:
chip.getAeViewer().getAePlayer().slowDown();
break;
}
}
}
@Override
public void keyPressed(KeyEvent ke) {
int k = ke.getKeyCode();
if (k == KeyEvent.VK_SHIFT) {
shiftPressed = true;
} else if (k == KeyEvent.VK_CONTROL) {
ctlPressed = true;
} else if (k == KeyEvent.VK_E) {
setEraseSamplesEnabled(true);
}
}
@Override
public void keyReleased(KeyEvent ke) {
int k = ke.getKeyCode();
if (k == KeyEvent.VK_SHIFT) {
shiftPressed = false;
} else if (k == KeyEvent.VK_CONTROL) {
ctlPressed = false;
} else if (k == KeyEvent.VK_E) {
setEraseSamplesEnabled(false);
}
}
/**
* @return the targetRadius
*/
public int getTargetRadius() {
return targetRadius;
}
/**
* @param targetRadius the targetRadius to set
*/
public void setTargetRadius(int targetRadius) {
this.targetRadius = targetRadius;
putInt("targetRadius", targetRadius);
}
/**
* @return the maxTimeLastTargetLocationValidUs
*/
public int getMaxTimeLastTargetLocationValidUs() {
return maxTimeLastTargetLocationValidUs;
}
/**
* @param maxTimeLastTargetLocationValidUs the
* maxTimeLastTargetLocationValidUs to set
*/
public void setMaxTimeLastTargetLocationValidUs(int maxTimeLastTargetLocationValidUs) {
if (maxTimeLastTargetLocationValidUs < minTargetPointIntervalUs) {
maxTimeLastTargetLocationValidUs = minTargetPointIntervalUs;
}
this.maxTimeLastTargetLocationValidUs = maxTimeLastTargetLocationValidUs;
putInt("maxTimeLastTargetLocationValidUs", maxTimeLastTargetLocationValidUs);
}
/**
* Returns true if any locations are specified already. However if there are
* no targets at all visible then also returns false.
*
*
* @return true if there are locations specified
* @see #isLocationsLoadedFromFile()
*/
public boolean hasLocations() {
return !targetLocations.isEmpty();
}
/**
* Returns the last target location
*
* @return the targetLocation
*/
public TargetLocation getTargetLocation() {
return targetLocation;
}
private void addSample(int timestamp, TargetLocation newTargetLocation) {
SimultaneouTargetLocations s = targetLocations.get(timestamp);
if (s == null) {
s = new SimultaneouTargetLocations();
targetLocations.put(timestamp, s);
}
s.add(newTargetLocation);
}
private int getFractionOfFileDuration(int timestamp) {
if (inputStreamDuration == 0) {
return 0;
}
return (int) Math.floor((N_FRACTIONS * ((float) (timestamp - firstInputStreamTimestamp))) / inputStreamDuration);
}
private class TargetLocationComparator implements Comparator<TargetLocation> {
@Override
public int compare(TargetLocation o1, TargetLocation o2) {
return Integer.valueOf(o1.frameNumber).compareTo(Integer.valueOf(o2.frameNumber));
}
}
private final Color[] targetTypeColors = {Color.BLUE, Color.CYAN, Color.GREEN, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED};
/**
* List of targets simultaneously present at a particular timestamp
*/
private class SimultaneouTargetLocations extends ArrayList<TargetLocation> {
boolean hasTargetWithLocation() {
for (TargetLocation t : this) {
if (t.location != null) {
return true;
}
}
return false;
}
}
class TargetLocation {
int timestamp;
int frameNumber;
Point location; // center of target location
int targetClassID; // class of target, i.e. car, person
int dimx; // dimension of target x
int dimy;
public TargetLocation(int frameNumber, int timestamp, Point location, int targetTypeID, int dimx, int dimy) {
this.frameNumber = frameNumber;
this.timestamp = timestamp;
this.location = location != null ? new Point(location) : null;
this.targetClassID = targetTypeID;
this.dimx = dimx;
this.dimy = dimy;
}
private void draw(GLAutoDrawable drawable, GL2 gl) {
// if (getTargetLocation() != null && getTargetLocation().location == null) {
// textRenderer.beginRendering(drawable.getSurfaceWidth(), drawable.getSurfaceHeight());
// textRenderer.draw("Target not visible", chip.getSizeX() / 2, chip.getSizeY() / 2);
// textRenderer.endRendering();
// return;
gl.glPushMatrix();
gl.glTranslatef(location.x, location.y, 0f);
float[] compArray = new float[4];
gl.glColor3fv(targetTypeColors[targetClassID % targetTypeColors.length].getColorComponents(compArray), 0);
// gl.glColor4f(0, 1, 0, .5f);
if (mouseQuad == null) {
mouseQuad = glu.gluNewQuadric();
}
glu.gluQuadricDrawStyle(mouseQuad, GLU.GLU_LINE);
//glu.gluDisk(mouseQuad, getTargetRadius(), getTargetRadius(), 32, 1);
int maxDim = Math.max(dimx, dimy);
glu.gluDisk(mouseQuad, maxDim / 2, (maxDim / 2) + 0.1, 32, 1);
//getTargetRadius(), getTargetRadius() + 1, 32, 1);
gl.glPopMatrix();
}
@Override
public String toString() {
return String.format("TargetLocation frameNumber=%d timestamp=%d location=%s", frameNumber, timestamp, location == null ? "null" : location.toString());
}
}
private void saveLocations(File f) {
try {
FileWriter writer = new FileWriter(f);
writer.write(String.format("# target locations\n"));
writer.write(String.format("# written %s\n", new Date().toString()));
// writer.write("# maxTargets=" + maxTargets+"\n");
writer.write(String.format("# frameNumber timestamp x y targetTypeID\n"));
for (Map.Entry<Integer, SimultaneouTargetLocations> entry : targetLocations.entrySet()) {
for (TargetLocation l : entry.getValue()) {
if (l.location != null) {
writer.write(String.format("%d %d %d %d %d\n", l.frameNumber, l.timestamp, l.location.x, l.location.y, l.targetClassID, l.dimx, l.dimy));
} else {
writer.write(String.format("%d %d -1 -1 -1\n", l.frameNumber, l.timestamp));
}
}
}
writer.close();
log.info("wrote locations to file " + f.getAbsolutePath());
if (f.getPath() != null) {
mapDataFilenameToTargetFilename.put(lastDataFilename, f.getPath());
}
try {
// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput oos = new ObjectOutputStream(bos);
oos.writeObject(mapDataFilenameToTargetFilename);
oos.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
getPrefs().putByteArray("TargetLabeler.hashmap", buf);
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(glCanvas, ex.toString(), "Couldn't save locations", JOptionPane.WARNING_MESSAGE, null);
return;
}
}
/**
* Loads last locations. Note that this is a lengthy operation
*/
synchronized public void loadLastLocations() {
if (lastFileName == null) {
return;
}
File f = new File(lastFileName);
if (!f.exists() || !f.isFile()) {
return;
}
loadLocations(f);
}
synchronized private void loadLocations(File f) {
long startMs = System.currentTimeMillis();
log.info("loading " + f);
doClearLocations();
TargetLocation tmpTargetLocation = null;
try {
setCursor(new Cursor(Cursor.WAIT_CURSOR));
targetLocations.clear();
minSampleTimestamp = Integer.MAX_VALUE;
maxSampleTimestamp = Integer.MIN_VALUE;
try {
BufferedReader reader = new BufferedReader(new FileReader(f));
String s = reader.readLine();
StringBuilder sb = new StringBuilder();
while ((s != null) && s.startsWith("
sb.append(s + "\n");
s = reader.readLine();
}
log.info("header lines on " + f.getAbsolutePath() + " are\n" + sb.toString());
Scanner scanner = new Scanner(reader);
while (scanner.hasNext()) {
try {
int frame = scanner.nextInt();
int ts = scanner.nextInt();
int x = scanner.nextInt();
int y = scanner.nextInt();
int targetTypeID = 0;
int targetdimx = targetRadius;
int targetdimy = targetRadius;
// see if more tokens in this line
String mt = scanner.findInLine("\\d+");
if (mt != null) {
targetTypeID = Integer.parseInt(scanner.match().group());
}
mt = scanner.findInLine("\\d+");
if (mt != null) {
targetdimx = Integer.parseInt(scanner.match().group());
}
mt = scanner.findInLine("\\d+");
if (mt != null) {
targetdimy = Integer.parseInt(scanner.match().group());
}
tmpTargetLocation = new TargetLocation(frame, ts,
new Point(x, y),
targetTypeID,
targetdimx,
targetdimy); // read target location
} catch (NoSuchElementException ex2) {
throw new IOException(("couldn't parse file " + f) == null ? "null" : f.toString() + ", got InputMismatchException on line: " + s);
}
if ((tmpTargetLocation.location.x == -1) && (tmpTargetLocation.location.y == -1)) {
tmpTargetLocation.location = null;
}
addSample(tmpTargetLocation.timestamp, tmpTargetLocation);
markDataHasTarget(tmpTargetLocation.timestamp, tmpTargetLocation.location != null);
if (tmpTargetLocation != null) {
if (tmpTargetLocation.timestamp > maxSampleTimestamp) {
maxSampleTimestamp = tmpTargetLocation.timestamp;
}
if (tmpTargetLocation.timestamp < minSampleTimestamp) {
minSampleTimestamp = tmpTargetLocation.timestamp;
}
}
}
long endMs = System.currentTimeMillis();
log.info("Took " + (endMs - startMs) + " ms to load " + f + " with " + targetLocations.size() + " SimultaneouTargetLocations entries");
if (lastDataFilename != null) {
mapDataFilenameToTargetFilename.put(lastDataFilename, f.getPath());
}
this.targetLocation = null; // null out current location
locationsLoadedFromFile = true;
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(glCanvas, ("couldn't find file " + f) == null ? "null" : f.toString() + ": got exception " + ex.toString(), "Couldn't load locations", JOptionPane.WARNING_MESSAGE, null);
} catch (IOException ex) {
JOptionPane.showMessageDialog(glCanvas, ("IOException with file " + f) == null ? "null" : f.toString() + ": got exception " + ex.toString(), "Couldn't load locations", JOptionPane.WARNING_MESSAGE, null);
}
} finally {
setCursor(Cursor.getDefaultCursor());
}
fixLabeledFraction();
}
int maxDataHasTargetWarningCount = 10;
/**
* marks this point in time as reviewed already
*
* @param timestamp
*/
private void markDataReviewedButNoTargetPresent(int timestamp) {
if (inputStreamDuration == 0) {
return;
}
int frac = getFractionOfFileDuration(timestamp);
labeledFractions[frac] = true;
targetPresentInFractions[frac] = false;
}
private void markDataHasTarget(int timestamp, boolean visible) {
if (inputStreamDuration == 0) {
return;
}
int frac = getFractionOfFileDuration(timestamp);
if ((frac < 0) || (frac >= labeledFractions.length)) {
if (maxDataHasTargetWarningCount
log.warning("fraction " + frac + " is out of range " + labeledFractions.length + ", something is wrong");
}
if (maxDataHasTargetWarningCount == 0) {
log.warning("suppressing futher warnings");
}
return;
}
labeledFractions[frac] = true;
targetPresentInFractions[frac] = visible;
}
private void fixLabeledFraction() {
if (chip.getAeInputStream() != null) {
firstInputStreamTimestamp = chip.getAeInputStream().getFirstTimestamp();
lastTimestamp = chip.getAeInputStream().getLastTimestamp();
inputStreamDuration = chip.getAeInputStream().getDurationUs();
fileLengthEvents = chip.getAeInputStream().size();
if (inputStreamDuration > 0) {
if ((targetLocations == null) || targetLocations.isEmpty()) {
Arrays.fill(labeledFractions, false);
return;
}
for (Map.Entry<Integer, SimultaneouTargetLocations> t : targetLocations.entrySet()) {
markDataHasTarget(t.getKey(), t.getValue().hasTargetWithLocation());
}
}
}
}
/**
* @return the showLabeledFraction
*/
public boolean isShowLabeledFraction() {
return showLabeledFraction;
}
/**
* @param showLabeledFraction the showLabeledFraction to set
*/
public void setShowLabeledFraction(boolean showLabeledFraction) {
this.showLabeledFraction = showLabeledFraction;
putBoolean("showLabeledFraction", showLabeledFraction);
}
/**
* @return the showHelpText
*/
public boolean isShowHelpText() {
return showHelpText;
}
/**
* @param showHelpText the showHelpText to set
*/
public void setShowHelpText(boolean showHelpText) {
this.showHelpText = showHelpText;
putBoolean("showHelpText", showHelpText);
}
@Override
public synchronized void setFilterEnabled(boolean yes) {
super.setFilterEnabled(yes); //To change body of generated methods, choose Tools | Templates.
fixLabeledFraction();
}
// /**
// * @return the maxTargets
// */
// public int getMaxTargets() {
// return maxTargets;
// /**
// * @param maxTargets the maxTargets to set
// */
// public void setMaxTargets(int maxTargets) {
// this.maxTargets = maxTargets;
/**
* @return the currentTargetTypeID
*/
public int getCurrentTargetTypeID() {
return currentTargetTypeID;
}
/**
* @param currentTargetTypeID the currentTargetTypeID to set
*/
public void setCurrentTargetTypeID(int currentTargetTypeID) {
// if (currentTargetTypeID >= maxTargets) {
// currentTargetTypeID = maxTargets;
this.currentTargetTypeID = currentTargetTypeID;
putInt("currentTargetTypeID", currentTargetTypeID);
}
/**
* @return the eraseSamplesEnabled
*/
public boolean isEraseSamplesEnabled() {
return eraseSamplesEnabled;
}
/**
* @param eraseSamplesEnabled the eraseSamplesEnabled to set
*/
public void setEraseSamplesEnabled(boolean eraseSamplesEnabled) {
boolean old = this.eraseSamplesEnabled;
this.eraseSamplesEnabled = eraseSamplesEnabled;
getSupport().firePropertyChange("eraseSamplesEnabled", old, this.eraseSamplesEnabled);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
switch (evt.getPropertyName()) {
case AEInputStream.EVENT_POSITION:
filePositionEvents = (long) evt.getNewValue();
if ((chip.getAeViewer().getAePlayer() == null) || (chip.getAeViewer().getAePlayer().getAEInputStream() == null)) {
log.warning("null input stream, cannot get most recent timestamp");
return;
}
filePositionTimestamp = chip.getAeViewer().getAePlayer().getAEInputStream().getMostRecentTimestamp();
break;
case AEInputStream.EVENT_REWIND:
case AEInputStream.EVENT_REPOSITIONED:
// log.info("rewind to start or mark position or reposition event " + evt.toString());
if (evt.getNewValue() instanceof Long) {
long position = (long) evt.getNewValue();
if (chip.getAeInputStream() == null) {
log.warning("AE input stream is null, cannot determine timestamp after rewind");
return;
}
int timestamp = chip.getAeInputStream().getMostRecentTimestamp();
Map.Entry<Integer, SimultaneouTargetLocations> targetsBeforeRewind = targetLocations.lowerEntry(timestamp);
if (targetsBeforeRewind != null) {
currentFrameNumber = targetsBeforeRewind.getValue().get(0).frameNumber;
lastFrameNumber = getCurrentFrameNumber() - 1;
lastTimestamp = targetsBeforeRewind.getValue().get(0).timestamp;
} else {
currentFrameNumber = 0;
lastFrameNumber = getCurrentFrameNumber() - 1;
lastInputStreamTimestamp = Integer.MIN_VALUE;
}
} else {
log.warning("couldn't determine stream position after rewind from PropertyChangeEvent " + evt.toString());
}
break;
case AEInputStream.EVENT_INIT:
fixLabeledFraction();
warnSave = true;
if (evt.getNewValue() instanceof AEFileInputStream) {
File f = ((AEFileInputStream) evt.getNewValue()).getFile();
lastDataFilename = f.getPath();
}
break;
}
}
/**
* @return the showStatistics
*/
public boolean isShowStatistics() {
return showStatistics;
}
/**
* @param showStatistics the showStatistics to set
*/
public void setShowStatistics(boolean showStatistics) {
this.showStatistics = showStatistics;
putBoolean("showStatistics", showStatistics);
}
/**
* @return the currentFrameNumber
*/
public int getCurrentFrameNumber() {
return currentFrameNumber;
}
/**
* False until locations are loaded from a file. Reset by clearLocations.
*
* @return the locationsLoadedFromFile true if data was loaded from a file
* successfully
*/
public boolean isLocationsLoadedFromFile() {
return locationsLoadedFromFile;
}
}
|
package org.voltdb;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import org.voltdb.types.TimestampType;
import org.voltdb.types.VoltDecimalHelper;
import org.voltdb.utils.Encoder;
/**
* ParameterConverter provides a static helper to convert a deserialized
* procedure invocation parameter to the correct Object required by a
* stored procedure's parameter type.
*
*/
public class ParameterConverter {
/**
* @throws Exception with a message describing why the types are incompatible.
*/
public static Object tryToMakeCompatible(
final boolean isPrimitive,
final boolean isArray,
final Class<?> paramType,
final Class<?> paramTypeComponentType,
final Object param)
throws Exception
{
if (param == null ||
param == VoltType.NULL_STRING_OR_VARBINARY ||
param == VoltType.NULL_DECIMAL)
{
if (isPrimitive) {
VoltType type = VoltType.typeFromClass(paramType);
switch (type) {
case TINYINT:
case SMALLINT:
case INTEGER:
case BIGINT:
case FLOAT:
return type.getNullValue();
}
}
// Pass null reference to the procedure run() method. These null values will be
// converted to a serialize-able NULL representation for the EE in getCleanParams()
// when the parameters are serialized for the plan fragment.
return null;
}
if (param instanceof ExecutionSite.SystemProcedureExecutionContext) {
return param;
}
Class<?> pclass = param.getClass();
// hack to make strings work with input as byte[]
if ((paramType == String.class) && (pclass == byte[].class)) {
String sparam = null;
sparam = new String((byte[]) param, "UTF-8");
return sparam;
}
// hack to make varbinary work with input as string
if ((paramType == byte[].class) && (pclass == String.class)) {
return Encoder.hexDecode((String) param);
}
if (isArray != pclass.isArray()) {
throw new Exception("Array / Scalar parameter mismatch");
}
if (isArray) {
Class<?> pSubCls = pclass.getComponentType();
Class<?> sSubCls = paramTypeComponentType;
if (pSubCls == sSubCls) {
return param;
}
// if it's an empty array, let it through
// this is a bit ugly as it might hide passing
// arrays of the wrong type, but it "does the right thing"
// more often that not I guess...
else if (Array.getLength(param) == 0) {
return Array.newInstance(sSubCls, 0);
}
else {
/*
* Arrays can be quite large so it doesn't make sense to silently do the conversion
* and incur the performance hit. The client should serialize the correct invocation
* parameters
*/
throw new Exception(
"tryScalarMakeCompatible: Unable to match parameter array:"
+ sSubCls.getName() + " to provided " + pSubCls.getName());
}
}
/*
* inline tryScalarMakeCompatible so we can save on reflection
*/
final Class<?> slot = paramType;
if ((slot == long.class) && (pclass == Long.class || pclass == Integer.class || pclass == Short.class || pclass == Byte.class)) return param;
if ((slot == int.class) && (pclass == Integer.class || pclass == Short.class || pclass == Byte.class)) return param;
if ((slot == short.class) && (pclass == Short.class || pclass == Byte.class)) return param;
if ((slot == byte.class) && (pclass == Byte.class)) return param;
if ((slot == double.class) && (param instanceof Number)) return ((Number)param).doubleValue();
if ((slot == String.class) && (pclass == String.class)) return param;
if (slot == TimestampType.class) {
if (pclass == Long.class) return new TimestampType((Long)param);
if (pclass == TimestampType.class) return param;
if (pclass == Date.class) return new TimestampType((Date) param);
// if a string is given for a date, use java's JDBC parsing
if (pclass == String.class) {
try {
return new TimestampType((String)param);
}
catch (IllegalArgumentException e) {
throw new Exception(
"tryToMakeCompatible: IllegalArgumentException was thrown -- the provided string (" +
(String)param + ") -- does not satisfy the TimestampType's JDBC format requirement.");
}
}
}
if (slot == BigDecimal.class) {
if ((pclass == Long.class) || (pclass == Integer.class) ||
(pclass == Short.class) || (pclass == Byte.class)) {
BigInteger bi = new BigInteger(param.toString());
BigDecimal bd = new BigDecimal(bi);
bd.setScale(4, BigDecimal.ROUND_HALF_EVEN);
return bd;
}
if (pclass == BigDecimal.class) {
BigDecimal bd = (BigDecimal) param;
bd.setScale(4, BigDecimal.ROUND_HALF_EVEN);
return bd;
}
if (pclass == String.class) {
BigDecimal bd = VoltDecimalHelper.deserializeBigDecimalFromString((String) param);
return bd;
}
}
if (slot == VoltTable.class && pclass == VoltTable.class) {
return param;
}
// handle truncation for integers
// Long targeting int parameter
if ((slot == int.class) && (pclass == Long.class)) {
long val = ((Number) param).longValue();
// if it's in the right range, and not null (target null), crop the value and return
if ((val <= Integer.MAX_VALUE) && (val >= Integer.MIN_VALUE) && (val != VoltType.NULL_INTEGER))
return ((Number) param).intValue();
}
// Long or Integer targeting short parameter
if ((slot == short.class) && (pclass == Long.class || pclass == Integer.class)) {
long val = ((Number) param).longValue();
// if it's in the right range, and not null (target null), crop the value and return
if ((val <= Short.MAX_VALUE) && (val >= Short.MIN_VALUE) && (val != VoltType.NULL_SMALLINT))
return ((Number) param).shortValue();
}
// Long, Integer or Short targeting byte parameter
if ((slot == byte.class) && (pclass == Long.class || pclass == Integer.class || pclass == Short.class)) {
long val = ((Number) param).longValue();
// if it's in the right range, and not null (target null), crop the value and return
if ((val <= Byte.MAX_VALUE) && (val >= Byte.MIN_VALUE) && (val != VoltType.NULL_TINYINT))
return ((Number) param).byteValue();
}
// Coerce strings to primitive numbers.
if (pclass == String.class) {
try {
if (slot == byte.class) {
return Byte.parseByte((String) param);
}
if (slot == short.class) {
return Short.parseShort((String) param);
}
if (slot == int.class) {
return Integer.parseInt((String) param);
}
if (slot == long.class) {
return Long.parseLong((String) param);
}
}
catch (NumberFormatException nfe) {
throw new Exception(
"tryToMakeCompatible: Unable to convert string "
+ (String)param + " to " + slot.getName()
+ " value for target parameter " + slot.getName());
}
}
throw new Exception(
"tryToMakeCompatible: Unable to match or convert to the type (" + slot.getName()
+ ") or value out of range for the target parameter from the provided " + pclass.getName()
+ " (" + param.toString() + ").");
}
/**
* Convert string inputs to Longs for TheHashinator if possible
* @param param
* @param slot
* @return Object parsed as Number or null if types not compatible
* @throws Exception if a parse error occurs (consistent with above).
*/
public static Object stringToLong(Object param, Class<?> slot)
throws Exception
{
try {
if (slot == byte.class ||
slot == short.class ||
slot == int.class ||
slot == long.class)
{
return Long.parseLong((String)param);
}
return null;
}
catch (NumberFormatException nfe) {
throw new Exception(
"tryToMakeCompatible: Unable to convert string "
+ (String)param + " to " + slot.getName()
+ " value for target parameter " + slot.getName());
}
}
}
|
package goryachev.fxdock.internal;
import goryachev.common.util.GlobalSettings;
import goryachev.common.util.SB;
import goryachev.common.util.SStream;
import goryachev.fxdock.FxDockFramework;
import goryachev.fxdock.FxDockPane;
import goryachev.fxdock.FxDockWindow;
import javafx.application.Platform;
import javafx.geometry.Orientation;
import javafx.scene.Node;
/**
* FxDock framework schema for the layout storage.
*/
public class FxDockSchema
{
public static final String PREFIX_DOCK = "fxdock.";
public static final String PREFIX_WINDOW = PREFIX_DOCK + "w.";
public static final String KEY_WINDOW_COUNT = PREFIX_WINDOW + "count";
public static final String NAME_PANE = ".P";
public static final String NAME_TAB = ".T";
public static final String NAME_SPLIT = ".S";
public static final String STAGE_FULL_SCEEN = "F";
public static final String STAGE_ICONIFIED = "I";
public static final String STAGE_MAXIMIZED = "X";
public static final String STAGE_NORMAL = "N";
public static final String SUFFIX_BINDINGS = ".bindings";
public static final String SUFFIX_LAYOUT = ".layout";
public static final String SUFFIX_SELECTED_TAB = ".tab";
public static final String SUFFIX_SPLITS = ".splits";
public static final String SUFFIX_WINDOW = ".window";
public static final String TYPE_EMPTY = "E";
public static final String TYPE_PANE = "P";
public static final String TYPE_HSPLIT = "H";
public static final String TYPE_VSPLIT = "V";
public static final String TYPE_TAB = "T";
public static int getWindowCount()
{
return GlobalSettings.getInt(KEY_WINDOW_COUNT, 0);
}
public static void setWindowCount(int n)
{
GlobalSettings.setInt(KEY_WINDOW_COUNT, n);
}
public static String windowID(int n)
{
return PREFIX_WINDOW + n;
}
public static void clearSettings()
{
// remove previously saved layout
for(String k: GlobalSettings.getKeys())
{
if(k.startsWith(PREFIX_WINDOW))
{
GlobalSettings.setString(k, null);
}
}
}
public static void storeWindow(String prefix, FxDockWindow w)
{
SStream s = new SStream();
s.add(w.getX());
s.add(w.getY());
s.add(w.getWidth());
s.add(w.getHeight());
if(w.isFullScreen())
{
s.add(STAGE_FULL_SCEEN);
}
else if(w.isMaximized())
{
s.add(STAGE_MAXIMIZED);
}
else if(w.isIconified())
{
s.add(STAGE_ICONIFIED);
}
else
{
s.add(STAGE_NORMAL);
}
GlobalSettings.setStream(prefix + SUFFIX_WINDOW, s);
}
public static void restoreWindow(String prefix, FxDockWindow w)
{
SStream s = GlobalSettings.getStream(prefix + SUFFIX_WINDOW);
if(s.size() == 5)
{
double x = s.nextDouble();
double y = s.nextDouble();
double width = s.nextDouble();
double h = s.nextDouble();
String t = s.nextString();
w.setX(x);
w.setY(y);
w.setWidth(width);
w.setHeight(h);
if(STAGE_FULL_SCEEN.equals(t))
{
w.setFullScreen(true);
}
else if(STAGE_MAXIMIZED.equals(t))
{
w.setMaximized(true);
}
else if(STAGE_ICONIFIED.equals(t))
{
w.setIconified(true);
}
}
}
public static Node loadLayout(String prefix)
{
SStream s = GlobalSettings.getStream(prefix + SUFFIX_LAYOUT);
return loadLayoutRecursively(s);
}
private static FxDockSplitPane loadSplit(SStream s, Orientation or)
{
FxDockSplitPane sp = new FxDockSplitPane();
sp.setOrientation(or);
int sz = s.nextInt();
for(int i=0; i<sz; i++)
{
Node ch = loadLayoutRecursively(s);
sp.addPane(ch);
}
return sp;
}
private static Node loadLayoutRecursively(SStream s)
{
String t = s.nextString();
if(t == null)
{
return null;
}
else if(TYPE_PANE.equals(t))
{
String type = s.nextString();
return FxDockFramework.createPane(type);
}
else if(TYPE_HSPLIT.equals(t))
{
return loadSplit(s, Orientation.HORIZONTAL);
}
else if(TYPE_VSPLIT.equals(t))
{
return loadSplit(s, Orientation.VERTICAL);
}
else if(TYPE_TAB.equals(t))
{
FxDockTabPane tp = new FxDockTabPane();
int sz = s.nextInt();
for(int i=0; i<sz; i++)
{
Node ch = loadLayoutRecursively(s);
tp.addTab(ch);
}
return tp;
}
else if(TYPE_EMPTY.equals(t))
{
return new FxDockEmptyPane();
}
else
{
return null;
}
}
public static void saveLayout(String prefix, Node n)
{
SStream s = saveLayoutPrivate(n);
GlobalSettings.setStream(prefix + SUFFIX_LAYOUT, s);
}
protected static SStream saveLayoutPrivate(Node content)
{
SStream s = new SStream();
saveLayoutRecursively(s, content);
return s;
}
private static void saveLayoutRecursively(SStream s, Node n)
{
if(n == null)
{
return;
}
else if(n instanceof FxDockPane)
{
String type = ((FxDockPane)n).getDockPaneType();
s.add(TYPE_PANE);
s.add(type);
}
else if(n instanceof FxDockSplitPane)
{
FxDockSplitPane sp = (FxDockSplitPane)n;
int ct = sp.getPaneCount();
Orientation or = sp.getOrientation();
s.add(or == Orientation.HORIZONTAL ? TYPE_HSPLIT : TYPE_VSPLIT);
s.add(ct);
for(Node ch: sp.getPanes())
{
saveLayoutRecursively(s, ch);
}
}
else if(n instanceof FxDockTabPane)
{
FxDockTabPane tp = (FxDockTabPane)n;
int ct = tp.getTabCount();
s.add(TYPE_TAB);
s.add(ct);
for(Node ch: tp.getPanes())
{
saveLayoutRecursively(s, ch);
}
}
else if(n instanceof FxDockEmptyPane)
{
s.add(TYPE_EMPTY);
}
else
{
throw new Error("?" + n);
}
}
public static String getPath(String prefix, Node n, String suffix)
{
SB sb = new SB(128);
sb.append(prefix);
getPathRecursive(sb, n);
if(suffix != null)
{
sb.a(suffix);
}
return sb.toString();
}
private static void getPathRecursive(SB sb, Node n)
{
Node p = DockTools.getParent(n);
if(p != null)
{
getPathRecursive(sb, p);
if(p instanceof FxDockSplitPane)
{
int ix = ((FxDockSplitPane)p).indexOfPane(n);
sb.a('.');
sb.a(ix);
}
else if(p instanceof FxDockTabPane)
{
int ix = ((FxDockTabPane)p).indexOfTab(n);
sb.a('.');
sb.a(ix);
}
}
if(n instanceof FxDockRootPane)
{
return;
}
else if(n instanceof FxDockSplitPane)
{
sb.a(NAME_SPLIT);
}
else if(n instanceof FxDockTabPane)
{
sb.a(NAME_TAB);
}
else if(n instanceof FxDockPane)
{
sb.a(NAME_PANE);
}
else
{
throw new Error("?" + n);
}
}
/**
* default functionality provided by the docking framework to load window content settings.
* what's being stored:
* - split positions
* - settings bindings
*/
public static void loadContentSettings(String prefix, Node n)
{
if(n != null)
{
if(n instanceof FxDockPane)
{
((FxDockPane)n).loadPaneSettings(prefix);
}
else if(n instanceof FxDockSplitPane)
{
FxDockSplitPane p = (FxDockSplitPane)n;
for(Node ch: p.getPanes())
{
loadContentSettings(prefix, ch);
}
// because of the split pane idiosyncrasy with layout
Platform.runLater(() -> loadSplitPaneSettings(prefix, p));
}
else if(n instanceof FxDockTabPane)
{
FxDockTabPane p = (FxDockTabPane)n;
loadTabPaneSettings(prefix, p);
for(Node ch: p.getPanes())
{
loadContentSettings(prefix, ch);
}
}
}
}
/**
* default functionality provided by the docking framework to store window content settings.
* what's being stored:
* - split positions
* - settings bindings
*/
public static void saveContentSettings(String prefix, Node n)
{
if(n != null)
{
if(n instanceof FxDockPane)
{
((FxDockPane)n).savePaneSettings(prefix);
}
else if(n instanceof FxDockSplitPane)
{
FxDockSplitPane p = (FxDockSplitPane)n;
saveSplitPaneSettings(prefix, p);
for(Node ch: p.getPanes())
{
saveContentSettings(prefix, ch);
}
}
else if(n instanceof FxDockTabPane)
{
FxDockTabPane p = (FxDockTabPane)n;
saveTabPaneSettings(prefix, p);
for(Node ch: p.getPanes())
{
saveContentSettings(prefix, ch);
}
}
}
}
private static void saveSplitPaneSettings(String prefix, FxDockSplitPane p)
{
double[] divs = p.getDividerPositions();
SStream s = new SStream();
s.addAll(divs);
String k = getPath(prefix, p, SUFFIX_SPLITS);
GlobalSettings.setStream(k, s);
}
private static void loadSplitPaneSettings(String prefix, FxDockSplitPane p)
{
String k = getPath(prefix, p, SUFFIX_SPLITS);
SStream s = GlobalSettings.getStream(k);
int ct = s.size();
if(p.getDividers().size() == ct)
{
for(int i=0; i<ct; i++)
{
double pos = s.nextDouble();
p.setDividerPosition(i, pos);
}
}
}
private static void saveTabPaneSettings(String prefix, FxDockTabPane p)
{
int ix = p.getSelectedTabIndex();
String k = getPath(prefix, p, SUFFIX_SELECTED_TAB);
GlobalSettings.setInt(k, ix);
}
private static void loadTabPaneSettings(String prefix, FxDockTabPane p)
{
String k = getPath(prefix, p, SUFFIX_SELECTED_TAB);
int ix = GlobalSettings.getInt(k, 0);
p.select(ix);
}
}
|
package gov.nih.nci.cananolab.util;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class ExcelParser {
private String fileName;
public ExcelParser(String fileName) {
this.fileName = fileName;
}
/**
* Vertically parse the Excel file into a 2-D matrix represented as a map of map.
* Key is Column header, value is a map, whose key is Row header and value is
* the cell.
*
* @return
* @throws IOException
*/
public SortedMap<String, SortedMap<String, Double>> verticalParse()
throws IOException {
InputStream inputStream = null;
SortedMap<String, SortedMap<String, Double>> dataMatrix = new TreeMap<String, SortedMap<String, Double>>();
try {
inputStream = new BufferedInputStream(new FileInputStream(fileName));
POIFSFileSystem fs = new POIFSFileSystem(inputStream);
Workbook wb = new HSSFWorkbook(fs);
Sheet sheet1 = wb.getSheetAt(0);
//printSheet(sheet1);
Row firstRow = sheet1.getRow(0);
int rowIndex = 0;
for (Row row : sheet1) {
int colIndex = 0;
String rowHeader = row.getCell(0).getStringCellValue();
for (Cell cell : row) {
if (rowIndex > 0 && colIndex > 0) { //skipping first row/column
String columnHeader = firstRow.getCell(colIndex)
.getStringCellValue();
SortedMap<String, Double> columnData = null;
if (dataMatrix.get(columnHeader) != null) {
columnData = dataMatrix.get(columnHeader);
} else {
columnData = new TreeMap<String, Double>();
}
if (cell != null) {
columnData.put(rowHeader, cell.getNumericCellValue());
dataMatrix.put(columnHeader, columnData);
}
}
colIndex++;
}
rowIndex++;
}
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
}
}
}
return dataMatrix;
}
/**
* Horizontal parse the Excel file into a 2-D matrix represented as a map of map.
* Key is Row header, value is a map, whose key is Column header and value is
* the cell.
*
* @return
* @throws IOException
*/
public SortedMap<String, SortedMap<String, Double>> horizontalParse()
throws IOException {
InputStream inputStream = null;
SortedMap<String, SortedMap<String, Double>> dataMatrix = new TreeMap<String, SortedMap<String, Double>>();
try {
inputStream = new BufferedInputStream(new FileInputStream(fileName));
POIFSFileSystem fs = new POIFSFileSystem(inputStream);
Workbook wb = new HSSFWorkbook(fs);
Sheet sheet1 = wb.getSheetAt(0);
//printSheet(sheet1);
Row firstRow = sheet1.getRow(0);
int rowIndex = 0;
for (Row row : sheet1) {
int colIndex = 0;
String rowHeader = row.getCell(0).getStringCellValue();
for (Cell cell : row) {
if (rowIndex > 0 && colIndex > 0) { //skipping first row/column
String columnHeader = firstRow.getCell(colIndex)
.getStringCellValue();
SortedMap<String, Double> rowData = null;
if (dataMatrix.get(rowHeader) != null) {
rowData = dataMatrix.get(rowHeader);
} else {
rowData = new TreeMap<String, Double>();
}
if (cell != null) {
rowData.put(columnHeader, cell.getNumericCellValue());
dataMatrix.put(rowHeader, rowData);
}
}
colIndex++;
}
rowIndex++;
}
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
}
}
}
return dataMatrix;
}
public void printSheet(Sheet sheet) {
for (Row row : sheet) {
for (Cell cell : row) {
CellReference cellRef = new CellReference(cell.getRowIndex(),
cell.getColumnIndex());
System.out.print(cellRef.formatAsString());
System.out.print(" - ");
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getRichStringCellValue()
.getString());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.println(cell.getDateCellValue());
} else {
System.out.println(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
System.out.println(cell.getCellFormula());
break;
default:
System.out.println();
}
}
}
}
public void printMatrix(
SortedMap<String, SortedMap<String, Double>> dataMatrix) {
for (String key : dataMatrix.keySet()) {
System.out.println("key:" + key);
Map<String, Double> data = dataMatrix.get(key);
for (Map.Entry<String, Double> entry : data.entrySet()) {
System.out.println("key-" + entry.getKey()+": "+entry.getValue());
}
}
}
public static void main(String[] args) {
if (args != null && args.length == 1) {
String inputFileName = args[0];
try {
ExcelParser parser = new ExcelParser(inputFileName);
SortedMap<String, SortedMap<String, Double>> matrix1 = parser
.verticalParse();
parser.printMatrix(matrix1);
SortedMap<String, SortedMap<String, Double>> matrix2 = parser
.horizontalParse();
parser.printMatrix(matrix2);
} catch (IOException e) {
System.out.println("Input file not found.");
e.printStackTrace();
System.exit(1);
}
} else {
System.out.println("Invalid argument!");
System.out.println("java ExcelParser <inputFileName>");
}
System.exit(0);
}
}
|
package com.threerings.gwt.ui;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.Widget;
/**
* Extends {@link FlexTable} and provides a fluent interface for adjusting the styles of cells.
*/
public class FluentTable extends FlexTable
{
/** Used to format cells. Returned by all methods that configure cells. */
public static class Cell
{
/** The row we're formatting. */
public final int row;
/** The column we're formatting. */
public final int column;
/** Sets the text of this cell to the string value of the supplied object. */
public Cell setText (Object text) {
_table.setText(row, column, String.valueOf(text));
return this;
}
/** Sets the HTML in this cell to the supplied value. Be careful! */
public Cell setHTML (String text) {
_table.setHTML(row, column, String.valueOf(text));
return this;
}
/** Sets the contents of this cell to the specified widget. */
public Cell setWidget (Widget widget) {
_table.setWidget(row, column, widget);
return this;
}
/** Sets the contents of this cell to a FlowPanel that contains the specified widgets. */
public Cell setWidgets (Widget... widgets) {
_table.setWidget(row, column, Widgets.newFlowPanel(widgets));
return this;
}
/** Makes the cell we're formatting align top. */
public Cell alignTop () {
_table.getFlexCellFormatter().setVerticalAlignment(
row, column, HasAlignment.ALIGN_TOP);
return this;
}
/** Makes the cell we're formatting align bottom. */
public Cell alignBottom () {
_table.getFlexCellFormatter().setVerticalAlignment(
row, column, HasAlignment.ALIGN_BOTTOM);
return this;
}
/** Makes the cell we're formatting align middle. */
public Cell alignMiddle () {
_table.getFlexCellFormatter().setVerticalAlignment(
row, column, HasAlignment.ALIGN_MIDDLE);
return this;
}
/** Makes the cell we're formatting align left. */
public Cell alignLeft () {
_table.getFlexCellFormatter().setHorizontalAlignment(
row, column, HasAlignment.ALIGN_LEFT);
return this;
}
/** Makes the cell we're formatting align right. */
public Cell alignRight () {
_table.getFlexCellFormatter().setHorizontalAlignment(
row, column, HasAlignment.ALIGN_RIGHT);
return this;
}
/** Makes the cell we're formatting align center. */
public Cell alignCenter () {
_table.getFlexCellFormatter().setHorizontalAlignment(
row, column, HasAlignment.ALIGN_CENTER);
return this;
}
/** Sets the rowspan of the cell we're formatting. */
public Cell setRowSpan (int rowSpan) {
_table.getFlexCellFormatter().setRowSpan(row, column, rowSpan);
return this;
}
/** Sets the colspan of the cell we're formatting. */
public Cell setColSpan (int colSpan) {
_table.getFlexCellFormatter().setColSpan(row, column, colSpan);
return this;
}
/** Configures the specified style names on our cell. The first style is set as the primary
* style and additional styles are added onto that. */
public Cell setStyles (String... styles)
{
int idx = 0;
for (String style : styles) {
if (idx++ == 0) {
_table.getFlexCellFormatter().setStyleName(row, column, style);
} else {
_table.getFlexCellFormatter().addStyleName(row, column, style);
}
}
return this;
}
protected Cell (FluentTable table, int row, int column)
{
_table = table;
this.row = row;
this.column = column;
}
protected FluentTable _table;
}
/**
* Creates an empty table with no styles and the default cell padding and spacing.
*/
public FluentTable ()
{
}
/**
* Creates a table with the specified styles and the default cell padding and spacing.
*/
public FluentTable (String... styles)
{
Widgets.setStyleNames(this, styles);
}
/**
* Creates a table with the specified cell pading and spacing and no styles.
*/
public FluentTable (int cellPadding, int cellSpacing)
{
setCellPadding(cellPadding);
setCellSpacing(cellSpacing);
}
/**
* Creates a table with the specified styles and cell padding and spacing.
*/
public FluentTable (int cellPadding, int cellSpacing, String... styles)
{
this(styles);
setCellPadding(cellPadding);
setCellSpacing(cellSpacing);
}
/**
* Returns the specified cell.
*/
public Cell at (int row, int column)
{
return new Cell(this, row, column);
}
/**
* Returns a {@link Cell} at the current row count and column zero (effectively adding a row to
* the table).
*/
public Cell add ()
{
return new Cell(this, getRowCount(), 0);
}
}
|
// $Id: FrameManager.java,v 1.16 2002/08/23 20:22:09 mdb Exp $
package com.threerings.media;
import java.applet.Applet;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.image.BufferStrategy;
import java.awt.image.VolatileImage;
import java.awt.EventQueue;
import javax.swing.JComponent;
import javax.swing.JLayeredPane;
import javax.swing.RepaintManager;
import com.samskivert.util.Interval;
import com.samskivert.util.IntervalManager;
import com.samskivert.util.ObserverList;
import com.samskivert.util.StringUtil;
import com.threerings.media.util.PerformanceMonitor;
import com.threerings.media.util.PerformanceObserver;
/**
* Provides a central point from which the computation for each "frame" or
* tick can be dispatched. This assumed that the application structures
* its activity around the rendering of each frame, which is a common
* architecture for games. The animation and sprite support provided by
* other classes in this package are structured for use in an application
* that uses a frame manager to tick everything once per frame.
*
* <p> The frame manager goes through a simple two part procedure every
* frame:
*
* <ul>
* <li> Ticking all of the frame participants: in {@link
* FrameParticipant#tick}, any processing that need be performed during
* this frame should be performed. Care should be taken not to execute
* code that will take unduly long, instead such processing should be
* broken up so that it can be performed in small pieces every frame (or
* performed on a separate thread with the results safely communicated
* back to the frame participants for incorporation into the rendering
* loop).
*
* <li> Painting the user interface hierarchy: the top-level component
* (the frame) is painted (via a call to {@link Frame#paint}) into a flip
* buffer (if supported, an off-screen buffer if not). Updates that were
* computed during the tick should be rendered in this call to paint. The
* paint call will propagate down to all components in the UI hierarchy,
* some of which may be {@link FrameParticipant}s and will have prepared
* themselves for their upcoming painting in the previous call to {@link
* FrameParticipant#tick}. When the call to paint completes, the flip
* buffer is flipped and the process starts all over again. </ul>
*
* <p> The ticking and rendering takes place on the AWT thread so as to
* avoid the need for complicated coordination between AWT event handler
* code and frame code. However, this means that all AWT (and Swing) event
* handlers <em>must not</em> perform any complicated processing. After
* each frame, control of the AWT thread is given back to the AWT which
* processes all pending AWT events before giving the frame manager an
* opportunity to process the next frame. Thus the convenience of
* everything running on the AWT thread comes with the price of requiring
* that AWT event handlers not block or perform any intensive processing.
* In general, this is a sensible structure for an application anyhow, so
* this organization tends to be preferable to an organization where the
* AWT and frame threads are separate and must tread lightly so as not to
* collide.
*/
public class FrameManager
implements PerformanceObserver
{
/**
* Constructs a frame manager that will do its rendering to the
* supplied frame. It is likely that the caller will want to have put
* the frame into full-screen exclusive mode prior to providing it to
* the frame manager so that the frame manager can take advantage of
* optimizations available in that mode.
*
* @see GraphicsDevice#setFullScreenWindow
*/
public FrameManager (Frame frame)
{
_frame = frame;
_frame.setIgnoreRepaint(true);
// set up our custom repaint manager
_remgr = new FrameRepaintManager(_frame);
RepaintManager.setCurrentManager(_remgr);
// turn off double buffering for the whole business because we
// handle repaints
_remgr.setDoubleBufferingEnabled(false);
// register with the performance monitor
PerformanceMonitor.register(this, "frame-rate", 1000l);
}
/**
* Instructs the frame manager to target the specified number of
* frames per second. If the computation and rendering for a frame are
* completed with time to spare, the frame manager will wait until the
* proper time to begin processing for the next frame. If a frame
* takes longer than its alotted time, the frame manager will
* immediately begin processing on the next frame.
*/
public void setTargetFrameRate (int fps)
{
// compute the number of milliseconds per frame
_millisPerFrame = 1000/fps;
}
/**
* Registers a frame participant. The participant will be given the
* opportunity to do processing and rendering on each frame.
*/
public void registerFrameParticipant (FrameParticipant participant)
{
_participants.add(participant);
}
/**
* Removes a frame participant.
*/
public void removeFrameParticipant (FrameParticipant participant)
{
_participants.remove(participant);
}
/**
* Starts up the per-frame tick
*/
public void start ()
{
if (_ticker == null) {
// create ticker for queueing up tick requests on AWT thread
_ticker = new Ticker();
// and start it up
_ticker.start();
// and kick off our first frame
_ticker.tickIn(_millisPerFrame, System.currentTimeMillis());
}
}
/**
* Stops the per-frame tick.
*/
public synchronized void stop ()
{
if (_ticker != null) {
_ticker = null;
}
}
/**
* Returns true if the tick interval is be running (not necessarily at
* that instant, but in general).
*/
public synchronized boolean isRunning ()
{
return (_ticker != null);
}
/**
* Called to perform the frame processing and rendering.
*/
protected void tick ()
{
// if our frame is not showing (or is impossibly sized), don't try
// rendering anything
if (_frame.isShowing() &&
_frame.getWidth() > 0 && _frame.getHeight() > 0) {
long tickStamp = System.currentTimeMillis();
// tick our participants
tickParticipants(tickStamp);
// repaint our participants
paintParticipants(tickStamp);
}
// now determine how many milliseconds we have left before we need
// to start the next frame (if any)
long end = System.currentTimeMillis();
long duration = end - _frameStart;
long remaining = _millisPerFrame - duration;
// note that we've done a frame
PerformanceMonitor.tick(this, "frame-rate");
// if we have no time remaining, queue up another tick immediately
if (remaining <= 0) {
// make a note that we're starting our next frame now
_frameStart = end;
EventQueue.invokeLater(_callTick);
} else {
// otherwise queue one up in the requisite number of millis
_ticker.tickIn(remaining, end);
}
}
/**
* Called once per frame to invoke {@link FrameParticipant#tick} on
* all of our frame participants.
*/
protected void tickParticipants (long tickStamp)
{
// validate any invalid components
try {
_remgr.validateComponents();
} catch (Throwable t) {
Log.warning("Failure validating components.");
Log.logStackTrace(t);
}
// tick all of our frame participants
_participantTickOp.setTickStamp(tickStamp);
_participants.apply(_participantTickOp);
}
/**
* Called once per frame to invoke {@link Component#paint} on all of
* our frame participants' components.
*/
protected void paintParticipants (long tickStamp)
{
// // create our buffer strategy if we don't already have one
// if (_bufstrat == null) {
// _frame.createBufferStrategy(2);
// _bufstrat = _frame.getBufferStrategy();
// start out assuming we can do an incremental render
boolean incremental = true;
do {
GraphicsConfiguration gc = _frame.getGraphicsConfiguration();
// create our off-screen buffer if necessary
if (_backimg == null) {
createBackBuffer(gc);
}
// make sure our back buffer hasn't disappeared
int valres = _backimg.validate(gc);
// if we've changed resolutions, recreate the buffer
if (valres == VolatileImage.IMAGE_INCOMPATIBLE) {
// Log.info("Back buffer incompatible, recreating.");
createBackBuffer(gc);
}
// if the image wasn't A-OK, we need to rerender the whole
// business rather than just the dirty parts
if (valres != VolatileImage.IMAGE_OK) {
// Log.info("Lost back buffer, redrawing.");
incremental = false;
}
// g = _bufstrat.getDrawGraphics();
// dirty everything if we're not incrementally rendering
if (!incremental) {
_frame.update(_bgfx);
}
// paint our frame participants (which want to be handled
// specially)
_participantPaintOp.setGraphics(_bgfx);
_participants.apply(_participantPaintOp);
// repaint any widgets that have declared there need to be
// repainted since the last tick
_remgr.paintComponents(_bgfx, this);
// we cache our frame's graphics object so that we can avoid
// instantiating a new one on every tick
if (_fgfx == null) {
_fgfx = _frame.getGraphics();
}
_fgfx.drawImage(_backimg, 0, 0, null);
// _bufstrat.show();
// if we loop through a second time, we'll need to rerender
// everything
incremental = false;
} while (_backimg.contentsLost());
}
/**
* Renders all components in all {@link JLayeredPane} layers that
* intersect the supplied bounds.
*/
protected void renderLayers (Graphics g, Component pcomp, Rectangle bounds,
boolean[] clipped)
{
JLayeredPane lpane =
JLayeredPane.getLayeredPaneAbove(pcomp);
if (lpane != null) {
renderLayer(g, bounds, lpane, clipped, JLayeredPane.PALETTE_LAYER);
renderLayer(g, bounds, lpane, clipped, JLayeredPane.MODAL_LAYER);
renderLayer(g, bounds, lpane, clipped, JLayeredPane.POPUP_LAYER);
renderLayer(g, bounds, lpane, clipped, JLayeredPane.DRAG_LAYER);
}
}
/**
* Renders all components in the specified layer of the supplied
* layered pane that intersect the supplied bounds.
*/
protected void renderLayer (Graphics g, Rectangle bounds, JLayeredPane pane,
boolean[] clipped, Integer layer)
{
// stop now if there are no components in that layer
int ccount = pane.getComponentCountInLayer(layer.intValue());
if (ccount == 0) {
return;
}
// render them up
Component[] comps = pane.getComponentsInLayer(layer.intValue());
for (int ii = 0; ii < ccount; ii++) {
Component comp = comps[ii];
_lbounds.setBounds(0, 0, comp.getWidth(), comp.getHeight());
getRoot(comp, _lbounds);
if (!_lbounds.intersects(bounds)) {
continue;
}
// if the clipping region has not yet been set during this
// render pass, the time has come to do so
if (!clipped[0]) {
g.setClip(bounds);
clipped[0] = true;
}
// translate into the components coordinate system and render
g.translate(_lbounds.x, _lbounds.y);
comp.paint(g);
g.translate(-_lbounds.x, -_lbounds.y);
}
}
// documentation inherited
public void checkpoint (String name, int ticks)
{
// Log.info("Frames in last second: " + ticks);
}
/**
* Used to queue up frame ticks on the AWT thread at some point in the
* future.
*/
protected class Ticker extends Thread
{
/**
* Tells the ticker to queue up a frame in the requisite number of
* milliseconds.
*/
public synchronized void tickIn (long millis, long now)
{
_sleepfor = millis;
_now = now;
this.notify();
}
public void run ()
{
synchronized (this) {
while (_sleepfor != -1) {
try {
if (_sleepfor == 0) {
this.wait();
}
if (_sleepfor > 0) {
Thread.sleep(_sleepfor);
// make a note of our frame start time
_frameStart = System.currentTimeMillis();
// long error =_frameStart - (_sleepfor + _now);
// if (Math.abs(error) > 3) {
// Log.warning("Funny business: " + error);
// queue up our ticker on the AWT thread
EventQueue.invokeLater(_callTick);
_sleepfor = 0;
}
} catch (InterruptedException ie) {
Log.warning("Girl interrupted!");
}
}
}
}
protected long _sleepfor = 0l;
protected long _now = 0l;
}
/**
* Creates the off-screen buffer used to perform double buffered
* rendering of the animated panel.
*/
protected void createBackBuffer (GraphicsConfiguration gc)
{
// if we have an old image, clear it out
if (_backimg != null) {
_backimg.flush();
_bgfx.dispose();
}
// create the offscreen buffer
int width = _frame.getWidth(), height = _frame.getHeight();
_backimg = gc.createCompatibleVolatileImage(width, height);
// fill the back buffer with white
_bgfx = _backimg.getGraphics();
_bgfx.fillRect(0, 0, width, height);
// clear out our frame graphics in case that became invalid for
// the same reasons our back buffer became invalid
_fgfx = null;
}
/**
* Returns the root component for the supplied component or null if it
* is not part of a rooted hierarchy or if any parent along the way is
* found to be hidden or without a peer. Along the way, it adjusts the
* supplied component-relative rectangle to be relative to the
* returned root component.
*/
public static Component getRoot (Component comp, Rectangle rect)
{
for (Component c = comp; c != null; c = c.getParent()) {
if (!c.isVisible() || !c.isDisplayable()) {
return null;
}
if (c instanceof Window || c instanceof Applet) {
return c;
}
rect.x += c.getX();
rect.y += c.getY();
}
return null;
}
/**
* An observer operation that calls {@link FrameParticipant#tick} with
* a specified tick stamp for all {@link FrameParticipant} objects in
* the observer list to which this operation is applied.
*/
protected class ParticipantTickOp
implements ObserverList.ObserverOp
{
/**
* Sets the tick stamp to be applied to the participants.
*/
public void setTickStamp (long tickStamp)
{
_tickStamp = tickStamp;
}
// documentation inherited
public boolean apply (Object observer)
{
try {
((FrameParticipant)observer).tick(_tickStamp);
} catch (Throwable t) {
Log.warning("Frame participant choked during tick " +
"[part=" +
StringUtil.safeToString(observer) + "].");
Log.logStackTrace(t);
}
return true;
}
/** The tick stamp to be applied to each frame participant. */
protected long _tickStamp;
}
/**
* An observer operation that paints the components associated with
* all {@link FrameParticipant} objects in the observer list to which
* this operation is applied.
*/
protected class ParticipantPaintOp
implements ObserverList.ObserverOp
{
/**
* Sets the graphics context to which the frame participants
* render themselves.
*/
public void setGraphics (Graphics g)
{
_g = g;
}
// documentation inherited
public boolean apply (Object observer)
{
FrameParticipant part = (FrameParticipant)observer;
Component pcomp = part.getComponent();
if (pcomp == null) {
return true;
}
// get the bounds of this component
pcomp.getBounds(_bounds);
// the bounds adjustment we're about to call will add in the
// components initial bounds offsets, so we remove them here
_bounds.setLocation(0, 0);
// convert them into top-level coordinates; also note that if
// this component does not have a valid or visible root, we
// don't want to paint it either
if (getRoot(pcomp, _bounds) == null) {
return true;
}
try {
// render this participant; we don't set the clip because
// frame participants are expected to handle clipping
// themselves; otherwise we might pointlessly set the clip
// here, creating a few Rectangle objects in the process,
// only to have the frame participant immediately set the
// clip to something more sensible
_g.translate(_bounds.x, _bounds.y);
pcomp.paint(_g);
_g.translate(-_bounds.x, -_bounds.y);
} catch (Throwable t) {
String ptos = StringUtil.safeToString(part);
Log.warning("Frame participant choked during paint " +
"[part=" + ptos + "].");
Log.logStackTrace(t);
}
// render any components in our layered pane that are not in
// the default layer
_clipped[0] = false;
renderLayers(_g, pcomp, _bounds, _clipped);
return true;
}
/** The graphics context to which the participants render. */
protected Graphics _g;
/** A handy rectangle that we reuse time and again to avoid having
* to instantiate a new rectangle in the midst of the core
* rendering loop. */
protected Rectangle _bounds = new Rectangle();
}
/** The frame into which we do our rendering. */
protected Frame _frame;
/** Our custom repaint manager. */
protected FrameRepaintManager _remgr;
// /** The buffer strategy used to do our rendering. */
// protected BufferStrategy _bufstrat;
/** The image used to render off-screen. */
protected VolatileImage _backimg;
/** The number of milliseconds per frame (33 by default, which gives
* an fps of 30). */
protected long _millisPerFrame = 33;
/** The time at which we started the most recent "frame". */
protected long _frameStart;
/** Used to queue up a tick. */
protected Ticker _ticker;
/** The graphics object from our back buffer. */
protected Graphics _bgfx;
/** The graphics object from our frame. */
protected Graphics _fgfx;
/** Used to avoid creating rectangles when rendering layered
* components. */
protected Rectangle _lbounds = new Rectangle();
/** Used to lazily set the clip when painting popups and other
* "layered" components. */
protected boolean[] _clipped = new boolean[1];
/** Used to queue up a call to {@link #tick} on the AWT thread. */
protected Runnable _callTick = new Runnable () {
public void run () {
tick();
}
};
/** The entites that are ticked each frame. */
protected ObserverList _participants =
new ObserverList(ObserverList.FAST_UNSAFE_NOTIFY);
/** The observer operation applied to all frame participants each tick. */
protected ParticipantTickOp _participantTickOp = new ParticipantTickOp();
/** The observer operation applied to all frame participants each time
* the frame is rendered. */
protected ParticipantPaintOp _participantPaintOp = new ParticipantPaintOp();
}
|
// $Id: FrameManager.java,v 1.48 2003/12/13 02:59:05 mdb Exp $
package com.threerings.media;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.EventQueue;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.RepaintManager;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import com.samskivert.swing.Label;
import com.samskivert.util.DebugChords;
import com.samskivert.util.ObserverList;
import com.samskivert.util.RunAnywhere;
import com.samskivert.util.RuntimeAdjust;
import com.samskivert.util.StringUtil;
import com.threerings.media.timer.MediaTimer;
import com.threerings.media.timer.SystemMediaTimer;
import com.threerings.media.util.TrailingAverage;
import com.threerings.util.unsafe.Unsafe;
/**
* Provides a central point from which the computation for each "frame" or
* tick can be dispatched. This assumed that the application structures
* its activity around the rendering of each frame, which is a common
* architecture for games. The animation and sprite support provided by
* other classes in this package are structured for use in an application
* that uses a frame manager to tick everything once per frame.
*
* <p> The frame manager goes through a simple two part procedure every
* frame:
*
* <ul>
* <li> Ticking all of the frame participants: in {@link
* FrameParticipant#tick}, any processing that need be performed during
* this frame should be performed. Care should be taken not to execute
* code that will take unduly long, instead such processing should be
* broken up so that it can be performed in small pieces every frame (or
* performed on a separate thread with the results safely communicated
* back to the frame participants for incorporation into the rendering
* loop).
*
* <li> Painting the user interface hierarchy: the top-level component
* (the frame) is painted (via a call to {@link JFrame#paint}) into a flip
* buffer (if supported, an off-screen buffer if not). Updates that were
* computed during the tick should be rendered in this call to paint. The
* paint call will propagate down to all components in the UI hierarchy,
* some of which may be {@link FrameParticipant}s and will have prepared
* themselves for their upcoming painting in the previous call to {@link
* FrameParticipant#tick}. When the call to paint completes, the flip
* buffer is flipped and the process starts all over again. </ul>
*
* <p> The ticking and rendering takes place on the AWT thread so as to
* avoid the need for complicated coordination between AWT event handler
* code and frame code. However, this means that all AWT (and Swing) event
* handlers <em>must not</em> perform any complicated processing. After
* each frame, control of the AWT thread is given back to the AWT which
* processes all pending AWT events before giving the frame manager an
* opportunity to process the next frame. Thus the convenience of
* everything running on the AWT thread comes with the price of requiring
* that AWT event handlers not block or perform any intensive processing.
* In general, this is a sensible structure for an application anyhow, so
* this organization tends to be preferable to an organization where the
* AWT and frame threads are separate and must tread lightly so as not to
* collide.
*
* <p> Note: the way that <code>JScrollPane</code> goes about improving
* performance when scrolling complicated contents cannot work with active
* rendering. If you use a <code>JScrollPane</code> in an application that
* uses the frame manager, you should either use the provided {@link
* SafeScrollPane} or set your scroll panes' viewports to
* <code>SIMPLE_SCROLL_MODE</code>.
*/
public abstract class FrameManager
{
/**
* Creates a frame manager that will use a {@link SystemMediaTimer} to
* obtain timing information, which is available on every platform,
* but returns inaccurate time stamps on many platforms.
*
* @see #newInstance(JFrame, MediaTimer)
*/
public static FrameManager newInstance (JFrame frame)
{
// first try creating a PerfTimer which is the best if we're using
// JDK1.4.2
MediaTimer timer = null;
try {
timer = (MediaTimer)Class.forName(PERF_TIMER).newInstance();
} catch (Throwable t) {
Log.info("Can't use PerfTimer (" + t + ") reverting to " +
"System.currentTimeMillis() based timer.");
timer = new SystemMediaTimer();
}
return newInstance(frame, timer);
}
/**
* Constructs a frame manager that will do its rendering to the
* supplied frame. It is likely that the caller will want to have put
* the frame into full-screen exclusive mode prior to providing it to
* the frame manager so that the frame manager can take advantage of
* optimizations available in that mode.
*
* @see GraphicsDevice#setFullScreenWindow
*/
public static FrameManager newInstance (JFrame frame, MediaTimer timer)
{
FrameManager fmgr;
if (_useFlip.getValue()) {
Log.info("Creating flip frame manager.");
fmgr = new FlipFrameManager();
} else {
Log.info("Creating back frame manager.");
fmgr = new BackFrameManager();
}
fmgr.init(frame, timer);
return fmgr;
}
/**
* Initializes this frame manager and prepares it for operation.
*/
protected void init (JFrame frame, MediaTimer timer)
{
_frame = frame;
if (frame instanceof ManagedJFrame) {
((ManagedJFrame)_frame).init(this);
}
_timer = timer;
// set up our custom repaint manager
_remgr = new FrameRepaintManager(_frame);
RepaintManager.setCurrentManager(_remgr);
// turn off double buffering for the whole business because we
// handle repaints
_remgr.setDoubleBufferingEnabled(false);
if (DEBUG_EVENTS) {
addTestListeners();
}
}
/**
* Adds a variety of listeners to the frame in order to provide
* visibility into the various events received by the frame.
*/
protected void addTestListeners ()
{
// add a test window listener
_frame.addWindowListener(new WindowListener() {
public void windowActivated (WindowEvent e) {
Log.info("Window activated [evt=" + e + "].");
}
public void windowClosed (WindowEvent e) {
Log.info("Window closed [evt=" + e + "].");
}
public void windowClosing (WindowEvent e) {
Log.info("Window closing [evt=" + e + "].");
}
public void windowDeactivated (WindowEvent e) {
Log.info("Window deactivated [evt=" + e + "].");
}
public void windowDeiconified (WindowEvent e) {
Log.info("Window deiconified [evt=" + e + "].");
}
public void windowIconified (WindowEvent e) {
Log.info("Window iconified [evt=" + e + "].");
}
public void windowOpened (WindowEvent e) {
Log.info("Window opened [evt=" + e + "].");
}
});
// add a component listener
_frame.addComponentListener(new ComponentListener() {
public void componentHidden (ComponentEvent e) {
Log.info("Window component hidden [evt=" + e + "].");
}
public void componentShown (ComponentEvent e) {
Log.info("Window component shown [evt=" + e + "].");
}
public void componentMoved (ComponentEvent e) {
Log.info("Window component moved [evt=" + e + "].");
}
public void componentResized (ComponentEvent e) {
Log.info("Window component resized [evt=" + e + "].");
}
});
// add test ancestor focus listener
_frame.getRootPane().addAncestorListener(
new AncestorListener() {
public void ancestorAdded (AncestorEvent e) {
Log.info("Root pane ancestor added [e=" + e + "].");
}
public void ancestorRemoved (AncestorEvent e) {
Log.info("Root pane ancestor removed [e=" + e + "].");
}
public void ancestorMoved (AncestorEvent e) {
Log.info("Root pane ancestor moved [e=" + e + "].");
}
});
// add test key event dispatcher
KeyboardFocusManager.getCurrentKeyboardFocusManager().
addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent (KeyEvent e) {
// if ((e.getModifiersEx() & KeyEvent.ALT_DOWN_MASK) != 0 &&
// e.getKeyCode() == KeyEvent.VK_TAB) {
// Log.info("Detected alt-tab key event " +
// "[e=" + e + "].");
// // attempt to eat the event so that windows
// // doesn't alt-tab into unhappy land
// e.consume();
// return true;
return false;
}
});
}
/**
* Instructs the frame manager to target the specified number of
* frames per second. If the computation and rendering for a frame are
* completed with time to spare, the frame manager will wait until the
* proper time to begin processing for the next frame. If a frame
* takes longer than its alotted time, the frame manager will
* immediately begin processing on the next frame.
*/
public void setTargetFrameRate (int fps)
{
// compute the number of milliseconds per frame
_millisPerFrame = 1000/fps;
}
/**
* Registers a frame participant. The participant will be given the
* opportunity to do processing and rendering on each frame.
*/
public void registerFrameParticipant (FrameParticipant participant)
{
_participants.add(participant);
}
/**
* Returns true if the specified participant is registered.
*/
public boolean isRegisteredFrameParticipant (FrameParticipant participant)
{
return _participants.contains(participant);
}
/**
* Removes a frame participant.
*/
public void removeFrameParticipant (FrameParticipant participant)
{
_participants.remove(participant);
}
/**
* Returns the frame being managed.
*/
public JFrame getFrame ()
{
return _frame;
}
/**
* Returns a millisecond granularity time stamp using the {@link
* MediaTimer} with which this frame manager was configured.
* <em>Note:</em> this should only be called from the AWT thread.
*/
public long getTimeStamp ()
{
return _timer.getElapsedMillis();
}
/**
* Starts up the per-frame tick
*/
public void start ()
{
if (_ticker == null) {
_ticker = new Ticker();
_ticker.start();
_lastTickStamp = 0;
}
}
/**
* Stops the per-frame tick.
*/
public synchronized void stop ()
{
if (_ticker != null) {
_ticker.cancel();
_ticker = null;
}
}
/**
* Returns true if the tick interval is be running (not necessarily at
* that instant, but in general).
*/
public synchronized boolean isRunning ()
{
return (_ticker != null);
}
/**
* Returns the number of ticks executed in the last second.
*/
public int getPerfTicks ()
{
return Math.round(_fps[1]);
}
/**
* Returns the number of ticks requested in the last second.
*/
public int getPerfTries ()
{
return Math.round(_fps[0]);
}
/**
* Returns debug performance metrics.
*/
public TrailingAverage[] getPerfMetrics ()
{
if (_metrics == null) {
_metrics = new TrailingAverage[] {
new TrailingAverage(150),
new TrailingAverage(150),
new TrailingAverage(150) };
}
return _metrics;
}
/**
* Called to perform the frame processing and rendering.
*/
protected void tick (long tickStamp)
{
long start = 0L, paint = 0L;
if (MediaPanel._perfDebug.getValue()) {
start = paint = System.currentTimeMillis();
}
// if our frame is not showing (or is impossibly sized), don't try
// rendering anything
if (_frame.isShowing() &&
_frame.getWidth() > 0 && _frame.getHeight() > 0) {
// tick our participants
tickParticipants(tickStamp);
paint = System.currentTimeMillis();
// repaint our participants and components
paint(tickStamp);
}
if (MediaPanel._perfDebug.getValue()) {
long end = System.currentTimeMillis();
getPerfMetrics()[1].record((int)(paint-start));
getPerfMetrics()[2].record((int)(end-paint));
}
}
/**
* Called once per frame to invoke {@link FrameParticipant#tick} on
* all of our frame participants.
*/
protected void tickParticipants (long tickStamp)
{
long gap = tickStamp - _lastTickStamp;
if (_lastTickStamp != 0 && gap > (HANG_DEBUG ? HANG_GAP : BIG_GAP)) {
Log.debug("Long tick delay [delay=" + gap + "ms].");
}
_lastTickStamp = tickStamp;
// validate any invalid components
try {
_remgr.validateComponents();
} catch (Throwable t) {
Log.warning("Failure validating components.");
Log.logStackTrace(t);
}
// tick all of our frame participants
_participantTickOp.setTickStamp(tickStamp);
_participants.apply(_participantTickOp);
}
/**
* Called once per frame to invoke {@link Component#paint} on all of
* our frame participants' components and all dirty components managed
* by our {@link FrameRepaintManager}.
*/
protected abstract void paint (long tickStamp);
/**
* Paints our frame participants and any dirty components via the
* repaint manager.
*
* @return true if anything was painted, false if not.
*/
protected boolean paint (Graphics2D gfx)
{
// paint our frame participants (which want to be handled
// specially)
_participantPaintOp.init(gfx);
_participants.apply(_participantPaintOp);
boolean ppart = _participantPaintOp.paintedSomething();
// repaint any widgets that have declared they need to be
// repainted since the last tick
boolean pcomp = _remgr.paintComponents(gfx, this);
// let the caller know if anybody painted anything
return (ppart || pcomp);
}
/**
* Called by the {@link ManagedJFrame} when our window was hidden and
* reexposed.
*/
protected abstract void restoreFromBack (Rectangle dirty);
/**
* Renders all components in all {@link JLayeredPane} layers that
* intersect the supplied bounds.
*/
protected void renderLayers (Graphics2D g, Component pcomp,
Rectangle bounds, boolean[] clipped)
{
JLayeredPane lpane =
JLayeredPane.getLayeredPaneAbove(pcomp);
if (lpane != null) {
renderLayer(g, bounds, lpane, clipped, JLayeredPane.PALETTE_LAYER);
renderLayer(g, bounds, lpane, clipped, JLayeredPane.MODAL_LAYER);
renderLayer(g, bounds, lpane, clipped, JLayeredPane.POPUP_LAYER);
renderLayer(g, bounds, lpane, clipped, JLayeredPane.DRAG_LAYER);
}
}
/**
* Renders all components in the specified layer of the supplied
* layered pane that intersect the supplied bounds.
*/
protected void renderLayer (Graphics2D g, Rectangle bounds,
JLayeredPane pane, boolean[] clipped,
Integer layer)
{
// stop now if there are no components in that layer
int ccount = pane.getComponentCountInLayer(layer.intValue());
if (ccount == 0) {
return;
}
// render them up
Component[] comps = pane.getComponentsInLayer(layer.intValue());
for (int ii = 0; ii < ccount; ii++) {
Component comp = comps[ii];
_lbounds.setBounds(0, 0, comp.getWidth(), comp.getHeight());
getRoot(comp, _lbounds);
if (!_lbounds.intersects(bounds)) {
continue;
}
// if the clipping region has not yet been set during this
// render pass, the time has come to do so
if (!clipped[0]) {
g.setClip(bounds);
clipped[0] = true;
}
// translate into the components coordinate system and render
g.translate(_lbounds.x, _lbounds.y);
comp.paint(g);
g.translate(-_lbounds.x, -_lbounds.y);
}
}
// documentation inherited
public void checkpoint (String name, int ticks)
{
Log.info("Frames in last second: " + ticks);
}
/**
* Returns the root component for the supplied component or null if it
* is not part of a rooted hierarchy or if any parent along the way is
* found to be hidden or without a peer. Along the way, it adjusts the
* supplied component-relative rectangle to be relative to the
* returned root component.
*/
public static Component getRoot (Component comp, Rectangle rect)
{
for (Component c = comp; c != null; c = c.getParent()) {
if (!c.isVisible() || !c.isDisplayable()) {
return null;
}
if (c instanceof Window || c instanceof Applet) {
return c;
}
rect.x += c.getX();
rect.y += c.getY();
}
return null;
}
/**
* An observer operation that calls {@link FrameParticipant#tick} with
* a specified tick stamp for all {@link FrameParticipant} objects in
* the observer list to which this operation is applied.
*/
protected class ParticipantTickOp
implements ObserverList.ObserverOp
{
/**
* Sets the tick stamp to be applied to the participants.
*/
public void setTickStamp (long tickStamp)
{
_tickStamp = tickStamp;
}
// documentation inherited
public boolean apply (Object observer)
{
try {
long start = 0L;
if (HANG_DEBUG) {
start = System.currentTimeMillis();
}
((FrameParticipant)observer).tick(_tickStamp);
if (HANG_DEBUG) {
long delay = (System.currentTimeMillis() - start);
if (delay > HANG_GAP) {
Log.info("Whoa nelly! Ticker took a long time " +
"[part=" + observer +
", time=" + delay + "ms].");
}
}
} catch (Throwable t) {
Log.warning("Frame participant choked during tick " +
"[part=" +
StringUtil.safeToString(observer) + "].");
Log.logStackTrace(t);
}
return true;
}
/** The tick stamp to be applied to each frame participant. */
protected long _tickStamp;
}
/**
* An observer operation that paints the components associated with
* all {@link FrameParticipant} objects in the observer list to which
* this operation is applied.
*/
protected class ParticipantPaintOp
implements ObserverList.ObserverOp
{
/**
* Sets the graphics context to which the frame participants
* render themselves.
*/
public void init (Graphics2D g)
{
_g = g;
_painted = 0;
}
/**
* Returns true if we painted at least one component in our last
* application.
*/
public boolean paintedSomething ()
{
return (_painted > 0);
}
// documentation inherited
public boolean apply (Object observer)
{
FrameParticipant part = (FrameParticipant)observer;
Component pcomp = part.getComponent();
if (pcomp == null || !part.needsPaint()) {
return true;
}
long start = 0L;
if (HANG_DEBUG) {
start = System.currentTimeMillis();
}
// get the bounds of this component
pcomp.getBounds(_bounds);
// the bounds adjustment we're about to call will add in the
// components initial bounds offsets, so we remove them here
_bounds.setLocation(0, 0);
// convert them into top-level coordinates; also note that if
// this component does not have a valid or visible root, we
// don't want to paint it either
if (getRoot(pcomp, _bounds) == null) {
return true;
}
try {
// render this participant; we don't set the clip because
// frame participants are expected to handle clipping
// themselves; otherwise we might pointlessly set the clip
// here, creating a few Rectangle objects in the process,
// only to have the frame participant immediately set the
// clip to something more sensible
_g.translate(_bounds.x, _bounds.y);
pcomp.paint(_g);
_g.translate(-_bounds.x, -_bounds.y);
_painted++;
} catch (Throwable t) {
String ptos = StringUtil.safeToString(part);
Log.warning("Frame participant choked during paint " +
"[part=" + ptos + "].");
Log.logStackTrace(t);
}
// render any components in our layered pane that are not in
// the default layer
_clipped[0] = false;
renderLayers(_g, pcomp, _bounds, _clipped);
if (HANG_DEBUG) {
long delay = (System.currentTimeMillis() - start);
if (delay > HANG_GAP) {
Log.warning("Whoa nelly! Painter took a long time " +
"[part=" + observer +
", time=" + delay + "ms].");
}
}
return true;
}
/** The graphics context to which the participants render. */
protected Graphics2D _g;
/** The number of participants that were actually painted. */
protected int _painted;
/** A handy rectangle that we reuse time and again to avoid having
* to instantiate a new rectangle in the midst of the core
* rendering loop. */
protected Rectangle _bounds = new Rectangle();
}
/** Used to effect periodic calls to {@link #tick}. */
protected class Ticker extends Thread
{
public void run ()
{
Log.info("Frame manager ticker running " +
"[sleepGran=" + _sleepGranularity.getValue() + "].");
while (_running) {
long start = 0L;
if (MediaPanel._perfDebug.getValue()) {
start = _timer.getElapsedMillis();
}
Unsafe.sleep(_sleepGranularity.getValue());
long woke = _timer.getElapsedMillis();
if (start > 0L) {
getPerfMetrics()[0].record((int)(woke-start));
}
// work around sketchy bug on WinXP that causes the clock
// to leap into the past from time to time
if (woke < _lastAttempt) {
Log.warning("Zoiks! We've leapt into the past, coping " +
"as best we can [dt=" +
(woke - _lastAttempt) + "].");
_lastAttempt = woke;
}
if (woke - _lastAttempt >= _millisPerFrame) {
_lastAttempt = woke;
if (testAndSet()) {
EventQueue.invokeLater(_awtTicker);
}
// else: drop the frame
}
}
}
public void cancel ()
{
_running = false;
}
protected final synchronized boolean testAndSet ()
{
_tries++;
if (!_ticking) {
_ticking = true;
return true;
}
return false;
}
protected final synchronized void clearTicking (long elapsed)
{
if (++_ticks == 100) {
long time = (elapsed - _lastTick);
_fps[0] = _tries * 1000f / time;
_fps[1] = _ticks * 1000f / time;
_lastTick = elapsed;
_ticks = _tries = 0;
}
_ticking = false;
}
/** Used to invoke the call to {@link #tick} on the AWT event
* queue thread. */
protected Runnable _awtTicker = new Runnable ()
{
public void run ()
{
long elapsed = _timer.getElapsedMillis();
try {
tick(elapsed);
} finally {
clearTicking(elapsed);
}
// call currentTimeMillis so that we are notified ASAP if
// time leaps into the past as it's useful for debugging
// other problems
RunAnywhere.currentTimeMillis();
}
};
/** Used to stick a fork in our ticker when desired. */
protected transient boolean _running = true;
/** Used to detect when we need to drop frames. */
protected boolean _ticking;
/** The time at which we last attempted to tick. */
protected long _lastAttempt;
/** Used to compute metrics. */
protected int _tries, _ticks, _time;
/** Used to compute metrics. */
protected long _lastTick;
};
/** The frame into which we do our rendering. */
protected JFrame _frame;
/** Used to obtain timing measurements. */
protected MediaTimer _timer;
/** Our custom repaint manager. */
protected FrameRepaintManager _remgr;
/** The number of milliseconds per frame (14 by default, which gives
* an fps of ~71). */
protected long _millisPerFrame = 14;
/** Used to track big delays in calls to our tick method. */
protected long _lastTickStamp;
/** The thread that dispatches our frame ticks. */
protected Ticker _ticker;
/** Used to track and report frames per second. */
protected float[] _fps = new float[2];
/** Used to track performance metrics. */
protected TrailingAverage[] _metrics;
/** Used to avoid creating rectangles when rendering layered
* components. */
protected Rectangle _lbounds = new Rectangle();
/** Used to lazily set the clip when painting popups and other
* "layered" components. */
protected boolean[] _clipped = new boolean[1];
/** The entites that are ticked each frame. */
protected ObserverList _participants =
new ObserverList(ObserverList.FAST_UNSAFE_NOTIFY);
/** The observer operation applied to all frame participants each tick. */
protected ParticipantTickOp _participantTickOp = new ParticipantTickOp();
/** The observer operation applied to all frame participants each time
* the frame is rendered. */
protected ParticipantPaintOp _participantPaintOp = new ParticipantPaintOp();
/** If we don't get ticked for 500ms, that's worth complaining about. */
protected static final long BIG_GAP = 500L;
/** If we don't get ticked for 100ms and we're hang debugging,
* complain. */
protected static final long HANG_GAP = 100L;
/** Enable this to log warnings when ticking or painting takes too
* long. */
protected static final boolean HANG_DEBUG = false;
/** A debug hook that toggles debug rendering of sprite paths. */
protected static RuntimeAdjust.BooleanAdjust _useFlip =
new RuntimeAdjust.BooleanAdjust(
"When active a flip-buffer will be used to manage our " +
"rendering, otherwise a volatile back buffer is used " +
"[requires restart]", "narya.media.frame",
// back buffer rendering doesn't work on the Mac, so we
// default to flip buffer on that platform; we still allow it
// to be toggled so that we can easily test things when they
// release new JVMs
MediaPrefs.config, RunAnywhere.isMacOS());
/** Allows us to tweak the sleep granularity. */
protected static RuntimeAdjust.IntAdjust _sleepGranularity =
new RuntimeAdjust.IntAdjust(
"The number of milliseconds slept before checking to see if " +
"it's time to queue up a new frame tick.", "narya.media.sleep_gran",
MediaPrefs.config, RunAnywhere.isWindows() ? 10 : 7);
/** Whether to enable AWT event debugging for the frame. */
protected static final boolean DEBUG_EVENTS = false;
/** The name of the high-performance timer class we attempt to load. */
protected static final String PERF_TIMER =
"com.threerings.media.timer.PerfTimer";
}
|
// $Id: DSet.java,v 1.23 2002/12/13 02:07:27 mdb Exp $
package com.threerings.presents.dobj;
import java.io.IOException;
import java.util.Comparator;
import java.util.Iterator;
import com.samskivert.util.ArrayUtil;
import com.samskivert.util.StringUtil;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
import com.threerings.presents.Log;
/**
* The distributed set class provides a means by which an unordered set of
* objects can be maintained as a distributed object field. Entries can be
* added to and removed from the set, requests for which will generate
* events much like other distributed object fields.
*
* <p> Classes that wish to act as set entries must implement the {@link
* Entry} interface which extends {@link Streamable} and adds the
* requirement that the object provide a key which will be used to
* identify entry equality. Thus an entry is declared to be in a set of
* the object returned by that entry's {@link Entry#getKey} method is
* equal (using {@link Object#equals}) to the entry returned by the {@link
* Entry#getKey} method of some other entry in the set. Additionally, in
* the case of entry removal, only the key for the entry to be removed
* will be transmitted with the removal event to save network
* bandwidth. Lastly, the object returned by {@link Entry#getKey} must be
* a {@link Streamable} type.
*/
public class DSet
implements Streamable, Cloneable
{
/**
* Entries of the set must implement this interface.
*/
public static interface Entry extends Streamable
{
/**
* Each entry provide an associated key which is used to determine
* its uniqueness in the set. See the {@link DSet} class
* documentation for further information.
*/
public Comparable getKey ();
}
/**
* Creates a distributed set and populates it with values from the
* supplied iterator. This should be done before the set is unleashed
* into the wild distributed object world because no associated entry
* added events will be generated. Additionally, this operation does
* not check for duplicates when adding entries, so one should be sure
* that the iterator contains only unique entries.
*
* @param source an iterator from which we will initially populate the
* set.
*/
public DSet (Iterator source)
{
while (source.hasNext()) {
add((Entry)source.next());
}
}
/**
* Constructs an empty distributed set.
*/
public DSet ()
{
}
/**
* Returns the number of entries in this set.
*/
public int size ()
{
return _size;
}
/**
* Returns true if the set contains an entry whose
* <code>getKey()</code> method returns a key that
* <code>equals()</code> the key returned by <code>getKey()</code> of
* the supplied entry. Returns false otherwise.
*/
public boolean contains (Entry elem)
{
return containsKey(elem.getKey());
}
/**
* Returns true if an entry in the set has a key that
* <code>equals()</code> the supplied key. Returns false otherwise.
*/
public boolean containsKey (Object key)
{
return get(key) != null;
}
/**
* Returns the entry that matches (<code>getKey().equals(key)</code>)
* the specified key or null if no entry could be found that matches
* the key.
*/
public Entry get (Object key)
{
// scan the array looking for a matching entry
int elength = _entries.length;
for (int i = 0; i < elength; i++) {
// the array may be sparse
if (_entries[i] != null) {
Entry elem = _entries[i];
if (elem.getKey().equals(key)) {
return elem;
}
}
}
return null;
}
/**
* Returns an iterator over the entries of this set. It does not
* support modification (nor iteration while modifications are being
* made to the set). It should not be kept around as it can quickly
* become out of date.
*/
public Iterator entries ()
{
return new Iterator() {
public boolean hasNext () {
return (_index < _size);
}
public Object next () {
return _entries[_index++];
}
public void remove () {
throw new UnsupportedOperationException();
}
protected int _index = 0;
};
}
/**
* Copies the elements of this distributed set into the supplied
* array. If the array is not large enough to hold all of the
* elements, as many as fit into the array will be copied. If the
* <code>array</code> argument is null, an object array of sufficient
* size to contain all of the elements of this set will be created and
* returned.
*/
public Object toArray (Object[] array)
{
if (array == null) {
array = new Object[size()];
}
System.arraycopy(_entries, 0, array, 0, array.length);
return array;
}
/**
* Adds the specified entry to the set. This should not be called
* directly, instead the associated <code>addTo{Set}()</code> method
* should be called on the distributed object that contains the set in
* question.
*
* @return true if the entry was added, false if it was already in
* the set.
*/
protected boolean add (Entry elem)
{
// determine where we'll be adding the new element
int eidx = ArrayUtil.binarySearch(
_entries, 0, _size, elem, ENTRY_COMP);
// if the element is already in the set, bail now
if (eidx >= 0) {
return false;
}
// convert the index into happy positive land
eidx = (eidx+1)*-1;
// expand our entries array if necessary
int elength = _entries.length;
if (_size >= elength) {
// sanity check
if (elength > 2048) {
Log.warning("Requested to expand to questionably large size " +
"[length=" + elength + "].");
Thread.dumpStack();
}
// create a new array and copy our data into it
Entry[] elems = new Entry[elength*2];
System.arraycopy(_entries, 0, elems, 0, elength);
_entries = elems;
}
// if the entry doesn't go at the end, shift the elements down to
// accomodate it
if (eidx < _size) {
System.arraycopy(_entries, eidx, _entries, eidx+1, _size-eidx);
}
// stuff the entry into the array and note that we're bigger
_entries[eidx] = elem;
_size++;
return true;
}
/**
* Removes the specified entry from the set. This should not be called
* directly, instead the associated <code>removeFrom{Set}()</code>
* method should be called on the distributed object that contains the
* set in question.
*
* @return true if the entry was removed, false if it was not in the
* set.
*/
protected boolean remove (Entry elem)
{
return removeKey(elem.getKey());
}
/**
* Removes from the set the entry whose key matches the supplied
* key. This should not be called directly, instead the associated
* <code>removeFrom{Set}()</code> method should be called on the
* distributed object that contains the set in question.
*
* @return true if a matching entry was removed, false if no entry
* in the set matched the key.
*/
protected boolean removeKey (Object key)
{
// look up this entry's position in our set
int eidx = ArrayUtil.binarySearch(
_entries, 0, _size, key, ENTRY_COMP);
// if we found it, remove it
if (eidx >= 0) {
// shift the remaining elements down
System.arraycopy(_entries, eidx+1, _entries, eidx, _size-eidx-1);
_entries[--_size] = null;
return true;
} else {
return false;
}
}
/**
* Updates the specified entry by locating an entry whose key matches
* the key of the supplied entry and overwriting it. This should not
* be called directly, instead the associated
* <code>update{Set}()</code> method should be called on the
* distributed object that contains the set in question.
*
* @return true if the entry was updated, false if it was not
* already in the set (in which case nothing is updated).
*/
protected boolean update (Entry elem)
{
// look up this entry's position in our set
int eidx = ArrayUtil.binarySearch(
_entries, 0, _size, elem, ENTRY_COMP);
// if we found it, update it
if (eidx >= 0) {
_entries[eidx] = elem;
return true;
} else {
return false;
}
}
/**
* Generates a shallow copy of this object.
*/
public Object clone ()
{
try {
DSet nset = (DSet)super.clone();
nset._entries = new Entry[_entries.length];
System.arraycopy(_entries, 0, nset._entries, 0, _entries.length);
nset._size = _size;
return nset;
} catch (CloneNotSupportedException cnse) {
throw new RuntimeException("WTF? " + cnse);
}
}
/**
* Writes our custom streamable fields.
*/
public void writeObject (ObjectOutputStream out)
throws IOException
{
out.defaultWriteObject();
out.writeInt(_size);
int ecount = _entries.length;
for (int ii = 0; ii < ecount; ii++) {
if (_entries[ii] != null) {
out.writeObject(_entries[ii]);
}
}
}
/**
* Reads our custom streamable fields.
*/
public void readObject (ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
_size = in.readInt();
_entries = new Entry[Math.max(_size, INITIAL_CAPACITY)];
for (int ii = 0; ii < _size; ii++) {
_entries[ii] = (Entry)in.readObject();
}
}
/**
* Generates a string representation of this set instance.
*/
public String toString ()
{
StringBuffer buf = new StringBuffer("(");
String prefix = "";
for (int i = 0; i < _entries.length; i++) {
Entry elem = _entries[i];
if (elem != null) {
buf.append(prefix);
prefix = ", ";
buf.append(elem);
}
}
buf.append(")");
return buf.toString();
}
/** The entries of the set (in a sparse array). */
protected Entry[] _entries = new Entry[INITIAL_CAPACITY];
/** The number of entries in this set. */
protected int _size;
/** The default capacity of a set instance. */
protected static final int INITIAL_CAPACITY = 2;
/** Used for lookups and to keep the set contents sorted on
* insertions. */
protected static Comparator ENTRY_COMP = new Comparator() {
public int compare (Object o1, Object o2) {
Comparable c1 = (o1 instanceof Entry) ?
((Entry)o1).getKey() : (Comparable)o1;
Comparable c2 = (o2 instanceof Entry) ?
((Entry)o2).getKey() : (Comparable)o2;
return c1.compareTo(c2);
}
};
}
|
package org.apache.cassandra.utils;
import java.nio.ByteBuffer;
public class Tracer {
public static String GetCallStack() {
StringBuilder sb = new StringBuilder(1024);
boolean first = true;
int i = 0;
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
i ++;
if (i <= 2) {
continue;
}
if (first) {
first = false;
} else {
sb.append("\n");
}
sb.append(ste);
}
return Indent(sb.toString(), 2);
}
public static String Indent(String in, int ind) {
StringBuilder indStr = new StringBuilder(10);
for (int i = 0; i < ind; i ++)
indStr.append(" ");
return in.replaceAll("(?m)^", indStr.toString());
}
public static String toHex(ByteBuffer bb) {
return toHex(bb.array());
}
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String toHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static long toLong(ByteBuffer bb) {
return toLong(bb.array());
}
public static long toLong(byte[] bytes) {
long i = 0;
for (int j = 0; j < bytes.length; j++) {
i = (i << 8) + bytes[j];
}
return i;
}
}
|
package org.jdesktop.swingx;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputListener;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.jdesktop.swingx.event.TableColumnModelExtListener;
import org.jdesktop.swingx.table.ColumnHeaderRenderer;
import org.jdesktop.swingx.table.TableColumnExt;
/**
* TableHeader with extended functionality if associated Table is of
* type JXTable.<p>
*
* The enhancements:
* <ul>
* <li> supports pluggable handler to control user interaction for sorting.
* The default handler toggles sort order on mouseClicked on the header
* of the column to sort. On shift-mouseClicked, it resets any column sorting.
* Both are done by invoking the corresponding methods of JXTable,
* <code> toggleSortOrder(int) </code> and <code> resetSortOrder() </code>
* <li> uses ColumnHeaderRenderer which can show the sort icon
* <li> triggers column pack (== auto-resize to exactly fit the contents)
* on double-click in resize region.
* </ul>
*
*
* @author Jeanette Winzenburg
*
* @see ColumnHeaderRenderer
* @see JXTable#toggleSortOrder(int)
* @see JXTable#resetSortOrder()
*/
public class JXTableHeader extends JTableHeader
implements TableColumnModelExtListener {
private SortGestureRecognizer sortGestureRecognizer;
public JXTableHeader() {
super();
}
public JXTableHeader(TableColumnModel columnModel) {
super(columnModel);
}
/**
* Sets the associated JTable. Enables enhanced header
* features if table is of type JXTable.<p>
*
* PENDING: who is responsible for synching the columnModel?
*/
@Override
public void setTable(JTable table) {
super.setTable(table);
// setColumnModel(table.getColumnModel());
// the additional listening option makes sense only if the table
// actually is a JXTable
if (getXTable() != null) {
installHeaderListener();
} else {
uninstallHeaderListener();
}
}
/**
* Implementing TableColumnModelExt: listening to column property changes.
* Here: triggers a resizeAndRepaint on every propertyChange which
* doesn't already fire a "normal" columnModelEvent.
*
* @param event change notification from a contained TableColumn.
* @see #isColumnEvent(PropertyChangeEvent)
*
*/
public void columnPropertyChange(PropertyChangeEvent event) {
if (isColumnEvent(event)) return;
resizeAndRepaint();
}
/**
* @param event the PropertyChangeEvent received as TableColumnModelExtListener.
* @return a boolean to decide whether the same event triggers a
* base columnModelEvent.
*/
protected boolean isColumnEvent(PropertyChangeEvent event) {
return "width".equals(event.getPropertyName()) ||
"preferredWidth".equals(event.getPropertyName())
|| "visible".equals(event.getPropertyName());
}
/**
* overridden to respect the column tooltip, if available.
*
* @return the column tooltip of the column at the mouse position
* if not null or super if not available.
*/
@Override
public String getToolTipText(MouseEvent event) {
String columnToolTipText = getColumnToolTipText(event);
return columnToolTipText != null ? columnToolTipText : super.getToolTipText(event);
}
/**
*
* @param event the mouseEvent representing the mouse location.
* @return the column tooltip of the column below the mouse location,
* or null if not available.
*/
protected String getColumnToolTipText(MouseEvent event) {
if (getXTable() == null) return null;
int column = columnAtPoint(event.getPoint());
if (column < 0) return null;
TableColumnExt columnExt = getXTable().getColumnExt(column);
return columnExt != null ? columnExt.getToolTipText() : null;
}
public JXTable getXTable() {
if (!(getTable() instanceof JXTable))
return null;
return (JXTable) getTable();
}
/**
* Returns the TableCellRenderer used for rendering the headerCell
* of the column at columnIndex.
*
* @param columnIndex the index of the column
* @return the renderer.
*/
public TableCellRenderer getCellRenderer(int columnIndex) {
TableCellRenderer renderer = getColumnModel().getColumn(columnIndex).getHeaderRenderer();
return renderer != null ? renderer : getDefaultRenderer();
}
/**
* Overridden to adjust for a minimum height as returned by
* #getMinimumHeight.
*
* @inheritDoc
*/
@Override
public Dimension getPreferredSize() {
Dimension pref = super.getPreferredSize();
pref = getPreferredSize(pref);
pref.height = getMinimumHeight(pref.height);
return pref;
}
/**
* Hack around #334-swingx: super doesnt measure all headerRenderers
* for prefSize. This hack does and adjusts the height of the
* given Dimension to be equal to the max fo all renderers.
*
* @param pref the adjusted preferred size respecting all renderers
* size requirements.
*/
protected Dimension getPreferredSize(Dimension pref) {
int height = pref.height;
for (int i = 0; i < getColumnModel().getColumnCount(); i++) {
TableCellRenderer renderer = getCellRenderer(i);
Component comp = renderer.getTableCellRendererComponent(table,
getColumnModel().getColumn(i).getHeaderValue(), false, false, -1, i);
height = Math.max(height, comp.getPreferredSize().height);
}
pref.height = height;
return pref;
}
/**
* Allows to enforce a minimum heigth in the
* getXXSize methods.
*
* Here: jumps in if the table's columnControl is visible and
* the input height is 0 - this happens if all
* columns are hidden - and configures the default
* header renderer with a dummy value for measuring.
*
* @param height the prefHeigth as calcualated by super.
* @return a minimum height for the preferredSize.
*/
protected int getMinimumHeight(int height) {
if ((height == 0) && (getXTable() != null)
&& getXTable().isColumnControlVisible()){
TableCellRenderer renderer = getDefaultRenderer();
Component comp = renderer.getTableCellRendererComponent(getTable(),
"dummy", false, false, -1, -1);
height = comp.getPreferredSize().height;
}
return height;
}
public void updateUI() {
super.updateUI();
if (getDefaultRenderer() instanceof JComponent) {
((JComponent) getDefaultRenderer()).updateUI();
}
}
/**
* Returns the the dragged column if and only if, a drag is in process and
* the column is visible, otherwise returns <code>null</code>.
*
* @return the dragged column, if a drag is in process and the column is
* visible, otherwise returns <code>null</code>
* @see #getDraggedDistance
*/
@Override
public TableColumn getDraggedColumn() {
return isVisible(draggedColumn) ? draggedColumn : null;
}
/**
* Checks and returns the column's visibility.
*
* @param column the <code>TableColumn</code> to check
* @return a boolean indicating if the column is visible
*/
private boolean isVisible(TableColumn column) {
return getViewIndexForColumn(column) >= 0;
}
/**
* Returns the (visible) view index for the given column
* or -1 if not visible or not contained in this header's
* columnModel.
*
*
* @param aColumn
* @return
*/
private int getViewIndexForColumn(TableColumn aColumn) {
if (aColumn == null)
return -1;
TableColumnModel cm = getColumnModel();
for (int column = 0; column < cm.getColumnCount(); column++) {
if (cm.getColumn(column) == aColumn) {
return column;
}
}
return -1;
}
protected TableCellRenderer createDefaultRenderer() {
return ColumnHeaderRenderer.createColumnHeaderRenderer();
}
/**
* Lazily creates and returns the SortGestureRecognizer.
*
* @return the SortGestureRecognizer used in Headerlistener.
*/
public SortGestureRecognizer getSortGestureRecognizer() {
if (sortGestureRecognizer == null) {
sortGestureRecognizer = createSortGestureRecognizer();
}
return sortGestureRecognizer;
}
/**
* Set the SortGestureRecognizer for use in the HeaderListener.
*
* @param recognizer the recognizer to use in HeaderListener.
*/
public void setSortGestureRecognizer(SortGestureRecognizer recognizer) {
this.sortGestureRecognizer = recognizer;
}
/**
* creates and returns the default SortGestureRecognizer.
* @return the SortGestureRecognizer used in Headerlistener.
*
*/
protected SortGestureRecognizer createSortGestureRecognizer() {
return new SortGestureRecognizer();
}
protected void installHeaderListener() {
if (headerListener == null) {
headerListener = new HeaderListener();
addMouseListener(headerListener);
addMouseMotionListener(headerListener);
}
}
protected void uninstallHeaderListener() {
if (headerListener != null) {
removeMouseListener(headerListener);
removeMouseMotionListener(headerListener);
headerListener = null;
}
}
private MouseInputListener headerListener;
private class HeaderListener implements MouseInputListener {
private TableColumn cachedResizingColumn;
public void mouseClicked(MouseEvent e) {
if (shouldIgnore(e)) {
return;
}
if (isInResizeRegion(e)) {
doResize(e);
} else {
doSort(e);
}
}
private boolean shouldIgnore(MouseEvent e) {
return !SwingUtilities.isLeftMouseButton(e)
|| !table.isEnabled();
}
private void doSort(MouseEvent e) {
JXTable table = getXTable();
if (!table.isSortable())
return;
if (getSortGestureRecognizer().isResetSortOrderGesture(e)) {
table.resetSortOrder();
repaint();
} else if (getSortGestureRecognizer().isToggleSortOrderGesture(e)){
int column = columnAtPoint(e.getPoint());
if (column >= 0) {
table.toggleSortOrder(column);
}
uncacheResizingColumn();
repaint();
}
}
private void doResize(MouseEvent e) {
if (e.getClickCount() != 2)
return;
int column = getViewIndexForColumn(cachedResizingColumn);
if (column >= 0) {
(getXTable()).packColumn(column, 5);
}
uncacheResizingColumn();
}
public void mouseReleased(MouseEvent e) {
cacheResizingColumn(e);
}
public void mousePressed(MouseEvent e) {
cacheResizingColumn(e);
}
private void cacheResizingColumn(MouseEvent e) {
if (!getSortGestureRecognizer().isSortOrderGesture(e))
return;
TableColumn column = getResizingColumn();
if (column != null) {
cachedResizingColumn = column;
}
}
private void uncacheResizingColumn() {
cachedResizingColumn = null;
}
private boolean isInResizeRegion(MouseEvent e) {
return cachedResizingColumn != null; // inResize;
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
uncacheResizingColumn();
}
public void mouseDragged(MouseEvent e) {
uncacheResizingColumn();
}
public void mouseMoved(MouseEvent e) {
}
}
/**
* Encapsulates decision about which MouseEvents should
* trigger sort/unsort events.
*
* Here: a single left click for toggling sort order, a
* single SHIFT-left click for unsorting.
*
*/
public static class SortGestureRecognizer {
public boolean isResetSortOrderGesture(MouseEvent e) {
return isSortOrderGesture(e) && isResetModifier(e);
}
protected boolean isResetModifier(MouseEvent e) {
return ((e.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) == MouseEvent.SHIFT_DOWN_MASK);
}
public boolean isToggleSortOrderGesture(MouseEvent e) {
return isSortOrderGesture(e) && !isResetModifier(e);
}
public boolean isSortOrderGesture(MouseEvent e) {
return e.getClickCount() == 1;
}
}
}
|
package org.jdesktop.swingx;
import java.awt.Component;
import java.awt.HeadlessException;
import java.util.prefs.Preferences;
import javax.swing.JDialog;
import org.jdesktop.swingx.plaf.JXTipOfTheDayAddon;
import org.jdesktop.swingx.plaf.LookAndFeelAddons;
import org.jdesktop.swingx.plaf.TipOfTheDayUI;
import org.jdesktop.swingx.tips.DefaultTipOfTheDayModel;
import org.jdesktop.swingx.tips.TipOfTheDayModel;
import org.jdesktop.swingx.tips.TipOfTheDayModel.Tip;
/**
* Provides the "Tip of The Day" pane and dialog.<br>
*
* <p>
* Tips are retrieved from the {@link org.jdesktop.swingx.tips.TipOfTheDayModel}.
* In the most common usage, a tip (as returned by
* {@link org.jdesktop.swingx.tips.TipOfTheDayModel.Tip#getTip()}) is just a
* <code>String</code>. However, the return type of this method is actually
* <code>Object</code>. Its interpretation depends on its type:
* <dl compact>
* <dt>Component
* <dd>The <code>Component</code> is displayed in the dialog.
* <dt>Icon
* <dd>The <code>Icon</code> is wrapped in a <code>JLabel</code> and
* displayed in the dialog.
* <dt>others
* <dd>The object is converted to a <code>String</code> by calling its
* <code>toString</code> method. The result is wrapped in a
* <code>JEditorPane</code> or <code>JTextArea</code> and displayed.
* </dl>
*
* <p>
* <code>JXTipOfTheDay<code> finds its tips in its {@link org.jdesktop.swingx.tips.TipOfTheDayModel}.
* Such model can be programmatically built using {@link org.jdesktop.swingx.tips.DefaultTipOfTheDayModel}
* and {@link org.jdesktop.swingx.tips.DefaultTip} but
* the {@link org.jdesktop.swingx.tips.TipLoader} provides a convenient method to
* build a model and its tips from a {@link java.util.Properties} object.
*
* <p>
* Example:
* <p>
* Let's consider a file <i>tips.properties</i> with the following content:
* <pre>
* <code>
* tip.1.description=This is the first time! Plain text.
* tip.2.description=<html>This is <b>another tip</b>, it uses HTML!
* tip.3.description=A third one
* </code>
* </pre>
*
* To load and display the tips:
*
* <pre>
* <code>
* Properties tips = new Properties();
* tips.load(new FileInputStream("tips.properties"));
*
* TipOfTheDayModel model = TipLoader.load(tips);
* JXTipOfTheDay totd = new JXTipOfTheDay(model);
*
* totd.showDialog(someParentComponent);
* </code>
* </pre>
*
* <p>
* Additionally, <code>JXTipOfTheDay</code> features an option enabling the end-user
* to choose to not display the "Tip Of The Day" dialog. This user choice can be stored
* in the user {@link java.util.prefs.Preferences} but <code>JXTipOfTheDay</code> also
* supports custom storage through the {@link org.jdesktop.swingx.JXTipOfTheDay.ShowOnStartupChoice} interface.
*
* <pre>
* <code>
* Preferences userPreferences = Preferences.userRoot().node("myApp");
* totd.showDialog(someParentComponent, userPreferences);
* </code>
* </pre>
* In this code, the first time showDialog is called, the dialog will be made
* visible and the user will have the choice to not display it again in the future
* (usually this is controlled by a checkbox "Show tips on startup"). If the user
* unchecks the option, subsequent calls to showDialog will not display the dialog.
* As the choice is saved in the user Preferences, it will persist when the application is relaunched.
*
* @see org.jdesktop.swingx.tips.TipLoader
* @see org.jdesktop.swingx.tips.TipOfTheDayModel
* @see org.jdesktop.swingx.tips.TipOfTheDayModel.Tip
* @see #showDialog(Component, Preferences)
* @see #showDialog(Component, ShowOnStartupChoice)
*
* @author <a href="mailto:fred@L2FProd.com">Frederic Lavigne</a>
*/
public class JXTipOfTheDay extends JXPanel {
/**
* JXTipOfTheDay pluggable UI key <i>swingx/TipOfTheDayUI</i>
*/
public final static String uiClassID = "swingx/TipOfTheDayUI";
// ensure at least the default ui is registered
static {
LookAndFeelAddons.contribute(new JXTipOfTheDayAddon());
}
/**
* Key used to store the status of the "Show tip on startup" checkbox"
*/
public static final String PREFERENCE_KEY = "ShowTipOnStartup";
/**
* Used when generating PropertyChangeEvents for the "currentTip" property
*/
public static final String CURRENT_TIP_CHANGED_KEY = "currentTip";
private TipOfTheDayModel model;
private int currentTip = 0;
/**
* Constructs a new <code>JXTipOfTheDay</code> with an empty
* TipOfTheDayModel
*/
public JXTipOfTheDay() {
this(new DefaultTipOfTheDayModel(new Tip[0]));
}
/**
* Constructs a new <code>JXTipOfTheDay</code> showing tips from the given
* TipOfTheDayModel.
*
* @param model
*/
public JXTipOfTheDay(TipOfTheDayModel model) {
this.model = model;
updateUI();
}
/**
* Notification from the <code>UIManager</code> that the L&F has changed.
* Replaces the current UI object with the latest version from the
* <code>UIManager</code>.
*
* @see javax.swing.JComponent#updateUI
*/
public void updateUI() {
setUI((TipOfTheDayUI)LookAndFeelAddons.getUI(this, TipOfTheDayUI.class));
}
/**
* Sets the L&F object that renders this component.
*
* @param ui
* the <code>TipOfTheDayUI</code> L&F object
* @see javax.swing.UIDefaults#getUI
*
* @beaninfo bound: true hidden: true description: The UI object that
* implements the taskpane group's LookAndFeel.
*/
public void setUI(TipOfTheDayUI ui) {
super.setUI(ui);
}
/**
* Gets the UI object which implements the L&F for this component.
*
* @return the TipOfTheDayUI object that implements the TipOfTheDayUI L&F
*/
@Override
public TipOfTheDayUI getUI() {
return (TipOfTheDayUI)ui;
}
/**
* Returns the name of the L&F class that renders this component.
*
* @return the string {@link #uiClassID}
* @see javax.swing.JComponent#getUIClassID
* @see javax.swing.UIDefaults#getUI
*/
@Override
public String getUIClassID() {
return uiClassID;
}
public TipOfTheDayModel getModel() {
return model;
}
public void setModel(TipOfTheDayModel model) {
if (model == null) {
throw new IllegalArgumentException("model can not be null");
}
TipOfTheDayModel old = this.model;
this.model = model;
firePropertyChange("model", old, model);
}
public int getCurrentTip() {
return currentTip;
}
public void setCurrentTip(int currentTip) {
if (currentTip < 0 || currentTip >= getModel().getTipCount()) {
throw new IllegalArgumentException(
"Current tip must be within the bounds [0, " + getModel().getTipCount()
+ "[");
}
int oldTip = this.currentTip;
this.currentTip = currentTip;
firePropertyChange(CURRENT_TIP_CHANGED_KEY, oldTip, currentTip);
}
/**
* Shows the next tip in the list. It cycles the tip list.
*/
public void nextTip() {
int count = getModel().getTipCount();
if (count == 0) { return; }
int nextTip = currentTip + 1;
if (nextTip >= count) {
nextTip = 0;
}
setCurrentTip(nextTip);
}
/**
* Shows the previous tip in the list. It cycles the tip list.
*/
public void previousTip() {
int count = getModel().getTipCount();
if (count == 0) { return; }
int previousTip = currentTip - 1;
if (previousTip < 0) {
previousTip = count - 1;
}
setCurrentTip(previousTip);
}
/**
* Pops up a "Tip of the day" dialog.
*
* @param parentComponent
* @exception HeadlessException
* if GraphicsEnvironment.isHeadless() returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public void showDialog(Component parentComponent) throws HeadlessException {
showDialog(parentComponent, (ShowOnStartupChoice)null);
}
public boolean showDialog(Component parentComponent,
Preferences showOnStartupPref) throws HeadlessException {
return showDialog(parentComponent, showOnStartupPref, false);
}
public boolean showDialog(Component parentComponent,
final Preferences showOnStartupPref, boolean force) throws HeadlessException {
if (showOnStartupPref == null) { throw new IllegalArgumentException(
"Preferences can not be null"); }
ShowOnStartupChoice store = new ShowOnStartupChoice() {
public boolean isShowingOnStartup() {
return showOnStartupPref.getBoolean(PREFERENCE_KEY, true);
}
public void setShowingOnStartup(boolean showOnStartup) {
if (showOnStartup && !showOnStartupPref.getBoolean(PREFERENCE_KEY, true)) {
// if the choice was previously not enable and now we re-enable it, we
// must remove the key
showOnStartupPref.remove(PREFERENCE_KEY);
} else if (!showOnStartup) {
// user does not want to see the tip
showOnStartupPref.putBoolean(PREFERENCE_KEY, showOnStartup);
}
}
};
return showDialog(parentComponent, store, force);
}
/**
* Pops up a "Tip of the day" dialog.
*
* If <code>choice</code> is not null, the method first checks if
* {@link ShowOnStartupChoice#isShowingOnStartup()} is true before showing the
* dialog.
*
* Additionally, it saves the state of the "Show tips on startup" checkbox
* using the given {@link ShowOnStartupChoice} object.
*
* @param parentComponent
* @param choice
* @exception HeadlessException
* if GraphicsEnvironment.isHeadless() returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @return true if the user chooses to see the tips again, false otherwise.
*/
public boolean showDialog(Component parentComponent,
ShowOnStartupChoice choice) {
return showDialog(parentComponent, choice, false);
}
/**
* Pops up a "Tip of the day" dialog.
*
* If <code>choice</code> is not null, the method first checks if
* <code>force</code> is true or if
* {@link ShowOnStartupChoice#isShowingOnStartup()} is true before showing the
* dialog.
*
* Additionally, it saves the state of the "Show tips on startup" checkbox
* using the given {@link ShowOnStartupChoice} object.
*
* @param parentComponent
* @param choice
* @param force
* if true, the dialog is displayed even if
* {@link ShowOnStartupChoice#isShowingOnStartup()} is false
* @exception HeadlessException
* if GraphicsEnvironment.isHeadless() returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
* @return true if the user chooses to see the tips again, false otherwise.
*/
public boolean showDialog(Component parentComponent,
ShowOnStartupChoice choice, boolean force) {
if (choice == null) {
JDialog dialog = createDialog(parentComponent, choice);
dialog.setVisible(true);
dialog.dispose();
return true;
} else if (force || choice.isShowingOnStartup()) {
JDialog dialog = createDialog(parentComponent, choice);
dialog.setVisible(true);
dialog.dispose();
return choice.isShowingOnStartup();
} else {
return false;
}
}
/**
* @param showOnStartupPref
* @return true if the key named "ShowTipOnStartup" is not set to false
*/
public static boolean isShowingOnStartup(Preferences showOnStartupPref) {
return showOnStartupPref.getBoolean(PREFERENCE_KEY, true);
}
/**
* Removes the value set for "ShowTipOnStartup" in the given Preferences to
* ensure the dialog shown by a later call to
* {@link #showDialog(Component, Preferences)} will be visible to the user.
*
* @param showOnStartupPref
*/
public static void forceShowOnStartup(Preferences showOnStartupPref) {
showOnStartupPref.remove(PREFERENCE_KEY);
}
/**
* Calls
* {@link TipOfTheDayUI#createDialog(Component, JXTipOfTheDay.ShowOnStartupChoice)}.
*
* This method can be overriden in order to control things such as the
* placement of the dialog or its title.
*
* @param parentComponent
* @param choice
* @return a JDialog to show this TipOfTheDay pane
*/
protected JDialog createDialog(Component parentComponent,
ShowOnStartupChoice choice) {
return getUI().createDialog(parentComponent, choice);
}
/**
* Used in conjunction with the
* {@link JXTipOfTheDay#showDialog(Component, ShowOnStartupChoice)} to save the
* "Show tips on startup" choice.
*/
public static interface ShowOnStartupChoice {
/**
* Persists the user choice
* @param showOnStartup the user choice
*/
void setShowingOnStartup(boolean showOnStartup);
/**
* @return the previously stored user choice
*/
boolean isShowingOnStartup();
}
}
|
package us.kbase.mobu.runner;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import com.fasterxml.jackson.core.type.TypeReference;
import us.kbase.auth.AuthService;
import us.kbase.auth.AuthToken;
import us.kbase.catalog.CatalogClient;
import us.kbase.catalog.ModuleVersion;
import us.kbase.catalog.SelectModuleVersion;
import us.kbase.common.executionengine.CallbackServer;
import us.kbase.common.executionengine.CallbackServerConfigBuilder;
import us.kbase.common.executionengine.LineLogger;
import us.kbase.common.executionengine.ModuleMethod;
import us.kbase.common.executionengine.ModuleRunVersion;
import us.kbase.common.executionengine.CallbackServerConfigBuilder.CallbackServerConfig;
import us.kbase.common.service.JsonServerServlet;
import us.kbase.common.service.JsonServerSyslog;
import us.kbase.common.service.UObject;
import us.kbase.common.utils.NetUtils;
import us.kbase.kbasejobservice.FinishJobParams;
import us.kbase.mobu.ModuleBuilder;
import us.kbase.mobu.tester.SDKCallbackServer;
import us.kbase.mobu.util.DirUtils;
import us.kbase.mobu.util.ProcessHelper;
public class ModuleRunner {
private final URL catalogUrl;
private final String kbaseEndpoint;
private final File runDir;
private String user;
private String password;
public ModuleRunner(String sdkHome) throws Exception {
if (sdkHome == null) {
sdkHome = System.getenv(ModuleBuilder.GLOBAL_SDK_HOME_ENV_VAR);
if (sdkHome == null)
throw new IllegalStateException("Path to kb-sdk home folder should be set either" +
" in command line (-h) or in " + ModuleBuilder.GLOBAL_SDK_HOME_ENV_VAR +
" system environment variable");
}
File sdkHomeDir = new File(sdkHome);
if (!sdkHomeDir.exists())
sdkHomeDir.mkdirs();
File sdkCfgFile = new File(sdkHomeDir, "sdk.cfg");
String sdkCfgPath = sdkCfgFile.getCanonicalPath();
if (!sdkCfgFile.exists()) {
System.out.println("Warning: file " + sdkCfgFile.getAbsolutePath() + " will be " +
"initialized (with 'kbase_endpoint'/'catalog_url' pointing to AppDev " +
"environment, user and password will be prompted every time if not set)");
FileUtils.writeLines(sdkCfgFile, Arrays.asList(
"kbase_endpoint=https://appdev.kbase.us/services",
"catalog_url=https://appdev.kbase.us/services/catalog",
"user=",
"password="));
}
Properties sdkConfig = new Properties();
try (InputStream is = new FileInputStream(sdkCfgFile)) {
sdkConfig.load(is);
}
kbaseEndpoint = sdkConfig.getProperty("kbase_endpoint");
if (kbaseEndpoint == null) {
throw new IllegalStateException("Couldn't find 'kbase_endpoint' parameter in " +
sdkCfgFile);
}
String catalogUrlText = sdkConfig.getProperty("catalog_url");
if (catalogUrlText == null) {
throw new IllegalStateException("Couldn't find 'catalog_url' parameter in " +
sdkCfgFile);
}
catalogUrl = new URL(catalogUrlText);
runDir = new File(sdkHomeDir, "run_local");
user = sdkConfig.getProperty("user");
password = sdkConfig.getProperty("password");
if (user == null || user.trim().isEmpty()) {
System.out.println("You haven't preset your user/password in " + sdkCfgPath + ". " +
"Please enter it now.");
user = new String(System.console().readLine("User: "));
password = new String(System.console().readPassword("Password: "));
} else {
if (password == null || password.trim().isEmpty()) {
System.out.println("You haven't preset your password in " + sdkCfgPath + ". " +
"Please enter it now.");
password = new String(System.console().readPassword("Password: "));
}
}
}
public ModuleRunner(URL catalogUrl, String kbaseEndpoint, File runDir, String user,
String password) {
this.catalogUrl = catalogUrl;
this.kbaseEndpoint = kbaseEndpoint;
this.runDir = runDir;
this.user = user;
this.password = password;
}
public int run(String methodName, File inputFile, boolean stdin, String inputJson,
File output, String tagVer, boolean verbose, boolean keepTempFiles,
String provRefs, String mountPoints) throws Exception {
AuthToken auth = AuthService.login(user, password).getToken();
////////////////////////////////// Loading image name /////////////////////////////////////
CatalogClient client = new CatalogClient(catalogUrl);
String moduleName = methodName.split(Pattern.quote("."))[0];
ModuleVersion mv = client.getModuleVersion(
new SelectModuleVersion().withModuleName(moduleName).withVersion(tagVer)
.withIncludeCompilationReport(1L));
if (mv.getDataVersion() != null)
throw new IllegalStateException("Reference data is required for module " + moduleName +
". This feature is not supported for local calls.");
String dockerImage = mv.getDockerImgName();
System.out.println("Docker image name recieved from Catalog: " + dockerImage);
////////////////////////////////// Standard files in run_local ////////////////////////////
if (!runDir.exists())
runDir.mkdir();
File runLocalSh = new File(runDir, "run_local.sh");
File runDockerSh = new File(runDir, "run_docker.sh");
if (!runLocalSh.exists()) {
FileUtils.writeLines(runLocalSh, Arrays.asList(
"#!/bin/bash",
"sdir=\"$(cd \"$(dirname \"$(readlink -f \"$0\")\")\" && pwd)\"",
"callback_url=$1",
"cnt_id=$2",
"docker_image=$3",
"mount_points=$4",
"$sdir/run_docker.sh run -v $sdir/workdir:/kb/module/work $mount_points " +
"-e \"SDK_CALLBACK_URL=$callback_url\" --name $cnt_id $docker_image async"));
ProcessHelper.cmd("chmod", "+x", runLocalSh.getCanonicalPath()).exec(runDir);
}
if (!runDockerSh.exists()) {
FileUtils.writeLines(runDockerSh, Arrays.asList(
"#!/bin/bash",
"docker \"$@\""));
ProcessHelper.cmd("chmod", "+x", runDockerSh.getCanonicalPath()).exec(runDir);
}
////////////////////////////////// Temporary files ////////////////////////////////////////
StringBuilder mountPointsDocker = new StringBuilder();
if (mountPoints != null) {
for (String part : mountPoints.split(Pattern.quote(","))) {
String[] fromTo = part.split(Pattern.quote(":"));
if (fromTo.length != 2)
throw new IllegalStateException("Unexpected mount point format: " + part);
String from = new File(fromTo[0]).getCanonicalPath();
String to = fromTo[1];
if (!to.startsWith("/"))
to = "/kb/module/work/" + to;
if (mountPointsDocker.length() > 0)
mountPointsDocker.append(" ");
mountPointsDocker.append("-v ").append(from).append(":").append(to);
}
}
File workDir = new File(runDir, "workdir");
if (workDir.exists())
FileUtils.deleteDirectory(workDir);
workDir.mkdir();
File subjobsDir = new File(runDir, "subjobs");
if (subjobsDir.exists())
FileUtils.deleteDirectory(subjobsDir);
File tokenFile = new File(workDir, "token");
try (FileWriter fw = new FileWriter(tokenFile)) {
fw.write(auth.toString());
}
String jobSrvUrl = kbaseEndpoint + "/userandjobstate";
String wsUrl = kbaseEndpoint + "/ws";
String shockUrl = kbaseEndpoint + "/shock-api";
File configPropsFile = new File(workDir, "config.properties");
PrintWriter pw = new PrintWriter(configPropsFile);
try {
pw.println("[global]");
pw.println("job_service_url = " + jobSrvUrl);
pw.println("workspace_url = " + wsUrl);
pw.println("shock_url = " + shockUrl);
pw.println("kbase_endpoint = " + kbaseEndpoint);
} finally {
pw.close();
}
////////////////////////////////// Preparing input.json ///////////////////////////////////
String jsonString;
if (inputFile != null) {
jsonString = FileUtils.readFileToString(inputFile);
} else if (inputJson != null) {
jsonString = inputJson;
} else if (stdin) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(System.in, baos);
jsonString = new String(baos.toByteArray(), Charset.forName("utf-8"));
} else {
throw new IllegalStateException("No one input method is used");
}
jsonString = jsonString.trim();
if (!jsonString.startsWith("["))
jsonString = "[" + jsonString + "]"; // Wrapping one argument by array
if (verbose)
System.out.println("Input parameters: " + jsonString);
Map<String, Object> rpc = new LinkedHashMap<String, Object>();
rpc.put("version", "1.1");
rpc.put("method", methodName);
List<UObject> params = UObject.getMapper().readValue(jsonString,
new TypeReference<List<UObject>>() {});
rpc.put("params", params);
rpc.put("context", new LinkedHashMap<String, Object>());
UObject.getMapper().writeValue(new File(workDir, "input.json"), rpc);
////////////////////////////////// Starting callback service //////////////////////////////
int callbackPort = NetUtils.findFreePort();
URL callbackUrl = CallbackServer.getCallbackUrl(callbackPort);
Server jettyServer = null;
if (callbackUrl != null) {
if( System.getProperty("os.name").startsWith("Windows") ) {
JsonServerSyslog.setStaticUseSyslog(false);
JsonServerSyslog.setStaticMlogFile(
new File(workDir, "callback.log").getCanonicalPath());
}
CallbackServerConfig cfg = new CallbackServerConfigBuilder(
new URL(kbaseEndpoint), callbackUrl, runDir.toPath(),
new LineLogger() {
@Override
public void logNextLine(String line, boolean isError) {
//do nothing, SDK callback server doesn't use a logger
}
}).build();
Set<String> releaseTags = new TreeSet<String>(mv.getReleaseTags());
System.out.println("Release tags: " + releaseTags);
String requestedRelease = null;
final ModuleRunVersion runver = new ModuleRunVersion(
new URL(mv.getGitUrl()), new ModuleMethod(methodName),
mv.getGitCommitHash(), mv.getVersion(),
requestedRelease);
List<String> inputWsObjects = new ArrayList<String>();
if (provRefs != null) {
inputWsObjects.addAll(Arrays.asList(provRefs.split(Pattern.quote(","))));
}
JsonServerServlet catalogSrv = new SDKCallbackServer(
auth, cfg, runver, params, inputWsObjects);
jettyServer = new Server(callbackPort);
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.SESSIONS);
context.setContextPath("/");
jettyServer.setHandler(context);
|
package jmetest.renderer;
import java.util.logging.Logger;
import com.jme.app.SimpleGame;
import com.jme.bounding.BoundingSphere;
import com.jme.image.Texture;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.Renderer;
import com.jme.renderer.TextureRenderer;
import com.jme.scene.Node;
import com.jme.scene.shape.Box;
import com.jme.scene.state.TextureState;
import com.jme.scene.state.ZBufferState;
import com.jme.util.TextureManager;
public class TestMultipleTexRender extends SimpleGame {
private static final Logger logger = Logger
.getLogger(TestMultipleTexRender.class.getName());
private Box realBox, realBox2, monkeyBox;
private Node fakeScene;
private Quaternion rotQuat = new Quaternion();
private Quaternion rotMBQuat = new Quaternion();
private Vector3f axis = new Vector3f(1, 1, 0.5f);
private float angle = 0;
private float angle2 = 0;
private TextureRenderer tRenderer;
private Texture fakeTex, fakeTex2;
private float lastRend = 1;
/**
* Entry point for the test,
* @param args
*/
public static void main(String[] args) {
TestMultipleTexRender app = new TestMultipleTexRender();
app.setDialogBehaviour(ALWAYS_SHOW_PROPS_DIALOG);
app.start();
}
protected void cleanup() {
tRenderer.cleanup();
super.cleanup();
}
protected void simpleUpdate() {
if (tpf < 1) {
angle = angle + (tpf * -.25f);
angle2 = angle2 + (tpf * 1);
if (angle < 0) {
angle = 360 - .25f;
}
if (angle2 >= 360) {
angle2 = 0;
}
}
rotQuat.fromAngleAxis(angle, axis);
rotMBQuat.fromAngleAxis(angle2, axis);
realBox.setLocalRotation(rotQuat);
monkeyBox.setLocalRotation(rotMBQuat);
fakeScene.updateGeometricState(0.0f, true);
}
protected void simpleRender() {
lastRend += tpf;
if (lastRend > .03f) {
tRenderer.render(fakeScene, fakeTex);
tRenderer.render(fakeScene, fakeTex2);
lastRend = 0;
}
}
@Override
protected void simpleInitGame() {
display.setTitle("Render to Texture");
cam.setLocation(new Vector3f(0, 0, 25));
cam.update();
// Setup dimensions for a box
Vector3f max = new Vector3f(5, 5, 5);
Vector3f min = new Vector3f( -5, -5, -5);
// Make the real world box -- you'll see this spinning around.. woo...
realBox = new Box("Box", min, max);
realBox.setModelBound(new BoundingSphere());
realBox.updateModelBound();
realBox.setLocalTranslation(new Vector3f(0, 0, 0));
//FIX ME: if the box is put into a queue the texture rendering has to be done before the scene rendering!
//realBox.setRenderQueueMode(Renderer.QUEUE_OPAQUE);
rootNode.attachChild(realBox);
realBox2 = new Box("Box", min, max);
realBox2.setModelBound(new BoundingSphere());
realBox2.updateModelBound();
realBox2.setLocalTranslation(new Vector3f(10, 0, 0));
//FIX ME: if the box is put into a queue the texture rendering has to be done before the scene rendering!
//realBox.setRenderQueueMode(Renderer.QUEUE_OPAQUE);
rootNode.attachChild(realBox2);
// Make a monkey box -- some geometry that will be rendered onto a flat texture.
// First, we'd like the box to be bigger, so...
min.multLocal(3);
max.multLocal(3);
monkeyBox = new Box("Fake Monkey Box", min, max);
monkeyBox.setModelBound(new BoundingSphere());
monkeyBox.updateModelBound();
monkeyBox.setLocalTranslation(new Vector3f(0, 0, 0));
// add the monkey box to a node. This node is a root node, not part of the "real world" tree.
fakeScene = new Node("Fake node");
fakeScene.setRenderQueueMode(Renderer.QUEUE_SKIP);
fakeScene.attachChild(monkeyBox);
// Setup our params for the depth buffer
ZBufferState buf = display.getRenderer().createZBufferState();
buf.setEnabled(true);
buf.setFunction(ZBufferState.CF_LEQUAL);
fakeScene.setRenderState(buf);
// Lets add a monkey texture to the geometry we are going to rendertotexture...
TextureState ts = display.getRenderer().createTextureState();
ts.setEnabled(true);
Texture tex = TextureManager.loadTexture(
TestMultipleTexRender.class.getClassLoader().getResource(
"jmetest/data/images/Monkey.jpg"),
Texture.MM_LINEAR_LINEAR,
Texture.FM_LINEAR);
ts.setTexture(tex);
fakeScene.setRenderState(ts);
// Ok, now lets create the Texture object that our monkey cube will be rendered to.
tRenderer = display.createTextureRenderer(512, 512, TextureRenderer.RENDER_TEXTURE_2D);
tRenderer.setBackgroundColor(new ColorRGBA(.667f, .667f, .851f, 1f));
fakeTex = new Texture();
fakeTex.setWrap(Texture.WM_CLAMP_S_CLAMP_T);
fakeTex2 = new Texture();
fakeTex2.setWrap(Texture.WM_CLAMP_S_CLAMP_T);
if ( tRenderer.isSupported() ) {
tRenderer.setMultipleTargets(true);
tRenderer.setupTexture(fakeTex);
tRenderer.setupTexture(fakeTex2);
tRenderer.getCamera().setLocation(new Vector3f(0, 0, 75f));
} else {
logger.severe("Render to texture not supported!");
}
// Now add that texture to the "real" cube.
ts = display.getRenderer().createTextureState();
ts.setEnabled(true);
ts.setTexture(fakeTex, 0);
// Heck, while we're at it, why not add another texture to blend with.
Texture tex2 = TextureManager.loadTexture(
TestMultipleTexRender.class.getClassLoader().getResource(
"jmetest/data/texture/dirt.jpg"),
Texture.MM_LINEAR_LINEAR,
Texture.FM_LINEAR);
ts.setTexture(tex2, 1);
realBox.setRenderState(ts);
// Now add that texture to the "real" cube.
ts = display.getRenderer().createTextureState();
ts.setEnabled(true);
ts.setTexture(fakeTex2, 0);
// Heck, while we're at it, why not add another texture to blend with.
tex2 = TextureManager.loadTexture(
TestMultipleTexRender.class.getClassLoader().getResource(
"jmetest/data/texture/dirt.jpg"),
Texture.MM_LINEAR_LINEAR,
Texture.FM_LINEAR);
ts.setTexture(tex2, 1);
realBox2.setRenderState(ts);
// Since we have 2 textures, the geometry needs to know how to split up the coords for the second state.
realBox.copyTextureCoords(0, 0, 1);
realBox2.copyTextureCoords(0, 0, 1);
fakeScene.updateGeometricState(0.0f, true);
fakeScene.updateRenderState();
}
}
|
package battlecode.common;
/**
* A RobotController allows contestants to make their robot sense and interact
* with the game world. When a contestant's <code>RobotPlayer</code> is
* constructed, it is passed an instance of <code>RobotController</code> that
* controls the newly created robot.
*/
@SuppressWarnings("unused")
public strictfp interface RobotController {
/**
* Returns the number of rounds in the game. After this many rounds, if neither
* team has been destroyed, tiebreakers will be used.
*
* @return the number of rounds in the game.
*
* @battlecode.doc.costlymethod
*/
int getRoundLimit();
/**
* Returns the current round number, where round 0 is the first round of the
* match.
*
* @return the current round number, where round 0 is the first round of the
* match.
*
* @battlecode.doc.costlymethod
*/
int getRoundNum();
/**
* Returns the team's total bullet supply.
*
* @return the team's total bullet supply.
*
* @battlecode.doc.costlymethod
*/
float getTeamBullets();
/**
* Returns the team's total victory points.
*
* @return the team's total victory points.
*
* @battlecode.doc.costlymethod
*/
int getTeamVictoryPoints();
/**
* Returns your opponent's total victory points.
*
* @return your opponent's total victory points.
*
* @battlecode.doc.costlymethod
*/
int getOpponentVictoryPoints();
/**
* Returns the number of robots on your team, including your archons.
* If this number ever reaches zero, the opposing team will automatically
* win by destruction.
*
* @return the number of robots on your team, including your archons.
*
* @battlecode.doc.costlymethod
*/
int getRobotCount();
/**
* Returns the number of trees on your team.
*
* @return the number of trees on your team.
*
* @battlecode.doc.costlymethod
*/
int getTreeCount();
/**
* Returns a list of the INITIAL locations of the archons of a particular
* team. The locations will be sorted by increasing x, with ties broken by
* increasing y. Will return an empty list if you query for {@code Team.NEUTRAL}.
*
* @param t the team for which you want to query the initial archon
* locations. Will return an empty list if you query for Team.NEUTRAL
* @return a list of the INITIAL locations of the archons of that team, or
* an empty list for Team.NEUTRAL.
*
* @battlecode.doc.costlymethod
*/
MapLocation[] getInitialArchonLocations(Team t);
/**
* Returns the ID of this robot.
*
* @return the ID of this robot.
*
* @battlecode.doc.costlymethod
*/
int getID();
/**
* Returns this robot's Team.
*
* @return this robot's Team.
*
* @battlecode.doc.costlymethod
*/
Team getTeam();
/**
* Returns this robot's type (SOLDIER, ARCHON, etc.).
*
* @return this robot's type.
*
* @battlecode.doc.costlymethod
*/
RobotType getType();
/**
* Returns this robot's current location.
*
* @return this robot's current location.
*
* @battlecode.doc.costlymethod
*/
MapLocation getLocation();
/**
* Returns this robot's current health.
*
* @return this robot's current health.
*
* @battlecode.doc.costlymethod
*/
float getHealth();
/**
* Returns the number of times the robot has attacked this turn.
*
* @return the number of times the robot has attacked this turn.
*
* @battlecode.doc.costlymethod
*/
int getAttackCount();
/**
* Returns the number of times the robot has moved this turn.
*
* @return the number of times the robot has moved this turn.
*
* @battlecode.doc.costlymethod
*/
int getMoveCount();
/**
* Senses whether a MapLocation is on the map. Will throw an exception if
* the location is not currently within sensor range.
*
* @param loc the location to check
* @return true if the location is on the map; false otherwise.
* @throws GameActionException if the location is not within sensor range.
*
* @battlecode.doc.costlymethod
*/
boolean onTheMap(MapLocation loc) throws GameActionException;
/**
* Senses whether a given circle is completely on the map. Will throw an exception if
* the circle is not completely within sensor range.
*
* @param center the center of the circle to check
* @param radius the radius of the circle to check
* @return true if the circle is completely on the map; false otherwise.
* @throws GameActionException if any portion of the given circle is not within sensor range.
*
* @battlecode.doc.costlymethod
*/
boolean onTheMap(MapLocation center, float radius) throws GameActionException;
/**
* Senses whether the given location is within the robot's bullet sense range.
*
* @param loc the location to check
* @return true if the given location is within the robot's bullet sense range, false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canSenseBulletLocation(MapLocation loc);
/**
* Senses whether the given location is within the robot's sensor range.
*
* @param loc the location to check
* @return true if the given location is within the robot's sensor range; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canSenseLocation(MapLocation loc);
/**
* Senses whether a point at the given radius is within the robot's sensor range.
*
* @param radius the radius to check
* @return true if the given location is within the robot's sensor range; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canSenseRadius(float radius);
/**
* Senses whether any portion of the given circle is within the robot's sensor range.
*
* @param center the center of the circle to check
* @param radius the radius of the circle to check
* @return true if a portion of the circle is within the robot's sensor range; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canSensePartOfCircle(MapLocation center, float radius);
/**
* Senses whether all of the given circle is within the robot's sensor range.
*
* @param center the center of the circle to check
* @param radius the radius of the circle to check
* @return true if all of the circle is within the robot's sensor range; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canSenseAllOfCircle(MapLocation center, float radius);
/**
* Senses whether there is a robot or tree at the given location.
*
* @param loc the location to check
* @return true if there is a robot or tree at the given location; false otherwise.
* @throws GameActionException if the location is not within sensor range.
*
* @battlecode.doc.costlymethod
*/
boolean isLocationOccupied(MapLocation loc) throws GameActionException;
/**
* Senses whether there is a tree at the given location.
*
* @param loc the location to check.
* @return true if there is a tree at the given location; false otherwise.
* @throws GameActionException if the location is not within sensor range.
*
* @battlecode.doc.costlymethod
*/
boolean isLocationOccupiedByTree(MapLocation loc) throws GameActionException;
/**
* Senses whether there is a robot at the given location.
*
* @param loc the location to check
* @return true if there is a robot at the given location; false otherwise.
* @throws GameActionException if the location is not within sensor range.
*
* @battlecode.doc.costlymethod
*/
boolean isLocationOccupiedByRobot(MapLocation loc) throws GameActionException;
/**
* Senses whether there is any robot or tree within a given circle.
*
* @param center the center of the circle to check
* @param radius the radius of the circle to check
* @return true if there is a robot or tree in the given circle; false otherwise.
* @throws GameActionException if any portion of the given circle is not within sensor range.
*
* @battlecode.doc.costlymethod
*/
boolean isCircleOccupied(MapLocation center, float radius) throws GameActionException;
/**
* Senses whether there is any robot or tree within a given circle, ignoring this robot
* if it itself occupies the circle.
*
* @param center the center of the circle to check
* @param radius the radius of the circle to check
* @return true if there is a robot or tree in the given circle; false otherwise.
* @throws GameActionException if any portion of the given circle is not within sensor range.
*
* @battlecode.doc.costlymethod
*/
boolean isCircleOccupiedExceptByThisRobot(MapLocation center, float radius) throws GameActionException;
/**
* Senses the tree at the given location, or null if there is no tree
* there.
*
* @param loc the location to check
* @return the tree at the given location.
* @throws GameActionException if the location is not within sensor range.
*
* @battlecode.doc.costlymethod
*/
TreeInfo senseTreeAtLocation(MapLocation loc) throws GameActionException;
/**
* Senses the robot at the given location, or null if there is no robot
* there.
*
* @param loc the location to check
* @return the robot at the given location.
* @throws GameActionException if the location is not within sensor range.
*
* @battlecode.doc.costlymethod
*/
RobotInfo senseRobotAtLocation(MapLocation loc) throws GameActionException;
/**
* Tests whether the given tree exists and any part of the given tree is
* within this robot's sensor range.
*
* @param id the ID of the tree to query
* @return true if the given tree is within this robot's sensor range; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canSenseTree(int id);
/**
* Tests whether the given robot exists and any part of the given robot is
* within this robot's sensor range.
*
* @param id the ID of the robot to query
* @return true if the given robot is within this robot's sensor range; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canSenseRobot(int id);
/**
* Tests the given bullet exists and it is within this robot's
* sensor range.
*
* @param id the ID of the bullet to query
* @return true if the given bullet is within this robot's sensor range; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canSenseBullet(int id);
/**
* Senses information about a particular tree given its ID.
*
* @param id the ID of the tree to query
* @return a TreeInfo object for the sensed tree.
* @throws GameActionException if the tree cannot be sensed (for example,
* if it doesn't exist or is out of sight range).
*
* @battlecode.doc.costlymethod
*/
TreeInfo senseTree(int id) throws GameActionException;
/**
* Senses information about a particular robot given its ID.
*
* @param id the ID of the robot to query
* @return a RobotInfo object for the sensed robot.
* @throws GameActionException if the robot cannot be sensed (for example,
* if it doesn't exist or is out of sight range).
*
* @battlecode.doc.costlymethod
*/
RobotInfo senseRobot(int id) throws GameActionException;
/**
* Senses information about a particular bullet given its ID.
*
* @param id the ID of the bullet to query
* @return a BulletInfo object for the sensed bullet.
* @throws GameActionException if the bullet cannot be sensed (for example,
* if it doesn't exist or is out of sight range).
*
* @battlecode.doc.costlymethod
*/
BulletInfo senseBullet(int id) throws GameActionException;
/**
* Returns all robots within sense radius. The objects are returned in order of
* increasing distance from your robot.
*
* @return sorted array of RobotInfo objects, which contain information about all
* the robots you sensed.
*
* @battlecode.doc.costlymethod
*/
RobotInfo[] senseNearbyRobots();
/**
* Returns all robots that can be sensed within a certain radius of this
* robot. The objects are returned in order of increasing distance from
* your robot.
*
* @param radius return robots this distance away from the center of
* this robot. If -1 is passed, all robots within sense radius are returned.
* @return sorted array of RobotInfo objects of all the robots you sensed.
*
* @battlecode.doc.costlymethod
*/
RobotInfo[] senseNearbyRobots(float radius);
/**
* Returns all robots of a given team that can be sensed within a certain
* radius of this robot. The objects are returned in order of increasing distance
* from your robot.
*
* @param radius return robots this distance away from the center of
* this robot. If -1 is passed, all robots within sense radius are returned
* @param team filter game objects by the given team. If null is passed,
* robots from any team are returned
* @return sorted array of RobotInfo objects of all the robots you sensed.
*
* @battlecode.doc.costlymethod
*/
RobotInfo[] senseNearbyRobots(float radius, Team team);
/**
* Returns all robots of a given team that can be sensed within a certain
* radius of a specified location. The objects are returned in order of
* increasing distance from the specified center.
*
* @param center center of the given search radius
* @param radius return robots this distance away from the given center
* location. If -1 is passed, all robots within sense radius are returned
* @param team filter game objects by the given team. If null is passed,
* objects from all teams are returned
* @return sorted array of RobotInfo objects of the robots you sensed.
*
* @battlecode.doc.costlymethod
*/
RobotInfo[] senseNearbyRobots(MapLocation center, float radius, Team team);
/**
* Returns all trees within sense radius. The objects are returned in order
* of increasing distance from your robot.
*
* @return sorted array of TreeInfo objects, which contain information about all
* the trees you sensed.
*
* @battlecode.doc.costlymethod
*/
TreeInfo[] senseNearbyTrees();
/**
* Returns all trees that can be sensed within a certain radius of this
* robot. The objects are returned in order of increasing distance from
* your robot.
*
* @param radius return trees this distance away from the center of
* this robot. If -1 is passed, all trees within sense radius are returned
* @return sorted array of TreeInfo objects of all the trees you sensed.
*
* @battlecode.doc.costlymethod
*/
TreeInfo[] senseNearbyTrees(float radius);
/**
* Returns all trees of a given team that can be sensed within a certain
* radius of this robot. The objects are returned in order of increasing distance
* from your robot.
*
* @param radius return trees this distance away from the center of
* this robot. If -1 is passed, all trees within sense radius are returned
* @param team filter game objects by the given team. If null is passed,
* robots from any team are returned
* @return sorted array of TreeInfo objects of all the trees you sensed.
*
* @battlecode.doc.costlymethod
*/
TreeInfo[] senseNearbyTrees(float radius, Team team);
/**
* Returns all trees of a given team that can be sensed within a certain
* radius of a specified location. The objects are returned in order of
* increasing distance from the specified center.
*
* @param center center of the given search radius
* @param radius return trees this distance away from given center
* location. If -1 is passed, all trees within sense radius are returned
* @param team filter game objects by the given team. If null is passed,
* objects from all teams are returned
* @return sorted array of TreeInfo objects of the trees you sensed.
*
* @battlecode.doc.costlymethod
*/
TreeInfo[] senseNearbyTrees(MapLocation center, float radius, Team team);
/**
* Returns all bullets within bullet sense radius. The objects are returned in
* order of increasing distance from your robot.
*
* @return sorted array of BulletInfo objects, which contain information about all
* the bullets you sensed.
*
* @battlecode.doc.costlymethod
*/
BulletInfo[] senseNearbyBullets();
/**
* Returns all bullets that can be sensed within a certain radius of this
* robot. The objects are returned in order of increasing distance from
* your robot.
*
* @param radius return bullets this distance away from the center of
* this robot. If -1 is passed, bullets from the whole map are returned
* @return sorted array of BulletInfo objects of all the bullets you sensed.
*
* @battlecode.doc.costlymethod
*/
BulletInfo[] senseNearbyBullets(float radius);
/**
* Returns all bullets that can be sensed within a certain
* radius of a specified location. The objects are returned in order of
* increasing distance from the specified center.
*
* @param center center of the given search radius
* @param radius return bullets this distance away from the given center
* location. If -1 is passed, all bullets within bullet sense radius are returned
* @return sorted array of TreeInfo objects of the bullets you sensed.
*
* @battlecode.doc.costlymethod
*/
BulletInfo[] senseNearbyBullets(MapLocation center, float radius);
/**
* Returns an array of all the locations of the robots that have
* broadcasted in the last round (unconstrained by sensor range or distance).
*
* @return an array of all the locations of the robots that have
* broadcasted in the last round.
*
* @battlecode.doc.costlymethod
*/
MapLocation[] senseBroadcastingRobotLocations();
/**
* Returns whether the robot has moved this turn.
*
* @return true if the robot has moved this turn; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean hasMoved();
/**
* Returns whether the robot has attacked this turn.
*
* @return true if the robot has attacked this turn; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean hasAttacked();
/**
* Returns whether the robot's build cooldown has expired.
*
* @return true if the robot's build cooldown has expired; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean isBuildReady();
/**
* Returns the number of cooldown turns remaining before this unit can build() again.
* When this number is 0, isBuildReady() is true.
*
* @return the number of cooldown turns remaining before this unit can build() again.
*
* @battlecode.doc.costlymethod
*/
int getBuildCooldownTurns();
/**
* Tells whether this robot can move one stride in the given direction,
* without taking into account if they have already moved. Takes into account only
* the positions of trees, positions of other robots, and the edge of the
* game map. Does not take into account whether this robot is currently
* active. Note that one stride is equivalent to this robot's {@code strideRadius}.
*
* @param dir the direction to move in
* @return true if there is no external obstruction to prevent this robot
* from moving one stride in the given direction; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canMove(Direction dir);
/**
* Tests whether this robot can move {@code distance} units in the given
* direction, without taking into account if they have already moved. Takes into
* account only the positions of trees, positions of other robots, and the
* edge of the game map. Does not take into account whether this robot is
* currently active. Note that one stride is equivalent to this robot's
* {@code strideRadius}.
*
* @param dir the direction to move in
* @param distance the distance of a move you wish to check. Must be
* in [0, RobotType.strideRadius]
* @return true if there is no external obstruction to prevent this robot
* from moving distance in the given direction; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canMove(Direction dir, float distance);
/**
* Tests whether this robot can move to the target MapLocation. If
* the location is outside the robot's {@code strideRadius}, the location
* is rescaled to be at the {@code strideRadius}. Takes into account only
* the positions of trees, other robots, and the edge of the game map. Does
* not take into account whether this robot is currently active.
*
* @param center the MapLocation to move to
* @return true if there is no external obstruction to prevent this robot
* from moving to this MapLocation (or in the direction of this MapLocation
* if it is too far); false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canMove(MapLocation center);
/**
* Moves one stride in the given direction. Note that one stride is equivalent
* to this robot's {@code strideRadius}.
*
* @param dir the direction to move in
* @throws GameActionException if the robot cannot move one stride in this
* direction, such as already moved that turn, the target location being
* off the map, and the target destination being occupied with either
* another robot or a tree.
*
* @battlecode.doc.costlymethod
*/
void move(Direction dir) throws GameActionException;
/**
* Moves distance in the given direction. If the distance exceeds the robot's
* {@code strideRadius}, it is rescaled to {@code strideRadius}.
*
* @param dir the direction to move in
* @param distance the distance to move in that direction
* @throws GameActionException if the robot cannot move distance in this
* direction, such as already moved that turn, the target location being
* off the map, and the target destination being occupied with either
* another robot or a tree.
*
* @battlecode.doc.costlymethod
*/
void move(Direction dir, float distance) throws GameActionException;
/**
* Moves to the target MapLocation. If the target location is outside the robot's
* {@code strideRadius}, it is rescaled to be {@code strideRadius} away.
*
* @param center the MapLocation to move to (or toward)
* @throws GameActionException if the robot can not move to the target MapLocation,
* such as already having moved that turn, the target location being off the map,
* or a target destination being occupied with either another robot or a tree.
*
* @battlecode.doc.costlymethod
*/
void move(MapLocation center) throws GameActionException;
/**
* Tests whether a robot is able to strike this turn. This takes into accout
* the robot's type, and if the robot has attacked this turn.
*
* @return true if the robot is able to strike this turn; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canStrike();
/**
* Strikes and deals damage to all other robots and trees within
* {@link GameConstants#LUMBERJACK_STRIKE_RADIUS} of this robot. Note that only Lumberjacks
* can perform this function.
*
* @throws GameActionException if the robot is not of type LUMBERJACK or
* cannot attack due to having already attacked that turn.
*
* @battlecode.doc.costlymethod
*/
void strike() throws GameActionException;
/**
* Tests whether there are enough bullets in your bullet supply to
* fire a single shot, the robot is of an appropriate type, and the
* robot has not attacked in the current turn.
*
* @return true if there are enough bullets in the bullet supply,
* this robot is of an appropriate type, and the robot hasn't attacked
* this turn; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canFireSingleShot();
/**
* Tests whether there are enough bullets in your bullet supply to
* fire a triad shot, the robot is of an appropriate type, and the
* robot has not attacked in the current turn.
*
* @return true if there are enough bullets in the bullet supply,
* this robot is of an appropriate type, and the robot hasn't attacked
* this turn; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canFireTriadShot();
/**
* Tests whether there is enough bullets in your bullet supply to
* fire a pentad shot, the robot is of an appropriate type, and the
* robot has not attacked in the current turn.
*
* @return true if there are enough bullets in the bullet supply,
* this robot is of an appropriate type, and the robot hasn't attacked
* this turn; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canFirePentadShot();
/**
* Fires a single bullet in the direction dir at the cost of
* {@link GameConstants#SINGLE_SHOT_COST} from your team's bullet supply. The speed
* and damage of the bullet is determined from the type of this robot.
*
* @param dir the direction you wish to fire the bullet
* @throws GameActionException if this robot is not of a type that can
* fire single shots (ARCHON, GARDENER, etc.), cannot attack due to having
* already attacked, or for having insufficient bullets in the bullet supply.
*
* @battlecode.doc.costlymethod
*/
void fireSingleShot(Direction dir) throws GameActionException;
/**
* Fires a three bullets with the center bullet in the direction dir and
* with a spread of {@link GameConstants#TRIAD_SPREAD_DEGREES} degrees for the other
* bullets. This function costs {@link GameConstants#TRIAD_SHOT_COST} bullets from
* your team's supply. The speed and damage of the bullets is determined
* from the type of this robot.
*
* @param dir the direction you wish to fire the center bullet
* @throws GameActionException if this robot is not of a type that can
* fire triad shots (ARCHON, GARDENER, etc.), cannot attack due to having
* already attacked, or for having insufficient bullets in the bullet supply.
*
* @battlecode.doc.costlymethod
*/
void fireTriadShot(Direction dir) throws GameActionException;
/**
* Fires a five bullets with the center bullet in the direction dir and
* with a spread of {@link GameConstants#PENTAD_SPREAD_DEGREES} degrees for the other
* bullets. This function costs {@link GameConstants#PENTAD_SHOT_COST} bullets from
* your team's supply. The speed and damage of the bullets is determined
* from the type of this robot.
*
* @param dir the direction you wish to fire the center bullet
* @throws GameActionException if this robot is not of a type that can
* fire pentad shots (ARCHON, GARDENER, etc.), cannot attack due to having
* already attacked, or for having insufficient bullets in the bullet supply.
*
* @battlecode.doc.costlymethod
*/
void firePentadShot(Direction dir) throws GameActionException;
/**
* Tests whether the robot can chop a tree at the given location.
* Checks if the location is within {@link GameConstants#INTERACTION_DIST_FROM_EDGE},
* the robot's type, if a tree exists, and if the robot hasn't attacked this turn.
*
* @param loc The location of the tree to chop
* @return true if this robot can chop the tree; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canChop(MapLocation loc);
/**
* Tests whether the robot can chop a tree with the given ID. Checks if the tree is within
* {@link GameConstants#INTERACTION_DIST_FROM_EDGE}, the robot's type,
* if a tree exists, and if the robot hasn't attacked this turn.
*
* @param id The ID of the tree to chop
* @return true if this robot can chop the tree; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canChop(int id);
/**
* Chops the tree at the given location. This action counts as an attack.
*
* @param loc the location of the tree to chop
* @throws GameActionException if the given location does not contain
* a tree, the specified tree is not within {@link GameConstants#INTERACTION_DIST_FROM_EDGE}
* of this robot, this robot is not of type LUMBERJACK, or this robot has already attacked
* this turn.
*
* @battlecode.doc.costlymethod
*/
void chop(MapLocation loc) throws GameActionException;
/**
* Chops the tree with the given ID. This action counts as an attack.
*
* @param id the ID of the tree you wish to chop
* @throws GameActionException if there isn't a tree with the given id,
* the specified tree is not within one stride of this robot, this robot
* is not of type LUMBERJACK, or this robot has already attacked this turn.
*
* @battlecode.doc.costlymethod
*/
void chop(int id) throws GameActionException;
/**
* Tests whether this robot can shake a tree at the given location. Checks
* if the tree is within {@link GameConstants#INTERACTION_DIST_FROM_EDGE},
* if a tree exists, and if the robot hasn't shaken this turn.
*
* @param loc The location of the tree to shake
* @return true if this robot can shake the tree; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canShake(MapLocation loc);
/**
* Tests whether this robot can shake a tree with the given ID. Checks if the
* tree is within {@link GameConstants#INTERACTION_DIST_FROM_EDGE},
* if a tree exists, and if the robot hasn't shaken this turn.
*
* @param id The ID of the tree to shake
* @return true if this robot can shake the tree; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canShake(int id);
/**
* Shakes the tree at the given location for all the bullets held within
* the tree; these bullets will be added to your team's bullet supply.
* Robots can only shake once per turn.
*
* @param loc the location of the tree to shake
* @throws GameActionException if the given location does not contain
* a tree, if the tree (not location) is not within {@link GameConstants#INTERACTION_DIST_FROM_EDGE}
* of this robot, or if this robot has already shaken a tree this turn.
*
* @battlecode.doc.costlymethod
*/
void shake(MapLocation loc) throws GameActionException;
/**
* Shakes the tree with the given ID for all the bullets held within
* the tree; these bullets will be added to your team's bullet supply.
* Robots can only shake once per turn.
*
* @param id the ID of the tree to shake
* @throws GameActionException if there isn't a tree with the given id,
* if the tree (not location) is not within one stride of this robot,
* or if this robot has already shaken a tree this turn
*
* @battlecode.doc.costlymethod
*/
void shake(int id) throws GameActionException;
/**
* Tests whether this robot can water a tree at the given location. Checks robot
* stride radius, the robot's type, if a tree exists, and if the robot hasn't
* watered this turn.
*
* @param loc The location of the tree to water
* @return true if this robot can water the tree; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canWater(MapLocation loc);
/**
* Tests whether this robot can water a tree with the given ID. Checks that the tree is within
* {@link GameConstants#INTERACTION_DIST_FROM_EDGE}, the robot's type, if a tree exists, and
* if the robot hasn't watered this turn.
*
* @param id The ID of a tree to check.
* @return true if this robot can water a tree; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canWater(int id);
/**
* Waters the target tree at the given location, restoring
* {@code WATER_HEALTH_REGEN_RATE} health to the tree.
* Robots can only water once per turn and only with robots
* of type GARDENER.
*
* @param loc the location of the tree you wish to water
* @throws GameActionException if the given location does not contain
* a tree, the tree is not within {@link GameConstants#INTERACTION_DIST_FROM_EDGE} of this robot,
* this robot is not of type GARDENER, or this robot has already
* watered a tree.
*
* @battlecode.doc.costlymethod
*/
void water(MapLocation loc) throws GameActionException;
/**
* Waters the target tree with the given ID, restoring
* {@link GameConstants#WATER_HEALTH_REGEN_RATE} health to the tree.
* Robots can only water once per turn and only with robots
* of type GARDENER.
*
* @param id the ID of the tree you wish to water.
* @throws GameActionException if there isn't a tree with the given id,
* the tree is not within {@link GameConstants#INTERACTION_DIST_FROM_EDGE} of this robot,
* this robot is not of type GARDENER, or this robot has already
* watered a tree.
*
* @battlecode.doc.costlymethod
*/
void water(int id) throws GameActionException;
/**
* Tests whether this robot can water a tree, taking into
* account how many times this robot has watered this turn and this
* robot's type.
*
* @return true if this robot can water a tree; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canWater();
/**
* Tests whether this robot can shake a tree, taking into
* account how many times this robot has shaken this turn.
*
* @return true if this robot can shake a tree; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean canShake();
/**
* Tests whether there is a tree at the given location and, if so,
* if the tree is within one stride of this robot and can therefore be
* interacted with through chop(), shake(), or water().
*
* @param loc the location you wish to test
* @return true if there is a tree located at loc and if said tree is
* within {@link GameConstants#INTERACTION_DIST_FROM_EDGE} of this robot.
*
* @battlecode.doc.costlymethod
*/
boolean canInteractWithTree(MapLocation loc);
/**
* Tests whether there is a tree with the given ID and, if so,
* if the tree is within one stride of this robot and can therefore be
* interacted with through chop(), shake(), or water().
*
* @param id the ID of the tree you wish to test
* @return true if there is a tree with id and if said tree is
* within {@link GameConstants#INTERACTION_DIST_FROM_EDGE} of this robot.
*
* @battlecode.doc.costlymethod
*/
boolean canInteractWithTree(int id);
/**
* Broadcasts an integer to the team-shared array at index channel.
* The data is not written until the end of the robot's turn.
*
* @param channel the index to write to, from 0 to <code>BROADCAST_MAX_CHANNELS</code>
* @param data one int of data to write
* @throws GameActionException if the channel is invalid
*
* @see #broadcastInt(int channel, int data)
*
* @battlecode.doc.costlymethod
*/
void broadcast(int channel, int data) throws GameActionException;
/**
* Retrieves the integer stored in the team-shared array at index channel.
*
* @param channel the index to query, from 0 to <code>BROADCAST_MAX_CHANNELS</code>
* @return the data currently stored on the channel, interpreted as an int.
* @throws GameActionException if the channel is invalid
*
* @see #readBroadcastInt(int channel)
*
* @battlecode.doc.costlymethod
*/
int readBroadcast(int channel) throws GameActionException;
/**
* Broadcasts a boolean to the team-shared array at index channel.
* The data is not written until the end of the robot's turn.
*
* @param channel the index to write to, from 0 to <code>BROADCAST_MAX_CHANNELS</code>
* @param data one int of data to write
* @throws GameActionException if the channel is invalid
*
* @battlecode.doc.costlymethod
*/
void broadcastBoolean(int channel, boolean data) throws GameActionException;
/**
* Retrieves the boolean stored in the team-shared array at index channel.
*
* @param channel the index to query, from 0 to <code>BROADCAST_MAX_CHANNELS</code>
* @return the data currently stored on the channel, interpreted as a boolean.
* @throws GameActionException if the channel is invalid
*
* @battlecode.doc.costlymethod
*/
boolean readBroadcastBoolean(int channel) throws GameActionException;
/**
* Broadcasts an int to the team-shared array at index channel.
* The data is not written until the end of the robot's turn.
*
* @param channel the index to write to, from 0 to <code>BROADCAST_MAX_CHANNELS</code>
* @param data one int of data to write
* @throws GameActionException if the channel is invalid
*
* @see #broadcast(int channel, int data)
*
* @battlecode.doc.costlymethod
*/
void broadcastInt(int channel, int data) throws GameActionException;
/**
* Retrieves the int stored in the team-shared array at index channel.
*
* @param channel the index to query, from 0 to <code>BROADCAST_MAX_CHANNELS</code>
* @return the data currently stored on the channel, interpreted as an int.
* @throws GameActionException if the channel is invalid
*
* @see #readBroadcast(int channel)
*
* @battlecode.doc.costlymethod
*/
int readBroadcastInt(int channel) throws GameActionException;
/**
* Broadcasts a float to the team-shared array at index channel.
* The data is not written until the end of the robot's turn.
*
* @param channel the index to write to, from 0 to <code>BROADCAST_MAX_CHANNELS</code>
* @param data one float of data to write
* @throws GameActionException if the channel is invalid
*
* @battlecode.doc.costlymethod
*/
void broadcastFloat(int channel, float data) throws GameActionException;
/**
* Retrieves the float stored in the team-shared array at index channel.
*
* @param channel the index to query, from 0 to <code>BROADCAST_MAX_CHANNELS</code>
* @return the data currently stored on the channel, interpreted as a float.
* @throws GameActionException if the channel is invalid
*
* @battlecode.doc.costlymethod
*/
float readBroadcastFloat(int channel) throws GameActionException;
/**
* Tests whether you have the bullets and dependencies to build the given
* robot, and this robot is a valid builder for the target robot.
*
* @param type the type of robot to build
* @return true if the requirements to build the given robot are met; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean hasRobotBuildRequirements(RobotType type);
/**
* Tests whether you have the bullets and dependencies to build a
* bullet tree, and this robot is a valid builder for a bullet tree.
*
* @return true if the requirements to plant a tree are met; false otherwise.
*
* @battlecode.doc.costlymethod
*/
boolean hasTreeBuildRequirements();
/**
* Tests whether the robot can build a robot of the given type in the
* given direction. Checks cooldown turns remaining, bullet costs,
* whether the robot can build, and that the given direction is
* not blocked.
*
* @param dir the direction to build in
* @param type the type of robot to build
* @return whether it is possible to build a robot of the given type in the
* given direction.
*
* @battlecode.doc.costlymethod
*/
boolean canBuildRobot(RobotType type, Direction dir);
/**
* Builds a robot of the given type in the given direction.
*
* @param dir the direction to spawn the unit
* @param type the type of robot to build
* @throws GameActionException if you don't have enough bullets, if
* the robot is still in build cooldown, if the direction is not a
* good build direction, or if this robot is not of an appropriate type.
*
* @battlecode.doc.costlymethod
*/
void buildRobot(RobotType type, Direction dir) throws GameActionException;
/**
* Tests whether the robot can build a bullet tree in the given direction.
* Checks cooldown turns remaining, bullet costs, whether the robot can
* plant, and that the given direction is not blocked
*
* @param dir the direction to build in
* @return whether it is possible to build a bullet tree in the
* given direction.
*
* @battlecode.doc.costlymethod
*/
boolean canPlantTree(Direction dir);
/**
* Plants a bullet tree in the given direction.
*
* @param dir the direction to plant the bullet tree
* @throws GameActionException if you don't have enough bullets, if
* the robot is still in build cooldown, if the direction is not a good build
* direction, or if this robot is not of an appropriate type.
*
* @battlecode.doc.costlymethod
*/
void plantTree(Direction dir) throws GameActionException;
/**
* Tests whether the robot can hire a Gardener in the given direction.
* Checks cooldown turns remaining, bullet costs, whether the robot can
* hire, and that the given direction is not blocked.
*
* @param dir the direction to build in
* @return whether it is possible to hire a gardener in the given direction.
*
* @battlecode.doc.costlymethod
*/
boolean canHireGardener(Direction dir);
/**
* Hires a Gardener in the given direction.
*
* @param dir the direction to spawn the Gardener
* @throws GameActionException if you don't have enough bullets, if
* the robot is still in build cooldown, if the direction is not a good build
* direction, or if this robot is not of an appropriate type.
*
* @battlecode.doc.costlymethod
*/
void hireGardener(Direction dir) throws GameActionException;
/**
* Returns the current cost of a victory point in bullets. This varies based
* on the round number, and is equal to {@link GameConstants#VP_BASE_COST} +
* NumRounds * {@link GameConstants#VP_INCREASE_PER_ROUND}.
*
* @return the current cost of a victory point in bullets
*
* @battlecode.doc.costlymethod
*/
float getVictoryPointCost();
/**
* Donates the given amount of bullets to the reforestation fund in
* exchange for one victory point per ten bullets donated. Note there
* are no fractions of victory points, meaning, for example, donating
* 11 bullets will only result in 1 victory point, not 1.1 victory points.
*
* @param bullets the amount of bullets you wish to donate
* @throws GameActionException if you have less bullets in your bullet
* supply than the amount of bullet you wish to donate.
*
* @battlecode.doc.costlymethod
*/
void donate(float bullets) throws GameActionException;
/**
* Kills your robot and ends the current round. Never fails.
*
* @battlecode.doc.costlymethod
*/
void disintegrate();
/**
* Causes your team to lose the game. It's like typing "gg."
*
* @battlecode.doc.costlymethod
*/
void resign();
/**
* Draw a dot on the game map for debugging purposes.
*
* @param loc the location to draw the dot.
* @param red the red component of the dot's color.
* @param green the green component of the dot's color.
* @param blue the blue component of the dot's color.
*
* @battlecode.doc.costlymethod
*/
void setIndicatorDot(MapLocation loc, int red, int green, int blue);
/**
* Draw a line on the game map for debugging purposes.
*
* @param startLoc the location to draw the line from.
* @param endLoc the location to draw the line to.
* @param red the red component of the line's color.
* @param green the green component of the line's color.
* @param blue the blue component of the line's color.
*
* @battlecode.doc.costlymethod
*/
void setIndicatorLine(MapLocation startLoc, MapLocation endLoc, int red, int green, int blue);
/**
* Sets the team's "memory", which is saved for the next game in the match.
* The memory is an array of {@link GameConstants#TEAM_MEMORY_LENGTH} longs.
* If this method is called more than once with the same index in the same
* game, the last call is what is saved for the next game.
*
* @param index the index of the array to set
* @param value the data that the team should remember for the next game
* @throws java.lang.ArrayIndexOutOfBoundsException if {@code index} is less
* than zero or greater than or equal to
* {@link GameConstants#TEAM_MEMORY_LENGTH}.
* @see #getTeamMemory
* @see #setTeamMemory(int, long, long)
*
* @battlecode.doc.costlymethod
*/
void setTeamMemory(int index, long value);
/**
* Sets this team's "memory". This function allows for finer control than
* {@link #setTeamMemory(int, long)} provides. For example, if
* {@code mask == 0xFF} then only the eight least significant bits of the
* memory will be set.
*
* @param index the index of the array to set
* @param value the data that the team should remember for the next game
* @param mask indicates which bits should be set
* @throws java.lang.ArrayIndexOutOfBoundsException if {@code index} is less
* than zero or greater than or equal to
* {@link GameConstants#TEAM_MEMORY_LENGTH}.
* @see #getTeamMemory
* @see #setTeamMemory(int, long)
*
* @battlecode.doc.costlymethod
*/
void setTeamMemory(int index, long value, long mask);
/**
* Returns the team memory from the last game of the match. The return value
* is an array of length {@link GameConstants#TEAM_MEMORY_LENGTH}. If
* setTeamMemory was not called in the last game, or there was no last game,
* the corresponding long defaults to 0.
*
* @return the team memory from the the last game of the match.
* @see #setTeamMemory(int, long)
* @see #setTeamMemory(int, long, long)
*
* @battlecode.doc.costlymethod
*/
long[] getTeamMemory();
/**
* Gets this robot's 'control bits' for debugging purposes. These bits can
* be set manually by the user, so a robot can respond to them. To set these
* bits, you must run the client in lockstep mode and right click the
* units.
*
* @return this robot's control bits.
*
* @battlecode.doc.costlymethod
*/
long getControlBits();
}
|
package app.lsgui.gui;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import app.lsgui.gui.channelinfopanel.ChannelInfoPanel;
import app.lsgui.gui.channellist.ChannelList;
import app.lsgui.gui.settings.SettingsController;
import app.lsgui.gui.settings.SettingsWindow;
import app.lsgui.model.channel.IChannel;
import app.lsgui.model.service.IService;
import app.lsgui.model.service.TwitchService;
import app.lsgui.rest.twitch.TwitchAPIClient;
import app.lsgui.rest.twitch.TwitchChannelUpdateService;
import app.lsgui.settings.Settings;
import app.lsgui.utils.Utils;
import de.jensd.fx.glyphs.GlyphsDude;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.Separator;
import javafx.scene.control.TextField;
import javafx.scene.control.ToolBar;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class MainController {
private static final Logger LOGGER = LoggerFactory.getLogger(MainController.class);
private static final String OFFLINEQUALITY = "Channel is offline";
private ChannelList channelList;
private ChannelInfoPanel channelInfoPanel;
private ProgressIndicator updateProgressIndicator;
@FXML
private ComboBox<String> qualityComboBox;
@FXML
private ComboBox<IService> serviceComboBox;
@FXML
private BorderPane contentBorderPane;
@FXML
private ToolBar toolBarTop;
@FXML
public void initialize() {
setupServiceComboBox();
setupChannelList();
setupQualityComboBox();
setupChannelInfoPanel();
setupToolbar();
}
private void setupQualityComboBox() {
qualityComboBox.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) -> {
if (newValue != null && !newValue.equals(OFFLINEQUALITY)) {
Settings.instance().setQuality(newValue);
}
});
}
private void setupServiceComboBox() {
if (Settings.instance().getStreamServices().isEmpty()) {
Settings.instance().getStreamServices().add(new TwitchService("Twitch.tv", "http://twitch.tv/"));
}
serviceComboBox.getItems().addAll(Settings.instance().getStreamServices());
serviceComboBox.setCellFactory(listView -> new ServiceCell());
serviceComboBox.setConverter(new StringConverter<IService>() {
@Override
public String toString(IService service) {
if (service == null) {
return null;
}
return service.getName().get();
}
@Override
public IService fromString(String string) {
return null;
}
});
serviceComboBox.getSelectionModel().select(0);
serviceComboBox.valueProperty().addListener((observable, oldValue, newValue) -> changeService(newValue));
}
private void setupChannelList() {
channelList = new ChannelList();
channelList.getListView().getSelectionModel().selectedItemProperty()
.addListener((observable, oldValue, newValue) -> {
IChannel value = newValue == null ? oldValue : newValue;
qualityComboBox.setItems(FXCollections.observableArrayList(value.getAvailableQualities()));
if (qualityComboBox.getItems().size() > 1) {
final String quality = Settings.instance().getQuality();
if (qualityComboBox.getItems().contains(quality)) {
qualityComboBox.getSelectionModel().select(quality);
} else {
qualityComboBox.getSelectionModel().select("Best");
}
} else {
qualityComboBox.getSelectionModel().select(0);
}
});
channelList.getStreams().bind(serviceComboBox.getSelectionModel().getSelectedItem().getChannels());
contentBorderPane.setLeft(channelList);
}
private void setupChannelInfoPanel() {
channelInfoPanel = new ChannelInfoPanel(serviceComboBox, qualityComboBox);
channelInfoPanel.getChannelProperty().bind(channelList.getSelectedChannelProperty());
contentBorderPane.setCenter(channelInfoPanel);
}
private void setupToolbar() {
Button addButton = GlyphsDude.createIconButton(FontAwesomeIcon.PLUS);
addButton.setOnAction(event -> addAction());
Button removeButton = GlyphsDude.createIconButton(FontAwesomeIcon.MINUS);
removeButton.setOnAction(event -> removeAction());
Button importButton = GlyphsDude.createIconButton(FontAwesomeIcon.USERS);
importButton.setOnAction(event -> importFollowedChannels());
toolBarTop.getItems().add(toolBarTop.getItems().size() - 1, addButton);
toolBarTop.getItems().add(toolBarTop.getItems().size() - 1, removeButton);
toolBarTop.getItems().add(toolBarTop.getItems().size() - 1, importButton);
toolBarTop.getItems().add(toolBarTop.getItems().size() - 1, new Separator());
updateProgressIndicator = new ProgressIndicator();
updateProgressIndicator.setVisible(false);
TwitchChannelUpdateService.getActiveChannelServicesProperty().addListener((obs, oldValue, newValue) -> {
if (newValue.size() > 0) {
updateProgressIndicator.setVisible(true);
} else {
updateProgressIndicator.setVisible(false);
}
});
toolBarTop.getItems().add(toolBarTop.getItems().size() - 1, updateProgressIndicator);
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
spacer.setMinWidth(Region.USE_PREF_SIZE);
toolBarTop.getItems().add(toolBarTop.getItems().size() - 1, spacer);
toolBarTop.getItems().add(toolBarTop.getItems().size() - 1, new Separator());
Button settingsButton = GlyphsDude.createIconButton(FontAwesomeIcon.COG);
settingsButton.setOnAction(event -> openSettings());
toolBarTop.getItems().add(toolBarTop.getItems().size(), settingsButton);
}
private void changeService(final IService newService) {
LOGGER.debug("Change Service to {}", newService.getName().get());
channelList.getStreams().bind(newService.getChannels());
}
private void openSettings() {
SettingsWindow sw = new SettingsWindow(contentBorderPane.getScene().getWindow());
sw.showAndWait();
}
private void addAction() {
final Dialog<Boolean> dialog = new Dialog<>();
dialog.setTitle("Add Channel");
final Stage dialogStage = (Stage) dialog.getDialogPane().getScene().getWindow();
dialogStage.setMinWidth(300);
final String style = SettingsController.class
.getResource("/styles/" + Settings.instance().getWindowStyle() + ".css").toExternalForm();
Utils.addStyleSheetToStage(dialogStage, style);
dialogStage.getIcons().add(new Image(getClass().getResourceAsStream("/icon.jpg")));
final ButtonType bt = new ButtonType("Submit", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(bt, ButtonType.CANCEL);
final BorderPane ap = new BorderPane();
final TextField tf = new TextField();
ap.setCenter(tf);
dialog.getDialogPane().setContent(ap);
final Node submitButton = dialog.getDialogPane().lookupButton(bt);
submitButton.setDisable(true);
tf.textProperty()
.addListener((observable, oldValue, newValue) -> submitButton.setDisable(newValue.trim().isEmpty()));
dialog.setResultConverter(button -> {
if ("".equals(tf.getText().trim()) || button.equals(ButtonType.CANCEL)) {
return false;
}
if (TwitchAPIClient.instance().channelExists(tf.getText().trim())) {
return true;
}
return false;
});
tf.requestFocus();
final Optional<Boolean> result = dialog.showAndWait();
if (result.isPresent() && result.get()) {
addChannelToCurrentService(tf.getText().trim());
}
}
private void removeAction() {
final IChannel toRemove = channelList.getListView().getSelectionModel().getSelectedItem();
removeChannelFromCurrentService(toRemove);
}
private void importFollowedChannels() {
final Dialog<Boolean> dialog = new Dialog<>();
final Stage dialogStage = (Stage) dialog.getDialogPane().getScene().getWindow();
dialogStage.setMinWidth(300);
final String style = SettingsController.class
.getResource("/styles/" + Settings.instance().getWindowStyle() + ".css").toExternalForm();
Utils.addStyleSheetToStage(dialogStage, style);
dialogStage.getIcons().add(new Image(getClass().getResourceAsStream("/icon.jpg")));
dialog.setTitle("Import Twitch.tv followed Channels");
final ButtonType bt = new ButtonType("Import", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(bt, ButtonType.CANCEL);
final BorderPane ap = new BorderPane();
final TextField tf = new TextField();
final Label description = new Label("Please enter your Twitch.tv Username:");
ap.setTop(description);
ap.setCenter(tf);
dialog.getDialogPane().setContent(ap);
final Node submitButton = dialog.getDialogPane().lookupButton(bt);
submitButton.setDisable(true);
tf.textProperty()
.addListener((observable, oldValue, newValue) -> submitButton.setDisable(newValue.trim().isEmpty()));
dialog.setResultConverter(button -> {
if ("".equals(tf.getText().trim()) || button.equals(ButtonType.CANCEL)) {
return false;
}
if (TwitchAPIClient.instance().channelExists(tf.getText().trim())) {
return true;
}
return false;
});
tf.requestFocus();
final Optional<Boolean> result = dialog.showAndWait();
if (result.isPresent() && result.get()) {
addFollowedChannelsToCurrentService(tf.getText().trim());
}
}
private void addChannelToCurrentService(final String channel) {
serviceComboBox.getSelectionModel().getSelectedItem().addChannel(channel);
}
private void addFollowedChannelsToCurrentService(final String channel) {
((TwitchService) serviceComboBox.getSelectionModel().getSelectedItem()).addFollowedChannels(channel);
}
private void removeChannelFromCurrentService(final IChannel channel) {
serviceComboBox.getSelectionModel().getSelectedItem().removeChannel(channel);
}
}
|
package app.lsgui.gui;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import app.lsgui.gui.channelinfopanel.ChannelInfoPanel;
import app.lsgui.gui.channellist.ChannelList;
import app.lsgui.gui.settings.SettingsController;
import app.lsgui.gui.settings.SettingsWindow;
import app.lsgui.model.channel.IChannel;
import app.lsgui.model.service.GenericService;
import app.lsgui.model.service.IService;
import app.lsgui.model.service.TwitchService;
import app.lsgui.rest.twitch.TwitchAPIClient;
import app.lsgui.rest.twitch.TwitchChannelUpdateService;
import app.lsgui.settings.Settings;
import app.lsgui.utils.Utils;
import de.jensd.fx.glyphs.GlyphsDude;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.Separator;
import javafx.scene.control.TextField;
import javafx.scene.control.ToolBar;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class MainController {
private static final Logger LOGGER = LoggerFactory.getLogger(MainController.class);
private static final String OFFLINEQUALITY = "Channel is offline";
private ChannelList channelList;
private ChannelInfoPanel channelInfoPanel;
private ProgressIndicator updateProgressIndicator;
private Button importButton;
private Button removeButton;
private Button addButton;
@FXML
private ComboBox<String> qualityComboBox;
@FXML
private ComboBox<IService> serviceComboBox;
@FXML
private BorderPane contentBorderPane;
@FXML
private ToolBar toolBarTop;
@FXML
public void initialize() {
setupServiceComboBox();
setupChannelList();
setupQualityComboBox();
setupChannelInfoPanel();
setupToolbar();
}
private void setupQualityComboBox() {
qualityComboBox.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) -> {
if (newValue != null && !newValue.equals(OFFLINEQUALITY)) {
Settings.instance().setQuality(newValue);
}
});
}
private void setupServiceComboBox() {
if (Settings.instance().getStreamServices().isEmpty()) {
Settings.instance().getStreamServices().add(new TwitchService("Twitch.tv", "http://twitch.tv/"));
}
serviceComboBox.getItems().addAll(Settings.instance().getStreamServices());
serviceComboBox.setCellFactory(listView -> new ServiceCell());
serviceComboBox.setConverter(new StringConverter<IService>() {
@Override
public String toString(IService service) {
if (service == null) {
return null;
}
return service.getName().get();
}
@Override
public IService fromString(String string) {
return null;
}
});
serviceComboBox.getSelectionModel().select(0);
serviceComboBox.valueProperty().addListener((observable, oldValue, newValue) -> changeService(newValue));
}
private void setupChannelList() {
channelList = new ChannelList();
channelList.getListView().getSelectionModel().selectedItemProperty()
.addListener((observable, oldValue, newValue) -> {
IChannel value = newValue == null ? oldValue : newValue;
qualityComboBox.setItems(FXCollections.observableArrayList(value.getAvailableQualities()));
if (qualityComboBox.getItems().size() > 1) {
final String quality = Settings.instance().getQuality();
if (qualityComboBox.getItems().contains(quality)) {
qualityComboBox.getSelectionModel().select(quality);
} else {
qualityComboBox.getSelectionModel().select("Best");
}
} else {
qualityComboBox.getSelectionModel().select(0);
}
});
channelList.getStreams().bind(serviceComboBox.getSelectionModel().getSelectedItem().getChannels());
contentBorderPane.setLeft(channelList);
}
private void setupChannelInfoPanel() {
channelInfoPanel = new ChannelInfoPanel(serviceComboBox, qualityComboBox);
channelInfoPanel.getChannelProperty().bind(channelList.getSelectedChannelProperty());
contentBorderPane.setCenter(channelInfoPanel);
}
private void setupToolbar() {
addButton = GlyphsDude.createIconButton(FontAwesomeIcon.PLUS);
addButton.setOnAction(event -> addAction());
removeButton = GlyphsDude.createIconButton(FontAwesomeIcon.MINUS);
removeButton.setOnAction(event -> removeAction());
importButton = GlyphsDude.createIconButton(FontAwesomeIcon.USERS);
importButton.setOnAction(event -> importFollowedChannels());
toolBarTop.getItems().add(toolBarTop.getItems().size() - 1, addButton);
toolBarTop.getItems().add(toolBarTop.getItems().size() - 1, removeButton);
toolBarTop.getItems().add(toolBarTop.getItems().size() - 1, importButton);
toolBarTop.getItems().add(toolBarTop.getItems().size() - 1, new Separator());
updateProgressIndicator = new ProgressIndicator();
updateProgressIndicator.setVisible(false);
TwitchChannelUpdateService.getActiveChannelServicesProperty().addListener((obs, oldValue, newValue) -> {
if (newValue.size() > 0) {
updateProgressIndicator.setVisible(true);
} else {
updateProgressIndicator.setVisible(false);
}
});
toolBarTop.getItems().add(toolBarTop.getItems().size() - 1, updateProgressIndicator);
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
spacer.setMinWidth(Region.USE_PREF_SIZE);
toolBarTop.getItems().add(toolBarTop.getItems().size() - 1, spacer);
toolBarTop.getItems().add(toolBarTop.getItems().size() - 1, new Separator());
Button settingsButton = GlyphsDude.createIconButton(FontAwesomeIcon.COG);
settingsButton.setOnAction(event -> openSettings());
toolBarTop.getItems().add(toolBarTop.getItems().size(), settingsButton);
}
private void changeService(final IService newService) {
LOGGER.debug("Change Service to {}", newService.getName().get());
channelList.getStreams().bind(newService.getChannels());
if (Utils.isTwitchService(newService)) {
importButton.setDisable(false);
} else {
importButton.setDisable(true);
}
}
private void openSettings() {
SettingsWindow sw = new SettingsWindow(contentBorderPane.getScene().getWindow());
sw.showAndWait();
}
private void addAction() {
final Dialog<String> dialog = new Dialog<>();
dialog.setTitle("Add Channel");
final Stage dialogStage = (Stage) dialog.getDialogPane().getScene().getWindow();
dialogStage.setMinWidth(350);
final String style = SettingsController.class
.getResource("/styles/" + Settings.instance().getWindowStyle() + ".css").toExternalForm();
Utils.addStyleSheetToStage(dialogStage, style);
dialogStage.getIcons().add(new Image(getClass().getResourceAsStream("/icon.jpg")));
final ButtonType buttonChannel = new ButtonType("Add Channel", ButtonData.APPLY);
final ButtonType buttonService = new ButtonType("Add Service", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(buttonChannel, buttonService, ButtonType.CANCEL);
final BorderPane ap = new BorderPane();
final TextField tf = new TextField();
final Label description = new Label("To add a Channel, type in the channel name\n"
+ "To add a Service type in: serviceName serviceUrl\n" + "Example: Twitch.tv http://twitch.tv/");
ap.setTop(description);
ap.setCenter(tf);
dialog.getDialogPane().setContent(ap);
final Node channelButton = dialog.getDialogPane().lookupButton(buttonChannel);
final Node serviceButton = dialog.getDialogPane().lookupButton(buttonService);
channelButton.setDisable(true);
serviceButton.setDisable(true);
tf.textProperty().addListener((observable, oldValue, newValue) -> {
channelButton.setDisable(newValue.trim().isEmpty());
if (newValue.trim().split(" ").length > 1) {
serviceButton.setDisable(false);
} else {
serviceButton.setDisable(true);
}
});
dialog.setResultConverter(button -> {
final String trimmed = tf.getText().trim();
if ("".equals(trimmed) || button.equals(ButtonType.CANCEL)) {
return "";
}
if (button.getButtonData().equals(ButtonData.APPLY)) {
if (TwitchAPIClient.instance().channelExists(trimmed)) {
return trimmed;
}
} else if (button.getButtonData().equals(ButtonData.OK_DONE)) {
return trimmed;
}
return "";
});
tf.requestFocus();
final Optional<String> result = dialog.showAndWait();
if (result.isPresent() && !"".equals(result.get())) {
final String[] isService = result.get().split(" ");
if (isService.length > 1) {
final String name = isService[0];
final String url = isService[0];
addService(name, url);
} else {
addChannelToCurrentService(result.get());
}
}
}
private void removeAction() {
final IChannel toRemove = channelList.getListView().getSelectionModel().getSelectedItem();
removeChannelFromCurrentService(toRemove);
}
private void importFollowedChannels() {
final Dialog<Boolean> dialog = new Dialog<>();
final Stage dialogStage = (Stage) dialog.getDialogPane().getScene().getWindow();
dialogStage.setMinWidth(300);
final String style = SettingsController.class
.getResource("/styles/" + Settings.instance().getWindowStyle() + ".css").toExternalForm();
Utils.addStyleSheetToStage(dialogStage, style);
dialogStage.getIcons().add(new Image(getClass().getResourceAsStream("/icon.jpg")));
dialog.setTitle("Import Twitch.tv followed Channels");
final ButtonType bt = new ButtonType("Import", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(bt, ButtonType.CANCEL);
final BorderPane ap = new BorderPane();
final TextField tf = new TextField();
final Label description = new Label("Please enter your Twitch.tv Username:");
ap.setTop(description);
ap.setCenter(tf);
dialog.getDialogPane().setContent(ap);
final Node submitButton = dialog.getDialogPane().lookupButton(bt);
submitButton.setDisable(true);
tf.textProperty()
.addListener((observable, oldValue, newValue) -> submitButton.setDisable(newValue.trim().isEmpty()));
dialog.setResultConverter(button -> {
if ("".equals(tf.getText().trim()) || button.equals(ButtonType.CANCEL)) {
return false;
}
if (TwitchAPIClient.instance().channelExists(tf.getText().trim())) {
return true;
}
return false;
});
tf.requestFocus();
final Optional<Boolean> result = dialog.showAndWait();
if (result.isPresent() && result.get()) {
addFollowedChannelsToCurrentService(tf.getText().trim());
}
}
private void addChannelToCurrentService(final String channel) {
serviceComboBox.getSelectionModel().getSelectedItem().addChannel(channel);
}
private void addFollowedChannelsToCurrentService(final String channel) {
((TwitchService) serviceComboBox.getSelectionModel().getSelectedItem()).addFollowedChannels(channel);
}
private void removeChannelFromCurrentService(final IChannel channel) {
serviceComboBox.getSelectionModel().getSelectedItem().removeChannel(channel);
}
private void addService(final String serviceName, final String serviceUrl) {
LOGGER.debug("Add new Service {} with URL {}", serviceName, serviceUrl);
String correctedUrl = serviceUrl;
if (!serviceUrl.endsWith("/")) {
correctedUrl += "/";
}
Settings.instance().getStreamServices().add(new GenericService(serviceName, correctedUrl));
}
}
|
package br.uff.ic.utility.graph;
import br.uff.ic.utility.GraphAttribute;
import br.uff.ic.provviewer.EdgeType;
import br.uff.ic.provviewer.VariableNames;
import br.uff.ic.provviewer.Variables;
import br.uff.ic.utility.Utils;
import java.awt.Color;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Edge Class
*
* @author Kohwalter
*/
public class Edge extends GraphObject {
private String id;
private Object source;
private Object target;
private final String type; // Edge type (prov edges)
//used to hide this edge when collapsing a group of edges
private boolean hide;
//used to say this edge is a temporary one
private boolean collapsed;
private Color defaultColor = new Color(0, 255, 255);
private String influenceName = "Influence";
/**
* Constructor for testing purposes since it construct a mostly blank edge
* @param id is the edge ID
* @param target is the target vertex
* @param source is the source vertex
*/
public Edge(String id, Object target, Object source) {
this.id = id;
this.source = source;
this.target = target;
this.type = "";
hide = false;
collapsed = false;
this.attributes = new HashMap<>();
GraphAttribute att = new GraphAttribute(influenceName, "");
this.attributes.put(att.getName(), att);
// this.attributes.putAll(attributes);
setLabel("");
}
/**
* Constructor
*
* @param id
* @param type
* @param value
* @param label
* @param attributes
* @param target
* @param source
*/
public Edge(String id, String type, String value,
String label, Map<String, GraphAttribute> attributes, Object target, Object source) {
this.id = id;
this.source = source;
this.target = target;
this.type = type;
hide = false;
collapsed = false;
this.attributes = new HashMap<>(attributes);
GraphAttribute att = new GraphAttribute(influenceName, value);
this.attributes.put(att.getName(), att);
setLabel(label);
}
/**
* Constructor without extra attributes
*
* @param id
* @param type
* @param value
* @param label
* @param target
* @param source
*/
public Edge(String id, String type, String label, String value, Object target, Object source) {
this.id = id;
this.source = source;
this.target = target;
this.type = type;
hide = false;
collapsed = false;
this.attributes = new HashMap<>();
GraphAttribute att = new GraphAttribute(influenceName, value);
this.attributes.put(att.getName(), att);
setLabel(label);
if (label.equalsIgnoreCase("") || label == null || "-".equals(label) || label.equalsIgnoreCase("Neutral")) {
setLabel("Neutral");
value = "0";
}
}
/**
* Constructor without influence value, label, type (type=influence) and no
* extra attribute
*
* @param id Edge's ID
* @deprecated Used only on outdated TSVReader
* @param target Vertex target
* @param source Vertex source
* @param influence Influence value and name (i.e. "+9 damage")
*/
public Edge(String id, Object target, Object source, String influence) {
this.id = id;
this.source = source;
this.target = target;
influence = "0";
this.type = getLabel();
hide = false;
collapsed = false;
this.attributes = new HashMap<>();
GraphAttribute att = new GraphAttribute(influenceName, influence);
this.attributes.put(att.getName(), att);
if (influence.equalsIgnoreCase("")) {
setLabel("Neutral");
} else {
setLabel(influence);
}
}
/**
* Return Edge id
*
* @return
*/
public String getID() {
return id;
}
/**
* Set the edge ID
* @param t is the new value
*/
public void setID(String t) {
id = t;
}
/**
* Method to get the edge source
*
* @return vertex source
*/
public Object getSource() {
return source;
}
/**
* Set the edge's source
* @param t is the new source
*/
public void setSource(Object t) {
source = t;
}
/**
* Method to get the edge target
*
* @return vertex target
*/
public Object getTarget() {
return target;
}
/**
* Set the edge's target/destionation
* @param t is the new target
*/
public void setTarget(Object t) {
target = t;
}
/**
* Method for returning the edge's numeric value (converted from String)
*
* @return (float) edge influence value
*/
public float getValue() {
if (Utils.tryParseFloat(this.getAttributeValue(influenceName))) {
return Float.parseFloat(this.getAttributeValue(influenceName));
} else if (Utils.tryParseFloat(this.getAttributeValue(influenceName).split(" ")[0])) {
return Float.parseFloat(this.getAttributeValue(influenceName).split(" ")[0]);
} else {
return 0;
}
}
/**
* Returns the edge's value as the original String instead of converting to numeric
* @return
*/
public String getStringValue() {
return this.getAttributeValue(influenceName);
}
/**
* Updates the edge's value
* @param t is the string with the new value
*/
public void setValue(String t) {
this.getAttribute(influenceName).setValue(t);
}
/**
* Method for returning the edge type
*
* @return
*/
public String getType() {
return this.type;
}
/**
* Method to get the edge influence + value
*
* @return (String) influence
*/
public String getEdgeTooltip() {
return "<br>ID: " + this.id
+ "<br>Label: " + getLabel()
// + "<br>Value: " + getValue()
+ "<br>Type: " + getType()
+ "<br>" + printAttributes();
}
/**
* Method to check if the edge is hidden (due to collapses)
*
* @return (boolean) if the edge is hidden or not
*/
public boolean isHidden() {
return hide;
}
/**
* Method to check if the edge is a collapsed edge (new edge that contains
* the information of the collapsed ones)
*
* @return (boolean) if the edge is collapsed or not
*/
public boolean isCollapased() {
return collapsed;
}
/**
* Method to set the hide parameter
*
* @param t (boolean) Hide = t
*/
public void setHide(boolean t) {
hide = t;
}
/**
* Method to set the collapsed parameter
*
* @param t (boolean) collapsed = t
*/
public void setCollapse(boolean t) {
collapsed = t;
}
/**
* Method to check if the edge is of the neutral type (Empty influence or
* value equals zero
*
* @return (boolean) is neutral or not
*/
public boolean isNeutral() {
return (getLabel().equalsIgnoreCase(""))
|| (getLabel().isEmpty())
|| (getLabel().equalsIgnoreCase("Neutral"));
}
/**
* Method to override JUNG's default toString method
*
* @return edge details
*/
@Override
public String toString() {
String font = VariableNames.FontConfiguration;
if (getLabel().isEmpty()) {
return font + this.type;
} else if (getLabel().equals(this.type)) {
return font + this.type;
} else {
return font + this.type + " (" + getLabel() + ")";
}
}
/**
* Method to get the edge color (red, black, or green), defined by value
*
* @param variables
* @return
*/
public Color getColor(Variables variables) {
if(variables.isEdgeColorByGraphs) {
String[] graphs = getAttributeValues(VariableNames.GraphFile);
return Utils.getGrayscaleColor(graphs.length, variables.numberOfGraphs);
} else {
float v = getValue();
if (v == 0) {
return defaultColor;
} else {
int j = 0;
for (int i = 0; i < variables.config.edgetype.size(); i++) {
if (this.getLabel().contains(variables.config.edgetype.get(i).type)) {
j = i;
}
}
// TODO add inverted color scheme for increase in value to be red and decrease to be green
if (variables.config.edgetype.get(j).isInverted) {
if (v > 0) {
return compareValueRed(v, 0, variables.config.edgetype.get(j).max, variables.config.edgetype.get(j).isInverted);
} else {
return compareValueGreen(v, variables.config.edgetype.get(j).min, 0, variables.config.edgetype.get(j).isInverted);
}
} else {
// else
if (v > 0) {
return compareValueGreen(v, 0, variables.config.edgetype.get(j).max, variables.config.edgetype.get(j).isInverted);
} else {
return compareValueRed(v, variables.config.edgetype.get(j).min, 0, variables.config.edgetype.get(j).isInverted);
}
}
}
}
}
/**
* Method that calculates the green gradient based on the edge's value and the maximum and minimum for the same edge type
* @param value is the edge's value
* @param min is the minimum value for the edge type
* @param max is the maximum value for the edge type
* @param isInverted tells if the color gradient will be increasing or decreasing
* @return
*/
public Color compareValueGreen(float value, double min, double max, boolean isInverted) {
if(!isInverted) {
int proportion = (int) Math.round(510 * Math.abs(value - min) / (float) Math.abs(max - min));
proportion = Math.max(proportion, 0);
return new Color(0, Math.min(255, proportion), 0);
}
else {
int proportion = (int) Math.round(510 * Math.abs(value - min) / (float) Math.abs(max - min));
proportion = Math.min(proportion, 510);
return new Color(0, Math.min(255, 510 - proportion), 0);
}
}
/**
* Method that calculates the red gradient based on the edge's value and the maximum and minimum for the same edge type
* @param value is the edge's value
* @param min is the minimum value for the edge type
* @param max is the maximum value for the edge type
* @param isInverted tells if the color gradient will be increasing or decreasing
* @return
*/
public Color compareValueRed(float value, double min, double max, boolean isInverted) {
if(!isInverted) {
int proportion = (int) Math.round(510 * Math.abs(value - min) / (float) Math.abs(max - min));
proportion = Math.min(proportion, 510);
return new Color(Math.min(255, 510 - proportion), 0, 0);
} else
{
int proportion = (int) Math.round(510 * Math.abs(value - min) / (float) Math.abs(max - min));
proportion = Math.max(proportion, 0);
return new Color(Math.min(255, proportion), 0, 0);
}
}
/**
* Method used during the collapse of edges. This method defines if the
* collapsed edge influence value will be the sum of the edges values or the
* average
*
* @param variables
* @return (boolean) Return true if influence from collapsed edges are
* added. Return false if average
*/
public boolean addInfluence(Variables variables) {
for (EdgeType edgetype : variables.config.edgetype) {
if (this.getType().contains(edgetype.type)) {
if (edgetype.collapse.equalsIgnoreCase("AVERAGE")) {
return false;
}
}
}
return true;
}
/**
* Function to merge two edges
* @param edge is the edge that we want to merge with
* @return the updated edge after merging with "edge"
*/
public Edge merge(Edge edge, String mergeCode) {
if(this.getType().equalsIgnoreCase(edge.getType())) {
this.updateAllAttributes(edge.getAttributes());
this.id = this.id + ", " + edge.id;
if(!this.getLabel().contains(edge.getLabel()))
this.setLabel(this.getLabel() + ", " + edge.getLabel());
edge.setHide(true);
GraphAttribute merged = new GraphAttribute(VariableNames.MergedEdgeAttribute, mergeCode);
this.addAttribute(merged);
}
return this;
}
}
|
package cn.wizzer.common.core;
import org.beetl.ext.nutz.BeetlViewMaker;
import org.nutz.integration.shiro.ShiroSessionProvider;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.ioc.provider.ComboIocProvider;
@Modules(scanPackage = true, packages = "cn.wizzer.modules")
@Ok("json:full")
@Fail("http:500")
@IocBy(type = ComboIocProvider.class, args = {"*json", "config/ioc/", "*anno", "cn.wizzer", "*tx", "*quartz", "*async"})
@Localization(value = "locales/", defaultLocalizationKey = "zh_CN")
@Encoding(input = "UTF-8", output = "UTF-8")
@Views({BeetlViewMaker.class})
@SetupBy(value = Setup.class)
@ChainBy(args = "config/chain/nutzwk-mvc-chain.json")
@SessionBy(ShiroSessionProvider.class)
public class Module {
}
|
package com.almasb.fxgl.util;
import com.almasb.fxgl.logging.Logger;
import com.almasb.fxgl.logging.SystemLogger;
import java.util.ResourceBundle;
/**
* Holds version info about various frameworks used in FXGL.
*
* @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com)
*/
public final class Version {
private static final Logger log = SystemLogger.INSTANCE;
private static final String FXGL_VERSION;
private static final String JAVAFX_VERSION;
private static final String JBOX_VERSION;
private static final String KOTLIN_VERSION;
static {
ResourceBundle resources = ResourceBundle.getBundle("com.almasb.fxgl.util.version");
FXGL_VERSION = resources.getString("fxgl.version");
JAVAFX_VERSION = resources.getString("javafx.version");
JBOX_VERSION = resources.getString("jbox.version");
KOTLIN_VERSION = resources.getString("kotlin.version");
}
public static void print() {
log.info("FXGL-" + getAsString());
log.info("JavaFX-" + getJavaFXAsString());
log.info("JBox2D-" + getJBox2DAsString());
log.info("Kotlin-" + getKotlinAsString());
log.info("Source code and latest versions at: https://github.com/AlmasB/FXGL");
log.info(" Join the FXGL chat at: https://gitter.im/AlmasB/FXGL");
}
/**
* @return compile time version of FXGL
*/
public static String getAsString() {
return FXGL_VERSION;
}
/**
* @return compile time version of JavaFX
*/
public static String getJavaFXAsString() {
return JAVAFX_VERSION;
}
/**
* @return compile time version of JBox2D
*/
public static String getJBox2DAsString() {
return JBOX_VERSION;
}
/**
* @return compile time version of Kotlin
*/
public static String getKotlinAsString() {
return KOTLIN_VERSION;
}
}
|
package com.bananity.locks;
// Java Utils
import java.util.HashMap;
// Java Concurrency Management
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
// Bean Setup
import javax.ejb.EJB;
import javax.ejb.Startup;
import javax.ejb.Singleton;
import javax.annotation.PostConstruct;
// JBoss Concurrency Management
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
// Log4j
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PropertyConfigurator;
/**
* @author Andreu Correa Casablanca
*/
@Startup
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class LocksBean {
/**
* Log4j reference
*/
private static Logger log;
/**
* Internal lock, used to update collection and token's locks
*/
private ReentrantReadWriteLock internalLock = null;
private ReadLock internalReadLock = null;
private WriteLock internalWriteLock = null;
/**
* Locks over Collections
*/
private HashMap<String, ReentrantReadWriteLock> collectionLocks = null;
@PostConstruct
void init() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
PropertyConfigurator.configure(classLoader.getResource("log4j.properties"));
log = Logger.getLogger(LocksBean.class);
internalLock = new ReentrantReadWriteLock();
internalReadLock = internalLock.readLock();
internalWriteLock = internalLock.writeLock();
collectionLocks = new HashMap<String, ReentrantReadWriteLock>();
}
private ReentrantReadWriteLock getCollectionReeentrantLock (String collName) {
internalReadLock.lock();
ReentrantReadWriteLock collectionLock = collectionLocks.get(collName);
if (collectionLock == null) {
internalReadLock.unlock();
internalWriteLock.lock();
collectionLock = collectionLocks.get(collName);
if (collectionLock == null) {
collectionLock = new ReentrantReadWriteLock();
collectionLocks.put(collName, collectionLock);
}
internalWriteLock.unlock();
} else {
internalReadLock.unlock();
}
return collectionLock;
}
public ReadLock getCollectionReadLock (String collName) {
return getCollectionReeentrantLock(collName).readLock();
}
public WriteLock getCollectionWriteLock (String collName) {
return getCollectionReeentrantLock(collName).writeLock();
}
public ReadLock getTokenReadLock (String collName, String token) {
// TODO : Implement a real token block
return getCollectionReadLock(collName);
}
public WriteLock getTokenWriteLock (String collName, String token) {
// TODO : Implement a real token block
return getCollectionWriteLock(collName);
}
}
|
package com.browserstack.local;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.json.*;
/**
* Creates and manages a secure tunnel connection to BrowserStack.
*/
public class Local {
private static final List<String> IGNORE_KEYS = Arrays.asList("key", "logfile", "binarypath");
List<String> command;
Map<String, String> startOptions;
String binaryPath;
String logFilePath;
int pid = 0;
private LocalProcess proc = null;
private final Map<String, String> parameters;
public Local() {
parameters = new HashMap<String, String>();
parameters.put("v", "-vvv");
parameters.put("f", "-f");
parameters.put("force", "-force");
parameters.put("only", "-only");
parameters.put("forcelocal", "-forcelocal");
parameters.put("localIdentifier", "-localIdentifier");
parameters.put("onlyAutomate", "-onlyAutomate");
parameters.put("proxyHost", "-proxyHost");
parameters.put("proxyPort", "-proxyPort");
parameters.put("proxyUser", "-proxyUser");
parameters.put("proxyPass", "-proxyPass");
parameters.put("forceproxy", "-forceproxy");
parameters.put("hosts", "-hosts");
}
/**
* Starts Local instance with options
*
* @param options Options for the Local instance
* @throws Exception
*/
public void start(Map<String, String> options) throws Exception {
startOptions = options;
if (options.get("binarypath") != null) {
binaryPath = options.get("binarypath");
} else {
LocalBinary lb = new LocalBinary();
binaryPath = lb.getBinaryPath();
}
logFilePath = options.get("logfile") == null ? (System.getProperty("user.dir") + "/local.log") : options.get("logfile");
makeCommand(options, "start");
if (options.get("onlyCommand") != null) return;
if (proc == null) {
FileWriter fw = new FileWriter(logFilePath);
fw.write("");
fw.close();
proc = runCommand(command);
BufferedReader stdoutbr = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stderrbr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String stdout="", stderr="", line;
while ((line = stdoutbr.readLine()) != null) {
stdout += line;
}
while ((line = stderrbr.readLine()) != null) {
stderr += line;
}
int r = proc.waitFor();
JSONObject obj = new JSONObject(stdout != "" ? stdout : stderr);
if(!obj.getString("state").equals("connected")){
throw new LocalException(obj.getString("message"));
}
else {
pid = obj.getInt("pid");
}
}
}
/**
* Stops the Local instance
*
* @throws InterruptedException
*/
public void stop() throws Exception {
if (pid != 0) {
makeCommand(startOptions, "stop");
proc = runCommand(command);
proc.waitFor();
pid = 0;
}
}
/**
* Checks if Local instance is running
*
* @return true if Local instance is running, else false
*/
public boolean isRunning() throws Exception {
if (pid == 0) return false;
return isProcessRunning(pid);
}
/**
* Creates a list of command-line arguments for the Local instance
*
* @param options Options supplied for the Local instance
*/
private void makeCommand(Map<String, String> options, String opCode) {
command = new ArrayList<String>();
command.add(binaryPath);
command.add("-d");
command.add(opCode);
command.add("-logFile");
command.add(logFilePath);
command.add(options.get("key"));
for (Map.Entry<String, String> opt : options.entrySet()) {
String parameter = opt.getKey().trim();
if (IGNORE_KEYS.contains(parameter)) {
continue;
}
if (parameters.get(parameter) != null) {
command.add(parameters.get(parameter));
} else {
command.add("-" + parameter);
}
if (opt.getValue() != null) {
command.add(opt.getValue().trim());
}
}
}
private boolean isProcessRunning(int pid) throws Exception {
ArrayList<String> cmd = new ArrayList<String>();
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
//tasklist exit code is always 0. Parse output
//findstr exit code 0 if found pid, 1 if it doesn't
cmd.add("cmd");
cmd.add("/c");
cmd.add("\"tasklist /FI \"PID eq " + pid + "\" | findstr " + pid + "\"");
}
else {
//ps exit code 0 if process exists, 1 if it doesn't
cmd.add("ps");
cmd.add("-p");
cmd.add(String.valueOf(pid));
}
proc = runCommand(cmd);
int exitValue = proc.waitFor();
// 0 is the default exit code which means the process exists
return exitValue == 0;
}
/**
* Executes the supplied command on the shell.
*
* @param command Command to be executed on the shell.
* @return {@link LocalProcess} for managing the launched process.
* @throws IOException
*/
protected LocalProcess runCommand(List<String> command) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder(command);
final Process process = processBuilder.start();
return new LocalProcess() {
public InputStream getInputStream() {
return process.getInputStream();
}
public InputStream getErrorStream() {
return process.getErrorStream();
}
public int waitFor() throws Exception {
return process.waitFor();
}
};
}
public interface LocalProcess {
InputStream getInputStream();
InputStream getErrorStream();
int waitFor() throws Exception;
}
}
|
package com.bugsnag;
import java.lang.Thread.UncaughtExceptionHandler;
class ExceptionHandler implements UncaughtExceptionHandler {
private UncaughtExceptionHandler originalHandler;
private Client client;
public static void install(Client client) {
UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
if(currentHandler instanceof ExceptionHandler) {
currentHandler = ((ExceptionHandler)currentHandler).originalHandler;
}
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(currentHandler, client));
}
public static void remove() {
UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
if(currentHandler instanceof ExceptionHandler) {
Thread.setDefaultUncaughtExceptionHandler(((ExceptionHandler)currentHandler).originalHandler);
}
}
public ExceptionHandler(UncaughtExceptionHandler originalHandler, Client client) {
this.originalHandler = originalHandler;
this.client = client;
}
public void uncaughtException(Thread t, Throwable e) {
client.autoNotify(e);
originalHandler.uncaughtException(t, e);
}
}
|
// File: Resource.java (11-Apr-2011)
// Tim Niblett (the Author) and may not be used,
// sold, licenced, transferred, copied or reproduced in whole or in
// part in any manner or form or in or on any media to any person
// other than in accordance with the terms of The Author's agreement
// or otherwise without the prior written consent of The Author. All
// information contained in this source file is confidential information
// belonging to The Author and as such may not be disclosed other
// than in accordance with the terms of The Author's agreement, or
// otherwise, without the prior written consent of The Author. As
// confidential information this source file must be kept fully and
// effectively secure at all times.
package com.cilogi.resource;
import com.cilogi.util.Digest;
import com.cilogi.util.MimeTypes;
import com.google.common.base.Preconditions;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
// Not sure if I should make this class immutable or not.
// At the moment its not.
public class Resource implements IResource, Comparable<Resource> {
static final Logger LOG = LoggerFactory.getLogger(Resource.class);
private final String path;
private IDataSource dataSource;
private Date created;
private Date modified;
private String mimeType;
private String etag;
private Multimap<String,Object> metaData;
public Resource(String path) {
this(path, new ByteArrayDataSource());
}
public Resource(String path, IDataSource dataSource) {
Preconditions.checkNotNull(path);
this.created = new Date();
this.modified = new Date();
this.mimeType = null;
this.etag = null;
this.metaData = LinkedHashMultimap.create();
this.path = path;
this.dataSource = dataSource;
}
@Override
public Resource created(Date created) {
Preconditions.checkNotNull(created);
this.created = new Date(created.getTime());
return this;
}
@Override
public Resource modified(Date modified) {
Preconditions.checkNotNull(modified);
this.modified = new Date(modified.getTime()); return this;
}
@Override
public Resource mimeType(String mimeType) {
this.mimeType = mimeType; return this;
}
@Override
public Resource dataSource(IDataSource dataSource) {
Preconditions.checkNotNull(dataSource);
this.dataSource = dataSource;
return this;
}
@Override
public Resource data(byte[] data) {
Preconditions.checkNotNull(data);
dataSource.setData(data);
return this;
}
@Override
public Resource withPath(String newPath) {
Preconditions.checkNotNull(newPath);
Resource out = new Resource(newPath);
return out
.dataSource(dataSource.copy())
.created(new Date(created.getTime()))
.modified(new Date(modified.getTime()))
.mimeType(mimeType);
}
@Override
public Resource metaData(Multimap<String,Object> metaData) {
Preconditions.checkNotNull(metaData, "metadata can't be null");
this.metaData = LinkedHashMultimap.create();
this.metaData.putAll(metaData); return this;
}
@Override
public String getPath() {
return path;
}
@Override
public synchronized byte[] getData() {
return dataSource.getData();
}
@Override
public synchronized IDataSource getDataSource() {
return dataSource;
}
@Override
public String getMimeType() {
if (mimeType != null) {
return mimeType;
}
int dot = path.lastIndexOf(".");
return (dot == -1) ? "application/binary" : MimeTypes.getMimeType(path.substring(dot + 1));
}
@Override
public String getEtag() {
return etag;
}
@Override
public IResource etag(String etag) {
this.etag = etag; return this;
}
@Override
public Date getCreated() {
return (created == null) ? null : new Date(created.getTime());
}
@Override
public Date getModified() {
return (modified == null) ? null : new Date(modified.getTime());
}
@Override
public Multimap<String,Object> getMetaData() {
Multimap<String,Object> map = LinkedHashMultimap.create(metaData);
return map;
}
@Override
public String getServingUrl() {
return null;
}
@Override
public int hashCode() {
return getPath().hashCode() * 31;
}
@Override
public boolean equals(Object o) {
if (o instanceof Resource) {
Resource r = (Resource)o;
return getPath().equals(r.getPath());
} else {
return false;
}
}
public String getDigest() {
return Digest.digestHex(getData(), Digest.Algorithm.MD5);
}
@Override
public String toString() {
return getPath();
}
@Override
public int compareTo(Resource resource) {
return getPath().compareTo(resource.getPath());
}
}
|
package com.conveyal.r5.analyst;
import com.conveyal.r5.common.GeometryUtils;
import com.conveyal.r5.util.ShapefileReader;
import com.csvreader.CsvReader;
import com.google.common.io.LittleEndianDataInputStream;
import com.google.common.io.LittleEndianDataOutputStream;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.prep.PreparedGeometry;
import com.vividsolutions.jts.geom.prep.PreparedGeometryFactory;
import org.apache.commons.math3.util.FastMath;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridCoverageFactory;
import org.geotools.coverage.grid.io.AbstractGridFormat;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureWriter;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.Transaction;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.gce.geotiff.GeoTiffFormat;
import org.geotools.gce.geotiff.GeoTiffWriteParams;
import org.geotools.gce.geotiff.GeoTiffWriter;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.parameter.GeneralParameterValue;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.TransformException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.conveyal.gtfs.util.Util.human;
import static java.lang.Double.parseDouble;
import static org.apache.commons.math3.util.FastMath.atan;
import static org.apache.commons.math3.util.FastMath.cos;
import static org.apache.commons.math3.util.FastMath.log;
import static org.apache.commons.math3.util.FastMath.sinh;
import static org.apache.commons.math3.util.FastMath.tan;
/**
* Class that represents a grid in the spherical Mercator "projection" at a given zoom level.
* This is actually a sub-grid of the full-world web mercator grid, with a specified width and height and offset from
* the edges of the world.
*/
public class Grid {
public static final Logger LOG = LoggerFactory.getLogger(Grid.class);
/** The web mercator zoom level for this grid. */
public final int zoom;
/* The following fields establish the position of this sub-grid within the full worldwide web mercator grid. */
/**
* The pixel number of the northernmost pixel in this grid (smallest y value in web Mercator,
* because y increases from north to south in web Mercator).
*/
public final int north;
/** The pixel number of the westernmost pixel in this grid (smallest x value). */
public final int west;
/** The width of the grid in web Mercator pixels. */
public final int width;
/** The height of the grid in web Mercator pixels. */
public final int height;
/** The data values for each pixel within this grid. */
public final double[][] grid;
/** Maximum area allowed for the bounding box of an uploaded shapefile -- large enough for New York State. */
private static final double MAX_BOUNDING_BOX_AREA_SQ_KM = 250 000;
/** Maximum area allowed for features in a shapefile upload */
double MAX_FEATURE_AREA_SQ_DEG = 2;
/**
* @param zoom web mercator zoom level for the grid.
* @param north latitude in decimal degrees of the north edge of this grid.
* @param east longitude in decimal degrees of the east edge of this grid.
* @param south latitude in decimal degrees of the south edge of this grid.
* @param west longitude in decimal degrees of the west edge of this grid.
*/
public Grid (int zoom, double north, double east, double south, double west) {
this.zoom = zoom;
this.north = latToPixel(north, zoom);
/**
* The grid extent is computed from the points. If the cell number for the right edge of the grid is rounded
* down, some points could fall outside the grid. `latToPixel` and `lonToPixel` naturally round down - which is
* the correct behavior for binning points into cells but means the grid is always 1 row too narrow/short.
*
* So we add 1 to the height and width when a grid is created in this manner.
*/
this.height = (latToPixel(south, zoom) - this.north) + 1; // minimum height is 1
this.west = lonToPixel(west, zoom);
this.width = (lonToPixel(east, zoom) - this.west) + 1; // minimum width is 1
this.grid = new double[width][height];
}
/**
* Used when reading a saved grid.
* FIXME we have two constructors with five numeric parameters, differentiated only by int/double type.
*/
public Grid (int zoom, int width, int height, int north, int west) {
this.zoom = zoom;
this.width = width;
this.height = height;
this.north = north;
this.west = west;
this.grid = new double[width][height];
}
public static class PixelWeight {
public final int x;
public final int y;
public final double weight;
private PixelWeight (int x, int y, double weight){
this.x = x;
this.y = y;
this.weight = weight;
}
}
/**
* Version of getPixelWeights which returns the weights as relative to the total area of the input geometry (i.e.
* the weight at a pixel is the proportion of the input geometry that falls within that pixel.
*/
public List<PixelWeight> getPixelWeights (Geometry geometry) {
return getPixelWeights(geometry, false);
}
// PreparedGeometry is often faster for small numbers of vertices;
private PreparedGeometryFactory pgFact = new PreparedGeometryFactory();
/**
* Get the proportions of an input polygon feature that overlap each grid cell, for use in lists of PixelWeights.
* These lists can then be fed into the incrementFromPixelWeights function to actually burn a polygon into the
* grid.
*
* If relativeToPixels is true, the weights are the proportion of the pixel that is covered. Otherwise they are the
* portion of this polygon which is within the given pixel. If using incrementPixelWeights, this should be set to
* false.
*
* This used to return a map from int arrays containing the coordinates to the weight.
*/
public List<PixelWeight> getPixelWeights (Geometry geometry, boolean relativeToPixels) {
// No need to convert to a local coordinate system
// Both the supplied polygon and the web mercator pixel geometries are left in WGS84 geographic coordinates.
// Both are distorted equally along the X axis at a given latitude so the proportion of the geometry within
// each pixel is accurate, even though the surface area in WGS84 coordinates is not a usable value.
List<PixelWeight> weights = new ArrayList<>();
double area = geometry.getArea();
if (area < 1e-12) {
throw new IllegalArgumentException("Feature geometry is too small");
}
if (area > MAX_FEATURE_AREA_SQ_DEG) {
throw new IllegalArgumentException("Feature geometry is too large");
}
PreparedGeometry preparedGeom = pgFact.create(geometry);
Envelope env = geometry.getEnvelopeInternal();
for (int worldy = latToPixel(env.getMaxY(), zoom); worldy <= latToPixel(env.getMinY(), zoom); worldy++) {
// NB web mercator Y is reversed relative to latitude.
// Iterate over longitude (x) in the inner loop to avoid repeat calculations of pixel areas, which should be
// equal at a given latitude (y)
double pixelAreaAtLat = -1; //Set to -1 to recalculate pixelArea at each latitude.
for (int worldx = lonToPixel(env.getMinX(), zoom); worldx <= lonToPixel(env.getMaxX(), zoom); worldx++) {
int x = worldx - west;
int y = worldy - north;
if (x < 0 || x >= width || y < 0 || y >= height) continue; // off the grid
Geometry pixel = getPixelGeometry(x + west, y + north, zoom);
if (pixelAreaAtLat == -1) pixelAreaAtLat = pixel.getArea(); //Recalculate for a new latitude.
if (preparedGeom.intersects(pixel)){ // pixel is at least partly inside the feature
Geometry intersection = pixel.intersection(geometry);
double denominator = relativeToPixels ? pixelAreaAtLat : area;
double weight = intersection.getArea() / denominator;
weights.add(new PixelWeight(x, y, weight));
}
}
}
return weights;
}
/**
* Do pycnoplactic mapping:
* the value associated with the supplied polygon will be split out proportionately to
* all the web Mercator pixels that intersect it.
*
* If you are creating multiple grids of the same size for different attributes of the same input features, you should
* call getPixelWeights(geometry) once for each geometry on any one of the grids, and then pass the returned weights
* and the attribute value into incrementFromPixelWeights function; this will avoid duplicating expensive geometric
* math.
*/
private void rasterize (Geometry geometry, double value) {
incrementFromPixelWeights(getPixelWeights(geometry), value);
}
/** Using a grid of weights produced by getPixelWeights, burn the value of a polygon into the grid */
public void incrementFromPixelWeights (List weights, double value) {
Iterator<PixelWeight> pixelWeightIterator = weights.iterator();
while(pixelWeightIterator.hasNext()) {
PixelWeight pix = pixelWeightIterator.next();
grid[pix.x][pix.y] += pix.weight * value;
}
}
/**
* Burn point data into the grid.
*/
private void incrementPoint (double lat, double lon, double amount) {
int worldx = lonToPixel(lon, zoom);
int worldy = latToPixel(lat, zoom);
int x = worldx - west;
int y = worldy - north;
if (x >= 0 && x < width && y >= 0 && y < height) {
grid[x][y] += amount;
} else {
LOG.warn("{} opportunities are outside regional bounds, at {}, {}", amount, lon, lat);
}
}
/** Write this grid out in R5 binary grid format. */
public void write (OutputStream outputStream) throws IOException {
// Java's DataOutputStream only outputs big-endian format ("network byte order").
// These grids will be read out of Javascript typed arrays which use the machine's native byte order.
// On almost all current hardware this is little-endian. Guava saves us again.
LittleEndianDataOutputStream out = new LittleEndianDataOutputStream(outputStream);
// A header consisting of six 4-byte integers specifying the zoom level and bounds.
out.writeInt(zoom);
out.writeInt(west);
out.writeInt(north);
out.writeInt(width);
out.writeInt(height);
// The rest of the file is 32-bit integers in row-major order (x changes faster than y), delta-coded.
for (int y = 0, prev = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int val = (int) Math.round(grid[x][y]);
out.writeInt(val - prev);
prev = val;
}
}
out.close();
}
/**
* How to get the width of the world in meters according to the EPSG CRS spec:
* $ gdaltransform -s_srs epsg:4326 -t_srs epsg:3857
* 180, 0
* 20037508.3427892 -7.08115455161362e-10 0
* You can't do 180, 90 because this projection is cut off above a certain level to make the world square.
* You can do the reverse projection to find this latitude:
* $ gdaltransform -s_srs epsg:3857 -t_srs epsg:4326
* 20037508.342789, 20037508.342789
* 179.999999999998 85.0511287798064 0
*/
public Coordinate mercatorPixelToMeters (double xPixel, double yPixel) {
double worldWidthPixels = Math.pow(2, zoom) * 256D;
// Top left is min x and y because y increases toward the south in web Mercator. Bottom right is max x and y.
// The origin is WGS84 (0,0).
final double worldWidthMeters = 20037508.342789244 * 2;
double xMeters = ((xPixel / worldWidthPixels) - 0.5) * worldWidthMeters;
double yMeters = (0.5 - (yPixel / worldWidthPixels)) * worldWidthMeters; // flip y axis
return new Coordinate(xMeters, yMeters);
}
/**
* At zoom level zero, our coordinates are pixels in a single planetary tile, with coordinates are in the range
* [0...256). We want to export with a conventional web Mercator envelope in meters.
*/
public ReferencedEnvelope getMercatorEnvelopeMeters() {
Coordinate topLeft = mercatorPixelToMeters(west, north);
Coordinate bottomRight = mercatorPixelToMeters(west + width, north + height);
Envelope mercatorEnvelope = new Envelope(topLeft, bottomRight);
try {
// Get Spherical Mercator pseudo-projection CRS
CoordinateReferenceSystem webMercator = CRS.decode("EPSG:3857");
ReferencedEnvelope env = new ReferencedEnvelope(mercatorEnvelope, webMercator);
return env;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/** Write this grid out in GeoTIFF format */
public void writeGeotiff (OutputStream out) {
try {
float[][] data = new float[height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
data[y][x] = (float) grid[x][y];
}
}
ReferencedEnvelope env = getMercatorEnvelopeMeters();
GridCoverage2D coverage = new GridCoverageFactory().create("GRID", data, env);
GeoTiffWriteParams wp = new GeoTiffWriteParams();
wp.setCompressionMode(GeoTiffWriteParams.MODE_EXPLICIT);
wp.setCompressionType("LZW");
ParameterValueGroup params = new GeoTiffFormat().getWriteParameters();
params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue(wp);
GeoTiffWriter writer = new GeoTiffWriter(out);
writer.write(coverage, params.values().toArray(new GeneralParameterValue[1]));
writer.dispose();
out.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Grid read (InputStream inputStream) throws IOException {
LittleEndianDataInputStream data = new LittleEndianDataInputStream(inputStream);
int zoom = data.readInt();
int west = data.readInt();
int north = data.readInt();
int width = data.readInt();
int height = data.readInt();
Grid grid = new Grid(zoom, width, height, north, west);
// loop in row-major order
for (int y = 0, value = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
grid.grid[x][y] = (value += data.readInt());
}
}
data.close();
return grid;
}
/** Write this grid out to a normalized grayscale image in PNG format. */
public void writePng(OutputStream outputStream) throws IOException {
// Find maximum pixel value to normalize brightness
double maxPixel = 0;
for (double[] row : grid) {
for (double value : row) {
if (value > maxPixel) {
maxPixel = value;
}
}
}
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
byte[] imgPixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
int p = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
double density = grid[x][y];
imgPixels[p++] = (byte)(density * 255 / maxPixel);
}
}
ImageIO.write(img, "png", outputStream);
outputStream.close();
}
/** Write this grid out as an ESRI Shapefile. */
public void writeShapefile (String fileName, String fieldName) {
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("Mercator Grid");
builder.setCRS(DefaultGeographicCRS.WGS84);
builder.add("the_geom", Polygon.class);
builder.add(fieldName, Double.class);
final SimpleFeatureType gridCell = builder.buildFeatureType();
try {
FileDataStore store = FileDataStoreFinder.getDataStore(new File(fileName));
store.createSchema(gridCell);
Transaction transaction = new DefaultTransaction("Save Grid");
FeatureWriter writer = store.getFeatureWriterAppend(transaction);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
try {
double value = grid[x][y];
if (value > 0) {
SimpleFeature feature = (SimpleFeature) writer.next();
Polygon pixelPolygon = getPixelGeometry(x + west, y + north, zoom);
feature.setDefaultGeometry(pixelPolygon);
feature.setAttribute(fieldName, value);
writer.write();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
transaction.commit();
writer.close();
store.dispose();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasEqualExtents(Grid comparisonGrid){
return this.zoom == comparisonGrid.zoom && this.west == comparisonGrid.west && this.north == comparisonGrid.north && this.width == comparisonGrid.width && this.height == comparisonGrid.height;
}
/** Return the pixel the given longitude falls within */
public static int lonToPixel (double lon, int zoom) {
return (int) ((lon + 180) / 360 * Math.pow(2, zoom) * 256);
}
/** return the west side of the given pixel (assuming an integer pixel; noninteger pixels will return the appropriate location within the pixel) */
public static double pixelToLon (double pixel, int zoom) {
return pixel / (Math.pow(2, zoom) * 256) * 360 - 180;
}
/** Return the longitude of the center of the given pixel */
public static double pixelToCenterLon (int pixel, int zoom) {
return pixelToLon(pixel + 0.5, zoom);
}
/** Return the pixel the given latitude falls within */
public static int latToPixel (double lat, int zoom) {
double latRad = FastMath.toRadians(lat);
return (int) ((1 - log(tan(latRad) + 1 / cos(latRad)) / Math.PI) * Math.pow(2, zoom - 1) * 256);
}
/** Return the latitude of the center of the given pixel */
public static double pixelToCenterLat (int pixel, int zoom) {
return pixelToLat(pixel + 0.5, zoom);
}
// We're using FastMath here, because the built-in math functions were taking a large amount of time in profiling.
/** return the north side of the given pixel (assuming an integer pixel; noninteger pixels will return the appropriate location within the pixel) */
public static double pixelToLat (double pixel, int zoom) {
return FastMath.toDegrees(atan(sinh(Math.PI - (pixel / 256d) / Math.pow(2, zoom) * 2 * Math.PI)));
}
/**
* @param x absolute (world) x pixel number at the given zoom level.
* @param y absolute (world) y pixel number at the given zoom level.
* @return a JTS Polygon in WGS84 coordinates for the given absolute (world) pixel.
*/
public static Polygon getPixelGeometry (int x, int y, int zoom) {
double minLon = pixelToLon(x, zoom);
double maxLon = pixelToLon(x + 1, zoom);
// The y axis increases from north to south in web Mercator.
double minLat = pixelToLat(y + 1, zoom);
double maxLat = pixelToLat(y, zoom);
return GeometryUtils.geometryFactory.createPolygon(new Coordinate[] {
new Coordinate(minLon, minLat),
new Coordinate(minLon, maxLat),
new Coordinate(maxLon, maxLat),
new Coordinate(maxLon, minLat),
new Coordinate(minLon, minLat)
});
}
/** Create grids from a CSV file */
public static Map<String,Grid> fromCsv(File csvFile, String latField, String lonField, int zoom) throws IOException {
return fromCsv(csvFile, latField, lonField, zoom, null);
}
public static Map<String,Grid> fromCsv(File csvFile, String latField, String lonField, int zoom, BiConsumer<Integer, Integer> statusListener) throws IOException {
CsvReader reader = new CsvReader(new BufferedInputStream(new FileInputStream(csvFile)), Charset.forName("UTF-8"));
reader.readHeaders();
String[] headers = reader.getHeaders();
if (!Stream.of(headers).anyMatch(h -> h.equals(latField))) {
LOG.info("Lat field not found!");
throw new IOException("Latitude field not found in CSV.");
}
if (!Stream.of(headers).anyMatch(h -> h.equals(lonField))) {
LOG.info("Lon field not found!");
throw new IOException("Longitude field not found in CSV.");
}
Envelope envelope = new Envelope();
// Keep track of which fields contain numeric values
Set<String> numericColumns = Stream.of(headers).collect(Collectors.toCollection(HashSet::new));
numericColumns.remove(latField);
numericColumns.remove(lonField);
// Detect which columns are completely numeric by iterating over all the rows and trying to parse the fields
int total = 0;
while (reader.readRecord()) {
if (++total % 10000 == 0) LOG.info("{} records", human(total));
envelope.expandToInclude(parseDouble(reader.get(lonField)), parseDouble(reader.get(latField)));
// Remove columns that cannot be parsed as doubles
for (Iterator<String> it = numericColumns.iterator(); it.hasNext();) {
String field = it.next();
String value = reader.get(field);
if (value == null || "".equals(value)) continue; // allow missing data
try {
// TODO also exclude columns containing negatives?
parseDouble(value);
} catch (NumberFormatException e) {
it.remove();
}
}
}
reader.close();
if (statusListener != null) statusListener.accept(0, total);
// We now have an envelope and know which columns are numeric
// Make a grid for each numeric column
Map<String, Grid> grids = numericColumns.stream()
.collect(
Collectors.toMap(
c -> c,
c -> new Grid(
zoom,
envelope.getMaxY(),
envelope.getMaxX(),
envelope.getMinY(),
envelope.getMinX()
)));
// read it again, Sam - reread the CSV to get the actual values and populate the grids
reader = new CsvReader(new BufferedInputStream(new FileInputStream(csvFile)), Charset.forName("UTF-8"));
reader.readHeaders();
int i = 0;
while (reader.readRecord()) {
if (++i % 1000 == 0) {
LOG.info("{} records", human(i));
}
if (statusListener != null) statusListener.accept(i, total);
double lat = parseDouble(reader.get(latField));
double lon = parseDouble(reader.get(lonField));
for (String field : numericColumns) {
String value = reader.get(field);
double val;
if (value == null || "".equals(value)) {
val = 0;
} else {
val = parseDouble(value);
}
grids.get(field).incrementPoint(lat, lon, val);
}
}
reader.close();
return grids;
}
public static Map<String, Grid> fromShapefile (File shapefile, int zoom) throws IOException, FactoryException, TransformException {
return fromShapefile(shapefile, zoom, null);
}
public static Map<String, Grid> fromShapefile (File shapefile, int zoom, BiConsumer<Integer, Integer> statusListener) throws IOException, FactoryException, TransformException {
Map<String, Grid> grids = new HashMap<>();
ShapefileReader reader = new ShapefileReader(shapefile);
double boundingBoxAreaSqKm = reader.getAreaSqKm();
if (boundingBoxAreaSqKm > MAX_BOUNDING_BOX_AREA_SQ_KM){
throw new IllegalArgumentException("Shapefile extent (" + boundingBoxAreaSqKm + " sq. km.) exceeds limit (" +
MAX_BOUNDING_BOX_AREA_SQ_KM + "sq. km.).");
}
Envelope envelope = reader.wgs84Bounds();
int total = reader.getFeatureCount();
if (statusListener != null) statusListener.accept(0, total);
AtomicInteger count = new AtomicInteger(0);
reader.wgs84Stream().forEach(feat -> {
Geometry geom = (Geometry) feat.getDefaultGeometry();
for (Property p : feat.getProperties()) {
Object val = p.getValue();
if (val == null || !Number.class.isInstance(val)) continue;
double numericVal = ((Number) val).doubleValue();
if (numericVal == 0) continue;
String attributeName = p.getName().getLocalPart();
if (!grids.containsKey(attributeName)) {
grids.put(attributeName, new Grid(
zoom,
envelope.getMaxY(),
envelope.getMaxX(),
envelope.getMinY(),
envelope.getMinX()
));
}
Grid grid = grids.get(attributeName);
if (geom instanceof Point) {
Point point = (Point) geom;
// already in WGS 84
grid.incrementPoint(point.getY(), point.getX(), numericVal);
} else if (geom instanceof Polygon || geom instanceof MultiPolygon) {
grid.rasterize(geom, numericVal);
} else {
throw new IllegalArgumentException("Unsupported geometry type");
}
}
int currentCount = count.incrementAndGet();
if (statusListener != null) statusListener.accept(currentCount, total);
if (currentCount % 10000 == 0) {
LOG.info("{} / {} features read", human(currentCount), human(total));
}
});
reader.close();
return grids;
}
}
|
package com.gengo.client;
import java.awt.image.BufferedImage;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.gengo.client.enums.HttpMethod;
import com.gengo.client.enums.Rating;
import com.gengo.client.enums.RejectReason;
import com.gengo.client.exceptions.GengoException;
import com.gengo.client.payloads.Approval;
import com.gengo.client.payloads.FileJob;
import com.gengo.client.payloads.Payload;
import com.gengo.client.payloads.Rejection;
import com.gengo.client.payloads.Revision;
import com.gengo.client.payloads.TranslationJob;
import com.gengo.client.payloads.Payloads;
public class GengoClient extends JsonHttpApi
{
private static final String STANDARD_BASE_URL = "http://api.gengo.com/v2/";
private static final String SANDBOX_BASE_URL = "http://api.sandbox.gengo.com/v2/";
/** Strings used to represent TRUE and FALSE in requests */
public static final String MYGENGO_TRUE = "1";
public static final String MYGENGO_FALSE = "0";
private String baseUrl = STANDARD_BASE_URL;
/**
* Initialize the client.
* @param publicKey your Gengo.com public API key
* @param privateKey your Gengo.com private API key
*/
public GengoClient(String publicKey, String privateKey)
{
this(publicKey, privateKey, false);
}
/**
* Initialize the client with the option to use the sandbox.
* @param publicKey your Gengo.com public API key
* @param privateKey your Gengo.com private API key
* @param useSandbox true to use the sandbox, false to use the live service
*/
public GengoClient(String publicKey, String privateKey, boolean useSandbox)
{
super(publicKey, privateKey);
setUseSandbox(useSandbox);
}
/**
* @return true iff the client is using the sandbox
*/
public boolean getUseSandbox()
{
return SANDBOX_BASE_URL.equals(baseUrl);
}
/**
* Set the client to use the sandbox or the live service.
* @param use true iff the client should use the sandbox
*/
public void setUseSandbox(boolean use)
{
baseUrl = use ? SANDBOX_BASE_URL : STANDARD_BASE_URL;
}
/**
* Set a custom base URL. For development testing purposes only.
* @param baseUrl a custom API base URL
*/
public void setBaseUrl(String baseUrl)
{
this.baseUrl = baseUrl;
}
/**
* Get account statistics.
* @return the response from the server
* @throws GengoException
*/
public JSONObject getAccountStats() throws GengoException
{
String url = baseUrl + "account/stats";
return call(url, HttpMethod.GET);
}
/**
* Get account balance.
* @return the response from the server
* @throws GengoException
*/
public JSONObject getAccountBalance() throws GengoException
{
String url = baseUrl + "account/balance";
return call(url, HttpMethod.GET);
}
/**
* Get preferred translators in array by langs and tier
* @return the response from the server
* @throws GengoException
*/
public JSONObject getAccountPreferredTranslators() throws GengoException
{
String url = baseUrl + "account/preferred_translators";
return call(url, HttpMethod.GET);
}
/**
* Submit multiple jobs for translation.
* @param jobs TranslationJob payload objects
* @param processAsGroup true iff the jobs should be processed as a group
* @return the response from the server
* @throws GengoException
*/
public JSONObject postTranslationJobs(List<TranslationJob> jobs, boolean processAsGroup)
throws GengoException
{
try
{
String url = baseUrl + "translate/jobs";
JSONObject data = new JSONObject();
/* We can safely cast our list of jobs into a list of the payload base type */
@SuppressWarnings({ "rawtypes", "unchecked" })
List<Payload> p = (List)jobs;
data.put("jobs", (new Payloads(p)).toJSONArray());
data.put("as_group", processAsGroup ? MYGENGO_TRUE : MYGENGO_FALSE);
JSONObject rsp = call(url, HttpMethod.POST, data);
return rsp;
}
catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Request revisions for a job.
* @param id The job ID
* @param comments Comments for the translator
* @return the response from the server
* @throws GengoException
*/
public JSONObject reviseTranslationJob(int id, String comments)
throws GengoException
{
try
{
String url = baseUrl + "translate/job/" + id;
JSONObject data = new JSONObject();
data.put("action", "revise");
data.put("comment", comments);
return call(url, HttpMethod.PUT, data);
} catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Approve a translation.
* @param id The job ID
* @param rating A rating for the translation
* @param commentsForTranslator Comments for the translator
* @param commentsForGengo Comments for Gengo
* @param feedbackIsPublic true iff the feedback can be shared publicly
* @return the response from the server
* @throws GengoException
*/
public JSONObject approveTranslationJob(int id, Rating rating,
String commentsForTranslator, String commentsForGengo,
boolean feedbackIsPublic) throws GengoException
{
try
{
String url = baseUrl + "translate/job/" + id;
JSONObject data = new JSONObject();
data.put("action", "approve");
if (commentsForTranslator != null) {
data.put("for_translator", commentsForTranslator);
}
if (commentsForGengo != null) {
data.put("for_gengo", commentsForGengo);
}
if (rating != null) {
data.put("rating", rating.toString());
}
data.put("public", feedbackIsPublic ? MYGENGO_TRUE : MYGENGO_FALSE);
return call(url, HttpMethod.PUT, data);
} catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
public JSONObject approveTranslationJob(int id, Rating rating,
String commentsForTranslator, String commentsForGengo) throws GengoException
{
return approveTranslationJob(id, rating, commentsForTranslator, commentsForGengo, false);
}
/**
* Reject a translation.
* @param id the job ID
* @param reason reason for rejection
* @param comments comments for Gengo
* @param captcha the captcha image text
* @param requeue true iff the job should be passed on to another translator
* @return the response from the server
* @throws GengoException
*/
public JSONObject rejectTranslationJob(int id, RejectReason reason,
String comments, String captcha, boolean requeue)
throws GengoException
{
try
{
String url = baseUrl + "translate/job/" + id;
JSONObject data = new JSONObject();
data.put("action", "reject");
data.put("reason", reason.toString().toLowerCase());
data.put("comment", comments);
data.put("captcha", captcha);
data.put("follow_up", requeue ? "requeue" : "cancel");
return call(url, HttpMethod.PUT, data);
} catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Get a translation job
* @param id the job id
* @return the response from the server
* @throws GengoException
*/
public JSONObject getTranslationJob(int id) throws GengoException
{
String url = baseUrl + "translate/job/" + id;
return call(url, HttpMethod.GET);
}
/**
* Get all translation jobs
* @return the response from the server
* @throws GengoException
*/
public JSONObject getTranslationJobs() throws GengoException
{
String url = baseUrl + "translate/jobs/";
return call(url, HttpMethod.GET);
}
/**
* Get selected translation jobs
* @param ids a list of job ids to retrieve
* @return the response from the server
* @throws GengoException
*/
public JSONObject getTranslationJobs(List<Integer> ids) throws GengoException
{
String url = baseUrl + "translate/jobs/";
url += join(ids, ",");
return call(url, HttpMethod.GET);
}
/**
* Post a comment for a translation job
* @param id the ID of the job to comment on
* @param comment the comment
* @return the response from the server
* @throws GengoException
*/
public JSONObject postTranslationJobComment(int id, String comment)
throws GengoException
{
try
{
String url = baseUrl + "translate/job/" + id + "/comment";
JSONObject data = new JSONObject();
data.put("body", comment);
return call(url, HttpMethod.POST, data);
}
catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Get comments for a translation job
* @param id the job ID
* @return the response from the server
* @throws GengoException
*/
public JSONObject getTranslationJobComments(int id) throws GengoException
{
String url = baseUrl + "translate/job/" + id + "/comments/";
return call(url, HttpMethod.GET);
}
/**
* Get feedback for a translation job
* @param id the job ID
* @return the response from the server
* @throws GengoException
*/
public JSONObject getTranslationJobFeedback(int id) throws GengoException
{
String url = baseUrl + "translate/job/" + id + "/feedback";
return call(url, HttpMethod.GET);
}
/**
* Get all revisions for a translation job
* @param id the job ID
* @return the response from the server
* @throws GengoException
*/
public JSONObject getTranslationJobRevisions(int id) throws GengoException
{
String url = baseUrl + "translate/job/" + id + "/revisions";
return call(url, HttpMethod.GET);
}
/**
* Get a specific revision for a translation job
* @param id the job ID
* @param revisionId the ID of the revision to retrieve
* @return the response from the server
* @throws GengoException
*/
public JSONObject getTranslationJobRevision(int id, int revisionId)
throws GengoException
{
String url = baseUrl + "translate/job/" + id + "/revision/"
+ revisionId;
return call(url, HttpMethod.GET);
}
/**
* Cancel a translation job. It can only be deleted if it has not been started by a translator.
* @param id the job ID
* @return the response from the server
* @throws GengoException
*/
public JSONObject deleteTranslationJob(int id) throws GengoException
{
String url = baseUrl + "translate/job/" + id;
return call(url, HttpMethod.DELETE);
}
/**
* Cancel translation jobs. They can only be deleted if they have not been started by a translator.
* @param ids a list of job IDs to delete
* @return the response from the server
* @throws GengoException
*/
public JSONObject deleteTranslationJobs(List<Integer> ids) throws GengoException
{
try
{
String url = baseUrl + "translate/jobs/";
JSONObject data = new JSONObject();
data.put("job_ids", ids);
return call(url, HttpMethod.DELETE, data);
}
catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Get a list of supported languages and their language codes.
* @return the response from the server
* @throws GengoException
*/
public JSONObject getServiceLanguages() throws GengoException
{
String url = baseUrl + "translate/service/languages";
return call(url, HttpMethod.GET);
}
/**
* Get a list of supported language pairs, tiers, and credit prices.
* @return the response from the server
* @throws GengoException
*/
public JSONObject getServiceLanguagePairs() throws GengoException
{
String url = baseUrl + "translate/service/language_pairs";
return call(url, HttpMethod.GET);
}
/**
* Get a list of supported language pairs, tiers and credit prices for a specific source language.
* @param sourceLanguageCode the language code for the source language
* @return the response from the server
* @throws GengoException
*/
public JSONObject getServiceLanguagePairs(String sourceLanguageCode) throws GengoException
{
try
{
String url = baseUrl + "translate/service/language_pairs";
JSONObject data = new JSONObject();
data.put("lc_src", sourceLanguageCode);
return call(url, HttpMethod.GET, data);
}
catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Get a quote for translation jobs.
* @param jobs Translation job objects to be quoted for
* @return the response from the server
* @throws GengoException
*/
public JSONObject determineTranslationCost(Payloads jobs) throws GengoException
{
try
{
String url = baseUrl + "translate/service/quote/";
JSONObject data = new JSONObject();
data.put("jobs", jobs.toJSONArray());
return call(url, HttpMethod.POST, data);
} catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Get translation jobs which were previously submitted together by their order id.
*
* @param orderId
* @return the response from the server
* @throws GengoException
*/
public JSONObject getOrderJobs(int orderId) throws GengoException
{
String url = baseUrl + "translate/order/";
url += orderId;
return call(url, HttpMethod.GET);
}
/**
* Get a quote for file jobs.
* @param jobs Translation job objects to be quoted
* @param filePaths map of file keys to filesystem paths
* @return the response from the server
* @throws GengoException
*/
public JSONObject determineTranslationCostFiles(List<FileJob> jobs, Map<String, String> filePaths) throws GengoException
{
try
{
JSONObject theJobs = new JSONObject();
for (int i = 0; i < jobs.size(); i++) {
theJobs.put(String.format("job_%s", i), jobs.get(i).toJSONObject());
}
String url = baseUrl + "translate/service/quote/file";
JSONObject data = new JSONObject();
data.put("jobs", theJobs);
return httpPostFileUpload(url, data, filePaths);
} catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Utility function.
*/
private String join(Iterable<? extends Object> pColl, String separator)
{
Iterator<? extends Object> oIter;
if (pColl == null || (!(oIter = pColl.iterator()).hasNext()))
{
return "";
}
StringBuffer oBuilder = new StringBuffer(String.valueOf(oIter.next()));
while (oIter.hasNext())
{
oBuilder.append(separator).append(oIter.next());
}
return oBuilder.toString();
}
}
|
package com.gengo.client;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;
import org.json.JSONException;
import org.json.JSONObject;
import com.gengo.client.enums.HttpMethod;
import com.gengo.client.exceptions.ErrorResponseException;
import com.gengo.client.exceptions.GengoException;
/**
* The basis of an authenticated API client built on JSON over HTTP
*/
public class JsonHttpApi
{
public static final String CLIENT_VERSION = "2.1.2";
/** Whether authentication is required by default for API method calls. */
private static final boolean AUTHENTICATION_REQUIRED_DEFAULT = true;
protected String publicKey;
protected String privateKey;
/**
* Initialize a new API instance with the specified keys.
* @param publicKey Public API key
* @param privateKey Private API key
*/
public JsonHttpApi(String publicKey, String privateKey)
{
this.publicKey = publicKey;
this.privateKey = privateKey;
}
/**
* @return A timestamp string representing the current time.
*/
private String getTimestamp()
{
Calendar cal = Calendar.getInstance();
//cal.add(Calendar.MILLISECOND, -cal.get(Calendar.DST_OFFSET) - cal.get(Calendar.ZONE_OFFSET));
return String.valueOf(cal.getTimeInMillis() / 1000);
}
/**
* @param url The API method URL
* @param method An HTTP method
* @return A JSONObject containing the response from the server
* @throws GengoException if something went wrong :(
*/
protected JSONObject call(String url, HttpMethod method) throws GengoException
{
return call(url, method, null, AUTHENTICATION_REQUIRED_DEFAULT);
}
/**
* @param url The API method URL
* @param method An HTTP method
* @param data JSON data to send in request
* @return A JSONObject containing the response from the server
* @throws GengoException if something went wrong :(
*/
protected JSONObject call(String url, HttpMethod method, JSONObject data) throws GengoException
{
return call(url, method, data, AUTHENTICATION_REQUIRED_DEFAULT);
}
/**
* @param url The API method URL
* @param method An HTTP method
* @param requiresAuthentication true iff authentication is required for this call
* @return A JSONObject containing the response from the server
* @throws GengoException if something went wrong :(
*/
protected JSONObject call(String url, HttpMethod method, boolean requiresAuthentication) throws GengoException
{
return call(url, method, null, requiresAuthentication);
}
private void handleData(Map<String, String> parameters, JSONObject data, HttpMethod method)
{
if (null != data)
{
if (HttpMethod.GET == method)
{
@SuppressWarnings("rawtypes") // This flows in from JSONJava
Iterator dataKeys = data.keys();
while (dataKeys.hasNext())
{
String k = dataKeys.next().toString();
try
{
parameters.put(k, data.getString(k));
} catch (JSONException e)
{
// Skip keys that don't map to strings
}
}
}
else// if (HttpMethod.POST == method || HttpMethod.PUT == method)
{
parameters.put("data", data.toString());
}
}
}
/**
* @param url The API method URL
* @param method An HTTP method
* @param data JSON data to send in request
* @param requiresAuthentication true iff authentication is required for this call
* @return A JSONObject containing the response from the server
* @throws GengoException if something went wrong :(
*/
protected JSONObject call(String url, HttpMethod method, JSONObject data, boolean requiresAuthentication) throws GengoException
{
if (requiresAuthentication && (null == this.publicKey) || (null == this.privateKey))
{
throw new GengoException("This API requires authentication. Both a public and private key must be specified.");
}
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("api_key", this.publicKey);
if (requiresAuthentication)
{
parameters.put("ts", getTimestamp());
parameters.put("api_sig", hmac(parameters.get("ts")));
}
handleData(parameters, data, method);
String queryString = makeQueryString(parameters);
String rsp = sendRequest(method, url, queryString);
JSONObject doc;
try
{
doc = new JSONObject(rsp);
if ("error".equals(doc.getString("opstat")))
{
JSONObject error = doc.getJSONObject("err");
if (!error.has("msg") && error.has("0"))
{
error = error.getJSONArray("0").getJSONObject(0);
}
throw new ErrorResponseException(error.getString("msg"), error.getInt("code"));
}
}
catch (JSONException e)
{
throw new GengoException("The response from the server is not valid JSON: " + rsp, e);
}
return doc;
}
/**
* Builds a query string from a dictionary of parameters and values
* @param data Maps parameters to values
* @return A properly encoded URL query string
* @throws GengoException
*/
private String makeQueryString(Map<String, String> data) throws GengoException
{
StringBuffer sb = new StringBuffer();
for(Map.Entry<String, String> e : data.entrySet())
{
try {
sb.append(String.format(
"&%s=%s",
URLEncoder.encode(e.getKey(), "UTF-8"),
URLEncoder.encode(e.getValue(), "UTF-8")
));
}
catch (UnsupportedEncodingException ex)
{
throw new GengoException("URLEncoder does not support UTF-8", ex);
}
}
//sb.deleteCharAt(0); // Remove the initial ampersand
return sb.toString();
}
/**
* Create a signature for data
* Note: both data and private_key are assumed to be ISO-8859-1
* @param data The data to be hashed
* @param private_key The key used to create the MAC
* @return The HMAC in Hex format
*/
private String hmac(String data) throws GengoException
{
try
{
SecretKeySpec signingKey = new SecretKeySpec(this.privateKey.getBytes("iso-8859-1"), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes("iso-8859-1"));
StringBuffer buf = new StringBuffer();
for (int i = 0; i < rawHmac.length; i++)
{
int num = (rawHmac[i] & 0xff);
String hex = Integer.toHexString(num);
if (hex.length() == 1) {
hex = "0" + hex;
}
buf.append(hex);
}
return buf.toString();
}
catch (Exception ex)
{
throw new GengoException("Signing failed", ex);
}
}
/**
* Perform an HTTP POST
* @param con An open, configured HTTP connection
* @param query An encoded query string
* @return The response from the server
* @throws GengoException if something went wrong :(
*/
private String httpPost(HttpURLConnection con, String query) throws GengoException
{
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
try
{
String length = Integer.toString(query.getBytes("UTF-8").length);
con.setRequestProperty("Content-Length", length);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
out.write(query);
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8")));
String line;
StringBuffer buf = new StringBuffer();
while (null != (line = reader.readLine()))
{
buf.append(line);
}
if (HttpURLConnection.HTTP_OK != con.getResponseCode()
&& HttpURLConnection.HTTP_CREATED != con.getResponseCode())
{
throw new GengoException(String.format("Unexpected HTTP response: %d", con.getResponseCode()));
}
return buf.toString();
}
catch (Exception e)
{
throw new GengoException("HTTP POST failed", e);
}
}
/**
* Perform an HTTP POST for file upload
* @param url the URL to POST to
* @param data the jobs payloads JSONObject
* @param filePaths a map of file keys to file paths
* @return The response from the server
* @throws GengoException if something went wrong :(
*/
protected JSONObject httpPostFileUpload(String url, JSONObject data, Map<String, String> filePaths) throws GengoException
{
try {
String charset = "UTF-8";
HttpURLConnection con = createHttpConnection(HttpMethod.POST, url, null);
con.setDoOutput(true);
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("api_key", this.publicKey);
parameters.put("ts", getTimestamp());
parameters.put("api_sig", hmac(parameters.get("ts")));
PrintWriter writer = null;
try
{
OutputStream output = con.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!
// Send normal params.
for (Map.Entry<String, String> param : parameters.entrySet()) {
writer.append("--" + boundary).append(CRLF);
writer.append(String.format("Content-Disposition: form-data; name=\"%s\"", param.getKey())).append(CRLF);
writer.append("Content-Type: text/plain").append(CRLF);
writer.append(CRLF);
writer.append(param.getValue()).append(CRLF).flush();
}
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"data\"").append(CRLF);
writer.append("Content-Type: text/plain").append(CRLF);
writer.append(CRLF);
writer.append(data.toString()).append(CRLF).flush();
// Send files.
for (Map.Entry<String, String> file : filePaths.entrySet()) {
File binaryFile = new File(file.getValue());
writer.append("--" + boundary).append(CRLF);
writer.append(String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", file.getKey(), file.getValue())).append(CRLF);
writer.append("Content-Type: " + HttpURLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
writer.append(CRLF).flush();
InputStream input = null;
try {
input = new FileInputStream(binaryFile);
byte[] buffer = new byte[1024];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
output.flush(); // Important! Output cannot be closed. Close of writer will close output as well.
} finally {
if (input != null) try {
input.close();
} catch (IOException e) {
throw e;
}
}
writer.append(CRLF).flush(); // CRLF is important! It indicates end of binary boundary.
}
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF);
} finally {
if (writer != null) {
writer.close();
}
}
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8")));
String line;
StringBuffer buf = new StringBuffer();
while (null != (line = reader.readLine()))
{
buf.append(line);
}
if (HttpURLConnection.HTTP_OK != con.getResponseCode()
&& HttpURLConnection.HTTP_CREATED != con.getResponseCode())
{
throw new GengoException(String.format("Unexpected HTTP response: %d", con.getResponseCode()));
}
JSONObject doc;
String rsp = buf.toString();
try
{
doc = new JSONObject(rsp);
if ("error".equals(doc.getString("opstat")))
{
JSONObject error = doc.getJSONObject("err");
throw new ErrorResponseException(error.getString("msg"), error.getInt("code"));
}
}
catch (JSONException e)
{
throw new GengoException("The response from the server is not valid JSON: " + rsp, e);
}
return doc;
}
catch (Exception e)
{
throw new GengoException("HTTP POST failed", e);
}
}
/**
* Perform an HTTP GET
* @param con An open, configured HTTP connection
* @return The response from the server
* @throws GengoException if something went wrong :(
*/
private String httpGet(HttpURLConnection con) throws GengoException
{
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8")));
String line;
StringBuffer buf = new StringBuffer();
while (null != (line = reader.readLine()))
{
buf.append(line);
}
if (HttpURLConnection.HTTP_OK != con.getResponseCode())
{
throw new GengoException(String.format("Unexpected HTTP response: %i", con.getResponseCode()));
}
return buf.toString();
}
catch (Exception e)
{
throw new GengoException("HTTP GET failed", e);
}
}
/**
* Perform an HTTP DELETE
* @param con An open, configured HTTP connection
* @return The response from the server
* @throws GengoException if something went wrong :(
*/
private String httpDelete(HttpURLConnection con) throws GengoException
{
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8")));
String line;
StringBuffer buf = new StringBuffer();
while (null != (line = reader.readLine()))
{
buf.append(line);
}
if (HttpURLConnection.HTTP_OK != con.getResponseCode())
{
throw new GengoException(String.format("Unexpected HTTP response: %i", con.getResponseCode()));
}
return buf.toString();
}
catch (Exception e)
{
throw new GengoException("HTTP DELETE failed", e);
}
}
private String httpPut(HttpURLConnection con, String query) throws GengoException
{
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
try
{
String length = Integer.toString(query.getBytes("UTF-8").length);
con.setRequestProperty("Content-Length", length);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(query);
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8")));
String line;
StringBuffer buf = new StringBuffer();
while (null != (line = reader.readLine()))
{
buf.append(line);
}
if (HttpURLConnection.HTTP_OK != con.getResponseCode())
{
throw new GengoException(String.format("Unexpected HTTP response: %i", con.getResponseCode()));
}
return buf.toString();
}
catch (Exception e)
{
throw new GengoException("HTTP PUT failed", e);
}
}
/**
* Configure and open an HTTP connection
* @param method The HTTP method to use
* @param url The URL to connect to (without query string)
* @param queryString The query string
* @return The HTTP connection
* @throws GengoException if something went wrong :(
*/
private HttpURLConnection createHttpConnection(HttpMethod method, String url, String queryString) throws GengoException
{
HttpURLConnection con;
try
{
if (HttpMethod.GET == method || HttpMethod.DELETE == method)
{
url += "?" + queryString;
}
URL u = new URL(url);
con = (HttpURLConnection)u.openConnection();
con.setRequestMethod(method.toString());
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("User-Agent", "Gengo Java library; Version " + CLIENT_VERSION + "; http://gengo.com/");
con.setRequestProperty("accept", "application/json");
}
catch (Exception e)
{
throw new GengoException("Failed to create HTTP connection", e);
}
return con;
}
/**
* Send an HTTP request
* @param method The HTTP method to use
* @param url The URL to connect to (without query string)
* @param queryString The query string
* @return The response from the server
* @throws GengoException
*/
private String sendRequest(HttpMethod method, String url, String queryString) throws GengoException
{
HttpURLConnection con = createHttpConnection(method, url, queryString);
switch (method)
{
case GET:
con.setRequestProperty("Content-Length", "0");
return httpGet(con);
case PUT:
return httpPut(con, queryString);
case POST:
return httpPost(con, queryString);
case DELETE:
return httpDelete(con);
default:
throw new GengoException("HTTP method " + method.toString() + " is not supported");
}
}
/**
* Get an image from a specified URL with authentication and timestamp.
* @param url The URL to which authentication and timestamp parameters will be added.
* @return an image downloaded from the specified URL
* @throws GengoException
*/
protected BufferedImage getImage(String url) throws GengoException
{
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("api_key", this.publicKey);
parameters.put("ts", getTimestamp());
parameters.put("api_sig", hmac(parameters.get("ts")));
String queryString = makeQueryString(parameters);
try
{
URL imgUrl = new URL(url + "?" + queryString);
BufferedImage image = ImageIO.read(imgUrl);
return image;
} catch (MalformedURLException e)
{
throw new GengoException("Bad URL for image", e);
} catch (IOException e)
{
// Call the JSON way to generate a more meaningful exception
// The server side doesn't give meaningful errors yet.
call(url, HttpMethod.GET);
throw new GengoException("IO Exception loading image", e);
}
}
}
|
package com.gooddata.processor;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import com.gooddata.connector.CsvConnector;
import com.gooddata.connector.GaConnector;
import com.gooddata.exceptions.InvalidArgumentException;
import com.gooddata.google.analytics.GaQuery;
import com.gooddata.integration.ftp.GdcFTPApiWrapper;
import com.gooddata.integration.model.DLI;
import com.gooddata.integration.model.DLIPart;
import com.gooddata.integration.rest.GdcRESTApiWrapper;
import com.gooddata.integration.rest.configuration.NamePasswordConfiguration;
import com.gooddata.integration.rest.exceptions.GdcLoginException;
import com.gooddata.util.FileUtil;
import org.gooddata.connector.AbstractConnector;
import org.gooddata.connector.backend.AbstractConnectorBackend;
/**
* The GoodData Data Integration CLI processor.
*
* @author jiri.zaloudek
* @author Zdenek Svoboda <zd@gooddata.org>
* @version 1.0
*/
public class GdcDI {
private final String ftpHost;
private final String host;
private final String userName;
private final String password;
private GdcRESTApiWrapper _restApi = null;
private GdcFTPApiWrapper _ftpApi = null;
private String projectId = null;
private AbstractConnector connector = null;
private int defaultConnectorBackend = AbstractConnectorBackend.CONNECTOR_BACKEND_DERBY_SQL;
private GdcDI(final String host, final String userName, final String password) throws GdcLoginException {
String ftpHost = null;
// Create the FTP host automatically
String[] hcs = host.split("\\.");
if(hcs != null && hcs.length > 0) {
for(String hc : hcs) {
if(ftpHost != null && ftpHost.length()>0)
ftpHost += "." + hc;
else
ftpHost = hc + "-upload";
}
}
else {
throw new IllegalArgumentException("Invalid format of the GoodData REST API host: " + host);
}
this.host = host;
this.ftpHost = ftpHost;
this.userName = userName;
this.password = password;
}
private void setProject(String projectId) {
this.projectId = projectId;
}
public void execute(final String commandsStr) throws Exception {
List<Command> cmds = new ArrayList<Command>();
cmds.addAll(parseCmd(commandsStr));
for(Command command : cmds) {
processCommand(command);
}
}
private GdcRESTApiWrapper getRestApi() throws GdcLoginException {
if (_restApi == null) {
if (userName == null || password == null) {
throw new IllegalArgumentException(
"Please specify both GoodData username (-u or --username) and password (-p or --password) command-line options");
}
final NamePasswordConfiguration httpConfiguration = new NamePasswordConfiguration(
"https", host,
userName, password);
_restApi = new GdcRESTApiWrapper(httpConfiguration);
_restApi.login();
}
return _restApi;
}
private GdcFTPApiWrapper getFtpApi() {
if (_ftpApi == null) {
System.out.println("Using the GoodData FTP host '" + ftpHost + "'.");
NamePasswordConfiguration ftpConfiguration = new NamePasswordConfiguration("ftp",
ftpHost, userName, password);
_ftpApi = new GdcFTPApiWrapper(ftpConfiguration);
}
return _ftpApi;
}
/**
* The main CLI processor
* @param args command line argument
* @throws Exception any issue
*/
public static void main(String[] args) throws Exception {
String host = "secure.gooddata.com";
Options o = new Options();
o.addOption("u", "username", true, "GoodData username");
o.addOption("p", "password", true, "GoodData password");
o.addOption("h", "host", true, "GoodData host");
o.addOption("i", "project", true, "GoodData project identifier (a string like nszfbgkr75otujmc4smtl6rf5pnmz9yl)");
o.addOption("e", "execute", true, "Commands and params to execute before the commands in provided files");
CommandLineParser parser = new GnuParser();
CommandLine line = parser.parse(o, args);
try {
if(line.hasOption("host")) {
host = line.getOptionValue("host");
}
else {
System.out.println("Using the default GoodData REST API host '" + host + "'.");
}
final String userName = line.getOptionValue("username");
final String password = line.getOptionValue("password");
GdcDI gdcDi = new GdcDI(host, userName, password);
if (line.hasOption("project")) {
gdcDi.setProject(line.getOptionValue("project"));
}
if (line.hasOption("execute")) {
gdcDi.execute(line.getOptionValue("execute"));
}
if (line.getArgs().length == 0 && !line.hasOption("execute")) {
printErrorHelpandExit("No command has been given, quitting", o);
}
for (final String arg : line.getArgs()) {
gdcDi.execute(FileUtil.readStringFromFile(arg));
}
} catch (final IllegalArgumentException e) {
printErrorHelpandExit(e.getMessage(), o);
}
}
/**
* Parses the commands
* @param cmd commands string
* @return array of commands
* @throws InvalidArgumentException in case there is an invalid command
*/
protected static List<Command> parseCmd(String cmd) throws InvalidArgumentException {
if(cmd != null && cmd.length()>0) {
List<Command> cmds = new ArrayList<Command>();
String[] commands = cmd.split(";");
for( String component : commands) {
component = component.trim();
if(component != null && component.length() > 0 && !component.startsWith("
Pattern p = Pattern.compile(".*?\\(.*?\\)");
Matcher m = p.matcher(component);
if(!m.matches())
throw new InvalidArgumentException("Invalid command: "+component);
p = Pattern.compile(".*?\\(");
m = p.matcher(component);
String command = "";
if(m.find()) {
command = m.group();
command = command.substring(0, command.length() - 1);
}
else {
throw new InvalidArgumentException("Can't extract command from: "+component);
}
p = Pattern.compile("\\(.*?\\)");
m = p.matcher(component);
Properties args = new Properties();
if(m.find()) {
String as = m.group();
as = as.substring(1,as.length()-1);
try {
args.load(new StringReader(as.replace(",","\n")));
}
catch (IOException e) {
throw new InvalidArgumentException(e.getMessage());
}
}
else {
throw new InvalidArgumentException("Can't extract command from: "+component);
}
cmds.add(new Command(command, args));
}
}
return cmds;
}
throw new InvalidArgumentException("Can't parse command.");
}
/**
* Returns the help for commands
* @return help text
*/
protected static String commandsHelp() throws Exception {
try {
final InputStream is = GdcDI.class.getResourceAsStream("/com/gooddata/processor/COMMANDS.txt");
if (is == null)
throw new IOException();
return FileUtil.readStringFromStream(is);
} catch (IOException e) {
throw new Exception("Could not read com/gooddata/processor/COMMANDS.txt");
}
}
/**
* Prints an err message, help and exits with status code 1
* @param err the err message
* @param o options
*/
protected static void printErrorHelpandExit(String err, Options o) throws Exception {
HelpFormatter formatter = new HelpFormatter();
System.out.println("ERROR: " + err);
System.out.println(commandsHelp());
System.exit(1);
}
/**
* Executes the command
* @param command to execute
* @throws Exception general error
*/
private void processCommand(Command command) throws Exception {
if(command.getCommand().equalsIgnoreCase("CreateProject")) {
String name = (String)command.getParameters().get("name");
String desc = (String)command.getParameters().get("desc");
if(name != null && name.length() > 0) {
if(desc != null && desc.length() > 0)
projectId = getRestApi().createProject(name, desc);
else
projectId = getRestApi().createProject(name, name);
System.out.println("Project id = '"+projectId+"' created.");
}
else
throw new IllegalArgumentException("CreateProject: Command requires the 'name' parameter.");
}
if(command.getCommand().equalsIgnoreCase("OpenProject")) {
String id = (String)command.getParameters().get("id");
if(id != null && id.length() > 0) {
projectId = id;
}
else {
throw new IllegalArgumentException("OpenProject: Command requires the 'id' parameter.");
}
}
if(command.getCommand().equalsIgnoreCase("GenerateCsvConfigTemplate")) {
String configFile = (String)command.getParameters().get("configFile");
String csvHeaderFile = (String)command.getParameters().get("csvHeaderFile");
if(configFile != null && configFile.length() > 0) {
File cf = new File(configFile);
if(csvHeaderFile != null && csvHeaderFile.length() > 0) {
File csvf = new File(csvHeaderFile);
if(csvf.exists()) {
CsvConnector.saveConfigTemplate(configFile, csvHeaderFile);
}
else
throw new IllegalArgumentException(
"GenerateCsvConfigTemplate: File '" + csvHeaderFile +
"' doesn't exists.");
}
else
throw new IllegalArgumentException(
"GenerateCsvConfigTemplate: Command requires the 'csvHeaderFile' parameter.");
}
else
throw new IllegalArgumentException("GenerateCsvConfigTemplate: Command requires the 'configFile' parameter.");
}
if(command.getCommand().equalsIgnoreCase("LoadCsv")) {
String configFile = (String)command.getParameters().get("configFile");
String csvDataFile = (String)command.getParameters().get("csvDataFile");
if(configFile != null && configFile.length() > 0) {
File conf = new File(configFile);
if(conf.exists()) {
if(csvDataFile != null && csvDataFile.length() > 0) {
File csvf = new File(csvDataFile);
if(csvf.exists()) {
if(projectId != null) {
connector = CsvConnector.createConnector(projectId, configFile, csvDataFile,
defaultConnectorBackend);
}
else
throw new IllegalArgumentException(
"LoadCsv: No active project found. Use command 'CreateProject'" +
" or 'OpenProject' first.");
}
else
throw new IllegalArgumentException(
"LoadCsv: File '" + csvDataFile +
"' doesn't exists.");
}
else
throw new IllegalArgumentException(
"LoadCsv: Command requires the 'csvHeaderFile' parameter.");
}
else
throw new IllegalArgumentException(
"LoadCsv: File '" + configFile +
"' doesn't exists.");
}
else
throw new IllegalArgumentException(
"LoadCsv: Command requires the 'configFile' parameter.");
}
if(command.getCommand().equalsIgnoreCase("GenerateGoogleAnalyticsConfigTemplate")) {
String configFile = (String)command.getParameters().get("configFile");
String name = (String)command.getParameters().get("name");
String dimensions = (String)command.getParameters().get("dimensions");
String metrics = (String)command.getParameters().get("metrics");
if(configFile != null && configFile.length() > 0) {
File cf = new File(configFile);
if(dimensions != null && dimensions.length() > 0) {
if(metrics != null && metrics.length() > 0) {
if(name != null && name.length() > 0) {
GaQuery gq = null;
try {
gq = new GaQuery();
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e.getMessage());
}
gq.setDimensions(dimensions);
gq.setMetrics(metrics);
GaConnector.saveConfigTemplate(name, configFile, gq);
}
else
throw new IllegalArgumentException(
"GenerateGoogleAnalyticsConfigTemplate: Please specify a name using the name parameter.");
}
else
throw new IllegalArgumentException(
"GenerateGoogleAnalyticsConfigTemplate: Please specify a metrics using the metrics parameter.");
}
else
throw new IllegalArgumentException(
"GenerateGoogleAnalyticsConfigTemplate: Please specify a dimensions using the dimensions parameter.");
}
else
throw new IllegalArgumentException(
"GenerateGoogleAnalyticsConfigTemplate: Please specify a config file using the configFile parameter.");
}
if(command.getCommand().equalsIgnoreCase("LoadGoogleAnalytics")) {
String configFile = (String)command.getParameters().get("configFile");
String usr = (String)command.getParameters().get("username");
String psw = (String)command.getParameters().get("password");
String id = (String)command.getParameters().get("profileId");
String dimensions = (String)command.getParameters().get("dimensions");
String metrics = (String)command.getParameters().get("metrics");
String startDate = (String)command.getParameters().get("startDate");
String endDate = (String)command.getParameters().get("endDate");
String filters = (String)command.getParameters().get("filters");
if(configFile != null && configFile.length() > 0) {
File conf = new File(configFile);
if(conf.exists()) {
if(projectId != null) {
if(usr != null && usr.length() > 0) {
if(psw != null && psw.length() > 0) {
if(id != null && id.length() > 0) {
GaQuery gq = null;
try {
gq = new GaQuery();
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e.getMessage());
}
if(dimensions != null && dimensions.length() > 0)
gq.setDimensions(dimensions.replace("|",","));
else
throw new IllegalArgumentException(
"LoadGoogleAnalytics: Please specify a dimensions using the dimensions parameter.");
if(metrics != null && metrics.length() > 0)
gq.setMetrics(metrics.replace("|",","));
else
throw new IllegalArgumentException(
"LoadGoogleAnalytics: Please specify a metrics using the metrics parameter.");
if(startDate != null && startDate.length() > 0)
gq.setStartDate(startDate);
if(endDate != null && endDate.length() > 0)
gq.setEndDate(endDate);
if(filters != null && filters.length() > 0)
gq.setFilters(filters);
connector = GaConnector.createConnector(projectId, configFile, usr, psw, id, gq,
defaultConnectorBackend);
}
else
throw new IllegalArgumentException(
"LoadGoogleAnalytics: Please specify a Google Profile ID using the profileId parameter.");
}
else
throw new IllegalArgumentException(
"LoadGoogleAnalytics: Please specify a Google username using the username parameter.");
}
else
throw new IllegalArgumentException(
"LoadGoogleAnalytics: Please specify a Google password using the password parameter.");
}
else
throw new IllegalArgumentException(
"LoadGoogleAnalytics: No active project found. Use command 'CreateProject'" +
" or 'OpenProject' first.");
}
else
throw new IllegalArgumentException(
"LoadGoogleAnalytics: File '" + configFile +
"' doesn't exists.");
}
else
throw new IllegalArgumentException(
"LoadGoogleAnalytics: Command requires the 'configFile' parameter.");
}
if(command.getCommand().equalsIgnoreCase("GenerateMaql")) {
String maqlFile = (String)command.getParameters().get("maqlFile");
if(maqlFile != null && maqlFile.length() > 0) {
if(connector != null) {
String maql = connector.generateMaql();
FileUtil.writeStringToFile(maql, maqlFile);
}
else
throw new IllegalArgumentException("GenerateMaql: No data source loaded. Use a 'LoadXXX' to load a data source.");
}
else
throw new IllegalArgumentException("GenerateMaql: Command requires the 'maqlFile' parameter.");
}
if(command.getCommand().equalsIgnoreCase("ExecuteMaql")) {
String maqlFile = (String)command.getParameters().get("maqlFile");
if(maqlFile != null && maqlFile.length() > 0) {
File mf = new File(maqlFile);
if(mf.exists()) {
if(projectId != null) {
String maql = FileUtil.readStringFromFile(maqlFile);
getRestApi().executeMAQL(projectId, maql);
}
else
throw new IllegalArgumentException(
"ExecuteMaql: No active project found. Use command 'CreateProject'" +
" or 'OpenProject' first.");
}
else
throw new IllegalArgumentException(
"ExecuteMaql: File '" + maqlFile +
"' doesn't exists.");
}
else
throw new IllegalArgumentException("ExecuteMaql: Command requires the 'maqlFile' parameter.");
}
if(command.getCommand().equalsIgnoreCase("ListSnapshots")) {
if(connector != null) {
System.out.println(connector.listSnapshots());
}
else
throw new IllegalArgumentException("ListSnapshots: No data source loaded. Use a 'LoadXXX' to load a data source.");
}
if(command.getCommand().equalsIgnoreCase("DropSnapshots")) {
if(connector != null) {
connector.dropSnapshots();
}
else
throw new IllegalArgumentException("DropSnapshots: No data source loaded. Use a 'LoadXXX' to load a data source.");
}
if(command.getCommand().equalsIgnoreCase("TransferData")) {
if(connector != null) {
if(!connector.isInitialized())
connector.initialize();
// retrieve the DLI
DLI dli = getRestApi().getDLIById("dataset." + connector.getSchema().getName().toLowerCase(), projectId);
List<DLIPart> parts= getRestApi().getDLIParts("dataset." + connector.getSchema().getName().toLowerCase(), projectId);
// target directories and ZIP names
String incremental = (String)command.getParameters().get("incremental");
if(incremental != null && incremental.length() > 0 && incremental.equalsIgnoreCase("true")) {
for(DLIPart part : parts) {
if(part.getFileName().startsWith("f_")) {
part.setLoadMode(DLIPart.LM_INCREMENTAL);
}
}
}
File tmpDir = FileUtil.createTempDir();
File tmpZipDir = FileUtil.createTempDir();
String archiveName = tmpDir.getName();
String archivePath = tmpZipDir.getAbsolutePath() + System.getProperty("file.separator") +
archiveName + ".zip";
// loads the CSV data to the embedded Derby SQL
connector.extract();
// normalize the data in the Derby
connector.transform();
// load data from the Derby to the local GoodData data integration package
connector.deploy(dli, parts, tmpDir.getAbsolutePath(), archivePath);
// transfer the data package to the GoodData server
getFtpApi().transferDir(archivePath);
// kick the GooDData server to load the data package to the project
getRestApi().startLoading(projectId, archiveName);
}
else
throw new IllegalArgumentException("TransferData: No data source loaded. Use a 'LoadXXX' to load a data source.");
}
if(command.getCommand().equalsIgnoreCase("TransferSnapshots")) {
String firstSnapshot = (String)command.getParameters().get("firstSnapshot");
String lastSnapshot = (String)command.getParameters().get("lastSnapshot");
if(firstSnapshot != null && firstSnapshot.length() > 0) {
if(lastSnapshot != null && lastSnapshot.length() > 0) {
int fs = 0,ls = 0;
try {
fs = Integer.parseInt(firstSnapshot);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("TransferSnapshots: The 'firstSnapshot' (" + firstSnapshot +
") parameter is not a number.");
}
try {
ls = Integer.parseInt(lastSnapshot);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("TransferSnapshots: The 'lastSnapshot' (" + lastSnapshot +
") parameter is not a number.");
}
int cnt = ls - fs;
if(cnt >= 0) {
int[] snapshots = new int[cnt];
for(int i = 0; i < cnt; i++) {
snapshots[i] = fs + i;
}
if(connector != null) {
if(!connector.isInitialized())
connector.initialize();
// retrieve the DLI
DLI dli = getRestApi().getDLIById("dataset." + connector.getSchema().getName().toLowerCase(),
projectId);
List<DLIPart> parts= getRestApi().getDLIParts("dataset." +
connector.getSchema().getName().toLowerCase(), projectId);
String incremental = (String)command.getParameters().get("incremental");
if(incremental != null && incremental.length() > 0 &&
incremental.equalsIgnoreCase("true")) {
for(DLIPart part : parts) {
if(part.getFileName().startsWith("f_")) {
part.setLoadMode(DLIPart.LM_INCREMENTAL);
}
}
}
// target directories and ZIP names
File tmpDir = FileUtil.createTempDir();
File tmpZipDir = FileUtil.createTempDir();
String archiveName = tmpDir.getName();
String archivePath = tmpZipDir.getAbsolutePath() +
System.getProperty("file.separator") + archiveName + ".zip";
// loads the CSV data to the embedded Derby SQL
connector.extract();
// normalize the data in the Derby
connector.transform();
// load data from the Derby to the local GoodData data integration package
connector.deploySnapshot(dli, parts, tmpDir.getAbsolutePath(), archivePath,
snapshots);
// transfer the data package to the GoodData server
getFtpApi().transferDir(archivePath);
// kick the GooDData server to load the data package to the project
getRestApi().startLoading(projectId, archiveName);
}
else
throw new IllegalArgumentException("TransferSnapshots: No data source loaded." +
"Use a 'LoadXXX' to load a data source.");
}
else
throw new IllegalArgumentException("TransferSnapshots: The 'lastSnapshot' (" + lastSnapshot +
") parameter must be higher than the 'firstSnapshot' (" + firstSnapshot +
") parameter.");
}
else
throw new IllegalArgumentException("TransferSnapshots: Command requires the 'lastSnapshot' parameter.");
}
else
throw new IllegalArgumentException("TransferSnapshots: Command requires the 'firstSnapshot' parameter.");
}
if(command.getCommand().equalsIgnoreCase("TransferLastSnapshot")) {
if(connector != null) {
if(!connector.isInitialized())
connector.initialize();
// retrieve the DLI
DLI dli = getRestApi().getDLIById("dataset." + connector.getSchema().getName().toLowerCase(),
projectId);
List<DLIPart> parts= getRestApi().getDLIParts("dataset." +
connector.getSchema().getName().toLowerCase(), projectId);
String incremental = (String)command.getParameters().get("incremental");
if(incremental != null && incremental.length() > 0 &&
incremental.equalsIgnoreCase("true")) {
for(DLIPart part : parts) {
if(part.getFileName().startsWith("f_")) {
part.setLoadMode(DLIPart.LM_INCREMENTAL);
}
}
}
// target directories and ZIP names
File tmpDir = FileUtil.createTempDir();
File tmpZipDir = FileUtil.createTempDir();
String archiveName = tmpDir.getName();
String archivePath = tmpZipDir.getAbsolutePath() +
System.getProperty("file.separator") + archiveName + ".zip";
// loads the CSV data to the embedded Derby SQL
connector.extract();
// normalize the data in the Derby
connector.transform();
// load data from the Derby to the local GoodData data integration package
connector.deploySnapshot(dli, parts, tmpDir.getAbsolutePath(), archivePath,
new int[] {connector.getLastSnapshotId()});
// transfer the data package to the GoodData server
getFtpApi().transferDir(archivePath);
// kick the GooDData server to load the data package to the project
getRestApi().startLoading(projectId, archiveName);
}
else
throw new IllegalArgumentException("TransferLastSnapshot: No data source loaded." +
"Use a 'LoadXXX' to load a data source.");
}
}
}
|
package com.jaamsim.input;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import com.jaamsim.basicsim.Entity;
import com.jaamsim.basicsim.ErrorException;
import com.jaamsim.basicsim.Group;
import com.jaamsim.basicsim.ObjectType;
import com.jaamsim.math.Vec3d;
import com.jaamsim.ui.ExceptionBox;
import com.jaamsim.ui.FrameBox;
import com.jaamsim.ui.LogBox;
import com.sandwell.JavaSimulation.FileEntity;
import com.sandwell.JavaSimulation.Simulation;
import com.sandwell.JavaSimulation3D.GUIFrame;
public class InputAgent {
private static final String recordEditsMarker = "RecordEdits";
private static int numErrors = 0;
private static int numWarnings = 0;
private static FileEntity logFile;
private static double lastTimeForTrace;
private static File configFile; // present configuration file
private static boolean batchRun;
private static boolean sessionEdited; // TRUE if any inputs have been changed after loading a configuration file
private static boolean recordEditsFound; // TRUE if the "RecordEdits" marker is found in the configuration file
private static boolean recordEdits; // TRUE if input changes are to be marked as edited.
private static final String INP_ERR_DEFINEUSED = "The name: %s has already been used and is a %s";
private static File reportDir;
static {
recordEditsFound = false;
sessionEdited = false;
batchRun = false;
configFile = null;
reportDir = null;
lastTimeForTrace = -1.0d;
}
public static void clear() {
logFile = null;
numErrors = 0;
numWarnings = 0;
recordEditsFound = false;
sessionEdited = false;
configFile = null;
reportDir = null;
lastTimeForTrace = -1.0d;
setReportDirectory(null);
}
private static String getReportDirectory() {
if (reportDir != null)
return reportDir.getPath() + File.separator;
if (configFile != null)
return configFile.getParentFile().getPath() + File.separator;
return null;
}
public static String getReportFileName(String name) {
return getReportDirectory() + name;
}
public static void setReportDirectory(File dir) {
reportDir = dir;
}
public static void prepareReportDirectory() {
if (reportDir != null) reportDir.mkdirs();
}
/**
* Sets the present configuration file.
*
* @param file - the present configuration file.
*/
public static void setConfigFile(File file) {
configFile = file;
}
/**
* Returns the present configuration file.
* <p>
* Null is returned if no configuration file has been loaded or saved yet.
* <p>
* @return the present configuration file.
*/
public static File getConfigFile() {
return configFile;
}
/**
* Returns the name of the simulation run.
* <p>
* For example, if the configuration file name is "case1.cfg", then the
* run name is "case1".
* <p>
* @return the name of simulation run.
*/
public static String getRunName() {
if( InputAgent.getConfigFile() == null )
return "";
String name = InputAgent.getConfigFile().getName();
int index = name.lastIndexOf( "." );
if( index == -1 )
return name;
return name.substring( 0, index );
}
/**
* Specifies whether a RecordEdits marker was found in the present configuration file.
*
* @param bool - TRUE if a RecordEdits marker was found.
*/
public static void setRecordEditsFound(boolean bool) {
recordEditsFound = bool;
}
/**
* Indicates whether a RecordEdits marker was found in the present configuration file.
*
* @return - TRUE if a RecordEdits marker was found.
*/
public static boolean getRecordEditsFound() {
return recordEditsFound;
}
/**
* Returns the "RecordEdits" mode for the InputAgent.
* <p>
* When RecordEdits is TRUE, any model inputs that are changed and any objects that
* are defined are marked as "edited". When FALSE, model inputs and object
* definitions are marked as "unedited".
* <p>
* RecordEdits mode is used to determine the way JaamSim saves a configuration file
* through the graphical user interface. Object definitions and model inputs
* that are marked as unedited will be copied exactly as they appear in the original
* configuration file that was first loaded. Object definitions and model inputs
* that are marked as edited will be generated automatically by the program.
*
* @return the RecordEdits mode for the InputAgent.
*/
public static boolean recordEdits() {
return recordEdits;
}
/**
* Sets the "RecordEdits" mode for the InputAgent.
* <p>
* When RecordEdits is TRUE, any model inputs that are changed and any objects that
* are defined are marked as "edited". When FALSE, model inputs and object
* definitions are marked as "unedited".
* <p>
* RecordEdits mode is used to determine the way JaamSim saves a configuration file
* through the graphical user interface. Object definitions and model inputs
* that are marked as unedited will be copied exactly as they appear in the original
* configuration file that was first loaded. Object definitions and model inputs
* that are marked as edited will be generated automatically by the program.
*
* @param b - boolean value for the RecordEdits mode
*/
public static void setRecordEdits(boolean b) {
recordEdits = b;
}
public static boolean isSessionEdited() {
return sessionEdited;
}
public static void setBatch(boolean batch) {
batchRun = batch;
}
public static boolean getBatch() {
return batchRun;
}
private static int getBraceDepth(ArrayList<String> tokens, int startingBraceDepth, int startingIndex) {
int braceDepth = startingBraceDepth;
for (int i = startingIndex; i < tokens.size(); i++) {
String token = tokens.get(i);
if (token.equals("{"))
braceDepth++;
if (token.equals("}"))
braceDepth
if (braceDepth < 0) {
InputAgent.logBadInput(tokens, "Extra closing braces found");
tokens.clear();
}
if (braceDepth > 3) {
InputAgent.logBadInput(tokens, "Maximum brace depth (3) exceeded");
tokens.clear();
}
}
return braceDepth;
}
private static URI resRoot;
private static URI resPath;
private static final String res = "/resources/";
static {
try {
// locate the resource folder, and create
resRoot = InputAgent.class.getResource(res).toURI();
}
catch (URISyntaxException e) {}
resPath = URI.create(resRoot.toString());
}
private static void rethrowWrapped(Exception ex) {
StringBuilder causedStack = new StringBuilder();
for (StackTraceElement elm : ex.getStackTrace())
causedStack.append(elm.toString()).append("\n");
throw new InputErrorException("Caught exception: %s", ex.getMessage() + "\n" + causedStack.toString());
}
public static final void readResource(String res) {
if (res == null)
return;
try {
readStream(resRoot.toString(), resPath, res);
GUIFrame.instance().setProgressText(null);
}
catch (URISyntaxException ex) {
rethrowWrapped(ex);
}
}
public static final boolean readStream(String root, URI path, String file) throws URISyntaxException {
String shortName = file.substring(file.lastIndexOf('/') + 1, file.length());
GUIFrame.instance().setProgressText(shortName);
URI resolved = getFileURI(path, file, root);
URL url = null;
try {
url = resolved.normalize().toURL();
}
catch (MalformedURLException e) {
rethrowWrapped(e);
}
if (url == null) {
InputAgent.logError("Unable to resolve path %s%s - %s", root, path.toString(), file);
return false;
}
BufferedReader buf = null;
try {
InputStream in = url.openStream();
buf = new BufferedReader(new InputStreamReader(in));
} catch (IOException e) {
InputAgent.logError("Could not read from %s", url.toString());
return false;
}
try {
ArrayList<String> record = new ArrayList<>();
int braceDepth = 0;
ParseContext pc = new ParseContext(resolved, root);
while (true) {
String line = buf.readLine();
// end of file, stop reading
if (line == null)
break;
int previousRecordSize = record.size();
Parser.tokenize(record, line, true);
braceDepth = InputAgent.getBraceDepth(record, braceDepth, previousRecordSize);
if( braceDepth != 0 )
continue;
if (record.size() == 0)
continue;
InputAgent.echoInputRecord(record);
if ("DEFINE".equalsIgnoreCase(record.get(0))) {
InputAgent.processDefineRecord(record);
record.clear();
continue;
}
if ("INCLUDE".equalsIgnoreCase(record.get(0))) {
try {
InputAgent.processIncludeRecord(pc, record);
}
catch (URISyntaxException ex) {
rethrowWrapped(ex);
}
record.clear();
continue;
}
if ("RECORDEDITS".equalsIgnoreCase(record.get(0))) {
InputAgent.setRecordEditsFound(true);
InputAgent.setRecordEdits(true);
record.clear();
continue;
}
// Otherwise assume it is a Keyword record
InputAgent.processKeywordRecord(record, pc);
record.clear();
}
// Leftover Input at end of file
if (record.size() > 0)
InputAgent.logBadInput(record, "Leftover input at end of file");
buf.close();
}
catch (IOException e) {
// Make best effort to ensure it closes
try { buf.close(); } catch (IOException e2) {}
}
return true;
}
private static void processIncludeRecord(ParseContext pc, ArrayList<String> record) throws URISyntaxException {
if (record.size() != 2) {
InputAgent.logError("Bad Include record, should be: Include <File>");
return;
}
InputAgent.readStream(pc.jail, pc.context, record.get(1).replaceAll("\\\\", "/"));
}
private static void processDefineRecord(ArrayList<String> record) {
if (record.size() < 5 ||
!record.get(2).equals("{") ||
!record.get(record.size() - 1).equals("}")) {
InputAgent.logError("Bad Define record, should be: Define <Type> { <names>... }");
return;
}
Class<? extends Entity> proto = null;
try {
if( record.get( 1 ).equalsIgnoreCase( "ObjectType" ) ) {
proto = ObjectType.class;
}
else {
proto = Input.parseEntityType(record.get(1));
}
}
catch (InputErrorException e) {
InputAgent.logError("%s", e.getMessage());
return;
}
// Loop over all the new Entity names
for (int i = 3; i < record.size() - 1; i++) {
InputAgent.defineEntity(proto, record.get(i), InputAgent.recordEdits());
}
}
public static <T extends Entity> T generateEntityWithName(Class<T> proto, String key) {
if (key != null && !isValidName(key)) {
InputAgent.logError("Entity names cannot contain spaces, tabs, { or }: %s", key);
return null;
}
T ent = null;
try {
ent = proto.newInstance();
ent.setFlag(Entity.FLAG_GENERATED);
if (key != null)
ent.setName(key);
else
ent.setName(proto.getSimpleName() + "-" + ent.getEntityNumber());
}
catch (InstantiationException e) {}
catch (IllegalAccessException e) {}
finally {
if (ent == null) {
InputAgent.logError("Could not create new Entity: %s", key);
return null;
}
}
return ent;
}
/**
* Like defineEntity(), but will generate a unique name if a name collision exists
* @param proto
* @param key
* @param sep
* @param addedEntity
* @return
*/
public static <T extends Entity> T defineEntityWithUniqueName(Class<T> proto, String key, String sep, boolean addedEntity) {
// Has the provided name been used already?
if (Entity.getNamedEntity(key) == null) {
return defineEntity(proto, key, addedEntity);
}
// Try the provided name plus "1", "2", etc. until an unused name is found
int entityNum = 1;
while(true) {
String name = String.format("%s%s%d", key, sep, entityNum);
if (Entity.getNamedEntity(name) == null) {
return defineEntity(proto, name, addedEntity);
}
entityNum++;
}
}
private static boolean isValidName(String key) {
for (int i = 0; i < key.length(); ++i) {
final char c = key.charAt(i);
if (c == ' ' || c == '\t' || c == '{' || c == '}')
return false;
}
return true;
}
/**
* if addedEntity is true then this is an entity defined
* by user interaction or after added record flag is found;
* otherwise, it is from an input file define statement
* before the model is configured
* @param proto
* @param key
* @param addedEntity
*/
private static <T extends Entity> T defineEntity(Class<T> proto, String key, boolean addedEntity) {
Entity existingEnt = Input.tryParseEntity(key, Entity.class);
if (existingEnt != null) {
InputAgent.logError(INP_ERR_DEFINEUSED, key, existingEnt.getClass().getSimpleName());
return null;
}
if (!isValidName(key)) {
InputAgent.logError("Entity names cannot contain spaces, tabs, { or }: %s", key);
return null;
}
T ent = null;
try {
ent = proto.newInstance();
if (addedEntity) {
ent.setFlag(Entity.FLAG_ADDED);
sessionEdited = true;
}
}
catch (InstantiationException e) {}
catch (IllegalAccessException e) {}
finally {
if (ent == null) {
InputAgent.logError("Could not create new Entity: %s", key);
return null;
}
}
ent.setName(key);
return ent;
}
public static void processKeywordRecord(ArrayList<String> record, ParseContext context) {
Entity ent = Input.tryParseEntity(record.get(0), Entity.class);
if (ent == null) {
InputAgent.logError("Could not find Entity: %s", record.get(0));
return;
}
// Validate the tokens have the Entity Keyword { Args... } Keyword { Args... }
ArrayList<KeywordIndex> words = InputAgent.getKeywords(record, context);
for (KeywordIndex keyword : words) {
try {
InputAgent.processKeyword(ent, keyword);
}
catch (Throwable e) {
InputAgent.logInpError("Entity: %s, Keyword: %s - %s", ent.getName(), keyword.keyword, e.getMessage());
}
}
}
private static ArrayList<KeywordIndex> getKeywords(ArrayList<String> input, ParseContext context) {
ArrayList<KeywordIndex> ret = new ArrayList<>();
int braceDepth = 0;
int keyWordIdx = 1;
for (int i = 1; i < input.size(); i++) {
String tok = input.get(i);
if ("{".equals(tok)) {
braceDepth++;
continue;
}
if ("}".equals(tok)) {
braceDepth
if (braceDepth == 0) {
// validate keyword form
String keyword = input.get(keyWordIdx);
if (keyword.equals("{") || keyword.equals("}") || !input.get(keyWordIdx + 1).equals("{"))
throw new InputErrorException("The input for a keyword must be enclosed by braces. Should be <keyword> { <args> }");
ret.add(new KeywordIndex(input, keyword, keyWordIdx + 2, i, context));
keyWordIdx = i + 1;
continue;
}
}
}
if (keyWordIdx != input.size())
throw new InputErrorException("The input for a keyword must be enclosed by braces. Should be <keyword> { <args> }");
return ret;
}
public static void doError(Throwable e) {
if (!batchRun)
return;
LogBox.logLine("An error occurred in the simulation environment. Please check inputs for an error:");
LogBox.logLine(e.toString());
GUIFrame.shutdown(1);
}
// Load the run file
public static void loadConfigurationFile( File file) throws URISyntaxException {
String inputTraceFileName = InputAgent.getRunName() + ".log";
// Initializing the tracing for the model
try {
System.out.println( "Creating trace file" );
URI confURI = file.toURI();
URI logURI = confURI.resolve(new URI(null, inputTraceFileName, null)); // The new URI here effectively escapes the file name
// Set and open the input trace file name
logFile = new FileEntity( logURI.getPath());
}
catch( Exception e ) {
InputAgent.logWarning("Could not create trace file");
}
URI dirURI = file.getParentFile().toURI();
InputAgent.readStream("", dirURI, file.getName());
GUIFrame.instance().setProgressText(null);
GUIFrame.instance().setProgress(0);
// At this point configuration file is loaded
// The session is not considered to be edited after loading a configuration file
sessionEdited = false;
// Save and close the input trace file
if (logFile != null) {
if (InputAgent.numWarnings == 0 && InputAgent.numErrors == 0) {
logFile.close();
logFile.delete();
logFile = new FileEntity( inputTraceFileName);
}
}
// Check for found errors
if( InputAgent.numErrors > 0 )
throw new InputErrorException("%d input errors and %d warnings found, check %s", InputAgent.numErrors, InputAgent.numWarnings, inputTraceFileName);
if (Simulation.getPrintInputReport())
InputAgent.printInputFileKeywords();
}
public static final void apply(Entity ent, KeywordIndex kw) {
Input<?> in = ent.getInput(kw.keyword);
if (in == null) {
InputAgent.logError("Keyword %s could not be found for Entity %s.", kw.keyword, ent.getName());
return;
}
InputAgent.apply(ent, in, kw);
FrameBox.valueUpdate();
}
public static final void apply(Entity ent, Input<?> in, KeywordIndex kw) {
// If the input value is blank, restore the default
if (kw.numArgs() == 0) {
in.reset();
}
else {
in.parse(kw);
in.setTokens(kw);
}
// Only mark the keyword edited if we have finished initial configuration
if (InputAgent.recordEdits()) {
in.setEdited(true);
ent.setFlag(Entity.FLAG_EDITED);
if (!ent.testFlag(Entity.FLAG_GENERATED))
sessionEdited = true;
}
ent.updateForInput(in);
}
public static void processKeyword(Entity entity, KeywordIndex key) {
if (entity.testFlag(Entity.FLAG_LOCKED))
throw new InputErrorException("Entity: %s is locked and cannot be modified", entity.getName());
Input<?> input = entity.getInput( key.keyword );
if (input != null) {
InputAgent.apply(entity, input, key);
FrameBox.valueUpdate();
return;
}
if (!(entity instanceof Group))
throw new InputErrorException("Not a valid keyword");
Group grp = (Group)entity;
grp.saveGroupKeyword(key);
// Store the keyword data for use in the edit table
for( int i = 0; i < grp.getList().size(); i++ ) {
Entity ent = grp.getList().get( i );
InputAgent.apply(ent, key);
}
}
public static void load(GUIFrame gui) {
LogBox.logLine("Loading...");
// Create a file chooser
final JFileChooser chooser = new JFileChooser(InputAgent.getConfigFile());
// Set the file extension filters
chooser.setAcceptAllFileFilterUsed(true);
FileNameExtensionFilter cfgFilter =
new FileNameExtensionFilter("JaamSim Configuration File (*.cfg)", "CFG");
chooser.addChoosableFileFilter(cfgFilter);
chooser.setFileFilter(cfgFilter);
// Show the file chooser and wait for selection
int returnVal = chooser.showOpenDialog(gui);
// Load the selected file
if (returnVal == JFileChooser.APPROVE_OPTION) {
File temp = chooser.getSelectedFile();
InputAgent.setLoadFile(gui, temp);
}
}
public static void save(GUIFrame gui) {
LogBox.logLine("Saving...");
if( InputAgent.getConfigFile() != null ) {
setSaveFile(gui, InputAgent.getConfigFile().getPath() );
}
else {
saveAs( gui );
}
}
public static void saveAs(GUIFrame gui) {
LogBox.logLine("Save As...");
// Create a file chooser
final JFileChooser chooser = new JFileChooser(InputAgent.getConfigFile());
// Set the file extension filters
chooser.setAcceptAllFileFilterUsed(true);
FileNameExtensionFilter cfgFilter =
new FileNameExtensionFilter("JaamSim Configuration File (*.cfg)", "CFG");
chooser.addChoosableFileFilter(cfgFilter);
chooser.setFileFilter(cfgFilter);
chooser.setSelectedFile(InputAgent.getConfigFile());
// Show the file chooser and wait for selection
int returnVal = chooser.showSaveDialog(gui);
// Load the selected file
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
String filePath = file.getPath();
// Add the file extension ".cfg" if needed
filePath = filePath.trim();
if (filePath.indexOf(".") == -1)
filePath = filePath.concat(".cfg");
// Confirm overwrite if file already exists
File temp = new File(filePath);
if (temp.exists()) {
int userOption = JOptionPane.showConfirmDialog( null,
file.getName() + " already exists.\n" +
"Do you wish to replace it?", "Confirm Save As",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE );
if (userOption == JOptionPane.NO_OPTION) {
return;
}
}
// Save the configuration file
InputAgent.setSaveFile(gui, filePath);
}
}
public static void configure(GUIFrame gui, File file) {
try {
gui.clear();
InputAgent.setConfigFile(file);
gui.updateForSimulationState(GUIFrame.SIM_STATE_UNCONFIGURED);
try {
InputAgent.loadConfigurationFile(file);
}
catch( InputErrorException iee ) {
if (!batchRun)
ExceptionBox.instance().setErrorBox(iee.getMessage());
else
LogBox.logLine( iee.getMessage() );
}
LogBox.logLine("Configuration File Loaded");
// show the present state in the user interface
gui.setTitle( Simulation.getModelName() + " - " + InputAgent.getRunName() );
gui.updateForSimulationState(GUIFrame.SIM_STATE_CONFIGURED);
gui.enableSave(InputAgent.getRecordEditsFound());
}
catch( Throwable t ) {
ExceptionBox.instance().setError(t);
}
}
/**
* Loads the configuration file.
* <p>
* @param gui - the Control Panel.
* @param file - the configuration file to be loaded.
*/
private static void setLoadFile(final GUIFrame gui, File file) {
final File chosenfile = file;
new Thread(new Runnable() {
@Override
public void run() {
InputAgent.setRecordEdits(false);
InputAgent.configure(gui, chosenfile);
InputAgent.setRecordEdits(true);
GUIFrame.displayWindows();
FrameBox.valueUpdate();
}
}).start();
}
/**
* Saves the configuration file.
* @param gui = Control Panel window for JaamSim
* @param fileName = absolute file path and file name for the file to be saved
*/
private static void setSaveFile(GUIFrame gui, String fileName) {
// Set root directory
File temp = new File(fileName);
// Save the configuration file
InputAgent.printNewConfigurationFileWithName( fileName );
sessionEdited = false;
InputAgent.setConfigFile(temp);
// Set the title bar to match the new run name
gui.setTitle( Simulation.getModelName() + " - " + InputAgent.getRunName() );
}
/*
* write input file keywords and values
*
* input file format:
* Define Group { <Group names> }
* Define <Object> { <Object names> }
*
* <Object name> <Keyword> { < values > }
*
*/
public static void printInputFileKeywords() {
// Create report file for the inputs
String inputReportFileName = InputAgent.getReportFileName(InputAgent.getRunName() + ".inp");
FileEntity inputReportFile = new FileEntity( inputReportFileName);
inputReportFile.flush();
// Loop through the entity classes printing Define statements
for (ObjectType type : ObjectType.getAll()) {
Class<? extends Entity> each = type.getJavaClass();
// Loop through the instances for this entity class
int count = 0;
for (Entity ent : Entity.getInstanceIterator(each)) {
boolean hasinput = false;
for (Input<?> in : ent.getEditableInputs()) {
// If the keyword has been used, then add a record to the report
if (in.getValueString().length() != 0) {
hasinput = true;
count++;
break;
}
}
if (hasinput) {
String entityName = ent.getName();
if ((count - 1) % 5 == 0) {
inputReportFile.putString("Define");
inputReportFile.putTab();
inputReportFile.putString(type.getName());
inputReportFile.putTab();
inputReportFile.putString("{ " + entityName);
inputReportFile.putTab();
}
else if ((count - 1) % 5 == 4) {
inputReportFile.putString(entityName + " }");
inputReportFile.newLine();
}
else {
inputReportFile.putString(entityName);
inputReportFile.putTab();
}
}
}
if (!Entity.getInstanceIterator(each).hasNext()) {
if (count % 5 != 0) {
inputReportFile.putString(" }");
inputReportFile.newLine();
}
inputReportFile.newLine();
}
}
for (ObjectType type : ObjectType.getAll()) {
Class<? extends Entity> each = type.getJavaClass();
// Get the list of instances for this entity class
// sort the list alphabetically
ArrayList<? extends Entity> cloneList = Entity.getInstancesOf(each);
// Print the entity class name to the report (in the form of a comment)
if (cloneList.size() > 0) {
inputReportFile.putString("\" " + each.getSimpleName() + " \"");
inputReportFile.newLine();
inputReportFile.newLine(); // blank line below the class name heading
}
Collections.sort(cloneList, new Comparator<Entity>() {
@Override
public int compare(Entity a, Entity b) {
return a.getName().compareTo(b.getName());
}
});
// Loop through the instances for this entity class
for (int j = 0; j < cloneList.size(); j++) {
// Make sure the clone is an instance of the class (and not an instance of a subclass)
if (cloneList.get(j).getClass() == each) {
Entity ent = cloneList.get(j);
String entityName = ent.getName();
boolean hasinput = false;
// Loop through the editable keywords for this instance
for (Input<?> in : ent.getEditableInputs()) {
// If the keyword has been used, then add a record to the report
if (in.getValueString().length() != 0) {
if (!in.getCategory().contains("Graphics")) {
hasinput = true;
inputReportFile.putTab();
inputReportFile.putString(entityName);
inputReportFile.putTab();
inputReportFile.putString(in.getKeyword());
inputReportFile.putTab();
if (in.getValueString().lastIndexOf("{") > 10) {
String[] item1Array;
item1Array = in.getValueString().trim().split(" }");
inputReportFile.putString("{ " + item1Array[0] + " }");
for (int l = 1; l < (item1Array.length); l++) {
inputReportFile.newLine();
inputReportFile.putTabs(5);
inputReportFile.putString(item1Array[l] + " } ");
}
inputReportFile.putString(" }");
}
else {
inputReportFile.putString("{ " + in.getValueString() + " }");
}
inputReportFile.newLine();
}
}
}
// Put a blank line after each instance
if (hasinput) {
inputReportFile.newLine();
}
}
}
}
// Close out the report
inputReportFile.flush();
inputReportFile.close();
}
public static void closeLogFile() {
if (logFile == null)
return;
logFile.flush();
logFile.close();
if (numErrors ==0 && numWarnings == 0) {
logFile.delete();
}
logFile = null;
}
private static final String errPrefix = "*** ERROR *** %s%n";
private static final String inpErrPrefix = "*** INPUT ERROR *** %s%n";
private static final String wrnPrefix = "***WARNING*** %s%n";
public static int numErrors() {
return numErrors;
}
public static int numWarnings() {
return numWarnings;
}
private static void echoInputRecord(ArrayList<String> tokens) {
if (logFile == null)
return;
boolean beginLine = true;
for (int i = 0; i < tokens.size(); i++) {
if (!beginLine)
logFile.write(" ");
String tok = tokens.get(i);
logFile.write(tok);
beginLine = false;
if (tok.startsWith("\"")) {
logFile.newLine();
beginLine = true;
}
}
// If there were any leftover string written out, make sure the line gets terminated
if (!beginLine)
logFile.newLine();
logFile.flush();
}
private static void logBadInput(ArrayList<String> tokens, String msg) {
InputAgent.echoInputRecord(tokens);
InputAgent.logError("%s", msg);
}
public static void logMessage(String fmt, Object... args) {
String msg = String.format(fmt, args);
LogBox.logLine(msg);
if (logFile == null)
return;
logFile.write(msg);
logFile.newLine();
logFile.flush();
}
public static void trace(int indent, Entity ent, String meth, String... text) {
// Create an indent string to space the lines
StringBuilder ind = new StringBuilder("");
for (int i = 0; i < indent; i++)
ind.append(" ");
String spacer = ind.toString();
// Print a TIME header every time time has advanced
double traceTime = ent.getCurrentTime();
if (lastTimeForTrace != traceTime) {
System.out.format(" \nTIME = %.5f\n", traceTime);
lastTimeForTrace = traceTime;
}
// Output the traces line(s)
System.out.format("%s%s %s\n", spacer, ent.getName(), meth);
for (String line : text) {
System.out.format("%s%s\n", spacer, line);
}
System.out.flush();
}
public static void logWarning(String fmt, Object... args) {
numWarnings++;
String msg = String.format(fmt, args);
InputAgent.logMessage(wrnPrefix, msg);
}
public static void logError(String fmt, Object... args) {
numErrors++;
String msg = String.format(fmt, args);
InputAgent.logMessage(errPrefix, msg);
}
public static void logInpError(String fmt, Object... args) {
numErrors++;
String msg = String.format(fmt, args);
InputAgent.logMessage(inpErrPrefix, msg);
}
/**
* Prepares the keyword and input value for processing.
*
* @param ent - the entity whose keyword and value has been entered.
* @param keyword - the keyword.
* @param value - the input value String for the keyword.
*/
public static void processEntity_Keyword_Value(Entity ent, String keyword, String value){
// Keyword
ArrayList<String> tokens = new ArrayList<>();
// Value
if (!value.equals(Input.getNoValue()))
Parser.tokenize(tokens, value, true);
// Parse the keyword inputs
KeywordIndex kw = new KeywordIndex(tokens, keyword, 0, tokens.size(), null);
InputAgent.processKeyword(ent, kw);
}
/**
* Prints the present state of the model to a new configuration file.
*
* @param fileName - the full path and file name for the new configuration file.
*/
public static void printNewConfigurationFileWithName( String fileName ) {
// 1) WRITE LINES FROM THE ORIGINAL CONFIGURATION FILE
// Copy the original configuration file up to the "RecordEdits" marker (if present)
// Temporary storage for the copied lines is needed in case the original file is to be overwritten
ArrayList<String> preAddedRecordLines = new ArrayList<>();
if( InputAgent.getConfigFile() != null ) {
try {
BufferedReader in = new BufferedReader( new FileReader(InputAgent.getConfigFile()) );
String line;
while ( ( line = in.readLine() ) != null ) {
preAddedRecordLines.add( line );
if ( line.startsWith( recordEditsMarker ) ) {
break;
}
}
in.close();
}
catch ( Exception e ) {
throw new ErrorException( e );
}
}
// Create the new configuration file and copy the saved lines
FileEntity file = new FileEntity( fileName);
for( int i=0; i < preAddedRecordLines.size(); i++ ) {
file.format("%s%n", preAddedRecordLines.get( i ));
}
// If not already present, insert the "RecordEdits" marker at the end of the original configuration file
if( ! InputAgent.getRecordEditsFound() ) {
file.format("%n%s%n", recordEditsMarker);
InputAgent.setRecordEditsFound(true);
}
// 2) WRITE THE DEFINITION STATEMENTS FOR NEW OBJECTS
// Determine all the new classes that were created
ArrayList<Class<? extends Entity>> newClasses = new ArrayList<>();
for (Entity ent : Entity.getAll()) {
if (!ent.testFlag(Entity.FLAG_ADDED) || ent.testFlag(Entity.FLAG_GENERATED))
continue;
if (!newClasses.contains(ent.getClass()))
newClasses.add(ent.getClass());
}
// Add a blank line before the first object definition
if( !newClasses.isEmpty() )
file.format("%n");
// Identify the object types for which new instances were defined
for( Class<? extends Entity> newClass : newClasses ) {
for (ObjectType o : ObjectType.getAll()) {
if (o.getJavaClass() == newClass) {
// Print the first part of the "Define" statement for this object type
file.format("Define %s {", o.getName());
break;
}
}
// Print the new instances that were defined
for (Entity ent : Entity.getAll()) {
if (!ent.testFlag(Entity.FLAG_ADDED) || ent.testFlag(Entity.FLAG_GENERATED))
continue;
if (ent.getClass() == newClass)
file.format(" %s ", ent.getName());
}
// Close the define statement
file.format("}%n");
}
// 3) WRITE THE ATTRIBUTE DEFINITIONS
boolean blankLinePrinted = false;
for (Entity ent : Entity.getAll()) {
if (!ent.testFlag(Entity.FLAG_EDITED))
continue;
if (ent.testFlag(Entity.FLAG_GENERATED))
continue;
final Input<?> in = ent.getInput("AttributeDefinitionList");
if (in == null || !in.isEdited())
continue;
if (!blankLinePrinted) {
file.format("%n");
blankLinePrinted = true;
}
writeInputOnFile_ForEntity(file, ent, in);
}
// 4) WRITE THE INPUTS FOR KEYWORDS THAT WERE EDITED
// Identify the entities whose inputs were edited
for (Entity ent : Entity.getAll()) {
if (!ent.testFlag(Entity.FLAG_EDITED))
continue;
if (ent.testFlag(Entity.FLAG_GENERATED))
continue;
file.format("%n");
ArrayList<Input<?>> deferredInputs = new ArrayList<>();
// Print the key inputs first
for (Input<?> in : ent.getEditableInputs()) {
if (!in.isEdited())
continue;
if ("AttributeDefinitionList".equals(in.getKeyword()))
continue;
// defer all inputs outside the Key Inputs category
if (!"Key Inputs".equals(in.getCategory())) {
deferredInputs.add(in);
continue;
}
writeInputOnFile_ForEntity(file, ent, in);
}
for (Input<?> in : deferredInputs) {
writeInputOnFile_ForEntity(file, ent, in);
}
}
// Close the new configuration file
file.flush();
file.close();
}
static void writeInputOnFile_ForEntity(FileEntity file, Entity ent, Input<?> in) {
file.format("%s %s { %s }%n",
ent.getName(), in.getKeyword(), in.getValueString());
}
/**
* Returns the relative file path for the specified URI.
* <p>
* The path can start from either the folder containing the present
* configuration file or from the resources folder.
* <p>
* @param uri - the URI to be relativized.
* @return the relative file path.
*/
static public String getRelativeFilePath(URI uri) {
// Relativize the file path against the resources folder
String resString = resRoot.toString();
String inputString = uri.toString();
if (inputString.startsWith(resString)) {
return String.format("'<res>/%s'", inputString.substring(resString.length()));
}
// Relativize the file path against the configuration file
try {
URI configDirURI = InputAgent.getConfigFile().getParentFile().toURI();
return String.format("'%s'", configDirURI.relativize(uri).getPath());
}
catch (Exception ex) {
return String.format("'%s'", uri.getPath());
}
}
/**
* Loads the default configuration file.
*/
public static void loadDefault() {
// Read the default configuration file
InputAgent.readResource("inputs/default.cfg");
// A RecordEdits marker in the default configuration must be ignored
InputAgent.setRecordEditsFound(false);
// Set the model state to unedited
sessionEdited = false;
}
public static KeywordIndex formatPointsInputs(String keyword, ArrayList<Vec3d> points, Vec3d offset) {
ArrayList<String> tokens = new ArrayList<>(points.size() * 6);
for (Vec3d v : points) {
tokens.add("{");
tokens.add(String.format((Locale)null, "%.3f", v.x + offset.x));
tokens.add(String.format((Locale)null, "%.3f", v.y + offset.y));
tokens.add(String.format((Locale)null, "%.3f", v.z + offset.z));
tokens.add("m");
tokens.add("}");
}
// Parse the keyword inputs
return new KeywordIndex(tokens, keyword, 0, tokens.size(), null);
}
public static KeywordIndex formatPointInputs(String keyword, Vec3d point, String unit) {
ArrayList<String> tokens = new ArrayList<>(4);
tokens.add(String.format((Locale)null, "%.6f", point.x));
tokens.add(String.format((Locale)null, "%.6f", point.y));
tokens.add(String.format((Locale)null, "%.6f", point.z));
if (unit != null)
tokens.add(unit);
// Parse the keyword inputs
return new KeywordIndex(tokens, keyword, 0, tokens.size(), null);
}
/**
* Split an input (list of strings) down to a single level of nested braces, this may then be called again for
* further nesting.
* @param input
* @return
*/
public static ArrayList<ArrayList<String>> splitForNestedBraces(List<String> input) {
ArrayList<ArrayList<String>> inputs = new ArrayList<>();
int braceDepth = 0;
ArrayList<String> currentLine = null;
for (int i = 0; i < input.size(); i++) {
if (currentLine == null)
currentLine = new ArrayList<>();
currentLine.add(input.get(i));
if (input.get(i).equals("{")) {
braceDepth++;
continue;
}
if (input.get(i).equals("}")) {
braceDepth
if (braceDepth == 0) {
inputs.add(currentLine);
currentLine = null;
continue;
}
}
}
return inputs;
}
/**
* Converts a file path String to a URI.
* <p>
* The specified file path can be either relative or absolute. In the case
* of a relative file path, a 'context' folder must be specified. A context
* of null indicates an absolute file path.
* <p>
* To avoid bad input accessing an inappropriate file, a 'jail' folder can
* be specified. The URI to be returned must include the jail folder for it
* to be valid.
* <p>
* @param context - full file path for the folder that is the reference for relative file paths.
* @param filePath - string to be resolved to a URI.
* @param jailPrefix - file path to a base folder from which a relative cannot escape.
* @return the URI corresponding to the context and filePath.
*/
public static URI getFileURI(URI context, String filePath, String jailPrefix) throws URISyntaxException {
// Replace all backslashes with slashes
String path = filePath.replaceAll("\\\\", "/");
int colon = path.indexOf(':');
int openBrace = path.indexOf('<');
int closeBrace = path.indexOf('>');
int firstSlash = path.indexOf('/');
// Add a leading slash if needed to convert from Windows format (e.g. from "C:" to "/C:")
if (colon == 1)
path = String.format("/%s", path);
// 1) File path starts with a tagged folder, using the syntax "<tagName>/"
URI ret = null;
if (openBrace == 0 && closeBrace != -1 && firstSlash == closeBrace + 1) {
String specPath = path.substring(openBrace + 1, closeBrace);
// Resources folder in the Jar file
if (specPath.equals("res")) {
ret = new URI(resRoot.getScheme(), resRoot.getSchemeSpecificPart() + path.substring(closeBrace+2), null).normalize();
}
}
// 2) Normal file path
else {
URI pathURI = new URI(null, path, null).normalize();
if (context != null) {
if (context.isOpaque()) {
// Things are going to get messy in here
URI schemeless = new URI(null, context.getSchemeSpecificPart(), null);
URI resolved = schemeless.resolve(pathURI).normalize();
// Note: we are using the one argument constructor here because the 'resolved' URI is already encoded
// and we do not want to double-encode (and schemes should never need encoding, I hope)
ret = new URI(context.getScheme() + ":" + resolved.toString());
} else {
ret = context.resolve(pathURI).normalize();
}
} else {
// We have no context, so append a 'file' scheme if necessary
if (pathURI.getScheme() == null) {
ret = new URI("file", pathURI.getPath(), null);
} else {
ret = pathURI;
}
}
}
// Check that the file path includes the jail folder
if (jailPrefix != null && ret.toString().indexOf(jailPrefix) != 0) {
LogBox.format("Failed jail test: %s in jail: %s context: %s\n", ret.toString(), jailPrefix, context.toString());
LogBox.getInstance().setVisible(true);
return null; // This resolved URI is not in our jail
}
return ret;
}
/**
* Determines whether or not a file exists.
* <p>
* @param filePath - URI for the file to be tested.
* @return true if the file exists, false if it does not.
*/
public static boolean fileExists(URI filePath) {
try {
InputStream in = filePath.toURL().openStream();
in.close();
return true;
}
catch (MalformedURLException ex) {
return false;
}
catch (IOException ex) {
return false;
}
}
}
|
package com.jcabi.github.mock;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import com.jcabi.github.Coordinates;
import com.jcabi.github.Repo;
import com.jcabi.github.Tree;
import java.io.IOException;
import javax.json.JsonObject;
import javax.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
/**
* Mock of Github Tree.
* @author Alexander Lukashevich (sanai56967@gmail.com)
* @version $Id$
*/
@Immutable
@Loggable(Loggable.DEBUG)
@EqualsAndHashCode(of = { "storage", "self", "coords", "sha" })
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
final class MkTree implements Tree {
/**
* Storage.
*/
private final transient MkStorage storage;
/**
* Login of the user logged in.
*/
private final transient String self;
/**
* Repo name.
*/
private final transient Coordinates coords;
/**
* The Tree's sha.
*/
private final transient String sha;
/**
* Public constructor.
* @param strg The storage.
* @param login The login name
* @param crds Credential
* @param identifier Tree's sha.
* @checkstyle ParameterNumber (5 lines)
*/
MkTree(
@NotNull(message = "strg can't be NULL") final MkStorage strg,
@NotNull(message = "login can't be NULL") final String login,
@NotNull(message = "crds can't be NULL") final Coordinates crds,
@NotNull(message = "identifier can't be NULL") final String identifier
) {
this.storage = strg;
this.self = login;
this.coords = crds;
this.sha = new StringBuilder().append('"').append(identifier)
.append('"').toString();
}
@Override
@NotNull(message = "JSON is never NULL")
public JsonObject json() throws IOException {
return new JsonNode(
this.storage.xml().nodes(this.xpath()).get(0)
).json();
}
@Override
@NotNull(message = "repository is never NULL")
public Repo repo() {
return new MkRepo(this.storage, this.self, this.coords);
}
@Override
@NotNull(message = "sha is never NULL")
public String sha() {
return this.sha;
}
/**
* XPath of this element in XML tree.
*
* @return XPath
*/
@NotNull(message = "Xpath is never NULL")
private String xpath() {
return String.format(
"/github/repos/repo[@coords = '%s']/git/trees/tree[sha = '%s']",
this.coords, this.sha
);
}
}
|
package com.senac.petshop.infra;
import java.util.List;
public interface Crud<T> {
void salvar(T bean);
void excluir(T bean);
T consultar(T bean);
void alterar(T bean);
List<T> pesquisar(String pesquisa);
}
|
package com.tale.webhook;
import com.blade.ioc.annotation.Bean;
import com.blade.ioc.annotation.Inject;
import com.blade.kit.StringKit;
import com.blade.kit.UUID;
import com.blade.mvc.hook.Signature;
import com.blade.mvc.hook.WebHook;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import com.tale.init.TaleConst;
import com.tale.model.dto.Types;
import com.tale.model.entity.Users;
import com.tale.service.UsersService;
import com.tale.utils.MapCache;
import com.tale.utils.TaleUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Bean
public class BaseWebHook implements WebHook {
private static final Logger log = LoggerFactory.getLogger(BaseWebHook.class);
@Inject
private UsersService usersService;
private MapCache cache = MapCache.single();
@Override
public boolean before(Signature signature) {
Request request = signature.request();
Response response = signature.response();
String uri = request.uri();
String ip = request.address();
if(TaleConst.BLOCK_IPS.contains(ip)){
response.text("You have been banned, brother");
return false;
}
log.info("UserAgent: {}", request.userAgent());
log.info(": {}, : {}", uri, ip);
if (uri.startsWith("/static")) {
return true;
}
if (!TaleConst.INSTALL && !uri.startsWith("/install")) {
response.redirect("/install");
return false;
}
if (TaleConst.INSTALL) {
Users user = TaleUtils.getLoginUser();
if (null == user) {
Integer uid = TaleUtils.getCookieUid(request);
if (null != uid) {
user = usersService.byId(Integer.valueOf(uid));
request.session().attribute(TaleConst.LOGIN_SESSION_KEY, user);
}
}
if(uri.startsWith("/admin") && !uri.startsWith("/admin/login")){
if(null == user){
response.redirect("/admin/login");
return false;
}
request.attribute("plugin_menus", TaleConst.plugin_menus);
}
}
String method = request.method();
if(method.equals("GET")){
String csrf_token = UUID.UU64();
int timeout = TaleConst.BCONF.getInt("app.csrf-token-timeout", 20) * 60;
cache.hset(Types.CSRF_TOKEN, csrf_token, uri, timeout);
request.attribute("_csrf_token", csrf_token);
}
return true;
}
@Override
public boolean after(Signature signature) {
Request request = signature.request();
String _csrf_token = request.attribute("del_csrf_token");
if(StringKit.isNotBlank(_csrf_token)){
// token
cache.hdel(Types.CSRF_TOKEN, _csrf_token);
}
return true;
}
}
|
package com.wizzardo.epoll;
import com.wizzardo.tools.io.FileTools;
import com.wizzardo.tools.misc.Unchecked;
import com.wizzardo.tools.reflection.FieldReflection;
import com.wizzardo.tools.reflection.FieldReflectionFactory;
import com.wizzardo.tools.reflection.UnsafeTools;
import java.io.*;
import java.net.InetAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.regex.Pattern;
import static com.wizzardo.epoll.Utils.readInt;
import static com.wizzardo.epoll.Utils.readShort;
public class EpollCore<T extends Connection> extends Thread implements ByteBufferProvider {
// gcc -m32 -shared -fpic -o ../../../../../libepoll-core_x32.so -I /home/moxa/soft/jdk1.6.0_45/include/ -I /home/moxa/soft/jdk1.6.0_45/include/linux/ EpollCore.c
// gcc -shared -fpic -o ../../../../../libepoll-core_x64.so -I /home/moxa/soft/jdk1.6.0_45/include/ -I /home/moxa/soft/jdk1.6.0_45/include/linux/ EpollCore.c
// javah -jni com.wizzardo.epoll.EpollCore
public static final boolean SUPPORTED;
ByteBuffer events;
volatile long scope;
protected volatile boolean running = true;
protected volatile boolean started = false;
protected final ByteBufferWrapper buffer = new ByteBufferWrapper(ByteBuffer.allocateDirect(16 * 1024));
private static final Pattern IP_PATTERN = Pattern.compile("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
private int ioThreadsCount = Runtime.getRuntime().availableProcessors();
protected SslConfig sslConfig;
long ttl = 30000;
private IOThread[] ioThreads;
static {
boolean supported = false;
try {
loadLib("libepoll-core");
supported = true;
} catch (Throwable e) {
e.printStackTrace();
}
SUPPORTED = supported;
}
public EpollCore() {
this(100);
}
public EpollCore(int maxEvents) {
initEpoll(maxEvents);
}
protected void initEpoll(int maxEvents) {
events = ByteBuffer.allocateDirect((maxEvents + 500) * 11);
scope = init(maxEvents, events);
}
public void setIoThreadsCount(int ioThreadsCount) {
this.ioThreadsCount = ioThreadsCount;
}
public boolean isStarted() {
return started;
}
// protected AtomicInteger eventCounter = new AtomicInteger(0);
@Override
public void run() {
started = true;
System.out.println("io threads count: " + ioThreadsCount);
ioThreads = new IOThread[ioThreadsCount];
for (int i = 0; i < ioThreadsCount; i++) {
ioThreads[i] = createIOThread(i, ioThreadsCount);
ioThreads[i].setTTL(ttl);
ioThreads[i].loadCertificates(sslConfig);
ioThreads[i].start();
}
byte[] events = new byte[this.events.capacity()];
byte[] newConnections = new byte[this.events.capacity()];
while (running) {
try {
this.events.position(0);
Long now = System.nanoTime() * 1000;
int r = waitForEvents(500);
// System.out.println("events length: "+r);
this.events.limit(r);
this.events.get(events, 0, r);
int i = 0;
// eventCounter.addAndGet(r / 5);
while (i < r) {
int event = events[i];
i += 5;
switch (event) {
case 0: {
acceptConnections(newConnections, now);
break;
}
default:
throw new IllegalStateException("this thread only for accepting new connections, event: " + event);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
for (int i = 0; i < ioThreads.length; i++) {
ioThreads[i].close();
}
}
public void setTTL(long milliseconds) {
ttl = milliseconds;
}
public long getTTL() {
return ttl;
}
public void close() {
synchronized (this) {
if (running) {
running = false;
stopListening(scope);
try {
join();
} catch (InterruptedException ignored) {
}
}
}
}
private Long acceptConnections(byte[] buffer, Long eventTime) throws IOException {
events.position(0);
int k = acceptConnections(scope);
events.limit(k);
events.get(buffer, 0, k);
// eventCounter.addAndGet(k / 10);
for (int j = 0; j < k; j += 10) {
int fd = readInt(buffer, j);
T connection = createConnection(fd, readInt(buffer, j + 4), readShort(buffer, j + 8));
putConnection(connection, eventTime++);
}
return eventTime;
}
private void putConnection(T connection, Long eventTime) throws IOException {
ioThreads[connection.fd % ioThreadsCount].putConnection(connection, eventTime);
}
public T connect(String host, int port) throws IOException {
boolean resolve = !IP_PATTERN.matcher(host).matches();
if (resolve) {
InetAddress address = InetAddress.getByName(host);
host = address.getHostAddress();
}
T connection = createConnection(connect(scope, host, port), 0, port);
connection.setIpString(host);
synchronized (this) {
putConnection(connection, System.nanoTime() * 1000);
}
return connection;
}
protected boolean bind(String host, int port) {
listen(scope, host, String.valueOf(port));
return true;
}
protected int waitForEvents(int timeout) {
return waitForEvents(scope, timeout);
}
protected int waitForEvents() {
return waitForEvents(scope, -1);
}
void mod(Connection connection, int mode) {
if (connection.isAlive() && connection.getMode() != mode) {
synchronized (connection) {
if (connection.isAlive() && connection.getMode() != mode)
if (!mod(scope, connection.fd, mode))
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
else
connection.setMode(mode);
}
}
}
@Override
public ByteBufferWrapper getBuffer() {
return buffer;
}
protected T createConnection(int fd, int ip, int port) {
return (T) new Connection(fd, ip, port);
}
protected IOThread<T> createIOThread(int number, int divider) {
return new IOThread<T>(number, divider);
}
long createSSL(int fd) {
return createSSL(scope, fd);
}
public void loadCertificates(String certFile, String keyFile) {
loadCertificates(new SslConfig(certFile, keyFile));
}
public void loadCertificates(SslConfig sslConfig) {
this.sslConfig = sslConfig;
}
protected boolean isSecured() {
return sslConfig != null;
}
native void close(int fd);
native boolean attach(long scope, int fd);
native void initSSL(long scope);
native long createSSL(long scope, int fd);
native void closeSSL(long ssl);
native boolean acceptSSL(long ssl);
native void releaseSslContext(long scope);
native void loadCertificates(long scope, String certFile, String keyFile);
private native long init(int maxEvents, ByteBuffer events);
private native void listen(long scope, String host, String port);
private native boolean stopListening(long scope);
private native int waitForEvents(long scope, int timeout);
private native int acceptConnections(long scope);
private native int connect(long scope, String host, int port);
private native boolean mod(long scope, int fd, int mode);
native int read(int fd, long bbPointer, int off, int len) throws IOException;
native int write(int fd, long bbPointer, int off, int len) throws IOException;
native int readSSL(int fd, long bbPointer, int off, int lenm, long ssl) throws IOException;
native int writeSSL(int fd, long bbPointer, int off, int len, long ssl) throws IOException;
private native static long getAddress(ByteBuffer buffer);
private static final FieldReflection byteBufferAddressReflection = getByteBufferAddressReflection();
private static FieldReflection getByteBufferAddressReflection() {
try {
return new FieldReflectionFactory().create(Buffer.class, "address", true);
} catch (NoSuchFieldException e) {
throw Unchecked.rethrow(e);
}
}
static long address(ByteBuffer buffer) {
return SUPPORTED ? getAddress(buffer) : byteBufferAddressReflection.getLong(buffer);
}
public static void arraycopy(ByteBuffer src, int srcPos, ByteBuffer dest, int destPos, int length) {
if (length < 0)
throw new IndexOutOfBoundsException("length must be >= 0. (length = " + length + ")");
if (srcPos < 0)
throw new IndexOutOfBoundsException("srcPos must be >= 0. (srcPos = " + srcPos + ")");
if (destPos < 0)
throw new IndexOutOfBoundsException("destPos must be >= 0. (destPos = " + destPos + ")");
if (srcPos + length > src.capacity())
throw new IndexOutOfBoundsException("srcPos + length must be <= src.capacity(). (srcPos = " + srcPos + ", length = " + length + ", capacity = " + src.capacity() + ")");
if (destPos + length > dest.capacity())
throw new IndexOutOfBoundsException("destPos + length must be <= dest.capacity(). (destPos = " + destPos + ", length = " + length + ", capacity = " + dest.capacity() + ")");
if (SUPPORTED) {
copy(src, srcPos, dest, destPos, length);
} else {
UnsafeTools.getUnsafe().copyMemory(address(src) + srcPos, address(dest) + destPos, length);
}
}
private native static void copy(ByteBuffer src, int srcPos, ByteBuffer dest, int destPos, int length);
private static void loadLib(String name) throws IOException {
String arch = System.getProperty("os.arch");
name = name + (arch.contains("64") ? "_x64" : "_x32") + ".so";
// have to use a stream
InputStream in = EpollCore.class.getResourceAsStream("/" + name);
File fileOut;
if (in == null) {
File file = new File(name);
if (file.exists())
in = new FileInputStream(file);
else
in = new FileInputStream(new File("build/" + name));
}
fileOut = File.createTempFile(name, "lib");
FileTools.bytes(fileOut, in);
System.load(fileOut.toString());
fileOut.deleteOnExit();
}
}
|
package com.wizzardo.servlet;
import com.wizzardo.http.ChainUrlMapping;
import com.wizzardo.http.Path;
import com.wizzardo.http.UrlMapping;
import com.wizzardo.tools.misc.UncheckedThrow;
import javax.servlet.*;
import javax.servlet.descriptor.JspConfigDescriptor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class Context implements ServletContext {
private static final int MAJOR_SERVLET_VERSION = 3;
private static final int MINOR_SERVLET_VERSION = 0;
protected ServletServer<? extends ServletHttpConnection> server;
protected String contextPath;
protected File contextDir;
protected UrlMapping<ServletHolder> servletsMapping = new UrlMapping<>();
protected ChainUrlMapping<Filter> filtersMapping = new ChainUrlMapping<>();
protected List<Servlet> servletsToDestroy = new ArrayList<>();
protected List<Filter> filtersToDestroy = new ArrayList<>();
protected List<ServletContextListener> contextListeners = new ArrayList<>();
protected Map<String, Object> attributes = new ConcurrentHashMap<>();
protected Map<String, String> initParams = new ConcurrentHashMap<>();
protected Map<String, ServletHolder> servlets = new ConcurrentHashMap<>();
protected boolean initialized = false;
public Context(ServletServer<? extends ServletHttpConnection> server, String contextPath) {
this.server = server;
this.contextPath = contextPath;
}
void setContextDir(File contextDir) {
this.contextDir = contextDir;
}
public String getContextPath() {
return contextPath;
}
public String getHost() {
return server.getHost();
}
public int getPort() {
return server.getPort();
}
public boolean isSecure() {
return false;
}
public ChainUrlMapping<Filter> getFiltersMapping() {
return filtersMapping;
}
public void addServletHolder(String path, ServletHolder servletHolder) {
servletsMapping.append(path, servletHolder);
servlets.put(servletHolder.name, servletHolder);
}
public ServletHolder getServletHolder(HttpRequest request, Path path) {
return servletsMapping.get(request, path);
}
public String createAbsoluteUrl(String path) {
StringBuilder sb = new StringBuilder();
if (isSecure())
sb.append("https:
else
sb.append("http:
sb.append(server.getHost());
if ((!isSecure() && server.getPort() != 80) || (isSecure() && server.getPort() != 443))
sb.append(":").append(server.getPort());
sb.append(path);
return sb.toString();
}
protected void onInit() {
ServletContextEvent event = new ServletContextEvent(this);
for (ServletContextListener listener : contextListeners)
listener.contextInitialized(event);
initialized = true;
}
protected void addServletToDestroy(Servlet servlet) {
servletsToDestroy.add(servlet);
}
protected void addFilterToDestroy(Filter filter) {
filtersToDestroy.add(filter);
}
protected void onDestroy() {
for (Servlet servlet : servletsToDestroy)
servlet.destroy();
for (Filter filter : filtersToDestroy)
filter.destroy();
ServletContextEvent event = new ServletContextEvent(this);
for (int i = contextListeners.size() - 1; i >= 0; i
contextListeners.get(i).contextDestroyed(event);
}
@Override
public ServletContext getContext(String uripath) {
return server.getContext(uripath);
}
@Override
public int getMajorVersion() {
return MAJOR_SERVLET_VERSION;
}
@Override
public int getMinorVersion() {
return MINOR_SERVLET_VERSION;
}
@Override
public int getEffectiveMajorVersion() {
return getMajorVersion();
}
@Override
public int getEffectiveMinorVersion() {
return getMinorVersion();
}
@Override
public String getMimeType(String file) {
return server.getMimeProvider().getMimeType(file);
}
@Override
public Set<String> getResourcePaths(String path) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public URL getResource(String path) throws MalformedURLException {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public InputStream getResourceAsStream(String path) {
try {
return new FileInputStream(new File(contextDir, path));
} catch (FileNotFoundException e) {
throw UncheckedThrow.rethrow(e);
}
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
return new ServletRequestDispatcher(servletsMapping.get(path), path);
}
public RequestDispatcher getRequestDispatcher(Path path) {
return new ServletRequestDispatcher(servletsMapping.get(null, path), path.toString());
}
@Override
public RequestDispatcher getNamedDispatcher(String name) {
return new ServletRequestDispatcher(servlets.get(name), null);
}
@Override
public Servlet getServlet(String name) throws ServletException {
return null;
}
@Override
public Enumeration<Servlet> getServlets() {
return Collections.emptyEnumeration();
}
@Override
public Enumeration<String> getServletNames() {
return Collections.emptyEnumeration();
}
@Override
public void log(String msg) {
System.out.println(msg);
}
@Override
public void log(Exception exception, String msg) {
System.out.println(msg);
exception.printStackTrace();
}
@Override
public void log(String message, Throwable throwable) {
System.out.println(message);
throwable.printStackTrace();
}
@Override
public String getRealPath(String path) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public String getServerInfo() {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public String getInitParameter(String name) {
return initParams.get(name);
}
@Override
public Enumeration<String> getInitParameterNames() {
return Collections.enumeration(initParams.keySet());
}
@Override
public boolean setInitParameter(String name, String value) {
if (initialized)
throw new IllegalStateException("this ServletContext has already been initialized");
return initParams.putIfAbsent(name, value) != null;
}
@Override
public Object getAttribute(String name) {
return attributes.get(name);
}
@Override
public Enumeration<String> getAttributeNames() {
return Collections.enumeration(attributes.keySet());
}
@Override
public void setAttribute(String name, Object object) {
if (object == null)
removeAttribute(name);
else
attributes.put(name, object);
}
@Override
public void removeAttribute(String name) {
attributes.remove(name);
}
@Override
public String getServletContextName() {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public ServletRegistration.Dynamic addServlet(String servletName, String className) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public <T extends Servlet> T createServlet(Class<T> clazz) throws ServletException {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public ServletRegistration getServletRegistration(String servletName) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public Map<String, ? extends ServletRegistration> getServletRegistrations() {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public FilterRegistration.Dynamic addFilter(String filterName, String className) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public <T extends Filter> T createFilter(Class<T> clazz) throws ServletException {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public FilterRegistration getFilterRegistration(String filterName) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public Map<String, ? extends FilterRegistration> getFilterRegistrations() {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public Set<SessionTrackingMode> getDefaultSessionTrackingModes() {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public void addListener(String className) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public <T extends EventListener> void addListener(T t) {
throw new UnsupportedOperationException("Not implemented yet.");
}
public void addContextListener(ServletContextListener listener) {
contextListeners.add(listener);
}
@Override
public void addListener(Class<? extends EventListener> listenerClass) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public <T extends EventListener> T createListener(Class<T> clazz) throws ServletException {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public JspConfigDescriptor getJspConfigDescriptor() {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public ClassLoader getClassLoader() {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public void declareRoles(String... roleNames) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public String getVirtualServerName() {
throw new UnsupportedOperationException("Not implemented yet.");
}
}
|
package de.tblsoft.solr.util;
import com.google.common.io.Files;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class IOUtils {
public static String getAbsoluteFile(String directory, String fileName) {
if(fileName.toLowerCase().startsWith("c:\\")) {
return fileName;
} else if(fileName.startsWith("/")) {
return fileName;
} else if(fileName.startsWith("./")) {
return fileName;
} else {
return directory + "/" + fileName;
}
}
public static String getDirectoryForFile(String file) {
File f = new File(file);
File currentPath = new File(f.getParent());
return currentPath.getName();
}
public static List<String> getFiles(String path) {
List<String> fileList = new ArrayList<String>();
File root = new File(path);
if(path.contains("*")) {
IOFileFilter fileFilter = new WildcardFileFilter(root.getName());
IOFileFilter dirFilter = new WildcardFileFilter("*");
Collection<File> files = FileUtils.listFiles(root.getParentFile(), fileFilter, dirFilter);
for(File file:files) {
fileList.add(file.getAbsolutePath());
}
return fileList;
}
if(root.isFile()) {
fileList.add(path);
return fileList;
}
if(root.isDirectory()) {
for (File file : Files.fileTreeTraverser().preOrderTraversal(root)) {
if (file.isFile()) {
fileList.add(file.getAbsolutePath());
}
}
return fileList;
}
throw new RuntimeException("The file or path does not exists: " + path);
}
public static InputStream getInputStream(String inputFileName) throws IOException {
InputStream fileStream = new FileInputStream(inputFileName);
if (inputFileName.endsWith(".gz")) {
return new GZIPInputStream(fileStream);
}
if(inputFileName.endsWith(".bz2")) {
return new BZip2CompressorInputStream(fileStream);
}
return fileStream;
}
public static OutputStream getOutputStream(String outputFileName) throws IOException {
if("stdout".equals(outputFileName)) {
return System.out;
} else if("stderr".equals(outputFileName)) {
return System.err;
} else if (outputFileName.endsWith(".gz")) {
OutputStream out = new FileOutputStream(outputFileName);
return new GZIPOutputStream(out);
} else {
return new FileOutputStream(outputFileName);
}
}
public static void appendToOutputStream(OutputStream out, String value ) throws IOException {
out.write(value.getBytes("UTF-8"));
}
}
|
package de.tudarmstadt.lt.pal;
import java.util.Arrays;
import java.util.List;
/**
* Represents a triple that can be used in a SPARQL query. May contain
* yet unmapped properties/resources.
*/
public class Triple implements Cloneable {
public static abstract class Element implements Cloneable {
public String name;
public List<String> trace;
public abstract boolean isConstant();
public String sparqlString() {
return name;
}
@Override
public String toString() {
return name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Element other = (Element) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
/**
* A type constraint for a variable (or resource), which distinguishes between "resource" and
* "literal", as well as a specific URI for the type, e.g. (BasicType.Literal, xsd:date) or
* (BasicType.Resource, bibo:Book)
*/
public static class TypeConstraint {
public enum BasicType {
Resource,
Literal
}
public BasicType basicType;
public MappedString typeURI;
public TypeConstraint(BasicType basicType, MappedString typeURI) {
this.basicType = basicType;
this.typeURI = typeURI;
}
@Override
public String toString() {
return typeURI + " (" + basicType + ")";
}
}
/**
* A triple element that is no variable,
* e.g. "dbpedia:Dan_Brown" and "dbpedia-owl:author" in
* [dbpedia:Dan_Brown dbpedia-owl:author ?book]
*/
public static class Constant extends Element {
public String type;
public Constant(String name) {
this.name = name;
}
@Override
public boolean isConstant() {
return true;
}
}
/**
* A variable, e.g. "?book" in [dbpedia:Dan_Brown dbpedia-owl:author ?book]
*/
public static class Variable extends Element {
public enum Type {
Agent,
Date,
Place,
Number,
Literal,
Unknown
}
public Type unmappedType;
public TypeConstraint mappedType;
public Variable(String name, Type unmappedType) {
this.name = name;
this.unmappedType = unmappedType;
// A variable name does not have a real derivation trace
this.trace = Arrays.asList(name);
}
@Override
public boolean isConstant() {
return false;
}
@Override
public String sparqlString() {
return "?" + name;
}
@Override
public String toString() {
return "?" + name + " (" + unmappedType + ", " + mappedType + ")";
}
}
public Element subject;
public Element predicate;
public Element object;
public Triple(Element s, Element p, Element o) {
subject = s;
predicate = p;
object = o;
}
/**
* Produces a human-readable representation of this triple. Not meant for SPARQL etc.
*/
public String toString() {
return "[Subject: " + subject + "] [Predicate: " + predicate + "] [Object: " + object + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((object == null) ? 0 : object.hashCode());
result = prime * result
+ ((predicate == null) ? 0 : predicate.hashCode());
result = prime * result + ((subject == null) ? 0 : subject.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Triple other = (Triple) obj;
if (object == null) {
if (other.object != null)
return false;
} else if (!object.equals(other.object))
return false;
if (predicate == null) {
if (other.predicate != null)
return false;
} else if (!predicate.equals(other.predicate))
return false;
if (subject == null) {
if (other.subject != null)
return false;
} else if (!subject.equals(other.subject))
return false;
return true;
}
}
|
package eu.amidst.scai2015;
import eu.amidst.core.datastream.*;
import eu.amidst.core.distribution.Multinomial;
import eu.amidst.core.inference.InferenceAlgorithmForBN;
import eu.amidst.core.inference.messagepassing.VMP;
import eu.amidst.core.io.DataStreamLoader;
import eu.amidst.core.learning.StreamingVariationalBayesVMP;
import eu.amidst.core.models.BayesianNetwork;
import eu.amidst.core.models.DAG;
import eu.amidst.core.utils.Utils;
import eu.amidst.core.variables.StaticVariables;
import eu.amidst.core.variables.Variable;
import weka.classifiers.evaluation.NominalPrediction;
import weka.classifiers.evaluation.Prediction;
import weka.classifiers.evaluation.ThresholdCurve;
import weka.core.Instances;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class wrapperBN {
int seed = 0;
Variable classVariable;
Variable classVariable_PM;
Attribute SEQUENCE_ID;
Attribute TIME_ID;
static int DEFAULTER_VALUE_INDEX = 1;
static int NON_DEFAULTER_VALUE_INDEX = 0;
int NbrClients= 50000;
HashMap<Integer, Multinomial> posteriorsGlobal = new HashMap<>();
static boolean usePRCArea = false; //By default ROCArea is used
static boolean dynamicNB = false;
static boolean onlyPrediction = false;
public static boolean isDynamicNB() {
return dynamicNB;
}
public static void setDynamicNB(boolean dynamicNB) {
wrapperBN.dynamicNB = dynamicNB;
}
public static boolean isOnlyPrediction() {
return onlyPrediction;
}
public static void setOnlyPrediction(boolean onlyPrediction) {
wrapperBN.onlyPrediction = onlyPrediction;
}
HashMap<Integer, Integer> defaultingClients = new HashMap<>();
public static boolean isUsePRCArea() {
return usePRCArea;
}
public static void setUsePRCArea(boolean usePRCArea) {
wrapperBN.usePRCArea = usePRCArea;
}
public Attribute getSEQUENCE_ID() {
return SEQUENCE_ID;
}
public void setSEQUENCE_ID(Attribute SEQUENCE_ID) {
this.SEQUENCE_ID = SEQUENCE_ID;
}
public Attribute getTIME_ID() {
return TIME_ID;
}
public void setTIME_ID(Attribute TIME_ID) {
this.TIME_ID = TIME_ID;
}
public Variable getClassVariable_PM() {
return classVariable_PM;
}
public void setClassVariable_PM(Variable classVariable_PM) {
this.classVariable_PM = classVariable_PM;
}
public int getSeed() {
return seed;
}
public void setSeed(int seed) {
this.seed = seed;
}
public Variable getClassVariable() {
return classVariable;
}
public void setClassVariable(Variable classVariable) {
this.classVariable = classVariable;
}
public BayesianNetwork wrapperBNOneMonthNB(DataOnMemory<DataInstance> data){
StaticVariables Vars = new StaticVariables(data.getAttributes());
//Split the whole data into training and testing
List<DataOnMemory<DataInstance>> splitData = this.splitTrainAndTest(data,66.0);
DataOnMemory<DataInstance> trainingData = splitData.get(0);
DataOnMemory<DataInstance> testData = splitData.get(1);
List<Variable> NSF = new ArrayList<>(Vars.getListOfVariables()); // NSF: non selected features
NSF.remove(classVariable); //remove C
NSF.remove(classVariable_PM); // remove C'
int nbrNSF = NSF.size();
List<Variable> SF = new ArrayList(); // SF:selected features
Boolean stop = false;
//Learn the initial BN with training data including only the class variable
BayesianNetwork bNet = train(trainingData, Vars, SF,false);
//System.out.println(bNet.toString());
//Evaluate the initial BN with testing data including only the class variable, i.e., initial score or initial auc
double score = testFS(testData, bNet);
int cont=0;
//iterate until there is no improvement in score
while (nbrNSF > 0 && stop == false ){
//System.out.print("Iteration: " + cont + ", Score: "+score +", Number of selected variables: "+ SF.size() + ", ");
//SF.stream().forEach(v -> System.out.print(v.getName() + ", "));
//System.out.println();
Map<Variable, Double> scores = new ConcurrentHashMap<>(); //scores for each considered feature
//Scores for adding
NSF.parallelStream().forEach(V -> {
List<Variable> SF_TMP = new ArrayList();
SF_TMP.addAll(SF);
SF_TMP.add(V);
//train
BayesianNetwork bNet_TMP = train(trainingData, Vars, SF_TMP, false);
//evaluate
scores.put(V, testFS(testData, bNet_TMP));
SF_TMP.remove(V);
});
//Scores for removing
SF.parallelStream().forEach(V ->{
List<Variable> SF_TMP = new ArrayList();
SF_TMP.addAll(SF);
SF_TMP.remove(V);
//train
BayesianNetwork bNet_TMP = train(trainingData, Vars, SF_TMP, false);
//evaluate
scores.put(V, testFS(testData, bNet_TMP));
SF_TMP.add(V);
});
//determine the Variable V with max score
double maxScore = (Collections.max(scores.values())); //returns max value in the Hashmap
if (maxScore - score > 0.001){
score = maxScore;
//Variable with best score
for (Map.Entry<Variable, Double> entry : scores.entrySet()) {
if (entry.getValue()== maxScore){
Variable SelectedV = entry.getKey();
SF.add(SelectedV);
NSF.remove(SelectedV);
break;
}
}
nbrNSF = nbrNSF - 1;
}
else{
stop = true;
}
cont++;
}
//Final training with the winning SF and the full initial data
bNet = train(data, Vars, SF, true);
//System.out.println(bNet.getDAG().toString());
return bNet;
}
List<DataOnMemory<DataInstance>> splitTrainAndTest(DataOnMemory<DataInstance> data, double trainPercentage) {
Random random = new Random(this.seed);
DataOnMemoryListContainer<DataInstance> train = new DataOnMemoryListContainer(data.getAttributes());
DataOnMemoryListContainer<DataInstance> test = new DataOnMemoryListContainer(data.getAttributes());
for (DataInstance dataInstance : data) {
if (dataInstance.getValue(classVariable) == DEFAULTER_VALUE_INDEX)
continue;
if (random.nextDouble()<trainPercentage/100.0)
train.add(dataInstance);
else
test.add(dataInstance);
}
for (DataInstance dataInstance : data) {
if (dataInstance.getValue(classVariable) != DEFAULTER_VALUE_INDEX)
continue;
if (random.nextDouble()<trainPercentage/100.0)
train.add(dataInstance);
else
test.add(dataInstance);
}
Collections.shuffle(train.getList(), random);
Collections.shuffle(test.getList(), random);
return Arrays.asList(train, test);
}
public BayesianNetwork train(DataOnMemory<DataInstance> data, StaticVariables allVars, List<Variable> SF, boolean includeClassVariablePM){
DAG dag = new DAG(allVars);
if(includeClassVariablePM)
dag.getParentSet(classVariable).addParent(classVariable_PM);
/* Add classVariable to all SF*/
dag.getParentSets().stream()
.filter(parent -> SF.contains(parent.getMainVar()))
.filter(w -> w.getMainVar().getVarID() != classVariable.getVarID())
.forEach(w -> w.addParent(classVariable));
StreamingVariationalBayesVMP vmp = new StreamingVariationalBayesVMP();
vmp.setDAG(dag);
vmp.setDataStream(data);
vmp.setWindowsSize(100);
vmp.runLearning();
return vmp.getLearntBayesianNetwork();
}
public BayesianNetwork train(DataOnMemory<DataInstance> data, StaticVariables allVars, List<Variable> SF){
DAG dag = new DAG(allVars);
if(data.getDataInstance(0).getValue(TIME_ID)!=0)
dag.getParentSet(classVariable).addParent(classVariable_PM);
/* Add classVariable to all SF*/
dag.getParentSets().stream()
.filter(parent -> SF.contains(parent.getMainVar()))
.filter(w -> w.getMainVar().getVarID() != classVariable.getVarID())
.forEach(w -> w.addParent(classVariable));
StreamingVariationalBayesVMP vmp = new StreamingVariationalBayesVMP();
vmp.setDAG(dag);
vmp.setDataStream(data);
vmp.setWindowsSize(100);
vmp.runLearning();
return vmp.getLearntBayesianNetwork();
}
public double testFS(DataOnMemory<DataInstance> data, BayesianNetwork bn){
InferenceAlgorithmForBN vmp = new VMP();
ArrayList<Prediction> predictions = new ArrayList<>();
int currentMonthIndex = (int)data.getDataInstance(0).getValue(TIME_ID);
for (DataInstance instance : data) {
int clientID = (int) instance.getValue(SEQUENCE_ID);
double classValue = instance.getValue(classVariable);
Prediction prediction;
Multinomial posterior;
vmp.setModel(bn);
instance.setValue(classVariable, Utils.missingValue());
vmp.setEvidence(instance);
vmp.runInference();
posterior = vmp.getPosterior(classVariable);
instance.setValue(classVariable, classValue);
prediction = new NominalPrediction(classValue, posterior.getProbabilities());
predictions.add(prediction);
}
ThresholdCurve thresholdCurve = new ThresholdCurve();
Instances tcurve = thresholdCurve.getCurve(predictions);
if(usePRCArea)
return ThresholdCurve.getPRCArea(tcurve);
else
return ThresholdCurve.getROCArea(tcurve);
}
public double test(DataOnMemory<DataInstance> data, BayesianNetwork bn, HashMap<Integer, Multinomial> posteriors, boolean updatePosteriors){
InferenceAlgorithmForBN vmp = new VMP();
ArrayList<Prediction> predictions = new ArrayList<>();
int currentMonthIndex = (int)data.getDataInstance(0).getValue(TIME_ID);
for (DataInstance instance : data) {
int clientID = (int) instance.getValue(SEQUENCE_ID);
double classValue = instance.getValue(classVariable);
Prediction prediction;
Multinomial posterior;
/*Propagates*/
bn.setConditionalDistribution(classVariable_PM, posteriors.get(clientID));
/*
Multinomial_MultinomialParents distClass = bn.getConditionalDistribution(classVariable);
Multinomial deterministic = new Multinomial(classVariable);
deterministic.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 1.0);
deterministic.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.0);
distClass.setMultinomial(DEFAULTER_VALUE_INDEX, deterministic);
*/
vmp.setModel(bn);
double classValue_PM = instance.getValue(classVariable_PM);
instance.setValue(classVariable, Utils.missingValue());
instance.setValue(classVariable_PM, Utils.missingValue());
vmp.setEvidence(instance);
vmp.runInference();
posterior = vmp.getPosterior(classVariable);
instance.setValue(classVariable, classValue);
instance.setValue(classVariable_PM, classValue_PM);
prediction = new NominalPrediction(classValue, posterior.getProbabilities());
predictions.add(prediction);
if (classValue == DEFAULTER_VALUE_INDEX) {
defaultingClients.putIfAbsent(clientID, currentMonthIndex);
}
if(updatePosteriors) {
Multinomial multi_PM = posterior.toEFUnivariateDistribution().deepCopy(classVariable_PM).toUnivariateDistribution();
if (classValue == DEFAULTER_VALUE_INDEX) {
multi_PM.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 1.0);
multi_PM.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0);
}
posteriors.put(clientID, multi_PM);
}
}
ThresholdCurve thresholdCurve = new ThresholdCurve();
Instances tcurve = thresholdCurve.getCurve(predictions);
if(usePRCArea)
return ThresholdCurve.getPRCArea(tcurve);
else
return ThresholdCurve.getROCArea(tcurve);
}
public double propagateAndTest(Queue<DataOnMemory<DataInstance>> data, BayesianNetwork bn){
HashMap<Integer, Multinomial> posteriors = new HashMap<>();
InferenceAlgorithmForBN vmp = new VMP();
ArrayList<Prediction> predictions = new ArrayList<>();
/*
for (int i = 0; i < NbrClients ; i++){
Multinomial uniform = new Multinomial(classVariable_PM);
uniform.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 0.5);
uniform.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.5);
posteriors.put(i, uniform);
}
*/
boolean firstMonth = true;
Iterator<DataOnMemory<DataInstance>> iterator = data.iterator();
while(iterator.hasNext()){
Prediction prediction = null;
Multinomial posterior = null;
DataOnMemory<DataInstance> batch = iterator.next();
int currentMonthIndex = (int)batch.getDataInstance(0).getValue(TIME_ID);
for (DataInstance instance : batch) {
int clientID = (int) instance.getValue(SEQUENCE_ID);
double classValue = instance.getValue(classVariable);
/*Propagates*/
double classValue_PM = -1;
if(!firstMonth){
bn.setConditionalDistribution(classVariable_PM, posteriors.get(clientID));
classValue_PM = instance.getValue(classVariable_PM);
instance.setValue(classVariable_PM, Utils.missingValue());
}
vmp.setModel(bn);
instance.setValue(classVariable, Utils.missingValue());
vmp.setEvidence(instance);
vmp.runInference();
posterior = vmp.getPosterior(classVariable);
instance.setValue(classVariable, classValue);
if(!firstMonth) {
instance.setValue(classVariable_PM, classValue_PM);
}
if(!iterator.hasNext()) { //Last month or present
prediction = new NominalPrediction(classValue, posterior.getProbabilities());
predictions.add(prediction);
}
Multinomial multi_PM = posterior.toEFUnivariateDistribution().deepCopy(classVariable_PM).toUnivariateDistribution();
posteriors.put(clientID, multi_PM);
}
firstMonth = false;
if(!iterator.hasNext()) {//Last month or present time
ThresholdCurve thresholdCurve = new ThresholdCurve();
Instances tcurve = thresholdCurve.getCurve(predictions);
if(usePRCArea)
return ThresholdCurve.getPRCArea(tcurve);
else
return ThresholdCurve.getROCArea(tcurve);
}
}
throw new UnsupportedOperationException("Something went wrong: The method should have stopped at some point in the loop.");
}
void learnCajamarModel(DataStream<DataInstance> data) {
StaticVariables Vars = new StaticVariables(data.getAttributes());
classVariable = Vars.getVariableById(Vars.getNumberOfVars()-1);
classVariable_PM = Vars.getVariableById(Vars.getNumberOfVars()-2);
TIME_ID = data.getAttributes().getAttributeByName("TIME_ID");
SEQUENCE_ID = data.getAttributes().getAttributeByName("SEQUENCE_ID");
int count = 0;
double averageAUC = 0;
/*
for (int i = 0; i < NbrClients ; i++){
Multinomial uniform = new Multinomial(classVariable_PM);
uniform.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 0.5);
uniform.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.5);
posteriorsGlobal.put(i, uniform);
}
*/
Iterable<DataOnMemory<DataInstance>> iteratable = data.iterableOverBatches(NbrClients);
Iterator<DataOnMemory<DataInstance>> iterator = iteratable.iterator();
Queue<DataOnMemory<DataInstance>> monthsMinus12to0 = new LinkedList<>();
iterator.next(); //First month is discarded
//Take 13 batches at a time - 1 for training and 12 for testing
for (int i = 0; i < 12; i++) {
monthsMinus12to0.add(iterator.next());
}
while(iterator.hasNext()){
DataOnMemory<DataInstance> currentMonth = iterator.next();
monthsMinus12to0.add(currentMonth);
int idMonthMinus12 = (int)monthsMinus12to0.peek().getDataInstance(0).getValue(TIME_ID);
BayesianNetwork bn = null;
if(isOnlyPrediction()){
DataOnMemory<DataInstance> batch = monthsMinus12to0.poll();
StaticVariables vars = new StaticVariables(batch.getAttributes());
bn = train(batch, vars, vars.getListOfVariables(),this.isDynamicNB());
double auc = propagateAndTest(monthsMinus12to0, bn);
System.out.println( idMonthMinus12 + "\t" + auc);
averageAUC += auc;
}
else {
bn = wrapperBNOneMonthNB(monthsMinus12to0.poll());
double auc = propagateAndTest(monthsMinus12to0, bn);
System.out.print( idMonthMinus12 + "\t" + auc);
bn.getDAG().getParentSets().stream().filter(p -> p.getNumberOfParents()>0).forEach(p-> System.out.print("\t" + p.getMainVar().getName()));
System.out.println();
averageAUC += auc;
}
count += NbrClients;
}
System.out.println("Average Accuracy: " + averageAUC / (count / NbrClients));
}
public static void main(String[] args) throws IOException {
//DataStream<DataInstance> data = DataStreamLoader.loadFromFile("datasets/BankArtificialDataSCAI2015_DEFAULTING_PM.arff");
DataStream<DataInstance> data = DataStreamLoader.loadFromFile(args[0]);
for (int i = 1; i < args.length ; i++) {
if(args[i].equalsIgnoreCase("PRCArea"))
setUsePRCArea(true);
if(args[i].equalsIgnoreCase("onlyPrediction"))
setOnlyPrediction(true);
if(args[i].equalsIgnoreCase("dynamic"))
setDynamicNB(true);
}
wrapperBN wbnet = new wrapperBN();
wbnet.learnCajamarModel(data);
}
}
|
package hex.singlenoderf;
import water.*;
import water.fvec.Frame;
import water.fvec.Vec;
import water.util.Log;
import water.util.Log.Tag.Sys;
import java.text.DecimalFormat;
import java.util.Arrays;
/**A DataAdapter maintains an encoding of the original data. Every raw value (of type float)
* is represented by a short value. When the number of unique raw value is larger that binLimit,
* the DataAdapter will perform binning on the data and use the same short encoded value to
* represent several consecutive raw values.
*
* Missing values, NaNs and Infinity are treated as BAD data. */
final class DataAdapter {
/** Place holder for missing data, NaN, Inf in short encoding.*/
static final short BAD = Short.MIN_VALUE;
/** Number of classes. */
private final int _numClasses;
/** Columns. */
final Col[] _c;
/** Seed for sampling */
private final long _seed;
/** Number of rows */
public final int _numRows;
/** Class weights */
public final double[] _classWt;
/** Use regression */
public final boolean _regression;
public Key _jobKey;
DataAdapter(Frame fr, SpeeDRFModel model, int[] modelDataMap, int rows,
long unique, long seed, int binLimit, double[] classWt) {
// assert model._dataKey == fr._key;
_seed = seed+(unique<<16); // This is important to preserve sampling selection!!!
/* Maximum arity for a column (not a hard limit) */
_numRows = rows;
_jobKey = model.jobKey;
_numClasses = model.regression ? 1 : model.classes();
_regression = model.regression;
_c = new Col[fr.numCols()];
for( int i = 0; i < _c.length; i++ ) {
if(model.jobKey != null && !Job.isRunning(model.jobKey)) throw new Job.JobCancelledException();
assert fr._names[modelDataMap[i]].equals(fr._names[i]);
Vec v = fr.vecs()[i];
if( isByteCol(v,rows, i == _c.length-1, _regression) ) // we do not bin for small values
_c[i] = new Col(fr._names[i], rows, i == _c.length-1);
else
_c[i] = new Col(fr._names[i], rows, i == _c.length-1, binLimit, !(v.isEnum() || v.isInt()));
}
boolean trivial = true;
if (classWt != null) for(double f: classWt) if (f != 1.0) trivial = false;
_classWt = trivial ? null : classWt;
}
static boolean isByteCol( Vec C, int rows, boolean isClass, boolean regression) {
if (regression) {
return !isClass && (C.isInt() || C.isEnum()) && C.min() >= 0 && C.length() == rows && (C.max() < 255 || C.max() < 256 && C.length() == rows);
}
return (C.isInt() || C.isEnum()) && !isClass && C.min() >= 0 && C.length()==rows &&
(C.max()<255 || C.max() <256 && C.length()==rows);
}
/** Given a value in enum format, returns: the value in the original format if no
* binning was applied, or if binning was applied a value that is inbetween
* the idx and the next value. If the idx is the last value return (2*idx+1)/2. */
public float unmap(int col, int idx){ return _c[col].rawSplit(idx); }
public boolean isFloat(int col) { return _c[col].isFloat(); }
public long seed() { return _seed; }
public int columns() { return _c.length;}
public int classOf(int idx) { return _c[_c.length-1].get(idx); }
/** The number of possible prediction classes. */
public int classes() { return _numClasses; }
/** Transforms given binned index (short) from class column into a value from interval [0..N-1]
* corresponding to a particular predictor class */
public int unmapClass(int clazz) {
Col c = _c[_c.length-1];
if (c._isByte)
return clazz;
else {
// OK, this is not fully correct bad handle corner-cases like for example dataset uses classes only
// with 0 and 3. Our API reports that there are 4 classes but in fact there are only 2 classes.
if (clazz >= c._binned2raw.length) clazz = c._binned2raw.length - 1;
return (int) (c.raw(clazz) - c._min);
}
}
/** Returns the number of bins, i.e. the number of distinct values in the column. */
public int columnArity(int col) { return _c[col].arity(); }
public int columnArityOfClassCol() { return _c[_c.length - 1].arity(); }
/** Return a short that represents the binned value of the original row,column value. */
public short getEncodedColumnValue(int row, int col) { return _c[col].get(row); }
public short getEncodedClassColumnValue(int row) { return _c[_c.length-1].get(row); }
public double getRawColumnValue(int row, int col) { return _c[col].getRaw(row); }
public float getRawClassColumnValueFromBin(int row) {
int idx = _c.length-1;
short btor = _c[idx].get(row);
if (_c[idx]._binned == null) {
return (float)(0xFF & _c[idx]._rawB[row]);
}
return _c[_c.length-1]._binned2raw[btor];
}
public void shrink() {
if(_jobKey != null && !Job.isRunning(_jobKey)) throw new Job.JobCancelledException();
// for ( Col c: _c) c.shrink();
// sort columns in parallel: c.shrink() calls single-threaded Arrays.sort()
Futures fs = new Futures();
for ( final Col c: _c) {
H2O.H2OCountedCompleter t = new H2O.H2OCountedCompleter() {
@Override public byte priority() { return H2O.MIN_HI_PRIORITY; }
@Override public void compute2() {
c.shrink();
tryComplete();
}
};
H2O.submitTask(t);
fs.add(t);
}
fs.blockForPending();
}
public String columnName(int i) { return _c[i].name(); }
public boolean isValid(int col, float f) {
return !_c[col].isFloat() || !Float.isInfinite(f);
}
public final void add(float v, int row, int col) {
_c[col].add (row,v); }
public final void add1(int v, int row, int col) {
_c[col].add1(row,v); }
public final void addBad(int row, int col) { _c[col].addBad(row); }
public final boolean hasBadValue(int row, int col) { return _c[col].isBad(row); }
public final boolean isBadRow(int row) { return _c[_c.length-1].isBad(row); }
public final boolean isBadRowRaw(int row) { return _c[_c.length-1].isBadRaw(row); }
public final boolean isIgnored(int col) { return _c[col].isIgnored(); }
public final void markIgnoredRow(int row) { _c[_c.length-1].addBad(row); }
public final int classColIdx() { return _c.length - 1; }
public final boolean hasAnyInvalid(int col) { return _c[col]._invalidValues!=0; }
static class Col {
/** Encoded values*/
short[] _binned;
/** Original values, kept only during inhale*/
float[] _raw;
/** Original values which we do not want to bin */
byte[] _rawB;
/** Map from binned to original*/
float[] _binned2raw;
final boolean _isClass, _isFloat, _isByte;
final int _colBinLimit;
final String _name;
/** Total number of bad values in the column. */
int _invalidValues;
float _min, _max;
int _arity;
static final DecimalFormat df = new DecimalFormat ("0.
boolean _ignored;
Col(String s, int rows, boolean isClass) {
_name = s; _isClass = isClass;
_rawB = MemoryManager.malloc1(rows);
_isFloat = false;
_isByte = true;
_colBinLimit = 0;
}
Col(String s, int rows, boolean isClass, int binLimit, boolean isFloat) {
_name = s; _isFloat = isFloat; _isClass = isClass; _colBinLimit = binLimit; _isByte = false;
_raw = MemoryManager.malloc4f(rows);
_ignored = false;
}
boolean isFloat() { return _isFloat; }
boolean isIgnored() { return _ignored; }
int arity() { return _ignored ? -1 : _arity; }
String name() { return _name; }
short get(int row) { return (short) (_isByte ? (_rawB[row]&0xFF) : _binned[row]); }
double getRaw(int row) { return (double)(_isByte ? (_rawB[row]&0xFF) : _binned2raw[_binned[row]]);}
void add(int row, float val) {
_raw [row] = val; }
void add1(int row, int val) {
_rawB[row] = (byte)val; }
void addBad(int row) { if (!_isByte) _raw[row] = Float.NaN; else _rawB[row] = (byte)255; }
private boolean isBadRaw(float f) { return Float.isNaN(f); }
boolean isBad(int row) {
return _isByte ? (_rawB[row]&0xFF)==255 : _binned[row] == BAD;
}
/** For all columns - encode all floats as unique shorts. */
void shrink() {
if (_isByte) {
_arity = 256;
return ; // do not shrink byte columns
}
float[] vs = _raw.clone();
Arrays.sort(vs); // Sort puts all Float.NaN at the end of the array (according Float.NaN doc)
int ndups = 0, i = 0, nans = 0; // Counter of all NaNs
while(i < vs.length-1) { // count dups
int j = i+1;
if (isBadRaw(vs[i])) { nans = vs.length - i; break; } // skip all NaNs
if (isBadRaw(vs[j])) { nans = vs.length - j; break; } // there is only one remaining NaN (do not forget on it)
while(j < vs.length && vs[i] == vs[j]){ ++ndups; ++j; }
i = j;
}
_invalidValues = nans;
if ( vs.length <= nans) {
// to many NaNs in the column => ignore it
_ignored = true;
_raw = null;
Log.info(Sys.RANDF, "Ignore column: " + this);
return;
}
int n = vs.length - ndups - nans;
int rem = n % _colBinLimit;
int maxBinSize = (n > _colBinLimit) ? (n / _colBinLimit + Math.min(rem,1)) : 1;
// Assign shorts to floats, with binning.
_binned2raw = MemoryManager.malloc4f(Math.min(n, _colBinLimit)); // if n is smaller than bin limit no need to compact
int smax = 0, cntCurBin = 1;
i = 0;
_binned2raw[0] = vs[i];
for(; i < vs.length; ++i) {
if(isBadRaw(vs[i])) break; // the first NaN, there are only NaN in the rest of vs[] array
if(vs[i] == _binned2raw[smax]) continue; // remove dups
if( ++cntCurBin > maxBinSize ) {
if(rem > 0 && --rem == 0)--maxBinSize; // check if we can reduce the bin size
++smax;
cntCurBin = 1;
}
_binned2raw[smax] = vs[i];
}
++smax;
// for(i = 0; i< vs.length; i++) if (!isBadRaw(vs[i])) break;
// All Float.NaN are at the end of vs => min is stored in vs[0]
_min = vs[0];
for(i = vs.length -1; i>= 0; i--) if (!isBadRaw(vs[i])) break;
_max = vs[i];
vs = null; // GCed
_binned = MemoryManager.malloc2(_raw.length);
// Find the bin value by lookup in bin2raw array which is sorted so we can do binary lookup.
for(i = 0; i < _raw.length; i++)
if (isBadRaw(_raw[i]))
_binned[i] = BAD;
else {
short idx = (short) Arrays.binarySearch(_binned2raw, _raw[i]);
if (idx >= 0) _binned[i] = idx;
else _binned[i] = (short) (-idx - 1); // this occurs when we are looking for a binned value, we return the smaller value in the array.
assert _binned[i] < _binned2raw.length;
}
if( n > _colBinLimit ) Log.info(Sys.RANDF,this+" this column's arity was cut from "+n+" to "+smax);
_arity = _binned2raw.length;
_raw = null; // GCced
}
/**Given an encoded short value, return the original float*/
public float raw(int idx) { return _binned2raw[idx]; }
/**Given an encoded short value, return the float that splits that value with the next.*/
public float rawSplit(int idx){
if (_isByte) return idx; // treat index as value
if (idx == BAD) return Float.NaN;
float flo = _binned2raw[idx]; // Convert to the original values
float fhi = (idx+1 < _binned2raw.length)? _binned2raw[idx+1] : flo+1.f;
//assert flo < fmid && fmid < fhi : "Values " + flo +","+fhi ; // Assert that the float will properly split
return (flo+fhi)/2.0f;
}
int rows() { return _isByte ? _rawB.length : _binned.length; }
@Override public String toString() {
String res = "Column("+_name+"){";
if (_ignored) res+="IGNORED";
else {
res+= " ["+df.format(_min) +","+df.format(_max)+"]";
res+=",bad values=" + _invalidValues + "/" + rows();
if (_isClass) res+= " CLASS ";
}
res += "}";
return res;
}
}
}
|
package httpserver;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.HashMap;
import java.util.Map;
public class HttpRequestReader {
private static final char CR = '\r';
private static final char LF = '\n';
private static final char HT = '\t';
private final PushbackInputStream in;
public HttpRequestReader(InputStream in) {
this.in = new PushbackInputStream(in);
}
public String[] readRequestLine() throws IOException {
int b;
ByteArrayOutputStream method = new ByteArrayOutputStream();
while (-1 != (b = in.read())) {
if (b == ' ' || b == HT) {
break;
}
method.write(b);
}
if (method.size() == 0) {
throw new IllegalStateException();
}
//SPHT
while (-1 != (b = in.read())) {
if (b != ' ' && b != HT) {
in.unread(b);
break;
}
}
ByteArrayOutputStream requestUri = new ByteArrayOutputStream();
while (-1 != (b = in.read())) {
if (b == ' ' || b == HT) {
break;
}
requestUri.write(b);
}
if (requestUri.size() == 0) {
throw new IllegalStateException();
}
//SPHT
while (-1 != (b = in.read())) {
if (b != ' ' && b != HT) {
in.unread(b);
break;
}
}
ByteArrayOutputStream httpVersion = new ByteArrayOutputStream();
while (-1 != (b = in.read())) {
if (b == CR) {
b = in.read();
}
if (b == LF) {
return new String[] {
method.toString(),
requestUri.toString(),
httpVersion.toString() };
}
httpVersion.write(b);
}
throw new IllegalArgumentException();
}
public Map<String, String> readRequestHeader() throws IOException {
Map<String, String> requestHeader = new HashMap<>();
int b;
while (-1 != (b = in.read())) {
if (b == CR) {
b = in.read();
}
if (b == LF) {
break;
}
in.unread(b);
String[] requestHeaderField = readRequestHeaderField();
requestHeader.put(requestHeaderField[0], requestHeaderField[1]);
}
return requestHeader;
}
protected String[] readRequestHeaderField() throws IOException {
ByteArrayOutputStream name = new ByteArrayOutputStream();
int b;
while (-1 != (b = in.read())) {
if (b == ':') {
break;
}
name.write(b);
}
//fieldLWS
b = in.read();
if (b == CR) {
b = in.read();
}
if (b == LF) {
b = in.read();
}
if ((b != ' ' && b != HT) == false) {
while (-1 != (b = in.read())) {
if (b != ' ' && b != HT) {
break;
}
}
}
ByteArrayOutputStream value = new ByteArrayOutputStream();
value.write(b);
while (-1 != (b = in.read())) {
if (b == CR) {
b = in.read();
}
if (b == LF) {
b = in.read();
if (b != ' ' && b != HT) {
in.unread(b);
//field-name
return new String[] {
name.toString().toLowerCase(),
value.toString() };
}
//field-valueLWS
while (-1 != (b = in.read())) {
if (b != ' ' && b != HT) {
break;
}
}
}
value.write(b);
}
throw new IllegalStateException();
}
public byte[] readEntityBody(int contentLength) throws IOException {
int b;
ByteArrayOutputStream entityBody = new ByteArrayOutputStream();
while (-1 != (b = in.read())) {
entityBody.write(b);
if (entityBody.size() == contentLength) {
return entityBody.toByteArray();
}
}
throw new IllegalStateException();
}
}
|
package io.sigpipe.sing.graph;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NavigableMap;
import java.util.logging.Logger;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import io.sigpipe.sing.dataset.Pair;
import io.sigpipe.sing.dataset.Quantizer;
import io.sigpipe.sing.dataset.feature.Feature;
import io.sigpipe.sing.dataset.feature.FeatureType;
import io.sigpipe.sing.stat.RunningStatisticsND;
import io.sigpipe.sing.util.TestConfiguration;
public class Sketch {
private static final Logger logger = Logger.getLogger("io.sigpipe.sing");
/** The root vertex. */
private Vertex root = new Vertex();
/** Describes each level in the Feature hierarchy. */
private Map<String, HierarchyLevel> levels = new HashMap<>();
/**
* We maintain a separate Queue with Feature names inserted in
* hierarchical order. While levels.keySet() contains the same information,
* there is no contractual obligation for HashMap to return the keyset in
* the original insertion order (although in practice, it probably does).
*/
private Queue<String> features = new LinkedList<>();
/**
* Tracks information about each level in the graph hierarchy.
*/
private class HierarchyLevel {
public HierarchyLevel(int order, FeatureType type) {
this.order = order;
this.type = type;
}
public int order;
public FeatureType type;
}
public Sketch() {
}
/**
* Creates a HierarchicalGraph with a set Feature hierarchy. Features are
* entered into the hierarchy in the order they are received.
*
* @param hierarchy Graph hierarchy represented as a
* {@link FeatureHierarchy}.
*/
public Sketch(FeatureHierarchy hierarchy) {
for (Pair<String, FeatureType> feature : hierarchy) {
getOrder(feature.a, feature.b);
}
}
/**
* When a path does not contain a particular Feature, we use a null feature
* (FeatureType.NULL) to act as a "wildcard" in the graph so that the path
* stays linked together. The side effect of this is that 'less than'
* comparisons may return wildcards, which are removed with this method.
*
* @param map The map to remove the first NULL element from. If the map has
* no elements or the first element is not a NULL FeatureType, then no
* modifications are made to the map.
*/
private void removeWildcard(NavigableMap<Feature, Vertex> map) {
if (map.size() <= 0) {
return;
}
Feature first = map.firstKey();
if (first.getType() == FeatureType.NULL) {
map.remove(first);
}
}
/**
* Adds a new {@link Path} to the Hierarchical Graph.
*/
public void addPath(Path path)
throws FeatureTypeMismatchException, GraphException {
if (path.size() == 0) {
throw new GraphException("Attempted to add empty path!");
}
Iterator<Vertex> it = path.iterator();
while (it.hasNext()) {
Vertex v = it.next();
Quantizer q = TestConfiguration.quantizers.get(
v.getLabel().getName());
if (q == null) {
if (v.getLabel().getName().equals("location")) {
continue;
}
it.remove();
continue;
}
boolean ok = false;
for (String featureName : TestConfiguration.FEATURE_NAMES) {
if (featureName.equals(v.getLabel().getName()) == true) {
ok = true;
break;
}
}
if (ok == false) {
it.remove();
continue;
}
Feature quantizedFeature = q.quantize(v.getLabel());
v.setLabel(new Feature(v.getLabel().getName(), quantizedFeature));
}
checkFeatureTypes(path);
addNullFeatures(path);
reorientPath(path);
optimizePath(path);
double[] values = new double[path.size() - 1];
for (int i = 0; i < path.size() - 1; ++i) {
values[i] = path.get(i).getLabel().getDouble();
}
RunningStatisticsND rsnd = new RunningStatisticsND(values);
DataContainer container = new DataContainer(rsnd);
/* Place the path payload (traversal result) at the end of this path. */
path.get(path.size() - 1).setData(container);
root.addPath(path.iterator());
}
/**
* This method ensures that the Features in the path being added have the
* same FeatureTypes as the current hierarchy. This ensures that different
* FeatureTypes (such as an int and a double) get placed on the same level
* in the hierarchy.
*
* @param path the Path to check for invalid FeatureTypes.
*
* @throws FeatureTypeMismatchException if an invalid type is found
*/
private void checkFeatureTypes(Path path)
throws FeatureTypeMismatchException {
for (Feature feature : path.getLabels()) {
/* If this feature is NULL, then it's effectively a wildcard. */
if (feature.getType() == FeatureType.NULL) {
continue;
}
HierarchyLevel level = levels.get(feature.getName());
if (level != null) {
if (level.type != feature.getType()) {
throw new FeatureTypeMismatchException(
"Feature insertion at graph level " + level.order
+ " is not possible due to a FeatureType mismatch. "
+ "Expected: " + level.type + ", "
+ "found: " + feature.getType() + "; "
+ "Feature: <" + feature + ">");
}
}
}
}
/**
* For missing feature values, add a null feature to a path. This maintains
* the graph structure for sparse schemas or cases where a feature reading
* is not available.
*/
private void addNullFeatures(Path path) {
Set<String> unknownFeatures = new HashSet<>(levels.keySet());
for (Feature feature : path.getLabels()) {
unknownFeatures.remove(feature.getName());
}
/* Create null features for missing values */
for (String featureName : unknownFeatures) {
Vertex v = new Vertex();
v.setLabel(new Feature(featureName));
path.add(v);
}
}
/**
* Reorients a nonhierarchical path in place to match the current graph
* hierarchy.
*/
private void reorientPath(Path path) {
if (path.size() == 1) {
/* This doesn't need to be sorted... */
getOrder(path.get(0).getLabel());
return;
}
path.sort(new Comparator<Vertex>() {
public int compare(Vertex a, Vertex b) {
int o2 = getOrder(b.getLabel());
int o1 = getOrder(a.getLabel());
return o1 - o2;
}
});
}
/**
* Perform optimizations on a path to reduce the number of vertices inserted
* into the graph.
*/
private void optimizePath(Path path) {
/* Remove all trailing null features. During a traversal, trailing null
* features are unnecessary to traverse. */
for (int i = path.size() - 1; i >= 0; --i) {
if (path.get(i).getLabel().getType() == FeatureType.NULL) {
path.remove(i);
} else {
break;
}
}
}
/**
* Removes all null Features from a path. This includes any Features that
* are the standard Java null, or Features with a NULL FeatureType.
*
* @param path Path to remove null Features from.
*/
private void removeNullFeatures(Path path) {
Iterator<Vertex> it = path.iterator();
while (it.hasNext()) {
Feature f = it.next().getLabel();
if (f == null || f.getType() == FeatureType.NULL) {
it.remove();
}
}
}
/**
* Determines the numeric order of a Feature based on the current
* orientation of the graph. For example, humidity features may come first,
* followed by temperature, etc. If the feature in question has not yet
* been added to the graph, then it is connected to the current leaf nodes,
* effectively placing it at the bottom of the hierarchy, and its order
* number is set to the current number of feature types in the graph.
*
* @return int representing the list ordering of the Feature
*/
private int getOrder(String name, FeatureType type) {
int order;
HierarchyLevel level = levels.get(name);
if (level != null) {
order = level.order;
} else {
order = addNewFeature(name, type);
}
return order;
}
private int getOrder(Feature feature) {
return getOrder(feature.getName(), feature.getType());
}
/**
* Update the hierarchy levels and known Feature list with a new Feature.
*/
private int addNewFeature(String name, FeatureType type) {
logger.info("New feature: " + name + ", type: " + type);
Integer order = levels.keySet().size();
levels.put(name, new HierarchyLevel(order, type));
features.offer(name);
return order;
}
/**
* Retrieves the ordering of Feature names in this graph hierarchy.
*/
public FeatureHierarchy getFeatureHierarchy() {
FeatureHierarchy hierarchy = new FeatureHierarchy();
for (String feature : features) {
try {
hierarchy.addFeature(feature, levels.get(feature).type);
} catch (GraphException e) {
/* If a GraphException is thrown here, something is seriously
* wrong. */
logger.severe("NULL FeatureType found in graph hierarchy!");
}
}
return hierarchy;
}
public Vertex getRoot() {
return root;
}
@Override
public String toString() {
return root.toString();
}
}
|
package mcjty.xnet.proxy;
import mcjty.lib.McJtyLib;
import mcjty.lib.compat.MainCompatHandler;
import mcjty.lib.setup.DefaultCommonSetup;
import mcjty.xnet.CommandHandler;
import mcjty.xnet.ForgeEventHandlers;
import mcjty.xnet.XNet;
import mcjty.xnet.apiimpl.energy.EnergyChannelType;
import mcjty.xnet.apiimpl.fluids.FluidChannelType;
import mcjty.xnet.apiimpl.items.ItemChannelType;
import mcjty.xnet.apiimpl.logic.LogicChannelType;
import mcjty.xnet.config.ConfigSetup;
import mcjty.xnet.gui.GuiProxy;
import mcjty.xnet.init.ModBlocks;
import mcjty.xnet.init.ModItems;
import mcjty.xnet.network.XNetMessages;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
public class CommonSetup extends DefaultCommonSetup {
public static boolean rftools = false;
@Override
public void preInit(FMLPreInitializationEvent e) {
super.preInit(e);
McJtyLib.registerMod(XNet.instance); // @todo why only xnet?
MinecraftForge.EVENT_BUS.register(new ForgeEventHandlers());
NetworkRegistry.INSTANCE.registerGuiHandler(XNet.instance, new GuiProxy());
CommandHandler.registerCommands();
XNetMessages.registerMessages("xnet");
ConfigSetup.init();
ModItems.init();
ModBlocks.init();
XNet.xNetApi.registerConsumerProvider((world, blob, net) -> blob.getConsumers(net));
XNet.xNetApi.registerChannelType(new ItemChannelType());
XNet.xNetApi.registerChannelType(new EnergyChannelType());
XNet.xNetApi.registerChannelType(new FluidChannelType());
XNet.xNetApi.registerChannelType(new LogicChannelType());
}
@Override
protected void setupModCompat() {
rftools = Loader.isModLoaded("rftools");
MainCompatHandler.registerWaila();
MainCompatHandler.registerTOP();
}
@Override
public void createTabs() {
createTab("XNet", new ItemStack(Item.getItemFromBlock(Blocks.ANVIL)));
}
@Override
public void postInit(FMLPostInitializationEvent e) {
super.postInit(e);
ConfigSetup.postInit();
}
}
|
package me.legrange.net;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class is an network access list tree that can contain permit and deny
* policies and match a specific IP address against the policies
*/
public class IPAccessList implements java.io.Serializable {
/**
* Create a new access list with the given default policy
*
* @param policy
*/
public IPAccessList(boolean policy) {
v4 = new Node(IPv4Network.ALL, policy);
v6 = new Node(IPv6Network.ALL, policy);
}
public void add(String network, int mask, boolean policy) throws NetworkException {
try {
InetAddress addr = InetAddress.getByName(network);
if (addr instanceof Inet4Address) {
add(IPv4Network.getByAddress(network, mask), policy);
} else if (addr instanceof Inet6Address) {
add(IPv6Network.getByAddress(network, mask), policy);
}
} catch (UnknownHostException ex) {
throw new InvalidAddressException(ex.getMessage(), ex);
}
}
public void add(IPNetwork network, boolean policy) throws NetworkException {
Node place = findPlace(network);
if (place.getPolicy() != policy) {
place.addChild(new Node(network, policy));
}
}
public boolean checkAccess(IPNetwork net) throws NetworkException {
return findPlace(net).getPolicy();
}
public boolean checkAccess(String ip) throws InvalidAddressException {
try {
return checkAccess(InetAddress.getByName(ip));
} catch (UnknownHostException ex) {
throw new InvalidAddressException(ex.getMessage(), ex);
}
}
public boolean checkAccess(InetAddress addr) throws InvalidAddressException {
if (addr instanceof Inet4Address) {
try {
return checkV4Access(addr.getHostAddress());
} catch (NetworkException ex) {
throw new InvalidAddressException(ex.getMessage(), ex);
}
} else if (addr instanceof Inet6Address) {
try {
return checkV6Access(addr.getHostAddress());
} catch (NetworkException ex) {
throw new InvalidAddressException(ex.getMessage(), ex);
}
}
return false;
}
private boolean checkV4Access(String ip) throws NetworkException {
return checkAccess(IPv4Network.getByAddress(ip, 32));
}
private boolean checkV6Access(String ip) throws NetworkException {
return checkAccess(IPv6Network.getByAddress(ip, 128));
}
/**
* find the correct parent node for the given network
*/
private Node findPlace(IPNetwork net) throws NetworkException {
if (net instanceof IPv4Network) {
return findPlace(net, v4);
}
return findPlace(net, v6);
}
/**
* find the correct parent node for the given network relative to the given
* root
*/
private Node findPlace(IPNetwork network, Node root) throws NetworkException {
for (Node child : root.getChildren()) {
if (child.getNetwork().containsAddress(network.getAddress())) {
return findPlace(network, child);
}
}
return root;
}
/**
* A node in the access tree
*/
private static class Node {
/**
* create a new node
*/
private Node(IPNetwork network, boolean policy) {
this.network = network;
this.policy = policy;
}
/**
* return the children for this node
*/
private List<Node> getChildren() {
return children;
}
/**
* return the network for this node
*/
private IPNetwork getNetwork() {
return network;
}
/**
* return the policy for this node
*/
private boolean getPolicy() {
return policy;
}
/**
* add a child to this node
*/
private void addChild(Node child) throws NetworkException {
children.add(child);
for (Iterator<Node> it = children.iterator(); it.hasNext();) {
Node have = it.next();
if (have == child) {
continue;
}
if (child.getNetwork().containsAddress(have.getNetwork().getAddress())) {
it.remove();
child.addChild(have);
}
}
}
private IPNetwork network;
private boolean policy;
private List<Node> children = new ArrayList<>();
}
private Node v4;
private Node v6;
}
|
package me.michidk.FakeMCServer;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.ConsoleHandler;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* @author michidk
*/
public class Main
{
public static final String version = "v1.0";
public static final Logger log = Logger.getLogger("FakeMCServer");
private static volatile boolean debug = false;
private static volatile boolean stopping = false;
public static final int SOCKET_BACKLOG = 5;
public static String host = null;
public static Integer port = null;
public static volatile String icon = null;
public static volatile String verText = null;
public static volatile String motd = null;
public static volatile String[] players = null;
public static volatile Integer maxPlayers = null;
public static volatile String kickMessage = null;
public static volatile ServerSocket server = null;
public static final String blankIcon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAADIjAAAyIwHN55PYAAA50WlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4KPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS41LWMwMTQgNzkuMTUxNDgxLCAyMDEzLzAzLzEzLTEyOjA5OjE1ICAgICAgICAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iCiAgICAgICAgICAgIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIgogICAgICAgICAgICB4bWxuczpzdEV2dD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlRXZlbnQjIgogICAgICAgICAgICB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iCiAgICAgICAgICAgIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICAgICAgICAgIHhtbG5zOmV4aWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vZXhpZi8xLjAvIj4KICAgICAgICAgPHhtcDpDcmVhdG9yVG9vbD5BZG9iZSBQaG90b3Nob3AgQ0MgKFdpbmRvd3MpPC94bXA6Q3JlYXRvclRvb2w+CiAgICAgICAgIDx4bXA6Q3JlYXRlRGF0ZT4yMDE0LTA1LTMxVDAzOjAyOjI2KzAyOjAwPC94bXA6Q3JlYXRlRGF0ZT4KICAgICAgICAgPHhtcDpNZXRhZGF0YURhdGU+MjAxNC0wNS0zMVQwMzowMjoyNiswMjowMDwveG1wOk1ldGFkYXRhRGF0ZT4KICAgICAgICAgPHhtcDpNb2RpZnlEYXRlPjIwMTQtMDUtMzFUMDM6MDI6MjYrMDI6MDA8L3htcDpNb2RpZnlEYXRlPgogICAgICAgICA8eG1wTU06SW5zdGFuY2VJRD54bXAuaWlkOjMwMzZiNjc2LThmZDYtNTI0Mi05MjE0LWQ5YzYzZTQ2MmRiYjwveG1wTU06SW5zdGFuY2VJRD4KICAgICAgICAgPHhtcE1NOkRvY3VtZW50SUQ+eG1wLmRpZDplOGMwNGViMy01ZGQ1LTAwNDAtODc5Ny0yNThkZjRiZmVlOTg8L3htcE1NOkRvY3VtZW50SUQ+CiAgICAgICAgIDx4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ+eG1wLmRpZDplOGMwNGViMy01ZGQ1LTAwNDAtODc5Ny0yNThkZjRiZmVlOTg8L3htcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD4KICAgICAgICAgPHhtcE1NOkhpc3Rvcnk+CiAgICAgICAgICAgIDxyZGY6U2VxPgogICAgICAgICAgICAgICA8cmRmOmxpIHJkZjpwYXJzZVR5cGU9IlJlc291cmNlIj4KICAgICAgICAgICAgICAgICAgPHN0RXZ0OmFjdGlvbj5jcmVhdGVkPC9zdEV2dDphY3Rpb24+CiAgICAgICAgICAgICAgICAgIDxzdEV2dDppbnN0YW5jZUlEPnhtcC5paWQ6ZThjMDRlYjMtNWRkNS0wMDQwLTg3OTctMjU4ZGY0YmZlZTk4PC9zdEV2dDppbnN0YW5jZUlEPgogICAgICAgICAgICAgICAgICA8c3RFdnQ6d2hlbj4yMDE0LTA1LTMxVDAzOjAyOjI2KzAyOjAwPC9zdEV2dDp3aGVuPgogICAgICAgICAgICAgICAgICA8c3RFdnQ6c29mdHdhcmVBZ2VudD5BZG9iZSBQaG90b3Nob3AgQ0MgKFdpbmRvd3MpPC9zdEV2dDpzb2Z0d2FyZUFnZW50PgogICAgICAgICAgICAgICA8L3JkZjpsaT4KICAgICAgICAgICAgICAgPHJkZjpsaSByZGY6cGFyc2VUeXBlPSJSZXNvdXJjZSI+CiAgICAgICAgICAgICAgICAgIDxzdEV2dDphY3Rpb24+c2F2ZWQ8L3N0RXZ0OmFjdGlvbj4KICAgICAgICAgICAgICAgICAgPHN0RXZ0Omluc3RhbmNlSUQ+eG1wLmlpZDozMDM2YjY3Ni04ZmQ2LTUyNDItOTIxNC1kOWM2M2U0NjJkYmI8L3N0RXZ0Omluc3RhbmNlSUQ+CiAgICAgICAgICAgICAgICAgIDxzdEV2dDp3aGVuPjIwMTQtMDUtMzFUMDM6MDI6MjYrMDI6MDA8L3N0RXZ0OndoZW4+CiAgICAgICAgICAgICAgICAgIDxzdEV2dDpzb2Z0d2FyZUFnZW50PkFkb2JlIFBob3Rvc2hvcCBDQyAoV2luZG93cyk8L3N0RXZ0OnNvZnR3YXJlQWdlbnQ+CiAgICAgICAgICAgICAgICAgIDxzdEV2dDpjaGFuZ2VkPi88L3N0RXZ0OmNoYW5nZWQ+CiAgICAgICAgICAgICAgIDwvcmRmOmxpPgogICAgICAgICAgICA8L3JkZjpTZXE+CiAgICAgICAgIDwveG1wTU06SGlzdG9yeT4KICAgICAgICAgPGRjOmZvcm1hdD5pbWFnZS9wbmc8L2RjOmZvcm1hdD4KICAgICAgICAgPHBob3Rvc2hvcDpDb2xvck1vZGU+MzwvcGhvdG9zaG9wOkNvbG9yTW9kZT4KICAgICAgICAgPHRpZmY6T3JpZW50YXRpb24+MTwvdGlmZjpPcmllbnRhdGlvbj4KICAgICAgICAgPHRpZmY6WFJlc29sdXRpb24+MzI2MDAwMC8xMDAwMDwvdGlmZjpYUmVzb2x1dGlvbj4KICAgICAgICAgPHRpZmY6WVJlc29sdXRpb24+MzI2MDAwMC8xMDAwMDwvdGlmZjpZUmVzb2x1dGlvbj4KICAgICAgICAgPHRpZmY6UmVzb2x1dGlvblVuaXQ+MjwvdGlmZjpSZXNvbHV0aW9uVW5pdD4KICAgICAgICAgPGV4aWY6Q29sb3JTcGFjZT42NTUzNTwvZXhpZjpDb2xvclNwYWNlPgogICAgICAgICA8ZXhpZjpQaXhlbFhEaW1lbnNpb24+NjQ8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+NjQ8L2V4aWY6UGl4ZWxZRGltZW5zaW9uPgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAKPD94cGFja2V0IGVuZD0idyI/PjB4J1kAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAAGhJREFUeNrs0AEBAAAEAzD073w92CKsk9RnU88JECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgIALFgAA//8DAFW2A3065VKgAAAAAElFTkSuQmCC";
public static void main(final String[] args)
{
// parse args
for(int index = 0; index < args.length; index++)
{
switch(args[index].toLowerCase())
{
case "--help":
display_help();
System.exit(0);
return;
case "--debug":
case "-d":
debug = true;
System.out.println("debug mode enabled");
break;
case "-v":
case "--version":
display_version();
System.exit(0);
return;
case "-h":
case "--host":
index++;
host = args[index];
if("*".equals(host) || "any".equalsIgnoreCase(host))
host = "*";
break;
case "-p":
case "--port":
index++;
try
{
port = new Integer(Integer.parseInt(args[index]));
}
catch (NumberFormatException e)
{
System.out.println("invalid port argument");
e.printStackTrace();
System.exit(1);
return;
}
break;
default:
System.out.println();
System.out.println("invalid option: "+args[index]);
System.out.println();
System.exit(1);
return;
}
}
final ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter(new LogFormatter());
log.addHandler(handler);
log.setUseParentHandlers(false);
loadResources();
addShutdownHook();
startServer();
}
public static void display_header()
{
System.out.println("==> FakeMCServer " + version + " by xxmicloxx and michidk <==");
System.out.println("Github: https://github.com/michidk/FakeMCServer");
System.out.println("YouTube: https:
System.out.println("
System.out.println();
}
public static void display_version()
{
display_header();
}
public static void display_help()
{
display_header();
// get jar self file name
final String jarSelfStr;
{
final String str = Main.class.getProtectionDomain().getCodeSource().getLocation().getFile();
final int pos = str.lastIndexOf('/');
if(pos == -1)
jarSelfStr = str;
else
jarSelfStr = str.substring(pos + 1);
}
System.out.println("Usage:");
System.out.println(" java -jar "+jarSelfStr+" [options]");
System.out.println();
System.out.println("Options:");
System.out.println(" -h, --host <hostname/ip> Host to listen on");
System.out.println(" -p, --port <port> Port to listen on");
System.out.println();
System.out.println(" --help display this help and exit");
System.out.println(" -v, --version output version information and exit");
System.out.println();
}
public static void loadResources()
{
log.info("loading resources...");
//load servericon
final String iconPath = "server-icon.png";
final File serverIcon = new File(iconPath);
if (!serverIcon.exists())
{
log.warning("icon file '" + iconPath + "' not found");
icon = null;
}
else
{
final String base64 = FileHelper.decodeBase64(serverIcon);
if (base64 == null || base64.isEmpty())
{
log.warning("something went wrong while decoding '" + iconPath + "'");
icon = null;
}
else
{
icon = "data:image/png;base64," + base64;
log.info("icon file '" + iconPath + "' successfully loaded");
}
}
//load version
verText = parseColors(
getFileString("version.txt")
);
//load motd
motd = parseColors(
getFileString("motd.txt")
);
//kick message
kickMessage = parseColors(
getFileString("kickmessage.txt")
);
//players
{
final String str = getFileString("players.txt");
if(str != null)
{
final List<String> list = new ArrayList<String>();
for(final String player : str.replace("\r", ",").replace("\n", ",").split(","))
{
if(player == null || player.isEmpty())
continue;
list.add(parseColors(player));
}
players = list.toArray(new String[0]);
}
}
//maxplayers
{
final String str = getFileString("maxplayers.txt");
try {
maxPlayers = (str == null ? null : new Integer(Integer.parseInt(str)));
}
catch (NumberFormatException e)
{
log.warning("invalid number in 'maxplayers.txt'");
maxPlayers = null;
}
}
}
private static String getFileString(final String fileName)
{
final File file = new File(fileName);
if(!file.isFile()) {
try {
file.createNewFile();
log.warning("created empty file '"+fileName+"'");
}
catch (IOException e)
{
log.warning("file '"+fileName+"' not found");
e.printStackTrace();
}
return null;
}
if(!file.canRead()) {
log.warning("file '"+fileName+"' not readable");
return null;
}
final String str = FileHelper.stringFromFile(file);
if(str == null || str.isEmpty()) {
log.warning("file '"+fileName+"' is empty");
return null;
}
log.info("file '"+fileName+"' successfully loaded");
return str;
}
public static void addShutdownHook()
{
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
stopServer();
}
} );
}
public static void startServer()
{
if(stopping) throw new IllegalAccessError();
log.info("starting server...");
try
{
final String hst = (host == null || host.isEmpty()) ? "*" : host;
final int prt = (port == null) ? 25565 : port.intValue();
if("*".equals(hst))
{
server = new ServerSocket(prt, SOCKET_BACKLOG);
log.info("server started on *:"+Integer.toString(prt));
}
else
{
final InetAddress address = InetAddress.getByName(hst);
server = new ServerSocket(prt, SOCKET_BACKLOG, address);
log.info("server started on "+address.getHostAddress()+":"+Integer.toString(prt));
}
while(!server.isClosed())
{
new ResponderThread(server.accept()).start();
}
}
catch(Exception e)
{
if(!stopping)
{
log.warning("failed to start the server on "+host+":"+port);
log.severe("error: "+e.getMessage());
e.printStackTrace();
System.exit(0);
}
}
finally
{
stopServer();
}
}
public static void stopServer()
{
stopping = true;
if (server == null) return;
log.info("stopping server...");
safeClose(server);
server = null;
log.info("server stopped");
}
private static Pattern colorPattern = Pattern.compile("&([0-9a-fk-or])");
public static String parseColors(final String message)
{
if(message == null) return null;
return colorPattern.matcher(message).replaceAll("\u00a7$1");
}
public static void debug()
{
debug(null);
}
public static void debug(final String msg)
{
if(!debug) return;
if(msg == null || msg.isEmpty())
System.out.println();
else
System.out.println(msg);
}
public static void safeClose(final Closeable obj)
{
if(obj == null) return;
try
{
obj.close();
}
catch (Exception ignore) {}
}
}
|
package mho.qbar.testing;
import mho.qbar.iterableProviders.QBarExhaustiveProvider;
import mho.qbar.iterableProviders.QBarIterableProvider;
import mho.wheels.io.TextInput;
import mho.wheels.iterables.ExhaustiveProvider;
import mho.wheels.numberUtils.IntegerUtils;
import mho.wheels.ordering.Ordering;
import mho.wheels.structures.Pair;
import mho.wheels.structures.Triple;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import static mho.wheels.iterables.IterableUtils.*;
import static mho.wheels.ordering.Ordering.eq;
import static mho.wheels.ordering.Ordering.le;
import static mho.wheels.testing.Testing.*;
public class QBarTesting {
public static final @NotNull QBarExhaustiveProvider QEP = QBarExhaustiveProvider.INSTANCE;
private enum ReadState { NONE, LIST, MAP }
private static Map<String, List<String>> testingLists = null;
private static Map<String, Map<String, String>> testingMaps = null;
private static void initializeTestData() {
testingLists = new HashMap<>();
testingMaps = new HashMap<>();
ReadState state = ReadState.NONE;
int counter = 0;
String name = "";
List<String> list = null;
Map<String, String> map = null;
String key = null;
boolean quoted = false;
for (String line : new TextInput(QBarTesting.class, "testOutput.txt")) {
switch (state) {
case NONE:
if (line.isEmpty()) break;
String[] tokens = line.split(" ");
if (tokens.length != 3 && tokens.length != 4) {
throw new IllegalStateException("Bad data header: " + line);
}
if (tokens.length == 4) {
if (!tokens[3].equals("q")) {
throw new IllegalStateException("Bad 4th token: " + tokens[3]);
}
quoted = true;
} else {
quoted = false;
}
name = tokens[0];
counter = Integer.parseInt(tokens[2]);
if (counter < 0) {
throw new IllegalStateException("Bad counter: " + counter);
}
switch (tokens[1]) {
case "list":
if (testingLists.containsKey(name)) {
throw new IllegalStateException("Duplicate list name: " + name);
}
state = ReadState.LIST;
list = new ArrayList<>(counter);
break;
case "map":
if (testingMaps.containsKey(name)) {
throw new IllegalStateException("Duplicate map name: " + name);
}
state = ReadState.MAP;
map = new HashMap<>(counter);
break;
default:
throw new IllegalStateException("Bad data type: " + tokens[1]);
}
if (counter == 0) {
if (state == ReadState.LIST) {
testingLists.put(name, list);
state = ReadState.NONE;
} else {
testingMaps.put(name, map);
state = ReadState.NONE;
}
}
break;
case LIST:
list.add(readTestOutput(line, quoted));
counter
if (counter == 0) {
testingLists.put(name, list);
state = ReadState.NONE;
}
break;
case MAP:
int colonIndex = line.indexOf(':');
String value = colonIndex == line.length() - 1 ?
"" :
readTestOutput(line.substring(colonIndex + 2), quoted);
map.put(value, line.substring(0, colonIndex));
counter
if (counter == 0) {
testingMaps.put(name, map);
state = ReadState.NONE;
}
}
}
list = null;
map = null;
}
private static @NotNull String readTestOutput(@NotNull String s, boolean quoted) {
if (quoted) {
if (s.length() < 2 || head(s) != '\'' || last(s) != '\'') {
throw new IllegalStateException("line should be quoted: " + s);
}
s = s.substring(1, s.length() - 1);
}
if (!elem('\\', s)) return s;
StringBuilder sb = new StringBuilder();
boolean sawBackslash = false;
int counter4 = -1;
int cAcc = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (sawBackslash) {
if (c == '\\') {
sb.append('\\');
sawBackslash = false;
continue;
} else if (c == 'u') {
counter4 = 4;
sawBackslash = false;
continue;
} else {
throw new IllegalStateException("Improperly escaped backslash: " + s);
}
}
if (counter4 != -1) {
cAcc = cAcc * 16 + IntegerUtils.fromDigit(Character.toUpperCase(c));
counter4
if (counter4 == 0) {
sb.append((char) cAcc);
counter4 = -1;
cAcc = 0;
}
} else if (c != '\\') {
sb.append(c);
}
sawBackslash = c == '\\';
}
return sb.toString();
}
public static void aeqitQBarLog(Iterable<?> a, String b) {
if (testingLists == null) {
initializeTestData();
}
List<String> list = testingLists.get(b);
List<String> actual = toList(map(Objects::toString, a));
if (!Objects.equals(list, actual)) {
boolean quote = containsTrailingSpaces(actual);
System.out.println();
System.out.print(b + " list " + actual.size());
if (quote) {
System.out.println(" q");
} else {
System.out.println();
}
for (String s : actual) {
if (quote) System.out.print('\'');
System.out.print(escape(s));
if (quote) {
System.out.println('\'');
} else {
System.out.println();
}
}
fail("No match for " + b);
}
}
public static void aeqitLimitQBarLog(int limit, Iterable<?> a, String b) {
if (testingLists == null) {
initializeTestData();
}
List<String> list = testingLists.get(b);
List<String> actual = itsList(limit, a);
if (!Objects.equals(list, actual)) {
boolean quote = containsTrailingSpaces(actual);
System.out.println();
System.out.print(b + " list " + actual.size());
if (quote) {
System.out.println(" q");
} else {
System.out.println();
}
for (String s : actual) {
if (quote) System.out.print('\'');
System.out.print(escape(s));
if (quote) {
System.out.println('\'');
} else {
System.out.println();
}
}
fail("No match for " + b);
}
}
public static void aeqMapQBarLog(Map<?, ?> a, String b) {
if (testingLists == null) {
initializeTestData();
}
Map<String, String> map = testingMaps.get(b);
Map<String, String> actual = itsMap(a);
if (!Objects.equals(map, actual)) {
boolean quote = containsTrailingSpaces(actual);
System.out.println();
System.out.print(b + " map " + actual.size());
if (quote) {
System.out.println(" q");
} else {
System.out.println();
}
Map<Integer, Set<String>> sortedActual = new TreeMap<>(Comparator.reverseOrder());
for (Map.Entry<String, String> entry : actual.entrySet()) {
int frequency = Integer.parseInt(entry.getValue());
Set<String> values = sortedActual.get(frequency);
if (values == null) {
values = new TreeSet<>();
sortedActual.put(frequency, values);
}
values.add(entry.getKey());
}
for (Map.Entry<Integer, Set<String>> entry : sortedActual.entrySet()) {
int frequency = entry.getKey();
for (String value : entry.getValue()) {
System.out.print(frequency);
System.out.print(": ");
if (quote) System.out.print('\'');
System.out.print(escape(value));
if (quote) {
System.out.println('\'');
} else {
System.out.println();
}
}
}
fail("No match for " + b);
}
}
private static boolean containsTrailingSpaces(@NotNull List<String> strings) {
for (String s : strings) {
if (!s.isEmpty() && last(s) == ' ') return true;
}
return false;
}
private static boolean containsTrailingSpaces(@NotNull Map<String, String> strings) {
for (Map.Entry<String, String> entry : strings.entrySet()) {
if (!entry.getKey().isEmpty() && last(entry.getKey()) == ' ') return true;
if (!entry.getValue().isEmpty() && last(entry.getValue()) == ' ') return true;
}
return false;
}
private static @NotNull String escape(@NotNull String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c < ' ' || c > '~') {
sb.append("\\u").append(String.format("%4s", Integer.toHexString(c)).replace(' ', '0'));
} else {
if (c == '\\') {
sb.append('\\');
}
sb.append(c);
}
}
return sb.toString();
}
public static <T> void propertiesEqualsHelper(
int limit,
@NotNull QBarIterableProvider ip,
@NotNull Function<QBarIterableProvider, Iterable<T>> fxs
) {
QBarIterableProvider iq = ip.deepCopy();
QBarIterableProvider ir = ip.deepCopy();
for (Triple<T, T, T> t : take(limit, zip3(fxs.apply(ip), fxs.apply(iq), fxs.apply(ir)))) {
//noinspection ObjectEqualsNull
assertFalse(t, t.a.equals(null));
assertTrue(t, t.a.equals(t.b));
assertTrue(t, t.b.equals(t.c));
}
ip.reset();
iq.reset();
for (Pair<T, T> p : take(limit, ExhaustiveProvider.INSTANCE.pairs(fxs.apply(ip), fxs.apply(iq)))) {
symmetric(Object::equals, p);
}
ip.reset();
iq.reset();
ir.reset();
Iterable<Triple<T, T, T>> ts = ExhaustiveProvider.INSTANCE.triples(
fxs.apply(ip),
fxs.apply(iq),
fxs.apply(ir)
);
for (Triple<T, T, T> t : take(limit, ts)) {
transitive(Object::equals, t);
}
}
public static <T> void propertiesHashCodeHelper(
int limit,
@NotNull QBarIterableProvider ip,
@NotNull Function<QBarIterableProvider, Iterable<T>> fxs
) {
QBarIterableProvider iq = ip.deepCopy();
for (Pair<T, T> p : take(limit, zip(fxs.apply(ip), fxs.apply(iq)))) {
assertTrue(p, p.a.equals(p.b));
assertEquals(p, p.a.hashCode(), p.b.hashCode());
}
}
public static <T extends Comparable<T>> void propertiesCompareToHelper(
int limit,
@NotNull QBarIterableProvider ip,
@NotNull Function<QBarIterableProvider, Iterable<T>> fxs
) {
QBarIterableProvider iq = ip.deepCopy();
QBarIterableProvider ir = ip.deepCopy();
for (Pair<T, T> p : take(limit, zip(fxs.apply(ip), fxs.apply(iq)))) {
assertTrue(p, eq(p.a, p.b));
}
ip.reset();
iq.reset();
for (Pair<T, T> p : take(limit, ExhaustiveProvider.INSTANCE.pairs(fxs.apply(ip), fxs.apply(iq)))) {
int compare = p.a.compareTo(p.b);
assertTrue(p, compare == 0 || compare == 1 || compare == -1);
antiSymmetric(Ordering::le, p);
assertTrue(p, le(p.a, p.b) || le(p.b, p.a));
antiCommutative(Comparable::compareTo, c -> -c, p);
}
ip.reset();
iq.reset();
ir.reset();
Iterable<Triple<T, T, T>> ts = ExhaustiveProvider.INSTANCE.triples(
fxs.apply(ip),
fxs.apply(iq),
fxs.apply(ir)
);
for (Triple<T, T, T> t : take(limit, ts)) {
transitive(Ordering::le, t);
}
}
public static <T> void propertiesReadHelper(
int limit,
@NotNull QBarIterableProvider P,
@NotNull String usedChars,
@NotNull Iterable<T> xs,
@NotNull Function<String, Optional<T>> read,
@NotNull Consumer<T> validate,
boolean denseInUsedCharString
) {
for (String s : take(limit, P.strings())) {
read.apply(s);
}
for (T x : take(limit, xs)) {
Optional<T> ox = read.apply(x.toString());
T y = ox.get();
validate.accept(y);
assertEquals(x, y, x);
}
if (denseInUsedCharString) {
for (String s : take(limit, filterInfinite(t -> read.apply(t).isPresent(), P.strings(usedChars)))) {
inverse(t -> read.apply(t).get(), Object::toString, s);
validate.accept(read.apply(s).get());
}
}
}
}
|
package net.fortuna.ical4j.model;
import net.fortuna.ical4j.util.Dates;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.io.IOException;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;
public class Dur implements Comparable<Dur>, Serializable {
private static final long serialVersionUID = 5013232281547134583L;
private static final int DAYS_PER_WEEK = 7;
private static final int SECONDS_PER_MINUTE = 60;
private static final int MINUTES_PER_HOUR = 60;
private static final int HOURS_PER_DAY = 24;
private static final int DAYS_PER_YEAR = 365;
private boolean negative;
private int weeks;
private int days;
private int hours;
private int minutes;
private int seconds;
/**
* Constructs a new duration instance from a string representation.
* @param value a string representation of a duration
*/
public Dur(final String value) {
negative = false;
weeks = 0;
days = 0;
hours = 0;
minutes = 0;
seconds = 0;
String token = null;
String prevToken;
final StringTokenizer t = new StringTokenizer(value, "+-PWDTHMS", true);
while (t.hasMoreTokens()) {
prevToken = token;
token = t.nextToken();
if ("+".equals(token)) {
negative = false;
}
else if ("-".equals(token)) {
negative = true;
}
// does nothing..
// else if ("P".equals(token)) {
else if ("W".equals(token)) {
weeks = Integer.parseInt(prevToken);
}
else if ("D".equals(token)) {
days = Integer.parseInt(prevToken);
}
// does nothing..
// else if ("T".equals(token)) {
else if ("H".equals(token)) {
hours = Integer.parseInt(prevToken);
}
else if ("M".equals(token)) {
minutes = Integer.parseInt(prevToken);
}
else if ("S".equals(token)) {
seconds = Integer.parseInt(prevToken);
}
}
}
/**
* Constructs a new duration from the specified weeks.
* @param weeks a duration in weeks.
*/
public Dur(final int weeks) {
this.weeks = Math.abs(weeks);
this.days = 0;
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
this.negative = weeks < 0;
}
/**
* Constructs a new duration from the specified arguments.
* @param days duration in days
* @param hours duration in hours
* @param minutes duration in minutes
* @param seconds duration in seconds
*/
public Dur(final int days, final int hours, final int minutes,
final int seconds) {
if (!(days >= 0 && hours >= 0 && minutes >= 0 && seconds >= 0)
&& !(days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0)) {
throw new IllegalArgumentException("Invalid duration representation");
}
this.weeks = 0;
this.days = Math.abs(days);
this.hours = Math.abs(hours);
this.minutes = Math.abs(minutes);
this.seconds = Math.abs(seconds);
this.negative = days < 0 || hours < 0 || minutes < 0 || seconds < 0;
}
/**
* Constructs a new duration representing the time between the two specified dates. The end date may precede the
* start date in order to represent a negative duration.
* @param date1 the first date of the duration
* @param date2 the second date of the duration
*/
public Dur(final Date date1, final Date date2) {
Date start;
Date end;
// Negative range? (start occurs after end)
negative = date1.compareTo(date2) > 0;
if (negative) {
// Swap the dates (which eliminates the need to bother with
// negative after this!)
start = date2;
end = date1;
}
else {
start = date1;
end = date2;
}
final Calendar startCal;
if (start instanceof net.fortuna.ical4j.model.Date) {
startCal = Dates.getCalendarInstance((net.fortuna.ical4j.model.Date)start);
} else {
startCal = Calendar.getInstance();
}
startCal.setTime(start);
final Calendar endCal = Calendar.getInstance(startCal.getTimeZone());
endCal.setTime(end);
// Init our duration interval (which is in units that evolve as we
// compute, below)
int dur = 0;
// Count days to get to the right year (loop in the very rare chance
// that a leap year causes us to come up short)
int nYears = endCal.get(Calendar.YEAR) - startCal.get(Calendar.YEAR);
while (nYears > 0) {
startCal.add(Calendar.DATE, DAYS_PER_YEAR * nYears);
dur += DAYS_PER_YEAR * nYears;
nYears = endCal.get(Calendar.YEAR) - startCal.get(Calendar.YEAR);
}
// Count days to get to the right day
dur += endCal.get(Calendar.DAY_OF_YEAR)
- startCal.get(Calendar.DAY_OF_YEAR);
// Count hours to get to right hour
dur *= HOURS_PER_DAY; // days -> hours
dur += endCal.get(Calendar.HOUR_OF_DAY)
- startCal.get(Calendar.HOUR_OF_DAY);
// ... to the right minute
dur *= MINUTES_PER_HOUR; // hours -> minutes
dur += endCal.get(Calendar.MINUTE) - startCal.get(Calendar.MINUTE);
// ... and second
dur *= SECONDS_PER_MINUTE; // minutes -> seconds
dur += endCal.get(Calendar.SECOND) - startCal.get(Calendar.SECOND);
// Now unwind our units
seconds = dur % SECONDS_PER_MINUTE;
dur = dur / SECONDS_PER_MINUTE; // seconds -> minutes (drop remainder seconds)
minutes = dur % MINUTES_PER_HOUR;
dur /= MINUTES_PER_HOUR; // minutes -> hours (drop remainder minutes)
hours = dur % HOURS_PER_DAY;
dur /= HOURS_PER_DAY; // hours -> days (drop remainder hours)
days = dur;
weeks = 0;
// Special case for week-only representation
if (seconds == 0 && minutes == 0 && hours == 0
&& (days % DAYS_PER_WEEK) == 0) {
weeks = days / DAYS_PER_WEEK;
days = 0;
}
}
/**
* Returns a date representing the end of this duration from the specified start date.
* @param start the date to start the duration
* @return the end of the duration as a date
*/
public final Date getTime(final Date start) {
final Calendar cal;
if (start instanceof net.fortuna.ical4j.model.Date) {
cal = Dates.getCalendarInstance((net.fortuna.ical4j.model.Date)start);
} else {
cal = Calendar.getInstance();
}
cal.setTime(start);
if (isNegative()) {
cal.add(Calendar.WEEK_OF_YEAR, -weeks);
cal.add(Calendar.DAY_OF_WEEK, -days);
cal.add(Calendar.HOUR_OF_DAY, -hours);
cal.add(Calendar.MINUTE, -minutes);
cal.add(Calendar.SECOND, -seconds);
}
else {
cal.add(Calendar.WEEK_OF_YEAR, weeks);
cal.add(Calendar.DAY_OF_WEEK, days);
cal.add(Calendar.HOUR_OF_DAY, hours);
cal.add(Calendar.MINUTE, minutes);
cal.add(Calendar.SECOND, seconds);
}
return cal.getTime();
}
/**
* Provides a negation of this instance.
* @return a Dur instance that represents a negation of this instance
*/
public final Dur negate() {
final Dur negated = new Dur(days, hours, minutes, seconds);
negated.weeks = weeks;
negated.negative = !negative;
return negated;
}
/**
* Add two durations. Durations may only be added if they are both positive
* or both negative durations.
* @param duration the duration to add to this duration
* @return a new instance representing the sum of the two durations.
*/
public final Dur add(final Dur duration) {
if ((!isNegative() && duration.isNegative())
|| (isNegative() && !duration.isNegative())) {
throw new IllegalArgumentException(
"Cannot add a negative and a positive duration");
}
Dur sum;
if (weeks > 0 && duration.weeks > 0) {
sum = new Dur(weeks + duration.weeks);
}
else {
int daySum = (weeks > 0) ? weeks * DAYS_PER_WEEK + days : days;
int hourSum = hours;
int minuteSum = minutes;
int secondSum = seconds;
if ((secondSum + duration.seconds) / SECONDS_PER_MINUTE > 0) {
minuteSum += (secondSum + duration.seconds) / SECONDS_PER_MINUTE;
secondSum = (secondSum + duration.seconds) % SECONDS_PER_MINUTE;
}
else {
secondSum += duration.seconds;
}
if ((minuteSum + duration.minutes) / MINUTES_PER_HOUR > 0) {
hourSum += (minuteSum + duration.minutes) / MINUTES_PER_HOUR;
minuteSum = (minuteSum + duration.minutes) % MINUTES_PER_HOUR;
}
else {
minuteSum += duration.minutes;
}
if ((hourSum + duration.hours) / HOURS_PER_DAY > 0) {
daySum += (hourSum + duration.hours) / HOURS_PER_DAY;
hourSum = (hourSum + duration.hours) % HOURS_PER_DAY;
}
else {
hourSum += duration.hours;
}
daySum += (duration.weeks > 0) ? duration.weeks * DAYS_PER_WEEK
+ duration.days : duration.days;
sum = new Dur(daySum, hourSum, minuteSum, secondSum);
}
sum.negative = negative;
return sum;
}
/**
* {@inheritDoc}
*/
public final String toString() {
final StringBuilder b = new StringBuilder();
if (negative) {
b.append('-');
}
b.append('P');
if (weeks > 0) {
b.append(weeks);
b.append('W');
}
else {
if (days > 0) {
b.append(days);
b.append('D');
}
if (hours > 0 || minutes > 0 || seconds > 0) {
b.append('T');
if (hours > 0) {
b.append(hours);
b.append('H');
}
if (minutes > 0) {
b.append(minutes);
b.append('M');
}
if (seconds > 0) {
b.append(seconds);
b.append('S');
}
}
// handle case of zero length duration
if ((hours + minutes + seconds + days + weeks) == 0) {
b.append("T0S");
}
}
return b.toString();
}
/**
* Compares this duration with another, acording to their length.
* @param arg0 another duration instance
* @return a postive value if this duration is longer, zero if the duration
* lengths are equal, otherwise a negative value
*/
public final int compareTo(final Dur arg0) {
int result;
if (isNegative() != arg0.isNegative()) {
// return Boolean.valueOf(isNegative()).compareTo(Boolean.valueOf(arg0.isNegative()));
// for pre-java 1.5 compatibility..
if (isNegative()) {
return Integer.MIN_VALUE;
}
else {
return Integer.MAX_VALUE;
}
}
else if (getWeeks() != arg0.getWeeks()) {
result = getWeeks() - arg0.getWeeks();
}
else if (getDays() != arg0.getDays()) {
result = getDays() - arg0.getDays();
}
else if (getHours() != arg0.getHours()) {
result = getHours() - arg0.getHours();
}
else if (getMinutes() != arg0.getMinutes()) {
result = getMinutes() - arg0.getMinutes();
}
else {
result = getSeconds() - arg0.getSeconds();
}
// invert sense of all tests if both durations are negative
if (isNegative()) {
return -result;
}
else {
return result;
}
}
/**
* {@inheritDoc}
*/
public boolean equals(final Object obj) {
if (obj instanceof Dur) {
return ((Dur) obj).compareTo(this) == 0;
}
return super.equals(obj);
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return new HashCodeBuilder().append(weeks).append(days).append(
hours).append(minutes).append(seconds).append(negative).toHashCode();
}
/**
* @return Returns the days.
*/
public final int getDays() {
return days;
}
/**
* @return Returns the hours.
*/
public final int getHours() {
return hours;
}
/**
* @return Returns the minutes.
*/
public final int getMinutes() {
return minutes;
}
/**
* @return Returns the negative.
*/
public final boolean isNegative() {
return negative;
}
/**
* @return Returns the seconds.
*/
public final int getSeconds() {
return seconds;
}
/**
* @return Returns the weeks.
*/
public final int getWeeks() {
return weeks;
}
/**
* @param stream
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(final java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
}
}
|
package net.imagej.ops.fopd;
import net.imagej.ops.OpMatchingService;
import net.imagej.ops.OpService;
import net.imglib2.img.ImagePlusAdapter;
import net.imglib2.img.Img;
import net.imglib2.img.display.imagej.ImageJFunctions;
import net.imglib2.type.numeric.real.FloatType;
import org.scijava.Context;
import org.scijava.cache.CacheService;
import org.scijava.plugin.Parameter;
import ij.IJ;
/**
*
* @author Tim-Oliver Buchholz, University of Konstanz
*
*/
public class Examples {
@Parameter
private OpService ops;
public static void main(String[] args) {
Examples ex = new Examples();
final int numIts = 100;
ImageJFunctions.show(ex.getNoisyImg());
ImageJFunctions.show(ex.denoisingL1TV2D(ex.getNoisyImg(), numIts));
ImageJFunctions.show(ex.denoisingL1TVHuber2D(ex.getNoisyImg(), numIts));
ImageJFunctions.show(ex.denoisingL1TGV2D(ex.getNoisyImg(), numIts));
ImageJFunctions.show(ex.getConvolvedImg());
ImageJFunctions.show(ex.deconvolutionL1TV2D(ex.getConvolvedImg(), ex.getKernel(), numIts));
ImageJFunctions.show(ex.deconvolutionL1TVHuber2D(ex.getConvolvedImg(), ex.getKernel(), numIts));
ImageJFunctions.show(ex.deconvolutionL1TGV2D(ex.getConvolvedImg(), ex.getKernel(), numIts));
}
public Examples() {
Context context = new Context(OpService.class, OpMatchingService.class, CacheService.class);
context.inject(this);
}
private Img<FloatType> getNoisyImg() {
return ImagePlusAdapter.wrap(IJ.openImage(this.getClass().getResource("2D_noise.tif").getPath()));
}
private Img<FloatType> getConvolvedImg() {
return ImagePlusAdapter.wrap(IJ.openImage(this.getClass().getResource("2D_convolved.tif").getPath()));
}
private Img<FloatType> getKernel() {
return ImagePlusAdapter.wrap(IJ.openImage(this.getClass().getResource("2D_kernel.tif").getPath()));
}
@SuppressWarnings("unchecked")
private Img<FloatType> denoisingL1TV2D(final Img<FloatType> img, final int numIts) {
long t = System.currentTimeMillis();
final Img<FloatType> result = (Img<FloatType>) ops.run(TVL1Denoising.class, img, 2, numIts);
t = System.currentTimeMillis() - t;
System.out
.println("TVL1-Denoising [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec");
System.out.println("Time/Iteration: " + (double) t / numIts + "millisec");
return result;
}
@SuppressWarnings("unchecked")
private Img<FloatType> denoisingL1TVHuber2D(final Img<FloatType> img, final int numIts) {
long t = System.currentTimeMillis();
final Img<FloatType> result = (Img<FloatType>) ops.run(TVHuberL1Denoising.class, img, 2, 0.02, numIts);
t = System.currentTimeMillis() - t;
System.out.println(
"TVHuberL1-Denoising [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec");
System.out.println("Time/Iteration: " + (double) t / numIts + "millisec");
return result;
}
@SuppressWarnings("unchecked")
private Img<FloatType> denoisingL1TGV2D(final Img<FloatType> img, final int numIts) {
long t = System.currentTimeMillis();
final Img<FloatType> result = (Img<FloatType>) ops.run(TGVL1Denoising.class, img, 1.0, 2.0, numIts);
t = System.currentTimeMillis() - t;
System.out.println(
"TGVL1-Denoising [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec");
System.out.println("Time/Iteration: " + (double) t / numIts + "millisec");
return result;
}
@SuppressWarnings("unchecked")
private Img<FloatType> deconvolutionL1TV2D(final Img<FloatType> img, final Img<FloatType> kernel,
final int numIts) {
long t = System.currentTimeMillis();
final Img<FloatType> result = (Img<FloatType>) ops.run(TVL1Deconvolution.class, img, kernel, 0.08, numIts);
t = System.currentTimeMillis() - t;
System.out.println(
"TVL1-Deconvolution [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec");
System.out.println("Time/Iteration: " + (double) t / numIts + "millisec");
return result;
}
@SuppressWarnings("unchecked")
private Img<FloatType> deconvolutionL1TVHuber2D(final Img<FloatType> img, final Img<FloatType> kernel,
final int numIts) {
long t = System.currentTimeMillis();
final Img<FloatType> result = (Img<FloatType>) ops.run(TVHuberL1Deconvolution.class, img, kernel, 0.1, 0.05,
numIts);
t = System.currentTimeMillis() - t;
System.out.println(
"TVHuberL1-Deconvolution [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec");
System.out.println("Time/Iteration: " + (double) t / numIts + "millisec");
return result;
}
@SuppressWarnings("unchecked")
private Img<FloatType> deconvolutionL1TGV2D(final Img<FloatType> img, final Img<FloatType> kernel,
final int numIts) {
long t = System.currentTimeMillis();
final Img<FloatType> result = (Img<FloatType>) ops.run(TGVL1Deconvolution.class, img, kernel, 0.1, 0.2, numIts);
t = System.currentTimeMillis() - t;
System.out.println(
"TGVL1-Deconvolution [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec");
System.out.println("Time/Iteration: " + (double) t / numIts + "millisec");
return result;
}
}
|
package org.broad.igv.ui;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.track.TrackType;
import java.awt.*;
/**
* @author jrobinso
*/
public class UIConstants {
private static Logger log = Logger.getLogger(UIConstants.class);
final public static String APPLICATION_NAME = "IGV";
final public static int groupGap = 10;
final public static Dimension preferredSize = new Dimension(1000, 750);
// To support mutation track overlay. Generalize later. Cancer specific option.
public static TrackType overlayTrackType = TrackType.MUTATION;
private static int doubleClickInterval = -1;
// Menu tooltips
static final public String LOAD_TRACKS_TOOLTIP = "Load tracks or sample information";
static final public String LOAD_SERVER_DATA_TOOLTIP = "Load tracks or sample information from a server";
static final public String SAVE_IMAGE_TOOLTIP = "Capture and save an image";
static final public String NEW_SESSION_TOOLTIP = "Create a new session";
static final public String SAVE_SESSION_TOOLTIP = "Save the current session";
static final public String OPEN_SESSION_TOOLTIP = "Load a session";
static final public String RELOAD_SESSION_TOOLTIP = "Reload the current session";
static final public String EXIT_TOOLTIP = "Exit the application";
static final public String IMPORT_GENOME_TOOLTIP = "Create a .genome file";
static final public String REMOVE_IMPORTED_GENOME_TOOLTIP = "Removes user-defined genomes from the drop-down list";
static final public String CLEAR_GENOME_CACHE_TOOLTIP = "Clears locally cached versions of IGV hosted genomes";
static final public String SELECT_DISPLAYABLE_ATTRIBUTES_TOOLTIP =
"Customize attribute display to show only checked attributes";
static final public String SORT_TRACKS_TOOLTIP = "Sort tracks by attribute value";
static final public String GROUP_TRACKS_TOOLTIP = "Group tracks by attribute value";
static final public String OVERLAY_TRACKS_TOOLTIP = "Overlay data (wig) tracks by attribute value";
static final public String RENAME_TRACKS_TOOLTIP = "Rename tracks by attribute value";
static final public String FILTER_TRACKS_TOOLTIP = "Filter tracks by attribute value";
static final public String SET_DEFAULT_TRACK_HEIGHT_TOOLTIP = "Set the height for all tracks";
static final public String FIT_DATA_TO_WINDOW_TOOLTIP =
"Resize track heights to make best use of vertical space without scrolling";
static final public String EXPORT_REGION_TOOLTIP = "Save all defined regions to a file";
static final public String IMPORT_REGION_TOOLTIP = "Load regions from a file";
static final public String HELP_TOOLTIP = "Open web help page";
static final public String ABOUT_TOOLTIP = "Display application information";
static final public String RESET_FACTORY_TOOLTIP = "Restores all user preferences to their default settings.";
public static final String REGION_NAVIGATOR_TOOLTIP = "Navigate regions";
static final public String CLICK_ITEM_TO_EDIT_TOOLTIP = "Click this item bring up its editor";
static final public String CHANGE_GENOME_TOOLTIP = "Switch the current genome";
static final public String PREFERENCE_TOOLTIP = "Set user specific preferences";
static final public String SHOW_HEATMAP_LEGEND_TOOLTIP = "Edit color legends and scales";
final public static String OVERWRITE_SESSION_MESSAGE =
"<html>Opening a session will unload all current data. " + "<br>Are you sure you wish to continue?";
final public static String CANNOT_ACCESS_SERVER_GENOME_LIST = "The Genome server is currently inaccessible.";
final public static int NUMBER_OF_RECENT_SESSIONS_TO_LIST = 3;
final public static String DEFAULT_SESSION_FILE = "igv_session" + Globals.SESSION_FILE_EXTENSION;
static final public String SERVER_BASE_URL = "http:
static final public Color LIGHT_YELLOW = new Color(255, 244, 201);
final public static Color LIGHT_GREY = new Color(238, 239, 240);
final public static Color TRACK_BORDER_GRAY = new Color(240, 240, 240);
static final public String REMOVE_GENOME_LIST_MENU_ITEM = "Remove Imported Genomes...";
static final public String GENOME_LIST_SEPARATOR = "--SEPARATOR
static final public int DEFAULT_DOUBLE_CLICK_INTERVAL = 400;
public static int getDoubleClickInterval() {
// if (doubleClickInterval < 0) {
// Number obj = (Number) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
// if (obj != null) {
// doubleClickInterval = obj.intValue();
// } else {
doubleClickInterval = DEFAULT_DOUBLE_CLICK_INTERVAL;
return doubleClickInterval;
}
}
|
package org.dungeon.debug;
import static org.dungeon.date.DungeonTimeUnit.DAY;
import static org.dungeon.date.DungeonTimeUnit.SECOND;
import org.dungeon.achievements.Achievement;
import org.dungeon.achievements.AchievementTracker;
import org.dungeon.commands.Command;
import org.dungeon.commands.IssuedCommand;
import org.dungeon.date.Date;
import org.dungeon.entity.creatures.Creature;
import org.dungeon.entity.creatures.CreatureFactory;
import org.dungeon.entity.items.CreatureInventory.SimulationResult;
import org.dungeon.entity.items.Item;
import org.dungeon.entity.items.ItemFactory;
import org.dungeon.game.Engine;
import org.dungeon.game.Game;
import org.dungeon.game.GameData;
import org.dungeon.game.GameState;
import org.dungeon.game.ID;
import org.dungeon.game.Location;
import org.dungeon.game.LocationPreset;
import org.dungeon.game.PartOfDay;
import org.dungeon.game.Point;
import org.dungeon.io.IO;
import org.dungeon.map.WorldMap;
import org.dungeon.map.WorldMapWriter;
import org.dungeon.stats.CauseOfDeath;
import org.dungeon.stats.ExplorationStatistics;
import org.dungeon.util.CounterMap;
import org.dungeon.util.Matches;
import org.dungeon.util.Messenger;
import org.dungeon.util.Table;
import org.dungeon.util.Utils;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* A set of debugging tools.
*/
public class DebugTools {
private static final List<Command> commands = new ArrayList<Command>();
private static boolean uninitialized = true;
/**
* Parses an IssuedCommand and executes the corresponding debugging Command if there is one.
*
* @param issuedCommand the last command issued by the player
*/
public static void parseDebugCommand(IssuedCommand issuedCommand) {
if (issuedCommand.hasArguments()) {
if (uninitialized) {
initialize();
}
for (Command command : commands) {
if (issuedCommand.firstArgumentEquals(command.getDescription().getName())) {
command.execute(issuedCommand);
return;
}
}
IO.writeString("Command not recognized.");
} else {
Messenger.printMissingArgumentsMessage();
}
}
/**
* Creates all debugging Commands.
* <p/>
* This method also sets {@code uninitialized} to false.
*/
private static void initialize() {
commands.add(new Command("achievements") {
@Override
public void execute(@NotNull IssuedCommand issuedCommand) {
printNotYetUnlockedAchievements();
}
});
commands.add(new Command("exploration") {
@Override
public void execute(@NotNull IssuedCommand issuedCommand) {
printExplorationStatistics();
}
});
commands.add(new Command("kills") {
@Override
public void execute(@NotNull IssuedCommand issuedCommand) {
printKills();
}
});
commands.add(new Command("location") {
@Override
public void execute(@NotNull IssuedCommand issuedCommand) {
printCurrentLocationInformation();
}
});
commands.add(new Command("map") {
@Override
public void execute(@NotNull IssuedCommand issuedCommand) {
WorldMapWriter.writeMap(WorldMap.makeDebugWorldMap());
}
});
commands.add(new Command("list") {
@Override
public void execute(@NotNull IssuedCommand issuedCommand) {
listAllArguments();
}
});
commands.add(new Command("give") {
@Override
public void execute(@NotNull IssuedCommand issuedCommand) {
if (issuedCommand.getTokenCount() >= 3) {
give(issuedCommand.getArguments()[1]);
} else {
Messenger.printMissingArgumentsMessage();
}
}
});
commands.add(new Command("saved") {
@Override
public void execute(@NotNull IssuedCommand issuedCommand) {
printIsSaved();
}
});
commands.add(new Command("spawn") {
@Override
public void execute(@NotNull IssuedCommand issuedCommand) {
spawn(issuedCommand);
}
});
commands.add(new Command("tomorrow") {
@Override
public void execute(@NotNull IssuedCommand issuedCommand) {
Engine.rollDateAndRefresh((int) DAY.as(SECOND));
IO.writeString("A day has passed.");
}
});
commands.add(new Command("time") {
@Override
public void execute(@NotNull IssuedCommand issuedCommand) {
printTime();
}
});
commands.add(new Command("wait") {
@Override
public void execute(@NotNull IssuedCommand issuedCommand) {
DebugTools.wait(issuedCommand);
}
});
uninitialized = false;
}
private static void printKills() {
CounterMap<CauseOfDeath> map = Game.getGameState().getStatistics().getBattleStatistics().getKillsByCauseOfDeath();
if (map.isNotEmpty()) {
Table table = new Table("Type", "Count");
for (CauseOfDeath causeOfDeath : map.keySet()) {
table.insertRow(causeOfDeath.toString(), String.valueOf(map.getCounter(causeOfDeath)));
}
table.print();
} else {
IO.writeString("You haven't killed anything yet. Go kill something!");
}
}
private static void printNotYetUnlockedAchievements() {
AchievementTracker tracker = Game.getGameState().getHero().getAchievementTracker();
List<Achievement> achievementList = new ArrayList<Achievement>();
for (Achievement achievement : GameData.ACHIEVEMENTS.values()) {
if (!tracker.isUnlocked(achievement)) {
achievementList.add(achievement);
}
}
if (achievementList.isEmpty()) {
IO.writeString("All achievements have been unlocked.");
} else {
Collections.sort(achievementList);
for (Achievement achievement : achievementList) {
IO.writeString(String.format("%s : %s", achievement.getName(), achievement.getInfo()));
}
}
}
private static void printExplorationStatistics() {
ExplorationStatistics explorationStatistics = Game.getGameState().getStatistics().getExplorationStatistics();
Table table = new Table("Name", "Kills", "Visited so far", "Maximum number of visits");
for (LocationPreset preset : GameData.getLocationPresetStore().getAllPresets()) {
String name = preset.getName().getSingular();
String kills = String.valueOf(explorationStatistics.getKillCount(preset.getID()));
String VisitedSoFar = String.valueOf(explorationStatistics.getVisitedLocations(preset.getID()));
String maximumNumberOfVisits = String.valueOf(explorationStatistics.getMaximumNumberOfVisits(preset.getID()));
table.insertRow(name, kills, VisitedSoFar, maximumNumberOfVisits);
}
table.print();
}
/**
* Prints a lot of information about the Location the Hero is in.
*/
private static void printCurrentLocationInformation() {
final int WIDTH = 40; // The width of the row's "tag".
GameState gameState = Game.getGameState();
Point heroPosition = gameState.getHeroPosition();
Location location = gameState.getWorld().getLocation(heroPosition);
StringBuilder sb = new StringBuilder();
sb.append(Utils.padString("Point:", WIDTH)).append(heroPosition.toString()).append('\n');
sb.append(Utils.padString("Creatures (" + location.getCreatureCount() + "):", WIDTH)).append('\n');
for (Creature creature : location.getCreatures()) {
sb.append(Utils.padString(" " + creature.getName(), WIDTH));
sb.append(creature.getVisibility().toPercentage()).append('\n');
}
if (!location.getItemList().isEmpty()) {
sb.append(Utils.padString("Items (" + location.getItemList().size() + "):", WIDTH)).append('\n');
for (Item item : location.getItemList()) {
sb.append(Utils.padString(" " + item.getQualifiedName(), WIDTH));
sb.append(item.getVisibility().toPercentage()).append('\n');
}
} else {
sb.append("No items.\n");
}
sb.append(Utils.padString("Luminosity:", WIDTH)).append(location.getLuminosity().toPercentage()).append('\n');
sb.append(Utils.padString("Permittivity:", WIDTH)).append(location.getLightPermittivity()).append('\n');
sb.append(Utils.padString("Blocked Entrances:", WIDTH)).append(location.getBlockedEntrances()).append('\n');
IO.writeString(sb.toString());
}
/**
* Attempts to give an Item to the Hero.
*
* @param itemID the ID of the Item, as provided by the player
*/
private static void give(String itemID) {
Date date = Game.getGameState().getWorld().getWorldDate();
Item item = ItemFactory.makeItem(new ID(itemID.toUpperCase()), date);
if (item != null) {
IO.writeString("Item successfully created.");
if (Game.getGameState().getHero().getInventory().simulateItemAddition(item) == SimulationResult.SUCCESSFUL) {
Game.getGameState().getHero().addItem(item);
} else {
Game.getGameState().getHeroLocation().addItem(item);
IO.writeString("Item could not be added to your inventory. It was added to the current location instead.");
}
Engine.refresh(); // Set the game state to unsaved after adding an item to the world.
} else {
IO.writeString("Item could not be created.");
}
}
private static void listAllArguments() {
StringBuilder builder = new StringBuilder();
builder.append("Valid commands:");
for (Command command : commands) {
builder.append("\n ").append(command.getDescription().getName());
}
IO.writeString(builder.toString());
}
/**
* Spawns the specified creatures in the Location the Hero is in.
*/
private static void spawn(IssuedCommand issuedCommand) {
if (issuedCommand.getTokenCount() >= 3) {
for (int i = 1; i < issuedCommand.getArguments().length; i++) {
ID givenID = new ID(issuedCommand.getArguments()[i].toUpperCase());
Creature clone = CreatureFactory.makeCreature(givenID);
if (clone != null) {
Game.getGameState().getHeroLocation().addCreature(clone);
IO.writeString("Spawned a " + clone.getName() + ".");
Engine.refresh(); // Set the game state to unsaved after adding a creature to the world.
} else {
IO.writeString(givenID + " does not match any known creature.");
}
}
} else {
Messenger.printMissingArgumentsMessage();
}
}
private static void printIsSaved() {
if (Game.getGameState().isSaved()) {
IO.writeString("The game is saved.");
} else {
IO.writeString("This game state is not saved.");
}
}
private static void wait(IssuedCommand issuedCommand) {
if (issuedCommand.getTokenCount() >= 3) {
int seconds = 0;
boolean gotSeconds = false;
String argument = issuedCommand.getArguments()[1];
Matches<PartOfDay> matches = Utils.findBestCompleteMatches(Arrays.asList(PartOfDay.values()), argument);
if (matches.size() == 1) {
seconds = PartOfDay.getSecondsToNext(Game.getGameState().getWorld().getWorldDate(), matches.getMatch(0));
gotSeconds = true;
} else if (matches.size() > 1) {
Messenger.printAmbiguousSelectionMessage();
} else {
try {
seconds = Integer.parseInt(argument);
gotSeconds = true;
} catch (NumberFormatException warn) {
Messenger.printInvalidNumberFormatOrValue();
}
}
if (gotSeconds) {
if (seconds > 0) {
Engine.rollDateAndRefresh(seconds);
IO.writeString("Waited for " + seconds + " seconds.");
} else {
IO.writeString("The amount of seconds should be positive!");
}
}
} else {
Messenger.printMissingArgumentsMessage();
}
}
private static void printTime() {
IO.writeString(Game.getGameState().getWorld().getWorldDate().toTimeString());
}
}
|
package org.dynmap.hdmap;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import javax.imageio.ImageIO;
import org.dynmap.Color;
import org.dynmap.ConfigurationNode;
import org.dynmap.DynmapCore;
import org.dynmap.Log;
import org.dynmap.MapManager;
import org.dynmap.common.BiomeMap;
import org.dynmap.exporter.OBJExport;
import org.dynmap.renderer.CustomColorMultiplier;
import org.dynmap.utils.BlockStep;
import org.dynmap.utils.BufferOutputStream;
import org.dynmap.utils.DynIntHashMap;
import org.dynmap.utils.DynmapBufferedImage;
import org.dynmap.utils.ForgeConfigFile;
import org.dynmap.utils.MapIterator;
/**
* Loader and processor class for minecraft texture packs
* Texture packs are found in dynmap/texturepacks directory, and either are either ZIP files
* or are directories whose content matches the structure of a zipped texture pack:
* ./terrain.png - main color data (required)
* misc/grasscolor.png - tone for grass color, biome sensitive (required)
* misc/foliagecolor.png - tone for leaf color, biome sensitive (required)
* custom_lava_still.png - custom still lava animation (optional)
* custom_lava_flowing.png - custom flowing lava animation (optional)
* custom_water_still.png - custom still water animation (optional)
* custom_water_flowing.png - custom flowing water animation (optional)
* misc/watercolorX.png - custom water color multiplier (optional)
* misc/swampgrasscolor.png - tone for grass color in swamps (optional)
* misc/swampfoliagecolor.png - tone for leaf color in swamps (optional)
*/
public class TexturePack {
/* Loaded texture packs */
private static HashMap<String, TexturePack> packs = new HashMap<String, TexturePack>();
private static Object packlock = new Object();
private static final String TERRAIN_PNG = "terrain.png";
private static final String GRASSCOLOR_PNG = "misc/grasscolor.png";
private static final String GRASSCOLOR_RP_PNG = "assets/minecraft/textures/colormap/grass.png";
private static final String FOLIAGECOLOR_PNG = "misc/foliagecolor.png";
private static final String FOLIAGECOLOR_RP_PNG = "assets/minecraft/textures/colormap/foliage.png";
private static final String WATERCOLORX_PNG = "misc/watercolorX.png";
private static final String WATERCOLORX_RP_PNG = "assets/minecraft/mcpatcher/colormap/watercolorX.png";
private static final String WATERCOLORX2_RP_PNG = "assets/minecraft/mcpatcher/colormap/water.png";
private static final String CUSTOMLAVASTILL_PNG = "custom_lava_still.png";
private static final String CUSTOMLAVAFLOWING_PNG = "custom_lava_flowing.png";
private static final String CUSTOMWATERSTILL_PNG = "custom_water_still.png";
private static final String CUSTOMWATERFLOWING_PNG = "custom_water_flowing.png";
private static final String SWAMPGRASSCOLOR_PNG = "misc/swampgrasscolor.png";
private static final String SWAMPGRASSCOLOR_RP_PNG = "assets/minecraft/mcpatcher/colormap/swampgrass.png";
private static final String SWAMPFOLIAGECOLOR_PNG = "misc/swampfoliagecolor.png";
private static final String SWAMPFOLIAGECOLOR_RP_PNG = "assets/minecraft/mcpatcher/colormap/swampfoliage.png";
private static final String PINECOLOR_PNG = "misc/pinecolor.png";
private static final String PINECOLOR_RP_PNG = "assets/minecraft/mcpatcher/colormap/pine.png";
private static final String BIRCHCOLOR_PNG = "misc/birchcolor.png";
private static final String BIRCHCOLOR_RP_PNG = "assets/minecraft/mcpatcher/colormap/birch.png";
/* Color modifier codes (x1000 for value in definition file, x1000000 for internal value) */
//private static final int COLORMOD_NONE = 0;
public static final int COLORMOD_GRASSTONED = 1;
public static final int COLORMOD_FOLIAGETONED = 2;
public static final int COLORMOD_WATERTONED = 3;
public static final int COLORMOD_ROT90 = 4;
public static final int COLORMOD_ROT180 = 5;
public static final int COLORMOD_ROT270 = 6;
public static final int COLORMOD_FLIPHORIZ = 7;
public static final int COLORMOD_SHIFTDOWNHALF = 8;
public static final int COLORMOD_SHIFTDOWNHALFANDFLIPHORIZ = 9;
public static final int COLORMOD_INCLINEDTORCH = 10;
public static final int COLORMOD_GRASSSIDE = 11;
public static final int COLORMOD_CLEARINSIDE = 12;
public static final int COLORMOD_PINETONED = 13;
public static final int COLORMOD_BIRCHTONED = 14;
public static final int COLORMOD_LILYTONED = 15;
//private static final int COLORMOD_OLD_WATERSHADED = 16;
public static final int COLORMOD_MULTTONED = 17; /* Toned with colorMult or custColorMult - not biome-style */
public static final int COLORMOD_GRASSTONED270 = 18; // GRASSTONED + ROT270
public static final int COLORMOD_FOLIAGETONED270 = 19; // FOLIAGETONED + ROT270
public static final int COLORMOD_WATERTONED270 = 20; // WATERTONED + ROT270
public static final int COLORMOD_MULTTONED_CLEARINSIDE = 21; // MULTTONED + CLEARINSIDE
public static final int COLORMOD_FOLIAGEMULTTONED = 22; // FOLIAGETONED + colorMult or custColorMult
private static final int COLORMOD_MULT_FILE = 1000;
private static final int COLORMOD_MULT_INTERNAL = 1000000;
/* Special tile index values */
private static final int TILEINDEX_BLANK = -1;
private static final int TILEINDEX_GRASS = 0;
private static final int TILEINDEX_GRASSMASK = 38;
private static final int TILEINDEX_SNOW = 66;
private static final int TILEINDEX_SNOWSIDE = 68;
private static final int TILEINDEX_PISTONSIDE = 108;
private static final int TILEINDEX_GLASSPANETOP = 148;
private static final int TILEINDEX_AIRFRAME = 158;
private static final int TILEINDEX_REDSTONE_NSEW_TONE = 164;
private static final int TILEINDEX_REDSTONE_EW_TONE = 165;
private static final int TILEINDEX_EYEOFENDER = 174;
private static final int TILEINDEX_REDSTONE_NSEW = 180;
private static final int TILEINDEX_REDSTONE_EW = 181;
private static final int TILEINDEX_STATIONARYWATER = 257;
private static final int TILEINDEX_MOVINGWATER = 258;
private static final int TILEINDEX_STATIONARYLAVA = 259;
private static final int TILEINDEX_MOVINGLAVA = 260;
private static final int TILEINDEX_PISTONEXTSIDE = 261;
private static final int TILEINDEX_PISTONSIDE_EXT = 262;
private static final int TILEINDEX_PANETOP_X = 263;
private static final int TILEINDEX_AIRFRAME_EYE = 264;
private static final int TILEINDEX_WHITE = 267; // Pure white tile
private static final int MAX_TILEINDEX = 267; /* Index of last static tile definition */
/* Indexes of faces in a CHEST format tile file */
private static final int TILEINDEX_CHEST_TOP = 0;
private static final int TILEINDEX_CHEST_LEFT = 1;
private static final int TILEINDEX_CHEST_RIGHT = 2;
private static final int TILEINDEX_CHEST_FRONT = 3;
private static final int TILEINDEX_CHEST_BACK = 4;
private static final int TILEINDEX_CHEST_BOTTOM = 5;
private static final int TILEINDEX_CHEST_COUNT = 6;
/* Indexes of faces in a BIGCHEST format tile file */
private static final int TILEINDEX_BIGCHEST_TOPLEFT = 0;
private static final int TILEINDEX_BIGCHEST_TOPRIGHT = 1;
private static final int TILEINDEX_BIGCHEST_FRONTLEFT = 2;
private static final int TILEINDEX_BIGCHEST_FRONTRIGHT = 3;
private static final int TILEINDEX_BIGCHEST_LEFT = 4;
private static final int TILEINDEX_BIGCHEST_RIGHT = 5;
private static final int TILEINDEX_BIGCHEST_BACKLEFT = 6;
private static final int TILEINDEX_BIGCHEST_BACKRIGHT = 7;
private static final int TILEINDEX_BIGCHEST_BOTTOMLEFT = 8;
private static final int TILEINDEX_BIGCHEST_BOTTOMRIGHT = 9;
private static final int TILEINDEX_BIGCHEST_COUNT = 10;
/* Indexes of faces in the SIGN format tile file */
private static final int TILEINDEX_SIGN_FRONT = 0;
private static final int TILEINDEX_SIGN_BACK = 1;
private static final int TILEINDEX_SIGN_TOP = 2;
private static final int TILEINDEX_SIGN_BOTTOM = 3;
private static final int TILEINDEX_SIGN_LEFTSIDE = 4;
private static final int TILEINDEX_SIGN_RIGHTSIDE = 5;
private static final int TILEINDEX_SIGN_POSTFRONT = 6;
private static final int TILEINDEX_SIGN_POSTBACK = 7;
private static final int TILEINDEX_SIGN_POSTLEFT = 8;
private static final int TILEINDEX_SIGN_POSTRIGHT = 9;
private static final int TILEINDEX_SIGN_COUNT = 10;
/* Indexes of faces in the SKIN format tile file */
private static final int TILEINDEX_SKIN_FACEFRONT = 0;
private static final int TILEINDEX_SKIN_FACELEFT = 1;
private static final int TILEINDEX_SKIN_FACERIGHT = 2;
private static final int TILEINDEX_SKIN_FACEBACK = 3;
private static final int TILEINDEX_SKIN_FACETOP = 4;
private static final int TILEINDEX_SKIN_FACEBOTTOM = 5;
private static final int TILEINDEX_SKIN_COUNT = 6;
private static final int BLOCKTABLELEN = 4096; // Max block ID range
public static enum TileFileFormat {
GRID,
CHEST,
BIGCHEST,
SIGN,
SKIN,
CUSTOM,
TILESET,
BIOME
};
// Material type: used for setting advanced rendering/export characteristics for image in given file
// (e.g. reflective surfaces, index of refraction, etc)
public static enum MaterialType {
GLASS(1.5, 200, 3), // Glass material: Ni=1.5, Ns=100, illum=3
WATER(1.33, 100, 3); // Water material: Ni=1.33, Ns=95, illum=3
public final double Ni;
public final double Ns;
public final int illum;
MaterialType(double Ni, double Ns, int illum) {
this.Ni = Ni;
this.Ns = Ns;
this.illum = illum;
}
}
/* Map of 1.5 texture files to 0-255 texture indices */
private static final String[] terrain_map = {
"grass_top", "stone", "dirt", "grass_side", "wood", "stoneslab_side", "stoneslab_top", "brick",
"tnt_side", "tnt_top", "tnt_bottom", "web", "rose", "flower", "portal", "sapling",
"stonebrick", "bedrock", "sand", "gravel", "tree_side", "tree_top", "blockIron", "blockGold",
"blockDiamond", "blockEmerald", null, null, "mushroom_red", "mushroom_brown", "sapling_jungle", null,
"oreGold", "oreIron", "oreCoal", "bookshelf", "stoneMoss", "obsidian", "grass_side_overlay", "tallgrass",
null, "beacon", null, "workbench_top", "furnace_front", "furnace_side", "dispenser_front", null,
"sponge", "glass", "oreDiamond", "oreRedstone", "leaves", "leaves_opaque", "stonebricksmooth", "deadbush",
"fern", null, null, "workbench_side", "workbench_front", "furnace_front_lit", "furnace_top", "sapling_spruce",
"cloth_0", "mobSpawner", "snow", "ice", "snow_side", "cactus_top", "cactus_side", "cactus_bottom",
"clay", "reeds", "musicBlock", "jukebox_top", "waterlily", "mycel_side", "mycel_top", "sapling_birch",
"torch", "doorWood_upper", "doorIron_upper", "ladder", "trapdoor", "fenceIron", "farmland_wet", "farmland_dry",
"crops_0", "crops_1", "crops_2", "crops_3", "crops_4", "crops_5", "crops_6", "crops_7",
"lever", "doorWood_lower", "doorIron_lower", "redtorch_lit", "stonebricksmooth_mossy", "stonebricksmooth_cracked", "pumpkin_top", "hellrock",
"hellsand", "lightgem", "piston_top_sticky", "piston_top", "piston_side", "piston_bottom", "piston_inner_top", "stem_straight",
"rail_turn", "cloth_15", "cloth_7", "redtorch", "tree_spruce", "tree_birch", "pumpkin_side", "pumpkin_face",
"pumpkin_jack", "cake_top", "cake_side", "cake_inner", "cake_bottom", "mushroom_skin_red", "mushroom_skin_brown", "stem_bent",
"rail", "cloth_14", "cloth_6", "repeater", "leaves_spruce", "leaves_spruce_opaque", "bed_feet_top", "bed_head_top",
"melon_side", "melon_top", "cauldron_top", "cauldron_inner", null, "mushroom_skin_stem", "mushroom_inside", "vine",
"blockLapis", "cloth_13", "cloth_5", "repeater_lit", "thinglass_top", "bed_feet_end", "bed_feet_side", "bed_head_side",
"bed_head_end", "tree_jungle", "cauldron_side", "cauldron_bottom", "brewingStand_base", "brewingStand", "endframe_top", "endframe_side",
"oreLapis", "cloth_12", "cloth_4", "goldenRail", "redstoneDust_cross", "redstoneDust_line", "enchantment_top", "dragonEgg",
"cocoa_2", "cocoa_1", "cocoa_0", "oreEmerald", "tripWireSource", "tripWire", "endframe_eye", "whiteStone",
"sandstone_top", "cloth_11", "cloth_3", "goldenRail_powered", "redstoneDust_cross_overlay", "redstoneDust_line_overlay", "enchantment_side", "enchantment_bottom",
"commandBlock", "itemframe_back", "flowerPot", null, null, null, null, null,
"sandstone_side", "cloth_10", "cloth_2", "detectorRail", "leaves_jungle", "leaves_jungle_opaque", "wood_spruce", "wood_jungle",
"carrots_0", "carrots_1", "carrots_2", "carrots_3", "potatoes_3", null, null, null,
"sandstone_bottom", "cloth_9", "cloth_1", "redstoneLight", "redstoneLight_lit", "stonebricksmooth_carved", "wood_birch", "anvil_base",
"anvil_top_damaged_1", null, null, null, null, null, null, null,
"netherBrick", "cloth_8", "netherStalk_0", "netherStalk_1", "netherStalk_2", "sandstone_carved", "sandstone_smooth", "anvil_top",
"anvil_top_damaged_2", null, null, null, null, null, null, null,
"destroy_0", "destroy_1", "destroy_2", "destroy_3", "destroy_4", "destroy_5", "destroy_6", "destroy_7",
"destroy_8", "destroy_9", null, null, null, null, null, null,
/* Extra 1.5-based textures: starting at 256 (corresponds to TILEINDEX_ values) */
null, "water", "water_flow", "lava", "lava_flow", null, null, null,
null, "fire_0", "portal"
};
/* Map of 1.6 resource files to 0-255 texture indices */
private static final String[] terrain_rp_map = {
"grass_top", "stone", "dirt", "grass_side", "planks_oak", "stone_slab_side", "stone_slab_top", "brick",
"tnt_side", "tnt_top", "tnt_bottom", "web", "flower_rose", "flower_dandelion", "portal", "sapling_oak",
"cobblestone", "bedrock", "sand", "gravel", "log_oak", "log_oak_top", "iron_block", "gold_block",
"diamond_block", "emerald_block", null, null, "mushroom_red", "mushroom_brown", "sapling_jungle", null,
"gold_ore", "iron_ore", "coal_ore", "bookshelf", "cobblestone_mossy", "obsidian", "grass_side_overlay", "tallgrass",
null, "beacon", null, "crafting_table_top", "furnace_front_off", "furnace_side", "dispenser_front_horizontal", null,
"sponge", "glass", "diamond_ore", "redstone_ore", "leaves_oak", "leaves_oak_opaque", "stonebrick", "deadbush",
"fern", null, null, "crafting_table_side", "crafting_table_front", "furnace_front_on", "furnace_top", "sapling_spruce",
"wool_colored_white", "mob_spawner", "snow", "ice", "grass_side_snowed", "cactus_top", "cactus_side", "cactus_bottom",
"clay", "reeds", "jukebox_side", "jukebox_top", "waterlily", "mycelium_side", "mycelium_top", "sapling_birch",
"torch_on", "door_wood_upper", "door_iron_upper", "ladder", "trapdoor", "iron_bars", "farmland_wet", "farmland_dry",
"wheat_stage_0", "wheat_stage_1", "wheat_stage_2", "wheat_stage_3", "wheat_stage_4", "wheat_stage_5", "wheat_stage_6", "wheat_stage_7",
"lever", "door_wood_lower", "door_iron_lower", "redstone_torch_on", "stonebrick_mossy", "stonebrick_cracked", "pumpkin_top", "netherrack",
"soul_sand", "glowstone", "piston_top_sticky", "piston_top_normal", "piston_side", "piston_bottom", "piston_inner", "pumpkin_stem_disconnected",
"rail_normal_turned", "wool_colored_black", "wool_colored_gray", "redstone_torch_off", "log_spruce", "log_birch", "pumpkin_side", "pumpkin_face_off",
"pumpkin_face_on", "cake_top", "cake_side", "cake_inner", "cake_bottom", "mushroom_block_skin_red", "mushroom_block_skin_brown", "pumpkin_stem_connected",
"rail_normal", "wool_colored_red", "wool_colored_pink", "repeater_off", "leaves_spruce", "leaves_spruce_opaque", "bed_feet_top", "bed_head_top",
"melon_side", "melon_top", "cauldron_top", "cauldron_inner", null, "mushroom_block_skin_stem", "mushroom_block_inside", "vine",
"lapis_block", "wool_colored_green", "wool_colored_lime", "repeater_on", "glass_pane_top", "bed_feet_end", "bed_feet_side", "bed_head_side",
"bed_head_end", "log_jungle", "cauldron_side", "cauldron_bottom", "brewibrewing_stand_base", "brewing_stand", "endframe_top", "endframe_side",
"lapis_ore", "wool_colored_brown", "wool_colored_yellow", "rail_golden", "redstone_dust_cross", "redstone_dust_line", "enchanting_table_top", "dragon_egg",
"cocoa_stage_2", "cocoa_stage_1", "cocoa_stage_0", "emerald_ore", "trip_wire_source", "trip_wire", "endframe_eye", "end_stone",
"sandstone_top", "wool_colored_blue", "wool_colored_light_blue", "rail_golden_powered", "redstone_dust_cross_overlay", "redstone_dust_line_overlay", "enchanting_table_side", "enchanting_table_bottom",
"command_block", "itemframe_background", "flower_pot", null, null, null, null, null,
"sandstone_normal", "wool_colored_purple", "wool_colored_magenta", "rail_detector", "leaves_jungle", "leaves_jungle_opaque", "planks_spruce", "planks_jungle",
"carrots_stage_0", "carrots_stage_1", "carrots_stage_2", "carrots_stage_3", "potatoes_stage_3", null, null, null,
"sandstone_bottom", "wool_colored_cyan", "wool_colored_orange", "redstone_lamp_off", "redstone_lamp_on", "stonebrick_carved", "planks_birch", "anvil_base",
"anvil_top_damaged_1", null, null, null, null, null, null, null,
"nether_brick", "wool_colored_silver", "nether_wart_stage_0", "nether_wart_stage_1", "nether_wart_stage_2", "sandstone_carved", "sandstone_smooth", "anvil_top_damaged_0",
"anvil_top_damaged_2", null, null, null, null, null, null, null,
"destroy_stage_0", "destroy_stage_1", "destroy_stage_2", "destroy_stage_3", "destroy_stage_4", "destroy_stage_5", "destroy_stage_6", "destroy_stage_7",
"destroy_stage_8", "destroy_stage_9", null, null, null, null, null, null,
/* Extra 1.5-based textures: starting at 256 (corresponds to TILEINDEX_ values) */
null, "water_still", "water_flow", "lava_still", "lava_flow", null, null, null,
null, "fire_layer_0", "portal"
};
private static class CustomTileRec {
int srcx, srcy, width, height, targetx, targety;
}
private static int next_dynamic_tile = MAX_TILEINDEX+1;
private static class DynamicTileFile {
int idx; /* Index of tile in addonfiles */
String filename;
String modname; /* Modname associated with file, if any */
int tilecnt_x, tilecnt_y; /* Number of tiles horizontally and vertically */
int tile_to_dyntile[]; /* Mapping from tile index in tile file to dynamic ID in global tile table (terrain_argb): 0=unassigned */
TileFileFormat format;
List<CustomTileRec> cust;
String[] tilenames; /* For TILESET, array of tilenames, indexed by tile index */
boolean used; // Set to true if any active references to the file
MaterialType material; // Material type, if specified
}
private static ArrayList<DynamicTileFile> addonfiles = new ArrayList<DynamicTileFile>();
private static Map<String, DynamicTileFile> addonfilesbyname = new HashMap<String, DynamicTileFile>();
private Map<Integer, MaterialType> materialbytileid = new HashMap<Integer, MaterialType>();
private Map<Integer, String> matIDByTileID = new HashMap<Integer, String>();
private Map<String, Integer> tileIDByMatID = new HashMap<String, Integer>();
// Mods supplying their own texture files
private static HashSet<String> loadedmods = new HashSet<String>();
private static String getBlockFileName(int idx) {
if ((idx >= 0) && (idx < terrain_map.length) && (terrain_map[idx] != null)) {
return "textures/blocks/" + terrain_map[idx] + ".png";
}
return null;
}
private static String getRPFileName(int idx) {
if ((idx >= 0) && (idx < terrain_rp_map.length) && (terrain_rp_map[idx] != null)) {
return "assets/minecraft/textures/blocks/" + terrain_rp_map[idx] + ".png";
}
return null;
}
/* Reset add-on tile data */
private static void resetFiles(DynmapCore core) {
synchronized(packlock) {
packs.clear();
}
addonfiles.clear();
addonfilesbyname.clear();
loadedmods.clear();
next_dynamic_tile = MAX_TILEINDEX+1;
/* Now, load entries for vanilla v1.6.x RP files */
for(int i = 0; i < terrain_rp_map.length; i++) {
String fn = getRPFileName(i);
if (fn != null) {
int idx = findOrAddDynamicTileFile(fn, null, 1, 1, TileFileFormat.GRID, new String[0]);
DynamicTileFile dtf = addonfiles.get(idx);
if (dtf != null) { // Fix mapping of tile ID to global table index
dtf.tile_to_dyntile[0] = i;
dtf.used = true;
}
}
}
/* Now, load entries for vanilla v1.5.x files (put second so that add-on TP overrides built in RP) */
for(int i = 0; i < terrain_map.length; i++) {
String fn = getBlockFileName(i);
if (fn != null) {
int idx = findOrAddDynamicTileFile(fn, null, 1, 1, TileFileFormat.GRID, new String[0]);
DynamicTileFile dtf = addonfiles.get(idx);
if (dtf != null) { // Fix mapping of tile ID to global table index
dtf.used = true;
dtf.tile_to_dyntile[0] = i;
}
}
}
}
private static class LoadedImage {
int[] argb;
int width, height;
int trivial_color;
boolean isLoaded;
}
private int[][] tile_argb;
private int[] blank;
private int native_scale;
private CTMTexturePack ctm;
private BitSet hasBlockColoring = new BitSet(); // Quick lookup - (blockID << 4) + blockMeta - set if custom colorizer
private DynIntHashMap blockColoring = new DynIntHashMap(); // Map - index by (blockID << 4) + blockMeta - Index of image for color map
private int colorMultBirch = 0x80a755; /* From ColorizerFoliage.java in MCP */
private int colorMultPine = 0x619961; /* From ColorizerFoliage.java in MCP */
private int colorMultLily = 0x208030; /* from BlockLilyPad.java in MCP */
private int colorMultWater = 0xFFFFFF;
private static final int IMG_GRASSCOLOR = 0;
private static final int IMG_FOLIAGECOLOR = 1;
private static final int IMG_CUSTOMWATERMOVING = 2;
private static final int IMG_CUSTOMWATERSTILL = 3;
private static final int IMG_CUSTOMLAVAMOVING = 4;
private static final int IMG_CUSTOMLAVASTILL = 5;
private static final int IMG_WATERCOLORX = 6;
private static final int IMG_SWAMPGRASSCOLOR = 7;
private static final int IMG_SWAMPFOLIAGECOLOR = 8;
private static final int IMG_PINECOLOR = 9;
private static final int IMG_BIRCHCOLOR = 10;
private static final int IMG_CNT = 11;
/* 0-(IMG_CNT-1) are fixed, IMG_CNT+x is dynamic file x */
private LoadedImage[] imgs;
private HashMap<Integer, TexturePack> scaled_textures;
private Object scaledlock = new Object();
public enum BlockTransparency {
OPAQUE, /* Block is opaque - blocks light - lit by light from adjacent blocks */
TRANSPARENT, /* Block is transparent - passes light - lit by light level in own block */
SEMITRANSPARENT, /* Opaque block that doesn't block all rays (steps, slabs) - use light above for face lighting on opaque blocks */
LEAVES /* Special case of transparent, to work around lighting errors in SpoutPlugin */
}
public static class HDTextureMap {
private int faces[]; /* index in terrain.png of image for each face (indexed by BlockStep.ordinal() OR patch index) */
private byte[] layers; /* If layered, each index corresponds to faces index, and value is index of next layer */
private List<Integer> blockids;
private int databits;
private BlockTransparency bt;
private boolean userender;
private String blockset;
private int colorMult;
private CustomColorMultiplier custColorMult;
private boolean stdrotate; // Marked for corrected to proper : stdrot=true
private static HDTextureMap[] texmaps;
private static BlockTransparency transp[];
private static boolean userenderdata[];
private static HDTextureMap blank;
public int getIndexForFace(int face) {
if ((faces != null) && (faces.length > face))
return faces[face];
return TILEINDEX_BLANK;
}
private static void initializeTable() {
texmaps = new HDTextureMap[16*BLOCKTABLELEN];
transp = new BlockTransparency[BLOCKTABLELEN];
userenderdata = new boolean[BLOCKTABLELEN];
blank = new HDTextureMap();
for(int i = 0; i < texmaps.length; i++)
texmaps[i] = blank;
for(int i = 0; i < transp.length; i++)
transp[i] = BlockTransparency.OPAQUE;
}
private HDTextureMap() {
blockids = Collections.singletonList(Integer.valueOf(0));
databits = 0xFFFF;
userender = false;
blockset = null;
colorMult = 0;
custColorMult = null;
faces = new int[] { TILEINDEX_BLANK, TILEINDEX_BLANK, TILEINDEX_BLANK, TILEINDEX_BLANK, TILEINDEX_BLANK, TILEINDEX_BLANK };
layers = null;
stdrotate = true;
}
public HDTextureMap(List<Integer> blockids, int databits, int[] faces, byte[] layers, BlockTransparency trans, boolean userender, int colorMult, CustomColorMultiplier custColorMult, String blockset, boolean stdrot) {
this.faces = faces;
this.layers = layers;
this.blockids = blockids;
this.databits = databits;
this.bt = trans;
this.colorMult = colorMult;
this.custColorMult = custColorMult;
this.userender = userender;
this.blockset = blockset;
this.stdrotate = stdrot;
}
public HDTextureMap(List<Integer> blockids, int databits, HDTextureMap map) {
this.faces = map.faces;
this.layers = map.layers;
this.blockids = blockids;
this.databits = databits;
this.bt = map.bt;
this.colorMult = map.colorMult;
this.custColorMult = map.custColorMult;
this.userender = map.userender;
this.blockset = map.blockset;
this.stdrotate = map.stdrotate;
}
public void addToTable() {
/* Add entries to lookup table */
for(Integer blkid : blockids) {
if(blkid > 0) {
for(int i = 0; i < 16; i++) {
if((databits & (1 << i)) != 0) {
int idx = 16*blkid + i;
if((this.blockset != null) && (this.blockset.equals("core") == false)) {
HDBlockModels.resetIfNotBlockSet(blkid, i, this.blockset);
}
texmaps[idx] = this;
}
}
transp[blkid] = bt; /* Transparency is only blocktype based right now */
userenderdata[blkid] = userender; /* Ditto for using render data */
}
}
}
public static HDTextureMap getMap(int blkid, int blkdata, int blkrenderdata) {
try {
if(userenderdata[blkid])
return texmaps[(blkid<<4) + blkrenderdata];
else
return texmaps[(blkid<<4) + blkdata];
} catch (Exception x) {
return blank;
}
}
public static BlockTransparency getTransparency(int blkid) {
try {
return transp[blkid];
} catch (Exception x) {
return BlockTransparency.OPAQUE;
}
}
private static void remapTexture(int id, int srcid) {
for(int i = 0; i < 16; i++) {
texmaps[(id<<4)+i] = texmaps[(srcid<<4)+i];
}
transp[id] = transp[srcid];
userenderdata[id] = userenderdata[srcid];
}
}
/**
* Texture map - used for accumulation of textures from different sources, keyed by lookup value
*/
public static class TextureMap {
private Map<Integer, Integer> key_to_index = new HashMap<Integer, Integer>();
private List<Integer> texture_ids = new ArrayList<Integer>();
private List<Integer> blockids = new ArrayList<Integer>();
private int databits = 0;
private BlockTransparency trans = BlockTransparency.OPAQUE;
private boolean userender = false;
private int colorMult = 0;
private CustomColorMultiplier custColorMult = null;
private String blockset;
public int addTextureByKey(int key, int textureid) {
int off = texture_ids.size(); /* Next index in array is texture index */
texture_ids.add(textureid); /* Add texture ID to list */
key_to_index.put(key, off); /* Add texture index to lookup by key */
return off;
}
}
private static HashMap<String, TextureMap> textmap_by_id = new HashMap<String, TextureMap>();
/**
* Set tile ARGB buffer at index
*/
public final void setTileARGB(int idx, int[] buf) {
if (idx >= tile_argb.length) {
tile_argb = Arrays.copyOf(tile_argb, 3*idx/2);
}
tile_argb[idx] = buf;
}
/**
* Get number of entries in tile list
* @return length of tile list
*/
public final int getTileARGBCount() {
return tile_argb.length;
}
/**
* Get tile ARGB buffer at index
*/
public final int[] getTileARGB(int idx) {
int[] rslt = blank;
if (idx < tile_argb.length) {
rslt = tile_argb[idx];
if (rslt == null) {
rslt = tile_argb[idx] = blank;
}
}
return rslt;
}
/**
* Add texture to texture map
*/
private static int addTextureByKey(String id, int key, int textureid) {
TextureMap idx = textmap_by_id.get(id);
if(idx == null) { /* Add empty one, if not found */
idx = new TextureMap();
textmap_by_id.put(id, idx);
}
return idx.addTextureByKey(key, textureid);
}
/**
* Add settings for texture map
*/
private static void addTextureIndex(String id, List<Integer> blockids, int databits, BlockTransparency trans, boolean userender, int colorMult, CustomColorMultiplier custColorMult, String blockset) {
TextureMap idx = textmap_by_id.get(id);
if(idx == null) { /* Add empty one, if not found */
idx = new TextureMap();
textmap_by_id.put(id, idx);
}
idx.blockids = blockids;
idx.databits = databits;
idx.trans = trans;
idx.userender = userender;
idx.colorMult = colorMult;
idx.custColorMult = custColorMult;
}
/**
* Finish processing of texture indexes - add to texture maps
*/
private static void processTextureMaps() {
for(TextureMap ti : textmap_by_id.values()) {
if(ti.blockids.isEmpty()) continue;
int[] txtids = new int[ti.texture_ids.size()];
for(int i = 0; i < txtids.length; i++) {
txtids[i] = ti.texture_ids.get(i).intValue();
}
HDTextureMap map = new HDTextureMap(ti.blockids, ti.databits, txtids, null, ti.trans, ti.userender, ti.colorMult, ti.custColorMult, ti.blockset, true);
map.addToTable();
}
}
/**
* Get index of texture in texture map
*/
public static int getTextureIndexFromTextureMap(String id, int key) {
int idx = -1;
TextureMap map = textmap_by_id.get(id);
if(map != null) {
Integer txtidx = map.key_to_index.get(key);
if(txtidx != null) {
idx = txtidx.intValue();
}
}
return idx;
}
/*
* Get count of textures in given texture map
*/
public static int getTextureMapLength(String id) {
TextureMap map = textmap_by_id.get(id);
if(map != null) {
return map.texture_ids.size();
}
return -1;
}
/** Get or load texture pack */
public static TexturePack getTexturePack(DynmapCore core, String tpname) {
synchronized(packlock) {
TexturePack tp = packs.get(tpname);
if(tp != null)
return tp;
try {
tp = new TexturePack(core, tpname); /* Attempt to load pack */
packs.put(tpname, tp);
return tp;
} catch (FileNotFoundException fnfx) {
Log.severe("Error loading texture pack '" + tpname + "' - not found");
}
return null;
}
}
/**
* Constructor for texture pack, by name
*/
private TexturePack(DynmapCore core, String tpname) throws FileNotFoundException {
File texturedir = getTexturePackDirectory(core);
/* Set up for enough files */
imgs = new LoadedImage[IMG_CNT + addonfiles.size()];
// Get texture pack
File f = new File(texturedir, tpname);
// Build loader
TexturePackLoader tpl = new TexturePackLoader(f, core);
InputStream is = null;
try {
boolean is_rp = false;
/* Check if resource pack */
is = tpl.openTPResource("pack.mcmeta");
if (is != null) {
tpl.closeResource(is);
is_rp = true;
Log.info("Loading resource pack " + f.getName());
}
else if(tpname.equals("standard")) { // Built in is RP
is_rp = true;
Log.info("Loading default resource pack");
}
else {
Log.info("Loading texture pack " + f.getName());
}
/* Load CTM support, if enabled */
if(core.isCTMSupportEnabled()) {
ctm = new CTMTexturePack(tpl, this, core, is_rp);
if(ctm.isValid() == false) {
ctm = null;
}
}
String fn;
/* Load custom colors support, if enabled */
if(core.isCustomColorsSupportEnabled()) {
fn = (is_rp?"assets/minecraft/mcpatcher/color.properties":"color.properties");
is = tpl.openTPResource(fn);
Properties p;
if (is != null) {
p = new Properties();
try {
p.load(is);
} finally {
tpl.closeResource(is);
}
processCustomColors(p);
}
}
/* Loop through dynamic files */
for(int i = 0; i < addonfiles.size(); i++) {
DynamicTileFile dtf = addonfiles.get(i);
if (dtf.used == false) { // Not used, skip it - save memory and avoid errors for downlevel mods and such
continue;
}
is = tpl.openModTPResource(dtf.filename, dtf.modname);
try {
if(dtf.format == TileFileFormat.BIOME)
loadBiomeShadingImage(is, i+IMG_CNT); /* Load image file */
else
loadImage(is, i+IMG_CNT); /* Load image file */
} finally {
tpl.closeResource(is);
}
}
/* Find and load terrain.png */
is = tpl.openTPResource(TERRAIN_PNG); /* Try to find terrain.png */
if (is != null) {
loadTerrainPNG(is, is_rp);
tpl.closeResource(is);
}
/* Try to find and load misc/grasscolor.png */
is = tpl.openTPResource(GRASSCOLOR_PNG, GRASSCOLOR_RP_PNG);
if (is != null) {
loadBiomeShadingImage(is, IMG_GRASSCOLOR);
tpl.closeResource(is);
}
/* Try to find and load misc/foliagecolor.png */
is = tpl.openTPResource(FOLIAGECOLOR_PNG, FOLIAGECOLOR_RP_PNG);
if (is != null) {
loadBiomeShadingImage(is, IMG_FOLIAGECOLOR);
tpl.closeResource(is);
}
/* Try to find and load misc/swampgrasscolor.png */
is = tpl.openTPResource(SWAMPGRASSCOLOR_PNG, SWAMPGRASSCOLOR_RP_PNG);
if (is != null) {
loadBiomeShadingImage(is, IMG_SWAMPGRASSCOLOR);
tpl.closeResource(is);
}
/* Try to find and load misc/swampfoliagecolor.png */
is = tpl.openTPResource(SWAMPFOLIAGECOLOR_PNG, SWAMPFOLIAGECOLOR_RP_PNG);
if (is != null) {
loadBiomeShadingImage(is, IMG_SWAMPFOLIAGECOLOR);
tpl.closeResource(is);
}
/* Try to find and load misc/watercolor.png */
is = tpl.openTPResource(WATERCOLORX_PNG, WATERCOLORX_RP_PNG);
if (is == null) {
/* Try to find and load colormap/water.png */
is = tpl.openTPResource(WATERCOLORX_PNG, WATERCOLORX2_RP_PNG);
}
if (is != null) {
loadBiomeShadingImage(is, IMG_WATERCOLORX);
tpl.closeResource(is);
}
/* Try to find pine.png */
is = tpl.openTPResource(PINECOLOR_PNG, PINECOLOR_RP_PNG);
if (is != null) {
loadBiomeShadingImage(is, IMG_PINECOLOR);
tpl.closeResource(is);
}
/* Try to find birch.png */
is = tpl.openTPResource(BIRCHCOLOR_PNG, BIRCHCOLOR_RP_PNG);
if (is != null) {
loadBiomeShadingImage(is, IMG_BIRCHCOLOR);
tpl.closeResource(is);
}
/* Optional files - process if they exist */
is = tpl.openTPResource(CUSTOMLAVASTILL_PNG);
if (is == null) {
is = tpl.openTPResource("anim/" + CUSTOMLAVASTILL_PNG);
}
if (is != null) {
loadImage(is, IMG_CUSTOMLAVASTILL);
tpl.closeResource(is);
patchTextureWithImage(IMG_CUSTOMLAVASTILL, TILEINDEX_STATIONARYLAVA);
patchTextureWithImage(IMG_CUSTOMLAVASTILL, TILEINDEX_MOVINGLAVA);
}
is = tpl.openTPResource(CUSTOMLAVAFLOWING_PNG);
if (is == null) {
is = tpl.openTPResource("anim/" + CUSTOMLAVAFLOWING_PNG);
}
if (is != null) {
loadImage(is, IMG_CUSTOMLAVAMOVING);
tpl.closeResource(is);
patchTextureWithImage(IMG_CUSTOMLAVAMOVING, TILEINDEX_MOVINGLAVA);
}
is = tpl.openTPResource(CUSTOMWATERSTILL_PNG);
if (is == null) {
is = tpl.openTPResource("anim/" + CUSTOMWATERSTILL_PNG);
}
if (is != null) {
loadImage(is, IMG_CUSTOMWATERSTILL);
tpl.closeResource(is);
patchTextureWithImage(IMG_CUSTOMWATERSTILL, TILEINDEX_STATIONARYWATER);
patchTextureWithImage(IMG_CUSTOMWATERSTILL, TILEINDEX_MOVINGWATER);
}
is = tpl.openTPResource(CUSTOMWATERFLOWING_PNG);
if (is == null) {
is = tpl.openTPResource("anim/" + CUSTOMWATERFLOWING_PNG);
}
if (is != null) {
loadImage(is, IMG_CUSTOMWATERMOVING);
tpl.closeResource(is);
patchTextureWithImage(IMG_CUSTOMWATERMOVING, TILEINDEX_MOVINGWATER);
}
/* Loop through dynamic files */
for(int i = 0; i < addonfiles.size(); i++) {
DynamicTileFile dtf = addonfiles.get(i);
processDynamicImage(i, dtf.format);
}
} catch (IOException iox) {
Log.severe("Error loadling texture pack", iox);
} finally {
if (is != null) {
try { is.close(); } catch (IOException iox) {}
is = null;
}
tpl.close();
}
}
/**
* Copy subimage from portions of given image
* @param img_id - image ID of raw image
* @param from_x - top-left X
* @param from_y - top-left Y
* @param to_x - dest topleft
* @param to_y - dest topleft
* @param width - width to copy
* @param height - height to copy
* @param dest_argb - destination tile buffer
* @param dest_width - width of destination tile buffer
*/
private void copySubimageFromImage(int img_id, int from_x, int from_y, int to_x, int to_y, int width, int height, int[] dest_argb, int dest_width) {
for(int h = 0; h < height; h++) {
System.arraycopy(imgs[img_id].argb, (h+from_y)*imgs[img_id].width + from_x, dest_argb, dest_width*(h+to_y) + to_x, width);
}
}
private enum HandlePos { CENTER, LEFT, RIGHT, NONE, LEFTFRONT, RIGHTFRONT };
/**
* Make chest side image (based on chest and largechest layouts)
* @param img_id - source image ID
* @param dest_idx - destination tile index
* @param src_x - starting X of source (scaled based on 64 high)
* @param width - width to copy (scaled based on 64 high)
* @param dest_x - destination X (scaled based on 64 high)
* @param handlepos - 0=middle,1=leftedge,2=rightedge
*/
private void makeChestSideImage(int img_id, int dest_idx, int src_x, int width, int dest_x, HandlePos handlepos) {
if(dest_idx <= 0) return;
int mult = imgs[img_id].height / 64; /* Nominal height for chest images is 64 */
int[] tile = new int[16 * 16 * mult * mult]; /* Make image */
/* Copy top part */
copySubimageFromImage(img_id, src_x * mult, 14 * mult, dest_x * mult, 2 * mult, width * mult, 5 * mult, tile, 16 * mult);
/* Copy bottom part */
copySubimageFromImage(img_id, src_x * mult, 34 * mult, dest_x * mult, 7 * mult, width * mult, 9 * mult, tile, 16 * mult);
/* Handle the handle image */
if(handlepos == HandlePos.CENTER) { /* Middle */
copySubimageFromImage(img_id, 1 * mult, 1 * mult, 7 * mult, 4 * mult, 2 * mult, 4 * mult, tile, 16 * mult);
}
else if(handlepos == HandlePos.LEFT) { /* left edge */
copySubimageFromImage(img_id, 3 * mult, 1 * mult, 0 * mult, 4 * mult, 1 * mult, 4 * mult, tile, 16 * mult);
}
else if(handlepos == HandlePos.LEFTFRONT) { /* left edge - front of handle */
copySubimageFromImage(img_id, 2 * mult, 1 * mult, 0 * mult, 4 * mult, 1 * mult, 4 * mult, tile, 16 * mult);
}
else if(handlepos == HandlePos.RIGHT) { /* Right */
copySubimageFromImage(img_id, 0 * mult, 1 * mult, 15 * mult, 4 * mult, 1 * mult, 4 * mult, tile, 16 * mult);
}
else if(handlepos == HandlePos.RIGHTFRONT) { /* Right - front of handle */
copySubimageFromImage(img_id, 1 * mult, 1 * mult, 15 * mult, 4 * mult, 1 * mult, 4 * mult, tile, 16 * mult);
}
/* Put scaled result into tile buffer */
int new_argb[] = new int[native_scale*native_scale];
scaleTerrainPNGSubImage(16*mult, native_scale, tile, new_argb);
setTileARGB(dest_idx, new_argb);
}
/**
* Make chest top/bottom image (based on chest and largechest layouts)
* @param img_id - source image ID
* @param dest_idx - destination tile index
* @param src_x - starting X of source (scaled based on 64 high)
* @param src_y - starting Y of source (scaled based on 64 high)
* @param width - width to copy (scaled based on 64 high)
* @param dest_x - destination X (scaled based on 64 high)
* @param handlepos - 0=middle,1=left-edge (righttop),2=right-edge (lefttop)
*/
private void makeChestTopBottomImage(int img_id, int dest_idx, int src_x, int src_y, int width, int dest_x, HandlePos handlepos) {
if(dest_idx <= 0) return;
int mult = imgs[img_id].height / 64; /* Nominal height for chest images is 64 */
int[] tile = new int[16 * 16 * mult * mult]; /* Make image */
copySubimageFromImage(img_id, src_x * mult, src_y * mult, dest_x * mult, 1 * mult, width * mult, 14 * mult, tile, 16 * mult);
/* Handle the handle image */
if(handlepos == HandlePos.CENTER) { /* Middle */
copySubimageFromImage(img_id, 1 * mult, 0, 7 * mult, 15 * mult, 2 * mult, 1 * mult, tile, 16 * mult);
}
else if(handlepos == HandlePos.LEFT) { /* left edge */
copySubimageFromImage(img_id, 2 * mult, 0, 0 * mult, 15 * mult, 1 * mult, 1 * mult, tile, 16 * mult);
}
else if(handlepos == HandlePos.RIGHT) { /* Right */
copySubimageFromImage(img_id, 1 * mult, 0, 15 * mult, 15 * mult, 1 * mult, 1 * mult, tile, 16 * mult);
}
/* Put scaled result into tile buffer */
int new_argb[] = new int[native_scale*native_scale];
scaleTerrainPNGSubImage(16*mult, native_scale, tile, new_argb);
setTileARGB(dest_idx, new_argb);
}
/**
* Patch tiles based on image with chest-style layout
*/
private void patchChestImages(int img_id, int tile_top, int tile_bottom, int tile_front, int tile_back, int tile_left, int tile_right) {
makeChestSideImage(img_id, tile_front, 14, 14, 1, HandlePos.CENTER);
makeChestSideImage(img_id, tile_back, 42, 14, 1, HandlePos.NONE);
makeChestSideImage(img_id, tile_left, 0, 14, 1, HandlePos.RIGHT);
makeChestSideImage(img_id, tile_right, 28, 14, 1, HandlePos.LEFT);
makeChestTopBottomImage(img_id, tile_top, 14, 0, 14, 1, HandlePos.CENTER);
makeChestTopBottomImage(img_id, tile_bottom, 28, 19, 14, 1, HandlePos.CENTER);
}
/**
* Patch tiles based on image with large-chest-style layout
*/
private void patchLargeChestImages(int img_id, int tile_topright, int tile_topleft, int tile_bottomright, int tile_bottomleft, int tile_right, int tile_left, int tile_frontright, int tile_frontleft, int tile_backright, int tile_backleft) {
makeChestSideImage(img_id, tile_frontleft, 14, 15, 1, HandlePos.RIGHTFRONT);
makeChestSideImage(img_id, tile_frontright, 29, 15, 0, HandlePos.LEFTFRONT);
makeChestSideImage(img_id, tile_left, 0, 14, 1, HandlePos.RIGHT);
makeChestSideImage(img_id, tile_right, 44, 14, 1, HandlePos.LEFT);
makeChestSideImage(img_id, tile_backright, 58, 15, 1, HandlePos.NONE);
makeChestSideImage(img_id, tile_backleft, 73, 15, 0, HandlePos.NONE);
makeChestTopBottomImage(img_id, tile_topleft, 14, 0, 15, 1, HandlePos.RIGHT);
makeChestTopBottomImage(img_id, tile_topright, 29, 0, 15, 0, HandlePos.LEFT);
makeChestTopBottomImage(img_id, tile_bottomleft, 34, 19, 15, 1, HandlePos.RIGHT);
makeChestTopBottomImage(img_id, tile_bottomright, 49, 19, 15, 0, HandlePos.LEFT);
}
/**
* Make sign image (based on sign layouts)
* @param img_id - source image ID
* @param dest_idx - destination tile index
* @param src_x - starting X of source (scaled based on 32 high)
* @param src_y - starting Y of source (scaled based on 32 high)
* @param width - width to copy (scaled based on 32 high)
* @param height - height to copy (scaled based on 32 high)
*/
private void makeSignImage(int img_id, int dest_idx, int src_x, int src_y, int width, int height) {
int mult = imgs[img_id].height / 32; /* Nominal height for sign images is 32 */
int[] tile = new int[24 * 24 * mult * mult]; /* Make image (all are 24x24) */
copySubimageFromImage(img_id, src_x * mult, src_y * mult, 0, (24-height)*mult, width * mult, height * mult, tile, 24 * mult);
/* Put scaled result into tile buffer */
int new_argb[] = new int[native_scale*native_scale];
scaleTerrainPNGSubImage(24*mult, native_scale, tile, new_argb);
setTileARGB(dest_idx, new_argb);
}
private void patchSignImages(int img, int sign_front, int sign_back, int sign_top, int sign_bottom, int sign_left, int sign_right, int post_front, int post_back, int post_left, int post_right)
{
/* Load images at lower left corner of each tile */
makeSignImage(img, sign_front, 2, 2, 24, 12);
makeSignImage(img, sign_back, 28, 2, 24, 12);
makeSignImage(img, sign_top, 2, 0, 24, 2);
makeSignImage(img, sign_left, 0, 2, 2, 12);
makeSignImage(img, sign_right, 26, 2, 2, 12);
makeSignImage(img, sign_bottom, 26, 0, 24, 2);
makeSignImage(img, post_front, 0, 16, 2, 14);
makeSignImage(img, post_right, 2, 16, 2, 14);
makeSignImage(img, post_back, 4, 16, 2, 14);
makeSignImage(img, post_left, 6, 16, 2, 14);
}
/**
* Make face image (based on skin layouts)
* @param img_id - source image ID
* @param dest_idx - destination tile index
* @param src_x - starting X of source (scaled based on 32 high)
* @param src_y - starting Y of source (scaled based on 32 high)
*/
private void makeFaceImage(int img_id, int dest_idx, int src_x, int src_y) {
int mult = imgs[img_id].width / 64; /* Nominal height for skin images is 32 */
int[] tile = new int[8 * 8 * mult * mult]; /* Make image (all are 8x8) */
copySubimageFromImage(img_id, src_x * mult, src_y * mult, 0, 0, 8 * mult, 8 * mult, tile, 8 * mult);
/* Put scaled result into tile buffer */
int new_argb[] = new int[native_scale*native_scale];
scaleTerrainPNGSubImage(8 * mult, native_scale, tile, new_argb);
setTileARGB(dest_idx, new_argb);
}
private void patchSkinImages(int img, int face_front, int face_left, int face_right, int face_back, int face_top, int face_bottom)
{
makeFaceImage(img, face_front, 8, 8);
makeFaceImage(img, face_left, 16, 8);
makeFaceImage(img, face_right, 0, 8);
makeFaceImage(img, face_back, 24, 8);
makeFaceImage(img, face_top, 8, 0);
makeFaceImage(img, face_bottom, 16, 0);
}
private void patchCustomImages(int img_id, int[] imgids, List<CustomTileRec> recs, int xcnt, int ycnt)
{
int mult = imgs[img_id].height / (ycnt * 16); /* Compute scale based on nominal tile count vertically (ycnt * 16) */
for(int i = 0; i < imgids.length; i++) {
if(imgids[i] <= 0) continue;
CustomTileRec ctr = recs.get(i);
if(ctr == null) continue;
int[] tile = new int[16 * 16 * mult * mult]; /* Make image */
copySubimageFromImage(img_id, ctr.srcx * mult, ctr.srcy * mult, ctr.targetx * mult, ctr.targety * mult,
ctr.width * mult, ctr.height * mult, tile, 16 * mult);
/* Put scaled result into tile buffer */
int new_argb[] = new int[native_scale*native_scale];
scaleTerrainPNGSubImage(16*mult, native_scale, tile, new_argb);
setTileARGB(imgids[i], new_argb);
}
}
/* Copy texture pack */
private TexturePack(TexturePack tp) {
this.tile_argb = Arrays.copyOf(tp.tile_argb, tp.tile_argb.length);
this.native_scale = tp.native_scale;
this.ctm = tp.ctm;
this.imgs = tp.imgs;
this.hasBlockColoring = tp.hasBlockColoring;
this.blockColoring = tp.blockColoring;
}
/* Load terrain.png */
private void loadTerrainPNG(InputStream is, boolean is_rp) throws IOException {
int i, j;
/* Load image */
ImageIO.setUseCache(false);
BufferedImage img = ImageIO.read(is);
if(img == null) { throw new FileNotFoundException(); }
tile_argb = new int[MAX_TILEINDEX][];
/* If we're using pre 1.5 terrain.png */
if(img.getWidth() >= 256) {
native_scale = img.getWidth() / 16;
blank = new int[native_scale*native_scale];
for(i = 0; i < 256; i++) {
int[] buf = new int[native_scale*native_scale];
img.getRGB((i & 0xF)*native_scale, (i>>4)*native_scale, native_scale, native_scale, buf, 0, native_scale);
setTileARGB(i, buf);
}
/* Now, load extra scaled images */
for(i = 256; i < terrain_map.length; i++) {
String fn = getBlockFileName(i);
if (fn == null) continue;
DynamicTileFile dtf = addonfilesbyname.get(fn);
if (dtf == null) continue;
LoadedImage li = imgs[dtf.idx + IMG_CNT];
if(li != null) {
int[] buf = new int[native_scale * native_scale];
scaleTerrainPNGSubImage(li.width, native_scale, li.argb, buf);
setTileARGB(i, buf);
}
}
}
else if (is_rp) { // If resource pack (1.6+)
native_scale = 16;
/* Loop through textures - find biggest one */
for(i = 0; i < terrain_rp_map.length; i++) {
String fn = getRPFileName(i);
if (fn == null) continue;
DynamicTileFile dtf = addonfilesbyname.get(fn);
if (dtf == null) continue;
LoadedImage li = imgs[dtf.idx+IMG_CNT];
if(li != null) {
if(native_scale < li.width) native_scale = li.width;
}
}
blank = new int[native_scale*native_scale];
/* Now, load scaled images */
for(i = 0; i < terrain_rp_map.length; i++) {
String fn = getRPFileName(i);
if (fn == null) continue;
DynamicTileFile dtf = addonfilesbyname.get(fn);
if (dtf == null) continue;
LoadedImage li = imgs[dtf.idx + IMG_CNT];
if(li != null) {
int[] buf = new int[native_scale * native_scale];
scaleTerrainPNGSubImage(li.width, native_scale, li.argb, buf);
setTileARGB(i, buf);
}
}
}
else { /* Else, use v1.5 tile files */
native_scale = 16;
/* Loop through textures - find biggest one */
for(i = 0; i < terrain_map.length; i++) {
String fn = getBlockFileName(i);
if (fn == null) continue;
DynamicTileFile dtf = addonfilesbyname.get(fn);
if (dtf == null) continue;
LoadedImage li = imgs[dtf.idx+IMG_CNT];
if(li != null) {
if(native_scale < li.width) native_scale = li.width;
}
}
blank = new int[native_scale*native_scale];
/* Now, load scaled images */
for(i = 0; i < terrain_map.length; i++) {
String fn = getBlockFileName(i);
if (fn == null) continue;
DynamicTileFile dtf = addonfilesbyname.get(fn);
if (dtf == null) continue;
LoadedImage li = imgs[dtf.idx + IMG_CNT];
if(li != null) {
int[] buf = new int[native_scale * native_scale];
scaleTerrainPNGSubImage(li.width, native_scale, li.argb, buf);
setTileARGB(i, buf);
}
}
}
/* Now, build redstone textures with active wire color (since we're not messing with that) */
Color tc = new Color();
int[] red_nsew_tone = getTileARGB(TILEINDEX_REDSTONE_NSEW_TONE);
int[] red_nsew = getTileARGB(TILEINDEX_REDSTONE_NSEW);
int[] red_ew_tone = getTileARGB(TILEINDEX_REDSTONE_EW_TONE);
int[] red_ew = getTileARGB(TILEINDEX_REDSTONE_EW);
for(i = 0; i < native_scale*native_scale; i++) {
if(red_nsew_tone[i] != 0) {
/* Overlay NSEW redstone texture with toned wire color */
tc.setARGB(red_nsew_tone[i]);
tc.blendColor(0xFFC00000); /* Blend in red */
red_nsew[i] = tc.getARGB();
}
if(red_ew_tone[i] != 0) {
/* Overlay NSEW redstone texture with toned wire color */
tc.setARGB(red_ew_tone[i]);
tc.blendColor(0xFFC00000); /* Blend in red */
red_ew[i] = tc.getARGB();
}
}
/* Build extended piston side texture - take top 1/4 of piston side, use to make piston extension */
int[] buf = new int[native_scale*native_scale];
setTileARGB(TILEINDEX_PISTONEXTSIDE, buf);
int[] piston_side = getTileARGB(TILEINDEX_PISTONSIDE);
System.arraycopy(piston_side, 0, buf, 0, native_scale * native_scale / 4);
for(i = 0; i < native_scale/4; i++) {
for(j = 0; j < (3*native_scale/4); j++) {
buf[native_scale*(native_scale/4 + j) + (3*native_scale/8 + i)] = piston_side[native_scale*i + j];
}
}
/* Build piston side while extended (cut off top 1/4, replace with rotated top for extension */
buf = new int[native_scale*native_scale];
setTileARGB(TILEINDEX_PISTONSIDE_EXT, buf);
System.arraycopy(piston_side, native_scale*native_scale/4, buf, native_scale*native_scale/4,
3 * native_scale * native_scale / 4); /* Copy bottom 3/4 */
for(i = 0; i < native_scale/4; i++) {
for(j = 3*native_scale/4; j < native_scale; j++) {
buf[native_scale*(j - 3*native_scale/4) + (3*native_scale/8 + i)] =
piston_side[native_scale*i + j];
}
}
/* Build glass pane top in NSEW config (we use model to clip it) */
buf = new int[native_scale*native_scale];
setTileARGB(TILEINDEX_PANETOP_X, buf);
int[] glasspanetop = getTileARGB(TILEINDEX_GLASSPANETOP);
System.arraycopy(glasspanetop, 0, buf, 0, native_scale*native_scale);
for(i = native_scale*7/16; i < native_scale*9/16; i++) {
for(j = 0; j < native_scale; j++) {
buf[native_scale*i + j] = buf[native_scale*j + i];
}
}
/* Build air frame with eye overlay */
buf = new int[native_scale*native_scale];
setTileARGB(TILEINDEX_AIRFRAME_EYE, buf);
int[] airframe = getTileARGB(TILEINDEX_AIRFRAME);
int[] eyeofender = getTileARGB(TILEINDEX_EYEOFENDER);
System.arraycopy(airframe, 0, buf, 0, native_scale*native_scale);
for(i = native_scale/4; i < native_scale*3/4; i++) {
for(j = native_scale/4; j < native_scale*3/4; j++) {
buf[native_scale*i + j] = eyeofender[native_scale*i + j];
}
}
/* Build white tile */
buf = new int[native_scale*native_scale];
setTileARGB(TILEINDEX_WHITE, buf);
Arrays.fill(buf, 0xFFFFFFFF);
img.flush();
}
/* Load image into image array */
private void loadImage(InputStream is, int idx) throws IOException {
BufferedImage img = null;
/* Load image */
if(is != null) {
ImageIO.setUseCache(false);
img = ImageIO.read(is);
if(img == null) { throw new FileNotFoundException(); }
}
if(idx >= imgs.length) {
LoadedImage[] newimgs = new LoadedImage[idx+1];
System.arraycopy(imgs, 0, newimgs, 0, imgs.length);
imgs = newimgs;
}
imgs[idx] = new LoadedImage();
if (img != null) {
imgs[idx].width = img.getWidth();
imgs[idx].height = img.getHeight();
imgs[idx].argb = new int[imgs[idx].width * imgs[idx].height];
img.getRGB(0, 0, imgs[idx].width, imgs[idx].height, imgs[idx].argb, 0, imgs[idx].width);
img.flush();
imgs[idx].isLoaded = true;
}
else { // Pad with blank image
imgs[idx].width = 16;
imgs[idx].height = 16;
imgs[idx].argb = new int[imgs[idx].width * imgs[idx].height];
}
}
/* Process dynamic texture files, and patch into terrain_argb */
private void processDynamicImage(int idx, TileFileFormat format) {
DynamicTileFile dtf = addonfiles.get(idx); /* Get tile file definition */
LoadedImage li = imgs[idx+IMG_CNT];
if (li == null) return;
switch(format) {
case GRID: /* If grid format tile file */
int dim = li.width / dtf.tilecnt_x; /* Dimension of each tile */
int dim2 = li.height / dtf.tilecnt_y;
if (dim2 < dim) dim = dim2;
int old_argb[] = new int[dim*dim];
for(int x = 0; x < dtf.tilecnt_x; x++) {
for(int y = 0; y < dtf.tilecnt_y; y++) {
int tileidx = dtf.tile_to_dyntile[y*dtf.tilecnt_x + x];
if (tileidx < 0) continue;
if((tileidx >= terrain_map.length) || (terrain_map[tileidx] == null)) { /* dynamic ID? */
/* Copy source tile */
for(int j = 0; j < dim; j++) {
System.arraycopy(li.argb, (y*dim+j)*li.width + (x*dim), old_argb, j*dim, dim);
}
/* Rescale to match rest of terrain PNG */
int new_argb[] = new int[native_scale*native_scale];
scaleTerrainPNGSubImage(dim, native_scale, old_argb, new_argb);
setTileARGB(tileidx, new_argb);
}
}
}
break;
case CHEST:
patchChestImages(idx+IMG_CNT, dtf.tile_to_dyntile[TILEINDEX_CHEST_TOP], dtf.tile_to_dyntile[TILEINDEX_CHEST_BOTTOM], dtf.tile_to_dyntile[TILEINDEX_CHEST_FRONT], dtf.tile_to_dyntile[TILEINDEX_CHEST_BACK], dtf.tile_to_dyntile[TILEINDEX_CHEST_LEFT], dtf.tile_to_dyntile[TILEINDEX_CHEST_RIGHT]);
break;
case BIGCHEST:
patchLargeChestImages(idx+IMG_CNT, dtf.tile_to_dyntile[TILEINDEX_BIGCHEST_TOPRIGHT], dtf.tile_to_dyntile[TILEINDEX_BIGCHEST_TOPLEFT], dtf.tile_to_dyntile[TILEINDEX_BIGCHEST_BOTTOMRIGHT], dtf.tile_to_dyntile[TILEINDEX_BIGCHEST_BOTTOMLEFT], dtf.tile_to_dyntile[TILEINDEX_BIGCHEST_RIGHT], dtf.tile_to_dyntile[TILEINDEX_BIGCHEST_LEFT], dtf.tile_to_dyntile[TILEINDEX_BIGCHEST_FRONTRIGHT], dtf.tile_to_dyntile[TILEINDEX_BIGCHEST_FRONTLEFT], dtf.tile_to_dyntile[TILEINDEX_BIGCHEST_BACKRIGHT], dtf.tile_to_dyntile[TILEINDEX_BIGCHEST_BACKLEFT]);
break;
case SIGN:
patchSignImages(idx+IMG_CNT, dtf.tile_to_dyntile[TILEINDEX_SIGN_FRONT], dtf.tile_to_dyntile[TILEINDEX_SIGN_BACK], dtf.tile_to_dyntile[TILEINDEX_SIGN_TOP], dtf.tile_to_dyntile[TILEINDEX_SIGN_BOTTOM], dtf.tile_to_dyntile[TILEINDEX_SIGN_LEFTSIDE], dtf.tile_to_dyntile[TILEINDEX_SIGN_RIGHTSIDE], dtf.tile_to_dyntile[TILEINDEX_SIGN_POSTFRONT], dtf.tile_to_dyntile[TILEINDEX_SIGN_POSTBACK], dtf.tile_to_dyntile[TILEINDEX_SIGN_POSTLEFT], dtf.tile_to_dyntile[TILEINDEX_SIGN_POSTRIGHT]);
break;
case SKIN:
patchSkinImages(idx+IMG_CNT, dtf.tile_to_dyntile[TILEINDEX_SKIN_FACEFRONT], dtf.tile_to_dyntile[TILEINDEX_SKIN_FACELEFT], dtf.tile_to_dyntile[TILEINDEX_SKIN_FACERIGHT], dtf.tile_to_dyntile[TILEINDEX_SKIN_FACEBACK], dtf.tile_to_dyntile[TILEINDEX_SKIN_FACETOP], dtf.tile_to_dyntile[TILEINDEX_SKIN_FACEBOTTOM]);
break;
case CUSTOM:
patchCustomImages(idx+IMG_CNT, dtf.tile_to_dyntile, dtf.cust, dtf.tilecnt_x, dtf.tilecnt_y);
break;
case TILESET:
break;
default:
break;
}
if (dtf.tile_to_dyntile != null) {
for (int i = 0; i < dtf.tile_to_dyntile.length; i++) {
if (dtf.tile_to_dyntile[i] >= 0) {
if (dtf.material != null) {
materialbytileid.put(dtf.tile_to_dyntile[i], dtf.material);
}
setMatIDForTileID(dtf.filename, dtf.tile_to_dyntile[i]);
}
}
}
}
/* Load biome shading image into image array */
private void loadBiomeShadingImage(InputStream is, int idx) throws IOException {
loadImage(is, idx); /* Get image */
LoadedImage li = imgs[idx];
if (li.width != 256) { /* Required to be 256 x 256 */
int[] scaled = new int[256*256];
scaleTerrainPNGSubImage(li.width, 256, li.argb, scaled);
li.argb = scaled;
li.width = 256;
li.height = 256;
}
/* Get trivial color for biome-shading image */
int clr = li.argb[li.height*li.width*3/4 + li.width/2];
boolean same = true;
for(int j = 0; same && (j < li.height); j++) {
for(int i = 0; same && (i <= j); i++) {
if(li.argb[li.width*j+i] != clr)
same = false;
}
}
/* All the same - no biome lookup needed */
if(same) {
li.trivial_color = clr;
}
else { /* Else, calculate color average for lower left quadrant */
int[] clr_scale = new int[16];
scaleTerrainPNGSubImage(li.width, 4, li.argb, clr_scale);
li.trivial_color = clr_scale[9];
}
// If we didn't actually load, don't use color lookup for this (handle broken RPs like John Smith)
if (li.isLoaded == false) {
// See who uses this biome map
List<Integer> badcolors = this.blockColoring.keysWithValue(idx);
for (Integer idm : badcolors) {
this.blockColoring.remove(idm);
this.hasBlockColoring.clear(idm);
}
}
}
/* Patch image into texture table */
private void patchTextureWithImage(int image_idx, int block_idx) {
/* Now, patch in to block table */
int new_argb[] = new int[native_scale*native_scale];
scaleTerrainPNGSubImage(imgs[image_idx].width, native_scale, imgs[image_idx].argb, new_argb);
setTileARGB(block_idx, new_argb);
}
/* Get texture pack directory */
private static File getTexturePackDirectory(DynmapCore core) {
return new File(core.getDataFolder(), "texturepacks");
}
/**
* Resample terrain pack for given scale, and return copy using that scale
*/
public TexturePack resampleTexturePack(int scale) {
synchronized(scaledlock) {
if(scaled_textures == null) scaled_textures = new HashMap<Integer, TexturePack>();
TexturePack stp = scaled_textures.get(scale);
if(stp != null)
return stp;
stp = new TexturePack(this); /* Make copy */
/* Scale terrain.png, if needed */
if(stp.native_scale != scale) {
stp.native_scale = scale;
scaleTerrainPNG(stp);
}
/* Remember it */
scaled_textures.put(scale, stp);
return stp;
}
}
/**
* Scale our terrain_argb into the terrain_argb of the provided destination, matching the scale of that destination
* @param tp
*/
private void scaleTerrainPNG(TexturePack tp) {
tp.tile_argb = new int[tile_argb.length][];
/* Terrain.png is 16x16 array of images : process one at a time */
for(int idx = 0; idx < tile_argb.length; idx++) {
tp.tile_argb[idx] = new int[tp.native_scale*tp.native_scale];
scaleTerrainPNGSubImage(native_scale, tp.native_scale, getTileARGB(idx), tp.tile_argb[idx]);
}
/* Special case - some textures are used as masks - need pure alpha (00 or FF) */
makeAlphaPure(tp.tile_argb[TILEINDEX_GRASSMASK]); /* Grass side mask */
}
public static void scaleTerrainPNGSubImage(int srcscale, int destscale, int[] src_argb, int[] dest_argb) {
int nativeres = srcscale;
int res = destscale;
Color c = new Color();
/* Same size, so just copy */
if(res == nativeres) {
System.arraycopy(src_argb, 0, dest_argb, 0, dest_argb.length);
}
/* If we're scaling larger source pixels into smaller pixels, each destination pixel
* receives input from 1 or 2 source pixels on each axis
*/
else if(res > nativeres) {
int weights[] = new int[res];
int offsets[] = new int[res];
/* LCM of resolutions is used as length of line (res * nativeres)
* Each native block is (res) long, each scaled block is (nativeres) long
* Each scaled block overlaps 1 or 2 native blocks: starting with native block 'offsets[]' with
* 'weights[]' of its (res) width in the first, and the rest in the second
*/
for(int v = 0, idx = 0; v < res*nativeres; v += nativeres, idx++) {
offsets[idx] = (v/res); /* Get index of the first native block we draw from */
if((v+nativeres-1)/res == offsets[idx]) { /* If scaled block ends in same native block */
weights[idx] = nativeres;
}
else { /* Else, see how much is in first one */
weights[idx] = (offsets[idx]*res + res) - v;
}
}
/* Now, use weights and indices to fill in scaled map */
for(int y = 0; y < res; y++) {
int ind_y = offsets[y];
int wgt_y = weights[y];
for(int x = 0; x < res; x++) {
int ind_x = offsets[x];
int wgt_x = weights[x];
double accum_red = 0;
double accum_green = 0;
double accum_blue = 0;
double accum_alpha = 0;
for(int xx = 0; xx < 2; xx++) {
int wx = (xx==0)?wgt_x:(nativeres-wgt_x);
if(wx == 0) continue;
for(int yy = 0; yy < 2; yy++) {
int wy = (yy==0)?wgt_y:(nativeres-wgt_y);
if(wy == 0) continue;
/* Accumulate */
c.setARGB(src_argb[(ind_y+yy)*nativeres + ind_x + xx]);
int w = wx * wy;
double a = (double)w * (double)c.getAlpha();
accum_red += c.getRed() * a;
accum_green += c.getGreen() * a;
accum_blue += c.getBlue() * a;
accum_alpha += a;
}
}
double newalpha = accum_alpha;
if(newalpha == 0.0) newalpha = 1.0;
/* Generate weighted compnents into color */
c.setRGBA((int)(accum_red / newalpha), (int)(accum_green / newalpha),
(int)(accum_blue / newalpha), (int)(accum_alpha / (nativeres*nativeres)));
dest_argb[(y*res) + x] = c.getARGB();
}
}
}
else { /* nativeres > res */
int weights[] = new int[nativeres];
int offsets[] = new int[nativeres];
/* LCM of resolutions is used as length of line (res * nativeres)
* Each native block is (res) long, each scaled block is (nativeres) long
* Each native block overlaps 1 or 2 scaled blocks: starting with scaled block 'offsets[]' with
* 'weights[]' of its (res) width in the first, and the rest in the second
*/
for(int v = 0, idx = 0; v < res*nativeres; v += res, idx++) {
offsets[idx] = (v/nativeres); /* Get index of the first scaled block we draw to */
if((v+res-1)/nativeres == offsets[idx]) { /* If native block ends in same scaled block */
weights[idx] = res;
}
else { /* Else, see how much is in first one */
weights[idx] = (offsets[idx]*nativeres + nativeres) - v;
}
}
double accum_red[] = new double[res*res];
double accum_green[] = new double[res*res];
double accum_blue[] = new double[res*res];
double accum_alpha[] = new double[res*res];
/* Now, use weights and indices to fill in scaled map */
for(int y = 0; y < nativeres; y++) {
int ind_y = offsets[y];
int wgt_y = weights[y];
for(int x = 0; x < nativeres; x++) {
int ind_x = offsets[x];
int wgt_x = weights[x];
c.setARGB(src_argb[(y*nativeres) + x]);
for(int xx = 0; xx < 2; xx++) {
int wx = (xx==0)?wgt_x:(res-wgt_x);
if(wx == 0) continue;
for(int yy = 0; yy < 2; yy++) {
int wy = (yy==0)?wgt_y:(res-wgt_y);
if(wy == 0) continue;
double w = wx * wy;
double a = w * c.getAlpha();
accum_red[(ind_y+yy)*res + (ind_x+xx)] += c.getRed() * a;
accum_green[(ind_y+yy)*res + (ind_x+xx)] += c.getGreen() * a;
accum_blue[(ind_y+yy)*res + (ind_x+xx)] += c.getBlue() * a;
accum_alpha[(ind_y+yy)*res + (ind_x+xx)] += a;
}
}
}
}
/* Produce normalized scaled values */
for(int y = 0; y < res; y++) {
for(int x = 0; x < res; x++) {
int off = (y*res) + x;
double aa = accum_alpha[off];
if(aa == 0.0) aa = 1.0;
c.setRGBA((int)(accum_red[off]/aa), (int)(accum_green[off]/aa),
(int)(accum_blue[off]/aa), (int)(accum_alpha[off] / (nativeres*nativeres)));
dest_argb[y*res + x] = c.getARGB();
}
}
}
}
private static void addFiles(List<String> tsfiles, List<String> txfiles, File dir, String path) {
File[] listfiles = dir.listFiles();
if(listfiles == null) return;
for(File f : listfiles) {
String fn = f.getName();
if(fn.equals(".") || (fn.equals(".."))) continue;
if(f.isFile()) {
if(fn.endsWith("-texture.txt")) {
txfiles.add(path + fn);
}
if(fn.endsWith("-tilesets.txt")) {
tsfiles.add(path + fn);
}
}
else if(f.isDirectory()) {
addFiles(tsfiles, txfiles, f, path + f.getName() + "/");
}
}
}
/**
* Load texture pack mappings
*/
public static void loadTextureMapping(DynmapCore core, ConfigurationNode config) {
File datadir = core.getDataFolder();
/* Start clean with texture packs - need to be loaded after mapping */
resetFiles(core);
/* Initialize map with blank map for all entries */
HDTextureMap.initializeTable();
/* Load block textures (0-N) */
int i = 0;
boolean done = false;
InputStream in = null;
while (!done) {
in = TexturePack.class.getResourceAsStream("/texture_" + i + ".txt");
if(in != null) {
loadTextureFile(in, "texture_" + i + ".txt", config, core, "core");
if(in != null) { try { in.close(); } catch (IOException x) {} in = null; }
}
else {
done = true;
}
i++;
}
// Check mods to see if texture files defined there
for (String modid : core.getServer().getModList()) {
File f = core.getServer().getModContainerFile(modid); // Get mod file
if (f.isFile()) {
ZipFile zf = null;
in = null;
try {
zf = new ZipFile(f);
String fn = "assets/" + modid.toLowerCase() + "/dynmap-texture.txt";
ZipEntry ze = zf.getEntry(fn);
if (ze != null) {
in = zf.getInputStream(ze);
loadTextureFile(in, fn, config, core, modid);
loadedmods.add(modid); // Add to set: prevent others definitions for same mod
}
} catch (ZipException e) {
} catch (IOException e) {
} finally {
if (in != null) {
try { in.close(); } catch (IOException e) { }
in = null;
}
if (zf != null) {
try { zf.close(); } catch (IOException e) { }
zf = null;
}
}
}
}
// Load external tile sets
File renderdir = new File(datadir, "renderdata");
ArrayList<String> tsfiles = new ArrayList<String>();
ArrayList<String> txfiles = new ArrayList<String>();
addFiles(tsfiles, txfiles, renderdir, "");
for(String fname : tsfiles) {
File custom = new File(renderdir, fname);
if(custom.canRead()) {
try {
in = new FileInputStream(custom);
loadTileSetsFile(in, custom.getPath(), config, core, HDBlockModels.getModIDFromFileName(fname));
} catch (IOException iox) {
Log.severe("Error loading " + custom.getPath() + " - " + iox);
} finally {
if(in != null) { try { in.close(); } catch (IOException x) {} in = null; }
}
}
}
// Load external texture files (before internals, to allow them to override them)
for(String fname : txfiles) {
File custom = new File(renderdir, fname);
if(custom.canRead()) {
try {
in = new FileInputStream(custom);
loadTextureFile(in, custom.getPath(), config, core, HDBlockModels.getModIDFromFileName(fname));
} catch (IOException iox) {
Log.severe("Error loading " + custom.getPath() + " - " + iox);
} finally {
if(in != null) { try { in.close(); } catch (IOException x) {} in = null; }
}
}
}
// Load internal texture files (last, so that others can override)
ZipFile zf = null;
try {
zf = new ZipFile(core.getPluginJarFile());
Enumeration<? extends ZipEntry> e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze = e.nextElement();
String n = ze.getName();
if (!n.startsWith("renderdata/")) continue;
if (!n.endsWith("-texture.txt")) continue;
in = zf.getInputStream(ze);
if (in != null) {
loadTextureFile(in, n, config, core, HDBlockModels.getModIDFromFileName(n));
try { in.close(); } catch (IOException x) { in = null; }
}
}
} catch (IOException iox) {
Log.severe("Error processing texture files");
} finally {
if (in != null) {
try { in.close(); } catch (IOException iox) {}
in = null;
}
if (zf != null) {
try { zf.close(); } catch (IOException iox) {}
zf = null;
}
}
/* Finish processing of texture maps */
processTextureMaps();
/* Check integrity of texture mappings versus models */
for(int blkiddata = 0; blkiddata < HDTextureMap.texmaps.length; blkiddata++) {
int blkid = (blkiddata >> 4);
int blkdata = blkiddata & 0xF;
HDTextureMap tm = HDTextureMap.texmaps[blkiddata];
int cnt = HDBlockModels.getNeededTextureCount(blkid, blkdata);
if(cnt > tm.faces.length){
Log.severe("Block ID " + blkid + ":" + blkdata + " - not enough textures for faces (" + cnt + " > " + tm.faces.length + ")");
int[] newfaces = new int[cnt];
System.arraycopy(tm.faces, 0, newfaces, 0, tm.faces.length);
for(i = tm.faces.length; i < cnt; i++) {
newfaces[i] = TILEINDEX_BLANK;
}
}
}
// Check to see if any blocks exist without corresponding mappings
if (core.dumpMissingBlocks()) {
Map<Integer, String> blks = core.getServer().getBlockIDMap();
String missing = "";
for (Integer blkid : new TreeSet<Integer>(blks.keySet())) {
if (blkid.intValue() == 0) continue;
boolean blank = true;
for (int blkiddata = 16 * blkid; blank && (blkiddata < 16 * (blkid+1)); blkiddata++) {
if (HDTextureMap.texmaps[blkiddata] != HDTextureMap.blank) {
blank = false;
}
}
if (blank) {
String id = blks.get(blkid);
if ((id != null) && (id.length() > 0)) {
missing += blkid + "(" + id + ") ";
}
else {
missing += blkid + " ";
}
}
}
if (missing.length() > 0) {
Log.warning("Blocks missing texture definition: " + missing);
}
}
}
private static Integer getIntValue(Map<String,Integer> vars, String val) throws NumberFormatException {
char c = val.charAt(0);
if(Character.isLetter(c) || (c == '%') || (c == '&')) {
int off = val.indexOf('+');
int offset = 0;
if (off > 0) {
offset = Integer.valueOf(val.substring(off+1));
val = val.substring(0, off);
}
Integer v = vars.get(val);
if(v == null) {
if ((c == '%') || (c == '&')) {
vars.put(val, 0);
v = 0;
}
else {
throw new NumberFormatException("invalid ID - " + val);
}
}
if((offset != 0) && (v.intValue() > 0))
v = v.intValue() + offset;
return v;
}
else {
return Integer.valueOf(val);
}
}
private static int parseTextureIndex(HashMap<String,Integer> filetoidx, int srctxtid, String val) throws NumberFormatException {
int off = val.indexOf(':');
int txtid = -1;
if(off > 0) {
String txt = val.substring(off+1);
if(filetoidx.containsKey(txt)) {
srctxtid = filetoidx.get(txt);
}
else {
throw new NumberFormatException("Unknown attribute: " + txt);
}
txtid = Integer.valueOf(val.substring(0, off));
}
else {
txtid = Integer.valueOf(val);
}
/* Shift function code from x1000 to x1000000 for internal processing */
int funcid = (txtid / COLORMOD_MULT_FILE);
txtid = txtid - (COLORMOD_MULT_FILE * funcid);
/* If we have source texture, need to map values to dynamic ids */
if((srctxtid >= 0) && (txtid >= 0)) {
/* Map to assigned ID in global tile table: preserve modifier */
txtid =findOrAddDynamicTile(srctxtid, txtid);
}
if(srctxtid == TXTID_INVALID) {
throw new NumberFormatException("Invalid texture ID: no default terrain.png: " + val);
}
return txtid + (COLORMOD_MULT_INTERNAL * funcid);
}
/**
* Load texture pack mappings from tilesets.txt file
*/
private static void loadTileSetsFile(InputStream txtfile, String txtname, ConfigurationNode config, DynmapCore core, String blockset) {
LineNumberReader rdr = null;
DynamicTileFile tfile = null;
try {
String line;
rdr = new LineNumberReader(new InputStreamReader(txtfile));
while((line = rdr.readLine()) != null) {
if(line.startsWith("
}
else if(line.startsWith("tileset:")) { /* Start of tileset definition */
line = line.substring(line.indexOf(':')+1);
int xdim = 16, ydim = 16;
String fname = null;
String setdir = null;
String[] toks = line.split(",");
for(String tok : toks) {
String[] v = tok.split("=");
if(v.length < 2) continue;
if(v[0].equals("xcount")) {
xdim = Integer.parseInt(v[1]);
}
else if(v[0].equals("ycount")) {
ydim = Integer.parseInt(v[1]);
}
else if(v[0].equals("setdir")) {
setdir = v[1];
}
else if(v[0].equals("filename")) {
fname = v[1];
}
}
if ((fname != null) && (setdir != null)) {
/* Register tile file */
int fid = findOrAddDynamicTileFile(fname, null, xdim, ydim, TileFileFormat.TILESET, new String[0]);
tfile = addonfiles.get(fid);
if (tfile == null) {
Log.severe("Error registering tile set " + fname + " at " + rdr.getLineNumber() + " of " + txtname);
return;
}
/* Initialize tile name map and set directory path */
tfile.tilenames = new String[tfile.tile_to_dyntile.length];
}
else {
Log.severe("Error defining tile set at " + rdr.getLineNumber() + " of " + txtname);
return;
}
}
else if(Character.isDigit(line.charAt(0))) { /* Starts with digit? tile mapping */
int split = line.indexOf('-'); /* Find first dash */
if(split < 0) continue;
String id = line.substring(0, split).trim();
String name = line.substring(split+1).trim();
String[] coord = id.split(",");
int idx = -1;
if(coord.length == 2) { /* If x,y */
idx = (Integer.parseInt(coord[1]) * tfile.tilecnt_x) + Integer.parseInt(coord[0]);
}
else if(coord.length == 1) { /* Just index */
idx = Integer.parseInt(coord[0]);
}
if((idx >= 0) && (idx < tfile.tilenames.length)) {
tfile.tilenames[idx] = name;
}
else {
Log.severe("Bad tile index - line " + rdr.getLineNumber() + " of " + txtname);
}
}
}
} catch (IOException iox) {
Log.severe("Error reading " + txtname + " - " + iox.toString());
} catch (NumberFormatException nfx) {
Log.severe("Format error - line " + rdr.getLineNumber() + " of " + txtname + ": " + nfx.getMessage());
} finally {
if(rdr != null) {
try {
rdr.close();
rdr = null;
} catch (IOException e) {
}
}
}
}
private static final int TXTID_INVALID = -2;
private static final int TXTID_TERRAINPNG = -1;
/**
* Load texture pack mappings from texture.txt file
*/
private static void loadTextureFile(InputStream txtfile, String txtname, ConfigurationNode config, DynmapCore core, String blockset) {
LineNumberReader rdr = null;
int cnt = 0;
HashMap<String,Integer> filetoidx = new HashMap<String,Integer>();
HashMap<String,Integer> varvals = new HashMap<String,Integer>();
final String mcver = core.getDynmapPluginPlatformVersion();
boolean mod_cfg_needed = false;
boolean mod_cfg_loaded = false;
String modname = null;
String modversion = null;
String texturemod = null;
String texturepath = null;
boolean terrain_ok = true;
try {
String line;
rdr = new LineNumberReader(new InputStreamReader(txtfile));
while((line = rdr.readLine()) != null) {
boolean skip = false;
if ((line.length() > 0) && (line.charAt(0) == '[')) { // If version constrained like
int end = line.indexOf(']'); // Find end
if (end < 0) {
Log.severe("Format error - line " + rdr.getLineNumber() + " of " + txtname + ": bad version limit");
return;
}
String vertst = line.substring(1, end);
String tver = mcver;
if (vertst.startsWith("mod:")) { // If mod version ranged
tver = modversion;
vertst = vertst.substring(4);
}
if (!HDBlockModels.checkVersionRange(tver, vertst)) {
skip = true;
}
line = line.substring(end+1);
}
// If we're skipping due to version restriction
if (skip) {
}
else if(line.startsWith("block:")) {
ArrayList<Integer> blkids = new ArrayList<Integer>();
int databits = -1;
int srctxtid = TXTID_TERRAINPNG;
if (!terrain_ok)
srctxtid = TXTID_INVALID; // Mark as not usable
int faces[] = new int[] { TILEINDEX_BLANK, TILEINDEX_BLANK, TILEINDEX_BLANK, TILEINDEX_BLANK, TILEINDEX_BLANK, TILEINDEX_BLANK };
int txtidx[] = new int[] { -1, -1, -1, -1, -1, -1 };
byte layers[] = null;
line = line.substring(6);
BlockTransparency trans = BlockTransparency.OPAQUE;
int colorMult = 0;
boolean stdrot = false; // Legacy top/bottom rotation
CustomColorMultiplier custColorMult = null;
String[] args = line.split(",");
for(String a : args) {
String[] av = a.split("=");
if(av.length < 2) continue;
else if(av[0].equals("txtid")) {
if(filetoidx.containsKey(av[1]))
srctxtid = filetoidx.get(av[1]);
else
Log.severe("Format error - line " + rdr.getLineNumber() + " of " + txtname + ": bad texture " + av[1]);
}
}
// Build ID list : abort rest of processing if no valid values
for(String a : args) {
String[] av = a.split("=");
if(av.length < 2) continue;
if(av[0].equals("id")) {
Integer id = getIntValue(varvals, av[1]);
if ((id != null) && (id > 0)) {
blkids.add(id);
}
}
}
boolean userenderdata = false;
if (blkids.size() > 0) {
for(String a : args) {
String[] av = a.split("=");
if(av.length < 2) continue;
if(av[0].equals("data")) {
if(databits < 0) databits = 0;
if(av[1].equals("*"))
databits = 0xFFFF;
else
databits |= (1 << getIntValue(varvals,av[1]));
}
else if(av[0].equals("top") || av[0].equals("y-") || av[0].equals("face1")) {
faces[BlockStep.Y_MINUS.ordinal()] = parseTextureIndex(filetoidx, srctxtid, av[1]);
}
else if(av[0].equals("bottom") || av[0].equals("y+") || av[0].equals("face0")) {
faces[BlockStep.Y_PLUS.ordinal()] = parseTextureIndex(filetoidx, srctxtid, av[1]);
}
else if(av[0].equals("north") || av[0].equals("x+") || av[0].equals("face4")) {
faces[BlockStep.X_PLUS.ordinal()] = parseTextureIndex(filetoidx, srctxtid, av[1]);
}
else if(av[0].equals("south") || av[0].equals("x-") || av[0].equals("face5")) {
faces[BlockStep.X_MINUS.ordinal()] = parseTextureIndex(filetoidx, srctxtid, av[1]);
}
else if(av[0].equals("west") || av[0].equals("z-") || av[0].equals("face3")) {
faces[BlockStep.Z_MINUS.ordinal()] = parseTextureIndex(filetoidx, srctxtid, av[1]);
}
else if(av[0].equals("east") || av[0].equals("z+") || av[0].equals("face2")) {
faces[BlockStep.Z_PLUS.ordinal()] = parseTextureIndex(filetoidx, srctxtid, av[1]);
}
else if(av[0].startsWith("face")) {
int fid0, fid1;
String idrange = av[0].substring(4);
String[] ids = idrange.split("-");
if(ids.length > 1) {
fid0 = Integer.parseInt(ids[0]);
fid1 = Integer.parseInt(ids[1]);
}
else {
fid0 = fid1 = Integer.parseInt(ids[0]);
}
if((fid0 < 0) || (fid1 < fid0)) {
Log.severe("Texture mapping has invalid face index - " + av[1] + " - line " + rdr.getLineNumber() + " of " + txtname);
return;
}
int faceToOrd[] = { BlockStep.Y_PLUS.ordinal(), BlockStep.Y_MINUS.ordinal(),
BlockStep.Z_PLUS.ordinal(), BlockStep.Z_MINUS.ordinal(),
BlockStep.X_PLUS.ordinal(), BlockStep.X_MINUS.ordinal()
};
int txtid = parseTextureIndex(filetoidx, srctxtid, av[1]);
for(int i = fid0; (i <= fid1) && (i < 6); i++) {
faces[faceToOrd[i]] = txtid;
}
}
else if(av[0].equals("allfaces")) {
int id = parseTextureIndex(filetoidx, srctxtid, av[1]);
for(int i = 0; i < 6; i++) {
faces[i] = id;
}
}
else if(av[0].equals("allsides")) {
int id = parseTextureIndex(filetoidx, srctxtid, av[1]);
faces[BlockStep.X_PLUS.ordinal()] = id;
faces[BlockStep.X_MINUS.ordinal()] = id;
faces[BlockStep.Z_PLUS.ordinal()] = id;
faces[BlockStep.Z_MINUS.ordinal()] = id;
}
else if(av[0].equals("topbottom")) {
faces[BlockStep.Y_MINUS.ordinal()] =
faces[BlockStep.Y_PLUS.ordinal()] = parseTextureIndex(filetoidx, srctxtid, av[1]);
}
else if(av[0].startsWith("patch")) {
int patchid0, patchid1;
String idrange = av[0].substring(5);
String[] ids = idrange.split("-");
if(ids.length > 1) {
patchid0 = Integer.parseInt(ids[0]);
patchid1 = Integer.parseInt(ids[1]);
}
else {
patchid0 = patchid1 = Integer.parseInt(ids[0]);
}
if((patchid0 < 0) || (patchid1 < patchid0)) {
Log.severe("Texture mapping has invalid patch index - " + av[1] + " - line " + rdr.getLineNumber() + " of " + txtname);
return;
}
if(faces.length <= patchid1) {
int[] newfaces = new int[patchid1+1];
Arrays.fill(newfaces, TILEINDEX_BLANK);
System.arraycopy(faces, 0, newfaces, 0, faces.length);
faces = newfaces;
int[] newtxtidx = new int[patchid1+1];
Arrays.fill(newtxtidx, -1);
System.arraycopy(txtidx, 0, newtxtidx, 0, txtidx.length);
txtidx = newtxtidx;
}
int txtid = parseTextureIndex(filetoidx, srctxtid, av[1]);
for(int i = patchid0; i <= patchid1; i++) {
faces[i] = txtid;
}
}
else if(av[0].equals("transparency")) {
trans = BlockTransparency.valueOf(av[1]);
if(trans == null) {
trans = BlockTransparency.OPAQUE;
Log.severe("Texture mapping has invalid transparency setting - " + av[1] + " - line " + rdr.getLineNumber() + " of " + txtname);
}
/* For leaves, base on leaf transparency setting */
if(trans == BlockTransparency.LEAVES) {
if(core.getLeafTransparency())
trans = BlockTransparency.TRANSPARENT;
else
trans = BlockTransparency.OPAQUE;
}
/* If no water lighting fix */
if((blkids.contains(8) || blkids.contains(9)) && (HDMapManager.waterlightingfix == false)) {
trans = BlockTransparency.TRANSPARENT; /* Treat water as transparent if no fix */
}
}
else if(av[0].equals("userenderdata")) {
userenderdata = av[1].equals("true");
}
else if(av[0].equals("colorMult")) {
colorMult = (int)Long.parseLong(av[1], 16);
}
else if(av[0].equals("custColorMult")) {
try {
Class<?> cls = Class.forName(av[1]);
custColorMult = (CustomColorMultiplier)cls.newInstance();
} catch (Exception x) {
Log.severe("Error loading custom color multiplier - " + av[1] + ": " + x.getMessage());
}
}
else if(av[0].equals("stdrot")) {
stdrot = av[1].equals("true");
}
}
for(String a : args) {
String[] av = a.split("=");
if(av.length < 2) continue;
if(av[0].startsWith("layer")) {
if(layers == null) {
layers = new byte[faces.length];
Arrays.fill(layers, (byte)-1);
}
String v[] = av[0].substring(5).split("-");
int id1, id2;
id1 = id2 = Integer.parseInt(v[0]);
if(v.length > 1) {
id2 = Integer.parseInt(v[1]);
}
byte val = (byte)Integer.parseInt(av[1]);
for(; id1 <= id2; id1++) {
layers[id1] = val;
}
}
}
/* If no data bits, assume all */
if(databits < 0) databits = 0xFFFF;
/* If we have everything, build block */
if(blkids.size() > 0) {
HDTextureMap map = new HDTextureMap(blkids, databits, faces, layers, trans, userenderdata, colorMult, custColorMult, blockset, stdrot);
map.addToTable();
cnt++;
}
else {
Log.severe("Texture mapping missing required parameters = line " + rdr.getLineNumber() + " of " + txtname);
}
}
}
else if(line.startsWith("copyblock:")) {
ArrayList<Integer> blkids = new ArrayList<Integer>();
int databits = -1;
line = line.substring(line.indexOf(':')+1);
String[] args = line.split(",");
int srcid = -1;
int srcmeta = 0;
for(String a : args) {
String[] av = a.split("=");
if(av.length < 2) continue;
if(av[0].equals("id")) {
Integer id = getIntValue(varvals, av[1]);
if ((id != null) && (id > 0)) {
blkids.add(id);
}
}
else if(av[0].equals("data")) {
if(databits < 0) databits = 0;
if(av[1].equals("*"))
databits = 0xFFFF;
else
databits |= (1 << getIntValue(varvals,av[1]));
}
else if(av[0].equals("srcid")) {
srcid = getIntValue(varvals, av[1]);
}
else if(av[0].equals("srcmeta")) {
srcmeta = getIntValue(varvals,av[1]);
}
}
/* If no data bits, assume all */
if(databits < 0) databits = 0xFFFF;
/* If we have everything, build block */
if((blkids.size() > 0) && (srcid > 0)) {
HDTextureMap map = HDTextureMap.getMap(srcid, srcmeta, srcmeta);
if (map == null) {
Log.severe("Copy of texture mapping failed = line " + rdr.getLineNumber() + " of " + txtname);
}
else {
HDTextureMap nmap = new HDTextureMap(blkids, databits, map);
nmap.addToTable();
cnt++;
}
}
else {
Log.severe("Texture mapping copy missing required parameters = line " + rdr.getLineNumber() + " of " + txtname);
}
}
else if(line.startsWith("addtotexturemap:")) {
int srctxtid = -1;
String mapid = null;
line = line.substring(line.indexOf(':') + 1);
String[] args = line.split(",");
for(String a : args) {
String[] av = a.split("=");
if(av.length < 2) continue;
else if(av[0].equals("txtid")) {
if(filetoidx.containsKey(av[1]))
srctxtid = filetoidx.get(av[1]);
else
Log.severe("Format error - line " + rdr.getLineNumber() + " of " + txtname);
}
else if(av[0].equals("mapid")) {
mapid = av[1];
}
}
if(mapid != null) {
for(String a : args) {
String[] av = a.split("=");
if(av.length < 2) continue;
if(av[0].startsWith("key:")) {
Integer key = getIntValue(varvals, av[0].substring(4));
if ((key != null) && (key > 0)) {
addTextureByKey(mapid, key, parseTextureIndex(filetoidx, srctxtid, av[1]));
}
}
}
}
else {
Log.severe("Missing mapid - line " + rdr.getLineNumber() + " of " + txtname);
}
}
else if(line.startsWith("texturemap:")) {
ArrayList<Integer> blkids = new ArrayList<Integer>();
int databits = -1;
String mapid = null;
line = line.substring(line.indexOf(':') + 1);
BlockTransparency trans = BlockTransparency.OPAQUE;
int colorMult = 0;
CustomColorMultiplier custColorMult = null;
String[] args = line.split(",");
boolean userenderdata = false;
for(String a : args) {
String[] av = a.split("=");
if(av.length < 2) continue;
if(av[0].equals("id")) {
Integer id = getIntValue(varvals, av[1]);
if ((id != null) && (id > 0)) {
blkids.add(id);
}
}
else if(av[0].equals("mapid")) {
mapid = av[1];
}
else if(av[0].equals("data")) {
if(databits < 0) databits = 0;
if(av[1].equals("*"))
databits = 0xFFFF;
else
databits |= (1 << getIntValue(varvals,av[1]));
}
else if(av[0].equals("transparency")) {
trans = BlockTransparency.valueOf(av[1]);
if(trans == null) {
trans = BlockTransparency.OPAQUE;
Log.severe("Texture mapping has invalid transparency setting - " + av[1] + " - line " + rdr.getLineNumber() + " of " + txtname);
}
/* For leaves, base on leaf transparency setting */
if(trans == BlockTransparency.LEAVES) {
if(core.getLeafTransparency())
trans = BlockTransparency.TRANSPARENT;
else
trans = BlockTransparency.OPAQUE;
}
/* If no water lighting fix */
if((blkids.contains(8) || blkids.contains(9)) && (HDMapManager.waterlightingfix == false)) {
trans = BlockTransparency.TRANSPARENT; /* Treat water as transparent if no fix */
}
}
else if(av[0].equals("userenderdata")) {
userenderdata = av[1].equals("true");
}
else if(av[0].equals("colorMult")) {
colorMult = Integer.valueOf(av[1], 16);
}
else if(av[0].equals("custColorMult")) {
try {
Class<?> cls = Class.forName(av[1]);
custColorMult = (CustomColorMultiplier)cls.newInstance();
} catch (Exception x) {
Log.severe("Error loading custom color multiplier - " + av[1] + ": " + x.getMessage());
}
}
}
/* If no data bits, assume all */
if(databits < 0) databits = 0xFFFF;
/* If we have everything, build texture map */
if((blkids.size() > 0) && (mapid != null)) {
addTextureIndex(mapid, blkids, databits, trans, userenderdata, colorMult, custColorMult, blockset);
}
else {
Log.severe("Texture map missing required parameters = line " + rdr.getLineNumber() + " of " + txtname);
}
}
else if(line.startsWith("texturefile:") || line.startsWith("texture:")) {
boolean istxt = line.startsWith("texture:");
line = line.substring(line.indexOf(':')+1);
String[] args = line.split(",");
int xdim = 16, ydim = 16;
String fname = null;
String id = null;
TileFileFormat fmt = TileFileFormat.GRID;
MaterialType mt = null;
if(istxt) {
xdim = ydim = 1;
fmt = TileFileFormat.GRID;
}
for(String arg : args) {
String[] aval = arg.split("=");
if(aval.length < 2)
continue;
if(aval[0].equals("id")) {
id = aval[1];
if (fname == null) {
if (texturepath != null) {
fname = texturepath + id + ".png";
}
else if (texturemod != null) {
fname = "mods/" + texturemod + "/textures/blocks/" + id + ".png";
}
}
}
else if(aval[0].equals("filename"))
fname = aval[1];
else if(aval[0].equals("xcount"))
xdim = Integer.parseInt(aval[1]);
else if(aval[0].equals("ycount"))
ydim = Integer.parseInt(aval[1]);
else if(aval[0].equals("format")) {
fmt = TileFileFormat.valueOf(aval[1].toUpperCase());
if(fmt == null) {
Log.severe("Invalid format type " + aval[1] + " - line " + rdr.getLineNumber() + " of " + txtname);
return;
}
}
else if(aval[0].equals("material")) {
mt = MaterialType.valueOf(aval[1]);
if (mt == null) {
Log.warning("Bad custom material type: " + aval[1]);
}
}
}
if((fname != null) && (id != null)) {
/* Register the file */
int fid = findOrAddDynamicTileFile(fname, modname, xdim, ydim, fmt, args);
filetoidx.put(id, fid); /* Save lookup */
if (mt != null) {
addonfiles.get(fid).material = mt;
}
}
else {
Log.severe("Format error - line " + rdr.getLineNumber() + " of " + txtname);
return;
}
}
else if(line.startsWith("#") || line.startsWith(";")) {
}
else if(line.startsWith("enabled:")) { /* Test if texture file is enabled */
line = line.substring(8).trim();
if(line.startsWith("true")) { /* We're enabled? */
/* Nothing to do - keep processing */
}
else if(line.startsWith("false")) { /* Disabled */
return; /* Quit */
}
/* If setting is not defined or false, quit */
else if(config.getBoolean(line, false) == false) {
return;
}
else {
Log.info(line + " textures enabled");
}
}
else if(line.startsWith("var:")) { /* Test if variable declaration */
line = line.substring(4).trim();
String args[] = line.split(",");
for(int i = 0; i < args.length; i++) {
String[] v = args[i].split("=");
if(v.length < 2) {
Log.severe("Format error - line " + rdr.getLineNumber() + " of " + txtname);
return;
}
try {
int val = Integer.valueOf(v[1]); /* Parse default value */
int parmval = config.getInteger(v[0], val); /* Read value, with applied default */
varvals.put(v[0], parmval); /* And save value */
} catch (NumberFormatException nfx) {
Log.severe("Format error - line " + rdr.getLineNumber() + " of " + txtname + ": " + nfx.getMessage());
return;
}
}
}
else if(line.startsWith("cfgfile:")) { /* If config file */
if (!mod_cfg_loaded) {
mod_cfg_needed = true;
}
File cfgfile = new File(line.substring(8).trim());
ForgeConfigFile cfg = new ForgeConfigFile(cfgfile);
if(cfg.load()) {
cfg.addBlockIDs(varvals);
mod_cfg_needed = false;
mod_cfg_loaded = true;
}
}
else if(line.startsWith("modname:")) {
String[] names = line.substring(8).split(",");
boolean found = false;
for(String n : names) {
String[] ntok = n.split("[\\[\\]]");
String rng = null;
if (ntok.length > 1) {
n = ntok[0].trim();
rng = ntok[1].trim();
}
n = n.trim();
// If already supplied by mod, quit processing this file
if (loadedmods.contains(n)) {
return;
}
String modver = core.getServer().getModVersion(n);
if((modver != null) && ((rng == null) || HDBlockModels.checkVersionRange(modver, rng))) {
found = true;
Log.info(n + "[" + modver + "] textures enabled");
modname = n;
modversion = modver;
if(texturemod == null) texturemod = modname;
loadedmods.add(n);
// Prime values from block and item unique IDs
core.addModBlockItemIDs(modname, varvals);
break;
}
}
if(!found) return;
}
else if(line.startsWith("texturemod:")) {
texturemod = line.substring(line.indexOf(':')+1).trim();
}
else if(line.startsWith("texturepath:")) {
texturepath = line.substring(line.indexOf(':')+1).trim();
if (texturepath.charAt(texturepath.length()-1) != '/') {
texturepath += "/";
}
}
else if(line.startsWith("biome:")) {
line = line.substring(6).trim();
String args[] = line.split(",");
int id = 0;
int grasscolormult = -1;
int foliagecolormult = -1;
int watercolormult = -1;
double rain = -1.0;
double tmp = -1.0;
for(int i = 0; i < args.length; i++) {
String[] v = args[i].split("=");
if(v.length < 2) {
Log.severe("Format error - line " + rdr.getLineNumber() + " of " + txtname);
return;
}
if(v[0].equals("id")) {
id = getIntValue(varvals, v[1]);
}
else if(v[0].equals("grassColorMult")) {
grasscolormult = Integer.valueOf(v[1], 16);
}
else if(v[0].equals("foliageColorMult")) {
foliagecolormult = Integer.valueOf(v[1], 16);
}
else if(v[0].equals("waterColorMult")) {
watercolormult = Integer.valueOf(v[1], 16);
}
else if(v[0].equals("temp")) {
tmp = Double.parseDouble(v[1]);
}
else if(v[0].equals("rain")) {
rain = Double.parseDouble(v[1]);
}
}
if(id > 0) {
BiomeMap b = BiomeMap.byBiomeID(id); /* Find biome */
if(b == null) {
Log.severe("Format error - line " + rdr.getLineNumber() + " of " + txtname + ": " + id);
}
else {
if(foliagecolormult != -1)
b.setFoliageColorMultiplier(foliagecolormult);
if(grasscolormult != -1)
b.setGrassColorMultiplier(grasscolormult);
if(watercolormult != -1)
b.setWaterColorMultiplier(watercolormult);
if(tmp != -1.0)
b.setTemperature(tmp);
if(rain != -1.0)
b.setRainfall(rain);
}
}
}
else if(line.startsWith("version:")) {
line = line.substring(line.indexOf(':')+1);
if (!HDBlockModels.checkVersionRange(mcver, line)) {
return;
}
}
else if(line.startsWith("noterrainpng:")) {
line = line.substring(line.indexOf(':')+1);
if (line.startsWith("true")) {
terrain_ok = false;
}
else {
terrain_ok = true;
}
}
}
if(mod_cfg_needed) {
Log.severe("Error loading configuration file for " + modname);
}
Log.verboseinfo("Loaded " + cnt + " texture mappings from " + txtname);
} catch (IOException iox) {
Log.severe("Error reading " + txtname + " - " + iox.toString());
} catch (NumberFormatException nfx) {
Log.severe("Format error - line " + rdr.getLineNumber() + " of " + txtname + ": " + nfx.getMessage());
} finally {
if(rdr != null) {
try {
rdr.close();
rdr = null;
} catch (IOException e) {
}
}
}
}
/* Process any block aliases */
public static void handleBlockAlias() {
for(int i = 0; i < BLOCKTABLELEN; i++) {
int id = MapManager.mapman.getBlockIDAlias(i);
if(id != i) { /* New mapping? */
HDTextureMap.remapTexture(i, id);
}
}
}
private static final int BLOCKID_GRASS = 2;
private static final int BLOCKID_SNOW = 78;
/**
* Read color for given subblock coordinate, with given block id and data and face
*/
public final void readColor(final HDPerspectiveState ps, final MapIterator mapiter, final Color rslt, final int blkid, final int lastblocktype,
final TexturePackHDShader.ShaderState ss) {
int blkdata = ps.getBlockData();
HDTextureMap map = HDTextureMap.getMap(blkid, blkdata, ps.getBlockRenderData());
BlockStep laststep = ps.getLastBlockStep();
int patchid = ps.getTextureIndex(); /* See if patch index */
int textid;
int faceindex;
if(patchid >= 0) {
faceindex = patchid;
}
else {
faceindex = laststep.ordinal();
}
textid = map.faces[faceindex];
if (ctm != null) {
int mod = 0;
if(textid >= COLORMOD_MULT_INTERNAL) {
mod = (textid / COLORMOD_MULT_INTERNAL) * COLORMOD_MULT_INTERNAL;
textid -= mod;
}
textid = mod + ctm.mapTexture(mapiter, blkid, blkdata, laststep, textid, ss);
}
readColor(ps, mapiter, rslt, blkid, lastblocktype, ss, blkdata, map, laststep, patchid, textid, map.stdrotate);
if(map.layers != null) { /* If layered */
/* While transparent and more layers */
while(rslt.isTransparent() && (map.layers[faceindex] >= 0)) {
faceindex = map.layers[faceindex];
textid = map.faces[faceindex];
readColor(ps, mapiter, rslt, blkid, lastblocktype, ss, blkdata, map, laststep, patchid, textid, map.stdrotate);
}
}
}
/**
* Read color for given subblock coordinate, with given block id and data and face
*/
private final void readColor(final HDPerspectiveState ps, final MapIterator mapiter, final Color rslt, final int blkid, final int lastblocktype,
final TexturePackHDShader.ShaderState ss, int blkdata, HDTextureMap map, BlockStep laststep, int patchid, int textid, boolean stdrot) {
if(textid < 0) {
rslt.setTransparent();
return;
}
int blkindex = indexByIDMeta(blkid, blkdata);
boolean hasblockcoloring = ss.do_biome_shading && hasBlockColoring.get(blkindex);
// Test if we have no texture modifications
boolean simplemap = (textid < COLORMOD_MULT_INTERNAL) && (!hasblockcoloring);
if (simplemap) { /* If simple mapping */
int[] texture = getTileARGB(textid);
/* Get texture coordinates (U=horizontal(left=0),V=vertical(top=0)) */
int u = 0, v = 0;
/* If not patch, compute U and V */
if(patchid < 0) {
int[] xyz = ps.getSubblockCoord();
switch(laststep) {
case X_MINUS: /* South face: U = East (Z-), V = Down (Y-) */
u = native_scale-xyz[2]-1; v = native_scale-xyz[1]-1;
break;
case X_PLUS: /* North face: U = West (Z+), V = Down (Y-) */
u = xyz[2]; v = native_scale-xyz[1]-1;
break;
case Z_MINUS: /* West face: U = South (X+), V = Down (Y-) */
u = xyz[0]; v = native_scale-xyz[1]-1;
break;
case Z_PLUS: /* East face: U = North (X-), V = Down (Y-) */
u = native_scale-xyz[0]-1; v = native_scale-xyz[1]-1;
break;
case Y_MINUS: /* U = East(Z-), V = South(X+) */
if(stdrot) {
u = xyz[0]; v = xyz[2];
}
else {
u = native_scale-xyz[2]-1; v = xyz[0];
}
break;
case Y_PLUS:
if(stdrot) {
u = native_scale-xyz[0]-1; v = xyz[2];
}
else {
u = xyz[2]; v = xyz[0];
}
break;
}
}
else {
u = fastFloor(ps.getPatchU() * native_scale);
v = native_scale - fastFloor(ps.getPatchV() * native_scale) - 1;
}
/* Read color from texture */
try {
rslt.setARGB(texture[v*native_scale + u]);
} catch(ArrayIndexOutOfBoundsException aoobx) {
u = ((u < 0) ? 0 : ((u >= native_scale) ? (native_scale-1) : u));
v = ((v < 0) ? 0 : ((v >= native_scale) ? (native_scale-1) : v));
try {
rslt.setARGB(texture[v*native_scale + u]);
} catch(ArrayIndexOutOfBoundsException oob2) { }
}
return;
}
/* See if not basic block texture */
int textop = textid / COLORMOD_MULT_INTERNAL;
textid = textid % COLORMOD_MULT_INTERNAL;
/* If clear-inside op, get out early */
if((textop == COLORMOD_CLEARINSIDE) || (textop == COLORMOD_MULTTONED_CLEARINSIDE)) {
/* Check if previous block is same block type as we are: surface is transparent if it is */
if(blkid == lastblocktype) {
rslt.setTransparent();
return;
}
/* If water block, to watercolor tone op */
if((blkid == 8) || (blkid == 9)) {
textop = COLORMOD_WATERTONED;
}
else if(textop == COLORMOD_MULTTONED_CLEARINSIDE) {
textop = COLORMOD_MULTTONED;
}
}
int[] texture = getTileARGB(textid);
/* Get texture coordinates (U=horizontal(left=0),V=vertical(top=0)) */
int u = 0, v = 0, tmp;
if(patchid < 0) {
int[] xyz = ps.getSubblockCoord();
switch(laststep) {
case X_MINUS: /* South face: U = East (Z-), V = Down (Y-) */
u = native_scale-xyz[2]-1; v = native_scale-xyz[1]-1;
break;
case X_PLUS: /* North face: U = West (Z+), V = Down (Y-) */
u = xyz[2]; v = native_scale-xyz[1]-1;
break;
case Z_MINUS: /* West face: U = South (X+), V = Down (Y-) */
u = xyz[0]; v = native_scale-xyz[1]-1;
break;
case Z_PLUS: /* East face: U = North (X-), V = Down (Y-) */
u = native_scale-xyz[0]-1; v = native_scale-xyz[1]-1;
break;
case Y_MINUS: /* U = East(Z-), V = South(X+) */
if(stdrot) {
u = xyz[0]; v = xyz[2];
}
else {
u = native_scale-xyz[2]-1; v = xyz[0];
}
break;
case Y_PLUS:
if(stdrot) {
u = native_scale-xyz[0]-1; v = xyz[2];
}
else {
u = xyz[2]; v = xyz[0];
}
break;
}
}
else {
u = fastFloor(ps.getPatchU() * native_scale);
v = native_scale - fastFloor(ps.getPatchV() * native_scale) - 1;
}
/* Handle U-V transorms before fetching color */
switch(textop) {
case COLORMOD_ROT90:
tmp = u; u = native_scale - v - 1; v = tmp;
break;
case COLORMOD_ROT180:
u = native_scale - u - 1; v = native_scale - v - 1;
break;
case COLORMOD_ROT270:
case COLORMOD_GRASSTONED270:
case COLORMOD_FOLIAGETONED270:
case COLORMOD_WATERTONED270:
tmp = u; u = v; v = native_scale - tmp - 1;
break;
case COLORMOD_FLIPHORIZ:
u = native_scale - u - 1;
break;
case COLORMOD_SHIFTDOWNHALF:
if(v < native_scale/2) {
rslt.setTransparent();
return;
}
v -= native_scale/2;
break;
case COLORMOD_SHIFTDOWNHALFANDFLIPHORIZ:
if(v < native_scale/2) {
rslt.setTransparent();
return;
}
v -= native_scale/2;
u = native_scale - u - 1;
break;
case COLORMOD_INCLINEDTORCH:
if(v >= (3*native_scale/4)) {
rslt.setTransparent();
return;
}
v += native_scale/4;
if(u < native_scale/2) u = native_scale/2-1;
if(u > native_scale/2) u = native_scale/2;
break;
case COLORMOD_GRASSSIDE:
boolean do_grass_side = false;
boolean do_snow_side = false;
if(ss.do_better_grass) {
mapiter.unstepPosition(laststep);
if(mapiter.getBlockTypeID() == BLOCKID_SNOW)
do_snow_side = true;
if(mapiter.getBlockTypeIDAt(BlockStep.Y_MINUS) == BLOCKID_GRASS)
do_grass_side = true;
mapiter.stepPosition(laststep);
}
/* Check if snow above block */
if(mapiter.getBlockTypeIDAt(BlockStep.Y_PLUS) == BLOCKID_SNOW) {
if(do_snow_side) {
texture = getTileARGB(TILEINDEX_SNOW); /* Snow full side block */
textid = TILEINDEX_SNOW;
}
else {
texture = getTileARGB(TILEINDEX_SNOWSIDE); /* Snow block */
textid = TILEINDEX_SNOWSIDE;
}
textop = 0;
}
else { /* Else, check the grass color overlay */
if(do_grass_side) {
texture = getTileARGB(TILEINDEX_GRASS); /* Grass block */
textid = TILEINDEX_GRASS;
textop = COLORMOD_GRASSTONED; /* Force grass toning */
}
else {
int ovclr = getTileARGB(TILEINDEX_GRASSMASK)[v*native_scale+u];
if((ovclr & 0xFF000000) != 0) { /* Hit? */
texture = getTileARGB(TILEINDEX_GRASSMASK); /* Use it */
textop = COLORMOD_GRASSTONED; /* Force grass toning */
}
}
}
break;
case COLORMOD_LILYTONED:
/* Rotate texture based on lily orientation function (from renderBlockLilyPad in RenderBlocks.jara in MCP) */
long l1 = (long)(mapiter.getX() * 0x2fc20f) ^ (long)mapiter.getZ() * 0x6ebfff5L ^ (long)mapiter.getY();
l1 = l1 * l1 * 0x285b825L + l1 * 11L;
int orientation = (int)(l1 >> 16 & 3L);
switch(orientation) {
case 0:
tmp = u; u = native_scale - v - 1; v = tmp;
break;
case 1:
u = native_scale - u - 1; v = native_scale - v - 1;
break;
case 2:
tmp = u; u = v; v = native_scale - tmp - 1;
break;
case 3:
break;
}
break;
}
/* Read color from texture */
try {
rslt.setARGB(texture[v*native_scale + u]);
} catch (ArrayIndexOutOfBoundsException aioobx) {
rslt.setARGB(0);
}
int clrmult = -1;
int clralpha = 0xFF000000;
int custclrmult = -1;
// If block has custom coloring
if (hasblockcoloring) {
Integer idx = (Integer) this.blockColoring.get(blkindex);
LoadedImage img = imgs[idx];
if (img.argb != null) {
custclrmult = mapiter.getSmoothWaterColorMultiplier(img.argb);
}
else {
hasblockcoloring = false;
}
}
//if (!hasblockcoloring) {
// Switch based on texture modifier
switch(textop) {
case COLORMOD_GRASSTONED:
case COLORMOD_GRASSTONED270:
if(ss.do_biome_shading) {
if(imgs[IMG_SWAMPGRASSCOLOR] != null)
clrmult = mapiter.getSmoothColorMultiplier(imgs[IMG_GRASSCOLOR].argb, imgs[IMG_SWAMPGRASSCOLOR].argb);
else
clrmult = mapiter.getSmoothGrassColorMultiplier(imgs[IMG_GRASSCOLOR].argb);
}
else {
clrmult = imgs[IMG_GRASSCOLOR].trivial_color;
}
break;
case COLORMOD_FOLIAGETONED:
case COLORMOD_FOLIAGETONED270:
if(ss.do_biome_shading) {
if(imgs[IMG_SWAMPFOLIAGECOLOR] != null)
clrmult = mapiter.getSmoothColorMultiplier(imgs[IMG_FOLIAGECOLOR].argb, imgs[IMG_SWAMPFOLIAGECOLOR].argb);
else
clrmult = mapiter.getSmoothFoliageColorMultiplier(imgs[IMG_FOLIAGECOLOR].argb);
}
else {
clrmult = imgs[IMG_FOLIAGECOLOR].trivial_color;
}
break;
case COLORMOD_FOLIAGEMULTTONED:
if(ss.do_biome_shading) {
if(imgs[IMG_SWAMPFOLIAGECOLOR] != null)
clrmult = mapiter.getSmoothColorMultiplier(imgs[IMG_FOLIAGECOLOR].argb, imgs[IMG_SWAMPFOLIAGECOLOR].argb);
else
clrmult = mapiter.getSmoothFoliageColorMultiplier(imgs[IMG_FOLIAGECOLOR].argb);
}
else {
clrmult = imgs[IMG_FOLIAGECOLOR].trivial_color;
}
if(map.custColorMult != null) {
clrmult = ((clrmult & 0xFEFEFE) + map.custColorMult.getColorMultiplier(mapiter)) / 2;
}
else {
clrmult = ((clrmult & 0xFEFEFE) + map.colorMult) / 2;
}
break;
case COLORMOD_WATERTONED:
case COLORMOD_WATERTONED270:
if(imgs[IMG_WATERCOLORX] != null) {
if(ss.do_biome_shading) {
clrmult = mapiter.getSmoothWaterColorMultiplier(imgs[IMG_WATERCOLORX].argb);
}
else {
clrmult = imgs[IMG_WATERCOLORX].trivial_color;
}
}
else {
if(ss.do_biome_shading) {
if (colorMultWater != 0xFFFFFF)
clrmult = colorMultWater;
else
clrmult = mapiter.getSmoothWaterColorMultiplier();
}
}
break;
case COLORMOD_BIRCHTONED:
if(ss.do_biome_shading) {
if(imgs[IMG_BIRCHCOLOR] != null)
clrmult = mapiter.getSmoothFoliageColorMultiplier(imgs[IMG_BIRCHCOLOR].argb);
else
clrmult = colorMultBirch;
}
else {
clrmult = colorMultBirch;
}
break;
case COLORMOD_PINETONED:
if(ss.do_biome_shading) {
if(imgs[IMG_PINECOLOR] != null)
clrmult = mapiter.getSmoothFoliageColorMultiplier(imgs[IMG_PINECOLOR].argb);
else
clrmult = colorMultPine;
}
else {
clrmult = colorMultPine;
}
break;
case COLORMOD_LILYTONED:
clrmult = colorMultLily;
break;
case COLORMOD_MULTTONED: /* Use color multiplier */
if(map.custColorMult != null) {
clrmult = map.custColorMult.getColorMultiplier(mapiter);
}
else {
clrmult = map.colorMult;
}
if((clrmult & 0xFF000000) != 0) {
clralpha = clrmult & 0xFF000000;
}
break;
}
if((clrmult != -1) && (clrmult != 0)) {
rslt.blendColor(clrmult | clralpha);
}
if (hasblockcoloring && (custclrmult != -1)) {
rslt.blendColor(custclrmult | clralpha);
}
}
private static final void makeAlphaPure(int[] argb) {
for(int i = 0; i < argb.length; i++) {
if((argb[i] & 0xFF000000) != 0)
argb[i] |= 0xFF000000;
}
}
private static final int fastFloor(double f) {
return ((int)(f + 1000000000.0)) - 1000000000;
}
/**
* Get tile index, based on tile file name and relative index within tile file
* @param fname - filename
* @param idx - tile index (= (y * xdim) + x)
* @return global tile index, or -1 if not found
*/
public static int findDynamicTile(String fname, int idx) {
DynamicTileFile f;
/* Find existing, if already there */
f = addonfilesbyname.get(fname);
if (f != null) {
if ((idx >= 0) && (idx < f.tile_to_dyntile.length) && (f.tile_to_dyntile[idx] >= 0)) {
f.used = true;
return f.tile_to_dyntile[idx];
}
}
return -1;
}
/**
* Add new dynmaic file definition, or return existing
*
* @param fname
* @param xdim
* @param ydim
* @param fmt
* @param args
* @return dynamic file index
*/
public static int findOrAddDynamicTileFile(String fname, String modname, int xdim, int ydim, TileFileFormat fmt, String[] args) {
DynamicTileFile f;
/* Find existing, if already there */
f = addonfilesbyname.get(fname);
if (f != null) {
return f.idx;
}
/* Add new tile file entry */
f = new DynamicTileFile();
f.filename = fname;
f.modname = modname;
f.tilecnt_x = xdim;
f.tilecnt_y = ydim;
f.format = fmt;
f.used = false;
// Assume all biome files are used (not referred to by index)
if (fmt == TileFileFormat.BIOME) {
f.used = true;
}
switch(fmt) {
case GRID:
f.tile_to_dyntile = new int[xdim*ydim];
break;
case CHEST:
f.tile_to_dyntile = new int[TILEINDEX_CHEST_COUNT]; /* 6 images for chest tile */
break;
case BIGCHEST:
f.tile_to_dyntile = new int[TILEINDEX_BIGCHEST_COUNT]; /* 10 images for chest tile */
break;
case SIGN:
f.tile_to_dyntile = new int[TILEINDEX_SIGN_COUNT]; /* 10 images for sign tile */
break;
case CUSTOM:
{
List<CustomTileRec> recs = new ArrayList<CustomTileRec>();
for(String a : args) {
String[] v = a.split("=");
if(v.length != 2) continue;
if(v[0].startsWith("tile")) {
int id = 0;
try {
id = Integer.parseInt(v[0].substring(4));
} catch (NumberFormatException nfx) {
Log.warning("Bad tile ID: " + v[0]);
continue;
}
while(recs.size() <= id) {
recs.add(null);
}
CustomTileRec rec = new CustomTileRec();
try {
String[] coords = v[1].split("/");
String[] topleft = coords[0].split(":");
rec.srcx = Integer.parseInt(topleft[0]);
rec.srcy = Integer.parseInt(topleft[1]);
String[] size = coords[1].split(":");
rec.width = Integer.parseInt(size[0]);
rec.height = Integer.parseInt(size[1]);
if(coords.length >= 3) {
String[] dest = coords[2].split(":");
rec.targetx = Integer.parseInt(dest[0]);
rec.targety = Integer.parseInt(dest[1]);
}
recs.set(id, rec);
} catch (Exception x) {
Log.warning("Bad custom tile coordinate: " + v[1]);
}
}
}
f.tile_to_dyntile = new int[recs.size()];
f.cust = recs;
}
break;
case SKIN:
f.tile_to_dyntile = new int[TILEINDEX_SKIN_COUNT]; /* 6 images for skin tile */
break;
case TILESET:
f.tile_to_dyntile = new int[xdim*ydim];
break;
default:
f.tile_to_dyntile = new int[xdim*ydim];
break;
}
Arrays.fill(f.tile_to_dyntile, -1);
f.idx = addonfiles.size();
addonfiles.add(f);
addonfilesbyname.put(f.filename, f);
return f.idx;
}
/**
* Add or find dynamic tile index of given dynamic tile
* @param dynfile_idx - index of file
* @param tile_id - ID of tile within file
* @return global tile ID
*/
public static int findOrAddDynamicTile(int dynfile_idx, int tile_id) {
DynamicTileFile f = addonfiles.get(dynfile_idx);
if(f == null) {
throw new NumberFormatException("Invalid add-on file index: " + dynfile_idx);
}
if (tile_id >= f.tile_to_dyntile.length) {
throw new NumberFormatException("Invalid index " + tile_id + " for texture file " + f.filename + " on mod " + f.modname);
}
if(f.tile_to_dyntile[tile_id] < 0) { /* Not assigned yet? */
f.tile_to_dyntile[tile_id] = next_dynamic_tile;
next_dynamic_tile++; /* Allocate next ID */
}
f.used = true; // Mark file as being used
return f.tile_to_dyntile[tile_id];
}
private static final int[] smooth_water_mult = new int[10];
public static int getTextureIDAt(MapIterator mapiter, int blkdata, int blkmeta, BlockStep face) {
HDTextureMap map = HDTextureMap.getMap(blkdata, blkmeta, blkmeta);
int idx = -1;
if (map != null) {
int sideidx = face.ordinal();
if (map.faces != null) {
if (sideidx < map.faces.length)
idx = map.faces[sideidx];
else
idx = map.faces[0];
}
}
if(idx > 0)
idx = idx % COLORMOD_MULT_INTERNAL;
return idx;
}
private static final String PALETTE_BLOCK_KEY = "palette.block.";
private void processCustomColorMap(String fname, String ids) {
// Register file name
int idx = findOrAddDynamicTileFile(fname, null, 1, 1, TileFileFormat.BIOME, new String[0]);
if(idx < 0) {
Log.info("Error registering custom color file: " + fname);
return;
}
Integer index = idx + IMG_CNT;
// Now, parse block ID list
for (String id : ids.split("\\s+")) {
String[] tok = id.split(":");
int meta = -1;
int blkid = -1;
if (tok.length == 1) { /* Only ID */
try {
blkid = Integer.parseInt(tok[0]);
} catch (NumberFormatException nfx) {
Log.info("Bad custom color block ID: " + tok[0]);
}
}
else if (tok.length == 2) { /* ID : meta */
try {
blkid = Integer.parseInt(tok[0]);
} catch (NumberFormatException nfx) {
Log.info("Bad custom color block ID: " + tok[0]);
}
try {
meta = Integer.parseInt(tok[1]);
} catch (NumberFormatException nfx) {
Log.info("Bad custom color meta ID: " + tok[1]);
}
}
/* Add mappings for values */
if ((blkid > 0) && (blkid < 4096)) {
if ((meta >= 0) && (meta < 16)) {
int idm = indexByIDMeta(blkid, meta);
this.hasBlockColoring.set(idm);
this.blockColoring.put(idm, index);
}
else if (meta == -1) { /* All meta IDs */
for (meta = 0; meta < 16; meta++) {
int idm = indexByIDMeta(blkid, meta);
this.hasBlockColoring.set(idm);
this.blockColoring.put(idm, index);
}
}
}
}
}
private void processCustomColors(Properties p) {
// Loop through keys
for(String pname : p.stringPropertyNames()) {
if(!pname.startsWith(PALETTE_BLOCK_KEY))
continue;
String v = p.getProperty(pname);
String fname = pname.substring(PALETTE_BLOCK_KEY.length()).trim(); // Get filename of color map
if(fname.charAt(0) == '/') fname = fname.substring(1); // Strip leading /
if(fname.charAt(0) == '~') fname = "assets/minecraft/mcpatcher" + fname.substring(1);
processCustomColorMap(fname, v);
}
}
private static final int indexByIDMeta(int blkid, int meta) {
return ((blkid << 4) | meta);
}
static {
/*
* Generate smoothed swamp multipliers (indexed by swamp biome count)
*/
Color c = new Color();
for(int i = 0; i < 10; i++) {
/* Use water color multiplier base for 1.1 (E0FFAE) */
int r = (((9-i) * 0xFF) + (i * 0xE0)) / 9;
int g = 0xFF;
int b = (((9-i) * 0xFF) + (i * 0xAE)) / 9;
c.setRGBA(r & 0xFE, g & 0xFE, b & 0xFE, 0xFF);
smooth_water_mult[i] = c.getARGB();
}
}
public int getTrivialFoliageMultiplier() {
return imgs[IMG_FOLIAGECOLOR].argb[BiomeMap.FOREST.biomeLookup()];
}
public int getTrivialGrassMultiplier() {
return imgs[IMG_GRASSCOLOR].argb[BiomeMap.FOREST.biomeLookup()];
}
public int getTrivialWaterMultiplier() {
if(imgs[IMG_WATERCOLORX] != null) {
return imgs[IMG_WATERCOLORX].argb[BiomeMap.FOREST.biomeLookup()];
}
else {
return 0xFFFFFF;
}
}
public int getCustomBlockMultiplier(int blkid, int blkdata) {
int blkindex = indexByIDMeta(blkid, blkdata);
if (hasBlockColoring.get(blkindex)) {
Integer idx = (Integer) this.blockColoring.get(blkindex);
LoadedImage img = imgs[idx];
if (img.argb != null) {
return img.argb[BiomeMap.FOREST.biomeLookup()];
}
}
return 0xFFFFFF;
}
private static class ExportedTexture {
public String filename;
public Color diffuseColor;
public String filename_a;
public MaterialType material;
}
private static class ExportedTexturePack {
Map<String, ExportedTexture> txtids = new HashMap<String, ExportedTexture>();
DynmapBufferedImage img;
OBJExport exp;
String name;
}
// Encode image as PNG and add to ZIP
private void addImageToZip(String idstr, int idx, int colormult, ExportedTexturePack etp) throws IOException {
if (etp.txtids.containsKey(idstr)) { // Already in set?
return;
}
colormult = colormult & 0xFFFFFF; // Mask multiplier
int[] argb = getTileARGB(idx); // Look up tile data
if (colormult != 0xFFFFFF) { // Non-trivial color multiplier
colormult |= 0xFF000000;
for (int i = 0; i < etp.img.argb_buf.length; i++) {
etp.img.argb_buf[i] = Color.blendColor(argb[i], colormult);
}
}
else { // Else, just copy into destination
for (int i = 0; i < etp.img.argb_buf.length; i++) {
etp.img.argb_buf[i] = argb[i];
}
}
boolean hasAlpha = false;
// Compute simple color
double r = 0.0, g = 0.0, b = 0.0, w = 0.0;
for (int i = 0; i < etp.img.argb_buf.length; i++) {
int v = etp.img.argb_buf[i];
int ww = (v >> 24) & 0xFF;
int rr = (v >> 16) & 0xFF;
int gg = (v >> 8) & 0xFF;
int bb = v & 0xFF;
r += ww * rr;
g += ww * gg;
b += ww * bb;
w += ww;
if (ww != 0xFF) { // Non-trivial alpha?
hasAlpha = true;
}
}
BufferOutputStream baos = new BufferOutputStream();
ImageIO.setUseCache(false); /* Don't use file cache - too small to be worth it */
String fname = etp.name + "/" + idstr + ".png";
etp.exp.startExportedFile(fname);
ImageIO.write(etp.img.buf_img, "png", baos);
etp.exp.addBytesToExportedFile(baos.buf, 0, baos.len);
etp.exp.finishExportedFile();
String fname_a = null;
// If has alpha, convert to gray scale for alpha image
if (hasAlpha) {
for (int i = 0; i < etp.img.argb_buf.length; i++) {
int v = etp.img.argb_buf[i];
int ww = (v >> 24) & 0xFF;
etp.img.argb_buf[i] = (ww << 24) | (ww << 16) | (ww << 8) | ww;
}
fname_a = etp.name + "/" + idstr + "_a.png";
etp.exp.startExportedFile(fname_a);
baos.reset();
ImageIO.write(etp.img.buf_img, "png", baos);
etp.exp.addBytesToExportedFile(baos.buf, 0, baos.len);
etp.exp.finishExportedFile();
}
ExportedTexture et = new ExportedTexture();
et.filename = fname;
et.filename_a = fname_a;
if (w > 0)
et.diffuseColor = new Color((int)(r / w), (int)(g / w), (int)(b / w));
else
et.diffuseColor = new Color();
et.material = getMaterialTypeByTile(idx);
etp.txtids.put(idstr, et); // Add to set
}
// Export texture pack as OBJ format material library
public void exportAsOBJMaterialLibrary(OBJExport exp, String name) throws IOException {
ExportedTexturePack etp = new ExportedTexturePack();
etp.img = DynmapBufferedImage.allocateBufferedImage(this.native_scale, this.native_scale);
etp.name = name;
etp.exp = exp;
// Get set of texture references from export
Set<String> txtids = exp.getMaterialIDs();
// Loop through them, adding the textures needed
for (String txt : txtids) {
int off = txt.lastIndexOf("__");
int mult = -1;
String txtbase = txt;
if ((off > 0) && ((off + 8) == txt.length())) {
String end = txt.substring(off+2);
try {
mult = Integer.parseInt(end, 16);
} catch (NumberFormatException x) {
Log.warning("Invalid multiplier " + end);
}
txtbase = txt.substring(0, off);
}
Integer txt_id = tileIDByMatID.get(txtbase);
int id = -1;
if (txt_id == null) {
if (txtbase.startsWith("txt") == false) {
continue;
}
try {
id = Integer.parseInt(txtbase.substring(3));
} catch (NumberFormatException x) {
Log.warning("Invalid texture ID " + txtbase);
}
}
else {
id = txt_id;
}
if (id >= 0) {
addImageToZip(txt, id, mult, etp);
}
}
// Build MTL file
exp.startExportedFile(etp.name + ".mtl");
TreeSet<String> ids = new TreeSet<String>(etp.txtids.keySet());
for (String id : ids) {
ExportedTexture et = etp.txtids.get(id);
String lines = "newmtl " + id + "\n";
lines += String.format("Ka %.3f %.3f %.3f\n", (double)et.diffuseColor.getRed() / 256.0, (double)et.diffuseColor.getGreen() / 256.0, (double) et.diffuseColor.getBlue() / 256.0);
lines += String.format("Kd %.3f %.3f %.3f\n", (double)et.diffuseColor.getRed() / 256.0, (double)et.diffuseColor.getGreen() / 256.0, (double) et.diffuseColor.getBlue() / 256.0);
lines += "map_Kd " + et.filename + "\n";
lines += "map_Ka " + et.filename + "\n";
if (et.filename_a != null) {
lines += "map_d " + et.filename_a + "\n";
}
if (et.material != null) {
lines += String.format("Ni %.3f\n", et.material.Ni);
lines += String.format("Ns %.3f\n", et.material.Ns);
lines += "Ks 0.500 0.500 0.500\n";
lines += String.format("illum %d\n", et.material.illum);
}
else {
lines += "Ks 0.000 0.000 0.000\n";
}
lines += "\n";
exp.addStringToExportedFile(lines);
}
exp.finishExportedFile();
}
private static final int[] deftxtidx = { 0, 1, 2, 3, 4, 5 };
public String[] getCurrentBlockMaterials(int blkid, int blkdata, int renderdata, MapIterator mapiter, int[] txtidx, BlockStep[] steps) {
HDTextureMap map = HDTextureMap.getMap(blkid, blkdata, renderdata);
int blkindex = indexByIDMeta(blkid, blkdata);
if (txtidx == null) txtidx = deftxtidx;
String[] rslt = new String[txtidx.length]; // One for each face
boolean handlestdrot = (steps != null) && (!map.stdrotate);
for (int patchidx = 0; patchidx < txtidx.length; patchidx++) {
int faceindex = txtidx[patchidx];
int textid = map.faces[faceindex];
int mod = textid / COLORMOD_MULT_INTERNAL;
textid = textid % COLORMOD_MULT_INTERNAL;
BlockStep step = steps[patchidx];
/* If clear-inside op, get out early */
if((mod == COLORMOD_CLEARINSIDE) || (mod == COLORMOD_MULTTONED_CLEARINSIDE)) {
BlockStep dir = step.opposite();
/* Check if previous block is same block type as we are: surface is transparent if it is */
if((blkid == mapiter.getBlockTypeIDAt(dir)) && (blkdata == mapiter.getBlockDataAt(dir.xoff, dir.yoff, dir.zoff))) {
continue; // Skip: no texture
}
/* If water block, to watercolor tone op */
if ((blkid == 8) || (blkid == 9)) {
mod = COLORMOD_WATERTONED;
}
else if (mod == COLORMOD_MULTTONED_CLEARINSIDE) {
mod = COLORMOD_MULTTONED;
}
}
if (ctm != null) {
textid = ctm.mapTexture(mapiter, blkid, blkdata, step, textid, null);
}
if (textid >= 0) {
rslt[patchidx] = getMatIDForTileID(textid); // Default texture
int mult = 0xFFFFFF;
BiomeMap bio;
switch (mod) {
case COLORMOD_GRASSTONED:
case COLORMOD_GRASSTONED270:
bio = mapiter.getBiome();
if ((bio == BiomeMap.SWAMPLAND) && (imgs[IMG_SWAMPGRASSCOLOR] != null)) {
mult = getBiomeTonedColor(imgs[IMG_SWAMPGRASSCOLOR], -1, bio, blkindex);
}
else {
mult = getBiomeTonedColor(imgs[IMG_GRASSCOLOR], -1, bio, blkindex);
}
break;
case COLORMOD_FOLIAGETONED:
case COLORMOD_FOLIAGETONED270:
case COLORMOD_FOLIAGEMULTTONED:
mult = getBiomeTonedColor(imgs[IMG_FOLIAGECOLOR], -1, mapiter.getBiome(), blkindex);
break;
case COLORMOD_WATERTONED:
case COLORMOD_WATERTONED270:
mult = getBiomeTonedColor(imgs[IMG_WATERCOLORX], -1, mapiter.getBiome(), blkindex);
break;
case COLORMOD_PINETONED:
mult = getBiomeTonedColor(imgs[IMG_PINECOLOR], colorMultPine, mapiter.getBiome(), blkindex);
break;
case COLORMOD_BIRCHTONED:
mult = getBiomeTonedColor(imgs[IMG_BIRCHCOLOR], colorMultBirch, mapiter.getBiome(), blkindex);
break;
case COLORMOD_LILYTONED:
mult = getBiomeTonedColor(null, colorMultLily, mapiter.getBiome(), blkindex);
break;
case COLORMOD_MULTTONED:
case COLORMOD_MULTTONED_CLEARINSIDE:
if(map.custColorMult == null) {
mult = getBiomeTonedColor(null, map.colorMult, mapiter.getBiome(), blkindex);
}
else {
mult = map.custColorMult.getColorMultiplier(mapiter);
}
break;
default:
mult = getBiomeTonedColor(null, -1, mapiter.getBiome(), blkindex);
break;
}
if ((mult & 0xFFFFFF) != 0xFFFFFF) {
rslt[patchidx] += String.format("__%06X", mult & 0xFFFFFF);
}
if (handlestdrot && (!map.stdrotate) && ((step == BlockStep.Y_MINUS) || (step == BlockStep.Y_PLUS))) {
// Handle rotations
switch (mod) {
case COLORMOD_ROT90:
mod = COLORMOD_ROT180;
break;
case COLORMOD_ROT180:
mod = COLORMOD_ROT270;
break;
case COLORMOD_ROT270:
case COLORMOD_GRASSTONED270:
case COLORMOD_FOLIAGETONED270:
case COLORMOD_WATERTONED270:
mod = 0;
break;
default:
mod = COLORMOD_ROT90;
break;
}
}
// Handle rotations
switch (mod) {
case COLORMOD_ROT90:
rslt[patchidx] += "@" + OBJExport.ROT90;
break;
case COLORMOD_ROT180:
rslt[patchidx] += "@" + OBJExport.ROT180;
break;
case COLORMOD_ROT270:
case COLORMOD_GRASSTONED270:
case COLORMOD_FOLIAGETONED270:
case COLORMOD_WATERTONED270:
rslt[patchidx] += "@" + + OBJExport.ROT270;
break;
case COLORMOD_FLIPHORIZ:
rslt[patchidx] += "@" + OBJExport.HFLIP;
break;
}
}
}
return rslt;
}
// Get biome-specific color multpliers
private int getBiomeTonedColor(LoadedImage tonemap, int defcolormult, BiomeMap biome, int blkidx) {
int mult;
if (tonemap == null) { // No map? just use trivial
mult = defcolormult;
}
else if (tonemap.argb == null) { // No details, use trivial
mult = tonemap.trivial_color;
}
else {
mult = tonemap.argb[biome.biomeLookup()];
}
if(hasBlockColoring.get(blkidx)) {
Integer cidx = (Integer) this.blockColoring.get(blkidx);
LoadedImage custimg = imgs[cidx];
if (custimg.argb != null) {
mult = Color.blendColor(mult, custimg.argb[biome.biomeLookup()]);
}
}
return mult;
}
public MaterialType getMaterialTypeByTile(int tileidx) {
return materialbytileid.get(tileidx);
}
private void setMatIDForTileID(String matid, int tileid) {
String id = matIDByTileID.get(tileid);
if (id != null) return;
id = matid;
String[] tok = id.split("/");
if (tok.length < 5) {
id = tok[tok.length-1];
}
else {
id = tok[4];
for (int i = 5; i < tok.length; i++) {
id = id + "_" + tok[i];
}
}
id = id.replace(' ', '_');
int off = id.lastIndexOf('.');
if (off > 0) {
id = id.substring(0, off);
}
int cnt = 2;
String baseid = id;
while (true) {
Integer v = tileIDByMatID.get(id);
if (v == null) { // Not defined, use ID
tileIDByMatID.put(id, tileid);
matIDByTileID.put(tileid, id);
return;
}
else if ((v != null) && (v.intValue() == tileid)) {
return;
}
id = baseid + "_" + cnt;
cnt++;
}
}
private String getMatIDForTileID(int txtid) {
String id = matIDByTileID.get(txtid);
if (id == null) {
id = "txt" + txtid;
matIDByTileID.put(txtid, id);
tileIDByMatID.put(id, txtid);
}
return id;
}
}
|
package org.dynmap.hdmap;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.imageio.ImageIO;
import org.dynmap.Color;
import org.dynmap.DynmapPlugin;
import org.dynmap.Log;
import org.dynmap.kzedmap.KzedMap;
* BetterGlass/*.png - mod-based improved windows (future optional)
*/
public class TexturePack {
/* Loaded texture packs */
private static HashMap<String, TexturePack> packs = new HashMap<String, TexturePack>();
private static final String TERRAIN_PNG = "terrain.png";
private static final String GRASSCOLOR_PNG = "misc/grasscolor.png";
private static final String FOLIAGECOLOR_PNG = "misc/foliagecolor.png";
private static final String WATER_PNG = "misc/water.png";
private int[] terrain_argb;
private int terrain_width, terrain_height;
private int native_scale;
private int[] grasscolor_argb;
private int grasscolor_width, grasscolor_height;
private int[] foliagecolor_argb;
private int foliagecolor_width, foliagecolor_height;
private int[] water_argb;
private int water_width, water_height;
private HashMap<Integer, TexturePack> scaled_textures;
/** Get or load texture pack */
public static TexturePack getTexturePack(String tpname) {
TexturePack tp = packs.get(tpname);
if(tp != null)
return tp;
try {
tp = new TexturePack(tpname); /* Attempt to load pack */
packs.put(tpname, tp);
return tp;
} catch (FileNotFoundException fnfx) {
Log.severe("Error loading texture pack '" + tpname + "' - not found");
}
return null;
}
/**
* Constructor for texture pack, by name
*/
private TexturePack(String tpname) throws FileNotFoundException {
ZipFile zf = null;
File texturedir = getTexturePackDirectory();
try {
/* Try to open zip */
zf = new ZipFile(new File(texturedir, tpname + ".zip"));
/* Find and load terrain.png */
ZipEntry ze = zf.getEntry(TERRAIN_PNG); /* Try to find terrain.png */
if(ze == null) {
throw new FileNotFoundException();
}
InputStream is = zf.getInputStream(ze); /* Get input stream for terrain.png */
loadTerrainPNG(is);
is.close();
/* Try to find and load misc/grasscolor.png */
ze = zf.getEntry(GRASSCOLOR_PNG);
if(ze != null) { /* Found it, so load it */
is = zf.getInputStream(ze);
loadGrassColorPNG(is);
is.close();
}
/* Try to find and load misc/foliagecolor.png */
ze = zf.getEntry(FOLIAGECOLOR_PNG);
if(ze != null) { /* Found it, so load it */
is = zf.getInputStream(ze);
loadFoliageColorPNG(is);
is.close();
}
/* Try to find and load misc/water.png */
ze = zf.getEntry(WATER_PNG);
if(ze != null) { /* Found it, so load it */
is = zf.getInputStream(ze);
loadWaterPNG(is);
is.close();
}
zf.close();
return;
} catch (IOException iox) {
if(zf != null) {
try { zf.close(); } catch (IOException io) {}
}
/* No zip, or bad - try directory next */
}
/* Try loading terrain.png from directory of name */
File f = null;
FileInputStream fis = null;
try {
/* Open and load terrain.png */
f = new File(texturedir, tpname + "/" + TERRAIN_PNG);
fis = new FileInputStream(f);
loadTerrainPNG(fis);
fis.close();
/* Check for misc/grasscolor.png */
f = new File(texturedir, tpname + "/" + GRASSCOLOR_PNG);
if(f.canRead()) {
fis = new FileInputStream(f);
loadGrassColorPNG(fis);
fis.close();
}
/* Check for misc/foliagecolor.png */
f = new File(texturedir, tpname + "/" + FOLIAGECOLOR_PNG);
if(f.canRead()) {
fis = new FileInputStream(f);
loadFoliageColorPNG(fis);
fis.close();
}
/* Check for misc/water.png */
f = new File(texturedir, tpname + "/" + WATER_PNG);
if(f.canRead()) {
fis = new FileInputStream(f);
loadWaterPNG(fis);
fis.close();
}
} catch (IOException iox) {
if(fis != null) {
try { fis.close(); } catch (IOException io) {}
}
throw new FileNotFoundException();
}
}
/* Copy texture pack */
private TexturePack(TexturePack tp) {
this.terrain_argb = tp.terrain_argb;
this.terrain_width = tp.terrain_width;
this.terrain_height = tp.terrain_height;
this.native_scale = tp.native_scale;
this.grasscolor_argb = tp.grasscolor_argb;
this.grasscolor_height = tp.grasscolor_height;
this.grasscolor_width = tp.grasscolor_width;
this.foliagecolor_argb = tp.foliagecolor_argb;
this.foliagecolor_height = tp.foliagecolor_height;
this.foliagecolor_width = tp.foliagecolor_width;
this.water_argb = tp.water_argb;
this.water_height = tp.water_height;
this.water_width = tp.water_width;
}
/* Load terrain.png */
private void loadTerrainPNG(InputStream is) throws IOException {
/* Load image */
BufferedImage img = ImageIO.read(is);
if(img == null) { throw new FileNotFoundException(); }
terrain_width = img.getWidth();
terrain_height = img.getHeight();
terrain_argb = new int[terrain_width * terrain_height];
img.getRGB(0, 0, terrain_width, terrain_height, terrain_argb, 0, terrain_width);
img.flush();
native_scale = terrain_width / 16;
}
/* Load misc/grasscolor.png */
private void loadGrassColorPNG(InputStream is) throws IOException {
/* Load image */
BufferedImage img = ImageIO.read(is);
if(img == null) { throw new FileNotFoundException(); }
grasscolor_width = img.getWidth();
grasscolor_height = img.getHeight();
grasscolor_argb = new int[grasscolor_width * grasscolor_height];
img.getRGB(0, 0, grasscolor_width, grasscolor_height, grasscolor_argb, 0, grasscolor_width);
img.flush();
}
/* Load misc/foliagecolor.png */
private void loadFoliageColorPNG(InputStream is) throws IOException {
/* Load image */
BufferedImage img = ImageIO.read(is);
if(img == null) { throw new FileNotFoundException(); }
foliagecolor_width = img.getWidth();
foliagecolor_height = img.getHeight();
foliagecolor_argb = new int[foliagecolor_width * foliagecolor_height];
img.getRGB(0, 0, foliagecolor_width, foliagecolor_height, foliagecolor_argb, 0, foliagecolor_width);
img.flush();
}
/* Load misc/water.png */
private void loadWaterPNG(InputStream is) throws IOException {
/* Load image */
BufferedImage img = ImageIO.read(is);
if(img == null) { throw new FileNotFoundException(); }
water_width = img.getWidth();
water_height = img.getHeight();
water_argb = new int[water_width * water_height];
img.getRGB(0, 0, water_width, water_height, water_argb, 0, water_width);
img.flush();
}
/* Get texture pack directory */
private static File getTexturePackDirectory() {
// return new File(DynmapPlugin.dataDirectory, "texturepacks");
return new File("texturepacks");
}
/**
* Resample terrain pack for given scale, and return copy using that scale
*/
public TexturePack resampleTexturePack(int scale) {
if(scaled_textures == null) scaled_textures = new HashMap<Integer, TexturePack>();
TexturePack stp = scaled_textures.get(scale);
if(stp != null)
return stp;
stp = new TexturePack(this); /* Make copy */
/* Scale terrain.png, if needed */
if(stp.native_scale != scale) {
stp.native_scale = scale;
stp.terrain_height = 16*scale;
stp.terrain_width = 16*scale;
stp.terrain_argb = new int[stp.terrain_height*stp.terrain_width];
scaleTerrainPNG(stp);
}
/* Remember it */
scaled_textures.put(scale, stp);
return stp;
}
/**
* Scale out terrain_argb into the terrain_argb of the provided destination, matching the scale of that destination
* @param tp
*/
private void scaleTerrainPNG(TexturePack tp) {
/* Terrain.png is 16x16 array of images : process one at a time */
for(int ty = 0; ty < 16; ty++) {
for(int tx = 0; tx < 16; tx++) {
int srcoff = ty*native_scale*terrain_width + tx*native_scale;
int destoff = ty*tp.native_scale*tp.terrain_width + tx*tp.native_scale;
scaleTerrainPNGSubImage(tp, srcoff, destoff);
}
}
}
private void scaleTerrainPNGSubImage(TexturePack tp, int srcoff, int destoff) {
int nativeres = native_scale;
int res = tp.native_scale;
Color c = new Color();
/* If we're scaling larger source pixels into smaller pixels, each destination pixel
* receives input from 1 or 2 source pixels on each axis
*/
if(res > nativeres) {
int weights[] = new int[res];
int offsets[] = new int[res];
/* LCM of resolutions is used as length of line (res * nativeres)
* Each native block is (res) long, each scaled block is (nativeres) long
* Each scaled block overlaps 1 or 2 native blocks: starting with native block 'offsets[]' with
* 'weights[]' of its (res) width in the first, and the rest in the second
*/
for(int v = 0, idx = 0; v < res*nativeres; v += nativeres, idx++) {
offsets[idx] = (v/res); /* Get index of the first native block we draw from */
if((v+nativeres-1)/res == offsets[idx]) { /* If scaled block ends in same native block */
weights[idx] = nativeres;
}
else { /* Else, see how much is in first one */
weights[idx] = (offsets[idx]*res + res) - v;
}
}
/* Now, use weights and indices to fill in scaled map */
for(int y = 0, off = 0; y < res; y++) {
int ind_y = offsets[y];
int wgt_y = weights[y];
for(int x = 0; x < res; x++, off++) {
int ind_x = offsets[x];
int wgt_x = weights[x];
int accum_red = 0;
int accum_green = 0;
int accum_blue = 0;
int accum_alpha = 0;
for(int xx = 0; xx < 2; xx++) {
int wx = (xx==0)?wgt_x:(nativeres-wgt_x);
if(wx == 0) continue;
for(int yy = 0; yy < 2; yy++) {
int wy = (yy==0)?wgt_y:(nativeres-wgt_y);
if(wy == 0) continue;
/* Accumulate */
c.setARGB(terrain_argb[srcoff + (ind_y+yy)*terrain_width + ind_x + xx]);
accum_red += c.getRed() * wx * wy;
accum_green += c.getGreen() * wx * wy;
accum_blue += c.getBlue() * wx * wy;
accum_alpha += c.getAlpha() * wx * wy;
}
}
/* Generate weighted compnents into color */
c.setRGBA(accum_red / (nativeres*nativeres), accum_green / (nativeres*nativeres),
accum_blue / (nativeres*nativeres), accum_alpha / (nativeres*nativeres));
tp.terrain_argb[destoff + (y*tp.terrain_width) + x] = c.getARGB();
}
}
}
else { /* nativeres > res */
int weights[] = new int[nativeres];
int offsets[] = new int[nativeres];
/* LCM of resolutions is used as length of line (res * nativeres)
* Each native block is (res) long, each scaled block is (nativeres) long
* Each native block overlaps 1 or 2 scaled blocks: starting with scaled block 'offsets[]' with
* 'weights[]' of its (res) width in the first, and the rest in the second
*/
for(int v = 0, idx = 0; v < res*nativeres; v += res, idx++) {
offsets[idx] = (v/nativeres); /* Get index of the first scaled block we draw to */
if((v+res-1)/nativeres == offsets[idx]) { /* If native block ends in same scaled block */
weights[idx] = res;
}
else { /* Else, see how much is in first one */
weights[idx] = (offsets[idx]*nativeres + nativeres) - v;
}
}
int accum_red[] = new int[res*res];
int accum_green[] = new int[res*res];
int accum_blue[] = new int[res*res];
int accum_alpha[] = new int[res*res];
/* Now, use weights and indices to fill in scaled map */
for(int y = 0; y < nativeres; y++) {
int ind_y = offsets[y];
int wgt_y = weights[y];
for(int x = 0; x < nativeres; x++) {
int ind_x = offsets[x];
int wgt_x = weights[x];
c.setARGB(terrain_argb[srcoff + (y*terrain_width) + x]);
for(int xx = 0; xx < 2; xx++) {
int wx = (xx==0)?wgt_x:(res-wgt_x);
if(wx == 0) continue;
for(int yy = 0; yy < 2; yy++) {
int wy = (yy==0)?wgt_y:(res-wgt_y);
if(wy == 0) continue;
accum_red[(ind_y+yy)*res + (ind_x+xx)] += c.getRed() * wx * wy;
accum_green[(ind_y+yy)*res + (ind_x+xx)] += c.getGreen() * wx * wy;
accum_blue[(ind_y+yy)*res + (ind_x+xx)] += c.getBlue() * wx * wy;
accum_alpha[(ind_y+yy)*res + (ind_x+xx)] += c.getAlpha() * wx * wy;
}
}
}
}
/* Produce normalized scaled values */
for(int y = 0; y < res; y++) {
for(int x = 0; x < res; x++) {
int off = (y*res) + x;
c.setRGBA(accum_red[off]/(nativeres*nativeres), accum_green[off]/(nativeres*nativeres),
accum_blue[off]/(nativeres*nativeres), accum_alpha[off]/(nativeres*nativeres));
tp.terrain_argb[destoff + y*tp.terrain_width + x] = c.getARGB();
}
}
}
}
public void saveTerrainPNG(File f) throws IOException {
BufferedImage img = KzedMap.createBufferedImage(terrain_argb, terrain_width, terrain_height);
ImageIO.write(img, "png", f);
}
public static void main(String[] args) {
TexturePack tp = TexturePack.getTexturePack("test");
TexturePack tp2 = tp.resampleTexturePack(4);
try {
tp2.saveTerrainPNG(new File("test_terrain_4.png"));
} catch (IOException iox) {}
tp2 = tp.resampleTexturePack(16);
try {
tp2.saveTerrainPNG(new File("test_terrain_16.png"));
} catch (IOException iox) {}
tp2 = tp.resampleTexturePack(24);
try {
tp2.saveTerrainPNG(new File("test_terrain_24.png"));
} catch (IOException iox) {}
tp2 = tp.resampleTexturePack(64);
try {
tp2.saveTerrainPNG(new File("test_terrain_64.png"));
} catch (IOException iox) {}
tp2 = tp.resampleTexturePack(1);
try {
tp2.saveTerrainPNG(new File("test_terrain_1.png"));
} catch (IOException iox) {}
}
}
|
package org.ethereum.core;
import org.ethereum.db.DatabaseImpl;
import org.ethereum.manager.WorldManager;
import org.ethereum.net.message.StaticMessages;
import org.ethereum.net.submit.WalletTransaction;
import org.ethereum.util.ByteUtil;
import org.iq80.leveldb.DBIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import java.io.IOException;
import java.util.*;
import static org.ethereum.core.Denomination.*;
public class Blockchain {
private static Logger logger = LoggerFactory.getLogger("blockchain");
// to avoid using minGasPrice=0 from Genesis for the wallet
private static long INITIAL_MIN_GAS_PRICE = 10 * SZABO.longValue();
private DatabaseImpl db;
private Wallet wallet;
private long gasPrice = 1000;
private Block lastBlock;
// keep the index of the chain for
// convenient usage, <block_number, block_hash>
private HashMap<Long, byte[]> index = new HashMap<Long, byte[]>();
// This map of transaction designed
// to approve the tx by external trusted peer
private Map<String, WalletTransaction> walletTransactions =
Collections.synchronizedMap(new HashMap<String, WalletTransaction>());
public Blockchain(Wallet wallet) {
this.db = WorldManager.instance.chainDB;
this.wallet = wallet;
}
public Block getLastBlock() {
return lastBlock;
}
public void setLastBlock(Block block){
this.lastBlock = block;
}
public int getSize(){
return index.size();
}
public Block getByNumber(long rowIndex){
return new Block(db.get(ByteUtil.longToBytes(rowIndex)));
}
public void addBlocks(List<Block> blocks) {
if (blocks.isEmpty())
return;
Block firstBlockToAdd = blocks.get(blocks.size() - 1);
// if it is the first block to add
// check that the parent is the genesis
if (index.isEmpty()
&& !Arrays.equals(StaticMessages.GENESIS_HASH,
firstBlockToAdd.getParentHash())) {
return;
}
// if there is some blocks already keep chain continuity
if (!index.isEmpty()) {
String hashLast = Hex.toHexString(getLastBlock().getHash());
String blockParentHash = Hex.toHexString(firstBlockToAdd.getParentHash());
if (!hashLast.equals(blockParentHash)) return;
}
for (int i = blocks.size() - 1; i >= 0 ; --i){
Block block = blocks.get(i);
this.addBlock(block);
db.put(ByteUtil.longToBytes(block.getNumber()), block.getEncoded());
if (logger.isDebugEnabled())
logger.debug("block added to the chain with hash: {}", Hex.toHexString(block.getHash()));
}
// Remove all wallet transactions as they already approved by the net
for (Block block : blocks) {
for (Transaction tx : block.getTransactionsList()) {
if (logger.isDebugEnabled())
logger.debug("pending cleanup: tx.hash: [{}]", Hex.toHexString( tx.getHash()));
removeWalletTransaction(tx);
}
}
logger.info("*** Block chain size: [ {} ]", index.size());
}
private void addBlock(Block block) {
if(block.isValid()) {
this.wallet.processBlock(block);
// In case of the genesis block we don't want to rely on the min gas price
this.gasPrice = block.isGenesis() ? INITIAL_MIN_GAS_PRICE : block.getMinGasPrice();
setLastBlock(block);
index.put(block.getNumber(), block.getParentHash());
} else {
logger.warn("Invalid block with nr: {}", block.getNumber());
}
}
public long getGasPrice() {
return gasPrice;
}
/***********************************************************************
* 1) the dialog put a pending transaction on the list
* 2) the dialog send the transaction to a net
* 3) wherever the transaction got in from the wire it will change to approve state
* 4) only after the approve a) Wallet state changes
* 5) After the block is received with that tx the pending been clean up
*/
public WalletTransaction addWalletTransaction(Transaction transaction) {
String hash = Hex.toHexString(transaction.getHash());
logger.info("pending transaction placed hash: {}", hash );
WalletTransaction walletTransaction = this.walletTransactions.get(hash);
if (walletTransaction != null)
walletTransaction.incApproved();
else {
walletTransaction = new WalletTransaction(transaction);
this.walletTransactions.put(hash, walletTransaction);
}
return walletTransaction;
}
public void removeWalletTransaction(Transaction transaction){
String hash = Hex.toHexString(transaction.getHash());
logger.info("pending transaction removed with hash: {} ", hash);
walletTransactions.remove(hash);
}
public byte[] getLatestBlockHash(){
if (index.isEmpty())
return StaticMessages.GENESIS_HASH;
else
return getLastBlock().getHash();
}
public void loadChain() {
DBIterator iterator = db.iterator();
try {
if (!iterator.hasNext()) {
logger.info("DB is empty - adding Genesis");
this.lastBlock = Genesis.getInstance();
this.addBlock(lastBlock);
logger.debug("Block #{} -> {}", Genesis.NUMBER, lastBlock.toFlatString());
db.put(ByteUtil.longToBytes(Genesis.NUMBER), lastBlock.getEncoded());
}
logger.debug("Displaying blocks stored in DB sorted on blocknumber");
long blockNr = Genesis.NUMBER;
for (iterator.seekToFirst(); iterator.hasNext(); iterator.next()) {
this.lastBlock = new Block(db.get(ByteUtil.longToBytes(blockNr)));
// in case of cold load play the contracts
WorldManager.instance.applyBlock(lastBlock);
logger.debug("Block #{} -> {}", lastBlock.getNumber(), lastBlock.toFlatString());
this.addBlock(lastBlock);
blockNr = lastBlock.getNumber()+1;
}
} finally {
// Make sure you close the iterator to avoid resource leaks.
try {
iterator.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
}
|
package org.jibble.jmegahal;
import com.google.common.collect.ImmutableMap;
import com.mrpowergamerbr.loritta.Loritta;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class JMegaHal implements Serializable {
// These are valid chars for words. Anything else is treated as punctuation.
public static final String WORD_CHARS = "abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"0123456789";
public static final String END_CHARS = ".!?";
public static final Map<String, String> ANTONYMS = ImmutableMap.<String, String>builder()
.put("EU", "VOCÊ")
.build();
/**
* Construct an instance of JMegaHal with an empty brain.
*/
public JMegaHal() {
}
/**
* Adds an entire documents to the 'brain'. Useful for feeding in
* stray theses, but be careful not to put too much in, or you may
* run out of memory!
*/
public void addDocument(String uri) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(uri).openStream()));
StringBuffer buffer = new StringBuffer();
int ch = 0;
while ((ch = reader.read()) != -1) {
buffer.append((char) ch);
if (END_CHARS.indexOf((char) ch) >= 0) {
String sentence = buffer.toString();
sentence = sentence.replace('\r', ' ');
sentence = sentence.replace('\n', ' ');
add(sentence);
buffer = new StringBuffer();
}
}
add(buffer.toString());
reader.close();
}
/**
* Adds a new sentence to the 'brain'
*/
public void add(String sentence) {
if (words.size() >= 100000) {
words.clear();
quads.clear();
next.clear();
previous.clear();
}
sentence = sentence.trim();
ArrayList<String> parts = new ArrayList<String>();
char[] chars = sentence.toCharArray();
int i = 0;
boolean punctuation = false;
StringBuffer buffer = new StringBuffer();
while (i < chars.length) {
char ch = chars[i];
if ((WORD_CHARS.indexOf(ch) >= 0) == punctuation) {
punctuation = !punctuation;
String token = buffer.toString();
if (token.length() > 0) {
parts.add(token);
}
buffer = new StringBuffer();
continue;
}
buffer.append(ch);
i++;
}
String lastToken = buffer.toString();
if (lastToken.length() > 0) {
parts.add(lastToken);
}
if (parts.size() >= 4) {
for (i = 0; i < parts.size() - 3; i++) {
//System.out.println("\"" + parts.get(i) + "\"");
Quad quad = new Quad((String) parts.get(i), (String) parts.get(i + 1), (String) parts.get(i + 2), (String) parts.get(i + 3));
if (quads.containsKey(quad)) {
quad = (Quad) quads.get(quad);
}
else {
quads.put(quad, quad);
}
if (i == 0) {
quad.setCanStart(true);
}
//else if (i == parts.size() - 4) {
if (i == parts.size() - 4) {
quad.setCanEnd(true);
}
for (int n = 0; n < 4; n++) {
String token = (String) parts.get(i + n);
if (!words.containsKey(token)) {
words.put(token, new HashSet<Quad>(1));
}
HashSet<Quad> set = (HashSet<Quad>) words.get(token);
set.add(quad);
}
if (i > 0) {
String previousToken = (String) parts.get(i - 1);
if (!previous.containsKey(quad)) {
previous.put(quad, new HashSet<String>(1));
}
HashSet<String> set = (HashSet<String>) previous.get(quad);
set.add(previousToken);
}
if (i < parts.size() - 4) {
String nextToken = (String) parts.get(i + 4);
if (!next.containsKey(quad)) {
next.put(quad, new HashSet<String>(1));
}
HashSet<String> set = (HashSet<String>) next.get(quad);
set.add(nextToken);
}
}
}
else {
// Didn't learn anything.
}
}
/**
* Generate a Loritta.getRandom()om sentence from the brain.
*/
public String getSentence() {
return getSentence(null);
}
/**
* Generate a sentence that includes (if possible) the specified word.
*/
public String getSentence(String word) {
LinkedList<String> parts = new LinkedList<String>();
Quad[] quads;
if (words.containsKey(word)) {
quads = (Quad[]) ((HashSet<?>) words.get(word)).toArray(new Quad[0]);
}
else {
quads = (Quad[]) this.quads.keySet().toArray(new Quad[0]);
}
if (quads.length == 0) {
return "";
}
Quad middleQuad = quads[Loritta.getRandom().nextInt(quads.length)];
Quad quad = middleQuad;
for (int i = 0; i < 4; i++) {
parts.add(quad.getToken(i));
}
while (quad.canEnd() == false) {
String[] nextTokens = (String[]) ((HashSet<?>) next.get(quad)).toArray(new String[0]);
String nextToken = nextTokens[Loritta.getRandom().nextInt(nextTokens.length)];
quad = (Quad) this.quads.get(new Quad(quad.getToken(1), quad.getToken(2), quad.getToken(3), nextToken));
parts.add(nextToken);
}
quad = middleQuad;
while (quad.canStart() == false) {
String[] previousTokens = (String[]) ((HashSet<?>) previous.get(quad)).toArray(new String[0]);
String previousToken = previousTokens[Loritta.getRandom().nextInt(previousTokens.length)];
quad = (Quad) this.quads.get(new Quad(previousToken, quad.getToken(0), quad.getToken(1), quad.getToken(2)));
parts.addFirst(previousToken);
}
StringBuffer sentence = new StringBuffer();
Iterator<String> it = parts.iterator();
while (it.hasNext()) {
String token = (String) it.next();
sentence.append(token);
}
return sentence.toString();
}
// This maps a single word to a HashSet of all the Quads it is in.
private ConcurrentHashMap<String, HashSet<Quad>> words = new ConcurrentHashMap<String, HashSet<Quad>>();
// A self-referential HashMap of Quads.
private ConcurrentHashMap<Quad, Quad> quads = new ConcurrentHashMap<Quad, Quad>();
// This maps a Quad onto a Set of Strings that may come next.
private ConcurrentHashMap<Quad, HashSet<String>> next = new ConcurrentHashMap<Quad, HashSet<String>>();
// This maps a Quad onto a Set of Strings that may come before it.
private ConcurrentHashMap<Quad, HashSet<String>> previous = new ConcurrentHashMap<Quad, HashSet<String>>();
}
|
/**
*
* @author grog (at) myrobotlab.org
*
* */
package org.myrobotlab.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.myrobotlab.framework.Message;
import org.myrobotlab.framework.Service;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.service.config.ClockConfig;
import org.myrobotlab.service.config.ServiceConfig;
import org.slf4j.Logger;
/**
* Clock - This is a simple clock service that can be started and stopped. It
* generates a pulse with a timestamp on a regular interval defined by the
* setInterval(Integer) method. Interval is in milliseconds.
*/
public class Clock extends Service {
public class ClockThread implements Runnable {
private transient Thread thread = null;
public ClockThread() {
}
@Override
public void run() {
ClockConfig c = (ClockConfig) config;
try {
c.running = true;
while (c.running) {
Thread.sleep(c.interval);
Date now = new Date();
for (Message msg : events) {
send(msg);
}
invoke("pulse", now);
invoke("publishTime", now);
invoke("publishEpoch", now);
}
} catch (InterruptedException e) {
log.info("ClockThread interrupt");
}
c.running = false;
thread = null;
}
// FIXME - synchronized methods is silly here - access needs to be
// synchronized "between" start & stop
// TODO - create and use a single thread - use wait(sleep) notify for
// control
synchronized public void start() {
if (thread == null) {
thread = new Thread(this, getName() + "_ticking_thread");
thread.start();
invoke("publishClockStarted");
} else {
log.info("{} already started", getName());
}
}
synchronized public void stop() {
ClockConfig c = (ClockConfig) config;
if (thread != null) {
thread.interrupt();
} else {
log.info("{} already stopped");
}
// change state - broadcast it
if (c.running == true) {
broadcastState();
}
c.running = false;
thread = null;
}
}
private static final long serialVersionUID = 1L;
final public static Logger log = LoggerFactory.getLogger(Clock.class);
final protected transient ClockThread myClock = new ClockThread();
/**
* list of messages the clock can send - these are set with addClockEvent
*/
final protected List<Message> events = new ArrayList<>();
public Clock(String n, String id) {
super(n, id);
}
public void addClockEvent(String name, String method, Object... data) {
Message event = Message.createMessage(getName(), name, method, data);
events.add(event);
}
/**
* clears all the clock events
*/
public void clearClockEvents() {
events.clear();
}
/**
* event published for when the clock is started
*/
public void publishClockStarted() {
log.info("clock started");
broadcastState();
}
/**
* the clock was stopped event
*/
public void publishClockStopped() {
log.info("clock stopped");
broadcastState();
}
/**
* date is published at an interval here
*
* @param time
* t
* @return t
*/
@Deprecated /* use publishTime or preferably publishEpoch as epoch is in a useful millisecond value */
public Date pulse(Date time) {
return time;
}
/**
* publishing point for a the current date object
* @param time
* @return
*/
public Date publishTime(Date time) {
return time;
}
/**
* publishing point for epoch
* @param time - epoch value, number of milliseconds from Jan 1 1970
* @return
*/
public long publishEpoch(Date time) {
return time.getTime();
}
/**
* set the interval of clock events to the current millisecond value
* @param milliseconds
*/
public void setInterval(Integer milliseconds) {
ClockConfig c = (ClockConfig) config;
c.interval = milliseconds;
broadcastState();
}
@Deprecated /* use startClock skipFirst is default behavior */
public void startClock(boolean skipFirst) {
}
/**
* start the clock
*/
public void startClock() {
myClock.start();
}
/**
* see if the clock is running
* @return
*/
public boolean isClockRunning() {
ClockConfig c = (ClockConfig) config;
return c.running;
}
/**
* stop a clock
*/
public void stopClock() {
myClock.stop();
}
@Override
public void stopService() {
super.stopService();
stopClock();
}
/**
* return the current interval in milliseconds
* @return
*/
public Integer getInterval() {
return ((ClockConfig) config).interval;
}
@Override
public ServiceConfig apply(ServiceConfig c) {
super.apply(c);
ClockConfig config = (ClockConfig) c;
if (config.running != null) {
if (config.running) {
startClock();
} else {
stopClock();
}
}
return config;
}
public void restartClock() {
stopClock();
startClock();
}
public static void main(String[] args) throws Exception {
try {
Runtime.start("webgui", "WebGui");
Clock c1 = (Clock) Runtime.start("c1", "Clock");
c1.startClock();
c1.stopClock();
} catch (Exception e) {
log.error("main threw", e);
}
}
}
|
package org.osgl.mvc.result;
import org.osgl.http.H;
import org.osgl.http.Http;
import org.osgl.http.util.Path;
import org.osgl.util.E;
import org.osgl.util.IO;
import org.osgl.util.S;
public class Redirect extends Result {
protected String url;
public Redirect(String url) {
super(Http.Status.FOUND);
E.illegalArgumentIf(S.blank(url));
this.url = url;
}
public Redirect(String url, Object... args) {
this(S.fmt(url, args));
}
public Redirect(boolean permanent, String url) {
super(permanent ? Http.Status.MOVED_PERMANENTLY : H.Status.FOUND);
this.url = url;
}
public Redirect(boolean permanent, String url, Object... args) {
this(permanent, S.fmt(url, args));
}
@Override
public void apply(H.Request req, H.Response resp) {
String url = fullUrl(req);
if (req.isAjax()) {
resp.status(H.Status.FOUND_AJAX);
} else {
applyStatus(resp);
}
resp.header("Location", url);
applyBeforeCommitHandler(req, resp);
IO.close(resp.outputStream());
applyAfterCommitHandler(req, resp);
}
protected String fullUrl(H.Request request) {
return Path.fullUrl(this.url, request);
}
}
|
package org.realityforge.dbdiff;
import java.util.List;
import org.realityforge.cli.CLArgsParser;
import org.realityforge.cli.CLOption;
import org.realityforge.cli.CLOptionDescriptor;
import org.realityforge.cli.CLUtil;
/**
* The entry point in which to run the tool.
*/
public class Main
{
private static final int HELP_OPT = 1;
private static final int QUIET_OPT = 'q';
private static final int VERBOSE_OPT = 'v';
private static final CLOptionDescriptor[] OPTIONS = new CLOptionDescriptor[]{
new CLOptionDescriptor( "help",
CLOptionDescriptor.ARGUMENT_DISALLOWED,
HELP_OPT,
"print this message and exit" ),
new CLOptionDescriptor( "quiet",
CLOptionDescriptor.ARGUMENT_DISALLOWED,
QUIET_OPT,
"Do not output unless an error occurs, just return 0 on no difference." ),
new CLOptionDescriptor( "verbose",
CLOptionDescriptor.ARGUMENT_DISALLOWED,
VERBOSE_OPT,
"Verbose output of differences." ),
};
private static final int NO_DIFFERENCE_EXIT_CODE = 0;
private static final int DIFFERENCE_EXIT_CODE = 1;
private static final int ERROR_PARSING_ARGS_EXIT_CODE = 2;
private static final int QUIET = 0;
private static final int NORMAL = 1;
private static final int VERBOSE = 1;
private static int c_logLevel = NORMAL;
private static String c_database1;
private static String c_database2;
public static void main( final String[] args )
{
if ( !processOptions( args ) )
{
System.exit( ERROR_PARSING_ARGS_EXIT_CODE );
return;
}
if ( VERBOSE <= c_logLevel )
{
info( "Performing difference between databases" );
}
final boolean difference = diff();
if ( difference )
{
if ( NORMAL <= c_logLevel )
{
error( "Difference found between databases" );
}
System.exit( DIFFERENCE_EXIT_CODE );
}
else
{
if ( NORMAL <= c_logLevel )
{
info( "No difference found between databases" );
}
System.exit( NO_DIFFERENCE_EXIT_CODE );
}
}
private static boolean diff()
{
return System.getProperty( "X" ) != null;
}
private static boolean processOptions( final String[] args )
{
// Parse the arguments
final CLArgsParser parser = new CLArgsParser( args, OPTIONS );
//Make sure that there was no errors parsing arguments
if ( null != parser.getErrorString() )
{
error( parser.getErrorString() );
return false;
}
// Get a list of parsed options
@SuppressWarnings( "unchecked" ) final List<CLOption> options = parser.getArguments();
for ( final CLOption option : options )
{
switch ( option.getId() )
{
case CLOption.TEXT_ARGUMENT:
if ( null == c_database1 )
{
c_database1 = option.getArgument();
}
else if ( null == c_database2 )
{
c_database2 = option.getArgument();
}
else
{
error( "Unexpected 3rd test argument: " + option.getArgument() );
return false;
}
break;
case VERBOSE_OPT:
{
c_logLevel = VERBOSE;
break;
}
case QUIET_OPT:
{
c_logLevel = QUIET;
break;
}
case HELP_OPT:
{
printUsage();
return false;
}
}
}
if ( null == c_database1 || null == c_database2 )
{
error( "Two jdbc urls must supplied for the databases to check differences" );
return false;
}
if ( VERBOSE <= c_logLevel )
{
info( "Database 1: " + c_database1 );
info( "Database 2: " + c_database2 );
}
return true;
}
/**
* Print out a usage statement
*/
private static void printUsage()
{
final String lineSeparator = System.getProperty( "line.separator" );
final StringBuilder msg = new StringBuilder();
msg.append( "java " );
msg.append( Main.class.getName() );
msg.append( " [options] database1JDBCurl database2JDBCurl" );
msg.append( lineSeparator );
msg.append( "Options: " );
msg.append( lineSeparator );
msg.append( CLUtil.describeOptions( OPTIONS ).toString() );
info( msg.toString() );
}
private static void info( final String message )
{
System.out.println( message );
}
private static void error( final String message )
{
System.out.println( "Error: " + message );
}
}
|
package org.scijava.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* TODO
*
* @author Johannes Schindelin
*/
public class CheckSezpoz {
public static boolean verbose;
public static final String FILE_NAME = "latest-sezpoz-check.txt";
/**
* Checks the annotations of all CLASSPATH components. Optionally, it only
* checks the non-.jar components of the CLASSPATH. This is for Eclipse.
* Eclipse fails to run the annotation processor at each incremental build. In
* contrast to Maven, Eclipse usually does not build .jar files, though, so we
* can have a very quick check at startup if the annotation processor was not
* run correctly and undo the damage.
*
* @param checkJars whether to inspect .jar components of the CLASSPATH
* @return false, when the annotation processor had to be run
* @throws IOException
*/
public static boolean check(final boolean checkJars) throws IOException {
boolean upToDate = true;
for (final String path : System.getProperty("java.class.path").split(
File.pathSeparator))
{
if (!checkJars && path.endsWith(".jar")) continue;
if (!check(new File(path))) upToDate = false;
}
return upToDate;
}
/**
* Checks the annotations of a CLASSPATH component.
*
* @param file the CLASSPATH component (.jar file or directory)
* @return false, when the annotation processor had to be run
* @throws IOException
*/
public static boolean check(final File file) throws IOException {
if (!file.exists()) return true;
if (file.isDirectory()) return checkDirectory(file);
else if (file.isFile() && file.getName().endsWith(".jar")) checkJar(file);
else System.err.println("WARN: Skipping SezPoz check of " + file);
return true;
}
/**
* Checks the annotations of a directory in the CLASSPATH.
*
* @param classes the CLASSPATH component directory
* @return false, when the annotation processor had to be run
* @throws IOException
*/
public static boolean checkDirectory(final File classes) throws IOException {
final String path = FileUtils.getPath(classes);
if (!path.endsWith("target/classes") && !path.endsWith("target/test-classes")) {
System.err.println("WARN: Ignoring non-Maven build directory: " +
classes.getPath());
return true;
}
for (File file : classes.listFiles()) {
if (file.isFile() && file.getName().startsWith(".netbeans_")) {
System.err.println("WARN: Ignoring NetBeans build directory: " +
classes.getPath());
return true;
}
}
final File projectRoot = classes.getParentFile().getParentFile();
final File source = new File(projectRoot, "src/main/java");
if (!source.isDirectory()) {
System.err.println("WARN: No src/main/java found for " + classes);
return true;
}
final long latestCheck = getLatestCheck(classes.getParentFile());
final boolean upToDate = checkDirectory(classes, source, latestCheck);
if (!upToDate) {
fixEclipseConfiguration(projectRoot);
return !fix(classes, source);
}
return true;
}
/**
* Determines when we checked whether SezPoz ran alright last time.
*
* @param targetDirectory the <i>target/</i> directory Maven writes into
* @return the timestamp of our last check
*/
protected static long getLatestCheck(final File targetDirectory) {
try {
final File file = new File(targetDirectory, FILE_NAME);
if (!file.exists()) return -1;
final BufferedReader reader = new BufferedReader(new FileReader(file));
String firstLine = reader.readLine();
reader.close();
if (firstLine == null) return -1;
if (firstLine.endsWith("\n")) firstLine =
firstLine.substring(0, firstLine.length() - 1);
return Long.parseLong(firstLine);
}
catch (final IOException e) {
return -1;
}
catch (final NumberFormatException e) {
return -1;
}
}
/**
* Fakes the check for <i>.jar</i> files a la {@link #getLatestCheck(File)}.
*
* @param jar the <i>.jar</i> file
* @return -1 since we cannot really tell
*/
protected static long getLatestCheck(final JarFile jar) {
return -1;
}
private static void setLatestCheck(final File targetDirectory) {
final File file = new File(targetDirectory, FILE_NAME);
// let's make sure this file has LF-terminated lines
try {
final Date date = new Date();
final String content =
"" + date.getTime() + "\n" +
DateFormat.getDateTimeInstance().format(date) + "\n";
final OutputStream out = new FileOutputStream(file);
out.write(content.getBytes());
out.close();
}
catch (final IOException e) {
e.printStackTrace();
System.err.println("ERROR: Failure updating the Sezpoz check timestamp");
}
}
/**
* Checks whether the annotations are possibly out-of-date.
* <p>
* This method looks whether there are any <i>.class</i> files older than
* their corresponding <i>.java</i> files, or whether there are <i>.class</i>
* files that were generated since last time we checked.
* </p>
*
* @param classes the <i>classes/</i> directory where Maven puts the
* <i>.class</i> files
* @param source the <i>src/main/java/<i> directory where Maven expects the
* <i>.java</i> files
* @param youngerThan the date/time when we last checked
*/
public static boolean checkDirectory(final File classes, final File source,
final long youngerThan) throws IOException
{
if (classes.getName().equals("META-INF") || !source.isDirectory()) return true;
final File[] list = classes.listFiles();
if (list == null) return true;
for (final File file : list) {
final String name = file.getName();
if (file.isDirectory()) {
if (!checkDirectory(file, new File(source, name), youngerThan)) return false;
}
else if (file.isFile() &&
file.lastModified() > youngerThan &&
name.endsWith(".class") &&
hasAnnotation(new File(source, name.substring(0, name.length() - 5) +
"java")))
{
return false;
}
}
return true;
}
/**
* Checks a <i>.jar</i> file for stale annotations.
* <p>
* This method is broken at the moment since there is no good way to verify
* that SezPoz ran before the <i>.jar</i> file was packaged.
* </p>
*
* @param file the <i>.jar</i> file
*/
public static void checkJar(final File file) throws IOException {
final JarFile jar = new JarFile(file);
final long mtime = getLatestCheck(jar);
if (mtime < 0) {
// Eclipse cannot generate .jar files (except in manual mode).
// Assume everything is alright
return;
}
for (final JarEntry entry : new IteratorPlus<JarEntry>(jar.entries())) {
if (entry.getTime() > mtime) {
throw new IOException("Annotations for " + entry + " in " + file +
" are out-of-date!");
}
}
}
/**
* Determines whether the class defined in a file has at least one annotation.
* <p>
* This method simply parses everything before the first occurrence of the
* word {@code class}, skipping comments, for things looking like annotations.
* </p>
*
* @param file the <i>.java</i> file to check
*/
protected static boolean hasAnnotation(final File file) {
if (!file.getName().endsWith(".java")) return false;
try {
final BufferedReader reader = new BufferedReader(new FileReader(file));
boolean inComment = false;
for (;;) {
final String line = reader.readLine();
if (line == null) break;
int offset = 0;
if (inComment) {
offset = line.indexOf("*/");
if (offset < 0) continue;
offset += 2;
inComment = false;
}
final int eol = line.length();
while (offset < eol) {
final int commentStart = line.indexOf("/*", offset);
final int lineCommentStart = line.indexOf("//", offset);
final int end =
Math.min(eol, Math.min(commentStart < 0 ? Integer.MAX_VALUE
: commentStart, lineCommentStart < 0 ? Integer.MAX_VALUE
: lineCommentStart));
if (offset < end) {
final int at = line.indexOf("@", offset);
int clazz = offset;
for (;;) {
clazz = line.indexOf("class", clazz);
if (clazz < 0) break;
// is "class" the keyword, i.e. not a substring of
// something else?
if ((clazz == 0 || !Character.isJavaIdentifierPart(line
.charAt(clazz - 1))) &&
(clazz + 4 >= end || !Character.isJavaIdentifierPart(line
.charAt(clazz + 5)))) break;
clazz += 4;
}
if (at >= 0 && at < end && (clazz < 0 || at < clazz)) {
reader.close();
return true;
}
if (clazz >= 0 && clazz < end) {
reader.close();
return false;
}
}
if (end == commentStart) {
offset = line.indexOf("*/", commentStart + 2);
if (offset > 0) {
offset += 2;
continue;
}
inComment = true;
}
break;
}
}
reader.close();
return false;
}
catch (final Exception e) {
// If we cannot read it, it does not have an annotation for all we
// know.
return false;
}
}
* @return whether anything in {@code META-INF/annotations/*} changed
*/
public static boolean fix(final File classes, final File sources) {
final Method aptProcess;
try {
final Class<?> aptClass =
CheckSezpoz.class.getClassLoader().loadClass("com.sun.tools.apt.Main");
aptProcess =
aptClass.getMethod("process", new Class[] { String[].class });
}
catch (final Exception e) {
e.printStackTrace();
System.err
.println("ERROR: Could not fix " + sources + ": apt not found");
return false;
}
if (!sources.exists()) {
System.err.println("ERROR: Sources are not in the expected place: " +
sources);
return false;
}
final List<String> aptArgs = new ArrayList<String>();
aptArgs.add("-nocompile");
if (verbose) aptArgs.add("-verbose");
aptArgs.add("-factory");
aptArgs.add("net.java.sezpoz.impl.IndexerFactory");
aptArgs.add("-d");
aptArgs.add(classes.getPath());
final int count = aptArgs.size();
addJavaPathsRecursively(aptArgs, sources);
// do nothing if there is nothing to
if (count == aptArgs.size()) return false;
// remove possibly outdated annotations
final File[] annotationsBefore =
new File(classes, "META-INF/annotations").listFiles();
// checksum the annotations so that we can determine whether something
// changed
// if nothing changed, we can safely proceed
final Map<String, byte[]> checksumsBefore = checksum(annotationsBefore);
// before running, remove possibly outdated annotations
if (annotationsBefore != null) {
for (final File annotation : annotationsBefore)
annotation.delete();
}
final String[] args = aptArgs.toArray(new String[aptArgs.size()]);
try {
System.err.println("WARN: Updating the annotation index in " + classes);
aptProcess.invoke(null, new Object[] { args });
}
catch (final Exception e) {
e.printStackTrace();
System.err.println("WARN: Could not fix " + sources + ": apt failed");
return false;
}
boolean result = true;
final File[] annotationsAfter =
new File(classes, "META-INF/annotations").listFiles();
final Map<String, byte[]> checksumsAfter = checksum(annotationsAfter);
if (checksumsAfter.size() == checksumsBefore.size()) {
result = false;
for (final String key : checksumsAfter.keySet()) {
final byte[] before = checksumsBefore.get(key);
if (before == null || !Arrays.equals(before, checksumsAfter.get(key)))
{
result = true;
}
}
}
setLatestCheck(classes.getParentFile());
return result;
}
private static MessageDigest digest;
/**
* Calculates checksums of a list of files.
* <p>
* This method is used to determine whether annotation files have been changed
* by SezPoz rather than re-generated identically.
* </p>
*
* @param files the files to process
* @return a map containing (filename, checksum) mappings
*/
protected static Map<String, byte[]> checksum(final File[] files) {
final Map<String, byte[]> result = new HashMap<String, byte[]>();
if (files != null && files.length != 0) {
for (final File file : files)
result.put(file.getName(), checksum(file));
}
return result;
}
/**
* Calculate the checksum of one file.
*
* @param file the file to process
* @return the checksum
*/
protected synchronized static byte[] checksum(final File file) {
try {
if (digest == null) digest = MessageDigest.getInstance("SHA-1");
else digest.reset();
final byte[] buffer = new byte[65536];
final DigestInputStream digestStream =
new DigestInputStream(new FileInputStream(file), digest);
while (digestStream.read(buffer) >= 0) {
// do nothing
}
digestStream.close();
return digest.digest();
}
catch (final Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* Builds a list of <i>.java</i> files in a directory including all its
* sub-directories.
*
* @param list the list of filenames to append to
* @param directory the directory
*/
protected static void addJavaPathsRecursively(final List<String> list,
final File directory)
{
final File[] files = directory.listFiles();
if (files == null) return;
for (final File file : files) {
if (file.isDirectory()) addJavaPathsRecursively(list, file);
else if (file.isFile() && file.getName().endsWith(".java")) {
list.add(file.getPath());
}
}
}
/**
* Adjusts the mtime of a file to "now".
*
* @param file the file to touch
* @throws IOException
*/
protected static void touch(final File file) throws IOException {
new FileOutputStream(file, true).close();
}
/**
* Makes sure that the given Eclipse project is set up correctly to run
* SezPoz.
* <p>
* If the {@code directory} does not point to an Eclipse project, the method
* will simply return.
* </p>
*
* @param directory the directory in which the project lives
*/
protected static void fixEclipseConfiguration(final File directory) {
// is this an Eclipse project at all?
if (!new File(directory, ".settings").isDirectory()) return;
fixFactoryPath(directory);
fixAnnotationProcessingSettings(directory);
}
/**
* Makes sure that the given Eclipse project has a <i>.factorypath</i>
* pointing to SezPoz in the current user's Maven repository.
*
* @param directory the Eclipse project to fix
*/
protected static void fixFactoryPath(final File directory) {
final File factoryPath = new File(directory, ".factorypath");
try {
final Document xml;
if (factoryPath.exists()) {
xml = readXMLFile(factoryPath);
}
else {
xml =
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.newDocument();
xml.appendChild(xml.createElement("factorypath"));
}
if (!containsSezpozId(xml.getElementsByTagName("factorypathentry"))) {
final Element element = xml.createElement("factorypathentry");
element.setAttribute("enabled", "true");
element.setAttribute("id",
"M2_REPO/net/java/sezpoz/sezpoz/1.9/sezpoz-1.9.jar");
element.setAttribute("kind", "VARJAR");
element.setAttribute("runInBatchMode", "true");
xml.getDocumentElement().appendChild(element);
writeXMLFile(xml, factoryPath);
}
}
catch (final Exception e) {
e.printStackTrace();
System.err.println("ERROR: Could not modify " + factoryPath);
}
}
/**
* Determines whether a parsed Eclipse configuration file contains a SezPoz
* entry already.
*
* @param elements the parsed Eclipse configuration
* @return whether SezPoz is configured already
*/
private static boolean containsSezpozId(final NodeList elements) {
if (elements == null) return false;
for (int i = 0; i < elements.getLength(); i++) {
final NamedNodeMap attributes = elements.item(i).getAttributes();
for (int j = 0; j < attributes.getLength(); j++) {
final Attr attribute = (Attr) attributes.item(j);
if (attribute.getName().equals("id") &&
attribute.getValue().indexOf("sezpoz") >= 0) return true;
}
}
return false;
}
/**
* Parses an <i>.xml</i> file into a DOM.
*
* @param file the <i>.xml</i> file to parse
* @return the DOM
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
protected static Document readXMLFile(final File file)
throws ParserConfigurationException, SAXException, IOException
{
final DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
builder = builderFactory.newDocumentBuilder();
return builder.parse(file);
}
/**
* Writes out a DOM as <i>.xml</i> file.
*
* @param xml the DOM
* @param file the file to write
* @throws TransformerException
*/
public static void writeXMLFile(final Document xml, final File file)
throws TransformerException
{
final Source source = new DOMSource(xml);
final Result result = new StreamResult(file);
final TransformerFactory factory = TransformerFactory.newInstance();
final Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
"4");
transformer.transform(source, result);
}
/**
* Makes sure that the given Eclipse project has annotation processing
* switched on.
*
* @param directory the Eclipse project to fix
*/
protected static void fixAnnotationProcessingSettings(final File directory) {
final File jdtSettings =
new File(directory, ".settings/org.eclipse.jdt.apt.core.prefs");
try {
final Properties properties = new Properties();
if (jdtSettings.exists()) {
properties.load(new FileInputStream(jdtSettings));
}
boolean changed = false;
for (final String pair : new String[] { "aptEnabled=true",
"genSrcDir=target/classes", "reconcileEnabled=false" })
{
final int equals = pair.indexOf('=');
final String key = "org.eclipse.jdt.apt." + pair.substring(0, equals);
final String value = pair.substring(equals + 1);
if (value.equals(properties.get(key))) continue;
properties.put(key, value);
changed = true;
}
if (changed) properties.store(new FileOutputStream(jdtSettings), null);
}
catch (final Exception e) {
e.printStackTrace();
System.err.println("ERROR: Could not edit " + jdtSettings);
}
}
/**
* Writes plain text into a plain file.
*
* @param file the plain file
* @param contents the plain text
* @throws IOException
* @throws UnsupportedEncodingException
*/
protected static void write(final File file, final String contents)
throws IOException, UnsupportedEncodingException
{
final OutputStream out = new FileOutputStream(file);
out.write(contents.getBytes("UTF-8"));
out.close();
}
}
|
package org.scijava.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* TODO
*
* @author Johannes Schindelin
*/
public final class CheckSezpoz {
public static boolean verbose;
public static final String FILE_NAME = "latest-sezpoz-check.txt";
private CheckSezpoz() {
// NB: Prevent instantiation of utility class.
}
/**
* Checks the annotations of all CLASSPATH components. Optionally, it only
* checks the non-.jar components of the CLASSPATH. This is for Eclipse.
* Eclipse fails to run the annotation processor at each incremental build. In
* contrast to Maven, Eclipse usually does not build .jar files, though, so we
* can have a very quick check at startup if the annotation processor was not
* run correctly and undo the damage.
*
* @param checkJars whether to inspect .jar components of the CLASSPATH
* @return false, when the annotation processor had to be run
* @throws IOException
*/
public static boolean check(final boolean checkJars) throws IOException {
boolean upToDate = true;
for (final String path : System.getProperty("java.class.path").split(
File.pathSeparator))
{
if (!checkJars && path.endsWith(".jar")) continue;
if (!check(new File(path))) upToDate = false;
}
return upToDate;
}
/**
* Checks the annotations of a CLASSPATH component.
*
* @param file the CLASSPATH component (.jar file or directory)
* @return false, when the annotation processor had to be run
* @throws IOException
*/
public static boolean check(final File file) throws IOException {
if (!file.exists()) return true;
if (file.isDirectory()) return checkDirectory(file);
else if (file.isFile() && file.getName().endsWith(".jar")) checkJar(file);
else System.err.println("WARN: Skipping SezPoz check of " + file);
return true;
}
/**
* Checks the annotations of a directory in the CLASSPATH.
*
* @param classes the CLASSPATH component directory
* @return false, when the annotation processor had to be run
* @throws IOException
*/
public static boolean checkDirectory(final File classes) throws IOException {
if (!classes.isDirectory()) return false;
final String path = FileUtils.getPath(classes);
if (!path.endsWith("target/classes") && !path.endsWith("target/test-classes")) {
System.err.println("WARN: Ignoring non-Maven build directory: " +
classes.getPath());
return true;
}
final String type = path.endsWith("target/classes") ? "main" : "test";
for (File file : classes.listFiles()) {
if (file.isFile() && file.getName().startsWith(".netbeans_")) {
System.err.println("WARN: Ignoring NetBeans build directory: " +
classes.getPath());
return true;
}
}
final File projectRoot = classes.getParentFile().getParentFile();
final File source = new File(projectRoot, "src/" + type + "/java");
if (!source.isDirectory()) {
System.err.println("WARN: No src/main/java found for " + classes);
return true;
}
final long latestCheck = getLatestCheck(classes.getParentFile());
final boolean upToDate = checkDirectory(classes, source, latestCheck);
if (!upToDate) {
fixEclipseConfiguration(projectRoot);
return !fix(classes, source);
}
return true;
}
/**
* Determines when we checked whether SezPoz ran alright last time.
*
* @param targetDirectory the <i>target/</i> directory Maven writes into
* @return the timestamp of our last check
*/
static long getLatestCheck(final File targetDirectory) {
try {
final File file = new File(targetDirectory, FILE_NAME);
if (!file.exists()) return -1;
final BufferedReader reader = new BufferedReader(new FileReader(file));
String firstLine = reader.readLine();
reader.close();
if (firstLine == null) return -1;
if (firstLine.endsWith("\n")) firstLine =
firstLine.substring(0, firstLine.length() - 1);
return Long.parseLong(firstLine);
}
catch (final IOException e) {
return -1;
}
catch (final NumberFormatException e) {
return -1;
}
}
/**
* Fakes the check for <i>.jar</i> files a la {@link #getLatestCheck(File)}.
*
* @param jar the <i>.jar</i> file
* @return -1 since we cannot really tell
*/
private static long getLatestCheck(final JarFile jar) {
return -1;
}
private static void setLatestCheck(final File targetDirectory) {
final File file = new File(targetDirectory, FILE_NAME);
// let's make sure this file has LF-terminated lines
try {
final Date date = new Date();
final String content =
"" + date.getTime() + "\n" +
DateFormat.getDateTimeInstance().format(date) + "\n";
final OutputStream out = new FileOutputStream(file);
out.write(content.getBytes());
out.close();
}
catch (final IOException e) {
e.printStackTrace();
System.err.println("ERROR: Failure updating the Sezpoz check timestamp");
}
}
/**
* Checks whether the annotations are possibly out-of-date.
* <p>
* This method looks whether there are any <i>.class</i> files older than
* their corresponding <i>.java</i> files, or whether there are <i>.class</i>
* files that were generated since last time we checked.
* </p>
*
* @param classes the <i>classes/</i> directory where Maven puts the
* <i>.class</i> files
* @param source the <i>src/main/java/<i> directory where Maven expects the
* <i>.java</i> files
* @param youngerThan the date/time when we last checked
*/
public static boolean checkDirectory(final File classes, final File source,
final long youngerThan) throws IOException
{
if (classes.getName().equals("META-INF") || !source.isDirectory()) return true;
final File[] list = classes.listFiles();
if (list == null) return true;
for (final File file : list) {
final String name = file.getName();
if (file.isDirectory()) {
if (!checkDirectory(file, new File(source, name), youngerThan)) return false;
}
else if (file.isFile() &&
file.lastModified() > youngerThan &&
name.endsWith(".class") &&
hasAnnotation(new File(source, name.substring(0, name.length() - 5) +
"java")))
{
return false;
}
}
return true;
}
/**
* Checks a <i>.jar</i> file for stale annotations.
* <p>
* This method is broken at the moment since there is no good way to verify
* that SezPoz ran before the <i>.jar</i> file was packaged.
* </p>
*
* @param file the <i>.jar</i> file
*/
public static void checkJar(final File file) throws IOException {
final JarFile jar = new JarFile(file);
final long mtime = getLatestCheck(jar);
if (mtime < 0) {
// Eclipse cannot generate .jar files (except in manual mode).
// Assume everything is alright
return;
}
for (final JarEntry entry : new IteratorPlus<JarEntry>(jar.entries())) {
if (entry.getTime() > mtime) {
throw new IOException("Annotations for " + entry + " in " + file +
" are out-of-date!");
}
}
}
/**
* Determines whether the class defined in a file has at least one annotation.
* <p>
* This method simply parses everything before the first occurrence of the
* word {@code class}, skipping comments, for things looking like annotations.
* </p>
*
* @param file the <i>.java</i> file to check
*/
static boolean hasAnnotation(final File file) {
if (!file.getName().endsWith(".java")) return false;
try {
final BufferedReader reader = new BufferedReader(new FileReader(file));
boolean inComment = false;
for (;;) {
final String line = reader.readLine();
if (line == null) break;
int offset = 0;
if (inComment) {
offset = line.indexOf("*/");
if (offset < 0) continue;
offset += 2;
inComment = false;
}
final int eol = line.length();
while (offset < eol) {
final int commentStart = line.indexOf("/*", offset);
final int lineCommentStart = line.indexOf("//", offset);
final int end =
Math.min(eol, Math.min(commentStart < 0 ? Integer.MAX_VALUE
: commentStart, lineCommentStart < 0 ? Integer.MAX_VALUE
: lineCommentStart));
if (offset < end) {
final int at = line.indexOf("@", offset);
int clazz = offset;
for (;;) {
clazz = line.indexOf("class", clazz);
if (clazz < 0) break;
// is "class" the keyword, i.e. not a substring of
// something else?
if ((clazz == 0 || !Character.isJavaIdentifierPart(line
.charAt(clazz - 1))) &&
(clazz + 4 >= end || !Character.isJavaIdentifierPart(line
.charAt(clazz + 5)))) break;
clazz += 4;
}
if (at >= 0 && at < end && (clazz < 0 || at < clazz)) {
reader.close();
return true;
}
if (clazz >= 0 && clazz < end) {
reader.close();
return false;
}
}
if (end == commentStart) {
offset = line.indexOf("*/", commentStart + 2);
if (offset > 0) {
offset += 2;
continue;
}
inComment = true;
}
break;
}
}
reader.close();
return false;
}
catch (final Exception e) {
// If we cannot read it, it does not have an annotation for all we
// know.
return false;
}
}
* @return whether anything in {@code META-INF/annotations/*} changed
*/
public static boolean fix(final File classes, final File sources) {
if (!sources.exists()) {
System.err.println("ERROR: Sources are not in the expected place: " +
sources);
return false;
}
final List<String> aptArgs = new ArrayList<String>();
if (verbose) aptArgs.add("-verbose");
aptArgs.add("-d");
aptArgs.add(classes.getPath());
final int count = aptArgs.size();
addJavaPathsRecursively(aptArgs, sources);
// do nothing if there is nothing to
if (count == aptArgs.size()) return false;
// remove possibly outdated annotations
final File[] annotationsBefore =
new File(classes, "META-INF/annotations").listFiles();
// checksum the annotations so that we can determine whether something
// changed
// if nothing changed, we can safely proceed
final Map<String, byte[]> checksumsBefore = checksum(annotationsBefore);
// before running, remove possibly outdated annotations
if (annotationsBefore != null) {
for (final File annotation : annotationsBefore)
annotation.delete();
}
final String[] args = aptArgs.toArray(new String[aptArgs.size()]);
try {
System.err.println("WARN: Updating the annotation index in " + classes);
runApt(args);
}
catch (final Exception e) {
e.printStackTrace();
System.err.println("WARN: Could not fix " + sources + ": apt failed");
return false;
}
boolean result = true;
final File[] annotationsAfter =
new File(classes, "META-INF/annotations").listFiles();
final Map<String, byte[]> checksumsAfter = checksum(annotationsAfter);
if (checksumsAfter.size() == checksumsBefore.size()) {
result = false;
for (final String key : checksumsAfter.keySet()) {
final byte[] before = checksumsBefore.get(key);
if (before == null || !Arrays.equals(before, checksumsAfter.get(key)))
{
result = true;
}
}
}
setLatestCheck(classes.getParentFile());
return result;
}
private static void runApt(String[] args) throws ClassNotFoundException,
SecurityException, NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException
{
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler != null) {
final List<String> aptArgs = new ArrayList<String>();
aptArgs.add("-proc:only");
aptArgs.add("-processor");
aptArgs.add("net.java.sezpoz.impl.Indexer6");
aptArgs.addAll(Arrays.asList(args));
compiler.run(null, null, null, aptArgs.toArray(new String[aptArgs.size()]));
return;
}
System.err.println("WARN: falling back to calling the 'apt' Main class directly");
final List<String> aptArgs = new ArrayList<String>();
aptArgs.add("-nocompile");
aptArgs.add("-factory");
aptArgs.add("net.java.sezpoz.impl.IndexerFactory");
aptArgs.addAll(Arrays.asList(args));
final Method aptProcess;
final Class<?> aptClass =
ToolProvider.getSystemToolClassLoader().loadClass("com.sun.tools.apt.Main");
aptProcess =
aptClass.getMethod("process", new Class[] { String[].class });
aptProcess.invoke(null, (Object)aptArgs.toArray(new String[aptArgs.size()]));
}
private static MessageDigest digest;
/**
* Calculates checksums of a list of files.
* <p>
* This method is used to determine whether annotation files have been changed
* by SezPoz rather than re-generated identically.
* </p>
*
* @param files the files to process
* @return a map containing (filename, checksum) mappings
*/
private static Map<String, byte[]> checksum(final File[] files) {
final Map<String, byte[]> result = new HashMap<String, byte[]>();
if (files != null && files.length != 0) {
for (final File file : files)
result.put(file.getName(), checksum(file));
}
return result;
}
/**
* Calculate the checksum of one file.
*
* @param file the file to process
* @return the checksum
*/
private synchronized static byte[] checksum(final File file) {
try {
if (digest == null) digest = MessageDigest.getInstance("SHA-1");
else digest.reset();
final byte[] buffer = new byte[65536];
final DigestInputStream digestStream =
new DigestInputStream(new FileInputStream(file), digest);
while (digestStream.read(buffer) >= 0) {
// do nothing
}
digestStream.close();
return digest.digest();
}
catch (final Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* Builds a list of <i>.java</i> files in a directory including all its
* sub-directories.
*
* @param list the list of filenames to append to
* @param directory the directory
*/
private static void addJavaPathsRecursively(final List<String> list,
final File directory)
{
final File[] files = directory.listFiles();
if (files == null) return;
for (final File file : files) {
if (file.isDirectory()) addJavaPathsRecursively(list, file);
else if (file.isFile() && file.getName().endsWith(".java")) {
list.add(file.getPath());
}
}
}
/**
* Makes sure that the given Eclipse project is set up correctly to run
* SezPoz.
* <p>
* If the {@code directory} does not point to an Eclipse project, the method
* will simply return.
* </p>
*
* @param directory the directory in which the project lives
*/
private static void fixEclipseConfiguration(final File directory) {
// is this an Eclipse project at all?
if (!new File(directory, ".settings").isDirectory()) return;
fixFactoryPath(directory);
fixAnnotationProcessingSettings(directory);
}
/**
* Makes sure that the given Eclipse project has a <i>.factorypath</i>
* pointing to SezPoz in the current user's Maven repository.
*
* @param directory the Eclipse project to fix
*/
private static void fixFactoryPath(final File directory) {
final File factoryPath = new File(directory, ".factorypath");
try {
final Document xml;
if (factoryPath.exists()) {
xml = readXMLFile(factoryPath);
}
else {
xml =
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.newDocument();
xml.appendChild(xml.createElement("factorypath"));
}
if (!containsSezpozId(xml.getElementsByTagName("factorypathentry"))) {
final Element element = xml.createElement("factorypathentry");
element.setAttribute("enabled", "true");
element.setAttribute("id",
"M2_REPO/net/java/sezpoz/sezpoz/1.9-imagej/sezpoz-1.9-imagej.jar");
element.setAttribute("kind", "VARJAR");
element.setAttribute("runInBatchMode", "true");
xml.getDocumentElement().appendChild(element);
writeXMLFile(xml, factoryPath);
}
}
catch (final Exception e) {
e.printStackTrace();
System.err.println("ERROR: Could not modify " + factoryPath);
}
}
/**
* Determines whether a parsed Eclipse configuration file contains a SezPoz
* entry already.
*
* @param elements the parsed Eclipse configuration
* @return whether SezPoz is configured already
*/
private static boolean containsSezpozId(final NodeList elements) {
if (elements == null) return false;
for (int i = 0; i < elements.getLength(); i++) {
final NamedNodeMap attributes = elements.item(i).getAttributes();
for (int j = 0; j < attributes.getLength(); j++) {
final Attr attribute = (Attr) attributes.item(j);
if (attribute.getName().equals("id") &&
attribute.getValue().indexOf("sezpoz") >= 0) return true;
}
}
return false;
}
/**
* Parses an <i>.xml</i> file into a DOM.
*
* @param file the <i>.xml</i> file to parse
* @return the DOM
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
private static Document readXMLFile(final File file)
throws ParserConfigurationException, SAXException, IOException
{
final DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
builder = builderFactory.newDocumentBuilder();
return builder.parse(file);
}
/**
* Writes out a DOM as <i>.xml</i> file.
*
* @param xml the DOM
* @param file the file to write
* @throws TransformerException
*/
public static void writeXMLFile(final Document xml, final File file)
throws TransformerException
{
final Source source = new DOMSource(xml);
final Result result = new StreamResult(file);
final TransformerFactory factory = TransformerFactory.newInstance();
final Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
"4");
transformer.transform(source, result);
}
private static final String[] APT_PROPERTIES = {
"eclipse.preferences.version=1",
"org.eclipse.jdt.apt.aptEnabled=true",
"org.eclipse.jdt.apt.genSrcDir=target/classes",
"org.eclipse.jdt.apt.reconcileEnabled=false"
};
/**
* Makes sure that the given Eclipse project has annotation processing
* switched on.
*
* @param directory the Eclipse project to fix
*/
private static void fixAnnotationProcessingSettings(final File directory) {
final File aptSettings =
new File(directory, ".settings/org.eclipse.jdt.apt.core.prefs");
try {
final Properties properties = new Properties();
if (aptSettings.exists()) {
properties.load(new FileInputStream(aptSettings));
}
boolean changed = false;
for (final String pair : APT_PROPERTIES) {
final int equals = pair.indexOf('=');
final String key = pair.substring(0, equals);
final String value = pair.substring(equals + 1);
if (!value.equals(properties.get(key))) {
changed = true;
break;
}
}
if (changed) {
// write out the correct properties
// NB: We do not use the Properties.store method because it prepends a
// date comment which Eclipse 4.3+ later strips out, resulting in
// modified aptSettings files committed to source control.
// Further, because Properties is a hash, we cannot control the order
// the properties are written out; we want them to be written in exactly
// the order declared above, to minimize the chance of Eclipse
// modifying them in any way. The downside of this approach is that any
// additional properties previously stored in the file will be lost, but
// thus far we have not encountered that situation in practice.
final PrintWriter out = new PrintWriter(new FileWriter(aptSettings));
for (final String pair : APT_PROPERTIES) {
out.println(pair);
}
out.close();
}
}
catch (final Exception e) {
e.printStackTrace();
System.err.println("ERROR: Could not edit " + aptSettings);
}
}
}
|
package org.sysapp.bridge;
import fi.iki.elonen.NanoHTTPD;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.xml.sax.InputSource;
import rocks.xmpp.addr.Jid;
import rocks.xmpp.core.session.XmppClient;
import rocks.xmpp.extensions.rpc.RpcManager;
import rocks.xmpp.extensions.rpc.model.Value;
/**
*
* @author eobs
*/
public class HttpServer extends NanoHTTPD {
private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(HttpServer.class);
private XmppClient xmppClient;
private RpcManager rpcManager;
private static long requestCacheTime=0;
private JsonObject statusJS;
private static long maxCacheTime=120000;
public HttpServer(int port, XmppClient xmppClient) throws IOException {
super(port);
this.xmppClient = xmppClient;
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
log.info("Running! http://localhost:" + port);
rpcManager= xmppClient.getManager(RpcManager.class);
}
@Override
public Response serve(IHTTPSession session) {
Method method = session.getMethod();
String uri = session.getUri();
log.info(method + " '" + uri + "' from " + session.getRemoteHostName());
Map<String, List<String>> parms = session.getParameters();
for (String entr : parms.keySet()) {
log.debug("Key:" + entr);
}
if (uri.endsWith("getSingleValue"))
{
String id = parms.get("id").get(0);
String ch = parms.get("ch").get(0);
String port = parms.get("port").get(0);
String value;
try
{
JsonObject idJS=this.getDevices().getJsonObject(id);
JsonObject chJS=idJS.getJsonObject(ch);
value=chJS.getString(port);
}
catch (Exception e)
{
log.error("Value Problem",e);
return newFixedLengthResponse(Response.Status.BAD_REQUEST, "application/txt","0");
}
return newFixedLengthResponse(Response.Status.OK, "application/txt", value);
}
else if (uri.endsWith("getDevices")) {
return newFixedLengthResponse(Response.Status.OK, "application/json", this.getDevices().toString());
} else if (uri.endsWith("setDataPoint")) {
String id = parms.get("id").get(0);
String ch = parms.get("ch").get(0);
String port = parms.get("port").get(0);
String value = parms.get("value").get(0);
setDataPoint(id, ch, port, value);
return newFixedLengthResponse("OK");
}
return newFixedLengthResponse("OK");
}
private void setDataPoint(String serialNum, String channel, String port, String value) {
try {
String path = serialNum + "/" + channel + "/" + port;
log.debug(path + "set " + value);
Value response = rpcManager.call(Jid.of("mrha@busch-jaeger.de/rpc"), "RemoteInterface.setDatapoint", Value.of(path), Value.of(value)).getResult();
log.debug("Result:"); // Colorado
log.debug(response.getAsString()); // Colorado
response=null;
System.gc();
} catch (Exception e) {
log.error(e);
}
}
private JsonObject getDevices() {
if ((System.currentTimeMillis()-requestCacheTime)<maxCacheTime)
{
log.info("Read from Cahche ");
return statusJS ;
}
else
{
requestCacheTime=System.currentTimeMillis();
}
JsonObjectBuilder resultJS = Json.createObjectBuilder();
try {
Value response = rpcManager.call(Jid.of("mrha@busch-jaeger.de/rpc"), "RemoteInterface.getAll", Value.of("de"), Value.of(4), Value.of(0), Value.of(0)).getResult();
//log.debug(response.getAsString()); // Colorado
Document doc = new SAXBuilder().build(new InputSource(new StringReader(response.getAsString())));
Element dev = doc.getRootElement().getChild("devices");
for (Element el : dev.getChildren()) {
log.debug("Dev :" + el.getName() + " id :" + el.getAttributeValue("serialNumber"));
JsonObjectBuilder device = null;
for (Element cl : el.getChildren("attribute")) {
if (cl.getAttribute("name").getValue().compareToIgnoreCase("displayName") == 0) {
log.debug("\tDevice Name " + cl.getText());
device = Json.createObjectBuilder();
device.add("name", cl.getText());
device.add("id", el.getAttributeValue("serialNumber"));
}
}
if (device != null) {
Element channels = el.getChild("channels");
if (channels != null) {
for (Element ch : channels.getChildren()) {
log.debug("\t\tChanel ID: " + ch.getAttributeValue("i"));
JsonObjectBuilder channelJS = Json.createObjectBuilder();
for (Element outputs : ch.getChild("outputs").getChildren()) {
channelJS.add(outputs.getAttribute("i").getValue(), outputs.getChildText("value"));
log.debug("\t\t\t DataPoint :" + outputs.getAttribute("i") + "[" + outputs.getChildText("value") + "]");
}
for (Element outputs : ch.getChild("inputs").getChildren()) {
channelJS.add(outputs.getAttribute("i").getValue(), outputs.getChildText("value"));
log.debug("\t\t\t DataPoint :" + outputs.getAttribute("i") + "[" + outputs.getChildText("value") + "]");
}
device.add(ch.getAttributeValue("i"), channelJS);
}
}
resultJS.add(el.getAttributeValue("serialNumber"), device);
}
}
doc=null;
dev=null;
response=null;
System.gc();
} catch (Exception e) {
log.error(e);
}
statusJS=resultJS.build();
return statusJS ;
}
}
|
package org.yinwang.yin.ast;
import org.yinwang.yin._;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Argument {
public List<Node> elements;
public List<Node> positional = new ArrayList<>();
public Map<String, Node> keywords = new LinkedHashMap<>();
public Argument(List<Node> elements) {
boolean hasName = false;
boolean hasKeyword = false;
for (int i = 0; i < elements.size(); i++) {
if (elements.get(i) instanceof Keyword) {
hasKeyword = true;
i++;
} else {
hasName = true;
}
}
if (hasName && hasKeyword) {
_.abort(elements.get(0), "mix positional and keyword arguments not allowed: " + elements);
}
this.elements = elements;
for (int i = 0; i < elements.size(); i++) {
Node key = elements.get(i);
if (key instanceof Keyword) {
String id = ((Keyword) key).id;
positional.add(((Keyword) key).asName());
if (i >= elements.size() - 1) {
_.abort(key, "missing value for keyword: " + key);
} else {
Node value = elements.get(i + 1);
if (value instanceof Keyword) {
_.abort(value, "keywords can't be used as values: " + value);
} else {
if (keywords.containsKey(id)) {
_.abort(key, "duplicated keyword: " + key);
}
keywords.put(id, value);
i++;
}
}
} else {
positional.add(key);
}
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Node e : elements) {
if (!first) {
sb.append(" ");
}
sb.append(e);
first = false;
}
return sb.toString();
}
}
|
package org.yinwang.yin.parser;
import org.jetbrains.annotations.Nullable;
import org.yinwang.yin.Constants;
import org.yinwang.yin._;
import org.yinwang.yin.ast.*;
import java.util.*;
/**
* First phase parser
* parse text into a meanlingless but more structured format
* similar to S-expressions but with less syntax
*/
public class Lexer {
public String file;
public String text;
// current offset indicators
public int offset;
public int line;
public int col;
// all delimeters
public final Set<String> delims = new HashSet<>();
// map open delimeters to their matched closing ones
public final Map<String, String> delimMap = new HashMap<>();
public Lexer(String file) {
this.file = _.unifyPath(file);
this.text = _.readFile(file);
this.offset = 0;
this.line = 0;
this.col = 0;
if (text == null) {
_.abort("failed to read file: " + file);
}
addDelimiterPair(Constants.PAREN_BEGIN, Constants.PAREN_END);
addDelimiterPair(Constants.CURLY_BEGIN, Constants.CURLY_END);
addDelimiterPair(Constants.SQUARE_BEGIN, Constants.ARRAY_END);
addDelimiter(Constants.ATTRIBUTE_ACCESS);
}
public void forward() {
if (text.charAt(offset) == '\n') {
line++;
col = 0;
offset++;
} else {
col++;
offset++;
}
}
public void addDelimiterPair(String open, String close) {
delims.add(open);
delims.add(close);
delimMap.put(open, close);
}
public void addDelimiter(String delim) {
delims.add(delim);
}
public boolean isDelimiter(char c) {
return delims.contains(Character.toString(c));
}
public boolean isOpen(Node c) {
return (c instanceof Delimeter) && delimMap.keySet().contains(((Delimeter) c).shape);
}
public boolean isClose(Node c) {
return (c instanceof Delimeter) && delimMap.values().contains(((Delimeter) c).shape);
}
public boolean matchString(String open, String close) {
String matched = delimMap.get(open);
return matched != null && matched.equals(close);
}
public boolean matchDelim(Node open, Node close) {
return (open instanceof Delimeter) &&
(close instanceof Delimeter) &&
matchString(((Delimeter) open).shape, ((Delimeter) close).shape);
}
public boolean skipSpaces() {
boolean found = false;
while (offset < text.length() &&
Character.isWhitespace(text.charAt(offset)))
{
found = true;
forward();
}
return found;
}
public boolean skipComments() {
boolean found = false;
if (text.startsWith(Constants.LINE_COMMENT, offset)) {
found = true;
// skip to line end
while (offset < text.length() && text.charAt(offset) != '\n') {
forward();
}
if (offset < text.length()) {
forward();
}
}
return found;
}
public void skipSpacesAndComments() {
while (skipSpaces() || skipComments()) {
// do nothing
}
}
public boolean atStringStart() {
return text.charAt(offset) == '"' &&
(offset == 0 || text.charAt(offset - 1) != '\\');
}
public Node scanString() {
int start = offset;
int startLine = line;
int startCol = col;
forward(); // skip "
while (offset < text.length() && !atStringStart()) {
if (text.charAt(offset) == '\n') {
_.abort(file + ":" + startLine + ":" + startCol + ": runaway string");
return null;
}
forward();
}
if (offset >= text.length()) {
_.abort(file + ":" + startLine + ":" + startCol + ": runaway string");
return null;
}
forward(); // skip "
int end = offset;
String content = text.substring(start + 1, end - 1);
return new Str(content, file, start, end, startLine, startCol);
}
public Node scanNumber() {
char cur = text.charAt(offset);
int start = offset;
int startLine = line;
int startCol = col;
while (offset < text.length() &&
!Character.isWhitespace(cur) &&
!(isDelimiter(cur) && cur != '.'))
{
forward();
if (offset < text.length()) {
cur = text.charAt(offset);
}
}
String content = text.substring(start, offset);
IntNum intNum = IntNum.parse(content, file, start, offset, startLine, startCol);
if (intNum != null) {
return intNum;
} else {
FloatNum floatNum = FloatNum.parse(content, file, start, offset, startLine, startCol);
if (floatNum != null) {
return floatNum;
} else {
_.abort(file + ":" + startLine + ":" + startCol + " : incorrect number format: " + content);
return null;
}
}
}
public Node scanName() {
char cur = text.charAt(offset);
int start = offset;
int startLine = line;
int startCol = col;
while (offset < text.length() &&
!Character.isWhitespace(cur) &&
!isDelimiter(cur))
{
forward();
if (offset < text.length()) {
cur = text.charAt(offset);
}
}
String content = text.substring(start, offset);
if (content.matches(":\\w.*")) {
return new Keyword(content.substring(1), file, start, offset, startLine, startCol);
} else {
return new Name(content, file, start, offset, startLine, startCol);
}
}
/**
* Lexer
*
* @return a token or null if file ends
*/
@Nullable
public Node nextToken() {
skipSpacesAndComments();
// end of file
if (offset >= text.length()) {
return null;
}
char cur = text.charAt(offset);
// delimiters
if (isDelimiter(cur)) {
Node ret = new Delimeter(Character.toString(cur), file, offset, offset + 1, line, col);
forward();
return ret;
}
// string
if (atStringStart()) {
return scanString();
}
if (Character.isDigit(text.charAt(offset)) ||
((text.charAt(offset) == '+' || text.charAt(offset) == '-')
&& Character.isDigit(text.charAt(offset + 1))))
{
return scanNumber();
} else {
return scanName();
}
}
public static void main(String[] args) {
Lexer lex = new Lexer(args[0]);
List<Node> tokens = new ArrayList<>();
Node n = lex.nextToken();
while (n != null) {
tokens.add(n);
n = lex.nextToken();
}
_.msg("lexer result: ");
for (Node node : tokens) {
_.msg(node.toString());
}
}
}
|
package org.zeropage;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class MemCacheStorage implements CacheStorage {
private ConcurrentHashMap<String,Set<String>> cacheTable;
public MemCacheStorage() {
this.cacheTable = new ConcurrentHashMap<>(100,1);
}
@Override
public boolean hasKey(String key) { return cacheTable.containsKey(key); }
@Override
public Set<String> getData(String key) {
return cacheTable.get(key);
}
@Override
public void setData(String key, Set<String> data) {
cacheTable.put(key,data);
}
}
|
package pirateboat.info;
import org.springframework.stereotype.Service;
import pirateboat.torrent.Torrent;
import pirateboat.torrent.TorrentHelper;
import pirateboat.torrent.TorrentService;
import pirateboat.utilities.PropertiesHelper;
@Service
public class CloudService {
final TorrentService torrentService = new TorrentService();
public String buildDestinationPath(final Torrent torrent) {
String basePath = PropertiesHelper.getProperty("rclonedir");
String normalizedTorrentStringWithSpaces = TorrentHelper.getNormalizedTorrentStringWithSpacesKeepCase(torrent.name);
String cleanedString = removeReleaseTags(normalizedTorrentStringWithSpaces);
// matches movie pattern
final String typeOfMedia = determineTypeOfMedia(cleanedString);
// take only name infront of year
String[] split = cleanedString.split("[1-2][0-9]{3}");
if (split.length > 0) {
cleanedString = split[0];
}
// remove articles
cleanedString = cleanedString.replaceAll("(A[ .]|The[ .]|Der[ .])", "");
cleanedString = cleanedString.trim();
cleanedString = cleanedString.replaceAll("\"", "");
if (cleanedString.length() > 0) {
cleanedString = cleanedString.substring(0, 1);
}
cleanedString = cleanedString.toUpperCase();
return basePath + "/" + typeOfMedia + "/" + cleanedString + "/";
}
private String determineTypeOfMedia(String cleanedString) {
if (cleanedString.matches(".*[ ._-]+[re]*dump[ ._-]+.*") || cleanedString.matches(".*\\s[pP][dD][fF].*") || cleanedString.matches(".*\\s[eE][pP][uU][bB].*")) {
return "transfer";
} else if (cleanedString.matches("(.+[ .]+S[0-9]+.+)|(.+Season.+)")) {
return "Series-Shows";
} else if (isMovieString(cleanedString)) {
return "Movies";
}
return "transfer";
}
private boolean isMovieString(String string) {
return string.matches(".+[1-2][0-9]{3}.*");
}
private String removeReleaseTags(final String string) {
StringBuilder releaseTagsRemoved = new StringBuilder(string);
torrentService.getReleaseTags().forEach(tag -> {
String temporaryString = releaseTagsRemoved.toString().replaceAll("\\s(?i)" + tag + "\\s", " ");
releaseTagsRemoved.setLength(0);
releaseTagsRemoved.append(temporaryString);
});
return releaseTagsRemoved.toString();
}
}
|
package rdfanalyzer.spark;
import java.util.List;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.Row;
import org.json.JSONArray;
import org.json.JSONObject;
public class EntryPoint {
/**
* Reads the suggested entry points from initially computed files.
*
* @param graph
* The name of the graph to query from.
* @param method
* The ranking method which should be used to determine the top
* ranked items.
* @param num
* How many suggestions to return.
*
* @return A JSONArray mapping the URIs of the neighbors to a JSONObject of
* their properties for each neighbor.
*/
public static JSONArray getSuggestions(String graph, String method, int num) {
if (num <= 0) {
throw new IllegalArgumentException("Requested number of suggestions must be greater than zero.");
}
return new JSONArray(querySuggestions(graph + method, num));
}
/**
* Queries the neighbors from the graph.
*
* @param graph
* The name of the graph to query from.
* @param centralNode
* The URI of the central node.
* @param num
* How many neighbors to return.
*
* @return A List of JSON represented neighbors.
*/
private static List<String> querySuggestions(String graph, int num) {
final String tmpGraphName = "RankingGraph" + graph;
DataFrame graphFrame = Service.sqlCtx().parquetFile(Configuration.storage() + graph + ".parquet");
graphFrame.cache().registerTempTable(tmpGraphName);
// Only select valid URIs from the data.
DataFrame resultsFrame = Service.sqlCtx().sql("SELECT node, importance FROM " + tmpGraphName
+ " WHERE node LIKE '<%' ORDER BY importance DESC LIMIT " + num);
@SuppressWarnings("serial")
List<String> neighbors = resultsFrame.javaRDD().map(new Function<Row, String>() {
@Override
public String call(Row row) {
return convertSQLRowToJSON(row);
}
}).collect();
return neighbors;
}
/**
* Converts a SQL row with a suggested node into a JSONObject, represented
* as a String for serializability.
*
* @param row
* The SQL row to convert.
* @return The String representation of a JSONObject with the suggested
* nodes properties.
*/
private static String convertSQLRowToJSON(Row row) {
JSONObject suggestion = new JSONObject();
String URI = row.getString(0);
double importance = row.getDouble(1);
suggestion.put("URI", URI);
suggestion.put("name", RDFgraph.shortenURI(URI));
suggestion.put("importance", importance);
return suggestion.toString();
}
}
|
package robotutils.data;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.util.Arrays;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.SimpleWeightedGraph;
import org.jgrapht.graph.UnmodifiableGraph;
/**
* Helper class that converts GridMaps into a variety of useful formats.
* @author Prasanna Velagapudi <pkv@cs.cmu.edu>
*/
public class GridMapUtils {
public static UnmodifiableGraph<Coordinate, DefaultWeightedEdge> toGraph(GridMap map) {
SimpleWeightedGraph<Coordinate, DefaultWeightedEdge> graph =
new SimpleWeightedGraph<Coordinate, DefaultWeightedEdge>(DefaultWeightedEdge.class);
int dims = map.dims();
int length = map.length();
int[] sizes = map.sizes();
int[] idx = new int[dims];
// Add every vertex that is not an obstacle
for (int v = 0; v < length; v++) {
if (map.get(idx) >= 0) {
graph.addVertex(new IntCoord(idx));
}
for (int i = 0; i < dims; i++) {
if (idx[i] < sizes[i] - 1) {
idx[i]++;
break;
} else {
idx[i] = 0;
}
}
}
// Add every non-obstacle edge
for (int v = 0; v < length; v++) {
for (int i = 0; i < dims; i++) {
if (idx[i] < sizes[i] - 1) {
int[] idx1 = Arrays.copyOf(idx, idx.length);
idx1[i]++;
if (map.get(idx) >= 0 && map.get(idx1) >= 0) {
DefaultWeightedEdge e = graph.addEdge(new IntCoord(idx), new IntCoord(idx1));
graph.setEdgeWeight(e, ((double)map.get(idx) + (double)map.get(idx1))/2.0 + 1.0);
}
}
}
for (int i = 0; i < dims; i++) {
if (idx[i] < sizes[i] - 1) {
idx[i]++;
break;
} else {
idx[i] = 0;
}
}
}
return new UnmodifiableGraph<Coordinate, DefaultWeightedEdge>(graph);
}
public static BufferedImage toImage(StaticMap map) {
if (map.dims() != 2)
throw new IllegalArgumentException("Cannot display " + map.dims() + "-D map as image.");
BufferedImage image = new BufferedImage(map.size(0), map.size(1), BufferedImage.TYPE_BYTE_GRAY);
image.getRaster().setDataElements(0, 0, map.size(0), map.size(1), map.getData());
return image;
}
public static BufferedImage toImage(GridMap map) {
if (map.dims() != 2)
throw new IllegalArgumentException("Cannot display " + map.dims() + "-D map as image.");
BufferedImage image = new BufferedImage(map.size(0), map.size(1), BufferedImage.TYPE_BYTE_GRAY);
fillImage(image, map);
return image;
}
public static void fillImage(BufferedImage image, GridMap map) {
int width = Math.min(image.getWidth(), map.size(0));
int height = Math.min(image.getHeight(), map.size(1));
fillImage(image, map, 0, 0, width, height);
}
public static void fillImage(BufferedImage image, GridMap map, int x, int y, int width, int height) {
WritableRaster wr = image.getRaster();
for (int i = y; i < height; i++) {
for (int j = x; j < width; j++) {
wr.setSample(j, i, 0, map.get(j, i));
}
}
}
}
|
package seedu.tasklist.ui;
import java.util.Map;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.MenuItem;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import seedu.tasklist.commons.core.Config;
import seedu.tasklist.commons.core.GuiSettings;
import seedu.tasklist.commons.events.ui.ExitAppRequestEvent;
import seedu.tasklist.logic.Logic;
import seedu.tasklist.model.UserPrefs;
/**
* The Main Window. Provides the basic application layout containing a menu bar
* and space where other JavaFX elements can be placed.
*/
public class MainWindow extends UiPart {
private static final String ICON = "/images/tasklist.png";
private static final String FXML = "MainWindow.fxml";
public static final int MIN_HEIGHT = 600;
public static final int MIN_WIDTH = 450;
private Logic logic;
// Independent Ui parts residing in this Ui container
private TaskListPanel filteredTaskListPanel;
private TaskListPanel mainTaskListPanel;
private ResultDisplay resultDisplay;
@SuppressWarnings("unused")
private StatusBarFooter statusBarFooter;
private CommandBox commandBox;
private Config config;
// Handles to elements of this Ui container
private VBox rootLayout;
private Scene scene;
@FXML
private AnchorPane commandBoxPlaceholder;
@FXML
private AnchorPane filteredTaskListPanelPlaceholder;
@FXML
private AnchorPane mainTaskListPanelPlaceholder;
@FXML
private AnchorPane resultDisplayPlaceholder;
@FXML
private AnchorPane statusbarPlaceholder;
@FXML
private MenuItem mainMenuItem, helpMenuItem,
commandNextMenuItem, commandPreviousMenuItem,
filteredListNextMenuItem, filteredListPreviousMenuItem, filteredListFirstMenuItem, filteredListLastMenuItem,
mainListNextMenuItem, mainListPreviousMenuItem, mainListFirstMenuItem, mainListLastMenuItem;
public MainWindow() {
super();
}
@Override
public void setNode(Node node) {
rootLayout = (VBox) node;
}
@Override
public String getFxmlPath() {
return FXML;
}
public static MainWindow load(Stage primaryStage, Config config, UserPrefs prefs, Logic logic) {
MainWindow mainWindow = UiPartLoader.loadUiPart(primaryStage, new MainWindow());
mainWindow.configure(config.getAppTitle(), config.getTaskListName(), config, prefs, logic);
return mainWindow;
}
private void configure(String appTitle, String taskListName, Config config, UserPrefs prefs, Logic logic) {
// Set dependencies
this.logic = logic;
this.config = config;
// Configure the UI
setTitle(appTitle);
setIcon(ICON);
setWindowMinSize();
setWindowDefaultSize(prefs);
scene = new Scene(rootLayout);
primaryStage.setScene(scene);
setAccelerators();
addEventFilters();
}
//@@author A0146840E
private void setAccelerators() {
mainMenuItem.setAccelerator(KeyCombination.valueOf("F11"));
helpMenuItem.setAccelerator(KeyCombination.valueOf("F1"));
commandNextMenuItem.setAccelerator(KeyCombination.valueOf("UP"));
commandPreviousMenuItem.setAccelerator(KeyCombination.valueOf("DOWN"));
filteredListFirstMenuItem.setAccelerator(KeyCombination.valueOf("Home"));
filteredListLastMenuItem.setAccelerator(KeyCombination.valueOf("End"));
filteredListPreviousMenuItem.setAccelerator(KeyCombination.valueOf("Page Up"));
filteredListNextMenuItem.setAccelerator(KeyCombination.valueOf("Page Down"));
mainListFirstMenuItem.setAccelerator(KeyCombination.valueOf("Ctrl+Home"));
mainListLastMenuItem.setAccelerator(KeyCombination.valueOf("Ctrl+End"));
mainListPreviousMenuItem.setAccelerator(KeyCombination.valueOf("Ctrl+Page Up"));
mainListNextMenuItem.setAccelerator(KeyCombination.valueOf("Ctrl+Page Down"));
}
private void addEventFilters() {
scene.addEventFilter(KeyEvent.KEY_PRESSED, (event) -> {
Map<KeyCombination,Runnable> accelerators = scene.getAccelerators();
for (KeyCombination keyCombination : accelerators.keySet()) {
if (keyCombination.match(event)) {
accelerators.get(keyCombination).run();
event.consume();
return;
}
}
});
}
void fillInnerParts() {
mainTaskListPanel = TaskListPanel.load(primaryStage, mainTaskListPanelPlaceholder, logic.getMainFilteredTaskList(), TaskListPanel.Type.MAIN_TASKLIST);
filteredTaskListPanel = TaskListPanel.load(primaryStage, getTaskListPlaceholder(), logic.getFilteredTaskList(), TaskListPanel.Type.FILTERED_TASKLIST);
resultDisplay = ResultDisplay.load(primaryStage, getResultDisplayPlaceholder());
statusBarFooter = StatusBarFooter.load(primaryStage, getStatusbarPlaceholder(), config.getTaskListFilePath(), logic.getMainFilteredTaskList());
commandBox = CommandBox.load(primaryStage, getCommandBoxPlaceholder(), resultDisplay, logic);
}
//@@author
private AnchorPane getCommandBoxPlaceholder() {
return commandBoxPlaceholder;
}
private AnchorPane getStatusbarPlaceholder() {
return statusbarPlaceholder;
}
private AnchorPane getResultDisplayPlaceholder() {
return resultDisplayPlaceholder;
}
public AnchorPane getTaskListPlaceholder() {
return filteredTaskListPanelPlaceholder;
}
public void hide() {
primaryStage.hide();
}
private void setTitle(String appTitle) {
primaryStage.setTitle(appTitle);
}
/**
* Sets the default size based on user preferences.
*/
protected void setWindowDefaultSize(UserPrefs prefs) {
primaryStage.setHeight(prefs.getGuiSettings().getWindowHeight());
primaryStage.setWidth(prefs.getGuiSettings().getWindowWidth());
if (prefs.getGuiSettings().getWindowCoordinates() != null) {
primaryStage.setX(prefs.getGuiSettings().getWindowCoordinates().getX());
primaryStage.setY(prefs.getGuiSettings().getWindowCoordinates().getY());
}
}
private void setWindowMinSize() {
primaryStage.setMinHeight(MIN_HEIGHT);
primaryStage.setMinWidth(MIN_WIDTH);
}
/**
* Returns the current size and the position of the main Window.
*/
public GuiSettings getCurrentGuiSetting() {
return new GuiSettings(primaryStage.getWidth(), primaryStage.getHeight(), (int) primaryStage.getX(),
(int) primaryStage.getY());
}
@FXML
public void handleHelp() {
HelpWindow helpWindow = HelpWindow.load(primaryStage);
helpWindow.show();
}
//@@author A0146840E
/**
* Scroll to the first task in the main tasks list view
*/
@FXML
private void handleMainListPanelScrollToFirst() {
mainTaskListPanel.scrollToFirst();
}
/**
* Scroll to the last task in the main tasks list view
*/
@FXML
private void handleMainListPanelScrollToLast() {
mainTaskListPanel.scrollToLast();
}
/**
* Scroll up in the main tasks list view
*/
@FXML
private void handleMainListPanelScrollUp() {
mainTaskListPanel.scrollToPrevious();
}
/**
* Scroll down in the main tasks list view
*/
@FXML
private void handleMainListPanelScrollDown() {
mainTaskListPanel.scrollToNext();
}
/**
* Scroll to the first task in the filtered tasks list view
*/
@FXML
private void handleFilteredListPanelScrollToFirst() {
filteredTaskListPanel.scrollToFirst();
}
/**
* Scroll to the last task in the filtered tasks list view
*/
@FXML
private void handleFilteredListPanelScrollToLast() {
filteredTaskListPanel.scrollToLast();
}
/**
* Scroll up in the filtered tasks list view
*/
@FXML
private void handleFilteredListPanelScrollUp() {
filteredTaskListPanel.scrollToPrevious();
}
/**
* Scroll down in the filtered tasks list view
*/
@FXML
private void handleFilteredListPanelScrollDown() {
filteredTaskListPanel.scrollToNext();
}
/**
* Set the main Window into and out of full screen mode
*/
@FXML
private void handleFullScreen() {
if (primaryStage.isFullScreen()) {
primaryStage.setFullScreen(false);
} else {
primaryStage.setFullScreen(true);
}
}
/**
* Scroll through the previous commands by pressing the Up Key
*/
@FXML
private void handlePreviousCommandTextNext() {
commandBox.selectPreviousCommandTextNext();
}
/**
* Scroll through the previous commands by pressing the Down Key
*/
@FXML
private void handlePreviousCommandTextPrevious() {
commandBox.selectPreviousCommandTextPrevious();
}
//@@author
public void show() {
primaryStage.show();
}
/**
* Closes the application.
*/
@FXML
private void handleExit() {
raise(new ExitAppRequestEvent());
}
public TaskListPanel getTaskListPanel() {
return this.filteredTaskListPanel;
}
}
|
package tigase.server;
import tigase.conf.Configurable;
import tigase.disco.ServiceEntity;
import tigase.disco.ServiceIdentity;
import tigase.disco.XMPPService;
import tigase.osgi.OSGiScriptEngineManager;
import tigase.server.script.AddScriptCommand;
import tigase.server.script.CommandIfc;
import tigase.server.script.RemoveScriptCommand;
import tigase.util.DNSResolver;
import tigase.util.TigaseStringprepException;
import tigase.vhosts.VHostItem;
import tigase.vhosts.VHostListener;
import tigase.vhosts.VHostManagerIfc;
import tigase.xml.Element;
import tigase.xmpp.Authorization;
import tigase.xmpp.BareJID;
import tigase.xmpp.JID;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import javax.script.Bindings;
import javax.script.ScriptEngineManager;
/**
* Created: Oct 17, 2009 7:49:05 PM
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class BasicComponent
implements Configurable, XMPPService, VHostListener {
/** Field description */
public static final String ALL_PROP_KEY = "ALL";
/** Field description */
public static final String COMMAND_PROP_NODE = "command";
/** Field description */
public static final String SCRIPTS_DIR_PROP_DEF = "scripts/admin";
/** Field description */
public static final String SCRIPTS_DIR_PROP_KEY = "scripts-dir";
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log = Logger.getLogger(BasicComponent.class.getName());
/** Field description */
protected VHostManagerIfc vHostManager = null;
private ComponentInfo cmpInfo = null;
private JID compId = null;
private String DEF_HOSTNAME_PROP_VAL = DNSResolver.getDefaultHostname();
private String name = null;
private BareJID defHostname = BareJID.bareJIDInstanceNS(
DEF_HOSTNAME_PROP_VAL);
/** Field description */
protected Map<String, CommandIfc> scriptCommands = new ConcurrentHashMap<String,
CommandIfc>(20);
private boolean nonAdminCommands = false;
private Map<String, EnumSet<CmdAcl>> commandsACL = new ConcurrentHashMap<String,
EnumSet<CmdAcl>>(20);
/**
* List of the component administrators
*/
protected Set<BareJID> admins = new ConcurrentSkipListSet<BareJID>();
private ScriptEngineManager scriptEngineManager = null;
private String scriptsBaseDir = null;
private String scriptsCompDir = null;
private ServiceEntity serviceEntity = null;
private boolean initializationCompleted = false;
/**
* Method description
*
*
* @param domain
*/
public void addComponentDomain(String domain) {
vHostManager.addComponentDomain(domain);
}
/**
*
* @param jid
* @param commandId
*
*
* @return a value of <code>boolean</code>
*/
public boolean canCallCommand(JID jid, String commandId) {
boolean result = isAdmin(jid);
if (result) {
return true;
}
EnumSet<CmdAcl> acl = commandsACL.get(ALL_PROP_KEY);
if (acl != null) {
result = checkCommandAcl(jid, acl);
}
if (!result) {
acl = commandsACL.get(commandId);
if (acl != null) {
result = checkCommandAcl(jid, acl);
}
}
return result;
}
/**
* Method description
*
*
* @param jid
* @param acl
*
*
*
* @return a value of <code>boolean</code>
*/
public boolean checkCommandAcl(JID jid, EnumSet<CmdAcl> acl) {
for (CmdAcl cmdAcl : acl) {
switch (cmdAcl) {
case ALL :
return true;
case ADMIN :
if (isAdmin(jid)) {
return true;
}
break;
case LOCAL :
if (isLocalDomain(jid.getDomain())) {
return true;
}
break;
case DOMAIN :
if (jid.getDomain().equals(cmdAcl.getAclVal())) {
return true;
}
break;
case JID :
case OTHER :
default :
if (jid.getBareJID().toString().equals(cmdAcl.getAclVal())) {
return true;
}
}
}
return false;
}
/**
* Method description
*
*
*
*
* @return a value of <code>boolean</code>
*/
@Override
public boolean handlesLocalDomains() {
return false;
}
/**
* Method description
*
*
*
*
* @return a value of <code>boolean</code>
*/
@Override
public boolean handlesNameSubdomains() {
return true;
}
/**
* Method description
*
*
*
*
* @return a value of <code>boolean</code>
*/
@Override
public boolean handlesNonLocalDomains() {
return false;
}
/**
* Initialize a mapping of key/value pairs which can be used in scripts
* loaded by the server
*
* @param binds A mapping of key/value pairs, all of whose keys are Strings.
*/
public void initBindings(Bindings binds) {
binds.put(CommandIfc.VHOST_MANAGER, vHostManager);
binds.put(CommandIfc.ADMINS_SET, admins);
binds.put(CommandIfc.COMMANDS_ACL, commandsACL);
binds.put(CommandIfc.SCRI_MANA, scriptEngineManager);
binds.put(CommandIfc.ADMN_CMDS, scriptCommands);
binds.put(CommandIfc.ADMN_DISC, serviceEntity);
binds.put(CommandIfc.SCRIPT_BASE_DIR, scriptsBaseDir);
binds.put(CommandIfc.SCRIPT_COMP_DIR, scriptsCompDir);
binds.put(CommandIfc.COMPONENT_NAME, getName());
}
/**
* Method description
*
*/
@Override
public void initializationCompleted() {
initializationCompleted = true;
// log.log(Level.WARNING,
// "initializationCompleted for component name: {0}, full JID: {1}", new Object[] {
// getName(),
// getComponentId() });
// Thread.dumpStack();
}
/**
* Method description
*
*
* @param packet
* @param results
*/
@Override
public void processPacket(Packet packet, Queue<Packet> results) {
if (packet.isCommand() && getName().equals(packet.getStanzaTo().getLocalpart()) &&
isLocalDomain(packet.getStanzaTo().getDomain())) {
processScriptCommand(packet, results);
}
}
/**
* Method description
*
*/
@Override
public void release() {}
/**
* Method description
*
*
* @param domain
*/
public void removeComponentDomain(String domain) {
vHostManager.removeComponentDomain(domain);
}
/**
* Method description
*
*
* @param jid
* @param node
* @param description
*/
public void removeServiceDiscoveryItem(String jid, String node, String description) {
ServiceEntity item = new ServiceEntity(jid, node, description);
// item.addIdentities(new ServiceIdentity("component", identity_type,
// name));
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Modifying service-discovery info, removing: {0}", item);
}
serviceEntity.removeItems(item);
}
/**
* Method description
*
*
* @param jid
* @param node
* @param description
* @param admin
*/
public void updateServiceDiscoveryItem(String jid, String node, String description,
boolean admin) {
updateServiceDiscoveryItem(jid, node, description, admin, (String[]) null);
}
/**
* Method description
*
*
* @param jid
* @param node
* @param description
* @param admin
* @param features
*/
public void updateServiceDiscoveryItem(String jid, String node, String description,
boolean admin, String... features) {
updateServiceDiscoveryItem(jid, node, description, null, null, admin, features);
}
/**
* Method description
*
*
* @param jid
* @param node
* @param description
* @param category
* @param type
* @param admin
* @param features
*/
public void updateServiceDiscoveryItem(String jid, String node, String description,
String category, String type, boolean admin, String... features) {
if (serviceEntity.getJID().equals(jid) && (serviceEntity.getNode() == node)) {
serviceEntity.setAdminOnly(admin);
serviceEntity.setDescription(description);
if ((category != null) || (type != null)) {
serviceEntity.addIdentities(new ServiceIdentity(category, type, description));
}
if (features != null) {
serviceEntity.setFeatures("http://jabber.org/protocol/commands");
serviceEntity.addFeatures(features);
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Modifying service-discovery info: {0}", serviceEntity);
}
} else {
ServiceEntity item = new ServiceEntity(jid, node, description, admin);
if ((category != null) || (type != null)) {
item.addIdentities(new ServiceIdentity(category, type, description));
}
if (features != null) {
item.addFeatures(features);
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Adding new item: {0}", item);
}
serviceEntity.addItems(item);
}
}
/**
* Method description
*
*/
public void updateServiceEntity() {
serviceEntity = new ServiceEntity(name, null, getDiscoDescription(), true);
serviceEntity.addIdentities(new ServiceIdentity(getDiscoCategory(),
getDiscoCategoryType(), getDiscoDescription()));
serviceEntity.addFeatures("http://jabber.org/protocol/commands");
}
/**
* Method description
*
*
*
*
* @return a value of <code>JID</code>
*/
@Override
public JID getComponentId() {
return compId;
}
/**
* Allows to obtain various informations about components
*
* @return information about particular component
*/
@Override
public ComponentInfo getComponentInfo() {
if (cmpInfo == null) {
cmpInfo = new ComponentInfo(getName(), this.getClass());
}
return cmpInfo;
}
/**
* Method description
*
*
* @param params
*
*
*
* @return a value of <code>Map<String,Object></code>
*/
@Override
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> defs = new LinkedHashMap<String, Object>(50);
defs.put(COMPONENT_ID_PROP_KEY, compId.toString());
DEF_HOSTNAME_PROP_VAL = DNSResolver.getDefaultHostname();
defs.put(DEF_HOSTNAME_PROP_KEY, DEF_HOSTNAME_PROP_VAL);
String[] adm = null;
if (params.get(GEN_ADMINS) != null) {
adm = ((String) params.get(GEN_ADMINS)).split(",");
} else {
adm = new String[] { "admin@localhost" };
}
defs.put(ADMINS_PROP_KEY, adm);
String scripts_dir = (String) params.get(GEN_SCRIPT_DIR);
if (scripts_dir == null) {
scripts_dir = SCRIPTS_DIR_PROP_DEF;
}
defs.put(SCRIPTS_DIR_PROP_KEY, scripts_dir);
defs.put(COMMAND_PROP_NODE + "/" + ALL_PROP_KEY, CmdAcl.ADMIN.name());
return defs;
}
/**
* Method description
*
*
*
*
* @return a value of <code>BareJID</code>
*/
public BareJID getDefHostName() {
return defHostname;
}
/**
* Method description
*
*
*
*
* @return a value of <code>BareJID</code>
*/
public BareJID getDefVHostItem() {
return (vHostManager != null)
? vHostManager.getDefVHostItem()
: getDefHostName();
}
/**
* Method description
*
*
*
*
* @return a value of <code>String</code>
*/
public String getDiscoCategory() {
return "component";
}
/**
* Method description
*
*
*
*
* @return a value of <code>String</code>
*/
public String getDiscoCategoryType() {
return "generic";
}
/**
* Method description
*
*
*
*
* @return a value of <code>String</code>
*/
public String getDiscoDescription() {
return "Undefined description";
}
/**
* Exists for backward compatibility with the old API.
*
*
*
* @return a value of <code>List<Element></code>
*/
@Deprecated
public List<Element> getDiscoFeatures() {
return null;
}
/**
* Method description
*
*
* @param from
*
*
*
* @return a value of <code>List<Element></code>
*/
@Override
public List<Element> getDiscoFeatures(JID from) {
return getDiscoFeatures();
}
/**
* Exists for backward compatibility with the old API.
*
* @param node
* @param jid
*
*
*
* @return a value of <code>Element</code>
*/
@Deprecated
public Element getDiscoInfo(String node, JID jid) {
return null;
}
/**
* Method description
*
*
* @param node
* @param jid
* @param from
*
*
*
* @return a value of <code>Element</code>
*/
@Override
public Element getDiscoInfo(String node, JID jid, JID from) {
// This is only to support the old depreciated API.
Element result = getDiscoInfo(node, jid);
if (result != null) {
return result;
}
// OLD API support end
if (getName().equals(jid.getLocalpart()) || jid.toString().startsWith(getName() +
".")) {
return serviceEntity.getDiscoInfo(node, isAdmin(from) || nonAdminCommands);
}
return null;
}
/**
* Exists for backward compatibility with the old API.
*
* @deprecated
*
* @param node
* @param jid
*
*
*
* @return a value of <code>List<Element></code>
*/
@Deprecated
public List<Element> getDiscoItems(String node, JID jid) {
return null;
}
/**
* Method description
*
*
* @param node
* @param jid
* @param from
*
*
*
* @return a value of <code>List<Element></code>
*/
@Override
public List<Element> getDiscoItems(String node, JID jid, JID from) {
// This is only to support the old depreciated API.
List<Element> result = getDiscoItems(node, jid);
if (result != null) {
return result;
}
// OLD API support end
boolean isAdminFrom = isAdmin(from);
if (getName().equals(jid.getLocalpart()) || jid.toString().startsWith(getName() +
".")) {
if (node != null) {
if (node.equals("http://jabber.org/protocol/commands") && (isAdminFrom ||
nonAdminCommands)) {
result = new LinkedList<Element>();
for (CommandIfc comm : scriptCommands.values()) {
if (!comm.isAdminOnly() || isAdminFrom) {
result.add(new Element("item", new String[] { "node", "name", "jid" },
new String[] { comm.getCommandId(),
comm.getDescription(), jid.toString() }));
}
}
} else {
result = serviceEntity.getDiscoItems(node, jid.toString(), (isAdminFrom ||
nonAdminCommands));
}
} else {
result = serviceEntity.getDiscoItems(null, jid.toString(), (isAdminFrom ||
nonAdminCommands));
if (result != null) {
for (Iterator<Element> it = result.iterator(); it.hasNext(); ) {
Element element = it.next();
if (element.getAttributeStaticStr("node") == null) {
it.remove();
}
}
}
}
// Element result = serviceEntity.getDiscoItem(null, getName() + "." + jid);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Found disco items: {0}", ((result != null)
? result.toString()
: null));
}
return result;
} else {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "{0} General disco items request, node: {1}",
new Object[] { getName(),
node });
}
if (node == null) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "{0} Disco items request for null node", new Object[] {
getName() });
}
Element res = null;
if (!serviceEntity.isAdminOnly() || isAdmin(from) || nonAdminCommands) {
res = serviceEntity.getDiscoItem(null, isSubdomain()
? (getName() + "." + jid)
: getName() + "@" + jid.toString());
}
result = serviceEntity.getDiscoItems(null, null, (isAdminFrom ||
nonAdminCommands));
if (res != null) {
if (result != null) {
for (Iterator<Element> it = result.iterator(); it.hasNext(); ) {
Element element = it.next();
if (element.getAttributeStaticStr("node") != null) {
it.remove();
}
}
result.add(0, res);
} else {
result = Arrays.asList(res);
}
}
}
return result;
}
}
/**
* Method description
*
*
*
*
* @return a value of <code>String</code>
*/
@Override
public String getName() {
return name;
}
/**
* Method description
*
*
* @param node
* @param jid
* @param from
*
*
*
* @return a value of <code>List<Element></code>
*/
public List<Element> getScriptItems(String node, JID jid, JID from) {
LinkedList<Element> result = null;
boolean isAdminFrom = isAdmin(from);
if (node.equals("http://jabber.org/protocol/commands") && (isAdminFrom ||
nonAdminCommands)) {
result = new LinkedList<Element>();
for (CommandIfc comm : scriptCommands.values()) {
if (!comm.isAdminOnly() || isAdminFrom) {
result.add(new Element("item", new String[] { "node", "name", "jid" },
new String[] { comm.getCommandId(),
comm.getDescription(), jid.toString() }));
}
}
}
return result;
}
/**
* Method description
*
*
* @param domain
*
*
*
* @return a value of <code>VHostItem</code>
*/
public VHostItem getVHostItem(String domain) {
return (vHostManager != null)
? vHostManager.getVHostItem(domain)
: null;
}
/**
* Method description
*
*
* @param jid
*
*
*
* @return a value of <code>boolean</code>
*/
public boolean isAdmin(JID jid) {
return admins.contains(jid.getBareJID());
}
/**
* Method description
*
*
*
*
* @return a value of <code>boolean</code>
*/
@Override
public boolean isInitializationComplete() {
return initializationCompleted;
}
/**
* Method description
*
*
* @param domain
*
*
*
* @return a value of <code>boolean</code>
*/
public boolean isLocalDomain(String domain) {
return (vHostManager != null)
? vHostManager.isLocalDomain(domain)
: false;
}
/**
* Method description
*
*
* @param domain
*
*
*
* @return a value of <code>boolean</code>
*/
public boolean isLocalDomainOrComponent(String domain) {
return (vHostManager != null)
? vHostManager.isLocalDomainOrComponent(domain)
: false;
}
/**
* Method returns true is component should be represented as subdomain
*
*
*
* @return a value of <code>boolean</code>
*/
public boolean isSubdomain() {
return false;
}
/**
* Method description
*
*
* @param name
*/
@Override
public void setName(String name) {
this.name = name;
try {
compId = JID.jidInstance(name, defHostname.getDomain(), null);
} catch (TigaseStringprepException ex) {
log.log(Level.WARNING, "Problem setting component ID: ", ex);
}
}
/**
* Method description
*
*
* @param props
*/
@Override
public void setProperties(Map<String, Object> props) {
if (isInitializationComplete()) {
// Do we really need to do this again?
return;
}
if (scriptEngineManager == null) {
if (XMPPServer.isOSGi()) {
scriptEngineManager = new OSGiScriptEngineManager();
} else {
scriptEngineManager = new ScriptEngineManager();
}
}
if (props.get(COMPONENT_ID_PROP_KEY) != null) {
try {
compId = JID.jidInstance((String) props.get(COMPONENT_ID_PROP_KEY));
} catch (TigaseStringprepException ex) {
log.log(Level.WARNING, "Problem setting component ID: ", ex);
}
}
if (props.get(DEF_HOSTNAME_PROP_KEY) != null) {
defHostname = BareJID.bareJIDInstanceNS((String) props.get(DEF_HOSTNAME_PROP_KEY));
}
String[] admins_tmp = (String[]) props.get(ADMINS_PROP_KEY);
if (admins_tmp != null) {
for (String admin : admins_tmp) {
try {
admins.add(BareJID.bareJIDInstance(admin));
} catch (TigaseStringprepException ex) {
log.log(Level.CONFIG, "Incorrect admin JID: ", ex);
}
}
}
for (Map.Entry<String, Object> entry : props.entrySet()) {
if (entry.getKey().startsWith(COMMAND_PROP_NODE)) {
String cmdId = entry.getKey().substring(COMMAND_PROP_NODE.length() + 1);
String[] cmdAcl = entry.getValue().toString().split(",");
EnumSet<CmdAcl> acl = EnumSet.noneOf(CmdAcl.class);
for (String cmda : cmdAcl) {
CmdAcl acl_tmp = CmdAcl.valueof(cmda);
acl.add(acl_tmp);
if (acl_tmp != CmdAcl.ADMIN) {
nonAdminCommands = true;
}
}
commandsACL.put(cmdId, acl);
}
}
updateServiceEntity();
CommandIfc command = new AddScriptCommand();
command.init(CommandIfc.ADD_SCRIPT_CMD, "New command script");
scriptCommands.put(command.getCommandId(), command);
command = new RemoveScriptCommand();
command.init(CommandIfc.DEL_SCRIPT_CMD, "Remove command script");
scriptCommands.put(command.getCommandId(), command);
if (props.get(SCRIPTS_DIR_PROP_KEY) != null) {
scriptsBaseDir = (String) props.get(SCRIPTS_DIR_PROP_KEY);
scriptsCompDir = scriptsBaseDir + "/" + getName();
loadScripts();
}
cmpInfo = new ComponentInfo(getName(), this.getClass());
}
/**
* Method description
*
*
* @param manager
*/
@Override
public void setVHostManager(VHostManagerIfc manager) {
this.vHostManager = manager;
}
/**
* Method description
*
*
* @param pc
* @param results
*
*
*
* @return a value of <code>boolean</code>
*/
protected boolean processScriptCommand(Packet pc, Queue<Packet> results) {
// TODO: test if this is right
// It is not, the packet should actually have packetFrom set at all times
// to ensure the error can be sent back to the original sender.
// if ((pc.getStanzaFrom() == null) || (pc.getPacketFrom() != null)) {
//// The packet has not gone through session manager yet
// return false;
// This test is more correct as it says whether the packet went through
// session manager checking.
// TODO: test if commands still work for users from different XMPP servers
if (pc.getPermissions() == Permissions.NONE) {
return false;
}
Iq iqc = (Iq) pc;
Command.Action action = Command.getAction(iqc);
if (action == Command.Action.cancel) {
Packet result = iqc.commandResult(Command.DataType.result);
Command.addTextField(result, "Note", "Command canceled.");
results.offer(result);
return true;
}
String strCommand = iqc.getStrCommand();
CommandIfc com = scriptCommands.get(strCommand);
if ((strCommand != null) && (com != null)) {
boolean admin = false;
try {
admin = canCallCommand(iqc.getStanzaFrom(), strCommand);
if (admin) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Processing admin command: {0}", pc);
}
Bindings binds = com.getBindings();
if (binds == null) {
binds = scriptEngineManager.getBindings();
}
// Bindings binds = scriptEngineManager.getBindings();
initBindings(binds);
com.runCommand(iqc, binds, results);
} else {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Command rejected non-admin detected: {0}", pc
.getStanzaFrom());
}
results.offer(Authorization.FORBIDDEN.getResponseMessage(pc,
"Only Administrator can call the command.", true));
}
} catch (Exception e) {
log.log(Level.WARNING, "Unknown admin command processing exception: " + pc, e);
}
return true;
}
return false;
}
/**
* Method description
*
*
*
*
* @return a value of <code>Map<String,CommandIfc></code>
*/
protected Map<String, CommandIfc> getScriptCommands() {
return scriptCommands;
}
/**
* Method description
*
*
*
*
* @return a value of <code>ServiceEntity</code>
*/
protected ServiceEntity getServiceEntity() {
return serviceEntity;
}
/**
* Method description
*
*
*
*
* @return a value of <code>boolean</code>
*/
protected boolean isNonAdminCommands() {
return nonAdminCommands;
}
private void loadScripts() {
log.log(Level.CONFIG, "Loading admin scripts for component: {0}.", new Object[] {
getName() });
File file = null;
AddScriptCommand addCommand = new AddScriptCommand();
Bindings binds = scriptEngineManager.getBindings();
initBindings(binds);
String[] dirs = new String[] { scriptsBaseDir, scriptsCompDir };
for (String scriptsPath : dirs) {
log.log(Level.CONFIG, "{0}: Loading scripts from directory: {1}", new Object[] {
getName(),
scriptsPath });
try {
File adminDir = new File(scriptsPath);
if ((adminDir != null) && adminDir.exists()) {
for (File f : adminDir.listFiles()) {
// Just regular files here....
if (f.isFile() &&!f.toString().endsWith("~")) {
String cmdId = null;
String cmdDescr = null;
String comp = null;
file = f;
StringBuilder sb = new StringBuilder();
BufferedReader buffr = new BufferedReader(new FileReader(file));
String line = null;
while ((line = buffr.readLine()) != null) {
sb.append(line).append("\n");
int idx = line.indexOf(CommandIfc.SCRIPT_DESCRIPTION);
if (idx >= 0) {
cmdDescr = line.substring(idx + CommandIfc.SCRIPT_DESCRIPTION.length())
.trim();
}
idx = line.indexOf(CommandIfc.SCRIPT_ID);
if (idx >= 0) {
cmdId = line.substring(idx + CommandIfc.SCRIPT_ID.length()).trim();
}
idx = line.indexOf(CommandIfc.SCRIPT_COMPONENT);
if (idx >= 0) {
comp = line.substring(idx + CommandIfc.SCRIPT_COMPONENT.length())
.trim();
}
}
buffr.close();
if ((cmdId == null) || (cmdDescr == null) || (comp == null)) {
log.log(Level.WARNING,
"Admin script found but it has no command ID or command" +
"description: " + "{0}", file);
continue;
}
// What components should load the script....
String[] comp_names = comp.split(",");
boolean found = false;
for (String cmp : comp_names) {
found = getName().equals(cmp);
if (found) {
break;
}
}
if (!found) {
log.log(Level.CONFIG,
"{0}: skipping admin script {1} for component: {2}", new Object[] {
getName(),
scriptsPath, comp });
continue;
}
int idx = file.toString().lastIndexOf('.');
String ext = file.toString().substring(idx + 1);
addCommand.addAdminScript(cmdId, cmdDescr, sb.toString(), null, ext, binds);
log.log(Level.CONFIG,
"{0}: Loaded admin command from file: {1}, id: {2}, ext: {3}, descr: {4}",
new Object[] { getName(),
file, cmdId, ext, cmdDescr });
}
}
} else {
log.log(Level.CONFIG, "Admin scripts directory is missing: {0}, creating...",
adminDir);
try {
adminDir.mkdirs();
} catch (Exception e) {
log.log(Level.WARNING,
"Can't create scripts directory , read-only filesystem: " + file, e);
}
}
} catch (Exception e) {
log.log(Level.WARNING, "Can't load the admin script file: " + file, e);
}
}
}
}
//~ Formatted in Tigase Code Convention on 13/12/09
|
package org.brailleblaster.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
public class FileUtils {
public FileUtils() {
}
public boolean exists (String fileName) {
File file = new File (fileName);
return file.exists();
}
public void create (String fileName){
File f = new File(fileName);
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
new Notify ("Could not create file" + fileName);
}
}
}
public boolean delete(String fileName){
File f= new File(fileName);
if(f.exists()){
return f.delete();
}
return true;
}
public void copyFile (String inputFileName,
String outputFileName) {
FileInputStream inFile = null;
FileOutputStream outFile = null;
try {
inFile = new FileInputStream (new File(inputFileName));
} catch (FileNotFoundException e) {
new Notify ("Could not open input file " + inputFileName);
return;
}
try {
outFile = new FileOutputStream (new File(outputFileName));
} catch (FileNotFoundException e) {
new Notify ("Could not open output file " + outputFileName);
return;
}
byte[] buffer = new byte[1024];
int length = 0;
while (length != -1) {
try {
length = inFile.read (buffer, 0, buffer.length);
} catch (IOException e) {
new Notify ("Problem reading " + inputFileName);
break;
}
if (length == -1) {
break;
}
try {
outFile.write (buffer, 0, length);
} catch (IOException e) {
new Notify ("Problem writing to " + outputFileName);
break;
}
}
try {
outFile.close();
} catch (IOException e) {
new Notify ("output file " + outputFileName +
"could not be completed");
}
}
public boolean deleteDirectory(File directory) {
if (directory == null)
return false;
if (!directory.exists())
return true;
if (!directory.isDirectory())
return false;
String[] list = directory.list();
// Some JVMs return null for File.list() when the
// directory is empty.
if (list != null) {
for (int i = 0; i < list.length; i++) {
File entry = new File(directory, list[i]);
if (entry.isDirectory())
{
if (!deleteDirectory(entry))
return false;
}
else
{
if (!entry.delete())
return false;
}
}
}
return directory.delete();
}
}
|
package cz.xtf.core.openshift;
import static cz.xtf.core.config.OpenShiftConfig.routeDomain;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.ServiceLoader;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import cz.xtf.core.config.WaitingConfig;
import cz.xtf.core.event.EventList;
import cz.xtf.core.openshift.crd.CustomResourceDefinitionContextProvider;
import cz.xtf.core.waiting.SimpleWaiter;
import cz.xtf.core.waiting.Waiter;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.Endpoints;
import io.fabric8.kubernetes.api.model.EnvVar;
import io.fabric8.kubernetes.api.model.EnvVarBuilder;
import io.fabric8.kubernetes.api.model.Event;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesList;
import io.fabric8.kubernetes.api.model.LocalObjectReferenceBuilder;
import io.fabric8.kubernetes.api.model.Node;
import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.api.model.ObjectReferenceBuilder;
import io.fabric8.kubernetes.api.model.PersistentVolumeClaim;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodSpec;
import io.fabric8.kubernetes.api.model.ReplicationController;
import io.fabric8.kubernetes.api.model.ResourceQuota;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecretBuilder;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServiceAccount;
import io.fabric8.kubernetes.api.model.apps.StatefulSet;
import io.fabric8.kubernetes.api.model.autoscaling.v1.HorizontalPodAutoscaler;
import io.fabric8.kubernetes.api.model.rbac.Role;
import io.fabric8.kubernetes.api.model.rbac.RoleBinding;
import io.fabric8.kubernetes.api.model.rbac.RoleBindingBuilder;
import io.fabric8.kubernetes.api.model.rbac.Subject;
import io.fabric8.kubernetes.api.model.rbac.SubjectBuilder;
import io.fabric8.kubernetes.client.AppsAPIGroupClient;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.LocalPortForward;
import io.fabric8.kubernetes.client.dsl.LogWatch;
import io.fabric8.openshift.api.model.Build;
import io.fabric8.openshift.api.model.BuildConfig;
import io.fabric8.openshift.api.model.BuildRequest;
import io.fabric8.openshift.api.model.BuildRequestBuilder;
import io.fabric8.openshift.api.model.DeploymentConfig;
import io.fabric8.openshift.api.model.ImageStream;
import io.fabric8.openshift.api.model.ImageStreamTag;
import io.fabric8.openshift.api.model.Project;
import io.fabric8.openshift.api.model.ProjectRequest;
import io.fabric8.openshift.api.model.ProjectRequestBuilder;
import io.fabric8.openshift.api.model.Route;
import io.fabric8.openshift.api.model.RouteSpecBuilder;
import io.fabric8.openshift.api.model.Template;
import io.fabric8.openshift.client.DefaultOpenShiftClient;
import io.fabric8.openshift.client.OpenShiftConfig;
import io.fabric8.openshift.client.OpenShiftConfigBuilder;
import io.fabric8.openshift.client.ParameterValue;
import lombok.extern.slf4j.Slf4j;
import rx.Observable;
import rx.observables.StringObservable;
@Slf4j
public class OpenShift extends DefaultOpenShiftClient {
private static ServiceLoader<CustomResourceDefinitionContextProvider> crdContextProviderLoader;
private static volatile String routeSuffix;
public static final String KEEP_LABEL = "xtf.cz/keep";
public static final String XTF_MANAGED_LABEL = "xtf.cz/managed";
private final AppsAPIGroupClient appsAPIGroupClient;
/**
* Autoconfigures the client with the default fabric8 client rules
*
* @param namespace set namespace to the Openshift client instance
* @return this Openshift client instance
*/
public static OpenShift get(String namespace) {
Config kubeconfig = Config.autoConfigure(null);
OpenShiftConfig openShiftConfig = new OpenShiftConfig(kubeconfig);
setupTimeouts(openShiftConfig);
if (StringUtils.isNotEmpty(namespace)) {
openShiftConfig.setNamespace(namespace);
}
return new OpenShift(openShiftConfig);
}
public static OpenShift get(Path kubeconfigPath, String namespace) {
try {
String kubeconfigContents = new String(Files.readAllBytes(kubeconfigPath), StandardCharsets.UTF_8);
Config kubeconfig = Config.fromKubeconfig(null, kubeconfigContents, kubeconfigPath.toAbsolutePath().toString());
OpenShiftConfig openShiftConfig = new OpenShiftConfig(kubeconfig);
setupTimeouts(openShiftConfig);
if (StringUtils.isNotEmpty(namespace)) {
openShiftConfig.setNamespace(namespace);
}
return new OpenShift(openShiftConfig);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static OpenShift get(String masterUrl, String namespace, String username, String password) {
OpenShiftConfig openShiftConfig = new OpenShiftConfigBuilder()
.withMasterUrl(masterUrl)
.withTrustCerts(true)
.withNamespace(namespace)
.withUsername(username)
.withPassword(password)
.build();
setupTimeouts(openShiftConfig);
return new OpenShift(openShiftConfig);
}
public static OpenShift get(String masterUrl, String namespace, String token) {
OpenShiftConfig openShiftConfig = new OpenShiftConfigBuilder()
.withMasterUrl(masterUrl)
.withTrustCerts(true)
.withNamespace(namespace)
.withOauthToken(token)
.build();
setupTimeouts(openShiftConfig);
return new OpenShift(openShiftConfig);
}
private static void setupTimeouts(OpenShiftConfig config) {
config.setBuildTimeout(10 * 60 * 1000);
config.setRequestTimeout(120_000);
config.setConnectionTimeout(120_000);
}
protected static synchronized ServiceLoader<CustomResourceDefinitionContextProvider> getCRDContextProviders() {
if (crdContextProviderLoader == null) {
crdContextProviderLoader = ServiceLoader.load(CustomResourceDefinitionContextProvider.class);
}
return crdContextProviderLoader;
}
private final OpenShiftWaiters waiters;
public OpenShift(OpenShiftConfig openShiftConfig) {
super(openShiftConfig);
appsAPIGroupClient = new AppsAPIGroupClient(httpClient, openShiftConfig);
this.waiters = new OpenShiftWaiters(this);
}
public void setupPullSecret(String secret) {
setupPullSecret("xtf-pull-secret", secret);
}
public void setupPullSecret(String name, String secret) {
Secret pullSecret = new SecretBuilder()
.withNewMetadata()
.withNewName(name)
.addToLabels(KEEP_LABEL, "true")
.endMetadata()
.withNewType("kubernetes.io/dockerconfigjson")
.withData(Collections.singletonMap(".dockerconfigjson", Base64.getEncoder().encodeToString(secret.getBytes())))
.build();
secrets().createOrReplace(pullSecret);
serviceAccounts().withName("default").edit()
.addToImagePullSecrets(new LocalObjectReferenceBuilder().withName(pullSecret.getMetadata().getName()).build())
.done();
serviceAccounts().withName("builder").edit()
.addToSecrets(new ObjectReferenceBuilder().withName(pullSecret.getMetadata().getName()).build()).done();
}
// General functions
public KubernetesList createResources(HasMetadata... resources) {
return createResources(Arrays.asList(resources));
}
public KubernetesList createResources(List<HasMetadata> resources) {
KubernetesList list = new KubernetesList();
list.setItems(resources);
return createResources(list);
}
public KubernetesList createResources(KubernetesList resources) {
return lists().create(resources);
}
public boolean deleteResources(KubernetesList resources) {
return lists().delete(resources);
}
public void loadResource(InputStream is) {
load(is).deletingExisting().createOrReplace();
}
// Projects
public ProjectRequest createProjectRequest() {
return createProjectRequest(
new ProjectRequestBuilder().withNewMetadata().withName(getNamespace()).endMetadata().build());
}
public ProjectRequest createProjectRequest(String name) {
return createProjectRequest(new ProjectRequestBuilder().withNewMetadata().withName(name).endMetadata().build());
}
public ProjectRequest createProjectRequest(ProjectRequest projectRequest) {
return projectrequests().create(projectRequest);
}
/**
* Calls recreateProject(namespace).
*
* @return project request
* @see OpenShift#recreateProject(String)
*/
public ProjectRequest recreateProject() {
return recreateProject(new ProjectRequestBuilder().withNewMetadata().withName(getNamespace()).endMetadata().build());
}
/**
* Creates or recreates project specified by name.
*
* @param name name of a project to be created
* @return ProjectRequest instance
*/
public ProjectRequest recreateProject(String name) {
return recreateProject(new ProjectRequestBuilder().withNewMetadata().withName(name).endMetadata().build());
}
/**
* Creates or recreates project specified by projectRequest instance.
*
* @param projectRequest project request instance
* @return ProjectRequest instance
*/
public ProjectRequest recreateProject(ProjectRequest projectRequest) {
boolean deleted = deleteProject(projectRequest.getMetadata().getName());
if (deleted) {
BooleanSupplier bs = () -> getProject(projectRequest.getMetadata().getName()) == null;
new SimpleWaiter(bs, TimeUnit.MILLISECONDS, WaitingConfig.timeout(),
"Waiting for old project deletion before creating new one").waitFor();
}
return createProjectRequest(projectRequest);
}
/**
* Tries to retrieve project with name 'name'. Swallows KubernetesClientException
* if project doesn't exist or isn't accessible for user.
*
* @param name name of requested project.
* @return Project instance if accessible otherwise null.
*/
public Project getProject(String name) {
try {
return projects().withName(name).get();
} catch (KubernetesClientException e) {
return null;
}
}
public Project getProject() {
try {
return projects().withName(getNamespace()).get();
} catch (KubernetesClientException e) {
return null;
}
}
public boolean deleteProject() {
return deleteProject(getNamespace());
}
public boolean deleteProject(String name) {
return getProject(name) != null ? projects().withName(name).delete() : false;
}
// ImageStreams
public ImageStream createImageStream(ImageStream imageStream) {
return imageStreams().create(imageStream);
}
public ImageStream getImageStream(String name) {
return imageStreams().withName(name).get();
}
public List<ImageStream> getImageStreams() {
return imageStreams().list().getItems();
}
// StatefulSets
public StatefulSet createStatefulSet(StatefulSet statefulSet) {
return appsAPIGroupClient.statefulSets().create(statefulSet);
}
public StatefulSet getStatefulSet(String name) {
return appsAPIGroupClient.statefulSets().withName(name).get();
}
public List<StatefulSet> getStatefulSets() {
return appsAPIGroupClient.statefulSets().list().getItems();
}
public boolean deleteImageStream(ImageStream imageStream) {
return imageStreams().delete(imageStream);
}
// ImageStreamsTags
public ImageStreamTag createImageStreamTag(ImageStreamTag imageStreamTag) {
return imageStreamTags().create(imageStreamTag);
}
public ImageStreamTag getImageStreamTag(String imageStreamName, String tag) {
return imageStreamTags().withName(imageStreamName + ":" + tag).get();
}
public List<ImageStreamTag> getImageStreamTags() {
return imageStreamTags().list().getItems();
}
public boolean deleteImageStreamTag(ImageStreamTag imageStreamTag) {
return imageStreamTags().delete(imageStreamTag);
}
// Pods
public Pod createPod(Pod pod) {
return pods().create(pod);
}
public Pod getPod(String name) {
return pods().withName(name).get();
}
public String getPodLog(String deploymentConfigName) {
return getPodLog(this.getAnyPod(deploymentConfigName));
}
public String getPodLog(Pod pod) {
return getPodLog(pod, getAnyContainer(pod));
}
public String getPodLog(Pod pod, String containerName) {
return getPodLog(pod, getContainer(pod, containerName));
}
public String getPodLog(Pod pod, Container container) {
if (Objects.nonNull(container)) {
return pods().withName(pod.getMetadata().getName()).inContainer(container.getName()).getLog();
} else {
return pods().withName(pod.getMetadata().getName()).getLog();
}
}
/**
* Return logs of all containers from the pod
*
* @param pod Pod to retrieve from
* @return Map of container name / logs
*/
public Map<String, String> getAllContainerLogs(Pod pod) {
return retrieveFromPodContainers(pod, container -> this.getPodLog(pod, container));
}
public Reader getPodLogReader(Pod pod) {
return getPodLogReader(pod, getAnyContainer(pod));
}
public Reader getPodLogReader(Pod pod, String containerName) {
return getPodLogReader(pod, getContainer(pod, containerName));
}
public Reader getPodLogReader(Pod pod, Container container) {
if (Objects.nonNull(container)) {
return pods().withName(pod.getMetadata().getName()).inContainer(container.getName()).getLogReader();
} else {
return pods().withName(pod.getMetadata().getName()).getLogReader();
}
}
/**
* Return readers on logs of all containers from the pod
*
* @param pod Pod to retrieve from
* @return Map of container name / reader
*/
public Map<String, Reader> getAllContainerLogReaders(Pod pod) {
return retrieveFromPodContainers(pod, container -> this.getPodLogReader(pod, container));
}
public Observable<String> observePodLog(String dcName) {
return observePodLog(getAnyPod(dcName));
}
public Observable<String> observePodLog(Pod pod) {
return observePodLog(pod, getAnyContainer(pod));
}
public Observable<String> observePodLog(Pod pod, String containerName) {
return observePodLog(pod, getContainer(pod, containerName));
}
public Observable<String> observePodLog(Pod pod, Container container) {
LogWatch watcher;
if (Objects.nonNull(container)) {
watcher = pods().withName(pod.getMetadata().getName()).inContainer(container.getName()).watchLog();
} else {
watcher = pods().withName(pod.getMetadata().getName()).watchLog();
}
return StringObservable.byLine(StringObservable.from(new InputStreamReader(watcher.getOutput())));
}
/**
* Return obervables on logs of all containers from the pod
*
* @param pod Pod to retrieve from
* @return Map of container name / logs obervable
*/
public Map<String, Observable<String>> observeAllContainerLogs(Pod pod) {
return retrieveFromPodContainers(pod, container -> this.observePodLog(pod, container));
}
public List<Pod> getPods() {
return pods().list().getItems();
}
public List<Pod> getPods(String deploymentConfigName) {
return getLabeledPods("deploymentconfig", deploymentConfigName);
}
public List<Pod> getPods(String deploymentConfigName, int version) {
return getLabeledPods("deployment", deploymentConfigName + "-" + version);
}
public List<Pod> getLabeledPods(String key, String value) {
return getLabeledPods(Collections.singletonMap(key, value));
}
public List<Pod> getLabeledPods(Map<String, String> labels) {
return pods().withLabels(labels).list().getItems();
}
public Pod getAnyPod(String deploymentConfigName) {
return getAnyPod("deploymentconfig", deploymentConfigName);
}
public Pod getAnyPod(String key, String value) {
return getAnyPod(Collections.singletonMap(key, value));
}
public Pod getAnyPod(Map<String, String> labels) {
List<Pod> pods = getLabeledPods(labels);
return pods.get(new Random().nextInt(pods.size()));
}
public boolean deletePod(Pod pod) {
return deletePod(pod, 0L);
}
public boolean deletePod(Pod pod, long gracePeriod) {
return pods().withName(pod.getMetadata().getName()).withGracePeriod(gracePeriod).delete();
}
/**
* Deletes pods with specified label.
*
* @param key key of the label
* @param value value of the label
* @return True if any pod has been deleted
*/
public boolean deletePods(String key, String value) {
return pods().withLabel(key, value).delete();
}
public boolean deletePods(Map<String, String> labels) {
return pods().withLabels(labels).delete();
}
/**
* Retrieve pod containers
*
* @param pod pod to retrieve in
* @return List of containers of empty list if none ...
*/
public List<Container> getAllContainers(Pod pod) {
return Optional.ofNullable(pod.getSpec()).map(PodSpec::getContainers).orElse(new ArrayList<>());
}
/**
* Retrieve any container from the given pod
*
* @param pod Pod to retrieve from
* @return One random container from the pod
*/
public Container getAnyContainer(Pod pod) {
List<Container> containers = getAllContainers(pod);
return containers.get(new Random().nextInt(containers.size()));
}
public Container getContainer(Pod pod, String containerName) {
return getAllContainers(pod).stream()
.filter(c -> c.getName().equals(containerName))
.findFirst()
.orElseThrow(() -> new RuntimeException(
"Cannot find container with name " + containerName + " in pod " + pod.getMetadata().getName()));
}
private <R> Map<String, R> retrieveFromPodContainers(Pod pod, Function<Container, R> containerRetriever) {
return getAllContainers(pod).stream().collect(Collectors.toMap(Container::getName, containerRetriever));
}
// Secrets
public Secret createSecret(Secret secret) {
return secrets().create(secret);
}
public Secret getSecret(String name) {
return secrets().withName(name).get();
}
public List<Secret> getSecrets() {
return secrets().list().getItems();
}
/**
* Retrieves secrets that aren't considered default. Secrets that are left out contain type starting with 'kubernetes.io/'.
*
* @return List of secrets that aren't considered default.
*/
public List<Secret> getUserSecrets() {
return secrets().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems().stream()
.filter(s -> !s.getType().startsWith("kubernetes.io/"))
.collect(Collectors.toList());
}
public boolean deleteSecret(Secret secret) {
return secrets().delete(secret);
}
// Services
public Service createService(Service service) {
return services().create(service);
}
public Service getService(String name) {
return services().withName(name).get();
}
public List<Service> getServices() {
return services().list().getItems();
}
public boolean deleteService(Service service) {
return services().delete(service);
}
// Endpoints
public Endpoints createEndpoint(Endpoints endpoint) {
return endpoints().create(endpoint);
}
public Endpoints getEndpoint(String name) {
return endpoints().withName(name).get();
}
public List<Endpoints> getEndpoints() {
return endpoints().list().getItems();
}
public boolean deleteEndpoint(Endpoints endpoint) {
return endpoints().delete(endpoint);
}
// Routes
public Route createRoute(Route route) {
return routes().create(route);
}
public Route getRoute(String name) {
return routes().withName(name).get();
}
public List<Route> getRoutes() {
return routes().list().getItems();
}
public boolean deleteRoute(Route route) {
return routes().delete(route);
}
/**
* Generates hostname as is expected to be generated by OpenShift instance.
*
* @param routeName prefix for route hostname
* @return Hostname as is expected to be generated by OpenShift
*/
public String generateHostname(String routeName) {
if (routeSuffix == null) {
synchronized (OpenShift.class) {
if (routeSuffix == null) {
if (StringUtils.isNotBlank(routeDomain())) {
routeSuffix = routeDomain();
} else {
routeSuffix = retrieveRouteSuffix();
}
}
}
}
return routeName + "-" + getNamespace() + "." + routeSuffix;
}
private String retrieveRouteSuffix() {
Route route = new Route();
route.setMetadata(new ObjectMetaBuilder().withName("probing-route").build());
route.setSpec(new RouteSpecBuilder().withNewTo().withKind("Service").withName("imaginary-service").endTo().build());
route = createRoute(route);
deleteRoute(route);
return route.getSpec().getHost().replaceAll("^[^\\.]*\\.(.*)", "$1");
}
// ReplicationControllers - Only for internal usage with clean
private List<ReplicationController> getReplicationControllers() {
return replicationControllers().list().getItems();
}
private boolean deleteReplicationController(ReplicationController replicationController) {
return replicationControllers().withName(replicationController.getMetadata().getName()).cascading(false).delete();
}
// DeploymentConfigs
public DeploymentConfig createDeploymentConfig(DeploymentConfig deploymentConfig) {
return deploymentConfigs().create(deploymentConfig);
}
public DeploymentConfig getDeploymentConfig(String name) {
return deploymentConfigs().withName(name).get();
}
public List<DeploymentConfig> getDeploymentConfigs() {
return deploymentConfigs().list().getItems();
}
/**
* Returns first container environment variables.
*
* @param name name of deploymentConfig
* @return Map of environment variables
*/
public Map<String, String> getDeploymentConfigEnvVars(String name) {
Map<String, String> envVars = new HashMap<>();
getDeploymentConfig(name).getSpec().getTemplate().getSpec().getContainers().get(0).getEnv()
.forEach(envVar -> envVars.put(envVar.getName(), envVar.getValue()));
return envVars;
}
public DeploymentConfig updateDeploymentconfig(DeploymentConfig deploymentConfig) {
return deploymentConfigs().withName(deploymentConfig.getMetadata().getName()).replace(deploymentConfig);
}
/**
* Updates deployment config environment variables with envVars values.
*
* @param name name of deploymentConfig
* @param envVars environment variables
*
* @return deployment config
*/
public DeploymentConfig updateDeploymentConfigEnvVars(String name, Map<String, String> envVars) {
DeploymentConfig dc = getDeploymentConfig(name);
List<EnvVar> vars = envVars.entrySet().stream()
.map(x -> new EnvVarBuilder().withName(x.getKey()).withValue(x.getValue()).build())
.collect(Collectors.toList());
dc.getSpec().getTemplate().getSpec().getContainers().get(0).getEnv().removeIf(x -> envVars.containsKey(x.getName()));
dc.getSpec().getTemplate().getSpec().getContainers().get(0).getEnv().addAll(vars);
return updateDeploymentconfig(dc);
}
public boolean deleteDeploymentConfig(DeploymentConfig deploymentConfig) {
return deleteDeploymentConfig(deploymentConfig, false);
}
public boolean deleteDeploymentConfig(DeploymentConfig deploymentConfig, boolean cascading) {
return deploymentConfigs().withName(deploymentConfig.getMetadata().getName()).cascading(cascading).delete();
}
/**
* Scales deployment config to specified number of replicas.
*
* @param name name of deploymentConfig
* @param replicas number of target replicas
*/
public void scale(String name, int replicas) {
deploymentConfigs().withName(name).scale(replicas);
}
/**
* Redeploys deployment config to latest version.
*
* @param name name of deploymentConfig
*/
public void deployLatest(String name) {
deploymentConfigs().withName(name).deployLatest();
}
// Builds
public Build getBuild(String name) {
return inNamespace(getNamespace()).builds().withName(name).get();
}
public Build getLatestBuild(String buildConfigName) {
long lastVersion = buildConfigs().withName(buildConfigName).get().getStatus().getLastVersion();
return getBuild(buildConfigName + "-" + lastVersion);
}
public List<Build> getBuilds() {
return builds().list().getItems();
}
public String getBuildLog(Build build) {
return builds().withName(build.getMetadata().getName()).getLog();
}
public Reader getBuildLogReader(Build build) {
return builds().withName(build.getMetadata().getName()).getLogReader();
}
public boolean deleteBuild(Build build) {
return builds().delete(build);
}
public Build startBuild(String buildConfigName) {
BuildRequest request = new BuildRequestBuilder().withNewMetadata().withName(buildConfigName).endMetadata().build();
return buildConfigs().withName(buildConfigName).instantiate(request);
}
public Build startBinaryBuild(String buildConfigName, File file) {
return buildConfigs().withName(buildConfigName).instantiateBinary().fromFile(file);
}
// BuildConfigs
public BuildConfig createBuildConfig(BuildConfig buildConfig) {
return buildConfigs().create(buildConfig);
}
public BuildConfig getBuildConfig(String name) {
return buildConfigs().withName(name).get();
}
public List<BuildConfig> getBuildConfigs() {
return buildConfigs().list().getItems();
}
/**
* Returns environment variables of buildConfig specified under sourceStrategy.
*
* @param name name of buildConfig
* @return environment variables
*/
public Map<String, String> getBuildConfigEnvVars(String name) {
return getBuildConfig(name).getSpec().getStrategy().getSourceStrategy().getEnv().stream()
.collect(Collectors.toMap(EnvVar::getName, EnvVar::getValue));
}
public BuildConfig updateBuildConfig(BuildConfig buildConfig) {
return buildConfigs().withName(buildConfig.getMetadata().getName()).replace(buildConfig);
}
/**
* Updates build config with specified environment variables.
*
* @param name name of buildConfig
* @param envVars environment variables
*
* @return build config
*/
public BuildConfig updateBuildConfigEnvVars(String name, Map<String, String> envVars) {
BuildConfig bc = getBuildConfig(name);
List<EnvVar> vars = envVars.entrySet().stream()
.map(x -> new EnvVarBuilder().withName(x.getKey()).withValue(x.getValue()).build())
.collect(Collectors.toList());
bc.getSpec().getStrategy().getSourceStrategy().getEnv().removeIf(x -> envVars.containsKey(x.getName()));
bc.getSpec().getStrategy().getSourceStrategy().getEnv().addAll(vars);
return updateBuildConfig(bc);
}
public boolean deleteBuildConfig(BuildConfig buildConfig) {
return buildConfigs().delete(buildConfig);
}
// ServiceAccounts
public ServiceAccount createServiceAccount(ServiceAccount serviceAccount) {
return serviceAccounts().create(serviceAccount);
}
public ServiceAccount getServiceAccount(String name) {
return serviceAccounts().withName(name).get();
}
public List<ServiceAccount> getServiceAccounts() {
return serviceAccounts().list().getItems();
}
/**
* Retrieves service accounts that aren't considered default.
* Service accounts that are left out from list:
* <ul>
* <li>builder</li>
* <li>default</li>
* <li>deployer</li>
* </ul>
*
* @return List of service accounts that aren't considered default.
*/
public List<ServiceAccount> getUserServiceAccounts() {
return serviceAccounts().withLabelNotIn(KEEP_LABEL, "", "true").list().getItems().stream()
.filter(sa -> !sa.getMetadata().getName().matches("builder|default|deployer"))
.collect(Collectors.toList());
}
public boolean deleteServiceAccount(ServiceAccount serviceAccount) {
return serviceAccounts().delete(serviceAccount);
}
// RoleBindings
public RoleBinding createRoleBinding(RoleBinding roleBinding) {
return rbac().roleBindings().create(roleBinding);
}
public RoleBinding getRoleBinding(String name) {
return rbac().roleBindings().withName(name).get();
}
public List<RoleBinding> getRoleBindings() {
return rbac().roleBindings().list().getItems();
}
public Role getRole(String name) {
return rbac().roles().withName(name).get();
}
public List<Role> getRoles() {
return rbac().roles().list().getItems();
}
/**
* Retrieves role bindings that aren't considered default.
* Role bindings that are left out from list:
* <ul>
* <li>admin</li>
* <li>system:deployers</li>
* <li>system:image-builders</li>
* <li>system:image-pullers</li>
* </ul>
*
* @return List of role bindings that aren't considered default.
*/
public List<RoleBinding> getUserRoleBindings() {
return rbac().roleBindings().withLabelNotIn(KEEP_LABEL, "", "true")
.withLabelNotIn("olm.owner.kind", "ClusterServiceVersion").list().getItems().stream()
.filter(rb -> !rb.getMetadata().getName()
.matches("admin|system:deployers|system:image-builders|system:image-pullers"))
.collect(Collectors.toList());
}
public boolean deleteRoleBinding(RoleBinding roleBinding) {
return rbac().roleBindings().delete(roleBinding);
}
public RoleBinding addRoleToUser(String roleName, String username) {
return addRoleToUser(roleName, null, username);
}
public RoleBinding addRoleToUser(String roleName, String roleKind, String username) {
RoleBinding roleBinding = getOrCreateRoleBinding(roleName);
addSubjectToRoleBinding(roleBinding, "User", username, null);
return updateRoleBinding(roleBinding);
}
public RoleBinding addRoleToServiceAccount(String roleName, String serviceAccountName) {
return addRoleToServiceAccount(roleName, serviceAccountName, getNamespace());
}
public RoleBinding addRoleToServiceAccount(String roleName, String serviceAccountName, String namespace) {
return addRoleToServiceAccount(roleName, null, serviceAccountName, namespace);
}
public RoleBinding addRoleToServiceAccount(String roleName, String roleKind, String serviceAccountName, String namespace) {
RoleBinding roleBinding = getOrCreateRoleBinding(roleName, roleKind);
addSubjectToRoleBinding(roleBinding, "ServiceAccount", serviceAccountName, namespace);
return updateRoleBinding(roleBinding);
}
/**
* Most of the groups are `system:*` wide therefore use `kind: ClusterRole`
*
* @param roleName role name
* @param groupName group name
* @return role binging
* @deprecated use method {@link #addRoleToGroup(String, String, String)}
*
*/
@Deprecated
public RoleBinding addRoleToGroup(String roleName, String groupName) {
RoleBinding roleBinding = getOrCreateRoleBinding(roleName);
addSubjectToRoleBinding(roleBinding, "Group", groupName, null);
return updateRoleBinding(roleBinding);
}
public RoleBinding addRoleToGroup(String roleName, String roleKind, String groupName) {
RoleBinding roleBinding = getOrCreateRoleBinding(roleName, roleKind);
addSubjectToRoleBinding(roleBinding, "Group", groupName, null);
return updateRoleBinding(roleBinding);
}
private RoleBinding getOrCreateRoleBinding(String name) {
return getOrCreateRoleBinding(name, null);
}
private RoleBinding getOrCreateRoleBinding(String name, String kind) {
RoleBinding roleBinding = getRoleBinding(name);
if (roleBinding == null) {
// {admin, edit, view} are K8s ClusterRole that are considered user-facing
if (kind == null) {
kind = "Role";
if (Arrays.asList("admin", "edit", "view").contains(name)) {
kind = "ClusterRole";
}
}
roleBinding = new RoleBindingBuilder()
.withNewMetadata().withName(name).endMetadata()
.withNewRoleRef().withKind(kind).withName(name).endRoleRef()
.build();
createRoleBinding(roleBinding);
}
return roleBinding;
}
public RoleBinding updateRoleBinding(RoleBinding roleBinding) {
return rbac().roleBindings().withName(roleBinding.getMetadata().getName()).replace(roleBinding);
}
private void addSubjectToRoleBinding(RoleBinding roleBinding, String entityKind, String entityName) {
addSubjectToRoleBinding(roleBinding, entityKind, entityName, null);
}
private void addSubjectToRoleBinding(RoleBinding roleBinding, String entityKind, String entityName,
String entityNamespace) {
SubjectBuilder subjectBuilder = new SubjectBuilder().withKind(entityKind).withName(entityName);
if (entityNamespace != null) {
subjectBuilder.withNamespace(entityNamespace);
}
Subject subject = subjectBuilder.build();
if (roleBinding.getSubjects().stream()
.noneMatch(x -> x.getName().equals(subject.getName()) && x.getKind().equals(subject.getKind()))) {
roleBinding.getSubjects().add(subject);
}
}
public RoleBinding removeRoleFromServiceAccount(String roleName, String serviceAccountName) {
return removeRoleFromEntity(roleName, "ServiceAccount", serviceAccountName);
}
public RoleBinding removeRoleFromEntity(String roleName, String entityKind, String entityName) {
RoleBinding roleBinding = this.rbac().roleBindings().withName(roleName).get();
if (roleBinding != null) {
roleBinding.getSubjects().removeIf(s -> s.getName().equals(entityName) && s.getKind().equals(entityKind));
return updateRoleBinding(roleBinding);
}
return null;
}
// ResourceQuotas
public ResourceQuota createResourceQuota(ResourceQuota resourceQuota) {
return resourceQuotas().create(resourceQuota);
}
public ResourceQuota getResourceQuota(String name) {
return resourceQuotas().withName(name).get();
}
public boolean deleteResourceQuota(ResourceQuota resourceQuota) {
return resourceQuotas().delete(resourceQuota);
}
// Persistent volume claims
public PersistentVolumeClaim createPersistentVolumeClaim(PersistentVolumeClaim pvc) {
return persistentVolumeClaims().create(pvc);
}
public PersistentVolumeClaim getPersistentVolumeClaim(String name) {
return persistentVolumeClaims().withName(name).get();
}
public List<PersistentVolumeClaim> getPersistentVolumeClaims() {
return persistentVolumeClaims().list().getItems();
}
public boolean deletePersistentVolumeClaim(PersistentVolumeClaim pvc) {
return persistentVolumeClaims().delete(pvc);
}
// HorizontalPodAutoscalers
public HorizontalPodAutoscaler createHorizontalPodAutoscaler(HorizontalPodAutoscaler hpa) {
return autoscaling().v1().horizontalPodAutoscalers().create(hpa);
}
public HorizontalPodAutoscaler getHorizontalPodAutoscaler(String name) {
return autoscaling().v1().horizontalPodAutoscalers().withName(name).get();
}
public List<HorizontalPodAutoscaler> getHorizontalPodAutoscalers() {
return autoscaling().v1().horizontalPodAutoscalers().list().getItems();
}
public boolean deleteHorizontalPodAutoscaler(HorizontalPodAutoscaler hpa) {
return autoscaling().v1().horizontalPodAutoscalers().delete(hpa);
}
// ConfigMaps
public ConfigMap createConfigMap(ConfigMap configMap) {
return configMaps().create(configMap);
}
public ConfigMap getConfigMap(String name) {
return configMaps().withName(name).get();
}
public List<ConfigMap> getConfigMaps() {
return configMaps().list().getItems();
}
public List<ConfigMap> getUserConfigMaps() {
return configMaps().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems().stream()
.filter(cm -> !cm.getMetadata().getName().equals("kube-root-ca.crt"))
.collect(Collectors.toList());
}
public boolean deleteConfigMap(ConfigMap configMap) {
return configMaps().delete(configMap);
}
public Template createTemplate(Template template) {
return templates().create(template);
}
public Template getTemplate(String name) {
return templates().withName(name).get();
}
public List<Template> getTemplates() {
return templates().list().getItems();
}
public boolean deleteTemplate(String name) {
return templates().withName(name).delete();
}
public boolean deleteTemplate(Template template) {
return templates().delete(template);
}
public Template loadAndCreateTemplate(InputStream is) {
Template t = templates().load(is).get();
deleteTemplate(t);
return createTemplate(t);
}
public KubernetesList recreateAndProcessTemplate(Template template, Map<String, String> parameters) {
deleteTemplate(template.getMetadata().getName());
createTemplate(template);
return processTemplate(template.getMetadata().getName(), parameters);
}
public KubernetesList recreateAndProcessAndDeployTemplate(Template template, Map<String, String> parameters) {
return createResources(recreateAndProcessTemplate(template, parameters));
}
public KubernetesList processTemplate(String name, Map<String, String> parameters) {
ParameterValue[] values = processParameters(parameters);
return templates().withName(name).process(values);
}
public KubernetesList processAndDeployTemplate(String name, Map<String, String> parameters) {
return createResources(processTemplate(name, parameters));
}
private ParameterValue[] processParameters(Map<String, String> parameters) {
return parameters.entrySet().stream().map(entry -> new ParameterValue(entry.getKey(), entry.getValue()))
.collect(Collectors.toList()).toArray(new ParameterValue[parameters.size()]);
}
// Nodes
public Node getNode(String name) {
return nodes().withName(name).get();
}
public List<Node> getNodes() {
return nodes().list().getItems();
}
public List<Node> getNodes(Map<String, String> labels) {
return nodes().withLabels(labels).list().getItems();
}
// Events
public EventList getEventList() {
return new EventList(events().list().getItems());
}
/**
* Use {@link OpenShift#getEventList()} instead
*
* @return list of events
*/
@Deprecated
public List<Event> getEvents() {
return events().list().getItems();
}
// Port Forward
public LocalPortForward portForward(String deploymentConfigName, int remotePort, int localPort) {
return portForward(getAnyPod(deploymentConfigName), remotePort, localPort);
}
public LocalPortForward portForward(Pod pod, int remotePort, int localPort) {
return pods().withName(pod.getMetadata().getName()).portForward(remotePort, localPort);
}
// PodShell
public PodShell podShell(String dcName) {
return podShell(getAnyPod(dcName));
}
public PodShell podShell(Pod pod) {
return new PodShell(this, pod);
}
public PodShell podShell(Pod pod, String containerName) {
return new PodShell(this, pod, containerName);
}
// Clean up function
/**
* <pre>
* Deletes all* resources in namespace. Doesn't wait till all are deleted.
*
* * Only user created configmaps, secrets, service accounts and role bindings are deleted. Default will remain.
*
* </pre>
*
* @return waiter (for cleaning all resources)
* @see #getUserConfigMaps()
* @see #getUserSecrets()
* @see #getUserServiceAccounts()
* @see #getUserRoleBindings()
*/
public Waiter clean() {
for (CustomResourceDefinitionContextProvider crdContextProvider : OpenShift.getCRDContextProviders()) {
try {
customResource(crdContextProvider.getContext()).delete(getNamespace());
log.debug("DELETE :: " + crdContextProvider.getContext().getName() + " instances");
} catch (KubernetesClientException kce) {
log.debug(crdContextProvider.getContext().getName() + " might not be installed on the cluster.", kce);
}
}
templates().withLabelNotIn(KEEP_LABEL, "", "true").delete();
apps().deployments().withLabelNotIn(KEEP_LABEL, "", "true").delete();
apps().replicaSets().withLabelNotIn(KEEP_LABEL, "", "true").delete();
apps().statefulSets().withLabelNotIn(KEEP_LABEL, "", "true").delete();
batch().jobs().withLabelNotIn(KEEP_LABEL, "", "true").delete();
deploymentConfigs().withLabelNotIn(KEEP_LABEL, "", "true").delete();
replicationControllers().withLabelNotIn(KEEP_LABEL, "", "true").delete();
buildConfigs().withLabelNotIn(KEEP_LABEL, "", "true").delete();
imageStreams().withLabelNotIn(KEEP_LABEL, "", "true").delete();
endpoints().withLabelNotIn(KEEP_LABEL, "", "true").delete();
services().withLabelNotIn(KEEP_LABEL, "", "true").delete();
builds().withLabelNotIn(KEEP_LABEL, "", "true").delete();
routes().withLabelNotIn(KEEP_LABEL, "", "true").delete();
pods().withLabelNotIn(KEEP_LABEL, "", "true").withGracePeriod(0).delete();
persistentVolumeClaims().withLabelNotIn(KEEP_LABEL, "", "true").delete();
autoscaling().v1().horizontalPodAutoscalers().withLabelNotIn(KEEP_LABEL, "", "true").delete();
getUserConfigMaps().forEach(this::deleteConfigMap);
getUserSecrets().forEach(this::deleteSecret);
getUserServiceAccounts().forEach(this::deleteServiceAccount);
getUserRoleBindings().forEach(this::deleteRoleBinding);
rbac().roles().withLabelNotIn(KEEP_LABEL, "", "true").withLabelNotIn("olm.owner.kind", "ClusterServiceVersion")
.delete();
for (HasMetadata hasMetadata : listRemovableResources()) {
log.warn("DELETE LEFTOVER :: " + hasMetadata.getKind() + "/" + hasMetadata.getMetadata().getName());
resource(hasMetadata).withGracePeriod(0).cascading(true).delete();
}
return waiters.isProjectClean();
}
List<HasMetadata> listRemovableResources() {
// keep the order for deletion to prevent K8s creating resources again
List<HasMetadata> removables = new ArrayList<>();
removables.addAll(templates().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(apps().deployments().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(apps().replicaSets().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(batch().jobs().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(deploymentConfigs().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(apps().statefulSets().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(replicationControllers().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(buildConfigs().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(imageStreams().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(endpoints().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(services().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(builds().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(routes().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(pods().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(persistentVolumeClaims().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list().getItems());
removables.addAll(autoscaling().v1().horizontalPodAutoscalers().withLabelNotIn(OpenShift.KEEP_LABEL, "", "true").list()
.getItems());
removables.addAll(getUserConfigMaps());
removables.addAll(getUserSecrets());
removables.addAll(getUserServiceAccounts());
removables.addAll(getUserRoleBindings());
removables.addAll(rbac().roles().withLabelNotIn(KEEP_LABEL, "", "true")
.withLabelNotIn("olm.owner.kind", "ClusterServiceVersion").list().getItems());
return removables;
}
// Logs storing
public Path storePodLog(Pod pod, Path dirPath, String fileName) throws IOException {
String log = getPodLog(pod);
return storeLog(log, dirPath, fileName);
}
public Path storeBuildLog(Build build, Path dirPath, String fileName) throws IOException {
String log = getBuildLog(build);
return storeLog(log, dirPath, fileName);
}
private Path storeLog(String log, Path dirPath, String fileName) throws IOException {
Path filePath = dirPath.resolve(fileName);
Files.createDirectories(dirPath);
Files.createFile(filePath);
Files.write(filePath, log.getBytes());
return filePath;
}
// Waiting
/**
* Use {@link OpenShiftWaiters#get(OpenShift, cz.xtf.core.waiting.failfast.FailFastCheck)} instead.
*
* @return standard openshift waiters (with default fail fast checks)
*/
@Deprecated
public OpenShiftWaiters waiters() {
return waiters;
}
}
|
package waffle.util;
import java.awt.Desktop;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.sun.jna.Platform;
import com.sun.jna.platform.WindowUtils;
import com.sun.jna.platform.win32.LMJoin;
import com.sun.jna.platform.win32.Netapi32Util;
import com.sun.jna.platform.win32.Win32Exception;
import waffle.windows.auth.IWindowsAccount;
import waffle.windows.auth.IWindowsAuthProvider;
import waffle.windows.auth.IWindowsComputer;
import waffle.windows.auth.IWindowsDomain;
import waffle.windows.auth.impl.WindowsAccountImpl;
import waffle.windows.auth.impl.WindowsAuthProviderImpl;
/**
* A Utility class to read system info to help troubleshoot WAFFLE system configuration.
*
* This utility class collects system information and returns it as an XML document.
*
* From the command line, you can write the info to stdout using:
* <code>
* java -cp "jna.jar;waffle-core.jar;waffle-api.jar;platform.jar;guava-13.0.jar" waffle.util.WaffleInfo
* </code>
*
* To show this information in a browser, run:
* <code>
* java -cp "..." waffle.util.WaffleInfo -show
* </code>
*
* To lookup account names and return any listed info, run:
* <code>
* java -cp "..." waffle.util.WaffleInfo -lookup AccountName
* </code>
*
*/
public class WaffleInfo {
/**
* Get a Document with basic system information
*
* This uses the builtin javax.xml package even though the API is quite verbose
* @throws ParserConfigurationException
*/
public Document getWaffleInfo() throws ParserConfigurationException {
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
//create the root element and add it to the document
Element root = doc.createElement("waffle");
// Add Version Information as attributes
String version = WaffleInfo.class.getPackage().getImplementationVersion();
if (version!=null) {
root.setAttribute("version", version);
}
version = Platform.class.getPackage().getImplementationVersion();
if (version!=null) {
root.setAttribute("jna", version);
}
version = WindowUtils.class.getPackage().getImplementationVersion();
if (version!=null) {
root.setAttribute("jna-platform", version);
}
doc.appendChild(root);
root.appendChild(getAuthProviderInfo(doc));
return doc;
}
protected Element getAuthProviderInfo(Document doc) {
IWindowsAuthProvider auth = new WindowsAuthProviderImpl();
Element node = doc.createElement("auth");
node.setAttribute("class", auth.getClass().getName() );
Element wrap = node;
// Current User
try {
Element child = wrap = doc.createElement("currentUser");
node.appendChild(child);
String currentUsername = WindowsAccountImpl.getCurrentUsername();
addAccountInfo(doc,child,new WindowsAccountImpl(currentUsername));
}
catch(Win32Exception ex) {
wrap.appendChild(getException(doc, ex));
}
// Computer
try {
Element child = wrap = doc.createElement("computer");
node.appendChild(child);
IWindowsComputer c = auth.getCurrentComputer();
Element value = doc.createElement("computerName");
value.setTextContent(c.getComputerName());
child.appendChild(value);
value = doc.createElement("memberOf");
value.setTextContent(c.getMemberOf());
child.appendChild(value);
value = doc.createElement("joinStatus");
value.setTextContent(c.getJoinStatus());
child.appendChild(value);
value = doc.createElement("groups");
for (String s : c.getGroups()) {
Element g = doc.createElement("group");
g.setTextContent(s);
value.appendChild(g);
}
child.appendChild(value);
}
catch(Win32Exception ex) {
wrap.appendChild(getException(doc, ex));
}
// Only Show Domains if we are in a Domain
if (Netapi32Util.getJoinStatus() == LMJoin.NETSETUP_JOIN_STATUS.NetSetupDomainName ) {
try {
Element child = wrap = doc.createElement("domains");
node.appendChild(child);
for (IWindowsDomain domain : auth.getDomains()) {
Element d = doc.createElement("domain");
node.appendChild(d);
Element value = doc.createElement("FQN");
value.setTextContent(domain.getFqn());
child.appendChild(value);
value = doc.createElement("TrustTypeString");
value.setTextContent(domain.getTrustTypeString());
child.appendChild(value);
value = doc.createElement("TrustDirectionString");
value.setTextContent(domain.getTrustDirectionString());
child.appendChild(value);
}
}
catch(Win32Exception ex) {
wrap.appendChild(getException(doc, ex));
}
}
return node;
}
protected void addAccountInfo(Document doc, Element node, IWindowsAccount account) {
Element value = doc.createElement("Name");
value.setTextContent(account.getName());
node.appendChild(value);
value = doc.createElement("FQN");
value.setTextContent(account.getFqn());
node.appendChild(value);
value = doc.createElement("Domain");
value.setTextContent(account.getDomain());
node.appendChild(value);
value = doc.createElement("SID");
value.setTextContent(account.getSidString());
node.appendChild(value);
}
protected Element getLookupInfo(Document doc, String lookup) {
IWindowsAuthProvider auth = new WindowsAuthProviderImpl();
Element node = doc.createElement("lookup");
node.setAttribute("name", lookup );
try {
addAccountInfo(doc,node,auth.lookupAccount(lookup));
}
catch(Win32Exception ex) {
node.appendChild(getException(doc, ex));
}
return node;
}
public static Element getException(Document doc, Exception t) {
Element node = doc.createElement("exception");
node.setAttribute("class", t.getClass().getName() );
Element value = doc.createElement("message");
if (t.getMessage()!=null) {
value.setTextContent(t.getMessage());
node.appendChild(value);
}
value = doc.createElement("trace");
Writer result = new StringWriter();
PrintWriter printWriter = new PrintWriter(result);
t.printStackTrace(printWriter);
value.setTextContent(result.toString());
node.appendChild(value);
return node;
}
public static String toPrettyXML(Document doc) throws TransformerException {
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
return sw.toString();
}
/**
* Print system information
*/
public static void main(String[] args) {
boolean show = false;
List<String> lookup = new ArrayList<String>();
if (args!=null) {
for (int i=0; i<args.length; i++) {
String arg = args[i];
if ("-show".equals(arg)) {
show = true;
}
else if (arg.equals("-lookup")) {
lookup.add( args[++i] );
}
else {
System.err.println("Unknown Argument: "+arg);
System.exit(1);
}
}
}
WaffleInfo helper = new WaffleInfo();
try {
Document info = helper.getWaffleInfo();
for (String name : lookup) {
info.getDocumentElement().appendChild(helper.getLookupInfo(info, name));
}
String xml = toPrettyXML(info);
if (show) {
File f = File.createTempFile("waffle-info-", ".xml");
Files.write(xml, f, Charsets.UTF_8);
Desktop.getDesktop().open(f);
}
else {
System.out.println(xml);
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
|
package hudson.cli;
import hudson.AbortException;
import hudson.Extension;
import hudson.FilePath;
import hudson.PluginManager;
import hudson.util.VersionNumber;
import jenkins.model.Jenkins;
import hudson.model.UpdateSite;
import hudson.model.UpdateSite.Data;
import hudson.util.EditDistance;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import java.io.File;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import org.apache.commons.io.FileUtils;
/**
* Installs a plugin either from a file, an URL, or from update center.
*
* @author Kohsuke Kawaguchi
* @since 1.331
*/
@Extension
public class InstallPluginCommand extends CLICommand {
public String getShortDescription() {
return Messages.InstallPluginCommand_ShortDescription();
}
@Argument(metaVar="SOURCE",required=true,usage="If this points to a local file (‘-remoting’ mode only), that file will be installed. " +
"If this is an URL, Jenkins downloads the URL and installs that as a plugin. " +
"If it is the string ‘=’, the file will be read from standard input of the command, and ‘-name’ must be specified. " +
"Otherwise the name is assumed to be the short name of the plugin in the existing update center (like ‘findbugs’), " +
"and the plugin will be installed from the update center. If the short name includes a minimum version number " +
"(like ‘findbugs:1.4’), and there are multiple update centers publishing different versions, the update centers " +
"will be searched in order for the first one publishing a version that is at least the specified version.")
public List<String> sources = new ArrayList<String>();
@Option(name="-name",usage="If specified, the plugin will be installed as this short name (whereas normally the name is inferred from the source name automatically).")
public String name; // TODO better to parse out Short-Name from the manifest and deprecate this option
@Option(name="-restart",usage="Restart Jenkins upon successful installation.")
public boolean restart;
@Option(name="-deploy",usage="Deploy plugins right away without postponing them until the reboot.")
public boolean dynamicLoad;
protected int run() throws Exception {
Jenkins h = Jenkins.getActiveInstance();
h.checkPermission(PluginManager.UPLOAD_PLUGINS);
PluginManager pm = h.getPluginManager();
if (sources.size() > 1 && name != null) {
throw new IllegalArgumentException("-name is incompatible with multiple sources");
}
for (String source : sources) {
if (source.equals("=")) {
if (name == null) {
throw new IllegalArgumentException("-name required when using -source -");
}
stdout.println(Messages.InstallPluginCommand_InstallingPluginFromStdin());
File f = getTargetFile(name);
FileUtils.copyInputStreamToFile(stdin, f);
if (dynamicLoad) {
pm.dynamicLoad(f);
}
continue;
}
// is this a file?
if (channel!=null) {
FilePath f = new FilePath(channel, source);
if (f.exists()) {
stdout.println(Messages.InstallPluginCommand_InstallingPluginFromLocalFile(f));
String n = name != null ? name : f.getBaseName();
f.copyTo(getTargetFilePath(n));
if (dynamicLoad)
pm.dynamicLoad(getTargetFile(n));
continue;
}
}
// is this an URL?
try {
URL u = new URL(source);
stdout.println(Messages.InstallPluginCommand_InstallingPluginFromUrl(u));
String n;
if (name != null) {
n = name;
} else {
n = u.getPath();
n = n.substring(n.lastIndexOf('/') + 1);
n = n.substring(n.lastIndexOf('\\') + 1);
int idx = n.lastIndexOf('.');
if (idx > 0) {
n = n.substring(0, idx);
}
}
getTargetFilePath(n).copyFrom(u);
if (dynamicLoad)
pm.dynamicLoad(getTargetFile(n));
continue;
} catch (MalformedURLException e) {
// not an URL
}
// is this a plugin the update center?
int index = source.lastIndexOf(':');
UpdateSite.Plugin p;
if (index == -1) {
p = h.getUpdateCenter().getPlugin(source);
} else {
// try to find matching min version number
VersionNumber version = new VersionNumber(source.substring(index + 1));
p = h.getUpdateCenter().getPlugin(source.substring(0,index), version);
if (p == null) {
p = h.getUpdateCenter().getPlugin(source);
}
}
if (p!=null) {
stdout.println(Messages.InstallPluginCommand_InstallingFromUpdateCenter(source));
Throwable e = p.deploy(dynamicLoad).get().getError();
if (e!=null) {
AbortException myException = new AbortException("Failed to install plugin " + source);
myException.initCause(e);
throw myException;
}
continue;
}
stdout.println(Messages.InstallPluginCommand_NotAValidSourceName(source));
if (!source.contains(".") && !source.contains(":") && !source.contains("/") && !source.contains("\\")) {
// looks like a short plugin name. Why did we fail to find it in the update center?
if (h.getUpdateCenter().getSites().isEmpty()) {
stdout.println(Messages.InstallPluginCommand_NoUpdateCenterDefined());
} else {
Set<String> candidates = new HashSet<>();
for (UpdateSite s : h.getUpdateCenter().getSites()) {
Data dt = s.getData();
if (dt==null)
stdout.println(Messages.InstallPluginCommand_NoUpdateDataRetrieved(s.getUrl()));
else
candidates.addAll(dt.plugins.keySet());
}
stdout.println(Messages.InstallPluginCommand_DidYouMean(source,EditDistance.findNearest(source,candidates)));
}
}
throw new AbortException("Error occurred, see previous output.");
}
if (restart)
h.safeRestart();
return 0; // all success
}
private static FilePath getTargetFilePath(String name) {
return new FilePath(getTargetFile(name));
}
private static File getTargetFile(String name) {
return new File(Jenkins.getActiveInstance().getPluginManager().rootDir,name+".jpi");
}
}
|
package hudson.util;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.AxisState;
import org.jfree.chart.axis.CategoryTick;
import org.jfree.chart.axis.CategoryLabelPosition;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.entity.CategoryLabelEntity;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RectangleAnchor;
import org.jfree.text.TextBlock;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Point2D;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.util.List;
import java.util.Iterator;
/**
* {@link CategoryAxis} shifted to left to eliminate redundant space
* between area and the Y-axis.
*/
public final class ShiftedCategoryAxis extends CategoryAxis {
public ShiftedCategoryAxis(String label) {
super(label);
}
protected double calculateCategorySize(int categoryCount, Rectangle2D area, RectangleEdge edge) {
// we cut the left-half of the first item and the right-half of the last item,
// so we have more space
return super.calculateCategorySize(categoryCount-1, area, edge);
}
public double getCategoryEnd(int category, int categoryCount, Rectangle2D area, RectangleEdge edge) {
return super.getCategoryStart(category, categoryCount, area, edge)
+ calculateCategorySize(categoryCount, area, edge) / 2;
}
public double getCategoryMiddle(int category, int categoryCount, Rectangle2D area, RectangleEdge edge) {
return super.getCategoryStart(category, categoryCount, area, edge);
}
public double getCategoryStart(int category, int categoryCount, Rectangle2D area, RectangleEdge edge) {
return super.getCategoryStart(category, categoryCount, area, edge)
- calculateCategorySize(categoryCount, area, edge) / 2;
}
@Override
protected AxisState drawCategoryLabels(Graphics2D g2,
Rectangle2D plotArea,
Rectangle2D dataArea,
RectangleEdge edge,
AxisState state,
PlotRenderingInfo plotState) {
if (state == null) {
throw new IllegalArgumentException("Null 'state' argument.");
}
if (isTickLabelsVisible()) {
List ticks = refreshTicks(g2, state, plotArea, edge);
state.setTicks(ticks);
// remember the last drawn label so that we can avoid drawing overlapping labels.
Rectangle2D r = null;
int categoryIndex = 0;
Iterator iterator = ticks.iterator();
while (iterator.hasNext()) {
CategoryTick tick = (CategoryTick) iterator.next();
g2.setFont(getTickLabelFont(tick.getCategory()));
g2.setPaint(getTickLabelPaint(tick.getCategory()));
CategoryLabelPosition position
= this.getCategoryLabelPositions().getLabelPosition(edge);
double x0 = 0.0;
double x1 = 0.0;
double y0 = 0.0;
double y1 = 0.0;
if (edge == RectangleEdge.TOP) {
x0 = getCategoryStart(categoryIndex, ticks.size(),
dataArea, edge);
x1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea,
edge);
y1 = state.getCursor() - this.getCategoryLabelPositionOffset();
y0 = y1 - state.getMax();
}
else if (edge == RectangleEdge.BOTTOM) {
x0 = getCategoryStart(categoryIndex, ticks.size(),
dataArea, edge);
x1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea,
edge);
y0 = state.getCursor() + this.getCategoryLabelPositionOffset();
y1 = y0 + state.getMax();
}
else if (edge == RectangleEdge.LEFT) {
y0 = getCategoryStart(categoryIndex, ticks.size(),
dataArea, edge);
y1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea,
edge);
x1 = state.getCursor() - this.getCategoryLabelPositionOffset();
x0 = x1 - state.getMax();
}
else if (edge == RectangleEdge.RIGHT) {
y0 = getCategoryStart(categoryIndex, ticks.size(),
dataArea, edge);
y1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea,
edge);
x0 = state.getCursor() + this.getCategoryLabelPositionOffset();
x1 = x0 - state.getMax();
}
Rectangle2D area = new Rectangle2D.Double(x0, y0, (x1 - x0),
(y1 - y0));
if(r==null || !r.intersects(area)) {
Point2D anchorPoint = RectangleAnchor.coordinates(area,
position.getCategoryAnchor());
TextBlock block = tick.getLabel();
block.draw(g2, (float) anchorPoint.getX(),
(float) anchorPoint.getY(), position.getLabelAnchor(),
(float) anchorPoint.getX(), (float) anchorPoint.getY(),
position.getAngle());
Shape bounds = block.calculateBounds(g2,
(float) anchorPoint.getX(), (float) anchorPoint.getY(),
position.getLabelAnchor(), (float) anchorPoint.getX(),
(float) anchorPoint.getY(), position.getAngle());
if (plotState != null && plotState.getOwner() != null) {
EntityCollection entities
= plotState.getOwner().getEntityCollection();
if (entities != null) {
String tooltip = getCategoryLabelToolTip(
tick.getCategory());
entities.add(new CategoryLabelEntity(tick.getCategory(),
bounds, tooltip, null));
}
}
r = bounds.getBounds2D();
}
categoryIndex++;
}
if (edge.equals(RectangleEdge.TOP)) {
double h = state.getMax();
state.cursorUp(h);
}
else if (edge.equals(RectangleEdge.BOTTOM)) {
double h = state.getMax();
state.cursorDown(h);
}
else if (edge == RectangleEdge.LEFT) {
double w = state.getMax();
state.cursorLeft(w);
}
else if (edge == RectangleEdge.RIGHT) {
double w = state.getMax();
state.cursorRight(w);
}
}
return state;
}
}
|
package io.grpc.internal;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static io.grpc.internal.GrpcUtil.ACCEPT_ENCODING_JOINER;
import static io.grpc.internal.GrpcUtil.MESSAGE_ACCEPT_ENCODING_KEY;
import static io.grpc.internal.GrpcUtil.MESSAGE_ENCODING_KEY;
import static io.grpc.internal.GrpcUtil.TIMEOUT_KEY;
import static io.grpc.internal.GrpcUtil.USER_AGENT_KEY;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import io.grpc.CallOptions;
import io.grpc.ClientCall;
import io.grpc.Codec;
import io.grpc.Compressor;
import io.grpc.CompressorRegistry;
import io.grpc.Context;
import io.grpc.Decompressor;
import io.grpc.DecompressorRegistry;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.MethodDescriptor.MethodType;
import io.grpc.Status;
import java.io.InputStream;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* Implementation of {@link ClientCall}.
*/
final class ClientCallImpl<ReqT, RespT> extends ClientCall<ReqT, RespT>
implements Context.CancellationListener {
private final MethodDescriptor<ReqT, RespT> method;
private final Executor callExecutor;
private final Context context;
private final boolean unaryRequest;
private final CallOptions callOptions;
private ClientStream stream;
private volatile ScheduledFuture<?> deadlineCancellationFuture;
private volatile boolean deadlineCancellationFutureShouldBeCancelled;
private boolean cancelCalled;
private boolean halfCloseCalled;
private final ClientTransportProvider clientTransportProvider;
private String userAgent;
private ScheduledExecutorService deadlineCancellationExecutor;
private Compressor compressor;
private DecompressorRegistry decompressorRegistry = DecompressorRegistry.getDefaultInstance();
private CompressorRegistry compressorRegistry = CompressorRegistry.getDefaultInstance();
ClientCallImpl(MethodDescriptor<ReqT, RespT> method, Executor executor,
CallOptions callOptions, ClientTransportProvider clientTransportProvider,
ScheduledExecutorService deadlineCancellationExecutor) {
this.method = method;
// If we know that the executor is a direct executor, we don't need to wrap it with a
// SerializingExecutor. This is purely for performance reasons.
this.callExecutor = executor == directExecutor()
? new SerializeReentrantCallsDirectExecutor()
: new SerializingExecutor(executor);
// Propagate the context from the thread which initiated the call to all callbacks.
this.context = Context.current();
this.unaryRequest = method.getType() == MethodType.UNARY
|| method.getType() == MethodType.SERVER_STREAMING;
this.callOptions = callOptions;
this.clientTransportProvider = clientTransportProvider;
this.deadlineCancellationExecutor = deadlineCancellationExecutor;
}
@Override
public void cancelled(Context context) {
stream.cancel(Status.CANCELLED.withCause(context.cancellationCause()));
}
/**
* Provider of {@link ClientTransport}s.
*/
interface ClientTransportProvider {
/**
* Returns a transport for a new call.
*/
ClientTransport get(CallOptions callOptions);
}
ClientCallImpl<ReqT, RespT> setUserAgent(String userAgent) {
this.userAgent = userAgent;
return this;
}
ClientCallImpl<ReqT, RespT> setDecompressorRegistry(DecompressorRegistry decompressorRegistry) {
this.decompressorRegistry = decompressorRegistry;
return this;
}
ClientCallImpl<ReqT, RespT> setCompressorRegistry(CompressorRegistry compressorRegistry) {
this.compressorRegistry = compressorRegistry;
return this;
}
@VisibleForTesting
static void prepareHeaders(Metadata headers, CallOptions callOptions, String userAgent,
DecompressorRegistry decompressorRegistry, Compressor compressor) {
// Fill out the User-Agent header.
headers.removeAll(USER_AGENT_KEY);
if (userAgent != null) {
headers.put(USER_AGENT_KEY, userAgent);
}
headers.removeAll(MESSAGE_ENCODING_KEY);
if (compressor != Codec.Identity.NONE) {
headers.put(MESSAGE_ENCODING_KEY, compressor.getMessageEncoding());
}
headers.removeAll(MESSAGE_ACCEPT_ENCODING_KEY);
if (!decompressorRegistry.getAdvertisedMessageEncodings().isEmpty()) {
String acceptEncoding =
ACCEPT_ENCODING_JOINER.join(decompressorRegistry.getAdvertisedMessageEncodings());
headers.put(MESSAGE_ACCEPT_ENCODING_KEY, acceptEncoding);
}
}
@Override
public void start(final Listener<RespT> observer, Metadata headers) {
checkState(stream == null, "Already started");
checkNotNull(observer, "observer");
checkNotNull(headers, "headers");
if (context.isCancelled()) {
// Context is already cancelled so no need to create a real stream, just notify the observer
// of cancellation via callback on the executor
stream = NoopClientStream.INSTANCE;
callExecutor.execute(new ContextRunnable(context) {
@Override
public void runInContext() {
observer.onClose(Status.CANCELLED.withCause(context.cancellationCause()), new Metadata());
}
});
return;
}
final String compressorName = callOptions.getCompressor();
if (compressorName != null) {
compressor = compressorRegistry.lookupCompressor(compressorName);
if (compressor == null) {
stream = NoopClientStream.INSTANCE;
callExecutor.execute(new ContextRunnable(context) {
@Override
public void runInContext() {
observer.onClose(
Status.INTERNAL.withDescription(
String.format("Unable to find compressor by name %s", compressorName)),
new Metadata());
}
});
return;
}
} else {
compressor = Codec.Identity.NONE;
}
prepareHeaders(headers, callOptions, userAgent, decompressorRegistry, compressor);
if (updateTimeoutHeader(callOptions.getDeadlineNanoTime(), headers)) {
ClientTransport transport = clientTransportProvider.get(callOptions);
stream = transport.newStream(method, headers);
} else {
stream = new FailingClientStream(Status.DEADLINE_EXCEEDED);
}
if (callOptions.getAuthority() != null) {
stream.setAuthority(callOptions.getAuthority());
}
stream.setCompressor(compressor);
stream.start(new ClientStreamListenerImpl(observer));
if (compressor != Codec.Identity.NONE) {
stream.setMessageCompression(true);
}
// Delay any sources of cancellation after start(), because most of the transports are broken if
// they receive cancel before start. Issue #1343 has more details
// Start the deadline timer after stream creation because it will close the stream
Long timeoutNanos = getRemainingTimeoutNanos(callOptions.getDeadlineNanoTime());
if (timeoutNanos != null) {
deadlineCancellationFuture = startDeadlineTimer(timeoutNanos);
if (deadlineCancellationFutureShouldBeCancelled) {
// Race detected! ClientStreamListener.closed may have been called before
// deadlineCancellationFuture was set, thereby preventing the future from being cancelled.
// Go ahead and cancel again, just to be sure it was cancelled.
deadlineCancellationFuture.cancel(false);
}
}
// Propagate later Context cancellation to the remote side.
this.context.addListener(this, directExecutor());
}
/**
* Based on the deadline, calculate and set the timeout to the given headers.
*
* @return {@code false} if deadline already exceeded
*/
static boolean updateTimeoutHeader(@Nullable Long deadlineNanoTime, Metadata headers) {
// Fill out timeout on the headers
// TODO(carl-mastrangelo): Find out if this should always remove the timeout,
// even when returning false.
headers.removeAll(TIMEOUT_KEY);
// Convert the deadline to timeout. Timeout is more favorable than deadline on the wire
// because timeout tolerates the clock difference between machines.
Long timeoutNanos = getRemainingTimeoutNanos(deadlineNanoTime);
if (timeoutNanos != null) {
if (timeoutNanos <= 0) {
return false;
}
headers.put(TIMEOUT_KEY, timeoutNanos);
}
return true;
}
/**
* Return the remaining amount of nanoseconds before the deadline is reached.
*
* <p>{@code null} if deadline is not set. Negative value if already expired.
*/
@Nullable
private static Long getRemainingTimeoutNanos(@Nullable Long deadlineNanoTime) {
if (deadlineNanoTime == null) {
return null;
}
return deadlineNanoTime - System.nanoTime();
}
@Override
public void request(int numMessages) {
Preconditions.checkState(stream != null, "Not started");
checkArgument(numMessages >= 0, "Number requested must be non-negative");
stream.request(numMessages);
}
@Override
public void cancel() {
if (cancelCalled) {
return;
}
cancelCalled = true;
try {
// Cancel is called in exception handling cases, so it may be the case that the
// stream was never successfully created.
if (stream != null) {
stream.cancel(Status.CANCELLED);
}
} finally {
context.removeListener(ClientCallImpl.this);
}
}
@Override
public void halfClose() {
Preconditions.checkState(stream != null, "Not started");
Preconditions.checkState(!cancelCalled, "call was cancelled");
Preconditions.checkState(!halfCloseCalled, "call already half-closed");
halfCloseCalled = true;
stream.halfClose();
}
@Override
public void sendMessage(ReqT message) {
Preconditions.checkState(stream != null, "Not started");
Preconditions.checkState(!cancelCalled, "call was cancelled");
Preconditions.checkState(!halfCloseCalled, "call was half-closed");
try {
// TODO(notcarl): Find out if messageIs needs to be closed.
InputStream messageIs = method.streamRequest(message);
stream.writeMessage(messageIs);
} catch (Throwable e) {
stream.cancel(Status.CANCELLED.withCause(e).withDescription("Failed to stream message"));
return;
}
// For unary requests, we don't flush since we know that halfClose should be coming soon. This
// allows us to piggy-back the END_STREAM=true on the last message frame without opening the
// possibility of broken applications forgetting to call halfClose without noticing.
if (!unaryRequest) {
stream.flush();
}
}
@Override
public void setMessageCompression(boolean enabled) {
checkState(stream != null, "Not started");
stream.setMessageCompression(enabled);
}
@Override
public boolean isReady() {
return stream.isReady();
}
private ScheduledFuture<?> startDeadlineTimer(long timeoutNanos) {
return deadlineCancellationExecutor.schedule(new Runnable() {
@Override
public void run() {
stream.cancel(Status.DEADLINE_EXCEEDED);
}
}, timeoutNanos, TimeUnit.NANOSECONDS);
}
private class ClientStreamListenerImpl implements ClientStreamListener {
private final Listener<RespT> observer;
private boolean closed;
public ClientStreamListenerImpl(Listener<RespT> observer) {
this.observer = Preconditions.checkNotNull(observer, "observer");
}
@Override
public void headersRead(final Metadata headers) {
Decompressor decompressor = Codec.Identity.NONE;
if (headers.containsKey(MESSAGE_ENCODING_KEY)) {
String encoding = headers.get(MESSAGE_ENCODING_KEY);
decompressor = decompressorRegistry.lookupDecompressor(encoding);
if (decompressor == null) {
stream.cancel(Status.INTERNAL.withDescription(
String.format("Can't find decompressor for %s", encoding)));
return;
}
}
stream.setDecompressor(decompressor);
callExecutor.execute(new ContextRunnable(context) {
@Override
public final void runInContext() {
try {
if (closed) {
return;
}
observer.onHeaders(headers);
} catch (Throwable t) {
stream.cancel(Status.CANCELLED.withCause(t).withDescription("Failed to read headers"));
return;
}
}
});
}
@Override
public void messageRead(final InputStream message) {
callExecutor.execute(new ContextRunnable(context) {
@Override
public final void runInContext() {
try {
if (closed) {
return;
}
try {
observer.onMessage(method.parseResponse(message));
} finally {
message.close();
}
} catch (Throwable t) {
stream.cancel(Status.CANCELLED.withCause(t).withDescription("Failed to read message."));
return;
}
}
});
}
@Override
public void closed(Status status, Metadata trailers) {
Long timeoutNanos = getRemainingTimeoutNanos(callOptions.getDeadlineNanoTime());
if (status.getCode() == Status.Code.CANCELLED && timeoutNanos != null) {
// When the server's deadline expires, it can only reset the stream with CANCEL and no
// description. Since our timer may be delayed in firing, we double-check the deadline and
// turn the failure into the likely more helpful DEADLINE_EXCEEDED status.
if (timeoutNanos <= 0) {
status = Status.DEADLINE_EXCEEDED;
// Replace trailers to prevent mixing sources of status and trailers.
trailers = new Metadata();
}
}
final Status savedStatus = status;
final Metadata savedTrailers = trailers;
callExecutor.execute(new ContextRunnable(context) {
@Override
public final void runInContext() {
try {
closed = true;
deadlineCancellationFutureShouldBeCancelled = true;
// manually optimize the volatile read
ScheduledFuture<?> future = deadlineCancellationFuture;
if (future != null) {
future.cancel(false);
}
observer.onClose(savedStatus, savedTrailers);
} finally {
context.removeListener(ClientCallImpl.this);
}
}
});
}
@Override
public void onReady() {
callExecutor.execute(new ContextRunnable(context) {
@Override
public final void runInContext() {
observer.onReady();
}
});
}
}
}
|
package org.jasig.cas.event;
import java.io.Serializable;
import org.jasig.cas.ticket.Ticket;
/**
* Event representing an action taken on a ticket including
* the creation, validation, destruction of a Ticket.
*
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.0
*
*/
public class TicketEvent extends AbstractEvent {
/** TicketEvent of type Create Ticket Granting Ticket. */
public static final TicketEventType CREATE_TICKET_GRANTING_TICKET = new TicketEventType("CREATE_TICKET_GRANTING_TICKET");
/** TicketEvent of type Create Service Ticket. */
public static final TicketEventType CREATE_SERVCE_TICKET = new TicketEventType("CREATE_SERVICE_TICKET");
/** TicketEvent of type Destroy Ticket Granting Ticket. */
public static final TicketEventType DESTROY_TICKET_GRANTING_TICKET = new TicketEventType("DESTROY_TICKET_GRANTING_TICKET");
/** TicketEvent of type Validate Service Ticket. */
public static final TicketEventType VALIDATE_SERVICE_TICKET = new TicketEventType("VALIDATE_SERVICE_TICKET");
/** Unique Serializable Id. */
private static final long serialVersionUID = 3904682686680347187L;
/** The TicketEventType for this event. */
private final TicketEventType ticketEventType;
/** The String id of the Ticket for this event. */
private final String ticketId;
public TicketEvent(final Ticket ticket, final TicketEventType ticketEventType) {
this(ticket, ticketEventType, null);
}
public TicketEvent(final TicketEventType ticketEventType, final String ticketId) {
this(null, ticketEventType, ticketId);
}
private TicketEvent(final Ticket ticket, final TicketEventType ticketEventType, final String ticketId) {
super((ticket == null) ? (Object) ticketId : ticket);
if (ticketEventType == null) {
throw new IllegalStateException("ticketEventType cannot be null on " + this.getClass().getName());
}
if (ticketId == null && ticket == null) {
throw new IllegalStateException("Either ticketId or Ticket need to be provided.");
}
if (ticket != null) {
this.ticketId = ticket.getId();
} else {
this.ticketId = ticketId;
}
this.ticketEventType = ticketEventType;
}
/**
* Method to retrieve the Id of the Ticket.
* @return the id of the ticket.
*/
public String getTicketId() {
return this.ticketId;
}
/**
* Method to retrieve the Ticket.
* @return the ticket, or null if we have no ticket.
*/
public Ticket getTicket() {
return (getSource() instanceof Ticket) ? (Ticket) getSource() : null;
}
/** Method to retrieve the TicketEventType
*
* @return the event type.
*/
public TicketEventType getTicketEventType() {
return this.ticketEventType;
}
protected final static class TicketEventType implements Serializable {
private static final long serialVersionUID = 3258689897039671865L;
private final String name;
protected TicketEventType(String name) {
this.name = name;
}
public String getEventTypeAsString() {
return this.name;
}
}
}
|
package org.javarosa.core.model;
import org.javarosa.core.log.WrappedException;
import org.javarosa.core.model.actions.Action;
import org.javarosa.core.model.actions.ActionController;
import org.javarosa.core.model.condition.Condition;
import org.javarosa.core.model.condition.Constraint;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.condition.IConditionExpr;
import org.javarosa.core.model.condition.IFunctionHandler;
import org.javarosa.core.model.condition.Recalculate;
import org.javarosa.core.model.condition.Triggerable;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.IntegerData;
import org.javarosa.core.model.data.SelectMultiData;
import org.javarosa.core.model.data.SelectOneData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.core.model.instance.AbstractTreeElement;
import org.javarosa.core.model.instance.DataInstance;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.InstanceInitializationFactory;
import org.javarosa.core.model.instance.InvalidReferenceException;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.model.trace.EvaluationTrace;
import org.javarosa.core.model.util.restorable.RestoreUtils;
import org.javarosa.core.model.utils.QuestionPreloader;
import org.javarosa.core.services.locale.Localizer;
import org.javarosa.core.services.storage.IMetaData;
import org.javarosa.core.services.storage.Persistable;
import org.javarosa.core.util.CacheTable;
import org.javarosa.core.util.DataUtil;
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.ExtWrapListPoly;
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.PrototypeFactory;
import org.javarosa.model.xform.XPathReference;
import org.javarosa.xpath.XPathException;
import org.javarosa.xpath.XPathTypeMismatchException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.NoSuchElementException;
import java.util.Vector;
/**
* Definition of a form. This has some meta data about the form definition and a
* collection of groups together with question branching or skipping rules.
*
* @author Daniel Kayiwa, Drew Roos
*/
public class FormDef implements IFormElement, Persistable, IMetaData,
ActionController.ActionResultProcessor {
public static final String STORAGE_KEY = "FORMDEF";
public static final int TEMPLATING_RECURSION_LIMIT = 10;
/**
* Hierarchy of questions, groups and repeats in the form
*/
private Vector<IFormElement> children;
/**
* A collection of group definitions.
*/
private int id;
/**
* The numeric unique identifier of the form definition on the local device
*/
private String title;
/**
* The display title of the form.
*/
private String name;
private Vector<XFormExtension> extensions;
/**
* A unique external name that is used to identify the form between machines
*/
private Localizer localizer;
// This list is topologically ordered, meaning for any tA
// and tB in the list, where tA comes before tB, evaluating tA cannot
// depend on any result from evaluating tB
private Vector<Triggerable> triggerables;
// true if triggerables has been ordered topologically (DON'T DELETE ME
// EVEN THOUGH I'M UNUSED)
private boolean triggerablesInOrder;
// <IConditionExpr> contents of <output> tags that serve as parameterized
// arguments to captions
private Vector outputFragments;
/**
* Map references to the calculate/relevancy conditions that depend on that
* reference's value. Used to trigger re-evaluation of those conditionals
* when the reference is updated.
*/
private Hashtable<TreeReference, Vector<Triggerable>> triggerIndex;
/**
* Associates repeatable nodes with the Condition that determines their
* relevancy.
*/
private Hashtable<TreeReference, Condition> conditionRepeatTargetIndex;
public EvaluationContext exprEvalContext;
private QuestionPreloader preloader = new QuestionPreloader();
// XML ID's cannot start with numbers, so this should never conflict
private static final String DEFAULT_SUBMISSION_PROFILE = "1";
private Hashtable<String, SubmissionProfile> submissionProfiles;
/**
* Secondary and external instance pointers
*/
private Hashtable<String, DataInstance> formInstances;
private FormInstance mainInstance = null;
boolean mDebugModeEnabled = false;
private final Vector<Triggerable> triggeredDuringInsert = new Vector<Triggerable>();
private ActionController actionController;
//If this instance is just being edited, don't fire end of form events
private boolean isCompletedInstance;
/**
* Cache children that trigger target will cascade to. For speeding up
* calculations that determine what needs to be triggered when a value
* changes.
*/
private final CacheTable<TreeReference, Vector<TreeReference>> cachedCascadingChildren =
new CacheTable<TreeReference, Vector<TreeReference>>();
public FormDef() {
setID(-1);
setChildren(null);
triggerables = new Vector<Triggerable>();
triggerablesInOrder = true;
triggerIndex = new Hashtable<TreeReference, Vector<Triggerable>>();
//This is kind of a wreck...
setEvaluationContext(new EvaluationContext(null));
outputFragments = new Vector();
submissionProfiles = new Hashtable<String, SubmissionProfile>();
formInstances = new Hashtable<String, DataInstance>();
extensions = new Vector<XFormExtension>();
actionController = new ActionController();
}
/**
* Getters and setters for the vectors tha
*/
public void addNonMainInstance(DataInstance instance) {
formInstances.put(instance.getInstanceId(), instance);
this.setEvaluationContext(new EvaluationContext(null));
}
/**
* Get an instance based on a name
*/
public DataInstance getNonMainInstance(String name) {
if (!formInstances.containsKey(name)) {
return null;
}
return formInstances.get(name);
}
public Enumeration getNonMainInstances() {
return formInstances.elements();
}
/**
* Set the main instance
*/
public void setInstance(FormInstance fi) {
mainInstance = fi;
fi.setFormId(getID());
this.setEvaluationContext(new EvaluationContext(null));
attachControlsToInstanceData();
}
/**
* Get the main instance
*/
public FormInstance getMainInstance() {
return mainInstance;
}
public FormInstance getInstance() {
return getMainInstance();
}
public void addChild(IFormElement fe) {
this.children.addElement(fe);
}
public IFormElement getChild(int i) {
if (i < this.children.size())
return this.children.elementAt(i);
throw new ArrayIndexOutOfBoundsException(
"FormDef: invalid child index: " + i + " only "
+ children.size() + " children");
}
public IFormElement getChild(FormIndex index) {
IFormElement element = this;
while (index != null && index.isInForm()) {
element = element.getChild(index.getLocalIndex());
index = index.getNextLevel();
}
return element;
}
/**
* Dereference the form index and return a Vector of all interstitial nodes
* (top-level parent first; index target last)
*
* Ignore 'new-repeat' node for now; just return/stop at ref to
* yet-to-be-created repeat node (similar to repeats that already exist)
*/
public Vector explodeIndex(FormIndex index) {
Vector<Integer> indexes = new Vector<Integer>();
Vector<Integer> multiplicities = new Vector<Integer>();
Vector<IFormElement> elements = new Vector<IFormElement>();
collapseIndex(index, indexes, multiplicities, elements);
return elements;
}
// take a reference, find the instance node it refers to (factoring in
// multiplicities)
public TreeReference getChildInstanceRef(FormIndex index) {
Vector<Integer> indexes = new Vector<Integer>();
Vector<Integer> multiplicities = new Vector<Integer>();
Vector<IFormElement> elements = new Vector<IFormElement>();
collapseIndex(index, indexes, multiplicities, elements);
return getChildInstanceRef(elements, multiplicities);
}
/**
* Return a tree reference which follows the path down the concrete elements provided
* along with the multiplicities provided.
*/
public TreeReference getChildInstanceRef(Vector<IFormElement> elements,
Vector<Integer> multiplicities) {
if (elements.size() == 0) {
return null;
}
// get reference for target element
TreeReference ref = FormInstance.unpackReference(elements.lastElement().getBind()).clone();
for (int i = 0; i < ref.size(); i++) {
//There has to be a better way to encapsulate this
if (ref.getMultiplicity(i) != TreeReference.INDEX_ATTRIBUTE) {
ref.setMultiplicity(i, 0);
}
}
// fill in multiplicities for repeats along the way
for (int i = 0; i < elements.size(); i++) {
IFormElement temp = elements.elementAt(i);
if (temp instanceof GroupDef && ((GroupDef)temp).getRepeat()) {
TreeReference repRef = FormInstance.unpackReference(temp.getBind());
if (repRef.isParentOf(ref, false)) {
int repMult = multiplicities.elementAt(i).intValue();
ref.setMultiplicity(repRef.size() - 1, repMult);
} else {
// question/repeat hierarchy is not consistent with
// instance instance and bindings
return null;
}
}
}
return ref;
}
public void setLocalizer(Localizer l) {
if (this.localizer != null) {
this.localizer.unregisterLocalizable(this);
}
this.localizer = l;
if (this.localizer != null) {
this.localizer.registerLocalizable(this);
}
}
// don't think this should ever be called(!)
public XPathReference getBind() {
throw new RuntimeException("method not implemented");
}
public void setValue(IAnswerData data, TreeReference ref) {
setValue(data, ref, mainInstance.resolveReference(ref));
}
public void setValue(IAnswerData data, TreeReference ref, TreeElement node) {
setAnswer(data, node);
triggerTriggerables(ref);
//TODO: pre-populate fix-count repeats here?
}
public void setAnswer(IAnswerData data, TreeReference ref) {
setAnswer(data, mainInstance.resolveReference(ref));
}
public void setAnswer(IAnswerData data, TreeElement node) {
node.setAnswer(data);
}
/**
* Deletes the inner-most repeat that this node belongs to and returns the
* corresponding FormIndex. Behavior is currently undefined if you call this
* method on a node that is not contained within a repeat.
*/
public FormIndex deleteRepeat(FormIndex index) {
Vector indexes = new Vector();
Vector multiplicities = new Vector();
Vector elements = new Vector();
collapseIndex(index, indexes, multiplicities, elements);
// loop backwards through the elements, removing objects from each
// vector, until we find a repeat
// TODO: should probably check to make sure size > 0
for (int i = elements.size() - 1; i >= 0; i
IFormElement e = (IFormElement)elements.elementAt(i);
if (e instanceof GroupDef && ((GroupDef)e).getRepeat()) {
break;
} else {
indexes.removeElementAt(i);
multiplicities.removeElementAt(i);
elements.removeElementAt(i);
}
}
// build new formIndex which includes everything
// up to the node we're going to remove
FormIndex newIndex = buildIndex(indexes, multiplicities, elements);
TreeReference deleteRef = getChildInstanceRef(newIndex);
TreeElement deleteElement = mainInstance.resolveReference(deleteRef);
TreeReference parentRef = deleteRef.getParentRef();
TreeElement parentElement = mainInstance.resolveReference(parentRef);
int childMult = deleteElement.getMult();
parentElement.removeChild(deleteElement);
// update multiplicities of other child nodes
for (int i = 0; i < parentElement.getNumChildren(); i++) {
TreeElement child = parentElement.getChildAt(i);
if (child.getMult() > childMult) {
child.setMult(child.getMult() - 1);
}
}
this.getMainInstance().cleanCache();
triggerTriggerables(deleteRef);
return newIndex;
}
public void createNewRepeat(FormIndex index) throws InvalidReferenceException {
TreeReference repeatContextRef = getChildInstanceRef(index);
TreeElement template = mainInstance.getTemplate(repeatContextRef);
mainInstance.copyNode(template, repeatContextRef);
preloadInstance(mainInstance.resolveReference(repeatContextRef));
// Fire jr-insert events before "calculate"s
triggeredDuringInsert.removeAllElements();
actionController.triggerActionsFromEvent(Action.EVENT_JR_INSERT, this, repeatContextRef, this);
// trigger conditions that depend on the creation of this new node
triggerTriggerables(repeatContextRef);
// trigger conditions for the node (and sub-nodes)
initTriggerablesRootedBy(repeatContextRef, triggeredDuringInsert);
}
@Override
public void processResultOfAction(TreeReference refSetByAction, String event) {
if (Action.EVENT_JR_INSERT.equals(event)) {
Vector<Triggerable> triggerables =
triggerIndex.get(refSetByAction.genericize());
if (triggerables != null) {
for (Triggerable elem : triggerables) {
triggeredDuringInsert.addElement(elem);
}
}
}
}
public boolean isRepeatRelevant(TreeReference repeatRef) {
boolean relev = true;
Condition c = conditionRepeatTargetIndex.get(repeatRef.genericize());
if (c != null) {
relev = c.evalBool(mainInstance, new EvaluationContext(exprEvalContext, repeatRef));
}
//check the relevancy of the immediate parent
if (relev) {
TreeElement templNode = mainInstance.getTemplate(repeatRef);
TreeReference parentPath = templNode.getParent().getRef().genericize();
TreeElement parentNode = mainInstance.resolveReference(parentPath.contextualize(repeatRef));
relev = parentNode.isRelevant();
}
return relev;
}
/**
* Does the repeat group at the given index enable users to add more items,
* and if so, has the user reached the item limit?
*
* @param repeatRef Reference pointing to a particular repeat item
* @param repeatIndex Id for looking up the repeat group
* @return Do the current constraints on the repeat group allow for adding
* more children?
*/
public boolean canCreateRepeat(TreeReference repeatRef, FormIndex repeatIndex) {
GroupDef repeat = (GroupDef)this.getChild(repeatIndex);
//Check to see if this repeat can have children added by the user
if (repeat.noAddRemove) {
//Check to see if there's a count to use to determine how many children this repeat
//should have
if (repeat.getCountReference() != null) {
int currentMultiplicity = repeatIndex.getElementMultiplicity();
TreeReference absPathToCount = repeat.getConextualizedCountReference(repeatRef);
AbstractTreeElement countNode = this.getMainInstance().resolveReference(absPathToCount);
if (countNode == null) {
throw new XPathTypeMismatchException("Could not find the location " +
absPathToCount.toString() + " where the repeat at " +
repeatRef.toString(false) + " is looking for its count");
}
//get the total multiplicity possible
IAnswerData boxedCount = countNode.getValue();
int count;
if (boxedCount == null) {
count = 0;
} else {
try {
count = ((Integer)new IntegerData().cast(boxedCount.uncast()).getValue()).intValue();
} catch (IllegalArgumentException iae) {
throw new XPathTypeMismatchException("The repeat count value \"" +
boxedCount.uncast().getString() +
"\" at " + absPathToCount.toString() +
" must be a number!");
}
}
if (count <= currentMultiplicity) {
return false;
}
} else {
//Otherwise the user can never add repeat instances
return false;
}
}
//TODO: If we think the node is still relevant, we also need to figure out a way to test that assumption against
//the repeat's constraints.
return true;
}
public void copyItemsetAnswer(QuestionDef q, TreeElement targetNode, IAnswerData data) throws InvalidReferenceException {
ItemsetBinding itemset = q.getDynamicChoices();
TreeReference targetRef = targetNode.getRef();
TreeReference destRef = itemset.getDestRef().contextualize(targetRef);
Vector<Selection> selections = null;
Vector<String> selectedValues = new Vector<String>();
if (data instanceof SelectMultiData) {
selections = (Vector<Selection>)data.getValue();
} else if (data instanceof SelectOneData) {
selections = new Vector<Selection>();
selections.addElement((Selection)data.getValue());
}
if (itemset.valueRef != null) {
for (int i = 0; i < selections.size(); i++) {
selectedValues.addElement(selections.elementAt(i).choice.getValue());
}
}
//delete existing dest nodes that are not in the answer selection
Hashtable<String, TreeElement> existingValues = new Hashtable<String, TreeElement>();
Vector<TreeReference> existingNodes = exprEvalContext.expandReference(destRef);
for (int i = 0; i < existingNodes.size(); i++) {
TreeElement node = getMainInstance().resolveReference(existingNodes.elementAt(i));
if (itemset.valueRef != null) {
String value = itemset.getRelativeValue().evalReadable(this.getMainInstance(), new EvaluationContext(exprEvalContext, node.getRef()));
if (selectedValues.contains(value)) {
existingValues.put(value, node); //cache node if in selection and already exists
}
}
//delete from target
targetNode.removeChild(node);
}
//copy in nodes for new answer; preserve ordering in answer
for (int i = 0; i < selections.size(); i++) {
Selection s = selections.elementAt(i);
SelectChoice ch = s.choice;
TreeElement cachedNode = null;
if (itemset.valueRef != null) {
String value = ch.getValue();
if (existingValues.containsKey(value)) {
cachedNode = existingValues.get(value);
}
}
if (cachedNode != null) {
cachedNode.setMult(i);
targetNode.addChild(cachedNode);
} else {
getMainInstance().copyItemsetNode(ch.copyNode, destRef, this);
}
}
// trigger conditions that depend on the creation of these new nodes
triggerTriggerables(destRef);
// initialize conditions for the node (and sub-nodes)
// NOTE PLM: the following trigger initialization doesn't cascade to
// children because it is behaving like trigger initalization for new
// repeat entries. If we begin actually using this method, the trigger
// cascading logic should be fixed.
initTriggerablesRootedBy(destRef, new Vector<Triggerable>());
// not 100% sure this will work since destRef is ambiguous as the last
// step, but i think it's supposed to work
}
/**
* Add a Condition to the form's Collection.
*/
public Triggerable addTriggerable(Triggerable t) {
int existingIx = triggerables.indexOf(t);
if (existingIx != -1) {
// One node may control access to many nodes; this means many nodes
// effectively have the same condition. Let's identify when
// conditions are the same, and store and calculate it only once.
// nov-2-2011: ctsims - We need to merge the context nodes together
// whenever we do this (finding the highest common ground between
// the two), otherwise we can end up failing to trigger when the
// ignored context exists and the used one doesn't
Triggerable existingTriggerable = triggerables.elementAt(existingIx);
existingTriggerable.contextRef = existingTriggerable.contextRef.intersect(t.contextRef);
return existingTriggerable;
// NOTE: if the contextRef is unnecessarily deep, the condition
// will be evaluated more times than needed. Perhaps detect when
// 'identical' condition has a shorter contextRef, and use that one
// instead?
} else {
triggerables.addElement(t);
triggerablesInOrder = false;
for (TreeReference trigger : t.getTriggers()) {
TreeReference predicatelessTrigger = t.widenContextToAndClearPredicates(trigger);
if (!triggerIndex.containsKey(predicatelessTrigger)) {
triggerIndex.put(predicatelessTrigger.clone(), new Vector<Triggerable>());
}
Vector<Triggerable> triggered = triggerIndex.get(predicatelessTrigger);
if (!triggered.contains(t)) {
triggered.addElement(t);
}
}
return t;
}
}
/**
* Dependency-sorted enumerator for the triggerables present in the form.
*
* @return Enumerator of triggerables such that when an element X precedes
* Y then X doesn't have any references that are dependent on Y.
*/
public Enumeration getTriggerables() {
return triggerables.elements();
}
/**
* @return All references in the form that are depended on by
* calculate/relevancy conditions.
*/
public Enumeration refWithTriggerDependencies() {
return triggerIndex.keys();
}
/**
* Get the triggerable conditions, like relevancy/calculate, that depend on
* the given reference.
*
* @param ref An absolute reference that is used in relevancy/calculate
* expressions.
* @return All the triggerables that depend on the given reference.
*/
public Vector conditionsTriggeredByRef(TreeReference ref) {
return triggerIndex.get(ref);
}
public void finalizeTriggerables() throws IllegalStateException {
Vector<Triggerable[]> partialOrdering = new Vector<Triggerable[]>();
buildPartialOrdering(partialOrdering);
Vector<Triggerable> vertices = new Vector<Triggerable>();
for (Triggerable triggerable : triggerables) {
vertices.addElement(triggerable);
}
triggerables.removeAllElements();
while (vertices.size() > 0) {
Vector<Triggerable> roots = buildRootNodes(vertices, partialOrdering);
if (roots.size() == 0) {
// if no root nodes while graph still has nodes, graph has cycles
throwGraphCyclesException(vertices);
}
setOrderOfTriggerable(roots, vertices, partialOrdering);
}
triggerablesInOrder = true;
buildConditionRepeatTargetIndex();
}
private void buildPartialOrdering(Vector<Triggerable[]> partialOrdering) {
for (Triggerable t : triggerables) {
Vector<Triggerable> deps = new Vector<Triggerable>();
fillTriggeredElements(t, deps, false);
for (Triggerable u : deps) {
Triggerable[] edge = {t, u};
partialOrdering.addElement(edge);
}
}
}
private static Vector<Triggerable> buildRootNodes(Vector<Triggerable> vertices,
Vector<Triggerable[]> partialOrdering) {
Vector<Triggerable> roots = new Vector<Triggerable>();
for (Triggerable vertex : vertices) {
roots.addElement(vertex);
}
for (Triggerable[] edge : partialOrdering) {
edge[1].updateStopContextualizingAtFromDominator(edge[0]);
roots.removeElement(edge[1]);
}
return roots;
}
private void throwGraphCyclesException(Vector<Triggerable> vertices) {
String hints = "";
for (Triggerable t : vertices) {
for (TreeReference r : t.getTargets()) {
hints += "\n" + r.toString(true);
}
}
String message = "Cycle detected in form's relevant and calculation logic!";
if (!hints.equals("")) {
message += "\nThe following nodes are likely involved in the loop:" + hints;
}
throw new IllegalStateException(message);
}
private void setOrderOfTriggerable(Vector<Triggerable> roots,
Vector<Triggerable> vertices,
Vector<Triggerable[]> partialOrdering) {
for (Triggerable root : roots) {
triggerables.addElement(root);
vertices.removeElement(root);
}
for (int i = partialOrdering.size() - 1; i >= 0; i
Triggerable[] edge = partialOrdering.elementAt(i);
if (roots.contains(edge[0]))
partialOrdering.removeElementAt(i);
}
}
private void buildConditionRepeatTargetIndex() {
conditionRepeatTargetIndex = new Hashtable<TreeReference, Condition>();
for (Triggerable t : triggerables) {
if (t instanceof Condition) {
for (TreeReference target : t.getTargets()) {
if (mainInstance.getTemplate(target) != null) {
conditionRepeatTargetIndex.put(target, (Condition)t);
}
}
}
}
}
/**
* Get all of the elements which will need to be evaluated (in order) when
* the triggerable is fired.
*
* @param destination (mutated) Will have triggerables added to it.
* @param isRepeatEntryInit Don't cascade triggers to children when
* initializing a new repeat entry. Repeat entry
* children have already been queued to be
* triggered.
*/
private void fillTriggeredElements(Triggerable t,
Vector<Triggerable> destination,
boolean isRepeatEntryInit) {
if (t.canCascade()) {
for (TreeReference target : t.getTargets()) {
Vector<TreeReference> updatedNodes = new Vector<TreeReference>();
updatedNodes.addElement(target);
// Repeat sub-elements have already been added to 'destination'
// when we grabbed all triggerables that target children of the
// repeat entry (via initTriggerablesRootedBy). Hence skip them
if (!isRepeatEntryInit && t.isCascadingToChildren()) {
updatedNodes = findCascadeReferences(target, updatedNodes);
}
addTriggerablesTargetingNodes(updatedNodes, destination);
}
}
}
/**
* Gather list of generic references to children of a target reference for
* a triggerable that cascades to its children. This is needed when, for
* example, changing the relevancy of the target will require the triggers
* pointing to children be recalcualted.
*
* @param target Gather children of this by using a template or
* manually traversing the tree
* @param updatedNodes (potentially mutated) Gets generic child references
* added to it.
* @return Potentially cached version of updatedNodes argument that
* contains the target and generic references to the children it might
* cascade to.
*/
private Vector<TreeReference> findCascadeReferences(TreeReference target,
Vector<TreeReference> updatedNodes) {
Vector<TreeReference> cachedNodes = cachedCascadingChildren.retrieve(target);
if (cachedNodes == null) {
if (target.getMultLast() == TreeReference.INDEX_ATTRIBUTE) {
// attributes don't have children that might change under
// contextualization
cachedCascadingChildren.register(target, updatedNodes);
} else {
Vector<TreeReference> expandedRefs = exprEvalContext.expandReference(target);
if (expandedRefs.size() > 0) {
AbstractTreeElement template = mainInstance.getTemplatePath(target);
if (template != null) {
addChildrenOfElement(template, updatedNodes);
cachedCascadingChildren.register(target, updatedNodes);
} else {
// NOTE PLM: entirely possible this can be removed if
// the getTemplatePath code is updated to handle
// heterogeneous paths. Set a breakpoint here and run
// the test suite to see an example
// NOTE PLM: Though I'm pretty sure we could cache
// this, I'm going to avoid doing so because I'm unsure
// whether it is possible for children that are
// cascaded to will change when expandedRefs changes
// due to new data being added.
addChildrenOfReference(expandedRefs, updatedNodes);
}
}
}
} else {
updatedNodes = cachedNodes;
}
return updatedNodes;
}
/**
* Resolve the expanded references and gather their generic children and
* attributes into the genericRefs list.
*/
private void addChildrenOfReference(Vector<TreeReference> expandedRefs,
Vector<TreeReference> genericRefs) {
for (TreeReference ref : expandedRefs) {
addChildrenOfElement(exprEvalContext.resolveReference(ref), genericRefs);
}
}
/**
* Gathers generic children and attribute references for the provided
* element into the genericRefs list.
*/
private static void addChildrenOfElement(AbstractTreeElement treeElem,
Vector<TreeReference> genericRefs) {
// recursively add children of element
for (int i = 0; i < treeElem.getNumChildren(); ++i) {
AbstractTreeElement child = treeElem.getChildAt(i);
TreeReference genericChild = child.getRef().genericize();
if (!genericRefs.contains(genericChild)) {
genericRefs.addElement(genericChild);
}
addChildrenOfElement(child, genericRefs);
}
// add all the attributes of this element
for (int i = 0; i < treeElem.getAttributeCount(); ++i) {
AbstractTreeElement child =
treeElem.getAttribute(treeElem.getAttributeNamespace(i),
treeElem.getAttributeName(i));
TreeReference genericChild = child.getRef().genericize();
if (!genericRefs.contains(genericChild)) {
genericRefs.addElement(genericChild);
}
}
}
private void addTriggerablesTargetingNodes(Vector<TreeReference> updatedNodes,
Vector<Triggerable> destination) {
//Now go through each of these updated nodes (generally just 1 for a normal calculation,
//multiple nodes if there's a relevance cascade.
for (TreeReference ref : updatedNodes) {
//Check our index to see if that target is a Trigger for other conditions
//IE: if they are an element of a different calculation or relevancy calc
//We can't make this reference generic before now or we'll lose the target information,
//so we'll be more inclusive than needed and see if any of our triggers are keyed on
//the predicate-less path of this ref
TreeReference predicatelessRef = ref;
if (ref.hasPredicates()) {
predicatelessRef = ref.removePredicates();
}
Vector<Triggerable> triggered = triggerIndex.get(predicatelessRef);
if (triggered != null) {
//If so, walk all of these triggerables that we found
for (Triggerable triggerable : triggered) {
//And add them to the queue if they aren't there already
if (!destination.contains(triggerable)) {
destination.addElement(triggerable);
}
}
}
}
}
/**
* Enables debug traces in this form, which can be requested as a map after
* this call has been performed. Debug traces will be available until they
* are explicitly disabled.
*
* This call also re-executes all triggerables in debug mode to make their
* current traces available.
*
* Must be called after this form is initialized.
*/
public void enableDebugTraces() {
if (!mDebugModeEnabled) {
for (int i = 0; i < triggerables.size(); i++) {
Triggerable t = triggerables.elementAt(i);
t.setDebug(true);
}
// Re-execute all triggerables to collect traces
initAllTriggerables();
mDebugModeEnabled = true;
}
}
/**
* Disable debug tracing for this form. Debug traces will no longer be
* available after this call.
*/
public void disableDebugTraces() {
if (mDebugModeEnabled) {
for (int i = 0; i < triggerables.size(); i++) {
Triggerable t = triggerables.elementAt(i);
t.setDebug(false);
}
mDebugModeEnabled = false;
}
}
public Hashtable<TreeReference, Hashtable<String, EvaluationTrace>> getDebugTraceMap()
throws IllegalStateException {
if (!mDebugModeEnabled) {
throw new IllegalStateException("Debugging is not enabled");
}
// TODO: sure would be nice to be able to cache this at some point, but
// will have to have a way to invalidate by trigger or something
Hashtable<TreeReference, Hashtable<String, EvaluationTrace>> debugInfo =
new Hashtable<TreeReference, Hashtable<String, EvaluationTrace>>();
for (int i = 0; i < triggerables.size(); i++) {
Triggerable t = triggerables.elementAt(i);
Hashtable<TreeReference, EvaluationTrace> triggerOutputs = t.getEvaluationTraces();
for (Enumeration e = triggerOutputs.keys(); e.hasMoreElements(); ) {
TreeReference elementRef = (TreeReference)e.nextElement();
String label = t.getDebugLabel();
Hashtable<String, EvaluationTrace> traces = debugInfo.get(elementRef);
if (traces == null) {
traces = new Hashtable<String, EvaluationTrace>();
}
traces.put(label, triggerOutputs.get(elementRef));
debugInfo.put(elementRef, traces);
}
}
return debugInfo;
}
private void initAllTriggerables() {
// Use all triggerables because we can assume they are rooted by rootRef
TreeReference rootRef = TreeReference.rootRef();
Vector<Triggerable> applicable = new Vector<Triggerable>();
for (Triggerable triggerable : triggerables) {
applicable.addElement(triggerable);
}
evaluateTriggerables(applicable, rootRef, false);
}
/**
* Evaluate triggerables targeting references that are children of the
* provided newly created (repeat instance) ref. Ignore all triggerables
* that were already fired by processing the jr-insert action. Ignored
* triggerables can still be fired if a dependency is modified.
*
* @param triggeredDuringInsert Triggerables that don't need to be fired
* because they have already been fired while processing insert events
*/
private void initTriggerablesRootedBy(TreeReference rootRef,
Vector<Triggerable> triggeredDuringInsert) {
TreeReference genericRoot = rootRef.genericize();
Vector<Triggerable> applicable = new Vector<Triggerable>();
for (Triggerable triggerable : triggerables) {
for (TreeReference target : triggerable.getTargets()) {
if (genericRoot.isParentOf(target, false)) {
if (!triggeredDuringInsert.contains(triggerable)) {
applicable.addElement(triggerable);
break;
}
}
}
}
evaluateTriggerables(applicable, rootRef, true);
}
/**
* The entry point for the DAG cascade after a value is changed in the model.
*
* @param ref The full contextualized unambiguous reference of the value that was
* changed.
*/
public void triggerTriggerables(TreeReference ref) {
//turn unambiguous ref into a generic ref
//to identify what nodes should be triggered by this
//reference changing
TreeReference genericRef = ref.genericize();
//get triggerables which are activated by the generic reference
Vector<Triggerable> triggered = triggerIndex.get(genericRef);
if (triggered == null) {
return;
}
//Our vector doesn't have a shallow copy op, so make one
Vector<Triggerable> triggeredCopy = new Vector<Triggerable>();
for (int i = 0; i < triggered.size(); i++) {
triggeredCopy.addElement(triggered.elementAt(i));
}
//Evaluate all of the triggerables in our new vector
evaluateTriggerables(triggeredCopy, ref, false);
}
/**
* Step 2 in evaluating DAG computation updates from a value being changed
* in the instance. This step is responsible for taking the root set of
* directly triggered conditions, identifying which conditions should
* further be triggered due to their update, and then dispatching all of
* the evaluations.
*
* @param tv A vector of all of the trigerrables directly
* triggered by the value changed. Will be mutated
* by this method.
* @param anchorRef The reference to original value that was updated
* @param isRepeatEntryInit Don't cascade triggers to children when
* initializing a new repeat entry. Repeat entry
* children have already been queued to be
* triggered.
*/
private void evaluateTriggerables(Vector<Triggerable> tv,
TreeReference anchorRef,
boolean isRepeatEntryInit) {
// Update the list of triggerables that need to be evaluated.
for (int i = 0; i < tv.size(); i++) {
// NOTE PLM: tv may grow in size through iteration.
Triggerable t = tv.elementAt(i);
fillTriggeredElements(t, tv, isRepeatEntryInit);
}
// tv should now contain all of the triggerable components which are
// going to need to be addressed by this update.
// 'triggerables' is topologically-ordered by dependencies, so evaluate
// the triggerables in 'tv' in the order they appear in 'triggerables'
for (Triggerable triggerable : triggerables) {
if (tv.contains(triggerable)) {
evaluateTriggerable(triggerable, anchorRef);
}
}
}
/**
* Step 3 in DAG cascade. evaluate the individual triggerable expressions
* against the anchor (the value that changed which triggered
* recomputation)
*
* @param triggerable The triggerable to be updated
* @param anchorRef The reference to the value which was changed.
*/
private void evaluateTriggerable(Triggerable triggerable, TreeReference anchorRef) {
// Contextualize the reference used by the triggerable against the anchor
TreeReference contextRef = triggerable.narrowContextBy(anchorRef);
// Now identify all of the fully qualified nodes which this triggerable
// updates. (Multiple nodes can be updated by the same trigger)
Vector<TreeReference> expandedReferences = exprEvalContext.expandReference(contextRef);
for (TreeReference treeReference : expandedReferences) {
triggerable.apply(mainInstance, exprEvalContext, treeReference, this);
}
}
public boolean evaluateConstraint(TreeReference ref, IAnswerData data) {
if (data == null) {
return true;
}
TreeElement node = mainInstance.resolveReference(ref);
Constraint c = node.getConstraint();
if (c == null) {
return true;
}
EvaluationContext ec = new EvaluationContext(exprEvalContext, ref);
ec.isConstraint = true;
ec.candidateValue = data;
return c.constraint.eval(mainInstance, ec);
}
public void setEvaluationContext(EvaluationContext ec) {
ec = new EvaluationContext(mainInstance, formInstances, ec);
initEvalContext(ec);
this.exprEvalContext = ec;
}
public EvaluationContext getEvaluationContext() {
return this.exprEvalContext;
}
private void initEvalContext(EvaluationContext ec) {
if (!ec.getFunctionHandlers().containsKey("jr:itext")) {
final FormDef f = this;
ec.addFunctionHandler(new IFunctionHandler() {
@Override
public String getName() {
return "jr:itext";
}
@Override
public Object eval(Object[] args, EvaluationContext ec) {
String textID = (String)args[0];
try {
//SUUUUPER HACKY
String form = ec.getOutputTextForm();
if (form != null) {
textID = textID + ";" + form;
String result = f.getLocalizer().getRawText(f.getLocalizer().getLocale(), textID);
return result == null ? "" : result;
} else {
String text = f.getLocalizer().getText(textID);
return text == null ? "[itext:" + textID + "]" : text;
}
} catch (NoSuchElementException nsee) {
return "[nolocale]";
}
}
@Override
public Vector getPrototypes() {
Class[] proto = {String.class};
Vector<Class[]> v = new Vector<Class[]>();
v.addElement(proto);
return v;
}
@Override
public boolean rawArgs() {
return false;
}
});
}
/* function to reverse a select value into the display label for that choice in the question it came from
*
* arg 1: select value
* arg 2: string xpath referring to origin question; must be absolute path
*
* this won't work at all if the original label needed to be processed/calculated in some way (<output>s, etc.) (is this even allowed?)
* likely won't work with multi-media labels
* _might_ work for itemsets, but probably not very well or at all; could potentially work better if we had some context info
* DOES work with localization
*
* it's mainly intended for the simple case of reversing a question with compile-time-static fields, for use inside an <output>
*/
if (!ec.getFunctionHandlers().containsKey("jr:choice-name")) {
final FormDef f = this;
ec.addFunctionHandler(new IFunctionHandler() {
@Override
public String getName() {
return "jr:choice-name";
}
@Override
public Object eval(Object[] args, EvaluationContext ec) {
try {
String value = (String)args[0];
String questionXpath = (String)args[1];
TreeReference ref = RestoreUtils.ref(questionXpath);
QuestionDef q = FormDef.findQuestionByRef(ref, f);
if (q == null || (q.getControlType() != Constants.CONTROL_SELECT_ONE &&
q.getControlType() != Constants.CONTROL_SELECT_MULTI)) {
return "";
}
System.out.println("here!!");
Vector<SelectChoice> choices = q.getChoices();
for (SelectChoice ch : choices) {
if (ch.getValue().equals(value)) {
//this is really not ideal. we should hook into the existing code (FormEntryPrompt) for pulling
//display text for select choices. however, it's hard, because we don't really have
//any context to work with, and all the situations where that context would be used
//don't make sense for trying to reverse a select value back to a label in an unrelated
//expression
String textID = ch.getTextID();
if (textID != null) {
return f.getLocalizer().getText(textID);
} else {
return ch.getLabelInnerText();
}
}
}
return "";
} catch (Exception e) {
throw new WrappedException("error in evaluation of xpath function [choice-name]", e);
}
}
@Override
public Vector getPrototypes() {
Class[] proto = {String.class, String.class};
Vector<Class[]> v = new Vector<Class[]>();
v.addElement(proto);
return v;
}
@Override
public boolean rawArgs() {
return false;
}
});
}
}
public String fillTemplateString(String template, TreeReference contextRef) {
return fillTemplateString(template, contextRef, new Hashtable());
}
/**
* Performs substitutions on place-holder template from form text by
* evaluating args in template using the current context.
*
* @param template String
* @param contextRef TreeReference
* @param variables Hashtable<String, ?>
* @return String with the all args in the template filled with appropriate
* context values.
*/
public String fillTemplateString(String template, TreeReference contextRef, Hashtable<String, ?> variables) {
// argument to value mapping
Hashtable<String, String> args = new Hashtable<String, String>();
int depth = 0;
// grab all template arguments that need to have substitutions performed
Vector outstandingArgs = Localizer.getArgs(template);
String templateAfterSubstitution;
// Step through outstandingArgs from the template, looking up the value
// they map to, evaluating that under the evaluation context and
// storing in the local args mapping.
// Then perform substitutions over the template until a fixpoint is found
while (outstandingArgs.size() > 0) {
for (int i = 0; i < outstandingArgs.size(); i++) {
String argName = (String)outstandingArgs.elementAt(i);
// lookup value an arg points to if it isn't in our local mapping
if (!args.containsKey(argName)) {
int ix = -1;
try {
ix = Integer.parseInt(argName);
} catch (NumberFormatException nfe) {
System.err.println("Warning: expect arguments to be numeric [" + argName + "]");
}
if (ix < 0 || ix >= outputFragments.size()) {
continue;
}
IConditionExpr expr = (IConditionExpr)outputFragments.elementAt(ix);
EvaluationContext ec = new EvaluationContext(exprEvalContext, contextRef);
ec.setOriginalContext(contextRef);
ec.setVariables(variables);
String value = expr.evalReadable(this.getMainInstance(), ec);
args.put(argName, value);
}
}
templateAfterSubstitution = Localizer.processArguments(template, args);
// The last substitution made no progress, probably because the
// argument isn't in outputFragments, so stop looping and
// attempting more subs!
if (template.equals(templateAfterSubstitution)) {
return template;
}
template = templateAfterSubstitution;
// Since strings being substituted might themselves have arguments that
// need to be further substituted, we must recompute the unperformed
// substitutions and continue to loop.
outstandingArgs = Localizer.getArgs(template);
if (depth++ >= TEMPLATING_RECURSION_LIMIT) {
throw new RuntimeException("Dependency cycle in <output>s; recursion limit exceeded!!");
}
}
return template;
}
/**
* Identify the itemset in the backend model, and create a set of SelectChoice
* objects at the current question reference based on the data in the model.
*
* Will modify the itemset binding to contain the relevant choices
*
* @param itemset The binding for an itemset, where the choices will be populated
* @param curQRef A reference to the current question's element, which will be
* used to determine the values to be chosen from.
*/
public void populateDynamicChoices(ItemsetBinding itemset, TreeReference curQRef) {
Vector<SelectChoice> choices = new Vector<SelectChoice>();
DataInstance fi;
if (itemset.nodesetRef.getInstanceName() != null) //We're not dealing with the default instance
{
fi = getNonMainInstance(itemset.nodesetRef.getInstanceName());
if (fi == null) {
throw new XPathException("Instance " + itemset.nodesetRef.getInstanceName() + " not found");
}
} else {
fi = getMainInstance();
}
Vector<TreeReference> matches = itemset.nodesetExpr.evalNodeset(fi,
new EvaluationContext(exprEvalContext, itemset.contextRef.contextualize(curQRef)));
if (matches == null) {
String instanceName = itemset.nodesetRef.getInstanceName();
if (instanceName == null) {
// itemset references a path rooted in the main instance
throw new XPathException("No items found at '" + itemset.nodesetRef + "'");
} else {
// itemset references a path rooted in a lookup table
throw new XPathException("Make sure the '" + instanceName +
"' lookup table is available, and that its contents are accessible to the current user.");
}
}
for (int i = 0; i < matches.size(); i++) {
TreeReference item = matches.elementAt(i);
String label = itemset.labelExpr.evalReadable(fi, new EvaluationContext(exprEvalContext, item));
String value = null;
TreeElement copyNode = null;
if (itemset.copyMode) {
copyNode = this.getMainInstance().resolveReference(itemset.copyRef.contextualize(item));
}
if (itemset.valueRef != null) {
value = itemset.valueExpr.evalReadable(fi, new EvaluationContext(exprEvalContext, item));
}
SelectChoice choice = new SelectChoice(label, value != null ? value : "dynamic:" + i, itemset.labelIsItext);
choice.setIndex(i);
if (itemset.copyMode)
choice.copyNode = copyNode;
choices.addElement(choice);
}
itemset.setChoices(choices, this.getLocalizer());
}
public QuestionPreloader getPreloader() {
return preloader;
}
public void setPreloader(QuestionPreloader preloads) {
this.preloader = preloads;
}
@Override
public void localeChanged(String locale, Localizer localizer) {
for (Enumeration e = children.elements(); e.hasMoreElements(); ) {
((IFormElement)e.nextElement()).localeChanged(locale, localizer);
}
}
public String toString() {
return getTitle();
}
/**
* Preload the Data Model with the preload values that are enumerated in the
* data bindings.
*/
public void preloadInstance(TreeElement node) {
// if (node.isLeaf()) {
IAnswerData preload = null;
if (node.getPreloadHandler() != null) {
preload = preloader.getQuestionPreload(node.getPreloadHandler(),
node.getPreloadParams());
}
if (preload != null) { // what if we want to wipe out a value in the
// instance?
node.setAnswer(preload);
}
// } else {
if (!node.isLeaf()) {
for (int i = 0; i < node.getNumChildren(); i++) {
TreeElement child = node.getChildAt(i);
if (child.getMult() != TreeReference.INDEX_TEMPLATE)
// don't preload templates; new repeats are preloaded as they're created
preloadInstance(child);
}
}
}
public boolean postProcessInstance() {
if(!isCompletedInstance) {
actionController.triggerActionsFromEvent(Action.EVENT_XFORMS_REVALIDATE, this);
}
return postProcessInstance(mainInstance.getRoot());
}
/**
* Iterate over the form's data bindings, and evaluate all post procesing
* calls.
*
* @return true if the instance was modified in any way. false otherwise.
*/
private boolean postProcessInstance(TreeElement node) {
// we might have issues with ordering, for example, a handler that writes a value to a node,
// and a handler that does something external with the node. if both handlers are bound to the
// same node, we need to make sure the one that alters the node executes first. deal with that later.
// can we even bind multiple handlers to the same node currently?
// also have issues with conditions. it is hard to detect what conditions are affected by the actions
// of the post-processor. normally, it wouldn't matter because we only post-process when we are exiting
// the form, so the result of any triggered conditions is irrelevant. however, if we save a form in the
// interim, post-processing occurs, and then we continue to edit the form. it seems like having conditions
// dependent on data written during post-processing is a bad practice anyway, and maybe we shouldn't support it.
if (node.isLeaf()) {
if (node.getPreloadHandler() != null) {
return preloader.questionPostProcess(node, node.getPreloadHandler(), node.getPreloadParams());
} else {
return false;
}
} else {
boolean instanceModified = false;
for (int i = 0; i < node.getNumChildren(); i++) {
TreeElement child = node.getChildAt(i);
if (child.getMult() != TreeReference.INDEX_TEMPLATE)
instanceModified |= postProcessInstance(child);
}
return instanceModified;
}
}
/**
* Reads the form definition object from the supplied stream.
*
* Requires that the instance has been set to a prototype of the instance that
* should be used for deserialization.
*/
@Override
public void readExternal(DataInputStream dis, PrototypeFactory pf) throws IOException, DeserializationException {
setID(ExtUtil.readInt(dis));
setName(ExtUtil.nullIfEmpty(ExtUtil.readString(dis)));
setTitle((String)ExtUtil.read(dis, new ExtWrapNullable(String.class), pf));
setChildren((Vector)ExtUtil.read(dis, new ExtWrapListPoly(), pf));
setInstance((FormInstance)ExtUtil.read(dis, FormInstance.class, pf));
setLocalizer((Localizer)ExtUtil.read(dis, new ExtWrapNullable(Localizer.class), pf));
Vector vcond = (Vector)ExtUtil.read(dis, new ExtWrapList(Condition.class), pf);
for (Enumeration e = vcond.elements(); e.hasMoreElements(); ) {
addTriggerable((Condition)e.nextElement());
}
Vector vcalc = (Vector)ExtUtil.read(dis, new ExtWrapList(Recalculate.class), pf);
for (Enumeration e = vcalc.elements(); e.hasMoreElements(); ) {
addTriggerable((Recalculate)e.nextElement());
}
finalizeTriggerables();
outputFragments = (Vector)ExtUtil.read(dis, new ExtWrapListPoly(), pf);
submissionProfiles = (Hashtable<String, SubmissionProfile>)ExtUtil.read(dis, new ExtWrapMap(String.class, SubmissionProfile.class), pf);
formInstances = (Hashtable<String, DataInstance>)ExtUtil.read(dis, new ExtWrapMap(String.class, new ExtWrapTagged()), pf);
extensions = (Vector)ExtUtil.read(dis, new ExtWrapListPoly(), pf);
setEvaluationContext(new EvaluationContext(null));
actionController = (ActionController)ExtUtil.read(dis, ActionController.class, pf);
}
/**
* meant to be called after deserialization and initialization of handlers
*
* @param newInstance true if the form is to be used for a new entry interaction,
* false if it is using an existing IDataModel
* @param isCompletedInstance true if this is an already completed instance we are editing
* (presumably in HQ) - so don't fire end of form event.
*/
public void initialize(boolean newInstance, boolean isCompletedInstance,
InstanceInitializationFactory factory) {
initialize(newInstance, isCompletedInstance, factory, null);
}
public void initialize(boolean newInstance, InstanceInitializationFactory factory) {
initialize(newInstance, false, factory, null);
}
public void initialize(boolean newInstance, InstanceInitializationFactory factory, String locale) {
initialize(newInstance, false, factory, locale);
}
/**
* meant to be called after deserialization and initialization of handlers
*
* @param newInstance true if the form is to be used for a new entry interaction,
* false if it is using an existing IDataModel
* @param locale The default locale in the current environment, if provided. Can be null
* to rely on the form's internal default.
*/
public void initialize(boolean newInstance, boolean isCompletedInstance,
InstanceInitializationFactory factory, String locale) {
for (Enumeration en = formInstances.keys(); en.hasMoreElements(); ) {
String instanceId = (String)en.nextElement();
DataInstance instance = formInstances.get(instanceId);
formInstances.put(instanceId, instance.initialize(factory, instanceId));
}
if (newInstance) {
// only preload new forms (we may have to revisit this)
preloadInstance(mainInstance.getRoot());
}
initLocale(locale);
if (newInstance) {
// only dispatch on a form's first opening, not subsequent loadings
// of saved instances. Ensures setvalues triggered by xform-ready,
// useful for recording form start dates.
actionController.triggerActionsFromEvent(Action.EVENT_XFORMS_READY, this);
}
this.isCompletedInstance = isCompletedInstance;
initAllTriggerables();
}
private void initLocale(String locale) {
if (localizer != null) {
if (locale == null || !localizer.hasLocale(locale)) {
if (localizer.getLocale() == null) {
localizer.setToDefault();
}
} else {
localizer.setLocale(locale);
}
}
}
/**
* Writes the form definition object to the supplied stream.
*/
@Override
public void writeExternal(DataOutputStream dos) throws IOException {
ExtUtil.writeNumeric(dos, getID());
ExtUtil.writeString(dos, ExtUtil.emptyIfNull(getName()));
ExtUtil.write(dos, new ExtWrapNullable(getTitle()));
ExtUtil.write(dos, new ExtWrapListPoly(getChildren()));
ExtUtil.write(dos, getMainInstance());
ExtUtil.write(dos, new ExtWrapNullable(localizer));
Vector<Condition> conditions = new Vector<Condition>();
Vector<Recalculate> recalcs = new Vector<Recalculate>();
for (int i = 0; i < triggerables.size(); i++) {
Triggerable t = triggerables.elementAt(i);
if (t instanceof Condition) {
conditions.addElement((Condition)t);
} else if (t instanceof Recalculate) {
recalcs.addElement((Recalculate)t);
}
}
ExtUtil.write(dos, new ExtWrapList(conditions));
ExtUtil.write(dos, new ExtWrapList(recalcs));
ExtUtil.write(dos, new ExtWrapListPoly(outputFragments));
ExtUtil.write(dos, new ExtWrapMap(submissionProfiles));
//for support of multi-instance forms
ExtUtil.write(dos, new ExtWrapMap(formInstances, new ExtWrapTagged()));
ExtUtil.write(dos, new ExtWrapListPoly(extensions));
ExtUtil.write(dos, actionController);
}
public void collapseIndex(FormIndex index,
Vector<Integer> indexes,
Vector<Integer> multiplicities,
Vector<IFormElement> elements) {
if (!index.isInForm()) {
return;
}
IFormElement element = this;
while (index != null) {
int i = index.getLocalIndex();
element = element.getChild(i);
indexes.addElement(DataUtil.integer(i));
multiplicities.addElement(DataUtil.integer(index.getInstanceIndex() == -1 ? 0 : index.getInstanceIndex()));
elements.addElement(element);
index = index.getNextLevel();
}
}
public FormIndex buildIndex(Vector indexes, Vector multiplicities, Vector elements) {
FormIndex cur = null;
Vector curMultiplicities = new Vector();
for (int j = 0; j < multiplicities.size(); ++j) {
curMultiplicities.addElement(multiplicities.elementAt(j));
}
Vector curElements = new Vector();
for (int j = 0; j < elements.size(); ++j) {
curElements.addElement(elements.elementAt(j));
}
for (int i = indexes.size() - 1; i >= 0; i
int ix = ((Integer)indexes.elementAt(i)).intValue();
int mult = ((Integer)multiplicities.elementAt(i)).intValue();
if (!(elements.elementAt(i) instanceof GroupDef && ((GroupDef)elements.elementAt(i)).getRepeat())) {
mult = -1;
}
cur = new FormIndex(cur, ix, mult, getChildInstanceRef(curElements, curMultiplicities));
curMultiplicities.removeElementAt(curMultiplicities.size() - 1);
curElements.removeElementAt(curElements.size() - 1);
}
return cur;
}
public int getNumRepetitions(FormIndex index) {
Vector<Integer> indexes = new Vector();
Vector<Integer> multiplicities = new Vector();
Vector<IFormElement> elements = new Vector();
if (!index.isInForm()) {
throw new RuntimeException("not an in-form index");
}
collapseIndex(index, indexes, multiplicities, elements);
if (!(elements.lastElement() instanceof GroupDef) || !((GroupDef)elements.lastElement()).getRepeat()) {
throw new RuntimeException("current element not a repeat");
}
//so painful
TreeElement templNode = mainInstance.getTemplate(index.getReference());
TreeReference parentPath = templNode.getParent().getRef().genericize();
TreeElement parentNode = mainInstance.resolveReference(parentPath.contextualize(index.getReference()));
return parentNode.getChildMultiplicity(templNode.getName());
}
//repIndex == -1 => next repetition about to be created
public FormIndex descendIntoRepeat(FormIndex index, int repIndex) {
int numRepetitions = getNumRepetitions(index);
Vector<Integer> indexes = new Vector();
Vector<Integer> multiplicities = new Vector();
Vector<IFormElement> elements = new Vector();
collapseIndex(index, indexes, multiplicities, elements);
if (repIndex == -1) {
repIndex = numRepetitions;
} else {
if (repIndex < 0 || repIndex >= numRepetitions) {
throw new RuntimeException("selection exceeds current number of repetitions");
}
}
multiplicities.setElementAt(DataUtil.integer(repIndex), multiplicities.size() - 1);
return buildIndex(indexes, multiplicities, elements);
}
/*
* (non-Javadoc)
*
* @see org.javarosa.core.model.IFormElement#getDeepChildCount()
*/
public int getDeepChildCount() {
int total = 0;
Enumeration e = children.elements();
while (e.hasMoreElements()) {
total += ((IFormElement)e.nextElement()).getDeepChildCount();
}
return total;
}
public void registerStateObserver(FormElementStateListener qsl) {
// NO. (Or at least not yet).
}
public void unregisterStateObserver(FormElementStateListener qsl) {
// NO. (Or at least not yet).
}
public Vector getChildren() {
return children;
}
public void setChildren(Vector children) {
this.children = (children == null ? new Vector() : children);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public int getID() {
return id;
}
@Override
public void setID(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Localizer getLocalizer() {
return localizer;
}
public Vector getOutputFragments() {
return outputFragments;
}
public void setOutputFragments(Vector outputFragments) {
this.outputFragments = outputFragments;
}
public Object getMetaData(String fieldName) {
if (fieldName.equals("DESCRIPTOR")) {
return name;
}
if (fieldName.equals("XMLNS")) {
return ExtUtil.emptyIfNull(mainInstance.schema);
} else {
throw new IllegalArgumentException();
}
}
public String[] getMetaDataFields() {
return new String[]{"DESCRIPTOR", "XMLNS"};
}
/**
* Link a deserialized instance back up with its parent FormDef. this allows select/select1 questions to be
* internationalizable in chatterbox, and (if using CHOICE_INDEX mode) allows the instance to be serialized
* to xml
*/
public void attachControlsToInstanceData() {
attachControlsToInstanceData(getMainInstance().getRoot());
}
private void attachControlsToInstanceData(TreeElement node) {
for (int i = 0; i < node.getNumChildren(); i++) {
attachControlsToInstanceData(node.getChildAt(i));
}
IAnswerData val = node.getValue();
Vector selections = null;
if (val instanceof SelectOneData) {
selections = new Vector();
selections.addElement(val.getValue());
} else if (val instanceof SelectMultiData) {
selections = (Vector)val.getValue();
}
if (selections != null) {
QuestionDef q = findQuestionByRef(node.getRef(), this);
if (q == null) {
throw new RuntimeException("FormDef.attachControlsToInstanceData: can't find question to link");
}
if (q.getDynamicChoices() != null) {
//droos: i think we should do something like initializing the itemset here, so that default answers
//can be linked to the selectchoices. however, there are complications. for example, the itemset might
//not be ready to be evaluated at form initialization; it may require certain questions to be answered
//first. e.g., if we evaluate an itemset and it has no choices, the xform engine will throw an error
//itemset TODO
}
for (int i = 0; i < selections.size(); i++) {
Selection s = (Selection)selections.elementAt(i);
s.attachChoice(q);
}
}
}
public static QuestionDef findQuestionByRef(TreeReference ref, IFormElement fe) {
if (fe instanceof FormDef) {
ref = ref.genericize();
}
if (fe instanceof QuestionDef) {
QuestionDef q = (QuestionDef)fe;
TreeReference bind = FormInstance.unpackReference(q.getBind());
return (ref.equals(bind) ? q : null);
} else {
for (int i = 0; i < fe.getChildren().size(); i++) {
QuestionDef ret = findQuestionByRef(ref, fe.getChild(i));
if (ret != null)
return ret;
}
return null;
}
}
/**
* Appearance isn't a valid attribute for form, but this method must be included
* as a result of conforming to the IFormElement interface.
*/
public String getAppearanceAttr() {
throw new RuntimeException("This method call is not relevant for FormDefs getAppearanceAttr ()");
}
/**
* Appearance isn't a valid attribute for form, but this method must be included
* as a result of conforming to the IFormElement interface.
*/
public void setAppearanceAttr(String appearanceAttr) {
throw new RuntimeException("This method call is not relevant for FormDefs setAppearanceAttr()");
}
@Override
public ActionController getActionController() {
return this.actionController;
}
/**
* Not applicable here.
*/
public String getLabelInnerText() {
return null;
}
/**
* Not applicable
*/
public String getTextID() {
return null;
}
/**
* Not applicable
*/
public void setTextID(String textID) {
throw new RuntimeException("This method call is not relevant for FormDefs [setTextID()]");
}
public void setDefaultSubmission(SubmissionProfile profile) {
submissionProfiles.put(DEFAULT_SUBMISSION_PROFILE, profile);
}
public void addSubmissionProfile(String submissionId, SubmissionProfile profile) {
submissionProfiles.put(submissionId, profile);
}
public SubmissionProfile getSubmissionProfile() {
//At some point these profiles will be set by the <submit> control in the form.
//In the mean time, though, we can only promise that the default one will be used.
return submissionProfiles.get(DEFAULT_SUBMISSION_PROFILE);
}
public <X extends XFormExtension> X getExtension(Class<X> extension) {
for (XFormExtension ex : extensions) {
if (ex.getClass().isAssignableFrom(extension)) {
return (X)ex;
}
}
X newEx;
try {
newEx = extension.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException("Illegally Structured XForm Extension " + extension.getName());
} catch (IllegalAccessException e) {
throw new RuntimeException("Illegally Structured XForm Extension " + extension.getName());
}
extensions.addElement(newEx);
return newEx;
}
/**
* Frees all of the components of this form which are no longer needed once it is completed.
*
* Once this is called, the form is no longer capable of functioning, but all data should be retained.
*/
public void seal() {
triggerables = null;
triggerIndex = null;
conditionRepeatTargetIndex = null;
//We may need ths one, actually
exprEvalContext = null;
}
}
|
package org.typemeta.funcj.util;
import org.typemeta.funcj.data.Tuple2;
import java.util.Map;
import java.util.stream.Stream;
/**
* Utility methods relating to {@link Stream}s.
*/
public abstract class Streams {
/**
* Create a stream of {@link Tuple2}s from a {@link Map}.
* @param m the map
* @param <K> the map key type
* @param <V> the map value type
* @return a stream of {@code Tuple2}s
*/
public static <K, V> Stream<Tuple2<K, V>> of(Map<K, V> m) {
return m.entrySet().stream().map(en -> Tuple2.of(en.getKey(), en.getValue()));
}
}
|
package ie.dit;
import ddf.minim.Minim; //import the minim library
import ddf.minim.AudioPlayer;
import java.util.ArrayList;
import processing.core.PApplet; //import the processing PApplet
import processing.core.PVector; //import the processing PVector
public class Helicopter extends GameObject { //create the Helicopter class
//declare variables
public int health;
public PVector forward;
public ArrayList<GameObject> objects;
public float rotor_theta, shadow_scale, fireRate = 1f, timeSinceLastEvent = 0;
public Minim minim; // Required to use Minim.
public AudioPlayer snd_shoot;
Helicopter(PApplet applet) {
super(applet);
w = 30;
h = 40;
health = 50;
rotor_theta = 0.0f;
shadow_scale = 0.6f;
location = new PVector(300, 300);
objects = new ArrayList<GameObject>();
minim = new Minim(this.applet); // Required to use Minim.
snd_shoot = minim.loadFile("data/shoot.wav");
} // End Constructor.
public void update() {
rotor_theta += 0.5f;
fire_bullet();
for (int i = 0; i < objects.size(); ++i) {
objects.get(i).run();
if (!objects.get(i).alive)
objects.remove(i);
} // End loop.
} // End update.
public void display() {
applet.noStroke();
draw_helicopter_shadow();
draw_rotor_shadow();
draw_helicopter();
draw_rotor();
draw_health_bar();
applet.noFill();
//applet.noStroke();
} // End Display.
private void draw_helicopter_shadow() {
applet.pushMatrix();
applet.translate( (location.x + (w/2)) + 15, (location.y + (h/2)) + 10);
applet.rotate(theta);
applet.scale(shadow_scale);
applet.fill( 0, 0, 0, 120 );
applet.rect(-15, h, 30, 3); // Tail fin.
applet.rect(-3,h-20, 6, h-20); // Tail.
applet.ellipse(0,0, w, h); // Body.
applet.popMatrix();
} // End draw_helicopter_shadow.
private void draw_rotor_shadow() {
applet.pushMatrix();
applet.translate( (location.x + (w/2)) + 15, (location.y + (h/2)) + 10);
applet.rotate(rotor_theta);
applet.scale(shadow_scale);
applet.fill(0);
applet.rect(-1.5f, -40, 3, 80); // Vertical rotor.
applet.rect(-40, -1.5f, 80, 3); // Horizontal rotor.
applet.popMatrix();
} // End draw_rotor_shadow.
private void draw_helicopter() {
applet.pushMatrix();
applet.translate(location.x + (w/2), location.y + (h/2));
applet.rotate(theta);
applet.fill( colour.getRed(), colour.getGreen(), colour.getBlue(), colour.getAlpha() );
applet.rect(-15, h, 30, 3); // Tail fin.
applet.rect(-3,h-20, 6, h-20); // Tail.
applet.ellipse(0,0, w, h); // Body.
applet.popMatrix();
} // End draw_helicopter.
private void draw_rotor() {
applet.pushMatrix();
applet.translate(location.x + (w/2), location.y + (h/2));
applet.rotate(rotor_theta);
applet.fill(0);
applet.rect(-1.5f, -40, 3, 80); // Vertical rotor.
applet.rect(-40, -1.5f, 80, 3); // Horizontal rotor.
applet.popMatrix();
} // End draw_rotor.
public void draw_health_bar() {
applet.pushMatrix();
applet.translate(location.x, location.y);
applet.fill(255, 0, 0, 255);
applet.rect(-health/3, 20, health, 5);
applet.popMatrix();
} // End draw_health_bar.
public void fire_bullet() {
if(applet.millis() - timeSinceLastEvent >= 1000/fireRate){
snd_shoot.rewind();
snd_shoot.play();
objects.add( new Bullet(applet, location.x+(w/2), location.y+(h/2), theta) );
timeSinceLastEvent = applet.millis();
}
} // End fire_bullet.
} // End Helicopter Class.
|
package boa.compiler;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.Map.Entry;
import org.scannotation.AnnotationDB;
import boa.aggregators.AggregatorSpec;
import boa.functions.FunctionSpec;
import boa.types.*;
import boa.types.proto.*;
import boa.types.proto.enums.*;
import boa.compiler.ast.Operand;
public class SymbolTable {
private static HashMap<String, Class<?>> aggregators;
private static final Map<Class<?>, BoaType> protomap;
private static Map<String, BoaType> idmap;
private static final Map<String, BoaType> globals;
private static FunctionTrie globalFunctions;
private FunctionTrie functions;
private Map<String, BoaType> locals;
private String id;
private Operand operand;
private Stack<BoaType> operandType = new Stack<BoaType>();
private boolean needsBoxing;
private boolean isBeforeVisitor = false;
static {
aggregators = new HashMap<String, Class<?>>();
// this maps the Java types in protocol buffers into Boa types
protomap = new HashMap<Class<?>, BoaType>();
protomap.put(int.class, new BoaInt());
protomap.put(long.class, new BoaInt());
protomap.put(float.class, new BoaFloat());
protomap.put(double.class, new BoaFloat());
protomap.put(boolean.class, new BoaBool());
protomap.put(byte[].class, new BoaBytes());
protomap.put(Object.class, new BoaString());
// variables with a global scope
globals = new HashMap<String, BoaType>();
globals.put("input", new ProjectProtoTuple());
globals.put("true", new BoaBool());
globals.put("false", new BoaBool());
globals.put("PI", new BoaFloat());
globals.put("Inf", new BoaFloat());
globals.put("inf", new BoaFloat());
globals.put("NaN", new BoaFloat());
globals.put("nan", new BoaFloat());
// this maps scalar Boa scalar types names to their classes
idmap = new HashMap<String, BoaType>();
idmap.put("any", new BoaAny());
idmap.put("none", null);
idmap.put("bool", new BoaBool());
idmap.put("int", new BoaInt());
idmap.put("float", new BoaFloat());
idmap.put("time", new BoaTime());
idmap.put("fingerprint", new BoaFingerprint());
idmap.put("string", new BoaString());
idmap.put("bytes", new BoaBytes());
idmap.put("ASTRoot", new ASTRootProtoTuple());
idmap.put("Bug", new BugProtoTuple());
idmap.put("BugRepository", new BugRepositoryProtoTuple());
idmap.put("BugStatus", new IssueKindProtoMap());
idmap.put("ChangedFile", new ChangedFileProtoTuple());
idmap.put("ChangeKind", new ChangeKindProtoMap());
idmap.put("CodeRepository", new CodeRepositoryProtoTuple());
idmap.put("CommentKind", new CommentKindProtoMap());
idmap.put("Comment", new CommentProtoTuple());
idmap.put("Declaration", new DeclarationProtoTuple());
idmap.put("ExpressionKind", new ExpressionKindProtoMap());
idmap.put("Expression", new ExpressionProtoTuple());
idmap.put("FileKind", new FileKindProtoMap());
idmap.put("Method", new MethodProtoTuple());
idmap.put("ModifierKind", new ModifierKindProtoMap());
idmap.put("Modifier", new ModifierProtoTuple());
idmap.put("Namespace", new NamespaceProtoTuple());
idmap.put("Person", new PersonProtoTuple());
idmap.put("Project", new ProjectProtoTuple());
idmap.put("RepositoryKind", new RepositoryKindProtoMap());
idmap.put("Revision", new RevisionProtoTuple());
idmap.put("StatementKind", new StatementKindProtoMap());
idmap.put("Statement", new StatementProtoTuple());
idmap.put("TypeKind", new TypeKindProtoMap());
idmap.put("Type", new TypeProtoTuple());
idmap.put("Variable", new VariableProtoTuple());
idmap.put("Visibility", new VisibilityProtoMap());
globalFunctions = new FunctionTrie();
// these generic functions require more finagling than can currently be
// (easily) done with a static method, so they are handled with macros
// FIXME rdyer - def(protolist[i]) should generate "i < protolist.size()"
globalFunctions.addFunction("def", new BoaFunction(new BoaBool(), new BoaType[] { new BoaAny() }, "(${0} != null)"));
globalFunctions.addFunction("len", new BoaFunction(new BoaInt(), new BoaType[] { new BoaProtoList(new BoaScalar()) }, "${0}.size()"));
globalFunctions.addFunction("len", new BoaFunction(new BoaInt(), new BoaType[] { new BoaArray(new BoaScalar()) }, "${0}.length"));
globalFunctions.addFunction("len", new BoaFunction(new BoaInt(), new BoaType[] { new BoaMap(new BoaScalar(), new BoaScalar()) }, "${0}.keySet().size()"));
globalFunctions.addFunction("len", new BoaFunction(new BoaInt(), new BoaType[] { new BoaStack(new BoaScalar()) }, "${0}.size()"));
globalFunctions.addFunction("len", new BoaFunction(new BoaInt(), new BoaType[] { new BoaString() }, "${0}.length()"));
globalFunctions.addFunction("len", new BoaFunction(new BoaInt(), new BoaType[] { new BoaBytes() }, "${0}.length"));
// map functions
globalFunctions.addFunction("haskey", new BoaFunction(new BoaBool(), new BoaType[] { new BoaMap(new BoaScalar(), new BoaScalar()), new BoaScalar() }, "${0}.containsKey(${1})"));
globalFunctions.addFunction("keys", new BoaFunction(new BoaArray(new BoaTypeVar("K")), new BoaType[] { new BoaMap(new BoaTypeVar("V"), new BoaTypeVar("K")) }, "${0}.keySet().toArray(new ${K}[0])"));
globalFunctions.addFunction("lookup", new BoaFunction(new BoaTypeVar("V"), new BoaType[] { new BoaMap(new BoaTypeVar("V"), new BoaTypeVar("K")), new BoaTypeVar("K"), new BoaTypeVar("V") }, "(${0}.containsKey(${1}) ? ${0}.get(${1}) : ${2})"));
globalFunctions.addFunction("remove", new BoaFunction(new BoaAny(), new BoaType[] { new BoaMap(new BoaTypeVar("V"), new BoaTypeVar("K")), new BoaTypeVar("K") }, "${0}.remove(${1})"));
globalFunctions.addFunction("clear", new BoaFunction(new BoaAny(), new BoaType[] { new BoaMap(new BoaTypeVar("V"), new BoaTypeVar("K")) }, "${0}.clear()"));
globalFunctions.addFunction("regex", new BoaFunction(new BoaString(), new BoaType[] { new BoaName(new BoaScalar()), new BoaInt() }, "boa.functions.BoaSpecialIntrinsics.regex(\"${0}\", ${1})"));
globalFunctions.addFunction("regex", new BoaFunction(new BoaString(), new BoaType[] { new BoaName(new BoaScalar()) }, "boa.functions.BoaSpecialIntrinsics.regex(\"${0}\")"));
// these fingerprints are identity functions
globalFunctions.addFunction("fingerprintof", new BoaFunction(new BoaFingerprint(), new BoaScalar[] { new BoaInt() }));
globalFunctions.addFunction("fingerprintof", new BoaFunction(new BoaFingerprint(), new BoaScalar[] { new BoaTime() }));
// visitors
globalFunctions.addFunction("visit", new BoaFunction(new BoaAny(), new BoaType[] { new BoaScalar(), new BoaVisitor() }, "${1}.visit(${0})"));
globalFunctions.addFunction("visit", new BoaFunction(new BoaAny(), new BoaType[] { new BoaScalar() }, "visit(${0})"));
globalFunctions.addFunction("_cur_visitor", new BoaFunction(new BoaVisitor(), new BoaType[] { }, "this"));
globalFunctions.addFunction("ast_len", new BoaFunction(new BoaInt(), new BoaType[] { new BoaAny() }, "boa.functions.BoaAstIntrinsics.lenVisitor.getCount(${0})"));
// stack functions
globalFunctions.addFunction("push", new BoaFunction(new BoaAny(), new BoaType[] { new BoaStack(new BoaTypeVar("V")), new BoaTypeVar("V") }, "${0}.push(${1})"));
globalFunctions.addFunction("pop", new BoaFunction(new BoaTypeVar("V"), new BoaType[] { new BoaStack(new BoaTypeVar("V")) }, "boa.functions.BoaIntrinsics.stack_pop(${0})"));
globalFunctions.addFunction("peek", new BoaFunction(new BoaTypeVar("V"), new BoaType[] { new BoaStack(new BoaTypeVar("V")) }, "boa.functions.BoaIntrinsics.stack_peek(${0})"));
globalFunctions.addFunction("clear", new BoaFunction(new BoaAny(), new BoaType[] { new BoaStack(new BoaTypeVar("V")) }, "${0}.clear()"));
// casts from enums to string
globalFunctions.addFunction("string", new BoaFunction(new BoaString(), new BoaType[] { new IssueKindProtoMap() }, "${0}.name()"));
globalFunctions.addFunction("string", new BoaFunction(new BoaString(), new BoaType[] { new ChangeKindProtoMap() }, "${0}.name()"));
globalFunctions.addFunction("string", new BoaFunction(new BoaString(), new BoaType[] { new CommentKindProtoMap() }, "${0}.name()"));
globalFunctions.addFunction("string", new BoaFunction(new BoaString(), new BoaType[] { new ExpressionKindProtoMap() }, "${0}.name()"));
globalFunctions.addFunction("string", new BoaFunction(new BoaString(), new BoaType[] { new FileKindProtoMap() }, "${0}.name()"));
globalFunctions.addFunction("string", new BoaFunction(new BoaString(), new BoaType[] { new ModifierKindProtoMap() }, "${0}.name()"));
globalFunctions.addFunction("string", new BoaFunction(new BoaString(), new BoaType[] { new RepositoryKindProtoMap() }, "${0}.name()"));
globalFunctions.addFunction("string", new BoaFunction(new BoaString(), new BoaType[] { new StatementKindProtoMap() }, "${0}.name()"));
globalFunctions.addFunction("string", new BoaFunction(new BoaString(), new BoaType[] { new TypeKindProtoMap() }, "${0}.name()"));
globalFunctions.addFunction("string", new BoaFunction(new BoaString(), new BoaType[] { new VisibilityProtoMap() }, "${0}.name()"));
// string to bool
globalFunctions.addFunction("bool", new BoaFunction("boa.functions.BoaCasts.stringToBoolean", new BoaBool(), new BoaScalar[] { new BoaString() }));
// bool to int
globalFunctions.addFunction("int", new BoaFunction("boa.functions.BoaCasts.booleanToLong", new BoaInt(), new BoaScalar[] { new BoaBool() }));
// float to int
globalFunctions.addFunction("int", new BoaFunction(new BoaInt(), new BoaScalar[] { new BoaFloat() }, "(long)${0}"));
// time to int
globalFunctions.addFunction("int", new BoaFunction(new BoaInt(), new BoaScalar[] { new BoaTime() }, "${0}"));
// fingerprint to int
globalFunctions.addFunction("int", new BoaFunction(new BoaInt(), new BoaScalar[] { new BoaFingerprint() }, "${0}"));
// string to int
globalFunctions.addFunction("int", new BoaFunction("java.lang.Long.decode", new BoaInt(), new BoaScalar[] { new BoaString() }));
// string to int with param base
globalFunctions.addFunction("int", new BoaFunction(new BoaInt(), new BoaScalar[] { new BoaString(), new BoaInt() }, "java.lang.Long.parseLong(${0}, (int)${1})"));
// bytes to int with param encoding format
globalFunctions.addFunction("int", new BoaFunction("boa.functions.BoaCasts.bytesToLong", new BoaInt(), new BoaScalar[] { new BoaBytes(), new BoaString() }));
// int to float
globalFunctions.addFunction("float", new BoaFunction(new BoaFloat(), new BoaScalar[] { new BoaInt() }, "(double)${0}"));
// string to float
globalFunctions.addFunction("float", new BoaFunction("java.lang.Double.parseDouble", new BoaFloat(), new BoaScalar[] { new BoaString() }));
// int to time
globalFunctions.addFunction("time", new BoaFunction(new BoaTime(), new BoaScalar[] { new BoaInt() }, "${0}"));
// string to time
globalFunctions.addFunction("time", new BoaFunction("boa.functions.BoaCasts.stringToTime", new BoaTime(), new BoaScalar[] { new BoaString() }));
// string to time
globalFunctions.addFunction("time", new BoaFunction("boa.functions.BoaCasts.stringToTime", new BoaTime(), new BoaScalar[] { new BoaString(), new BoaString() }));
// int to fingerprint
globalFunctions.addFunction("fingerprint", new BoaFunction(new BoaFingerprint(), new BoaScalar[] { new BoaInt() }, "${0}"));
// string to fingerprint
globalFunctions.addFunction("fingerprint", new BoaFunction("java.lang.Long.parseLong", new BoaInt(), new BoaScalar[] { new BoaString() }));
// string to fingerprint with param base
globalFunctions.addFunction("fingerprint", new BoaFunction("java.lang.Long.parseLong", new BoaInt(), new BoaScalar[] { new BoaString(), new BoaInt() }));
// bytes to fingerprint
globalFunctions.addFunction("fingerprint", new BoaFunction("boa.functions.BoaCasts.bytesToFingerprint", new BoaFingerprint(), new BoaScalar[] { new BoaBytes() }));
// bool to string
globalFunctions.addFunction("string", new BoaFunction("java.lang.Boolean.toString", new BoaString(), new BoaScalar[] { new BoaBool() }));
// int to string
globalFunctions.addFunction("string", new BoaFunction("java.lang.Long.toString", new BoaString(), new BoaScalar[] { new BoaInt() }));
// int to string with parameter base
globalFunctions.addFunction("string", new BoaFunction("boa.functions.BoaCasts.longToString", new BoaString(), new BoaScalar[] { new BoaInt(), new BoaInt() }));
// float to string
globalFunctions.addFunction("string", new BoaFunction("java.lang.Double.toString", new BoaString(), new BoaScalar[] { new BoaFloat() }));
// time to string
globalFunctions.addFunction("string", new BoaFunction("boa.functions.BoaCasts.timeToString", new BoaString(), new BoaScalar[] { new BoaTime() }));
// fingerprint to string
globalFunctions.addFunction("string", new BoaFunction("java.lang.Long.toHexString", new BoaString(), new BoaScalar[] { new BoaFingerprint() }));
// bytes to string
globalFunctions.addFunction("string", new BoaFunction("new java.lang.String", new BoaString(), new BoaScalar[] { new BoaBytes() }));
// bytes to string
globalFunctions.addFunction("string", new BoaFunction("new java.lang.String", new BoaString(), new BoaScalar[] { new BoaBytes(), new BoaString() }));
// int to bytes with param encoding format
globalFunctions.addFunction("bytes", new BoaFunction("boa.functions.BoaCasts.longToBytes", new BoaInt(), new BoaScalar[] { new BoaInt(), new BoaString() }));
// fingerprint to bytes
globalFunctions.addFunction("bytes", new BoaFunction("boa.functions.BoaCasts.fingerprintToBytes", new BoaBytes(), new BoaScalar[] { new BoaFingerprint() }));
// string to bytes
globalFunctions.addFunction("bytes", new BoaFunction("boa.functions.BoaCasts.stringToBytes", new BoaBytes(), new BoaScalar[] { new BoaString() }));
/* expose the java.lang.Math class to Sawzall */
globalFunctions.addFunction("highbit", new BoaFunction("java.lang.Long.highestOneBit", new BoaInt(), new BoaScalar[] { new BoaInt() }));
// abs just needs to be overloaded
globalFunctions.addFunction("abs", new BoaFunction("java.lang.Math.abs", new BoaFloat(), new BoaScalar[] { new BoaInt() }));
globalFunctions.addFunction("abs", new BoaFunction("java.lang.Math.abs", new BoaFloat(), new BoaScalar[] { new BoaFloat() }));
// expose the rest of the unary functions
for (final String s : Arrays.asList("log", "log10", "exp", "sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "cosh", "sinh", "tanh", "ceil", "floor", "round", "cbrt", "expm1", "log1p", "rint", "signum", "ulp"))
globalFunctions.addFunction(s, new BoaFunction("java.lang.Math." + s, new BoaFloat(), new BoaScalar[] { new BoaFloat() }));
// expose the binary functions
for (final String s : Arrays.asList("pow", "atan2", "hypot"))
globalFunctions.addFunction(s, new BoaFunction("java.lang.Math." + s, new BoaFloat(), new BoaScalar[] { new BoaFloat(), new BoaFloat() }));
// these three have capitals in the name
globalFunctions.addFunction("ieeeremainder", new BoaFunction("java.lang.Math.IEEEremainder", new BoaFloat(), new BoaScalar[] { new BoaFloat(), new BoaFloat() }));
globalFunctions.addFunction("todegrees", new BoaFunction("java.lang.Math.toDegrees", new BoaFloat(), new BoaScalar[] { new BoaFloat() }));
globalFunctions.addFunction("toradians", new BoaFunction("java.lang.Math.toRadians", new BoaFloat(), new BoaScalar[] { new BoaFloat() }));
// max and min
for (final String s : Arrays.asList("max", "min"))
for (final BoaScalar t : Arrays.asList(new BoaInt(), new BoaFloat()))
globalFunctions.addFunction(s, new BoaFunction("java.lang.Math." + s, t, new BoaScalar[] { t, t }));
globalFunctions.addFunction("max", new BoaFunction(new BoaTime(), new BoaScalar[] { new BoaTime(), new BoaTime() }, "(${0} > ${1} ? ${0} : ${1})"));
globalFunctions.addFunction("min", new BoaFunction(new BoaTime(), new BoaScalar[] { new BoaTime(), new BoaTime() }, "(${0} < ${1} ? ${0} : ${1})"));
globalFunctions.addFunction("max", new BoaFunction(new BoaString(), new BoaScalar[] { new BoaString(), new BoaString() }, "(${0}.compareTo(${1}) > 0 ? ${0} : ${1})"));
globalFunctions.addFunction("min", new BoaFunction(new BoaString(), new BoaScalar[] { new BoaString(), new BoaString() }, "(${0}.compareTo(${1}) < 0 ? ${0} : ${1})"));
}
public SymbolTable() {
// variables with a local scope
this.locals = new HashMap<String, BoaType>();
functions = new FunctionTrie();
}
public static void initialize(final List<URL> libs) throws IOException {
importLibs(libs);
}
public SymbolTable cloneNonLocals() throws IOException {
SymbolTable st = new SymbolTable();
st.functions = this.functions;
st.locals = new HashMap<String, BoaType>(this.locals);
st.isBeforeVisitor = this.isBeforeVisitor;
return st;
}
public void set(final String id, final BoaType type) {
this.set(id, type, false);
}
public void set(final String id, final BoaType type, final boolean global) {
if (idmap.containsKey(id))
throw new RuntimeException(id + " already declared as type " + idmap.get(id));
if (type instanceof BoaFunction)
this.setFunction(id, (BoaFunction) type);
if (global)
globals.put(id, type);
else
this.locals.put(id, type);
}
public boolean hasGlobal(final String id) {
return globals.containsKey(id);
}
public boolean hasLocal(final String id) {
return this.locals.containsKey(id);
}
public BoaType get(final String id) {
if (idmap.containsKey(id))
return idmap.get(id);
if (globals.containsKey(id))
return globals.get(id);
if (this.locals.containsKey(id))
return this.locals.get(id);
throw new RuntimeException("no such identifier " + id);
}
public boolean hasType(final String id) {
return idmap.containsKey(id);
}
public static BoaType getType(final String id) {
if (idmap.containsKey(id))
return idmap.get(id);
if (id.startsWith("array of "))
return new BoaArray(getType(id.substring("array of ".length()).trim()));
if (id.startsWith("map"))
return new BoaMap(getType(id.substring(id.indexOf(" of ") + " of ".length()).trim()),
getType(id.substring(id.indexOf("[") + 1, id.indexOf("]")).trim()));
throw new RuntimeException("no such type " + id);
}
public void setType(final String id, final BoaType boaType) {
idmap.put(id, boaType);
}
private static void importAggregator(final Class<?> clazz) {
if (!clazz.isAnnotationPresent(AggregatorSpec.class))
return;
final AggregatorSpec annotation = clazz.getAnnotation(AggregatorSpec.class);
if (annotation == null)
return;
final String type = annotation.type();
if (type.equals("any"))
aggregators.put(annotation.name(), clazz);
else
aggregators.put(annotation.name() + ":" + type, clazz);
}
private static void importAggregator(final String c) {
try {
importAggregator(Class.forName(c));
} catch (final ClassNotFoundException e) {
throw new RuntimeException("no such class " + c, e);
}
}
public Class<?> getAggregator(final String name, final BoaScalar type) {
if (aggregators.containsKey(name + ":" + type))
return aggregators.get(name + ":" + type);
else if (aggregators.containsKey(name))
return aggregators.get(name);
else
throw new RuntimeException("no such aggregator " + name + " of " + type);
}
public List<Class<?>> getAggregators(final String name, final BoaType type) {
final List<Class<?>> aggregators = new ArrayList<Class<?>>();
if (type instanceof BoaTuple)
for (final BoaType subType : ((BoaTuple) type).getTypes())
aggregators.add(this.getAggregator(name, (BoaScalar) subType));
else
aggregators.add(this.getAggregator(name, (BoaScalar) type));
return aggregators;
}
private static void importFunction(final Method m) {
final FunctionSpec annotation = m.getAnnotation(FunctionSpec.class);
if (annotation == null)
return;
final String[] formalParameters = annotation.formalParameters();
final BoaType[] formalParameterTypes = new BoaType[formalParameters.length];
for (int i = 0; i < formalParameters.length; i++) {
final String id = formalParameters[i];
// check for varargs
if (id.endsWith("..."))
formalParameterTypes[i] = new BoaVarargs(getType(id.substring(0, id.indexOf('.'))));
else
formalParameterTypes[i] = getType(id);
}
globalFunctions.addFunction(annotation.name(), new BoaFunction(m.getDeclaringClass().getCanonicalName() + '.' + m.getName(), getType(annotation.returnType()), formalParameterTypes));
}
private static void importFunctions(final Class<?> c) {
for (final Method m : c.getMethods())
if (m.isAnnotationPresent(FunctionSpec.class))
importFunction(m);
}
private static void importFunctions(final String c) {
try {
importFunctions(Class.forName(c));
} catch (final ClassNotFoundException e) {
throw new RuntimeException("no such class " + c, e);
}
}
private static void importLibs(final List<URL> urls) throws IOException {
// load built-in functions
final Class<?>[] builtinFuncs = {
boa.functions.BoaAstIntrinsics.class,
boa.functions.BoaIntrinsics.class,
boa.functions.BoaMetricIntrinsics.class,
boa.functions.BoaModifierIntrinsics.class,
boa.functions.BoaCasts.class,
boa.functions.BoaEncodingIntrinsics.class,
boa.functions.BoaMathIntrinsics.class,
boa.functions.BoaSortIntrinsics.class,
boa.functions.BoaSpecialIntrinsics.class,
boa.functions.BoaStringIntrinsics.class,
boa.functions.BoaTimeIntrinsics.class
};
for (final Class<?> c : builtinFuncs)
importFunctions(c);
// load built-in aggregators
final Class<?>[] builtinAggs = {
boa.aggregators.BottomAggregator.class,
boa.aggregators.CollectionAggregator.class,
boa.aggregators.ConfidenceIntervalAggregator.class,
boa.aggregators.DistinctAggregator.class,
boa.aggregators.FloatHistogramAggregator.class,
boa.aggregators.FloatMeanAggregator.class,
boa.aggregators.FloatQuantileAggregator.class,
boa.aggregators.FloatSumAggregator.class,
boa.aggregators.IntHistogramAggregator.class,
boa.aggregators.IntMeanAggregator.class,
boa.aggregators.IntQuantileAggregator.class,
boa.aggregators.IntSumAggregator.class,
boa.aggregators.KurtosisAggregator.class,
boa.aggregators.LogAggregator.class,
boa.aggregators.MaximumAggregator.class,
boa.aggregators.MedianAggregator.class,
boa.aggregators.MinimumAggregator.class,
boa.aggregators.SetAggregator.class,
boa.aggregators.SkewnessAggregator.class,
boa.aggregators.StatisticsAggregator.class,
boa.aggregators.StDevAggregator.class,
boa.aggregators.TextAggregator.class,
boa.aggregators.TopAggregator.class,
boa.aggregators.UniqueAggregator.class,
boa.aggregators.VarianceAggregator.class,
};
for (final Class<?> c : builtinAggs)
importAggregator(c);
// also check any libs passed into the compiler
if (urls.size() > 0) {
final AnnotationDB db = new AnnotationDB();
db.setScanMethodAnnotations(true);
db.setScanClassAnnotations(true);
// db.setScanPackages(new String[] {"boa.aggregators", "boa.functions"});
for (final URL url : urls)
db.scanArchives(url);
final Map<String, Set<String>> annotationIndex = db.getAnnotationIndex();
for (final String s : annotationIndex.get(AggregatorSpec.class.getCanonicalName()))
importAggregator(s);
for (final String s : annotationIndex.get(FunctionSpec.class.getCanonicalName()))
importFunctions(s);
}
}
public BoaFunction getFunction(final String id) {
return this.getFunction(id, new BoaType[0]);
}
public BoaFunction getFunction(final String id, final List<BoaType> formalParameters) {
return this.getFunction(id, formalParameters.toArray(new BoaType[formalParameters.size()]));
}
public BoaFunction getFunction(final String id, final BoaType[] formalParameters) {
BoaFunction function = globalFunctions.getFunction(id, formalParameters);
if (function == null)
function = this.functions.getFunction(id, formalParameters);
if (function == null)
throw new RuntimeException("no such function " + id + "(" + Arrays.toString(formalParameters) + ")");
return function;
}
public boolean hasGlobalFunction(final String id) {
return globalFunctions.hasFunction(id);
}
public boolean hasLocalFunction(final String id) {
return functions.hasFunction(id);
}
public void setFunction(final String id, final BoaFunction boaFunction) {
this.functions.addFunction(id, boaFunction);
}
public boolean hasCast(final BoaType from, final BoaType to) {
try {
this.getFunction(to.toString(), new BoaType[] { from });
return true;
} catch (final RuntimeException e) {
return false;
}
}
public BoaFunction getCast(final BoaType from, final BoaType to) {
return this.getFunction(to.toString(), new BoaType[] { from });
}
public void setId(final String id) {
this.id = id;
}
public String getId() {
return this.id;
}
public void setOperand(final Operand operand) {
this.operand = operand;
}
public Operand getOperand() {
return this.operand;
}
public void setOperandType(final BoaType operandType) {
this.operandType.push(operandType);
}
public BoaType getOperandType() {
return this.operandType.pop();
}
public void setNeedsBoxing(final boolean needsBoxing) {
this.needsBoxing = needsBoxing;
}
public boolean getNeedsBoxing() {
return this.needsBoxing;
}
public void setIsBeforeVisitor(final boolean isBeforeVisitor) {
this.isBeforeVisitor = isBeforeVisitor;
}
public boolean getIsBeforeVisitor() {
return this.isBeforeVisitor;
}
@Override
public String toString() {
final List<String> r = new ArrayList<String>();
for (final Entry<String, BoaType> entry : this.locals.entrySet())
r.add(entry.getKey() + ":" + entry.getValue());
return r.toString();
}
}
|
package org.jscep.transaction;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;
import org.jscep.util.HexUtil;
/**
* This class represents the <code>senderNonce</code> and <code>recipientNonce</code>
* types.
*
* @author David Grant
*/
public class Nonce {
private static final Random RND = new SecureRandom();
private byte[] nonce;
/**
* Creates a new nonce with the given byte array.
*
* @param nonce the byte array.
*/
public Nonce(byte[] nonce) {
this.nonce = nonce;
}
/**
* Returns the nonce byte array.
*
* @return the byte array.
*/
public byte[] getBytes() {
return nonce;
}
@Override
public String toString() {
return HexUtil.toHexString(nonce);
}
/**
* Generates a new random Nonce.
* <p>
* This method does not guarantee that multiple invocations will produce a different
* nonce, as the byte generation is provided by a SecureRandom instance.
*
* @return the generated nonce.
* @see java.security.SecureRandom
*/
public static Nonce nextNonce() {
byte[] bytes = new byte[16];
RND.nextBytes(bytes);
return new Nonce(bytes);
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Nonce nonce1 = (Nonce) o;
if (!Arrays.equals(nonce, nonce1.nonce)) return false;
return true;
}
@Override
public int hashCode() {
return nonce != null ? Arrays.hashCode(nonce) : 0;
}
}
|
package processing.app;
import static processing.app.I18n._;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DefaultCaret;
import processing.app.debug.TextAreaFIFO;
import processing.app.legacy.PApplet;
@SuppressWarnings("serial")
public abstract class AbstractMonitor extends JFrame implements ActionListener {
protected final JLabel noLineEndingAlert;
protected TextAreaFIFO textArea;
protected JScrollPane scrollPane;
protected JTextField textField;
protected JButton sendButton;
protected JCheckBox autoscrollBox;
protected JComboBox lineEndings;
protected JComboBox serialRates;
private boolean monitorEnabled;
private boolean closed;
private Timer updateTimer;
private StringBuffer updateBuffer;
public AbstractMonitor(String title) {
super(title);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
try {
closed = true;
close();
} catch (Exception e) {
// ignore
}
}
});
// obvious, no?
KeyStroke wc = Editor.WINDOW_CLOSE_KEYSTROKE;
getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(wc, "close");
getRootPane().getActionMap().put("close", (new AbstractAction() {
public void actionPerformed(ActionEvent event) {
try {
close();
} catch (Exception e) {
// ignore
}
setVisible(false);
}
}));
getContentPane().setLayout(new BorderLayout());
Font consoleFont = Theme.getFont("console.font");
Font editorFont = PreferencesData.getFont("editor.font");
Font font = new Font(consoleFont.getName(), consoleFont.getStyle(), editorFont.getSize());
textArea = new TextAreaFIFO(8000000);
textArea.setRows(16);
textArea.setColumns(40);
textArea.setEditable(false);
textArea.setFont(font);
// don't automatically update the caret. that way we can manually decide
// whether or not to do so based on the autoscroll checkbox.
((DefaultCaret) textArea.getCaret()).setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
scrollPane = new JScrollPane(textArea);
getContentPane().add(scrollPane, BorderLayout.CENTER);
JPanel upperPane = new JPanel();
upperPane.setLayout(new BoxLayout(upperPane, BoxLayout.X_AXIS));
upperPane.setBorder(new EmptyBorder(4, 4, 4, 4));
textField = new JTextField(40);
sendButton = new JButton(_("Send"));
upperPane.add(textField);
upperPane.add(Box.createRigidArea(new Dimension(4, 0)));
upperPane.add(sendButton);
getContentPane().add(upperPane, BorderLayout.NORTH);
final JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.X_AXIS));
pane.setBorder(new EmptyBorder(4, 4, 4, 4));
autoscrollBox = new JCheckBox(_("Autoscroll"), true);
noLineEndingAlert = new JLabel(I18n.format(_("You've pressed {0} but nothing was sent. Should you select a line ending?"), _("Send")));
noLineEndingAlert.setToolTipText(noLineEndingAlert.getText());
noLineEndingAlert.setForeground(pane.getBackground());
Dimension minimumSize = new Dimension(noLineEndingAlert.getMinimumSize());
minimumSize.setSize(minimumSize.getWidth() / 3, minimumSize.getHeight());
noLineEndingAlert.setMinimumSize(minimumSize);
lineEndings = new JComboBox(new String[]{_("No line ending"), _("Newline"), _("Carriage return"), _("Both NL & CR")});
lineEndings.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
PreferencesData.setInteger("serial.line_ending", lineEndings.getSelectedIndex());
noLineEndingAlert.setForeground(pane.getBackground());
}
});
if (PreferencesData.get("serial.line_ending") != null) {
lineEndings.setSelectedIndex(PreferencesData.getInteger("serial.line_ending"));
}
lineEndings.setMaximumSize(lineEndings.getMinimumSize());
String[] serialRateStrings = {
"300", "1200", "2400", "4800", "9600",
"19200", "38400", "57600", "115200", "230400", "250000"
};
serialRates = new JComboBox();
for (String rate : serialRateStrings) {
serialRates.addItem(rate + " " + _("baud"));
}
serialRates.setMaximumSize(serialRates.getMinimumSize());
pane.add(autoscrollBox);
pane.add(Box.createHorizontalGlue());
pane.add(noLineEndingAlert);
pane.add(Box.createRigidArea(new Dimension(8, 0)));
pane.add(lineEndings);
pane.add(Box.createRigidArea(new Dimension(8, 0)));
pane.add(serialRates);
this.setMinimumSize(new Dimension(pane.getMinimumSize().width, this.getPreferredSize().height));
getContentPane().add(pane, BorderLayout.SOUTH);
pack();
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
if (PreferencesData.get("last.screen.height") != null) {
// if screen size has changed, the window coordinates no longer
// make sense, so don't use them unless they're identical
int screenW = PreferencesData.getInteger("last.screen.width");
int screenH = PreferencesData.getInteger("last.screen.height");
if ((screen.width == screenW) && (screen.height == screenH)) {
String locationStr = PreferencesData.get("last.serial.location");
if (locationStr != null) {
int[] location = PApplet.parseInt(PApplet.split(locationStr, ','));
setPlacement(location);
}
}
}
updateBuffer = new StringBuffer(1048576);
updateTimer = new Timer(33, this); // redraw serial monitor at 30 Hz
updateTimer.start();
monitorEnabled = true;
closed = false;
}
public void enableWindow(boolean enable)
{
textArea.setEnabled(enable);
scrollPane.setEnabled(enable);
textField.setEnabled(enable);
sendButton.setEnabled(enable);
autoscrollBox.setEnabled(enable);
lineEndings.setEnabled(enable);
serialRates.setEnabled(enable);
monitorEnabled = enable;
}
// Puts the window in suspend state, closing the serial port
// to allow other entity (the programmer) to use it
public void suspend()
{
enableWindow(false);
try {
close();
}
catch(Exception e) {
//throw new SerialException("Failed closing the port");
}
}
public void resume() throws SerialException
{
// Enable the window
enableWindow(true);
// If the window is visible, try to open the serial port
if (isVisible())
try {
open();
}
catch(Exception e) {
throw new SerialException("Failed opening the port");
}
}
public void onSerialRateChange(ActionListener listener) {
serialRates.addActionListener(listener);
}
public void onSendCommand(ActionListener listener) {
textField.addActionListener(listener);
sendButton.addActionListener(listener);
}
protected void setPlacement(int[] location) {
setBounds(location[0], location[1], location[2], location[3]);
}
protected int[] getPlacement() {
int[] location = new int[4];
// Get the dimensions of the Frame
Rectangle bounds = getBounds();
location[0] = bounds.x;
location[1] = bounds.y;
location[2] = bounds.width;
location[3] = bounds.height;
return location;
}
public void message(final String s) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(s);
if (autoscrollBox.isSelected()) {
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
});
}
public boolean requiresAuthorization() {
return false;
}
public String getAuthorizationKey() {
return null;
}
public boolean isClosed() {
return closed;
}
public abstract void open() throws Exception;
public abstract void close() throws Exception;
public synchronized void addToUpdateBuffer(char buff[], int n) {
updateBuffer.append(buff, 0, n);
}
private synchronized String consumeUpdateBuffer() {
String s = updateBuffer.toString();
updateBuffer.setLength(0);
return s;
}
public void actionPerformed(ActionEvent e) {
final String s = consumeUpdateBuffer();
if (s.length() > 0) {
//System.out.println("gui append " + s.length());
if (autoscrollBox.isSelected()) {
textArea.appendTrim(s);
textArea.setCaretPosition(textArea.getDocument().getLength());
} else {
textArea.appendNoTrim(s);
}
}
}
}
|
package com.ore.infinium;
import com.artemis.ComponentMapper;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.*;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.Scaling;
import com.ore.infinium.components.BlockComponent;
import com.ore.infinium.components.ItemComponent;
import com.ore.infinium.components.SpriteComponent;
import com.ore.infinium.systems.NetworkClientSystem;
import com.ore.infinium.systems.TileRenderSystem;
public class HotbarInventoryView implements Inventory.SlotListener {
private Skin m_skin;
private Table container;
private SlotElement[] m_slots = new SlotElement[Inventory.maxHotbarSlots];
private OreWorld m_world;
private ComponentMapper<ItemComponent> itemMapper;
private ComponentMapper<BlockComponent> blockMapper;
private ComponentMapper<SpriteComponent> spriteMapper;
//the model for this view
private Inventory m_hotbarInventory;
//the main player inventory, for drag and drop
private Inventory m_inventory;
private Label m_tooltip;
private Stage m_stage;
public HotbarInventoryView(Stage stage, Skin skin, Inventory hotbarInventory, Inventory inventory,
DragAndDrop dragAndDrop, OreWorld world) {
m_skin = skin;
m_inventory = inventory;
m_world = world;
m_stage = stage;
m_world.m_artemisWorld.inject(this);
m_hotbarInventory = hotbarInventory;
//attach to the inventory model
m_hotbarInventory.addListener(this);
container = new Table(m_skin);
container.setFillParent(true);
container.top().left().setSize(800, 100);
container.padLeft(10).padTop(10);
container.defaults().space(4);
stage.addActor(container);
Image dragImage = new Image();
dragImage.setSize(32, 32);
for (byte i = 0; i < Inventory.maxHotbarSlots; ++i) {
Image slotImage = new Image();
SlotElement element = new SlotElement();
m_slots[i] = element;
element.itemImage = slotImage;
Table slotTable = new Table(m_skin);
element.table = slotTable;
slotTable.setTouchable(Touchable.enabled);
slotTable.addListener(new SlotClickListener(this, i));
slotTable.addListener(new SlotInputListener(this, i));
slotTable.add(slotImage);
slotTable.background("default-pane");
slotTable.row();
Label itemCount = new Label(null, m_skin);
slotTable.add(itemCount).bottom().fill();
element.itemCountLabel = itemCount;
// container.add(slotTable).size(50, 50);
container.add(slotTable).fill().size(50, 50);
setHotbarSlotVisible(i, false);
dragAndDrop.addSource(new HotbarDragSource(slotTable, i, dragImage, this));
dragAndDrop.addTarget(new HotbarDragTarget(slotTable, i, this));
}
m_tooltip = new Label(null, m_skin);
stage.addActor(m_tooltip);
}
private void deselectPreviousSlot() {
m_slots[m_hotbarInventory.m_previousSelectedSlot].table.setColor(Color.WHITE);
}
@Override
public void countChanged(byte index, Inventory inventory) {
ItemComponent itemComponent = itemMapper.get(inventory.itemEntity(index));
m_slots[index].itemCountLabel.setText(Integer.toString(itemComponent.stackSize));
}
@Override
public void set(byte index, Inventory inventory) {
SlotElement slot = m_slots[index];
int itemEntity = inventory.itemEntity(index);
ItemComponent itemComponent = itemMapper.get(itemEntity);
m_slots[index].itemCountLabel.setText(Integer.toString(itemComponent.stackSize));
TextureRegion region;
SpriteComponent spriteComponent = spriteMapper.get(itemEntity);
if (blockMapper.get(itemEntity) != null) {
//fixme this concat is pretty...iffy
region = m_world.m_artemisWorld.getSystem(TileRenderSystem.class).m_tilesAtlas.findRegion(
spriteComponent.textureName.concat("-00"));
} else {
region = m_world.m_atlas.findRegion(spriteComponent.textureName);
}
assert region != null : "textureregion for inventory item was not found!";
Image slotImage = slot.itemImage;
// //m_blockAtlas.findRegion("stone"));
slotImage.setDrawable(new TextureRegionDrawable(region));
slotImage.setSize(region.getRegionWidth(), region.getRegionHeight());
slotImage.setScaling(Scaling.fit);
setHotbarSlotVisible(index, true);
//do not exceed the max size/resort to horrible upscaling. prefer native size of each inventory sprite.
//.maxSize(region.getRegionWidth(), region.getRegionHeight()).expand().center();
}
@Override
public void removed(byte index, Inventory inventory) {
SlotElement slot = m_slots[index];
// slot.itemImage.setDrawable(null);
// slot.itemCountLabel.setText(null);
setHotbarSlotVisible(index, false);
}
@Override
public void selected(byte index, Inventory inventory) {
deselectPreviousSlot();
m_slots[index].table.setColor(0, 0, 1, 1);
}
//FIXME: do the same for InventoryView
private void setHotbarSlotVisible(int index, boolean visible) {
if (!visible) {
m_slots[index].itemImage.setDrawable(null);
m_slots[index].itemCountLabel.setText(null);
}
m_slots[index].itemCountLabel.setVisible(visible);
m_slots[index].itemImage.setVisible(visible);
}
private static class HotbarDragSource extends DragAndDrop.Source {
private final byte index;
private Image dragImage;
private HotbarInventoryView hotbarInventoryView;
public HotbarDragSource(Table slotTable, byte index, Image dragImage, HotbarInventoryView hotbarInventoryView) {
super(slotTable);
this.index = index;
this.dragImage = dragImage;
this.hotbarInventoryView = hotbarInventoryView;
}
public DragAndDrop.Payload dragStart(InputEvent event, float x, float y, int pointer) {
//invalid drag start, ignore.
if (hotbarInventoryView.m_hotbarInventory.itemEntity(index) == OreWorld.ENTITY_INVALID) {
return null;
}
DragAndDrop.Payload payload = new DragAndDrop.Payload();
InventorySlotDragWrapper dragWrapper = new InventorySlotDragWrapper();
payload.setObject(dragWrapper);
dragWrapper.type = Inventory.InventoryType.Hotbar;
dragWrapper.dragSourceIndex = index;
payload.setDragActor(dragImage);
payload.setValidDragActor(dragImage);
payload.setInvalidDragActor(dragImage);
return payload;
}
}
private static class HotbarDragTarget extends DragAndDrop.Target {
private final byte index;
private HotbarInventoryView inventory;
public HotbarDragTarget(Table slotTable, byte index, HotbarInventoryView inventory) {
super(slotTable);
this.index = index;
this.inventory = inventory;
}
public boolean drag(DragAndDrop.Source source, DragAndDrop.Payload payload, float x, float y, int pointer) {
if (payload == null) {
return false;
}
if (isValidDrop(payload)) {
getActor().setColor(Color.GREEN);
payload.getDragActor().setColor(0, 1, 0, 1);
return true;
} else {
getActor().setColor(Color.RED);
payload.getDragActor().setColor(1, 0, 0, 1);
}
return false;
}
private boolean isValidDrop(DragAndDrop.Payload payload) {
InventorySlotDragWrapper dragWrapper = (InventorySlotDragWrapper) payload.getObject();
if (dragWrapper.dragSourceIndex != index) {
//maybe make it green? the source/dest is not the same
if (inventory.m_hotbarInventory.itemEntity(index) == OreWorld.ENTITY_INVALID) {
//only make it green if the slot is empty
return true;
}
}
return false;
}
public void reset(DragAndDrop.Source source, DragAndDrop.Payload payload) {
payload.getDragActor().setColor(1, 1, 1, 1);
getActor().setColor(Color.WHITE);
//restore selection, it was just dropped..
inventory.selected(inventory.m_hotbarInventory.m_selectedSlot, inventory.m_hotbarInventory);
}
public void drop(DragAndDrop.Source source, DragAndDrop.Payload payload, float x, float y, int pointer) {
InventorySlotDragWrapper dragWrapper = (InventorySlotDragWrapper) payload.getObject();
//ensure the dest is empty before attempting any drag & drop!
if (inventory.m_hotbarInventory.itemEntity(this.index) != OreWorld.ENTITY_INVALID) {
return;
}
if (dragWrapper.type == Inventory.InventoryType.Hotbar) {
//move the item from the source to the dest (from hotbarinventory to hotbarinventory)
inventory.m_hotbarInventory.setSlot(this.index, inventory.m_hotbarInventory.itemEntity(
dragWrapper.dragSourceIndex));
inventory.m_world.m_artemisWorld.getSystem(NetworkClientSystem.class)
.sendInventoryMove(Inventory.InventoryType.Hotbar,
dragWrapper.dragSourceIndex,
Inventory.InventoryType.Hotbar, index);
//remove the source item
inventory.m_hotbarInventory.takeItem(dragWrapper.dragSourceIndex);
} else {
//main inventory
//move the item from the source to the dest (from main inventory, to this hotbar inventory)
inventory.m_hotbarInventory.setSlot(this.index,
inventory.m_inventory.itemEntity(dragWrapper.dragSourceIndex));
//fixme? inventory.m_previousSelectedSlot = index;
inventory.m_world.m_artemisWorld.getSystem(NetworkClientSystem.class)
.sendInventoryMove(Inventory.InventoryType.Inventory,
dragWrapper.dragSourceIndex,
Inventory.InventoryType.Hotbar, index);
//remove the source item
inventory.m_inventory.takeItem(dragWrapper.dragSourceIndex);
}
//select new index
inventory.m_hotbarInventory.selectSlot(index);
}
}
private static class SlotInputListener extends InputListener {
private byte index;
private HotbarInventoryView inventory;
SlotInputListener(HotbarInventoryView inventory, byte index) {
this.index = index;
this.inventory = inventory;
}
@Override
public boolean mouseMoved(InputEvent event, float x, float y) {
int itemEntity = inventory.m_hotbarInventory.itemEntity(index);
if (itemEntity != OreWorld.ENTITY_INVALID) {
inventory.m_tooltip.setVisible(true);
inventory.m_tooltip.setPosition(Gdx.input.getX(), Gdx.graphics.getHeight() - Gdx.input.getY() - 50);
//fixme, obviously texture name is not a valid tooltip text. we need a real name, but should it be in
// sprite or item? everything should probably have a canonical name, no?
ItemComponent itemComponent = inventory.itemMapper.get(itemEntity);
SpriteComponent spriteComponent = inventory.spriteMapper.get(itemEntity);
inventory.m_tooltip.setText(spriteComponent.textureName);
} else {
inventory.m_tooltip.setVisible(false);
}
return super.mouseMoved(event, x, y);
}
@Override
public void exit(InputEvent event, float x, float y, int pointer, Actor toActor) {
super.exit(event, x, y, pointer, toActor);
}
}
private static class SlotClickListener extends ClickListener {
private byte index;
private HotbarInventoryView inventory;
public SlotClickListener(HotbarInventoryView inventory, byte index) {
this.inventory = inventory;
this.index = index;
}
@Override
public void clicked(InputEvent event, float x, float y) {
inventory.deselectPreviousSlot();
inventory.m_hotbarInventory.selectSlot(index);
}
}
private class SlotElement {
public Image itemImage;
public Label itemCountLabel;
public Table table;
}
}
|
package vistas;
import Datos.Conexion;
import Datos.Socio;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author Gonzalo
*/
public class Socio_agregarSocio extends javax.swing.JFrame {
/**
* Creates new form Socio_agregarSocio
*/
public Socio_agregarSocio() {
initComponents();
}
private Statement sentencia;
private ResultSet rsDatos;
Datos.Socio s;
Connection connection;//para la Conexion
PreparedStatement preparedStatement;//para preparar las querys
ResultSet resultSet;//para recibir resultados de una cosulta
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel2 = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
txtEmailSocio = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
txtDomicilioSocio = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
ComboBoxCategoriaSocio = new javax.swing.JComboBox<>();
jLabel9 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
txtCuilSocio = new javax.swing.JTextField();
txtApellidoSocio = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
txtNombreSocio = new javax.swing.JTextField();
txtDNISocio = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtLegajoSocio = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
txtTelefonoSocio = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
btnGuardarSocio = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
labelNombre = new javax.swing.JLabel();
labelApellido = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
btnBuscarSocio = new javax.swing.JButton();
txtBuscarSocio = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel7.setText("Categoria");
jLabel6.setText("E-mail");
jLabel5.setText("Domicilio");
jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel10.setText("Datos Profesionales");
ComboBoxCategoriaSocio.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Profesional", "Idoneo", "Auxiliar Informatico" }));
ComboBoxCategoriaSocio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ComboBoxCategoriaSocioActionPerformed(evt);
}
});
jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel9.setText("Datos Personales");
jLabel8.setText("CUIL/CUIT");
jLabel1.setText("Nombre");
txtNombreSocio.setToolTipText("Nombre");
txtNombreSocio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNombreSocioActionPerformed(evt);
}
});
jLabel3.setText("DNI");
jLabel4.setText("Telefono");
jLabel12.setText("Legajo");
txtTelefonoSocio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtTelefonoSocioActionPerformed(evt);
}
});
jLabel2.setText("Apellido");
btnGuardarSocio.setText("Guardar");
btnGuardarSocio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnGuardarSocioActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnGuardarSocio))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(jLabel9)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(35, 35, 35)
.addComponent(jLabel5))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(txtTelefonoSocio, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtDomicilioSocio, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(10, 10, 10)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(txtEmailSocio, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(txtNombreSocio, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(txtApellidoSocio, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(ComboBoxCategoriaSocio, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(37, 37, 37)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtCuilSocio, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtLegajoSocio)
.addComponent(txtDNISocio, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jLabel12))))))
.addGap(42, 42, 42))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtNombreSocio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtApellidoSocio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtDNISocio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(19, 19, 19)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtTelefonoSocio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtDomicilioSocio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtEmailSocio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(39, 39, 39)
.addComponent(jLabel10)
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jLabel8)
.addComponent(jLabel12))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtCuilSocio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ComboBoxCategoriaSocio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtLegajoSocio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 81, Short.MAX_VALUE)
.addComponent(btnGuardarSocio)
.addGap(35, 35, 35))
);
jTabbedPane1.addTab("tab1", jPanel2);
labelNombre.setText("..");
labelApellido.setText("..");
jLabel14.setText("Nombre: ");
jLabel15.setText("Apellido: ");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel14)
.addComponent(jLabel15))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(labelApellido, javax.swing.GroupLayout.DEFAULT_SIZE, 49, Short.MAX_VALUE)
.addComponent(labelNombre, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(218, 218, 218))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelNombre)
.addComponent(jLabel14))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelApellido)
.addComponent(jLabel15))
.addContainerGap(43, Short.MAX_VALUE))
);
btnBuscarSocio.setText("Buscar");
btnBuscarSocio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBuscarSocioActionPerformed(evt);
}
});
jLabel11.setText("Ingrese Legajo");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel11)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(txtBuscarSocio, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnBuscarSocio)))
.addGap(169, 169, 169))
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(57, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jLabel11)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnBuscarSocio)
.addComponent(txtBuscarSocio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(224, Short.MAX_VALUE))
);
jTabbedPane1.addTab("tab2", jPanel3);
jLabel13.setText("Gestionar Socios");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane1)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel13)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel13)
.addGap(22, 22, 22)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 425, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtNombreSocioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNombreSocioActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtNombreSocioActionPerformed
private void txtTelefonoSocioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTelefonoSocioActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtTelefonoSocioActionPerformed
private void ComboBoxCategoriaSocioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ComboBoxCategoriaSocioActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_ComboBoxCategoriaSocioActionPerformed
private void btnGuardarSocioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarSocioActionPerformed
try {
connection = Conexion.Cadena();
//Connection = Conexion.Cadena();
preparedStatement = connection.prepareStatement("INSERT INTO socio (nombre, apellido,dni,telefono,domicilio,categoria,cuilcuit,email,legajo_socio) VALUES (?,?,?,?,?,?,?,?,?)");
preparedStatement.setString(1, txtNombreSocio.getText());
preparedStatement.setString(2, txtApellidoSocio.getText());
preparedStatement.setString(3, txtDNISocio.getText());
preparedStatement.setString(4, txtTelefonoSocio.getText());
preparedStatement.setString(5, txtDomicilioSocio.getText());
preparedStatement.setString(6, ComboBoxCategoriaSocio.getSelectedItem().toString());
preparedStatement.setString(7, txtCuilSocio.getText());
preparedStatement.setString(8, txtEmailSocio.getText());
preparedStatement.setString(9, txtLegajoSocio.getText());
int res = preparedStatement.executeUpdate();
if (res > 0) {
JOptionPane.showMessageDialog(null, "Socio Guardado");
//LimpiarCajas();
} else {
JOptionPane.showMessageDialog(null, "Error al Guardar Personal");
//LimpiarCajas();
}
connection.close();
} catch (Exception ex) {
System.out.println(ex);
}
}//GEN-LAST:event_btnGuardarSocioActionPerformed
//dsdsdsdsdsd
//dsdsdsdsdsd
public ResultSet mostrarSocios() throws ClassNotFoundException
{
try {
System.out.println ("hola");
String query= "SELECT * FROM Socios";
Connection cn = Conexion.Cadena();
sentencia = cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
rsDatos = sentencia.executeQuery(query);
cn.commit();
} catch (SQLException ex) {
Logger.getLogger(Socio.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println (rsDatos);
return rsDatos;
}
private void btnBuscarSocioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarSocioActionPerformed
try {
Datos.Socio nuevoSocio = new Socio();
nuevoSocio=nuevoSocio.BuscarX(txtBuscarSocio.getText());
//System.out.println(nuevoSocio.getNombre());
labelNombre.setText(nuevoSocio.getNombre());
labelApellido.setText(nuevoSocio.getApellido());
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "ERROR!!", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_btnBuscarSocioActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Socio_agregarSocio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Socio_agregarSocio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Socio_agregarSocio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Socio_agregarSocio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Socio_agregarSocio().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox<String> ComboBoxCategoriaSocio;
private javax.swing.JButton btnBuscarSocio;
private javax.swing.JButton btnGuardarSocio;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JLabel labelApellido;
private javax.swing.JLabel labelNombre;
private javax.swing.JTextField txtApellidoSocio;
private javax.swing.JTextField txtBuscarSocio;
private javax.swing.JTextField txtCuilSocio;
private javax.swing.JTextField txtDNISocio;
private javax.swing.JTextField txtDomicilioSocio;
private javax.swing.JTextField txtEmailSocio;
private javax.swing.JTextField txtLegajoSocio;
private javax.swing.JTextField txtNombreSocio;
private javax.swing.JTextField txtTelefonoSocio;
// End of variables declaration//GEN-END:variables
}
|
package hudson.model;
import hudson.ExtensionPoint;
import hudson.Plugin;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Participates in the rendering of HTML pages for all pages of Hudson.
*
* <p>
* This class provides a few hooks to augument the HTML generation process of Hudson, across
* all the HTML pages that Hudson delivers.
*
* <p>
* For example, if you'd like to add a Google Analytics stat to Hudson, then you need to inject
* a small script fragment to all Hudson pages. This extension point provides a means to do that.
*
* <h2>Life-cycle</h2>
* <p>
* Instances of this class is singleton. {@link Plugin}s that contribute this extension point
* should instantiate a new decorator and add it to the {@link #ALL} list in {@link Plugin#start()}.
*
* <h2>Associated Views</h2>
* <h4>global.jelly</h4>
* <p>
* If this extension point needs to expose a global configuration, write this jelly page.
* See {@link Descriptor} for more about this. Optional.
*
* <h4>footer.jelly</h4>
* <p>
* This page is added right before the </body> tag. Convenient place for adding tracking beacons, etc.
*
* <h4>header.jelly</h4>
* <p>
* This page is added right before the </head> tag. Convenient place for additional stylesheet,
* <meta> tags, etc.
*
*
* @author Kohsuke Kawaguchi
* @since 1.235
*/
public abstract class PageDecorator extends Descriptor<PageDecorator> implements ExtensionPoint, Describable<PageDecorator> {
/**
* @param yourClass
* pass-in "this.getClass()" (except that the constructor parameters cannot use 'this',
* so you'd have to hard-code the class name.
*/
protected PageDecorator(Class<? extends PageDecorator> yourClass) {
super(yourClass);
}
public final Descriptor<PageDecorator> getDescriptor() {
return this;
}
/**
* Unless this object has additional web presence, display name is not used at all.
* So default to "".
*/
public String getDisplayName() {
return "";
}
/**
* All the registered instances.
*/
public static final List<PageDecorator> ALL = new CopyOnWriteArrayList<PageDecorator>();
}
|
package hudson.util.io;
import hudson.Functions;
import hudson.org.apache.tools.tar.TarOutputStream;
import hudson.os.PosixException;
import hudson.util.FileVisitor;
import hudson.util.IOUtils;
import org.apache.tools.tar.TarEntry;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import static org.apache.tools.tar.TarConstants.LF_SYMLINK;
/**
* {@link FileVisitor} that creates a tar archive.
*
* @see ArchiverFactory#TAR
*/
final class TarArchiver extends Archiver {
private final byte[] buf = new byte[8192];
private final TarArchiveOutputStream tar;
TarArchiver(OutputStream out) {
tar = new TarArchiveOutputStream(new BufferedOutputStream(out) {
// TarOutputStream uses TarBuffer internally,
// which flushes the stream for each block. this creates unnecessary
// data stream fragmentation, and flush request to a remote, which slows things down.
@Override
public void flush() throws IOException {
// so don't do anything in flush
}
});
tar.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
}
@Override
public void visitSymlink(File link, String target, String relativePath) throws IOException {
TarArchiveEntry e = new TarArchiveEntry(relativePath, LF_SYMLINK);
try {
int mode = IOUtils.mode(link);
if (mode != -1) {
e.setMode(mode);
}
} catch (PosixException x) {
// ignore
}
e.setLinkName(target);
tar.putArchiveEntry(e);
tar.closeArchiveEntry();
entriesWritten++;
}
@Override
public boolean understandsSymlink() {
return true;
}
public void visit(File file, String relativePath) throws IOException {
if(Functions.isWindows())
relativePath = relativePath.replace('\\','/');
if(file.isDirectory())
relativePath+='/';
TarArchiveEntry te = new TarArchiveEntry(relativePath);
int mode = IOUtils.mode(file);
if (mode!=-1) te.setMode(mode);
te.setModTime(file.lastModified());
if(!file.isDirectory())
te.setSize(file.length());
tar.putArchiveEntry(te);
if (!file.isDirectory()) {
FileInputStream in = new FileInputStream(file);
try {
int len;
while((len=in.read(buf))>=0)
tar.write(buf,0,len);
} finally {
in.close();
}
}
tar.closeArchiveEntry();
entriesWritten++;
}
public void close() throws IOException {
tar.close();
}
}
|
package net.time4j.tz;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* <p>SPI interface which encapsulates the timezone repository and
* provides all necessary data for a given timezone id. </p>
*
* <p>Implementations are usually stateless and should normally not
* try to manage a cache. Instead Time4J uses its own cache. The
* fact that this interface is used per {@code java.util.ServiceLoader}
* requires a concrete implementation to offer a public no-arg
* constructor. </p>
*
* @author Meno Hochschild
* @since 2.2
* @see java.util.ServiceLoader
*/
/*[deutsch]
* <p>SPI-Interface, das eine Zeitzonendatenbank kapselt und passend zu
* einer Zeitzonen-ID (hier als String statt als {@code TZID}) die
* Zeitzonendaten liefert. </p>
*
* <p>Implementierungen sind in der Regel zustandslos und halten keinen
* Cache. Letzterer sollte normalerweise der Klasse {@code Timezone}
* vorbehalten sein. Weil dieses Interface mittels eines
* {@code java.util.ServiceLoader} genutzt wird, muß eine
* konkrete Implementierung einen öffentlichen Konstruktor ohne
* Argumente definieren. </p>
*
* @author Meno Hochschild
* @since 2.2
* @see java.util.ServiceLoader
*/
public interface ZoneProvider {
/**
* <p>Gets all available and supported timezone identifiers. </p>
*
* @return unmodifiable set of timezone ids
* @see java.util.TimeZone#getAvailableIDs()
*/
/*[deutsch]
* <p>Liefert alle verfügbaren Zeitzonenkennungen. </p>
*
* @return unmodifiable set of timezone ids
* @see java.util.TimeZone#getAvailableIDs()
*/
Set<String> getAvailableIDs();
/**
* <p>Gets a {@code Set} of preferred timezone IDs for given
* ISO-3166-country code. </p>
*
* <p>This information is necessary to enable parsing of
* timezone names. </p>
*
* @param locale ISO-3166-alpha-2-country to be evaluated
* @param smart if {@code true} then try to select zone ids such
* that there is only one preferred id per zone name
* @return unmodifiable set of preferred timezone ids
*/
/*[deutsch]
* <p>Liefert die für einen gegebenen ISO-3166-Ländercode
* bevorzugten Zeitzonenkennungen. </p>
*
* <p>Diese Information ist für die Interpretation von Zeitzonennamen
* notwendig. </p>
*
* @param locale ISO-3166-alpha-2-country to be evaluated
* @param smart if {@code true} then try to select zone ids such
* that there is only one preferred id per zone name
* @return unmodifiable set of preferred timezone ids
*/
Set<String> getPreferredIDs(
Locale locale,
boolean smart
);
/**
* <p>Gets an alias table whose keys represent alternative identifiers
* mapped to other aliases or finally canonical timezone IDs.. </p>
*
* <p>Example: "PST" => "America/Los_Angeles". </p>
*
* @return map from all timezone aliases to canoncial ids
*/
/*[deutsch]
* <p>Liefert eine Alias-Tabelle, in der die Schlüssel alternative
* Zonen-IDs darstellen und in der die zugeordneten Werte wieder
* Aliasnamen oder letztlich kanonische Zonen-IDs sind. </p>
*
* <p>Beispiel: "PST" => "America/Los_Angeles". </p>
*
* @return map from all timezone aliases to canoncial ids
*/
Map<String, String> getAliases();
TransitionHistory load(String zoneID);
/**
* <p>Determines if in case of a failed search another {@code ZoneProvider}
* should be called as alternative with possibly different rules. </p>
*
* <p>The special name "DEFAULT" can be used to denote the
* default zone provider. Note that the fallback provider will only affect
* the rules but not the id or display names of a new timezone. </p>
*
* @return name of alternative provider or empty if no fallback happens
* @see #load(String)
*/
/*[deutsch]
* <p>Legt fest, ob ein alternativer {@code ZoneProvider} mit eventuell
* anderen Regeln gerufen werden soll, wenn die Suche nach einer Zeitzone
* erfolglos war. </p>
*
* <p>Der spezielle Name "DEFAULT" kann verwendet werden, um
* den Standard-{@code ZoneProvider} anzuzeigen. Zu beachten: Die
* Alternative wird nur die Regeln betreffen, nicht aber die ID oder
* Anzeigenamen einer neuen Zeitzone. </p>
*
* @return name of alternative provider or empty if no fallback happens
* @see #load(String)
*/
String getFallback();
/**
* <p>Gets the name of the underlying repository. </p>
*
* <p>The Olson/IANA-repository (and any provider which makes use of
* these data (direct or indirect)) has the name "TZDB".
* The names "java.util.TimeZone" and "DEFAULT"
* are reserved and cannot be used. </p>
*
* @return String
*/
/*[deutsch]
* <p>Gibt den Namen dieser Zeitzonendatenbank an. </p>
*
* <p>Die Olson/IANA-Zeitzonendatenbank hat den Namen
* "TZDB". Jeder {@code ZoneProvider}, der sich auf diese
* Daten bezieht, muß diesen Namen haben. Die Namen
* "java.util.TimeZone" and "DEFAULT" sind
* reserviert und können nicht verwendet werden. </p>
*
* @return String
*/
String getName();
/**
* <p>Describes the location or source of the repository. </p>
*
* @return String which refers to an URI or empty if unknown
*/
/*[deutsch]
* <p>Beschreibt die Quelle der Zeitzonendatenbank. </p>
*
* @return String which refers to an URI or empty if unknown
*/
String getLocation();
/**
* <p>Queries the version of the underlying repository. </p>
*
* <p>In most cases the version has the Olson format starting with
* a four-digit year number followed by a small letter in range
* a-z. </p>
*
* @return String (for example "2011n") or empty if unknown
*/
/*[deutsch]
* <p>Liefert die Version der Zeitzonendatenbank. </p>
*
* <p>Meist liegt die Version im Olson-Format vor. Dieses Format sieht
* als Versionskennung eine 4-stellige Jahreszahl gefolgt von einem
* Buchstaben im Bereich a-z vor. </p>
*
* @return String (for example "2011n") or empty if unknown
*/
String getVersion();
/**
* <p>Returns the name of this timezone suitable for presentation to
* users in given style and locale. </p>
*
* <p>The first argument never contains the provider name as prefix. It is
* instead the part after the "~"-char (if not absent). </p>
*
* @param zoneID timezone id (i.e. "Europe/London")
* @param style name style
* @param locale language setting
* @return localized timezone name for display purposes
* or empty if not supported
* @see java.util.TimeZone#getDisplayName(boolean,int,Locale)
* java.util.TimeZone.getDisplayName(boolean,int,Locale)
*/
/*[deutsch]
* <p>Liefert den anzuzeigenden Zeitzonennamen. </p>
*
* <p>Das erste Argument enthält nie den Provider-Namen als
* Präfix. Stattdessen ist es der Teil nach dem Zeichen
* "~" (falls vorhanden). </p>
*
* @param zoneID timezone id (i.e. "Europe/London")
* @param style name style
* @param locale language setting
* @return localized timezone name for display purposes
* or empty if not supported
* @see java.util.TimeZone#getDisplayName(boolean,int,Locale)
* java.util.TimeZone.getDisplayName(boolean,int,Locale)
*/
String getDisplayName(
String zoneID,
NameStyle style,
Locale locale
);
}
|
package GameFiles;
import java.util.ArrayList;
import java.util.Random;
public class GameAI {
protected int[][][] winChanceEachSpace;
protected int token;
protected double[][][] heuristic;
protected double[][][] winPercentage;
protected double[][][] moveFrequency;
protected double[][][] potWinsEverySpace;
protected int gameCount = 0;
protected int levelsToSearch = 0;
protected int nodeCount = 0;
public GameAI(int token, int levels, int nodecount){
this.token = token;
winPercentage = new double[4][4][4];
moveFrequency = new double[4][4][4];
for(int level = 0; level < winPercentage.length; level++){
for(int row = 0; row < winPercentage[0].length; row++){
for(int col = 0; col < winPercentage[0][0].length; col++){
winPercentage[level][row][col] = 0;
}
}
}
potWinsEverySpace = TicTacToe.potWinsEverySpace;
levelsToSearch = levels;
nodeCount = nodecount;
}
/*
Pretty simple compared to the search function as it does most of the heavy
lifting. Checks to see if there is a move it can do right now to win or
block the opponent's imminent victory next turn. If no move is found it will
call the search function to find the best move and use it.
*/
public void run(){
Coordinates move = checkWin();
if(move != null){
TicTacToe.board[move.getLevel()][move.getRow()][move.getColumn()] = token;
TicTacToe.available[move.getLevel()][move.getRow()][move.getColumn()] = false;
return;
}
move = checkOpponentWin();
if(move != null){
TicTacToe.board[move.getLevel()][move.getRow()][move.getColumn()] = token;
TicTacToe.available[move.getLevel()][move.getRow()][move.getColumn()] = false;
return;
}
int[][][] boardClone = TicTacToe.board.clone();
boolean[][][] availableClone = TicTacToe.available.clone();
move = search(token, levelsToSearch, token, null);
TicTacToe.board = boardClone;
TicTacToe.available = availableClone;
TicTacToe.board[move.level][move.row][move.column] = token;
TicTacToe.available[move.level][move.row][move.column] = false;
}
public Coordinates search(int curToken, int searchLevel, int originalToken, Coordinates parent){
//last move in the search and it's the AI's opponent
if(searchLevel <= 0 && curToken != originalToken){
Coordinates move = checkWin();
if(move != null){
move.adjustHeuristic(-1000);
move.setParent(parent);
return move;
}
}
//Setting what the opponent's token is
token = curToken;
int oppToken = getOppToken();
//Check to see if the current player has a winning move
Coordinates move = checkWin();
int level,row,col;
if(move != null){
move.setParent(parent);
if(curToken == originalToken){
move.adjustHeuristic(1000);
}
else{
move.adjustHeuristic(-1000);
}
return move;
}
//Need to check to see if the opponent wins, method handles both players
//and performs recursive calls
Coordinates oppPotentialWin = ifOpponentWins(originalToken,curToken,searchLevel,parent);
if(oppPotentialWin != null){
return oppPotentialWin;
}
if(TicTacToe.isDraw()){
return new Coordinates(0,0,0, parent, 1);
}
heuristic = new double[4][4][4];
for(level = 0; level < TicTacToe.board.length; level++){
for(row = 0; row < TicTacToe.board[0].length; row++){
for(col = 0; col < TicTacToe.board[0][0].length; col++){
heuristic[level][row][col] = potWinsEverySpace[level][row][col];
}
}
}
checkPlacement();
ArrayList<Coordinates> coordinateList = moveListGeneration(originalToken, curToken, parent);
if(originalToken != curToken){
Coordinates tmp = coordinateList.get(0);
int l = tmp.getLevel();
int r = tmp.getRow();
int c = tmp.getColumn();
searchLevel
TicTacToe.board[l][r][c] = token;
TicTacToe.available[l][r][c] = false;
tmp = search(oppToken, searchLevel, originalToken, parent);
TicTacToe.board[l][r][c] = 0;
TicTacToe.available[l][r][c] = true;
return tmp;
}
if(searchLevel == 0){
double maxHeuristic = -1000000;
Coordinates maxCoord = null;
for(Coordinates coordinate : coordinateList){
if(heuristic[coordinate.level][coordinate.row][coordinate.column] > maxHeuristic){
maxHeuristic = heuristic[coordinate.level][coordinate.row][coordinate.column];
maxCoord = coordinate;
}
}
return maxCoord;
}
ArrayList<Coordinates> returnList = new ArrayList();
searchLevel
for(Coordinates coordinate : coordinateList){
TicTacToe.board[coordinate.level][coordinate.row][coordinate.column] = token;
TicTacToe.available[coordinate.level][coordinate.row][coordinate.column] = false;
if(searchLevel >= 1){
returnList.add(search(oppToken, searchLevel, originalToken, coordinate));
}
TicTacToe.board[coordinate.level][coordinate.row][coordinate.column] = 0;
TicTacToe.available[coordinate.level][coordinate.row][coordinate.column] = true;
}
double maxHeuristic = -1000000;
Coordinates maxCoord = null;
for(int i = 0; i < returnList.size(); i++){
Coordinates coordinate = returnList.get(i);
if(coordinate.parent == null){
System.out.println("Missing parent for coordinate");
System.exit(0);
}
for(Coordinates coord : coordinateList){
if(coordinate.parent.level == coord.level && coordinate.parent.row == coord.row && coordinate.parent.column == coord.column){
coord.heuristic += coordinate.heuristic;
break;
}
}
}
for(Coordinates maxC : coordinateList){
if(maxC.heuristic > maxHeuristic){
maxHeuristic = maxC.heuristic;
maxCoord = maxC;
}
}
if(maxCoord == null){
System.out.println("Missing best move selection");
System.exit(0);
}
token = curToken;
return maxCoord;
//remove randomness here
// if(coordinateList.size() > 1){
// int length = coordinateList.size();
// Random random = new Random();
// int chosen = random.nextInt(length);
// Coordinates chosenCoordinate = coordinateList.remove(chosen);
// l = chosenCoordinate.level;
// r = chosenCoordinate.row;
// c = chosenCoordinate.column;
// TicTacToe.board[l][r][c] = token;
// TicTacToe.available[l][r][c] = false;
}
private Coordinates ifOpponentWins(int originalToken, int curToken, int searchLevel, Coordinates parent){
Coordinates move = checkOpponentWin();
int level, row, col;
int oppToken = getOppToken();
if(move != null){
level = move.getLevel();
row = move.getRow();
col = move.getColumn();
if(searchLevel != 0){
searchLevel
}
TicTacToe.board[level][row][col] = token;
TicTacToe.available[level][row][col] = false;
Coordinates tmp;
if(curToken == originalToken){
Coordinates currentCoor = new Coordinates(level,row,col,parent,0);
tmp = search(oppToken,searchLevel, originalToken, currentCoor);
currentCoor.adjustHeuristic(potWinsEverySpace[level][row][col]);
currentCoor.adjustHeuristic(checkPotentialPaths(level,row,col));
currentCoor.adjustHeuristic(4 * winPercentage[level][row][col]);
currentCoor.adjustHeuristic(tmp.heuristic);
TicTacToe.board[level][row][col] = 0;
TicTacToe.available[level][row][col] = true;
return currentCoor;
}
else{
tmp = search(oppToken,searchLevel, originalToken, parent);
TicTacToe.board[level][row][col] = 0;
TicTacToe.available[level][row][col] = true;
return tmp;
}
}
return null;
}
private ArrayList<Coordinates> moveListGeneration(int originalToken, int curToken, Coordinates parent){
double minMax = 1000000;
double max = 0;
ArrayList<Coordinates> coordinateList = new ArrayList();
Coordinates oppMove = null;
int l = 0; int r = 0; int c = 0;
for(int level = 0; level < TicTacToe.board.length; level++){
for(int row = 0; row < TicTacToe.board[0].length; row++){
for(int col = 0; col < TicTacToe.board[0][0].length; col++){
if(TicTacToe.board[level][row][col] == 0){
heuristic[level][row][col] += checkPotentialPaths(level,row,col);
//potWinsEverySpace = potWinsClone.clone();
heuristic[level][row][col] += 4 * winPercentage[level][row][col];
if(coordinateList.size() < nodeCount && originalToken == curToken && heuristic[level][row][col] >= 0){
if(heuristic[level][row][col] < minMax){
minMax = heuristic[level][row][col];
}
coordinateList.add(new Coordinates(level,row,col, parent, heuristic[level][row][col]));
}
else if(heuristic[level][row][col] > minMax && originalToken == curToken){
double newMinMax = heuristic[level][row][col];
boolean flag = false;
for(int i = 0; i < coordinateList.size(); i++){
Coordinates tmp = coordinateList.get(i);
double h = heuristic[tmp.level][tmp.row][tmp.column];
if(h == minMax && !flag){
coordinateList.remove(i);
flag = true;
}
else if(h < newMinMax){
newMinMax = h;
}
}
minMax = newMinMax;
coordinateList.add(new Coordinates(level,row,col,parent, heuristic[level][row][col]));
}
else if(originalToken != curToken){
if(heuristic[level][row][col] > max ){
max = heuristic[level][row][col];
oppMove = new Coordinates(level,row,col,parent, max);
}
}
}
}
}
}
if(oppMove != null){
coordinateList.clear();
coordinateList.add(oppMove);
return coordinateList;
}
return coordinateList;
}
private int getOppToken(){
int oppToken;
if(token == 1){
oppToken = 2;
}
else{
oppToken = 1;
}
return oppToken;
}
private void checkPlacement(){
for(int level = 0; level < TicTacToe.board.length; level++){
for(int row = 0; row < TicTacToe.board[0].length; row++){
for(int col = 0; col < TicTacToe.board[0][0].length; col++){
if( TicTacToe.available[level][row][col] == false){
heuristic[level][row][col] = -100;
}
}
}
}
}
private Coordinates checkOpponentWin(){
int oppToken = getOppToken();
Coordinates coordinate;
for(int level = 0; level < TicTacToe.board.length; level++){
for(int row = 0; row < TicTacToe.board[0].length; row++){
for(int col = 0; col < TicTacToe.board[0][0].length; col++){
if(TicTacToe.board[level][row][col] == 0){
TicTacToe.board[level][row][col] = oppToken;
if(TicTacToe.checkWin(oppToken)){
coordinate = new Coordinates();
coordinate.setLevel(level);
coordinate.setRow(row);
coordinate.setColumn(col);
TicTacToe.board[level][row][col] = 0;
return coordinate;
}
TicTacToe.board[level][row][col] = 0;
}
}
}
}
return null;
}
private Coordinates checkWin(){
Coordinates coordinate;
for(int level = 0; level < TicTacToe.board.length; level++){
for(int row = 0; row < TicTacToe.board[0].length; row++){
for(int col = 0; col < TicTacToe.board[0][0].length; col++){
if(TicTacToe.board[level][row][col] == 0){
TicTacToe.board[level][row][col] = token;
if(TicTacToe.checkWin(token)){
coordinate = new Coordinates();
coordinate.setLevel(level);
coordinate.setRow(row);
coordinate.setColumn(col);
TicTacToe.board[level][row][col] = 0;
return coordinate;
}
TicTacToe.board[level][row][col] = 0;
}
}
}
}
return null;
}
private int checkPotentialPaths(int level, int row, int col){
int total = 0;
total += check2DHorizontal(level, row, col);
total += check2DVertical(level, row, col);
total += check3DVertical(level, row, col);
if(row == col || row == (TicTacToe.board.length - (col + 1) )){
total += check2DDiagonal(level,row,col);
}
if(level == row || level == (TicTacToe.board.length - (row + 1) )){
total += check3DDiagonalCol(level,row,col);
}
if(level == col || level == (TicTacToe.board.length - (col + 1) )){
total += check3DDiagonalRow(level,row,col);
}
if(level == col && level == row || level == (TicTacToe.board.length - (col + 1) ) && level == row){
total += check3DDiagonalCross(level,row,col);
}
if(level == (TicTacToe.board.length - (row + 1) ) && level == col || level == (TicTacToe.board.length - (col + 1) ) && level == (TicTacToe.board.length - (row + 1) )){
total += check3DDiagonalCross(level,row,col);
}
return total;
}
private int check2DHorizontal(int l, int r, int c){
int oppToken = 0;
int num = 0;
boolean havePiece = false;
boolean oppPiece = false;
oppToken = getOppToken();
for(int col = 0; col < TicTacToe.board[0][0].length; col++){
if(TicTacToe.board[l][r][col] == token){
num++;
havePiece = true;
}
else if(TicTacToe.board[l][r][col] == oppToken){
if(havePiece){
heuristic[l][r][c]
return 0;
}
num++;
oppPiece=true;
}
}
if(oppPiece){
heuristic[l][r][c]
return num;
}
return num + 1;
}
private int check2DVertical(int l, int r, int c){
int oppToken = 0;
int num = 0;
boolean havePiece = false;
boolean oppPiece = false;
oppToken = getOppToken();
for(int row = 0; row < TicTacToe.board[0][0].length; row++){
if(TicTacToe.board[l][row][c] == token){
num++;
havePiece = true;
}
else if(TicTacToe.board[l][row][c] == oppToken){
if(havePiece){
heuristic[l][r][c]
return 0;
}
oppPiece = true;
num++;
}
}
if(oppPiece){
heuristic[l][r][c]
return num;
}
return num + 1;
}
private int check2DDiagonal(int l, int r, int c){
int oppToken = 0;
int num = 0;
boolean havePiece = false;
boolean oppPiece = false;
oppToken = getOppToken();
if(r == c){
int row = 0;
int col = 0;
while(row < TicTacToe.board.length){
if(TicTacToe.board[l][row][col] == token){
num++;
havePiece =true;
}
else if(TicTacToe.board[l][row][col] == oppToken){
if(havePiece){
heuristic[l][r][c]
return 0;
}
oppPiece = true;
num++;
}
row++;
col++;
}
}
else{
int row = 0;
int col = TicTacToe.board[0].length - 1;
while(row < TicTacToe.board.length){
if(TicTacToe.board[l][row][col] == token){
num++;
havePiece = true;
}
else if(TicTacToe.board[l][row][col] == oppToken){
if(havePiece){
heuristic[l][r][c]
return 0;
}
oppPiece = true;
num++;
}
row++;
col
}
}
if(oppPiece){
heuristic[l][r][c]
return num;
}
return num + 1;
}
private int check3DDiagonalCol(int l, int r, int c){
int oppToken = 0;
int num = 0;
boolean havePiece = false;
boolean oppPiece = false;
oppToken = getOppToken();
if(l == r){
int level = 0;
int row = 0;
while(row < TicTacToe.board.length){
if(TicTacToe.board[level][row][c] == token){
num++;
havePiece=true;
}
else if(TicTacToe.board[level][row][c] == oppToken){
if(havePiece){
heuristic[l][r][c]
return 0;
}
num++;
oppPiece = true;
}
row++;
level++;
}
}
else{
int level = 0;
int row = TicTacToe.board[0].length-1;
while(level < TicTacToe.board.length){
if(TicTacToe.board[level][row][c] == token){
num++;
havePiece=true;
}
else if(TicTacToe.board[level][row][c] == oppToken){
if(havePiece){
heuristic[l][r][c]
return 0;
}
num++;
oppPiece = true;
}
row
level++;
}
}
if(oppPiece){
heuristic[l][r][c]
return num;
}
return num + 1;
}
private int check3DDiagonalRow(int l, int r, int c){
int oppToken = 0;
int num = 0;
boolean havePiece = false;
boolean oppPiece = false;
oppToken = getOppToken();
if(l == c){
int level = 0;
int col = 0;
while(level < TicTacToe.board.length){
if(TicTacToe.board[level][r][col] == token){
num++;
havePiece=true;
}
else if(TicTacToe.board[level][r][col] == oppToken){
if(havePiece){
heuristic[l][r][c]
return 0;
}
num++;
oppPiece = true;
}
col++;
level++;
}
}
else{
int level = 0;
int col = TicTacToe.board[0].length - 1;
while(level < TicTacToe.board.length){
if(TicTacToe.board[level][r][col] == token){
num++;
havePiece=true;
}
else if(TicTacToe.board[level][r][col] == oppToken){
if(havePiece){
heuristic[l][r][c]
return 0;
}
num++;
oppPiece = true;
}
col
level++;
}
}
if(oppPiece){
heuristic[l][r][c]
return num;
}
return num + 1;
}
private int check3DDiagonalCross(int l, int r, int c){
int oppToken = 0;
int num = 0;
boolean havePiece = false;
boolean oppPiece = false;
oppToken = getOppToken();
if(l == c && l == r){
int level = 0;
int col = 0;
int row = 0;
while(level < TicTacToe.board.length){
if(TicTacToe.board[level][row][col] == token){
num++;
havePiece=true;
}
else if(TicTacToe.board[level][row][col] == oppToken){
if(havePiece){
heuristic[l][r][c]
return 0;
}
oppPiece = true;
num++;
}
col++;
level++;
row++;
}
}
else if(l == r && l == (TicTacToe.board.length - (c + 1) )) {
int level = 0;
int col = TicTacToe.board[0].length - 1;
int row = 0;
while(level < TicTacToe.board.length){
if(TicTacToe.board[level][row][col] == token){
num++;
havePiece=true;
}
else if(TicTacToe.board[level][row][col] == oppToken){
if(havePiece){
heuristic[l][r][c]
return 0;
}
oppPiece = true;
num++;
}
col
level++;
row++;
}
}
else if(l == c && l == (TicTacToe.board.length - (r + 1) )) {
int level = 0;
int col = 0;
int row = TicTacToe.board[0].length - 1;
while(level < TicTacToe.board.length){
if(TicTacToe.board[level][row][col] == token){
num++;
havePiece=true;
}
else if(TicTacToe.board[level][row][col] == oppToken){
if(havePiece){
heuristic[l][r][c]
return 0;
}
num++;
oppPiece = true;
}
col++;
level++;
row
}
}
else{
int level = 0;
int col = TicTacToe.board[0].length - 1;
int row = TicTacToe.board[0].length - 1;
while(level < TicTacToe.board.length){
if(TicTacToe.board[level][row][col] == token){
num++;
havePiece=true;
}
else if(TicTacToe.board[level][row][col] == oppToken){
if(havePiece){
heuristic[l][r][c]
return 0;
}
num++;
oppPiece = true;
}
col
level++;
row
}
}
if(oppPiece){
heuristic[l][r][c]
return num;
}
return num + 1;
}
private int check3DVertical(int l, int r, int c){
int oppToken = 0;
int num = 0;
boolean havePiece = false;
boolean oppPiece = false;
oppToken = getOppToken();
for(int level = 0; level < TicTacToe.board[0][0].length; level++){
if(TicTacToe.board[level][r][c] == token){
num++;
havePiece=true;
}
else if(TicTacToe.board[level][r][c] == oppToken){
if(havePiece){
heuristic[l][r][c]
return 0;
}
num++;
oppPiece = true;
}
}
if(oppPiece){
heuristic[l][r][c]
return num;
}
return num + 1;
}
public void update(int t){
gameCount++;
potWinsEverySpace = TicTacToe.potWinsEverySpace;
for(int level = 0; level < TicTacToe.board.length; level++){
for(int row = 0; row < TicTacToe.board[0].length; row++){
for(int col = 0; col < TicTacToe.board[0][0].length; col++){
if(TicTacToe.board[level][row][col] == t){
moveFrequency[level][row][col]++;
winPercentage[level][row][col] = moveFrequency[level][row][col] / gameCount;
}
else{
winPercentage[level][row][col] = moveFrequency[level][row][col] / gameCount;
}
}
}
}
}
public void printPercentage(){
for(int level = 0; level < winPercentage.length; level++){
System.out.println("Level: " + level);
for(int row = 0; row < winPercentage[0].length; row++){
for(int col = 0; col < winPercentage[0][0].length; col++){
System.out.print(winPercentage[level][row][col] + " ");
}
System.out.println("");
}
System.out.println("");
System.out.println("");
}
}
public void setWinPercentage(double[][][] x){
winPercentage = x;
}
}
|
package org.csstudio.trends.databrowser3.archive;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import org.csstudio.apputil.time.BenchmarkTimer;
import org.csstudio.archive.reader.ArchiveReader;
import org.csstudio.archive.reader.ArchiveRepository;
import org.csstudio.archive.reader.UnknownChannelException;
import org.csstudio.archive.reader.ValueIterator;
import org.csstudio.trends.databrowser3.Activator;
import org.csstudio.trends.databrowser3.Messages;
import org.csstudio.trends.databrowser3.model.ArchiveDataSource;
import org.csstudio.trends.databrowser3.model.PVItem;
import org.csstudio.trends.databrowser3.model.RequestType;
import org.csstudio.trends.databrowser3.model.TimeHelper;
import org.csstudio.trends.databrowser3.preferences.Preferences;
import org.diirt.vtype.VType;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.osgi.util.NLS;
/** Eclipse Job for fetching archived data.
* <p>
* Actually spawns another thread so that the 'main' job can
* poll the progress monitor for cancellation and ask the secondary
* thread to cancel.
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class ArchiveFetchJob extends Job
{
/** Poll period in millisecs */
private static final int POLL_PERIOD_MS = 1000;
/**to manage concurrency on postgresql*/
private final boolean concurrency;
/** Item for which to fetch samples */
final private PVItem item;
/** Start/End time */
final private Instant start, end;
/** Listener that's notified when (if) we completed OK */
final private ArchiveFetchJobListener listener;
/** Thread that performs the actual background work.
*
* Instead of directly accessing the archive, ArchiveFetchJob launches
* a WorkerThread for the actual archive access, so that the Job
* can then poll the progress monitor for cancellation and if
* necessary interrupt the WorkerThread which might be 'stuck'
* in a long running operation.
*/
class WorkerThread implements Runnable
{
private String message = "";
private volatile boolean cancelled = false;
/** Archive reader that's currently queried.
* Synchronize 'this' on access.
*/
private volatile ArchiveReader reader = null;
/** @return Message that somehow indicates progress */
public synchronized String getMessage()
{
return message;
}
/** Request thread to cancel its operation */
public synchronized void cancel()
{
cancelled = true;
synchronized (this)
{
if (reader != null)
reader.cancel();
}
}
/** {@inheritDoc} */
@Override
public void run()
{
Activator.getLogger().log(Level.FINE, "Starting {0}", ArchiveFetchJob.this);
final BenchmarkTimer timer = new BenchmarkTimer();
long samples = 0;
final int bins = Preferences.getPlotBins();
final ArchiveDataSource archives[] = item.getArchiveDataSources();
List<ArchiveDataSource> sourcesWhereChannelDoesntExist = new ArrayList<>();
for (int i=0; i<archives.length && !cancelled; ++i)
{
final ArchiveDataSource archive = archives[i];
final String url = archive.getUrl();
// Display "N/total", using '1' for the first sub-archive.
synchronized (this)
{
message = NLS.bind(Messages.ArchiveFetchDetailFmt,
new Object[]
{
archive.getName(),
(i+1),
archives.length
});
}
try
{
final ArchiveReader the_reader;
synchronized (this)
{
the_reader = reader = ArchiveRepository.getInstance().getArchiveReader(url);
}
the_reader.enableConcurrency(concurrency);
final ValueIterator value_iter;
try
{
if (item.getRequestType() == RequestType.RAW)
value_iter = the_reader.getRawValues(archive.getKey(), item.getResolvedName(),
start, end);
else
value_iter = the_reader.getOptimizedValues(archive.getKey(), item.getResolvedName(),
start, end, bins);
}
catch (UnknownChannelException e)
{
// Do not immediately notify about unknown channels. First search for the data in all archive
// sources and only report this kind of errors at the end
sourcesWhereChannelDoesntExist.add(archives[i]);
continue;
}
// Get samples into array
final List<VType> result = new ArrayList<VType>();
while (value_iter.hasNext())
result.add(value_iter.next());
samples += result.size();
item.mergeArchivedSamples(the_reader.getServerName(), result);
if (cancelled)
break;
value_iter.close();
}
catch (Exception ex)
{ // Tell listener unless it's the result of a 'cancel'?
if (! cancelled)
listener.archiveFetchFailed(ArchiveFetchJob.this, archive, ex);
// Continue with the next data source
}
finally
{
synchronized (this)
{
if (reader != null)
reader.close();
reader = null;
}
}
}
if (!sourcesWhereChannelDoesntExist.isEmpty() && !cancelled)
{
listener.channelNotFound(ArchiveFetchJob.this, sourcesWhereChannelDoesntExist.size() < archives.length,
sourcesWhereChannelDoesntExist
.toArray(new ArchiveDataSource[sourcesWhereChannelDoesntExist.size()]));
}
timer.stop();
if (!cancelled)
listener.fetchCompleted(ArchiveFetchJob.this);
Activator.getLogger().log(Level.FINE,
"Ended {0} with {1} samples in {2}",
new Object[] { ArchiveFetchJob.this, samples, timer });
}
@Override
public String toString()
{
return "WorkerTread for " + ArchiveFetchJob.this.toString();
}
}
/** Initialize
* @param item
* @param start
* @param end
* @param listener
*/
public ArchiveFetchJob(PVItem item, final Instant start,
final Instant end, final ArchiveFetchJobListener listener)
{
this(item, start, end, listener, false);
}
/**
* Construct a new job.
*
* @param item the item for which the data are fetched
* @param start the lower time boundary for the historic data
* @param end the upper time boundary for the history data
* @param listener the listener notified when the job is complete or an error happens
* @param enableConcurrency a parameter forwarded to the reader
*
* @see ArchiveReader#enableConcurrency(boolean)
*/
protected ArchiveFetchJob(PVItem item, final Instant start,
final Instant end, final ArchiveFetchJobListener listener, boolean enableConcurrency)
{
super(NLS.bind(Messages.ArchiveFetchJobFmt,
new Object[] { item.getResolvedDisplayName(), TimeHelper.format(start),
TimeHelper.format(end) }));
this.item = item;
this.start = start;
this.end = end;
this.listener = listener;
this.concurrency = enableConcurrency;
}
/** @return PVItem for which this job was created */
public PVItem getPVItem()
{
return item;
}
/** Job's main routine which starts and monitors WorkerThread */
@Override
protected IStatus run(final IProgressMonitor monitor)
{
if (item == null)
return Status.OK_STATUS;
monitor.beginTask(Messages.ArchiveFetchStart, IProgressMonitor.UNKNOWN);
final WorkerThread worker = new WorkerThread();
final Future<?> done = Activator.getThreadPool().submit(worker);
// Poll worker and progress monitor
long start = System.currentTimeMillis();
while (!done.isDone())
{ // Wait until worker is done, or time out to update info message
try
{
done.get(POLL_PERIOD_MS, TimeUnit.MILLISECONDS);
}
catch (Exception ex)
{
// Ignore
}
final long seconds = (System.currentTimeMillis() - start) / 1000;
final String info = NLS.bind(Messages.ArchiveFetchProgressFmt,
worker.getMessage(), seconds);
monitor.subTask(info);
// Try to cancel the worker in response to user's cancel request.
// Continues to cancel the worker until isDone()
if (monitor.isCanceled())
worker.cancel();
}
monitor.done();
return monitor.isCanceled() ? Status.CANCEL_STATUS : Status.OK_STATUS;
}
/** @return Debug string */
@Override
public String toString()
{
return getName();
}
}
|
package com.esri.arcgisruntime.samples.featurelayerdefinitionexpression;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import com.esri.arcgisruntime.datasource.arcgis.ServiceFeatureTable;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.Map;
import com.esri.arcgisruntime.mapping.view.MapView;
public class MainActivity extends AppCompatActivity {
MapView mMapView;
FeatureLayer mFeatureLayer;
boolean applyActive;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set up the bottom toolbar
createBottomToolbar();
// inflate MapView from layout
mMapView = (MapView) findViewById(R.id.mapView);
// create a map with the topographic basemap
Map map = new Map(Basemap.createTopographic());
// create feature layer with its service feature table
// create the service feature table
ServiceFeatureTable serviceFeatureTable = new ServiceFeatureTable(getResources().getString(R.string.sample_service_url));
// create the feature layer using the service feature table
mFeatureLayer = new FeatureLayer(serviceFeatureTable);
// add the layer to the map
map.getOperationalLayers().add(mFeatureLayer);
// set the map to be displayed in the mapview
mMapView.setMap(map);
// zoom to a view point of the USA
mMapView.setViewpointCenterWithScaleAsync(new Point(-13630845, 4544861, SpatialReferences.getWebMercator()), 600000);
}
private void applyDefinitionExpression() {
// apply a definition expression on the feature layer
// if this is called before the layer is loaded, it will be applied to the loaded layer
mFeatureLayer.setDefinitionExpression("req_Type = 'Tree Maintenance or Damage'");
}
private void resetDefinitionExpression() {
// set the definition expression to nothing (empty string, null also works)
mFeatureLayer.setDefinitionExpression("");
}
private void createBottomToolbar() {
Toolbar bottomToolbar = (Toolbar) findViewById(R.id.bottomToolbar);
bottomToolbar.inflateMenu(R.menu.menu_main);
bottomToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
// Handle action bar item clicks
int itemId = item.getItemId();
if(itemId == R.id.action_def_exp){
// check the state of the menu item
if (!applyActive) {
applyDefinitionExpression();
// change the text to reset
applyActive = true;
item.setTitle(R.string.action_reset);
} else {
resetDefinitionExpression();
// change the text to apply
applyActive = false;
item.setTitle(R.string.action_def_exp);
}
}
return true;
}
});
}
@Override
protected void onPause(){
super.onPause();
// pause MapView
mMapView.pause();
}
@Override
protected void onResume() {
super.onResume();
// resume MapView
mMapView.resume();
}
}
|
package org.ovirt.engine.ui.webadmin.section.main.view.tab.disk;
import javax.inject.Inject;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.idhandler.WithElementId;
import org.ovirt.engine.ui.common.uicommon.model.DetailModelProvider;
import org.ovirt.engine.ui.common.view.AbstractSubTabFormView;
import org.ovirt.engine.ui.common.widget.form.FormBuilder;
import org.ovirt.engine.ui.common.widget.form.FormItem;
import org.ovirt.engine.ui.common.widget.form.GeneralFormPanel;
import org.ovirt.engine.ui.common.widget.label.BooleanLabel;
import org.ovirt.engine.ui.common.widget.label.TextBoxLabel;
import org.ovirt.engine.ui.uicommonweb.models.disks.DiskGeneralModel;
import org.ovirt.engine.ui.uicommonweb.models.disks.DiskListModel;
import org.ovirt.engine.ui.webadmin.ApplicationConstants;
import org.ovirt.engine.ui.webadmin.gin.AssetProvider;
import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.disk.SubTabDiskGeneralPresenter;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Widget;
public class SubTabDiskGeneralView extends AbstractSubTabFormView<Disk, DiskListModel, DiskGeneralModel> implements SubTabDiskGeneralPresenter.ViewDef, Editor<DiskGeneralModel> {
interface ViewUiBinder extends UiBinder<Widget, SubTabDiskGeneralView> {
ViewUiBinder uiBinder = GWT.create(ViewUiBinder.class);
}
interface ViewIdHandler extends ElementIdHandler<SubTabDiskGeneralView> {
ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
}
interface Driver extends SimpleBeanEditorDriver<DiskGeneralModel, SubTabDiskGeneralView> {
}
TextBoxLabel alias = new TextBoxLabel();
TextBoxLabel description = new TextBoxLabel();
TextBoxLabel diskId = new TextBoxLabel();
TextBoxLabel lunId = new TextBoxLabel();
TextBoxLabel diskProfileName = new TextBoxLabel();
TextBoxLabel quotaName = new TextBoxLabel();
TextBoxLabel alignment = new TextBoxLabel();
BooleanLabel wipeAfterDelete = new BooleanLabel(constants.yes(), constants.no());
@UiField(provided = true)
@WithElementId
GeneralFormPanel formPanel;
FormBuilder formBuilder;
private final Driver driver = GWT.create(Driver.class);
private final static ApplicationConstants constants = AssetProvider.getConstants();
@Inject
public SubTabDiskGeneralView(DetailModelProvider<DiskListModel, DiskGeneralModel> modelProvider) {
super(modelProvider);
// Init formPanel
formPanel = new GeneralFormPanel();
initWidget(ViewUiBinder.uiBinder.createAndBindUi(this));
driver.initialize(this);
generateIds();
// Build a form using the FormBuilder
formBuilder = new FormBuilder(formPanel, 1, 8);
formBuilder.addFormItem(new FormItem(constants.aliasDisk(), alias, 0, 0), 2, 10);
formBuilder.addFormItem(new FormItem(constants.descriptionDisk(), description, 1, 0), 2, 10);
formBuilder.addFormItem(new FormItem(constants.idDisk(), diskId, 2, 0), 2, 10);
formBuilder.addFormItem(new FormItem(constants.diskAlignment(), alignment, 3, 0), 2, 10);
formBuilder.addFormItem(new FormItem(constants.lunIdSanStorage(), lunId, 4, 0) {
@Override
public boolean getIsAvailable() {
return getDetailModel().isLun();
}
}, 2, 10);
formBuilder.addFormItem(new FormItem(constants.diskProfile(), diskProfileName, 5, 0) {
@Override
public boolean getIsAvailable() {
return !getDetailModel().isLun();
}
}, 2, 10);
formBuilder.addFormItem(new FormItem(constants.quota(), quotaName, 6, 0) {
@Override
public boolean getIsAvailable() {
return getDetailModel().isQuotaAvailable();
}
}, 2, 10);
formBuilder.addFormItem(new FormItem(constants.wipeAfterDelete(), wipeAfterDelete, 7, 0) {
@Override
public boolean getIsAvailable() {
return getDetailModel().isImage();
}
}, 2, 10);
formBuilder.setRelativeColumnWidth(0, 12);
}
@Override
protected void generateIds() {
ViewIdHandler.idHandler.generateAndSetIds(this);
}
@Override
public void setMainTabSelectedItem(Disk selectedItem) {
driver.edit(getDetailModel());
formBuilder.update(getDetailModel());
}
}
|
package org.eclipse.oomph.projectconfig.presentation.sync;
import org.eclipse.oomph.preferences.PreferenceNode;
import org.eclipse.oomph.preferences.Property;
import org.eclipse.oomph.preferences.util.PreferencesUtil;
import org.eclipse.oomph.projectconfig.Project;
import org.eclipse.oomph.projectconfig.WorkspaceConfiguration;
import org.eclipse.oomph.projectconfig.impl.ProjectConfigPlugin;
import org.eclipse.oomph.projectconfig.presentation.ProjectConfigEditorPlugin;
import org.eclipse.oomph.projectconfig.presentation.sync.ProjectConfigSynchronizerPreferences.PropertyModificationHandling;
import org.eclipse.oomph.projectconfig.util.ProjectConfigUtil;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.osgi.service.prefs.BackingStoreException;
import org.osgi.service.prefs.Preferences;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
public final class ProjectConfigSynchronizer implements IStartup
{
private static final IWorkspace WORKSPACE = ResourcesPlugin.getWorkspace();
private static final IWorkspaceRoot WORKSPACE_ROOT = WORKSPACE.getRoot();
private WorkspaceConfiguration workspaceConfiguration;
private ProjectConfigSynchronizerDialog projectConfigSynchronizerDialog;
protected IResourceChangeListener resourceChangeListener = new IResourceChangeListener()
{
public void resourceChanged(IResourceChangeEvent event)
{
IResourceDelta delta = event.getDelta();
if (delta != null)
{
try
{
class ResourceDeltaVisitor implements IResourceDeltaVisitor
{
private Collection<IPath> changedPaths = new HashSet<IPath>();
public Collection<IPath> getChangedPaths()
{
return changedPaths;
}
public boolean visit(final IResourceDelta delta)
{
int type = delta.getResource().getType();
if (type == IResource.FOLDER)
{
// Visit the folder's children only if its the .settings folder.
IPath fullPath = delta.getFullPath();
if (!".settings".equals(fullPath.lastSegment()))
{
return false;
}
}
else if (type == IResource.FILE)
{
// Include only the *.prefs resources in the .settings folder.
IPath fullPath = delta.getFullPath();
if (fullPath.segmentCount() > 2 && "prefs".equals(fullPath.getFileExtension())
&& !ProjectConfigUtil.PROJECT_CONF_NODE_NAME.equals(fullPath.removeFileExtension().lastSegment()))
{
changedPaths.add(fullPath);
}
return false;
}
// Recursively visit only the workspace root, the projects, and the .settings folders in projects.
return true;
}
}
ResourceDeltaVisitor visitor = new ResourceDeltaVisitor();
delta.accept(visitor);
final Collection<IPath> changedPaths = visitor.getChangedPaths();
if (!changedPaths.isEmpty())
{
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable()
{
public void run()
{
final WorkspaceConfiguration newWorkspaceConfiguration = ProjectConfigUtil.getWorkspaceConfiguration();
try
{
newWorkspaceConfiguration.updatePreferenceProfileReferences();
Resource newWorkspaceConfigurationResource = newWorkspaceConfiguration.eResource();
Map<Property, Property> propertyMap = new LinkedHashMap<Property, Property>();
for (IPath preferenceNodePath : changedPaths)
{
String projectName = preferenceNodePath.segment(0);
Project oldProject = workspaceConfiguration.getProject(projectName);
Project newProject = newWorkspaceConfiguration.getProject(projectName);
if (newProject != null)
{
String preferenceNodeName = preferenceNodePath.removeFileExtension().lastSegment();
PreferenceNode oldPreferenceNode = oldProject == null ? null : oldProject.getPreferenceNode().getNode(preferenceNodeName);
PreferenceNode newPreferenceNode = newProject.getPreferenceNode().getNode(preferenceNodeName);
Map<Property, Property> modifiedProperties = collectModifiedProperties(workspaceConfiguration, oldPreferenceNode, newPreferenceNode);
if (!modifiedProperties.isEmpty())
{
for (Map.Entry<Property, Property> entry : modifiedProperties.entrySet())
{
Property property = entry.getKey();
String value = property.getValue();
Property preferenceProfileProperty = newProject.getProperty(property.getRelativePath());
if (preferenceProfileProperty != null)
{
String preferenceProfilePropertyValue = preferenceProfileProperty.getValue();
if (value == null ? preferenceProfilePropertyValue != null : !value.equals(preferenceProfilePropertyValue))
{
propertyMap.put(property, preferenceProfileProperty);
}
}
else
{
propertyMap.put(property, entry.getValue());
}
}
}
}
}
if (!propertyMap.isEmpty())
{
boolean dialogCreator = false;
IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
Shell shell = activeWorkbenchWindow.getShell();
if (projectConfigSynchronizerDialog == null
&& (configurationValidationPrompt || propertyModificationHandling == PropertyModificationHandling.PROMPT))
{
projectConfigSynchronizerDialog = new ProjectConfigSynchronizerDialog(shell);
projectConfigSynchronizerDialog.setWorkspaceConfiguration(newWorkspaceConfiguration);
dialogCreator = true;
}
Map<Property, Property> managedProperties = new HashMap<Property, Property>();
for (Map.Entry<Property, Property> propertyEntry : propertyMap.entrySet())
{
Property property = propertyEntry.getKey();
Property otherProperty = propertyEntry.getValue();
if (otherProperty != null && otherProperty.eResource() == newWorkspaceConfigurationResource)
{
if (propertyModificationHandling == PropertyModificationHandling.PROMPT)
{
projectConfigSynchronizerDialog.managedProperty(property, otherProperty);
}
managedProperties.put(property, otherProperty);
}
else
{
if (configurationValidationPrompt)
{
projectConfigSynchronizerDialog.unmanagedProperty(property, otherProperty);
}
}
}
if (projectConfigSynchronizerDialog != null)
{
if (dialogCreator)
{
ProjectConfigSynchronizerDialog dialog = projectConfigSynchronizerDialog;
projectConfigSynchronizerDialog.open();
if (dialog.hasUnmanagedProperties() && ProjectConfigSynchronizerPreferences.isEdit())
{
PreferenceDialog preferenceDialog = org.eclipse.ui.dialogs.PreferencesUtil.createPreferenceDialogOn(shell,
"org.eclipse.oomph.projectconfig.presentation.ProjectConfigPreferencePage", null, null);
preferenceDialog.open();
}
}
else
{
Shell dialogShell = projectConfigSynchronizerDialog.getShell();
Display display = dialogShell.getDisplay();
while (!dialogShell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
}
}
if (!managedProperties.isEmpty() && (propertyModificationHandling == PropertyModificationHandling.PROPAGATE
|| propertyModificationHandling == PropertyModificationHandling.PROMPT && ProjectConfigSynchronizerPreferences.isPropagate()))
{
for (Map.Entry<Property, Property> entry : managedProperties.entrySet())
{
Property managedProperty = entry.getKey();
Property managingProperty = entry.getValue();
try
{
Preferences preferences = PreferencesUtil.getPreferences(managingProperty.getParent(), false);
preferences.put(managingProperty.getName(), managedProperty.getValue());
}
catch (BackingStoreException ex)
{
ProjectConfigEditorPlugin.INSTANCE.log(ex);
}
}
try
{
WORKSPACE_ROOT.getWorkspace().run(new IWorkspaceRunnable()
{
public void run(IProgressMonitor monitor) throws CoreException
{
try
{
PreferencesUtil.getPreferences(newWorkspaceConfiguration.getInstancePreferenceNode().getParent().getNode("project"), false)
.flush();
}
catch (BackingStoreException ex)
{
ProjectConfigPlugin.INSTANCE.log(ex);
}
}
}, new NullProgressMonitor());
}
catch (CoreException ex)
{
ProjectConfigPlugin.INSTANCE.log(ex);
}
}
}
// We expect this processing of the managed property to cause another delta which will apply the
// preference profiles anyway, so
// don't do it now when we might overwrite the properties being propagated.
if (projectConfigSynchronizerDialog == null || !projectConfigSynchronizerDialog.hasManagedProperties())
{
newWorkspaceConfiguration.applyPreferenceProfiles();
}
}
finally
{
workspaceConfiguration = newWorkspaceConfiguration;
projectConfigSynchronizerDialog = null;
}
}
private Map<Property, Property> collectModifiedProperties(WorkspaceConfiguration workspaceConfiguration, PreferenceNode oldPreferenceNode,
PreferenceNode newPreferenceNode)
{
LinkedHashMap<Property, Property> result = new LinkedHashMap<Property, Property>();
collectModifiedProperties(result, workspaceConfiguration, oldPreferenceNode, newPreferenceNode);
return result;
}
private void collectModifiedProperties(Map<Property, Property> result, WorkspaceConfiguration workspaceConfiguration,
PreferenceNode oldPreferenceNode, PreferenceNode newPreferenceNode)
{
if (newPreferenceNode != null)
{
for (PreferenceNode newChild : newPreferenceNode.getChildren())
{
PreferenceNode oldChild = oldPreferenceNode == null ? null : oldPreferenceNode.getNode(newChild.getName());
if (oldChild == null)
{
for (Property newProperty : newChild.getProperties())
{
result.put(newProperty, null);
}
}
else
{
collectModifiedProperties(result, workspaceConfiguration, oldChild, newChild);
}
}
for (Property newProperty : newPreferenceNode.getProperties())
{
Property oldProperty = oldPreferenceNode == null ? null : oldPreferenceNode.getProperty(newProperty.getName());
if (oldProperty == null)
{
result.put(newProperty, null);
}
else
{
String newValue = newProperty.getValue();
String oldValue = oldProperty.getValue();
if (newValue == null ? oldValue != null : !newValue.equals(oldValue))
{
result.put(newProperty, oldProperty);
}
}
}
}
}
});
}
}
catch (CoreException exception)
{
ProjectConfigEditorPlugin.INSTANCE.log(exception);
}
}
}
};
private boolean configurationValidationPrompt = ProjectConfigSynchronizerPreferences.isConfigurationValidationPrompt();
private PropertyModificationHandling propertyModificationHandling = ProjectConfigSynchronizerPreferences.getPropertyModificationHandling();
public ProjectConfigSynchronizer()
{
ProjectConfigEditorPlugin.Implementation.setProjectConfigSynchronizer(this);
}
public void earlyStartup()
{
update();
}
public void stop()
{
WORKSPACE.removeResourceChangeListener(resourceChangeListener);
}
public void update()
{
if (ProjectConfigSynchronizerPreferences.isConfigurationManagementAutomatic())
{
new ProjectConfigUtil.CompletenessChecker()
{
@Override
protected void complete(WorkspaceConfiguration workspaceConfiguration)
{
ProjectConfigSynchronizer.this.workspaceConfiguration = workspaceConfiguration;
workspaceConfiguration.updatePreferenceProfileReferences();
}
};
WORKSPACE.addResourceChangeListener(resourceChangeListener);
}
else
{
WORKSPACE.removeResourceChangeListener(resourceChangeListener);
}
configurationValidationPrompt = ProjectConfigSynchronizerPreferences.isConfigurationValidationPrompt();
propertyModificationHandling = ProjectConfigSynchronizerPreferences.getPropertyModificationHandling();
}
}
|
package org.ow2.proactive.resourcemanager.gui.dialog;
import java.util.ArrayList;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.objectweb.proactive.core.config.ProActiveConfiguration;
import org.ow2.proactive.resourcemanager.exception.RMException;
import org.ow2.proactive.resourcemanager.frontend.RMAdmin;
import org.ow2.proactive.resourcemanager.gui.data.RMStore;
import org.ow2.proactive.resourcemanager.gui.dialog.nodesources.ConfigurablePanel;
import org.ow2.proactive.resourcemanager.gui.dialog.nodesources.NodeSourceName;
import org.ow2.proactive.resourcemanager.gui.views.ResourceExplorerView;
/**
* This class allow to pop up a dialogue to remove a source node.
*
* @author The ProActive Team
*/
public class CreateSourceDialog extends Dialog {
public class NodeSourceButtons extends Composite {
public NodeSourceButtons(Shell parent, int style) {
super(parent, style);
FormLayout layout = new FormLayout();
layout.marginHeight = 5;
layout.marginWidth = 5;
setLayout(layout);
Button okButton = new Button(this, SWT.NONE);
Button cancelButton = new Button(this, SWT.NONE);
okButton.setText("OK");
cancelButton.setText("Cancel");
FormData okFormData = new FormData();
okFormData.left = new FormAttachment(1, 100);
okFormData.width = 100;
okButton.setLayoutData(okFormData);
shell.setDefaultButton(okButton);
FormData cancelFormData = new FormData();
cancelFormData.left = new FormAttachment(okButton, 10);
cancelFormData.width = 100;
cancelButton.setLayoutData(cancelFormData);
okButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
try {
validateForm();
RMAdmin admin = RMStore.getInstance().getRMAdmin();
admin.createNodesource(name.getNodeSourceName(), infrastructure.getSelectedClass()
.getName(), infrastructure.getParameters(), policy.getSelectedClass()
.getName(), policy.getParameters());
shell.close();
} catch (Exception e) {
e.printStackTrace();
String message = e.getMessage();
if (e.getCause() != null) {
message = e.getCause().getMessage();
}
MessageDialog.openError(Display.getDefault().getActiveShell(),
"Cannot create nodesource", message);
}
}
});
cancelButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
shell.close();
}
});
pack();
}
protected void checkSubclass() {
}
}
private Shell shell;
private NodeSourceName name;
private ConfigurablePanel infrastructure;
private ConfigurablePanel policy;
private CreateSourceDialog(Shell parent) throws RMException {
// Pass the default styles here
super(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
// Load the proactive default configuration
ProActiveConfiguration.load();
// Init the display
Display display = parent.getDisplay();
// Init the shell
shell = new Shell(parent, SWT.BORDER | SWT.CLOSE);
shell.setText("Create a node source");
RowLayout layout = new RowLayout(SWT.VERTICAL);
layout.spacing = 5;
shell.setLayout(layout);
// creation
name = new NodeSourceName(shell, SWT.NONE);
infrastructure = new ConfigurablePanel(shell, "Node source infrastructure");
infrastructure.addComboValue("", null);
policy = new ConfigurablePanel(shell, "Node source policy");
policy.addComboValue("", null);
RMAdmin admin = RMStore.getInstance().getRMAdmin();
ArrayList<String> supportedInfrastructures = admin.getSupportedNodeSourceInfrastructures();
for (String className : supportedInfrastructures) {
try {
Class<?> cls = Class.forName(className);
infrastructure.addComboValue(beautifyName(cls.getSimpleName()), cls);
} catch (Throwable e) {
e.printStackTrace();
}
}
ArrayList<String> supportedPolicies = admin.getSupportedNodeSourcePolicies();
for (String className : supportedPolicies) {
try {
Class<?> cls = Class.forName(className);
policy.addComboValue(beautifyName(cls.getSimpleName()), cls);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
new NodeSourceButtons(shell, SWT.NONE);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* This method pop up a dialog for trying to connect a resource manager.
*
* @param parent the parent
*/
public static void showDialog(Shell parent) {
try {
new CreateSourceDialog(parent);
} catch (Exception e) {
e.printStackTrace();
String message = e.getMessage();
if (e.getCause() != null) {
message = e.getCause().getMessage();
}
MessageDialog.openError(Display.getDefault().getActiveShell(), "Cannot create nodesource",
message);
}
}
private void validateForm() {
if (name.getNodeSourceName().length() == 0) {
throw new RuntimeException("Node source name cannot be empty");
}
if (infrastructure.getSelectedClass() == null) {
throw new RuntimeException("Select node source infrastructure type");
}
if (policy.getSelectedClass() == null) {
throw new RuntimeException("Select node source policy type");
}
}
public static String beautifyName(String name) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
if (i == 0) {
buffer.append(Character.toUpperCase(ch));
} else if (i > 0 && (Character.isUpperCase(ch) || Character.isDigit(ch)) {
boolean nextCharInAupperCase = (i < name.length() - 1) &&
(Character.isUpperCase(name.charAt(i + 1)) || Character.isDigit(name.charAt(i + 1));
if (!nextCharInAupperCase) {
buffer.append(" " + ch);
} else {
buffer.append(ch);
}
} else {
buffer.append(ch);
}
}
return buffer.toString();
}
}
|
package com.ext.portlet.service.impl;
import com.ext.portlet.NoSuchProposalAttributeException;
import com.ext.portlet.NoSuchProposalException;
import com.ext.portlet.NoSuchProposalSupporterException;
import com.ext.portlet.NoSuchProposalVoteException;
import com.ext.portlet.ProposalAttributeKeys;
import com.ext.portlet.ProposalContestPhaseAttributeKeys;
import com.ext.portlet.discussions.DiscussionActions;
import com.ext.portlet.messaging.MessageUtil;
import com.ext.portlet.model.Contest;
import com.ext.portlet.model.ContestPhase;
import com.ext.portlet.model.ContestType;
import com.ext.portlet.model.DiscussionCategoryGroup;
import com.ext.portlet.model.FocusArea;
import com.ext.portlet.model.PlanSectionDefinition;
import com.ext.portlet.model.Proposal;
import com.ext.portlet.model.Proposal2Phase;
import com.ext.portlet.model.ProposalAttribute;
import com.ext.portlet.model.ProposalContestPhaseAttribute;
import com.ext.portlet.model.ProposalReference;
import com.ext.portlet.model.ProposalSupporter;
import com.ext.portlet.model.ProposalVersion;
import com.ext.portlet.model.ProposalVote;
import com.ext.portlet.service.ContestPhaseLocalServiceUtil;
import com.ext.portlet.service.FocusAreaLocalServiceUtil;
import com.ext.portlet.service.PlanSectionDefinitionLocalServiceUtil;
import com.ext.portlet.service.ProposalAttributeLocalServiceUtil;
import com.ext.portlet.service.ProposalContestPhaseAttributeLocalServiceUtil;
import com.ext.portlet.service.ProposalLocalServiceUtil;
import com.ext.portlet.service.ProposalReferenceLocalServiceUtil;
import com.ext.portlet.service.base.ProposalLocalServiceBaseImpl;
import com.ext.portlet.service.persistence.Proposal2PhasePK;
import com.ext.portlet.service.persistence.ProposalSupporterPK;
import com.ext.portlet.service.persistence.ProposalVersionPK;
import com.ext.portlet.service.persistence.ProposalVotePK;
import com.liferay.portal.NoSuchUserException;
import com.liferay.portal.kernel.bean.BeanReference;
import com.liferay.portal.kernel.bean.PortletBeanLocatorUtil;
import com.liferay.portal.kernel.dao.orm.Criterion;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
import com.liferay.portal.kernel.dao.orm.OrderFactoryUtil;
import com.liferay.portal.kernel.dao.orm.ProjectionFactoryUtil;
import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil;
import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.transaction.Transactional;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.GroupConstants;
import com.liferay.portal.model.MembershipRequest;
import com.liferay.portal.model.MembershipRequestConstants;
import com.liferay.portal.model.ResourceConstants;
import com.liferay.portal.model.Role;
import com.liferay.portal.model.RoleConstants;
import com.liferay.portal.model.User;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.service.GroupService;
import com.liferay.portal.service.MembershipRequestLocalServiceUtil;
import com.liferay.portal.service.ResourcePermissionLocalServiceUtil;
import com.liferay.portal.service.RoleLocalService;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.util.mail.MailEngineException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.xcolab.activityEntry.ActivityEntryType;
import org.xcolab.activityEntry.proposal.ProposalMemberAddedActivityEntry;
import org.xcolab.activityEntry.proposal.ProposalMemberRemovedActivityEntry;
import org.xcolab.activityEntry.proposal.ProposalSupporterAddedActivityEntry;
import org.xcolab.activityEntry.proposal.ProposalSupporterRemovedActivityEntry;
import org.xcolab.activityEntry.proposal.ProposalVoteActivityEntry;
import org.xcolab.activityEntry.proposal.ProposalVoteRetractActivityEntry;
import org.xcolab.activityEntry.proposal.ProposalVoteSwitchActivityEntry;
import org.xcolab.client.activities.ActivitiesClient;
import org.xcolab.client.activities.helper.ActivityEntryHelper;
import org.xcolab.client.comment.CommentClient;
import org.xcolab.enums.MembershipRequestStatus;
import org.xcolab.mail.EmailToAdminDispatcher;
import org.xcolab.proposals.events.ProposalAssociatedWithContestPhaseEvent;
import org.xcolab.proposals.events.ProposalMemberAddedEvent;
import org.xcolab.proposals.events.ProposalMemberRemovedEvent;
import org.xcolab.proposals.events.ProposalRemovedVoteEvent;
import org.xcolab.proposals.events.ProposalSupporterAddedEvent;
import org.xcolab.proposals.events.ProposalSupporterRemovedEvent;
import org.xcolab.proposals.events.ProposalVotedOnEvent;
import org.xcolab.services.EventBusService;
import org.xcolab.utils.TemplateReplacementUtil;
import org.xcolab.utils.UrlBuilder;
import org.xcolab.utils.judging.ProposalJudgingCommentHelper;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.mail.internet.AddressException;
import javax.portlet.PortletRequest;
/**
* The implementation of the proposal local service.
* <p/>
* <p>
* All custom service methods should be put in this class. Whenever methods are
* added, rerun ServiceBuilder to copy their definitions into the
* {@link com.ext.portlet.service.ProposalLocalService} interface.
* <p/>
* <p>
* This is a local service. Methods of this service will not have security
* checks based on the propagated JAAS credentials because this service can only
* be accessed from within the same VM.
* </p>
*
* @author janusz
* @see com.ext.portlet.service.base.ProposalLocalServiceBaseImpl
* @see com.ext.portlet.service.ProposalLocalServiceUtil
*/
public class ProposalLocalServiceImpl extends ProposalLocalServiceBaseImpl {
private static final Log _log = LogFactoryUtil.getLog(ProposalLocalServiceImpl.class);
private static final long ADMINISTRATOR_USER_ID = 10144L;
/**
* Default description of group working on a plan.
*/
public static final String DEFAULT_GROUP_DESCRIPTION = "Group working on <proposal/> %s";
@BeanReference(type = EventBusService.class)
private EventBusService eventBus;
@BeanReference(type = GroupService.class)
private GroupService groupService;
@BeanReference(type = RoleLocalService.class)
private RoleLocalService roleLocalService;
public ProposalLocalServiceImpl() {
}
/**
* <p>
* Creates new proposal, initializes it and associates it with contest phase. All related entities are
* created:
* </p>
* <ul>
* <li>liferay group</li>
* <li>discussion for proposal comments</li>
* <li>discussion for judges</li>
* <li>discussion for advisors</li>
* <li>discussion for</li>
* </ul>
* <p>
* Creation of all entities is wrapped into a transaction.
* </p>
*
* @param authorId id of proposal author
* @param contestPhaseId id of a contestPhase
* @return created proposal
* @throws SystemException in case of a Liferay error
* @throws PortalException in case of a Liferay error
* @author janusz
*/
@Override
@Transactional
public Proposal create(long authorId, long contestPhaseId) throws SystemException, PortalException {
long proposalId = counterLocalService.increment(Proposal.class.getName());
return create(authorId, contestPhaseId, proposalId, true);
}
/**
* <p>
* Creates new proposal, initializes it and associates it with contest phase. All related entities are
* created:
* </p>
* <ul>
* <li>liferay group</li>
* <li>discussion for proposal comments</li>
* <li>discussion for judges</li>
* <li>discussion for advisors</li>
* <li>discussion for</li>
* </ul>
* <p>
* Creation of all entities is wrapped into a transaction.
* </p>
*
* @param authorId id of proposal author
* @param contestPhaseId id of a contestPhase
* @return created proposal
* @throws SystemException in case of a Liferay error
* @throws PortalException in case of a Liferay error
* @author janusz
*/
@Override
@Transactional
public Proposal create(long authorId, long contestPhaseId, long proposalId, boolean publishActivity) throws SystemException, PortalException {
Proposal proposal = createProposal(proposalId);
proposal.setVisible(true);
proposal.setAuthorId(authorId);
proposal.setCreateDate(new Date());
ContestPhase contestPhase = ContestPhaseLocalServiceUtil.getContestPhase(contestPhaseId);
final Contest contest = contestLocalService.fetchContest(contestPhase.getContestPK());
ContestType contestType = contestTypeLocalService.getContestType(contest);
// create discussions
final String proposalEntityName = contestType.getProposalName()+" ";
DiscussionCategoryGroup proposalDiscussion = discussionCategoryGroupLocalService
.createDiscussionCategoryGroup(proposalEntityName + proposalId + " main discussion");
proposalDiscussion.setUrl(UrlBuilder.getProposalCommentsUrl(contest, proposal));
discussionCategoryGroupLocalService.updateDiscussionCategoryGroup(proposalDiscussion);
proposal.setDiscussionId(proposalDiscussion.getId());
DiscussionCategoryGroup resultsDiscussion = discussionCategoryGroupLocalService
.createDiscussionCategoryGroup(proposalEntityName + proposalId + " results discussion");
resultsDiscussion.setIsQuiet(true);
discussionCategoryGroupLocalService.updateDiscussionCategoryGroup(resultsDiscussion);
proposal.setResultsDiscussionId(resultsDiscussion.getId());
DiscussionCategoryGroup judgesDiscussion = discussionCategoryGroupLocalService
.createDiscussionCategoryGroup(proposalEntityName + proposalId + " judges discussion");
judgesDiscussion.setIsQuiet(true);
discussionCategoryGroupLocalService.updateDiscussionCategoryGroup(judgesDiscussion);
proposal.setJudgeDiscussionId(judgesDiscussion.getId());
DiscussionCategoryGroup advisorsDiscussion = discussionCategoryGroupLocalService
.createDiscussionCategoryGroup(proposalEntityName + proposalId + " advisors discussion");
advisorsDiscussion.setIsQuiet(true);
discussionCategoryGroupLocalService.updateDiscussionCategoryGroup(advisorsDiscussion);
proposal.setAdvisorDiscussionId(advisorsDiscussion.getId());
DiscussionCategoryGroup fellowsDiscussion = discussionCategoryGroupLocalService
.createDiscussionCategoryGroup(proposalEntityName + proposalId + " fellows discussion");
fellowsDiscussion.setIsQuiet(true);
discussionCategoryGroupLocalService.updateDiscussionCategoryGroup(fellowsDiscussion);
proposal.setFellowDiscussionId(fellowsDiscussion.getId());
// create group
Group group = createGroupAndSetUpPermissions(authorId, proposalId, contest);
proposal.setGroupId(group.getGroupId());
addProposal(proposal);
if (contestPhaseId > 0) {
// associate proposal with phase
Proposal2Phase p2p = proposal2PhaseLocalService.createProposal2Phase(new Proposal2PhasePK(proposalId, contestPhaseId));
p2p.setVersionFrom(proposal.getCurrentVersion());
p2p.setVersionTo(-1);
proposal2PhaseLocalService.addProposal2Phase(p2p);
if (publishActivity) {
eventBus.post(new ProposalAssociatedWithContestPhaseEvent(proposal,
contestPhaseLocalService.getContestPhase(contestPhaseId), UserLocalServiceUtil.getUser(authorId)));
}
}
// Automatically subscribe author to own proposal
subscribe(proposalId, authorId);
return proposal;
}
@Override
@Transactional
public void setVisibility(Long proposalId, Boolean visibility, Long authorId) throws SystemException, PortalException {
Proposal proposal = ProposalLocalServiceUtil.getProposal(proposalId);
proposal.setVisible(visibility);
ProposalLocalServiceUtil.updateProposal(proposal);
proposalAttributeLocalService.setAttribute(authorId, proposalId, ProposalAttributeKeys.VISIBLE, (visibility) ? 1L : 0L);
}
/**
* <p>Returns a list of all proposal version descriptors.</p>
*
* @param proposalId id of a proposal
* @return list of proposal versions covering entire change history for a proposal
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
* @author janusz
*/
@Override
public List<ProposalVersion> getProposalVersions(long proposalId) throws PortalException, SystemException {
return proposalVersionPersistence.findByProposalId(proposalId);
}
/**
* <p>Returns a concrete proposal version descriptor.</p>
*
* @param proposalId id of a proposal
* @param version version of a proposal
* @return proposal version descriptor
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
* @author janusz
*/
@Override
public ProposalVersion getProposalVersion(long proposalId, int version) throws PortalException, SystemException {
return proposalVersionLocalService.getProposalVersion(new ProposalVersionPK(proposalId, version));
}
/**
* <p>Returns a list of proposals associated with given contest phase</p>
*
* @param contestPhaseId id of a contest phase
* @return list of proposals from given contest phase
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
public List<Proposal> getProposalsInContestPhase(long contestPhaseId) throws PortalException, SystemException {
List<Proposal> proposals = new ArrayList<>();
for (Proposal2Phase proposal2Phase : proposal2PhasePersistence.findByContestPhaseId(contestPhaseId)) {
Proposal proposal = getProposal(proposal2Phase.getProposalId());
// set proper version for proposal to reflect max version that proposal has reached at given phase
if (proposal2Phase.getVersionTo() > 0) {
proposal.setCurrentVersion(proposal2Phase.getVersionTo());
}
proposals.add(proposal);
}
return proposals;
}
@Override
public List<Proposal> getProposalsInContestPhase(long contestPhaseId, String sortProperty, boolean sortAscending, int start, int end)
throws SystemException, NoSuchProposalException {
List<Proposal> proposals = new ArrayList<>();
for (Proposal2Phase proposal2Phase : proposal2PhasePersistence.findByContestPhaseId(contestPhaseId)) {
proposals.add(proposalPersistence.findByPrimaryKey(proposal2Phase.getProposalId()));
}
return proposals;
}
/**
* <p>Returns a list of proposals associated with the given contest phase which are both generally visible and visible in the given contest phase</p>
*
* @param contestPhaseId id of a contest phase
* @return list of proposals from given contest phase
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
public List<Proposal> getActiveProposalsInContestPhase(long contestPhaseId)
throws PortalException, SystemException {
final DynamicQuery phaseProposals = DynamicQueryFactoryUtil.forClass(Proposal2Phase.class, "phaseProposalIds");
phaseProposals.setProjection(ProjectionFactoryUtil.property("phaseProposalIds.primaryKey.proposalId"));
phaseProposals.add(PropertyFactoryUtil.forName("phaseProposalIds.primaryKey.contestPhaseId").eq(contestPhaseId));
final DynamicQuery phaseInvisibleProposals = DynamicQueryFactoryUtil.forClass(ProposalContestPhaseAttribute.class, "proposalContestPhaseAttributes");
phaseInvisibleProposals.setProjection(ProjectionFactoryUtil.property("proposalContestPhaseAttributes.proposalId"));
phaseInvisibleProposals.add(PropertyFactoryUtil.forName("contestPhaseId").eq(contestPhaseId));
phaseInvisibleProposals.add(PropertyFactoryUtil.forName("proposalContestPhaseAttributes.name").eq(ProposalContestPhaseAttributeKeys.VISIBLE));
phaseInvisibleProposals.add(PropertyFactoryUtil.forName("proposalContestPhaseAttributes.numericValue").eq(0L));
final DynamicQuery proposalsInPhaseNotDeleted = DynamicQueryFactoryUtil.forClass(Proposal.class, "proposal");
proposalsInPhaseNotDeleted.add(PropertyFactoryUtil.forName("proposal.proposalId").in(phaseProposals))
.add(PropertyFactoryUtil.forName("proposal.visible").eq(true))
.add(PropertyFactoryUtil.forName("proposal.proposalId").notIn(phaseInvisibleProposals));
return dynamicQuery(proposalsInPhaseNotDeleted);
}
/**
* <p>Returns a list of proposals associated with given contest</p>
*
* @param contestId id of a contest phase
* @return list of proposals from given contest
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
public List<Proposal> getProposalsInContest(long contestId) throws PortalException, SystemException {
List<Proposal> proposals = new ArrayList<>();
ContestPhase lastOrActivePhase = contestLocalService.getActiveOrLastPhase(contestLocalService.getContest(contestId));
if (lastOrActivePhase == null) {
return proposals;
}
for (Proposal2Phase proposal2Phase : proposal2PhasePersistence.findByContestPhaseId(lastOrActivePhase.getContestPhasePK())) {
Proposal proposal = getProposal(proposal2Phase.getProposalId());
// set proper version for proposal to reflect max version that proposal has reached at given phase
if (proposal2Phase.getVersionTo() > 0) {
proposal.setCurrentVersion(proposal2Phase.getVersionTo());
}
proposals.add(proposal);
}
return proposals;
}
/**
* Retrieves all proposals for which a user is either the author or member of the author group (proposals to which a user has contributed)
*
* @param userId The userId of the user
* @return A list of proposals the user has contributed to
* @throws SystemException
*/
@Override
public List<Proposal> getUserProposals(long userId) throws SystemException, PortalException {
// Get all groups the user is in
List<Long> groupIds = new ArrayList<>();
User user = userLocalService.getUser(userId);
List<Group> groups = user.getGroups();
for (Group group : groups) {
groupIds.add(group.getGroupId());
}
Criterion criterion = RestrictionsFactoryUtil.eq("authorId", userId);
criterion = RestrictionsFactoryUtil.or(criterion, RestrictionsFactoryUtil.in("groupId", groupIds));
final String ENTITY_CLASS_LOADER_CONTEXT = "plansProposalsFacade-portlet";
final DynamicQuery query = DynamicQueryFactoryUtil.forClass(Proposal.class, (ClassLoader) PortletBeanLocatorUtil.locate(
ENTITY_CLASS_LOADER_CONTEXT, "portletClassLoader"))
.add(criterion)
.add(PropertyFactoryUtil.forName("visible").eq(true))
.addOrder(OrderFactoryUtil.desc("createDate"));
//make an editable copy so we can remove proposals
List<Proposal> proposals = new ArrayList<>(proposalLocalService.dynamicQuery(query));
for (Iterator<Proposal> iterator = proposals.iterator(); iterator.hasNext(); ) {
Proposal proposal = iterator.next();
if (isDeleted(proposal)) {
iterator.remove();
}
}
return proposals;
}
/**
* <p>Returns count of proposals associated with given contest phase</p>
*
* @param contestPhaseId id of a contest phase
* @return count of proposals from given contest phase
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
public long countProposalsInContestPhase(long contestPhaseId) throws PortalException, SystemException {
List<Proposal> activeProposals = getActiveProposalsInContestPhase(contestPhaseId);
return activeProposals.size();
}
/**
* <p>Returns list of proposal team members</p>
*
* @param proposalId proposal id
* @return list of proposal team members
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
public List<User> getMembers(long proposalId) throws SystemException, PortalException {
Proposal proposal = ProposalLocalServiceUtil.getProposal(proposalId);
return UserLocalServiceUtil.getGroupUsers(proposal.getGroupId());
}
/**
* <p>Returns list of proposal supporters</p>
*
* @param proposalId proposal id
* @return list of proposal supporters
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
public List<User> getSupporters(long proposalId) throws SystemException, PortalException {
List<User> ret = new ArrayList<>();
for (ProposalSupporter supporter : proposalSupporterPersistence.findByProposalId(proposalId)) {
try {
ret.add(UserLocalServiceUtil.getUser(supporter.getUserId()));
} catch(NoSuchUserException e){
_log.warn("Could not add proposal supporter", e);
}
}
return ret;
}
/**
* <p>Returns number of proposal supporters</p>
*
* @param proposalId proposal id
* @return number of proposal supporters
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
public int getSupportersCount(long proposalId) throws SystemException, PortalException {
return proposalSupporterPersistence.countByProposalId(proposalId);
}
/**
* <p>Returns true if user is a proposal supporter, false otherwise.</p>
*
* @param proposalId proposal id
* @return true if user is a proposal supporter, false otherwise
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
public boolean isSupporter(long proposalId, long userId) throws SystemException, PortalException {
try {
proposalSupporterPersistence.findByPrimaryKey(new ProposalSupporterPK(proposalId, userId));
return true;
} catch (NoSuchProposalSupporterException e) {
return false;
}
}
/**
* <p>Adds supporter to a proposal</p>
*
* @param proposalId id of a proposal
* @param userId id of a supported to be added
* @throws SystemException in case of an LR error
* @throws PortalException
*/
@Override
@Transactional
public void addSupporter(long proposalId, long userId) throws SystemException, PortalException {
addSupporter(proposalId, userId, true);
}
/**
* <p>Adds supporter to a proposal</p>
*
* @param proposalId id of a proposal
* @param userId id of a supported to be added
* @throws SystemException in case of an LR error
* @throws PortalException
*/
@Override
@Transactional
public void addSupporter(long proposalId, long userId, boolean publishActivity) throws SystemException, PortalException {
ProposalSupporter supporter =
proposalSupporterLocalService.createProposalSupporter(new ProposalSupporterPK(proposalId, userId));
supporter.setCreateDate(new Date());
proposalSupporterLocalService.addProposalSupporter(supporter);
if (publishActivity) {
eventBus.post(new ProposalSupporterAddedEvent(getProposal(proposalId), userLocalService.getUser(userId)));
ActivityEntryHelper.createActivityEntry(userId,proposalId,null,
new ProposalSupporterAddedActivityEntry());
}
}
/**
* <p>Retracts support from a proposal</p>
*
* @param proposalId id of a proposal
* @param userId id of a supported to be removed
* @throws SystemException in case of an LR error
* @throws PortalException
*/
@Override
@Transactional
public void removeSupporter(long proposalId, long userId) throws SystemException, PortalException {
ProposalSupporter supporter =
proposalSupporterLocalService.createProposalSupporter(new ProposalSupporterPK(proposalId, userId));
proposalSupporterLocalService.deleteProposalSupporter(supporter);
eventBus.post(new ProposalSupporterRemovedEvent(getProposal(proposalId), userLocalService.getUser(userId)));
ActivityEntryHelper.createActivityEntry(userId,proposalId,null,
new ProposalSupporterRemovedActivityEntry());
}
/**
* <p>Returns list of users that have voted for a proposal in given contest phase</p>
*
* @param proposalId proposal id
* @param contestPhaseId contest phase id
* @return list of proposal voters
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
public List<User> getVoters(long proposalId, long contestPhaseId) throws SystemException, PortalException {
List<User> ret = new ArrayList<>();
for (ProposalVote proposalVote : proposalVotePersistence.findByProposalIdContestPhaseId(proposalId, contestPhaseId)) {
ret.add(UserLocalServiceUtil.getUser(proposalVote.getUserId()));
}
return ret;
}
/**
* <p>Return number of users that have voted for a proposal in given contest phase</p>
*
* @param proposalId proposal id
* @param contestPhaseId contest phase id
* @return number of votes
* @throws SystemException in case of an LR error
*/
@Override
public long getVotesCount(long proposalId, long contestPhaseId) throws SystemException {
return proposalVotePersistence.countByProposalIdContestPhaseId(proposalId, contestPhaseId);
}
/**
* <p>Adds a user vote to a proposal in context of given contest phase. If user has already voted
* for different proposal in this phase, then that vote is removed first. User has only one vote
* in one contestPhase.</p>
*
* @param proposalId id of a proposal
* @param contestPhaseId id of a contest phase
* @param userId id of an user
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
@Transactional
public void addVote(long proposalId, long contestPhaseId, long userId)
throws SystemException, PortalException {
addVote(proposalId, contestPhaseId, userId, true);
}
/**
* <p>Adds a user vote to a proposal in context of given contest phase. If user has already voted
* for different proposal in this phase, then that vote is removed first. User has only one vote
* in one contestPhase.</p>
*
* @param proposalId id of a proposal
* @param contestPhaseId id of a contest phase
* @param userId id of an user
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
@Transactional
public void addVote(long proposalId, long contestPhaseId, long userId, boolean publishActivity)
throws SystemException, PortalException {
// retract any vote that user has given to any proposal in context of provided phase
boolean voted = hasUserVoted(proposalId, contestPhaseId, userId);
if (voted) {
removeVote(contestPhaseId, userId);
}
// add vote to a proposal
ProposalVote vote = proposalVoteLocalService.createProposalVote(new ProposalVotePK(contestPhaseId, userId));
vote.setCreateDate(new Date());
vote.setProposalId(proposalId);
vote.setIsValid(true);
proposalVoteLocalService.addProposalVote(vote);
if (publishActivity) {
eventBus.post(new ProposalVotedOnEvent(getProposal(proposalId), userLocalService.getUser(userId), voted));
if(!voted) {
ActivityEntryHelper.createActivityEntry(userId, proposalId, null,
new ProposalVoteActivityEntry());
}else{
ActivityEntryHelper.createActivityEntry(userId, proposalId, null,
new ProposalVoteSwitchActivityEntry());
}
}
}
/**
* <p>Retracts user vote in context of a contest phase.</p>
*
* @param contestPhaseId id of a contest phase
* @param userId id of an user
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
@Transactional
public void removeVote(long contestPhaseId, long userId) throws SystemException, PortalException {
try {
ProposalVote proposalVote = proposalVoteLocalService.findByProposalIdContestPhaseIdUserId(contestPhaseId, userId);
proposalVoteLocalService.deleteProposalVote(proposalVote);
eventBus.post(new ProposalRemovedVoteEvent(getProposal(proposalVote.getProposalId()), userLocalService.getUser(userId)));
ActivityEntryHelper.createActivityEntry(userId,proposalVote.getProposalId(),null,
new ProposalVoteRetractActivityEntry());
} catch (NoSuchProposalVoteException ignored) { }
}
/**
* <p>Returns number of comments in discussion associated with this proposal</p>
*
* @param proposalId proposal id
* @return number of comments
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
public long getCommentsCount(long proposalId) throws SystemException, PortalException {
Proposal proposal = getProposal(proposalId);
final long discussionId = proposal.getDiscussionId();
if (discussionId > 0) {
return CommentClient.countComments(discussionId);
}
return 0;
}
/**
* <p>Returns number of fellow review comments in discussion associated with this proposal</p>
*
* @param proposalId proposal id
* @return number of comments
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
public long getFellowReviewCommentsCount(long proposalId) throws SystemException, PortalException {
Proposal proposal = getProposal(proposalId);
final long fellowDiscussionId = proposal.getFellowDiscussionId();
if (fellowDiscussionId > 0) {
return CommentClient.countComments(fellowDiscussionId);
}
return 0;
}
/**
* <p>Tells if user is a member of a proposal team</p>
*
* @param proposalId id of a proposal
* @param userId id of an user
* @return true if user is a member of given proposal team, false otherwise
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
public boolean isUserAMember(long proposalId, long userId) throws SystemException, PortalException {
Proposal proposal = getProposal(proposalId);
return GroupLocalServiceUtil.hasUserGroup(userId, proposal.getGroupId());
}
/**
* <p>Returns true if proposal is open (so it can be edited by any user).</p>
*
* @param proposalId id of proposal
* @return true if plan is open, false otherwise
* @throws PortalException in case of an LR error
* @throws SystemException in case of an LR error
*/
@Override
public boolean isOpen(long proposalId) throws PortalException, SystemException {
try {
ProposalAttribute attribute = proposalAttributeLocalService.getAttribute(proposalId, ProposalAttributeKeys.OPEN, 0);
return attribute.getNumericValue() > 0;
} catch (NoSuchProposalAttributeException e) {
// ignore
}
return false;
}
/**
* <p>Returns all team membership requests for a proposal.</p>
*
* @param proposalId proposal id
* @return list of membership requests
* @throws SystemException in case of LR error
* @throws PortalException in case of LR error
*/
@Override
public List<MembershipRequest> getMembershipRequests(long proposalId) throws SystemException, PortalException {
Proposal proposal = getProposal(proposalId);
List<MembershipRequest> invited = MembershipRequestLocalServiceUtil.search(proposal.getGroupId(),
MembershipRequestStatus.STATUS_PENDING_INVITED, 0, Integer.MAX_VALUE);
List<MembershipRequest> requested = MembershipRequestLocalServiceUtil.search(proposal.getGroupId(),
MembershipRequestStatus.STATUS_PENDING_REQUESTED, 0, Integer.MAX_VALUE);
List<MembershipRequest> olderRequests = MembershipRequestLocalServiceUtil.search(proposal.getGroupId(),
MembershipRequestConstants.STATUS_PENDING, 0, Integer.MAX_VALUE);
List<MembershipRequest> combined = new ArrayList<>();
if(invited!=null&&invited.size()> 0){combined.addAll(invited);}
if(requested!=null&&requested.size()> 0){combined.addAll(requested);}
if(olderRequests!=null&&olderRequests.size()> 0){combined.addAll(olderRequests);}
return combined;
}
/**
* <p>Sends a request to join proposal team</p>
*
* @param proposalId proposal id
* @param userId user id
* @param comment optional comment
* @throws PortalException in case of LR error
* @throws SystemException in case of LR error
*/
@Override
public MembershipRequest addMembershipRequest(long proposalId, long userId, String comment) throws PortalException, SystemException {
Proposal proposal = getProposal(proposalId);
return MembershipRequestLocalServiceUtil.addMembershipRequest(userId, proposal.getGroupId(), comment == null? StringPool.BLANK : comment, null);
}
/**
* <p>Sends a request to join proposal team</p>
*
* @param proposalId proposal id
* @param userId user id
* @param comment optional comment
* @throws PortalException in case of LR error
* @throws SystemException in case of LR error
*/
@Override
public MembershipRequest addRequestedMembershipRequest(long proposalId, long userId, String comment) throws PortalException, SystemException {
Proposal proposal = getProposal(proposalId);
MembershipRequest membershipRequest = addMembershipRequest(proposalId,userId,comment);
MembershipRequestLocalServiceUtil.updateStatus(0l,membershipRequest.getMembershipRequestId(),null,
MembershipRequestStatus.STATUS_PENDING_REQUESTED,false,null);
return membershipRequest;
}
/**
* <p>Sends a request to join proposal team</p>
*
* @param proposalId proposal id
* @param userId user id
* @param comment optional comment
* @throws PortalException in case of LR error
* @throws SystemException in case of LR error
*/
@Override
public MembershipRequest addInvitedMembershipRequest(long proposalId, long userId, String comment) throws PortalException, SystemException {
Proposal proposal = getProposal(proposalId);
MembershipRequest membershipRequest = addMembershipRequest(proposalId,userId,comment);
MembershipRequestLocalServiceUtil.updateStatus(0l,membershipRequest.getMembershipRequestId(),null,
MembershipRequestStatus.STATUS_PENDING_INVITED,false,null);
return membershipRequest;
}
/**
* <p>Remove a user from a proposal team</p>
*
* @param proposalId proposal id
* @param userId user id
* @throws PortalException in case of LR error
* @throws SystemException in case of LR error
*/
@Override
public void removeUserFromTeam(long proposalId, long userId) throws PortalException, SystemException {
Proposal proposal = getProposal(proposalId);
if (userId == proposal.getAuthorId()) {
final String errorMessage = String.format("Cannot delete user %d from proposal %d: userId == proposal.getAuthorId()", userId, proposalId);
try {
throw new PortalException(errorMessage);
} catch(PortalException e) {
//TODO: remove debug email
StringBuilder stringBuilder = new StringBuilder();
User deletedUser = UserLocalServiceUtil.fetchUser(userId);
stringBuilder.append(String.format("Deleted member: %s, %d <br/>", deletedUser.getScreenName(), deletedUser.getUserId()));
stringBuilder.append(String.format("Deleted from group: %d <br/>", proposal.getGroupId()));
stringBuilder.append(String.format("Proposal: %d <br/>", proposalId));
stringBuilder.append("<br/>Stack trace: <br/>");
stringBuilder.append(ExceptionUtils.getStackTrace(e));
new EmailToAdminDispatcher(errorMessage, stringBuilder.toString()).sendMessage();
throw e;
}
}
GroupLocalServiceUtil.unsetUserGroups(userId, new long[]{proposal.getGroupId()});
eventBus.post(new ProposalMemberRemovedEvent(proposal, userLocalService.getUser(userId)));
ActivityEntryHelper.createActivityEntry(userId,proposalId,null,
new ProposalMemberRemovedActivityEntry());
}
/**
* <p>Denies user as a member of proposal team</p>
*
* @param proposalId proposal id
* @param userId user id
* @throws PortalException in case of LR error
* @throws SystemException in case of LR error
*/
@Override
public void dennyMembershipRequest(long proposalId, long userId, long membershipRequestId, String reply, long updateAuthorId)
throws PortalException, SystemException {
if (hasUserRequestedMembership(proposalId, userId)) {
MembershipRequestLocalServiceUtil.updateStatus(userId, membershipRequestId, reply,
MembershipRequestConstants.STATUS_DENIED, false, null);
}
}
/**
* <p>Approves user as a member of proposal team</p>
*
* @param proposalId proposal id
* @param userId user id
* @throws PortalException in case of LR error
* @throws SystemException in case of LR error
*/
@Override
public void approveMembershipRequest(long proposalId, Long userId, MembershipRequest request, String reply, Long updateAuthorId)
throws PortalException, SystemException {
if (hasUserRequestedMembership(proposalId, userId)) {
MembershipRequestLocalServiceUtil.updateStatus(userId, request.getMembershipRequestId(), reply,
MembershipRequestConstants.STATUS_APPROVED, true, null);
eventBus.post(new ProposalMemberAddedEvent(getProposal(proposalId), userLocalService.getUser(userId)));
ActivityEntryHelper.createActivityEntry(userId,proposalId,null,
new ProposalMemberAddedActivityEntry());
if (!isSubscribed(proposalId, userId)) {
subscribe(proposalId, userId);
}
}
}
/**
* <p>Tells if user has requested membership of given plan</p>
*
* @param proposalId proposal id
* @param userId user id
* @return true if user has requested membership, false otherwise
* @throws PortalException in case of LR error
* @throws SystemException in case of LR error
*/
@Override
public boolean hasUserRequestedMembership(long proposalId, long userId) throws PortalException, SystemException {
Proposal proposal = ProposalLocalServiceUtil.getProposal(proposalId);
boolean hasRequested = !MembershipRequestLocalServiceUtil.getMembershipRequests(userId, proposal.getGroupId(),
MembershipRequestStatus.STATUS_PENDING_REQUESTED).isEmpty();
boolean hasBeenInvited = !MembershipRequestLocalServiceUtil.getMembershipRequests(userId, proposal.getGroupId(),
MembershipRequestStatus.STATUS_PENDING_INVITED).isEmpty();
return hasRequested||hasBeenInvited;
}
/**
* <p>Adds user to a proposal team if proposal is open and user is not a member already</p>
*
* @param proposalId proposal id
* @param userId user id
* @throws PortalException in case of LR error
* @throws SystemException in case of LR error
*/
@Override
public void joinIfNotAMemberAndProposalIsOpen(long proposalId, long userId) throws PortalException, SystemException {
Proposal proposal = ProposalLocalServiceUtil.getProposal(proposalId);
if (isOpen(proposalId) && !isUserAMember(proposalId, userId)) {
GroupLocalServiceUtil.addUserGroups(userId, new long[]{proposal.getGroupId()});
}
}
/**
* <p>Returns true if user is subscribed to given proposal</p>
*
* @param proposalId proposal id
* @param userId user id
* @return true if user has subscribed to a proposal, false otherwise
* @throws PortalException in case of LR error
* @throws SystemException in case of LR error
*/
@Override
public boolean isSubscribed(long proposalId, long userId) throws PortalException, SystemException {
return activitySubscriptionLocalService.isSubscribed(userId, Proposal.class, proposalId, 0, "");
}
/**
* <p>Subscribes user to a proposal</p>
*
* @param proposalId proposal id
* @param userId user id
* @throws PortalException in case of LR error
* @throws SystemException in case of LR error
*/
@Override
public void subscribe(long proposalId, long userId) throws PortalException, SystemException {
subscribe(proposalId, userId, false);
}
/**
* <p>Subscribes user to a proposal (supports manual and automatic subscriptions).
* Automatic subscription is created when user is being subscribed indirectly
* (ie. when new proposal is created in a contest to which user is subscribed). </p>
*
* @param proposalId proposal id
* @param userId user id
* @param automatic if this is an automatic subscription
* @throws PortalException in case of LR error
* @throws SystemException in case of LR error
*/
@Override
public void subscribe(long proposalId, long userId, boolean automatic) throws PortalException, SystemException {
// activitySubscriptionLocalService.addSubscription(Proposal.class, proposalId, 0, "", userId, automatic);
ActivitiesClient.addSubscription(ActivityEntryType.PROPOSOSAL.getPrimaryTypeId(),proposalId,0, null, userId);
Proposal proposal = getProposal(proposalId);
/*
DiscussionCategoryGroup dcg = discussionCategoryGroupLocalService.getDiscussionCategoryGroup(proposal.getDiscussionId());
activitySubscriptionLocalService.addSubscription(DiscussionCategoryGroup.class, dcg.getPrimaryKey(), 0, "", userId, automatic);
*/
ActivitiesClient.addSubscription(ActivityEntryType.DISCUSSION.getPrimaryTypeId(),proposal.getDiscussionId(),0, null, userId);
}
/**
* <p>Unsubscribes user from given proposal</p>
*
* @param proposalId proposal id
* @param userId user id
* @throws PortalException in case of LR error
* @throws SystemException in case of LR error
*/
@Override
public void unsubscribe(long proposalId, long userId) throws PortalException, SystemException {
unsubscribe(proposalId, userId, false);
}
/**
* <p>Unsubscribes user from given proposal (supports removal of automatic subscriptions).
* If user is unsubscribing manually then subscription is removed without any conditions,
* but if this is removal of an automatic subscription then a "automaticSubscriptionCounter"
* is decreased by 1 for this subscription and if it reaches 0 then subscription is removed. </p>
*
* @param proposalId proposal id
* @param userId user id
* @param automatic if this is an automatic subscription
* @throws PortalException in case of LR error
* @throws SystemException in case of LR error
*/
@Override
public void unsubscribe(long proposalId, long userId, boolean automatic) throws PortalException, SystemException {
activitySubscriptionLocalService.deleteSubscription(userId, Proposal.class, proposalId, 0, "", automatic);
ActivitiesClient.deleteSubscription(userId, ActivityEntryType.PROPOSOSAL.getPrimaryTypeId(), proposalId,0 , null );
Proposal proposal = getProposal(proposalId);
/*DiscussionCategoryGroup dcg = discussionCategoryGroupLocalService.getDiscussionCategoryGroup(proposal.getDiscussionId());
activitySubscriptionLocalService.deleteSubscription(userId, DiscussionCategoryGroup.class, dcg.getPrimaryKey(), 0, "", automatic);*/
ActivitiesClient.deleteSubscription(userId, ActivityEntryType.DISCUSSION.getPrimaryTypeId(), proposal.getDiscussionId(),0 , null );
}
/**
* <p>Returns true if user has voted for given proposal in context of a contest phase</p>
*
* @param proposalId proposal id
* @param contestPhaseId contest phase id
* @param userId user id
* @return true if user has voted for proposal in context of a contest phase
* @throws SystemException
*/
@Override
public boolean hasUserVoted(long proposalId, long contestPhaseId, long userId) throws SystemException {
try {
ProposalVote proposalVote = proposalVotePersistence.findByPrimaryKey(new ProposalVotePK(contestPhaseId, userId));
return proposalVote.getProposalId() == proposalId;
} catch (NoSuchProposalVoteException e) {
return false;
}
}
/**
* Returns number of proposals that user supports
*
* @throws SystemException
*/
@Override
public int getUserSupportedProposalsCount(long userId) throws SystemException {
return proposalSupporterPersistence.countByUserId(userId);
}
/**
* Returns number of proposals that user has given his vote to
*
* @throws SystemException
*/
@Override
public int getUserVotedProposalsCount(long userId) throws SystemException {
return proposalVotePersistence.countByUserId(userId);
}
@Override
public List<Proposal> getModifiedAfter(Date date) throws SystemException {
return proposalPersistence.findByModifiedAfter(date);
}
/**
* Sends out the judges' review about the proposal's advance decision as a CoLab message notification to all proposal
* contributers
* @param proposal The proposal for which the notification should be sent
* @param contestPhase The contestPhase in which the proposal is in
* @param request A PortletRequest object to extract the Portal's base URL (may be null - choose default portal URL in that case)
*/
@Override
public void contestPhasePromotionEmailNotifyProposalContributors(Proposal proposal, ContestPhase contestPhase, PortletRequest request)
throws PortalException, SystemException, AddressException, MailEngineException, UnsupportedEncodingException {
String subject = "Judging Results on your Proposal " + proposalAttributeLocalService.getAttribute(proposal.getProposalId(), ProposalAttributeKeys.NAME, 0).getStringValue();
ProposalJudgingCommentHelper reviewContentHelper = new ProposalJudgingCommentHelper(proposal, contestPhase);
String messageBody = reviewContentHelper.getPromotionComment(true);
if (Validator.isNotNull(messageBody)) {
MessageUtil.sendMessage(subject, messageBody, ADMINISTRATOR_USER_ID, ADMINISTRATOR_USER_ID, getMemberUserIds(proposal));
}
}
private List<Long> getMemberUserIds(Proposal proposal) throws PortalException, SystemException {
List<Long> recipientIds = new ArrayList<>();
for (User contributor : getMembers(proposal.getProposalId())) {
recipientIds.add(contributor.getUserId());
}
return recipientIds;
}
@Transactional
private Group createGroupAndSetUpPermissions(long authorId, long proposalId, Contest contest) throws PortalException,
SystemException {
// create new gropu
ServiceContext groupServiceContext = new ServiceContext();
groupServiceContext.setUserId(authorId);
final ContestType contestType = contestTypeLocalService.getContestType(contest);
String groupName = contestType.getProposalName() + "_" + proposalId + "_" + new Date().getTime();
final String groupDescription = TemplateReplacementUtil.replaceContestTypeStrings(DEFAULT_GROUP_DESCRIPTION, contestType);
Group group = groupService.addGroup(StringUtils.substring(groupName, 0, 80),
String.format(groupDescription, StringUtils.substring(groupName, 0, 80)),
GroupConstants.TYPE_SITE_RESTRICTED, null, true, true, groupServiceContext);
Long companyId = group.getCompanyId();
Role owner = roleLocalService.getRole(companyId, RoleConstants.SITE_OWNER);
Role admin = roleLocalService.getRole(companyId, RoleConstants.SITE_ADMINISTRATOR);
Role member = roleLocalService.getRole(companyId, RoleConstants.SITE_MEMBER);
Role userRole = roleLocalService.getRole(companyId, RoleConstants.USER);
Role guest = roleLocalService.getRole(companyId, RoleConstants.GUEST);
Role moderator = roleLocalService.getRole(companyId, "Moderator");
String[] ownerActions = {DiscussionActions.ADMIN.name(), DiscussionActions.ADD_CATEGORY.name(),
DiscussionActions.ADD_MESSAGE.name(), DiscussionActions.ADD_THREAD.name(),
DiscussionActions.ADMIN_CATEGORIES.name(), DiscussionActions.ADMIN_MESSAGES.name(),
DiscussionActions.ADD_COMMENT.name()};
String[] adminActions = {DiscussionActions.ADD_CATEGORY.name(), DiscussionActions.ADD_MESSAGE.name(),
DiscussionActions.ADD_THREAD.name(), DiscussionActions.ADMIN_CATEGORIES.name(),
DiscussionActions.ADMIN_MESSAGES.name(), DiscussionActions.ADD_COMMENT.name()};
String[] moderatorActions = {DiscussionActions.ADD_CATEGORY.name(), DiscussionActions.ADD_MESSAGE.name(),
DiscussionActions.ADD_THREAD.name(), DiscussionActions.ADMIN_CATEGORIES.name(),
DiscussionActions.ADMIN_MESSAGES.name(), DiscussionActions.ADD_COMMENT.name()};
String[] memberActions = {DiscussionActions.ADD_CATEGORY.name(), DiscussionActions.ADD_MESSAGE.name(),
DiscussionActions.ADD_THREAD.name(), DiscussionActions.ADD_COMMENT.name()};
String[] userActions = {DiscussionActions.ADD_MESSAGE.name(), DiscussionActions.ADD_THREAD.name(),
DiscussionActions.ADD_COMMENT.name()};
String[] guestActions = {};
Map<Long, String[]> rolesActionsMap = new HashMap<>();
rolesActionsMap.put(owner.getRoleId(), ownerActions);
rolesActionsMap.put(admin.getRoleId(), adminActions);
rolesActionsMap.put(member.getRoleId(), memberActions);
rolesActionsMap.put(userRole.getRoleId(), userActions);
rolesActionsMap.put(guest.getRoleId(), guestActions);
rolesActionsMap.put(moderator.getRoleId(), moderatorActions);
ResourcePermissionLocalServiceUtil.setResourcePermissions(companyId,
DiscussionCategoryGroup.class.getName(), ResourceConstants.SCOPE_GROUP,
String.valueOf(group.getGroupId()), rolesActionsMap);
return group;
}
/**
* Returns the URL link address for the passed proposal in the latest contest
*
* @param proposalId The proposal id
* @return Proposal URL as String
*/
@Override
public String getProposalLinkUrl(Long proposalId) throws SystemException, PortalException {
return getProposalLinkUrl(proposal2PhaseLocalService.getCurrentContestForProposal(proposalId), proposalId, 0L);
}
/**
* Returns the URL link address for the passed proposal and contest
*
* @param contest The contest object in which the proposal was written
* @param proposal The proposal object (must not be null)
* @return Proposal URL as String
*/
@Override
public String getProposalLinkUrl(Contest contest, Proposal proposal) {
return getProposalLinkUrl(contest, proposal.getProposalId(), 0L);
}
/**
* Returns the URL link address for the passed proposal, contest and contestPhase
*
* @param contest The contest object in which the proposal was written
* @param proposal The proposal object
* @param contestPhase The associated contestPhase of the proposal
* @return Proposal URL as String
*/
@Override
public String getProposalLinkUrl(Contest contest, Proposal proposal, ContestPhase contestPhase) {
return getProposalLinkUrl(contest, proposal.getProposalId(), contestPhase.getContestPhasePK());
}
@Override
public String getProposalLinkUrl(Contest contest, long proposalId, long contestPhaseId) {
String link = "/";
String friendlyUrlStringProposal;
try {
final ContestType contestType = contestTypeLocalService.getContestType(contest);
link += contestType.getFriendlyUrlStringContests();
friendlyUrlStringProposal = contestType.getFriendlyUrlStringProposal();
} catch (SystemException e) {
link += "contests";
friendlyUrlStringProposal = "proposal";
}
if (contestPhaseId > 0) {
try {
long activePhaseId = ContestPhaseLocalServiceUtil.getActivePhaseForContest(contest).getContestPhasePK();
if (activePhaseId == contestPhaseId) {
link += "/%d/%s/c/" + friendlyUrlStringProposal + "/%d";
return String.format(link, contest.getContestYear(), contest.getContestUrlName(), proposalId);
}
} catch (PortalException | SystemException ignored) { }
link += "/%d/%s/phase/%d/" + friendlyUrlStringProposal + "/%d";
return String.format(link, contest.getContestYear(), contest.getContestUrlName(),
contestPhaseId, proposalId);
}
link += "/%d/%s/c/" + friendlyUrlStringProposal + "/%d";
return String.format(link, contest.getContestYear(), contest.getContestUrlName(), proposalId);
}
/**
* Returns list of proposals referenced by given proposal that are relevant for the ingtegration contests
* @param proposalId The proposal for which subproposals should be returned
* @return collection of referenced proposals
*/
@Override
public List<Proposal> getContestIntegrationRelevantSubproposals(long proposalId) throws SystemException, PortalException {
final boolean onlyWithContestIntegrationRelevance = true;
final boolean includeProposalsInSameContest = false;
return getSubproposals(proposalId, includeProposalsInSameContest, onlyWithContestIntegrationRelevance);
}
/**
* Returns list of proposals referenced by given proposal
* @param proposalId The proposal for which subproposals should be returned
* @param includeProposalsInSameContest Specifies whether linked proposals in the same contest as the passed proposal
* should be included in the result or not
* @return collection of referenced proposals
*/
@Override
public List<Proposal> getSubproposals(long proposalId, boolean includeProposalsInSameContest) throws SystemException, PortalException {
final boolean onlyWithContestIntegrationRelevance = false;
return getSubproposals(proposalId, includeProposalsInSameContest, onlyWithContestIntegrationRelevance);
}
/**
* Returns list of proposals referenced by given proposal
* @param proposalId The proposal for which subproposals should be returned
* @param includeProposalsInSameContest Specifies whether linked proposals in the same contest as the passed proposal
* should be included in the result or not
* @param onlyWithContestIntegrationRelevance Specifies whether only proposal with relevance for integration should be included
*
* @return collection of referenced proposals
*/
@Override
public List<Proposal> getSubproposals(long proposalId, boolean includeProposalsInSameContest, boolean onlyWithContestIntegrationRelevance)
throws SystemException, PortalException {
List<ProposalReference> proposalReferences = ProposalReferenceLocalServiceUtil.getByProposalId(proposalId);
List<Proposal> proposals = new ArrayList<>();
for (ProposalReference proposalReference : proposalReferences) {
if (onlyWithContestIntegrationRelevance) {
ProposalAttribute attribute = ProposalAttributeLocalServiceUtil.fetchProposalAttribute(proposalReference.getSectionAttributeId());
PlanSectionDefinition psd = PlanSectionDefinitionLocalServiceUtil.fetchPlanSectionDefinition(attribute.getAdditionalId());
if (!psd.getContestIntegrationRelevance()) {
continue;
}
}
final long subProposalId = proposalReference.getSubProposalId();
Proposal p = getProposal(subProposalId);
if (p != null) {
if (!includeProposalsInSameContest) {
if (getLatestProposalContest(proposalId).equals(getLatestProposalContest(subProposalId))) {
continue;
}
}
if (p.getProposalId() != proposalId) {
proposals.add(p);
}
}
}
return proposals;
}
/**
* Returns latest contest phase to which proposal was submitted
*
* @param proposalId id of a proposal
* @return last contest phase to which proposal was submitted
* @throws PortalException
* @throws SystemException
*/
@Override
public ContestPhase getLatestProposalContestPhase(long proposalId) throws PortalException, SystemException {
Proposal2Phase latestP2p = null;
for (Proposal2Phase p2p: proposal2PhaseLocalService.getByProposalId(proposalId)) {
if (proposal2PhaseLocalService.isContestPhaseOfProposal2PhaseValidInContest(p2p)){
// This is always the most current phase
if (p2p.getVersionTo() == -1) {
latestP2p = p2p;
break;
}
if ((latestP2p == null || p2p.getVersionTo() == 0 || latestP2p.getVersionTo() < p2p.getVersionTo())) {
latestP2p = p2p;
}
}
}
if (latestP2p != null) {
return contestPhaseLocalService.getContestPhase(latestP2p.getContestPhaseId());
}
return null;
}
/**
* Returns latest contest to which proposal was submitted
*
* @param proposalId id of a proposal
* @return last contest to which proposal was submitted
* @throws PortalException
* @throws SystemException
*/
@Override
public Contest getLatestProposalContest(long proposalId) throws PortalException, SystemException {
return contestLocalService.getContest(this.getLatestProposalContestPhase(proposalId).getContestPK());
}
/**
* Returns all focus areas, for which entered proposal impact data is available
*
*/
@Override
public List<FocusArea> getImpactProposalFocusAreas(Proposal proposal) throws SystemException, PortalException {
Set<Long> focusAreaIdSet = new HashSet<>();
List<FocusArea> impactSeriesFocusAreas = new ArrayList<>();
for (ProposalAttribute attribute : proposalAttributeLocalService.getImpactProposalAttributes(proposal)) {
if (!focusAreaIdSet.contains(attribute.getAdditionalId())) {
focusAreaIdSet.add(attribute.getAdditionalId());
impactSeriesFocusAreas.add(FocusAreaLocalServiceUtil.getFocusArea(attribute.getAdditionalId()));
}
}
return impactSeriesFocusAreas;
}
@Override
public boolean isDeleted(Proposal proposal) throws SystemException, PortalException {
final ContestPhase contestPhase = getLatestProposalContestPhase(proposal.getProposalId());
long visibleAttributeValue = 1;
if (contestPhase != null) {
visibleAttributeValue = ProposalContestPhaseAttributeLocalServiceUtil.getAttributeLongValue(proposal.getProposalId(),
contestPhase.getContestPhasePK(), ProposalContestPhaseAttributeKeys.VISIBLE, 0, 1);
}
return !proposal.isVisible() || visibleAttributeValue == 0;
}
@Override
public boolean isVisibleInContest(Proposal proposal, long contestId) throws PortalException, SystemException {
final Contest currentContest = proposal2PhaseLocalService.getCurrentContestForProposal(proposal.getProposalId());
return !isDeleted(proposal) && currentContest.getContestPK() == contestId;
}
}
|
package Controller;
import java.util.ArrayList;
import java.util.Random;
import java.util.Set;
import org.bson.types.ObjectId;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
public class MongoDB {
static Mongo m;
DB AdressDB;
DB SendMailDB;
DB UserDB;
String UserName;
String SendDBName;
String GroupName;
String SendMailList;
DBCollection GroupColl;
DBCollection SendMailColl;
DBCollection UserColl;
public MongoDB()
{
this.DBStart();
}
boolean DBStart()
{
try {
m = new Mongo("controller.owl.or.kr");
SendDBName = "SendMail";
SendMailDB = m.getDB(SendDBName);
SendMailDB.authenticate("owl", "70210".toCharArray());
UserDB = m.getDB("User");
UserDB.authenticate("owl", "70210".toCharArray());
return true;
} catch (Exception e) {
return false;
}
}
boolean LogIn(String User) {
try {
UserName = User;
AdressDB = m.getDB(UserName);
AdressDB.authenticate("owl", "70210".toCharArray());
return true;
} catch (Exception e) {
return false;
}
}
boolean SenderDBStart() {
try {
m = new Mongo("controller.owl.or.kr");
SendDBName = "SendMail";
SendMailDB = m.getDB(SendDBName);
SendMailDB.authenticate("owl", "70210".toCharArray());
return true;
} catch (Exception e) {
return false;
}
}
Boolean Add_User(String Id, String Pw)
{
try
{
UserColl = UserDB.getCollection("User");
UserColl.insert(MakeUserDocument(Id, Pw));
return true;
} catch (Exception e) {
return false;
}
}
ArrayList<User> Load_UserList()
{
ArrayList<User> User_List = new ArrayList<User>();
UserColl = UserDB.getCollection("User");
if (UserColl.getCount() != 0) {
DBCursor cur;
cur = UserColl.find();
while (cur.hasNext()) {
User U_Temp = new User();
U_Temp.ID = cur.next().get("_id").toString();
U_Temp.PW = cur.curr().get("name").toString();
U_Temp.Key = null;
User_List.add(U_Temp);
}
}
return User_List;
}
boolean Update_User(String Id, String NewPw)
{
try
{
UserColl = UserDB.getCollection("User");
BasicDBObject doc;
doc = MakeUserDocument(Id,NewPw);
UserColl.update(new BasicDBObject().append("id", Id), doc);
return true;
}
catch (Exception e) {
return false;
}
}
Boolean Del_User(String Id, String Pw) {
try
{
m.dropDatabase(Id);
UserColl = UserDB.getCollection("User");
BasicDBObject doc;
doc = MakeUserDocument(Id,Pw);
UserColl.remove(doc);
return true;
}
catch (Exception e) {
return false;
}
}
boolean Add_Group(String G_Name) {
try {
GroupName = G_Name;
Set<String> colls = AdressDB.getCollectionNames();
if (!colls.isEmpty()) {
if (AdressDB.collectionExists(GroupName)) {
return false;
} else {
GroupColl = AdressDB.createCollection(GroupName, null);
return true;
}
} else {
GroupColl = AdressDB.createCollection(GroupName, null);
return true;
}
} catch (Exception e) {
return false;
}
}
Boolean Add_Person(String G_Name, String P_Name, String Mail_Address, String Phone) {
try
{
GroupColl = AdressDB.getCollection(G_Name);
GroupColl.insert(MakePersonDocument(P_Name, Mail_Address, Phone));
return true;
} catch (Exception e) {
return false;
}
}
Set<String> Load_Group() {
Set<String> ad = AdressDB.getCollectionNames();
for (String string : ad) {
System.out.println(string);
}
return ad;
}
ArrayList<Person> Load_GroupList(String G_Name) {
ArrayList<Person> PersonList = new ArrayList<Person>();
GroupColl = AdressDB.getCollection(G_Name);
if (GroupColl.getCount() != 0) {
DBCursor cur;
cur = GroupColl.find();
while (cur.hasNext()) {
Person P_Temp = new Person();
P_Temp.ObjectID = cur.next().get("_id").toString();
P_Temp.Name = cur.curr().get("name").toString();
P_Temp.Mail_Address = cur.curr().get("mail").toString();
P_Temp.Phone = cur.curr().get("phone").toString();
PersonList.add(P_Temp);
}
} else {
System.out.println(" ");
}
return PersonList;
}
Boolean Update_Group(String GroupName, String Re_GroupName)
{
try
{
GroupColl = AdressDB.getCollection(GroupName);
GroupColl.rename(Re_GroupName);
return true;
}
catch (Exception e) {
return false;
}
}
Boolean Update_Person(String GroupName, ArrayList<Person> P1)
{
try
{
GroupColl = AdressDB.getCollection(GroupName);
for (Person person : P1)
{
BasicDBObject doc;
doc = MakePersonDocument(person.Name, person.Mail_Address, person.Phone);
GroupColl.update(new BasicDBObject().append("_id", person.ObjectID), doc);
}
return true;
}
catch (Exception e) {
return false;
}
}
Boolean Del_Group(String G_Name)
{
try
{
GroupColl = AdressDB.getCollection(G_Name);
GroupColl.drop();
return true;
}
catch (Exception e) {
return false;
}
}
Boolean Add_Mail_Content(Boolean Sending, long Send_Time, int Send_Num, String From_Adress, String Mail_Title, String Mail_Content, String UserName)
{
try
{
SendMailColl = SendMailDB.getCollection("Mail_Content");
SendMailColl.insert(MakeSendMailDocument(Sending, Send_Time, Send_Num, From_Adress, Mail_Title, Mail_Content, UserName));
return true;
} catch (Exception e) {
return false;
}
}
Boolean Add_To_Person(long Send_Time, String To_Adress, String Group_Name)
{
try
{
Boolean Sending = false;
long Check_Time = 0;
String Cord = null;
int Key = (int) (Math.random()*1000000000);
String String_Send_Time = Long.toString(Send_Time);
SendMailColl = SendMailDB.getCollection(String_Send_Time);
SendMailColl.insert(MakeToPersonDocument(Sending, Check_Time, To_Adress, Cord, Group_Name, Key));
return true;
} catch (Exception e) {
return false;
}
}
// 0 1
ArrayList<Send_Mail> Load_Mail_List(long day, long checkday)
{
DBCursor cur;
SendMailColl = SendMailDB.getCollection("Mail_Content");
System.out.println(SendMailColl.getCount());
// cur = SendMailColl.find(new BasicDBObject().append("id", new
// BasicDBObject((checkday == 0 ? "$lte" : "$gte"), day)));// <=
if (checkday == 0) {
cur = SendMailColl.find(new BasicDBObject().append("time", new BasicDBObject("$lte", day)));
return Add_Mail_List(cur);
}
else if (checkday == 1) {
cur = SendMailColl.find(new BasicDBObject().append("time", new BasicDBObject("$gte", day)));
return Add_Mail_List(cur);
}
else {
BasicDBObject query = new BasicDBObject();
query.append("time", new BasicDBObject("$gte", day));
query.append("time", new BasicDBObject("$lte", checkday));
cur = SendMailColl.find(query);
return Add_Mail_List(cur);
}
}
ArrayList<Send_Mail> Add_Mail_List(DBCursor cur)
{
ArrayList<Send_Mail> Mail = new ArrayList<Send_Mail>();
while (cur.hasNext()) {
Send_Mail Mail_Temp = new Send_Mail();
Mail_Temp.From_Adress = cur.next().get("from_adress").toString();
Mail_Temp.Mail_Content = cur.curr().get("content").toString();
Mail_Temp.Mail_Title = cur.curr().get("title").toString();
Mail_Temp.Send_Num = Integer.parseInt(cur.curr().get("num").toString());
Mail_Temp.Send_Time = Long.parseLong(cur.curr().get("time").toString());
Mail_Temp.UserName = cur.curr().get("username").toString();
Mail.add(Mail_Temp);
}
return Mail;
}
ArrayList<To_Sender_Person> Load_Sender_Person(Long Time, int num)
{
ArrayList<To_Sender_Person> Sender_Person_List = new ArrayList<To_Sender_Person>();
DBCursor Personcur;
SendMailColl = SendMailDB.getCollection(Time.toString());
Personcur = SendMailColl.find(new BasicDBObject("sending", false));
if(Personcur.count() != 0)
{
for(int i=0;i<num;i++)
{
if(!Personcur.hasNext())
break;
To_Sender_Person Temp_Person = new To_Sender_Person();
Temp_Person.ObjectID = Personcur.next().get("_id").toString();
Temp_Person.To_Adress = Personcur.curr().get("toaddress").toString();
Temp_Person.Key = Integer.parseInt(Personcur.curr().get("key").toString());
Sender_Person_List.add(Temp_Person);
}
}
Boolean True;
True = true;
for (To_Sender_Person person : Sender_Person_List) {
BasicDBObject newDocument3 = new BasicDBObject().append("$set", new BasicDBObject().append("sending", True));
ObjectId id = new ObjectId(person.ObjectID);
SendMailColl.update(new BasicDBObject().append("_id", id), newDocument3);
}
return Sender_Person_List;
}
Boolean Update_MailList(Send_Mail send)
{
try
{
SendMailColl = AdressDB.getCollection("Mail_Content");
BasicDBObject doc;
doc = MakeSendMailDocument(send.Sending, send.Send_Time, send.Send_Num, send.From_Adress, send.Mail_Title, send.Mail_Content, send.UserName);
SendMailColl.update(new BasicDBObject().append("time", send.Send_Time), doc);
return true;
}
catch (Exception e) {
return false;
}
}
Boolean Update_MailList_User(ArrayList<To_Person> person, String SendTime)
{
try
{
SendMailColl = SendMailDB.getCollection(SendTime);
BasicDBObject doc;
for (To_Person Person : person) {
doc = MakeToPersonDocument(Person.Sending, Person.Check_Time, Person.To_Adress, Person.Cord, Person.Group_Name, Person.Key);
ObjectId id = new ObjectId(Person.ObjectID);
SendMailColl.update(new BasicDBObject().append("_id", id), doc);
}
return true;
}
catch (Exception e) {
return false;
}
}
Boolean Del_MailList(Send_Mail send)
{
try
{
SendMailColl = SendMailDB.getCollection("Mail_Content");
SendMailColl.remove(new BasicDBObject().append("time", send.Send_Time));
SendMailColl = SendMailDB.getCollection(Long.toString(send.Send_Time));
SendMailColl.drop();
return true;
}
catch (Exception e) {
return false;
}
}
Boolean Update_Cord(long Send_Time, String ObjectID, String Cord)
{
try
{
SendMailColl = SendMailDB.getCollection(Long.toString(Send_Time));
ObjectId id = new ObjectId(ObjectID);
BasicDBObject newDocument3 = new BasicDBObject().append("$set", new BasicDBObject().append("cord", Cord));
SendMailColl.update(new BasicDBObject().append("_id", id), newDocument3);
return true;
}
catch (Exception e) {
return false;
}
}
Boolean Update_CheckTime(long Send_Time, String ObjectID, int key)
{
try
{
long Check_Time;
Check_Time = System.currentTimeMillis();
SendMailColl = SendMailDB.getCollection(Long.toString(Send_Time));
ObjectId id = new ObjectId(ObjectID);
BasicDBObject newDocument3 = new BasicDBObject().append("$set", new BasicDBObject().append("checktime", Check_Time));
SendMailColl.update(new BasicDBObject().append("_id", id).append("key", key), newDocument3);
return true;
}
catch (Exception e) {
return false;
}
}
void printResults() {
DBCursor cur;
cur = GroupColl.find();
while (cur.hasNext()) {
System.out.println(cur.next().get("index") + ","
+ cur.curr().get("name") + "," + cur.curr().get("mail")
+ "," + cur.curr().get("phone"));
}
}
private static BasicDBObject MakeUserDocument(String Id, String Pw) {
BasicDBObject doc = new BasicDBObject();
doc.put("id", Id);
doc.put("password", Pw);
return doc;
}
private static BasicDBObject MakePersonDocument(String P_Name, String Mail_Address, String Phone) {
BasicDBObject doc = new BasicDBObject();
doc.put("name", P_Name);
doc.put("mail", Mail_Address);
doc.put("phone", Phone);
return doc;
}
private static BasicDBObject MakeSendMailDocument(Boolean Sending, long Send_Time, int Send_Num, String From_Adress, String Mail_Title, String Mail_Content, String UserName) {
BasicDBObject doc = new BasicDBObject();
doc.put("sending", Sending);
doc.put("time", Send_Time);
doc.put("num", Send_Num);
doc.put("from_adress", From_Adress);
doc.put("title", Mail_Title);
doc.put("content", Mail_Content);
doc.put("username", UserName);
return doc;
}
private static BasicDBObject MakeToPersonDocument(Boolean Sending, long Check_Time, String To_Adress, String Cord, String Group_Name, int Key) {
BasicDBObject doc = new BasicDBObject();
doc.put("sending", Sending);
doc.put("checktime", Check_Time);
doc.put("toaddress", To_Adress);
doc.put("cord", Cord);
doc.put("group_name", Group_Name);
doc.put("key", Key);
return doc;
}
}
class Person {
public String ObjectID;
public String Name;
public String Mail_Address;
public String Phone;
}
class Send_Mail {
public Boolean Sending;
public String ObjectID;
public long Send_Time;
public int Send_Num;
public String From_Adress;
public String Mail_Title;
public String Mail_Content;
public String UserName;
public ArrayList<To_Person> person = new ArrayList<To_Person>();
}
class To_Person {
public String ObjectID;
public Boolean Sending;
public long Check_Time;
public String To_Adress;
public String Cord;
public String Group_Name;
public int Key;
}
class To_Sender_Person
{
public String ObjectID;
public int Key;
public String To_Adress;
}
class User {
String ID;
String PW;
String Key;
}
|
package algorithms.compGeometry;
import algorithms.MultiArrayMergeSort;
import algorithms.util.PairInt;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Builds an unmodifiable data structure to make finding member points within
* a distance of a location faster than O(N^2).
*
* The runtime complexity is O(N*lg2(N)) for the constructor
* and for search is O(lg2(N)) + small number of scans surrounding the nearest x.
*
* @author nichole
*/
public class NearestPoints {
private final int[] x;
private final int[] y;
private final int[] originalIndexes;
public NearestPoints(int[] xPoints, int[] yPoints) {
if (xPoints == null) {
throw new IllegalStateException("xPoints cannot be null");
}
if (yPoints == null) {
throw new IllegalStateException("yPoints cannot be null");
}
if (xPoints.length != yPoints.length) {
throw new IllegalStateException(
"xPoints and yPoints must be the same length");
}
int n = xPoints.length;
x = new int[n];
y = new int[n];
originalIndexes = new int[n];
for (int i = 0; i < n; ++i) {
x[i] = xPoints[i];
y[i] = yPoints[i];
originalIndexes[i] = i;
}
MultiArrayMergeSort.sortBy1stArgThen2nd(x, y, originalIndexes);
}
/**
* find points within radius of (xCenter, yCenter) in the contained points.
* @param xCenter
* @param yCenter
* @param radius
* @return
*/
public Set<PairInt> findNeighbors(int xCenter, int yCenter, float radius) {
Set<PairInt> result = new HashSet<PairInt>();
if (x.length == 0) {
return result;
}
Set<Integer> indexes = findNeighborIndexesR(xCenter, yCenter, radius);
for (Integer index : indexes) {
int i = index.intValue();
result.add(new PairInt(x[i], y[i]));
}
return result;
}
/**
* find points within radius of (xCenter, yCenter) in the contained points.
* @param xCenter
* @param yCenter
* @param radius
* @return
*/
public Set<Integer> findNeighborIndexes(int xCenter, int yCenter, float radius) {
Set<Integer> result = new HashSet<Integer>();
if (x.length == 0) {
return result;
}
Set<Integer> indexes = findNeighborIndexesR(xCenter, yCenter, radius);
for (Integer index : indexes) {
int i = index.intValue();
result.add(originalIndexes[i]);
}
return result;
}
/**
* find points within radius of (xCenter, yCenter) in the contained points
* and return the indexes relative to the x,y arrays
* @param xCenter
* @param yCenter
* @param radius
* @return
*/
private Set<Integer> findNeighborIndexesR(int xCenter, int yCenter, float radius) {
Set<Integer> resultIndexes = new HashSet<Integer>();
if (x.length == 0) {
return resultIndexes;
}
// O(lg2(N))
int idx = Arrays.binarySearch(x, xCenter);
// if it's negative, (-(insertion point) - 1)
if (idx < 0) {
// idx = -*idx2 - 1
idx = -1*(idx + 1);
}
if (idx > (x.length - 1)) {
idx = x.length - 1;
}
double rSq = Math.sqrt(2) * radius * radius;
int startIdx = idx;
for (int i = (idx - 1); i > -1; --i) {
int diffX = Math.abs(x[i] - xCenter);
if (diffX > rSq) {
break;
}
startIdx = i;
}
int stopIdx = idx;
for (int i = idx; i < x.length; ++i) {
int diffX = Math.abs(x[i] - xCenter);
if (diffX > rSq) {
break;
}
stopIdx = i;
}
// search for points within startIdx and stopIdx that are within radius
for (int i = startIdx; i <= stopIdx; ++i) {
int diffX = x[i] - xCenter;
int diffY = y[i] - yCenter;
double distSq = (diffX*diffX) + (diffY*diffY);
if (distSq <= rSq) {
resultIndexes.add(Integer.valueOf(i));
}
}
return resultIndexes;
}
public PairInt getSmallestXY() {
return new PairInt(x[0], y[0]);
}
}
|
package tpe.fruh_razzaq_jando.pue1;
/**
* Diese Klasse implementiert einen Bruch
*
* @author TPE_UIB_01
*/
public class Bruch {
// Properties
private long nenner, zaehler, ganze;
// Constructors
Bruch(long zaehler, long nenner) {
if (nenner == 0)
throw new RuntimeException(
"Bruch(zaehler, nenner) - nenner darf nicht 0 sein!");
else {
this.zaehler = zaehler;
this.nenner = nenner;
kuerze();
}
}
Bruch(long ganze, long zaehler, long nenner) {
if (nenner == 0)
throw new RuntimeException(
"Bruch(zaehler, nenner, ganze) - nenner darf nicht 0 sein!");
else {
this.zaehler = zaehler;
this.nenner = nenner;
this.ganze = ganze;
kuerze();
}
}
// Accessors
public long getNenner() {
return nenner;
}
public void setNenner(long nenner) {
this.nenner = nenner;
}
public long getZaehler() {
return zaehler;
}
public void setZaehler(long zaehler) {
this.zaehler = zaehler;
}
public long getGanze() {
return ganze;
}
public void setGanze(long ganze) {
this.ganze = ganze;
}
// Methods
public Bruch addiere(Bruch zweiterBruch) {
boolean echt = false;
Bruch tmpBruch1;
Bruch tmpBruch2;
if (this.ganze != 0) {
echt = true;
tmpBruch1 = new Bruch(this.ganze, this.zaehler, this.nenner);
} else {
tmpBruch1 = new Bruch(this.zaehler, this.nenner);
}
if (zweiterBruch.ganze != 0) {
echt = true;
tmpBruch2 = new Bruch(zweiterBruch.ganze, zweiterBruch.zaehler, zweiterBruch.nenner);
} else {
tmpBruch2 = new Bruch(zweiterBruch.zaehler, zweiterBruch.nenner);
}
tmpBruch1.unechterBruch();
tmpBruch2.unechterBruch();
System.out.println(tmpBruch1);
System.out.println(tmpBruch2);
long zaehler = (tmpBruch1.zaehler * tmpBruch2.nenner) + (tmpBruch2.zaehler * tmpBruch1.nenner);
System.out.println(zaehler);
Bruch ergebnisBruch = new Bruch(zaehler, tmpBruch1.nenner * tmpBruch2.nenner);
ergebnisBruch.kuerze();
if (echt) {
ergebnisBruch.echterBruch();
}
return ergebnisBruch;
}
public void unechterBruch() {
if (this.ganze != 0) {
this.zaehler = (this.ganze * this.nenner) + this.zaehler;
this.ganze = 0;
}
}
public void echterBruch() {
while (this.zaehler > this.nenner) {
this.ganze++;
this.zaehler -= this.nenner;
}
}
public double getDezimalzahl() {
return ganze + ((double) zaehler / (double) nenner);
}
private void kuerze() {
long ggt = getGGT(Math.min(zaehler, nenner));
this.zaehler = this.zaehler / ggt;
this.nenner = this.nenner / ggt;
}
private long getGGT(long aktuelleZahl) {
if (zaehler % aktuelleZahl == 0 && nenner % aktuelleZahl == 0)
return aktuelleZahl;
else
return getGGT(aktuelleZahl - 1);
}
@Override
public String toString() {
if (ganze == 0)
return zaehler + "/" + nenner;
else if (zaehler == 0 && nenner == 0)
return ganze + "";
else
return ganze + " " + zaehler + "/" + nenner;
}
}
|
package io.tetrapod.core;
import static io.tetrapod.protocol.core.Core.UNADDRESSED;
import static io.tetrapod.protocol.core.CoreContract.*;
import io.netty.channel.socket.SocketChannel;
import io.tetrapod.core.rpc.*;
import io.tetrapod.core.rpc.Error;
import io.tetrapod.core.utils.*;
import io.tetrapod.protocol.core.*;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.net.ConnectException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import org.slf4j.*;
import ch.qos.logback.classic.LoggerContext;
import com.codahale.metrics.Timer.Context;
public class DefaultService implements Service, Fail.FailHandler, CoreContract.API, SessionFactory, EntityMessage.Handler,
TetrapodContract.Cluster.API {
private static final Logger logger = LoggerFactory.getLogger(DefaultService.class);
protected final Set<Integer> dependencies = new HashSet<>();
public final Dispatcher dispatcher;
protected final Client clusterClient;
protected final Contract contract;
protected final ServiceCache services;
protected boolean terminated;
protected int entityId;
protected int parentId;
protected String token;
private int status;
public final int buildNumber;
protected final LogBuffer logBuffer;
protected SSLContext sslContext;
private ServiceConnector serviceConnector;
protected final ServiceStats stats;
protected boolean startPaused;
private final LinkedList<ServerAddress> clusterMembers = new LinkedList<>();
private final MessageHandlers messageHandlers = new MessageHandlers();
public DefaultService() {
this(null);
}
public DefaultService(Contract mainContract) {
logBuffer = (LogBuffer) ((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger("ROOT").getAppender("BUFFER");
String m = getStartLoggingMessage();
logger.info(m);
Session.commsLog.info(m);
Fail.handler = this;
Metrics.init(getMetricsPrefix());
synchronized (this) {
status |= Core.STATUS_STARTING;
}
dispatcher = new Dispatcher();
clusterClient = new Client(this);
stats = new ServiceStats(this);
addContracts(new CoreContract());
addPeerContracts(new TetrapodContract());
addMessageHandler(new EntityMessage(), this);
addSubscriptionHandler(new TetrapodContract.Cluster(), this);
try {
if (Util.getProperty("tetrapod.tls", true)) {
sslContext = Util.createSSLContext(new FileInputStream(Util.getProperty("tetrapod.jks.file", "cfg/tetrapod.jks")), System
.getProperty("tetrapod.jks.pwd", "4pod.dop4").toCharArray());
}
} catch (Exception e) {
fail(e);
}
if (getEntityType() != Core.TYPE_TETRAPOD) {
services = new ServiceCache();
addSubscriptionHandler(new TetrapodContract.Services(), services);
} else {
services = null;
}
Runtime.getRuntime().addShutdownHook(new Thread("Shutdown Hook") {
public void run() {
logger.info("Shutdown Hook");
if (!isShuttingDown()) {
shutdown(false);
}
}
});
int num = 1;
try {
String b = Util.readFileAsString(new File("build_number.txt"));
num = Integer.parseInt(b.trim());
} catch (IOException e) {}
buildNumber = num;
checkHealth();
if (mainContract != null)
addContracts(mainContract);
this.contract = mainContract;
}
/**
* Returns a prefix for all exported metrics from this service.
*/
private String getMetricsPrefix() {
return Util.getProperty("devMode", "") + "." + Util.getProperty("product.name") + "." + Util.getHostName() + "."
+ getClass().getSimpleName();
}
public byte getEntityType() {
return Core.TYPE_SERVICE;
}
public synchronized int getStatus() {
return status;
}
@Override
public void messageEntity(EntityMessage m, MessageContext ctxA) {
SessionMessageContext ctx = (SessionMessageContext) ctxA;
if (ctx.session.getTheirEntityType() == Core.TYPE_TETRAPOD) {
synchronized (this) {
this.entityId = m.entityId;
}
ctx.session.setMyEntityId(m.entityId);
}
}
@Override
public void genericMessage(Message message, MessageContext ctx) {
logger.error("Unhandled message handler: {}", message.dump());
assert false;
}
// Service protocol
@Override
public void startNetwork(ServerAddress server, String token, Map<String, String> otherOpts) throws Exception {
this.token = token;
this.startPaused = otherOpts.get("paused").equals("true");
clusterMembers.addFirst(server);
connectToCluster(5);
}
/**
* Called after we've registered and dependencies are all available
*/
public void onReadyToServe() {}
private void onServiceRegistered() {
registerServiceInformation();
stats.publishTopic();
sendDirectRequest(new ServicesSubscribeRequest());
}
public boolean dependenciesReady() {
return services.checkDependencies(dependencies);
}
private final Object checkDependenciesLock = new Object();
public void checkDependencies() {
synchronized (checkDependenciesLock) {
if (!isShuttingDown() && isStartingUp()) {
logger.info("Checking Dependencies...");
if (dependenciesReady()) {
try {
if (startPaused) {
updateStatus(getStatus() | Core.STATUS_PAUSED);
}
onReadyToServe();
if (getEntityType() != Core.TYPE_TETRAPOD) {
if (serviceConnector != null) {
serviceConnector.shutdown();
}
serviceConnector = new ServiceConnector(this, sslContext);
}
} catch (Throwable t) {
fail(t);
}
// ok, we're good to go
updateStatus(getStatus() & ~Core.STATUS_STARTING);
onStarted();
if (startPaused) {
onPaused();
startPaused = false; // only start paused once
}
} else {
dispatcher.dispatch(1, TimeUnit.SECONDS, new Runnable() {
public void run() {
checkDependencies();
}
});
}
}
}
}
/**
* Periodically checks service health, updates metrics
*/
private void checkHealth() {
if (!isShuttingDown()) {
if (dispatcher.workQueueSize.getCount() > 0) {
logger.warn("DISPATCHER QUEUE SIZE = {}", dispatcher.workQueueSize.getCount());
}
if (dispatcher.workQueueSize.getCount() >= Session.DEFAULT_OVERLOAD_THRESHOLD) {
updateStatus(getStatus() | Core.STATUS_OVERLOADED);
} else {
updateStatus(getStatus() & ~Core.STATUS_OVERLOADED);
}
if (logBuffer.hasErrors()) {
updateStatus(getStatus() | Core.STATUS_ERRORS);
} else {
updateStatus(getStatus() & ~Core.STATUS_ERRORS);
}
if (logBuffer.hasWarnings()) {
updateStatus(getStatus() | Core.STATUS_WARNINGS);
} else {
updateStatus(getStatus() & ~Core.STATUS_WARNINGS);
}
dispatcher.dispatch(1, TimeUnit.SECONDS, new Runnable() {
public void run() {
checkHealth();
}
});
}
}
/**
* Called before shutting down. Default implementation is to do nothing. Subclasses are expecting to close any resources they opened (for
* example database connections or file handles).
*
* @param restarting true if we are shutting down in order to restart
*/
public void onShutdown(boolean restarting) {}
public void onPaused() {}
public void onPurged() {}
public void onReleaseExcess() {}
public void onRebalance() {}
public void onUnpaused() {}
public void onStarted() {}
public void shutdown(boolean restarting) {
updateStatus(getStatus() | Core.STATUS_STOPPING);
try {
onShutdown(restarting);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
if (restarting) {
clusterClient.close();
dispatcher.shutdown();
setTerminated(true);
try {
Launcher.relaunch(getRelaunchToken());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
} else {
if (getEntityId() != 0 && clusterClient.getSession() != null) {
sendDirectRequest(new UnregisterRequest(getEntityId())).handle(new ResponseHandler() {
@Override
public void onResponse(Response res) {
clusterClient.close();
dispatcher.shutdown();
setTerminated(true);
}
});
} else {
dispatcher.shutdown();
setTerminated(true);
}
}
// If JVM doesn't gracefully terminate after 1 minute, explicitly kill the process
final Thread hitman = new Thread(new Runnable() {
public void run() {
Util.sleep(Util.ONE_MINUTE);
logger.warn("Service did not complete graceful termination. Force Killing JVM.");
final Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
for (Thread t : map.keySet()) {
logger.warn("{}", t);
}
System.exit(1);
}
}, "Hitman");
hitman.setDaemon(true);
hitman.start();
}
public ServiceCache getServiceCache() {
return services;
}
protected String getRelaunchToken() {
return token;
}
/**
* Session factory for our session to our parent TetrapodService
*/
@Override
public Session makeSession(SocketChannel ch) {
final Session ses = new WireSession(ch, DefaultService.this);
ses.setMyEntityType(getEntityType());
ses.setTheirEntityType(Core.TYPE_TETRAPOD);
ses.addSessionListener(new Session.Listener() {
@Override
public void onSessionStop(Session ses) {
onDisconnectedFromCluster();
}
@Override
public void onSessionStart(Session ses) {
onConnectedToCluster();
}
});
return ses;
}
private void onConnectedToCluster() {
sendDirectRequest(new RegisterRequest(buildNumber, token, getContractId(), getShortName(), getStatus(), Util.getHostName())).handle(
new ResponseHandler() {
@Override
public void onResponse(Response res) {
if (res.isError()) {
Fail.fail("Unable to register: " + res.errorCode());
} else {
RegisterResponse r = (RegisterResponse) res;
entityId = r.entityId;
parentId = r.parentId;
token = r.token;
logger.info(String.format("%s My entityId is 0x%08X", clusterClient.getSession(), r.entityId));
clusterClient.getSession().setMyEntityId(r.entityId);
clusterClient.getSession().setTheirEntityId(r.parentId);
clusterClient.getSession().setMyEntityType(getEntityType());
clusterClient.getSession().setTheirEntityType(Core.TYPE_TETRAPOD);
onServiceRegistered();
}
}
});
}
public void onDisconnectedFromCluster() {
if (!isShuttingDown()) {
logger.info("Connection to tetrapod closed");
dispatcher.dispatch(3, TimeUnit.SECONDS, new Runnable() {
public void run() {
connectToCluster(1);
}
});
}
}
public boolean isConnected() {
return clusterClient.isConnected();
}
protected void connectToCluster(final int retrySeconds) {
if (!isShuttingDown() && !clusterClient.isConnected()) {
synchronized (clusterMembers) {
final ServerAddress server = clusterMembers.poll();
if (server != null) {
try {
if (sslContext != null) {
clusterClient.enableTLS(sslContext);
}
clusterClient.connect(server.host, server.port, dispatcher).sync();
if (clusterClient.isConnected()) {
clusterMembers.addFirst(server);
return;
}
} catch (ConnectException e) {
logger.info(e.getMessage());
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
clusterMembers.addLast(server);
}
}
// schedule a retry
dispatcher.dispatch(retrySeconds, TimeUnit.SECONDS, new Runnable() {
public void run() {
connectToCluster(retrySeconds);
}
});
}
}
// subclass utils
protected void addContracts(Contract... contracts) {
for (Contract c : contracts) {
c.registerStructs();
}
}
protected void addPeerContracts(Contract... contracts) {
for (Contract c : contracts) {
c.registerPeerStructs();
}
}
public int getEntityId() {
return entityId;
}
protected int getParentId() {
return parentId;
}
public synchronized boolean isShuttingDown() {
return (status & Core.STATUS_STOPPING) != 0;
}
public synchronized boolean isPaused() {
return (status & Core.STATUS_PAUSED) != 0;
}
public synchronized boolean isStartingUp() {
return (status & Core.STATUS_STARTING) != 0;
}
public synchronized boolean isNominal() {
int nonRunning = Core.STATUS_STARTING | Core.STATUS_FAILED | Core.STATUS_BUSY | Core.STATUS_PAUSED | Core.STATUS_STOPPING;
return (status & nonRunning) == 0;
}
public synchronized boolean isTerminated() {
return terminated;
}
private synchronized void setTerminated(boolean val) {
logger.info("TERMINATED");
terminated = val;
}
protected void updateStatus(int status) {
boolean changed = false;
synchronized (this) {
changed = this.status != status;
this.status = status;
}
if (changed && clusterClient.isConnected()) {
sendDirectRequest(new ServiceStatusUpdateRequest(status)).log();
}
}
@Override
public void fail(Throwable error) {
logger.error(error.getMessage(), error);
updateStatus(status | Core.STATUS_FAILED);
}
@Override
public void fail(String reason) {
logger.error("FAIL: {}", reason);
updateStatus(status | Core.STATUS_FAILED);
}
/**
* Get a URL for this service's icon to display in the admin apps. Subclasses should override this to customize
*/
public String getServiceIcon() {
return "media/gear.gif";
}
/**
* Get any custom metadata for the service. Subclasses should override this to customize
*/
public String getServiceMetadata() {
return null;
}
/**
* Get any custom admin commands for the service to show in command menu of admin app. Subclasses should override this to customize
*/
public ServiceCommand[] getServiceCommands() {
return null;
}
protected String getShortName() {
if (contract == null) {
return null;
}
return contract.getName();
}
protected String getFullName() {
if (contract == null) {
return null;
}
String s = contract.getClass().getCanonicalName();
return s.substring(0, s.length() - "Contract".length());
}
public long getAverageResponseTime() {
// TODO: verify this is correctly converting nanos to millis
return (long) dispatcher.requestTimes.getSnapshot().getMean() / 1000000L;
}
/**
* Services can override this to provide a service specific counter for display in the admin app
*/
public long getCounter() {
return 0;
}
public long getNumRequestsHandled() {
return dispatcher.requestsHandledCounter.getCount();
}
public long getNumMessagesSent() {
return dispatcher.messagesSentCounter.getCount();
}
/**
* Dispatches a request to ourselves
*/
@Override
public Async dispatchRequest(final RequestHeader header, final Request req, final Session fromSession) {
final Async async = new Async(req, header, fromSession);
final ServiceAPI svc = getServiceHandler(header.contractId);
if (svc != null) {
final long start = System.nanoTime();
final Context context = dispatcher.requestTimes.time();
if (!dispatcher.dispatch(new Runnable() {
public void run() {
try {
RequestContext ctx = new SessionRequestContext(header, fromSession);
Response res = req.securityCheck(ctx);
if (res == null) {
res = req.dispatch(svc, ctx);
}
if (res != null) {
async.setResponse(res);
} else {
async.setResponse(new Error(ERROR_UNKNOWN));
}
} catch (ErrorResponseException e) {
async.setResponse(new Error(e.errorCode));
} catch (Throwable e) {
logger.error(e.getMessage(), e);
async.setResponse(new Error(ERROR_UNKNOWN));
}
context.stop();
final long elapsed = System.nanoTime() - start;
dispatcher.requestsHandledCounter.mark();
if (Util.nanosToMillis(elapsed) > 1000) {
logger.warn("Request took {} {} millis", req, Util.nanosToMillis(elapsed));
}
}
}, Session.DEFAULT_OVERLOAD_THRESHOLD)) {
async.setResponse(new Error(ERROR_SERVICE_OVERLOADED));
}
} else {
logger.warn("{} No handler found for {}", this, header.dump());
async.setResponse(new Error(ERROR_UNKNOWN_REQUEST));
}
return async;
}
public Response sendPendingRequest(Request req, int toEntityId, PendingResponseHandler handler) {
if (serviceConnector != null) {
return serviceConnector.sendPendingRequest(req, toEntityId, handler);
}
return clusterClient.getSession().sendPendingRequest(req, toEntityId, (byte) 30, handler);
}
public Response sendPendingRequest(Request req, PendingResponseHandler handler) {
if (serviceConnector != null) {
return serviceConnector.sendPendingRequest(req, Core.UNADDRESSED, handler);
}
return clusterClient.getSession().sendPendingRequest(req, Core.UNADDRESSED, (byte) 30, handler);
}
public Response sendPendingDirectRequest(Request req, PendingResponseHandler handler) {
return clusterClient.getSession().sendPendingRequest(req, Core.DIRECT, (byte) 30, handler);
}
public Async sendRequest(Request req) {
if (serviceConnector != null) {
return serviceConnector.sendRequest(req, Core.UNADDRESSED);
}
return clusterClient.getSession().sendRequest(req, Core.UNADDRESSED, (byte) 30);
}
public Async sendRequest(Request req, int toEntityId) {
if (serviceConnector != null) {
return serviceConnector.sendRequest(req, toEntityId);
}
return clusterClient.getSession().sendRequest(req, toEntityId, (byte) 30);
}
public Async sendDirectRequest(Request req) {
return clusterClient.getSession().sendRequest(req, Core.DIRECT, (byte) 30);
}
public void sendMessage(Message msg, int toEntityId) {
clusterClient.getSession().sendMessage(msg, MessageHeader.TO_ENTITY, toEntityId);
}
public void sendBroadcastMessage(Message msg, int topicId) {
clusterClient.getSession().sendBroadcastMessage(msg, MessageHeader.TO_TOPIC, topicId);
}
public void sendAltBroadcastMessage(Message msg, int altId) {
clusterClient.getSession().sendBroadcastMessage(msg, MessageHeader.TO_ALTERNATE, altId);
}
/**
* Subscribe an entity to the given topic. If once is true, tetrapod won't subscribe them a second time
*/
public void subscribe(int topicId, int entityId, boolean once) {
sendMessage(new TopicSubscribedMessage(getEntityId(), topicId, entityId, once), UNADDRESSED);
}
public void subscribe(int topicId, int entityId) {
subscribe(topicId, entityId, false);
}
public void unsubscribe(int topicId, int entityId) {
sendMessage(new TopicUnsubscribedMessage(getEntityId(), topicId, entityId), UNADDRESSED);
}
public void unpublish(int topicId) {
sendMessage(new TopicUnpublishedMessage(getEntityId(), topicId), UNADDRESSED);
}
// Generic handlers for all request/subscriptions
public Response genericRequest(Request r, RequestContext ctx) {
logger.error("unhandled request " + r.dump());
return new Error(CoreContract.ERROR_UNKNOWN_REQUEST);
}
public void setDependencies(int... contractIds) {
for (int contractId : contractIds) {
dependencies.add(contractId);
}
}
// Session.Help implementation
@Override
public Dispatcher getDispatcher() {
return dispatcher;
}
public ServiceAPI getServiceHandler(int contractId) {
// this method allows us to have delegate objects that directly handle some contracts
return this;
}
@Override
public List<SubscriptionAPI> getMessageHandlers(int contractId, int structId) {
return messageHandlers.get(contractId, structId);
}
@Override
public int getContractId() {
return contract == null ? 0 : contract.getContractId();
}
public void addSubscriptionHandler(Contract sub, SubscriptionAPI handler) {
messageHandlers.add(sub, handler);
}
public void addMessageHandler(Message k, SubscriptionAPI handler) {
messageHandlers.add(k, handler);
}
@Override
public void messageClusterMember(ClusterMemberMessage m, MessageContext ctx) {
logger.info("******** {}", m.dump());
clusterMembers.add(new ServerAddress(m.host, m.servicePort));
}
@Override
public void messageClusterPropertyAdded(ClusterPropertyAddedMessage m, MessageContext ctx) {
logger.info("******** {}", m.dump());
System.setProperty(m.property.key, m.property.val);
}
@Override
public void messageClusterPropertyRemoved(ClusterPropertyRemovedMessage m, MessageContext ctx) {
logger.info("******** {}", m.dump());
System.clearProperty(m.key);
}
@Override
public void messageClusterSynced(ClusterSyncedMessage m, MessageContext ctx) {
checkDependencies();
}
// private methods
protected void registerServiceInformation() {
if (contract != null) {
AddServiceInformationRequest asi = new AddServiceInformationRequest();
asi.info = new ContractDescription();
asi.info.contractId = contract.getContractId();
asi.info.version = contract.getContractVersion();
asi.info.routes = contract.getWebRoutes();
asi.info.structs = new ArrayList<>();
for (Structure s : contract.getRequests()) {
asi.info.structs.add(s.makeDescription());
}
for (Structure s : contract.getResponses()) {
asi.info.structs.add(s.makeDescription());
}
for (Structure s : contract.getMessages()) {
asi.info.structs.add(s.makeDescription());
}
for (Structure s : contract.getStructs()) {
asi.info.structs.add(s.makeDescription());
}
sendDirectRequest(asi).handle(ResponseHandler.LOGGER);
}
}
// Base service implementation
@Override
public Response requestPause(PauseRequest r, RequestContext ctx) {
// TODO: Check admin rights or macaroon
updateStatus(getStatus() | Core.STATUS_PAUSED);
onPaused();
return Response.SUCCESS;
}
@Override
public Response requestPurge(PurgeRequest r, RequestContext ctx) {
onPurged();
return Response.SUCCESS;
}
@Override
public Response requestRebalance(RebalanceRequest r, RequestContext ctx) {
onRebalance();
return Response.SUCCESS;
}
@Override
public Response requestReleaseExcess(ReleaseExcessRequest r, RequestContext ctx) {
onReleaseExcess();
return Response.SUCCESS;
}
@Override
public Response requestUnpause(UnpauseRequest r, RequestContext ctx) {
// TODO: Check admin rights or macaroon
updateStatus(getStatus() & ~Core.STATUS_PAUSED);
onUnpaused();
return Response.SUCCESS;
}
@Override
public Response requestRestart(RestartRequest r, RequestContext ctx) {
// TODO: Check admin rights or macaroon
dispatcher.dispatch(new Runnable() {
public void run() {
shutdown(true);
}
});
return Response.SUCCESS;
}
@Override
public Response requestShutdown(ShutdownRequest r, RequestContext ctx) {
// TODO: Check admin rights or macaroon
dispatcher.dispatch(new Runnable() {
public void run() {
shutdown(false);
}
});
return Response.SUCCESS;
}
@Override
public Response requestServiceDetails(ServiceDetailsRequest r, RequestContext ctx) {
return new ServiceDetailsResponse(getServiceIcon(), getServiceMetadata(), getServiceCommands());
}
@Override
public Response requestServiceStatsSubscribe(ServiceStatsSubscribeRequest r, RequestContext ctx) {
stats.subscribe(ctx.header.fromId);
return Response.SUCCESS;
}
@Override
public Response requestServiceStatsUnsubscribe(ServiceStatsUnsubscribeRequest r, RequestContext ctx) {
stats.unsubscribe(ctx.header.fromId);
return Response.SUCCESS;
}
@Override
public Response requestServiceLogs(ServiceLogsRequest r, RequestContext ctx) {
if (logBuffer == null) {
return new Error(CoreContract.ERROR_NOT_CONFIGURED);
}
final List<ServiceLogEntry> list = new ArrayList<ServiceLogEntry>();
long last = logBuffer.getItems(r.logId, logBuffer.convert(r.level), r.maxItems, list);
return new ServiceLogsResponse(last, list);
}
protected String getStartLoggingMessage() {
return "*** Start Service ***" + "\n *** Service name: " + Util.getProperty("APPNAME") + "\n *** Options: "
+ Launcher.getAllOpts() + "\n *** VM Args: " + ManagementFactory.getRuntimeMXBean().getInputArguments().toString();
}
@Override
public Response requestServiceErrorLogs(ServiceErrorLogsRequest r, RequestContext ctx) {
if (logBuffer == null) {
return new Error(CoreContract.ERROR_NOT_CONFIGURED);
}
final List<ServiceLogEntry> list = new ArrayList<ServiceLogEntry>();
list.addAll(logBuffer.getErrors());
list.addAll(logBuffer.getWarnings());
Collections.sort(list, new Comparator<ServiceLogEntry>() {
@Override
public int compare(ServiceLogEntry e1, ServiceLogEntry e2) {
return ((Long) e1.timestamp).compareTo(e2.timestamp);
}
});
return new ServiceErrorLogsResponse(list);
}
@Override
public Response requestResetServiceErrorLogs(ResetServiceErrorLogsRequest r, RequestContext ctx) {
if (logBuffer == null) {
return new Error(CoreContract.ERROR_NOT_CONFIGURED);
}
logBuffer.resetErrorLogs();
return Response.SUCCESS;
}
@Override
public Response requestSetCommsLogLevel(SetCommsLogLevelRequest r, RequestContext ctx) {
ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("comms");
if (logger == null) {
return new Error(CoreContract.ERROR_NOT_CONFIGURED);
}
logger.setLevel(ch.qos.logback.classic.Level.valueOf(r.level));
return Response.SUCCESS;
}
@Override
public Response requestWebAPI(WebAPIRequest r, RequestContext ctx) {
return Response.error(CoreContract.ERROR_UNKNOWN_REQUEST);
}
@Override
public Response requestDirectConnection(DirectConnectionRequest r, RequestContext ctx) {
if (serviceConnector != null) {
return serviceConnector.requestDirectConnection(r, ctx);
}
return new Error(CoreContract.ERROR_NOT_CONFIGURED);
}
@Override
public Response requestValidateConnection(ValidateConnectionRequest r, RequestContext ctx) {
if (serviceConnector != null) {
return serviceConnector.requestValidateConnection(r, ctx);
}
return new Error(CoreContract.ERROR_NOT_CONFIGURED);
}
@Override
public Response requestDummy(DummyRequest r, RequestContext ctx) {
return Response.SUCCESS;
}
@Override
public Response requestHostInfo(HostInfoRequest r, RequestContext ctx) {
return new HostInfoResponse(Util.getHostName(), (byte) Metrics.getNumCores(), null);
}
@Override
public Response requestHostStats(HostStatsRequest r, RequestContext ctx) {
return new HostStatsResponse(Metrics.getLoadAverage(), Metrics.getFreeDiskSpace());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.